edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
from .figure import Figure
from .traces import Scatter, ErrorBand, Histogram, Heatmap, Contour, KDE
import plotly.graph_objects as go
import plotly
import numpy as np
import warnings
class PlotlyFigure(Figure):
def __init__(self):
super().__init__()
self.plotly_figure = go.Figure()
# Methods that must be overridden ----------------------------------
def show(self):
# Overriding this method as specified in the class Figure.
self.plotly_figure.show()
def save(self, file_name=None, include_plotlyjs='cdn', auto_open=False, **kwargs):
# Overriding this method as specified in the class Figure.
if file_name is None:
file_name = self.title
if file_name is None: # If it is still None...
raise ValueError(f'Please provide a name for saving the figure to a file by the <file_name> argument.')
if file_name[-5:] != '.html':
file_name += '.html'
plotly.offline.plot(
self.plotly_figure,
filename = file_name,
auto_open = auto_open,
include_plotlyjs = include_plotlyjs,
**kwargs
)
def draw_layout(self):
# Overriding this method as specified in the class Figure.
if self.show_title == True and self.title != None:
self.plotly_figure.update_layout(title = self.title)
self.plotly_figure.update_layout(
xaxis_title = self.xlabel,
yaxis_title = self.ylabel,
)
# Axes scale:
if self.xscale in [None, 'lin']:
pass
elif self.xscale == 'log':
self.plotly_figure.update_layout(xaxis_type = 'log')
if self.yscale in [None, 'lin']:
pass
elif self.yscale == 'log':
self.plotly_figure.update_layout(yaxis_type = 'log')
if self.aspect == 'equal':
self.plotly_figure.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
)
if self.subtitle != None:
self.plotly_figure.add_annotation(
text = self.subtitle.replace('\n','<br>'),
xref = "paper",
yref = "paper",
x = .5,
y = 1,
align = 'left',
arrowcolor="#ffffff",
font=dict(
family="Courier New, monospace",
color="#999999"
),
)
def draw_trace(self, trace):
# Overriding this method as specified in the class Figure.
traces_drawing_methods = {
Scatter: self._draw_scatter,
ErrorBand: self._draw_errorband,
Histogram: self._draw_histogram,
Heatmap: self._draw_heatmap,
Contour: self._draw_contour,
KDE: self._draw_scatter,
}
if type(trace) not in traces_drawing_methods:
raise RuntimeError(f"Don't know how to draw a <{type(trace)}> trace...")
traces_drawing_methods[type(trace)](trace)
# Methods that draw each of the traces (for internal use only) -----
def _draw_scatter(self, scatter: Scatter):
if not isinstance(scatter, Scatter):
raise TypeError(f'<scatter> must be an instance of {Scatter}, received object of type {type(scatter)}.')
self.plotly_figure.add_trace(
go.Scatter(
x = scatter.x,
y = scatter.y,
name = scatter.label,
opacity = scatter.alpha,
mode = translate_marker_and_linestyle_to_Plotly_mode(scatter.marker, scatter.linestyle),
marker_symbol = map_marker_to_Plotly_markers(scatter.marker),
showlegend = True if scatter.label is not None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(scatter.linestyle),
)
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(scatter.color)
self.plotly_figure['data'][-1]['line']['width'] = scatter.linewidth
def _draw_errorband(self, errorband: ErrorBand):
if not isinstance(errorband, ErrorBand):
raise TypeError(f'<errorband> must be an instance of {ErrorBand}, received object of type {type(errorband)}.')
x = errorband.x
y1 = errorband.y + errorband.higher
y2 = errorband.y - errorband.lower
legendgroup = str(np.random.rand(3))
# Draw the error band ---
self.plotly_figure.add_trace(
go.Scatter(
x = list(x) + list(x)[::-1],
y = list(y1) + list(y2)[::-1],
opacity = errorband.alpha/2,
mode = 'lines',
name = errorband.label,
legendgroup = legendgroup,
showlegend = False,
line = dict(
color = rgb2hexastr_color(errorband.color),
),
)
)
self.plotly_figure['data'][-1]['fill'] = 'toself'
self.plotly_figure['data'][-1]['hoveron'] = 'points'
self.plotly_figure['data'][-1]['line']['width'] = 0
# Draw the trace itself ---
self.plotly_figure.add_trace(
go.Scatter(
x = errorband.x,
y = errorband.y,
name = errorband.label,
opacity = errorband.alpha,
mode = translate_marker_and_linestyle_to_Plotly_mode(errorband.marker, errorband.linestyle),
marker_symbol = map_marker_to_Plotly_markers(errorband.marker),
showlegend = True if errorband.label is not None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(errorband.linestyle),
color = rgb2hexastr_color(errorband.color),
width = errorband.linewidth,
),
legendgroup = legendgroup,
)
)
def _draw_histogram(self, histogram):
if not isinstance(histogram, Histogram):
raise TypeError(f'<histogram> must be an instance of {Histogram}, received object of type {type(histogram)}.')
x = np.array(histogram.x) # Make a copy to avoid touching the original data.
x[0] = x[1] - (x[3]-x[1]) # Plotly does not plot points in infinity.
x[-1] = x[-2] + (x[-2]-x[-4]) # Plotly does not plot points in infinity.
legendgroup = str(np.random.rand(3))
# The following trace is the histogram lines ---
self.plotly_figure.add_traces(
go.Scatter(
x = x,
y = histogram.y,
opacity = histogram.alpha,
mode = 'lines',
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
showlegend = False,
hoverinfo='skip',
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = histogram.linewidth
# The following trace adds the markers in the middle of each bin ---
if histogram.marker is not None:
self.plotly_figure.add_traces(
go.Scatter(
x = [x[2*i] + (x[2*i+1]-x[2*i])/2 for i in range(int(len(x)/2))],
y = histogram.y[::2],
name = histogram.label,
mode = 'markers',
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
hoverinfo = 'skip',
showlegend = False,
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
# The following trace adds the hover texts ---
self.plotly_figure.add_traces(
go.Scatter(
x = [x[2*i] + (x[2*i+1]-x[2*i])/2 for i in range(int(len(x)/2))],
y = histogram.y[::2],
name = histogram.label,
mode = 'lines',
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
showlegend = False,
text = [f'Bin: (-∞, {histogram.bin_edges[0]})<br>Count: {histogram.bin_counts[0]}'] + [f'Bin: [{histogram.bin_edges[i]}, {histogram.bin_edges[i+1]})<br>Count: {histogram.bin_counts[i+1]}' for i in range(len(histogram.bin_edges)-1)] + [f'Bin: [{histogram.bin_edges[-1]},∞)<br>Count: {histogram.bin_counts[-1]}'],
hovertemplate = "%{text}",
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = 0
# The following trace is to add the item in the legend ---
self.plotly_figure.add_traces(
go.Scatter(
x = [float('NaN')],
y = [float('NaN')],
name = histogram.label,
mode = translate_marker_and_linestyle_to_Plotly_mode(histogram.marker, histogram.linestyle),
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
showlegend = True if histogram.label != None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = histogram.linewidth
def _draw_heatmap(self, heatmap):
if not isinstance(heatmap, Heatmap):
raise TypeError(f'<heatmap> must be an instance of {Heatmap}, received object of type {type(heatmap)}.')
x = heatmap.x
y = heatmap.y
z = heatmap.z
if heatmap.zscale == 'log' and (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. In the plot you will see them as NaN.')
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="invalid value encountered in log")
z = np.log(z)
self.plotly_figure.add_trace(
go.Heatmap(
x = x,
y = y,
z = z,
opacity = heatmap.alpha,
zmin = heatmap.zlim[0] if heatmap.zlim is not None else None,
zmax = heatmap.zlim[1] if heatmap.zlim is not None else None,
colorbar = dict(
title = ('log ' if heatmap.zscale == 'log' else '') + (heatmap.zlabel if heatmap.zlabel is not None else ''),
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else 'x')}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else 'y')}: %{{y}}<br>{(heatmap.zlabel if heatmap.zlabel is not None else 'color scale')}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6
)
)
self.plotly_figure.update_layout(legend_orientation="h")
def _draw_contour(self, contour):
if not isinstance(contour, Contour):
raise TypeError(f'<contour> must be an instance of {Contour}, received object of type {type(contour)}.')
x = contour.x
y = contour.y
z = contour.z
if contour.zscale == 'log' and (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. In the plot you will see them as NaN.')
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="invalid value encountered in log")
z = np.log(z)
lowest_contour = contour.zlim[0] if contour.zlim is not None else contour.z.min()
highest_contour = contour.zlim[1] if contour.zlim is not None else contour.z.max()
if hasattr(contour.contours, '__iter__'):
raise NotImplementedError(f'An iterable specifying which contours to use was not yet implemented. Only implemented an integer number specifying number of equidistant contours.')
n_contours = contour.contours
self.plotly_figure.add_trace(
go.Contour(
x = x,
y = y,
z = z,
opacity = contour.alpha,
zmin = contour.zlim[0] if contour.zlim is not None else None,
zmax = contour.zlim[1] if contour.zlim is not None else None,
colorbar = dict(
title = ('log ' if contour.zscale == 'log' else '') + (contour.zlabel if contour.zlabel is not None else ''),
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else 'x')}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else 'y')}: %{{y}}<br>{(contour.zlabel if contour.zlabel is not None else 'color scale')}: %{{z}}<extra></extra>',
contours = dict(
coloring = 'heatmap',
showlabels = True, # show labels on contours
labelfont = dict( # label font properties
color = 'black',
),
start = lowest_contour,
end = highest_contour,
size = (highest_contour-lowest_contour)/(n_contours),
)
)
)
self.plotly_figure.update_layout(legend_orientation="h")
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is not None and linestyle == 'none':
mode = 'markers'
else:
mode = 'lines'
return mode
def map_marker_to_Plotly_markers(marker):
markers_map = {
'.': 'circle',
'+': 'cross',
'x': 'x',
'o': 'circle-open',
'*': 'star',
None: None
}
return markers_map[marker]
def map_linestyle_to_Plotly_linestyle(linestyle):
linestyle_map = {
'solid': None,
None: None,
'none': None,
'dashed': 'dash',
'dotted': 'dot',
}
return linestyle_map[linestyle]
def rgb2hexastr_color(rgb_color: tuple):
# Assuming that <rgb_color> is a (r,g,b) tuple.
color_str = '#'
for rgb in rgb_color:
color_hex_code = hex(int(rgb*255))[2:]
if len(color_hex_code) < 2:
color_hex_code = f'0{color_hex_code}'
color_str += color_hex_code
return color_str
| from .figure import Figure
from .traces import Scatter, ErrorBand, Histogram, Heatmap, Contour, KDE
import plotly.graph_objects as go
import plotly
import numpy as np
import warnings
class PlotlyFigure(Figure):
def __init__(self):
super().__init__()
self.plotly_figure = go.Figure()
# Methods that must be overridden ----------------------------------
def show(self):
# Overriding this method as specified in the class Figure.
self.plotly_figure.show()
def save(self, file_name=None, include_plotlyjs='cdn', auto_open=False, **kwargs):
# Overriding this method as specified in the class Figure.
if file_name is None:
file_name = self.title
if file_name is None: # If it is still None...
raise ValueError(f'Please provide a name for saving the figure to a file by the <file_name> argument.')
if file_name[-5:] != '.html':
file_name += '.html'
plotly.offline.plot(
self.plotly_figure,
filename = file_name,
auto_open = auto_open,
include_plotlyjs = include_plotlyjs,
**kwargs
)
def draw_layout(self):
# Overriding this method as specified in the class Figure.
if self.show_title == True and self.title != None:
self.plotly_figure.update_layout(title = self.title)
self.plotly_figure.update_layout(
xaxis_title = self.xlabel,
yaxis_title = self.ylabel,
)
# Axes scale:
if self.xscale in [None, 'lin']:
pass
elif self.xscale == 'log':
self.plotly_figure.update_layout(xaxis_type = 'log')
if self.yscale in [None, 'lin']:
pass
elif self.yscale == 'log':
self.plotly_figure.update_layout(yaxis_type = 'log')
if self.aspect == 'equal':
self.plotly_figure.update_yaxes(
scaleanchor = "x",
scaleratio = 1,
)
if self.subtitle != None:
self.plotly_figure.add_annotation(
text = self.subtitle.replace('\n','<br>'),
xref = "paper",
yref = "paper",
x = .5,
y = 1,
align = 'left',
arrowcolor="#ffffff",
font=dict(
family="Courier New, monospace",
color="#999999"
),
)
def draw_trace(self, trace):
# Overriding this method as specified in the class Figure.
traces_drawing_methods = {
Scatter: self._draw_scatter,
ErrorBand: self._draw_errorband,
Histogram: self._draw_histogram,
Heatmap: self._draw_heatmap,
Contour: self._draw_contour,
KDE: self._draw_scatter,
}
if type(trace) not in traces_drawing_methods:
raise RuntimeError(f"Don't know how to draw a <{type(trace)}> trace...")
traces_drawing_methods[type(trace)](trace)
# Methods that draw each of the traces (for internal use only) -----
def _draw_scatter(self, scatter: Scatter):
if not isinstance(scatter, Scatter):
raise TypeError(f'<scatter> must be an instance of {Scatter}, received object of type {type(scatter)}.')
self.plotly_figure.add_trace(
go.Scatter(
x = scatter.x,
y = scatter.y,
name = scatter.label,
opacity = scatter.alpha,
mode = translate_marker_and_linestyle_to_Plotly_mode(scatter.marker, scatter.linestyle),
marker_symbol = map_marker_to_Plotly_markers(scatter.marker),
showlegend = True if scatter.label is not None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(scatter.linestyle),
)
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(scatter.color)
self.plotly_figure['data'][-1]['line']['width'] = scatter.linewidth
def _draw_errorband(self, errorband: ErrorBand):
if not isinstance(errorband, ErrorBand):
raise TypeError(f'<errorband> must be an instance of {ErrorBand}, received object of type {type(errorband)}.')
x = errorband.x
y1 = errorband.y + errorband.higher
y2 = errorband.y - errorband.lower
legendgroup = str(np.random.rand(3))
# Draw the error band ---
self.plotly_figure.add_trace(
go.Scatter(
x = list(x) + list(x)[::-1],
y = list(y1) + list(y2)[::-1],
opacity = errorband.alpha/2,
mode = 'lines',
name = errorband.label,
legendgroup = legendgroup,
showlegend = False,
line = dict(
color = rgb2hexastr_color(errorband.color),
),
)
)
self.plotly_figure['data'][-1]['fill'] = 'toself'
self.plotly_figure['data'][-1]['hoveron'] = 'points'
self.plotly_figure['data'][-1]['line']['width'] = 0
# Draw the trace itself ---
self.plotly_figure.add_trace(
go.Scatter(
x = errorband.x,
y = errorband.y,
name = errorband.label,
opacity = errorband.alpha,
mode = translate_marker_and_linestyle_to_Plotly_mode(errorband.marker, errorband.linestyle),
marker_symbol = map_marker_to_Plotly_markers(errorband.marker),
showlegend = True if errorband.label is not None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(errorband.linestyle),
color = rgb2hexastr_color(errorband.color),
width = errorband.linewidth,
),
legendgroup = legendgroup,
)
)
def _draw_histogram(self, histogram):
if not isinstance(histogram, Histogram):
raise TypeError(f'<histogram> must be an instance of {Histogram}, received object of type {type(histogram)}.')
x = np.array(histogram.x) # Make a copy to avoid touching the original data.
x[0] = x[1] - (x[3]-x[1]) # Plotly does not plot points in infinity.
x[-1] = x[-2] + (x[-2]-x[-4]) # Plotly does not plot points in infinity.
legendgroup = str(np.random.rand(3))
# The following trace is the histogram lines ---
self.plotly_figure.add_traces(
go.Scatter(
x = x,
y = histogram.y,
opacity = histogram.alpha,
mode = 'lines',
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
showlegend = False,
hoverinfo='skip',
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = histogram.linewidth
# The following trace adds the markers in the middle of each bin ---
if histogram.marker is not None:
self.plotly_figure.add_traces(
go.Scatter(
x = [x[2*i] + (x[2*i+1]-x[2*i])/2 for i in range(int(len(x)/2))],
y = histogram.y[::2],
name = histogram.label,
mode = 'markers',
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
hoverinfo = 'skip',
showlegend = False,
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
# The following trace adds the hover texts ---
self.plotly_figure.add_traces(
go.Scatter(
x = [x[2*i] + (x[2*i+1]-x[2*i])/2 for i in range(int(len(x)/2))],
y = histogram.y[::2],
name = histogram.label,
mode = 'lines',
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
showlegend = False,
text = [f'Bin: (-∞, {histogram.bin_edges[0]})<br>Count: {histogram.bin_counts[0]}'] + [f'Bin: [{histogram.bin_edges[i]}, {histogram.bin_edges[i+1]})<br>Count: {histogram.bin_counts[i+1]}' for i in range(len(histogram.bin_edges)-1)] + [f'Bin: [{histogram.bin_edges[-1]},∞)<br>Count: {histogram.bin_counts[-1]}'],
hovertemplate = "%{text}",
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = 0
# The following trace is to add the item in the legend ---
self.plotly_figure.add_traces(
go.Scatter(
x = [float('NaN')],
y = [float('NaN')],
name = histogram.label,
mode = translate_marker_and_linestyle_to_Plotly_mode(histogram.marker, histogram.linestyle),
marker_symbol = map_marker_to_Plotly_markers(histogram.marker),
opacity = histogram.alpha,
showlegend = True if histogram.label != None else False,
line = dict(
dash = map_linestyle_to_Plotly_linestyle(histogram.linestyle),
),
legendgroup = legendgroup,
)
)
self.plotly_figure['data'][-1]['marker']['color'] = rgb2hexastr_color(histogram.color)
self.plotly_figure['data'][-1]['line']['width'] = histogram.linewidth
def _draw_heatmap(self, heatmap):
if not isinstance(heatmap, Heatmap):
raise TypeError(f'<heatmap> must be an instance of {Heatmap}, received object of type {type(heatmap)}.')
x = heatmap.x
y = heatmap.y
z = heatmap.z
if heatmap.zscale == 'log' and (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. In the plot you will see them as NaN.')
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="invalid value encountered in log")
z = np.log(z)
self.plotly_figure.add_trace(
go.Heatmap(
x = x,
y = y,
z = z,
opacity = heatmap.alpha,
zmin = heatmap.zlim[0] if heatmap.zlim is not None else None,
zmax = heatmap.zlim[1] if heatmap.zlim is not None else None,
colorbar = dict(
title = ('log ' if heatmap.zscale == 'log' else '') + (heatmap.zlabel if heatmap.zlabel is not None else ''),
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else "x")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else "y")}: %{{y}}<br>{(heatmap.zlabel if heatmap.zlabel is not None else "color scale")}: %{{z}}<extra></extra>', # https://community.plotly.com/t/heatmap-changing-x-y-and-z-label-on-tooltip/23588/6
)
)
self.plotly_figure.update_layout(legend_orientation="h")
def _draw_contour(self, contour):
if not isinstance(contour, Contour):
raise TypeError(f'<contour> must be an instance of {Contour}, received object of type {type(contour)}.')
x = contour.x
y = contour.y
z = contour.z
if contour.zscale == 'log' and (z<=0).any():
warnings.warn('Warning: log color scale was selected and there are <z> values <= 0. In the plot you will see them as NaN.')
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="invalid value encountered in log")
z = np.log(z)
lowest_contour = contour.zlim[0] if contour.zlim is not None else contour.z.min()
highest_contour = contour.zlim[1] if contour.zlim is not None else contour.z.max()
if hasattr(contour.contours, '__iter__'):
raise NotImplementedError(f'An iterable specifying which contours to use was not yet implemented. Only implemented an integer number specifying number of equidistant contours.')
n_contours = contour.contours
self.plotly_figure.add_trace(
go.Contour(
x = x,
y = y,
z = z,
opacity = contour.alpha,
zmin = contour.zlim[0] if contour.zlim is not None else None,
zmax = contour.zlim[1] if contour.zlim is not None else None,
colorbar = dict(
title = ('log ' if contour.zscale == 'log' else '') + (contour.zlabel if contour.zlabel is not None else ''),
titleside = 'right',
),
hovertemplate = f'{(self.xlabel if self.xlabel is not None else "x")}: %{{x}}<br>{(self.ylabel if self.ylabel is not None else "y")}: %{{y}}<br>{(contour.zlabel if contour.zlabel is not None else "color scale")}: %{{z}}<extra></extra>',
contours = dict(
coloring = 'heatmap',
showlabels = True, # show labels on contours
labelfont = dict( # label font properties
color = 'black',
),
start = lowest_contour,
end = highest_contour,
size = (highest_contour-lowest_contour)/(n_contours),
)
)
)
self.plotly_figure.update_layout(legend_orientation="h")
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is not None and linestyle == 'none':
mode = 'markers'
else:
mode = 'lines'
return mode
def map_marker_to_Plotly_markers(marker):
markers_map = {
'.': 'circle',
'+': 'cross',
'x': 'x',
'o': 'circle-open',
'*': 'star',
None: None
}
return markers_map[marker]
def map_linestyle_to_Plotly_linestyle(linestyle):
linestyle_map = {
'solid': None,
None: None,
'none': None,
'dashed': 'dash',
'dotted': 'dot',
}
return linestyle_map[linestyle]
def rgb2hexastr_color(rgb_color: tuple):
# Assuming that <rgb_color> is a (r,g,b) tuple.
color_str = '#'
for rgb in rgb_color:
color_hex_code = hex(int(rgb*255))[2:]
if len(color_hex_code) < 2:
color_hex_code = f'0{color_hex_code}'
color_str += color_hex_code
return color_str
|
print("importing")
from datasets import load_dataset
from datasets import load_metric
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import TrainingArguments, DefaultFlowCallback, PrinterCallback
from transformers import Trainer
import torch
from torch import nn
import numpy as np
import pickle
from sklearn.preprocessing import StandardScaler
import random
import json
sep_token = "[SEP]" # FORDOR maybe many special tokens
pretrained_model_name = "roberta-base" # 'bert-base-cased'
class my_Bert(nn.Module):
def __init__(self, bert):
super().__init__()
self.bert = bert
def forward(self,input_ids,attention_mask=None,labels=None,**kwargs):
res = self.bert.forward(input_ids,attention_mask,labels=labels,**kwargs)
print(f"FORDOR-input_ids {input_ids}")
print(f"FORDOR-inputss {tokenizer.decode(input_ids[0])}")
print(f"FORDOR-inputss {tokenizer.decode(input_ids[1])}")
print(f"FORDOR-labels {labels}")
print(f"FORDOR-res {res}")
return res
print("starting load")
# for i in range(len(dataset["train_eli5"])):
# print(f'train= {dataset['train_eli5'][i]['answers']}')
# print(f'valid= {dataset['validation_eli5'][i]['answers']}')
# print(f'test= {dataset['test_eli5'][i]['answers']}')
class ELI5MetricDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
def changeArr(input1):
# Copy input array into newArray
newArray = input1.copy()
# Sort newArray[] in ascending order
newArray.sort()
# Dictionary to store the rank of
# the array element
ranks = {}
rank = 1
for index in range(len(newArray)):
element = newArray[index];
# Update rank of element
if element not in ranks:
ranks[element] = rank
rank += 1
# Assign ranks to elements
for index in range(len(input1)):
element = input1[index]
input1[index] = float(ranks[input1[index]])
my_dataset = {}
if False:# try:
with open("my_dataset.pickle", "rb" ) as f:
my_dataset = pickle.load(f)
else: # except IOError:
print("could not load my_dataset - preprocessing")
raw_datasets = load_dataset("eli5")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)
def preprocess_data(split_name):
with open(f'{split_name}.json', 'a') as the_file:
inputs = []
labels = []
cnt = 0
for example in raw_datasets[split_name]:
question = example["title"]+ example["selftext"] #FORDOR add special sep token?
for i in range (len (example["answers"]["a_id"])):
answer = example["answers"]["text"][i]
# question = question.replace('"','\\"')
# answer = answer.replace('"','\\"')
the_file.write(f'{{'text': {json.dumps(question)}, "summary": {json.dumps(answer)} }}\n')
# inputs.append(question + sep_token + answer)
# print (f'FORDOR float - {float(example['answers']['score'][i])} {example['answers']['score'][i]}')
# labels.append(float(example["answers"]["score"][i]))
cnt = cnt+1
if cnt > 200000:
break
# tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)
#shuffle data
# c = list(zip(inputs, labels))
# random.seed(42)
# random.shuffle(c)
# inputs, labels = zip(*c)
# inputs = list(inputs)
# labels = list(labels)
# encodings = tokenizer(inputs, padding="max_length", truncation=True)
# encodings2 = tokenizer(inputs, padding="max_length", truncation=False)
# for i in range(len(encodings)):
# if len(encodings[i]) != len( encodings2[i]):
# print (print(f"encoding and length {encodings[i]}, {len(encodings[i])} no truncation = {encodings2[i]}, {len(encodings2[i])}"))
#
# tensor_labels = torch.as_tensor(labels).reshape(-1,1)
# scaler = StandardScaler()
# scaler.fit(tensor_labels)
# scaled_labels = scaler.transform(tensor_labels).astype(np.float32)
# changeArr(labels)
# my_dataset[split_name] = ELI5MetricDataset(encodings, scaled_labels)
# print (f"FORDOR lens {len(encodings)}=={len(labels)}")
# assert len(encodings) == len(labels)
preprocess_data("train_eli5")
preprocess_data("validation_eli5")
# pickle.dump( my_dataset, open( "my_dataset.pickle", "wb" ) )
# metric = load_metric("spearmanr")
# def compute_metrics(eval_pred):
# logits, labels = eval_pred
# print(f'logits- {max(logits)}, {min(logits)}')
# print(f'labels- {max(labels)}, {min(labels)}')
# return metric.compute(predictions=logits, references=labels)
# model = AutoModelForSequenceClassification.from_pretrained(pretrained_model_name, num_labels=1)
# # freezing bert parameters leaving only regression layer
# # for param in model.bert.parameters():
# # param.requires_grad = False
# # model = my_Bert(model)
# # print (f"FORDOR model = {str(model)}")
# # print (f'FORDOR debug {raw_datasets['train_eli5'][0]['answers']} =:= {model(input_ids=my_dataset['train_eli5'][0]['input_ids'].unsqueeze(0), attention_mask=my_dataset['train_eli5'][0]['attention_mask'].unsqueeze(0), token_type_ids=my_dataset['train_eli5'][0]['token_type_ids'].unsqueeze(0))}')
# training_args = TrainingArguments("test_trainer", evaluation_strategy="steps", eval_steps=10000, save_steps=10000, per_device_train_batch_size=8, per_device_eval_batch_size=8)
# trainer = Trainer(model=model, args=training_args, train_dataset=my_dataset["train_eli5"], eval_dataset=my_dataset["validation_eli5"], compute_metrics=compute_metrics,
# callbacks = [
# DefaultFlowCallback(),
# PrinterCallback()
# ],
# )
# #, max_steps=3000
# trainer.train()
# # model.eval()
# # print (f'FORDOR2 debug {raw_datasets['train_eli5'][0]['answers']} =:= {model(input_ids=my_dataset['train_eli5'][0]['input_ids'].unsqueeze(0).cuda(), attention_mask=my_dataset['train_eli5'][0]['attention_mask'].unsqueeze(0).cuda(), token_type_ids=my_dataset['train_eli5'][0]['token_type_ids'].unsqueeze(0).cuda())}')
# # print (f'FORDOR3 debug {raw_datasets['train_eli5'][0]['answers']} =:= {model(input_ids=my_dataset['train_eli5'][1]['input_ids'].unsqueeze(0).cuda(), attention_mask=my_dataset['train_eli5'][1]['attention_mask'].unsqueeze(0).cuda(), token_type_ids=my_dataset['train_eli5'][1]['token_type_ids'].unsqueeze(0).cuda())}')
# # print (f'FORDOR4 debug {raw_datasets['train_eli5'][1]['answers']} =:= {model(input_ids=my_dataset['train_eli5'][4]['input_ids'].unsqueeze(0).cuda(), attention_mask=my_dataset['train_eli5'][4]['attention_mask'].unsqueeze(0).cuda(), token_type_ids=my_dataset['train_eli5'][4]['token_type_ids'].unsqueeze(0).cuda())}')
# print ("evaluation starting")
# print (trainer.evaluate())
| print("importing")
from datasets import load_dataset
from datasets import load_metric
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import TrainingArguments, DefaultFlowCallback, PrinterCallback
from transformers import Trainer
import torch
from torch import nn
import numpy as np
import pickle
from sklearn.preprocessing import StandardScaler
import random
import json
sep_token = "[SEP]" # FORDOR maybe many special tokens
pretrained_model_name = "roberta-base" # 'bert-base-cased'
class my_Bert(nn.Module):
def __init__(self, bert):
super().__init__()
self.bert = bert
def forward(self,input_ids,attention_mask=None,labels=None,**kwargs):
res = self.bert.forward(input_ids,attention_mask,labels=labels,**kwargs)
print(f"FORDOR-input_ids {input_ids}")
print(f"FORDOR-inputss {tokenizer.decode(input_ids[0])}")
print(f"FORDOR-inputss {tokenizer.decode(input_ids[1])}")
print(f"FORDOR-labels {labels}")
print(f"FORDOR-res {res}")
return res
print("starting load")
# for i in range(len(dataset["train_eli5"])):
# print(f'train= {dataset["train_eli5"][i]["answers"]}')
# print(f'valid= {dataset["validation_eli5"][i]["answers"]}')
# print(f'test= {dataset["test_eli5"][i]["answers"]}')
class ELI5MetricDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
def changeArr(input1):
# Copy input array into newArray
newArray = input1.copy()
# Sort newArray[] in ascending order
newArray.sort()
# Dictionary to store the rank of
# the array element
ranks = {}
rank = 1
for index in range(len(newArray)):
element = newArray[index];
# Update rank of element
if element not in ranks:
ranks[element] = rank
rank += 1
# Assign ranks to elements
for index in range(len(input1)):
element = input1[index]
input1[index] = float(ranks[input1[index]])
my_dataset = {}
if False:# try:
with open("my_dataset.pickle", "rb" ) as f:
my_dataset = pickle.load(f)
else: # except IOError:
print("could not load my_dataset - preprocessing")
raw_datasets = load_dataset("eli5")
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)
def preprocess_data(split_name):
with open(f'{split_name}.json', 'a') as the_file:
inputs = []
labels = []
cnt = 0
for example in raw_datasets[split_name]:
question = example["title"]+ example["selftext"] #FORDOR add special sep token?
for i in range (len (example["answers"]["a_id"])):
answer = example["answers"]["text"][i]
# question = question.replace('"','\\"')
# answer = answer.replace('"','\\"')
the_file.write(f'{{"text": {json.dumps(question)}, "summary": {json.dumps(answer)} }}\n')
# inputs.append(question + sep_token + answer)
# print (f'FORDOR float - {float(example["answers"]["score"][i])} {example["answers"]["score"][i]}')
# labels.append(float(example["answers"]["score"][i]))
cnt = cnt+1
if cnt > 200000:
break
# tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)
#shuffle data
# c = list(zip(inputs, labels))
# random.seed(42)
# random.shuffle(c)
# inputs, labels = zip(*c)
# inputs = list(inputs)
# labels = list(labels)
# encodings = tokenizer(inputs, padding="max_length", truncation=True)
# encodings2 = tokenizer(inputs, padding="max_length", truncation=False)
# for i in range(len(encodings)):
# if len(encodings[i]) != len( encodings2[i]):
# print (print(f"encoding and length {encodings[i]}, {len(encodings[i])} no truncation = {encodings2[i]}, {len(encodings2[i])}"))
#
# tensor_labels = torch.as_tensor(labels).reshape(-1,1)
# scaler = StandardScaler()
# scaler.fit(tensor_labels)
# scaled_labels = scaler.transform(tensor_labels).astype(np.float32)
# changeArr(labels)
# my_dataset[split_name] = ELI5MetricDataset(encodings, scaled_labels)
# print (f"FORDOR lens {len(encodings)}=={len(labels)}")
# assert len(encodings) == len(labels)
preprocess_data("train_eli5")
preprocess_data("validation_eli5")
# pickle.dump( my_dataset, open( "my_dataset.pickle", "wb" ) )
# metric = load_metric("spearmanr")
# def compute_metrics(eval_pred):
# logits, labels = eval_pred
# print(f'logits- {max(logits)}, {min(logits)}')
# print(f'labels- {max(labels)}, {min(labels)}')
# return metric.compute(predictions=logits, references=labels)
# model = AutoModelForSequenceClassification.from_pretrained(pretrained_model_name, num_labels=1)
# # freezing bert parameters leaving only regression layer
# # for param in model.bert.parameters():
# # param.requires_grad = False
# # model = my_Bert(model)
# # print (f"FORDOR model = {str(model)}")
# # print (f'FORDOR debug {raw_datasets["train_eli5"][0]["answers"]} =:= {model(input_ids=my_dataset["train_eli5"][0]["input_ids"].unsqueeze(0), attention_mask=my_dataset["train_eli5"][0]["attention_mask"].unsqueeze(0), token_type_ids=my_dataset["train_eli5"][0]["token_type_ids"].unsqueeze(0))}')
# training_args = TrainingArguments("test_trainer", evaluation_strategy="steps", eval_steps=10000, save_steps=10000, per_device_train_batch_size=8, per_device_eval_batch_size=8)
# trainer = Trainer(model=model, args=training_args, train_dataset=my_dataset["train_eli5"], eval_dataset=my_dataset["validation_eli5"], compute_metrics=compute_metrics,
# callbacks = [
# DefaultFlowCallback(),
# PrinterCallback()
# ],
# )
# #, max_steps=3000
# trainer.train()
# # model.eval()
# # print (f'FORDOR2 debug {raw_datasets["train_eli5"][0]["answers"]} =:= {model(input_ids=my_dataset["train_eli5"][0]["input_ids"].unsqueeze(0).cuda(), attention_mask=my_dataset["train_eli5"][0]["attention_mask"].unsqueeze(0).cuda(), token_type_ids=my_dataset["train_eli5"][0]["token_type_ids"].unsqueeze(0).cuda())}')
# # print (f'FORDOR3 debug {raw_datasets["train_eli5"][0]["answers"]} =:= {model(input_ids=my_dataset["train_eli5"][1]["input_ids"].unsqueeze(0).cuda(), attention_mask=my_dataset["train_eli5"][1]["attention_mask"].unsqueeze(0).cuda(), token_type_ids=my_dataset["train_eli5"][1]["token_type_ids"].unsqueeze(0).cuda())}')
# # print (f'FORDOR4 debug {raw_datasets["train_eli5"][1]["answers"]} =:= {model(input_ids=my_dataset["train_eli5"][4]["input_ids"].unsqueeze(0).cuda(), attention_mask=my_dataset["train_eli5"][4]["attention_mask"].unsqueeze(0).cuda(), token_type_ids=my_dataset["train_eli5"][4]["token_type_ids"].unsqueeze(0).cuda())}')
# print ("evaluation starting")
# print (trainer.evaluate())
|
import os
import tempfile
from contextlib import contextmanager
from ..hdl import *
from ..hdl.ast import SignalSet
from ..hdl.xfrm import ValueVisitor, StatementVisitor, LHSGroupFilter
from ._base import BaseProcess
__all__ = ["PyRTLProcess"]
class PyRTLProcess(BaseProcess):
__slots__ = ("is_comb", "runnable", "passive", "run")
def __init__(self, *, is_comb):
self.is_comb = is_comb
self.reset()
def reset(self):
self.runnable = self.is_comb
self.passive = True
class _PythonEmitter:
def __init__(self):
self._buffer = []
self._suffix = 0
self._level = 0
def append(self, code):
self._buffer.append(" " * self._level)
self._buffer.append(code)
self._buffer.append("\n")
@contextmanager
def indent(self):
self._level += 1
yield
self._level -= 1
def flush(self, indent=""):
code = "".join(self._buffer)
self._buffer.clear()
return code
def gen_var(self, prefix):
name = f"{prefix}_{self._suffix}"
self._suffix += 1
return name
def def_var(self, prefix, value):
name = self.gen_var(prefix)
self.append(f"{name} = {value}")
return name
class _Compiler:
def __init__(self, state, emitter):
self.state = state
self.emitter = emitter
class _ValueCompiler(ValueVisitor, _Compiler):
helpers = {
"sign": lambda value, sign: value | sign if value & sign else value,
"zdiv": lambda lhs, rhs: 0 if rhs == 0 else lhs // rhs,
"zmod": lambda lhs, rhs: 0 if rhs == 0 else lhs % rhs,
}
def on_ClockSignal(self, value):
raise NotImplementedError # :nocov:
def on_ResetSignal(self, value):
raise NotImplementedError # :nocov:
def on_AnyConst(self, value):
raise NotImplementedError # :nocov:
def on_AnySeq(self, value):
raise NotImplementedError # :nocov:
def on_Sample(self, value):
raise NotImplementedError # :nocov:
def on_Initial(self, value):
raise NotImplementedError # :nocov:
class _RHSValueCompiler(_ValueCompiler):
def __init__(self, state, emitter, *, mode, inputs=None):
super().__init__(state, emitter)
assert mode in ("curr", "next")
self.mode = mode
# If not None, `inputs` gets populated with RHS signals.
self.inputs = inputs
def on_Const(self, value):
return f"{value.value}"
def on_Signal(self, value):
if self.inputs is not None:
self.inputs.add(value)
if self.mode == "curr":
return f"slots[{self.state.get_signal(value)}].{self.mode}"
else:
return f"next_{self.state.get_signal(value)}"
def on_Operator(self, value):
def mask(value):
value_mask = (1 << len(value)) - 1
return f"({value_mask} & {self(value)})"
def sign(value):
if value.shape().signed:
return f"sign({mask(value)}, {-1 << (len(value) - 1)})"
else: # unsigned
return mask(value)
if len(value.operands) == 1:
arg, = value.operands
if value.operator == "~":
return f"(~{self(arg)})"
if value.operator == "-":
return f"(-{sign(arg)})"
if value.operator == "b":
return f"bool({mask(arg)})"
if value.operator == "r|":
return f"(0 != {mask(arg)})"
if value.operator == "r&":
return f"({(1 << len(arg)) - 1} == {mask(arg)})"
if value.operator == "r^":
# Believe it or not, this is the fastest way to compute a sideways XOR in Python.
return f"(format({mask(arg)}, 'b').count('1') % 2)"
if value.operator in ("u", "s"):
# These operators don't change the bit pattern, only its interpretation.
return self(arg)
elif len(value.operands) == 2:
lhs, rhs = value.operands
lhs_mask = (1 << len(lhs)) - 1
rhs_mask = (1 << len(rhs)) - 1
if value.operator == "+":
return f"({sign(lhs)} + {sign(rhs)})"
if value.operator == "-":
return f"({sign(lhs)} - {sign(rhs)})"
if value.operator == "*":
return f"({sign(lhs)} * {sign(rhs)})"
if value.operator == "//":
return f"zdiv({sign(lhs)}, {sign(rhs)})"
if value.operator == "%":
return f"zmod({sign(lhs)}, {sign(rhs)})"
if value.operator == "&":
return f"({self(lhs)} & {self(rhs)})"
if value.operator == "|":
return f"({self(lhs)} | {self(rhs)})"
if value.operator == "^":
return f"({self(lhs)} ^ {self(rhs)})"
if value.operator == "<<":
return f"({sign(lhs)} << {sign(rhs)})"
if value.operator == ">>":
return f"({sign(lhs)} >> {sign(rhs)})"
if value.operator == "==":
return f"({sign(lhs)} == {sign(rhs)})"
if value.operator == "!=":
return f"({sign(lhs)} != {sign(rhs)})"
if value.operator == "<":
return f"({sign(lhs)} < {sign(rhs)})"
if value.operator == "<=":
return f"({sign(lhs)} <= {sign(rhs)})"
if value.operator == ">":
return f"({sign(lhs)} > {sign(rhs)})"
if value.operator == ">=":
return f"({sign(lhs)} >= {sign(rhs)})"
elif len(value.operands) == 3:
if value.operator == "m":
sel, val1, val0 = value.operands
return f"({self(val1)} if {self(sel)} else {self(val0)})"
raise NotImplementedError("Operator '{}' not implemented".format(value.operator)) # :nocov:
def on_Slice(self, value):
return f"({(1 << len(value)) - 1} & ({self(value.value)} >> {value.start}))"
def on_Part(self, value):
offset_mask = (1 << len(value.offset)) - 1
offset = f"({value.stride} * ({offset_mask} & {self(value.offset)}))"
return f"({(1 << value.width) - 1} & " \
f"{self(value.value)} >> {offset})"
def on_Cat(self, value):
gen_parts = []
offset = 0
for part in value.parts:
part_mask = (1 << len(part)) - 1
gen_parts.append(f"(({part_mask} & {self(part)}) << {offset})")
offset += len(part)
if gen_parts:
return f"({" | ".join(gen_parts)})"
return f"0"
def on_Repl(self, value):
part_mask = (1 << len(value.value)) - 1
gen_part = self.emitter.def_var("repl", f"{part_mask} & {self(value.value)}")
gen_parts = []
offset = 0
for _ in range(value.count):
gen_parts.append(f"({gen_part} << {offset})")
offset += len(value.value)
if gen_parts:
return f"({" | ".join(gen_parts)})"
return f"0"
def on_ArrayProxy(self, value):
index_mask = (1 << len(value.index)) - 1
gen_index = self.emitter.def_var("rhs_index", f"{index_mask} & {self(value.index)}")
gen_value = self.emitter.gen_var("rhs_proxy")
if value.elems:
gen_elems = []
for index, elem in enumerate(value.elems):
if index == 0:
self.emitter.append(f"if {index} == {gen_index}:")
else:
self.emitter.append(f"elif {index} == {gen_index}:")
with self.emitter.indent():
self.emitter.append(f"{gen_value} = {self(elem)}")
self.emitter.append(f"else:")
with self.emitter.indent():
self.emitter.append(f"{gen_value} = {self(value.elems[-1])}")
return gen_value
else:
return f"0"
@classmethod
def compile(cls, state, value, *, mode):
emitter = _PythonEmitter()
compiler = cls(state, emitter, mode=mode)
emitter.append(f"result = {compiler(value)}")
return emitter.flush()
class _LHSValueCompiler(_ValueCompiler):
def __init__(self, state, emitter, *, rhs, outputs=None):
super().__init__(state, emitter)
# `rrhs` is used to translate rvalues that are syntactically a part of an lvalue, e.g.
# the offset of a Part.
self.rrhs = rhs
# `lrhs` is used to translate the read part of a read-modify-write cycle during partial
# update of an lvalue.
self.lrhs = _RHSValueCompiler(state, emitter, mode="next", inputs=None)
# If not None, `outputs` gets populated with signals on LHS.
self.outputs = outputs
def on_Const(self, value):
raise TypeError # :nocov:
def on_Signal(self, value):
if self.outputs is not None:
self.outputs.add(value)
def gen(arg):
value_mask = (1 << len(value)) - 1
if value.shape().signed:
value_sign = f"sign({value_mask} & {arg}, {-1 << (len(value) - 1)})"
else: # unsigned
value_sign = f"{value_mask} & {arg}"
self.emitter.append(f"next_{self.state.get_signal(value)} = {value_sign}")
return gen
def on_Operator(self, value):
raise TypeError # :nocov:
def on_Slice(self, value):
def gen(arg):
width_mask = (1 << (value.stop - value.start)) - 1
self(value.value)(f"({self.lrhs(value.value)} & " \
f"{~(width_mask << value.start)} | " \
f"(({width_mask} & {arg}) << {value.start}))")
return gen
def on_Part(self, value):
def gen(arg):
width_mask = (1 << value.width) - 1
offset_mask = (1 << len(value.offset)) - 1
offset = f"({value.stride} * ({offset_mask} & {self.rrhs(value.offset)}))"
self(value.value)(f"({self.lrhs(value.value)} & " \
f"~({width_mask} << {offset}) | " \
f"(({width_mask} & {arg}) << {offset}))")
return gen
def on_Cat(self, value):
def gen(arg):
gen_arg = self.emitter.def_var("cat", arg)
gen_parts = []
offset = 0
for part in value.parts:
part_mask = (1 << len(part)) - 1
self(part)(f"({part_mask} & ({gen_arg} >> {offset}))")
offset += len(part)
return gen
def on_Repl(self, value):
raise TypeError # :nocov:
def on_ArrayProxy(self, value):
def gen(arg):
index_mask = (1 << len(value.index)) - 1
gen_index = self.emitter.def_var("index", f"{self.rrhs(value.index)} & {index_mask}")
if value.elems:
gen_elems = []
for index, elem in enumerate(value.elems):
if index == 0:
self.emitter.append(f"if {index} == {gen_index}:")
else:
self.emitter.append(f"elif {index} == {gen_index}:")
with self.emitter.indent():
self(elem)(arg)
self.emitter.append(f"else:")
with self.emitter.indent():
self(value.elems[-1])(arg)
else:
self.emitter.append(f"pass")
return gen
class _StatementCompiler(StatementVisitor, _Compiler):
def __init__(self, state, emitter, *, inputs=None, outputs=None):
super().__init__(state, emitter)
self.rhs = _RHSValueCompiler(state, emitter, mode="curr", inputs=inputs)
self.lhs = _LHSValueCompiler(state, emitter, rhs=self.rhs, outputs=outputs)
def on_statements(self, stmts):
for stmt in stmts:
self(stmt)
if not stmts:
self.emitter.append("pass")
def on_Assign(self, stmt):
gen_rhs = f"({(1 << len(stmt.rhs)) - 1} & {self.rhs(stmt.rhs)})"
if stmt.rhs.shape().signed:
gen_rhs = f"sign({gen_rhs}, {-1 << (len(stmt.rhs) - 1)})"
return self.lhs(stmt.lhs)(gen_rhs)
def on_Switch(self, stmt):
gen_test = self.emitter.def_var("test",
f"{(1 << len(stmt.test)) - 1} & {self.rhs(stmt.test)}")
for index, (patterns, stmts) in enumerate(stmt.cases.items()):
gen_checks = []
if not patterns:
gen_checks.append(f"True")
else:
for pattern in patterns:
if "-" in pattern:
mask = int("".join("0" if b == "-" else "1" for b in pattern), 2)
value = int("".join("0" if b == "-" else b for b in pattern), 2)
gen_checks.append(f"{value} == ({mask} & {gen_test})")
else:
value = int(pattern, 2)
gen_checks.append(f"{value} == {gen_test}")
if index == 0:
self.emitter.append(f"if {" or ".join(gen_checks)}:")
else:
self.emitter.append(f"elif {" or ".join(gen_checks)}:")
with self.emitter.indent():
self(stmts)
def on_Assert(self, stmt):
raise NotImplementedError # :nocov:
def on_Assume(self, stmt):
raise NotImplementedError # :nocov:
def on_Cover(self, stmt):
raise NotImplementedError # :nocov:
@classmethod
def compile(cls, state, stmt):
output_indexes = [state.get_signal(signal) for signal in stmt._lhs_signals()]
emitter = _PythonEmitter()
for signal_index in output_indexes:
emitter.append(f"next_{signal_index} = slots[{signal_index}].next")
compiler = cls(state, emitter)
compiler(stmt)
for signal_index in output_indexes:
emitter.append(f"slots[{signal_index}].set(next_{signal_index})")
return emitter.flush()
class _FragmentCompiler:
def __init__(self, state):
self.state = state
def __call__(self, fragment):
processes = set()
for domain_name, domain_signals in fragment.drivers.items():
domain_stmts = LHSGroupFilter(domain_signals)(fragment.statements)
domain_process = PyRTLProcess(is_comb=domain_name is None)
emitter = _PythonEmitter()
emitter.append(f"def run():")
emitter._level += 1
if domain_name is None:
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"next_{signal_index} = {signal.reset}")
inputs = SignalSet()
_StatementCompiler(self.state, emitter, inputs=inputs)(domain_stmts)
for input in inputs:
self.state.add_trigger(domain_process, input)
else:
domain = fragment.domains[domain_name]
clk_trigger = 1 if domain.clk_edge == "pos" else 0
self.state.add_trigger(domain_process, domain.clk, trigger=clk_trigger)
if domain.rst is not None and domain.async_reset:
rst_trigger = 1
self.state.add_trigger(domain_process, domain.rst, trigger=rst_trigger)
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"next_{signal_index} = slots[{signal_index}].next")
_StatementCompiler(self.state, emitter)(domain_stmts)
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"slots[{signal_index}].set(next_{signal_index})")
# There shouldn't be any exceptions raised by the generated code, but if there are
# (almost certainly due to a bug in the code generator), use this environment variable
# to make backtraces useful.
code = emitter.flush()
if os.getenv("NMIGEN_pysim_dump"):
file = tempfile.NamedTemporaryFile("w", prefix="nmigen_pysim_", delete=False)
file.write(code)
filename = file.name
else:
filename = "<string>"
exec_locals = {"slots": self.state.slots, **_ValueCompiler.helpers}
exec(compile(code, filename, "exec"), exec_locals)
domain_process.run = exec_locals["run"]
processes.add(domain_process)
for subfragment_index, (subfragment, subfragment_name) in enumerate(fragment.subfragments):
if subfragment_name is None:
subfragment_name = "U${}".format(subfragment_index)
processes.update(self(subfragment))
return processes
| import os
import tempfile
from contextlib import contextmanager
from ..hdl import *
from ..hdl.ast import SignalSet
from ..hdl.xfrm import ValueVisitor, StatementVisitor, LHSGroupFilter
from ._base import BaseProcess
__all__ = ["PyRTLProcess"]
class PyRTLProcess(BaseProcess):
__slots__ = ("is_comb", "runnable", "passive", "run")
def __init__(self, *, is_comb):
self.is_comb = is_comb
self.reset()
def reset(self):
self.runnable = self.is_comb
self.passive = True
class _PythonEmitter:
def __init__(self):
self._buffer = []
self._suffix = 0
self._level = 0
def append(self, code):
self._buffer.append(" " * self._level)
self._buffer.append(code)
self._buffer.append("\n")
@contextmanager
def indent(self):
self._level += 1
yield
self._level -= 1
def flush(self, indent=""):
code = "".join(self._buffer)
self._buffer.clear()
return code
def gen_var(self, prefix):
name = f"{prefix}_{self._suffix}"
self._suffix += 1
return name
def def_var(self, prefix, value):
name = self.gen_var(prefix)
self.append(f"{name} = {value}")
return name
class _Compiler:
def __init__(self, state, emitter):
self.state = state
self.emitter = emitter
class _ValueCompiler(ValueVisitor, _Compiler):
helpers = {
"sign": lambda value, sign: value | sign if value & sign else value,
"zdiv": lambda lhs, rhs: 0 if rhs == 0 else lhs // rhs,
"zmod": lambda lhs, rhs: 0 if rhs == 0 else lhs % rhs,
}
def on_ClockSignal(self, value):
raise NotImplementedError # :nocov:
def on_ResetSignal(self, value):
raise NotImplementedError # :nocov:
def on_AnyConst(self, value):
raise NotImplementedError # :nocov:
def on_AnySeq(self, value):
raise NotImplementedError # :nocov:
def on_Sample(self, value):
raise NotImplementedError # :nocov:
def on_Initial(self, value):
raise NotImplementedError # :nocov:
class _RHSValueCompiler(_ValueCompiler):
def __init__(self, state, emitter, *, mode, inputs=None):
super().__init__(state, emitter)
assert mode in ("curr", "next")
self.mode = mode
# If not None, `inputs` gets populated with RHS signals.
self.inputs = inputs
def on_Const(self, value):
return f"{value.value}"
def on_Signal(self, value):
if self.inputs is not None:
self.inputs.add(value)
if self.mode == "curr":
return f"slots[{self.state.get_signal(value)}].{self.mode}"
else:
return f"next_{self.state.get_signal(value)}"
def on_Operator(self, value):
def mask(value):
value_mask = (1 << len(value)) - 1
return f"({value_mask} & {self(value)})"
def sign(value):
if value.shape().signed:
return f"sign({mask(value)}, {-1 << (len(value) - 1)})"
else: # unsigned
return mask(value)
if len(value.operands) == 1:
arg, = value.operands
if value.operator == "~":
return f"(~{self(arg)})"
if value.operator == "-":
return f"(-{sign(arg)})"
if value.operator == "b":
return f"bool({mask(arg)})"
if value.operator == "r|":
return f"(0 != {mask(arg)})"
if value.operator == "r&":
return f"({(1 << len(arg)) - 1} == {mask(arg)})"
if value.operator == "r^":
# Believe it or not, this is the fastest way to compute a sideways XOR in Python.
return f"(format({mask(arg)}, 'b').count('1') % 2)"
if value.operator in ("u", "s"):
# These operators don't change the bit pattern, only its interpretation.
return self(arg)
elif len(value.operands) == 2:
lhs, rhs = value.operands
lhs_mask = (1 << len(lhs)) - 1
rhs_mask = (1 << len(rhs)) - 1
if value.operator == "+":
return f"({sign(lhs)} + {sign(rhs)})"
if value.operator == "-":
return f"({sign(lhs)} - {sign(rhs)})"
if value.operator == "*":
return f"({sign(lhs)} * {sign(rhs)})"
if value.operator == "//":
return f"zdiv({sign(lhs)}, {sign(rhs)})"
if value.operator == "%":
return f"zmod({sign(lhs)}, {sign(rhs)})"
if value.operator == "&":
return f"({self(lhs)} & {self(rhs)})"
if value.operator == "|":
return f"({self(lhs)} | {self(rhs)})"
if value.operator == "^":
return f"({self(lhs)} ^ {self(rhs)})"
if value.operator == "<<":
return f"({sign(lhs)} << {sign(rhs)})"
if value.operator == ">>":
return f"({sign(lhs)} >> {sign(rhs)})"
if value.operator == "==":
return f"({sign(lhs)} == {sign(rhs)})"
if value.operator == "!=":
return f"({sign(lhs)} != {sign(rhs)})"
if value.operator == "<":
return f"({sign(lhs)} < {sign(rhs)})"
if value.operator == "<=":
return f"({sign(lhs)} <= {sign(rhs)})"
if value.operator == ">":
return f"({sign(lhs)} > {sign(rhs)})"
if value.operator == ">=":
return f"({sign(lhs)} >= {sign(rhs)})"
elif len(value.operands) == 3:
if value.operator == "m":
sel, val1, val0 = value.operands
return f"({self(val1)} if {self(sel)} else {self(val0)})"
raise NotImplementedError("Operator '{}' not implemented".format(value.operator)) # :nocov:
def on_Slice(self, value):
return f"({(1 << len(value)) - 1} & ({self(value.value)} >> {value.start}))"
def on_Part(self, value):
offset_mask = (1 << len(value.offset)) - 1
offset = f"({value.stride} * ({offset_mask} & {self(value.offset)}))"
return f"({(1 << value.width) - 1} & " \
f"{self(value.value)} >> {offset})"
def on_Cat(self, value):
gen_parts = []
offset = 0
for part in value.parts:
part_mask = (1 << len(part)) - 1
gen_parts.append(f"(({part_mask} & {self(part)}) << {offset})")
offset += len(part)
if gen_parts:
return f"({' | '.join(gen_parts)})"
return f"0"
def on_Repl(self, value):
part_mask = (1 << len(value.value)) - 1
gen_part = self.emitter.def_var("repl", f"{part_mask} & {self(value.value)}")
gen_parts = []
offset = 0
for _ in range(value.count):
gen_parts.append(f"({gen_part} << {offset})")
offset += len(value.value)
if gen_parts:
return f"({' | '.join(gen_parts)})"
return f"0"
def on_ArrayProxy(self, value):
index_mask = (1 << len(value.index)) - 1
gen_index = self.emitter.def_var("rhs_index", f"{index_mask} & {self(value.index)}")
gen_value = self.emitter.gen_var("rhs_proxy")
if value.elems:
gen_elems = []
for index, elem in enumerate(value.elems):
if index == 0:
self.emitter.append(f"if {index} == {gen_index}:")
else:
self.emitter.append(f"elif {index} == {gen_index}:")
with self.emitter.indent():
self.emitter.append(f"{gen_value} = {self(elem)}")
self.emitter.append(f"else:")
with self.emitter.indent():
self.emitter.append(f"{gen_value} = {self(value.elems[-1])}")
return gen_value
else:
return f"0"
@classmethod
def compile(cls, state, value, *, mode):
emitter = _PythonEmitter()
compiler = cls(state, emitter, mode=mode)
emitter.append(f"result = {compiler(value)}")
return emitter.flush()
class _LHSValueCompiler(_ValueCompiler):
def __init__(self, state, emitter, *, rhs, outputs=None):
super().__init__(state, emitter)
# `rrhs` is used to translate rvalues that are syntactically a part of an lvalue, e.g.
# the offset of a Part.
self.rrhs = rhs
# `lrhs` is used to translate the read part of a read-modify-write cycle during partial
# update of an lvalue.
self.lrhs = _RHSValueCompiler(state, emitter, mode="next", inputs=None)
# If not None, `outputs` gets populated with signals on LHS.
self.outputs = outputs
def on_Const(self, value):
raise TypeError # :nocov:
def on_Signal(self, value):
if self.outputs is not None:
self.outputs.add(value)
def gen(arg):
value_mask = (1 << len(value)) - 1
if value.shape().signed:
value_sign = f"sign({value_mask} & {arg}, {-1 << (len(value) - 1)})"
else: # unsigned
value_sign = f"{value_mask} & {arg}"
self.emitter.append(f"next_{self.state.get_signal(value)} = {value_sign}")
return gen
def on_Operator(self, value):
raise TypeError # :nocov:
def on_Slice(self, value):
def gen(arg):
width_mask = (1 << (value.stop - value.start)) - 1
self(value.value)(f"({self.lrhs(value.value)} & " \
f"{~(width_mask << value.start)} | " \
f"(({width_mask} & {arg}) << {value.start}))")
return gen
def on_Part(self, value):
def gen(arg):
width_mask = (1 << value.width) - 1
offset_mask = (1 << len(value.offset)) - 1
offset = f"({value.stride} * ({offset_mask} & {self.rrhs(value.offset)}))"
self(value.value)(f"({self.lrhs(value.value)} & " \
f"~({width_mask} << {offset}) | " \
f"(({width_mask} & {arg}) << {offset}))")
return gen
def on_Cat(self, value):
def gen(arg):
gen_arg = self.emitter.def_var("cat", arg)
gen_parts = []
offset = 0
for part in value.parts:
part_mask = (1 << len(part)) - 1
self(part)(f"({part_mask} & ({gen_arg} >> {offset}))")
offset += len(part)
return gen
def on_Repl(self, value):
raise TypeError # :nocov:
def on_ArrayProxy(self, value):
def gen(arg):
index_mask = (1 << len(value.index)) - 1
gen_index = self.emitter.def_var("index", f"{self.rrhs(value.index)} & {index_mask}")
if value.elems:
gen_elems = []
for index, elem in enumerate(value.elems):
if index == 0:
self.emitter.append(f"if {index} == {gen_index}:")
else:
self.emitter.append(f"elif {index} == {gen_index}:")
with self.emitter.indent():
self(elem)(arg)
self.emitter.append(f"else:")
with self.emitter.indent():
self(value.elems[-1])(arg)
else:
self.emitter.append(f"pass")
return gen
class _StatementCompiler(StatementVisitor, _Compiler):
def __init__(self, state, emitter, *, inputs=None, outputs=None):
super().__init__(state, emitter)
self.rhs = _RHSValueCompiler(state, emitter, mode="curr", inputs=inputs)
self.lhs = _LHSValueCompiler(state, emitter, rhs=self.rhs, outputs=outputs)
def on_statements(self, stmts):
for stmt in stmts:
self(stmt)
if not stmts:
self.emitter.append("pass")
def on_Assign(self, stmt):
gen_rhs = f"({(1 << len(stmt.rhs)) - 1} & {self.rhs(stmt.rhs)})"
if stmt.rhs.shape().signed:
gen_rhs = f"sign({gen_rhs}, {-1 << (len(stmt.rhs) - 1)})"
return self.lhs(stmt.lhs)(gen_rhs)
def on_Switch(self, stmt):
gen_test = self.emitter.def_var("test",
f"{(1 << len(stmt.test)) - 1} & {self.rhs(stmt.test)}")
for index, (patterns, stmts) in enumerate(stmt.cases.items()):
gen_checks = []
if not patterns:
gen_checks.append(f"True")
else:
for pattern in patterns:
if "-" in pattern:
mask = int("".join("0" if b == "-" else "1" for b in pattern), 2)
value = int("".join("0" if b == "-" else b for b in pattern), 2)
gen_checks.append(f"{value} == ({mask} & {gen_test})")
else:
value = int(pattern, 2)
gen_checks.append(f"{value} == {gen_test}")
if index == 0:
self.emitter.append(f"if {' or '.join(gen_checks)}:")
else:
self.emitter.append(f"elif {' or '.join(gen_checks)}:")
with self.emitter.indent():
self(stmts)
def on_Assert(self, stmt):
raise NotImplementedError # :nocov:
def on_Assume(self, stmt):
raise NotImplementedError # :nocov:
def on_Cover(self, stmt):
raise NotImplementedError # :nocov:
@classmethod
def compile(cls, state, stmt):
output_indexes = [state.get_signal(signal) for signal in stmt._lhs_signals()]
emitter = _PythonEmitter()
for signal_index in output_indexes:
emitter.append(f"next_{signal_index} = slots[{signal_index}].next")
compiler = cls(state, emitter)
compiler(stmt)
for signal_index in output_indexes:
emitter.append(f"slots[{signal_index}].set(next_{signal_index})")
return emitter.flush()
class _FragmentCompiler:
def __init__(self, state):
self.state = state
def __call__(self, fragment):
processes = set()
for domain_name, domain_signals in fragment.drivers.items():
domain_stmts = LHSGroupFilter(domain_signals)(fragment.statements)
domain_process = PyRTLProcess(is_comb=domain_name is None)
emitter = _PythonEmitter()
emitter.append(f"def run():")
emitter._level += 1
if domain_name is None:
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"next_{signal_index} = {signal.reset}")
inputs = SignalSet()
_StatementCompiler(self.state, emitter, inputs=inputs)(domain_stmts)
for input in inputs:
self.state.add_trigger(domain_process, input)
else:
domain = fragment.domains[domain_name]
clk_trigger = 1 if domain.clk_edge == "pos" else 0
self.state.add_trigger(domain_process, domain.clk, trigger=clk_trigger)
if domain.rst is not None and domain.async_reset:
rst_trigger = 1
self.state.add_trigger(domain_process, domain.rst, trigger=rst_trigger)
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"next_{signal_index} = slots[{signal_index}].next")
_StatementCompiler(self.state, emitter)(domain_stmts)
for signal in domain_signals:
signal_index = self.state.get_signal(signal)
emitter.append(f"slots[{signal_index}].set(next_{signal_index})")
# There shouldn't be any exceptions raised by the generated code, but if there are
# (almost certainly due to a bug in the code generator), use this environment variable
# to make backtraces useful.
code = emitter.flush()
if os.getenv("NMIGEN_pysim_dump"):
file = tempfile.NamedTemporaryFile("w", prefix="nmigen_pysim_", delete=False)
file.write(code)
filename = file.name
else:
filename = "<string>"
exec_locals = {"slots": self.state.slots, **_ValueCompiler.helpers}
exec(compile(code, filename, "exec"), exec_locals)
domain_process.run = exec_locals["run"]
processes.add(domain_process)
for subfragment_index, (subfragment, subfragment_name) in enumerate(fragment.subfragments):
if subfragment_name is None:
subfragment_name = "U${}".format(subfragment_index)
processes.update(self(subfragment))
return processes
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_layers.ipynb (unless otherwise specified).
from __future__ import annotations
__all__ = ['module', 'Identity', 'Lambda', 'PartialLambda', 'Flatten', 'ToTensorBase', 'View', 'ResizeBatch',
'Debugger', 'sigmoid_range', 'SigmoidRange', 'AdaptiveConcatPool1d', 'AdaptiveConcatPool2d', 'PoolType',
'adaptive_pool', 'PoolFlatten', 'NormType', 'BatchNorm', 'InstanceNorm', 'BatchNorm1dFlat', 'LinBnDrop',
'sigmoid', 'sigmoid_', 'vleaky_relu', 'init_default', 'init_linear', 'ConvLayer', 'AdaptiveAvgPool',
'MaxPool', 'AvgPool', 'trunc_normal_', 'Embedding', 'SelfAttention', 'PooledSelfAttention2d',
'SimpleSelfAttention', 'icnr_init', 'PixelShuffle_ICNR', 'sequential', 'SequentialEx', 'MergeLayer', 'Cat',
'SimpleCNN', 'ProdLayer', 'inplace_relu', 'SEModule', 'ResBlock', 'SEBlock', 'SEResNeXtBlock',
'SeparableBlock', 'TimeDistributed', 'swish', 'Swish', 'MishJitAutoFn', 'mish', 'Mish', 'ParameterModule',
'children_and_parameters', 'has_children', 'flatten_model', 'NoneReduce', 'in_channels']
# Cell
#nbdev_comment from __future__ import annotations
from .imports import *
from .torch_imports import *
from .torch_core import *
from torch.nn.utils import weight_norm, spectral_norm
# Cell
def module(*flds, **defaults):
"Decorator to create an `nn.Module` using `f` as `forward` method"
pa = [inspect.Parameter(o, inspect.Parameter.POSITIONAL_OR_KEYWORD) for o in flds]
pb = [inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=v)
for k,v in defaults.items()]
params = pa+pb
all_flds = [*flds,*defaults.keys()]
def _f(f):
class c(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
for i,o in enumerate(args): kwargs[all_flds[i]] = o
kwargs = merge(defaults,kwargs)
for k,v in kwargs.items(): setattr(self,k,v)
__repr__ = basic_repr(all_flds)
forward = f
c.__signature__ = inspect.Signature(params)
c.__name__ = c.__qualname__ = f.__name__
c.__doc__ = f.__doc__
return c
return _f
# Cell
@module()
def Identity(self, x):
"Do nothing at all"
return x
# Cell
@module('func')
def Lambda(self, x):
"An easy way to create a pytorch layer for a simple `func`"
return self.func(x)
# Cell
class PartialLambda(Lambda):
"Layer that applies `partial(func, **kwargs)`"
def __init__(self, func, **kwargs):
super().__init__(partial(func, **kwargs))
self.repr = f'{func.__name__}, {kwargs}'
def forward(self, x): return self.func(x)
def __repr__(self): return f'{self.__class__.__name__}({self.repr})'
# Cell
@module(full=False)
def Flatten(self, x):
"Flatten `x` to a single dimension, e.g. at end of a model. `full` for rank-1 tensor"
return TensorBase(x.view(-1) if self.full else x.view(x.size(0), -1))
# Cell
@module(tensor_cls=TensorBase)
def ToTensorBase(self, x):
"Remove `tensor_cls` to x"
return self.tensor_cls(x)
# Cell
class View(Module):
"Reshape `x` to `size`"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view(self.size)
# Cell
class ResizeBatch(Module):
"Reshape `x` to `size`, keeping batch dim the same size"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view((x.size(0),) + self.size)
# Cell
@module()
def Debugger(self,x):
"A module to debug inside a model."
set_trace()
return x
# Cell
def sigmoid_range(x, low, high):
"Sigmoid function with range `(low, high)`"
return torch.sigmoid(x) * (high - low) + low
# Cell
@module('low','high')
def SigmoidRange(self, x):
"Sigmoid module with range `(low, high)`"
return sigmoid_range(x, self.low, self.high)
# Cell
class AdaptiveConcatPool1d(Module):
"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool1d(self.size)
self.mp = nn.AdaptiveMaxPool1d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
# Cell
class AdaptiveConcatPool2d(Module):
"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool2d(self.size)
self.mp = nn.AdaptiveMaxPool2d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
# Cell
class PoolType: Avg,Max,Cat = 'Avg','Max','Cat'
# Cell
def adaptive_pool(pool_type):
return nn.AdaptiveAvgPool2d if pool_type=='Avg' else nn.AdaptiveMaxPool2d if pool_type=='Max' else AdaptiveConcatPool2d
# Cell
class PoolFlatten(nn.Sequential):
"Combine `nn.AdaptiveAvgPool2d` and `Flatten`."
def __init__(self, pool_type=PoolType.Avg): super().__init__(adaptive_pool(pool_type)(1), Flatten())
# Cell
NormType = Enum('NormType', 'Batch BatchZero Weight Spectral Instance InstanceZero')
# Cell
def _get_norm(prefix, nf, ndim=2, zero=False, **kwargs):
"Norm layer with `nf` features and `ndim` initialized depending on `norm_type`."
assert 1 <= ndim <= 3
bn = getattr(nn, f"{prefix}{ndim}d")(nf, **kwargs)
if bn.affine:
bn.bias.data.fill_(1e-3)
bn.weight.data.fill_(0. if zero else 1.)
return bn
# Cell
@delegates(nn.BatchNorm2d)
def BatchNorm(nf, ndim=2, norm_type=NormType.Batch, **kwargs):
"BatchNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('BatchNorm', nf, ndim, zero=norm_type==NormType.BatchZero, **kwargs)
# Cell
@delegates(nn.InstanceNorm2d)
def InstanceNorm(nf, ndim=2, norm_type=NormType.Instance, affine=True, **kwargs):
"InstanceNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('InstanceNorm', nf, ndim, zero=norm_type==NormType.InstanceZero, affine=affine, **kwargs)
# Cell
class BatchNorm1dFlat(nn.BatchNorm1d):
"`nn.BatchNorm1d`, but first flattens leading dimensions"
def forward(self, x):
if x.dim()==2: return super().forward(x)
*f,l = x.shape
x = x.contiguous().view(-1,l)
return super().forward(x).view(*f,l)
# Cell
class LinBnDrop(nn.Sequential):
"Module grouping `BatchNorm1d`, `Dropout` and `Linear` layers"
def __init__(self, n_in, n_out, bn=True, p=0., act=None, lin_first=False):
layers = [BatchNorm(n_out if lin_first else n_in, ndim=1)] if bn else []
if p != 0: layers.append(nn.Dropout(p))
lin = [nn.Linear(n_in, n_out, bias=not bn)]
if act is not None: lin.append(act)
layers = lin+layers if lin_first else layers+lin
super().__init__(*layers)
# Cell
def sigmoid(input, eps=1e-7):
"Same as `torch.sigmoid`, plus clamping to `(eps,1-eps)"
return input.sigmoid().clamp(eps,1-eps)
# Cell
def sigmoid_(input, eps=1e-7):
"Same as `torch.sigmoid_`, plus clamping to `(eps,1-eps)"
return input.sigmoid_().clamp_(eps,1-eps)
# Cell
from torch.nn.init import kaiming_uniform_,uniform_,xavier_uniform_,normal_
# Cell
def vleaky_relu(input, inplace=True):
"`F.leaky_relu` with 0.3 slope"
return F.leaky_relu(input, negative_slope=0.3, inplace=inplace)
# Cell
for o in F.relu,nn.ReLU,F.relu6,nn.ReLU6,F.leaky_relu,nn.LeakyReLU:
o.__default_init__ = kaiming_uniform_
# Cell
for o in F.sigmoid,nn.Sigmoid,F.tanh,nn.Tanh,sigmoid,sigmoid_:
o.__default_init__ = xavier_uniform_
# Cell
def init_default(m, func=nn.init.kaiming_normal_):
"Initialize `m` weights with `func` and set `bias` to 0."
if func and hasattr(m, 'weight'): func(m.weight)
with torch.no_grad(): nested_callable(m, 'bias.fill_')(0.)
return m
# Cell
def init_linear(m, act_func=None, init='auto', bias_std=0.01):
if getattr(m,'bias',None) is not None and bias_std is not None:
if bias_std != 0: normal_(m.bias, 0, bias_std)
else: m.bias.data.zero_()
if init=='auto':
if act_func in (F.relu_,F.leaky_relu_): init = kaiming_uniform_
else: init = nested_callable(act_func, '__class__.__default_init__')
if init == noop: init = getcallable(act_func, '__default_init__')
if callable(init): init(m.weight)
# Cell
def _conv_func(ndim=2, transpose=False):
"Return the proper conv `ndim` function, potentially `transposed`."
assert 1 <= ndim <=3
return getattr(nn, f'Conv{'Transpose' if transpose else ''}{ndim}d')
# Cell
defaults.activation=nn.ReLU
# Cell
class ConvLayer(nn.Sequential):
"Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and `norm_type` layers."
@delegates(nn.Conv2d)
def __init__(self, ni, nf, ks=3, stride=1, padding=None, bias=None, ndim=2, norm_type=NormType.Batch, bn_1st=True,
act_cls=defaults.activation, transpose=False, init='auto', xtra=None, bias_std=0.01, **kwargs):
if padding is None: padding = ((ks-1)//2 if not transpose else 0)
bn = norm_type in (NormType.Batch, NormType.BatchZero)
inn = norm_type in (NormType.Instance, NormType.InstanceZero)
if bias is None: bias = not (bn or inn)
conv_func = _conv_func(ndim, transpose=transpose)
conv = conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding, **kwargs)
act = None if act_cls is None else act_cls()
init_linear(conv, act, init=init, bias_std=bias_std)
if norm_type==NormType.Weight: conv = weight_norm(conv)
elif norm_type==NormType.Spectral: conv = spectral_norm(conv)
layers = [conv]
act_bn = []
if act is not None: act_bn.append(act)
if bn: act_bn.append(BatchNorm(nf, norm_type=norm_type, ndim=ndim))
if inn: act_bn.append(InstanceNorm(nf, norm_type=norm_type, ndim=ndim))
if bn_1st: act_bn.reverse()
layers += act_bn
if xtra: layers.append(xtra)
super().__init__(*layers)
# Cell
def AdaptiveAvgPool(sz=1, ndim=2):
"nn.AdaptiveAvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AdaptiveAvgPool{ndim}d")(sz)
# Cell
def MaxPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.MaxPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"MaxPool{ndim}d")(ks, stride=stride, padding=padding)
# Cell
def AvgPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.AvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AvgPool{ndim}d")(ks, stride=stride, padding=padding, ceil_mode=ceil_mode)
# Cell
def trunc_normal_(x, mean=0., std=1.):
"Truncated normal initialization (approximation)"
# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12
return x.normal_().fmod_(2).mul_(std).add_(mean)
# Cell
class Embedding(nn.Embedding):
"Embedding layer with truncated normal initialization"
def __init__(self, ni, nf, std=0.01):
super().__init__(ni, nf)
trunc_normal_(self.weight.data, std=std)
# Cell
class SelfAttention(Module):
"Self attention layer for `n_channels`."
def __init__(self, n_channels):
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels)]
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, ndim=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
#Notation from the paper.
size = x.size()
x = x.view(*size[:2],-1)
f,g,h = self.query(x),self.key(x),self.value(x)
beta = F.softmax(torch.bmm(f.transpose(1,2), g), dim=1)
o = self.gamma * torch.bmm(h, beta) + x
return o.view(*size).contiguous()
# Cell
class PooledSelfAttention2d(Module):
"Pooled self attention layer for 2d."
def __init__(self, n_channels):
self.n_channels = n_channels
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels//2)]
self.out = self._conv(n_channels//2, n_channels)
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
n_ftrs = x.shape[2]*x.shape[3]
f = self.query(x).view(-1, self.n_channels//8, n_ftrs)
g = F.max_pool2d(self.key(x), [2,2]).view(-1, self.n_channels//8, n_ftrs//4)
h = F.max_pool2d(self.value(x), [2,2]).view(-1, self.n_channels//2, n_ftrs//4)
beta = F.softmax(torch.bmm(f.transpose(1, 2), g), -1)
o = self.out(torch.bmm(h, beta.transpose(1,2)).view(-1, self.n_channels//2, x.shape[2], x.shape[3]))
return self.gamma * o + x
# Cell
def _conv1d_spect(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
return spectral_norm(conv)
# Cell
class SimpleSelfAttention(Module):
def __init__(self, n_in:int, ks=1, sym=False):
self.sym,self.n_in = sym,n_in
self.conv = _conv1d_spect(n_in, n_in, ks, padding=ks//2, bias=False)
self.gamma = nn.Parameter(tensor([0.]))
def forward(self,x):
if self.sym:
c = self.conv.weight.view(self.n_in,self.n_in)
c = (c + c.t())/2
self.conv.weight = c.view(self.n_in,self.n_in,1)
size = x.size()
x = x.view(*size[:2],-1)
convx = self.conv(x)
xxT = torch.bmm(x,x.permute(0,2,1).contiguous())
o = torch.bmm(xxT, convx)
o = self.gamma * o + x
return o.view(*size).contiguous()
# Cell
def icnr_init(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function"
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(x.new_zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
return k.contiguous().view([nf,ni,h,w]).transpose(0, 1)
# Cell
class PixelShuffle_ICNR(nn.Sequential):
"Upsample by `scale` from `ni` filters to `nf` (default `ni`), using `nn.PixelShuffle`."
def __init__(self, ni, nf=None, scale=2, blur=False, norm_type=NormType.Weight, act_cls=defaults.activation):
super().__init__()
nf = ifnone(nf, ni)
layers = [ConvLayer(ni, nf*(scale**2), ks=1, norm_type=norm_type, act_cls=act_cls, bias_std=0),
nn.PixelShuffle(scale)]
if norm_type == NormType.Weight:
layers[0][0].weight_v.data.copy_(icnr_init(layers[0][0].weight_v.data))
layers[0][0].weight_g.data.copy_(((layers[0][0].weight_v.data**2).sum(dim=[1,2,3])**0.5)[:,None,None,None])
else:
layers[0][0].weight.data.copy_(icnr_init(layers[0][0].weight.data))
if blur: layers += [nn.ReplicationPad2d((1,0,1,0)), nn.AvgPool2d(2, stride=1)]
super().__init__(*layers)
# Cell
def sequential(*args):
"Create an `nn.Sequential`, wrapping items with `Lambda` if needed"
if len(args) != 1 or not isinstance(args[0], OrderedDict):
args = list(args)
for i,o in enumerate(args):
if not isinstance(o,nn.Module): args[i] = Lambda(o)
return nn.Sequential(*args)
# Cell
class SequentialEx(Module):
"Like `nn.Sequential`, but with ModuleList semantics, and can access module input"
def __init__(self, *layers): self.layers = nn.ModuleList(layers)
def forward(self, x):
res = x
for l in self.layers:
res.orig = x
nres = l(res)
# We have to remove res.orig to avoid hanging refs and therefore memory leaks
res.orig, nres.orig = None, None
res = nres
return res
def __getitem__(self,i): return self.layers[i]
def append(self,l): return self.layers.append(l)
def extend(self,l): return self.layers.extend(l)
def insert(self,i,l): return self.layers.insert(i,l)
# Cell
class MergeLayer(Module):
"Merge a shortcut with the result of the module by adding them or concatenating them if `dense=True`."
def __init__(self, dense:bool=False): self.dense=dense
def forward(self, x): return torch.cat([x,x.orig], dim=1) if self.dense else (x+x.orig)
# Cell
class Cat(nn.ModuleList):
"Concatenate layers outputs over a given dim"
def __init__(self, layers, dim=1):
self.dim=dim
super().__init__(layers)
def forward(self, x): return torch.cat([l(x) for l in self], dim=self.dim)
# Cell
class SimpleCNN(nn.Sequential):
"Create a simple CNN with `filters`."
def __init__(self, filters, kernel_szs=None, strides=None, bn=True):
nl = len(filters)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
strides = ifnone(strides , [2]*nl)
layers = [ConvLayer(filters[i], filters[i+1], kernel_szs[i], stride=strides[i],
norm_type=(NormType.Batch if bn and i<nl-1 else None)) for i in range(nl)]
layers.append(PoolFlatten())
super().__init__(*layers)
# Cell
class ProdLayer(Module):
"Merge a shortcut with the result of the module by multiplying them."
def forward(self, x): return x * x.orig
# Cell
inplace_relu = partial(nn.ReLU, inplace=True)
# Cell
def SEModule(ch, reduction, act_cls=defaults.activation):
nf = math.ceil(ch//reduction/8)*8
return SequentialEx(nn.AdaptiveAvgPool2d(1),
ConvLayer(ch, nf, ks=1, norm_type=None, act_cls=act_cls),
ConvLayer(nf, ch, ks=1, norm_type=None, act_cls=nn.Sigmoid),
ProdLayer())
# Cell
class ResBlock(Module):
"Resnet block from `ni` to `nh` with `stride`"
@delegates(ConvLayer.__init__)
def __init__(self, expansion, ni, nf, stride=1, groups=1, reduction=None, nh1=None, nh2=None, dw=False, g2=1,
sa=False, sym=False, norm_type=NormType.Batch, act_cls=defaults.activation, ndim=2, ks=3,
pool=AvgPool, pool_first=True, **kwargs):
norm2 = (NormType.BatchZero if norm_type==NormType.Batch else
NormType.InstanceZero if norm_type==NormType.Instance else norm_type)
if nh2 is None: nh2 = nf
if nh1 is None: nh1 = nh2
nf,ni = nf*expansion,ni*expansion
k0 = dict(norm_type=norm_type, act_cls=act_cls, ndim=ndim, **kwargs)
k1 = dict(norm_type=norm2, act_cls=None, ndim=ndim, **kwargs)
convpath = [ConvLayer(ni, nh2, ks, stride=stride, groups=ni if dw else groups, **k0),
ConvLayer(nh2, nf, ks, groups=g2, **k1)
] if expansion == 1 else [
ConvLayer(ni, nh1, 1, **k0),
ConvLayer(nh1, nh2, ks, stride=stride, groups=nh1 if dw else groups, **k0),
ConvLayer(nh2, nf, 1, groups=g2, **k1)]
if reduction: convpath.append(SEModule(nf, reduction=reduction, act_cls=act_cls))
if sa: convpath.append(SimpleSelfAttention(nf,ks=1,sym=sym))
self.convpath = nn.Sequential(*convpath)
idpath = []
if ni!=nf: idpath.append(ConvLayer(ni, nf, 1, act_cls=None, ndim=ndim, **kwargs))
if stride!=1: idpath.insert((1,0)[pool_first], pool(stride, ndim=ndim, ceil_mode=True))
self.idpath = nn.Sequential(*idpath)
self.act = defaults.activation(inplace=True) if act_cls is defaults.activation else act_cls()
def forward(self, x): return self.act(self.convpath(x) + self.idpath(x))
# Cell
def SEBlock(expansion, ni, nf, groups=1, reduction=16, stride=1, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh1=nf*2, nh2=nf*expansion, **kwargs)
# Cell
def SEResNeXtBlock(expansion, ni, nf, groups=32, reduction=16, stride=1, base_width=4, **kwargs):
w = math.floor(nf * (base_width / 64)) * groups
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh2=w, **kwargs)
# Cell
def SeparableBlock(expansion, ni, nf, reduction=16, stride=1, base_width=4, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, reduction=reduction, nh2=nf*2, dw=True, **kwargs)
# Cell
def _stack_tups(tuples, stack_dim=1):
"Stack tuple of tensors along `stack_dim`"
return tuple(torch.stack([t[i] for t in tuples], dim=stack_dim) for i in range_of(tuples[0]))
# Cell
class TimeDistributed(Module):
"Applies `module` over `tdim` identically for each step, use `low_mem` to compute one at a time."
def __init__(self, module, low_mem=False, tdim=1):
store_attr()
def forward(self, *tensors, **kwargs):
"input x with shape:(bs,seq_len,channels,width,height)"
if self.low_mem or self.tdim!=1:
return self.low_mem_forward(*tensors, **kwargs)
else:
#only support tdim=1
inp_shape = tensors[0].shape
bs, seq_len = inp_shape[0], inp_shape[1]
out = self.module(*[x.view(bs*seq_len, *x.shape[2:]) for x in tensors], **kwargs)
return self.format_output(out, bs, seq_len)
def low_mem_forward(self, *tensors, **kwargs):
"input x with shape:(bs,seq_len,channels,width,height)"
seq_len = tensors[0].shape[self.tdim]
args_split = [torch.unbind(x, dim=self.tdim) for x in tensors]
out = []
for i in range(seq_len):
out.append(self.module(*[args[i] for args in args_split]), **kwargs)
if isinstance(out[0], tuple):
return _stack_tups(out, stack_dim=self.tdim)
return torch.stack(out, dim=self.tdim)
def format_output(self, out, bs, seq_len):
"unstack from batchsize outputs"
if isinstance(out, tuple):
return tuple(out_i.view(bs, seq_len, *out_i.shape[1:]) for out_i in out)
return out.view(bs, seq_len,*out.shape[1:])
def __repr__(self):
return f'TimeDistributed({self.module})'
# Cell
from torch.jit import script
# Cell
@script
def _swish_jit_fwd(x): return x.mul(torch.sigmoid(x))
@script
def _swish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
return grad_output * (x_sigmoid * (1 + x * (1 - x_sigmoid)))
class _SwishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _swish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _swish_jit_bwd(x, grad_output)
# Cell
def swish(x, inplace=False): return _SwishJitAutoFn.apply(x)
# Cell
class Swish(Module):
def forward(self, x): return _SwishJitAutoFn.apply(x)
# Cell
@script
def _mish_jit_fwd(x): return x.mul(torch.tanh(F.softplus(x)))
@script
def _mish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
x_tanh_sp = F.softplus(x).tanh()
return grad_output.mul(x_tanh_sp + x * x_sigmoid * (1 - x_tanh_sp * x_tanh_sp))
class MishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _mish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _mish_jit_bwd(x, grad_output)
# Cell
def mish(x): return F.mish(x) if torch.__version__ >= '1.9' else MishJitAutoFn.apply(x)
# Cell
class Mish(Module):
def forward(self, x): return MishJitAutoFn.apply(x)
# Cell
if ismin_torch('1.9'): Mish = nn.Mish
# Cell
for o in swish,Swish,mish,Mish: o.__default_init__ = kaiming_uniform_
# Cell
class ParameterModule(Module):
"Register a lone parameter `p` in a module."
def __init__(self, p): self.val = p
def forward(self, x): return x
# Cell
def children_and_parameters(m):
"Return the children of `m` and its direct parameters not registered in modules."
children = list(m.children())
children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[])
for p in m.parameters():
if id(p) not in children_p: children.append(ParameterModule(p))
return children
# Cell
def has_children(m):
try: next(m.children())
except StopIteration: return False
return True
# Cell
def flatten_model(m):
"Return the list of all submodules and parameters of `m`"
return sum(map(flatten_model,children_and_parameters(m)),[]) if has_children(m) else [m]
# Cell
class NoneReduce():
"A context manager to evaluate `loss_func` with none reduce."
def __init__(self, loss_func): self.loss_func,self.old_red = loss_func,None
def __enter__(self):
if hasattr(self.loss_func, 'reduction'):
self.old_red = self.loss_func.reduction
self.loss_func.reduction = 'none'
return self.loss_func
else: return partial(self.loss_func, reduction='none')
def __exit__(self, type, value, traceback):
if self.old_red is not None: self.loss_func.reduction = self.old_red
# Cell
def in_channels(m):
"Return the shape of the first weight layer in `m`."
try: return next(l.weight.shape[1] for l in flatten_model(m) if nested_attr(l,'weight.ndim',-1)==4)
except StopIteration as e: e.args = ["No weight layer"]; raise | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_layers.ipynb (unless otherwise specified).
from __future__ import annotations
__all__ = ['module', 'Identity', 'Lambda', 'PartialLambda', 'Flatten', 'ToTensorBase', 'View', 'ResizeBatch',
'Debugger', 'sigmoid_range', 'SigmoidRange', 'AdaptiveConcatPool1d', 'AdaptiveConcatPool2d', 'PoolType',
'adaptive_pool', 'PoolFlatten', 'NormType', 'BatchNorm', 'InstanceNorm', 'BatchNorm1dFlat', 'LinBnDrop',
'sigmoid', 'sigmoid_', 'vleaky_relu', 'init_default', 'init_linear', 'ConvLayer', 'AdaptiveAvgPool',
'MaxPool', 'AvgPool', 'trunc_normal_', 'Embedding', 'SelfAttention', 'PooledSelfAttention2d',
'SimpleSelfAttention', 'icnr_init', 'PixelShuffle_ICNR', 'sequential', 'SequentialEx', 'MergeLayer', 'Cat',
'SimpleCNN', 'ProdLayer', 'inplace_relu', 'SEModule', 'ResBlock', 'SEBlock', 'SEResNeXtBlock',
'SeparableBlock', 'TimeDistributed', 'swish', 'Swish', 'MishJitAutoFn', 'mish', 'Mish', 'ParameterModule',
'children_and_parameters', 'has_children', 'flatten_model', 'NoneReduce', 'in_channels']
# Cell
#nbdev_comment from __future__ import annotations
from .imports import *
from .torch_imports import *
from .torch_core import *
from torch.nn.utils import weight_norm, spectral_norm
# Cell
def module(*flds, **defaults):
"Decorator to create an `nn.Module` using `f` as `forward` method"
pa = [inspect.Parameter(o, inspect.Parameter.POSITIONAL_OR_KEYWORD) for o in flds]
pb = [inspect.Parameter(k, inspect.Parameter.POSITIONAL_OR_KEYWORD, default=v)
for k,v in defaults.items()]
params = pa+pb
all_flds = [*flds,*defaults.keys()]
def _f(f):
class c(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
for i,o in enumerate(args): kwargs[all_flds[i]] = o
kwargs = merge(defaults,kwargs)
for k,v in kwargs.items(): setattr(self,k,v)
__repr__ = basic_repr(all_flds)
forward = f
c.__signature__ = inspect.Signature(params)
c.__name__ = c.__qualname__ = f.__name__
c.__doc__ = f.__doc__
return c
return _f
# Cell
@module()
def Identity(self, x):
"Do nothing at all"
return x
# Cell
@module('func')
def Lambda(self, x):
"An easy way to create a pytorch layer for a simple `func`"
return self.func(x)
# Cell
class PartialLambda(Lambda):
"Layer that applies `partial(func, **kwargs)`"
def __init__(self, func, **kwargs):
super().__init__(partial(func, **kwargs))
self.repr = f'{func.__name__}, {kwargs}'
def forward(self, x): return self.func(x)
def __repr__(self): return f'{self.__class__.__name__}({self.repr})'
# Cell
@module(full=False)
def Flatten(self, x):
"Flatten `x` to a single dimension, e.g. at end of a model. `full` for rank-1 tensor"
return TensorBase(x.view(-1) if self.full else x.view(x.size(0), -1))
# Cell
@module(tensor_cls=TensorBase)
def ToTensorBase(self, x):
"Remove `tensor_cls` to x"
return self.tensor_cls(x)
# Cell
class View(Module):
"Reshape `x` to `size`"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view(self.size)
# Cell
class ResizeBatch(Module):
"Reshape `x` to `size`, keeping batch dim the same size"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view((x.size(0),) + self.size)
# Cell
@module()
def Debugger(self,x):
"A module to debug inside a model."
set_trace()
return x
# Cell
def sigmoid_range(x, low, high):
"Sigmoid function with range `(low, high)`"
return torch.sigmoid(x) * (high - low) + low
# Cell
@module('low','high')
def SigmoidRange(self, x):
"Sigmoid module with range `(low, high)`"
return sigmoid_range(x, self.low, self.high)
# Cell
class AdaptiveConcatPool1d(Module):
"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool1d(self.size)
self.mp = nn.AdaptiveMaxPool1d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
# Cell
class AdaptiveConcatPool2d(Module):
"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`"
def __init__(self, size=None):
self.size = size or 1
self.ap = nn.AdaptiveAvgPool2d(self.size)
self.mp = nn.AdaptiveMaxPool2d(self.size)
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
# Cell
class PoolType: Avg,Max,Cat = 'Avg','Max','Cat'
# Cell
def adaptive_pool(pool_type):
return nn.AdaptiveAvgPool2d if pool_type=='Avg' else nn.AdaptiveMaxPool2d if pool_type=='Max' else AdaptiveConcatPool2d
# Cell
class PoolFlatten(nn.Sequential):
"Combine `nn.AdaptiveAvgPool2d` and `Flatten`."
def __init__(self, pool_type=PoolType.Avg): super().__init__(adaptive_pool(pool_type)(1), Flatten())
# Cell
NormType = Enum('NormType', 'Batch BatchZero Weight Spectral Instance InstanceZero')
# Cell
def _get_norm(prefix, nf, ndim=2, zero=False, **kwargs):
"Norm layer with `nf` features and `ndim` initialized depending on `norm_type`."
assert 1 <= ndim <= 3
bn = getattr(nn, f"{prefix}{ndim}d")(nf, **kwargs)
if bn.affine:
bn.bias.data.fill_(1e-3)
bn.weight.data.fill_(0. if zero else 1.)
return bn
# Cell
@delegates(nn.BatchNorm2d)
def BatchNorm(nf, ndim=2, norm_type=NormType.Batch, **kwargs):
"BatchNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('BatchNorm', nf, ndim, zero=norm_type==NormType.BatchZero, **kwargs)
# Cell
@delegates(nn.InstanceNorm2d)
def InstanceNorm(nf, ndim=2, norm_type=NormType.Instance, affine=True, **kwargs):
"InstanceNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."
return _get_norm('InstanceNorm', nf, ndim, zero=norm_type==NormType.InstanceZero, affine=affine, **kwargs)
# Cell
class BatchNorm1dFlat(nn.BatchNorm1d):
"`nn.BatchNorm1d`, but first flattens leading dimensions"
def forward(self, x):
if x.dim()==2: return super().forward(x)
*f,l = x.shape
x = x.contiguous().view(-1,l)
return super().forward(x).view(*f,l)
# Cell
class LinBnDrop(nn.Sequential):
"Module grouping `BatchNorm1d`, `Dropout` and `Linear` layers"
def __init__(self, n_in, n_out, bn=True, p=0., act=None, lin_first=False):
layers = [BatchNorm(n_out if lin_first else n_in, ndim=1)] if bn else []
if p != 0: layers.append(nn.Dropout(p))
lin = [nn.Linear(n_in, n_out, bias=not bn)]
if act is not None: lin.append(act)
layers = lin+layers if lin_first else layers+lin
super().__init__(*layers)
# Cell
def sigmoid(input, eps=1e-7):
"Same as `torch.sigmoid`, plus clamping to `(eps,1-eps)"
return input.sigmoid().clamp(eps,1-eps)
# Cell
def sigmoid_(input, eps=1e-7):
"Same as `torch.sigmoid_`, plus clamping to `(eps,1-eps)"
return input.sigmoid_().clamp_(eps,1-eps)
# Cell
from torch.nn.init import kaiming_uniform_,uniform_,xavier_uniform_,normal_
# Cell
def vleaky_relu(input, inplace=True):
"`F.leaky_relu` with 0.3 slope"
return F.leaky_relu(input, negative_slope=0.3, inplace=inplace)
# Cell
for o in F.relu,nn.ReLU,F.relu6,nn.ReLU6,F.leaky_relu,nn.LeakyReLU:
o.__default_init__ = kaiming_uniform_
# Cell
for o in F.sigmoid,nn.Sigmoid,F.tanh,nn.Tanh,sigmoid,sigmoid_:
o.__default_init__ = xavier_uniform_
# Cell
def init_default(m, func=nn.init.kaiming_normal_):
"Initialize `m` weights with `func` and set `bias` to 0."
if func and hasattr(m, 'weight'): func(m.weight)
with torch.no_grad(): nested_callable(m, 'bias.fill_')(0.)
return m
# Cell
def init_linear(m, act_func=None, init='auto', bias_std=0.01):
if getattr(m,'bias',None) is not None and bias_std is not None:
if bias_std != 0: normal_(m.bias, 0, bias_std)
else: m.bias.data.zero_()
if init=='auto':
if act_func in (F.relu_,F.leaky_relu_): init = kaiming_uniform_
else: init = nested_callable(act_func, '__class__.__default_init__')
if init == noop: init = getcallable(act_func, '__default_init__')
if callable(init): init(m.weight)
# Cell
def _conv_func(ndim=2, transpose=False):
"Return the proper conv `ndim` function, potentially `transposed`."
assert 1 <= ndim <=3
return getattr(nn, f'Conv{"Transpose" if transpose else ""}{ndim}d')
# Cell
defaults.activation=nn.ReLU
# Cell
class ConvLayer(nn.Sequential):
"Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and `norm_type` layers."
@delegates(nn.Conv2d)
def __init__(self, ni, nf, ks=3, stride=1, padding=None, bias=None, ndim=2, norm_type=NormType.Batch, bn_1st=True,
act_cls=defaults.activation, transpose=False, init='auto', xtra=None, bias_std=0.01, **kwargs):
if padding is None: padding = ((ks-1)//2 if not transpose else 0)
bn = norm_type in (NormType.Batch, NormType.BatchZero)
inn = norm_type in (NormType.Instance, NormType.InstanceZero)
if bias is None: bias = not (bn or inn)
conv_func = _conv_func(ndim, transpose=transpose)
conv = conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding, **kwargs)
act = None if act_cls is None else act_cls()
init_linear(conv, act, init=init, bias_std=bias_std)
if norm_type==NormType.Weight: conv = weight_norm(conv)
elif norm_type==NormType.Spectral: conv = spectral_norm(conv)
layers = [conv]
act_bn = []
if act is not None: act_bn.append(act)
if bn: act_bn.append(BatchNorm(nf, norm_type=norm_type, ndim=ndim))
if inn: act_bn.append(InstanceNorm(nf, norm_type=norm_type, ndim=ndim))
if bn_1st: act_bn.reverse()
layers += act_bn
if xtra: layers.append(xtra)
super().__init__(*layers)
# Cell
def AdaptiveAvgPool(sz=1, ndim=2):
"nn.AdaptiveAvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AdaptiveAvgPool{ndim}d")(sz)
# Cell
def MaxPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.MaxPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"MaxPool{ndim}d")(ks, stride=stride, padding=padding)
# Cell
def AvgPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
"nn.AvgPool layer for `ndim`"
assert 1 <= ndim <= 3
return getattr(nn, f"AvgPool{ndim}d")(ks, stride=stride, padding=padding, ceil_mode=ceil_mode)
# Cell
def trunc_normal_(x, mean=0., std=1.):
"Truncated normal initialization (approximation)"
# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12
return x.normal_().fmod_(2).mul_(std).add_(mean)
# Cell
class Embedding(nn.Embedding):
"Embedding layer with truncated normal initialization"
def __init__(self, ni, nf, std=0.01):
super().__init__(ni, nf)
trunc_normal_(self.weight.data, std=std)
# Cell
class SelfAttention(Module):
"Self attention layer for `n_channels`."
def __init__(self, n_channels):
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels)]
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, ndim=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
#Notation from the paper.
size = x.size()
x = x.view(*size[:2],-1)
f,g,h = self.query(x),self.key(x),self.value(x)
beta = F.softmax(torch.bmm(f.transpose(1,2), g), dim=1)
o = self.gamma * torch.bmm(h, beta) + x
return o.view(*size).contiguous()
# Cell
class PooledSelfAttention2d(Module):
"Pooled self attention layer for 2d."
def __init__(self, n_channels):
self.n_channels = n_channels
self.query,self.key,self.value = [self._conv(n_channels, c) for c in (n_channels//8,n_channels//8,n_channels//2)]
self.out = self._conv(n_channels//2, n_channels)
self.gamma = nn.Parameter(tensor([0.]))
def _conv(self,n_in,n_out):
return ConvLayer(n_in, n_out, ks=1, norm_type=NormType.Spectral, act_cls=None, bias=False)
def forward(self, x):
n_ftrs = x.shape[2]*x.shape[3]
f = self.query(x).view(-1, self.n_channels//8, n_ftrs)
g = F.max_pool2d(self.key(x), [2,2]).view(-1, self.n_channels//8, n_ftrs//4)
h = F.max_pool2d(self.value(x), [2,2]).view(-1, self.n_channels//2, n_ftrs//4)
beta = F.softmax(torch.bmm(f.transpose(1, 2), g), -1)
o = self.out(torch.bmm(h, beta.transpose(1,2)).view(-1, self.n_channels//2, x.shape[2], x.shape[3]))
return self.gamma * o + x
# Cell
def _conv1d_spect(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
return spectral_norm(conv)
# Cell
class SimpleSelfAttention(Module):
def __init__(self, n_in:int, ks=1, sym=False):
self.sym,self.n_in = sym,n_in
self.conv = _conv1d_spect(n_in, n_in, ks, padding=ks//2, bias=False)
self.gamma = nn.Parameter(tensor([0.]))
def forward(self,x):
if self.sym:
c = self.conv.weight.view(self.n_in,self.n_in)
c = (c + c.t())/2
self.conv.weight = c.view(self.n_in,self.n_in,1)
size = x.size()
x = x.view(*size[:2],-1)
convx = self.conv(x)
xxT = torch.bmm(x,x.permute(0,2,1).contiguous())
o = torch.bmm(xxT, convx)
o = self.gamma * o + x
return o.view(*size).contiguous()
# Cell
def icnr_init(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function"
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(x.new_zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
return k.contiguous().view([nf,ni,h,w]).transpose(0, 1)
# Cell
class PixelShuffle_ICNR(nn.Sequential):
"Upsample by `scale` from `ni` filters to `nf` (default `ni`), using `nn.PixelShuffle`."
def __init__(self, ni, nf=None, scale=2, blur=False, norm_type=NormType.Weight, act_cls=defaults.activation):
super().__init__()
nf = ifnone(nf, ni)
layers = [ConvLayer(ni, nf*(scale**2), ks=1, norm_type=norm_type, act_cls=act_cls, bias_std=0),
nn.PixelShuffle(scale)]
if norm_type == NormType.Weight:
layers[0][0].weight_v.data.copy_(icnr_init(layers[0][0].weight_v.data))
layers[0][0].weight_g.data.copy_(((layers[0][0].weight_v.data**2).sum(dim=[1,2,3])**0.5)[:,None,None,None])
else:
layers[0][0].weight.data.copy_(icnr_init(layers[0][0].weight.data))
if blur: layers += [nn.ReplicationPad2d((1,0,1,0)), nn.AvgPool2d(2, stride=1)]
super().__init__(*layers)
# Cell
def sequential(*args):
"Create an `nn.Sequential`, wrapping items with `Lambda` if needed"
if len(args) != 1 or not isinstance(args[0], OrderedDict):
args = list(args)
for i,o in enumerate(args):
if not isinstance(o,nn.Module): args[i] = Lambda(o)
return nn.Sequential(*args)
# Cell
class SequentialEx(Module):
"Like `nn.Sequential`, but with ModuleList semantics, and can access module input"
def __init__(self, *layers): self.layers = nn.ModuleList(layers)
def forward(self, x):
res = x
for l in self.layers:
res.orig = x
nres = l(res)
# We have to remove res.orig to avoid hanging refs and therefore memory leaks
res.orig, nres.orig = None, None
res = nres
return res
def __getitem__(self,i): return self.layers[i]
def append(self,l): return self.layers.append(l)
def extend(self,l): return self.layers.extend(l)
def insert(self,i,l): return self.layers.insert(i,l)
# Cell
class MergeLayer(Module):
"Merge a shortcut with the result of the module by adding them or concatenating them if `dense=True`."
def __init__(self, dense:bool=False): self.dense=dense
def forward(self, x): return torch.cat([x,x.orig], dim=1) if self.dense else (x+x.orig)
# Cell
class Cat(nn.ModuleList):
"Concatenate layers outputs over a given dim"
def __init__(self, layers, dim=1):
self.dim=dim
super().__init__(layers)
def forward(self, x): return torch.cat([l(x) for l in self], dim=self.dim)
# Cell
class SimpleCNN(nn.Sequential):
"Create a simple CNN with `filters`."
def __init__(self, filters, kernel_szs=None, strides=None, bn=True):
nl = len(filters)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
strides = ifnone(strides , [2]*nl)
layers = [ConvLayer(filters[i], filters[i+1], kernel_szs[i], stride=strides[i],
norm_type=(NormType.Batch if bn and i<nl-1 else None)) for i in range(nl)]
layers.append(PoolFlatten())
super().__init__(*layers)
# Cell
class ProdLayer(Module):
"Merge a shortcut with the result of the module by multiplying them."
def forward(self, x): return x * x.orig
# Cell
inplace_relu = partial(nn.ReLU, inplace=True)
# Cell
def SEModule(ch, reduction, act_cls=defaults.activation):
nf = math.ceil(ch//reduction/8)*8
return SequentialEx(nn.AdaptiveAvgPool2d(1),
ConvLayer(ch, nf, ks=1, norm_type=None, act_cls=act_cls),
ConvLayer(nf, ch, ks=1, norm_type=None, act_cls=nn.Sigmoid),
ProdLayer())
# Cell
class ResBlock(Module):
"Resnet block from `ni` to `nh` with `stride`"
@delegates(ConvLayer.__init__)
def __init__(self, expansion, ni, nf, stride=1, groups=1, reduction=None, nh1=None, nh2=None, dw=False, g2=1,
sa=False, sym=False, norm_type=NormType.Batch, act_cls=defaults.activation, ndim=2, ks=3,
pool=AvgPool, pool_first=True, **kwargs):
norm2 = (NormType.BatchZero if norm_type==NormType.Batch else
NormType.InstanceZero if norm_type==NormType.Instance else norm_type)
if nh2 is None: nh2 = nf
if nh1 is None: nh1 = nh2
nf,ni = nf*expansion,ni*expansion
k0 = dict(norm_type=norm_type, act_cls=act_cls, ndim=ndim, **kwargs)
k1 = dict(norm_type=norm2, act_cls=None, ndim=ndim, **kwargs)
convpath = [ConvLayer(ni, nh2, ks, stride=stride, groups=ni if dw else groups, **k0),
ConvLayer(nh2, nf, ks, groups=g2, **k1)
] if expansion == 1 else [
ConvLayer(ni, nh1, 1, **k0),
ConvLayer(nh1, nh2, ks, stride=stride, groups=nh1 if dw else groups, **k0),
ConvLayer(nh2, nf, 1, groups=g2, **k1)]
if reduction: convpath.append(SEModule(nf, reduction=reduction, act_cls=act_cls))
if sa: convpath.append(SimpleSelfAttention(nf,ks=1,sym=sym))
self.convpath = nn.Sequential(*convpath)
idpath = []
if ni!=nf: idpath.append(ConvLayer(ni, nf, 1, act_cls=None, ndim=ndim, **kwargs))
if stride!=1: idpath.insert((1,0)[pool_first], pool(stride, ndim=ndim, ceil_mode=True))
self.idpath = nn.Sequential(*idpath)
self.act = defaults.activation(inplace=True) if act_cls is defaults.activation else act_cls()
def forward(self, x): return self.act(self.convpath(x) + self.idpath(x))
# Cell
def SEBlock(expansion, ni, nf, groups=1, reduction=16, stride=1, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh1=nf*2, nh2=nf*expansion, **kwargs)
# Cell
def SEResNeXtBlock(expansion, ni, nf, groups=32, reduction=16, stride=1, base_width=4, **kwargs):
w = math.floor(nf * (base_width / 64)) * groups
return ResBlock(expansion, ni, nf, stride=stride, groups=groups, reduction=reduction, nh2=w, **kwargs)
# Cell
def SeparableBlock(expansion, ni, nf, reduction=16, stride=1, base_width=4, **kwargs):
return ResBlock(expansion, ni, nf, stride=stride, reduction=reduction, nh2=nf*2, dw=True, **kwargs)
# Cell
def _stack_tups(tuples, stack_dim=1):
"Stack tuple of tensors along `stack_dim`"
return tuple(torch.stack([t[i] for t in tuples], dim=stack_dim) for i in range_of(tuples[0]))
# Cell
class TimeDistributed(Module):
"Applies `module` over `tdim` identically for each step, use `low_mem` to compute one at a time."
def __init__(self, module, low_mem=False, tdim=1):
store_attr()
def forward(self, *tensors, **kwargs):
"input x with shape:(bs,seq_len,channels,width,height)"
if self.low_mem or self.tdim!=1:
return self.low_mem_forward(*tensors, **kwargs)
else:
#only support tdim=1
inp_shape = tensors[0].shape
bs, seq_len = inp_shape[0], inp_shape[1]
out = self.module(*[x.view(bs*seq_len, *x.shape[2:]) for x in tensors], **kwargs)
return self.format_output(out, bs, seq_len)
def low_mem_forward(self, *tensors, **kwargs):
"input x with shape:(bs,seq_len,channels,width,height)"
seq_len = tensors[0].shape[self.tdim]
args_split = [torch.unbind(x, dim=self.tdim) for x in tensors]
out = []
for i in range(seq_len):
out.append(self.module(*[args[i] for args in args_split]), **kwargs)
if isinstance(out[0], tuple):
return _stack_tups(out, stack_dim=self.tdim)
return torch.stack(out, dim=self.tdim)
def format_output(self, out, bs, seq_len):
"unstack from batchsize outputs"
if isinstance(out, tuple):
return tuple(out_i.view(bs, seq_len, *out_i.shape[1:]) for out_i in out)
return out.view(bs, seq_len,*out.shape[1:])
def __repr__(self):
return f'TimeDistributed({self.module})'
# Cell
from torch.jit import script
# Cell
@script
def _swish_jit_fwd(x): return x.mul(torch.sigmoid(x))
@script
def _swish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
return grad_output * (x_sigmoid * (1 + x * (1 - x_sigmoid)))
class _SwishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _swish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _swish_jit_bwd(x, grad_output)
# Cell
def swish(x, inplace=False): return _SwishJitAutoFn.apply(x)
# Cell
class Swish(Module):
def forward(self, x): return _SwishJitAutoFn.apply(x)
# Cell
@script
def _mish_jit_fwd(x): return x.mul(torch.tanh(F.softplus(x)))
@script
def _mish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
x_tanh_sp = F.softplus(x).tanh()
return grad_output.mul(x_tanh_sp + x * x_sigmoid * (1 - x_tanh_sp * x_tanh_sp))
class MishJitAutoFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _mish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _mish_jit_bwd(x, grad_output)
# Cell
def mish(x): return F.mish(x) if torch.__version__ >= '1.9' else MishJitAutoFn.apply(x)
# Cell
class Mish(Module):
def forward(self, x): return MishJitAutoFn.apply(x)
# Cell
if ismin_torch('1.9'): Mish = nn.Mish
# Cell
for o in swish,Swish,mish,Mish: o.__default_init__ = kaiming_uniform_
# Cell
class ParameterModule(Module):
"Register a lone parameter `p` in a module."
def __init__(self, p): self.val = p
def forward(self, x): return x
# Cell
def children_and_parameters(m):
"Return the children of `m` and its direct parameters not registered in modules."
children = list(m.children())
children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[])
for p in m.parameters():
if id(p) not in children_p: children.append(ParameterModule(p))
return children
# Cell
def has_children(m):
try: next(m.children())
except StopIteration: return False
return True
# Cell
def flatten_model(m):
"Return the list of all submodules and parameters of `m`"
return sum(map(flatten_model,children_and_parameters(m)),[]) if has_children(m) else [m]
# Cell
class NoneReduce():
"A context manager to evaluate `loss_func` with none reduce."
def __init__(self, loss_func): self.loss_func,self.old_red = loss_func,None
def __enter__(self):
if hasattr(self.loss_func, 'reduction'):
self.old_red = self.loss_func.reduction
self.loss_func.reduction = 'none'
return self.loss_func
else: return partial(self.loss_func, reduction='none')
def __exit__(self, type, value, traceback):
if self.old_red is not None: self.loss_func.reduction = self.old_red
# Cell
def in_channels(m):
"Return the shape of the first weight layer in `m`."
try: return next(l.weight.shape[1] for l in flatten_model(m) if nested_attr(l,'weight.ndim',-1)==4)
except StopIteration as e: e.args = ["No weight layer"]; raise |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# modified by Axel Sauer for "Projected GANs Converge Faster"
#
"""Main training loop."""
import os
import time
import copy
import json
import dill
import psutil
import PIL.Image
import numpy as np
import torch
import torch.nn.functional as F
import dnnlib
import pickle
from torch_utils import misc
from torch_utils import training_stats
from torch_utils.ops import conv2d_gradfix
from torch_utils.ops import grid_sample_gradfix
import legacy
from metrics import metric_main
#----------------------------------------------------------------------------
def setup_snapshot_image_grid(training_set, random_seed=0):
rnd = np.random.RandomState(random_seed)
gw = np.clip(7680 // training_set.image_shape[2], 7, 32)
gh = np.clip(4320 // training_set.image_shape[1], 4, 32)
# No labels => show random subset of training samples.
if not training_set.has_labels:
all_indices = list(range(len(training_set)))
rnd.shuffle(all_indices)
grid_indices = [all_indices[i % len(all_indices)] for i in range(gw * gh)]
else:
# Group training samples by label.
label_groups = dict() # label => [idx, ...]
for idx in range(len(training_set)):
label = tuple(training_set.get_details(idx).raw_label.flat[::-1])
if label not in label_groups:
label_groups[label] = []
label_groups[label].append(idx)
# Reorder.
label_order = sorted(label_groups.keys())
for label in label_order:
rnd.shuffle(label_groups[label])
# Organize into grid.
grid_indices = []
for y in range(gh):
label = label_order[y % len(label_order)]
indices = label_groups[label]
grid_indices += [indices[x % len(indices)] for x in range(gw)]
label_groups[label] = [indices[(i + gw) % len(indices)] for i in range(len(indices))]
# Load data.
images, labels = zip(*[training_set[i] for i in grid_indices])
return (gw, gh), np.stack(images), np.stack(labels)
#----------------------------------------------------------------------------
def save_image_grid(img, fname, drange, grid_size):
lo, hi = drange
img = np.asarray(img, dtype=np.float32)
img = (img - lo) * (255 / (hi - lo))
img = np.rint(img).clip(0, 255).astype(np.uint8)
gw, gh = grid_size
_N, C, H, W = img.shape
img = img.reshape([gh, gw, C, H, W])
img = img.transpose(0, 3, 1, 4, 2)
img = img.reshape([gh * H, gw * W, C])
assert C in [1, 3]
if C == 1:
PIL.Image.fromarray(img[:, :, 0], 'L').save(fname)
if C == 3:
PIL.Image.fromarray(img, 'RGB').save(fname)
#----------------------------------------------------------------------------
def training_loop(
run_dir = '.', # Output directory.
training_set_kwargs = {}, # Options for training set.
data_loader_kwargs = {}, # Options for torch.utils.data.DataLoader.
G_kwargs = {}, # Options for generator network.
D_kwargs = {}, # Options for discriminator network.
G_opt_kwargs = {}, # Options for generator optimizer.
D_opt_kwargs = {}, # Options for discriminator optimizer.
loss_kwargs = {}, # Options for loss function.
metrics = [], # Metrics to evaluate during training.
random_seed = 0, # Global random seed.
num_gpus = 1, # Number of GPUs participating in the training.
rank = 0, # Rank of the current process in [0, num_gpus[.
batch_size = 4, # Total batch size for one training iteration. Can be larger than batch_gpu * num_gpus.
batch_gpu = 4, # Number of samples processed at a time by one GPU.
ema_kimg = 10, # Half-life of the exponential moving average (EMA) of generator weights.
ema_rampup = 0.05, # EMA ramp-up coefficient. None = no rampup.
G_reg_interval = None, # How often to perform regularization for G? None = disable lazy regularization.
D_reg_interval = 16, # How often to perform regularization for D? None = disable lazy regularization.
total_kimg = 25000, # Total length of the training, measured in thousands of real images.
kimg_per_tick = 4, # Progress snapshot interval.
image_snapshot_ticks = 50, # How often to save image snapshots? None = disable.
network_snapshot_ticks = 50, # How often to save network snapshots? None = disable.
resume_pkl = None, # Network pickle to resume training from.
resume_kimg = 0, # First kimg to report when resuming training.
cudnn_benchmark = True, # Enable torch.backends.cudnn.benchmark?
abort_fn = None, # Callback function for determining whether to abort training. Must return consistent results across ranks.
progress_fn = None, # Callback function for updating training progress. Called for all ranks.
restart_every = -1, # Time interval in seconds to exit code
):
# Initialize.
start_time = time.time()
device = torch.device('cuda', rank)
np.random.seed(random_seed * num_gpus + rank)
torch.manual_seed(random_seed * num_gpus + rank)
torch.backends.cudnn.benchmark = cudnn_benchmark # Improves training speed.
torch.backends.cuda.matmul.allow_tf32 = False # Improves numerical accuracy.
torch.backends.cudnn.allow_tf32 = False # Improves numerical accuracy.
conv2d_gradfix.enabled = True # Improves training speed.
grid_sample_gradfix.enabled = True # Avoids errors with the augmentation pipe.
__RESTART__ = torch.tensor(0., device=device) # will be broadcasted to exit loop
__CUR_NIMG__ = torch.tensor(resume_kimg * 1000, dtype=torch.long, device=device)
__CUR_TICK__ = torch.tensor(0, dtype=torch.long, device=device)
__BATCH_IDX__ = torch.tensor(0, dtype=torch.long, device=device)
__PL_MEAN__ = torch.zeros([], device=device)
best_fid = 9999
# Load training set.
if rank == 0:
print('Loading training set...')
training_set = dnnlib.util.construct_class_by_name(**training_set_kwargs) # subclass of training.dataset.Dataset
training_set_sampler = misc.InfiniteSampler(dataset=training_set, rank=rank, num_replicas=num_gpus, seed=random_seed)
training_set_iterator = iter(torch.utils.data.DataLoader(dataset=training_set, sampler=training_set_sampler, batch_size=batch_size//num_gpus, **data_loader_kwargs))
if rank == 0:
print()
print('Num images: ', len(training_set))
print('Image shape:', training_set.image_shape)
print('Label shape:', training_set.label_shape)
print()
# Construct networks.
if rank == 0:
print('Constructing networks...')
common_kwargs = dict(c_dim=training_set.label_dim, img_resolution=training_set.resolution, img_channels=training_set.num_channels)
G = dnnlib.util.construct_class_by_name(**G_kwargs, **common_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module
D = dnnlib.util.construct_class_by_name(**D_kwargs, **common_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module
G_ema = copy.deepcopy(G).eval()
# Check for existing checkpoint
ckpt_pkl = None
if restart_every > 0 and os.path.isfile(misc.get_ckpt_path(run_dir)):
ckpt_pkl = resume_pkl = misc.get_ckpt_path(run_dir)
# Resume from existing pickle.
if (resume_pkl is not None) and (rank == 0):
print(f'Resuming test from "{resume_pkl}"')
with dnnlib.util.open_url(resume_pkl) as f:
resume_data = legacy.load_network_pkl(f)
for name, module in [('G', G), ('D', D), ('G_ema', G_ema)]:
misc.copy_params_and_buffers(resume_data[name], module, require_all=False)
if ckpt_pkl is not None: # Load ticks
__CUR_NIMG__ = resume_data['progress']['cur_nimg'].to(device)
__CUR_TICK__ = resume_data['progress']['cur_tick'].to(device)
__BATCH_IDX__ = resume_data['progress']['batch_idx'].to(device)
__PL_MEAN__ = resume_data['progress'].get('pl_mean', torch.zeros([])).to(device)
best_fid = resume_data['progress']['best_fid'] # only needed for rank == 0
# Print network summary tables.
if rank == 0:
z = torch.empty([batch_gpu, G.z_dim], device=device)
c = torch.empty([batch_gpu, G.c_dim], device=device)
img = misc.print_module_summary(G, [z, c])
misc.print_module_summary(D, [img, c])
# Distribute across GPUs.
if rank == 0:
print(f'Distributing across {num_gpus} GPUs...')
for module in [G, D, G_ema]:
if module is not None and num_gpus > 1:
for param in misc.params_and_buffers(module):
torch.distributed.broadcast(param, src=0)
# Setup training phases.
if rank == 0:
print('Setting up training phases...')
loss = dnnlib.util.construct_class_by_name(device=device, G=G, G_ema=G_ema, D=D, **loss_kwargs) # subclass of training.loss.Loss
phases = []
for name, module, opt_kwargs, reg_interval in [('G', G, G_opt_kwargs, G_reg_interval), ('D', D, D_opt_kwargs, D_reg_interval)]:
if reg_interval is None:
opt = dnnlib.util.construct_class_by_name(params=module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
phases += [dnnlib.EasyDict(name=name+'both', module=module, opt=opt, interval=1)]
else: # Lazy regularization.
mb_ratio = reg_interval / (reg_interval + 1)
opt_kwargs = dnnlib.EasyDict(opt_kwargs)
opt_kwargs.lr = opt_kwargs.lr * mb_ratio
opt_kwargs.betas = [beta ** mb_ratio for beta in opt_kwargs.betas]
opt = dnnlib.util.construct_class_by_name(module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
phases += [dnnlib.EasyDict(name=name+'main', module=module, opt=opt, interval=1)]
phases += [dnnlib.EasyDict(name=name+'reg', module=module, opt=opt, interval=reg_interval)]
for phase in phases:
phase.start_event = None
phase.end_event = None
if rank == 0:
phase.start_event = torch.cuda.Event(enable_timing=True)
phase.end_event = torch.cuda.Event(enable_timing=True)
# Export sample images.
grid_size = None
grid_z = None
grid_c = None
if rank == 0:
print('Exporting sample images...')
grid_size, images, labels = setup_snapshot_image_grid(training_set=training_set)
save_image_grid(images, os.path.join(run_dir, 'reals.png'), drange=[0,255], grid_size=grid_size)
grid_z = torch.randn([labels.shape[0], G.z_dim], device=device).split(batch_gpu)
grid_c = torch.from_numpy(labels).to(device).split(batch_gpu)
images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() for z, c in zip(grid_z, grid_c)]).numpy()
save_image_grid(images, os.path.join(run_dir, 'fakes_init.png'), drange=[-1,1], grid_size=grid_size)
# Initialize logs.
if rank == 0:
print('Initializing logs...')
stats_collector = training_stats.Collector(regex='.*')
stats_metrics = dict()
stats_jsonl = None
stats_tfevents = None
if rank == 0:
stats_jsonl = open(os.path.join(run_dir, 'stats.jsonl'), 'wt')
try:
import torch.utils.tensorboard as tensorboard
stats_tfevents = tensorboard.SummaryWriter(run_dir)
except ImportError as err:
print('Skipping tfevents export:', err)
# Train.
if rank == 0:
print(f'Training for {total_kimg} kimg...')
print()
if num_gpus > 1: # broadcast loaded states to all
torch.distributed.broadcast(__CUR_NIMG__, 0)
torch.distributed.broadcast(__CUR_TICK__, 0)
torch.distributed.broadcast(__BATCH_IDX__, 0)
torch.distributed.broadcast(__PL_MEAN__, 0)
torch.distributed.barrier() # ensure all processes received this info
cur_nimg = __CUR_NIMG__.item()
cur_tick = __CUR_TICK__.item()
tick_start_nimg = cur_nimg
tick_start_time = time.time()
maintenance_time = tick_start_time - start_time
batch_idx = __BATCH_IDX__.item()
if progress_fn is not None:
progress_fn(cur_nimg // 1000, total_kimg)
if hasattr(loss, 'pl_mean'):
loss.pl_mean.copy_(__PL_MEAN__)
while True:
with torch.autograd.profiler.record_function('data_fetch'):
phase_real_img, phase_real_c = next(training_set_iterator)
phase_real_img = (phase_real_img.to(device).to(torch.float32) / 127.5 - 1).split(batch_gpu)
phase_real_c = phase_real_c.to(device).split(batch_gpu)
all_gen_z = torch.randn([len(phases) * batch_size, G.z_dim], device=device)
all_gen_z = [phase_gen_z.split(batch_gpu) for phase_gen_z in all_gen_z.split(batch_size)]
all_gen_c = [training_set.get_label(np.random.randint(len(training_set))) for _ in range(len(phases) * batch_size)]
all_gen_c = torch.from_numpy(np.stack(all_gen_c)).pin_memory().to(device)
all_gen_c = [phase_gen_c.split(batch_gpu) for phase_gen_c in all_gen_c.split(batch_size)]
# Execute training phases.
for phase, phase_gen_z, phase_gen_c in zip(phases, all_gen_z, all_gen_c):
if batch_idx % phase.interval != 0:
continue
if phase.start_event is not None:
phase.start_event.record(torch.cuda.current_stream(device))
# Accumulate gradients.
phase.opt.zero_grad(set_to_none=True)
phase.module.requires_grad_(True)
if phase.name in ['Dmain', 'Dboth', 'Dreg']:
phase.module.feature_network.requires_grad_(False)
for real_img, real_c, gen_z, gen_c in zip(phase_real_img, phase_real_c, phase_gen_z, phase_gen_c):
loss.accumulate_gradients(phase=phase.name, real_img=real_img, real_c=real_c, gen_z=gen_z, gen_c=gen_c, gain=phase.interval, cur_nimg=cur_nimg)
phase.module.requires_grad_(False)
# Update weights.
with torch.autograd.profiler.record_function(phase.name + '_opt'):
params = [param for param in phase.module.parameters() if param.grad is not None]
# for para in params:
# print(para)
if len(params) > 0:
flat = torch.cat([param.grad.flatten() for param in params])
if num_gpus > 1:
torch.distributed.all_reduce(flat)
flat /= num_gpus
misc.nan_to_num(flat, nan=0, posinf=1e5, neginf=-1e5, out=flat)
grads = flat.split([param.numel() for param in params])
for param, grad in zip(params, grads):
param.grad = grad.reshape(param.shape)
phase.opt.step()
# Phase done.
if phase.end_event is not None:
phase.end_event.record(torch.cuda.current_stream(device))
# Update G_ema.
with torch.autograd.profiler.record_function('Gema'):
ema_nimg = ema_kimg * 1000
if ema_rampup is not None:
ema_nimg = min(ema_nimg, cur_nimg * ema_rampup)
ema_beta = 0.5 ** (batch_size / max(ema_nimg, 1e-8))
for p_ema, p in zip(G_ema.parameters(), G.parameters()):
p_ema.copy_(p.lerp(p_ema, ema_beta))
for b_ema, b in zip(G_ema.buffers(), G.buffers()):
b_ema.copy_(b)
# Update state.
cur_nimg += batch_size
batch_idx += 1
# Perform maintenance tasks once per tick.
done = (cur_nimg >= total_kimg * 1000)
if (not done) and (cur_tick != 0) and (cur_nimg < tick_start_nimg + kimg_per_tick * 1000):
continue
# Print status line, accumulating the same information in training_stats.
tick_end_time = time.time()
fields = []
fields += [f"tick {training_stats.report0("Progress/tick", cur_tick):<5d}"]
fields += [f"kimg {training_stats.report0("Progress/kimg", cur_nimg / 1e3):<8.1f}"]
fields += [f"time {dnnlib.util.format_time(training_stats.report0("Timing/total_sec", tick_end_time - start_time)):<12s}"]
fields += [f"sec/tick {training_stats.report0("Timing/sec_per_tick", tick_end_time - tick_start_time):<7.1f}"]
fields += [f"sec/kimg {training_stats.report0("Timing/sec_per_kimg", (tick_end_time - tick_start_time) / (cur_nimg - tick_start_nimg) * 1e3):<7.2f}"]
fields += [f"maintenance {training_stats.report0("Timing/maintenance_sec", maintenance_time):<6.1f}"]
fields += [f"cpumem {training_stats.report0("Resources/cpu_mem_gb", psutil.Process(os.getpid()).memory_info().rss / 2**30):<6.2f}"]
fields += [f"gpumem {training_stats.report0("Resources/peak_gpu_mem_gb", torch.cuda.max_memory_allocated(device) / 2**30):<6.2f}"]
fields += [f"reserved {training_stats.report0("Resources/peak_gpu_mem_reserved_gb", torch.cuda.max_memory_reserved(device) / 2**30):<6.2f}"]
fields += [f"gpumemc {training_stats.report0("Resources/peak_gpu_mem_gbc", torch.cuda.memory_allocated(device) / 2**30):<6.2f}"]
fields += [f"reservedc {training_stats.report0("Resources/peak_gpu_mem_reserved_gbc", torch.cuda.memory_reserved(device) / 2**30):<6.2f}"]
torch.cuda.reset_peak_memory_stats()
training_stats.report0('Timing/total_hours', (tick_end_time - start_time) / (60 * 60))
training_stats.report0('Timing/total_days', (tick_end_time - start_time) / (24 * 60 * 60))
if rank == 0:
print(' '.join(fields))
# Check for abort.
if (not done) and (abort_fn is not None) and abort_fn():
done = True
if rank == 0:
print()
print('Aborting...')
# Check for restart.
if (rank == 0) and (restart_every > 0) and (time.time() - start_time > restart_every):
print('Restart job...')
__RESTART__ = torch.tensor(1., device=device)
if num_gpus > 1:
torch.distributed.broadcast(__RESTART__, 0)
if __RESTART__:
done = True
print(f'Process {rank} leaving...')
if num_gpus > 1:
torch.distributed.barrier()
# Save image snapshot.
if (rank == 0) and (image_snapshot_ticks is not None) and (done or cur_tick % image_snapshot_ticks == 0):
images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() for z, c in zip(grid_z, grid_c)]).numpy()
save_image_grid(images, os.path.join(run_dir, f'fakes{cur_nimg//1000:06d}.png'), drange=[-1,1], grid_size=grid_size)
# Save network snapshot.
snapshot_pkl = None
snapshot_data = None
if (network_snapshot_ticks is not None) and (done or cur_tick % network_snapshot_ticks == 0):
snapshot_data = dict(G=G, D=D, G_ema=G_ema, training_set_kwargs=dict(training_set_kwargs))
for key, value in snapshot_data.items():
if isinstance(value, torch.nn.Module):
snapshot_data[key] = value
del value # conserve memory
# Save Checkpoint if needed
if (rank == 0) and (restart_every > 0) and (network_snapshot_ticks is not None) and (
done or cur_tick % network_snapshot_ticks == 0):
snapshot_pkl = misc.get_ckpt_path(run_dir)
# save as tensors to avoid error for multi GPU
snapshot_data['progress'] = {
'cur_nimg': torch.LongTensor([cur_nimg]),
'cur_tick': torch.LongTensor([cur_tick]),
'batch_idx': torch.LongTensor([batch_idx]),
'best_fid': best_fid,
}
if hasattr(loss, 'pl_mean'):
snapshot_data['progress']['pl_mean'] = loss.pl_mean.cpu()
with open(snapshot_pkl, 'wb') as f:
pickle.dump(snapshot_data, f)
# Evaluate metrics.
# if (snapshot_data is not None) and (len(metrics) > 0):
if cur_tick and (snapshot_data is not None) and (len(metrics) > 0):
if rank == 0:
print('Evaluating metrics...')
for metric in metrics:
result_dict = metric_main.calc_metric(metric=metric, G=snapshot_data['G_ema'], run_dir=run_dir, cur_nimg=cur_nimg,
dataset_kwargs=training_set_kwargs, num_gpus=num_gpus, rank=rank, device=device)
if rank == 0:
metric_main.report_metric(result_dict, run_dir=run_dir, snapshot_pkl=snapshot_pkl)
stats_metrics.update(result_dict.results)
# save best fid ckpt
snapshot_pkl = os.path.join(run_dir, f'best_model.pkl')
cur_nimg_txt = os.path.join(run_dir, f'best_nimg.txt')
if rank == 0:
if 'fid50k_full' in stats_metrics and stats_metrics['fid50k_full'] < best_fid:
best_fid = stats_metrics['fid50k_full']
with open(snapshot_pkl, 'wb') as f:
dill.dump(snapshot_data, f)
# save curr iteration number (directly saving it to pkl leads to problems with multi GPU)
with open(cur_nimg_txt, 'w') as f:
f.write(str(cur_nimg))
del snapshot_data # conserve memory
# Collect statistics.
for phase in phases:
value = []
if (phase.start_event is not None) and (phase.end_event is not None) and \
not (phase.start_event.cuda_event == 0 and phase.end_event.cuda_event == 0): # Both events were not initialized yet, can happen with restart
phase.end_event.synchronize()
value = phase.start_event.elapsed_time(phase.end_event)
training_stats.report0('Timing/' + phase.name, value)
stats_collector.update()
stats_dict = stats_collector.as_dict()
# Update logs.
timestamp = time.time()
if stats_jsonl is not None:
fields = dict(stats_dict, timestamp=timestamp)
stats_jsonl.write(json.dumps(fields) + '\n')
stats_jsonl.flush()
if stats_tfevents is not None:
global_step = int(cur_nimg / 1e3)
walltime = timestamp - start_time
for name, value in stats_dict.items():
stats_tfevents.add_scalar(name, value.mean, global_step=global_step, walltime=walltime)
for name, value in stats_metrics.items():
stats_tfevents.add_scalar(f'Metrics/{name}', value, global_step=global_step, walltime=walltime)
stats_tfevents.flush()
if progress_fn is not None:
progress_fn(cur_nimg // 1000, total_kimg)
# Update state.
cur_tick += 1
tick_start_nimg = cur_nimg
tick_start_time = time.time()
maintenance_time = tick_start_time - tick_end_time
if done:
break
# Done.
if rank == 0:
print()
print('Exiting...')
#----------------------------------------------------------------------------
| # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# modified by Axel Sauer for "Projected GANs Converge Faster"
#
"""Main training loop."""
import os
import time
import copy
import json
import dill
import psutil
import PIL.Image
import numpy as np
import torch
import torch.nn.functional as F
import dnnlib
import pickle
from torch_utils import misc
from torch_utils import training_stats
from torch_utils.ops import conv2d_gradfix
from torch_utils.ops import grid_sample_gradfix
import legacy
from metrics import metric_main
#----------------------------------------------------------------------------
def setup_snapshot_image_grid(training_set, random_seed=0):
rnd = np.random.RandomState(random_seed)
gw = np.clip(7680 // training_set.image_shape[2], 7, 32)
gh = np.clip(4320 // training_set.image_shape[1], 4, 32)
# No labels => show random subset of training samples.
if not training_set.has_labels:
all_indices = list(range(len(training_set)))
rnd.shuffle(all_indices)
grid_indices = [all_indices[i % len(all_indices)] for i in range(gw * gh)]
else:
# Group training samples by label.
label_groups = dict() # label => [idx, ...]
for idx in range(len(training_set)):
label = tuple(training_set.get_details(idx).raw_label.flat[::-1])
if label not in label_groups:
label_groups[label] = []
label_groups[label].append(idx)
# Reorder.
label_order = sorted(label_groups.keys())
for label in label_order:
rnd.shuffle(label_groups[label])
# Organize into grid.
grid_indices = []
for y in range(gh):
label = label_order[y % len(label_order)]
indices = label_groups[label]
grid_indices += [indices[x % len(indices)] for x in range(gw)]
label_groups[label] = [indices[(i + gw) % len(indices)] for i in range(len(indices))]
# Load data.
images, labels = zip(*[training_set[i] for i in grid_indices])
return (gw, gh), np.stack(images), np.stack(labels)
#----------------------------------------------------------------------------
def save_image_grid(img, fname, drange, grid_size):
lo, hi = drange
img = np.asarray(img, dtype=np.float32)
img = (img - lo) * (255 / (hi - lo))
img = np.rint(img).clip(0, 255).astype(np.uint8)
gw, gh = grid_size
_N, C, H, W = img.shape
img = img.reshape([gh, gw, C, H, W])
img = img.transpose(0, 3, 1, 4, 2)
img = img.reshape([gh * H, gw * W, C])
assert C in [1, 3]
if C == 1:
PIL.Image.fromarray(img[:, :, 0], 'L').save(fname)
if C == 3:
PIL.Image.fromarray(img, 'RGB').save(fname)
#----------------------------------------------------------------------------
def training_loop(
run_dir = '.', # Output directory.
training_set_kwargs = {}, # Options for training set.
data_loader_kwargs = {}, # Options for torch.utils.data.DataLoader.
G_kwargs = {}, # Options for generator network.
D_kwargs = {}, # Options for discriminator network.
G_opt_kwargs = {}, # Options for generator optimizer.
D_opt_kwargs = {}, # Options for discriminator optimizer.
loss_kwargs = {}, # Options for loss function.
metrics = [], # Metrics to evaluate during training.
random_seed = 0, # Global random seed.
num_gpus = 1, # Number of GPUs participating in the training.
rank = 0, # Rank of the current process in [0, num_gpus[.
batch_size = 4, # Total batch size for one training iteration. Can be larger than batch_gpu * num_gpus.
batch_gpu = 4, # Number of samples processed at a time by one GPU.
ema_kimg = 10, # Half-life of the exponential moving average (EMA) of generator weights.
ema_rampup = 0.05, # EMA ramp-up coefficient. None = no rampup.
G_reg_interval = None, # How often to perform regularization for G? None = disable lazy regularization.
D_reg_interval = 16, # How often to perform regularization for D? None = disable lazy regularization.
total_kimg = 25000, # Total length of the training, measured in thousands of real images.
kimg_per_tick = 4, # Progress snapshot interval.
image_snapshot_ticks = 50, # How often to save image snapshots? None = disable.
network_snapshot_ticks = 50, # How often to save network snapshots? None = disable.
resume_pkl = None, # Network pickle to resume training from.
resume_kimg = 0, # First kimg to report when resuming training.
cudnn_benchmark = True, # Enable torch.backends.cudnn.benchmark?
abort_fn = None, # Callback function for determining whether to abort training. Must return consistent results across ranks.
progress_fn = None, # Callback function for updating training progress. Called for all ranks.
restart_every = -1, # Time interval in seconds to exit code
):
# Initialize.
start_time = time.time()
device = torch.device('cuda', rank)
np.random.seed(random_seed * num_gpus + rank)
torch.manual_seed(random_seed * num_gpus + rank)
torch.backends.cudnn.benchmark = cudnn_benchmark # Improves training speed.
torch.backends.cuda.matmul.allow_tf32 = False # Improves numerical accuracy.
torch.backends.cudnn.allow_tf32 = False # Improves numerical accuracy.
conv2d_gradfix.enabled = True # Improves training speed.
grid_sample_gradfix.enabled = True # Avoids errors with the augmentation pipe.
__RESTART__ = torch.tensor(0., device=device) # will be broadcasted to exit loop
__CUR_NIMG__ = torch.tensor(resume_kimg * 1000, dtype=torch.long, device=device)
__CUR_TICK__ = torch.tensor(0, dtype=torch.long, device=device)
__BATCH_IDX__ = torch.tensor(0, dtype=torch.long, device=device)
__PL_MEAN__ = torch.zeros([], device=device)
best_fid = 9999
# Load training set.
if rank == 0:
print('Loading training set...')
training_set = dnnlib.util.construct_class_by_name(**training_set_kwargs) # subclass of training.dataset.Dataset
training_set_sampler = misc.InfiniteSampler(dataset=training_set, rank=rank, num_replicas=num_gpus, seed=random_seed)
training_set_iterator = iter(torch.utils.data.DataLoader(dataset=training_set, sampler=training_set_sampler, batch_size=batch_size//num_gpus, **data_loader_kwargs))
if rank == 0:
print()
print('Num images: ', len(training_set))
print('Image shape:', training_set.image_shape)
print('Label shape:', training_set.label_shape)
print()
# Construct networks.
if rank == 0:
print('Constructing networks...')
common_kwargs = dict(c_dim=training_set.label_dim, img_resolution=training_set.resolution, img_channels=training_set.num_channels)
G = dnnlib.util.construct_class_by_name(**G_kwargs, **common_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module
D = dnnlib.util.construct_class_by_name(**D_kwargs, **common_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module
G_ema = copy.deepcopy(G).eval()
# Check for existing checkpoint
ckpt_pkl = None
if restart_every > 0 and os.path.isfile(misc.get_ckpt_path(run_dir)):
ckpt_pkl = resume_pkl = misc.get_ckpt_path(run_dir)
# Resume from existing pickle.
if (resume_pkl is not None) and (rank == 0):
print(f'Resuming test from "{resume_pkl}"')
with dnnlib.util.open_url(resume_pkl) as f:
resume_data = legacy.load_network_pkl(f)
for name, module in [('G', G), ('D', D), ('G_ema', G_ema)]:
misc.copy_params_and_buffers(resume_data[name], module, require_all=False)
if ckpt_pkl is not None: # Load ticks
__CUR_NIMG__ = resume_data['progress']['cur_nimg'].to(device)
__CUR_TICK__ = resume_data['progress']['cur_tick'].to(device)
__BATCH_IDX__ = resume_data['progress']['batch_idx'].to(device)
__PL_MEAN__ = resume_data['progress'].get('pl_mean', torch.zeros([])).to(device)
best_fid = resume_data['progress']['best_fid'] # only needed for rank == 0
# Print network summary tables.
if rank == 0:
z = torch.empty([batch_gpu, G.z_dim], device=device)
c = torch.empty([batch_gpu, G.c_dim], device=device)
img = misc.print_module_summary(G, [z, c])
misc.print_module_summary(D, [img, c])
# Distribute across GPUs.
if rank == 0:
print(f'Distributing across {num_gpus} GPUs...')
for module in [G, D, G_ema]:
if module is not None and num_gpus > 1:
for param in misc.params_and_buffers(module):
torch.distributed.broadcast(param, src=0)
# Setup training phases.
if rank == 0:
print('Setting up training phases...')
loss = dnnlib.util.construct_class_by_name(device=device, G=G, G_ema=G_ema, D=D, **loss_kwargs) # subclass of training.loss.Loss
phases = []
for name, module, opt_kwargs, reg_interval in [('G', G, G_opt_kwargs, G_reg_interval), ('D', D, D_opt_kwargs, D_reg_interval)]:
if reg_interval is None:
opt = dnnlib.util.construct_class_by_name(params=module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
phases += [dnnlib.EasyDict(name=name+'both', module=module, opt=opt, interval=1)]
else: # Lazy regularization.
mb_ratio = reg_interval / (reg_interval + 1)
opt_kwargs = dnnlib.EasyDict(opt_kwargs)
opt_kwargs.lr = opt_kwargs.lr * mb_ratio
opt_kwargs.betas = [beta ** mb_ratio for beta in opt_kwargs.betas]
opt = dnnlib.util.construct_class_by_name(module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer
phases += [dnnlib.EasyDict(name=name+'main', module=module, opt=opt, interval=1)]
phases += [dnnlib.EasyDict(name=name+'reg', module=module, opt=opt, interval=reg_interval)]
for phase in phases:
phase.start_event = None
phase.end_event = None
if rank == 0:
phase.start_event = torch.cuda.Event(enable_timing=True)
phase.end_event = torch.cuda.Event(enable_timing=True)
# Export sample images.
grid_size = None
grid_z = None
grid_c = None
if rank == 0:
print('Exporting sample images...')
grid_size, images, labels = setup_snapshot_image_grid(training_set=training_set)
save_image_grid(images, os.path.join(run_dir, 'reals.png'), drange=[0,255], grid_size=grid_size)
grid_z = torch.randn([labels.shape[0], G.z_dim], device=device).split(batch_gpu)
grid_c = torch.from_numpy(labels).to(device).split(batch_gpu)
images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() for z, c in zip(grid_z, grid_c)]).numpy()
save_image_grid(images, os.path.join(run_dir, 'fakes_init.png'), drange=[-1,1], grid_size=grid_size)
# Initialize logs.
if rank == 0:
print('Initializing logs...')
stats_collector = training_stats.Collector(regex='.*')
stats_metrics = dict()
stats_jsonl = None
stats_tfevents = None
if rank == 0:
stats_jsonl = open(os.path.join(run_dir, 'stats.jsonl'), 'wt')
try:
import torch.utils.tensorboard as tensorboard
stats_tfevents = tensorboard.SummaryWriter(run_dir)
except ImportError as err:
print('Skipping tfevents export:', err)
# Train.
if rank == 0:
print(f'Training for {total_kimg} kimg...')
print()
if num_gpus > 1: # broadcast loaded states to all
torch.distributed.broadcast(__CUR_NIMG__, 0)
torch.distributed.broadcast(__CUR_TICK__, 0)
torch.distributed.broadcast(__BATCH_IDX__, 0)
torch.distributed.broadcast(__PL_MEAN__, 0)
torch.distributed.barrier() # ensure all processes received this info
cur_nimg = __CUR_NIMG__.item()
cur_tick = __CUR_TICK__.item()
tick_start_nimg = cur_nimg
tick_start_time = time.time()
maintenance_time = tick_start_time - start_time
batch_idx = __BATCH_IDX__.item()
if progress_fn is not None:
progress_fn(cur_nimg // 1000, total_kimg)
if hasattr(loss, 'pl_mean'):
loss.pl_mean.copy_(__PL_MEAN__)
while True:
with torch.autograd.profiler.record_function('data_fetch'):
phase_real_img, phase_real_c = next(training_set_iterator)
phase_real_img = (phase_real_img.to(device).to(torch.float32) / 127.5 - 1).split(batch_gpu)
phase_real_c = phase_real_c.to(device).split(batch_gpu)
all_gen_z = torch.randn([len(phases) * batch_size, G.z_dim], device=device)
all_gen_z = [phase_gen_z.split(batch_gpu) for phase_gen_z in all_gen_z.split(batch_size)]
all_gen_c = [training_set.get_label(np.random.randint(len(training_set))) for _ in range(len(phases) * batch_size)]
all_gen_c = torch.from_numpy(np.stack(all_gen_c)).pin_memory().to(device)
all_gen_c = [phase_gen_c.split(batch_gpu) for phase_gen_c in all_gen_c.split(batch_size)]
# Execute training phases.
for phase, phase_gen_z, phase_gen_c in zip(phases, all_gen_z, all_gen_c):
if batch_idx % phase.interval != 0:
continue
if phase.start_event is not None:
phase.start_event.record(torch.cuda.current_stream(device))
# Accumulate gradients.
phase.opt.zero_grad(set_to_none=True)
phase.module.requires_grad_(True)
if phase.name in ['Dmain', 'Dboth', 'Dreg']:
phase.module.feature_network.requires_grad_(False)
for real_img, real_c, gen_z, gen_c in zip(phase_real_img, phase_real_c, phase_gen_z, phase_gen_c):
loss.accumulate_gradients(phase=phase.name, real_img=real_img, real_c=real_c, gen_z=gen_z, gen_c=gen_c, gain=phase.interval, cur_nimg=cur_nimg)
phase.module.requires_grad_(False)
# Update weights.
with torch.autograd.profiler.record_function(phase.name + '_opt'):
params = [param for param in phase.module.parameters() if param.grad is not None]
# for para in params:
# print(para)
if len(params) > 0:
flat = torch.cat([param.grad.flatten() for param in params])
if num_gpus > 1:
torch.distributed.all_reduce(flat)
flat /= num_gpus
misc.nan_to_num(flat, nan=0, posinf=1e5, neginf=-1e5, out=flat)
grads = flat.split([param.numel() for param in params])
for param, grad in zip(params, grads):
param.grad = grad.reshape(param.shape)
phase.opt.step()
# Phase done.
if phase.end_event is not None:
phase.end_event.record(torch.cuda.current_stream(device))
# Update G_ema.
with torch.autograd.profiler.record_function('Gema'):
ema_nimg = ema_kimg * 1000
if ema_rampup is not None:
ema_nimg = min(ema_nimg, cur_nimg * ema_rampup)
ema_beta = 0.5 ** (batch_size / max(ema_nimg, 1e-8))
for p_ema, p in zip(G_ema.parameters(), G.parameters()):
p_ema.copy_(p.lerp(p_ema, ema_beta))
for b_ema, b in zip(G_ema.buffers(), G.buffers()):
b_ema.copy_(b)
# Update state.
cur_nimg += batch_size
batch_idx += 1
# Perform maintenance tasks once per tick.
done = (cur_nimg >= total_kimg * 1000)
if (not done) and (cur_tick != 0) and (cur_nimg < tick_start_nimg + kimg_per_tick * 1000):
continue
# Print status line, accumulating the same information in training_stats.
tick_end_time = time.time()
fields = []
fields += [f"tick {training_stats.report0('Progress/tick', cur_tick):<5d}"]
fields += [f"kimg {training_stats.report0('Progress/kimg', cur_nimg / 1e3):<8.1f}"]
fields += [f"time {dnnlib.util.format_time(training_stats.report0('Timing/total_sec', tick_end_time - start_time)):<12s}"]
fields += [f"sec/tick {training_stats.report0('Timing/sec_per_tick', tick_end_time - tick_start_time):<7.1f}"]
fields += [f"sec/kimg {training_stats.report0('Timing/sec_per_kimg', (tick_end_time - tick_start_time) / (cur_nimg - tick_start_nimg) * 1e3):<7.2f}"]
fields += [f"maintenance {training_stats.report0('Timing/maintenance_sec', maintenance_time):<6.1f}"]
fields += [f"cpumem {training_stats.report0('Resources/cpu_mem_gb', psutil.Process(os.getpid()).memory_info().rss / 2**30):<6.2f}"]
fields += [f"gpumem {training_stats.report0('Resources/peak_gpu_mem_gb', torch.cuda.max_memory_allocated(device) / 2**30):<6.2f}"]
fields += [f"reserved {training_stats.report0('Resources/peak_gpu_mem_reserved_gb', torch.cuda.max_memory_reserved(device) / 2**30):<6.2f}"]
fields += [f"gpumemc {training_stats.report0('Resources/peak_gpu_mem_gbc', torch.cuda.memory_allocated(device) / 2**30):<6.2f}"]
fields += [f"reservedc {training_stats.report0('Resources/peak_gpu_mem_reserved_gbc', torch.cuda.memory_reserved(device) / 2**30):<6.2f}"]
torch.cuda.reset_peak_memory_stats()
training_stats.report0('Timing/total_hours', (tick_end_time - start_time) / (60 * 60))
training_stats.report0('Timing/total_days', (tick_end_time - start_time) / (24 * 60 * 60))
if rank == 0:
print(' '.join(fields))
# Check for abort.
if (not done) and (abort_fn is not None) and abort_fn():
done = True
if rank == 0:
print()
print('Aborting...')
# Check for restart.
if (rank == 0) and (restart_every > 0) and (time.time() - start_time > restart_every):
print('Restart job...')
__RESTART__ = torch.tensor(1., device=device)
if num_gpus > 1:
torch.distributed.broadcast(__RESTART__, 0)
if __RESTART__:
done = True
print(f'Process {rank} leaving...')
if num_gpus > 1:
torch.distributed.barrier()
# Save image snapshot.
if (rank == 0) and (image_snapshot_ticks is not None) and (done or cur_tick % image_snapshot_ticks == 0):
images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() for z, c in zip(grid_z, grid_c)]).numpy()
save_image_grid(images, os.path.join(run_dir, f'fakes{cur_nimg//1000:06d}.png'), drange=[-1,1], grid_size=grid_size)
# Save network snapshot.
snapshot_pkl = None
snapshot_data = None
if (network_snapshot_ticks is not None) and (done or cur_tick % network_snapshot_ticks == 0):
snapshot_data = dict(G=G, D=D, G_ema=G_ema, training_set_kwargs=dict(training_set_kwargs))
for key, value in snapshot_data.items():
if isinstance(value, torch.nn.Module):
snapshot_data[key] = value
del value # conserve memory
# Save Checkpoint if needed
if (rank == 0) and (restart_every > 0) and (network_snapshot_ticks is not None) and (
done or cur_tick % network_snapshot_ticks == 0):
snapshot_pkl = misc.get_ckpt_path(run_dir)
# save as tensors to avoid error for multi GPU
snapshot_data['progress'] = {
'cur_nimg': torch.LongTensor([cur_nimg]),
'cur_tick': torch.LongTensor([cur_tick]),
'batch_idx': torch.LongTensor([batch_idx]),
'best_fid': best_fid,
}
if hasattr(loss, 'pl_mean'):
snapshot_data['progress']['pl_mean'] = loss.pl_mean.cpu()
with open(snapshot_pkl, 'wb') as f:
pickle.dump(snapshot_data, f)
# Evaluate metrics.
# if (snapshot_data is not None) and (len(metrics) > 0):
if cur_tick and (snapshot_data is not None) and (len(metrics) > 0):
if rank == 0:
print('Evaluating metrics...')
for metric in metrics:
result_dict = metric_main.calc_metric(metric=metric, G=snapshot_data['G_ema'], run_dir=run_dir, cur_nimg=cur_nimg,
dataset_kwargs=training_set_kwargs, num_gpus=num_gpus, rank=rank, device=device)
if rank == 0:
metric_main.report_metric(result_dict, run_dir=run_dir, snapshot_pkl=snapshot_pkl)
stats_metrics.update(result_dict.results)
# save best fid ckpt
snapshot_pkl = os.path.join(run_dir, f'best_model.pkl')
cur_nimg_txt = os.path.join(run_dir, f'best_nimg.txt')
if rank == 0:
if 'fid50k_full' in stats_metrics and stats_metrics['fid50k_full'] < best_fid:
best_fid = stats_metrics['fid50k_full']
with open(snapshot_pkl, 'wb') as f:
dill.dump(snapshot_data, f)
# save curr iteration number (directly saving it to pkl leads to problems with multi GPU)
with open(cur_nimg_txt, 'w') as f:
f.write(str(cur_nimg))
del snapshot_data # conserve memory
# Collect statistics.
for phase in phases:
value = []
if (phase.start_event is not None) and (phase.end_event is not None) and \
not (phase.start_event.cuda_event == 0 and phase.end_event.cuda_event == 0): # Both events were not initialized yet, can happen with restart
phase.end_event.synchronize()
value = phase.start_event.elapsed_time(phase.end_event)
training_stats.report0('Timing/' + phase.name, value)
stats_collector.update()
stats_dict = stats_collector.as_dict()
# Update logs.
timestamp = time.time()
if stats_jsonl is not None:
fields = dict(stats_dict, timestamp=timestamp)
stats_jsonl.write(json.dumps(fields) + '\n')
stats_jsonl.flush()
if stats_tfevents is not None:
global_step = int(cur_nimg / 1e3)
walltime = timestamp - start_time
for name, value in stats_dict.items():
stats_tfevents.add_scalar(name, value.mean, global_step=global_step, walltime=walltime)
for name, value in stats_metrics.items():
stats_tfevents.add_scalar(f'Metrics/{name}', value, global_step=global_step, walltime=walltime)
stats_tfevents.flush()
if progress_fn is not None:
progress_fn(cur_nimg // 1000, total_kimg)
# Update state.
cur_tick += 1
tick_start_nimg = cur_nimg
tick_start_time = time.time()
maintenance_time = tick_start_time - tick_end_time
if done:
break
# Done.
if rank == 0:
print()
print('Exiting...')
#----------------------------------------------------------------------------
|
#!/usr/bin/env python3
import sys
import traceback
from os import makedirs
from os.path import basename, splitext
from os.path import join as pjoin
from catas import parsers
from catas.parsers import FileType
from catas.parsers import ParseError
from catas.cli import MyArgumentError
from catas.gentest.cli import cli
from catas.count import cazy_counts_multi
from catas.count import HMMError
from catas.model import Model, RCDResult, PCAWithLabels
from catas.external import call_hmmscan, call_hmmscan_parser
from catas import __email__
from catas.exitcodes import (
EXIT_KEYBOARD, EXIT_UNKNOWN, EXIT_INPUT_FORMAT, EXIT_SYSERR
)
def runner(
infile: str,
hmms: str,
model_fname: str,
version: str,
outdir: str,
hmmscan_cmd: str,
):
""" Runs the pipeline. """
makedirs(outdir, exist_ok=False)
# Just touch it to make easier to integrate into package.
with open(pjoin(outdir, "__init__.py"), "w") as handle:
print('', file=handle)
domtab_filename = pjoin(outdir, "hmmer_domtab.tsv")
hmmer_filename = pjoin(outdir, "hmmer_text.txt")
dbcan_filename = pjoin(outdir, "hmmer_dbcan.tsv")
counts_filename = pjoin(outdir, "counts.tsv")
pca_filename = pjoin(outdir, "pca.tsv")
rcd_filename = pjoin(outdir, "rcd.tsv")
with open(model_fname, "rb") as model_handle:
model = Model.read(model_handle)
call_hmmscan(infile, hmms, domtab_filename, hmmer_filename, hmmscan_cmd)
call_hmmscan_parser(domtab_filename, dbcan_filename)
required_cols = list(model.hmm_lengths.keys())
with open(dbcan_filename, "r") as dbcan_handle:
parsed = parsers.parse(
dbcan_handle,
format=FileType.dbcan,
hmm_lens=model.hmm_lengths
)
label = splitext(basename(infile))[0]
counts = cazy_counts_multi([parsed], [label], required_cols)
counts.write_tsv(counts_filename)
predictions = model.predict(counts)
with open(pca_filename, "w") as pca_handle:
(PCAWithLabels
.concat([predictions])
.write_tsv(pca_handle))
with open(rcd_filename, "w") as rcd_handle:
RCDResult.write_tsv(rcd_handle, predictions.rcd)
return
def main(): # noqa
try:
args = cli(prog=sys.argv[0], args=sys.argv[1:])
except MyArgumentError as e:
print(e.message, file=sys.stderr)
sys.exit(e.errno)
if args.outdir is None:
outdir = f"test_{args.version}"
else:
outdir = args.outdir
try:
runner(
args.infile,
args.hmms,
args.model,
args.version,
outdir,
args.hmmscan_path
)
except ParseError as e:
if e.line is not None:
header = "Failed to parse file <{}> at line {}.\n".format(
e.filename, e.line)
else:
header = "Failed to parse file <{}>.\n".format(e.filename)
print("{}\n{}".format(header, e.message), file=sys.stderr)
sys.exit(EXIT_INPUT_FORMAT)
except HMMError as e:
msg = (
"Encountered an hmm that wasn't present in the training data.\n"
f"Offending HMMs were: {", ".join(e.hmms)}"
)
print(msg, file=sys.stderr)
sys.exit(EXIT_INPUT_FORMAT)
pass
except OSError as e:
msg = (
"Encountered a system error.\n"
"We can't control these, and they're usually related to your OS.\n"
"Try running again.\n"
)
print(msg, file=sys.stderr)
print(e.strerror, file=sys.stderr)
sys.exit(EXIT_SYSERR)
except MemoryError:
msg = (
"Ran out of memory!\n"
"Catastrophy shouldn't use much RAM, so check other "
"processes and try running again."
)
print(msg, file=sys.stderr)
sys.exit(EXIT_SYSERR)
except KeyboardInterrupt:
print("Received keyboard interrupt. Exiting.", file=sys.stderr)
sys.exit(EXIT_KEYBOARD)
except Exception as e:
msg = (
"I'm so sorry, but we've encountered an unexpected error.\n"
"This shouldn't happen, so please file a bug report with the "
"authors.\nWe will be extremely grateful!\n\n"
"You can email us at {}.\n"
"Alternatively, you can file the issue directly on the repo "
"<https://github.com/ccdmb/catastrophy/issues>\n\n"
"Please attach a copy of the following message:"
).format(__email__)
print(e, file=sys.stderr)
traceback.print_exc(file=sys.stderr)
sys.exit(EXIT_UNKNOWN)
return
| #!/usr/bin/env python3
import sys
import traceback
from os import makedirs
from os.path import basename, splitext
from os.path import join as pjoin
from catas import parsers
from catas.parsers import FileType
from catas.parsers import ParseError
from catas.cli import MyArgumentError
from catas.gentest.cli import cli
from catas.count import cazy_counts_multi
from catas.count import HMMError
from catas.model import Model, RCDResult, PCAWithLabels
from catas.external import call_hmmscan, call_hmmscan_parser
from catas import __email__
from catas.exitcodes import (
EXIT_KEYBOARD, EXIT_UNKNOWN, EXIT_INPUT_FORMAT, EXIT_SYSERR
)
def runner(
infile: str,
hmms: str,
model_fname: str,
version: str,
outdir: str,
hmmscan_cmd: str,
):
""" Runs the pipeline. """
makedirs(outdir, exist_ok=False)
# Just touch it to make easier to integrate into package.
with open(pjoin(outdir, "__init__.py"), "w") as handle:
print('', file=handle)
domtab_filename = pjoin(outdir, "hmmer_domtab.tsv")
hmmer_filename = pjoin(outdir, "hmmer_text.txt")
dbcan_filename = pjoin(outdir, "hmmer_dbcan.tsv")
counts_filename = pjoin(outdir, "counts.tsv")
pca_filename = pjoin(outdir, "pca.tsv")
rcd_filename = pjoin(outdir, "rcd.tsv")
with open(model_fname, "rb") as model_handle:
model = Model.read(model_handle)
call_hmmscan(infile, hmms, domtab_filename, hmmer_filename, hmmscan_cmd)
call_hmmscan_parser(domtab_filename, dbcan_filename)
required_cols = list(model.hmm_lengths.keys())
with open(dbcan_filename, "r") as dbcan_handle:
parsed = parsers.parse(
dbcan_handle,
format=FileType.dbcan,
hmm_lens=model.hmm_lengths
)
label = splitext(basename(infile))[0]
counts = cazy_counts_multi([parsed], [label], required_cols)
counts.write_tsv(counts_filename)
predictions = model.predict(counts)
with open(pca_filename, "w") as pca_handle:
(PCAWithLabels
.concat([predictions])
.write_tsv(pca_handle))
with open(rcd_filename, "w") as rcd_handle:
RCDResult.write_tsv(rcd_handle, predictions.rcd)
return
def main(): # noqa
try:
args = cli(prog=sys.argv[0], args=sys.argv[1:])
except MyArgumentError as e:
print(e.message, file=sys.stderr)
sys.exit(e.errno)
if args.outdir is None:
outdir = f"test_{args.version}"
else:
outdir = args.outdir
try:
runner(
args.infile,
args.hmms,
args.model,
args.version,
outdir,
args.hmmscan_path
)
except ParseError as e:
if e.line is not None:
header = "Failed to parse file <{}> at line {}.\n".format(
e.filename, e.line)
else:
header = "Failed to parse file <{}>.\n".format(e.filename)
print("{}\n{}".format(header, e.message), file=sys.stderr)
sys.exit(EXIT_INPUT_FORMAT)
except HMMError as e:
msg = (
"Encountered an hmm that wasn't present in the training data.\n"
f"Offending HMMs were: {', '.join(e.hmms)}"
)
print(msg, file=sys.stderr)
sys.exit(EXIT_INPUT_FORMAT)
pass
except OSError as e:
msg = (
"Encountered a system error.\n"
"We can't control these, and they're usually related to your OS.\n"
"Try running again.\n"
)
print(msg, file=sys.stderr)
print(e.strerror, file=sys.stderr)
sys.exit(EXIT_SYSERR)
except MemoryError:
msg = (
"Ran out of memory!\n"
"Catastrophy shouldn't use much RAM, so check other "
"processes and try running again."
)
print(msg, file=sys.stderr)
sys.exit(EXIT_SYSERR)
except KeyboardInterrupt:
print("Received keyboard interrupt. Exiting.", file=sys.stderr)
sys.exit(EXIT_KEYBOARD)
except Exception as e:
msg = (
"I'm so sorry, but we've encountered an unexpected error.\n"
"This shouldn't happen, so please file a bug report with the "
"authors.\nWe will be extremely grateful!\n\n"
"You can email us at {}.\n"
"Alternatively, you can file the issue directly on the repo "
"<https://github.com/ccdmb/catastrophy/issues>\n\n"
"Please attach a copy of the following message:"
).format(__email__)
print(e, file=sys.stderr)
traceback.print_exc(file=sys.stderr)
sys.exit(EXIT_UNKNOWN)
return
|
import base64
from ocs_ci.framework import config
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs import constants
from ocs_ci.helpers.helpers import storagecluster_independent_check
class RGW(object):
"""
Wrapper class for interaction with a cluster's RGW service
"""
def __init__(self, namespace=None):
self.namespace = (
namespace if namespace else config.ENV_DATA["cluster_namespace"]
)
if storagecluster_independent_check():
sc_name = constants.DEFAULT_EXTERNAL_MODE_STORAGECLASS_RGW
else:
sc_name = constants.DEFAULT_STORAGECLASS_RGW
self.storageclass = OCP(
kind="storageclass", namespace=namespace, resource_name=sc_name
)
self.s3_internal_endpoint = (
self.storageclass.get().get("parameters").get("endpoint")
)
self.region = self.storageclass.get().get("parameters").get("region")
# Todo: Implement retrieval in cases where CephObjectStoreUser is available
self.key_id = None
self.secret_key = None
self.s3_resource = None
def get_credentials(self, secret_name=constants.NOOBAA_OBJECTSTOREUSER_SECRET):
"""
Get Endpoint, Access key and Secret key from OCS secret. Endpoint is
taken from rgw exposed service. Use rgw_endpoint fixture in test to get
it exposed.
Args:
secret_name (str): Name of secret to be used
for getting RGW credentials
Returns:
tuple: Endpoint, Access key, Secret key
"""
secret_ocp_obj = OCP(kind=constants.SECRET, namespace=self.namespace)
route_ocp_obj = OCP(
kind=constants.ROUTE, namespace=config.ENV_DATA["cluster_namespace"]
)
creds_secret_obj = secret_ocp_obj.get(secret_name)
if config.DEPLOYMENT["external_mode"]:
endpoint = route_ocp_obj.get(
resource_name=constants.RGW_SERVICE_EXTERNAL_MODE
)
else:
endpoint = route_ocp_obj.get(
resource_name=constants.RGW_SERVICE_INTERNAL_MODE
)
endpoint = f"http://{endpoint["status"]["ingress"][0]["host"]}"
access_key = base64.b64decode(
creds_secret_obj.get("data").get("AccessKey")
).decode("utf-8")
secret_key = base64.b64decode(
creds_secret_obj.get("data").get("SecretKey")
).decode("utf-8")
return (endpoint, access_key, secret_key)
| import base64
from ocs_ci.framework import config
from ocs_ci.ocs.ocp import OCP
from ocs_ci.ocs import constants
from ocs_ci.helpers.helpers import storagecluster_independent_check
class RGW(object):
"""
Wrapper class for interaction with a cluster's RGW service
"""
def __init__(self, namespace=None):
self.namespace = (
namespace if namespace else config.ENV_DATA["cluster_namespace"]
)
if storagecluster_independent_check():
sc_name = constants.DEFAULT_EXTERNAL_MODE_STORAGECLASS_RGW
else:
sc_name = constants.DEFAULT_STORAGECLASS_RGW
self.storageclass = OCP(
kind="storageclass", namespace=namespace, resource_name=sc_name
)
self.s3_internal_endpoint = (
self.storageclass.get().get("parameters").get("endpoint")
)
self.region = self.storageclass.get().get("parameters").get("region")
# Todo: Implement retrieval in cases where CephObjectStoreUser is available
self.key_id = None
self.secret_key = None
self.s3_resource = None
def get_credentials(self, secret_name=constants.NOOBAA_OBJECTSTOREUSER_SECRET):
"""
Get Endpoint, Access key and Secret key from OCS secret. Endpoint is
taken from rgw exposed service. Use rgw_endpoint fixture in test to get
it exposed.
Args:
secret_name (str): Name of secret to be used
for getting RGW credentials
Returns:
tuple: Endpoint, Access key, Secret key
"""
secret_ocp_obj = OCP(kind=constants.SECRET, namespace=self.namespace)
route_ocp_obj = OCP(
kind=constants.ROUTE, namespace=config.ENV_DATA["cluster_namespace"]
)
creds_secret_obj = secret_ocp_obj.get(secret_name)
if config.DEPLOYMENT["external_mode"]:
endpoint = route_ocp_obj.get(
resource_name=constants.RGW_SERVICE_EXTERNAL_MODE
)
else:
endpoint = route_ocp_obj.get(
resource_name=constants.RGW_SERVICE_INTERNAL_MODE
)
endpoint = f"http://{endpoint['status']['ingress'][0]['host']}"
access_key = base64.b64decode(
creds_secret_obj.get("data").get("AccessKey")
).decode("utf-8")
secret_key = base64.b64decode(
creds_secret_obj.get("data").get("SecretKey")
).decode("utf-8")
return (endpoint, access_key, secret_key)
|
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
from PySide2 import QtWidgets
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
import azlmbr.legacy.general as general
# fmt: off
class Tests():
new_action = "File->New action working as expected"
open_action = "File->Open action working as expected"
# fmt: on
GENERAL_WAIT = 0.5 # seconds
class TestFileMenuDefaultNewOpen:
"""
Summary:
When clicked on File->New, new script opens
File->Open should open the FileBrowser
Expected Behavior:
New and Open actions should work as expected.
Test Steps:
1) Open Script Canvas window (Tools > Script Canvas)
2) Get the SC window object
3) Trigger File->New action
4) Verify if New tab is opened
5) Trigger File->Open action
6) Close Script Canvas window
Note:
- This test file must be called from the Open 3D Engine Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
:return: None
"""
@pyside_utils.wrap_async
async def run_test(self):
# 1) Open Script Canvas window (Tools > Script Canvas)
general.open_pane("Script Canvas")
# 2) Get the SC window object
editor_window = pyside_utils.get_editor_main_window()
sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas")
sc_main = sc.findChild(QtWidgets.QMainWindow)
sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs")
# wait for the intial tab count
general.idle_wait(GENERAL_WAIT)
initial_tabs_count = sc_tabs.count()
# 3) Trigger File->New action
action = pyside_utils.find_child_by_pattern(
sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction}
)
action.trigger()
# 4) Verify if New tab is opened
general.idle_wait(GENERAL_WAIT)
Report.info(f"{Tests.new_action}: {sc_tabs.count() == initial_tabs_count + 1}")
# 5) Trigger File->Open action
action = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_Open", "type": QtWidgets.QAction})
pyside_utils.trigger_action_async(action)
general.idle_wait(GENERAL_WAIT)
popup = await pyside_utils.wait_for_modal_widget()
Report.info(f"{Tests.open_action}: {popup and "Open" in popup.windowTitle()}")
popup.close()
# 6) Close Script Canvas window
general.close_pane("Script Canvas")
test = TestFileMenuDefaultNewOpen()
test.run_test()
| """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
from PySide2 import QtWidgets
import editor_python_test_tools.pyside_utils as pyside_utils
from editor_python_test_tools.utils import Report
import azlmbr.legacy.general as general
# fmt: off
class Tests():
new_action = "File->New action working as expected"
open_action = "File->Open action working as expected"
# fmt: on
GENERAL_WAIT = 0.5 # seconds
class TestFileMenuDefaultNewOpen:
"""
Summary:
When clicked on File->New, new script opens
File->Open should open the FileBrowser
Expected Behavior:
New and Open actions should work as expected.
Test Steps:
1) Open Script Canvas window (Tools > Script Canvas)
2) Get the SC window object
3) Trigger File->New action
4) Verify if New tab is opened
5) Trigger File->Open action
6) Close Script Canvas window
Note:
- This test file must be called from the Open 3D Engine Editor command terminal
- Any passed and failed tests are written to the Editor.log file.
Parsing the file or running a log_monitor are required to observe the test results.
:return: None
"""
@pyside_utils.wrap_async
async def run_test(self):
# 1) Open Script Canvas window (Tools > Script Canvas)
general.open_pane("Script Canvas")
# 2) Get the SC window object
editor_window = pyside_utils.get_editor_main_window()
sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas")
sc_main = sc.findChild(QtWidgets.QMainWindow)
sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs")
# wait for the intial tab count
general.idle_wait(GENERAL_WAIT)
initial_tabs_count = sc_tabs.count()
# 3) Trigger File->New action
action = pyside_utils.find_child_by_pattern(
sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction}
)
action.trigger()
# 4) Verify if New tab is opened
general.idle_wait(GENERAL_WAIT)
Report.info(f"{Tests.new_action}: {sc_tabs.count() == initial_tabs_count + 1}")
# 5) Trigger File->Open action
action = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_Open", "type": QtWidgets.QAction})
pyside_utils.trigger_action_async(action)
general.idle_wait(GENERAL_WAIT)
popup = await pyside_utils.wait_for_modal_widget()
Report.info(f"{Tests.open_action}: {popup and 'Open' in popup.windowTitle()}")
popup.close()
# 6) Close Script Canvas window
general.close_pane("Script Canvas")
test = TestFileMenuDefaultNewOpen()
test.run_test()
|
"""
Computes a dendrogram based on a given categorical observation.
"""
from typing import Optional, Sequence, Dict, Any
import pandas as pd
from anndata import AnnData
from pandas.api.types import is_categorical_dtype
from .. import logging as logg
from .._utils import _doc_params
from ..tools._utils import _choose_representation, doc_use_rep, doc_n_pcs
@_doc_params(n_pcs=doc_n_pcs, use_rep=doc_use_rep)
def dendrogram(
adata: AnnData,
groupby: str,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
var_names: Optional[Sequence[str]] = None,
use_raw: Optional[bool] = None,
cor_method: str = 'pearson',
linkage_method: str = 'complete',
optimal_ordering: bool = False,
key_added: Optional[str] = None,
inplace: bool = True,
) -> Optional[Dict[str, Any]]:
"""\
Computes a hierarchical clustering for the given `groupby` categories.
By default, the PCA representation is used unless `.X`
has less than 50 variables.
Alternatively, a list of `var_names` (e.g. genes) can be given.
Average values of either `var_names` or components are used
to compute a correlation matrix.
The hierarchical clustering can be visualized using
:func:`scanpy.pl.dendrogram` or multiple other visualizations that can
include a dendrogram: :func:`~scanpy.pl.matrixplot`,
:func:`~scanpy.pl.heatmap`, :func:`~scanpy.pl.dotplot`,
and :func:`~scanpy.pl.stacked_violin`.
.. note::
The computation of the hierarchical clustering is based on predefined
groups and not per cell. The correlation matrix is computed using by
default pearson but other methods are available.
Parameters
----------
adata
Annotated data matrix
{n_pcs}
{use_rep}
var_names
List of var_names to use for computing the hierarchical clustering.
If `var_names` is given, then `use_rep` and `n_pcs` is ignored.
use_raw
Only when `var_names` is not None.
Use `raw` attribute of `adata` if present.
cor_method
correlation method to use.
Options are 'pearson', 'kendall', and 'spearman'
linkage_method
linkage method to use. See :func:`scipy.cluster.hierarchy.linkage`
for more information.
optimal_ordering
Same as the optimal_ordering argument of :func:`scipy.cluster.hierarchy.linkage`
which reorders the linkage matrix so that the distance between successive
leaves is minimal.
key_added
By default, the dendrogram information is added to
`.uns[f'dendrogram_{{groupby}}']`.
Notice that the `groupby` information is added to the dendrogram.
inplace
If `True`, adds dendrogram information to `adata.uns[key_added]`,
else this function returns the information.
Returns
-------
If `inplace=False`, returns dendrogram information,
else `adata.uns[key_added]` is updated with it.
Examples
--------
>>> import scanpy as sc
>>> adata = sc.datasets.pbmc68k_reduced()
>>> sc.tl.dendrogram(adata, groupby='bulk_labels')
>>> sc.pl.dendrogram(adata)
>>> markers = ['C1QA', 'PSAP', 'CD79A', 'CD79B', 'CST3', 'LYZ']
>>> sc.pl.dotplot(adata, markers, groupby='bulk_labels', dendrogram=True)
"""
if isinstance(groupby, str):
# if not a list, turn into a list
groupby = [groupby]
for group in groupby:
if group not in adata.obs_keys():
raise ValueError(
'groupby has to be a valid observation. '
f'Given value: {group}, valid observations: {adata.obs_keys()}'
)
if not is_categorical_dtype(adata.obs[group]):
raise ValueError(
'groupby has to be a categorical observation. '
f'Given value: {group}, Column type: {adata.obs[group].dtype}'
)
if var_names is None:
rep_df = pd.DataFrame(
_choose_representation(adata, use_rep=use_rep, n_pcs=n_pcs)
)
categorical = adata.obs[groupby[0]]
if len(groupby) > 1:
for group in groupby[1:]:
# create new category by merging the given groupby categories
categorical = (
categorical.astype(str) + "_" + adata.obs[group].astype(str)
).astype('category')
categorical.name = "_".join(groupby)
rep_df.set_index(categorical, inplace=True)
categories = rep_df.index.categories
else:
gene_names = adata.raw.var_names if use_raw else adata.var_names
from ..plotting._anndata import _prepare_dataframe
categories, rep_df = _prepare_dataframe(adata, gene_names, groupby, use_raw)
# aggregate values within categories using 'mean'
mean_df = rep_df.groupby(level=0).mean()
import scipy.cluster.hierarchy as sch
corr_matrix = mean_df.T.corr(method=cor_method)
z_var = sch.linkage(
corr_matrix, method=linkage_method, optimal_ordering=optimal_ordering
)
dendro_info = sch.dendrogram(z_var, labels=list(categories), no_plot=True)
dat = dict(
linkage=z_var,
groupby=groupby,
use_rep=use_rep,
cor_method=cor_method,
linkage_method=linkage_method,
categories_ordered=dendro_info['ivl'],
categories_idx_ordered=dendro_info['leaves'],
dendrogram_info=dendro_info,
correlation_matrix=corr_matrix.values,
)
if inplace:
if key_added is None:
key_added = f'dendrogram_{'_'.join(groupby)}'
logg.info(f'Storing dendrogram info using `.uns[{key_added!r}]`')
adata.uns[key_added] = dat
else:
return dat
| """
Computes a dendrogram based on a given categorical observation.
"""
from typing import Optional, Sequence, Dict, Any
import pandas as pd
from anndata import AnnData
from pandas.api.types import is_categorical_dtype
from .. import logging as logg
from .._utils import _doc_params
from ..tools._utils import _choose_representation, doc_use_rep, doc_n_pcs
@_doc_params(n_pcs=doc_n_pcs, use_rep=doc_use_rep)
def dendrogram(
adata: AnnData,
groupby: str,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
var_names: Optional[Sequence[str]] = None,
use_raw: Optional[bool] = None,
cor_method: str = 'pearson',
linkage_method: str = 'complete',
optimal_ordering: bool = False,
key_added: Optional[str] = None,
inplace: bool = True,
) -> Optional[Dict[str, Any]]:
"""\
Computes a hierarchical clustering for the given `groupby` categories.
By default, the PCA representation is used unless `.X`
has less than 50 variables.
Alternatively, a list of `var_names` (e.g. genes) can be given.
Average values of either `var_names` or components are used
to compute a correlation matrix.
The hierarchical clustering can be visualized using
:func:`scanpy.pl.dendrogram` or multiple other visualizations that can
include a dendrogram: :func:`~scanpy.pl.matrixplot`,
:func:`~scanpy.pl.heatmap`, :func:`~scanpy.pl.dotplot`,
and :func:`~scanpy.pl.stacked_violin`.
.. note::
The computation of the hierarchical clustering is based on predefined
groups and not per cell. The correlation matrix is computed using by
default pearson but other methods are available.
Parameters
----------
adata
Annotated data matrix
{n_pcs}
{use_rep}
var_names
List of var_names to use for computing the hierarchical clustering.
If `var_names` is given, then `use_rep` and `n_pcs` is ignored.
use_raw
Only when `var_names` is not None.
Use `raw` attribute of `adata` if present.
cor_method
correlation method to use.
Options are 'pearson', 'kendall', and 'spearman'
linkage_method
linkage method to use. See :func:`scipy.cluster.hierarchy.linkage`
for more information.
optimal_ordering
Same as the optimal_ordering argument of :func:`scipy.cluster.hierarchy.linkage`
which reorders the linkage matrix so that the distance between successive
leaves is minimal.
key_added
By default, the dendrogram information is added to
`.uns[f'dendrogram_{{groupby}}']`.
Notice that the `groupby` information is added to the dendrogram.
inplace
If `True`, adds dendrogram information to `adata.uns[key_added]`,
else this function returns the information.
Returns
-------
If `inplace=False`, returns dendrogram information,
else `adata.uns[key_added]` is updated with it.
Examples
--------
>>> import scanpy as sc
>>> adata = sc.datasets.pbmc68k_reduced()
>>> sc.tl.dendrogram(adata, groupby='bulk_labels')
>>> sc.pl.dendrogram(adata)
>>> markers = ['C1QA', 'PSAP', 'CD79A', 'CD79B', 'CST3', 'LYZ']
>>> sc.pl.dotplot(adata, markers, groupby='bulk_labels', dendrogram=True)
"""
if isinstance(groupby, str):
# if not a list, turn into a list
groupby = [groupby]
for group in groupby:
if group not in adata.obs_keys():
raise ValueError(
'groupby has to be a valid observation. '
f'Given value: {group}, valid observations: {adata.obs_keys()}'
)
if not is_categorical_dtype(adata.obs[group]):
raise ValueError(
'groupby has to be a categorical observation. '
f'Given value: {group}, Column type: {adata.obs[group].dtype}'
)
if var_names is None:
rep_df = pd.DataFrame(
_choose_representation(adata, use_rep=use_rep, n_pcs=n_pcs)
)
categorical = adata.obs[groupby[0]]
if len(groupby) > 1:
for group in groupby[1:]:
# create new category by merging the given groupby categories
categorical = (
categorical.astype(str) + "_" + adata.obs[group].astype(str)
).astype('category')
categorical.name = "_".join(groupby)
rep_df.set_index(categorical, inplace=True)
categories = rep_df.index.categories
else:
gene_names = adata.raw.var_names if use_raw else adata.var_names
from ..plotting._anndata import _prepare_dataframe
categories, rep_df = _prepare_dataframe(adata, gene_names, groupby, use_raw)
# aggregate values within categories using 'mean'
mean_df = rep_df.groupby(level=0).mean()
import scipy.cluster.hierarchy as sch
corr_matrix = mean_df.T.corr(method=cor_method)
z_var = sch.linkage(
corr_matrix, method=linkage_method, optimal_ordering=optimal_ordering
)
dendro_info = sch.dendrogram(z_var, labels=list(categories), no_plot=True)
dat = dict(
linkage=z_var,
groupby=groupby,
use_rep=use_rep,
cor_method=cor_method,
linkage_method=linkage_method,
categories_ordered=dendro_info['ivl'],
categories_idx_ordered=dendro_info['leaves'],
dendrogram_info=dendro_info,
correlation_matrix=corr_matrix.values,
)
if inplace:
if key_added is None:
key_added = f'dendrogram_{"_".join(groupby)}'
logg.info(f'Storing dendrogram info using `.uns[{key_added!r}]`')
adata.uns[key_added] = dat
else:
return dat
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from pathlib import Path
from qlib.model.meta.task import MetaTask
from qlib.contrib.meta.data_selection.model import MetaModelDS
from qlib.contrib.meta.data_selection.dataset import InternalData, MetaDatasetDS
from qlib.data.dataset.handler import DataHandlerLP
import pandas as pd
import fire
import sys
from tqdm.auto import tqdm
import yaml
import pickle
from qlib import auto_init
from qlib.model.trainer import TrainerR, task_train
from qlib.utils import init_instance_by_config
from qlib.workflow.task.gen import RollingGen, task_generator
from qlib.workflow import R
from qlib.tests.data import GetData
DIRNAME = Path(__file__).absolute().resolve().parent
sys.path.append(str(DIRNAME.parent / "baseline"))
from rolling_benchmark import RollingBenchmark # NOTE: sys.path is changed for import RollingBenchmark
class DDGDA:
"""
please run `python workflow.py run_all` to run the full workflow of the experiment
**NOTE**
before running the example, please clean your previous results with following command
- `rm -r mlruns`
"""
def __init__(self, sim_task_model="linear", forecast_model="linear"):
self.step = 20
# NOTE:
# the horizon must match the meaning in the base task template
self.horizon = 20
self.meta_exp_name = "DDG-DA"
self.sim_task_model = sim_task_model # The model to capture the distribution of data.
self.forecast_model = forecast_model # downstream forecasting models' type
def get_feature_importance(self):
# this must be lightGBM, because it needs to get the feature importance
rb = RollingBenchmark(model_type="gbdt")
task = rb.basic_task()
model = init_instance_by_config(task["model"])
dataset = init_instance_by_config(task["dataset"])
model.fit(dataset)
fi = model.get_feature_importance()
# Because the model use numpy instead of dataframe for training lightgbm
# So the we must use following extra steps to get the right feature importance
df = dataset.prepare(segments=slice(None), col_set="feature", data_key=DataHandlerLP.DK_R)
cols = df.columns
fi_named = {cols[int(k.split("_")[1])]: imp for k, imp in fi.to_dict().items()}
return pd.Series(fi_named)
def dump_data_for_proxy_model(self):
"""
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
"""
topk = 30
fi = self.get_feature_importance()
col_selected = fi.nlargest(topk)
rb = RollingBenchmark(model_type=self.sim_task_model)
task = rb.basic_task()
dataset = init_instance_by_config(task["dataset"])
prep_ds = dataset.prepare(slice(None), col_set=["feature", "label"], data_key=DataHandlerLP.DK_L)
feature_df = prep_ds["feature"]
label_df = prep_ds["label"]
feature_selected = feature_df.loc[:, col_selected.index]
feature_selected = feature_selected.groupby("datetime").apply(lambda df: (df - df.mean()).div(df.std()))
feature_selected = feature_selected.fillna(0.0)
df_all = {
"label": label_df.reindex(feature_selected.index),
"feature": feature_selected,
}
df_all = pd.concat(df_all, axis=1)
df_all.to_pickle(DIRNAME / "fea_label_df.pkl")
# dump data in handler format for aligning the interface
handler = DataHandlerLP(
data_loader={
"class": "qlib.data.dataset.loader.StaticDataLoader",
"kwargs": {"config": DIRNAME / "fea_label_df.pkl"},
}
)
handler.to_pickle(DIRNAME / "handler_proxy.pkl", dump_all=True)
@property
def _internal_data_path(self):
return DIRNAME / f"internal_data_s{self.step}.pkl"
def dump_meta_ipt(self):
"""
Dump data for training meta model.
This function will dump the input data for meta model
"""
# According to the experiments, the choice of the model type is very important for achieving good results
rb = RollingBenchmark(model_type=self.sim_task_model)
sim_task = rb.basic_task()
if self.sim_task_model == "gbdt":
sim_task["model"].setdefault("kwargs", {}).update({"early_stopping_rounds": None, "num_boost_round": 150})
exp_name_sim = f"data_sim_s{self.step}"
internal_data = InternalData(sim_task, self.step, exp_name=exp_name_sim)
internal_data.setup(trainer=TrainerR)
with self._internal_data_path.open("wb") as f:
pickle.dump(internal_data, f)
def train_meta_model(self):
"""
training a meta model based on a simplified linear proxy model;
"""
# 1) leverage the simplified proxy forecasting model to train meta model.
# - Only the dataset part is important, in current version of meta model will integrate the
rb = RollingBenchmark(model_type=self.sim_task_model)
sim_task = rb.basic_task()
proxy_forecast_model_task = {
# "model": "qlib.contrib.model.linear.LinearModel",
"dataset": {
"class": "qlib.data.dataset.DatasetH",
"kwargs": {
"handler": f"file://{(DIRNAME / "handler_proxy.pkl").absolute()}",
"segments": {
"train": ("2008-01-01", "2010-12-31"),
"test": ("2011-01-01", sim_task["dataset"]["kwargs"]["segments"]["test"][1]),
},
},
},
# "record": ["qlib.workflow.record_temp.SignalRecord"]
}
# the proxy_forecast_model_task will be used to create meta tasks.
# The test date of first task will be 2011-01-01. Each test segment will be about 20days
# The tasks include all training tasks and test tasks.
# 2) preparing meta dataset
kwargs = dict(
task_tpl=proxy_forecast_model_task,
step=self.step,
segments=0.62, # keep test period consistent with the dataset yaml
trunc_days=1 + self.horizon,
hist_step_n=30,
fill_method="max",
rolling_ext_days=0,
)
# NOTE:
# the input of meta model (internal data) are shared between proxy model and final forecasting model
# but their task test segment are not aligned! It worked in my previous experiment.
# So the misalignment will not affect the effectiveness of the method.
with self._internal_data_path.open("rb") as f:
internal_data = pickle.load(f)
md = MetaDatasetDS(exp_name=internal_data, **kwargs)
# 3) train and logging meta model
with R.start(experiment_name=self.meta_exp_name):
R.log_params(**kwargs)
mm = MetaModelDS(step=self.step, hist_step_n=kwargs["hist_step_n"], lr=0.001, max_epoch=200, seed=43)
mm.fit(md)
R.save_objects(model=mm)
@property
def _task_path(self):
return DIRNAME / f"tasks_s{self.step}.pkl"
def meta_inference(self):
"""
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
"""
# 1) get meta model
exp = R.get_exp(experiment_name=self.meta_exp_name)
rec = exp.list_recorders(rtype=exp.RT_L)[0]
meta_model: MetaModelDS = rec.load_object("model")
# 2)
# we are transfer to knowledge of meta model to final forecasting tasks.
# Create MetaTaskDataset for the final forecasting tasks
# Aligning the setting of it to the MetaTaskDataset when training Meta model is necessary
# 2.1) get previous config
param = rec.list_params()
trunc_days = int(param["trunc_days"])
step = int(param["step"])
hist_step_n = int(param["hist_step_n"])
fill_method = param.get("fill_method", "max")
rb = RollingBenchmark(model_type=self.forecast_model)
task_l = rb.create_rolling_tasks()
# 2.2) create meta dataset for final dataset
kwargs = dict(
task_tpl=task_l,
step=step,
segments=0.0, # all the tasks are for testing
trunc_days=trunc_days,
hist_step_n=hist_step_n,
fill_method=fill_method,
task_mode=MetaTask.PROC_MODE_TRANSFER,
)
with self._internal_data_path.open("rb") as f:
internal_data = pickle.load(f)
mds = MetaDatasetDS(exp_name=internal_data, **kwargs)
# 3) meta model make inference and get new qlib task
new_tasks = meta_model.inference(mds)
with self._task_path.open("wb") as f:
pickle.dump(new_tasks, f)
def train_and_eval_tasks(self):
"""
Training the tasks generated by meta model
Then evaluate it
"""
with self._task_path.open("rb") as f:
tasks = pickle.load(f)
rb = RollingBenchmark(rolling_exp="rolling_ds", model_type=self.forecast_model)
rb.train_rolling_tasks(tasks)
rb.ens_rolling()
rb.update_rolling_rec()
def run_all(self):
# 1) file: handler_proxy.pkl
self.dump_data_for_proxy_model()
# 2)
# file: internal_data_s20.pkl
# mlflow: data_sim_s20, models for calculating meta_ipt
self.dump_meta_ipt()
# 3) meta model will be stored in `DDG-DA`
self.train_meta_model()
# 4) new_tasks are saved in "tasks_s20.pkl" (reweighter is added)
self.meta_inference()
# 5) load the saved tasks and train model
self.train_and_eval_tasks()
if __name__ == "__main__":
GetData().qlib_data(exists_skip=True)
auto_init()
fire.Fire(DDGDA)
| # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from pathlib import Path
from qlib.model.meta.task import MetaTask
from qlib.contrib.meta.data_selection.model import MetaModelDS
from qlib.contrib.meta.data_selection.dataset import InternalData, MetaDatasetDS
from qlib.data.dataset.handler import DataHandlerLP
import pandas as pd
import fire
import sys
from tqdm.auto import tqdm
import yaml
import pickle
from qlib import auto_init
from qlib.model.trainer import TrainerR, task_train
from qlib.utils import init_instance_by_config
from qlib.workflow.task.gen import RollingGen, task_generator
from qlib.workflow import R
from qlib.tests.data import GetData
DIRNAME = Path(__file__).absolute().resolve().parent
sys.path.append(str(DIRNAME.parent / "baseline"))
from rolling_benchmark import RollingBenchmark # NOTE: sys.path is changed for import RollingBenchmark
class DDGDA:
"""
please run `python workflow.py run_all` to run the full workflow of the experiment
**NOTE**
before running the example, please clean your previous results with following command
- `rm -r mlruns`
"""
def __init__(self, sim_task_model="linear", forecast_model="linear"):
self.step = 20
# NOTE:
# the horizon must match the meaning in the base task template
self.horizon = 20
self.meta_exp_name = "DDG-DA"
self.sim_task_model = sim_task_model # The model to capture the distribution of data.
self.forecast_model = forecast_model # downstream forecasting models' type
def get_feature_importance(self):
# this must be lightGBM, because it needs to get the feature importance
rb = RollingBenchmark(model_type="gbdt")
task = rb.basic_task()
model = init_instance_by_config(task["model"])
dataset = init_instance_by_config(task["dataset"])
model.fit(dataset)
fi = model.get_feature_importance()
# Because the model use numpy instead of dataframe for training lightgbm
# So the we must use following extra steps to get the right feature importance
df = dataset.prepare(segments=slice(None), col_set="feature", data_key=DataHandlerLP.DK_R)
cols = df.columns
fi_named = {cols[int(k.split("_")[1])]: imp for k, imp in fi.to_dict().items()}
return pd.Series(fi_named)
def dump_data_for_proxy_model(self):
"""
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
"""
topk = 30
fi = self.get_feature_importance()
col_selected = fi.nlargest(topk)
rb = RollingBenchmark(model_type=self.sim_task_model)
task = rb.basic_task()
dataset = init_instance_by_config(task["dataset"])
prep_ds = dataset.prepare(slice(None), col_set=["feature", "label"], data_key=DataHandlerLP.DK_L)
feature_df = prep_ds["feature"]
label_df = prep_ds["label"]
feature_selected = feature_df.loc[:, col_selected.index]
feature_selected = feature_selected.groupby("datetime").apply(lambda df: (df - df.mean()).div(df.std()))
feature_selected = feature_selected.fillna(0.0)
df_all = {
"label": label_df.reindex(feature_selected.index),
"feature": feature_selected,
}
df_all = pd.concat(df_all, axis=1)
df_all.to_pickle(DIRNAME / "fea_label_df.pkl")
# dump data in handler format for aligning the interface
handler = DataHandlerLP(
data_loader={
"class": "qlib.data.dataset.loader.StaticDataLoader",
"kwargs": {"config": DIRNAME / "fea_label_df.pkl"},
}
)
handler.to_pickle(DIRNAME / "handler_proxy.pkl", dump_all=True)
@property
def _internal_data_path(self):
return DIRNAME / f"internal_data_s{self.step}.pkl"
def dump_meta_ipt(self):
"""
Dump data for training meta model.
This function will dump the input data for meta model
"""
# According to the experiments, the choice of the model type is very important for achieving good results
rb = RollingBenchmark(model_type=self.sim_task_model)
sim_task = rb.basic_task()
if self.sim_task_model == "gbdt":
sim_task["model"].setdefault("kwargs", {}).update({"early_stopping_rounds": None, "num_boost_round": 150})
exp_name_sim = f"data_sim_s{self.step}"
internal_data = InternalData(sim_task, self.step, exp_name=exp_name_sim)
internal_data.setup(trainer=TrainerR)
with self._internal_data_path.open("wb") as f:
pickle.dump(internal_data, f)
def train_meta_model(self):
"""
training a meta model based on a simplified linear proxy model;
"""
# 1) leverage the simplified proxy forecasting model to train meta model.
# - Only the dataset part is important, in current version of meta model will integrate the
rb = RollingBenchmark(model_type=self.sim_task_model)
sim_task = rb.basic_task()
proxy_forecast_model_task = {
# "model": "qlib.contrib.model.linear.LinearModel",
"dataset": {
"class": "qlib.data.dataset.DatasetH",
"kwargs": {
"handler": f"file://{(DIRNAME / 'handler_proxy.pkl').absolute()}",
"segments": {
"train": ("2008-01-01", "2010-12-31"),
"test": ("2011-01-01", sim_task["dataset"]["kwargs"]["segments"]["test"][1]),
},
},
},
# "record": ["qlib.workflow.record_temp.SignalRecord"]
}
# the proxy_forecast_model_task will be used to create meta tasks.
# The test date of first task will be 2011-01-01. Each test segment will be about 20days
# The tasks include all training tasks and test tasks.
# 2) preparing meta dataset
kwargs = dict(
task_tpl=proxy_forecast_model_task,
step=self.step,
segments=0.62, # keep test period consistent with the dataset yaml
trunc_days=1 + self.horizon,
hist_step_n=30,
fill_method="max",
rolling_ext_days=0,
)
# NOTE:
# the input of meta model (internal data) are shared between proxy model and final forecasting model
# but their task test segment are not aligned! It worked in my previous experiment.
# So the misalignment will not affect the effectiveness of the method.
with self._internal_data_path.open("rb") as f:
internal_data = pickle.load(f)
md = MetaDatasetDS(exp_name=internal_data, **kwargs)
# 3) train and logging meta model
with R.start(experiment_name=self.meta_exp_name):
R.log_params(**kwargs)
mm = MetaModelDS(step=self.step, hist_step_n=kwargs["hist_step_n"], lr=0.001, max_epoch=200, seed=43)
mm.fit(md)
R.save_objects(model=mm)
@property
def _task_path(self):
return DIRNAME / f"tasks_s{self.step}.pkl"
def meta_inference(self):
"""
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
"""
# 1) get meta model
exp = R.get_exp(experiment_name=self.meta_exp_name)
rec = exp.list_recorders(rtype=exp.RT_L)[0]
meta_model: MetaModelDS = rec.load_object("model")
# 2)
# we are transfer to knowledge of meta model to final forecasting tasks.
# Create MetaTaskDataset for the final forecasting tasks
# Aligning the setting of it to the MetaTaskDataset when training Meta model is necessary
# 2.1) get previous config
param = rec.list_params()
trunc_days = int(param["trunc_days"])
step = int(param["step"])
hist_step_n = int(param["hist_step_n"])
fill_method = param.get("fill_method", "max")
rb = RollingBenchmark(model_type=self.forecast_model)
task_l = rb.create_rolling_tasks()
# 2.2) create meta dataset for final dataset
kwargs = dict(
task_tpl=task_l,
step=step,
segments=0.0, # all the tasks are for testing
trunc_days=trunc_days,
hist_step_n=hist_step_n,
fill_method=fill_method,
task_mode=MetaTask.PROC_MODE_TRANSFER,
)
with self._internal_data_path.open("rb") as f:
internal_data = pickle.load(f)
mds = MetaDatasetDS(exp_name=internal_data, **kwargs)
# 3) meta model make inference and get new qlib task
new_tasks = meta_model.inference(mds)
with self._task_path.open("wb") as f:
pickle.dump(new_tasks, f)
def train_and_eval_tasks(self):
"""
Training the tasks generated by meta model
Then evaluate it
"""
with self._task_path.open("rb") as f:
tasks = pickle.load(f)
rb = RollingBenchmark(rolling_exp="rolling_ds", model_type=self.forecast_model)
rb.train_rolling_tasks(tasks)
rb.ens_rolling()
rb.update_rolling_rec()
def run_all(self):
# 1) file: handler_proxy.pkl
self.dump_data_for_proxy_model()
# 2)
# file: internal_data_s20.pkl
# mlflow: data_sim_s20, models for calculating meta_ipt
self.dump_meta_ipt()
# 3) meta model will be stored in `DDG-DA`
self.train_meta_model()
# 4) new_tasks are saved in "tasks_s20.pkl" (reweighter is added)
self.meta_inference()
# 5) load the saved tasks and train model
self.train_and_eval_tasks()
if __name__ == "__main__":
GetData().qlib_data(exists_skip=True)
auto_init()
fire.Fire(DDGDA)
|
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
from __future__ import annotations
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from azureml.core import Run
from InnerEye.Azure.azure_util import RUN_CONTEXT, download_outputs_from_run, fetch_child_runs, tag_values_all_distinct
from InnerEye.Common.common_util import OTHER_RUNS_SUBDIR_NAME, check_properties_are_not_none
from InnerEye.ML.common import BEST_CHECKPOINT_FILE_NAME_WITH_SUFFIX, get_best_checkpoint_path, \
get_recovery_checkpoint_path
from InnerEye.ML.deep_learning_config import CHECKPOINT_FOLDER, OutputParams
@dataclass(frozen=True)
class RunRecovery:
"""
Class to encapsulate information relating to run recovery (eg: check point paths for parent and child runs)
"""
checkpoints_roots: List[Path]
@staticmethod
def download_best_checkpoints_from_child_runs(config: OutputParams, run: Run) -> RunRecovery:
"""
Downloads the best checkpoints from all child runs of the provided Hyperdrive parent run.
The checkpoints for the sibling runs will go into folder 'OTHER_RUNS/<cross_validation_split>'
in the checkpoint folder. There is special treatment for the child run that is equal to the present AzureML
run, its checkpoints will be read off the checkpoint folder as-is.
:param config: Model related configs.
:param run: The Hyperdrive parent run to download from.
:return: run recovery information
"""
child_runs: List[Run] = fetch_child_runs(run)
if not child_runs:
raise ValueError(f"AzureML run {run.id} does not have any child runs.")
logging.info(f"Run {run.id} has {len(child_runs)} child runs: {", ".join(c.id for c in child_runs)}")
tag_to_use = 'cross_validation_split_index'
can_use_split_indices = tag_values_all_distinct(child_runs, tag_to_use)
# download checkpoints for the child runs in the root of the parent
child_runs_checkpoints_roots: List[Path] = []
for child in child_runs:
if child.id == RUN_CONTEXT.id:
# We expect to find the file(s) we need in config.checkpoint_folder
child_dst = config.checkpoint_folder
else:
subdir = str(child.tags[tag_to_use] if can_use_split_indices else child.number)
child_dst = config.checkpoint_folder / OTHER_RUNS_SUBDIR_NAME / subdir
download_outputs_from_run(
blobs_path=Path(CHECKPOINT_FOLDER) / BEST_CHECKPOINT_FILE_NAME_WITH_SUFFIX,
destination=child_dst,
run=child,
is_file=True
)
child_runs_checkpoints_roots.append(child_dst)
return RunRecovery(checkpoints_roots=child_runs_checkpoints_roots)
@staticmethod
def download_all_checkpoints_from_run(config: OutputParams, run: Run,
subfolder: Optional[str] = None) -> RunRecovery:
"""
Downloads all checkpoints of the provided run inside the checkpoints folder.
:param config: Model related configs.
:param run: Run whose checkpoints should be recovered
:param subfolder: optional subfolder name, if provided the checkpoints will be downloaded to
CHECKPOINT_FOLDER / subfolder. If None, the checkpoint are downloaded to CHECKPOINT_FOLDER of the current run.
:return: run recovery information
"""
if fetch_child_runs(run):
raise ValueError(f"AzureML run {run.id} has child runs, this method does not support those.")
destination_folder = config.checkpoint_folder / subfolder if subfolder else config.checkpoint_folder
download_outputs_from_run(
blobs_path=Path(CHECKPOINT_FOLDER),
destination=destination_folder,
run=run
)
time.sleep(60) # Needed because AML is not fast enough to download
return RunRecovery(checkpoints_roots=[destination_folder])
def get_recovery_checkpoint_paths(self) -> List[Path]:
return [get_recovery_checkpoint_path(x) for x in self.checkpoints_roots]
def get_best_checkpoint_paths(self) -> List[Path]:
return [get_best_checkpoint_path(x) for x in self.checkpoints_roots]
def _validate(self) -> None:
check_properties_are_not_none(self)
if len(self.checkpoints_roots) == 0:
raise ValueError("checkpoints_roots must not be empty")
def __post_init__(self) -> None:
self._validate()
logging.info(f"Storing {len(self.checkpoints_roots)}checkpoints roots:")
for p in self.checkpoints_roots:
logging.info(str(p))
| # ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
from __future__ import annotations
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
from azureml.core import Run
from InnerEye.Azure.azure_util import RUN_CONTEXT, download_outputs_from_run, fetch_child_runs, tag_values_all_distinct
from InnerEye.Common.common_util import OTHER_RUNS_SUBDIR_NAME, check_properties_are_not_none
from InnerEye.ML.common import BEST_CHECKPOINT_FILE_NAME_WITH_SUFFIX, get_best_checkpoint_path, \
get_recovery_checkpoint_path
from InnerEye.ML.deep_learning_config import CHECKPOINT_FOLDER, OutputParams
@dataclass(frozen=True)
class RunRecovery:
"""
Class to encapsulate information relating to run recovery (eg: check point paths for parent and child runs)
"""
checkpoints_roots: List[Path]
@staticmethod
def download_best_checkpoints_from_child_runs(config: OutputParams, run: Run) -> RunRecovery:
"""
Downloads the best checkpoints from all child runs of the provided Hyperdrive parent run.
The checkpoints for the sibling runs will go into folder 'OTHER_RUNS/<cross_validation_split>'
in the checkpoint folder. There is special treatment for the child run that is equal to the present AzureML
run, its checkpoints will be read off the checkpoint folder as-is.
:param config: Model related configs.
:param run: The Hyperdrive parent run to download from.
:return: run recovery information
"""
child_runs: List[Run] = fetch_child_runs(run)
if not child_runs:
raise ValueError(f"AzureML run {run.id} does not have any child runs.")
logging.info(f"Run {run.id} has {len(child_runs)} child runs: {', '.join(c.id for c in child_runs)}")
tag_to_use = 'cross_validation_split_index'
can_use_split_indices = tag_values_all_distinct(child_runs, tag_to_use)
# download checkpoints for the child runs in the root of the parent
child_runs_checkpoints_roots: List[Path] = []
for child in child_runs:
if child.id == RUN_CONTEXT.id:
# We expect to find the file(s) we need in config.checkpoint_folder
child_dst = config.checkpoint_folder
else:
subdir = str(child.tags[tag_to_use] if can_use_split_indices else child.number)
child_dst = config.checkpoint_folder / OTHER_RUNS_SUBDIR_NAME / subdir
download_outputs_from_run(
blobs_path=Path(CHECKPOINT_FOLDER) / BEST_CHECKPOINT_FILE_NAME_WITH_SUFFIX,
destination=child_dst,
run=child,
is_file=True
)
child_runs_checkpoints_roots.append(child_dst)
return RunRecovery(checkpoints_roots=child_runs_checkpoints_roots)
@staticmethod
def download_all_checkpoints_from_run(config: OutputParams, run: Run,
subfolder: Optional[str] = None) -> RunRecovery:
"""
Downloads all checkpoints of the provided run inside the checkpoints folder.
:param config: Model related configs.
:param run: Run whose checkpoints should be recovered
:param subfolder: optional subfolder name, if provided the checkpoints will be downloaded to
CHECKPOINT_FOLDER / subfolder. If None, the checkpoint are downloaded to CHECKPOINT_FOLDER of the current run.
:return: run recovery information
"""
if fetch_child_runs(run):
raise ValueError(f"AzureML run {run.id} has child runs, this method does not support those.")
destination_folder = config.checkpoint_folder / subfolder if subfolder else config.checkpoint_folder
download_outputs_from_run(
blobs_path=Path(CHECKPOINT_FOLDER),
destination=destination_folder,
run=run
)
time.sleep(60) # Needed because AML is not fast enough to download
return RunRecovery(checkpoints_roots=[destination_folder])
def get_recovery_checkpoint_paths(self) -> List[Path]:
return [get_recovery_checkpoint_path(x) for x in self.checkpoints_roots]
def get_best_checkpoint_paths(self) -> List[Path]:
return [get_best_checkpoint_path(x) for x in self.checkpoints_roots]
def _validate(self) -> None:
check_properties_are_not_none(self)
if len(self.checkpoints_roots) == 0:
raise ValueError("checkpoints_roots must not be empty")
def __post_init__(self) -> None:
self._validate()
logging.info(f"Storing {len(self.checkpoints_roots)}checkpoints roots:")
for p in self.checkpoints_roots:
logging.info(str(p))
|
"""
This module contains StructuredLogEvent and EventSummary classes.
"""
from collections import defaultdict
import json
import logging
import os
import re
import sys
from datetime import datetime
from prettytable import PrettyTable
from jade.common import JOBS_OUTPUT_DIR
from jade.exceptions import InvalidConfiguration
from jade.utils.utils import dump_data, load_data
EVENT_DIR = "events"
EVENTS_FILENAME = "events.json"
EVENT_CATEGORY_ERROR = "Error"
EVENT_CATEGORY_HPC = "HPC"
EVENT_CATEGORY_RESOURCE_UTIL = "ResourceUtilization"
EVENT_NAME_HPC_SUBMIT = "hpc_submit"
EVENT_NAME_HPC_JOB_ASSIGNED = "hpc_job_assigned"
EVENT_NAME_HPC_JOB_STATE_CHANGE = "hpc_job_state_change"
EVENT_NAME_CPU_STATS = "cpu_stats"
EVENT_NAME_DISK_STATS = "disk_stats"
EVENT_NAME_MEMORY_STATS = "mem_stats"
EVENT_NAME_NETWORK_STATS = "net_stats"
EVENT_NAME_BYTES_CONSUMED = "bytes_consumed"
EVENT_NAME_UNHANDLED_ERROR = "unhandled_error"
EVENT_NAME_ERROR_LOG = "log_error"
EVENT_NAME_SUBMIT_STARTED = "submit_started"
EVENT_NAME_SUBMIT_COMPLETED = "submit_completed"
EVENT_NAME_CONFIG_EXEC_SUMMARY = "config_exec_summary"
logger = logging.getLogger(__name__)
class StructuredLogEvent:
"""
A class for recording structured log events.
"""
def __init__(self, source, category, name, message, **kwargs):
"""
Initialize the class
Parameters
----------
source: str,
The source of the event.
category: str,
An event category given by the user.
name: str,
An event name given by the user.
message:
An event message given the user.
kwargs:
Other information that the user needs to record into event.
"""
self.source = source
self.category = category
self.name = name
self.message = message
self.event_class = self.__class__.__name__
if "timestamp" in kwargs:
self.timestamp = kwargs.pop("timestamp")
else:
self.timestamp = str(datetime.now())
self.data = kwargs
def base_field_names(self):
"""Return the base field names for the event.
Returns
-------
list
"""
return self._base_field_names()
@staticmethod
def _base_field_names():
return ["timestamp", "source", "message"]
def field_names(self):
"""Return all field names for the event.
Returns
-------
list
"""
return self.base_field_names() + list(self.data.keys())
def values(self):
"""Return the values for all fields in the event.
Returns
-------
list
"""
# Account for events generated with different versions of code.
values = [getattr(self, x, "") for x in self.base_field_names()]
values += [self.data.get(x, "") for x in self.data]
return values
@classmethod
def deserialize(cls, record):
"""Deserialize event from JSON.
Parameters
----------
record : dict
Returns
-------
StructuredLogEvent
"""
return cls(
source=record.get("source", ""),
category=record.get("category", ""),
name=record.get("name", ""),
message=record.get("message", ""),
timestamp=record.get("timestamp", ""),
**record["data"],
)
def __str__(self):
"""To format a event instance to string"""
return json.dumps(self.__dict__, sort_keys=True)
def to_dict(self):
"""Convert event object to dict"""
return self.__dict__
class StructuredErrorLogEvent(StructuredLogEvent):
"""Event specific to exceptions"""
def __init__(self, source, category, name, message, **kwargs):
"""Must be called in an exception context."""
super().__init__(source, category, name, message, **kwargs)
if "exception" not in kwargs:
self._parse_traceback()
def base_field_names(self):
return self._base_field_names()
def _parse_traceback(self):
"""
Parse the system exception information - exception, filename, and lineno.
"""
exc_type, exc_obj, tb = sys.exc_info()
assert tb is not None, "must be called in an exception context"
self.data["exception"] = str(exc_type)
self.data["error"] = str(exc_obj).strip()
self.data["filename"] = os.path.basename(tb.tb_frame.f_code.co_filename)
self.data["lineno"] = tb.tb_lineno
def deserialize_event(data):
"""Construct an event from raw data.
Parameters
----------
data : dict
Returns
-------
StructuredLogEvent
"""
if data["event_class"] == "StructuredLogEvent":
return StructuredLogEvent.deserialize(data)
if data["event_class"] == "StructuredErrorLogEvent":
return StructuredErrorLogEvent.deserialize(data)
raise Exception(f"unknown event class {data["event_class"]}")
class EventsSummary:
"""Provides summary of all events."""
def __init__(self, output_dir, preload=False):
"""
Initialize EventsSummary class
Parameters
----------
output_dir: str
Path of jade output directory.
preload: bool
Load all events into memory; otherwise, load by name on demand.
"""
self._events = defaultdict(list)
self._output_dir = output_dir
self._event_dir = os.path.join(output_dir, EVENT_DIR)
os.makedirs(self._event_dir, exist_ok=True)
self._job_outputs_dir = os.path.join(output_dir, JOBS_OUTPUT_DIR)
event_files = os.listdir(self._event_dir)
if not event_files:
# The old "consolidate_events" code stored all events in one file
# called events.json. They are now stored in one file per event
# type, but we still detect and convert the old format. We can
# remove this once we're sure the old format doesn't exist.
legacy_file = os.path.join(output_dir, EVENTS_FILENAME)
if os.path.exists(legacy_file):
self._handle_legacy_file(legacy_file)
else:
self._consolidate_events()
self._save_events_summary()
elif preload:
self._load_all_events()
# else, events have already been consolidated, load them on demand
def _most_recent_event_files(self):
"""
Find most recent event log files in job outputs directory.
Examples
--------
a/events.log
a/events.log.1
a/events.log.2
b/events.log
b/events.log.1
b/events.log.2
...
event_files = [a/events.log, b/events.log]
Returns
-------
list, a list of event log files.
"""
regex = re.compile(r"\w*events.log")
return [
os.path.join(self._output_dir, x)
for x in os.listdir(self._output_dir)
if regex.search(x)
]
def _consolidate_events(self):
"""Find most recent event log files, and merge event data together."""
for event_file in self._most_recent_event_files():
with open(event_file, "r") as f:
for line in f.readlines():
record = json.loads(line)
event = deserialize_event(record)
self._events[event.name].append(event)
for name in self._events.keys():
self._events[name].sort(key=lambda x: x.timestamp)
def _deserialize_events(self, name, path):
self._events[name] = [deserialize_event(x) for x in load_data(path)]
def _get_events(self, name):
if name not in self._events:
self._load_event_file(name)
return self._events.get(name, [])
def _handle_legacy_file(self, legacy_file):
with open(legacy_file) as f_in:
for line in f_in:
event = deserialize_event(json.loads(line.strip()))
self._events[event.name].append(event)
self._save_events_summary()
os.remove(legacy_file)
logger.info("Converted events to new format")
def _load_all_events(self):
for filename in os.listdir(self._event_dir):
name = os.path.splitext(filename)[0]
if name in self._events:
continue
path = os.path.join(self._event_dir, filename)
self._deserialize_events(name, path)
def _load_event_file(self, name):
filename = self._make_event_filename(name)
if os.path.exists(filename):
self._deserialize_events(name, filename)
def _make_event_filename(self, name):
return os.path.join(self._event_dir, name) + ".json"
def _save_events_summary(self):
"""Save events to one file per event name."""
for name, events in self._events.items():
dict_events = [event.to_dict() for event in events]
dump_data(dict_events, self._make_event_filename(name))
def get_bytes_consumed(self):
"""Return a sum of all bytes_consumed events.
Returns
-------
int
Size in bytes of files produced by all jobs
"""
total = 0
for event in self.iter_events(EVENT_NAME_BYTES_CONSUMED):
total += event.data["bytes_consumed"]
return total
def get_config_exec_time(self):
"""Return the total number of seconds to run all jobs in the config.
Returns
-------
int
"""
events = self.list_events(EVENT_NAME_CONFIG_EXEC_SUMMARY)
if not events:
raise InvalidConfiguration("no batch summary events found")
return events[0].data["config_execution_time"]
def iter_events(self, name):
"""Return a generator over events with name.
Parameters
----------
name : str
Yields
------
event : StructuredLogEvent
"""
for event in self._get_events(name):
yield event
def list_events(self, name):
"""Return the events of type name.
Returns
-------
list
list of StructuredLogEvent
"""
return self._get_events(name)
def list_unique_categories(self):
"""Return the unique event categories in the log. Will cause all events
to get loaded into memory.
Returns
-------
list
"""
self._load_all_events()
categories = set()
for events in self._events.values():
if not events:
continue
categories.add(events[0].category)
categories = list(categories)
categories.sort()
return categories
def list_unique_names(self):
"""Return the unique event names in the log.
Returns
-------
list
"""
return [os.path.splitext(x)[0] for x in os.listdir(self._event_dir)]
def show_events(self, name):
"""Print tabular events in terminal"""
table = PrettyTable()
field_names = None
count = 0
for event in self.iter_events(name):
if field_names is None:
field_names = event.field_names()
table.add_row(event.values())
count += 1
if count == 0:
print(f"No events of type {name}")
return
table.field_names = field_names
print(f"Events of type {name} from directory: {self._output_dir}")
print(table)
print(f"Total events: {count}\n")
def show_events_in_category(self, category):
"""Print tabular events matching category in terminal. Will cause all
events to get loaded into memory.
"""
event_names = []
self._load_all_events()
for name, events in self._events.items():
if not events:
continue
if events[0].category == category:
event_names.append(name)
if not event_names:
print(f"There are no events in category {category}")
return
for event_name in sorted(event_names):
self.show_events(event_name)
def show_event_categories(self):
"""Show the unique event categories in the log."""
print("Catgories: {}".format(" ".join(self.list_unique_categories())))
def show_event_names(self):
"""Show the unique event names in the log."""
print("Names: {}".format(" ".join(self.list_unique_names())))
def to_json(self):
"""Return all events in JSON format.
Returns
-------
str
"""
self._load_all_events()
return json.dumps(
[x.to_dict() for events in self._events.values() for x in events], indent=2
)
| """
This module contains StructuredLogEvent and EventSummary classes.
"""
from collections import defaultdict
import json
import logging
import os
import re
import sys
from datetime import datetime
from prettytable import PrettyTable
from jade.common import JOBS_OUTPUT_DIR
from jade.exceptions import InvalidConfiguration
from jade.utils.utils import dump_data, load_data
EVENT_DIR = "events"
EVENTS_FILENAME = "events.json"
EVENT_CATEGORY_ERROR = "Error"
EVENT_CATEGORY_HPC = "HPC"
EVENT_CATEGORY_RESOURCE_UTIL = "ResourceUtilization"
EVENT_NAME_HPC_SUBMIT = "hpc_submit"
EVENT_NAME_HPC_JOB_ASSIGNED = "hpc_job_assigned"
EVENT_NAME_HPC_JOB_STATE_CHANGE = "hpc_job_state_change"
EVENT_NAME_CPU_STATS = "cpu_stats"
EVENT_NAME_DISK_STATS = "disk_stats"
EVENT_NAME_MEMORY_STATS = "mem_stats"
EVENT_NAME_NETWORK_STATS = "net_stats"
EVENT_NAME_BYTES_CONSUMED = "bytes_consumed"
EVENT_NAME_UNHANDLED_ERROR = "unhandled_error"
EVENT_NAME_ERROR_LOG = "log_error"
EVENT_NAME_SUBMIT_STARTED = "submit_started"
EVENT_NAME_SUBMIT_COMPLETED = "submit_completed"
EVENT_NAME_CONFIG_EXEC_SUMMARY = "config_exec_summary"
logger = logging.getLogger(__name__)
class StructuredLogEvent:
"""
A class for recording structured log events.
"""
def __init__(self, source, category, name, message, **kwargs):
"""
Initialize the class
Parameters
----------
source: str,
The source of the event.
category: str,
An event category given by the user.
name: str,
An event name given by the user.
message:
An event message given the user.
kwargs:
Other information that the user needs to record into event.
"""
self.source = source
self.category = category
self.name = name
self.message = message
self.event_class = self.__class__.__name__
if "timestamp" in kwargs:
self.timestamp = kwargs.pop("timestamp")
else:
self.timestamp = str(datetime.now())
self.data = kwargs
def base_field_names(self):
"""Return the base field names for the event.
Returns
-------
list
"""
return self._base_field_names()
@staticmethod
def _base_field_names():
return ["timestamp", "source", "message"]
def field_names(self):
"""Return all field names for the event.
Returns
-------
list
"""
return self.base_field_names() + list(self.data.keys())
def values(self):
"""Return the values for all fields in the event.
Returns
-------
list
"""
# Account for events generated with different versions of code.
values = [getattr(self, x, "") for x in self.base_field_names()]
values += [self.data.get(x, "") for x in self.data]
return values
@classmethod
def deserialize(cls, record):
"""Deserialize event from JSON.
Parameters
----------
record : dict
Returns
-------
StructuredLogEvent
"""
return cls(
source=record.get("source", ""),
category=record.get("category", ""),
name=record.get("name", ""),
message=record.get("message", ""),
timestamp=record.get("timestamp", ""),
**record["data"],
)
def __str__(self):
"""To format a event instance to string"""
return json.dumps(self.__dict__, sort_keys=True)
def to_dict(self):
"""Convert event object to dict"""
return self.__dict__
class StructuredErrorLogEvent(StructuredLogEvent):
"""Event specific to exceptions"""
def __init__(self, source, category, name, message, **kwargs):
"""Must be called in an exception context."""
super().__init__(source, category, name, message, **kwargs)
if "exception" not in kwargs:
self._parse_traceback()
def base_field_names(self):
return self._base_field_names()
def _parse_traceback(self):
"""
Parse the system exception information - exception, filename, and lineno.
"""
exc_type, exc_obj, tb = sys.exc_info()
assert tb is not None, "must be called in an exception context"
self.data["exception"] = str(exc_type)
self.data["error"] = str(exc_obj).strip()
self.data["filename"] = os.path.basename(tb.tb_frame.f_code.co_filename)
self.data["lineno"] = tb.tb_lineno
def deserialize_event(data):
"""Construct an event from raw data.
Parameters
----------
data : dict
Returns
-------
StructuredLogEvent
"""
if data["event_class"] == "StructuredLogEvent":
return StructuredLogEvent.deserialize(data)
if data["event_class"] == "StructuredErrorLogEvent":
return StructuredErrorLogEvent.deserialize(data)
raise Exception(f"unknown event class {data['event_class']}")
class EventsSummary:
"""Provides summary of all events."""
def __init__(self, output_dir, preload=False):
"""
Initialize EventsSummary class
Parameters
----------
output_dir: str
Path of jade output directory.
preload: bool
Load all events into memory; otherwise, load by name on demand.
"""
self._events = defaultdict(list)
self._output_dir = output_dir
self._event_dir = os.path.join(output_dir, EVENT_DIR)
os.makedirs(self._event_dir, exist_ok=True)
self._job_outputs_dir = os.path.join(output_dir, JOBS_OUTPUT_DIR)
event_files = os.listdir(self._event_dir)
if not event_files:
# The old "consolidate_events" code stored all events in one file
# called events.json. They are now stored in one file per event
# type, but we still detect and convert the old format. We can
# remove this once we're sure the old format doesn't exist.
legacy_file = os.path.join(output_dir, EVENTS_FILENAME)
if os.path.exists(legacy_file):
self._handle_legacy_file(legacy_file)
else:
self._consolidate_events()
self._save_events_summary()
elif preload:
self._load_all_events()
# else, events have already been consolidated, load them on demand
def _most_recent_event_files(self):
"""
Find most recent event log files in job outputs directory.
Examples
--------
a/events.log
a/events.log.1
a/events.log.2
b/events.log
b/events.log.1
b/events.log.2
...
event_files = [a/events.log, b/events.log]
Returns
-------
list, a list of event log files.
"""
regex = re.compile(r"\w*events.log")
return [
os.path.join(self._output_dir, x)
for x in os.listdir(self._output_dir)
if regex.search(x)
]
def _consolidate_events(self):
"""Find most recent event log files, and merge event data together."""
for event_file in self._most_recent_event_files():
with open(event_file, "r") as f:
for line in f.readlines():
record = json.loads(line)
event = deserialize_event(record)
self._events[event.name].append(event)
for name in self._events.keys():
self._events[name].sort(key=lambda x: x.timestamp)
def _deserialize_events(self, name, path):
self._events[name] = [deserialize_event(x) for x in load_data(path)]
def _get_events(self, name):
if name not in self._events:
self._load_event_file(name)
return self._events.get(name, [])
def _handle_legacy_file(self, legacy_file):
with open(legacy_file) as f_in:
for line in f_in:
event = deserialize_event(json.loads(line.strip()))
self._events[event.name].append(event)
self._save_events_summary()
os.remove(legacy_file)
logger.info("Converted events to new format")
def _load_all_events(self):
for filename in os.listdir(self._event_dir):
name = os.path.splitext(filename)[0]
if name in self._events:
continue
path = os.path.join(self._event_dir, filename)
self._deserialize_events(name, path)
def _load_event_file(self, name):
filename = self._make_event_filename(name)
if os.path.exists(filename):
self._deserialize_events(name, filename)
def _make_event_filename(self, name):
return os.path.join(self._event_dir, name) + ".json"
def _save_events_summary(self):
"""Save events to one file per event name."""
for name, events in self._events.items():
dict_events = [event.to_dict() for event in events]
dump_data(dict_events, self._make_event_filename(name))
def get_bytes_consumed(self):
"""Return a sum of all bytes_consumed events.
Returns
-------
int
Size in bytes of files produced by all jobs
"""
total = 0
for event in self.iter_events(EVENT_NAME_BYTES_CONSUMED):
total += event.data["bytes_consumed"]
return total
def get_config_exec_time(self):
"""Return the total number of seconds to run all jobs in the config.
Returns
-------
int
"""
events = self.list_events(EVENT_NAME_CONFIG_EXEC_SUMMARY)
if not events:
raise InvalidConfiguration("no batch summary events found")
return events[0].data["config_execution_time"]
def iter_events(self, name):
"""Return a generator over events with name.
Parameters
----------
name : str
Yields
------
event : StructuredLogEvent
"""
for event in self._get_events(name):
yield event
def list_events(self, name):
"""Return the events of type name.
Returns
-------
list
list of StructuredLogEvent
"""
return self._get_events(name)
def list_unique_categories(self):
"""Return the unique event categories in the log. Will cause all events
to get loaded into memory.
Returns
-------
list
"""
self._load_all_events()
categories = set()
for events in self._events.values():
if not events:
continue
categories.add(events[0].category)
categories = list(categories)
categories.sort()
return categories
def list_unique_names(self):
"""Return the unique event names in the log.
Returns
-------
list
"""
return [os.path.splitext(x)[0] for x in os.listdir(self._event_dir)]
def show_events(self, name):
"""Print tabular events in terminal"""
table = PrettyTable()
field_names = None
count = 0
for event in self.iter_events(name):
if field_names is None:
field_names = event.field_names()
table.add_row(event.values())
count += 1
if count == 0:
print(f"No events of type {name}")
return
table.field_names = field_names
print(f"Events of type {name} from directory: {self._output_dir}")
print(table)
print(f"Total events: {count}\n")
def show_events_in_category(self, category):
"""Print tabular events matching category in terminal. Will cause all
events to get loaded into memory.
"""
event_names = []
self._load_all_events()
for name, events in self._events.items():
if not events:
continue
if events[0].category == category:
event_names.append(name)
if not event_names:
print(f"There are no events in category {category}")
return
for event_name in sorted(event_names):
self.show_events(event_name)
def show_event_categories(self):
"""Show the unique event categories in the log."""
print("Catgories: {}".format(" ".join(self.list_unique_categories())))
def show_event_names(self):
"""Show the unique event names in the log."""
print("Names: {}".format(" ".join(self.list_unique_names())))
def to_json(self):
"""Return all events in JSON format.
Returns
-------
str
"""
self._load_all_events()
return json.dumps(
[x.to_dict() for events in self._events.values() for x in events], indent=2
)
|
from bot.decorators import error_handler
from bot.Cats_more_pages import MorePagesCats
import requests
URL_DOGS = 'https://izpriuta.ru/sobaki'
class MorePagesDogs: # The class for pages-parsing dogs
def __init__(self, url):
self.url = url
@error_handler
def parse_dogs(self):
html = requests.get(self.url)
if html.status_code == 200:
all_pages = []
pages = MorePagesCats(URL_DOGS).pages_count(html.text)
int_pages = int(pages)
for page in range(1, int_pages):
html = requests.get(self.url, params={'page': page})
all_pages.extend([i for i in MorePagesCats(URL_DOGS).get_content_to_user(html.text)])
yield all_pages
@error_handler
def img_parse_from_pages_dogs(self):
html = requests.get(self.url)
if html.status_code == 200:
all_pages = []
pages = MorePagesCats(URL_DOGS).pages_count(html.text)
int_pages = int(pages)
for page in range(1, int_pages):
html = requests.get(self.url, params={'page': page})
all_pages.extend([i for i in self.photo_writer(html.text)])
yield all_pages
@error_handler
def photo_writer(self, html):
for img in list(MorePagesCats(URL_DOGS).img_parse_cats_pages(html))[0]:
with open(f"img_pages_dogs/{img["name"] + ".jpg"}",
'wb') as file:
for bit in requests.get(img['photo'], verify=False).iter_content():
file.write(bit)
yield file.name
| from bot.decorators import error_handler
from bot.Cats_more_pages import MorePagesCats
import requests
URL_DOGS = 'https://izpriuta.ru/sobaki'
class MorePagesDogs: # The class for pages-parsing dogs
def __init__(self, url):
self.url = url
@error_handler
def parse_dogs(self):
html = requests.get(self.url)
if html.status_code == 200:
all_pages = []
pages = MorePagesCats(URL_DOGS).pages_count(html.text)
int_pages = int(pages)
for page in range(1, int_pages):
html = requests.get(self.url, params={'page': page})
all_pages.extend([i for i in MorePagesCats(URL_DOGS).get_content_to_user(html.text)])
yield all_pages
@error_handler
def img_parse_from_pages_dogs(self):
html = requests.get(self.url)
if html.status_code == 200:
all_pages = []
pages = MorePagesCats(URL_DOGS).pages_count(html.text)
int_pages = int(pages)
for page in range(1, int_pages):
html = requests.get(self.url, params={'page': page})
all_pages.extend([i for i in self.photo_writer(html.text)])
yield all_pages
@error_handler
def photo_writer(self, html):
for img in list(MorePagesCats(URL_DOGS).img_parse_cats_pages(html))[0]:
with open(f"img_pages_dogs/{img['name'] + '.jpg'}",
'wb') as file:
for bit in requests.get(img['photo'], verify=False).iter_content():
file.write(bit)
yield file.name
|
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #
# Utilities. The full HSDS copyright notice, including #
# terms governing use, modification, and redistribution, is contained in #
# the file COPYING, which can be found at the root of the source code #
# distribution tree. If you do not have access to this file, you may #
# request a copy from help@hdfgroup.org. #
##############################################################################
import time
import hashlib
import numpy as np
from aiohttp.client_exceptions import ClientError
from aiohttp.web_exceptions import HTTPNotFound, HTTPInternalServerError, HTTPForbidden
from .util.idUtil import isValidUuid, isSchema2Id, getS3Key, isS3ObjKey, getObjId, isValidChunkId, getCollectionForId
from .util.chunkUtil import getDatasetId, getNumChunks, ChunkIterator
from .util.hdf5dtype import getItemSize, createDataType
from .util.arrayUtil import getShapeDims, getNumElements, bytesToArray
from .util.dsetUtil import getHyperslabSelection, getFilterOps
from .util.storUtil import getStorKeys, putStorJSONObj, getStorJSONObj, deleteStorObj, getStorBytes, isStorObj
from . import hsds_logger as log
from . import config
# List all keys under given root and optionally update info.json
# Note: only works with schema v2 domains!
async def getDatasetJson(app, dsetid, bucket=None):
# try to read the dataset json from s3
s3_key = getS3Key(dsetid)
try:
dset_json = await getStorJSONObj(app, s3_key, bucket=bucket)
except HTTPNotFound:
log.warn(f"HTTPNotFound for {s3_key} bucket:{bucket}")
return None
except HTTPForbidden:
log.warn(f"HTTPForbidden error for {s3_key} bucket:{bucket}")
return None
except HTTPInternalServerError:
log.warn(f"HTTPInternalServerError error for {s3_key} bucket:{bucket}")
return None
return dset_json
async def updateDatasetInfo(app, dset_id, dataset_info, bucket=None):
# get dataset metadata and deteermine number logical)_bytes, linked_bytes, and num_linked_chunks
dset_json = await getDatasetJson(app, dset_id, bucket=bucket)
log.debug(f"updateDatasetInfo - id: {dset_id} dataset_info: {dataset_info}")
if "shape" not in dset_json:
log.debug(f"updateDatasetInfo - no shape dataset_json for {dset_id} - skipping")
return # null dataspace
shape_json = dset_json["shape"]
if "class" in shape_json and shape_json["class"] == 'H5S_NULL':
log.debug(f"updatedDatasetInfo - null space for {dset_id} - skipping")
return
if "type" not in dset_json:
log.warn(f"updateDatasetInfo - expected to find type in dataset_json for {dset_id}")
return
type_json = dset_json["type"]
item_size = getItemSize(type_json)
if "layout" not in dset_json:
log.warn(f"updateDatasetInfo - expected to find layout in dataset_json for {dset_id}")
return
layout = dset_json["layout"]
log.info(f"updateDatasetInfo - shape: {shape_json} type: {type_json} item size: {item_size} layout: {layout}")
dims = getShapeDims(shape_json) # returns None for HS_NULL dsets
if dims is None:
return # null dataspace
if item_size == 'H5T_VARIABLE':
# arbitrary lgoical size for vaariable, so just set to allocated size
logical_bytes = dataset_info['allocated_bytes']
else:
num_elements = getNumElements(dims)
logical_bytes = num_elements * item_size
dataset_info["logical_bytes"] = logical_bytes
log.debug(f"dims: {dims}")
rank = len(dims)
layout_class = layout["class"]
log.debug(f"updateDatasetInfo - {dset_id} has layout_class: {layout_class}")
selection = getHyperslabSelection(dims) # select entire datashape
linked_bytes = 0
num_linked_chunks = 0
if layout_class == 'H5D_CONTIGUOUS_REF':
# In H5D_CONTIGUOUS_REF a non-compressed part of the HDF5 is divided into equal size chunks,
# so we can just compute link bytes and num chunks based on the size of the coniguous dataset
layout_dims = layout["dims"]
num_chunks = getNumChunks(selection, layout_dims)
chunk_size = item_size
for dim in layout_dims:
chunk_size *= dim
log.debug(f"updateDatasetInfo, H5D_CONTIGUOUS_REF, num_chunks: {num_chunks} chunk_size: {chunk_size}")
linked_bytes = chunk_size * num_chunks
num_linked_chunks = num_chunks
elif layout_class == 'H5D_CHUNKED_REF':
chunks = layout["chunks"]
# chunks is a dict with tuples (offset, size)
for chunk_id in chunks:
chunk_info = chunks[chunk_id]
linked_bytes += chunk_info[1]
num_linked_chunks = len(chunks)
elif layout_class == 'H5D_CHUNKED_REF_INDIRECT':
log.debug("chunk ref indirect")
if "chunk_table" not in layout:
log.error(f"Expected to find chunk_table in dataset layout for {dset_id}")
return
chunktable_id = layout["chunk_table"]
# get state for dataset from DN.
chunktable_json = await getDatasetJson(app, chunktable_id, bucket=bucket)
log.debug(f"chunktable_json: {chunktable_json}")
chunktable_dims = getShapeDims(chunktable_json["shape"])
if len(chunktable_dims) != rank:
msg = f"Expected rank of chunktable to be same as the dataset for {dset_id}"
log.warn(msg)
return
chunktable_layout = chunktable_json["layout"]
log.debug(f"chunktable_layout: {chunktable_layout}")
if not isinstance(chunktable_layout, dict) or "class" not in chunktable_layout:
log.warn(f"expected chunktable_layout: {chunktable_id}")
return
if chunktable_layout["class"] != 'H5D_CHUNKED':
log.warn("expected chunktable layout class to be chunked")
return
if "dims" not in chunktable_layout:
log.warn("expected chunktable layout to have dims key")
return
chunktable_layout_dims = chunktable_layout["dims"]
chunktable_type_json = chunktable_json["type"]
chunktable_item_size = getItemSize(chunktable_type_json)
chunktable_dt = createDataType(chunktable_type_json)
chunktable_filter_ops = getFilterOps(app, chunktable_json, chunktable_item_size)
# read chunktable one chunk at a time - this can be slow if there are a lot of chunks,
# but this is only used by the async bucket scan task
chunktable_selection = getHyperslabSelection(chunktable_dims)
it = ChunkIterator(chunktable_id, chunktable_selection, chunktable_layout_dims)
log.debug(f"updateDatasetInfo - iterating over chunks in {chunktable_id}")
while True:
try:
chunktable_chunk_id = it.next()
log.debug(f"updateDatasetInfo - gotchunktable chunk id: {chunktable_chunk_id}")
chunktable_chunk_s3key = getS3Key(chunktable_chunk_id)
# read the chunk
try:
is_stor_obj = await isStorObj(app, chunktable_chunk_s3key, bucket=bucket)
except HTTPInternalServerError as hse:
log.warning(f"updateDatasetInfo - got error checking for key: {chunktable_chunk_s3key}: {hse}")
continue
if not is_stor_obj:
log.debug(f"updateDatasetInfo - no chunk found for chunktable id: {chunktable_chunk_id}")
else:
try:
chunk_bytes = await getStorBytes(app, chunktable_chunk_s3key, filter_ops=chunktable_filter_ops, bucket=bucket)
except HTTPInternalServerError as hse:
log.warning(f"updateDatasetInfo - got error reading chunktable for key: {chunktable_chunk_s3key}: {hse}")
continue
chunk_arr = bytesToArray(chunk_bytes, chunktable_dt, chunktable_layout_dims)
if chunk_arr is None:
log.warn(f"updateDatasetInfo - expected to find chunk found fo: {chunktable_chunk_s3key}")
else:
# convert to 1-d list
try:
nelements = getNumElements(chunk_arr.shape)
chunk_arr = chunk_arr.reshape((nelements,))
for i in range(nelements):
e = chunk_arr[i]
# elements should have 2 (if it is offset and size) or 3 (if it is offset, size, and path)
chunk_size = int(e[1])
if chunk_size > 0:
linked_bytes += chunk_size
num_linked_chunks += 1
except Exception as e:
log.error(f"updateDatasetInfo - got exception parsing chunktable array {chunktable_chunk_id}: {e}")
except StopIteration:
break
log.debug(f"updateDatasetInfo - done with chunktable iteration for {chunktable_id}")
elif layout_class == 'H5D_CHUNKED':
log.debug("updateDatasetInfo - no linked bytes/chunks for H5D_CHUNKED layout")
else:
log.error(f"unexpected chunk layout: {layout_class}")
log.debug(f"updateDatasetInfo - {dset_id} setting linked_bytes to {linked_bytes}, num_linked_chunks to {num_linked_chunks}")
dataset_info["linked_bytes"] = linked_bytes
dataset_info["num_linked_chunks"] = num_linked_chunks
def scanRootCallback(app, s3keys):
log.debug(f"scanRoot - callback, {len(s3keys)} items")
if isinstance(s3keys, list):
log.error("got list result for s3keys callback")
raise ValueError("unexpected callback format")
results = app["scanRoot_results"]
scanRoot_keyset = app["scanRoot_keyset"]
checksums = results["checksums"]
for s3key in s3keys.keys():
if not isS3ObjKey(s3key):
log.info(f"not s3obj key, ignoring: {s3key}")
continue
if s3key in scanRoot_keyset:
log.warn(f"scanRoot - dejavu for key: {s3key}")
continue
scanRoot_keyset.add(s3key)
objid = getObjId(s3key)
etag = None
obj_size = None
lastModified = None
item = s3keys[s3key]
if "ETag" in item:
etag = item["ETag"]
checksums[objid] = etag
if "Size" in item:
obj_size = item["Size"]
if "LastModified" in item:
lastModified = item["LastModified"]
log.debug(f"scanRoot - got key {objid}: {etag} {obj_size} {lastModified}")
if lastModified > results["lastModified"]:
log.debug(f"scanRoot: changing lastModified from: {results["lastModified"]} to {lastModified}")
results["lastModified"] = lastModified
is_chunk = False
if isValidChunkId(objid):
is_chunk = True
results["num_chunks"] += 1
results["allocated_bytes"] += obj_size
else:
results["metadata_bytes"] += obj_size
if is_chunk or getCollectionForId(objid) == "datasets":
if is_chunk:
dsetid = getDatasetId(objid)
else:
dsetid = objid
datasets = results["datasets"]
if dsetid not in datasets:
dataset_info = {}
dataset_info["lastModified"] = 0
dataset_info["num_chunks"] = 0
dataset_info["allocated_bytes"] = 0
dataset_info["logical_bytes"] = 0
dataset_info["linked_bytes"] = 0
dataset_info["num_linked_chunks"] = 0
dataset_info["logical_bytes"] = 0
datasets[dsetid] = dataset_info
dataset_info = datasets[dsetid]
if lastModified > dataset_info["lastModified"]:
dataset_info["lastModified"] = lastModified
if is_chunk:
dataset_info["num_chunks"] += 1
dataset_info["allocated_bytes"] += obj_size
elif getCollectionForId(objid) == "groups":
results["num_groups"] += 1
elif getCollectionForId(objid) == "datatypes":
results["num_datatypes"] += 1
else:
log.error(f"scanRoot - Unexpected collection type for id: {objid}")
async def scanRoot(app, rootid, update=False, bucket=None):
# iterate through all s3 keys under the given root.
# Return dict with stats for the root.
#
# Note: not re-entrant! Only one scanRoot an be run at a time per app.
log.info(f"scanRoot for rootid: {rootid} bucket: {bucket}")
if not isValidUuid(rootid):
raise ValueError("Invalid root id")
if not isSchema2Id(rootid):
log.warn(f"no tabulation for schema v1 id: {rootid} returning null results")
return {}
if not bucket:
bucket = config.get("bucket_name")
if not bucket:
raise ValueError(f"no bucket defined for scan of {rootid}")
root_key = getS3Key(rootid)
if not root_key.endswith("/.group.json"):
raise ValueError("unexpected root key")
root_prefix = root_key[:-(len(".group.json"))]
log.debug(f"scanRoot - using prefix: {root_prefix}")
results = {}
results["lastModified"] = 0
results["num_groups"] = 0
results["num_datatypes"] = 0
results["datasets"] = {} # since we need per dataset info
results["num_chunks"] = 0
results["allocated_bytes"] = 0
results["metadata_bytes"] = 0
results["num_linked_chunks"] = 0
results["linked_bytes"] = 0
results["logical_bytes"] = 0
results["checksums"] = {} # map of objid to checksums
results["bucket"] = bucket
results["scan_start"] = time.time()
app["scanRoot_results"] = results
app["scanRoot_keyset"] = set()
await getStorKeys(app, prefix=root_prefix, include_stats=True, bucket=bucket, callback=scanRootCallback)
num_objects = results["num_groups"] + results["num_datatypes"] + len(results["datasets"]) + results["num_chunks"]
log.info(f"scanRoot - got {num_objects} keys for rootid: {rootid}")
dataset_results = results["datasets"]
for dsetid in dataset_results:
dataset_info = dataset_results[dsetid]
log.info(f"got dataset: {dsetid}: {dataset_info}")
await updateDatasetInfo(app, dsetid, dataset_info, bucket=bucket)
if dataset_info["logical_bytes"] != "variable":
results["logical_bytes"] += dataset_info["logical_bytes"]
results["linked_bytes"] += dataset_info["linked_bytes"]
results["num_linked_chunks"] += dataset_info["num_linked_chunks"]
log.info(f"scanRoot - scan complete for rootid: {rootid}")
# compute overall checksum
checksums = results["checksums"]
if len(checksums) != num_objects:
log.warn(f"skipping domain checksum calculation - {len(checksums)} found but {num_objects} hdf objects")
else:
# create a numpy array to store checksums
log.debug(f"creating numpy checksum array for {num_objects} checksums")
checksum_arr = np.zeros((num_objects,), dtype='S16')
objids = list(checksums.keys())
objids.sort()
for i in range(num_objects):
objid = objids[i]
checksum_arr[i] = checksums[objid]
log.debug("numpy array created")
hash_object = hashlib.md5(checksum_arr.tobytes())
md5_sum = hash_object.hexdigest()
log.debug(f"got domain_checksum: {md5_sum}")
results["md5_sum"] = md5_sum
# free up memory used by the checksums
del results["checksums"]
results["scan_complete"] = time.time()
if update:
# write .info object back to S3
info_key = root_prefix + ".info.json"
log.info(f"scanRoot - updating info key: {info_key} with results: {results}")
await putStorJSONObj(app, info_key, results, bucket=bucket)
return results
async def objDeleteCallback(app, s3keys):
log.info(f"objDeleteCallback, {len(s3keys)} items")
if not isinstance(s3keys, list):
log.error("expected list result for objDeleteCallback")
raise ValueError("unexpected callback format")
if "objDelete_prefix" not in app or not app["objDelete_prefix"]:
log.error("Unexpected objDeleteCallback")
raise ValueError("Invalid objDeleteCallback")
prefix = app["objDelete_prefix"]
prefix_len = len(prefix)
for s3key in s3keys:
if not s3key.startswith(prefix):
log.error(f"Unexpected key {s3key} for prefix: {prefix}")
raise ValueError("invalid s3key for objDeleteCallback")
full_key = prefix + s3key[prefix_len:]
log.info(f"removeKeys - objDeleteCallback deleting key: {full_key}")
await deleteStorObj(app, full_key)
log.info("objDeleteCallback complete")
async def removeKeys(app, objid):
# iterate through all s3 keys under the given root or dataset id and delete them
#
# Note: not re-entrant! Only one removeKeys an be run at a time per app.
log.debug(f"removeKeys: {objid}")
if not isSchema2Id(objid):
log.warn("ignoring non-schema2 id")
raise KeyError("Invalid key")
s3key = getS3Key(objid)
log.debug(f"removeKeys - got s3key: {s3key}")
expected_suffixes = (".dataset.json", ".group.json")
s3prefix = None
for suffix in expected_suffixes:
if s3key.endswith(suffix):
s3prefix = s3key[:-len(suffix)]
if not s3prefix:
log.error("removeKeys - unexpected s3key for delete_set")
raise KeyError("unexpected key suffix")
log.info(f"removeKeys - delete for {objid} searching for s3prefix: {s3prefix}")
if app["objDelete_prefix"]:
log.error("removeKeys - objDelete_prefix is already set - improper use of non-reentrant call?")
# just continue and reset
app["objDelete_prefix"] = s3prefix
try:
await getStorKeys(app, prefix=s3prefix, include_stats=False, callback=objDeleteCallback)
except ClientError as ce:
log.error(f"removeKeys - getS3Keys faiiled: {ce}")
except HTTPNotFound:
log.warn(f"removeKeys - HTTPNotFound error for getStorKeys with prefix: {s3prefix}")
except HTTPInternalServerError:
log.error(f"removeKeys - HTTPInternalServerError for getStorKeys with prefix: {s3prefix}")
except Exception as e:
log.error(f"removeKeys - Unexpected Exception for getStorKeys with prefix: {s3prefix}: {e}")
# reset the prefix
app["objDelete_prefix"] = None
| ##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #
# Utilities. The full HSDS copyright notice, including #
# terms governing use, modification, and redistribution, is contained in #
# the file COPYING, which can be found at the root of the source code #
# distribution tree. If you do not have access to this file, you may #
# request a copy from help@hdfgroup.org. #
##############################################################################
import time
import hashlib
import numpy as np
from aiohttp.client_exceptions import ClientError
from aiohttp.web_exceptions import HTTPNotFound, HTTPInternalServerError, HTTPForbidden
from .util.idUtil import isValidUuid, isSchema2Id, getS3Key, isS3ObjKey, getObjId, isValidChunkId, getCollectionForId
from .util.chunkUtil import getDatasetId, getNumChunks, ChunkIterator
from .util.hdf5dtype import getItemSize, createDataType
from .util.arrayUtil import getShapeDims, getNumElements, bytesToArray
from .util.dsetUtil import getHyperslabSelection, getFilterOps
from .util.storUtil import getStorKeys, putStorJSONObj, getStorJSONObj, deleteStorObj, getStorBytes, isStorObj
from . import hsds_logger as log
from . import config
# List all keys under given root and optionally update info.json
# Note: only works with schema v2 domains!
async def getDatasetJson(app, dsetid, bucket=None):
# try to read the dataset json from s3
s3_key = getS3Key(dsetid)
try:
dset_json = await getStorJSONObj(app, s3_key, bucket=bucket)
except HTTPNotFound:
log.warn(f"HTTPNotFound for {s3_key} bucket:{bucket}")
return None
except HTTPForbidden:
log.warn(f"HTTPForbidden error for {s3_key} bucket:{bucket}")
return None
except HTTPInternalServerError:
log.warn(f"HTTPInternalServerError error for {s3_key} bucket:{bucket}")
return None
return dset_json
async def updateDatasetInfo(app, dset_id, dataset_info, bucket=None):
# get dataset metadata and deteermine number logical)_bytes, linked_bytes, and num_linked_chunks
dset_json = await getDatasetJson(app, dset_id, bucket=bucket)
log.debug(f"updateDatasetInfo - id: {dset_id} dataset_info: {dataset_info}")
if "shape" not in dset_json:
log.debug(f"updateDatasetInfo - no shape dataset_json for {dset_id} - skipping")
return # null dataspace
shape_json = dset_json["shape"]
if "class" in shape_json and shape_json["class"] == 'H5S_NULL':
log.debug(f"updatedDatasetInfo - null space for {dset_id} - skipping")
return
if "type" not in dset_json:
log.warn(f"updateDatasetInfo - expected to find type in dataset_json for {dset_id}")
return
type_json = dset_json["type"]
item_size = getItemSize(type_json)
if "layout" not in dset_json:
log.warn(f"updateDatasetInfo - expected to find layout in dataset_json for {dset_id}")
return
layout = dset_json["layout"]
log.info(f"updateDatasetInfo - shape: {shape_json} type: {type_json} item size: {item_size} layout: {layout}")
dims = getShapeDims(shape_json) # returns None for HS_NULL dsets
if dims is None:
return # null dataspace
if item_size == 'H5T_VARIABLE':
# arbitrary lgoical size for vaariable, so just set to allocated size
logical_bytes = dataset_info['allocated_bytes']
else:
num_elements = getNumElements(dims)
logical_bytes = num_elements * item_size
dataset_info["logical_bytes"] = logical_bytes
log.debug(f"dims: {dims}")
rank = len(dims)
layout_class = layout["class"]
log.debug(f"updateDatasetInfo - {dset_id} has layout_class: {layout_class}")
selection = getHyperslabSelection(dims) # select entire datashape
linked_bytes = 0
num_linked_chunks = 0
if layout_class == 'H5D_CONTIGUOUS_REF':
# In H5D_CONTIGUOUS_REF a non-compressed part of the HDF5 is divided into equal size chunks,
# so we can just compute link bytes and num chunks based on the size of the coniguous dataset
layout_dims = layout["dims"]
num_chunks = getNumChunks(selection, layout_dims)
chunk_size = item_size
for dim in layout_dims:
chunk_size *= dim
log.debug(f"updateDatasetInfo, H5D_CONTIGUOUS_REF, num_chunks: {num_chunks} chunk_size: {chunk_size}")
linked_bytes = chunk_size * num_chunks
num_linked_chunks = num_chunks
elif layout_class == 'H5D_CHUNKED_REF':
chunks = layout["chunks"]
# chunks is a dict with tuples (offset, size)
for chunk_id in chunks:
chunk_info = chunks[chunk_id]
linked_bytes += chunk_info[1]
num_linked_chunks = len(chunks)
elif layout_class == 'H5D_CHUNKED_REF_INDIRECT':
log.debug("chunk ref indirect")
if "chunk_table" not in layout:
log.error(f"Expected to find chunk_table in dataset layout for {dset_id}")
return
chunktable_id = layout["chunk_table"]
# get state for dataset from DN.
chunktable_json = await getDatasetJson(app, chunktable_id, bucket=bucket)
log.debug(f"chunktable_json: {chunktable_json}")
chunktable_dims = getShapeDims(chunktable_json["shape"])
if len(chunktable_dims) != rank:
msg = f"Expected rank of chunktable to be same as the dataset for {dset_id}"
log.warn(msg)
return
chunktable_layout = chunktable_json["layout"]
log.debug(f"chunktable_layout: {chunktable_layout}")
if not isinstance(chunktable_layout, dict) or "class" not in chunktable_layout:
log.warn(f"expected chunktable_layout: {chunktable_id}")
return
if chunktable_layout["class"] != 'H5D_CHUNKED':
log.warn("expected chunktable layout class to be chunked")
return
if "dims" not in chunktable_layout:
log.warn("expected chunktable layout to have dims key")
return
chunktable_layout_dims = chunktable_layout["dims"]
chunktable_type_json = chunktable_json["type"]
chunktable_item_size = getItemSize(chunktable_type_json)
chunktable_dt = createDataType(chunktable_type_json)
chunktable_filter_ops = getFilterOps(app, chunktable_json, chunktable_item_size)
# read chunktable one chunk at a time - this can be slow if there are a lot of chunks,
# but this is only used by the async bucket scan task
chunktable_selection = getHyperslabSelection(chunktable_dims)
it = ChunkIterator(chunktable_id, chunktable_selection, chunktable_layout_dims)
log.debug(f"updateDatasetInfo - iterating over chunks in {chunktable_id}")
while True:
try:
chunktable_chunk_id = it.next()
log.debug(f"updateDatasetInfo - gotchunktable chunk id: {chunktable_chunk_id}")
chunktable_chunk_s3key = getS3Key(chunktable_chunk_id)
# read the chunk
try:
is_stor_obj = await isStorObj(app, chunktable_chunk_s3key, bucket=bucket)
except HTTPInternalServerError as hse:
log.warning(f"updateDatasetInfo - got error checking for key: {chunktable_chunk_s3key}: {hse}")
continue
if not is_stor_obj:
log.debug(f"updateDatasetInfo - no chunk found for chunktable id: {chunktable_chunk_id}")
else:
try:
chunk_bytes = await getStorBytes(app, chunktable_chunk_s3key, filter_ops=chunktable_filter_ops, bucket=bucket)
except HTTPInternalServerError as hse:
log.warning(f"updateDatasetInfo - got error reading chunktable for key: {chunktable_chunk_s3key}: {hse}")
continue
chunk_arr = bytesToArray(chunk_bytes, chunktable_dt, chunktable_layout_dims)
if chunk_arr is None:
log.warn(f"updateDatasetInfo - expected to find chunk found fo: {chunktable_chunk_s3key}")
else:
# convert to 1-d list
try:
nelements = getNumElements(chunk_arr.shape)
chunk_arr = chunk_arr.reshape((nelements,))
for i in range(nelements):
e = chunk_arr[i]
# elements should have 2 (if it is offset and size) or 3 (if it is offset, size, and path)
chunk_size = int(e[1])
if chunk_size > 0:
linked_bytes += chunk_size
num_linked_chunks += 1
except Exception as e:
log.error(f"updateDatasetInfo - got exception parsing chunktable array {chunktable_chunk_id}: {e}")
except StopIteration:
break
log.debug(f"updateDatasetInfo - done with chunktable iteration for {chunktable_id}")
elif layout_class == 'H5D_CHUNKED':
log.debug("updateDatasetInfo - no linked bytes/chunks for H5D_CHUNKED layout")
else:
log.error(f"unexpected chunk layout: {layout_class}")
log.debug(f"updateDatasetInfo - {dset_id} setting linked_bytes to {linked_bytes}, num_linked_chunks to {num_linked_chunks}")
dataset_info["linked_bytes"] = linked_bytes
dataset_info["num_linked_chunks"] = num_linked_chunks
def scanRootCallback(app, s3keys):
log.debug(f"scanRoot - callback, {len(s3keys)} items")
if isinstance(s3keys, list):
log.error("got list result for s3keys callback")
raise ValueError("unexpected callback format")
results = app["scanRoot_results"]
scanRoot_keyset = app["scanRoot_keyset"]
checksums = results["checksums"]
for s3key in s3keys.keys():
if not isS3ObjKey(s3key):
log.info(f"not s3obj key, ignoring: {s3key}")
continue
if s3key in scanRoot_keyset:
log.warn(f"scanRoot - dejavu for key: {s3key}")
continue
scanRoot_keyset.add(s3key)
objid = getObjId(s3key)
etag = None
obj_size = None
lastModified = None
item = s3keys[s3key]
if "ETag" in item:
etag = item["ETag"]
checksums[objid] = etag
if "Size" in item:
obj_size = item["Size"]
if "LastModified" in item:
lastModified = item["LastModified"]
log.debug(f"scanRoot - got key {objid}: {etag} {obj_size} {lastModified}")
if lastModified > results["lastModified"]:
log.debug(f"scanRoot: changing lastModified from: {results['lastModified']} to {lastModified}")
results["lastModified"] = lastModified
is_chunk = False
if isValidChunkId(objid):
is_chunk = True
results["num_chunks"] += 1
results["allocated_bytes"] += obj_size
else:
results["metadata_bytes"] += obj_size
if is_chunk or getCollectionForId(objid) == "datasets":
if is_chunk:
dsetid = getDatasetId(objid)
else:
dsetid = objid
datasets = results["datasets"]
if dsetid not in datasets:
dataset_info = {}
dataset_info["lastModified"] = 0
dataset_info["num_chunks"] = 0
dataset_info["allocated_bytes"] = 0
dataset_info["logical_bytes"] = 0
dataset_info["linked_bytes"] = 0
dataset_info["num_linked_chunks"] = 0
dataset_info["logical_bytes"] = 0
datasets[dsetid] = dataset_info
dataset_info = datasets[dsetid]
if lastModified > dataset_info["lastModified"]:
dataset_info["lastModified"] = lastModified
if is_chunk:
dataset_info["num_chunks"] += 1
dataset_info["allocated_bytes"] += obj_size
elif getCollectionForId(objid) == "groups":
results["num_groups"] += 1
elif getCollectionForId(objid) == "datatypes":
results["num_datatypes"] += 1
else:
log.error(f"scanRoot - Unexpected collection type for id: {objid}")
async def scanRoot(app, rootid, update=False, bucket=None):
# iterate through all s3 keys under the given root.
# Return dict with stats for the root.
#
# Note: not re-entrant! Only one scanRoot an be run at a time per app.
log.info(f"scanRoot for rootid: {rootid} bucket: {bucket}")
if not isValidUuid(rootid):
raise ValueError("Invalid root id")
if not isSchema2Id(rootid):
log.warn(f"no tabulation for schema v1 id: {rootid} returning null results")
return {}
if not bucket:
bucket = config.get("bucket_name")
if not bucket:
raise ValueError(f"no bucket defined for scan of {rootid}")
root_key = getS3Key(rootid)
if not root_key.endswith("/.group.json"):
raise ValueError("unexpected root key")
root_prefix = root_key[:-(len(".group.json"))]
log.debug(f"scanRoot - using prefix: {root_prefix}")
results = {}
results["lastModified"] = 0
results["num_groups"] = 0
results["num_datatypes"] = 0
results["datasets"] = {} # since we need per dataset info
results["num_chunks"] = 0
results["allocated_bytes"] = 0
results["metadata_bytes"] = 0
results["num_linked_chunks"] = 0
results["linked_bytes"] = 0
results["logical_bytes"] = 0
results["checksums"] = {} # map of objid to checksums
results["bucket"] = bucket
results["scan_start"] = time.time()
app["scanRoot_results"] = results
app["scanRoot_keyset"] = set()
await getStorKeys(app, prefix=root_prefix, include_stats=True, bucket=bucket, callback=scanRootCallback)
num_objects = results["num_groups"] + results["num_datatypes"] + len(results["datasets"]) + results["num_chunks"]
log.info(f"scanRoot - got {num_objects} keys for rootid: {rootid}")
dataset_results = results["datasets"]
for dsetid in dataset_results:
dataset_info = dataset_results[dsetid]
log.info(f"got dataset: {dsetid}: {dataset_info}")
await updateDatasetInfo(app, dsetid, dataset_info, bucket=bucket)
if dataset_info["logical_bytes"] != "variable":
results["logical_bytes"] += dataset_info["logical_bytes"]
results["linked_bytes"] += dataset_info["linked_bytes"]
results["num_linked_chunks"] += dataset_info["num_linked_chunks"]
log.info(f"scanRoot - scan complete for rootid: {rootid}")
# compute overall checksum
checksums = results["checksums"]
if len(checksums) != num_objects:
log.warn(f"skipping domain checksum calculation - {len(checksums)} found but {num_objects} hdf objects")
else:
# create a numpy array to store checksums
log.debug(f"creating numpy checksum array for {num_objects} checksums")
checksum_arr = np.zeros((num_objects,), dtype='S16')
objids = list(checksums.keys())
objids.sort()
for i in range(num_objects):
objid = objids[i]
checksum_arr[i] = checksums[objid]
log.debug("numpy array created")
hash_object = hashlib.md5(checksum_arr.tobytes())
md5_sum = hash_object.hexdigest()
log.debug(f"got domain_checksum: {md5_sum}")
results["md5_sum"] = md5_sum
# free up memory used by the checksums
del results["checksums"]
results["scan_complete"] = time.time()
if update:
# write .info object back to S3
info_key = root_prefix + ".info.json"
log.info(f"scanRoot - updating info key: {info_key} with results: {results}")
await putStorJSONObj(app, info_key, results, bucket=bucket)
return results
async def objDeleteCallback(app, s3keys):
log.info(f"objDeleteCallback, {len(s3keys)} items")
if not isinstance(s3keys, list):
log.error("expected list result for objDeleteCallback")
raise ValueError("unexpected callback format")
if "objDelete_prefix" not in app or not app["objDelete_prefix"]:
log.error("Unexpected objDeleteCallback")
raise ValueError("Invalid objDeleteCallback")
prefix = app["objDelete_prefix"]
prefix_len = len(prefix)
for s3key in s3keys:
if not s3key.startswith(prefix):
log.error(f"Unexpected key {s3key} for prefix: {prefix}")
raise ValueError("invalid s3key for objDeleteCallback")
full_key = prefix + s3key[prefix_len:]
log.info(f"removeKeys - objDeleteCallback deleting key: {full_key}")
await deleteStorObj(app, full_key)
log.info("objDeleteCallback complete")
async def removeKeys(app, objid):
# iterate through all s3 keys under the given root or dataset id and delete them
#
# Note: not re-entrant! Only one removeKeys an be run at a time per app.
log.debug(f"removeKeys: {objid}")
if not isSchema2Id(objid):
log.warn("ignoring non-schema2 id")
raise KeyError("Invalid key")
s3key = getS3Key(objid)
log.debug(f"removeKeys - got s3key: {s3key}")
expected_suffixes = (".dataset.json", ".group.json")
s3prefix = None
for suffix in expected_suffixes:
if s3key.endswith(suffix):
s3prefix = s3key[:-len(suffix)]
if not s3prefix:
log.error("removeKeys - unexpected s3key for delete_set")
raise KeyError("unexpected key suffix")
log.info(f"removeKeys - delete for {objid} searching for s3prefix: {s3prefix}")
if app["objDelete_prefix"]:
log.error("removeKeys - objDelete_prefix is already set - improper use of non-reentrant call?")
# just continue and reset
app["objDelete_prefix"] = s3prefix
try:
await getStorKeys(app, prefix=s3prefix, include_stats=False, callback=objDeleteCallback)
except ClientError as ce:
log.error(f"removeKeys - getS3Keys faiiled: {ce}")
except HTTPNotFound:
log.warn(f"removeKeys - HTTPNotFound error for getStorKeys with prefix: {s3prefix}")
except HTTPInternalServerError:
log.error(f"removeKeys - HTTPInternalServerError for getStorKeys with prefix: {s3prefix}")
except Exception as e:
log.error(f"removeKeys - Unexpected Exception for getStorKeys with prefix: {s3prefix}: {e}")
# reset the prefix
app["objDelete_prefix"] = None
|
#!/usr/bin/env python
""" provides a storage layer for meta-data and snv distances from the
findneighbour4 system in a RDBMS
Tested with:
- Oracle Autonomous (ATP and ADW cloud service)
- Sqlite (but, sqlite can't be used as a server backend)
Not tested:
MS SQL server, PostgreSQL
Tested but doesn't work at present
MySQL - the issue is with storage of character large objects in TEXT fields. The SQL alchemy version used make TEXT, not LARGETEXT fields.
- Workarounds described https://stackoverflow.com/questions/47644739/what-column-type-does-sqlalchemy-use-for-text-on-mysql did not fix this
- probably a soluble problem
- tested with MySQL 8 on Ubuntu 20. Connection string was "mysql://root:root@localhost:3306/test_db" with user/password root
A component of the findNeighbour4 system for bacterial relatedness monitoring
Copyright (C) 2021 David Wyllie david.wyllie@phe.gov.uk
repo: https://github.com/davidhwyllie/findNeighbour4
This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License as published
by the Free Software Foundation. See <https://opensource.org/licenses/MIT>, and the LICENSE file.
"""
# import gc
import bson # type: ignore
from datetime import datetime, timedelta, date
import hashlib
import os
import json
import pandas as pd
import psutil
import logging
import numpy as np
import warnings
import uuid
import cx_Oracle
from sentry_sdk import capture_exception
import progressbar
from sqlalchemy import (
Integer,
Column,
Float,
MetaData,
Text,
String,
DateTime,
Identity,
Index,
TIMESTAMP,
func,
create_engine,
inspect,
)
# from sqlalchemy.pool import NullPool
from findn.seq2json import SeqDictConverter
from sqlalchemy.sql.expression import desc
from sqlalchemy.orm import (
sessionmaker,
scoped_session,
)
from sqlalchemy.ext.declarative import declarative_base
from typing import (
Any,
Dict,
Iterable,
List,
NoReturn,
Optional,
Set,
TypedDict,
Union,
)
Guid2NeighboursFormat1 = List[Union[str, int]]
Guid2NeighboursFormat3 = Union[str]
Guid2NeighboursFormat4 = Dict[str, Union[str, int]]
Guid2NeighboursFormats = Union[
Guid2NeighboursFormat1, Guid2NeighboursFormat3, Guid2NeighboursFormat4
]
class RecentDatabaseMonitoringRet(TypedDict, total=False):
recompression_data: bool
latest_stats: Dict[str, Union[int, np.float64]]
trend_stats: List[Dict[str, Any]]
# global: definition of database structure
# classes mapping to persistence database inherit from this
db_pc = declarative_base() # global
metadata = MetaData()
class RDBMSError(Exception):
"""a general purpose error used by the rdbms module."""
pass
## define schema
class BulkLoadTest(db_pc):
"""used only for testing bulk uploads as part of unit testing"""
__tablename__ = "fn4_bulk_load_test"
blt_int_id = Column(Integer, Identity(start=1), primary_key=True)
bulk1 = Column(Integer)
bulk2 = Column(Integer)
class FNLock(db_pc):
"""used for storing details of one or more classes of lock"""
__tablename__ = "fn4lock"
lock_int_id = Column(
Integer,
primary_key=True,
comment="an integer reflecting the kind of lock studied",
)
sequence_id = Column(
String(60),
comment="the sample_id represented by the entry; sample_ids are typically guids",
)
lock_set_date = Column(
TIMESTAMP, index=True, comment="the date and time the lock was modified"
)
uuid = Column(String(32))
lock_status = Column(
Integer, comment="whether the lock is in place (1) or not in place (0)"
)
class Config(db_pc):
"""stores config data"""
__tablename__ = "config"
cfg_int_id = Column(Integer, Identity(start=1), primary_key=True)
config_key = Column(String(56), index=True, unique=True)
config_value = Column(Text(50000000)) # 50M limit. Required for Mysql
class RefCompressedSeq(db_pc):
"""stores reference compressed sequences, which are large character objects, and their annotations.
Note: the mongodb equivalent is the GridFS meta-collection refcompressedseq and the standard collection guid2meta.
"""
__tablename__ = "refcompressedseq"
seq_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sequence_id = Column(
String(60),
index=True,
unique=True,
comment="the sample_id represented by the entry; sample_ids are typically guids",
)
examination_date = Column(
TIMESTAMP,
index=True,
comment="the date and time the record was examined and compressed",
)
annotations = Column(
Text, comment="a json string, representing metadata about the sequence"
)
invalid = Column(
Integer,
default=-1,
index=True,
comment="whether the sequence is of sufficient quality to be analysed (invalid = 0) or is not (invalid = 1). Part of the annotations, but extracted into separate field for indexing.",
)
prop_actg = Column(
Float,
index=True,
comment="the proportion of A,C,G,T (as opposed to N,-, or IUPAC codes). Part of the annotations, but extracted into separate field for indexing.",
)
content = Column(
Text, comment="a json string, representing the reference compressed sequence"
)
class Edge(db_pc):
"""represents a pair of RefCompressedSeq which are similar. Table is called 'edge' because it represents an edge in a network in which the vertices are RefCompressedSequences.
Note
- that an edge A -> B is represented twice in this data representation: as A -> B, and as B -> A.
- This means that all the edges of A can be obtained by
statements such as SELECT * from Edge where seq_int_id_1 = 217, where 217 is the seq_int_id of sequence A.
- if insertion is fast enough, we could enable foreign key constraints here.
- it is likely that insert speed will be the main determinant of server speed
- and the faster the inserts work the better.
- in the mongo implementation, FK constraints are not implemented, and the relationships are guaranteed by application logic, not at a database level .
At present, this approach is being used here too.
"""
__tablename__ = "edge"
edge_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sequence_id_1 = Column(
String(60),
comment="One of a pair of sequences. Note: foreign key constraint not enforced at a database level",
)
sequence_id_2 = Column(
String(60),
comment="One of a pair of sequences. Note: foreign key constraint not enforced at a database level ",
)
dist = Column(Integer, comment="the SNV distance between sequences")
Index("ix_Edge_1", Edge.sequence_id_1, unique=False, oracle_compress=1)
class Cluster(db_pc):
"""stores clusters, which are large character objects (json)"""
__tablename__ = "sequence_cluster"
cl_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
cluster_build_id = Column(
String(40),
index=True,
comment="an identifier for the contents; this is typically a sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="a json string describing the cluster")
class Monitor(db_pc):
"""stores monitor entries, which are large character objects (html)"""
__tablename__ = "monitor"
mo_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
mo_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
content = Column(Text, comment="html data")
class ServerMonitoring(db_pc):
"""stores server monitoring entries, which are large character objects (json)"""
__tablename__ = "server_monitoring"
sm_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sm_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="a json dictionary including ")
class MSA(db_pc):
"""stores multisequence alignments, which are large character objects (json)"""
__tablename__ = "msa"
msa_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
msa_id = Column(
String(60),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="character large object containing a json string")
class TreeStorage(db_pc):
"""stores trees and related data, which are large character objects (json)"""
__tablename__ = "tree"
ts_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
ts_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="character large object containing a json string")
class NPEncoder(json.JSONEncoder):
"""encodes Numpy and datetime types as jsonisable equivalents"""
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
else:
return super(NPEncoder, self).default(obj)
class fn3persistence_r:
"""System for persisting results from large numbers of sequences stored in FindNeighbour 3+.
Uses a generic rdbms, with optimisations for Oracle databases when using the cx_oracle package.
the associated schema is defined using SQLalchemy tables, as above.
Note that parts of this code are taken from the class pcadb.PCADatabaseManager.
In future, it may be possible to integrate this class with that, if successful
implementation of findNeighbour4 functionality using an RDBMS is possible
See also the Persistence class in the persistence module.
This provides an API which will either use this class, or the mongo based fn3persistence class, depending on
software settings.
"""
def __init__(
self, connection_config, debug=0, server_monitoring_min_interval_msec=0
):
"""creates the RDBMS connection
Parameters
-----------
connection_config:
One of
1. a key to a dictionary containing one or more database configuration details: (e.g. 'prod', 'test')
2. a valid sqlalchemy database connection string (if this is sufficient for connections) e.g. 'pyodbc+mssql://myserver'
3. None. This is considered to mean 'sqlite://' i.e. an in memory sqlite database, which is not persisted when the program stops.
if it is not none, a variable called DB_CONNECTION_CONFIG_FILE must be present. This must point to a file containing credentials.
the name of an environment variable containing (in json format) a dictionary, or None if it is not required.
An example of such a dictionary is as below:
{
'prod':{'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite:///db/proddb.sqlite'}
'dev': {'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite:///db/devdb.sqlite'},
'test':{'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite://'}
}
The DBTYPE and ENGINE_NAME keys are essential.
Other keys may also be present, and are required in some cases (for example by Oracle connections).
{
'prod':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
},
'dev':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
}
}
Note, the bit after the @(description describes where your database is, and will be found in your cloud wallet, if you are using cloud databases. See below.
In this case, TNS_ADMIN is the value you wish the TNS_ADMIN environment variable to be set to.
The software will set TNS_ADMIN, and, if you are using a virtual environment, it will be scoped to the virtual environment.
In summary, it will configure necessary settings to allow Oracle database connections.
Note, if you are using a python virtual environment, this environment variable should be included in the .env file in the root of your project. The .env file should not be under source control.
configuration engine_name: an SQLalchemy connect string, e.g. sqlite::// for temporary memory db, see https://docs.sqlalchemy.org/en/13/core/engines.html
debug: if True, deletes any existing data on startup.
show_bar: show a progress bar during long operations
NOTE:
This software has been tested with
(i) Sqlite 3.3.2+
(ii) Oracle Autonomous Database (cloud)
https://blogs.oracle.com/oraclemagazine/getting-started-with-autonomous
To connect to Oracle there are several steps.
0. Install dependencies, see
https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html
wget https://download.oracle.com/otn_software/linux/instantclient/211000/instantclient-basic-linux.x64-21.1.0.0.0.zip
need to set the LD_LIBRARY_PATH variable, see
https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html
e.g. export LD_LIBRARY_PATH=/data/software/instantclient_21_1:LD_LIBRARY_PATH
these parameters have to go into the python .env file e.g.
----------------------------------------------------------------
LD_LIBRARY_PATH="/software/instantclient_21_1"
PCADB_CONNECTION_CONFIGFILE="/secret/config.json"
Where config.json looks like
{
'prod':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
}
}
** NOTE: as per normal json conventions, escape quotes (i.e. \" not " around the certificate name, otherwise SSL connections will fail) **
1. Download your OCI wallet, & unzip it somewhere
2. Set the TNS_ADMIN env var to point to this directory
3. Edit the WALLET_LOCATION in the sqlnet.ora file to point to the relevant directory, e.g. WALLET_LOCATION = (SOURCE = (METHOD = file) (METHOD_DATA = (DIRECTORY="/data/credentials/oci_test")))
4. Create a user with relevant privileges see below)
5. Set the OCI_ENGINE_NAME env var.
An example of this is as below (redacted so not live)
oracle+cx_oracle://scott:tigerX22@(description= (retry_count=20)(retry_delay=3)(address=(protocol=tcps)(port=1522)(host=host.oraclecloud.com))(connect_data=(service_name=redacted))(security=(ssl_server_cert_dn="redacted")))
This data can be found in the tnsnames.ora file: for details, see
https://docs.sqlalchemy.org/en/14/dialects/oracle.html#dialect-oracle-cx_oracle-connect
https://stackoverflow.com/questions/37471892/using-sqlalchemy-dburi-with-oracle-using-external-password-store
https://stackoverflow.com/questions/14140902/using-oracle-service-names-with-sqlalchemy/35215324
https://blogs.oracle.com/sql/how-to-create-users-grant-them-privileges-and-remove-them-in-oracle-database
https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/GRANT.html#GUID-20B4E2C0-A7F8-4BC8-A5E8-BE61BDC41AC3
Configuring interactions with external OCI databases
====================================================
Your application will need to run as a user (we'll call it PCADB) will need some priviledges granted.
The exact privileges required involving creating, dropping tables & indexes, as well as inserting and deleting data.
CREATE USER PCADB IDENTIFIED BY 'MyPassword1234!';
GRANT CONNECT TO PCADB;
GRANT CREATE SESSION TO PCADB;
GRANT CREATE SEQUENCE TO PCADB;
GRANT CREATE TABLE TO PCADB;
GRANT CREATE SYNONYM TO PCADB;
ALTER USER PCADB DEFAULT TABLESPACE DATA quota unlimited on DATA;
"""
self.sjc = SeqDictConverter()
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
self.debug = debug
self.storage_technology = "rdbms"
self.logger.info("Storage technology is {0}".format(self.storage_technology))
self.server_monitoring_min_interval_msec = server_monitoring_min_interval_msec
self.previous_server_monitoring_data = {}
self.previous_server_monitoring_time = None
# connect and create session. Validate inputs carefully.
if connection_config is None:
self.logger.info("Connection config is None: using in-memory sqlite.")
self.engine_name = "sqlite://"
elif "://" in connection_config:
# it's not None, and we assume what we are provided is an sqlalchemy database connection string
self.logger.info(
"Connection config provided; using {0}".format(connection_config)
)
self.engine_name = connection_config
else:
# we have been passed a token. this should be a key to a dictionary, stored in
# DB_CONNECTION_CONFIG_FILE which contains credentials
conn_detail_file = None
try:
conn_detail_file = os.environ["DB_CONNECTION_CONFIG_FILE"]
except KeyError:
raise RDBMSError(
"Environment variable DB_CONNECTION_CONFIG_FILE does not exist; however, it is required. If you are using a python virtual environment, you need to set it in .env, not globally"
)
if conn_detail_file is None:
# we failed to set it
raise RDBMSError(
"Tried to set conn_detail_file from environment variable DB_CONNECTION_CONFIG_FILE, but it is still None."
)
if not os.path.exists(conn_detail_file):
raise FileNotFoundError(
"Connection file specified but not found: {0}".format(
conn_detail_file
)
)
# read the config file
with open(conn_detail_file, "rt") as f:
conn_detail = json.load(f)
if connection_config not in conn_detail.keys():
raise RDBMSError(
"Connection {0} does not correspond to one of the keys {1} of the configuration json file at {2}".format(
connection_config, conn_detail.keys(), conn_detail_file
)
)
# configure engine
this_configuration = conn_detail[
connection_config
] # extract the relevant part of the config dictionary
# two keys are always present
essential_keys = set(["DBTYPE", "ENGINE_NAME"])
if len(essential_keys - set(this_configuration.keys())) > 0:
raise RDBMSError(
"Provided keys for {0} are not correct. Required are {1}".format(
connection_config, essential_keys
)
)
# if it's Oracle, then three keys are required.
if this_configuration["DBTYPE"] == "oracle":
essential_keys = set(["DBTYPE", "ENGINE_NAME", "TNS_ADMIN"])
if len(essential_keys - set(this_configuration.keys())) > 0:
raise RDBMSError(
"Provided keys for oracle db in {0} are not correct. Required are {1}".format(
connection_config, essential_keys
)
)
# set the TNS_ADMIN variable.
self.logger.info(
"Set TNS_ADMIN to value specified in config file {0}".format(
this_configuration["TNS_ADMIN"]
)
)
os.environ["TNS_ADMIN"] = this_configuration["TNS_ADMIN"]
self.logger.info("Set ENGINE_NAME configuration string from config file.")
self.engine_name = this_configuration["ENGINE_NAME"]
self.using_sqlite = self.engine_name.startswith("sqlite://")
# now we can start
self.Base = db_pc
self.logger.info("DatabaseManager: Connecting to database")
self.is_oracle = "oracle+cx" in self.engine_name
self.is_sqlite = "sqlite://" in self.engine_name
self.show_bar = True # maybe define a method to switch this off
self._create_engine()
self.logger.info(
"DatabaseManager: Database connection made; there are {0} tables. Oracle database = {1}".format(
len(self._table_names()), self.is_oracle
)
)
self.Base.metadata.create_all(
bind=self.engine
) # create the table(s) if they don't exist
# create thread-local sessions, see https://docs.sqlalchemy.org/en/14/orm/contextual.html#using-custom-created-scopes
session_factory = sessionmaker(bind=self.engine)
# this object will call session factory when we create/request a thread local session
# e.g. thread_local_session = self.Session()
self.Session = scoped_session(session_factory)
# drop existing tables if in debug mode
# delete any pre-existing data if we are in debug mode.
if debug == 2:
logging.warning(
"Debug mode operational [DEBUG={0}]; deleting all data from tables.".format(
debug
)
)
self._delete_existing_clustering_data()
self._delete_existing_data()
else:
self.logger.info("Using stored data in rdbms")
def _create_engine(self):
"""create database connection engine"""
if self.is_oracle:
# it is important to set arraysize, see
# https://docs.sqlalchemy.org/en/14/dialects/oracle.html
# https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#tuningfetch
# but if you set it too large you can get DPI-1015 (allocated cursor size > 2G) see
# https://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html
# to disable connection pooling
# https://docs.sqlalchemy.org/en/14/core/pooling.html#switching-pool-implementations
# self.engine = create_engine(
# self.engine_name, arraysize=1000000,
# poolclass=NullPool
# ) # fetch results in batches of 1m.
self.engine = create_engine(
self.engine_name, arraysize=1000000
) # fetch results in batches of 1m.
logging.info("Created engine connecting to Oracle database")
else:
# sqlalchemy generic pool manager, for non-Oracle databases
self.engine = create_engine(self.engine_name)
# oracle pool manager code
# use cx_Oracle pool manager
# u, p, dsn = self.oracle_connstring_parts(self.engine_name)
# self.oracle_pool = cx_Oracle.SessionPool(
# user = u,
# password = p,
# dsn = dsn,
# min = 4,
# max = 4,
# encoding="UTF-8",
# nencoding="UTF-8"
# )
# self.engine = create_engine("oracle://", creator = self.oracle_pool.acquire, poolclass = NullPool)
def closedown(self):
"""closes the session(s) & disposes of any engine.
Is required for unit testing"""
try:
self.engine.dispose()
except AttributeError as e:
# the class may not have an engine object attached, generates an AttributeError
pass
logging.info(
"Failed to dispose of engine during closedown(). AttributeError logged to sentry"
)
capture_exception(e)
except Exception as e1:
logging.warning(
"Failed to dispose of engine during closedown(). Error logged to sentry"
)
capture_exception(e1)
def no_progressbar(self):
"""don't use progress bars"""
self.show_bar = False
def _table_names(self):
"""returns table names in the schema.
If the schema's contents have not been created, returns an empty list"""
return inspect(self.engine).get_table_names()
def thread_local_session(self, n_retries=3, simulate_failure="no", log_errors=True):
"""generates, or selects a thread local session from a session factory or pool.
For context, see https://docs.sqlalchemy.org/en/13/orm/contextual.html
Checks that the session recovered from the session pool is still valid, since they can time out.
If it is timed out, tries another. Will retry up to n_retries times.
Parameters:
n_retries: the number of attempts which will be made to generate a functional connection.
simulate_failure: simulates the failure of a connection (closes the connection before returning it) - used only for unittesting. Valid values:
'no' : normal operation
'once': fail once
'always': fail every time, even on repeated attempts to connect
log_errors: logs any errors to sentry & error log (recommended)"""
tries = n_retries
while tries > 0:
tries = tries - 1
tls = self.Session()
# simulate failure if required to do so
if (simulate_failure == "once" and tries - 1 == n_retries) or (
simulate_failure == "always"
):
tls = (
None # not a session object. Attempts to use it as such will fail.
)
# test whether it is working
try:
tls.query(Config).filter_by(
config_key="config"
).first() # try to connect
# if execution continues here, the session works
return tls
except Exception as e1:
logging.info(
"Failed to connect on trial {0}/{1}; error raised was {2}. Recreating engine".format(
n_retries - tries, n_retries, e1
)
)
if log_errors:
capture_exception(e1)
logging.error(e1)
# try to remove the failing session, if it has been constructed properly
try:
self.engine.dispose()
tls.close()
except Exception:
logging.info("Failed to remove session and dispose of engine")
# succeeded in disposing of existing engine; try reconnecting
self._create_engine()
# could not connect despite multiple attempts.
raise RDBMSError(
"Could not connect to database. Tried {0} times with different sessions despite recreating database connection".format(
n_retries
)
)
def _drop_existing_tables(self):
"""empties, but does not drop, any existing tables"""
self.Base.metadata.create_all(
self.engine
) # create the table(s) if they don't already exist
BulkLoadTest.__table__.drop(self.engine)
Config.__table__.drop(self.engine)
Edge.__table__.drop(self.engine)
Cluster.__table__.drop(self.engine)
Monitor.__table__.drop(self.engine)
ServerMonitoring.__table__.drop(self.engine)
MSA.__table__.drop(self.engine)
TreeStorage.__table__.drop(self.engine)
RefCompressedSeq.__table__.drop(self.engine)
remaining = len(self._table_names())
if remaining > 0:
warnings.warn(
"Failed to remove all tables in the database. Is this database being used by another program? The following remain: {0}".format(
self._table_names()
)
)
return
def oracle_connstring_parts(self, connstring):
"""splits an oracle connection string into username, password and DSN"""
if connstring.startswith("oracle+cx_oracle://"):
e1 = self.engine_name.replace("oracle+cx_oracle://", "")
up, dns = e1.split("@")
u, p = up.split(":")
return u, p, dns
else:
return None
def _bulk_load(self, upload_df, target_table, max_batch=100000):
"""bulk uploads pandas dataframes.
If using an oracle database, uses Oracle's cx-oracle package to bulk upload data
upload_df: a pandas dataframe. Names **much match** the table target_table
target_table: the name of the table to upload into
(note: this is not the name of the class in the table definition, it's the name of the table in the SQL)
Returns:
number of items uploaded (integer)
Background:
- ORM is slow for large inserts
- Oracle is not currently supported by pandas .to_sql method='multi', so a bespoke method is needed
- Need custom code for bulk loading to Oracle. Methods are provided in the cx_oracle package, see
https://cx-oracle.readthedocs.io/en/latest/user_guide/batch_statement.html
The maximum size that can be transmitted to the Oracle server is 2G.
If this happens, a cx_Oracle.DatabaseError
is raised with result DPI-1015. R Code to prevent this by auto-setting max_batch is provided.
"""
# verify data : ensure that target_table is a table [Essential: otherwise, can be a vector for SQL injection]
if target_table not in self._table_names():
raise ValueError(
"target_table {0} does not exist: valid tables are {1}".format(
target_table, self._table_names()
)
)
# check that upload_df is pandas dataframe
if not isinstance(upload_df, pd.DataFrame):
raise TypeError(
"upload_df needs to be pandas DataFrame, not a {0}".format(
type(upload_df)
)
)
# check that we have been passed data
ncol = len(upload_df.columns)
if ncol == 0:
# we treat this as an error
raise RDBMSError(
"Passed data frame to _bulk_upload to {0} contains no columns {1}".format(
target_table, upload_df
)
)
self.logger.info("Bulk upload to {0} started".format(target_table))
if self.is_sqlite:
# there is a max variable limit of 32,766 for Sqlite 3.32.0 on https://www.sqlite.org/limits.html
# set max_batch to keep below this.
max_batch = int(32000 / ncol)
self.logger.info(
"Autoset max_batch to {0}, as running SQLite".format(max_batch)
)
if self.is_oracle:
# ************* commit via cx_Oracle bulk upload syntax ****************
# parse the engine_name into dsn, database & password
u, p, dsn = self.oracle_connstring_parts(self.engine_name)
# get into the right format for loading: note: holds all data in ram
loadvar = list(upload_df.itertuples(index=False, name=None))
ncol = len(upload_df.columns.to_list())
# estimate the maximum buffer size required and auto-reduce the max_batch if required.
estimated_row_size = len(str(loadvar[0]))
estimated_max_batch = int(
1e7 / (estimated_row_size)
) # large margin of safety 10M batch size
if estimated_max_batch < max_batch:
max_batch = estimated_max_batch
self.logger.info(
"Reduced max_batch to keep estimated buffer size within acceptable limits (<= 10M target). max_batch is {0}".format(
max_batch
)
)
# construct sql statment.
# Should be injection-safe; we have checked the target_table is a table, and are incorporating integers and verified strings only.
collabels = [":" + str(x + 1) for x in list(range(ncol))]
insert_cols = ",".join(collabels)
target_cols = ",".join(upload_df.columns.to_list())
sql_statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(
target_table, target_cols, insert_cols
)
start_n = len(loadvar)
if self.show_bar:
bar = progressbar.ProgressBar(max_value=start_n)
with cx_Oracle.connect(user=u, password=p, dsn=dsn) as conn:
cursor = conn.cursor()
while len(loadvar) > 0:
if self.show_bar:
bar.update(start_n - len(loadvar))
try:
cursor.executemany(sql_statement, loadvar[0:max_batch])
loadvar = loadvar[max_batch:]
conn.commit()
except Exception:
conn.rollback()
raise
if self.show_bar:
bar.finish()
else:
# ***************************** ALL DATABASES OTHER THAN ORACLE ************************
# note: there may be limits to the complexity of the statement permitted: a maximum number of parameters.
# therefore, we do this in batches as well.
start_n = len(upload_df.index)
if self.show_bar:
bar = progressbar.ProgressBar(max_value=start_n)
while len(upload_df.index) > 0:
self.logger.info(
"Bulk upload of {0} : {1} remain".format(
target_table, len(upload_df)
)
)
to_upload = upload_df.head(n=max_batch)
to_upload.to_sql(
target_table,
self.engine,
if_exists="append",
index=False,
method="multi",
) # pandas method
upload_df = upload_df.iloc[max_batch:]
if self.show_bar:
bar.update(start_n - len(upload_df.index))
self.logger.info("Bulk upload to {0} complete".format(target_table))
if self.show_bar:
bar.finish()
return len(upload_df.index)
def delete_server_monitoring_entries(self, before_seconds: int) -> None:
"""deletes server monitoring entries more than before_seconds ago"""
try:
tls = self.thread_local_session()
earliest_allowed = datetime.now() - timedelta(seconds=before_seconds)
tls.query(ServerMonitoring).filter(
ServerMonitoring.upload_date < earliest_allowed
).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def summarise_stored_items(self) -> Dict[str, Any]:
"""counts how many sequences exist of various types"""
return {}
def connect(self) -> None:
"""test whether the database is connected, and if not, tries to connect.
Does nothing here, just a stub."""
pass
def rotate_log(self) -> None:
"""forces rotation of the mongo log file; a stub here, does nothing"""
pass
def raise_error(self, token: str) -> NoReturn:
"""raises a ZeroDivisionError, with token as the message.
useful for unit tests of error logging"""
raise ZeroDivisionError(token)
def _delete_existing_data(self) -> None:
"""deletes existing data from the databases"""
try:
tls = self.thread_local_session()
tls.query(Config).delete()
tls.query(Edge).delete()
tls.query(RefCompressedSeq).delete()
tls.query(Monitor).delete()
tls.query(ServerMonitoring).delete()
tls.query(BulkLoadTest).delete()
tls.query(Cluster).delete()
tls.query(MSA).delete()
tls.query(TreeStorage).delete()
tls.query(FNLock).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
def _delete_existing_clustering_data(self) -> None:
"""deletes any clustering data from the databases"""
try:
tls = self.thread_local_session()
tls.query(Cluster).delete()
tls.query(MSA).delete()
tls.query(TreeStorage).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def first_run(self) -> bool:
"""if there is no config entry, it is a first-run situation"""
tls = self.thread_local_session()
row = tls.query(Config).filter_by(config_key="config").first()
return row is None
def __del__(self) -> None:
"""closes any session"""
self.closedown()
def memory_usage(self) -> Dict[str, Union[int, float]]:
"""returns memory usage by current python3 process
Uses the psutil module, as the resource module is not available in windows.
"""
memdict = psutil.virtual_memory()._asdict()
sm = {"server|mstat|" + k: v for k, v in memdict.items()}
return sm
# methods for the config collection
def config_store(self, key: str, object: Dict[str, Any]) -> Any:
"""stores object into config collection
It is assumed object is a dictionary
"""
if not isinstance(object, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(object))
)
tls = self.thread_local_session()
if row := tls.query(Config).filter_by(config_key=key).first():
row.config_value = json.dumps(object, cls=NPEncoder).encode("utf-8")
else:
try:
row = Config(
config_key=key,
config_value=json.dumps(object, cls=NPEncoder).encode("utf-8"),
)
tls.add(row)
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def config_read(self, key: str) -> Any:
"""loads object from config.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
row = tls.query(Config).filter_by(config_key=key).first()
if row is None:
return None
else:
return dict(_id=key, **json.loads(row.config_value))
# methods for the server and database monitoring
def recent_database_monitoring(
self, max_reported: int = 100
) -> RecentDatabaseMonitoringRet:
"""computes trends in the number of records holding pairs (guid2neighbours) vs. records.
This ratio is a measure of database health. Ratios > 100 indicate the database may become very large, and query slowly"""
return {"recompression_data": False, "latest_stats": {"storage_ratio": 1}}
def _to_string(self, x=[str, bytes]) -> str:
"""returns a string version of x; if x is bytes, returns a string, assuming utf-8 encoding
This function is required because some databases return bytes objects
from 'text' fields (like sqlite) while others return str objects (like oracle)
"""
if isinstance(x, bytes):
return x.decode("utf-8")
else:
return x
def recent_server_monitoring(
self,
max_reported: int = 100,
selection_field: Optional[str] = None,
selection_string: Optional[str] = None,
) -> List[dict]:
"""returns a list containing recent server monitoring, in reverse order (i.e. tail first).
The _id field is an integer reflecting the order added. Lowest numbers are most recent.
Inputs
max_reported - return this number of lines, at most.
selection_field - if not None, will only return lines containing selection_string
in the 'selection_field' key of the returned dictionary.
selection_string -if selection_field is not None, only returns rows if
selection_string is present in the 'selection_field' key of the
monitoring element. If None, this constraint is ignored.
"""
if not isinstance(max_reported, int):
raise TypeError(
f"limit must be an integer, but it is a {type(max_reported)}"
)
if not max_reported >= 0:
raise ValueError("limit must be more than or equal to zero")
if max_reported == 0:
return []
def row_to_dict(res: ServerMonitoring) -> dict:
d = json.loads(res.content)
d["_id"] = res.sm_int_id
if selection_field is None:
return d
else:
if d[selection_field] == selection_string:
return d
else:
return None
tls = self.thread_local_session()
return [
d
for res in tls.query(ServerMonitoring)
.order_by(desc(ServerMonitoring.sm_int_id))
.limit(max_reported)
for d in (row_to_dict(res),)
if d is not None
]
def server_monitoring_store(
self,
message: str = "No message provided",
what: Optional[str] = None,
guid: Optional[str] = None,
content: Dict[str, Any] = {},
) -> bool:
"""stores content, a dictionary, into the server monitoring log"""
if not isinstance(content, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(content))
)
tls = self.thread_local_session()
now = dict(content)
if what is not None:
now["content|activity|whatprocess"] = what
if guid is not None:
now["content|activity|guid"] = guid
now["context|info|message"] = message
current_time = datetime.now()
now["context|time|time_now"] = str(current_time.isoformat())
now["context|time|time_boot"] = datetime.fromtimestamp(
psutil.boot_time()
).strftime("%Y-%m-%d %H:%M:%S")
# should we write this data? We have the option not to log all messages, to prevent the store getting very full.
write_content = False
if self.previous_server_monitoring_time is None:
# yes if this is the first record written.
write_content = True
else:
time_since_last_write = current_time - self.previous_server_monitoring_time
# yes if it's after the previous_server_monitoring_time in milliseconds
t = (
1000 * float(time_since_last_write.seconds)
+ float(time_since_last_write.microseconds) / 1000
)
if t >= self.server_monitoring_min_interval_msec:
write_content = True
if write_content:
try:
json_now = json.dumps(now).encode("utf-8")
row = ServerMonitoring(
sm_id=hashlib.sha1(json_now).hexdigest(),
upload_date=current_time,
content=json_now,
)
tls.add(row)
self.previous_server_monitoring_time = current_time
self.previous_server_monitoring_data = now
tls.commit()
# finished
return True
except Exception:
tls.rollback()
raise
else:
return False
# methods for monitor, which store the contents of an html file
# in a gridFS store.
def monitor_store(self, monitoring_id: str, html: str) -> str:
"""stores the monitor output string html. Overwrites any prior object."""
if not isinstance(html, str):
raise TypeError("Can only store string objects, not {0}".format(type(html)))
try:
tls = self.thread_local_session()
tls.query(Monitor).filter_by(mo_id=monitoring_id).delete()
row = Monitor(mo_id=monitoring_id, content=html.encode("utf-8"))
tls.add(row)
tls.commit()
# finished
except Exception:
tls.rollback()
def monitor_read(self, monitoring_id: str) -> Optional[str]:
"""loads stored string (e.g. html object) from the monitor collection."""
tls = self.thread_local_session()
if res := tls.query(Monitor).filter_by(mo_id=monitoring_id).first():
return self._to_string(res.content)
else:
return None
# methods for multisequence alignments
def msa_store(self, msa_token: str, msa: dict) -> Optional[str]:
"""stores the msa object msa under token msa_token."""
tls = self.thread_local_session()
if not isinstance(msa, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(msa))
)
# we don't replace. These entries are write once.
if tls.query(MSA).filter_by(msa_id=msa_token).one_or_none() is None:
try:
res = MSA(
msa_id=msa_token,
upload_date=datetime.now(),
content=json.dumps(msa).encode("utf-8"),
)
tls.add(res)
tls.commit()
except Exception:
tls.rollback()
raise
def msa_read(self, msa_token: str) -> Optional[dict]:
"""loads object from msa collection.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
if res := tls.query(MSA).filter_by(msa_id=msa_token).first():
return json.loads(res.content)
else:
return None
def msa_delete(self, msa_token: str) -> None:
try:
"""deletes the msa with token msa_token"""
tls = self.thread_local_session()
tls.query(MSA).filter_by(msa_id=msa_token).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def msa_stored_ids(self) -> List[str]:
"""returns a list of msa tokens of all objects stored"""
tls = self.thread_local_session()
return [res.msa_id for res in tls.query(MSA)]
def msa_delete_unless_whitelisted(self, whitelist: Iterable[str]) -> None:
try:
"""deletes the msa unless the id is in whitelist"""
tls = self.thread_local_session()
tls.query(MSA).filter(MSA.msa_id.not_in(whitelist)).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
# methods for trees
def tree_store(self, tree_token: str, tree: dict) -> Optional[str]:
"""stores the tree object tree under token tree_token.
Will not overwrite; requests to do so fail, silently."""
if not isinstance(tree, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(tree))
)
tls = self.thread_local_session()
if tls.query(TreeStorage).filter_by(ts_id=tree_token).one_or_none() is None:
try:
row = TreeStorage(
ts_id=tree_token,
upload_date=datetime.now(),
content=json.dumps(tree).encode("utf-8"),
)
tls.add(row)
tls.commit()
except Exception:
tls.rollback()
raise
def tree_read(self, tree_token: str) -> Optional[dict]:
"""loads object from tree collection.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
if res := tls.query(TreeStorage).filter_by(ts_id=tree_token).first():
return json.loads(res.content)
else:
return None
def tree_delete(self, tree_token: str) -> None:
try:
"""deletes the tree with token tree_token"""
tls = self.thread_local_session()
tls.query(TreeStorage).filter_by(ts_id=tree_token).delete()
tls.commit()
except Exception:
tls.rollback()
raise
def tree_stored_ids(self) -> List[str]:
"""returns a list of tree tokens of all objects stored"""
tls = self.thread_local_session()
return [res.ts_id for res in tls.query(TreeStorage)]
def tree_delete_unless_whitelisted(self, whitelist: Iterable[str]) -> None:
try:
"""deletes the tree unless the id is in whitelist"""
tls = self.thread_local_session()
tls.query(TreeStorage).filter(TreeStorage.ts_id.not_in(whitelist)).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
# methods for clusters
def cluster_store(self, clustering_key: str, obj: dict) -> int:
"""stores the clustering object obj. retains previous version.
obj: a dictionary to store
clustering_key: the name of the clustering, e.g. TBSNP12-graph
Returns:
current cluster version
Note: does not replace previous version, but stores a new one.
Note: to delete legacy versions, call cluster_delete_legacy().
"""
tls = self.thread_local_session()
if not isinstance(obj, dict):
raise TypeError(f"Can only store dictionary objects, not {type(obj)}")
try:
json_repr = json.dumps(obj, cls=NPEncoder).encode("utf-8")
cluster = Cluster(
cluster_build_id=clustering_key,
upload_date=datetime.now(),
content=json_repr,
)
tls.add(cluster)
tls.commit()
# finished
return cluster.cl_int_id
except Exception:
tls.rollback()
raise
def cluster_read(self, clustering_key: str) -> Optional[dict]:
"""loads object from clusters collection corresponding to the most recent version of
the clustering identified by 'clustering_key'.
Parameters:
clustering_key: a string identifying a clustering result
Returns:
the clustering information, in the form of a dictionary if it exists, or None if it does not
"""
tls = self.thread_local_session()
if (
res := tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.order_by(desc(Cluster.cl_int_id))
.first()
):
return json.loads(res.content)
else:
return None
def cluster_read_update(
self, clustering_key: str, current_cluster_version: int
) -> Optional[dict]:
"""loads object from clusters collection corresponding to the most recent version
of the clustering, saved with cluster_build_id = 'clustering_key'.
it will read only if the current version is different from current_cluster_version; other wise, it returns None
Parameters:
clustering_key: a string identifying the cluster
current_cluster_version: an integer identifying a legacy cluster version
Returns:
the clustering information, in the form of a dictionary if it exists, or None if it does not
"""
tls = self.thread_local_session()
if (
res := tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.filter(Cluster.cl_int_id != current_cluster_version)
.order_by(desc(Cluster.cl_int_id))
.first()
):
return json.loads(res.content)
return None
def cluster_latest_version(self, clustering_key: str) -> int:
"""returns id of latest version, which is the maximum number
Parameters:
clustering_key: a string identifying the cluster
Returns:
cl_int_id, the primary key to the cluster table"""
tls = self.thread_local_session()
if (
res := tls.query(func.max(Cluster.cl_int_id))
.filter(Cluster.cluster_build_id == clustering_key)
.first()
):
retVal = res[0] # it's a tuple
return retVal
else:
return None
def cluster_keys(self, clustering_name: Optional[str] = None) -> List[str]:
"""lists clustering keys beginning with clustering_name. If clustering_name is none, all clustering keys are returned."""
tls = self.thread_local_session()
if clustering_name:
return list(
sorted(
set(
res.cluster_build_id
for res in tls.query(Cluster).filter(
Cluster.cluster_build_id.startswith(clustering_name)
)
)
)
)
else:
return list(sorted(set(res.cluster_build_id for res in tls.query(Cluster))))
def cluster_versions(self, clustering_key: str) -> List[bson.objectid.ObjectId]:
"""lists ids and storage dates corresponding to versions of clustering identifed by clustering_key.
the newest version is first.
"""
tls = self.thread_local_session()
return list(
tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.order_by(desc(Cluster.upload_date))
)
def cluster_delete_all(self, clustering_key: str) -> None:
"""delete all clustering objects, including the latest version, stored under clustering_key"""
try:
tls = self.thread_local_session()
tls.query(Cluster).filter(
Cluster.cluster_build_id == clustering_key
).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def cluster_delete_legacy_by_key(self, clustering_key: str) -> None:
"""delete all clustering objects, except latest version, stored with key clustering_key"""
tls = self.thread_local_session()
cl_int_ids = set()
for (cl_int_id,) in tls.query(Cluster.cl_int_id).filter_by(
cluster_build_id=clustering_key
):
cl_int_ids.add(cl_int_id)
if len(cl_int_ids) == 0:
return
else:
latest_cl_int_id = max(cl_int_ids)
for this_cl_int_id in cl_int_ids:
if not this_cl_int_id == latest_cl_int_id:
tls.query(Cluster).filter_by(cl_int_id=this_cl_int_id).delete()
try:
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def cluster_delete_legacy(self, clustering_name: str) -> None:
"""delete all clustering objects, except latest version, stored with clustering_name"""
for clustering_key in self.cluster_keys(clustering_name=clustering_name):
self.cluster_delete_legacy_by_key(clustering_key)
def refcompressedseq_store(self, guid: str, obj: dict) -> str:
"""stores the json object obj with guid guid.
Parameters:
guid: the sequence identifer
obj: a reference compressed sequence representation, as produced by py_seqComparer.compress().
Here is an example:
{
'A':set([1,2,3]), 'C':set([6]), 'T':set([4]), 'G':set([5]), 'M':{11:'Y', 12:'k'}, 'invalid':0
}
If the guid already exists in the database, raises a FileExistsError, as is the case with the mongo client."""
tls = self.thread_local_session()
if not isinstance(obj, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(obj))
)
if "invalid" not in obj.keys():
raise KeyError(
"An invalid key must be present. Keys are: {0}".format(obj.keys())
)
# if the record already exists, we don't re-add it
res = (
tls.query(RefCompressedSeq.seq_int_id)
.filter_by(sequence_id=guid)
.one_or_none()
)
if res is None: # it doesn't exits
tls.add(
RefCompressedSeq(
sequence_id=guid,
invalid=obj["invalid"],
examination_date=datetime.now(),
content=self.sjc.to_json(obj),
prop_actg=None,
annotations=json.dumps({}),
)
)
try:
tls.commit()
except Exception:
tls.rollback()
raise
else: # it does exist
raise FileExistsError("Attempting to overwrite {0}".format(guid))
# finished
def refcompressedsequence_read(self, guid: str) -> Any:
"""loads object from refcompressedseq collection.
the object loaded is identified by guid.
It is assumed object stored is a dictionary
returns:
dictionary containing referencecompressed sequences"""
tls = self.thread_local_session()
if (
rcs := tls.query(RefCompressedSeq.content)
.filter_by(sequence_id=guid)
.first()
):
return self.sjc.from_json(rcs.content)
else:
return None
def refcompressedsequence_read_many(self, guids: Iterable) -> Any:
"""loads objects identified by all members of guids from refcompressedseq collection.
It is assumed object stored is a dictionary
returns:
generator, which yields a tuple
(guid, referencecompressedsequence)
raises:
ValueError, if length of guids is > 1000
"""
if len(guids) > 1000:
raise ValueError("Maximum number of samples which can be sought is 1000")
tls = self.thread_local_session()
results = (
tls.query(RefCompressedSeq.sequence_id, RefCompressedSeq.content)
.filter(RefCompressedSeq.sequence_id.in_(guids))
.all()
)
for result in results:
yield (result.sequence_id, self.sjc.from_json(result.content))
def refcompressedsequence_read_all(self, internal_batch_size=5000) -> Any:
"""loads objects identified by all members of guids from refcompressedseq collection.
It is assumed object stored is a dictionary
parameters:
internal_batch_size: how many samples are loaded into ram at a time. Default should be fine unless low memory
returns:
generator, which yields a tuple
(guid, referencecompressedsequence)
"""
# sanity check
if internal_batch_size < 1:
raise ValueError("Internal batch size must be >= 1")
tls = self.thread_local_session()
seq_int_ids = [
seq_int_id
for seq_int_id, in tls.query(RefCompressedSeq.seq_int_id)
.order_by(RefCompressedSeq.seq_int_id)
.all()
]
start_position = 0
while start_position < len(seq_int_ids):
end_position = internal_batch_size + start_position - 1
if end_position >= len(seq_int_ids):
end_position = len(seq_int_ids) - 1
start_seq_int_id = seq_int_ids[start_position]
end_seq_int_id = seq_int_ids[end_position]
# load batch
results = (
tls.query(RefCompressedSeq.sequence_id, RefCompressedSeq.content)
.filter(RefCompressedSeq.seq_int_id >= start_seq_int_id)
.filter(RefCompressedSeq.seq_int_id <= end_seq_int_id)
.all()
)
for result in results:
yield (result.sequence_id, self.sjc.from_json(result.content))
# next batch
start_position = end_position + 1
def refcompressedsequence_guids(self) -> Set[str]:
"""loads guids from refcompressedseq collection."""
tls = self.thread_local_session()
return set(res.sequence_id for res in tls.query(RefCompressedSeq.sequence_id))
def guid_annotate(self, guid: str, nameSpace: str, annotDict: dict) -> None:
"""adds multiple annotations of guid from a dictionary;
all annotations go into a namespace.
updates the annotation if it exists"""
tls = self.thread_local_session()
if not isinstance(annotDict, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(annotDict))
)
# The reference compressed sequence must exist.
rcs = (
tls.query(RefCompressedSeq)
.filter(RefCompressedSeq.sequence_id == guid)
.one_or_none()
)
if rcs is None:
raise RDBMSError(
"Asked to annotate a record {0} but it does not exist".format(guid)
)
if nameSpace == "DNAQuality":
# coerce examination date to string
if "examinationDate" in annotDict:
rcs.examination_date = annotDict["examinationDate"]
if isinstance(annotDict["examinationDate"], datetime):
# convert to isoformat pre-jsonisation
annotDict["examinationDate"] = annotDict[
"examinationDate"
].isoformat()
if "propACTG" in annotDict:
rcs.prop_actg = annotDict["propACTG"]
annotations = json.loads(rcs.annotations) # what's there now
annotations[nameSpace] = annotDict # replace or add the new namespace
rcs.annotations = json.dumps(annotations).encode("utf-8")
try:
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def guids(self) -> Set[str]:
"""returns all registered guids"""
return self.refcompressedsequence_guids()
def guids_added_after_sample(self, guid: str) -> Set[str]:
"""returns all guids added after a sample"""
tls = self.thread_local_session()
rcs = (
tls.query(RefCompressedSeq.seq_int_id)
.filter(RefCompressedSeq.sequence_id == guid)
.one_or_none()
)
if rcs is None:
return None # does not exist
(this_seq_int_id,) = rcs # the sequence int id of the sample
retVal = []
for (guid,) in tls.query(RefCompressedSeq.sequence_id).filter(
RefCompressedSeq.seq_int_id > this_seq_int_id
):
retVal.append(guid)
return set(retVal)
def guids_considered_after(self, addition_datetime: datetime) -> Set[str]:
"""returns all registered guid added after addition_datetime
addition_datetime: a date of datetime class."""
tls = self.thread_local_session()
if not isinstance(addition_datetime, datetime):
raise TypeError(
"addition_datetime must be a datetime value. It is {0}. Value = {1}".format(
type(addition_datetime), addition_datetime
)
)
retVal = []
for (guid,) in tls.query(RefCompressedSeq.sequence_id).filter(
RefCompressedSeq.examination_date > addition_datetime
):
retVal.append(guid)
return set(retVal)
def _guids_selected_by_validity(self, validity: int) -> Set[str]:
"""returns registered guids, selected on their validity
0 = guid is valid
1 = guid is invalid
"""
tls = self.thread_local_session()
return set(
res.sequence_id
for res in tls.query(RefCompressedSeq.sequence_id).filter_by(
invalid=validity
)
)
def singletons(
self, method: str = "approximate", return_top: int = 1000
) -> pd.DataFrame:
"""
This method is not important in the RDBMS implementation of the fn3persistence store.
Returns:
An empty data frame.
"""
return pd.DataFrame()
def guids_valid(self) -> set:
"""return all registered valid guids.
Validity is determined by the contents of the DNAQuality.invalid field, on which there is an index"""
return self._guids_selected_by_validity(0)
def guids_invalid(self) -> set:
"""return all invalid guids
Validity is determined by the contents of the DNAQuality.invalid field, on which there is an index"""
return self._guids_selected_by_validity(1)
def guid_exists(self, guid: str) -> bool:
"""checks the presence of a single guid"""
tls = self.thread_local_session()
return (
tls.query(RefCompressedSeq.sequence_id).filter_by(sequence_id=guid).first()
is not None
)
def guid_valid(self, guid: str) -> int:
"""checks the validity of a single guid
Parameters:
guid: the sequence identifier
Returns
-1 The guid does not exist
0 The guid exists and the sequence is valid
1 The guid exists and the sequence is invalid
"""
tls = self.thread_local_session()
if (
res := tls.query(RefCompressedSeq.invalid)
.filter_by(sequence_id=guid)
.first()
):
if res.invalid == 0:
return 0
elif res.invalid == 1:
return 1
else:
raise ValueError(
"invalid is neither 1 nor 0 but {0}".format(res.invalid)
)
else:
return -1
def guid_examination_time(self, guid: str) -> Optional[datetime]:
"""returns the examination time for a single guid
Parameters:
guid: the sequence identifier
Returns either
The examination datetime value for this guid OR
None if the guid does not exist
"""
tls = self.thread_local_session()
if (
res := tls.query(RefCompressedSeq.examination_date)
.filter_by(sequence_id=guid)
.first()
):
return res.examination_date
else:
return None
def guids_considered_after_guid(self, guid: str) -> Set[str]:
"""returns all registered guids added after guid
guid: a sequence identifier"""
if addition_datetime := self.guid_examination_time(guid):
return self.guids_considered_after(addition_datetime)
else:
raise ValueError("guid is not valid: {0}".format(guid))
def guid_quality_check(
self, guid: str, cutoff: Union[float, int]
) -> Optional[bool]:
"""Checks whether the quality of one guid exceeds the cutoff.
If the guid does not exist, returns None.
If the guid does exist and has quality< cutoff, returns False.
Otherwise, returns True.
"""
tls = self.thread_local_session()
# test input
if not type(cutoff) in [float, int]:
raise TypeError(
"Cutoff should be either floating point or integer, but it is %s"
% type(cutoff)
)
if not type(guid) == str:
raise TypeError("The guid passed should be as string, not %s" % str(guid))
# recover record, compare with quality
res = tls.query(RefCompressedSeq).filter_by(sequence_id=guid).first()
if res is None: # no entry for this guid
return None
else:
# report whether it is larger or smaller than cutoff
return res.prop_actg >= cutoff
def _guid2seq(self, guidList: Optional[List[str]]) -> Iterable[RefCompressedSeq]:
"""returns the annotations, sequence_id and prop_actg from each RefCompressedSeq for each guid in guidList
If guidList is None, all items are returned.
"""
tls = self.thread_local_session()
if guidList is None: # rreturn everything
return tls.query(
RefCompressedSeq.sequence_id,
RefCompressedSeq.annotations,
RefCompressedSeq.prop_actg,
RefCompressedSeq.examination_date,
)
else:
return tls.query(RefCompressedSeq).filter(
RefCompressedSeq.sequence_id.in_(guidList)
)
def guid2item(
self, guidList: Optional[List[str]], namespace: str, tag: str
) -> dict:
"""returns the annotation (such as sequence quality, which is stored as an annotation)
in namespace:tag for all guids in guidlist.
If guidList is None, all items are returned.
An error is raised if namespace and tag is not present in each record.
"""
return {
res.sequence_id: json.loads(res.annotations)[namespace][tag]
for res in self._guid2seq(guidList)
}
def guid2ExaminationDateTime(self, guidList: Optional[List[str]] = None) -> dict:
"""returns quality scores and examinationDate for all guids in guidlist. If guidList is None, all results are returned."""
return {
res.sequence_id: res.examination_date for res in self._guid2seq(guidList)
}
def guid2quality(self, guidList: Optional[List[str]] = None) -> Optional[dict]:
"""returns quality scores for all guids in guidlist (or all samples if guidList is None)
potentially expensive query if guidList is None."""
return {res.sequence_id: res.prop_actg for res in self._guid2seq(guidList)}
def guid2propACTG_filtered(self, cutoff: Union[int, float] = 0) -> Dict[str, float]:
"""recover guids which have good quality, > cutoff.
These are in the majority, so we run a table scan to find these.
This query is potentially very inefficient- best avoided
"""
tls = self.thread_local_session()
query = tls.query(
RefCompressedSeq.sequence_id, RefCompressedSeq.prop_actg
).filter(RefCompressedSeq.prop_actg >= cutoff)
return {res.sequence_id: res.prop_actg for res in query}
def guid2items(
self, guidList: Optional[List[str]], namespaces: Optional[Set[str]]
) -> Dict[Any, Dict[str, Any]]:
"""returns all annotations in namespaces, which is a list
If namespaces is None, all namespaces are returned.
If guidList is None, all items are returned.
To do this, a table scan is performed - indices are not used.
"""
def select_namespaces(annotations: dict) -> dict:
if namespaces:
return {ns: annotations[ns] for ns in annotations.keys() & namespaces}
else:
return annotations
return {
res.sequence_id: select_namespaces(json.loads(res.annotations))
for res in self._guid2seq(guidList)
}
def guid_annotations(self) -> Optional[Dict[Any, Dict[str, Any]]]:
"""return all annotations of all guids"""
return self.guid2items(None, None) # no restriction by namespace or by guid.
def guid_annotation(self, guid: str) -> Optional[Dict[Any, Dict[str, Any]]]:
"""return all annotations of one guid"""
return self.guid2items([guid], None) # restriction by guid.
def guid2neighbour_add_links(
self,
guid: str,
targetguids: Dict[str, Dict[str, int]],
use_update: bool = False,
) -> Dict[str, int]:
"""adds links between guid and their neighbours ('targetguids')
Parameters:
guid: the 'source' guid for the matches eg 'guid1'
targetguids: what is guid linked to, eg
{
'guid2':{'dist':12},
'guid3':{'dist':2}
}
use_update - currently ignored, always False. Setting True yields NotImplementedError
This stores links in the guid2neighbour collection.
Returns:
The number of records written
Note:
uses bulk upload methodology to write fast, as some samples may have thousands or tens of thousands of neighbours
"""
load_list = []
for guid2, dist in targetguids.items():
load_list.append(
{"sequence_id_1": guid, "sequence_id_2": guid2, "dist": dist["dist"]}
)
load_list.append(
{"sequence_id_1": guid2, "sequence_id_2": guid, "dist": dist["dist"]}
)
load_df = pd.DataFrame.from_records(load_list)
if len(load_df.index) > 0:
self._bulk_load(load_df, "edge")
class Guid2NeighbourRepackRet(TypedDict):
guid: str
finished: str
pre_optimisation: dict
actions_taken: Dict[str, int]
def guid2neighbour_repack(
self, guid: str, always_optimise: bool = False, min_optimisable_size: int = 1
) -> Guid2NeighbourRepackRet:
"""In the mongo implementation, alters the mongodb representation of the links of guid.
In the rdbms implementation, this does nothing, and just returns a status report.
Parameters:
guid : the identifier of a sample to repack
always_optimise: consider for optimisation even if there are no 's' (single item) records
"""
return {
"guid": guid,
"finished": datetime.now().isoformat(),
"pre_optimisation": {
"s_records": 0,
"msg": "Repacking not necessary on RDBMS",
},
"actions_taken": {},
}
class Guid2NeighboursRet(TypedDict):
guid: str
neighbours: List[Guid2NeighboursFormats]
def guid2neighbours(
self, guid: str, cutoff: int = 20, returned_format: int = 2
) -> Guid2NeighboursRet:
"""returns neighbours of guid with cutoff <=cutoff.
Parameters:
guid: the sequence identifier
cutoff: a SNV distance cutoff
returned_format: see below.
Returns links either as
format 1 [[otherGuid, distance],[otherGuid2, distance2],...]
or as
format 2 [[otherGuid, distance, N_just1, N_just2, N_either],[],...]
or as
format 3 [otherGuid1, otherGuid2, otherGuid3]
or as
format 4 [{'guid':otherguid, 'snv':distance}]
Internally, the documents in guid2neighbour are of the form
{'guid':'guid1', 'rstat':'s', 'neighbours':{'guid2':{'dist':12, ...}}} OR
{'guid':'guid1', 'rstat':'m', 'neighbours':{'guid2':{'dist':12, ...}, 'guid3':{'dist':5, ...}} OR
{'guid':'guid1', 'rstat':'f', 'neighbours':{'guid2':{'dist':12, ...}, 'guid3':{'dist':5, ...}}
However, irrespective of their internal representation, this function always returns
exactly one item for each link of 'guid'; duplicates are not possible.
The last example occurs when the maximum number of neighbours permitted per record has been reached.
"""
def f(res):
otherGuid = res.sequence_id_2
dist = res.dist
if returned_format == 1:
return [otherGuid, dist]
elif returned_format == 2:
raise NotImplementedError("format 2 is no longer supported")
elif returned_format == 3:
return otherGuid
elif returned_format == 4:
return {"guid": otherGuid, "snv": dist}
else:
raise ValueError(
f"Unable to understand returned_format = {returned_format}"
)
tls = self.Session()
return {
"guid": guid,
"neighbours": [
f(res)
for res in tls.query(Edge)
.filter_by(sequence_id_1=guid)
.filter(Edge.dist <= cutoff)
],
}
def _set_lock_status(self, lock_int_id, lock_status, sequence_id="-NotSpecified-"):
"""locks or unlocks resources identified by lock_int_id, allowing cross- process sequential processing (e.g. insertion)
To lock, set lock_status =1 ; to unlock, set lock_status =0
To return the relevant row, set lock_status to None
See the acquire_lock() method for more details
returns:
If lock_status is either 1 or 0:
True if update succeeded, false if it did not
If lock_status is None:
the lock row, as an Sqlalchemy object, from which field values can be accessed by dot notation, e.g. retVal.lock_set_date, or retVal.lock_status
Technical notes:
https://docs.sqlalchemy.org/en/14/orm/session_transaction.html
https://www.amazon.com/Expert-Oracle-Database-Architecture-Thomas-dp-1430262982/dp/1430262982/ref=dp_ob_title_bk
"""
# make sure there is an entry for this lock
tls = self.Session()
lock_row = (
tls.query(FNLock).filter(FNLock.lock_int_id == lock_int_id).one_or_none()
)
# if the row doesn't exist, we add it, with the lock not set.
if lock_row is None:
try:
lock_row = FNLock(
lock_int_id=lock_int_id,
lock_status=0,
sequence_id=sequence_id,
lock_set_date=datetime.now(),
uuid=uuid.uuid4().hex,
)
tls.add(lock_row)
tls.commit()
except Exception:
tls.rollback()
raise
# analyse the record for this row
lock_row = (
tls.query(FNLock)
.filter(FNLock.lock_int_id == lock_int_id)
.with_for_update()
.one()
)
if lock_status is None:
retval = lock_row
elif lock_row.lock_status == 0 and lock_status == 0:
# it's already unlocked
retval = True
elif lock_row.lock_status == 1 and lock_status == 1:
# it's already locked and we're asked to acquire a lock. We can't.
retval = False
elif lock_row.lock_status == 0 and lock_status == 1:
# it's already unlocked, we can lock
lock_row.lock_status = 1
lock_row.lock_set_date = datetime.now()
lock_row.sequence_id = sequence_id
lock_row.uuid = uuid.uuid4().hex
retval = True
elif lock_row.lock_status == 1 and lock_status == 0:
# it's already locked, we can unlock
lock_row.lock_status = 0
lock_row.lock_set_date = datetime.now()
lock_row.sequence_id = "-NotSpecified-"
lock_row.uuid = uuid.uuid4().hex
retval = True
try:
tls.commit()
return retval
except Exception:
tls.rollback()
raise
def lock_details(self, lock_int_id):
"""returns details of the lock as a dictionary
Parameters:
lock_int_id: an integer identifier to the lock of interest
Returns:
None if there is no lock,
or a dictionary containing details of the lock held including sequence_id, lock_status, lock_set_date, and uuid"""
res = self.lock_status(lock_int_id)
if res.lock_status == 0:
return None
else:
return dict(
sequence_id=res.sequence_id,
lock_set_date=res.lock_set_date,
uuid=res.uuid,
)
def lock_status(self, lock_int_id):
"""determine whether a database-based lock is open (0) or closed (1).
Parameters:
lock_int_id: an integer identifier to the lock of interest
Returns:
a sqlalchemy object containing the lock row"""
return self._set_lock_status(lock_int_id, None)
def lock(self, lock_int_id, sequence_id):
"""obtains a database-based lock.
Parameters:
lock_int_id: an integer identifier to the lock of interest
sequence_id: the id (typically guid) of the sequence being added. Used if the inserting process crashes
Returns:
True if the lock is acquired
False if it is not"""
return self._set_lock_status(lock_int_id, 1, sequence_id)
def unlock(self, lock_int_id, force=False):
"""obtains a database-based lock.
Parameters:
lock_int_id: an integer identifier to the lock of interest
force: if True, will unlock irrespective of current status, returning True
Returns:
True if the lock is acquired
False if it is not"""
res = self._set_lock_status(lock_int_id, 0)
if force:
return True
else:
return res
| #!/usr/bin/env python
""" provides a storage layer for meta-data and snv distances from the
findneighbour4 system in a RDBMS
Tested with:
- Oracle Autonomous (ATP and ADW cloud service)
- Sqlite (but, sqlite can't be used as a server backend)
Not tested:
MS SQL server, PostgreSQL
Tested but doesn't work at present
MySQL - the issue is with storage of character large objects in TEXT fields. The SQL alchemy version used make TEXT, not LARGETEXT fields.
- Workarounds described https://stackoverflow.com/questions/47644739/what-column-type-does-sqlalchemy-use-for-text-on-mysql did not fix this
- probably a soluble problem
- tested with MySQL 8 on Ubuntu 20. Connection string was "mysql://root:root@localhost:3306/test_db" with user/password root
A component of the findNeighbour4 system for bacterial relatedness monitoring
Copyright (C) 2021 David Wyllie david.wyllie@phe.gov.uk
repo: https://github.com/davidhwyllie/findNeighbour4
This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License as published
by the Free Software Foundation. See <https://opensource.org/licenses/MIT>, and the LICENSE file.
"""
# import gc
import bson # type: ignore
from datetime import datetime, timedelta, date
import hashlib
import os
import json
import pandas as pd
import psutil
import logging
import numpy as np
import warnings
import uuid
import cx_Oracle
from sentry_sdk import capture_exception
import progressbar
from sqlalchemy import (
Integer,
Column,
Float,
MetaData,
Text,
String,
DateTime,
Identity,
Index,
TIMESTAMP,
func,
create_engine,
inspect,
)
# from sqlalchemy.pool import NullPool
from findn.seq2json import SeqDictConverter
from sqlalchemy.sql.expression import desc
from sqlalchemy.orm import (
sessionmaker,
scoped_session,
)
from sqlalchemy.ext.declarative import declarative_base
from typing import (
Any,
Dict,
Iterable,
List,
NoReturn,
Optional,
Set,
TypedDict,
Union,
)
Guid2NeighboursFormat1 = List[Union[str, int]]
Guid2NeighboursFormat3 = Union[str]
Guid2NeighboursFormat4 = Dict[str, Union[str, int]]
Guid2NeighboursFormats = Union[
Guid2NeighboursFormat1, Guid2NeighboursFormat3, Guid2NeighboursFormat4
]
class RecentDatabaseMonitoringRet(TypedDict, total=False):
recompression_data: bool
latest_stats: Dict[str, Union[int, np.float64]]
trend_stats: List[Dict[str, Any]]
# global: definition of database structure
# classes mapping to persistence database inherit from this
db_pc = declarative_base() # global
metadata = MetaData()
class RDBMSError(Exception):
"""a general purpose error used by the rdbms module."""
pass
## define schema
class BulkLoadTest(db_pc):
"""used only for testing bulk uploads as part of unit testing"""
__tablename__ = "fn4_bulk_load_test"
blt_int_id = Column(Integer, Identity(start=1), primary_key=True)
bulk1 = Column(Integer)
bulk2 = Column(Integer)
class FNLock(db_pc):
"""used for storing details of one or more classes of lock"""
__tablename__ = "fn4lock"
lock_int_id = Column(
Integer,
primary_key=True,
comment="an integer reflecting the kind of lock studied",
)
sequence_id = Column(
String(60),
comment="the sample_id represented by the entry; sample_ids are typically guids",
)
lock_set_date = Column(
TIMESTAMP, index=True, comment="the date and time the lock was modified"
)
uuid = Column(String(32))
lock_status = Column(
Integer, comment="whether the lock is in place (1) or not in place (0)"
)
class Config(db_pc):
"""stores config data"""
__tablename__ = "config"
cfg_int_id = Column(Integer, Identity(start=1), primary_key=True)
config_key = Column(String(56), index=True, unique=True)
config_value = Column(Text(50000000)) # 50M limit. Required for Mysql
class RefCompressedSeq(db_pc):
"""stores reference compressed sequences, which are large character objects, and their annotations.
Note: the mongodb equivalent is the GridFS meta-collection refcompressedseq and the standard collection guid2meta.
"""
__tablename__ = "refcompressedseq"
seq_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sequence_id = Column(
String(60),
index=True,
unique=True,
comment="the sample_id represented by the entry; sample_ids are typically guids",
)
examination_date = Column(
TIMESTAMP,
index=True,
comment="the date and time the record was examined and compressed",
)
annotations = Column(
Text, comment="a json string, representing metadata about the sequence"
)
invalid = Column(
Integer,
default=-1,
index=True,
comment="whether the sequence is of sufficient quality to be analysed (invalid = 0) or is not (invalid = 1). Part of the annotations, but extracted into separate field for indexing.",
)
prop_actg = Column(
Float,
index=True,
comment="the proportion of A,C,G,T (as opposed to N,-, or IUPAC codes). Part of the annotations, but extracted into separate field for indexing.",
)
content = Column(
Text, comment="a json string, representing the reference compressed sequence"
)
class Edge(db_pc):
"""represents a pair of RefCompressedSeq which are similar. Table is called 'edge' because it represents an edge in a network in which the vertices are RefCompressedSequences.
Note
- that an edge A -> B is represented twice in this data representation: as A -> B, and as B -> A.
- This means that all the edges of A can be obtained by
statements such as SELECT * from Edge where seq_int_id_1 = 217, where 217 is the seq_int_id of sequence A.
- if insertion is fast enough, we could enable foreign key constraints here.
- it is likely that insert speed will be the main determinant of server speed
- and the faster the inserts work the better.
- in the mongo implementation, FK constraints are not implemented, and the relationships are guaranteed by application logic, not at a database level .
At present, this approach is being used here too.
"""
__tablename__ = "edge"
edge_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sequence_id_1 = Column(
String(60),
comment="One of a pair of sequences. Note: foreign key constraint not enforced at a database level",
)
sequence_id_2 = Column(
String(60),
comment="One of a pair of sequences. Note: foreign key constraint not enforced at a database level ",
)
dist = Column(Integer, comment="the SNV distance between sequences")
Index("ix_Edge_1", Edge.sequence_id_1, unique=False, oracle_compress=1)
class Cluster(db_pc):
"""stores clusters, which are large character objects (json)"""
__tablename__ = "sequence_cluster"
cl_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
cluster_build_id = Column(
String(40),
index=True,
comment="an identifier for the contents; this is typically a sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="a json string describing the cluster")
class Monitor(db_pc):
"""stores monitor entries, which are large character objects (html)"""
__tablename__ = "monitor"
mo_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
mo_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
content = Column(Text, comment="html data")
class ServerMonitoring(db_pc):
"""stores server monitoring entries, which are large character objects (json)"""
__tablename__ = "server_monitoring"
sm_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
sm_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="a json dictionary including ")
class MSA(db_pc):
"""stores multisequence alignments, which are large character objects (json)"""
__tablename__ = "msa"
msa_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
msa_id = Column(
String(60),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="character large object containing a json string")
class TreeStorage(db_pc):
"""stores trees and related data, which are large character objects (json)"""
__tablename__ = "tree"
ts_int_id = Column(
Integer,
Identity(start=1),
primary_key=True,
comment="the primary key to the table",
)
ts_id = Column(
String(40),
index=True,
unique=True,
comment="an identifier for the contents; this is typically and sha-1 hash on the contents",
)
upload_date = Column(
DateTime, index=True, comment="the time the record was inserted"
)
content = Column(Text, comment="character large object containing a json string")
class NPEncoder(json.JSONEncoder):
"""encodes Numpy and datetime types as jsonisable equivalents"""
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
else:
return super(NPEncoder, self).default(obj)
class fn3persistence_r:
"""System for persisting results from large numbers of sequences stored in FindNeighbour 3+.
Uses a generic rdbms, with optimisations for Oracle databases when using the cx_oracle package.
the associated schema is defined using SQLalchemy tables, as above.
Note that parts of this code are taken from the class pcadb.PCADatabaseManager.
In future, it may be possible to integrate this class with that, if successful
implementation of findNeighbour4 functionality using an RDBMS is possible
See also the Persistence class in the persistence module.
This provides an API which will either use this class, or the mongo based fn3persistence class, depending on
software settings.
"""
def __init__(
self, connection_config, debug=0, server_monitoring_min_interval_msec=0
):
"""creates the RDBMS connection
Parameters
-----------
connection_config:
One of
1. a key to a dictionary containing one or more database configuration details: (e.g. 'prod', 'test')
2. a valid sqlalchemy database connection string (if this is sufficient for connections) e.g. 'pyodbc+mssql://myserver'
3. None. This is considered to mean 'sqlite://' i.e. an in memory sqlite database, which is not persisted when the program stops.
if it is not none, a variable called DB_CONNECTION_CONFIG_FILE must be present. This must point to a file containing credentials.
the name of an environment variable containing (in json format) a dictionary, or None if it is not required.
An example of such a dictionary is as below:
{
'prod':{'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite:///db/proddb.sqlite'}
'dev': {'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite:///db/devdb.sqlite'},
'test':{'DBTYPE':'sqlite', 'ENGINE_NAME':'sqlite://'}
}
The DBTYPE and ENGINE_NAME keys are essential.
Other keys may also be present, and are required in some cases (for example by Oracle connections).
{
'prod':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
},
'dev':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
}
}
Note, the bit after the @(description describes where your database is, and will be found in your cloud wallet, if you are using cloud databases. See below.
In this case, TNS_ADMIN is the value you wish the TNS_ADMIN environment variable to be set to.
The software will set TNS_ADMIN, and, if you are using a virtual environment, it will be scoped to the virtual environment.
In summary, it will configure necessary settings to allow Oracle database connections.
Note, if you are using a python virtual environment, this environment variable should be included in the .env file in the root of your project. The .env file should not be under source control.
configuration engine_name: an SQLalchemy connect string, e.g. sqlite::// for temporary memory db, see https://docs.sqlalchemy.org/en/13/core/engines.html
debug: if True, deletes any existing data on startup.
show_bar: show a progress bar during long operations
NOTE:
This software has been tested with
(i) Sqlite 3.3.2+
(ii) Oracle Autonomous Database (cloud)
https://blogs.oracle.com/oraclemagazine/getting-started-with-autonomous
To connect to Oracle there are several steps.
0. Install dependencies, see
https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html
wget https://download.oracle.com/otn_software/linux/instantclient/211000/instantclient-basic-linux.x64-21.1.0.0.0.zip
need to set the LD_LIBRARY_PATH variable, see
https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html
e.g. export LD_LIBRARY_PATH=/data/software/instantclient_21_1:LD_LIBRARY_PATH
these parameters have to go into the python .env file e.g.
----------------------------------------------------------------
LD_LIBRARY_PATH="/software/instantclient_21_1"
PCADB_CONNECTION_CONFIGFILE="/secret/config.json"
Where config.json looks like
{
'prod':{'DBTYPE':'oracle',
'ENGINE_NAME':''oracle+cx_oracle://PROD:97bxxxxxxxxX@(description: .........)))',
'TNS_ADMIN':'/secrets/oracle/pca_prod'
}
}
** NOTE: as per normal json conventions, escape quotes (i.e. \" not " around the certificate name, otherwise SSL connections will fail) **
1. Download your OCI wallet, & unzip it somewhere
2. Set the TNS_ADMIN env var to point to this directory
3. Edit the WALLET_LOCATION in the sqlnet.ora file to point to the relevant directory, e.g. WALLET_LOCATION = (SOURCE = (METHOD = file) (METHOD_DATA = (DIRECTORY="/data/credentials/oci_test")))
4. Create a user with relevant privileges see below)
5. Set the OCI_ENGINE_NAME env var.
An example of this is as below (redacted so not live)
oracle+cx_oracle://scott:tigerX22@(description= (retry_count=20)(retry_delay=3)(address=(protocol=tcps)(port=1522)(host=host.oraclecloud.com))(connect_data=(service_name=redacted))(security=(ssl_server_cert_dn="redacted")))
This data can be found in the tnsnames.ora file: for details, see
https://docs.sqlalchemy.org/en/14/dialects/oracle.html#dialect-oracle-cx_oracle-connect
https://stackoverflow.com/questions/37471892/using-sqlalchemy-dburi-with-oracle-using-external-password-store
https://stackoverflow.com/questions/14140902/using-oracle-service-names-with-sqlalchemy/35215324
https://blogs.oracle.com/sql/how-to-create-users-grant-them-privileges-and-remove-them-in-oracle-database
https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/GRANT.html#GUID-20B4E2C0-A7F8-4BC8-A5E8-BE61BDC41AC3
Configuring interactions with external OCI databases
====================================================
Your application will need to run as a user (we'll call it PCADB) will need some priviledges granted.
The exact privileges required involving creating, dropping tables & indexes, as well as inserting and deleting data.
CREATE USER PCADB IDENTIFIED BY 'MyPassword1234!';
GRANT CONNECT TO PCADB;
GRANT CREATE SESSION TO PCADB;
GRANT CREATE SEQUENCE TO PCADB;
GRANT CREATE TABLE TO PCADB;
GRANT CREATE SYNONYM TO PCADB;
ALTER USER PCADB DEFAULT TABLESPACE DATA quota unlimited on DATA;
"""
self.sjc = SeqDictConverter()
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
self.debug = debug
self.storage_technology = "rdbms"
self.logger.info("Storage technology is {0}".format(self.storage_technology))
self.server_monitoring_min_interval_msec = server_monitoring_min_interval_msec
self.previous_server_monitoring_data = {}
self.previous_server_monitoring_time = None
# connect and create session. Validate inputs carefully.
if connection_config is None:
self.logger.info("Connection config is None: using in-memory sqlite.")
self.engine_name = "sqlite://"
elif "://" in connection_config:
# it's not None, and we assume what we are provided is an sqlalchemy database connection string
self.logger.info(
"Connection config provided; using {0}".format(connection_config)
)
self.engine_name = connection_config
else:
# we have been passed a token. this should be a key to a dictionary, stored in
# DB_CONNECTION_CONFIG_FILE which contains credentials
conn_detail_file = None
try:
conn_detail_file = os.environ["DB_CONNECTION_CONFIG_FILE"]
except KeyError:
raise RDBMSError(
"Environment variable DB_CONNECTION_CONFIG_FILE does not exist; however, it is required. If you are using a python virtual environment, you need to set it in .env, not globally"
)
if conn_detail_file is None:
# we failed to set it
raise RDBMSError(
"Tried to set conn_detail_file from environment variable DB_CONNECTION_CONFIG_FILE, but it is still None."
)
if not os.path.exists(conn_detail_file):
raise FileNotFoundError(
"Connection file specified but not found: {0}".format(
conn_detail_file
)
)
# read the config file
with open(conn_detail_file, "rt") as f:
conn_detail = json.load(f)
if connection_config not in conn_detail.keys():
raise RDBMSError(
"Connection {0} does not correspond to one of the keys {1} of the configuration json file at {2}".format(
connection_config, conn_detail.keys(), conn_detail_file
)
)
# configure engine
this_configuration = conn_detail[
connection_config
] # extract the relevant part of the config dictionary
# two keys are always present
essential_keys = set(["DBTYPE", "ENGINE_NAME"])
if len(essential_keys - set(this_configuration.keys())) > 0:
raise RDBMSError(
"Provided keys for {0} are not correct. Required are {1}".format(
connection_config, essential_keys
)
)
# if it's Oracle, then three keys are required.
if this_configuration["DBTYPE"] == "oracle":
essential_keys = set(["DBTYPE", "ENGINE_NAME", "TNS_ADMIN"])
if len(essential_keys - set(this_configuration.keys())) > 0:
raise RDBMSError(
"Provided keys for oracle db in {0} are not correct. Required are {1}".format(
connection_config, essential_keys
)
)
# set the TNS_ADMIN variable.
self.logger.info(
"Set TNS_ADMIN to value specified in config file {0}".format(
this_configuration["TNS_ADMIN"]
)
)
os.environ["TNS_ADMIN"] = this_configuration["TNS_ADMIN"]
self.logger.info("Set ENGINE_NAME configuration string from config file.")
self.engine_name = this_configuration["ENGINE_NAME"]
self.using_sqlite = self.engine_name.startswith("sqlite://")
# now we can start
self.Base = db_pc
self.logger.info("DatabaseManager: Connecting to database")
self.is_oracle = "oracle+cx" in self.engine_name
self.is_sqlite = "sqlite://" in self.engine_name
self.show_bar = True # maybe define a method to switch this off
self._create_engine()
self.logger.info(
"DatabaseManager: Database connection made; there are {0} tables. Oracle database = {1}".format(
len(self._table_names()), self.is_oracle
)
)
self.Base.metadata.create_all(
bind=self.engine
) # create the table(s) if they don't exist
# create thread-local sessions, see https://docs.sqlalchemy.org/en/14/orm/contextual.html#using-custom-created-scopes
session_factory = sessionmaker(bind=self.engine)
# this object will call session factory when we create/request a thread local session
# e.g. thread_local_session = self.Session()
self.Session = scoped_session(session_factory)
# drop existing tables if in debug mode
# delete any pre-existing data if we are in debug mode.
if debug == 2:
logging.warning(
"Debug mode operational [DEBUG={0}]; deleting all data from tables.".format(
debug
)
)
self._delete_existing_clustering_data()
self._delete_existing_data()
else:
self.logger.info("Using stored data in rdbms")
def _create_engine(self):
"""create database connection engine"""
if self.is_oracle:
# it is important to set arraysize, see
# https://docs.sqlalchemy.org/en/14/dialects/oracle.html
# https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#tuningfetch
# but if you set it too large you can get DPI-1015 (allocated cursor size > 2G) see
# https://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html
# to disable connection pooling
# https://docs.sqlalchemy.org/en/14/core/pooling.html#switching-pool-implementations
# self.engine = create_engine(
# self.engine_name, arraysize=1000000,
# poolclass=NullPool
# ) # fetch results in batches of 1m.
self.engine = create_engine(
self.engine_name, arraysize=1000000
) # fetch results in batches of 1m.
logging.info("Created engine connecting to Oracle database")
else:
# sqlalchemy generic pool manager, for non-Oracle databases
self.engine = create_engine(self.engine_name)
# oracle pool manager code
# use cx_Oracle pool manager
# u, p, dsn = self.oracle_connstring_parts(self.engine_name)
# self.oracle_pool = cx_Oracle.SessionPool(
# user = u,
# password = p,
# dsn = dsn,
# min = 4,
# max = 4,
# encoding="UTF-8",
# nencoding="UTF-8"
# )
# self.engine = create_engine("oracle://", creator = self.oracle_pool.acquire, poolclass = NullPool)
def closedown(self):
"""closes the session(s) & disposes of any engine.
Is required for unit testing"""
try:
self.engine.dispose()
except AttributeError as e:
# the class may not have an engine object attached, generates an AttributeError
pass
logging.info(
"Failed to dispose of engine during closedown(). AttributeError logged to sentry"
)
capture_exception(e)
except Exception as e1:
logging.warning(
"Failed to dispose of engine during closedown(). Error logged to sentry"
)
capture_exception(e1)
def no_progressbar(self):
"""don't use progress bars"""
self.show_bar = False
def _table_names(self):
"""returns table names in the schema.
If the schema's contents have not been created, returns an empty list"""
return inspect(self.engine).get_table_names()
def thread_local_session(self, n_retries=3, simulate_failure="no", log_errors=True):
"""generates, or selects a thread local session from a session factory or pool.
For context, see https://docs.sqlalchemy.org/en/13/orm/contextual.html
Checks that the session recovered from the session pool is still valid, since they can time out.
If it is timed out, tries another. Will retry up to n_retries times.
Parameters:
n_retries: the number of attempts which will be made to generate a functional connection.
simulate_failure: simulates the failure of a connection (closes the connection before returning it) - used only for unittesting. Valid values:
'no' : normal operation
'once': fail once
'always': fail every time, even on repeated attempts to connect
log_errors: logs any errors to sentry & error log (recommended)"""
tries = n_retries
while tries > 0:
tries = tries - 1
tls = self.Session()
# simulate failure if required to do so
if (simulate_failure == "once" and tries - 1 == n_retries) or (
simulate_failure == "always"
):
tls = (
None # not a session object. Attempts to use it as such will fail.
)
# test whether it is working
try:
tls.query(Config).filter_by(
config_key="config"
).first() # try to connect
# if execution continues here, the session works
return tls
except Exception as e1:
logging.info(
"Failed to connect on trial {0}/{1}; error raised was {2}. Recreating engine".format(
n_retries - tries, n_retries, e1
)
)
if log_errors:
capture_exception(e1)
logging.error(e1)
# try to remove the failing session, if it has been constructed properly
try:
self.engine.dispose()
tls.close()
except Exception:
logging.info("Failed to remove session and dispose of engine")
# succeeded in disposing of existing engine; try reconnecting
self._create_engine()
# could not connect despite multiple attempts.
raise RDBMSError(
"Could not connect to database. Tried {0} times with different sessions despite recreating database connection".format(
n_retries
)
)
def _drop_existing_tables(self):
"""empties, but does not drop, any existing tables"""
self.Base.metadata.create_all(
self.engine
) # create the table(s) if they don't already exist
BulkLoadTest.__table__.drop(self.engine)
Config.__table__.drop(self.engine)
Edge.__table__.drop(self.engine)
Cluster.__table__.drop(self.engine)
Monitor.__table__.drop(self.engine)
ServerMonitoring.__table__.drop(self.engine)
MSA.__table__.drop(self.engine)
TreeStorage.__table__.drop(self.engine)
RefCompressedSeq.__table__.drop(self.engine)
remaining = len(self._table_names())
if remaining > 0:
warnings.warn(
"Failed to remove all tables in the database. Is this database being used by another program? The following remain: {0}".format(
self._table_names()
)
)
return
def oracle_connstring_parts(self, connstring):
"""splits an oracle connection string into username, password and DSN"""
if connstring.startswith("oracle+cx_oracle://"):
e1 = self.engine_name.replace("oracle+cx_oracle://", "")
up, dns = e1.split("@")
u, p = up.split(":")
return u, p, dns
else:
return None
def _bulk_load(self, upload_df, target_table, max_batch=100000):
"""bulk uploads pandas dataframes.
If using an oracle database, uses Oracle's cx-oracle package to bulk upload data
upload_df: a pandas dataframe. Names **much match** the table target_table
target_table: the name of the table to upload into
(note: this is not the name of the class in the table definition, it's the name of the table in the SQL)
Returns:
number of items uploaded (integer)
Background:
- ORM is slow for large inserts
- Oracle is not currently supported by pandas .to_sql method='multi', so a bespoke method is needed
- Need custom code for bulk loading to Oracle. Methods are provided in the cx_oracle package, see
https://cx-oracle.readthedocs.io/en/latest/user_guide/batch_statement.html
The maximum size that can be transmitted to the Oracle server is 2G.
If this happens, a cx_Oracle.DatabaseError
is raised with result DPI-1015. R Code to prevent this by auto-setting max_batch is provided.
"""
# verify data : ensure that target_table is a table [Essential: otherwise, can be a vector for SQL injection]
if target_table not in self._table_names():
raise ValueError(
"target_table {0} does not exist: valid tables are {1}".format(
target_table, self._table_names()
)
)
# check that upload_df is pandas dataframe
if not isinstance(upload_df, pd.DataFrame):
raise TypeError(
"upload_df needs to be pandas DataFrame, not a {0}".format(
type(upload_df)
)
)
# check that we have been passed data
ncol = len(upload_df.columns)
if ncol == 0:
# we treat this as an error
raise RDBMSError(
"Passed data frame to _bulk_upload to {0} contains no columns {1}".format(
target_table, upload_df
)
)
self.logger.info("Bulk upload to {0} started".format(target_table))
if self.is_sqlite:
# there is a max variable limit of 32,766 for Sqlite 3.32.0 on https://www.sqlite.org/limits.html
# set max_batch to keep below this.
max_batch = int(32000 / ncol)
self.logger.info(
"Autoset max_batch to {0}, as running SQLite".format(max_batch)
)
if self.is_oracle:
# ************* commit via cx_Oracle bulk upload syntax ****************
# parse the engine_name into dsn, database & password
u, p, dsn = self.oracle_connstring_parts(self.engine_name)
# get into the right format for loading: note: holds all data in ram
loadvar = list(upload_df.itertuples(index=False, name=None))
ncol = len(upload_df.columns.to_list())
# estimate the maximum buffer size required and auto-reduce the max_batch if required.
estimated_row_size = len(str(loadvar[0]))
estimated_max_batch = int(
1e7 / (estimated_row_size)
) # large margin of safety 10M batch size
if estimated_max_batch < max_batch:
max_batch = estimated_max_batch
self.logger.info(
"Reduced max_batch to keep estimated buffer size within acceptable limits (<= 10M target). max_batch is {0}".format(
max_batch
)
)
# construct sql statment.
# Should be injection-safe; we have checked the target_table is a table, and are incorporating integers and verified strings only.
collabels = [":" + str(x + 1) for x in list(range(ncol))]
insert_cols = ",".join(collabels)
target_cols = ",".join(upload_df.columns.to_list())
sql_statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(
target_table, target_cols, insert_cols
)
start_n = len(loadvar)
if self.show_bar:
bar = progressbar.ProgressBar(max_value=start_n)
with cx_Oracle.connect(user=u, password=p, dsn=dsn) as conn:
cursor = conn.cursor()
while len(loadvar) > 0:
if self.show_bar:
bar.update(start_n - len(loadvar))
try:
cursor.executemany(sql_statement, loadvar[0:max_batch])
loadvar = loadvar[max_batch:]
conn.commit()
except Exception:
conn.rollback()
raise
if self.show_bar:
bar.finish()
else:
# ***************************** ALL DATABASES OTHER THAN ORACLE ************************
# note: there may be limits to the complexity of the statement permitted: a maximum number of parameters.
# therefore, we do this in batches as well.
start_n = len(upload_df.index)
if self.show_bar:
bar = progressbar.ProgressBar(max_value=start_n)
while len(upload_df.index) > 0:
self.logger.info(
"Bulk upload of {0} : {1} remain".format(
target_table, len(upload_df)
)
)
to_upload = upload_df.head(n=max_batch)
to_upload.to_sql(
target_table,
self.engine,
if_exists="append",
index=False,
method="multi",
) # pandas method
upload_df = upload_df.iloc[max_batch:]
if self.show_bar:
bar.update(start_n - len(upload_df.index))
self.logger.info("Bulk upload to {0} complete".format(target_table))
if self.show_bar:
bar.finish()
return len(upload_df.index)
def delete_server_monitoring_entries(self, before_seconds: int) -> None:
"""deletes server monitoring entries more than before_seconds ago"""
try:
tls = self.thread_local_session()
earliest_allowed = datetime.now() - timedelta(seconds=before_seconds)
tls.query(ServerMonitoring).filter(
ServerMonitoring.upload_date < earliest_allowed
).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def summarise_stored_items(self) -> Dict[str, Any]:
"""counts how many sequences exist of various types"""
return {}
def connect(self) -> None:
"""test whether the database is connected, and if not, tries to connect.
Does nothing here, just a stub."""
pass
def rotate_log(self) -> None:
"""forces rotation of the mongo log file; a stub here, does nothing"""
pass
def raise_error(self, token: str) -> NoReturn:
"""raises a ZeroDivisionError, with token as the message.
useful for unit tests of error logging"""
raise ZeroDivisionError(token)
def _delete_existing_data(self) -> None:
"""deletes existing data from the databases"""
try:
tls = self.thread_local_session()
tls.query(Config).delete()
tls.query(Edge).delete()
tls.query(RefCompressedSeq).delete()
tls.query(Monitor).delete()
tls.query(ServerMonitoring).delete()
tls.query(BulkLoadTest).delete()
tls.query(Cluster).delete()
tls.query(MSA).delete()
tls.query(TreeStorage).delete()
tls.query(FNLock).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
def _delete_existing_clustering_data(self) -> None:
"""deletes any clustering data from the databases"""
try:
tls = self.thread_local_session()
tls.query(Cluster).delete()
tls.query(MSA).delete()
tls.query(TreeStorage).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def first_run(self) -> bool:
"""if there is no config entry, it is a first-run situation"""
tls = self.thread_local_session()
row = tls.query(Config).filter_by(config_key="config").first()
return row is None
def __del__(self) -> None:
"""closes any session"""
self.closedown()
def memory_usage(self) -> Dict[str, Union[int, float]]:
"""returns memory usage by current python3 process
Uses the psutil module, as the resource module is not available in windows.
"""
memdict = psutil.virtual_memory()._asdict()
sm = {"server|mstat|" + k: v for k, v in memdict.items()}
return sm
# methods for the config collection
def config_store(self, key: str, object: Dict[str, Any]) -> Any:
"""stores object into config collection
It is assumed object is a dictionary
"""
if not isinstance(object, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(object))
)
tls = self.thread_local_session()
if row := tls.query(Config).filter_by(config_key=key).first():
row.config_value = json.dumps(object, cls=NPEncoder).encode("utf-8")
else:
try:
row = Config(
config_key=key,
config_value=json.dumps(object, cls=NPEncoder).encode("utf-8"),
)
tls.add(row)
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def config_read(self, key: str) -> Any:
"""loads object from config.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
row = tls.query(Config).filter_by(config_key=key).first()
if row is None:
return None
else:
return dict(_id=key, **json.loads(row.config_value))
# methods for the server and database monitoring
def recent_database_monitoring(
self, max_reported: int = 100
) -> RecentDatabaseMonitoringRet:
"""computes trends in the number of records holding pairs (guid2neighbours) vs. records.
This ratio is a measure of database health. Ratios > 100 indicate the database may become very large, and query slowly"""
return {"recompression_data": False, "latest_stats": {"storage_ratio": 1}}
def _to_string(self, x=[str, bytes]) -> str:
"""returns a string version of x; if x is bytes, returns a string, assuming utf-8 encoding
This function is required because some databases return bytes objects
from 'text' fields (like sqlite) while others return str objects (like oracle)
"""
if isinstance(x, bytes):
return x.decode("utf-8")
else:
return x
def recent_server_monitoring(
self,
max_reported: int = 100,
selection_field: Optional[str] = None,
selection_string: Optional[str] = None,
) -> List[dict]:
"""returns a list containing recent server monitoring, in reverse order (i.e. tail first).
The _id field is an integer reflecting the order added. Lowest numbers are most recent.
Inputs
max_reported - return this number of lines, at most.
selection_field - if not None, will only return lines containing selection_string
in the 'selection_field' key of the returned dictionary.
selection_string -if selection_field is not None, only returns rows if
selection_string is present in the 'selection_field' key of the
monitoring element. If None, this constraint is ignored.
"""
if not isinstance(max_reported, int):
raise TypeError(
f"limit must be an integer, but it is a {type(max_reported)}"
)
if not max_reported >= 0:
raise ValueError("limit must be more than or equal to zero")
if max_reported == 0:
return []
def row_to_dict(res: ServerMonitoring) -> dict:
d = json.loads(res.content)
d["_id"] = res.sm_int_id
if selection_field is None:
return d
else:
if d[selection_field] == selection_string:
return d
else:
return None
tls = self.thread_local_session()
return [
d
for res in tls.query(ServerMonitoring)
.order_by(desc(ServerMonitoring.sm_int_id))
.limit(max_reported)
for d in (row_to_dict(res),)
if d is not None
]
def server_monitoring_store(
self,
message: str = "No message provided",
what: Optional[str] = None,
guid: Optional[str] = None,
content: Dict[str, Any] = {},
) -> bool:
"""stores content, a dictionary, into the server monitoring log"""
if not isinstance(content, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(content))
)
tls = self.thread_local_session()
now = dict(content)
if what is not None:
now["content|activity|whatprocess"] = what
if guid is not None:
now["content|activity|guid"] = guid
now["context|info|message"] = message
current_time = datetime.now()
now["context|time|time_now"] = str(current_time.isoformat())
now["context|time|time_boot"] = datetime.fromtimestamp(
psutil.boot_time()
).strftime("%Y-%m-%d %H:%M:%S")
# should we write this data? We have the option not to log all messages, to prevent the store getting very full.
write_content = False
if self.previous_server_monitoring_time is None:
# yes if this is the first record written.
write_content = True
else:
time_since_last_write = current_time - self.previous_server_monitoring_time
# yes if it's after the previous_server_monitoring_time in milliseconds
t = (
1000 * float(time_since_last_write.seconds)
+ float(time_since_last_write.microseconds) / 1000
)
if t >= self.server_monitoring_min_interval_msec:
write_content = True
if write_content:
try:
json_now = json.dumps(now).encode("utf-8")
row = ServerMonitoring(
sm_id=hashlib.sha1(json_now).hexdigest(),
upload_date=current_time,
content=json_now,
)
tls.add(row)
self.previous_server_monitoring_time = current_time
self.previous_server_monitoring_data = now
tls.commit()
# finished
return True
except Exception:
tls.rollback()
raise
else:
return False
# methods for monitor, which store the contents of an html file
# in a gridFS store.
def monitor_store(self, monitoring_id: str, html: str) -> str:
"""stores the monitor output string html. Overwrites any prior object."""
if not isinstance(html, str):
raise TypeError("Can only store string objects, not {0}".format(type(html)))
try:
tls = self.thread_local_session()
tls.query(Monitor).filter_by(mo_id=monitoring_id).delete()
row = Monitor(mo_id=monitoring_id, content=html.encode("utf-8"))
tls.add(row)
tls.commit()
# finished
except Exception:
tls.rollback()
def monitor_read(self, monitoring_id: str) -> Optional[str]:
"""loads stored string (e.g. html object) from the monitor collection."""
tls = self.thread_local_session()
if res := tls.query(Monitor).filter_by(mo_id=monitoring_id).first():
return self._to_string(res.content)
else:
return None
# methods for multisequence alignments
def msa_store(self, msa_token: str, msa: dict) -> Optional[str]:
"""stores the msa object msa under token msa_token."""
tls = self.thread_local_session()
if not isinstance(msa, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(msa))
)
# we don't replace. These entries are write once.
if tls.query(MSA).filter_by(msa_id=msa_token).one_or_none() is None:
try:
res = MSA(
msa_id=msa_token,
upload_date=datetime.now(),
content=json.dumps(msa).encode("utf-8"),
)
tls.add(res)
tls.commit()
except Exception:
tls.rollback()
raise
def msa_read(self, msa_token: str) -> Optional[dict]:
"""loads object from msa collection.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
if res := tls.query(MSA).filter_by(msa_id=msa_token).first():
return json.loads(res.content)
else:
return None
def msa_delete(self, msa_token: str) -> None:
try:
"""deletes the msa with token msa_token"""
tls = self.thread_local_session()
tls.query(MSA).filter_by(msa_id=msa_token).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def msa_stored_ids(self) -> List[str]:
"""returns a list of msa tokens of all objects stored"""
tls = self.thread_local_session()
return [res.msa_id for res in tls.query(MSA)]
def msa_delete_unless_whitelisted(self, whitelist: Iterable[str]) -> None:
try:
"""deletes the msa unless the id is in whitelist"""
tls = self.thread_local_session()
tls.query(MSA).filter(MSA.msa_id.not_in(whitelist)).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
# methods for trees
def tree_store(self, tree_token: str, tree: dict) -> Optional[str]:
"""stores the tree object tree under token tree_token.
Will not overwrite; requests to do so fail, silently."""
if not isinstance(tree, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(tree))
)
tls = self.thread_local_session()
if tls.query(TreeStorage).filter_by(ts_id=tree_token).one_or_none() is None:
try:
row = TreeStorage(
ts_id=tree_token,
upload_date=datetime.now(),
content=json.dumps(tree).encode("utf-8"),
)
tls.add(row)
tls.commit()
except Exception:
tls.rollback()
raise
def tree_read(self, tree_token: str) -> Optional[dict]:
"""loads object from tree collection.
It is assumed object is a dictionary"""
tls = self.thread_local_session()
if res := tls.query(TreeStorage).filter_by(ts_id=tree_token).first():
return json.loads(res.content)
else:
return None
def tree_delete(self, tree_token: str) -> None:
try:
"""deletes the tree with token tree_token"""
tls = self.thread_local_session()
tls.query(TreeStorage).filter_by(ts_id=tree_token).delete()
tls.commit()
except Exception:
tls.rollback()
raise
def tree_stored_ids(self) -> List[str]:
"""returns a list of tree tokens of all objects stored"""
tls = self.thread_local_session()
return [res.ts_id for res in tls.query(TreeStorage)]
def tree_delete_unless_whitelisted(self, whitelist: Iterable[str]) -> None:
try:
"""deletes the tree unless the id is in whitelist"""
tls = self.thread_local_session()
tls.query(TreeStorage).filter(TreeStorage.ts_id.not_in(whitelist)).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
# methods for clusters
def cluster_store(self, clustering_key: str, obj: dict) -> int:
"""stores the clustering object obj. retains previous version.
obj: a dictionary to store
clustering_key: the name of the clustering, e.g. TBSNP12-graph
Returns:
current cluster version
Note: does not replace previous version, but stores a new one.
Note: to delete legacy versions, call cluster_delete_legacy().
"""
tls = self.thread_local_session()
if not isinstance(obj, dict):
raise TypeError(f"Can only store dictionary objects, not {type(obj)}")
try:
json_repr = json.dumps(obj, cls=NPEncoder).encode("utf-8")
cluster = Cluster(
cluster_build_id=clustering_key,
upload_date=datetime.now(),
content=json_repr,
)
tls.add(cluster)
tls.commit()
# finished
return cluster.cl_int_id
except Exception:
tls.rollback()
raise
def cluster_read(self, clustering_key: str) -> Optional[dict]:
"""loads object from clusters collection corresponding to the most recent version of
the clustering identified by 'clustering_key'.
Parameters:
clustering_key: a string identifying a clustering result
Returns:
the clustering information, in the form of a dictionary if it exists, or None if it does not
"""
tls = self.thread_local_session()
if (
res := tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.order_by(desc(Cluster.cl_int_id))
.first()
):
return json.loads(res.content)
else:
return None
def cluster_read_update(
self, clustering_key: str, current_cluster_version: int
) -> Optional[dict]:
"""loads object from clusters collection corresponding to the most recent version
of the clustering, saved with cluster_build_id = 'clustering_key'.
it will read only if the current version is different from current_cluster_version; other wise, it returns None
Parameters:
clustering_key: a string identifying the cluster
current_cluster_version: an integer identifying a legacy cluster version
Returns:
the clustering information, in the form of a dictionary if it exists, or None if it does not
"""
tls = self.thread_local_session()
if (
res := tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.filter(Cluster.cl_int_id != current_cluster_version)
.order_by(desc(Cluster.cl_int_id))
.first()
):
return json.loads(res.content)
return None
def cluster_latest_version(self, clustering_key: str) -> int:
"""returns id of latest version, which is the maximum number
Parameters:
clustering_key: a string identifying the cluster
Returns:
cl_int_id, the primary key to the cluster table"""
tls = self.thread_local_session()
if (
res := tls.query(func.max(Cluster.cl_int_id))
.filter(Cluster.cluster_build_id == clustering_key)
.first()
):
retVal = res[0] # it's a tuple
return retVal
else:
return None
def cluster_keys(self, clustering_name: Optional[str] = None) -> List[str]:
"""lists clustering keys beginning with clustering_name. If clustering_name is none, all clustering keys are returned."""
tls = self.thread_local_session()
if clustering_name:
return list(
sorted(
set(
res.cluster_build_id
for res in tls.query(Cluster).filter(
Cluster.cluster_build_id.startswith(clustering_name)
)
)
)
)
else:
return list(sorted(set(res.cluster_build_id for res in tls.query(Cluster))))
def cluster_versions(self, clustering_key: str) -> List[bson.objectid.ObjectId]:
"""lists ids and storage dates corresponding to versions of clustering identifed by clustering_key.
the newest version is first.
"""
tls = self.thread_local_session()
return list(
tls.query(Cluster)
.filter_by(cluster_build_id=clustering_key)
.order_by(desc(Cluster.upload_date))
)
def cluster_delete_all(self, clustering_key: str) -> None:
"""delete all clustering objects, including the latest version, stored under clustering_key"""
try:
tls = self.thread_local_session()
tls.query(Cluster).filter(
Cluster.cluster_build_id == clustering_key
).delete()
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def cluster_delete_legacy_by_key(self, clustering_key: str) -> None:
"""delete all clustering objects, except latest version, stored with key clustering_key"""
tls = self.thread_local_session()
cl_int_ids = set()
for (cl_int_id,) in tls.query(Cluster.cl_int_id).filter_by(
cluster_build_id=clustering_key
):
cl_int_ids.add(cl_int_id)
if len(cl_int_ids) == 0:
return
else:
latest_cl_int_id = max(cl_int_ids)
for this_cl_int_id in cl_int_ids:
if not this_cl_int_id == latest_cl_int_id:
tls.query(Cluster).filter_by(cl_int_id=this_cl_int_id).delete()
try:
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def cluster_delete_legacy(self, clustering_name: str) -> None:
"""delete all clustering objects, except latest version, stored with clustering_name"""
for clustering_key in self.cluster_keys(clustering_name=clustering_name):
self.cluster_delete_legacy_by_key(clustering_key)
def refcompressedseq_store(self, guid: str, obj: dict) -> str:
"""stores the json object obj with guid guid.
Parameters:
guid: the sequence identifer
obj: a reference compressed sequence representation, as produced by py_seqComparer.compress().
Here is an example:
{
'A':set([1,2,3]), 'C':set([6]), 'T':set([4]), 'G':set([5]), 'M':{11:'Y', 12:'k'}, 'invalid':0
}
If the guid already exists in the database, raises a FileExistsError, as is the case with the mongo client."""
tls = self.thread_local_session()
if not isinstance(obj, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(obj))
)
if "invalid" not in obj.keys():
raise KeyError(
"An invalid key must be present. Keys are: {0}".format(obj.keys())
)
# if the record already exists, we don't re-add it
res = (
tls.query(RefCompressedSeq.seq_int_id)
.filter_by(sequence_id=guid)
.one_or_none()
)
if res is None: # it doesn't exits
tls.add(
RefCompressedSeq(
sequence_id=guid,
invalid=obj["invalid"],
examination_date=datetime.now(),
content=self.sjc.to_json(obj),
prop_actg=None,
annotations=json.dumps({}),
)
)
try:
tls.commit()
except Exception:
tls.rollback()
raise
else: # it does exist
raise FileExistsError("Attempting to overwrite {0}".format(guid))
# finished
def refcompressedsequence_read(self, guid: str) -> Any:
"""loads object from refcompressedseq collection.
the object loaded is identified by guid.
It is assumed object stored is a dictionary
returns:
dictionary containing referencecompressed sequences"""
tls = self.thread_local_session()
if (
rcs := tls.query(RefCompressedSeq.content)
.filter_by(sequence_id=guid)
.first()
):
return self.sjc.from_json(rcs.content)
else:
return None
def refcompressedsequence_read_many(self, guids: Iterable) -> Any:
"""loads objects identified by all members of guids from refcompressedseq collection.
It is assumed object stored is a dictionary
returns:
generator, which yields a tuple
(guid, referencecompressedsequence)
raises:
ValueError, if length of guids is > 1000
"""
if len(guids) > 1000:
raise ValueError("Maximum number of samples which can be sought is 1000")
tls = self.thread_local_session()
results = (
tls.query(RefCompressedSeq.sequence_id, RefCompressedSeq.content)
.filter(RefCompressedSeq.sequence_id.in_(guids))
.all()
)
for result in results:
yield (result.sequence_id, self.sjc.from_json(result.content))
def refcompressedsequence_read_all(self, internal_batch_size=5000) -> Any:
"""loads objects identified by all members of guids from refcompressedseq collection.
It is assumed object stored is a dictionary
parameters:
internal_batch_size: how many samples are loaded into ram at a time. Default should be fine unless low memory
returns:
generator, which yields a tuple
(guid, referencecompressedsequence)
"""
# sanity check
if internal_batch_size < 1:
raise ValueError("Internal batch size must be >= 1")
tls = self.thread_local_session()
seq_int_ids = [
seq_int_id
for seq_int_id, in tls.query(RefCompressedSeq.seq_int_id)
.order_by(RefCompressedSeq.seq_int_id)
.all()
]
start_position = 0
while start_position < len(seq_int_ids):
end_position = internal_batch_size + start_position - 1
if end_position >= len(seq_int_ids):
end_position = len(seq_int_ids) - 1
start_seq_int_id = seq_int_ids[start_position]
end_seq_int_id = seq_int_ids[end_position]
# load batch
results = (
tls.query(RefCompressedSeq.sequence_id, RefCompressedSeq.content)
.filter(RefCompressedSeq.seq_int_id >= start_seq_int_id)
.filter(RefCompressedSeq.seq_int_id <= end_seq_int_id)
.all()
)
for result in results:
yield (result.sequence_id, self.sjc.from_json(result.content))
# next batch
start_position = end_position + 1
def refcompressedsequence_guids(self) -> Set[str]:
"""loads guids from refcompressedseq collection."""
tls = self.thread_local_session()
return set(res.sequence_id for res in tls.query(RefCompressedSeq.sequence_id))
def guid_annotate(self, guid: str, nameSpace: str, annotDict: dict) -> None:
"""adds multiple annotations of guid from a dictionary;
all annotations go into a namespace.
updates the annotation if it exists"""
tls = self.thread_local_session()
if not isinstance(annotDict, dict):
raise TypeError(
"Can only store dictionary objects, not {0}".format(type(annotDict))
)
# The reference compressed sequence must exist.
rcs = (
tls.query(RefCompressedSeq)
.filter(RefCompressedSeq.sequence_id == guid)
.one_or_none()
)
if rcs is None:
raise RDBMSError(
"Asked to annotate a record {0} but it does not exist".format(guid)
)
if nameSpace == "DNAQuality":
# coerce examination date to string
if "examinationDate" in annotDict:
rcs.examination_date = annotDict["examinationDate"]
if isinstance(annotDict["examinationDate"], datetime):
# convert to isoformat pre-jsonisation
annotDict["examinationDate"] = annotDict[
"examinationDate"
].isoformat()
if "propACTG" in annotDict:
rcs.prop_actg = annotDict["propACTG"]
annotations = json.loads(rcs.annotations) # what's there now
annotations[nameSpace] = annotDict # replace or add the new namespace
rcs.annotations = json.dumps(annotations).encode("utf-8")
try:
tls.commit()
# finished
except Exception:
tls.rollback()
raise
def guids(self) -> Set[str]:
"""returns all registered guids"""
return self.refcompressedsequence_guids()
def guids_added_after_sample(self, guid: str) -> Set[str]:
"""returns all guids added after a sample"""
tls = self.thread_local_session()
rcs = (
tls.query(RefCompressedSeq.seq_int_id)
.filter(RefCompressedSeq.sequence_id == guid)
.one_or_none()
)
if rcs is None:
return None # does not exist
(this_seq_int_id,) = rcs # the sequence int id of the sample
retVal = []
for (guid,) in tls.query(RefCompressedSeq.sequence_id).filter(
RefCompressedSeq.seq_int_id > this_seq_int_id
):
retVal.append(guid)
return set(retVal)
def guids_considered_after(self, addition_datetime: datetime) -> Set[str]:
"""returns all registered guid added after addition_datetime
addition_datetime: a date of datetime class."""
tls = self.thread_local_session()
if not isinstance(addition_datetime, datetime):
raise TypeError(
"addition_datetime must be a datetime value. It is {0}. Value = {1}".format(
type(addition_datetime), addition_datetime
)
)
retVal = []
for (guid,) in tls.query(RefCompressedSeq.sequence_id).filter(
RefCompressedSeq.examination_date > addition_datetime
):
retVal.append(guid)
return set(retVal)
def _guids_selected_by_validity(self, validity: int) -> Set[str]:
"""returns registered guids, selected on their validity
0 = guid is valid
1 = guid is invalid
"""
tls = self.thread_local_session()
return set(
res.sequence_id
for res in tls.query(RefCompressedSeq.sequence_id).filter_by(
invalid=validity
)
)
def singletons(
self, method: str = "approximate", return_top: int = 1000
) -> pd.DataFrame:
"""
This method is not important in the RDBMS implementation of the fn3persistence store.
Returns:
An empty data frame.
"""
return pd.DataFrame()
def guids_valid(self) -> set:
"""return all registered valid guids.
Validity is determined by the contents of the DNAQuality.invalid field, on which there is an index"""
return self._guids_selected_by_validity(0)
def guids_invalid(self) -> set:
"""return all invalid guids
Validity is determined by the contents of the DNAQuality.invalid field, on which there is an index"""
return self._guids_selected_by_validity(1)
def guid_exists(self, guid: str) -> bool:
"""checks the presence of a single guid"""
tls = self.thread_local_session()
return (
tls.query(RefCompressedSeq.sequence_id).filter_by(sequence_id=guid).first()
is not None
)
def guid_valid(self, guid: str) -> int:
"""checks the validity of a single guid
Parameters:
guid: the sequence identifier
Returns
-1 The guid does not exist
0 The guid exists and the sequence is valid
1 The guid exists and the sequence is invalid
"""
tls = self.thread_local_session()
if (
res := tls.query(RefCompressedSeq.invalid)
.filter_by(sequence_id=guid)
.first()
):
if res.invalid == 0:
return 0
elif res.invalid == 1:
return 1
else:
raise ValueError(
"invalid is neither 1 nor 0 but {0}".format(res.invalid)
)
else:
return -1
def guid_examination_time(self, guid: str) -> Optional[datetime]:
"""returns the examination time for a single guid
Parameters:
guid: the sequence identifier
Returns either
The examination datetime value for this guid OR
None if the guid does not exist
"""
tls = self.thread_local_session()
if (
res := tls.query(RefCompressedSeq.examination_date)
.filter_by(sequence_id=guid)
.first()
):
return res.examination_date
else:
return None
def guids_considered_after_guid(self, guid: str) -> Set[str]:
"""returns all registered guids added after guid
guid: a sequence identifier"""
if addition_datetime := self.guid_examination_time(guid):
return self.guids_considered_after(addition_datetime)
else:
raise ValueError("guid is not valid: {0}".format(guid))
def guid_quality_check(
self, guid: str, cutoff: Union[float, int]
) -> Optional[bool]:
"""Checks whether the quality of one guid exceeds the cutoff.
If the guid does not exist, returns None.
If the guid does exist and has quality< cutoff, returns False.
Otherwise, returns True.
"""
tls = self.thread_local_session()
# test input
if not type(cutoff) in [float, int]:
raise TypeError(
"Cutoff should be either floating point or integer, but it is %s"
% type(cutoff)
)
if not type(guid) == str:
raise TypeError("The guid passed should be as string, not %s" % str(guid))
# recover record, compare with quality
res = tls.query(RefCompressedSeq).filter_by(sequence_id=guid).first()
if res is None: # no entry for this guid
return None
else:
# report whether it is larger or smaller than cutoff
return res.prop_actg >= cutoff
def _guid2seq(self, guidList: Optional[List[str]]) -> Iterable[RefCompressedSeq]:
"""returns the annotations, sequence_id and prop_actg from each RefCompressedSeq for each guid in guidList
If guidList is None, all items are returned.
"""
tls = self.thread_local_session()
if guidList is None: # rreturn everything
return tls.query(
RefCompressedSeq.sequence_id,
RefCompressedSeq.annotations,
RefCompressedSeq.prop_actg,
RefCompressedSeq.examination_date,
)
else:
return tls.query(RefCompressedSeq).filter(
RefCompressedSeq.sequence_id.in_(guidList)
)
def guid2item(
self, guidList: Optional[List[str]], namespace: str, tag: str
) -> dict:
"""returns the annotation (such as sequence quality, which is stored as an annotation)
in namespace:tag for all guids in guidlist.
If guidList is None, all items are returned.
An error is raised if namespace and tag is not present in each record.
"""
return {
res.sequence_id: json.loads(res.annotations)[namespace][tag]
for res in self._guid2seq(guidList)
}
def guid2ExaminationDateTime(self, guidList: Optional[List[str]] = None) -> dict:
"""returns quality scores and examinationDate for all guids in guidlist. If guidList is None, all results are returned."""
return {
res.sequence_id: res.examination_date for res in self._guid2seq(guidList)
}
def guid2quality(self, guidList: Optional[List[str]] = None) -> Optional[dict]:
"""returns quality scores for all guids in guidlist (or all samples if guidList is None)
potentially expensive query if guidList is None."""
return {res.sequence_id: res.prop_actg for res in self._guid2seq(guidList)}
def guid2propACTG_filtered(self, cutoff: Union[int, float] = 0) -> Dict[str, float]:
"""recover guids which have good quality, > cutoff.
These are in the majority, so we run a table scan to find these.
This query is potentially very inefficient- best avoided
"""
tls = self.thread_local_session()
query = tls.query(
RefCompressedSeq.sequence_id, RefCompressedSeq.prop_actg
).filter(RefCompressedSeq.prop_actg >= cutoff)
return {res.sequence_id: res.prop_actg for res in query}
def guid2items(
self, guidList: Optional[List[str]], namespaces: Optional[Set[str]]
) -> Dict[Any, Dict[str, Any]]:
"""returns all annotations in namespaces, which is a list
If namespaces is None, all namespaces are returned.
If guidList is None, all items are returned.
To do this, a table scan is performed - indices are not used.
"""
def select_namespaces(annotations: dict) -> dict:
if namespaces:
return {ns: annotations[ns] for ns in annotations.keys() & namespaces}
else:
return annotations
return {
res.sequence_id: select_namespaces(json.loads(res.annotations))
for res in self._guid2seq(guidList)
}
def guid_annotations(self) -> Optional[Dict[Any, Dict[str, Any]]]:
"""return all annotations of all guids"""
return self.guid2items(None, None) # no restriction by namespace or by guid.
def guid_annotation(self, guid: str) -> Optional[Dict[Any, Dict[str, Any]]]:
"""return all annotations of one guid"""
return self.guid2items([guid], None) # restriction by guid.
def guid2neighbour_add_links(
self,
guid: str,
targetguids: Dict[str, Dict[str, int]],
use_update: bool = False,
) -> Dict[str, int]:
"""adds links between guid and their neighbours ('targetguids')
Parameters:
guid: the 'source' guid for the matches eg 'guid1'
targetguids: what is guid linked to, eg
{
'guid2':{'dist':12},
'guid3':{'dist':2}
}
use_update - currently ignored, always False. Setting True yields NotImplementedError
This stores links in the guid2neighbour collection.
Returns:
The number of records written
Note:
uses bulk upload methodology to write fast, as some samples may have thousands or tens of thousands of neighbours
"""
load_list = []
for guid2, dist in targetguids.items():
load_list.append(
{"sequence_id_1": guid, "sequence_id_2": guid2, "dist": dist["dist"]}
)
load_list.append(
{"sequence_id_1": guid2, "sequence_id_2": guid, "dist": dist["dist"]}
)
load_df = pd.DataFrame.from_records(load_list)
if len(load_df.index) > 0:
self._bulk_load(load_df, "edge")
class Guid2NeighbourRepackRet(TypedDict):
guid: str
finished: str
pre_optimisation: dict
actions_taken: Dict[str, int]
def guid2neighbour_repack(
self, guid: str, always_optimise: bool = False, min_optimisable_size: int = 1
) -> Guid2NeighbourRepackRet:
"""In the mongo implementation, alters the mongodb representation of the links of guid.
In the rdbms implementation, this does nothing, and just returns a status report.
Parameters:
guid : the identifier of a sample to repack
always_optimise: consider for optimisation even if there are no 's' (single item) records
"""
return {
"guid": guid,
"finished": datetime.now().isoformat(),
"pre_optimisation": {
"s_records": 0,
"msg": "Repacking not necessary on RDBMS",
},
"actions_taken": {},
}
class Guid2NeighboursRet(TypedDict):
guid: str
neighbours: List[Guid2NeighboursFormats]
def guid2neighbours(
self, guid: str, cutoff: int = 20, returned_format: int = 2
) -> Guid2NeighboursRet:
"""returns neighbours of guid with cutoff <=cutoff.
Parameters:
guid: the sequence identifier
cutoff: a SNV distance cutoff
returned_format: see below.
Returns links either as
format 1 [[otherGuid, distance],[otherGuid2, distance2],...]
or as
format 2 [[otherGuid, distance, N_just1, N_just2, N_either],[],...]
or as
format 3 [otherGuid1, otherGuid2, otherGuid3]
or as
format 4 [{'guid':otherguid, 'snv':distance}]
Internally, the documents in guid2neighbour are of the form
{'guid':'guid1', 'rstat':'s', 'neighbours':{'guid2':{'dist':12, ...}}} OR
{'guid':'guid1', 'rstat':'m', 'neighbours':{'guid2':{'dist':12, ...}, 'guid3':{'dist':5, ...}} OR
{'guid':'guid1', 'rstat':'f', 'neighbours':{'guid2':{'dist':12, ...}, 'guid3':{'dist':5, ...}}
However, irrespective of their internal representation, this function always returns
exactly one item for each link of 'guid'; duplicates are not possible.
The last example occurs when the maximum number of neighbours permitted per record has been reached.
"""
def f(res):
otherGuid = res.sequence_id_2
dist = res.dist
if returned_format == 1:
return [otherGuid, dist]
elif returned_format == 2:
raise NotImplementedError("format 2 is no longer supported")
elif returned_format == 3:
return otherGuid
elif returned_format == 4:
return {"guid": otherGuid, "snv": dist}
else:
raise ValueError(
f"Unable to understand returned_format = {returned_format}"
)
tls = self.Session()
return {
"guid": guid,
"neighbours": [
f(res)
for res in tls.query(Edge)
.filter_by(sequence_id_1=guid)
.filter(Edge.dist <= cutoff)
],
}
def _set_lock_status(self, lock_int_id, lock_status, sequence_id="-NotSpecified-"):
"""locks or unlocks resources identified by lock_int_id, allowing cross- process sequential processing (e.g. insertion)
To lock, set lock_status =1 ; to unlock, set lock_status =0
To return the relevant row, set lock_status to None
See the acquire_lock() method for more details
returns:
If lock_status is either 1 or 0:
True if update succeeded, false if it did not
If lock_status is None:
the lock row, as an Sqlalchemy object, from which field values can be accessed by dot notation, e.g. retVal.lock_set_date, or retVal.lock_status
Technical notes:
https://docs.sqlalchemy.org/en/14/orm/session_transaction.html
https://www.amazon.com/Expert-Oracle-Database-Architecture-Thomas-dp-1430262982/dp/1430262982/ref=dp_ob_title_bk
"""
# make sure there is an entry for this lock
tls = self.Session()
lock_row = (
tls.query(FNLock).filter(FNLock.lock_int_id == lock_int_id).one_or_none()
)
# if the row doesn't exist, we add it, with the lock not set.
if lock_row is None:
try:
lock_row = FNLock(
lock_int_id=lock_int_id,
lock_status=0,
sequence_id=sequence_id,
lock_set_date=datetime.now(),
uuid=uuid.uuid4().hex,
)
tls.add(lock_row)
tls.commit()
except Exception:
tls.rollback()
raise
# analyse the record for this row
lock_row = (
tls.query(FNLock)
.filter(FNLock.lock_int_id == lock_int_id)
.with_for_update()
.one()
)
if lock_status is None:
retval = lock_row
elif lock_row.lock_status == 0 and lock_status == 0:
# it's already unlocked
retval = True
elif lock_row.lock_status == 1 and lock_status == 1:
# it's already locked and we're asked to acquire a lock. We can't.
retval = False
elif lock_row.lock_status == 0 and lock_status == 1:
# it's already unlocked, we can lock
lock_row.lock_status = 1
lock_row.lock_set_date = datetime.now()
lock_row.sequence_id = sequence_id
lock_row.uuid = uuid.uuid4().hex
retval = True
elif lock_row.lock_status == 1 and lock_status == 0:
# it's already locked, we can unlock
lock_row.lock_status = 0
lock_row.lock_set_date = datetime.now()
lock_row.sequence_id = "-NotSpecified-"
lock_row.uuid = uuid.uuid4().hex
retval = True
try:
tls.commit()
return retval
except Exception:
tls.rollback()
raise
def lock_details(self, lock_int_id):
"""returns details of the lock as a dictionary
Parameters:
lock_int_id: an integer identifier to the lock of interest
Returns:
None if there is no lock,
or a dictionary containing details of the lock held including sequence_id, lock_status, lock_set_date, and uuid"""
res = self.lock_status(lock_int_id)
if res.lock_status == 0:
return None
else:
return dict(
sequence_id=res.sequence_id,
lock_set_date=res.lock_set_date,
uuid=res.uuid,
)
def lock_status(self, lock_int_id):
"""determine whether a database-based lock is open (0) or closed (1).
Parameters:
lock_int_id: an integer identifier to the lock of interest
Returns:
a sqlalchemy object containing the lock row"""
return self._set_lock_status(lock_int_id, None)
def lock(self, lock_int_id, sequence_id):
"""obtains a database-based lock.
Parameters:
lock_int_id: an integer identifier to the lock of interest
sequence_id: the id (typically guid) of the sequence being added. Used if the inserting process crashes
Returns:
True if the lock is acquired
False if it is not"""
return self._set_lock_status(lock_int_id, 1, sequence_id)
def unlock(self, lock_int_id, force=False):
"""obtains a database-based lock.
Parameters:
lock_int_id: an integer identifier to the lock of interest
force: if True, will unlock irrespective of current status, returning True
Returns:
True if the lock is acquired
False if it is not"""
res = self._set_lock_status(lock_int_id, 0)
if force:
return True
else:
return res
|
import logging
from abc import ABC, abstractmethod
from fritzconnection.core.exceptions import ActionError, ServiceError, FritzInternalError
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARN)
class FritzCapability(ABC):
capabilities = []
def __init__(self) -> None:
self.present = False
self.requirements = []
self.metrics = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
FritzCapability.capabilities.append(cls)
def checkCapability(self, device):
self.present = all([(service in device.fc.services) and (action in device.fc.services[service].actions) for (service, action) in self.requirements])
logger.debug(f'Capability {type(self).__name__} set to {self.present} on device {device.host}')
# It seems some boxes report service/actions they don't actually support. So try calling the requirements,
# and if it throws "InvalidService", "InvalidAction" or "FritzInternalError" disable this again.
if self.present:
for (svc, action) in self.requirements:
try:
device.fc.call_action(svc, action)
except (ServiceError, ActionError, FritzInternalError) as e:
logger.warn(f'disabling metrics at service {svc}, action {action} - fritzconnection.call_action returned {e}')
self.present = False
def getMetrics(self, devices, name):
for device in devices:
if device.capabilities[name].present:
yield from self._getMetricValues(device)
@abstractmethod
def createMetrics():
pass
@abstractmethod
def _getMetricValues(self, device):
pass
class FritzCapabilities():
def __init__(self, device=None) -> None:
self.capabilities = {capability.__name__: capability() for capability in FritzCapability.capabilities}
if device:
self.checkPresent(device)
def __iter__(self):
return iter(self.capabilities)
def __len__(self):
return len(self.capabilities)
def __getitem__(self, index):
return self.capabilities[index]
def items(self):
return self.capabilities.items()
def merge(self, other_caps):
for cap in self.capabilities:
self.capabilities[cap].present = self.capabilities[cap].present or other_caps.capabilities[cap].present
def empty(self):
return not any([cap.present for cap in list(self.capabilities.values())])
def checkPresent(self, device):
for c in self.capabilities:
self.capabilities[c].checkCapability(device)
class DeviceInfo(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('DeviceInfo1', 'GetInfo'))
def createMetrics(self):
self.metrics['uptime'] = CounterMetricFamily('fritz_uptime', 'FritzBox uptime, system info in labels',
labels=['modelname', 'softwareversion', 'serial', 'friendly_name'], unit='seconds')
def _getMetricValues(self, device):
info_result = device.fc.call_action('DeviceInfo:1', 'GetInfo')
self.metrics['uptime'].add_metric([info_result['NewModelName'], info_result['NewSoftwareVersion'], info_result['NewSerialNumber'],
device.friendly_name], info_result['NewUpTime'])
yield self.metrics['uptime']
class HostNumberOfEntries(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('Hosts1', 'GetHostNumberOfEntries'))
def createMetrics(self):
self.metrics['numhosts'] = GaugeMetricFamily('fritz_known_devices', 'Number of devices in hosts table',
labels=['serial', 'friendly_name'], unit='count')
def _getMetricValues(self, device):
num_hosts_result = device.fc.call_action('Hosts1', 'GetHostNumberOfEntries')
self.metrics['numhosts'].add_metric([device.serial, device.friendly_name], num_hosts_result['NewHostNumberOfEntries'])
yield self.metrics['numhosts']
# class HostInfo(FritzCapability):
# def __init__(self) -> None:
# super().__init__()
# self.requirements.append(('Hosts1', 'GetHostNumberOfEntries'))
# self.requirements.append(('Hosts1', 'GetGenericHostEntry'))
# self.requirements.append(('Hosts1', 'X_AVM-DE_GetSpecificHostEntryByIP'))
#
# def createMetrics(self):
# self.metrics['hostactive'] = GaugeMetricFamily('fritz_host_active', 'Indicates that the device is curently active',
# labels=['serial', 'ip_address', 'mac_address', 'hostname', 'interface', 'port', 'model'])
# self.metrics['hostspeed'] = GaugeMetricFamily('fritz_host_speed', 'Connection speed of the device',
# labels=['serial', 'ip_address', 'mac_address', 'hostname', 'interface', 'port', 'model'])
#
# def _getMetricValues(self, device):
# num_hosts_result = device.fc.call_action('Hosts1', 'GetHostNumberOfEntries')
# logger.debug(f'Fetching host information for device serial {device.serial} (hosts found: {num_hosts_result['NewHostNumberOfEntries']}')
# for host_index in range(num_hosts_result['NewHostNumberOfEntries']):
# logger.debug(f'Fetching generic host information for host number {host_index}')
# host_result = device.fc.call_action('Hosts1', 'GetGenericHostEntry', NewIndex=host_index)
#
# host_ip = host_result['NewIPAddress']
# host_mac = host_result['NewMACAddress']
# host_name = host_result['NewHostName']
#
# if host_ip != "":
# logger.debug(f'Fetching extended AVM host information for host number {host_index} by IP {host_ip}')
# avm_host_result = device.fc.call_action('Hosts1', 'X_AVM-DE_GetSpecificHostEntryByIP', NewIPAddress=host_ip)
# host_interface = avm_host_result['NewInterfaceType']
# host_port = str(avm_host_result['NewX_AVM-DE_Port'])
# host_model = avm_host_result['NewX_AVM-DE_Model']
# host_speed = avm_host_result['NewX_AVM-DE_Speed']
# else:
# logger.debug(f'Unable to fetch extended AVM host information for host number {host_index}: no IP found')
# host_interface = "n/a"
# host_port = "n/a"
# host_model = "n/a"
# host_speed = 0
#
# host_active = 1.0 if host_result['NewActive'] else 0.0
# self.metrics['hostactive'].add_metric([device.serial, host_ip, host_mac, host_name, host_interface, host_port, host_model], host_active)
# self.metrics['hostspeed'].add_metric([device.serial, host_ip, host_mac, host_name, host_interface, host_port, host_model], host_speed)
#
# yield self.metrics['hostactive']
# yield self.metrics['hostspeed']
class UserInterface(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('UserInterface1', 'GetInfo'))
def createMetrics(self):
self.metrics['update'] = GaugeMetricFamily('fritz_update_available', 'FritzBox update available',
labels=['serial', 'friendly_name', 'newsoftwareversion'])
def _getMetricValues(self, device):
update_result = device.fc.call_action('UserInterface:1', 'GetInfo')
upd_available = 1 if update_result['NewUpgradeAvailable'] else 0
new_software_version = update_result['NewX_AVM-DE_Version'] if update_result['NewUpgradeAvailable'] else 'n/a'
self.metrics['update'].add_metric([device.serial, device.friendly_name, new_software_version], upd_available)
yield self.metrics['update']
class LanInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('LANEthernetInterfaceConfig1', 'GetInfo'))
def createMetrics(self):
self.metrics['lanenable'] = GaugeMetricFamily('fritz_lan_status_enabled', 'LAN Interface enabled', labels=['serial', 'friendly_name'])
self.metrics['lanstatus'] = GaugeMetricFamily('fritz_lan_status', 'LAN Interface status', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
lanstatus_result = device.fc.call_action('LANEthernetInterfaceConfig:1', 'GetInfo')
self.metrics['lanenable'].add_metric([device.serial, device.friendly_name], lanstatus_result['NewEnable'])
lanstatus = 1 if lanstatus_result['NewStatus'] == 'Up' else 0
self.metrics['lanstatus'].add_metric([device.serial, device.friendly_name], lanstatus)
yield self.metrics['lanenable']
yield self.metrics['lanstatus']
class LanInterfaceConfigStatistics(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('LANEthernetInterfaceConfig1', 'GetStatistics'))
def createMetrics(self):
self.metrics['lanbytes'] = CounterMetricFamily('fritz_lan_data', 'LAN bytes received', labels=['serial', 'friendly_name', 'direction'], unit='bytes')
self.metrics['lanpackets'] = CounterMetricFamily('fritz_lan_packet', 'LAN packets transmitted',
labels=['serial', 'friendly_name', 'direction'], unit='count')
def _getMetricValues(self, device):
lanstats_result = device.fc.call_action('LANEthernetInterfaceConfig:1', 'GetStatistics')
self.metrics['lanbytes'].add_metric([device.serial, device.friendly_name, 'rx'], lanstats_result['NewBytesReceived'])
self.metrics['lanbytes'].add_metric([device.serial, device.friendly_name, 'tx'], lanstats_result['NewBytesSent'])
self.metrics['lanpackets'].add_metric([device.serial, device.friendly_name, 'rx'], lanstats_result['NewPacketsReceived'])
self.metrics['lanpackets'].add_metric([device.serial, device.friendly_name, 'tx'], lanstats_result['NewPacketsSent'])
yield self.metrics['lanbytes']
yield self.metrics['lanpackets']
class WanDSLInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANDSLInterfaceConfig1', 'GetInfo'))
def createMetrics(self):
self.metrics['enable'] = GaugeMetricFamily('fritz_dsl_status_enabled', 'DSL enabled', labels=['serial', 'friendly_name'])
self.metrics['datarate'] = GaugeMetricFamily('fritz_dsl_datarate', 'DSL datarate in kbps',
labels=['serial', 'friendly_name', 'direction', 'type'], unit='kbps')
self.metrics['noisemargin'] = GaugeMetricFamily('fritz_dsl_noise_margin', 'Noise Margin in dB',
labels=['serial', 'friendly_name', 'direction'], unit='dB')
self.metrics['attenuation'] = GaugeMetricFamily('fritz_dsl_attenuation', 'Line attenuation in dB',
labels=['serial', 'friendly_name', 'direction'], unit='dB')
self.metrics['status'] = GaugeMetricFamily('fritz_dsl_status', 'DSL status', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
fritz_dslinfo_result = device.fc.call_action('WANDSLInterfaceConfig:1', 'GetInfo')
self.metrics['enable'].add_metric([device.serial, device.friendly_name], fritz_dslinfo_result['NewEnable'])
dslstatus = 1 if fritz_dslinfo_result['NewStatus'] == 'Up' else 0
self.metrics['status'].add_metric([device.serial, device.friendly_name], dslstatus)
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'tx', 'curr'], fritz_dslinfo_result['NewUpstreamCurrRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'rx', 'curr'], fritz_dslinfo_result['NewDownstreamCurrRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'tx', 'max'], fritz_dslinfo_result['NewUpstreamMaxRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'rx', 'max'], fritz_dslinfo_result['NewDownstreamMaxRate'])
self.metrics['noisemargin'].add_metric([device.serial, device.friendly_name, 'tx'], fritz_dslinfo_result['NewUpstreamNoiseMargin']/10)
self.metrics['noisemargin'].add_metric([device.serial, device.friendly_name, 'rx'], fritz_dslinfo_result['NewDownstreamNoiseMargin']/10)
self.metrics['attenuation'].add_metric([device.serial, device.friendly_name, 'tx'], fritz_dslinfo_result['NewUpstreamAttenuation']/10)
self.metrics['attenuation'].add_metric([device.serial, device.friendly_name, 'rx'], fritz_dslinfo_result['NewDownstreamAttenuation']/10)
yield self.metrics['enable']
yield self.metrics['status']
yield self.metrics['datarate']
yield self.metrics['noisemargin']
yield self.metrics['attenuation']
class WanDSLInterfaceConfigAVM(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANDSLInterfaceConfig1', 'X_AVM-DE_GetDSLInfo'))
def createMetrics(self):
self.metrics['fec'] = CounterMetricFamily('fritz_dsl_fec_errors_count', 'Number of Forward Error Correction Errors', labels=['serial', 'friendly_name'])
self.metrics['crc'] = CounterMetricFamily('fritz_dsl_crc_errors_count', 'Number of CRC Errors', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
fritz_avm_dsl_result = device.fc.call_action('WANDSLInterfaceConfig1', 'X_AVM-DE_GetDSLInfo')
self.metrics['fec'].add_metric([device.serial, device.friendly_name], fritz_avm_dsl_result['NewFECErrors'])
self.metrics['crc'].add_metric([device.serial, device.friendly_name], fritz_avm_dsl_result['NewCRCErrors'])
yield self.metrics['fec']
yield self.metrics['crc']
class WanPPPConnectionStatus(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANPPPConnection1', 'GetStatusInfo'))
def createMetrics(self):
self.metrics['uptime'] = CounterMetricFamily('fritz_ppp_connection_uptime', 'PPP connection uptime', labels=['serial', 'friendly_name'], unit='seconds')
self.metrics['connected'] = GaugeMetricFamily('fritz_ppp_connection_state', 'PPP connection state', labels=['serial', 'friendly_name', 'last_error'])
def _getMetricValues(self, device):
fritz_pppstatus_result = device.fc.call_action('WANPPPConnection:1', 'GetStatusInfo')
pppconnected = 1 if fritz_pppstatus_result['NewConnectionStatus'] == 'Connected' else 0
self.metrics['uptime'].add_metric([device.serial, device.friendly_name], fritz_pppstatus_result['NewUptime'])
self.metrics['connected'].add_metric([device.serial, device.friendly_name, fritz_pppstatus_result['NewLastConnectionError']], pppconnected)
yield self.metrics['uptime']
yield self.metrics['connected']
class WanCommonInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetCommonLinkProperties'))
def createMetrics(self):
self.metrics['wanconfig'] = GaugeMetricFamily('fritz_wan_max_bitrate', 'max bitrate at the physical layer',
labels=['serial', 'friendly_name', 'wantype', 'direction'], unit='bps')
self.metrics['wanlinkstatus'] = GaugeMetricFamily('fritz_wan_phys_link_status', 'link status at the physical layer',
labels=['serial', 'friendly_name', 'wantype'])
def _getMetricValues(self, device):
wanstatus_result = device.fc.call_action('WANCommonInterfaceConfig1', 'GetCommonLinkProperties')
self.metrics['wanconfig'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType'], 'tx'],
wanstatus_result['NewLayer1UpstreamMaxBitRate'])
self.metrics['wanconfig'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType'], 'rx'],
wanstatus_result['NewLayer1DownstreamMaxBitRate'])
l1_status = wanstatus_result['NewPhysicalLinkStatus']
wanstatus = 1 if l1_status == "Up" else 0
self.metrics['wanlinkstatus'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType']], wanstatus)
yield self.metrics['wanconfig']
yield self.metrics['wanlinkstatus']
class WanCommonInterfaceDataBytes(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalBytesReceived'))
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalBytesSent'))
def createMetrics(self):
self.metrics['wanbytes'] = CounterMetricFamily('fritz_wan_data', 'WAN data in bytes', labels=['serial', 'friendly_name', 'direction'], unit='bytes')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalBytesReceived')
wan_bytes_rx = fritz_wan_result['NewTotalBytesReceived']
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalBytesSent')
wan_bytes_tx = fritz_wan_result['NewTotalBytesSent']
self.metrics['wanbytes'].add_metric([device.serial, device.friendly_name, 'tx'], wan_bytes_tx)
self.metrics['wanbytes'].add_metric([device.serial, device.friendly_name, 'rx'], wan_bytes_rx)
yield self.metrics['wanbytes']
class WanCommonInterfaceByteRate(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonIFC1', 'GetAddonInfos'))
def createMetrics(self):
self.metrics['wanbyterate'] = GaugeMetricFamily('fritz_wan_datarate', 'Current WAN data rate in bytes/s',
labels=['serial', 'friendly_name', 'direction'], unit='bytes')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonIFC1', 'GetAddonInfos')
wan_byterate_rx = fritz_wan_result['NewByteReceiveRate']
wan_byterate_tx = fritz_wan_result['NewByteSendRate']
self.metrics['wanbyterate'].add_metric([device.serial, device.friendly_name, 'rx'], wan_byterate_rx)
self.metrics['wanbyterate'].add_metric([device.serial, device.friendly_name, 'tx'], wan_byterate_tx)
yield self.metrics['wanbyterate']
class WanCommonInterfaceDataPackets(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalPacketsReceived'))
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalPacketsSent'))
def createMetrics(self):
self.metrics['wanpackets'] = CounterMetricFamily('fritz_wan_data_packets', 'WAN data in packets',
labels=['serial', 'friendly_name', 'direction'], unit='count')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalPacketsReceived')
wan_packets_rx = fritz_wan_result['NewTotalPacketsReceived']
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalPacketsSent')
wan_packets_tx = fritz_wan_result['NewTotalPacketsSent']
self.metrics['wanpackets'].add_metric([device.serial, device.friendly_name, 'tx'], wan_packets_tx)
self.metrics['wanpackets'].add_metric([device.serial, device.friendly_name, 'rx'], wan_packets_rx)
yield self.metrics['wanpackets']
def wlanConsructorFactory(obj_ref, index):
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetInfo'))
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetTotalAssociations'))
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetPacketStatistics'))
def wlanCreateMetricsFactory(obj_ref, name):
m_name = name.replace('.', '_')
obj_ref.metrics['wlanstatus'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_status', f'Status of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'])
obj_ref.metrics['wlanchannel'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_channel', f'Channel of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'])
obj_ref.metrics['wlanassocs'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_associations', f'Number of associations (devices) of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'], unit='count')
obj_ref.metrics['wlanpackets'] = CounterMetricFamily(f'fritz_wifi_{m_name}_packets', f'Amount of packets of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid', 'direction'], unit='count')
def wlanGetMetricsFactory(obj_ref, index, device):
wlan_result = device.fc.call_action(f'WLANConfiguration{index}', 'GetInfo')
wlan_status = 1 if wlan_result['NewStatus'] == "Up" else 0
wlan_enabled = '1' if wlan_result['NewEnable'] else '0'
obj_ref.metrics['wlanstatus'].add_metric([device.serial, device.friendly_name, wlan_enabled,
wlan_result['NewStandard'], wlan_result['NewSSID']], wlan_status)
obj_ref.metrics['wlanchannel'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'],
wlan_result['NewSSID']], wlan_result['NewChannel'])
assoc_results = device.fc.call_action(f'WLANConfiguration{index}', 'GetTotalAssociations')
obj_ref.metrics['wlanassocs'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'],
wlan_result['NewSSID']], assoc_results['NewTotalAssociations'])
packet_stats_result = device.fc.call_action(f'WLANConfiguration{index}', 'GetPacketStatistics')
obj_ref.metrics['wlanpackets'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'], wlan_result['NewSSID'], 'rx'],
packet_stats_result['NewTotalPacketsReceived'])
obj_ref.metrics['wlanpackets'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'], wlan_result['NewSSID'], 'tx'],
packet_stats_result['NewTotalPacketsSent'])
yield obj_ref.metrics['wlanstatus']
yield obj_ref.metrics['wlanchannel']
yield obj_ref.metrics['wlanassocs']
yield obj_ref.metrics['wlanpackets']
class WlanConfigurationInfo2_4GHz(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 1)
def createMetrics(self):
wlanCreateMetricsFactory(self, '2.4GHz')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 1, device)
class WlanConfigurationInfo5GHz(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 2)
def createMetrics(self):
wlanCreateMetricsFactory(self, '5GHz')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 2, device)
class WlanConfigurationInfoGuest(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 3)
def createMetrics(self):
wlanCreateMetricsFactory(self, 'guest')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 3, device)
| import logging
from abc import ABC, abstractmethod
from fritzconnection.core.exceptions import ActionError, ServiceError, FritzInternalError
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARN)
class FritzCapability(ABC):
capabilities = []
def __init__(self) -> None:
self.present = False
self.requirements = []
self.metrics = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
FritzCapability.capabilities.append(cls)
def checkCapability(self, device):
self.present = all([(service in device.fc.services) and (action in device.fc.services[service].actions) for (service, action) in self.requirements])
logger.debug(f'Capability {type(self).__name__} set to {self.present} on device {device.host}')
# It seems some boxes report service/actions they don't actually support. So try calling the requirements,
# and if it throws "InvalidService", "InvalidAction" or "FritzInternalError" disable this again.
if self.present:
for (svc, action) in self.requirements:
try:
device.fc.call_action(svc, action)
except (ServiceError, ActionError, FritzInternalError) as e:
logger.warn(f'disabling metrics at service {svc}, action {action} - fritzconnection.call_action returned {e}')
self.present = False
def getMetrics(self, devices, name):
for device in devices:
if device.capabilities[name].present:
yield from self._getMetricValues(device)
@abstractmethod
def createMetrics():
pass
@abstractmethod
def _getMetricValues(self, device):
pass
class FritzCapabilities():
def __init__(self, device=None) -> None:
self.capabilities = {capability.__name__: capability() for capability in FritzCapability.capabilities}
if device:
self.checkPresent(device)
def __iter__(self):
return iter(self.capabilities)
def __len__(self):
return len(self.capabilities)
def __getitem__(self, index):
return self.capabilities[index]
def items(self):
return self.capabilities.items()
def merge(self, other_caps):
for cap in self.capabilities:
self.capabilities[cap].present = self.capabilities[cap].present or other_caps.capabilities[cap].present
def empty(self):
return not any([cap.present for cap in list(self.capabilities.values())])
def checkPresent(self, device):
for c in self.capabilities:
self.capabilities[c].checkCapability(device)
class DeviceInfo(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('DeviceInfo1', 'GetInfo'))
def createMetrics(self):
self.metrics['uptime'] = CounterMetricFamily('fritz_uptime', 'FritzBox uptime, system info in labels',
labels=['modelname', 'softwareversion', 'serial', 'friendly_name'], unit='seconds')
def _getMetricValues(self, device):
info_result = device.fc.call_action('DeviceInfo:1', 'GetInfo')
self.metrics['uptime'].add_metric([info_result['NewModelName'], info_result['NewSoftwareVersion'], info_result['NewSerialNumber'],
device.friendly_name], info_result['NewUpTime'])
yield self.metrics['uptime']
class HostNumberOfEntries(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('Hosts1', 'GetHostNumberOfEntries'))
def createMetrics(self):
self.metrics['numhosts'] = GaugeMetricFamily('fritz_known_devices', 'Number of devices in hosts table',
labels=['serial', 'friendly_name'], unit='count')
def _getMetricValues(self, device):
num_hosts_result = device.fc.call_action('Hosts1', 'GetHostNumberOfEntries')
self.metrics['numhosts'].add_metric([device.serial, device.friendly_name], num_hosts_result['NewHostNumberOfEntries'])
yield self.metrics['numhosts']
# class HostInfo(FritzCapability):
# def __init__(self) -> None:
# super().__init__()
# self.requirements.append(('Hosts1', 'GetHostNumberOfEntries'))
# self.requirements.append(('Hosts1', 'GetGenericHostEntry'))
# self.requirements.append(('Hosts1', 'X_AVM-DE_GetSpecificHostEntryByIP'))
#
# def createMetrics(self):
# self.metrics['hostactive'] = GaugeMetricFamily('fritz_host_active', 'Indicates that the device is curently active',
# labels=['serial', 'ip_address', 'mac_address', 'hostname', 'interface', 'port', 'model'])
# self.metrics['hostspeed'] = GaugeMetricFamily('fritz_host_speed', 'Connection speed of the device',
# labels=['serial', 'ip_address', 'mac_address', 'hostname', 'interface', 'port', 'model'])
#
# def _getMetricValues(self, device):
# num_hosts_result = device.fc.call_action('Hosts1', 'GetHostNumberOfEntries')
# logger.debug(f'Fetching host information for device serial {device.serial} (hosts found: {num_hosts_result["NewHostNumberOfEntries"]}')
# for host_index in range(num_hosts_result['NewHostNumberOfEntries']):
# logger.debug(f'Fetching generic host information for host number {host_index}')
# host_result = device.fc.call_action('Hosts1', 'GetGenericHostEntry', NewIndex=host_index)
#
# host_ip = host_result['NewIPAddress']
# host_mac = host_result['NewMACAddress']
# host_name = host_result['NewHostName']
#
# if host_ip != "":
# logger.debug(f'Fetching extended AVM host information for host number {host_index} by IP {host_ip}')
# avm_host_result = device.fc.call_action('Hosts1', 'X_AVM-DE_GetSpecificHostEntryByIP', NewIPAddress=host_ip)
# host_interface = avm_host_result['NewInterfaceType']
# host_port = str(avm_host_result['NewX_AVM-DE_Port'])
# host_model = avm_host_result['NewX_AVM-DE_Model']
# host_speed = avm_host_result['NewX_AVM-DE_Speed']
# else:
# logger.debug(f'Unable to fetch extended AVM host information for host number {host_index}: no IP found')
# host_interface = "n/a"
# host_port = "n/a"
# host_model = "n/a"
# host_speed = 0
#
# host_active = 1.0 if host_result['NewActive'] else 0.0
# self.metrics['hostactive'].add_metric([device.serial, host_ip, host_mac, host_name, host_interface, host_port, host_model], host_active)
# self.metrics['hostspeed'].add_metric([device.serial, host_ip, host_mac, host_name, host_interface, host_port, host_model], host_speed)
#
# yield self.metrics['hostactive']
# yield self.metrics['hostspeed']
class UserInterface(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('UserInterface1', 'GetInfo'))
def createMetrics(self):
self.metrics['update'] = GaugeMetricFamily('fritz_update_available', 'FritzBox update available',
labels=['serial', 'friendly_name', 'newsoftwareversion'])
def _getMetricValues(self, device):
update_result = device.fc.call_action('UserInterface:1', 'GetInfo')
upd_available = 1 if update_result['NewUpgradeAvailable'] else 0
new_software_version = update_result['NewX_AVM-DE_Version'] if update_result['NewUpgradeAvailable'] else 'n/a'
self.metrics['update'].add_metric([device.serial, device.friendly_name, new_software_version], upd_available)
yield self.metrics['update']
class LanInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('LANEthernetInterfaceConfig1', 'GetInfo'))
def createMetrics(self):
self.metrics['lanenable'] = GaugeMetricFamily('fritz_lan_status_enabled', 'LAN Interface enabled', labels=['serial', 'friendly_name'])
self.metrics['lanstatus'] = GaugeMetricFamily('fritz_lan_status', 'LAN Interface status', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
lanstatus_result = device.fc.call_action('LANEthernetInterfaceConfig:1', 'GetInfo')
self.metrics['lanenable'].add_metric([device.serial, device.friendly_name], lanstatus_result['NewEnable'])
lanstatus = 1 if lanstatus_result['NewStatus'] == 'Up' else 0
self.metrics['lanstatus'].add_metric([device.serial, device.friendly_name], lanstatus)
yield self.metrics['lanenable']
yield self.metrics['lanstatus']
class LanInterfaceConfigStatistics(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('LANEthernetInterfaceConfig1', 'GetStatistics'))
def createMetrics(self):
self.metrics['lanbytes'] = CounterMetricFamily('fritz_lan_data', 'LAN bytes received', labels=['serial', 'friendly_name', 'direction'], unit='bytes')
self.metrics['lanpackets'] = CounterMetricFamily('fritz_lan_packet', 'LAN packets transmitted',
labels=['serial', 'friendly_name', 'direction'], unit='count')
def _getMetricValues(self, device):
lanstats_result = device.fc.call_action('LANEthernetInterfaceConfig:1', 'GetStatistics')
self.metrics['lanbytes'].add_metric([device.serial, device.friendly_name, 'rx'], lanstats_result['NewBytesReceived'])
self.metrics['lanbytes'].add_metric([device.serial, device.friendly_name, 'tx'], lanstats_result['NewBytesSent'])
self.metrics['lanpackets'].add_metric([device.serial, device.friendly_name, 'rx'], lanstats_result['NewPacketsReceived'])
self.metrics['lanpackets'].add_metric([device.serial, device.friendly_name, 'tx'], lanstats_result['NewPacketsSent'])
yield self.metrics['lanbytes']
yield self.metrics['lanpackets']
class WanDSLInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANDSLInterfaceConfig1', 'GetInfo'))
def createMetrics(self):
self.metrics['enable'] = GaugeMetricFamily('fritz_dsl_status_enabled', 'DSL enabled', labels=['serial', 'friendly_name'])
self.metrics['datarate'] = GaugeMetricFamily('fritz_dsl_datarate', 'DSL datarate in kbps',
labels=['serial', 'friendly_name', 'direction', 'type'], unit='kbps')
self.metrics['noisemargin'] = GaugeMetricFamily('fritz_dsl_noise_margin', 'Noise Margin in dB',
labels=['serial', 'friendly_name', 'direction'], unit='dB')
self.metrics['attenuation'] = GaugeMetricFamily('fritz_dsl_attenuation', 'Line attenuation in dB',
labels=['serial', 'friendly_name', 'direction'], unit='dB')
self.metrics['status'] = GaugeMetricFamily('fritz_dsl_status', 'DSL status', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
fritz_dslinfo_result = device.fc.call_action('WANDSLInterfaceConfig:1', 'GetInfo')
self.metrics['enable'].add_metric([device.serial, device.friendly_name], fritz_dslinfo_result['NewEnable'])
dslstatus = 1 if fritz_dslinfo_result['NewStatus'] == 'Up' else 0
self.metrics['status'].add_metric([device.serial, device.friendly_name], dslstatus)
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'tx', 'curr'], fritz_dslinfo_result['NewUpstreamCurrRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'rx', 'curr'], fritz_dslinfo_result['NewDownstreamCurrRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'tx', 'max'], fritz_dslinfo_result['NewUpstreamMaxRate'])
self.metrics['datarate'].add_metric([device.serial, device.friendly_name, 'rx', 'max'], fritz_dslinfo_result['NewDownstreamMaxRate'])
self.metrics['noisemargin'].add_metric([device.serial, device.friendly_name, 'tx'], fritz_dslinfo_result['NewUpstreamNoiseMargin']/10)
self.metrics['noisemargin'].add_metric([device.serial, device.friendly_name, 'rx'], fritz_dslinfo_result['NewDownstreamNoiseMargin']/10)
self.metrics['attenuation'].add_metric([device.serial, device.friendly_name, 'tx'], fritz_dslinfo_result['NewUpstreamAttenuation']/10)
self.metrics['attenuation'].add_metric([device.serial, device.friendly_name, 'rx'], fritz_dslinfo_result['NewDownstreamAttenuation']/10)
yield self.metrics['enable']
yield self.metrics['status']
yield self.metrics['datarate']
yield self.metrics['noisemargin']
yield self.metrics['attenuation']
class WanDSLInterfaceConfigAVM(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANDSLInterfaceConfig1', 'X_AVM-DE_GetDSLInfo'))
def createMetrics(self):
self.metrics['fec'] = CounterMetricFamily('fritz_dsl_fec_errors_count', 'Number of Forward Error Correction Errors', labels=['serial', 'friendly_name'])
self.metrics['crc'] = CounterMetricFamily('fritz_dsl_crc_errors_count', 'Number of CRC Errors', labels=['serial', 'friendly_name'])
def _getMetricValues(self, device):
fritz_avm_dsl_result = device.fc.call_action('WANDSLInterfaceConfig1', 'X_AVM-DE_GetDSLInfo')
self.metrics['fec'].add_metric([device.serial, device.friendly_name], fritz_avm_dsl_result['NewFECErrors'])
self.metrics['crc'].add_metric([device.serial, device.friendly_name], fritz_avm_dsl_result['NewCRCErrors'])
yield self.metrics['fec']
yield self.metrics['crc']
class WanPPPConnectionStatus(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANPPPConnection1', 'GetStatusInfo'))
def createMetrics(self):
self.metrics['uptime'] = CounterMetricFamily('fritz_ppp_connection_uptime', 'PPP connection uptime', labels=['serial', 'friendly_name'], unit='seconds')
self.metrics['connected'] = GaugeMetricFamily('fritz_ppp_connection_state', 'PPP connection state', labels=['serial', 'friendly_name', 'last_error'])
def _getMetricValues(self, device):
fritz_pppstatus_result = device.fc.call_action('WANPPPConnection:1', 'GetStatusInfo')
pppconnected = 1 if fritz_pppstatus_result['NewConnectionStatus'] == 'Connected' else 0
self.metrics['uptime'].add_metric([device.serial, device.friendly_name], fritz_pppstatus_result['NewUptime'])
self.metrics['connected'].add_metric([device.serial, device.friendly_name, fritz_pppstatus_result['NewLastConnectionError']], pppconnected)
yield self.metrics['uptime']
yield self.metrics['connected']
class WanCommonInterfaceConfig(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetCommonLinkProperties'))
def createMetrics(self):
self.metrics['wanconfig'] = GaugeMetricFamily('fritz_wan_max_bitrate', 'max bitrate at the physical layer',
labels=['serial', 'friendly_name', 'wantype', 'direction'], unit='bps')
self.metrics['wanlinkstatus'] = GaugeMetricFamily('fritz_wan_phys_link_status', 'link status at the physical layer',
labels=['serial', 'friendly_name', 'wantype'])
def _getMetricValues(self, device):
wanstatus_result = device.fc.call_action('WANCommonInterfaceConfig1', 'GetCommonLinkProperties')
self.metrics['wanconfig'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType'], 'tx'],
wanstatus_result['NewLayer1UpstreamMaxBitRate'])
self.metrics['wanconfig'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType'], 'rx'],
wanstatus_result['NewLayer1DownstreamMaxBitRate'])
l1_status = wanstatus_result['NewPhysicalLinkStatus']
wanstatus = 1 if l1_status == "Up" else 0
self.metrics['wanlinkstatus'].add_metric([device.serial, device.friendly_name, wanstatus_result['NewWANAccessType']], wanstatus)
yield self.metrics['wanconfig']
yield self.metrics['wanlinkstatus']
class WanCommonInterfaceDataBytes(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalBytesReceived'))
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalBytesSent'))
def createMetrics(self):
self.metrics['wanbytes'] = CounterMetricFamily('fritz_wan_data', 'WAN data in bytes', labels=['serial', 'friendly_name', 'direction'], unit='bytes')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalBytesReceived')
wan_bytes_rx = fritz_wan_result['NewTotalBytesReceived']
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalBytesSent')
wan_bytes_tx = fritz_wan_result['NewTotalBytesSent']
self.metrics['wanbytes'].add_metric([device.serial, device.friendly_name, 'tx'], wan_bytes_tx)
self.metrics['wanbytes'].add_metric([device.serial, device.friendly_name, 'rx'], wan_bytes_rx)
yield self.metrics['wanbytes']
class WanCommonInterfaceByteRate(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonIFC1', 'GetAddonInfos'))
def createMetrics(self):
self.metrics['wanbyterate'] = GaugeMetricFamily('fritz_wan_datarate', 'Current WAN data rate in bytes/s',
labels=['serial', 'friendly_name', 'direction'], unit='bytes')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonIFC1', 'GetAddonInfos')
wan_byterate_rx = fritz_wan_result['NewByteReceiveRate']
wan_byterate_tx = fritz_wan_result['NewByteSendRate']
self.metrics['wanbyterate'].add_metric([device.serial, device.friendly_name, 'rx'], wan_byterate_rx)
self.metrics['wanbyterate'].add_metric([device.serial, device.friendly_name, 'tx'], wan_byterate_tx)
yield self.metrics['wanbyterate']
class WanCommonInterfaceDataPackets(FritzCapability):
def __init__(self) -> None:
super().__init__()
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalPacketsReceived'))
self.requirements.append(('WANCommonInterfaceConfig1', 'GetTotalPacketsSent'))
def createMetrics(self):
self.metrics['wanpackets'] = CounterMetricFamily('fritz_wan_data_packets', 'WAN data in packets',
labels=['serial', 'friendly_name', 'direction'], unit='count')
def _getMetricValues(self, device):
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalPacketsReceived')
wan_packets_rx = fritz_wan_result['NewTotalPacketsReceived']
fritz_wan_result = device.fc.call_action('WANCommonInterfaceConfig:1', 'GetTotalPacketsSent')
wan_packets_tx = fritz_wan_result['NewTotalPacketsSent']
self.metrics['wanpackets'].add_metric([device.serial, device.friendly_name, 'tx'], wan_packets_tx)
self.metrics['wanpackets'].add_metric([device.serial, device.friendly_name, 'rx'], wan_packets_rx)
yield self.metrics['wanpackets']
def wlanConsructorFactory(obj_ref, index):
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetInfo'))
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetTotalAssociations'))
obj_ref.requirements.append((f'WLANConfiguration{index}', 'GetPacketStatistics'))
def wlanCreateMetricsFactory(obj_ref, name):
m_name = name.replace('.', '_')
obj_ref.metrics['wlanstatus'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_status', f'Status of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'])
obj_ref.metrics['wlanchannel'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_channel', f'Channel of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'])
obj_ref.metrics['wlanassocs'] = GaugeMetricFamily(f'fritz_wifi_{m_name}_associations', f'Number of associations (devices) of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid'], unit='count')
obj_ref.metrics['wlanpackets'] = CounterMetricFamily(f'fritz_wifi_{m_name}_packets', f'Amount of packets of the {name} WiFi',
labels=['serial', 'friendly_name', 'enabled', 'standard', 'ssid', 'direction'], unit='count')
def wlanGetMetricsFactory(obj_ref, index, device):
wlan_result = device.fc.call_action(f'WLANConfiguration{index}', 'GetInfo')
wlan_status = 1 if wlan_result['NewStatus'] == "Up" else 0
wlan_enabled = '1' if wlan_result['NewEnable'] else '0'
obj_ref.metrics['wlanstatus'].add_metric([device.serial, device.friendly_name, wlan_enabled,
wlan_result['NewStandard'], wlan_result['NewSSID']], wlan_status)
obj_ref.metrics['wlanchannel'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'],
wlan_result['NewSSID']], wlan_result['NewChannel'])
assoc_results = device.fc.call_action(f'WLANConfiguration{index}', 'GetTotalAssociations')
obj_ref.metrics['wlanassocs'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'],
wlan_result['NewSSID']], assoc_results['NewTotalAssociations'])
packet_stats_result = device.fc.call_action(f'WLANConfiguration{index}', 'GetPacketStatistics')
obj_ref.metrics['wlanpackets'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'], wlan_result['NewSSID'], 'rx'],
packet_stats_result['NewTotalPacketsReceived'])
obj_ref.metrics['wlanpackets'].add_metric([device.serial, device.friendly_name, wlan_enabled, wlan_result['NewStandard'], wlan_result['NewSSID'], 'tx'],
packet_stats_result['NewTotalPacketsSent'])
yield obj_ref.metrics['wlanstatus']
yield obj_ref.metrics['wlanchannel']
yield obj_ref.metrics['wlanassocs']
yield obj_ref.metrics['wlanpackets']
class WlanConfigurationInfo2_4GHz(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 1)
def createMetrics(self):
wlanCreateMetricsFactory(self, '2.4GHz')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 1, device)
class WlanConfigurationInfo5GHz(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 2)
def createMetrics(self):
wlanCreateMetricsFactory(self, '5GHz')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 2, device)
class WlanConfigurationInfoGuest(FritzCapability):
def __init__(self) -> None:
super().__init__()
wlanConsructorFactory(self, 3)
def createMetrics(self):
wlanCreateMetricsFactory(self, 'guest')
def _getMetricValues(self, device):
yield from wlanGetMetricsFactory(self, 3, device)
|
import traceback
import argparse
import numpy as np
from src import NeuralNetwork
from typing import *
def get_args() -> argparse.Namespace:
"""Set-up the argument parser
Returns:
argparse.Namespace:
"""
parser = argparse.ArgumentParser(
description='Project 1 for the Deep Learning class (COSC 525). '
'Involves the development of a Feed-Forward Neural Network.',
add_help=False)
# Required Args
required_args = parser.add_argument_group('Required Arguments')
required_args.add_argument('-d', '--dataset', required=True,
help="The datasets to train the network on. "
"Options: [and, xor, class_example]")
required_args.add_argument('-n', '--network', required=True,
help="The network configuration to use. "
"Options: [1x1_net, 2x1_net, 2x2_net]")
# Optional args
optional_args = parser.add_argument_group('Optional Arguments')
optional_args.add_argument("-h", "--help", action="help", help="Show this help message and exit")
return parser.parse_args()
def get_network_config(network_name: str) -> Dict[str, Any]:
"""Get the network configuration
Args:
network_name (str): The name of the network to get the configuration for
Returns:
Dict[str, Any]: The network configuration
"""
nn_conf = {}
if network_name == '1x1_net':
nn_conf['neurons_per_layer'] = [1]
nn_conf['activations'] = ['logistic']
nn_conf['loss_function'] = 'square_error'
nn_conf['learning_rate'] = 5
nn_conf['epochs'] = 5000
nn_conf['print_every'] = 500
elif network_name == '2x1_net':
nn_conf['neurons_per_layer'] = [2, 1]
nn_conf['activations'] = ['logistic', 'logistic']
nn_conf['loss_function'] = 'square_error'
nn_conf['learning_rate'] = 5
nn_conf['epochs'] = 5000
nn_conf['print_every'] = 500
elif network_name == '2x2_net':
nn_conf['neurons_per_layer'] = [2, 2]
nn_conf['activations'] = ['logistic', 'logistic']
nn_conf['loss_function'] = 'cross_entropy'
nn_conf['learning_rate'] = 0.5
nn_conf['epochs'] = 100
nn_conf['print_every'] = 100
else:
raise ValueError(f"Network name {network_name} not recognized.")
return nn_conf
def get_dataset_config(dataset_name: str) -> Dict[str, Any]:
"""Get the dataset configuration
Args:
dataset_name (str): The name of the dataset to get the configuration for
Returns:
Dict[str, Any]: The dataset configuration
"""
dataset_conf = {}
if dataset_name == 'and':
dataset_conf['inputs'] = [[0, 0], [0, 1], [1, 0], [1, 1]]
dataset_conf['outputs'] = [[0], [0], [0], [1]]
elif dataset_name == 'xor':
dataset_conf['inputs'] = [[0, 0], [0, 1], [1, 0], [1, 1]]
dataset_conf['outputs'] = [[0], [1], [1], [0]]
elif dataset_name == 'class_example':
dataset_conf['inputs'] = [0.05, 0.1]
dataset_conf['desired_outputs'] = [0.01, 0.99]
dataset_conf['weights'] = [[[0.15, 0.20, 0.35], [0.25, 0.30, 0.35]],
[[0.40, 0.45, 0.60], [0.50, 0.55, 0.60]]]
else:
raise ValueError(f"Dataset name {dataset_name} not recognized.")
return dataset_conf
def main():
"""This is the main function of main.py
Example:
python main.py --dataset xor --network 2x1_net
"""
# Initializing
args = get_args()
# Load the configurations
nn_type = args.network
nn_conf = get_network_config(nn_type)
dataset_type = args.dataset
dataset_conf = get_dataset_config(dataset_type)
# ------- Start of Code ------- #
print()
print(f'Training the `{nn_type}` network on the `{dataset_type}` dataset.')
if args.dataset != 'class_example': # XOR and AND cases
# Train the network
inputs = np.array(dataset_conf['inputs'])
outputs = np.array(dataset_conf['outputs'])
# Initialize the network
netWork = NeuralNetwork(input_size=inputs.shape[1],
loss_function=nn_conf['loss_function'],
learning_rate=nn_conf['learning_rate'])
# Add the layers
for num_neurons, activation in zip(nn_conf['neurons_per_layer'], nn_conf['activations']):
netWork.addFCLayer(num_neurons=num_neurons, activation=activation)
# Train the network for the given number of epochs
for epoch in range(nn_conf['epochs']):
netWork.train(inputs, outputs) # Train the network
loss = netWork.calculate_loss(inputs, outputs) # Calculate the loss
if epoch % nn_conf['print_every'] == 0:
print(f"Epoch: {epoch} Loss: {loss}")
print(f"Epoch: {nn_conf["epochs"]} Loss: {loss}")
# Test on the predictions
print(f'Predictions on the {dataset_type} dataset')
for inp, outp in zip(inputs, outputs):
print(f"True Output: {outp} Prediction: {netWork.calculate(inp)[0]}")
else: # Class Example
# Set up the weights and biases based on the class example
inputs = [np.array(dataset_conf['inputs'])]
desired_outputs = np.array(dataset_conf['desired_outputs'])
weights = [np.array(weight) for weight in dataset_conf['weights']]
# Initialize the network using the predefined weights and biases
netWork = NeuralNetwork(input_size=2,
loss_function=nn_conf['loss_function'],
learning_rate=nn_conf['learning_rate'])
# Add the layers
for num_neurons, activation, weights_ in \
zip(nn_conf['neurons_per_layer'], nn_conf['activations'], weights):
netWork.addFCLayer(num_neurons=num_neurons, activation=activation,
weights=weights_)
# Print the network inputs and weights before training
print("Pre-training Inputs:")
print(f"{inputs[0]}")
print("Pre-training Weights:")
print(f"{netWork.layers[0].neurons[0].weights} (h1) x "
"{netWork.layers[1].neurons[0].weights} (O1)")
print(f"{netWork.layers[0].neurons[1].weights} (h1) x "
"{netWork.layers[1].neurons[1].weights} (O1)")
# Activate the network
outputs = netWork.calculate(inputs[0]) # Feed-forward the network
print(f"Outputs after calling `activate()`:")
print(f"{outputs}")
# Calculate the wdeltas - single step of backpropagation
wdeltas = [netWork.loss_derivative(np.array(outputs), desired_outputs)]
for j in range(len(netWork.layers) - 1, -1, -1):
wdeltas = netWork.layers[j].calculate_wdeltas(wdeltas)
# Print the wdeltas, the weights, and the outputs after backpropagation
print("Wdeltas after calling `calculate_wdeltas()`:")
print(f"{wdeltas}")
print("Weights after a single step of back-propagation:")
print(f"{netWork.layers[0].neurons[0].weights} (h1) x "
"{netWork.layers[1].neurons[0].weights} (O1)")
print(f"{netWork.layers[0].neurons[1].weights} (h1) x "
"{netWork.layers[1].neurons[1].weights} (O1)")
outputs = netWork.calculate(inputs[0])
print("Post-training Outputs:")
print(f"{outputs}")
if __name__ == '__main__':
try:
main()
except Exception as e:
print(str(e) + '\n' + str(traceback.format_exc()))
raise e
| import traceback
import argparse
import numpy as np
from src import NeuralNetwork
from typing import *
def get_args() -> argparse.Namespace:
"""Set-up the argument parser
Returns:
argparse.Namespace:
"""
parser = argparse.ArgumentParser(
description='Project 1 for the Deep Learning class (COSC 525). '
'Involves the development of a Feed-Forward Neural Network.',
add_help=False)
# Required Args
required_args = parser.add_argument_group('Required Arguments')
required_args.add_argument('-d', '--dataset', required=True,
help="The datasets to train the network on. "
"Options: [and, xor, class_example]")
required_args.add_argument('-n', '--network', required=True,
help="The network configuration to use. "
"Options: [1x1_net, 2x1_net, 2x2_net]")
# Optional args
optional_args = parser.add_argument_group('Optional Arguments')
optional_args.add_argument("-h", "--help", action="help", help="Show this help message and exit")
return parser.parse_args()
def get_network_config(network_name: str) -> Dict[str, Any]:
"""Get the network configuration
Args:
network_name (str): The name of the network to get the configuration for
Returns:
Dict[str, Any]: The network configuration
"""
nn_conf = {}
if network_name == '1x1_net':
nn_conf['neurons_per_layer'] = [1]
nn_conf['activations'] = ['logistic']
nn_conf['loss_function'] = 'square_error'
nn_conf['learning_rate'] = 5
nn_conf['epochs'] = 5000
nn_conf['print_every'] = 500
elif network_name == '2x1_net':
nn_conf['neurons_per_layer'] = [2, 1]
nn_conf['activations'] = ['logistic', 'logistic']
nn_conf['loss_function'] = 'square_error'
nn_conf['learning_rate'] = 5
nn_conf['epochs'] = 5000
nn_conf['print_every'] = 500
elif network_name == '2x2_net':
nn_conf['neurons_per_layer'] = [2, 2]
nn_conf['activations'] = ['logistic', 'logistic']
nn_conf['loss_function'] = 'cross_entropy'
nn_conf['learning_rate'] = 0.5
nn_conf['epochs'] = 100
nn_conf['print_every'] = 100
else:
raise ValueError(f"Network name {network_name} not recognized.")
return nn_conf
def get_dataset_config(dataset_name: str) -> Dict[str, Any]:
"""Get the dataset configuration
Args:
dataset_name (str): The name of the dataset to get the configuration for
Returns:
Dict[str, Any]: The dataset configuration
"""
dataset_conf = {}
if dataset_name == 'and':
dataset_conf['inputs'] = [[0, 0], [0, 1], [1, 0], [1, 1]]
dataset_conf['outputs'] = [[0], [0], [0], [1]]
elif dataset_name == 'xor':
dataset_conf['inputs'] = [[0, 0], [0, 1], [1, 0], [1, 1]]
dataset_conf['outputs'] = [[0], [1], [1], [0]]
elif dataset_name == 'class_example':
dataset_conf['inputs'] = [0.05, 0.1]
dataset_conf['desired_outputs'] = [0.01, 0.99]
dataset_conf['weights'] = [[[0.15, 0.20, 0.35], [0.25, 0.30, 0.35]],
[[0.40, 0.45, 0.60], [0.50, 0.55, 0.60]]]
else:
raise ValueError(f"Dataset name {dataset_name} not recognized.")
return dataset_conf
def main():
"""This is the main function of main.py
Example:
python main.py --dataset xor --network 2x1_net
"""
# Initializing
args = get_args()
# Load the configurations
nn_type = args.network
nn_conf = get_network_config(nn_type)
dataset_type = args.dataset
dataset_conf = get_dataset_config(dataset_type)
# ------- Start of Code ------- #
print()
print(f'Training the `{nn_type}` network on the `{dataset_type}` dataset.')
if args.dataset != 'class_example': # XOR and AND cases
# Train the network
inputs = np.array(dataset_conf['inputs'])
outputs = np.array(dataset_conf['outputs'])
# Initialize the network
netWork = NeuralNetwork(input_size=inputs.shape[1],
loss_function=nn_conf['loss_function'],
learning_rate=nn_conf['learning_rate'])
# Add the layers
for num_neurons, activation in zip(nn_conf['neurons_per_layer'], nn_conf['activations']):
netWork.addFCLayer(num_neurons=num_neurons, activation=activation)
# Train the network for the given number of epochs
for epoch in range(nn_conf['epochs']):
netWork.train(inputs, outputs) # Train the network
loss = netWork.calculate_loss(inputs, outputs) # Calculate the loss
if epoch % nn_conf['print_every'] == 0:
print(f"Epoch: {epoch} Loss: {loss}")
print(f"Epoch: {nn_conf['epochs']} Loss: {loss}")
# Test on the predictions
print(f'Predictions on the {dataset_type} dataset')
for inp, outp in zip(inputs, outputs):
print(f"True Output: {outp} Prediction: {netWork.calculate(inp)[0]}")
else: # Class Example
# Set up the weights and biases based on the class example
inputs = [np.array(dataset_conf['inputs'])]
desired_outputs = np.array(dataset_conf['desired_outputs'])
weights = [np.array(weight) for weight in dataset_conf['weights']]
# Initialize the network using the predefined weights and biases
netWork = NeuralNetwork(input_size=2,
loss_function=nn_conf['loss_function'],
learning_rate=nn_conf['learning_rate'])
# Add the layers
for num_neurons, activation, weights_ in \
zip(nn_conf['neurons_per_layer'], nn_conf['activations'], weights):
netWork.addFCLayer(num_neurons=num_neurons, activation=activation,
weights=weights_)
# Print the network inputs and weights before training
print("Pre-training Inputs:")
print(f"{inputs[0]}")
print("Pre-training Weights:")
print(f"{netWork.layers[0].neurons[0].weights} (h1) x "
"{netWork.layers[1].neurons[0].weights} (O1)")
print(f"{netWork.layers[0].neurons[1].weights} (h1) x "
"{netWork.layers[1].neurons[1].weights} (O1)")
# Activate the network
outputs = netWork.calculate(inputs[0]) # Feed-forward the network
print(f"Outputs after calling `activate()`:")
print(f"{outputs}")
# Calculate the wdeltas - single step of backpropagation
wdeltas = [netWork.loss_derivative(np.array(outputs), desired_outputs)]
for j in range(len(netWork.layers) - 1, -1, -1):
wdeltas = netWork.layers[j].calculate_wdeltas(wdeltas)
# Print the wdeltas, the weights, and the outputs after backpropagation
print("Wdeltas after calling `calculate_wdeltas()`:")
print(f"{wdeltas}")
print("Weights after a single step of back-propagation:")
print(f"{netWork.layers[0].neurons[0].weights} (h1) x "
"{netWork.layers[1].neurons[0].weights} (O1)")
print(f"{netWork.layers[0].neurons[1].weights} (h1) x "
"{netWork.layers[1].neurons[1].weights} (O1)")
outputs = netWork.calculate(inputs[0])
print("Post-training Outputs:")
print(f"{outputs}")
if __name__ == '__main__':
try:
main()
except Exception as e:
print(str(e) + '\n' + str(traceback.format_exc()))
raise e
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility classes for representing QASM."""
from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING
import re
import numpy as np
from cirq import ops, linalg, protocols, value
if TYPE_CHECKING:
import cirq
@value.value_equality(approximate=True)
class QasmUGate(ops.SingleQubitGate):
def __init__(self, theta, phi, lmda) -> None:
"""A QASM gate representing any single qubit unitary with a series of
three rotations, Z, Y, and Z.
The angles are normalized to the range [0, 2) half_turns.
Args:
theta: Half turns to rotate about Y (applied second).
phi: Half turns to rotate about Z (applied last).
lmda: Half turns to rotate about Z (applied first).
"""
self.lmda = lmda % 2
self.theta = theta % 2
self.phi = phi % 2
@staticmethod
def from_matrix(mat: np.array) -> 'QasmUGate':
pre_phase, rotation, post_phase = linalg.deconstruct_single_qubit_matrix_into_angles(mat)
return QasmUGate(
rotation / np.pi,
post_phase / np.pi,
pre_phase / np.pi,
)
def _has_unitary_(self):
return True
def _qasm_(self, qubits: Tuple['cirq.Qid', ...], args: 'cirq.QasmArgs') -> str:
args.validate_version('2.0')
return args.format(
'u3({0:half_turns},{1:half_turns},{2:half_turns}) {3};\n',
self.theta,
self.phi,
self.lmda,
qubits[0],
)
def __repr__(self) -> str:
return (
f'cirq.circuits.qasm_output.QasmUGate('
f'theta={self.theta!r}, '
f'phi={self.phi!r}, '
f'lmda={self.lmda})'
)
def _decompose_(self, qubits):
q = qubits[0]
return [
ops.rz(self.lmda * np.pi).on(q),
ops.ry(self.theta * np.pi).on(q),
ops.rz(self.phi * np.pi).on(q),
]
def _value_equality_values_(self):
return self.lmda, self.theta, self.phi
@value.value_equality
class QasmTwoQubitGate(ops.TwoQubitGate):
def __init__(self, kak: linalg.KakDecomposition) -> None:
"""A two qubit gate represented in QASM by the KAK decomposition.
All angles are in half turns. Assumes a canonicalized KAK
decomposition.
Args:
kak: KAK decomposition of the two-qubit gate.
"""
self.kak = kak
def _value_equality_values_(self):
return self.kak
@staticmethod
def from_matrix(mat: np.array, atol=1e-8) -> 'QasmTwoQubitGate':
"""Creates a QasmTwoQubitGate from the given matrix.
Args:
mat: The unitary matrix of the two qubit gate.
atol: Absolute error tolerance when decomposing.
Returns:
A QasmTwoQubitGate implementing the matrix.
"""
kak = linalg.kak_decomposition(mat, atol=atol)
return QasmTwoQubitGate(kak)
def _unitary_(self):
return protocols.unitary(self.kak)
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
q0, q1 = qubits
x, y, z = self.kak.interaction_coefficients
a = x * -2 / np.pi + 0.5
b = y * -2 / np.pi + 0.5
c = z * -2 / np.pi + 0.5
b0, b1 = self.kak.single_qubit_operations_before
yield QasmUGate.from_matrix(b0).on(q0)
yield QasmUGate.from_matrix(b1).on(q1)
yield ops.X(q0) ** 0.5
yield ops.CNOT(q0, q1)
yield ops.X(q0) ** a
yield ops.Y(q1) ** b
yield ops.CNOT(q1, q0)
yield ops.X(q1) ** -0.5
yield ops.Z(q1) ** c
yield ops.CNOT(q0, q1)
a0, a1 = self.kak.single_qubit_operations_after
yield QasmUGate.from_matrix(a0).on(q0)
yield QasmUGate.from_matrix(a1).on(q1)
def __repr__(self) -> str:
return f'cirq.circuits.qasm_output.QasmTwoQubitGate({self.kak!r})'
class QasmOutput:
"""Representation of a circuit in QASM (quantum assembly) format.
Please note that the QASM importer is in an experimental state and
currently only supports a subset of the full OpenQASM spec.
Amongst others, classical control, arbitrary gate definitions,
and even some of the gates that don't have a one-to-one representation
in Cirq, are not yet supported.
QASM output can be saved to a file using the save method.
"""
valid_id_re = re.compile(r'[a-z][a-zA-Z0-9_]*\Z')
def __init__(
self,
operations: 'cirq.OP_TREE',
qubits: Tuple['cirq.Qid', ...],
header: str = '',
precision: int = 10,
version: str = '2.0',
) -> None:
self.operations = tuple(ops.flatten_to_ops(operations))
self.qubits = qubits
self.header = header
self.measurements = tuple(
op for op in self.operations if isinstance(op.gate, ops.MeasurementGate)
)
meas_key_id_map, meas_comments = self._generate_measurement_ids()
self.meas_comments = meas_comments
qubit_id_map = self._generate_qubit_ids()
self.args = protocols.QasmArgs(
precision=precision,
version=version,
qubit_id_map=qubit_id_map,
meas_key_id_map=meas_key_id_map,
)
def _generate_measurement_ids(self) -> Tuple[Dict[str, str], Dict[str, Optional[str]]]:
# Pick an id for the creg that will store each measurement
meas_key_id_map = {} # type: Dict[str, str]
meas_comments = {} # type: Dict[str, Optional[str]]
meas_i = 0
for meas in self.measurements:
key = protocols.measurement_key(meas)
if key in meas_key_id_map:
continue
meas_id = f'm_{key}'
if self.is_valid_qasm_id(meas_id):
meas_comments[key] = None
else:
meas_id = f'm{meas_i}'
meas_i += 1
meas_comments[key] = ' '.join(key.split('\n'))
meas_key_id_map[key] = meas_id
return meas_key_id_map, meas_comments
def _generate_qubit_ids(self) -> Dict['cirq.Qid', str]:
return {qubit: f'q[{i}]' for i, qubit in enumerate(self.qubits)}
def is_valid_qasm_id(self, id_str: str) -> bool:
"""Test if id_str is a valid id in QASM grammar."""
return self.valid_id_re.match(id_str) != None
def save(self, path: Union[str, bytes, int]) -> None:
"""Write QASM output to a file specified by path."""
with open(path, 'w') as f:
def write(s: str) -> None:
f.write(s)
self._write_qasm(write)
def __str__(self) -> str:
"""Return QASM output as a string."""
output = []
self._write_qasm(lambda s: output.append(s))
return ''.join(output)
def _write_qasm(self, output_func: Callable[[str], None]) -> None:
self.args.validate_version('2.0')
# Generate nice line spacing
line_gap = [0]
def output_line_gap(n):
line_gap[0] = max(line_gap[0], n)
def output(text):
if line_gap[0] > 0:
output_func('\n' * line_gap[0])
line_gap[0] = 0
output_func(text)
# Comment header
if self.header:
for line in self.header.split('\n'):
output(('// ' + line).rstrip() + '\n')
output('\n')
# Version
output('OPENQASM 2.0;\n')
output('include "qelib1.inc";\n')
output_line_gap(2)
# Function definitions
# None yet
# Register definitions
# Qubit registers
output(f"// Qubits: [{", ".join(map(str, self.qubits))}]\n")
if len(self.qubits) > 0:
output(f'qreg q[{len(self.qubits)}];\n')
# Classical registers
# Pick an id for the creg that will store each measurement
already_output_keys: Set[str] = set()
for meas in self.measurements:
key = protocols.measurement_key(meas)
if key in already_output_keys:
continue
already_output_keys.add(key)
meas_id = self.args.meas_key_id_map[key]
comment = self.meas_comments[key]
if comment is None:
output(f'creg {meas_id}[{len(meas.qubits)}];\n')
else:
output(f'creg {meas_id}[{len(meas.qubits)}]; // Measurement: {comment}\n')
output_line_gap(2)
# Operations
self._write_operations(self.operations, output, output_line_gap)
def _write_operations(
self,
op_tree: 'cirq.OP_TREE',
output: Callable[[str], None],
output_line_gap: Callable[[int], None],
) -> None:
def keep(op: 'cirq.Operation') -> bool:
return protocols.qasm(op, args=self.args, default=None) is not None
def fallback(op):
if len(op.qubits) not in [1, 2]:
return NotImplemented
mat = protocols.unitary(op, None)
if mat is None:
return NotImplemented
if len(op.qubits) == 1:
return QasmUGate.from_matrix(mat).on(*op.qubits)
return QasmTwoQubitGate.from_matrix(mat).on(*op.qubits)
def on_stuck(bad_op):
return ValueError(f'Cannot output operation as QASM: {bad_op!r}')
for main_op in ops.flatten_op_tree(op_tree):
decomposed = protocols.decompose(
main_op, keep=keep, fallback_decomposer=fallback, on_stuck_raise=on_stuck
)
qasms = [protocols.qasm(op, args=self.args) for op in decomposed]
should_annotate = decomposed != [main_op] or qasms[0].count('\n') > 1
if should_annotate:
output_line_gap(1)
if isinstance(main_op, ops.GateOperation):
x = str(main_op.gate).replace('\n', '\n //')
output(f'// Gate: {x!s}\n')
else:
x = str(main_op).replace('\n', '\n //')
output(f'// Operation: {x!s}\n')
for qasm in qasms:
output(qasm)
if should_annotate:
output_line_gap(1)
| # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility classes for representing QASM."""
from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING
import re
import numpy as np
from cirq import ops, linalg, protocols, value
if TYPE_CHECKING:
import cirq
@value.value_equality(approximate=True)
class QasmUGate(ops.SingleQubitGate):
def __init__(self, theta, phi, lmda) -> None:
"""A QASM gate representing any single qubit unitary with a series of
three rotations, Z, Y, and Z.
The angles are normalized to the range [0, 2) half_turns.
Args:
theta: Half turns to rotate about Y (applied second).
phi: Half turns to rotate about Z (applied last).
lmda: Half turns to rotate about Z (applied first).
"""
self.lmda = lmda % 2
self.theta = theta % 2
self.phi = phi % 2
@staticmethod
def from_matrix(mat: np.array) -> 'QasmUGate':
pre_phase, rotation, post_phase = linalg.deconstruct_single_qubit_matrix_into_angles(mat)
return QasmUGate(
rotation / np.pi,
post_phase / np.pi,
pre_phase / np.pi,
)
def _has_unitary_(self):
return True
def _qasm_(self, qubits: Tuple['cirq.Qid', ...], args: 'cirq.QasmArgs') -> str:
args.validate_version('2.0')
return args.format(
'u3({0:half_turns},{1:half_turns},{2:half_turns}) {3};\n',
self.theta,
self.phi,
self.lmda,
qubits[0],
)
def __repr__(self) -> str:
return (
f'cirq.circuits.qasm_output.QasmUGate('
f'theta={self.theta!r}, '
f'phi={self.phi!r}, '
f'lmda={self.lmda})'
)
def _decompose_(self, qubits):
q = qubits[0]
return [
ops.rz(self.lmda * np.pi).on(q),
ops.ry(self.theta * np.pi).on(q),
ops.rz(self.phi * np.pi).on(q),
]
def _value_equality_values_(self):
return self.lmda, self.theta, self.phi
@value.value_equality
class QasmTwoQubitGate(ops.TwoQubitGate):
def __init__(self, kak: linalg.KakDecomposition) -> None:
"""A two qubit gate represented in QASM by the KAK decomposition.
All angles are in half turns. Assumes a canonicalized KAK
decomposition.
Args:
kak: KAK decomposition of the two-qubit gate.
"""
self.kak = kak
def _value_equality_values_(self):
return self.kak
@staticmethod
def from_matrix(mat: np.array, atol=1e-8) -> 'QasmTwoQubitGate':
"""Creates a QasmTwoQubitGate from the given matrix.
Args:
mat: The unitary matrix of the two qubit gate.
atol: Absolute error tolerance when decomposing.
Returns:
A QasmTwoQubitGate implementing the matrix.
"""
kak = linalg.kak_decomposition(mat, atol=atol)
return QasmTwoQubitGate(kak)
def _unitary_(self):
return protocols.unitary(self.kak)
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
q0, q1 = qubits
x, y, z = self.kak.interaction_coefficients
a = x * -2 / np.pi + 0.5
b = y * -2 / np.pi + 0.5
c = z * -2 / np.pi + 0.5
b0, b1 = self.kak.single_qubit_operations_before
yield QasmUGate.from_matrix(b0).on(q0)
yield QasmUGate.from_matrix(b1).on(q1)
yield ops.X(q0) ** 0.5
yield ops.CNOT(q0, q1)
yield ops.X(q0) ** a
yield ops.Y(q1) ** b
yield ops.CNOT(q1, q0)
yield ops.X(q1) ** -0.5
yield ops.Z(q1) ** c
yield ops.CNOT(q0, q1)
a0, a1 = self.kak.single_qubit_operations_after
yield QasmUGate.from_matrix(a0).on(q0)
yield QasmUGate.from_matrix(a1).on(q1)
def __repr__(self) -> str:
return f'cirq.circuits.qasm_output.QasmTwoQubitGate({self.kak!r})'
class QasmOutput:
"""Representation of a circuit in QASM (quantum assembly) format.
Please note that the QASM importer is in an experimental state and
currently only supports a subset of the full OpenQASM spec.
Amongst others, classical control, arbitrary gate definitions,
and even some of the gates that don't have a one-to-one representation
in Cirq, are not yet supported.
QASM output can be saved to a file using the save method.
"""
valid_id_re = re.compile(r'[a-z][a-zA-Z0-9_]*\Z')
def __init__(
self,
operations: 'cirq.OP_TREE',
qubits: Tuple['cirq.Qid', ...],
header: str = '',
precision: int = 10,
version: str = '2.0',
) -> None:
self.operations = tuple(ops.flatten_to_ops(operations))
self.qubits = qubits
self.header = header
self.measurements = tuple(
op for op in self.operations if isinstance(op.gate, ops.MeasurementGate)
)
meas_key_id_map, meas_comments = self._generate_measurement_ids()
self.meas_comments = meas_comments
qubit_id_map = self._generate_qubit_ids()
self.args = protocols.QasmArgs(
precision=precision,
version=version,
qubit_id_map=qubit_id_map,
meas_key_id_map=meas_key_id_map,
)
def _generate_measurement_ids(self) -> Tuple[Dict[str, str], Dict[str, Optional[str]]]:
# Pick an id for the creg that will store each measurement
meas_key_id_map = {} # type: Dict[str, str]
meas_comments = {} # type: Dict[str, Optional[str]]
meas_i = 0
for meas in self.measurements:
key = protocols.measurement_key(meas)
if key in meas_key_id_map:
continue
meas_id = f'm_{key}'
if self.is_valid_qasm_id(meas_id):
meas_comments[key] = None
else:
meas_id = f'm{meas_i}'
meas_i += 1
meas_comments[key] = ' '.join(key.split('\n'))
meas_key_id_map[key] = meas_id
return meas_key_id_map, meas_comments
def _generate_qubit_ids(self) -> Dict['cirq.Qid', str]:
return {qubit: f'q[{i}]' for i, qubit in enumerate(self.qubits)}
def is_valid_qasm_id(self, id_str: str) -> bool:
"""Test if id_str is a valid id in QASM grammar."""
return self.valid_id_re.match(id_str) != None
def save(self, path: Union[str, bytes, int]) -> None:
"""Write QASM output to a file specified by path."""
with open(path, 'w') as f:
def write(s: str) -> None:
f.write(s)
self._write_qasm(write)
def __str__(self) -> str:
"""Return QASM output as a string."""
output = []
self._write_qasm(lambda s: output.append(s))
return ''.join(output)
def _write_qasm(self, output_func: Callable[[str], None]) -> None:
self.args.validate_version('2.0')
# Generate nice line spacing
line_gap = [0]
def output_line_gap(n):
line_gap[0] = max(line_gap[0], n)
def output(text):
if line_gap[0] > 0:
output_func('\n' * line_gap[0])
line_gap[0] = 0
output_func(text)
# Comment header
if self.header:
for line in self.header.split('\n'):
output(('// ' + line).rstrip() + '\n')
output('\n')
# Version
output('OPENQASM 2.0;\n')
output('include "qelib1.inc";\n')
output_line_gap(2)
# Function definitions
# None yet
# Register definitions
# Qubit registers
output(f"// Qubits: [{', '.join(map(str, self.qubits))}]\n")
if len(self.qubits) > 0:
output(f'qreg q[{len(self.qubits)}];\n')
# Classical registers
# Pick an id for the creg that will store each measurement
already_output_keys: Set[str] = set()
for meas in self.measurements:
key = protocols.measurement_key(meas)
if key in already_output_keys:
continue
already_output_keys.add(key)
meas_id = self.args.meas_key_id_map[key]
comment = self.meas_comments[key]
if comment is None:
output(f'creg {meas_id}[{len(meas.qubits)}];\n')
else:
output(f'creg {meas_id}[{len(meas.qubits)}]; // Measurement: {comment}\n')
output_line_gap(2)
# Operations
self._write_operations(self.operations, output, output_line_gap)
def _write_operations(
self,
op_tree: 'cirq.OP_TREE',
output: Callable[[str], None],
output_line_gap: Callable[[int], None],
) -> None:
def keep(op: 'cirq.Operation') -> bool:
return protocols.qasm(op, args=self.args, default=None) is not None
def fallback(op):
if len(op.qubits) not in [1, 2]:
return NotImplemented
mat = protocols.unitary(op, None)
if mat is None:
return NotImplemented
if len(op.qubits) == 1:
return QasmUGate.from_matrix(mat).on(*op.qubits)
return QasmTwoQubitGate.from_matrix(mat).on(*op.qubits)
def on_stuck(bad_op):
return ValueError(f'Cannot output operation as QASM: {bad_op!r}')
for main_op in ops.flatten_op_tree(op_tree):
decomposed = protocols.decompose(
main_op, keep=keep, fallback_decomposer=fallback, on_stuck_raise=on_stuck
)
qasms = [protocols.qasm(op, args=self.args) for op in decomposed]
should_annotate = decomposed != [main_op] or qasms[0].count('\n') > 1
if should_annotate:
output_line_gap(1)
if isinstance(main_op, ops.GateOperation):
x = str(main_op.gate).replace('\n', '\n //')
output(f'// Gate: {x!s}\n')
else:
x = str(main_op).replace('\n', '\n //')
output(f'// Operation: {x!s}\n')
for qasm in qasms:
output(qasm)
if should_annotate:
output_line_gap(1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
import re
from setuptools import setup, find_packages
from distutils.core import Command
class DepsCommand(Command):
"""A custom distutils command to print selective dependency groups.
# show available dependency groups:
python setup.py -q deps
# print dependency list for specified groups
python setup.py -q deps --dep-groups=core,vision
# see all options:
python setup.py -q deps --help
"""
description = 'show dependency groups and their packages'
user_options = [
# format: (long option, short option, description).
('dep-groups=', None, 'comma separated dependency groups'),
('dep-quote', None, 'quote each dependency'),
('dep-conda', None, 'adjust output for conda'),
]
def initialize_options(self):
"""Set default values for options."""
self.dep_groups = ''
self.dep_quote = False
self.dep_conda = False
def finalize_options(self):
"""Post-process options."""
pass
def parse(self):
arg = self.dep_groups.strip()
return re.split(r' *, *', arg) if len(arg) else []
def run(self):
"""Run command."""
wanted_groups = self.parse()
deps = []
invalid_groups = []
for grp in wanted_groups:
if grp in dep_groups: deps.extend(dep_groups[grp])
else: invalid_groups.append(grp)
if invalid_groups or not wanted_groups:
print("Available dependency groups:", ", ".join(sorted(dep_groups.keys())))
if invalid_groups:
print(f"Error: Invalid group name(s): {", ".join(invalid_groups)}")
exit(1)
else:
# prepare for shell word splitting (no whitespace in items)
deps = [re.sub(" ", "", x, 0) for x in sorted(set(deps))]
if self.dep_conda:
for i in range(len(deps)):
# strip pip-specific syntax
deps[i] = re.sub(r';.*', '', deps[i])
# rename mismatching package names
deps[i] = re.sub(r'^torch>', 'pytorch>', deps[i])
if self.dep_quote:
# for manual copy-n-paste (assuming no " in vars)
print(" ".join(map(lambda x: f'"{x}"', deps)))
else:
# if fed directly to `pip install` via backticks/$() don't quote
print(" ".join(deps))
# note: version is maintained inside fastai/version.py
exec(open('fastai/version.py').read())
with open('README.md') as readme_file: readme = readme_file.read()
# helper functions to make it easier to list dependencies not as a python list, but vertically w/ optional built-in comments to why a certain version of the dependency is listed
def cleanup(x): return re.sub(r' *#.*', '', x.strip()) # comments
def to_list(buffer): return list(filter(None, map(cleanup, buffer.splitlines())))
### normal dependencies ###
#
# these get resolved and installed via either of these two:
#
# pip install fastai
# pip install -e .
#
# IMPORTANT: when updating these, please make sure to sync conda/meta.yaml
dep_groups = {
'core': to_list("""
bottleneck # performance-improvement for numpy
dataclasses ; python_version<'3.7'
fastprogress>=0.2.1
beautifulsoup4
matplotlib
numexpr # performance-improvement for numpy
numpy>=1.15
nvidia-ml-py3
pandas
packaging
Pillow
pyyaml
pynvx>=1.0.0 ; platform_system=="Darwin" # only pypi at the moment
requests
scipy
torch>=1.0.0
"""),
'text': to_list("""
spacy>=2.0.18; python_version<'3.8'
"""),
'vision': to_list("""
torchvision
"""),
}
requirements = [y for x in dep_groups.values() for y in x]
### developer dependencies ###
#
# anything else that's not required by a user to run the library, but
# either is an enhancement or a developer-build requirement goes here.
#
# the [dev] feature is documented here:
# https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies
#
# these, including the normal dependencies, get installed with:
#
# pip install "fastai[dev]"
#
# or via an editable install:
#
# pip install -e ".[dev]"
#
# some of the listed modules appear in test_requirements as well, as explained below.
#
dev_requirements = { 'dev' : to_list("""
coverage # make coverage
distro
ipython
jupyter
jupyter_contrib_nbextensions
nbconvert>=5.4
nbdime # help with nb diff/merge
nbformat
notebook>=5.7.0
pip>=9.0.1
pipreqs>=0.4.9
pytest>=4.4.0
pytest-xdist # make test-fast (faster parallel testing)
responses # for requests testing
traitlets
wheel>=0.30.0
""") }
### setup dependencies ###
# need at least setuptools>=36.2 to support syntax:
# dataclasses ; python_version<'3.7'
setup_requirements = to_list("""
pytest-runner
setuptools>=36.2
""")
# notes:
#
# * these deps will be installed locally under .eggs/ and will not be
# visible to pytest unless it's invoked via `python setup test`.
# Therefore it's the best to install them explicitly with:
# pip install -e .[dev]
#
### test dependencies ###
test_requirements = to_list("""
pytest
""")
# list of classifiers: https://pypi.org/pypi?%3Aaction=list_classifiers
setup(
cmdclass = { 'deps': DepsCommand },
name = 'fastai',
version = __version__,
packages = find_packages(),
include_package_data = True,
install_requires = requirements,
setup_requires = setup_requirements,
extras_require = dev_requirements,
tests_require = test_requirements,
python_requires = '>=3.6',
test_suite = 'tests',
description = "fastai makes deep learning with PyTorch faster, more accurate, and easier",
long_description = readme,
long_description_content_type = 'text/markdown',
keywords = 'fastai, deep learning, machine learning',
license = "Apache Software License 2.0",
url = 'https://github.com/fastai/fastai1',
author = "Jeremy Howard",
author_email = 'info@fast.ai',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
zip_safe = False,
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
import re
from setuptools import setup, find_packages
from distutils.core import Command
class DepsCommand(Command):
"""A custom distutils command to print selective dependency groups.
# show available dependency groups:
python setup.py -q deps
# print dependency list for specified groups
python setup.py -q deps --dep-groups=core,vision
# see all options:
python setup.py -q deps --help
"""
description = 'show dependency groups and their packages'
user_options = [
# format: (long option, short option, description).
('dep-groups=', None, 'comma separated dependency groups'),
('dep-quote', None, 'quote each dependency'),
('dep-conda', None, 'adjust output for conda'),
]
def initialize_options(self):
"""Set default values for options."""
self.dep_groups = ''
self.dep_quote = False
self.dep_conda = False
def finalize_options(self):
"""Post-process options."""
pass
def parse(self):
arg = self.dep_groups.strip()
return re.split(r' *, *', arg) if len(arg) else []
def run(self):
"""Run command."""
wanted_groups = self.parse()
deps = []
invalid_groups = []
for grp in wanted_groups:
if grp in dep_groups: deps.extend(dep_groups[grp])
else: invalid_groups.append(grp)
if invalid_groups or not wanted_groups:
print("Available dependency groups:", ", ".join(sorted(dep_groups.keys())))
if invalid_groups:
print(f"Error: Invalid group name(s): {', '.join(invalid_groups)}")
exit(1)
else:
# prepare for shell word splitting (no whitespace in items)
deps = [re.sub(" ", "", x, 0) for x in sorted(set(deps))]
if self.dep_conda:
for i in range(len(deps)):
# strip pip-specific syntax
deps[i] = re.sub(r';.*', '', deps[i])
# rename mismatching package names
deps[i] = re.sub(r'^torch>', 'pytorch>', deps[i])
if self.dep_quote:
# for manual copy-n-paste (assuming no " in vars)
print(" ".join(map(lambda x: f'"{x}"', deps)))
else:
# if fed directly to `pip install` via backticks/$() don't quote
print(" ".join(deps))
# note: version is maintained inside fastai/version.py
exec(open('fastai/version.py').read())
with open('README.md') as readme_file: readme = readme_file.read()
# helper functions to make it easier to list dependencies not as a python list, but vertically w/ optional built-in comments to why a certain version of the dependency is listed
def cleanup(x): return re.sub(r' *#.*', '', x.strip()) # comments
def to_list(buffer): return list(filter(None, map(cleanup, buffer.splitlines())))
### normal dependencies ###
#
# these get resolved and installed via either of these two:
#
# pip install fastai
# pip install -e .
#
# IMPORTANT: when updating these, please make sure to sync conda/meta.yaml
dep_groups = {
'core': to_list("""
bottleneck # performance-improvement for numpy
dataclasses ; python_version<'3.7'
fastprogress>=0.2.1
beautifulsoup4
matplotlib
numexpr # performance-improvement for numpy
numpy>=1.15
nvidia-ml-py3
pandas
packaging
Pillow
pyyaml
pynvx>=1.0.0 ; platform_system=="Darwin" # only pypi at the moment
requests
scipy
torch>=1.0.0
"""),
'text': to_list("""
spacy>=2.0.18; python_version<'3.8'
"""),
'vision': to_list("""
torchvision
"""),
}
requirements = [y for x in dep_groups.values() for y in x]
### developer dependencies ###
#
# anything else that's not required by a user to run the library, but
# either is an enhancement or a developer-build requirement goes here.
#
# the [dev] feature is documented here:
# https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies
#
# these, including the normal dependencies, get installed with:
#
# pip install "fastai[dev]"
#
# or via an editable install:
#
# pip install -e ".[dev]"
#
# some of the listed modules appear in test_requirements as well, as explained below.
#
dev_requirements = { 'dev' : to_list("""
coverage # make coverage
distro
ipython
jupyter
jupyter_contrib_nbextensions
nbconvert>=5.4
nbdime # help with nb diff/merge
nbformat
notebook>=5.7.0
pip>=9.0.1
pipreqs>=0.4.9
pytest>=4.4.0
pytest-xdist # make test-fast (faster parallel testing)
responses # for requests testing
traitlets
wheel>=0.30.0
""") }
### setup dependencies ###
# need at least setuptools>=36.2 to support syntax:
# dataclasses ; python_version<'3.7'
setup_requirements = to_list("""
pytest-runner
setuptools>=36.2
""")
# notes:
#
# * these deps will be installed locally under .eggs/ and will not be
# visible to pytest unless it's invoked via `python setup test`.
# Therefore it's the best to install them explicitly with:
# pip install -e .[dev]
#
### test dependencies ###
test_requirements = to_list("""
pytest
""")
# list of classifiers: https://pypi.org/pypi?%3Aaction=list_classifiers
setup(
cmdclass = { 'deps': DepsCommand },
name = 'fastai',
version = __version__,
packages = find_packages(),
include_package_data = True,
install_requires = requirements,
setup_requires = setup_requirements,
extras_require = dev_requirements,
tests_require = test_requirements,
python_requires = '>=3.6',
test_suite = 'tests',
description = "fastai makes deep learning with PyTorch faster, more accurate, and easier",
long_description = readme,
long_description_content_type = 'text/markdown',
keywords = 'fastai, deep learning, machine learning',
license = "Apache Software License 2.0",
url = 'https://github.com/fastai/fastai1',
author = "Jeremy Howard",
author_email = 'info@fast.ai',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
zip_safe = False,
)
|
import base64
import datetime
import sys
import pytest
from mock import patch
from nbgrader.utils import make_unique_key, notebook_hash
from nbexchange.handlers.base import BaseHandler
from nbexchange.tests.utils import (
AsyncSession,
async_requests,
clear_database,
get_feedback_dict,
get_files_dict,
user_brobbere_student,
user_kiz_instructor,
user_kiz_student,
user_lkihlman_instructor,
)
# set up the file to be uploaded
feedback_filename = sys.argv[0] # ourself :)
feedbacks = get_feedback_dict(feedback_filename)
feedback_base64 = base64.b64encode(open(sys.argv[0]).read().encode("utf-8"))
files = get_files_dict(sys.argv[0]) # ourself :)
@pytest.mark.gen_test
def test_feedback_unauthenticated(app):
"""
Require authenticated user
"""
r = yield async_requests.get(app.url + "/feedback")
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_authenticated_no_params(app, clear_database):
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.get(app.url + "/feedback")
response_data = r.json()
assert response_data["success"] == False
assert (
response_data["note"]
== "Feedback call requires an assignment id and a course id"
)
@pytest.mark.gen_test
def test_feedback_authenticated_with_params(app, clear_database):
assignment_id = "my_assignment"
course_id = "my_course"
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.get(app.url + url)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_unauthenticated(app, clear_database):
"""
Require authenticated user for posting
"""
r = yield async_requests.post(app.url + "/feedback", files=feedbacks)
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_params(app, clear_database):
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + "/feedback", files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_assignment_id(app, clear_database):
url = f"/feedback?course_id=faked¬ebook=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_course_id(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}¬ebook=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_notebook(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_student(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_timestamp(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked&student=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_checksum(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked&student=faked×tamp=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_params(app, clear_database):
assignment_id = "my_assignment"
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id=course_2"
f"¬ebook=faked"
f"&student=faked"
f"×tamp=faked"
f"&checksum=faked"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_assignment_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id=faked"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_notebook_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={course_id}"
f"&course_id={course_id}"
f"¬ebook=faked"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_student_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_brobbere_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={course_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
# Not yet implemented on exchange server...
@pytest.mark.skip
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_checksum(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum=faked"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params_incorrect_instructor(
app, clear_database
):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_lkihlman_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert response_data["note"] == f"User not subscribed to course {course_id}"
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params_student_submitter(
app, clear_database
):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert response_data["note"] == f"User not an instructor to course {course_id}"
@pytest.mark.gen_test
def test_feedback_get_authenticated_with_incorrect_student(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(
BaseHandler, "get_current_user", return_value=user_brobbere_student
):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) == 0
@pytest.mark.gen_test
def test_feedback_get_authenticated_with_correct_params(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) >= 1
assert response_data["feedback"][0].get("content") == feedback_base64.decode(
"utf-8"
)
# test feedback picks up the correct assignment when two courses have the same assignment name
# Should pick up course 2.
@pytest.mark.gen_test
def test_feedback_get_correct_assignment_across_courses(app, clear_database):
pass
# set up the situation
assignment_id = "assign_a"
course_1 = "course_1"
course_2 = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_2, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
# release assignment on course 1 & 2
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url + f"/assignment?course_id={course_1}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url + f"/assignment?course_id={course_2}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
# Now fetch & submit on course 2 as student
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_2}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url + f"/submission?course_id={course_2}&assignment_id={assignment_id}",
files=files,
)
# Instructor releases for course 2
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_2}"
f"¬ebook={notebook}"
f"&student={student["name"]}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_1}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 404
url = f"/feedback?assignment_id={assignment_id}&course_id={course_2}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) >= 1
assert response_data["feedback"][0].get("content") == feedback_base64.decode(
"utf-8"
)
| import base64
import datetime
import sys
import pytest
from mock import patch
from nbgrader.utils import make_unique_key, notebook_hash
from nbexchange.handlers.base import BaseHandler
from nbexchange.tests.utils import (
AsyncSession,
async_requests,
clear_database,
get_feedback_dict,
get_files_dict,
user_brobbere_student,
user_kiz_instructor,
user_kiz_student,
user_lkihlman_instructor,
)
# set up the file to be uploaded
feedback_filename = sys.argv[0] # ourself :)
feedbacks = get_feedback_dict(feedback_filename)
feedback_base64 = base64.b64encode(open(sys.argv[0]).read().encode("utf-8"))
files = get_files_dict(sys.argv[0]) # ourself :)
@pytest.mark.gen_test
def test_feedback_unauthenticated(app):
"""
Require authenticated user
"""
r = yield async_requests.get(app.url + "/feedback")
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_authenticated_no_params(app, clear_database):
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.get(app.url + "/feedback")
response_data = r.json()
assert response_data["success"] == False
assert (
response_data["note"]
== "Feedback call requires an assignment id and a course id"
)
@pytest.mark.gen_test
def test_feedback_authenticated_with_params(app, clear_database):
assignment_id = "my_assignment"
course_id = "my_course"
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.get(app.url + url)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_unauthenticated(app, clear_database):
"""
Require authenticated user for posting
"""
r = yield async_requests.post(app.url + "/feedback", files=feedbacks)
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_params(app, clear_database):
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + "/feedback", files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_assignment_id(app, clear_database):
url = f"/feedback?course_id=faked¬ebook=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_course_id(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}¬ebook=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_notebook(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked&student=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_student(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked×tamp=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_timestamp(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked&student=faked&checksum=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_no_checksum(app, clear_database):
assignment_id = "my_assignment"
url = f"/feedback?assignment_id={assignment_id}&course_id=faked¬ebook=faked&student=faked×tamp=faked"
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert (
response_data["note"]
== "Feedback call requires a course id, assignment id, notebook name, student id, checksum and timestamp."
)
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_params(app, clear_database):
assignment_id = "my_assignment"
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id=course_2"
f"¬ebook=faked"
f"&student=faked"
f"×tamp=faked"
f"&checksum=faked"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_assignment_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id=faked"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_notebook_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={course_id}"
f"&course_id={course_id}"
f"¬ebook=faked"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_student_id(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_brobbere_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={course_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 404
# Not yet implemented on exchange server...
@pytest.mark.skip
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_incorrect_checksum(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum=faked"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 403
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params_incorrect_instructor(
app, clear_database
):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_lkihlman_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert response_data["note"] == f"User not subscribed to course {course_id}"
@pytest.mark.gen_test
def test_feedback_post_authenticated_with_correct_params_student_submitter(
app, clear_database
):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(app.url + url, files=feedbacks)
response_data = r.json()
assert response_data["success"] is False
assert response_data["note"] == f"User not an instructor to course {course_id}"
@pytest.mark.gen_test
def test_feedback_get_authenticated_with_incorrect_student(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(
BaseHandler, "get_current_user", return_value=user_brobbere_student
):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) == 0
@pytest.mark.gen_test
def test_feedback_get_authenticated_with_correct_params(app, clear_database):
assignment_id = "assign_a"
course_id = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_id, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url
+ f"/assignment?course_id={course_id}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_id}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url
+ f"/submission?course_id={course_id}&assignment_id={assignment_id}",
files=files,
)
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_id}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_id}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) >= 1
assert response_data["feedback"][0].get("content") == feedback_base64.decode(
"utf-8"
)
# test feedback picks up the correct assignment when two courses have the same assignment name
# Should pick up course 2.
@pytest.mark.gen_test
def test_feedback_get_correct_assignment_across_courses(app, clear_database):
pass
# set up the situation
assignment_id = "assign_a"
course_1 = "course_1"
course_2 = "course_2"
notebook = "notebook"
student = user_kiz_student
timestamp = datetime.datetime.utcnow().isoformat(" ")
checksum = notebook_hash(
feedback_filename,
make_unique_key(course_2, assignment_id, notebook, student["name"], timestamp),
)
# XXX: Doing this in a separate function doesn't work for some reason (Exchange doesn't get called)
kwargs = {"data": {"notebooks": [notebook]}}
# release assignment on course 1 & 2
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url + f"/assignment?course_id={course_1}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(
app.url + f"/assignment?course_id={course_2}&assignment_id={assignment_id}",
files=files,
**kwargs,
)
# Now fetch & submit on course 2 as student
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(
app.url + f"/assignment?course_id={course_2}&assignment_id={assignment_id}"
)
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.post(
app.url + f"/submission?course_id={course_2}&assignment_id={assignment_id}",
files=files,
)
# Instructor releases for course 2
url = (
f"/feedback?assignment_id={assignment_id}"
f"&course_id={course_2}"
f"¬ebook={notebook}"
f"&student={student['name']}"
f"×tamp={timestamp}"
f"&checksum={checksum}"
)
with patch.object(
BaseHandler, "get_current_user", return_value=user_kiz_instructor
):
r = yield async_requests.post(app.url + url, files=feedbacks)
url = f"/feedback?assignment_id={assignment_id}&course_id={course_1}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 404
url = f"/feedback?assignment_id={assignment_id}&course_id={course_2}"
with patch.object(BaseHandler, "get_current_user", return_value=user_kiz_student):
r = yield async_requests.get(app.url + url)
assert r.status_code == 200
response_data = r.json()
assert response_data["success"] is True
assert len(response_data["feedback"]) >= 1
assert response_data["feedback"][0].get("content") == feedback_base64.decode(
"utf-8"
)
|
import app.scripts.terminal_scripts as term
import app.scripts.cloudhsm_mgmt_utility_scripts as cmu
import time
import json
class CloudHSMMgmtUtil():
def __init__(self, eni_ip, crypto_officer_type, crypto_officer_username, crypto_officer_password):
self.eni_ip = eni_ip
self.crypto_officer_type = crypto_officer_type
self.crypto_officer_username = crypto_officer_username
self.crypto_officer_password = crypto_officer_password
self.child = False
self.logged_in = False
self.configured = self.configure()
self.active = self.is_active()
@property
def hostname(self):
with open('/opt/cloudhsm/etc/cloudhsm_client.cfg', 'r') as file:
client_data_json = file.read()
client_data = json.loads(client_data_json)
hostname = client_data['server']['hostname']
return hostname
@property
def users(self):
if self.child is False:
resp = self.connect()
users = cmu.list_users(child=self.child)
resp = self.quit()
return users
@property
def crypto_officers(self):
crypto_officers = [
user for user in self.users if user['user_type'] == 'CO']
return crypto_officers
@property
def crypto_users(self):
crypto_users = [
user for user in self.users if user['user_type'] == 'CU']
return crypto_users
@property
def pre_crypto_officers(self):
pre_crypto_officers = [
user for user in self.users if user['user_type'] == 'PRECO']
return pre_crypto_officers
def is_active(self):
if len(self.pre_crypto_officers) != 0:
return False
else:
return True
def configure(self, count=0):
count += 1
if self.hostname == self.eni_ip:
return True
try:
output = term.configure_cloudhsm_mgmt_util(eni_ip=self.eni_ip)
time.sleep(1)
assert self.hostname == self.eni_ip
return True
except AssertionError as e:
if count > 5:
raise ConfigurationError(
'Unable to configure the CloudHSM Mgmt Util')
else:
return self.configure(count=count)
def connect(self, count=0):
count += 1
try:
resp = cmu.connect()
assert resp.get('error') is None, f"#connect: {resp["error"]}"
child = resp['data']['child']
self.child = child
return True
except AssertionError as e:
if count > 5:
raise ConnectionError(e.args[0])
else:
time.sleep(1)
return self.connect(count=count)
def login(self):
if self.active is False:
raise CloudMgmtUtilNotActiveError(
'Must activate the CloudHSM Mgmt Util first')
if self.child is False:
self.connect()
try:
resp = cmu.login(
child=self.child,
crypto_officer_type=self.crypto_officer_type,
crypto_officer_username=self.crypto_officer_username,
crypto_officer_password=self.crypto_officer_password
)
assert resp.get('error') is None, f"Login Failed: {resp["error"]}"
return True
except AssertionError as e:
self.child = False
raise LoginError(e.args[0])
def crypto_user_login(self, username, password):
if self.active is False:
raise CloudMgmtUtilNotActiveError(
'Must activate the CloudHSM Mgmt Util first')
if self.child is False:
self.connect()
try:
resp = cmu.login(
child=self.child,
crypto_officer_type='CU',
crypto_officer_username=username,
crypto_officer_password=password
)
assert resp.get(
'error') is None, f"Crypto User Login Failed: {resp["error"]}"
return True
except AssertionError as e:
self.child = False
raise LoginError(e.args[0])
def change_password(self, user_type, username, new_password):
if self.child is False:
self.connect()
if self.logged_in is False:
self.login()
try:
resp = cmu.change_user_password(
child=self.child,
user_type=user_type,
user_username=username,
user_password=new_password
)
assert resp.get(
'error') is None, f"Change password failed: {resp["error"]}"
return True
except AssertionError as e:
self.child = False
raise ChangePasswordError(e.args[0])
def create_user(self, user_type, username, password):
if self.child is False:
self.connect()
if self.logged_in is False:
self.login()
try:
resp = cmu.create_user(
child=self.child,
user_type=user_type,
user_username=username,
user_password=password
)
assert resp.get(
'error') is None, f"Create user failed: {resp["error"]}"
return True
except AssertionError as e:
self.child = False
raise CreateUserError(e.args[0])
def quit(self):
if self.child is False:
return True
else:
cmu.quit(child=self.child)
self.child = False
return True
class CloudMgmtUtilNotActiveError(Exception):
pass
class ConfigurationError(Exception):
pass
class ConnectionError(Exception):
pass
class LoginError(Exception):
pass
class ChangePasswordError(Exception):
pass
class CreateUserError(Exception):
pass
| import app.scripts.terminal_scripts as term
import app.scripts.cloudhsm_mgmt_utility_scripts as cmu
import time
import json
class CloudHSMMgmtUtil():
def __init__(self, eni_ip, crypto_officer_type, crypto_officer_username, crypto_officer_password):
self.eni_ip = eni_ip
self.crypto_officer_type = crypto_officer_type
self.crypto_officer_username = crypto_officer_username
self.crypto_officer_password = crypto_officer_password
self.child = False
self.logged_in = False
self.configured = self.configure()
self.active = self.is_active()
@property
def hostname(self):
with open('/opt/cloudhsm/etc/cloudhsm_client.cfg', 'r') as file:
client_data_json = file.read()
client_data = json.loads(client_data_json)
hostname = client_data['server']['hostname']
return hostname
@property
def users(self):
if self.child is False:
resp = self.connect()
users = cmu.list_users(child=self.child)
resp = self.quit()
return users
@property
def crypto_officers(self):
crypto_officers = [
user for user in self.users if user['user_type'] == 'CO']
return crypto_officers
@property
def crypto_users(self):
crypto_users = [
user for user in self.users if user['user_type'] == 'CU']
return crypto_users
@property
def pre_crypto_officers(self):
pre_crypto_officers = [
user for user in self.users if user['user_type'] == 'PRECO']
return pre_crypto_officers
def is_active(self):
if len(self.pre_crypto_officers) != 0:
return False
else:
return True
def configure(self, count=0):
count += 1
if self.hostname == self.eni_ip:
return True
try:
output = term.configure_cloudhsm_mgmt_util(eni_ip=self.eni_ip)
time.sleep(1)
assert self.hostname == self.eni_ip
return True
except AssertionError as e:
if count > 5:
raise ConfigurationError(
'Unable to configure the CloudHSM Mgmt Util')
else:
return self.configure(count=count)
def connect(self, count=0):
count += 1
try:
resp = cmu.connect()
assert resp.get('error') is None, f"#connect: {resp['error']}"
child = resp['data']['child']
self.child = child
return True
except AssertionError as e:
if count > 5:
raise ConnectionError(e.args[0])
else:
time.sleep(1)
return self.connect(count=count)
def login(self):
if self.active is False:
raise CloudMgmtUtilNotActiveError(
'Must activate the CloudHSM Mgmt Util first')
if self.child is False:
self.connect()
try:
resp = cmu.login(
child=self.child,
crypto_officer_type=self.crypto_officer_type,
crypto_officer_username=self.crypto_officer_username,
crypto_officer_password=self.crypto_officer_password
)
assert resp.get('error') is None, f"Login Failed: {resp['error']}"
return True
except AssertionError as e:
self.child = False
raise LoginError(e.args[0])
def crypto_user_login(self, username, password):
if self.active is False:
raise CloudMgmtUtilNotActiveError(
'Must activate the CloudHSM Mgmt Util first')
if self.child is False:
self.connect()
try:
resp = cmu.login(
child=self.child,
crypto_officer_type='CU',
crypto_officer_username=username,
crypto_officer_password=password
)
assert resp.get(
'error') is None, f"Crypto User Login Failed: {resp['error']}"
return True
except AssertionError as e:
self.child = False
raise LoginError(e.args[0])
def change_password(self, user_type, username, new_password):
if self.child is False:
self.connect()
if self.logged_in is False:
self.login()
try:
resp = cmu.change_user_password(
child=self.child,
user_type=user_type,
user_username=username,
user_password=new_password
)
assert resp.get(
'error') is None, f"Change password failed: {resp['error']}"
return True
except AssertionError as e:
self.child = False
raise ChangePasswordError(e.args[0])
def create_user(self, user_type, username, password):
if self.child is False:
self.connect()
if self.logged_in is False:
self.login()
try:
resp = cmu.create_user(
child=self.child,
user_type=user_type,
user_username=username,
user_password=password
)
assert resp.get(
'error') is None, f"Create user failed: {resp['error']}"
return True
except AssertionError as e:
self.child = False
raise CreateUserError(e.args[0])
def quit(self):
if self.child is False:
return True
else:
cmu.quit(child=self.child)
self.child = False
return True
class CloudMgmtUtilNotActiveError(Exception):
pass
class ConfigurationError(Exception):
pass
class ConnectionError(Exception):
pass
class LoginError(Exception):
pass
class ChangePasswordError(Exception):
pass
class CreateUserError(Exception):
pass
|
# MIT License
# Copyright (c) 2020 Dr. Jan-Philip Gehrcke
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This program is part of https://github.com/jgehrcke/covid-19-germany-gae
"""
import os
import logging
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import bokeh.plotting
import bokeh.models
from bokeh.layouts import column, layout
import bokeh.io
import bokeh.embed
import bokeh.resources
import jinja2
log = logging.getLogger()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s.%(msecs)03d %(levelname)s: %(message)s",
datefmt="%y%m%d-%H:%M:%S",
)
NOW = datetime.utcnow()
def main():
# About "Meldedatum", vom RKI dashboard: Für die Darstellung der
# neuübermittelten Fälle pro Tag wird das Meldedatum verwendet – das Datum,
# an dem das lokale Gesundheitsamt Kenntnis über den Fall erlangt und ihn
# elektronisch erfasst hat.
# Zwischen der Meldung durch die Ärzte und Labore an das Gesundheitsamt und
# der Übermittlung der Fälle an die zuständigen Landesbehörden und das RKI
# können einige Tage vergehen (Melde- und Übermittlungsverzug). Jeden Tag
# werden dem RKI neue Fälle übermittelt, die am gleichen Tag oder bereits
# an früheren Tagen an das Gesundheitsamt gemeldet worden sind. Diese Fälle
# werden in der Grafik Neue COVID-19-Fälle/Tag dann bei dem jeweiligen
# Datum ergänzt.
START_DATE = "2020-03-09"
def _build_case_rate(df):
# Get time differences (unit: seconds) in the df's datetimeindex. `dt`
# is a magic accessor that yields an array of time deltas.
dt_seconds = pd.Series(df.index).diff().dt.total_seconds()
# Construct new series with original datetimeindex as index and time
# differences (unit: days) as values.
dt_days = pd.Series(dt_seconds) / 86400.0
dt_days.index = df.index
# print(dt_days)
cases_change_per_day = df["sum_cases"].diff().div(dt_days)
df["cases_change_per_day"] = cases_change_per_day
print(df)
# increase resolution and forward-fill values. Could also use
# `interpolate()` but that's too artificial, I think it's fair to see
# the actual discrete jumps in data as of "batch processing".
df_case_change = df["cases_change_per_day"].resample("1H").pad()
print(type(df_case_change))
# sys.exit()
# Should be >= 7 to be meaningful.
window_width_days = 5
window = df_case_change.rolling(window="%sD" % window_width_days)
# Manually build rolling window mean.
wdw_norm = window.sum() / (window_width_days * 24.0)
# During the rolling window analysis the value derived from the current
# window position is assigned to the right window boundary (i.e. to the
# newest timestamp in the window). For presentation it is more convenient
# and intuitive to have it assigned to the temporal center of the time
# window. Invoking `rolling(..., center=True)` however yields
# `NotImplementedError: center is not implemented for datetimelike and
# offset based windows`. As a workaround, shift the data by half the window
# size to 'the left': shift the timestamp index by a constant / offset.
offset = pd.DateOffset(days=window_width_days / 2.0)
wdw_norm.index = wdw_norm.index - offset
print(wdw_norm)
# sys.exit()
# cut the last 2 days worth of data, at least for RKI this is just too
# much affected by Meldeverzug
d_end = NOW - timedelta(days=3)
# t_end = f"{d_end.strftime("%Y-%m-%d")} 23:59:59"
return wdw_norm[:f"{d_end.strftime("%Y-%m-%d")}"]
df_mixed_data = pd.read_csv(
"data.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
date_parser=lambda col: pd.to_datetime(col, utc=True),
)[START_DATE:]
df_mixed_data.index.name = "time"
df_mixed_case_rate_rw = _build_case_rate(df_mixed_data)[START_DATE:]
df_rl = pd.read_csv(
"cases-rl-crowdsource-by-state.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
)[START_DATE:]
df_rl.index.name = "time"
df_rl_case_rate_rw = _build_case_rate(df_rl)[START_DATE:]
df_rki = pd.read_csv(
"cases-rki-by-state.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
)[START_DATE:]
df_rki.index.name = "time"
df_rki_case_rate_rw = _build_case_rate(df_rki)[START_DATE:]
df_jhu = jhu_csse_csv_to_dataframe(os.environ["JHU_TS_CSV_PATH"], "germany")[
START_DATE:
]
df_jhu.index.name = "time"
df_jhu_case_rate_rw = _build_case_rate(df_jhu)[START_DATE:]
# Normalize for 'sum_cases' plots
for _df in [df_rki, df_jhu, df_mixed_data, df_rl]:
_df["sum_cases"] = _df["sum_cases"] / 10000
plt.figure()
ax = df_rki["sum_cases"].plot(linestyle="solid", marker="x", color="red",)
df_rl["sum_cases"].plot(linestyle="solid", marker="x", color="black", ax=ax)
df_mixed_data["sum_cases"].plot(
linestyle="dashdot", marker="x", color="black", ax=ax
)
df_jhu["sum_cases"].plot(linestyle="dashdot", marker="x", color="gray", ax=ax)
ax.legend(
[
"RKI data, by Meldedatum",
"Risklayer/Tagesspiegel crowdsource data, daily snapshots",
"ZEIT ONLINE, daily snapshots",
"JHU (GitHub CSSEGISandData/COVID-19)",
],
numpoints=4,
handlelength=8,
)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.xlabel("Time")
plt.ylabel("cumulative case count, all Germany / 10^4")
# plt.title("COVID-19 case count, Germany, comparison of data sources")
# set_title('Override command rate (from both DC/OS repositories)')
# set_subtitle('Arithmetic mean over rolling time window')
# plt.tight_layout(rect=(0, 0, 1, 0.95))
plt.tight_layout()
fig_filepath_wo_ext = (
f"gae/static/data-sources-comparison-{NOW.strftime("%Y-%m-%d")}"
)
plt.savefig(fig_filepath_wo_ext + ".png", dpi=150)
plt.savefig(fig_filepath_wo_ext + ".pdf")
# -----------
plt.figure(figsize=(16.0, 9.0))
ax = df_rki["cases_change_per_day"].plot(
linestyle="None", marker="x", color="black",
)
df_rki_case_rate_rw.plot(linestyle="solid", marker=None, color="black", ax=ax)
df_jhu_case_rate_rw.plot(linestyle="dashdot", marker=None, color="gray", ax=ax)
ax.legend(
[
'raw RKI data, by date of report ("Meldedatum")',
"RKI rolling window mean (width: 5 days)",
"JHU rolling window mean (width: 5 days)",
],
numpoints=4,
handlelength=8,
loc="upper left",
)
plt.xlabel("")
plt.ylabel("COVID-19 cumulative case count, change per day (all Germany)")
plt.tight_layout()
fig_filepath_wo_ext = f"gae/static/case-rate-rw-{NOW.strftime("%Y-%m-%d")}"
plt.savefig(fig_filepath_wo_ext + ".png", dpi=150)
plt.savefig(fig_filepath_wo_ext + ".pdf")
# plt.show()
plot_with_bokeh(df_rki, df_jhu, df_mixed_data, df_rl)
def _set_common_bokeh_fig_props(fig):
fig.toolbar.active_drag = None
fig.toolbar.active_scroll = None
fig.toolbar.active_tap = None
fig.outline_line_color = "#333333"
fig.outline_line_width = 1
fig.outline_line_alpha = 0.7
fig.title.text_font_size = "10px"
fig.legend.label_text_font_size = "10px"
# fig.legend.label_text_font = "'Open Sans Condensed', sans-serif"
fig.legend.spacing = 0
fig.legend.margin = 3
fig.legend.label_standoff = 5
fig.legend.label_height = 0
# import json
# print(json.dumps(dir(fig.legend), indent=2))
# fig.text_font_size = "12pt"
fig.xaxis.ticker.desired_num_ticks = 21
fig.xaxis.formatter = bokeh.models.DatetimeTickFormatter(days=["%b-%d"])
fig.xaxis.major_label_orientation = 3.1415 / 4 + 0.5
# fig.xaxis.axis_label = "Date"
fig.xaxis.axis_label_text_font_size = "16px"
fig.xaxis.major_label_text_font_size = "10px"
fig.xaxis.axis_label_text_font_style = "normal"
fig.y_range.start = 0
# fig.yaxis.axis_label = "confirmed cases / 10000"
fig.yaxis.axis_label_text_font_size = "10px"
fig.yaxis.axis_label_text_font_style = "normal"
fig.yaxis.major_label_text_font_size = "10px"
def plot_with_bokeh(df_rki, df_jhu, df_mixed_data, df_rl):
# html_file_path = 'bokeh-comp-plot.html'
# bokeh.plotting.output_file(html_file_path)
# bokeh.io.curdoc().theme = "dark_minimal"
cname = "sum_cases"
fig = bokeh.plotting.figure(
# title=f"Generated at {now.strftime("%Y-%m-%d %H:%M UTC")}",
title="Germany, cumulative cases / 10000",
x_axis_type="datetime",
toolbar_location=None,
background_fill_color="#eeeeee",
height=450,
)
# Scatter and line seemingly need to be done separately.
# RKI
fig.line(
"time",
cname,
line_color="red",
line_width=2,
line_dash="solid",
legend_label="RKI data, by Meldedatum",
source=bokeh.models.ColumnDataSource(data=df_rki),
)
fig.scatter(
"time",
cname,
marker="x",
line_color="red",
line_width=2,
size=8,
source=bokeh.models.ColumnDataSource(data=df_rki),
)
# JHU
fig.line(
"time",
"sum_cases",
line_color="black",
line_width=1,
line_dash="solid",
legend_label="JHU (GitHub)",
source=bokeh.models.ColumnDataSource(data=df_jhu),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="black",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_jhu),
)
# Risklayer
fig.line(
"time",
"sum_cases",
line_color="gray",
line_width=1,
line_dash="dashdot",
legend_label="Risklayer / Tagesspiegel",
source=bokeh.models.ColumnDataSource(data=df_rl),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="gray",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_rl),
)
fig.line(
"time",
"sum_cases",
line_color="gray",
line_width=1,
line_dash="solid",
legend_label="ZEIT ONLINE",
source=bokeh.models.ColumnDataSource(data=df_mixed_data),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="gray",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_mixed_data),
)
# fig.line(
# "time",
# "sum_cases",
# marker="x",
# size=8,
# line_color="black",
# line_width=3,
# ,
# source=bokeh.models.ColumnDataSource(data=df_jhu),
# )
_set_common_bokeh_fig_props(fig)
fig.legend.location = "top_left"
templ_env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="./"))
template = templ_env.get_template("gae/static/index.html.template")
html = bokeh.embed.file_html(
column(fig, fig, sizing_mode="stretch_both"),
template=template,
resources=bokeh.resources.CDN,
template_variables={"today_string": NOW.strftime("%Y-%m-%d"),},
)
with open("gae/static/index.html", "wb") as f:
f.write(html.encode("utf-8"))
def jhu_csse_csv_to_dataframe(data_file_path, location_name):
"""
data_file_path: expect an instance of `time_series_19-covid-Confirmed.csv`
from https://github.com/CSSEGISandData/COVID-19/
location_name: the lower-cased version of this must be a column in the
processed data set.
"""
log.info("parse JHU data file")
df = pd.read_csv(data_file_path)
log.info("process JHU data file")
# Merge location names into somewhat more managable identifiers.
countries = [
"_".join(c.lower().split()) if c != "nan" else ""
for c in list(df["Country/Region"].astype("str"))
]
provinces = [
"_".join(p.lower().split()) if p != "nan" else ""
for p in list(df["Province/State"].astype("str"))
]
countries = [c.replace(",", "").replace(".", "") for c in countries]
provinces = [p.replace(",", "").replace(".", "") for p in provinces]
df["where"] = [f"{c}_{p}" if p else c for c, p in zip(countries, provinces)]
# Make each column represent a location, and each row represent a day
# (date).
df.drop(["Lat", "Long", "Country/Region", "Province/State"], axis=1, inplace=True)
df = df.set_index("where")
df = df.transpose()
# Parse date strings into pandas DateTime objects, set proper
# DateTimeIndex.
normalized_date_strings = [
"/".join(t.zfill(2) for t in o.split("/")) for o in list(df.index)
]
df.index = normalized_date_strings
df.index = pd.to_datetime(df.index, format="%m/%d/%y")
df.index.name = "date"
# df.sort_index(inplace=True)
# Only return series for specific location
loc = location_name.lower()
# rename column for consistency with other dfs
df["sum_cases"] = df[loc]
return df["sum_cases"].to_frame()
def matplotlib_config():
plt.style.use("ggplot")
matplotlib.rcParams["figure.figsize"] = [10.5, 7.0]
matplotlib.rcParams["figure.dpi"] = 100
matplotlib.rcParams["savefig.dpi"] = 150
# mpl.rcParams['font.size'] = 12
if __name__ == "__main__":
matplotlib_config()
main()
| # MIT License
# Copyright (c) 2020 Dr. Jan-Philip Gehrcke
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This program is part of https://github.com/jgehrcke/covid-19-germany-gae
"""
import os
import logging
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import bokeh.plotting
import bokeh.models
from bokeh.layouts import column, layout
import bokeh.io
import bokeh.embed
import bokeh.resources
import jinja2
log = logging.getLogger()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s.%(msecs)03d %(levelname)s: %(message)s",
datefmt="%y%m%d-%H:%M:%S",
)
NOW = datetime.utcnow()
def main():
# About "Meldedatum", vom RKI dashboard: Für die Darstellung der
# neuübermittelten Fälle pro Tag wird das Meldedatum verwendet – das Datum,
# an dem das lokale Gesundheitsamt Kenntnis über den Fall erlangt und ihn
# elektronisch erfasst hat.
# Zwischen der Meldung durch die Ärzte und Labore an das Gesundheitsamt und
# der Übermittlung der Fälle an die zuständigen Landesbehörden und das RKI
# können einige Tage vergehen (Melde- und Übermittlungsverzug). Jeden Tag
# werden dem RKI neue Fälle übermittelt, die am gleichen Tag oder bereits
# an früheren Tagen an das Gesundheitsamt gemeldet worden sind. Diese Fälle
# werden in der Grafik Neue COVID-19-Fälle/Tag dann bei dem jeweiligen
# Datum ergänzt.
START_DATE = "2020-03-09"
def _build_case_rate(df):
# Get time differences (unit: seconds) in the df's datetimeindex. `dt`
# is a magic accessor that yields an array of time deltas.
dt_seconds = pd.Series(df.index).diff().dt.total_seconds()
# Construct new series with original datetimeindex as index and time
# differences (unit: days) as values.
dt_days = pd.Series(dt_seconds) / 86400.0
dt_days.index = df.index
# print(dt_days)
cases_change_per_day = df["sum_cases"].diff().div(dt_days)
df["cases_change_per_day"] = cases_change_per_day
print(df)
# increase resolution and forward-fill values. Could also use
# `interpolate()` but that's too artificial, I think it's fair to see
# the actual discrete jumps in data as of "batch processing".
df_case_change = df["cases_change_per_day"].resample("1H").pad()
print(type(df_case_change))
# sys.exit()
# Should be >= 7 to be meaningful.
window_width_days = 5
window = df_case_change.rolling(window="%sD" % window_width_days)
# Manually build rolling window mean.
wdw_norm = window.sum() / (window_width_days * 24.0)
# During the rolling window analysis the value derived from the current
# window position is assigned to the right window boundary (i.e. to the
# newest timestamp in the window). For presentation it is more convenient
# and intuitive to have it assigned to the temporal center of the time
# window. Invoking `rolling(..., center=True)` however yields
# `NotImplementedError: center is not implemented for datetimelike and
# offset based windows`. As a workaround, shift the data by half the window
# size to 'the left': shift the timestamp index by a constant / offset.
offset = pd.DateOffset(days=window_width_days / 2.0)
wdw_norm.index = wdw_norm.index - offset
print(wdw_norm)
# sys.exit()
# cut the last 2 days worth of data, at least for RKI this is just too
# much affected by Meldeverzug
d_end = NOW - timedelta(days=3)
# t_end = f"{d_end.strftime('%Y-%m-%d')} 23:59:59"
return wdw_norm[:f"{d_end.strftime('%Y-%m-%d')}"]
df_mixed_data = pd.read_csv(
"data.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
date_parser=lambda col: pd.to_datetime(col, utc=True),
)[START_DATE:]
df_mixed_data.index.name = "time"
df_mixed_case_rate_rw = _build_case_rate(df_mixed_data)[START_DATE:]
df_rl = pd.read_csv(
"cases-rl-crowdsource-by-state.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
)[START_DATE:]
df_rl.index.name = "time"
df_rl_case_rate_rw = _build_case_rate(df_rl)[START_DATE:]
df_rki = pd.read_csv(
"cases-rki-by-state.csv",
index_col=["time_iso8601"],
parse_dates=["time_iso8601"],
)[START_DATE:]
df_rki.index.name = "time"
df_rki_case_rate_rw = _build_case_rate(df_rki)[START_DATE:]
df_jhu = jhu_csse_csv_to_dataframe(os.environ["JHU_TS_CSV_PATH"], "germany")[
START_DATE:
]
df_jhu.index.name = "time"
df_jhu_case_rate_rw = _build_case_rate(df_jhu)[START_DATE:]
# Normalize for 'sum_cases' plots
for _df in [df_rki, df_jhu, df_mixed_data, df_rl]:
_df["sum_cases"] = _df["sum_cases"] / 10000
plt.figure()
ax = df_rki["sum_cases"].plot(linestyle="solid", marker="x", color="red",)
df_rl["sum_cases"].plot(linestyle="solid", marker="x", color="black", ax=ax)
df_mixed_data["sum_cases"].plot(
linestyle="dashdot", marker="x", color="black", ax=ax
)
df_jhu["sum_cases"].plot(linestyle="dashdot", marker="x", color="gray", ax=ax)
ax.legend(
[
"RKI data, by Meldedatum",
"Risklayer/Tagesspiegel crowdsource data, daily snapshots",
"ZEIT ONLINE, daily snapshots",
"JHU (GitHub CSSEGISandData/COVID-19)",
],
numpoints=4,
handlelength=8,
)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.xlabel("Time")
plt.ylabel("cumulative case count, all Germany / 10^4")
# plt.title("COVID-19 case count, Germany, comparison of data sources")
# set_title('Override command rate (from both DC/OS repositories)')
# set_subtitle('Arithmetic mean over rolling time window')
# plt.tight_layout(rect=(0, 0, 1, 0.95))
plt.tight_layout()
fig_filepath_wo_ext = (
f"gae/static/data-sources-comparison-{NOW.strftime('%Y-%m-%d')}"
)
plt.savefig(fig_filepath_wo_ext + ".png", dpi=150)
plt.savefig(fig_filepath_wo_ext + ".pdf")
# -----------
plt.figure(figsize=(16.0, 9.0))
ax = df_rki["cases_change_per_day"].plot(
linestyle="None", marker="x", color="black",
)
df_rki_case_rate_rw.plot(linestyle="solid", marker=None, color="black", ax=ax)
df_jhu_case_rate_rw.plot(linestyle="dashdot", marker=None, color="gray", ax=ax)
ax.legend(
[
'raw RKI data, by date of report ("Meldedatum")',
"RKI rolling window mean (width: 5 days)",
"JHU rolling window mean (width: 5 days)",
],
numpoints=4,
handlelength=8,
loc="upper left",
)
plt.xlabel("")
plt.ylabel("COVID-19 cumulative case count, change per day (all Germany)")
plt.tight_layout()
fig_filepath_wo_ext = f"gae/static/case-rate-rw-{NOW.strftime('%Y-%m-%d')}"
plt.savefig(fig_filepath_wo_ext + ".png", dpi=150)
plt.savefig(fig_filepath_wo_ext + ".pdf")
# plt.show()
plot_with_bokeh(df_rki, df_jhu, df_mixed_data, df_rl)
def _set_common_bokeh_fig_props(fig):
fig.toolbar.active_drag = None
fig.toolbar.active_scroll = None
fig.toolbar.active_tap = None
fig.outline_line_color = "#333333"
fig.outline_line_width = 1
fig.outline_line_alpha = 0.7
fig.title.text_font_size = "10px"
fig.legend.label_text_font_size = "10px"
# fig.legend.label_text_font = "'Open Sans Condensed', sans-serif"
fig.legend.spacing = 0
fig.legend.margin = 3
fig.legend.label_standoff = 5
fig.legend.label_height = 0
# import json
# print(json.dumps(dir(fig.legend), indent=2))
# fig.text_font_size = "12pt"
fig.xaxis.ticker.desired_num_ticks = 21
fig.xaxis.formatter = bokeh.models.DatetimeTickFormatter(days=["%b-%d"])
fig.xaxis.major_label_orientation = 3.1415 / 4 + 0.5
# fig.xaxis.axis_label = "Date"
fig.xaxis.axis_label_text_font_size = "16px"
fig.xaxis.major_label_text_font_size = "10px"
fig.xaxis.axis_label_text_font_style = "normal"
fig.y_range.start = 0
# fig.yaxis.axis_label = "confirmed cases / 10000"
fig.yaxis.axis_label_text_font_size = "10px"
fig.yaxis.axis_label_text_font_style = "normal"
fig.yaxis.major_label_text_font_size = "10px"
def plot_with_bokeh(df_rki, df_jhu, df_mixed_data, df_rl):
# html_file_path = 'bokeh-comp-plot.html'
# bokeh.plotting.output_file(html_file_path)
# bokeh.io.curdoc().theme = "dark_minimal"
cname = "sum_cases"
fig = bokeh.plotting.figure(
# title=f"Generated at {now.strftime('%Y-%m-%d %H:%M UTC')}",
title="Germany, cumulative cases / 10000",
x_axis_type="datetime",
toolbar_location=None,
background_fill_color="#eeeeee",
height=450,
)
# Scatter and line seemingly need to be done separately.
# RKI
fig.line(
"time",
cname,
line_color="red",
line_width=2,
line_dash="solid",
legend_label="RKI data, by Meldedatum",
source=bokeh.models.ColumnDataSource(data=df_rki),
)
fig.scatter(
"time",
cname,
marker="x",
line_color="red",
line_width=2,
size=8,
source=bokeh.models.ColumnDataSource(data=df_rki),
)
# JHU
fig.line(
"time",
"sum_cases",
line_color="black",
line_width=1,
line_dash="solid",
legend_label="JHU (GitHub)",
source=bokeh.models.ColumnDataSource(data=df_jhu),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="black",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_jhu),
)
# Risklayer
fig.line(
"time",
"sum_cases",
line_color="gray",
line_width=1,
line_dash="dashdot",
legend_label="Risklayer / Tagesspiegel",
source=bokeh.models.ColumnDataSource(data=df_rl),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="gray",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_rl),
)
fig.line(
"time",
"sum_cases",
line_color="gray",
line_width=1,
line_dash="solid",
legend_label="ZEIT ONLINE",
source=bokeh.models.ColumnDataSource(data=df_mixed_data),
)
fig.scatter(
"time",
"sum_cases",
marker="x",
line_color="gray",
line_width=1,
size=8,
source=bokeh.models.ColumnDataSource(data=df_mixed_data),
)
# fig.line(
# "time",
# "sum_cases",
# marker="x",
# size=8,
# line_color="black",
# line_width=3,
# ,
# source=bokeh.models.ColumnDataSource(data=df_jhu),
# )
_set_common_bokeh_fig_props(fig)
fig.legend.location = "top_left"
templ_env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="./"))
template = templ_env.get_template("gae/static/index.html.template")
html = bokeh.embed.file_html(
column(fig, fig, sizing_mode="stretch_both"),
template=template,
resources=bokeh.resources.CDN,
template_variables={"today_string": NOW.strftime("%Y-%m-%d"),},
)
with open("gae/static/index.html", "wb") as f:
f.write(html.encode("utf-8"))
def jhu_csse_csv_to_dataframe(data_file_path, location_name):
"""
data_file_path: expect an instance of `time_series_19-covid-Confirmed.csv`
from https://github.com/CSSEGISandData/COVID-19/
location_name: the lower-cased version of this must be a column in the
processed data set.
"""
log.info("parse JHU data file")
df = pd.read_csv(data_file_path)
log.info("process JHU data file")
# Merge location names into somewhat more managable identifiers.
countries = [
"_".join(c.lower().split()) if c != "nan" else ""
for c in list(df["Country/Region"].astype("str"))
]
provinces = [
"_".join(p.lower().split()) if p != "nan" else ""
for p in list(df["Province/State"].astype("str"))
]
countries = [c.replace(",", "").replace(".", "") for c in countries]
provinces = [p.replace(",", "").replace(".", "") for p in provinces]
df["where"] = [f"{c}_{p}" if p else c for c, p in zip(countries, provinces)]
# Make each column represent a location, and each row represent a day
# (date).
df.drop(["Lat", "Long", "Country/Region", "Province/State"], axis=1, inplace=True)
df = df.set_index("where")
df = df.transpose()
# Parse date strings into pandas DateTime objects, set proper
# DateTimeIndex.
normalized_date_strings = [
"/".join(t.zfill(2) for t in o.split("/")) for o in list(df.index)
]
df.index = normalized_date_strings
df.index = pd.to_datetime(df.index, format="%m/%d/%y")
df.index.name = "date"
# df.sort_index(inplace=True)
# Only return series for specific location
loc = location_name.lower()
# rename column for consistency with other dfs
df["sum_cases"] = df[loc]
return df["sum_cases"].to_frame()
def matplotlib_config():
plt.style.use("ggplot")
matplotlib.rcParams["figure.figsize"] = [10.5, 7.0]
matplotlib.rcParams["figure.dpi"] = 100
matplotlib.rcParams["savefig.dpi"] = 150
# mpl.rcParams['font.size'] = 12
if __name__ == "__main__":
matplotlib_config()
main()
|
from nextcord.ext import commands
import json
import pymongo
import os
class AddBadWords(commands.Cog):
def __init__(self, client):
self.client = client
@commands.guild_only()
@commands.has_permissions(send_messages=True, manage_messages=True)
@commands.command(name="add-bad-words", aliases=["add-bad-word", "addbadwords", "addbadword", 'add_bad_words', "add_bad_word"])
async def addbadwords(self, ctx, *, new_words):
if '"' not in new_words:
await ctx.send(f"Error", delete_after=8)
return
client = pymongo.MongoClient(
f"mongodb+srv://{os.environ["info"]}@cluster0.o0xc5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
cluster = client["Guardzilla"]
blockedwords = cluster["blockedwords"]
data = blockedwords.find_one({"_id": 0})
if not data:
blockedwords.insert_one({"_id": 0, str(ctx.guild.id): [0, []]})
data = blockedwords.find_one({"_id": 0})
if str(ctx.guild.id) not in data:
blockedwords.insert_one({"_id": 0, str(ctx.guild.id): [0, []]})
data = blockedwords.find_one({"_id": 0})
words, added_blocked = [], []
for i in range(len(str(new_words).split('"'))//2):
words.append(str(new_words).split('"')[i*2+1])
for bad_word in words:
if bad_word not in data[str(ctx.message.guild.id)][1]:
if bad_word:
data[str(ctx.message.guild.id)][1].append(bad_word)
added_blocked.append(bad_word)
# delete data from data base
blockedwords.delete_one({"_id": 0})
# add the new data to the data base
blockedwords.insert_one(data)
if bool(added_blocked):
await ctx.send(f"New bad words:\n" + ' | '.join([f"`{x}`" for x in added_blocked]) + "\nadded!!", delete_after=8)
else:
await ctx.send(f"no bad words added.", delete_after=8)
def setup(client):
client.add_cog(AddBadWords(client))
| from nextcord.ext import commands
import json
import pymongo
import os
class AddBadWords(commands.Cog):
def __init__(self, client):
self.client = client
@commands.guild_only()
@commands.has_permissions(send_messages=True, manage_messages=True)
@commands.command(name="add-bad-words", aliases=["add-bad-word", "addbadwords", "addbadword", 'add_bad_words', "add_bad_word"])
async def addbadwords(self, ctx, *, new_words):
if '"' not in new_words:
await ctx.send(f"Error", delete_after=8)
return
client = pymongo.MongoClient(
f"mongodb+srv://{os.environ['info']}@cluster0.o0xc5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
cluster = client["Guardzilla"]
blockedwords = cluster["blockedwords"]
data = blockedwords.find_one({"_id": 0})
if not data:
blockedwords.insert_one({"_id": 0, str(ctx.guild.id): [0, []]})
data = blockedwords.find_one({"_id": 0})
if str(ctx.guild.id) not in data:
blockedwords.insert_one({"_id": 0, str(ctx.guild.id): [0, []]})
data = blockedwords.find_one({"_id": 0})
words, added_blocked = [], []
for i in range(len(str(new_words).split('"'))//2):
words.append(str(new_words).split('"')[i*2+1])
for bad_word in words:
if bad_word not in data[str(ctx.message.guild.id)][1]:
if bad_word:
data[str(ctx.message.guild.id)][1].append(bad_word)
added_blocked.append(bad_word)
# delete data from data base
blockedwords.delete_one({"_id": 0})
# add the new data to the data base
blockedwords.insert_one(data)
if bool(added_blocked):
await ctx.send(f"New bad words:\n" + ' | '.join([f"`{x}`" for x in added_blocked]) + "\nadded!!", delete_after=8)
else:
await ctx.send(f"no bad words added.", delete_after=8)
def setup(client):
client.add_cog(AddBadWords(client))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved.
#
from __future__ import division
import os
import shutil
import time
from collections import namedtuple
from io import BytesIO
from logging import getLogger
from typing import TYPE_CHECKING
from .azure_util import SnowflakeAzureUtil
from .constants import ResultStatus
from .encryption_util import SnowflakeEncryptionUtil
from .gcs_util import SnowflakeGCSUtil
from .s3_util import SnowflakeS3Util
if TYPE_CHECKING: # pragma: no cover
from .file_transfer_agent import SnowflakeFileMeta
DEFAULT_CONCURRENCY = 1
DEFAULT_MAX_RETRY = 5
logger = getLogger(__name__)
"""
Encryption Material
"""
SnowflakeFileEncryptionMaterial = namedtuple(
"SnowflakeS3FileEncryptionMaterial", [
"query_stage_master_key", # query stage master key
"query_id", # query id
"smk_id" # SMK id
]
)
class NeedRenewTokenError(Exception):
pass
class SnowflakeRemoteStorageUtil(object):
@staticmethod
def get_for_storage_type(_type):
if _type == 'S3':
return SnowflakeS3Util
elif _type == 'AZURE':
return SnowflakeAzureUtil
elif _type == 'GCS':
return SnowflakeGCSUtil
else:
return None
@staticmethod
def create_client(stage_info, use_accelerate_endpoint=False):
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(
stage_info['locationType'])
return util_class.create_client(
stage_info,
use_accelerate_endpoint=use_accelerate_endpoint)
@staticmethod
def upload_one_file(meta: 'SnowflakeFileMeta') -> None:
"""Uploads a file to S3."""
encryption_metadata = None
if meta.encryption_material is not None:
if meta.src_stream is None:
(encryption_metadata,
data_file) = SnowflakeEncryptionUtil.encrypt_file(
meta.encryption_material,
meta.real_src_file_name, tmp_dir=meta.tmp_dir)
logger.debug(f'encrypted data file={data_file}, size={os.path.getsize(data_file)}')
else:
encrypted_stream = BytesIO()
src_stream = meta.real_src_stream or meta.src_stream
src_stream.seek(0)
encryption_metadata = SnowflakeEncryptionUtil.encrypt_stream(
meta.encryption_material,
src_stream,
encrypted_stream
)
src_stream.seek(0)
logger.debug(f'encrypted data stream size={encrypted_stream.seek(0, os.SEEK_END)}')
encrypted_stream.seek(0)
if meta.real_src_stream is not None:
meta.real_src_stream.close()
meta.real_src_stream = encrypted_stream
data_file = meta.real_src_file_name
else:
logger.debug('not encrypted data file')
data_file = meta.real_src_file_name
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(
meta.stage_info['locationType'])
logger.debug(f"putting a file: {meta.stage_info["location"]}, {meta.dst_file_name}")
max_concurrency = meta.parallel
last_err = None
max_retry = DEFAULT_MAX_RETRY
for retry in range(max_retry):
if not meta.overwrite:
file_header = util_class.get_file_header(
meta, meta.dst_file_name)
if file_header and \
meta.result_status == ResultStatus.UPLOADED:
logger.debug(f'file already exists location="{meta.stage_info['location']}", '
f'file_name="{meta.dst_file_name}"')
meta.dst_file_size = 0
meta.result_status = ResultStatus.SKIPPED
return
if meta.overwrite or meta.result_status == ResultStatus.NOT_FOUND_FILE:
util_class.upload_file(
data_file,
meta,
encryption_metadata,
max_concurrency,
multipart_threshold=meta.multipart_threshold
)
if meta.result_status == ResultStatus.UPLOADED:
return
elif meta.result_status == ResultStatus.RENEW_TOKEN:
return
elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL:
return
elif meta.result_status == ResultStatus.NEED_RETRY:
last_err = meta.last_error
logger.debug(f'Failed to upload a file: {data_file}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping {sleeping_time}")
time.sleep(sleeping_time)
elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY:
last_err = meta.last_error
max_concurrency = meta.parallel - int(
retry * meta.parallel / max_retry)
max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency)
meta.last_max_concurrency = max_concurrency
logger.debug(
f'Failed to upload a file: {data_file}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if meta.no_sleeping_time is None:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping: {sleeping_time}")
time.sleep(sleeping_time)
else:
if last_err:
raise last_err
else:
msg = f"Unknown Error in uploading a file: {data_file}"
raise Exception(msg)
@staticmethod
def download_one_file(meta: 'SnowflakeFileMeta') -> None:
"""Downloads a file from S3."""
full_dst_file_name = os.path.join(meta.local_location, os.path.basename(meta.dst_file_name))
full_dst_file_name = os.path.realpath(full_dst_file_name)
# TODO: validate full_dst_file_name is under the writable directory
base_dir = os.path.dirname(full_dst_file_name)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(meta.stage_info['locationType'])
file_header = util_class.get_file_header(meta, meta.src_file_name)
if file_header:
meta.src_file_size = file_header.content_length
full_dst_file_name = os.path.join(meta.local_location, os.path.basename(meta.dst_file_name))
full_dst_file_name = os.path.realpath(full_dst_file_name)
max_concurrency = meta.parallel
last_err = None
max_retry = DEFAULT_MAX_RETRY
for retry in range(max_retry):
util_class._native_download_file(meta, full_dst_file_name,
max_concurrency)
if meta.result_status == ResultStatus.DOWNLOADED:
if meta.encryption_material is not None:
logger.debug(f'encrypted data file={full_dst_file_name}')
# For storage utils that do not have the privilege of
# getting the metadata early, both object and metadata
# are downloaded at once. In which case, the file meta will
# be updated with all the metadata that we need and
# then we can call get_file_header to get just that and also
# preserve the idea of getting metadata in the first place.
# One example of this is the utils that use presigned url
# for upload/download and not the storage client library.
if meta.presigned_url is not None:
file_header = util_class.get_file_header(meta, meta.src_file_name)
tmp_dst_file_name = SnowflakeEncryptionUtil.decrypt_file(
file_header.encryption_metadata,
meta.encryption_material,
full_dst_file_name, tmp_dir=meta.tmp_dir)
shutil.copyfile(tmp_dst_file_name, full_dst_file_name)
os.unlink(tmp_dst_file_name)
else:
logger.debug(f'not encrypted data file={full_dst_file_name}')
stat_info = os.stat(full_dst_file_name)
meta.dst_file_size = stat_info.st_size
return
elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL:
return
elif meta.result_status == ResultStatus.RENEW_TOKEN:
return
elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY:
max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry)
max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency)
meta.last_max_concurrency = max_concurrency
last_err = meta.last_error
logger.debug(f'Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug("sleeping: %s", sleeping_time)
time.sleep(sleeping_time)
elif meta.result_status == ResultStatus.NEED_RETRY:
last_err = meta.last_error
logger.debug(
f'Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping: {sleeping_time}")
time.sleep(sleeping_time)
else:
if last_err:
raise last_err
else:
msg = f"Unknown Error in downloading a file: {full_dst_file_name}"
raise Exception(msg)
@staticmethod
def upload_one_file_with_retry(meta: 'SnowflakeFileMeta') -> None:
"""Uploads one file with retry."""
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(meta.stage_info['locationType'])
for _ in range(10):
# retry
SnowflakeRemoteStorageUtil.upload_one_file(meta)
if meta.result_status == ResultStatus.UPLOADED:
for _ in range(10):
util_class.get_file_header(meta, meta.dst_file_name)
if meta.result_status == ResultStatus.NOT_FOUND_FILE:
time.sleep(1) # wait 1 second
logger.debug('not found. double checking...')
continue
break
else:
# not found. retry with the outer loop
logger.debug('not found. gave up. re-uploading...')
continue
break
else:
# could not upload a file even after retry
meta.result_status = ResultStatus.ERROR
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved.
#
from __future__ import division
import os
import shutil
import time
from collections import namedtuple
from io import BytesIO
from logging import getLogger
from typing import TYPE_CHECKING
from .azure_util import SnowflakeAzureUtil
from .constants import ResultStatus
from .encryption_util import SnowflakeEncryptionUtil
from .gcs_util import SnowflakeGCSUtil
from .s3_util import SnowflakeS3Util
if TYPE_CHECKING: # pragma: no cover
from .file_transfer_agent import SnowflakeFileMeta
DEFAULT_CONCURRENCY = 1
DEFAULT_MAX_RETRY = 5
logger = getLogger(__name__)
"""
Encryption Material
"""
SnowflakeFileEncryptionMaterial = namedtuple(
"SnowflakeS3FileEncryptionMaterial", [
"query_stage_master_key", # query stage master key
"query_id", # query id
"smk_id" # SMK id
]
)
class NeedRenewTokenError(Exception):
pass
class SnowflakeRemoteStorageUtil(object):
@staticmethod
def get_for_storage_type(_type):
if _type == 'S3':
return SnowflakeS3Util
elif _type == 'AZURE':
return SnowflakeAzureUtil
elif _type == 'GCS':
return SnowflakeGCSUtil
else:
return None
@staticmethod
def create_client(stage_info, use_accelerate_endpoint=False):
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(
stage_info['locationType'])
return util_class.create_client(
stage_info,
use_accelerate_endpoint=use_accelerate_endpoint)
@staticmethod
def upload_one_file(meta: 'SnowflakeFileMeta') -> None:
"""Uploads a file to S3."""
encryption_metadata = None
if meta.encryption_material is not None:
if meta.src_stream is None:
(encryption_metadata,
data_file) = SnowflakeEncryptionUtil.encrypt_file(
meta.encryption_material,
meta.real_src_file_name, tmp_dir=meta.tmp_dir)
logger.debug(f'encrypted data file={data_file}, size={os.path.getsize(data_file)}')
else:
encrypted_stream = BytesIO()
src_stream = meta.real_src_stream or meta.src_stream
src_stream.seek(0)
encryption_metadata = SnowflakeEncryptionUtil.encrypt_stream(
meta.encryption_material,
src_stream,
encrypted_stream
)
src_stream.seek(0)
logger.debug(f'encrypted data stream size={encrypted_stream.seek(0, os.SEEK_END)}')
encrypted_stream.seek(0)
if meta.real_src_stream is not None:
meta.real_src_stream.close()
meta.real_src_stream = encrypted_stream
data_file = meta.real_src_file_name
else:
logger.debug('not encrypted data file')
data_file = meta.real_src_file_name
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(
meta.stage_info['locationType'])
logger.debug(f"putting a file: {meta.stage_info['location']}, {meta.dst_file_name}")
max_concurrency = meta.parallel
last_err = None
max_retry = DEFAULT_MAX_RETRY
for retry in range(max_retry):
if not meta.overwrite:
file_header = util_class.get_file_header(
meta, meta.dst_file_name)
if file_header and \
meta.result_status == ResultStatus.UPLOADED:
logger.debug(f'file already exists location="{meta.stage_info["location"]}", '
f'file_name="{meta.dst_file_name}"')
meta.dst_file_size = 0
meta.result_status = ResultStatus.SKIPPED
return
if meta.overwrite or meta.result_status == ResultStatus.NOT_FOUND_FILE:
util_class.upload_file(
data_file,
meta,
encryption_metadata,
max_concurrency,
multipart_threshold=meta.multipart_threshold
)
if meta.result_status == ResultStatus.UPLOADED:
return
elif meta.result_status == ResultStatus.RENEW_TOKEN:
return
elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL:
return
elif meta.result_status == ResultStatus.NEED_RETRY:
last_err = meta.last_error
logger.debug(f'Failed to upload a file: {data_file}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping {sleeping_time}")
time.sleep(sleeping_time)
elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY:
last_err = meta.last_error
max_concurrency = meta.parallel - int(
retry * meta.parallel / max_retry)
max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency)
meta.last_max_concurrency = max_concurrency
logger.debug(
f'Failed to upload a file: {data_file}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if meta.no_sleeping_time is None:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping: {sleeping_time}")
time.sleep(sleeping_time)
else:
if last_err:
raise last_err
else:
msg = f"Unknown Error in uploading a file: {data_file}"
raise Exception(msg)
@staticmethod
def download_one_file(meta: 'SnowflakeFileMeta') -> None:
"""Downloads a file from S3."""
full_dst_file_name = os.path.join(meta.local_location, os.path.basename(meta.dst_file_name))
full_dst_file_name = os.path.realpath(full_dst_file_name)
# TODO: validate full_dst_file_name is under the writable directory
base_dir = os.path.dirname(full_dst_file_name)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(meta.stage_info['locationType'])
file_header = util_class.get_file_header(meta, meta.src_file_name)
if file_header:
meta.src_file_size = file_header.content_length
full_dst_file_name = os.path.join(meta.local_location, os.path.basename(meta.dst_file_name))
full_dst_file_name = os.path.realpath(full_dst_file_name)
max_concurrency = meta.parallel
last_err = None
max_retry = DEFAULT_MAX_RETRY
for retry in range(max_retry):
util_class._native_download_file(meta, full_dst_file_name,
max_concurrency)
if meta.result_status == ResultStatus.DOWNLOADED:
if meta.encryption_material is not None:
logger.debug(f'encrypted data file={full_dst_file_name}')
# For storage utils that do not have the privilege of
# getting the metadata early, both object and metadata
# are downloaded at once. In which case, the file meta will
# be updated with all the metadata that we need and
# then we can call get_file_header to get just that and also
# preserve the idea of getting metadata in the first place.
# One example of this is the utils that use presigned url
# for upload/download and not the storage client library.
if meta.presigned_url is not None:
file_header = util_class.get_file_header(meta, meta.src_file_name)
tmp_dst_file_name = SnowflakeEncryptionUtil.decrypt_file(
file_header.encryption_metadata,
meta.encryption_material,
full_dst_file_name, tmp_dir=meta.tmp_dir)
shutil.copyfile(tmp_dst_file_name, full_dst_file_name)
os.unlink(tmp_dst_file_name)
else:
logger.debug(f'not encrypted data file={full_dst_file_name}')
stat_info = os.stat(full_dst_file_name)
meta.dst_file_size = stat_info.st_size
return
elif meta.result_status == ResultStatus.RENEW_PRESIGNED_URL:
return
elif meta.result_status == ResultStatus.RENEW_TOKEN:
return
elif meta.result_status == ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY:
max_concurrency = meta.parallel - int(retry * meta.parallel / max_retry)
max_concurrency = max(DEFAULT_CONCURRENCY, max_concurrency)
meta.last_max_concurrency = max_concurrency
last_err = meta.last_error
logger.debug(f'Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug("sleeping: %s", sleeping_time)
time.sleep(sleeping_time)
elif meta.result_status == ResultStatus.NEED_RETRY:
last_err = meta.last_error
logger.debug(
f'Failed to download a file: {full_dst_file_name}, err: {last_err}. Retrying with '
f'max concurrency: {max_concurrency}')
if not meta.no_sleeping_time:
sleeping_time = min(2 ** retry, 16)
logger.debug(f"sleeping: {sleeping_time}")
time.sleep(sleeping_time)
else:
if last_err:
raise last_err
else:
msg = f"Unknown Error in downloading a file: {full_dst_file_name}"
raise Exception(msg)
@staticmethod
def upload_one_file_with_retry(meta: 'SnowflakeFileMeta') -> None:
"""Uploads one file with retry."""
util_class = SnowflakeRemoteStorageUtil.get_for_storage_type(meta.stage_info['locationType'])
for _ in range(10):
# retry
SnowflakeRemoteStorageUtil.upload_one_file(meta)
if meta.result_status == ResultStatus.UPLOADED:
for _ in range(10):
util_class.get_file_header(meta, meta.dst_file_name)
if meta.result_status == ResultStatus.NOT_FOUND_FILE:
time.sleep(1) # wait 1 second
logger.debug('not found. double checking...')
continue
break
else:
# not found. retry with the outer loop
logger.debug('not found. gave up. re-uploading...')
continue
break
else:
# could not upload a file even after retry
meta.result_status = ResultStatus.ERROR
|
LICNECE = """
Copyright © 2021 Social404
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import os
print(LICNECE)
time.sleep(3)
os.system('cls' if os.name == 'nt' else 'clear')
import random
import string
import ctypes
try: # Check if the requrements have been installed
from discord_webhook import DiscordWebhook # Try to import discord_webhook
except ImportError: # If it chould not be installed
input(f"Module discord_webhook not installed, to install run '{"py -3" if os.name == "nt" else "python3.8"} -m pip install discord_webhook'\nPress enter to exit") # Tell the user it has not been installed and how to install it
exit() # Exit the program
try: # Setup try statement to catch the error
import requests # Try to import requests
except ImportError: # If it has not been installed
input(f"Module requests not installed, to install run '{"py -3" if os.name == "nt" else "python3.8"} -m pip install requests'\nPress enter to exit")# Tell the user it has not been installed and how to install it
exit() # Exit the program
class NitroGen: # Initialise the class
def __init__(self): # The initaliseaiton function
self.fileName = "Nitro Codes.txt" # Set the file name the codes are stored in
def main(self): # The main function contains the most important code
os.system('cls' if os.name == 'nt' else 'clear') # Clear the screen
if os.name == "nt": # If the system is windows
print("")
ctypes.windll.kernel32.SetConsoleTitleW("Nitro Generator and Checker - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf") # Change the
else: # Or if it is unix
print(f'\33]0;Nitro Generator and Checker - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf\a', end='', flush=True) # Update title of command prompt
print(""" █████╗ ███╗ ██╗ ██████╗ ███╗ ██╗██╗██╗ ██╗
██╔══██╗████╗ ██║██╔═══██╗████╗ ██║██║╚██╗██╔╝
███████║██╔██╗ ██║██║ ██║██╔██╗ ██║██║ ╚███╔╝
██╔══██║██║╚██╗██║██║ ██║██║╚██╗██║██║ ██╔██╗
██║ ██║██║ ╚████║╚██████╔╝██║ ╚████║██║██╔╝ ██╗
╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝
""") # Print the title card
time.sleep(2) # Wait a few seconds
self.slowType("Made by: Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf", .02) # Print who developed the code
time.sleep(1) # Wait a little more
self.slowType("\nInput How Many Codes to Generate and Check: ", .02, newLine = False) # Print the first question
num = int(input('')) # Ask the user for the amount of codes
# Get the webhook url, if the user does not wish to use a webhook the message will be an empty string
self.slowType("\nDo you wish to use a discord webhook? \nIf so type it here or press enter to ignore: ", .02, newLine = False)
url = input('') # Get the awnser
webhook = url if url != "" else None # If the url is empty make it be None insted
# print() # Print a newline for looks
valid = [] # Keep track of valid codes
invalid = 0 # Keep track of how many invalid codes was detected
for i in range(num): # Loop over the amount of codes to check
try: # Catch any errors that may happen
code = "".join(random.choices( # Generate the id for the gift
string.ascii_uppercase + string.digits + string.ascii_lowercase,
k = 16
))
url = f"https://discord.gift/{code}" # Generate the url
result = self.quickChecker(url, webhook) # Check the codes
if result: # If the code was valid
valid.append(url) # Add that code to the list of found codes
else: # If the code was not valid
invalid += 1 # Increase the invalid counter by one
except Exception as e: # If the request fails
print(f" Error | {url} ") # Tell the user an error occurred
if os.name == "nt": # If the system is windows
ctypes.windll.kernel32.SetConsoleTitleW(f"Nitro Generator and Checker - {len(valid)} Valid | {invalid} Invalid - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf") # Change the title
print("")
else: # If it is a unix system
print(f'\33]0;Nitro Generator and Checker - {len(valid)} Valid | {invalid} Invalid - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf\a', end='', flush=True) # Change the title
print(f"""
Results:
Valid: {len(valid)}
Invalid: {invalid}
Valid Codes: {', '.join(valid )}""") # Give a report of the results of the check
input("\nThe end! Press Enter 5 times to close the program.") # Tell the user the program finished
[input(i) for i in range(4,0,-1)] # Wait for 4 enter presses
def slowType(self, text, speed, newLine = True): # Function used to print text a little more fancier
for i in text: # Loop over the message
print(i, end = "", flush = True) # Print the one charecter, flush is used to force python to print the char
time.sleep(speed) # Sleep a little before the next one
if newLine: # Check if the newLine argument is set to True
print() # Print a final newline to make it act more like a normal print statement
def generator(self, amount): # Function used to generate and store nitro codes in a seperate file
with open(self.fileName, "w", encoding="utf-8") as file: # Load up the file in write mode
print("Wait, Generating for you") # Let the user know the code is generating the codes
start = time.time() # Note the initaliseation time
for i in range(amount): # Loop the amount of codes to generate
code = "".join(random.choices(
string.ascii_uppercase + string.digits + string.ascii_lowercase,
k = 16
)) # Generate the code id
file.write(f"https://discord.gift/{code}\n") # Write the code
# Tell the user its done generating and how long tome it took
print(f"Genned {amount} codes | Time taken: {round(time.time() - start, 5)}s\n") #
def fileChecker(self, notify = None): # Function used to check nitro codes from a file
valid = [] # A list of the valid codes
invalid = 0 # The amount of invalid codes detected
with open(self.fileName, "r", encoding="utf-8") as file: # Open the file containing the nitro codes
for line in file.readlines(): # Loop over each line in the file
nitro = line.strip("\n") # Remove the newline at the end of the nitro code
# Create the requests url for later use
url = f"https://discordapp.com/api/v6/entitlements/gift-codes/{nitro}?with_application=false&with_subscription_plan=true"
response = requests.get(url) # Get the responce from the url
if response.status_code == 200: # If the responce went through
print(f" Valid | {nitro} ") # Notify the user the code was valid
valid.append(nitro) # Append the nitro code the the list of valid codes
if notify is not None: # If a webhook has been added
DiscordWebhook( # Send the message to discord letting the user know there has been a valid nitro code
url = notify,
content = f"Valid Nito Code detected! @everyone \n{nitro}"
).execute()
else: # If there has not been a discord webhook setup just stop the code
break # Stop the loop since a valid code was found
else: # If the responce got ignored or is invalid ( such as a 404 or 405 )
print(f" Invalid | {nitro} ") # Tell the user it tested a code and it was invalid
invalid += 1 # Increase the invalid counter by one
return {"valid" : valid, "invalid" : invalid} # Return a report of the results
def quickChecker(self, nitro, notify = None): # Used to check a single code at a time
# Generate the request url
url = f"https://discordapp.com/api/v6/entitlements/gift-codes/{nitro}?with_application=false&with_subscription_plan=true"
response = requests.get(url) # Get the response from discord
if response.status_code == 200: # If the responce went through
print(f" Valid | {nitro} ", flush=True, end="" if os.name == 'nt' else "\n") # Notify the user the code was valid
with open("Nitro Codes.txt", "w") as file: # Open file to write
file.write(nitro) # Write the nitro code to the file it will automatically add a newline
if notify is not None: # If a webhook has been added
DiscordWebhook( # Send the message to discord letting the user know there has been a valid nitro code
url = notify,
content = f"Valid Nito Code detected! @everyone \n{nitro}"
).execute()
return True # Tell the main function the code was found
else: # If the responce got ignored or is invalid ( such as a 404 or 405 )
print(f" Invalid | {nitro} ", flush=True, end="" if os.name == 'nt' else "\n") # Tell the user it tested a code and it was invalid
return False # Tell the main function there was not a code found
if __name__ == '__main__':
Gen = NitroGen() # Create the nitro generator object
Gen.main() # Run the main code
| LICNECE = """
Copyright © 2021 Social404
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import time
import os
print(LICNECE)
time.sleep(3)
os.system('cls' if os.name == 'nt' else 'clear')
import random
import string
import ctypes
try: # Check if the requrements have been installed
from discord_webhook import DiscordWebhook # Try to import discord_webhook
except ImportError: # If it chould not be installed
input(f"Module discord_webhook not installed, to install run '{'py -3' if os.name == 'nt' else 'python3.8'} -m pip install discord_webhook'\nPress enter to exit") # Tell the user it has not been installed and how to install it
exit() # Exit the program
try: # Setup try statement to catch the error
import requests # Try to import requests
except ImportError: # If it has not been installed
input(f"Module requests not installed, to install run '{'py -3' if os.name == 'nt' else 'python3.8'} -m pip install requests'\nPress enter to exit")# Tell the user it has not been installed and how to install it
exit() # Exit the program
class NitroGen: # Initialise the class
def __init__(self): # The initaliseaiton function
self.fileName = "Nitro Codes.txt" # Set the file name the codes are stored in
def main(self): # The main function contains the most important code
os.system('cls' if os.name == 'nt' else 'clear') # Clear the screen
if os.name == "nt": # If the system is windows
print("")
ctypes.windll.kernel32.SetConsoleTitleW("Nitro Generator and Checker - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf") # Change the
else: # Or if it is unix
print(f'\33]0;Nitro Generator and Checker - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf\a', end='', flush=True) # Update title of command prompt
print(""" █████╗ ███╗ ██╗ ██████╗ ███╗ ██╗██╗██╗ ██╗
██╔══██╗████╗ ██║██╔═══██╗████╗ ██║██║╚██╗██╔╝
███████║██╔██╗ ██║██║ ██║██╔██╗ ██║██║ ╚███╔╝
██╔══██║██║╚██╗██║██║ ██║██║╚██╗██║██║ ██╔██╗
██║ ██║██║ ╚████║╚██████╔╝██║ ╚████║██║██╔╝ ██╗
╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝
""") # Print the title card
time.sleep(2) # Wait a few seconds
self.slowType("Made by: Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf", .02) # Print who developed the code
time.sleep(1) # Wait a little more
self.slowType("\nInput How Many Codes to Generate and Check: ", .02, newLine = False) # Print the first question
num = int(input('')) # Ask the user for the amount of codes
# Get the webhook url, if the user does not wish to use a webhook the message will be an empty string
self.slowType("\nDo you wish to use a discord webhook? \nIf so type it here or press enter to ignore: ", .02, newLine = False)
url = input('') # Get the awnser
webhook = url if url != "" else None # If the url is empty make it be None insted
# print() # Print a newline for looks
valid = [] # Keep track of valid codes
invalid = 0 # Keep track of how many invalid codes was detected
for i in range(num): # Loop over the amount of codes to check
try: # Catch any errors that may happen
code = "".join(random.choices( # Generate the id for the gift
string.ascii_uppercase + string.digits + string.ascii_lowercase,
k = 16
))
url = f"https://discord.gift/{code}" # Generate the url
result = self.quickChecker(url, webhook) # Check the codes
if result: # If the code was valid
valid.append(url) # Add that code to the list of found codes
else: # If the code was not valid
invalid += 1 # Increase the invalid counter by one
except Exception as e: # If the request fails
print(f" Error | {url} ") # Tell the user an error occurred
if os.name == "nt": # If the system is windows
ctypes.windll.kernel32.SetConsoleTitleW(f"Nitro Generator and Checker - {len(valid)} Valid | {invalid} Invalid - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf") # Change the title
print("")
else: # If it is a unix system
print(f'\33]0;Nitro Generator and Checker - {len(valid)} Valid | {invalid} Invalid - Made by Social404 | Join Our Discord Server: \n https://discord.gg/kE9vk9Zeuf\a', end='', flush=True) # Change the title
print(f"""
Results:
Valid: {len(valid)}
Invalid: {invalid}
Valid Codes: {', '.join(valid )}""") # Give a report of the results of the check
input("\nThe end! Press Enter 5 times to close the program.") # Tell the user the program finished
[input(i) for i in range(4,0,-1)] # Wait for 4 enter presses
def slowType(self, text, speed, newLine = True): # Function used to print text a little more fancier
for i in text: # Loop over the message
print(i, end = "", flush = True) # Print the one charecter, flush is used to force python to print the char
time.sleep(speed) # Sleep a little before the next one
if newLine: # Check if the newLine argument is set to True
print() # Print a final newline to make it act more like a normal print statement
def generator(self, amount): # Function used to generate and store nitro codes in a seperate file
with open(self.fileName, "w", encoding="utf-8") as file: # Load up the file in write mode
print("Wait, Generating for you") # Let the user know the code is generating the codes
start = time.time() # Note the initaliseation time
for i in range(amount): # Loop the amount of codes to generate
code = "".join(random.choices(
string.ascii_uppercase + string.digits + string.ascii_lowercase,
k = 16
)) # Generate the code id
file.write(f"https://discord.gift/{code}\n") # Write the code
# Tell the user its done generating and how long tome it took
print(f"Genned {amount} codes | Time taken: {round(time.time() - start, 5)}s\n") #
def fileChecker(self, notify = None): # Function used to check nitro codes from a file
valid = [] # A list of the valid codes
invalid = 0 # The amount of invalid codes detected
with open(self.fileName, "r", encoding="utf-8") as file: # Open the file containing the nitro codes
for line in file.readlines(): # Loop over each line in the file
nitro = line.strip("\n") # Remove the newline at the end of the nitro code
# Create the requests url for later use
url = f"https://discordapp.com/api/v6/entitlements/gift-codes/{nitro}?with_application=false&with_subscription_plan=true"
response = requests.get(url) # Get the responce from the url
if response.status_code == 200: # If the responce went through
print(f" Valid | {nitro} ") # Notify the user the code was valid
valid.append(nitro) # Append the nitro code the the list of valid codes
if notify is not None: # If a webhook has been added
DiscordWebhook( # Send the message to discord letting the user know there has been a valid nitro code
url = notify,
content = f"Valid Nito Code detected! @everyone \n{nitro}"
).execute()
else: # If there has not been a discord webhook setup just stop the code
break # Stop the loop since a valid code was found
else: # If the responce got ignored or is invalid ( such as a 404 or 405 )
print(f" Invalid | {nitro} ") # Tell the user it tested a code and it was invalid
invalid += 1 # Increase the invalid counter by one
return {"valid" : valid, "invalid" : invalid} # Return a report of the results
def quickChecker(self, nitro, notify = None): # Used to check a single code at a time
# Generate the request url
url = f"https://discordapp.com/api/v6/entitlements/gift-codes/{nitro}?with_application=false&with_subscription_plan=true"
response = requests.get(url) # Get the response from discord
if response.status_code == 200: # If the responce went through
print(f" Valid | {nitro} ", flush=True, end="" if os.name == 'nt' else "\n") # Notify the user the code was valid
with open("Nitro Codes.txt", "w") as file: # Open file to write
file.write(nitro) # Write the nitro code to the file it will automatically add a newline
if notify is not None: # If a webhook has been added
DiscordWebhook( # Send the message to discord letting the user know there has been a valid nitro code
url = notify,
content = f"Valid Nito Code detected! @everyone \n{nitro}"
).execute()
return True # Tell the main function the code was found
else: # If the responce got ignored or is invalid ( such as a 404 or 405 )
print(f" Invalid | {nitro} ", flush=True, end="" if os.name == 'nt' else "\n") # Tell the user it tested a code and it was invalid
return False # Tell the main function there was not a code found
if __name__ == '__main__':
Gen = NitroGen() # Create the nitro generator object
Gen.main() # Run the main code
|
from pathlib import Path
from params_proto.neo_hyper import Sweep
from sac_dennis_rff.config import Args, Actor, Critic, Agent
from model_free_analysis import RUN
with Sweep(RUN, Args, Actor, Critic, Agent) as sweep:
Args.dmc = True
Args.train_frames = 1_000_000
Args.env_name = 'dmc:Quadruped-run-v1'
Args.checkpoint_root = "gs://ge-data-improbable/checkpoints"
Args.save_final_replay_buffer = True
Agent.critic_tau = None
RUN.prefix = "{project}/{project}/{file_stem}/{job_name}"
with sweep.product:
Args.seed = [100, 200, 300, 400, 500]
@sweep.each
def tail(RUN, Args, Actor, Critic, Agent, *_):
RUN.prefix, RUN.job_name, _ = RUN(script_path=__file__,
job_name=f"{Args.env_name.split(":")[-1][:-3]}/{Args.seed}")
sweep.save(f"{Path(__file__).stem}.jsonl")
| from pathlib import Path
from params_proto.neo_hyper import Sweep
from sac_dennis_rff.config import Args, Actor, Critic, Agent
from model_free_analysis import RUN
with Sweep(RUN, Args, Actor, Critic, Agent) as sweep:
Args.dmc = True
Args.train_frames = 1_000_000
Args.env_name = 'dmc:Quadruped-run-v1'
Args.checkpoint_root = "gs://ge-data-improbable/checkpoints"
Args.save_final_replay_buffer = True
Agent.critic_tau = None
RUN.prefix = "{project}/{project}/{file_stem}/{job_name}"
with sweep.product:
Args.seed = [100, 200, 300, 400, 500]
@sweep.each
def tail(RUN, Args, Actor, Critic, Agent, *_):
RUN.prefix, RUN.job_name, _ = RUN(script_path=__file__,
job_name=f"{Args.env_name.split(':')[-1][:-3]}/{Args.seed}")
sweep.save(f"{Path(__file__).stem}.jsonl")
|
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Logger to use in all modules
"""
import logging
import logging.config
import logging.handlers
import os
import structlog
import decisionengine.framework.modules.logging_configDict as logconf
import decisionengine.framework.modules.QueueLogger as QueueLogger
MB = 1000000
delogger = structlog.getLogger(logconf.LOGGERNAME)
delogger = delogger.bind(module=__name__.split(".")[-1], channel=logconf.DELOGGER_CHANNEL_NAME)
queue_logger = QueueLogger.QueueLogger()
def configure_logging(
log_level="DEBUG",
file_rotate_by="size",
rotation_time_unit="D",
rotation_interval=1,
max_backup_count=6,
max_file_size=200 * MB,
log_file_name="/tmp/decision_engine_logs/decisionengine.log",
start_q_logger="True",
):
"""
:type log_level: :obj:`str`
:arg log_level: log level
:type file_rotate_by: :obj: `str`
:arg file_rotate_by: files rotation by size or by time
:type rotation_time_unit: :obj:`str`
:arg rotation_time_unit: unit of time for file rotation
:type rotation_interval: :obj:`int`
:arg rotation_interval: time in rotation_time_units between file rotations
:type log_file_name: :obj:`str`
:arg log_file_name: log file name
:type max_file_size: :obj:`int`
:arg max_file_size: maximal size of log file. If reached save and start new log.
:type max_backup_count: :obj:`int`
:arg max_backup_count: start rotaion after this number is reached
:rtype: None
"""
dirname = os.path.dirname(log_file_name)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
delogger.setLevel(getattr(logging, log_level.upper()))
if delogger.handlers:
delogger.debug("Reusing existing logging handlers")
return None
# configure handlers
handlers_list = []
if file_rotate_by == "size":
for files in logconf.de_outfile_info:
handler = logging.handlers.RotatingFileHandler(
filename=f"{log_file_name}" + files[0], maxBytes=max_file_size, backupCount=max_backup_count
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
elif file_rotate_by == "time":
for files in logconf.de_outfile_info:
handler = logging.handlers.TimedRotatingFileHandler(
filename=f"{log_file_name}" + files[0],
when=rotation_time_unit,
interval=rotation_interval,
backupCount=max_backup_count,
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
else:
raise ValueError(f"Incorrect 'file_rotate_by':'{file_rotate_by}:'")
structlog_handlers_list = [handlers_list.pop(i) for i in logconf.structlog_file_index]
# setup standard file handlers
for h in handlers_list:
delogger.addHandler(h)
# setup the queue logger
if start_q_logger == "True":
queue_logger.setup_queue_logging(delogger, structlog_handlers_list)
queue_logger.start()
delogger.debug("de logging setup complete")
def get_logger():
"""
get default logger - "decisionengine"
:rtype: :class:`logging.Logger` - rotating file logger
"""
return delogger
def get_queue_logger():
"""
get QueueLogger which owns the logging queues and listeners
:rtype: :class:`decisionengine.framework.modules.QueueLogger``
"""
return queue_logger
def stop_queue_logger():
queue_logger.stop()
if __name__ == "__main__":
configure_logging(
"ERROR",
"size",
"D",
1,
max_backup_count=5,
max_file_size=100000,
log_file_name=f"{os.environ.get("HOME")}/de_log/decision_engine_log0",
)
delogger.error("THIS IS ERROR")
delogger.info("THIS IS INFO")
delogger.debug("THIS IS DEBUG")
| # SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Logger to use in all modules
"""
import logging
import logging.config
import logging.handlers
import os
import structlog
import decisionengine.framework.modules.logging_configDict as logconf
import decisionengine.framework.modules.QueueLogger as QueueLogger
MB = 1000000
delogger = structlog.getLogger(logconf.LOGGERNAME)
delogger = delogger.bind(module=__name__.split(".")[-1], channel=logconf.DELOGGER_CHANNEL_NAME)
queue_logger = QueueLogger.QueueLogger()
def configure_logging(
log_level="DEBUG",
file_rotate_by="size",
rotation_time_unit="D",
rotation_interval=1,
max_backup_count=6,
max_file_size=200 * MB,
log_file_name="/tmp/decision_engine_logs/decisionengine.log",
start_q_logger="True",
):
"""
:type log_level: :obj:`str`
:arg log_level: log level
:type file_rotate_by: :obj: `str`
:arg file_rotate_by: files rotation by size or by time
:type rotation_time_unit: :obj:`str`
:arg rotation_time_unit: unit of time for file rotation
:type rotation_interval: :obj:`int`
:arg rotation_interval: time in rotation_time_units between file rotations
:type log_file_name: :obj:`str`
:arg log_file_name: log file name
:type max_file_size: :obj:`int`
:arg max_file_size: maximal size of log file. If reached save and start new log.
:type max_backup_count: :obj:`int`
:arg max_backup_count: start rotaion after this number is reached
:rtype: None
"""
dirname = os.path.dirname(log_file_name)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
delogger.setLevel(getattr(logging, log_level.upper()))
if delogger.handlers:
delogger.debug("Reusing existing logging handlers")
return None
# configure handlers
handlers_list = []
if file_rotate_by == "size":
for files in logconf.de_outfile_info:
handler = logging.handlers.RotatingFileHandler(
filename=f"{log_file_name}" + files[0], maxBytes=max_file_size, backupCount=max_backup_count
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
elif file_rotate_by == "time":
for files in logconf.de_outfile_info:
handler = logging.handlers.TimedRotatingFileHandler(
filename=f"{log_file_name}" + files[0],
when=rotation_time_unit,
interval=rotation_interval,
backupCount=max_backup_count,
)
handler.setLevel(files[1])
handler.setFormatter(logging.Formatter(files[2]))
handlers_list.append(handler)
else:
raise ValueError(f"Incorrect 'file_rotate_by':'{file_rotate_by}:'")
structlog_handlers_list = [handlers_list.pop(i) for i in logconf.structlog_file_index]
# setup standard file handlers
for h in handlers_list:
delogger.addHandler(h)
# setup the queue logger
if start_q_logger == "True":
queue_logger.setup_queue_logging(delogger, structlog_handlers_list)
queue_logger.start()
delogger.debug("de logging setup complete")
def get_logger():
"""
get default logger - "decisionengine"
:rtype: :class:`logging.Logger` - rotating file logger
"""
return delogger
def get_queue_logger():
"""
get QueueLogger which owns the logging queues and listeners
:rtype: :class:`decisionengine.framework.modules.QueueLogger``
"""
return queue_logger
def stop_queue_logger():
queue_logger.stop()
if __name__ == "__main__":
configure_logging(
"ERROR",
"size",
"D",
1,
max_backup_count=5,
max_file_size=100000,
log_file_name=f"{os.environ.get('HOME')}/de_log/decision_engine_log0",
)
delogger.error("THIS IS ERROR")
delogger.info("THIS IS INFO")
delogger.debug("THIS IS DEBUG")
|
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import colorsys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from measurements.name_prompt import NamePrompt
sys.path.insert(1, os.path.realpath(os.path.join(sys.path[0], os.pardir, os.pardir)))
from measurements.name_index import NameIndex, NameItem
from measurements.crawler import Crawler
from frequency_response import FrequencyResponse
DIR_PATH = os.path.abspath(os.path.join(__file__, os.pardir))
class ReferenceAudioAnalyzerCrawler(Crawler):
pro_report_regex = re.compile(r'^pro report$', re.I)
performed_on_stand_regex = re.compile(r'^Measurements were performed on the stands?:$')
def __init__(self, driver=None):
if driver is None:
opts = Options()
opts.add_argument('--headless')
driver = webdriver.Chrome(os.path.abspath(os.path.join(DIR_PATH, '..', 'chromedriver')), options=opts)
super().__init__(driver=driver)
@staticmethod
def read_name_index():
return NameIndex.read_tsv(os.path.join(DIR_PATH, 'name_index.tsv'))
def write_name_index(self):
self.name_index.write_tsv(os.path.join(DIR_PATH, 'name_index.tsv'))
@staticmethod
def get_existing():
suffix_regex = re.compile(r' \(.*\)$')
name_index = NameIndex.read_files(os.path.join(DIR_PATH, 'data', '**', '*.csv'))
# Add models without mod suffixes which don't exist
for i, row in name_index.df.iterrows():
model = re.sub(suffix_regex, '', row.true_name)
if model != row.true_name:
name_index.df = name_index.df.append(pd.DataFrame(
[[row.false_name, model, row.form]],
columns=name_index.df.columns
))
name_index.df.drop_duplicates()
return name_index
def get_urls(self):
if self.driver is None:
raise TypeError('self.driver cannot be None')
document = self.get_beautiful_soup('https://reference-audio-analyzer.pro/en/catalog-reports.php?sp_1=1&tp=1')
anchors = document.find(name='article', attrs={'class': 'ar3'}).find_all('a')
urls = {}
for anchor in anchors:
if not anchor.has_attr('href'):
continue
urls[anchor.text] = f'https://reference-audio-analyzer.pro{anchor['href']}'
return urls
@staticmethod
def find_curve(im, inspection, min_hue, max_hue, min_saturation, max_saturation, a_max, a_res):
amplitude = []
# Iterate each column
for x in range(im.size[0]):
pxs = [] # Graph pixels
# Iterate each row (pixel in column)
for y in range(im.size[1]):
# Convert read RGB pixel values and convert to HSV
h, s, v = colorsys.rgb_to_hsv(*[v / 255.0 for v in im.getpixel((x, y))][:3])
# Graph pixels are colored
if min_saturation < s < max_saturation and min_hue / 360 < h < max_hue / 360:
pxs.append(float(y))
else:
p = im.getpixel((x, y))
inspection[x, y] = (int(0.3 * p[0]), int(255 * 0.7 + 0.3 * p[1]), int(0 + 0.3 * p[2]))
if not pxs:
# No graph pixels found on this column
amplitude.append(None)
else:
# Mean of recorded pixels
v = np.mean(pxs)
# Convert to dB value
v = a_max - v * a_res
amplitude.append(v)
return amplitude, im, inspection
@staticmethod
def parse_image(im, model):
"""Parses graph image downloaded from innerfidelity.com"""
# Crop by left and right edges
box = (69, 31, 550, 290)
im = im.crop(box)
px_a_max = 0
px_a_min = im.size[1]
# im.show()
# X axis
f_min = 20
f_max = 20000
f_step = (f_max / f_min) ** (1 / im.size[0])
f = [f_min]
for _ in range(1, im.size[0]):
f.append(f[-1] * f_step)
# Y axis
a_max = 150
a_min = 66
a_res = (a_max - a_min) / (px_a_min - px_a_max)
# Try blue curve
_im = im.copy()
inspection = _im.load()
amplitude, _im, _inspection = ReferenceAudioAnalyzerCrawler.find_curve(
_im, inspection, 203, 206, 0.8, 1.0, a_max, a_res
)
if len([x for x in amplitude if x is None]) >= 0.5 * len(amplitude):
# More than half of the pixels were discarded, try green curve
_im = im.copy()
inspection = _im.load()
amplitude, _im, _inspection = ReferenceAudioAnalyzerCrawler.find_curve(
_im, inspection, 119, 121, 0.8, 1.0, a_max, a_res
)
# Inspection image
draw = ImageDraw.Draw(_im)
x0 = np.log(30 / f_min) / np.log(f_step)
x1 = np.log(10000 / f_min) / np.log(f_step)
y_0 = px_a_max + 12 / a_res
y_1 = px_a_min - 12 / a_res
draw.rectangle(((x0, y_0), (x1, y_1)), outline='magenta')
draw.rectangle(((x0 + 1, y_0 + 1), (x1 - 1, y_1 - 1)), outline='magenta')
# Create frequency response
fr = FrequencyResponse(model, f, amplitude)
fr.interpolate()
if len(fr.frequency) < 2:
im.show()
raise ValueError(f'Failed to parse image for {fr.name}')
fr.smoothen_fractional_octave(window_size=1/3, treble_window_size=1/3)
fr.raw = fr.smoothed.copy()
fr.smoothed = np.array([])
fr.center()
return fr, _im
def process(self, item, url):
if item.form == 'ignore':
return
image_dir = os.path.join(DIR_PATH, 'images')
inspection_dir = os.path.join(DIR_PATH, 'inspection')
data_dir = os.path.join(DIR_PATH, 'data')
os.makedirs(image_dir, exist_ok=True)
os.makedirs(os.path.join(inspection_dir, 'parse'), exist_ok=True)
os.makedirs(os.path.join(inspection_dir, 'fr'), exist_ok=True)
# Download and parse image
self.download_images(url, item, data_dir, image_dir, inspection_dir, callback=self.process_image)
def download_images(self, url, item, data_dir, image_dir, inspection_dir, callback):
document = self.get_beautiful_soup(url) # Reports page
for label in document.find_all(name='span', text=self.pro_report_regex):
parent = label.parent.parent.parent
anchor = parent.find_all('a')[1]
report_url = f'https://reference-audio-analyzer.pro{anchor['href']}'
suffix = anchor.text.lower().strip()
name = item.true_name
if suffix != item.false_name.lower() and suffix != 'default':
name += f' ({suffix})'
# The suffixes above are read automatically from the reports compilation page.
# However these might not be the names that should exist in AutoEq.
mods = self.name_index.find(false_name=name)
if mods:
# Find an item in name index which has the given name with automatic
# suffixes as false name and replace the name with it's true name.
true_name = mods.items[0].true_name
image_path, rig = self.download_image(report_url, image_dir, item.false_name, true_name, item.form)
if image_path:
callback(image_path, rig, true_name, item.form, data_dir, inspection_dir)
else:
# Not in the name index, prompt user
manufacturer, manufacturer_match = self.manufacturers.find(name)
if manufacturer:
model = re.sub(re.escape(manufacturer_match), '', name, flags=re.IGNORECASE).strip()
name_proposals = self.get_name_proposals(name)
similar_names = self.get_name_proposals(name, n=6, normalize_digits=True, threshold=0)
similar_names = [item.true_name for item in similar_names.items]
else:
model = name
name_proposals = None
similar_names = None
prompt = NamePrompt(
model,
self.prompt_mod_callback(name, report_url, data_dir, image_dir, inspection_dir, callback),
manufacturer=manufacturer,
name_proposals=name_proposals,
search_callback=self.search,
false_name=item.false_name,
similar_names=similar_names
).widget
if len(self.prompts.children) > 0:
if type(self.prompts.children) == tuple:
self.prompts.children = [x for x in self.prompts.children] + [prompt]
else:
self.prompts.children.append(prompt)
else:
self.prompts.children = [prompt]
else:
true_name = name
image_path, rig = self.download_image(report_url, image_dir, item.false_name, true_name, item.form)
if image_path:
callback(image_path, rig, true_name, item.form, data_dir, inspection_dir)
def prompt_mod_callback(self, false_name, report_url, data_dir, image_dir, inspection_dir, callback):
def fn(true_name, form):
self.name_index.add(NameItem(false_name, true_name, form))
self.write_name_index()
image_path, rig = self.download_image(report_url, image_dir, false_name, true_name, form)
if image_path:
callback(image_path, rig, true_name, form, data_dir, inspection_dir)
return fn
def download_image(self, report_url, image_dir, false_name, true_name, form):
document = self.get_beautiful_soup(report_url) # Sets the driver also
el = document.find(name='li', text=self.performed_on_stand_regex)
try:
rig = el.parent.find(name='ul').find(name='a').text
except AttributeError as err:
rig = 'HDM-X' if form == 'onear' else 'SIEC'
print(f'Measurement rig could not be read for "{false_name}", guessing {rig}')
try:
graph = self.driver.find_element_by_id('response9').find_element_by_tag_name('div') # FR Graph
except Exception:
print(f'No graph for {false_name}')
return None, None
# Background image
report_url = graph.value_of_css_property('background-image').replace('url("', '').replace('")', '')
file_path = self.download(report_url, true_name, image_dir)
return file_path, rig
def process_image(self, image_path, rig, name, form, data_dir, inspection_dir):
im = Image.open(image_path)
if im is None:
print(f'Could not open image in "{image_path}"')
return
mod = self.name_index.find(true_name=name)
# Get the form from name index if an entry already exists
form = mod.items[0].form if mod else form
fr, inspection = ReferenceAudioAnalyzerCrawler.parse_image(im, name)
out_dir = os.path.join(data_dir, form, rig, name)
os.makedirs(out_dir, exist_ok=True)
# Save inspection images
inspection.save(os.path.join(inspection_dir, 'parse', f'{name}.png'))
fig, ax = fr.plot_graph(show=False, file_path=os.path.join(inspection_dir, 'fr', f'{name}.png'))
plt.close(fig)
# Write to CSV
fr.write_to_csv(os.path.join(out_dir, f'{name}.csv'))
print(f'Wrote CSV to "{os.path.join(out_dir, f'{name}.csv')}"')
def main():
crawler = ReferenceAudioAnalyzerCrawler()
crawler.process_new(prompt=False)
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import colorsys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from measurements.name_prompt import NamePrompt
sys.path.insert(1, os.path.realpath(os.path.join(sys.path[0], os.pardir, os.pardir)))
from measurements.name_index import NameIndex, NameItem
from measurements.crawler import Crawler
from frequency_response import FrequencyResponse
DIR_PATH = os.path.abspath(os.path.join(__file__, os.pardir))
class ReferenceAudioAnalyzerCrawler(Crawler):
pro_report_regex = re.compile(r'^pro report$', re.I)
performed_on_stand_regex = re.compile(r'^Measurements were performed on the stands?:$')
def __init__(self, driver=None):
if driver is None:
opts = Options()
opts.add_argument('--headless')
driver = webdriver.Chrome(os.path.abspath(os.path.join(DIR_PATH, '..', 'chromedriver')), options=opts)
super().__init__(driver=driver)
@staticmethod
def read_name_index():
return NameIndex.read_tsv(os.path.join(DIR_PATH, 'name_index.tsv'))
def write_name_index(self):
self.name_index.write_tsv(os.path.join(DIR_PATH, 'name_index.tsv'))
@staticmethod
def get_existing():
suffix_regex = re.compile(r' \(.*\)$')
name_index = NameIndex.read_files(os.path.join(DIR_PATH, 'data', '**', '*.csv'))
# Add models without mod suffixes which don't exist
for i, row in name_index.df.iterrows():
model = re.sub(suffix_regex, '', row.true_name)
if model != row.true_name:
name_index.df = name_index.df.append(pd.DataFrame(
[[row.false_name, model, row.form]],
columns=name_index.df.columns
))
name_index.df.drop_duplicates()
return name_index
def get_urls(self):
if self.driver is None:
raise TypeError('self.driver cannot be None')
document = self.get_beautiful_soup('https://reference-audio-analyzer.pro/en/catalog-reports.php?sp_1=1&tp=1')
anchors = document.find(name='article', attrs={'class': 'ar3'}).find_all('a')
urls = {}
for anchor in anchors:
if not anchor.has_attr('href'):
continue
urls[anchor.text] = f'https://reference-audio-analyzer.pro{anchor["href"]}'
return urls
@staticmethod
def find_curve(im, inspection, min_hue, max_hue, min_saturation, max_saturation, a_max, a_res):
amplitude = []
# Iterate each column
for x in range(im.size[0]):
pxs = [] # Graph pixels
# Iterate each row (pixel in column)
for y in range(im.size[1]):
# Convert read RGB pixel values and convert to HSV
h, s, v = colorsys.rgb_to_hsv(*[v / 255.0 for v in im.getpixel((x, y))][:3])
# Graph pixels are colored
if min_saturation < s < max_saturation and min_hue / 360 < h < max_hue / 360:
pxs.append(float(y))
else:
p = im.getpixel((x, y))
inspection[x, y] = (int(0.3 * p[0]), int(255 * 0.7 + 0.3 * p[1]), int(0 + 0.3 * p[2]))
if not pxs:
# No graph pixels found on this column
amplitude.append(None)
else:
# Mean of recorded pixels
v = np.mean(pxs)
# Convert to dB value
v = a_max - v * a_res
amplitude.append(v)
return amplitude, im, inspection
@staticmethod
def parse_image(im, model):
"""Parses graph image downloaded from innerfidelity.com"""
# Crop by left and right edges
box = (69, 31, 550, 290)
im = im.crop(box)
px_a_max = 0
px_a_min = im.size[1]
# im.show()
# X axis
f_min = 20
f_max = 20000
f_step = (f_max / f_min) ** (1 / im.size[0])
f = [f_min]
for _ in range(1, im.size[0]):
f.append(f[-1] * f_step)
# Y axis
a_max = 150
a_min = 66
a_res = (a_max - a_min) / (px_a_min - px_a_max)
# Try blue curve
_im = im.copy()
inspection = _im.load()
amplitude, _im, _inspection = ReferenceAudioAnalyzerCrawler.find_curve(
_im, inspection, 203, 206, 0.8, 1.0, a_max, a_res
)
if len([x for x in amplitude if x is None]) >= 0.5 * len(amplitude):
# More than half of the pixels were discarded, try green curve
_im = im.copy()
inspection = _im.load()
amplitude, _im, _inspection = ReferenceAudioAnalyzerCrawler.find_curve(
_im, inspection, 119, 121, 0.8, 1.0, a_max, a_res
)
# Inspection image
draw = ImageDraw.Draw(_im)
x0 = np.log(30 / f_min) / np.log(f_step)
x1 = np.log(10000 / f_min) / np.log(f_step)
y_0 = px_a_max + 12 / a_res
y_1 = px_a_min - 12 / a_res
draw.rectangle(((x0, y_0), (x1, y_1)), outline='magenta')
draw.rectangle(((x0 + 1, y_0 + 1), (x1 - 1, y_1 - 1)), outline='magenta')
# Create frequency response
fr = FrequencyResponse(model, f, amplitude)
fr.interpolate()
if len(fr.frequency) < 2:
im.show()
raise ValueError(f'Failed to parse image for {fr.name}')
fr.smoothen_fractional_octave(window_size=1/3, treble_window_size=1/3)
fr.raw = fr.smoothed.copy()
fr.smoothed = np.array([])
fr.center()
return fr, _im
def process(self, item, url):
if item.form == 'ignore':
return
image_dir = os.path.join(DIR_PATH, 'images')
inspection_dir = os.path.join(DIR_PATH, 'inspection')
data_dir = os.path.join(DIR_PATH, 'data')
os.makedirs(image_dir, exist_ok=True)
os.makedirs(os.path.join(inspection_dir, 'parse'), exist_ok=True)
os.makedirs(os.path.join(inspection_dir, 'fr'), exist_ok=True)
# Download and parse image
self.download_images(url, item, data_dir, image_dir, inspection_dir, callback=self.process_image)
def download_images(self, url, item, data_dir, image_dir, inspection_dir, callback):
document = self.get_beautiful_soup(url) # Reports page
for label in document.find_all(name='span', text=self.pro_report_regex):
parent = label.parent.parent.parent
anchor = parent.find_all('a')[1]
report_url = f'https://reference-audio-analyzer.pro{anchor["href"]}'
suffix = anchor.text.lower().strip()
name = item.true_name
if suffix != item.false_name.lower() and suffix != 'default':
name += f' ({suffix})'
# The suffixes above are read automatically from the reports compilation page.
# However these might not be the names that should exist in AutoEq.
mods = self.name_index.find(false_name=name)
if mods:
# Find an item in name index which has the given name with automatic
# suffixes as false name and replace the name with it's true name.
true_name = mods.items[0].true_name
image_path, rig = self.download_image(report_url, image_dir, item.false_name, true_name, item.form)
if image_path:
callback(image_path, rig, true_name, item.form, data_dir, inspection_dir)
else:
# Not in the name index, prompt user
manufacturer, manufacturer_match = self.manufacturers.find(name)
if manufacturer:
model = re.sub(re.escape(manufacturer_match), '', name, flags=re.IGNORECASE).strip()
name_proposals = self.get_name_proposals(name)
similar_names = self.get_name_proposals(name, n=6, normalize_digits=True, threshold=0)
similar_names = [item.true_name for item in similar_names.items]
else:
model = name
name_proposals = None
similar_names = None
prompt = NamePrompt(
model,
self.prompt_mod_callback(name, report_url, data_dir, image_dir, inspection_dir, callback),
manufacturer=manufacturer,
name_proposals=name_proposals,
search_callback=self.search,
false_name=item.false_name,
similar_names=similar_names
).widget
if len(self.prompts.children) > 0:
if type(self.prompts.children) == tuple:
self.prompts.children = [x for x in self.prompts.children] + [prompt]
else:
self.prompts.children.append(prompt)
else:
self.prompts.children = [prompt]
else:
true_name = name
image_path, rig = self.download_image(report_url, image_dir, item.false_name, true_name, item.form)
if image_path:
callback(image_path, rig, true_name, item.form, data_dir, inspection_dir)
def prompt_mod_callback(self, false_name, report_url, data_dir, image_dir, inspection_dir, callback):
def fn(true_name, form):
self.name_index.add(NameItem(false_name, true_name, form))
self.write_name_index()
image_path, rig = self.download_image(report_url, image_dir, false_name, true_name, form)
if image_path:
callback(image_path, rig, true_name, form, data_dir, inspection_dir)
return fn
def download_image(self, report_url, image_dir, false_name, true_name, form):
document = self.get_beautiful_soup(report_url) # Sets the driver also
el = document.find(name='li', text=self.performed_on_stand_regex)
try:
rig = el.parent.find(name='ul').find(name='a').text
except AttributeError as err:
rig = 'HDM-X' if form == 'onear' else 'SIEC'
print(f'Measurement rig could not be read for "{false_name}", guessing {rig}')
try:
graph = self.driver.find_element_by_id('response9').find_element_by_tag_name('div') # FR Graph
except Exception:
print(f'No graph for {false_name}')
return None, None
# Background image
report_url = graph.value_of_css_property('background-image').replace('url("', '').replace('")', '')
file_path = self.download(report_url, true_name, image_dir)
return file_path, rig
def process_image(self, image_path, rig, name, form, data_dir, inspection_dir):
im = Image.open(image_path)
if im is None:
print(f'Could not open image in "{image_path}"')
return
mod = self.name_index.find(true_name=name)
# Get the form from name index if an entry already exists
form = mod.items[0].form if mod else form
fr, inspection = ReferenceAudioAnalyzerCrawler.parse_image(im, name)
out_dir = os.path.join(data_dir, form, rig, name)
os.makedirs(out_dir, exist_ok=True)
# Save inspection images
inspection.save(os.path.join(inspection_dir, 'parse', f'{name}.png'))
fig, ax = fr.plot_graph(show=False, file_path=os.path.join(inspection_dir, 'fr', f'{name}.png'))
plt.close(fig)
# Write to CSV
fr.write_to_csv(os.path.join(out_dir, f'{name}.csv'))
print(f'Wrote CSV to "{os.path.join(out_dir, f"{name}.csv")}"')
def main():
crawler = ReferenceAudioAnalyzerCrawler()
crawler.process_new(prompt=False)
if __name__ == '__main__':
main()
|
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""normalization"""
import itertools
import numbers
from mindspore.ops import operations as P
from mindspore.ops import functional as F
from mindspore.ops.operations import _inner_ops as inner
from mindspore.common.parameter import Parameter
from mindspore.common.initializer import initializer, Initializer
from mindspore.common.tensor import Tensor
from mindspore.common._decorator import deprecated
from mindspore.ops.primitive import constexpr
import mindspore.context as context
from mindspore._checkparam import Rel
from mindspore._checkparam import Validator as validator
from mindspore._extends import cell_attr_register
from mindspore.communication.management import get_group_size, get_rank
from mindspore.communication import management
from mindspore.common import dtype as mstype
from mindspore.parallel._utils import _is_in_auto_parallel_mode
from ..cell import Cell
__all__ = ['BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'LayerNorm', 'GroupNorm',
'GlobalBatchNorm', 'SyncBatchNorm', 'InstanceNorm2d']
SYNC_BN_GROUP_NAME = ""
class _BatchNorm(Cell):
"""Batch Normalization base class."""
@cell_attr_register
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
device_num_each_group=1,
process_groups=0,
input_dims='2d',
data_format='NCHW'):
"""Initialize _BatchNorm."""
super(_BatchNorm, self).__init__()
validator.check_value_type('num_features', num_features, [int], self.cls_name)
if num_features < 1:
raise ValueError(f"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.")
if momentum < 0 or momentum > 1:
raise ValueError(f"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], "
f"but got {momentum}.")
self.input_dims = input_dims
self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.cls_name)
if context.get_context("device_target") != "GPU" and self.format == "NHWC":
raise ValueError(f"For '{self.cls_name}', the 'NHWC' format only support in GPU target, but got device "
f"target {context.get_context("device_target")}.")
self.use_batch_statistics = use_batch_statistics
if self.use_batch_statistics is not None and not isinstance(self.use_batch_statistics, bool):
raise ValueError(f"For '{self.cls_name}', the 'use_batch_statistics' should be a boolean value or None,"
f" but got {use_batch_statistics}.")
self.num_features = num_features
self.eps = eps
self.moving_mean = Parameter(initializer(
moving_mean_init, num_features), name="mean", requires_grad=False)
self.moving_variance = Parameter(initializer(
moving_var_init, num_features), name="variance", requires_grad=False)
self.gamma = Parameter(initializer(
gamma_init, num_features), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_features), name="beta", requires_grad=affine)
self.group_device_num = validator.check_positive_int(device_num_each_group, "device_num_each_group",
self.cls_name)
self.process_groups = process_groups
self.is_global = False
self.parallel_mode = context.get_auto_parallel_context("parallel_mode")
global SYNC_BN_GROUP_NAME
# for GlobalBatchNorm
if self.group_device_num != 1:
self.rank_id = get_rank()
self.rank_size = get_group_size()
self.device_list = [i for i in range(0, self.rank_size)]
self.rank_list = self.list_group(self.device_list, self.group_device_num)
self.rank_list_idx = len(self.rank_list)
self._create_global_groups()
# for SyncBatchNorm
if self.process_groups != 0:
self.rank_id = get_rank()
self.rank_size = get_group_size()
if self.process_groups is not None:
validator.check_isinstance("process_groups", self.process_groups, list)
self._check_rank_ids(self.process_groups, self.rank_size)
self._create_sync_groups()
elif self.rank_size > 1:
self.is_global = True
self.group_device_num = self.rank_size
self.device_list = [i for i in range(0, self.rank_size)]
if context.get_context("device_target") == "Ascend":
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group0"
management.create_group(SYNC_BN_GROUP_NAME, self.device_list)
elif context.get_context("device_target") == "GPU":
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "nccl_world_group"
self.shape = P.Shape()
self.reduce_mean = P.ReduceMean(keep_dims=True)
self.square = P.Square()
self.sqrt = P.Sqrt()
self.cast = P.Cast()
self.dtype = P.DType()
self.reshape = P.Reshape()
self._target = context.get_context("device_target")
self.is_graph_mode = context.get_context("mode") == context.GRAPH_MODE
self.momentum = 1.0 - momentum
if context.get_context("enable_ge"):
self.is_ge_backend = True
else:
self.is_ge_backend = False
self.bn_train = P.BatchNorm(is_training=True,
epsilon=self.eps,
momentum=self.momentum,
data_format=self.format)
if self.is_global:
self.bn_train = inner.SyncBatchNorm(epsilon=self.eps,
momentum=self.momentum,
group=SYNC_BN_GROUP_NAME,
device_num=self.group_device_num)
self.bn_infer = P.BatchNorm(is_training=False, epsilon=self.eps, data_format=self.format)
if _is_in_auto_parallel_mode():
data_parallel_strategy = ((1,), (1,))
data_parallel_strategy_one = ((1,), ())
else:
data_parallel_strategy = None
data_parallel_strategy_one = None
self.sub_mean = P.Sub().shard(data_parallel_strategy)
self.sub_var = P.Sub().shard(data_parallel_strategy)
self.mul_mean = P.Mul().shard(data_parallel_strategy_one)
self.mul_var = P.Mul().shard(data_parallel_strategy_one)
self.assign_sub_mean = P.AssignSub().shard(data_parallel_strategy)
self.assign_sub_var = P.AssignSub().shard(data_parallel_strategy)
def _check_data_dim(self, x):
raise NotImplementedError
def list_group(self, world_rank, group_size):
""" Check whether world_rank and group_size are valid. """
if group_size > get_group_size():
raise ValueError(f"For '{self.cls_name}', the 'device_num_each_group' cannot be greater than "
f"local rank size, but got 'device_num_each_group': {group_size}, "
f"local rank size: {get_group_size()}.")
if len(world_rank) % group_size != 0:
raise ValueError(f"For '{self.cls_name}', the dimension of device_list should be divisible by "
f"'device_num_each_group', but got the length of device_list: {len(world_rank)}, "
f"'device_num_each_group': {group_size}.")
world_rank_list = zip(*(iter(world_rank),) * group_size)
group_list = [list(i) for i in world_rank_list]
return group_list
def _check_rank_ids(self, process_groups, rank_size):
seen = set()
for rid in itertools.chain(*process_groups):
validator.check_int_range(rid, 0, rank_size, Rel.INC_LEFT, "rank id in process_groups", self.cls_name)
if rid in seen:
raise ValueError(f"For '{self.cls_name}', rank id in 'process_groups' should not be duplicated, "
f"but got {process_groups}.")
seen.add(rid)
def _create_global_groups(self):
for i in range(self.rank_list_idx):
if self.rank_id in self.rank_list[i]:
self.is_global = True
global SYNC_BN_GROUP_NAME
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group" + str(i)
management.create_group(SYNC_BN_GROUP_NAME, self.rank_list[i])
def _create_sync_groups(self):
for i in range(len(self.process_groups)):
validator.check_isinstance("process_groups[" + str(i) + "]", self.process_groups[i], list)
self.group_device_num = len(self.process_groups[i])
if self.rank_id in self.process_groups[i] and self.group_device_num > 1:
self.is_global = True
global SYNC_BN_GROUP_NAME
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group" + str(i)
management.create_group(SYNC_BN_GROUP_NAME, self.process_groups[i])
def construct(self, x):
_shape_check_bn(self.shape(x), self.input_dims, self.cls_name)
if self.use_batch_statistics is None:
if self.training:
return self.bn_train(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
if not self.training:
return self.bn_infer(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
if self.use_batch_statistics is True:
return self.bn_train(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
return self.bn_infer(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
def extend_repr(self):
return 'num_features={}, eps={}, momentum={}, gamma={}, beta={}, moving_mean={}, moving_variance={}'.format(
self.num_features, self.eps, self.momentum, self.gamma, self.beta, self.moving_mean, self.moving_variance)
@constexpr
def _channel_check(channel, num_channel, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if channel != num_channel:
raise ValueError(f"{msg_prefix} channel(the second dim of the input 'x') should be equal to num_channels, "
f"but got channel: {channel}, num_channels: {num_channel}.")
@constexpr
def _shape_check(in_shape, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if len(in_shape) != 4:
raise ValueError(f"{msg_prefix} in_shape must has 4 dims, but got the length of in_shape: {len(in_shape)}.")
@constexpr
def _shape_check_bn(in_shape, in_dims, prim_name=None):
"""check input dims of batch norm."""
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
dim = len(in_shape)
if in_dims == '1d' and dim != 2:
raise ValueError(f"{msg_prefix} in_shape must have 2 dims, but got {len(in_shape)}.")
if in_dims == '2d' and dim != 4:
raise ValueError(f"{msg_prefix} in_shape must have 4 dims, but got {len(in_shape)}.")
if in_dims == '3d' and dim != 5:
raise ValueError(f"{msg_prefix} in_shape must have 5 dims, but got {len(in_shape)}.")
if in_dims == 'both' and dim != 2 and dim != 4:
raise ValueError(f"{msg_prefix} in_shape must have 2 dims or 4 dims, but got {len(in_shape)}.")
@constexpr
def _shape_infer(x_shape, num_feature):
"""global Batch Normalization shape and axes infer"""
if len(x_shape) == 4:
axes = (0, 2, 3)
re_shape = (1, num_feature, 1, 1)
else:
axes = (0,)
re_shape = (1, num_feature)
return axes, re_shape
class BatchNorm1d(_BatchNorm):
r"""
Batch Normalization layer over a 2D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 2D input (a mini-batch of 1D inputs) to
reduce internal covariate shift as described in the paper
`Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It
rescales and recenters the feature using a mini-batch of data and
the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore the mode is not
recommended to be changed after net was initialized.
Args:
num_features (int): `C` from an expected input of size (N, C).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, the training process will use the mean
and variance of current batch data and track the running mean and variance, the evaluation process will use
the running mean and variance. Default: None.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out})`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm1d(num_features=4)
>>> x = Tensor(np.array([[0.7, 0.5, 0.5, 0.6],
... [0.5, 0.4, 0.6, 0.9]]).astype(np.float32))
>>> output = net(x)
>>> print(output)
[[ 0.6999965 0.4999975 0.4999975 0.59999704 ]
[ 0.4999975 0.399998 0.59999704 0.89999545 ]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None):
"""Initialize BatchNorm1d."""
super(BatchNorm1d, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
input_dims='1d')
def _check_data_dim(self, x):
if x.ndim != 2:
pass
class BatchNorm2d(_BatchNorm):
r"""
Batch Normalization layer over a 4D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with
additional channel dimension) to avoid internal covariate shift as described
in the paper `Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It
rescales and recenters the feature using a mini-batch of data and
the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore that mode can not be
changed after net was initialized.
Note that the formula for updating the moving_mean and moving_var is
.. math::
\text{moving_mean}=\text{moving_mean∗momentum}+μ_β\text{∗(1−momentum)}\\
\text{moving_var}=\text{moving_var∗momentum}+σ^2_β\text{∗(1−momentum)}
where :math:`moving_mean, moving_var` are the updated mean and variance,
:math:`μ_β, σ^2_β` are the observed value (mean and variance) of each batch of data.
Args:
num_features (int): The number of channels of the input tensor. Expected input size is (N, C, H, W),
`C` represents the number of channels
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool):
- If true, use the mean value and variance value of current batch data and track running mean
and running variance.
- If false, use the mean value and variance value of specified value, and not track statistical value.
- If None, the use_batch_statistics is automatically set to true or false according to the training
and evaluation mode. During training, the parameter is set to true, and during evaluation, the
parameter is set to false. Default: None.
data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'.
Default: 'NCHW'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If `data_format` is neither 'NHWC' not 'NCHW'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm2d(num_features=3)
>>> x = Tensor(np.ones([1, 3, 2, 2]).astype(np.float32))
>>> output = net(x)
>>> print(output)
[[[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
data_format='NCHW'):
"""Initialize BatchNorm2d."""
super(BatchNorm2d, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
input_dims='2d',
data_format=data_format)
def _check_data_dim(self, x):
if x.ndim != 4:
pass
@constexpr
def _check_3d_shape(input_shape, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if len(input_shape) != 5:
raise ValueError(f"{msg_prefix} input_shape must be 5-dimensional, but got the length of input_shape: "
f"{len(input_shape)}.")
class BatchNorm3d(Cell):
r"""
Batch Normalization layer over a 5D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with
additional channel dimension) to avoid internal covariate shift.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore that mode can not be
changed after net was initialized.
Note that the formula for updating the running_mean and running_var is
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times x_t + \text{momentum} \times \hat{x}`,
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value.
Args:
num_features (int): `C` from an expected input of size (N, C, D, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, the training process will use the mean
and variance of current batch data and track the running mean and variance, the evaluation process will use
the running mean and variance. Default: None.
data_format (str): The optional value for data format is 'NCDHW'. Default: 'NCDHW'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, D_{out},H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If `data_format` is not 'NCDHW'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm3d(num_features=3)
>>> x = Tensor(np.ones([16, 3, 10, 32, 32]).astype(np.float32))
>>> output = net(x)
>>> print(output.shape)
(16, 3, 10, 32, 32)
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
data_format='NCDHW'):
"""Initialize BatchNorm3d."""
super(BatchNorm3d, self).__init__()
self.format = validator.check_string(data_format, ['NCDHW'], 'format', self.cls_name)
self.reshape = P.Reshape()
self.bn2d = BatchNorm2d(num_features=num_features,
eps=eps,
momentum=momentum,
affine=affine,
gamma_init=gamma_init,
beta_init=beta_init,
moving_mean_init=moving_mean_init,
moving_var_init=moving_var_init,
use_batch_statistics=use_batch_statistics,
data_format="NCHW")
def construct(self, input_x):
x_shape = F.shape(input_x)
_check_3d_shape(x_shape, self.cls_name)
input_x = self.reshape(input_x, (x_shape[0], x_shape[1], x_shape[2] * x_shape[3], x_shape[4]))
bn2d_out = self.bn2d(input_x)
bn3d_out = self.reshape(bn2d_out, x_shape)
return bn3d_out
class GlobalBatchNorm(_BatchNorm):
r"""
The GlobalBatchNorm interface is deprecated, please use the :class:`mindspore.nn.SyncBatchNorm` instead.
Supported Platforms:
deprecated
"""
@deprecated("1.2", "SyncBatchNorm", True)
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
device_num_each_group=2):
"""Initialize GlobalBatchNorm."""
super(GlobalBatchNorm, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
device_num_each_group,
input_dims='both')
self.group_device_num = validator.check_positive_int(device_num_each_group, "device_num_each_group",
self.cls_name)
if self.group_device_num <= 1:
raise ValueError(f"For '{self.cls_name}', the 'device_num_each_group' must be greater than 1, "
f"but got {self.group_device_num}.")
def _check_data_dim(self, x):
if x.dim == 0:
pass
class SyncBatchNorm(_BatchNorm):
r"""
Sync Batch Normalization layer over a N-dimension input.
Sync Batch Normalization is cross device synchronized Batch Normalization. The implementation of Batch
Normalization only normalizes the data within each device. Sync Batch Normalization will normalize the input
within the group. It has been described in the paper `Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It rescales and recenters the
feature using a mini-batch of data and the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
Currently, SyncBatchNorm only supports 2D and 4D inputs.
Args:
num_features (int): `C` from an expected input of size (N, C, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, training process will use the mean and
variance of current batch data and track the running mean and variance, eval process will use the running
mean and variance. Default: None.
process_groups (list): A list to divide devices into different sync groups, containing N subtraction lists.
Each subtraction list contains int numbers identifying rank ids which need to be synchronized in the same
group. All int values must be in [0, rank_size) and different from each other. Default: None, indicating
synchronization across all devices.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `process_groups` is not a list.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If rank_id in `process_groups` is not in range [0, rank_size).
Supported Platforms:
``Ascend``
Examples:
>>> # This example should be run with multiple processes.
>>> # Please refer to the tutorial > Distributed Training on mindspore.cn.
>>> import numpy as np
>>> from mindspore.communication import init
>>> from mindspore import context
>>> from mindspore.context import ParallelMode
>>> from mindspore import Tensor
>>> from mindspore import nn
>>> from mindspore import dtype as mstype
>>>
>>> context.set_context(mode=context.GRAPH_MODE)
>>> init()
>>> context.reset_auto_parallel_context()
>>> context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL)
>>> sync_bn_op = nn.SyncBatchNorm(num_features=3, process_groups=[[0, 1], [2, 3]])
>>> x = Tensor(np.ones([1, 3, 2, 2]), mstype.float32)
>>> output = sync_bn_op(x)
>>> print(output)
[[[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
process_groups=None):
"""Initialize SyncBatchNorm."""
super(SyncBatchNorm, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
process_groups=process_groups,
input_dims='both')
def _check_data_dim(self, x):
if x.dim == 0:
pass
class LayerNorm(Cell):
r"""
Applies Layer Normalization over a mini-batch of inputs.
Layer Normalization is widely used in recurrent neural networks. It applies
normalization on a mini-batch of inputs for each single training case as described
in the paper `Layer Normalization <https://arxiv.org/pdf/1607.06450.pdf>`_. Unlike Batch
Normalization, Layer Normalization performs exactly the same computation at training and
testing time. It can be described using the following formula. It is applied across all channels
and pixel but only one batch size.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Args:
normalized_shape (Union(tuple[int], list[int])): The normalization is performed over axis
`begin_norm_axis ... R - 1`.
begin_norm_axis (int): The first normalization dimension: normalization will be performed along dimensions
`begin_norm_axis: rank(inputs)`, the value should be in [-1, rank(input)). Default: -1.
begin_params_axis (int): The first parameter(beta, gamma)dimension: scale and centering parameters
will have dimensions `begin_params_axis: rank(inputs)` and will be broadcast with
the normalized inputs accordingly, the value should be in [-1, rank(input)). Default: -1.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
epsilon (float): A value added to the denominator for numerical stability. Default: 1e-7.
Inputs:
- **x** (Tensor) - The shape of 'x' is :math:`(x_1, x_2, ..., x_R)`,
and `input_shape[begin_norm_axis:]` is equal to `normalized_shape`.
Outputs:
Tensor, the normalized and scaled offset tensor, has the same shape and data type as the `x`.
Raises:
TypeError: If `normalized_shape` is neither a list nor tuple.
TypeError: If `begin_norm_axis` or `begin_params_axis` is not an int.
TypeError: If `epsilon` is not a float.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.ones([20, 5, 10, 10]), mindspore.float32)
>>> shape1 = x.shape[1:]
>>> m = nn.LayerNorm(shape1, begin_norm_axis=1, begin_params_axis=1)
>>> output = m(x).shape
>>> print(output)
(20, 5, 10, 10)
"""
def __init__(self,
normalized_shape,
begin_norm_axis=-1,
begin_params_axis=-1,
gamma_init='ones',
beta_init='zeros',
epsilon=1e-7
):
"""Initialize LayerNorm."""
super(LayerNorm, self).__init__()
if not isinstance(normalized_shape, (tuple, list)):
raise TypeError(f"For '{self.cls_name}', the type of 'normalized_shape' should be tuple[int] or list[int], "
f"but got {normalized_shape} and the type is {type(normalized_shape)}.")
self.normalized_shape = normalized_shape
self.begin_norm_axis = begin_norm_axis
self.begin_params_axis = begin_params_axis
self.epsilon = epsilon
self.gamma = Parameter(initializer(
gamma_init, normalized_shape), name="gamma")
self.beta = Parameter(initializer(
beta_init, normalized_shape), name="beta")
self.layer_norm = P.LayerNorm(begin_norm_axis=self.begin_norm_axis,
begin_params_axis=self.begin_params_axis,
epsilon=self.epsilon)
def construct(self, input_x):
y, _, _ = self.layer_norm(input_x, self.gamma, self.beta)
return y
def extend_repr(self):
return 'normalized_shape={}, begin_norm_axis={}, begin_params_axis={}, gamma{}, beta={}'.format(
self.normalized_shape, self.begin_norm_axis, self.begin_params_axis, self.gamma, self.beta)
class InstanceNorm2d(Cell):
r"""
Instance Normalization layer over a 4D input.
This layer applies Instance Normalization over a 4D input (a mini-batch of 2D inputs with
additional channel dimension) as described in the paper `Instance Normalization: The Missing Ingredient for
Fast Stylization <https://arxiv.org/abs/1607.08022>`_. It rescales and recenters the feature using a mini-batch
of data and the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
\gamma and \beta are learnable parameter vectors of size num_features if affine is True. The standard-deviation
is calculated via the biased estimator.
This layer uses instance statistics computed from input data in both training and evaluation modes.
InstanceNorm2d and BatchNorm2d are very similar, but have some differences. InstanceNorm2d is applied on each
channel of channeled data like RGB images, but BatchNorm2d is usually applied on each batch of batched data.
Note:
Note that the formula for updating the running_mean and running_var is
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times x_t + \text{momentum} \times \hat{x}`,
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value.
Args:
num_features (int): `C` from an expected input of size (N, C, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.1.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C, H, W)`. Data type: float16 or float32.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C, H, W)`. Same type and
shape as the `x`.
Supported Platforms:
``GPU``
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `momentum` is not a float.
TypeError: If `affine` is not a bool.
TypeError: If the type of `gamma_init`/`beta_init` is not same, or if the initialized element type is not
float32.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
KeyError: If any of `gamma_init`/`beta_init` is str and the homonymous class inheriting from `Initializer` not
exists.
Examples:
>>> import mindspore
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.InstanceNorm2d(3)
>>> x = Tensor(np.ones([2, 3, 2, 2]), mindspore.float32)
>>> output = net(x)
>>> print(output.shape)
(2, 3, 2, 2)
"""
@cell_attr_register
def __init__(self,
num_features,
eps=1e-5,
momentum=0.1,
affine=True,
gamma_init='ones',
beta_init='zeros'):
"""Initialize InstanceNorm2d."""
super(InstanceNorm2d, self).__init__()
validator.check_value_type('num_features', num_features, [int], self.cls_name)
validator.check_value_type('eps', eps, [float], self.cls_name)
validator.check_value_type('momentum', momentum, [float], self.cls_name)
validator.check_value_type('affine', affine, [bool], self.cls_name)
args_input = {"gamma_init": gamma_init, "beta_init": beta_init}
self.check_types_valid(args_input, 'InstanceNorm2d')
if num_features < 1:
raise ValueError(f"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.")
if momentum < 0 or momentum > 1:
raise ValueError(f"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], "
f"but got {momentum}.")
self.num_features = num_features
self.eps = eps
self.input_dims = '2d'
self.moving_mean = Parameter(initializer('zeros', num_features), name="mean", requires_grad=False)
self.moving_variance = Parameter(initializer('ones', num_features), name="variance", requires_grad=False)
self.gamma = Parameter(initializer(
gamma_init, num_features), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_features), name="beta", requires_grad=affine)
self.shape = P.Shape()
self.momentum = momentum
self.instance_bn = P.InstanceNorm(epsilon=self.eps, momentum=self.momentum)
def _check_data_dim(self, x):
raise NotImplementedError
def construct(self, x):
_shape_check_bn(self.shape(x), self.input_dims, self.cls_name)
return self.instance_bn(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
def extend_repr(self):
return 'num_features={}, eps={}, momentum={}, gamma={}, beta={}, moving_mean={}, moving_variance={}'.format(
self.num_features, self.eps, self.momentum, self.gamma, self.beta, self.moving_mean, self.moving_variance)
def check_types_valid(self, args_dict, name):
for key, _ in args_dict.items():
val = args_dict[key]
if not isinstance(val, (Tensor, numbers.Number, str, Initializer)):
raise TypeError(f"For '{self.cls_name}', the type of '{key}' should be in "
f"[Tensor, numbers.Number, str, Initializer], but got type {type(val).__name__}.")
if isinstance(val, Tensor) and val.dtype != mstype.float32:
raise TypeError(f"For '{self.cls_name}', the type of '{key}' should be float32, "
f"but got {val.dtype}.")
class GroupNorm(Cell):
r"""
Group Normalization over a mini-batch of inputs.
Group Normalization is widely used in recurrent neural networks. It applies
normalization on a mini-batch of inputs for each single training case as described
in the paper `Group Normalization <https://arxiv.org/pdf/1803.08494.pdf>`_. Group Normalization
divides the channels into groups and computes within each group the mean and variance for normalization,
and it performs very stable over a wide range of batch size. It can be described using the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Args:
num_groups (int): The number of groups to be divided along the channel dimension.
num_channels (int): The number of channels per group.
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
affine (bool): A bool value, this layer will have learnable affine parameters when set to true. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'. If gamma_init is a Tensor, the shape must be [num_channels].
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'. If beta_init is a Tensor, the shape must be [num_channels].
Inputs:
- **x** (Tensor) - The input feature with shape [N, C, H, W].
Outputs:
Tensor, the normalized and scaled offset tensor, has the same shape and data type as the `x`.
Raises:
TypeError: If `num_groups` or `num_channels` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `affine` is not a bool.
ValueError: If `num_groups` or `num_channels` is less than 1.
ValueError: If `num_channels` is not divided by `num_groups`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> group_norm_op = nn.GroupNorm(2, 2)
>>> x = Tensor(np.ones([1, 2, 4, 4], np.float32))
>>> output = group_norm_op(x)
>>> print(output)
[[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]]
"""
def __init__(self, num_groups, num_channels, eps=1e-05, affine=True, gamma_init='ones', beta_init='zeros'):
"""Initialize GroupNorm."""
super(GroupNorm, self).__init__()
self.num_groups = validator.check_positive_int(num_groups, "num_groups", self.cls_name)
self.num_channels = validator.check_positive_int(num_channels, "num_channels", self.cls_name)
if num_channels % num_groups != 0:
raise ValueError(f"For '{self.cls_name}', the 'num_channels' should be divided by 'num_groups', "
f"but got 'num_channels': {num_channels}, 'num_groups': {num_groups}.")
self.eps = validator.check_value_type('eps', eps, (float,), type(self).__name__)
self.affine = validator.check_bool(affine, arg_name="affine", prim_name=self.cls_name)
self.gamma = Parameter(initializer(
gamma_init, num_channels), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_channels), name="beta", requires_grad=affine)
self.shape = F.shape
self.reshape = F.reshape
self.reduce_mean = P.ReduceMean(keep_dims=True)
self.square = F.square
self.reduce_sum = P.ReduceSum(keep_dims=True)
self.sqrt = P.Sqrt()
def _cal_output(self, x):
"""calculate groupnorm output"""
batch, channel, height, width = self.shape(x)
_channel_check(channel, self.num_channels, self.cls_name)
x = self.reshape(x, (batch, self.num_groups, -1))
mean = self.reduce_mean(x, 2)
var = self.reduce_sum(self.square(x - mean), 2) / (channel * height * width / self.num_groups)
std = self.sqrt(var + self.eps)
x = (x - mean) / std
x = self.reshape(x, (batch, channel, height, width))
output = x * self.reshape(self.gamma, (-1, 1, 1)) + self.reshape(self.beta, (-1, 1, 1))
return output
def construct(self, x):
_shape_check(self.shape(x), self.cls_name)
output = self._cal_output(x)
return output
def extend_repr(self):
return 'num_groups={}, num_channels={}'.format(self.num_groups, self.num_channels)
| # Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""normalization"""
import itertools
import numbers
from mindspore.ops import operations as P
from mindspore.ops import functional as F
from mindspore.ops.operations import _inner_ops as inner
from mindspore.common.parameter import Parameter
from mindspore.common.initializer import initializer, Initializer
from mindspore.common.tensor import Tensor
from mindspore.common._decorator import deprecated
from mindspore.ops.primitive import constexpr
import mindspore.context as context
from mindspore._checkparam import Rel
from mindspore._checkparam import Validator as validator
from mindspore._extends import cell_attr_register
from mindspore.communication.management import get_group_size, get_rank
from mindspore.communication import management
from mindspore.common import dtype as mstype
from mindspore.parallel._utils import _is_in_auto_parallel_mode
from ..cell import Cell
__all__ = ['BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'LayerNorm', 'GroupNorm',
'GlobalBatchNorm', 'SyncBatchNorm', 'InstanceNorm2d']
SYNC_BN_GROUP_NAME = ""
class _BatchNorm(Cell):
"""Batch Normalization base class."""
@cell_attr_register
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
device_num_each_group=1,
process_groups=0,
input_dims='2d',
data_format='NCHW'):
"""Initialize _BatchNorm."""
super(_BatchNorm, self).__init__()
validator.check_value_type('num_features', num_features, [int], self.cls_name)
if num_features < 1:
raise ValueError(f"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.")
if momentum < 0 or momentum > 1:
raise ValueError(f"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], "
f"but got {momentum}.")
self.input_dims = input_dims
self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.cls_name)
if context.get_context("device_target") != "GPU" and self.format == "NHWC":
raise ValueError(f"For '{self.cls_name}', the 'NHWC' format only support in GPU target, but got device "
f"target {context.get_context('device_target')}.")
self.use_batch_statistics = use_batch_statistics
if self.use_batch_statistics is not None and not isinstance(self.use_batch_statistics, bool):
raise ValueError(f"For '{self.cls_name}', the 'use_batch_statistics' should be a boolean value or None,"
f" but got {use_batch_statistics}.")
self.num_features = num_features
self.eps = eps
self.moving_mean = Parameter(initializer(
moving_mean_init, num_features), name="mean", requires_grad=False)
self.moving_variance = Parameter(initializer(
moving_var_init, num_features), name="variance", requires_grad=False)
self.gamma = Parameter(initializer(
gamma_init, num_features), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_features), name="beta", requires_grad=affine)
self.group_device_num = validator.check_positive_int(device_num_each_group, "device_num_each_group",
self.cls_name)
self.process_groups = process_groups
self.is_global = False
self.parallel_mode = context.get_auto_parallel_context("parallel_mode")
global SYNC_BN_GROUP_NAME
# for GlobalBatchNorm
if self.group_device_num != 1:
self.rank_id = get_rank()
self.rank_size = get_group_size()
self.device_list = [i for i in range(0, self.rank_size)]
self.rank_list = self.list_group(self.device_list, self.group_device_num)
self.rank_list_idx = len(self.rank_list)
self._create_global_groups()
# for SyncBatchNorm
if self.process_groups != 0:
self.rank_id = get_rank()
self.rank_size = get_group_size()
if self.process_groups is not None:
validator.check_isinstance("process_groups", self.process_groups, list)
self._check_rank_ids(self.process_groups, self.rank_size)
self._create_sync_groups()
elif self.rank_size > 1:
self.is_global = True
self.group_device_num = self.rank_size
self.device_list = [i for i in range(0, self.rank_size)]
if context.get_context("device_target") == "Ascend":
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group0"
management.create_group(SYNC_BN_GROUP_NAME, self.device_list)
elif context.get_context("device_target") == "GPU":
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "nccl_world_group"
self.shape = P.Shape()
self.reduce_mean = P.ReduceMean(keep_dims=True)
self.square = P.Square()
self.sqrt = P.Sqrt()
self.cast = P.Cast()
self.dtype = P.DType()
self.reshape = P.Reshape()
self._target = context.get_context("device_target")
self.is_graph_mode = context.get_context("mode") == context.GRAPH_MODE
self.momentum = 1.0 - momentum
if context.get_context("enable_ge"):
self.is_ge_backend = True
else:
self.is_ge_backend = False
self.bn_train = P.BatchNorm(is_training=True,
epsilon=self.eps,
momentum=self.momentum,
data_format=self.format)
if self.is_global:
self.bn_train = inner.SyncBatchNorm(epsilon=self.eps,
momentum=self.momentum,
group=SYNC_BN_GROUP_NAME,
device_num=self.group_device_num)
self.bn_infer = P.BatchNorm(is_training=False, epsilon=self.eps, data_format=self.format)
if _is_in_auto_parallel_mode():
data_parallel_strategy = ((1,), (1,))
data_parallel_strategy_one = ((1,), ())
else:
data_parallel_strategy = None
data_parallel_strategy_one = None
self.sub_mean = P.Sub().shard(data_parallel_strategy)
self.sub_var = P.Sub().shard(data_parallel_strategy)
self.mul_mean = P.Mul().shard(data_parallel_strategy_one)
self.mul_var = P.Mul().shard(data_parallel_strategy_one)
self.assign_sub_mean = P.AssignSub().shard(data_parallel_strategy)
self.assign_sub_var = P.AssignSub().shard(data_parallel_strategy)
def _check_data_dim(self, x):
raise NotImplementedError
def list_group(self, world_rank, group_size):
""" Check whether world_rank and group_size are valid. """
if group_size > get_group_size():
raise ValueError(f"For '{self.cls_name}', the 'device_num_each_group' cannot be greater than "
f"local rank size, but got 'device_num_each_group': {group_size}, "
f"local rank size: {get_group_size()}.")
if len(world_rank) % group_size != 0:
raise ValueError(f"For '{self.cls_name}', the dimension of device_list should be divisible by "
f"'device_num_each_group', but got the length of device_list: {len(world_rank)}, "
f"'device_num_each_group': {group_size}.")
world_rank_list = zip(*(iter(world_rank),) * group_size)
group_list = [list(i) for i in world_rank_list]
return group_list
def _check_rank_ids(self, process_groups, rank_size):
seen = set()
for rid in itertools.chain(*process_groups):
validator.check_int_range(rid, 0, rank_size, Rel.INC_LEFT, "rank id in process_groups", self.cls_name)
if rid in seen:
raise ValueError(f"For '{self.cls_name}', rank id in 'process_groups' should not be duplicated, "
f"but got {process_groups}.")
seen.add(rid)
def _create_global_groups(self):
for i in range(self.rank_list_idx):
if self.rank_id in self.rank_list[i]:
self.is_global = True
global SYNC_BN_GROUP_NAME
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group" + str(i)
management.create_group(SYNC_BN_GROUP_NAME, self.rank_list[i])
def _create_sync_groups(self):
for i in range(len(self.process_groups)):
validator.check_isinstance("process_groups[" + str(i) + "]", self.process_groups[i], list)
self.group_device_num = len(self.process_groups[i])
if self.rank_id in self.process_groups[i] and self.group_device_num > 1:
self.is_global = True
global SYNC_BN_GROUP_NAME
if SYNC_BN_GROUP_NAME == "":
SYNC_BN_GROUP_NAME = "sync_bn_group" + str(i)
management.create_group(SYNC_BN_GROUP_NAME, self.process_groups[i])
def construct(self, x):
_shape_check_bn(self.shape(x), self.input_dims, self.cls_name)
if self.use_batch_statistics is None:
if self.training:
return self.bn_train(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
if not self.training:
return self.bn_infer(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
if self.use_batch_statistics is True:
return self.bn_train(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
return self.bn_infer(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
def extend_repr(self):
return 'num_features={}, eps={}, momentum={}, gamma={}, beta={}, moving_mean={}, moving_variance={}'.format(
self.num_features, self.eps, self.momentum, self.gamma, self.beta, self.moving_mean, self.moving_variance)
@constexpr
def _channel_check(channel, num_channel, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if channel != num_channel:
raise ValueError(f"{msg_prefix} channel(the second dim of the input 'x') should be equal to num_channels, "
f"but got channel: {channel}, num_channels: {num_channel}.")
@constexpr
def _shape_check(in_shape, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if len(in_shape) != 4:
raise ValueError(f"{msg_prefix} in_shape must has 4 dims, but got the length of in_shape: {len(in_shape)}.")
@constexpr
def _shape_check_bn(in_shape, in_dims, prim_name=None):
"""check input dims of batch norm."""
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
dim = len(in_shape)
if in_dims == '1d' and dim != 2:
raise ValueError(f"{msg_prefix} in_shape must have 2 dims, but got {len(in_shape)}.")
if in_dims == '2d' and dim != 4:
raise ValueError(f"{msg_prefix} in_shape must have 4 dims, but got {len(in_shape)}.")
if in_dims == '3d' and dim != 5:
raise ValueError(f"{msg_prefix} in_shape must have 5 dims, but got {len(in_shape)}.")
if in_dims == 'both' and dim != 2 and dim != 4:
raise ValueError(f"{msg_prefix} in_shape must have 2 dims or 4 dims, but got {len(in_shape)}.")
@constexpr
def _shape_infer(x_shape, num_feature):
"""global Batch Normalization shape and axes infer"""
if len(x_shape) == 4:
axes = (0, 2, 3)
re_shape = (1, num_feature, 1, 1)
else:
axes = (0,)
re_shape = (1, num_feature)
return axes, re_shape
class BatchNorm1d(_BatchNorm):
r"""
Batch Normalization layer over a 2D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 2D input (a mini-batch of 1D inputs) to
reduce internal covariate shift as described in the paper
`Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It
rescales and recenters the feature using a mini-batch of data and
the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore the mode is not
recommended to be changed after net was initialized.
Args:
num_features (int): `C` from an expected input of size (N, C).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, the training process will use the mean
and variance of current batch data and track the running mean and variance, the evaluation process will use
the running mean and variance. Default: None.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out})`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm1d(num_features=4)
>>> x = Tensor(np.array([[0.7, 0.5, 0.5, 0.6],
... [0.5, 0.4, 0.6, 0.9]]).astype(np.float32))
>>> output = net(x)
>>> print(output)
[[ 0.6999965 0.4999975 0.4999975 0.59999704 ]
[ 0.4999975 0.399998 0.59999704 0.89999545 ]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None):
"""Initialize BatchNorm1d."""
super(BatchNorm1d, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
input_dims='1d')
def _check_data_dim(self, x):
if x.ndim != 2:
pass
class BatchNorm2d(_BatchNorm):
r"""
Batch Normalization layer over a 4D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with
additional channel dimension) to avoid internal covariate shift as described
in the paper `Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It
rescales and recenters the feature using a mini-batch of data and
the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore that mode can not be
changed after net was initialized.
Note that the formula for updating the moving_mean and moving_var is
.. math::
\text{moving_mean}=\text{moving_mean∗momentum}+μ_β\text{∗(1−momentum)}\\
\text{moving_var}=\text{moving_var∗momentum}+σ^2_β\text{∗(1−momentum)}
where :math:`moving_mean, moving_var` are the updated mean and variance,
:math:`μ_β, σ^2_β` are the observed value (mean and variance) of each batch of data.
Args:
num_features (int): The number of channels of the input tensor. Expected input size is (N, C, H, W),
`C` represents the number of channels
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool):
- If true, use the mean value and variance value of current batch data and track running mean
and running variance.
- If false, use the mean value and variance value of specified value, and not track statistical value.
- If None, the use_batch_statistics is automatically set to true or false according to the training
and evaluation mode. During training, the parameter is set to true, and during evaluation, the
parameter is set to false. Default: None.
data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'.
Default: 'NCHW'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If `data_format` is neither 'NHWC' not 'NCHW'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm2d(num_features=3)
>>> x = Tensor(np.ones([1, 3, 2, 2]).astype(np.float32))
>>> output = net(x)
>>> print(output)
[[[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
data_format='NCHW'):
"""Initialize BatchNorm2d."""
super(BatchNorm2d, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
input_dims='2d',
data_format=data_format)
def _check_data_dim(self, x):
if x.ndim != 4:
pass
@constexpr
def _check_3d_shape(input_shape, prim_name=None):
msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
if len(input_shape) != 5:
raise ValueError(f"{msg_prefix} input_shape must be 5-dimensional, but got the length of input_shape: "
f"{len(input_shape)}.")
class BatchNorm3d(Cell):
r"""
Batch Normalization layer over a 5D input.
Batch Normalization is widely used in convolutional networks. This layer
applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with
additional channel dimension) to avoid internal covariate shift.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
The implementation of BatchNorm is different in graph mode and pynative mode, therefore that mode can not be
changed after net was initialized.
Note that the formula for updating the running_mean and running_var is
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times x_t + \text{momentum} \times \hat{x}`,
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value.
Args:
num_features (int): `C` from an expected input of size (N, C, D, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, the training process will use the mean
and variance of current batch data and track the running mean and variance, the evaluation process will use
the running mean and variance. Default: None.
data_format (str): The optional value for data format is 'NCDHW'. Default: 'NCDHW'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, D_{out},H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If `data_format` is not 'NCDHW'.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.BatchNorm3d(num_features=3)
>>> x = Tensor(np.ones([16, 3, 10, 32, 32]).astype(np.float32))
>>> output = net(x)
>>> print(output.shape)
(16, 3, 10, 32, 32)
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
data_format='NCDHW'):
"""Initialize BatchNorm3d."""
super(BatchNorm3d, self).__init__()
self.format = validator.check_string(data_format, ['NCDHW'], 'format', self.cls_name)
self.reshape = P.Reshape()
self.bn2d = BatchNorm2d(num_features=num_features,
eps=eps,
momentum=momentum,
affine=affine,
gamma_init=gamma_init,
beta_init=beta_init,
moving_mean_init=moving_mean_init,
moving_var_init=moving_var_init,
use_batch_statistics=use_batch_statistics,
data_format="NCHW")
def construct(self, input_x):
x_shape = F.shape(input_x)
_check_3d_shape(x_shape, self.cls_name)
input_x = self.reshape(input_x, (x_shape[0], x_shape[1], x_shape[2] * x_shape[3], x_shape[4]))
bn2d_out = self.bn2d(input_x)
bn3d_out = self.reshape(bn2d_out, x_shape)
return bn3d_out
class GlobalBatchNorm(_BatchNorm):
r"""
The GlobalBatchNorm interface is deprecated, please use the :class:`mindspore.nn.SyncBatchNorm` instead.
Supported Platforms:
deprecated
"""
@deprecated("1.2", "SyncBatchNorm", True)
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
device_num_each_group=2):
"""Initialize GlobalBatchNorm."""
super(GlobalBatchNorm, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
device_num_each_group,
input_dims='both')
self.group_device_num = validator.check_positive_int(device_num_each_group, "device_num_each_group",
self.cls_name)
if self.group_device_num <= 1:
raise ValueError(f"For '{self.cls_name}', the 'device_num_each_group' must be greater than 1, "
f"but got {self.group_device_num}.")
def _check_data_dim(self, x):
if x.dim == 0:
pass
class SyncBatchNorm(_BatchNorm):
r"""
Sync Batch Normalization layer over a N-dimension input.
Sync Batch Normalization is cross device synchronized Batch Normalization. The implementation of Batch
Normalization only normalizes the data within each device. Sync Batch Normalization will normalize the input
within the group. It has been described in the paper `Batch Normalization: Accelerating Deep Network Training by
Reducing Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`_. It rescales and recenters the
feature using a mini-batch of data and the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Note:
Currently, SyncBatchNorm only supports 2D and 4D inputs.
Args:
num_features (int): `C` from an expected input of size (N, C, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.9.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
moving_mean_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving mean.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
moving_var_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the moving variance.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
use_batch_statistics (bool): If true, use the mean value and variance value of current batch data. If false,
use the mean value and variance value of specified value. If None, training process will use the mean and
variance of current batch data and track the running mean and variance, eval process will use the running
mean and variance. Default: None.
process_groups (list): A list to divide devices into different sync groups, containing N subtraction lists.
Each subtraction list contains int numbers identifying rank ids which need to be synchronized in the same
group. All int values must be in [0, rank_size) and different from each other. Default: None, indicating
synchronization across all devices.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `process_groups` is not a list.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
ValueError: If rank_id in `process_groups` is not in range [0, rank_size).
Supported Platforms:
``Ascend``
Examples:
>>> # This example should be run with multiple processes.
>>> # Please refer to the tutorial > Distributed Training on mindspore.cn.
>>> import numpy as np
>>> from mindspore.communication import init
>>> from mindspore import context
>>> from mindspore.context import ParallelMode
>>> from mindspore import Tensor
>>> from mindspore import nn
>>> from mindspore import dtype as mstype
>>>
>>> context.set_context(mode=context.GRAPH_MODE)
>>> init()
>>> context.reset_auto_parallel_context()
>>> context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL)
>>> sync_bn_op = nn.SyncBatchNorm(num_features=3, process_groups=[[0, 1], [2, 3]])
>>> x = Tensor(np.ones([1, 3, 2, 2]), mstype.float32)
>>> output = sync_bn_op(x)
>>> print(output)
[[[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]
[[ 0.999995 0.999995 ]
[ 0.999995 0.999995 ]]]]
"""
def __init__(self,
num_features,
eps=1e-5,
momentum=0.9,
affine=True,
gamma_init='ones',
beta_init='zeros',
moving_mean_init='zeros',
moving_var_init='ones',
use_batch_statistics=None,
process_groups=None):
"""Initialize SyncBatchNorm."""
super(SyncBatchNorm, self).__init__(num_features,
eps,
momentum,
affine,
gamma_init,
beta_init,
moving_mean_init,
moving_var_init,
use_batch_statistics,
process_groups=process_groups,
input_dims='both')
def _check_data_dim(self, x):
if x.dim == 0:
pass
class LayerNorm(Cell):
r"""
Applies Layer Normalization over a mini-batch of inputs.
Layer Normalization is widely used in recurrent neural networks. It applies
normalization on a mini-batch of inputs for each single training case as described
in the paper `Layer Normalization <https://arxiv.org/pdf/1607.06450.pdf>`_. Unlike Batch
Normalization, Layer Normalization performs exactly the same computation at training and
testing time. It can be described using the following formula. It is applied across all channels
and pixel but only one batch size.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Args:
normalized_shape (Union(tuple[int], list[int])): The normalization is performed over axis
`begin_norm_axis ... R - 1`.
begin_norm_axis (int): The first normalization dimension: normalization will be performed along dimensions
`begin_norm_axis: rank(inputs)`, the value should be in [-1, rank(input)). Default: -1.
begin_params_axis (int): The first parameter(beta, gamma)dimension: scale and centering parameters
will have dimensions `begin_params_axis: rank(inputs)` and will be broadcast with
the normalized inputs accordingly, the value should be in [-1, rank(input)). Default: -1.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'.
epsilon (float): A value added to the denominator for numerical stability. Default: 1e-7.
Inputs:
- **x** (Tensor) - The shape of 'x' is :math:`(x_1, x_2, ..., x_R)`,
and `input_shape[begin_norm_axis:]` is equal to `normalized_shape`.
Outputs:
Tensor, the normalized and scaled offset tensor, has the same shape and data type as the `x`.
Raises:
TypeError: If `normalized_shape` is neither a list nor tuple.
TypeError: If `begin_norm_axis` or `begin_params_axis` is not an int.
TypeError: If `epsilon` is not a float.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.ones([20, 5, 10, 10]), mindspore.float32)
>>> shape1 = x.shape[1:]
>>> m = nn.LayerNorm(shape1, begin_norm_axis=1, begin_params_axis=1)
>>> output = m(x).shape
>>> print(output)
(20, 5, 10, 10)
"""
def __init__(self,
normalized_shape,
begin_norm_axis=-1,
begin_params_axis=-1,
gamma_init='ones',
beta_init='zeros',
epsilon=1e-7
):
"""Initialize LayerNorm."""
super(LayerNorm, self).__init__()
if not isinstance(normalized_shape, (tuple, list)):
raise TypeError(f"For '{self.cls_name}', the type of 'normalized_shape' should be tuple[int] or list[int], "
f"but got {normalized_shape} and the type is {type(normalized_shape)}.")
self.normalized_shape = normalized_shape
self.begin_norm_axis = begin_norm_axis
self.begin_params_axis = begin_params_axis
self.epsilon = epsilon
self.gamma = Parameter(initializer(
gamma_init, normalized_shape), name="gamma")
self.beta = Parameter(initializer(
beta_init, normalized_shape), name="beta")
self.layer_norm = P.LayerNorm(begin_norm_axis=self.begin_norm_axis,
begin_params_axis=self.begin_params_axis,
epsilon=self.epsilon)
def construct(self, input_x):
y, _, _ = self.layer_norm(input_x, self.gamma, self.beta)
return y
def extend_repr(self):
return 'normalized_shape={}, begin_norm_axis={}, begin_params_axis={}, gamma{}, beta={}'.format(
self.normalized_shape, self.begin_norm_axis, self.begin_params_axis, self.gamma, self.beta)
class InstanceNorm2d(Cell):
r"""
Instance Normalization layer over a 4D input.
This layer applies Instance Normalization over a 4D input (a mini-batch of 2D inputs with
additional channel dimension) as described in the paper `Instance Normalization: The Missing Ingredient for
Fast Stylization <https://arxiv.org/abs/1607.08022>`_. It rescales and recenters the feature using a mini-batch
of data and the learned parameters which can be described in the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
\gamma and \beta are learnable parameter vectors of size num_features if affine is True. The standard-deviation
is calculated via the biased estimator.
This layer uses instance statistics computed from input data in both training and evaluation modes.
InstanceNorm2d and BatchNorm2d are very similar, but have some differences. InstanceNorm2d is applied on each
channel of channeled data like RGB images, but BatchNorm2d is usually applied on each batch of batched data.
Note:
Note that the formula for updating the running_mean and running_var is
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times x_t + \text{momentum} \times \hat{x}`,
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the new observed value.
Args:
num_features (int): `C` from an expected input of size (N, C, H, W).
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
momentum (float): A floating hyperparameter of the momentum for the
running_mean and running_var computation. Default: 0.1.
affine (bool): A bool value. When set to True, gamma and beta can be learned. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'ones'.
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', etc. Default: 'zeros'.
Inputs:
- **x** (Tensor) - Tensor of shape :math:`(N, C, H, W)`. Data type: float16 or float32.
Outputs:
Tensor, the normalized, scaled, offset tensor, of shape :math:`(N, C, H, W)`. Same type and
shape as the `x`.
Supported Platforms:
``GPU``
Raises:
TypeError: If `num_features` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `momentum` is not a float.
TypeError: If `affine` is not a bool.
TypeError: If the type of `gamma_init`/`beta_init` is not same, or if the initialized element type is not
float32.
ValueError: If `num_features` is less than 1.
ValueError: If `momentum` is not in range [0, 1].
KeyError: If any of `gamma_init`/`beta_init` is str and the homonymous class inheriting from `Initializer` not
exists.
Examples:
>>> import mindspore
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> net = nn.InstanceNorm2d(3)
>>> x = Tensor(np.ones([2, 3, 2, 2]), mindspore.float32)
>>> output = net(x)
>>> print(output.shape)
(2, 3, 2, 2)
"""
@cell_attr_register
def __init__(self,
num_features,
eps=1e-5,
momentum=0.1,
affine=True,
gamma_init='ones',
beta_init='zeros'):
"""Initialize InstanceNorm2d."""
super(InstanceNorm2d, self).__init__()
validator.check_value_type('num_features', num_features, [int], self.cls_name)
validator.check_value_type('eps', eps, [float], self.cls_name)
validator.check_value_type('momentum', momentum, [float], self.cls_name)
validator.check_value_type('affine', affine, [bool], self.cls_name)
args_input = {"gamma_init": gamma_init, "beta_init": beta_init}
self.check_types_valid(args_input, 'InstanceNorm2d')
if num_features < 1:
raise ValueError(f"For '{self.cls_name}', the 'num_features' must be at least 1, but got {num_features}.")
if momentum < 0 or momentum > 1:
raise ValueError(f"For '{self.cls_name}', the 'momentum' should be a number in range [0, 1], "
f"but got {momentum}.")
self.num_features = num_features
self.eps = eps
self.input_dims = '2d'
self.moving_mean = Parameter(initializer('zeros', num_features), name="mean", requires_grad=False)
self.moving_variance = Parameter(initializer('ones', num_features), name="variance", requires_grad=False)
self.gamma = Parameter(initializer(
gamma_init, num_features), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_features), name="beta", requires_grad=affine)
self.shape = P.Shape()
self.momentum = momentum
self.instance_bn = P.InstanceNorm(epsilon=self.eps, momentum=self.momentum)
def _check_data_dim(self, x):
raise NotImplementedError
def construct(self, x):
_shape_check_bn(self.shape(x), self.input_dims, self.cls_name)
return self.instance_bn(x,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance)[0]
def extend_repr(self):
return 'num_features={}, eps={}, momentum={}, gamma={}, beta={}, moving_mean={}, moving_variance={}'.format(
self.num_features, self.eps, self.momentum, self.gamma, self.beta, self.moving_mean, self.moving_variance)
def check_types_valid(self, args_dict, name):
for key, _ in args_dict.items():
val = args_dict[key]
if not isinstance(val, (Tensor, numbers.Number, str, Initializer)):
raise TypeError(f"For '{self.cls_name}', the type of '{key}' should be in "
f"[Tensor, numbers.Number, str, Initializer], but got type {type(val).__name__}.")
if isinstance(val, Tensor) and val.dtype != mstype.float32:
raise TypeError(f"For '{self.cls_name}', the type of '{key}' should be float32, "
f"but got {val.dtype}.")
class GroupNorm(Cell):
r"""
Group Normalization over a mini-batch of inputs.
Group Normalization is widely used in recurrent neural networks. It applies
normalization on a mini-batch of inputs for each single training case as described
in the paper `Group Normalization <https://arxiv.org/pdf/1803.08494.pdf>`_. Group Normalization
divides the channels into groups and computes within each group the mean and variance for normalization,
and it performs very stable over a wide range of batch size. It can be described using the following formula.
.. math::
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
Args:
num_groups (int): The number of groups to be divided along the channel dimension.
num_channels (int): The number of channels per group.
eps (float): A value added to the denominator for numerical stability. Default: 1e-5.
affine (bool): A bool value, this layer will have learnable affine parameters when set to true. Default: True.
gamma_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the gamma weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'ones'. If gamma_init is a Tensor, the shape must be [num_channels].
beta_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the beta weight.
The values of str refer to the function `initializer` including 'zeros', 'ones', 'xavier_uniform',
'he_uniform', etc. Default: 'zeros'. If beta_init is a Tensor, the shape must be [num_channels].
Inputs:
- **x** (Tensor) - The input feature with shape [N, C, H, W].
Outputs:
Tensor, the normalized and scaled offset tensor, has the same shape and data type as the `x`.
Raises:
TypeError: If `num_groups` or `num_channels` is not an int.
TypeError: If `eps` is not a float.
TypeError: If `affine` is not a bool.
ValueError: If `num_groups` or `num_channels` is less than 1.
ValueError: If `num_channels` is not divided by `num_groups`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> group_norm_op = nn.GroupNorm(2, 2)
>>> x = Tensor(np.ones([1, 2, 4, 4], np.float32))
>>> output = group_norm_op(x)
>>> print(output)
[[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]]]
"""
def __init__(self, num_groups, num_channels, eps=1e-05, affine=True, gamma_init='ones', beta_init='zeros'):
"""Initialize GroupNorm."""
super(GroupNorm, self).__init__()
self.num_groups = validator.check_positive_int(num_groups, "num_groups", self.cls_name)
self.num_channels = validator.check_positive_int(num_channels, "num_channels", self.cls_name)
if num_channels % num_groups != 0:
raise ValueError(f"For '{self.cls_name}', the 'num_channels' should be divided by 'num_groups', "
f"but got 'num_channels': {num_channels}, 'num_groups': {num_groups}.")
self.eps = validator.check_value_type('eps', eps, (float,), type(self).__name__)
self.affine = validator.check_bool(affine, arg_name="affine", prim_name=self.cls_name)
self.gamma = Parameter(initializer(
gamma_init, num_channels), name="gamma", requires_grad=affine)
self.beta = Parameter(initializer(
beta_init, num_channels), name="beta", requires_grad=affine)
self.shape = F.shape
self.reshape = F.reshape
self.reduce_mean = P.ReduceMean(keep_dims=True)
self.square = F.square
self.reduce_sum = P.ReduceSum(keep_dims=True)
self.sqrt = P.Sqrt()
def _cal_output(self, x):
"""calculate groupnorm output"""
batch, channel, height, width = self.shape(x)
_channel_check(channel, self.num_channels, self.cls_name)
x = self.reshape(x, (batch, self.num_groups, -1))
mean = self.reduce_mean(x, 2)
var = self.reduce_sum(self.square(x - mean), 2) / (channel * height * width / self.num_groups)
std = self.sqrt(var + self.eps)
x = (x - mean) / std
x = self.reshape(x, (batch, channel, height, width))
output = x * self.reshape(self.gamma, (-1, 1, 1)) + self.reshape(self.beta, (-1, 1, 1))
return output
def construct(self, x):
_shape_check(self.shape(x), self.cls_name)
output = self._cal_output(x)
return output
def extend_repr(self):
return 'num_groups={}, num_channels={}'.format(self.num_groups, self.num_channels)
|
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
"""
Holds the GitHub repository service.
"""
import json
import os
import uuid
from typing import List, Union, Optional
import falcon
import github
from github import PullRequest
from github.GithubException import UnknownObjectException, BadCredentialsException, GithubException, IncompletableObject
from requests_oauthlib import OAuth2Session
import cla
from cla.controllers.github_application import GitHubInstallation
from cla.models import repository_service_interface, DoesNotExist
from cla.models.dynamo_models import Repository, GitHubOrg
from cla.utils import get_project_instance, append_project_version_to_url
# some emails we want to exclude when we register the users
EXCLUDE_GITHUB_EMAILS = ["noreply.github.com"]
class GitHub(repository_service_interface.RepositoryService):
"""
The GitHub repository service.
"""
def __init__(self):
self.client = None
def initialize(self, config):
# username = config['GITHUB_USERNAME']
# token = config['GITHUB_TOKEN']
# self.client = self._get_github_client(username, token)
pass
def _get_github_client(self, username, token): # pylint: disable=no-self-use
return github.Github(username, token)
def get_repository_id(self, repo_name, installation_id=None):
"""
Helper method to get a GitHub repository ID based on repository name.
:param repo_name: The name of the repository, example: 'linuxfoundation/cla'.
:type repo_name: string
:param installation_id: The github installation id
:type installation_id: string
:return: The repository ID.
:rtype: integer
"""
if installation_id is not None:
self.client = get_github_integration_client(installation_id)
try:
return self.client.get_repo(repo_name).id
except github.GithubException as err:
cla.log.error('Could not find GitHub repository (%s), ensure it exists and that '
'your personal access token is configured with the repo scope', repo_name)
except Exception as err:
cla.log.error('Unknown error while getting GitHub repository ID for repository %s: %s',
repo_name, str(err))
def received_activity(self, data):
cla.log.debug('github_models.received_activity - Received GitHub activity: %s', data)
if 'pull_request' not in data:
cla.log.debug('github_models.received_activity - Activity not related to pull request - ignoring')
return {'message': 'Not a pull request - no action performed'}
if data['action'] == 'opened':
cla.log.debug('github_models.received_activity - Handling opened pull request')
return self.process_opened_pull_request(data)
elif data['action'] == 'reopened':
cla.log.debug('github_models.received_activity - Handling reopened pull request')
return self.process_reopened_pull_request(data)
elif data['action'] == 'closed':
cla.log.debug('github_models.received_activity - Handling closed pull request')
return self.process_closed_pull_request(data)
elif data['action'] == 'synchronize':
cla.log.debug('github_models.received_activity - Handling synchronized pull request')
return self.process_synchronized_pull_request(data)
else:
cla.log.debug('github_models.received_activity - Ignoring unsupported action: {}'.format(data['action']))
def sign_request(self, installation_id, github_repository_id, change_request_id, request):
"""
This method gets called when the OAuth2 app (NOT the GitHub App) needs to get info on the
user trying to sign. In this case we begin an OAuth2 exchange with the 'user:email' scope.
"""
fn = 'github_models.sign_request' # function name
cla.log.debug(f'{fn} - Initiating GitHub sign request for installation_id: {installation_id}, '
f'for repository {github_repository_id}, '
f'for PR: {change_request_id}')
# Not sure if we need a different token for each installation ID...
cla.log.debug(f'{fn} - Loading session from request: {request}...')
session = self._get_request_session(request)
cla.log.debug(f'{fn} - Adding github details to session: {session} which is type: {type(session)}...')
session['github_installation_id'] = installation_id
session['github_repository_id'] = github_repository_id
session['github_change_request_id'] = change_request_id
cla.log.debug(f'{fn} - Determining return URL from the inbound request...')
origin_url = self.get_return_url(github_repository_id, change_request_id, installation_id)
cla.log.debug(f'{fn} - Return URL from the inbound request is {origin_url}')
session['github_origin_url'] = origin_url
cla.log.debug(f'{fn} - Stored origin url in session as session["github_origin_url"] = {origin_url}')
if 'github_oauth2_token' in session:
cla.log.debug(f'{fn} - Using existing session GitHub OAuth2 token')
return self.redirect_to_console(
installation_id, github_repository_id, change_request_id,
origin_url, request)
else:
cla.log.debug(f'{fn} - No existing GitHub OAuth2 token - building authorization url and state')
authorization_url, state = self.get_authorization_url_and_state(installation_id,
github_repository_id,
int(change_request_id),
['user:email'])
cla.log.debug(f'{fn} - Obtained GitHub OAuth2 state from authorization - storing state in the session...')
session['github_oauth2_state'] = state
cla.log.debug(f'{fn} - GitHub OAuth2 request with state {state} - sending user to {authorization_url}')
raise falcon.HTTPFound(authorization_url)
def _get_request_session(self, request) -> dict: # pylint: disable=no-self-use
"""
Mockable method used to get the current user session.
"""
fn = 'cla.models.github_models._get_request_session'
session = request.context.get('session')
if session is None:
cla.log.warning(f'Session is empty for request: {request}')
cla.log.debug(f'{fn} - loaded session: {session}')
# Ensure session is a dict - getting issue where session is a string
if isinstance(session, str):
# convert string to a dict
cla.log.debug(f'{fn} - session is type: {type(session)} - converting to dict...')
session = json.loads(session)
# Reset the session now that we have converted it to a dict
request.context['session'] = session
cla.log.debug(f'{fn} - session: {session} which is now type: {type(session)}...')
return session
def get_authorization_url_and_state(self, installation_id, github_repository_id, pull_request_number, scope):
"""
Helper method to get the GitHub OAuth2 authorization URL and state.
This will be used to get the user's emails from GitHub.
:TODO: Update comments.
:param repository_id: The ID of the repository this request was initiated in.
:type repository_id: int
:param pull_request_number: The PR number this request was generated in.
:type pull_request_number: int
:param scope: The list of OAuth2 scopes to request from GitHub.
:type scope: [string]
"""
# Get the PR's html_url property.
# origin = self.get_return_url(github_repository_id, pull_request_number, installation_id)
# Add origin to user's session here?
fn = 'github_models.get_authorization_url_and_state'
redirect_uri = os.environ.get('CLA_API_BASE', '').strip() + "/v2/github/installation"
github_oauth_url = cla.conf['GITHUB_OAUTH_AUTHORIZE_URL']
github_oauth_client_id = os.environ['GH_OAUTH_CLIENT_ID']
cla.log.debug(f'{fn} - Directing user to the github authorization url: {github_oauth_url} via '
f'our github installation flow: {redirect_uri} '
f'using the github oauth client id: {github_oauth_client_id[0:5]} '
f'with scope: {scope}')
return self._get_authorization_url_and_state(client_id=github_oauth_client_id,
redirect_uri=redirect_uri,
scope=scope,
authorize_url=github_oauth_url)
def _get_authorization_url_and_state(self, client_id, redirect_uri, scope, authorize_url):
"""
Mockable helper method to do the fetching of the authorization URL and state from GitHub.
"""
return cla.utils.get_authorization_url_and_state(client_id, redirect_uri, scope, authorize_url)
def oauth2_redirect(self, state, code, request): # pylint: disable=too-many-arguments
"""
This is where the user will end up after having authorized the CLA system
to get information such as email address.
It will handle storing the OAuth2 session information for this user for
further requests and initiate the signing workflow.
"""
fn = 'github_models.oauth2_redirect'
cla.log.debug(f'{fn} - handling GitHub OAuth2 redirect with request: {dir(request)}')
session = self._get_request_session(request) # request.context['session']
cla.log.debug(f'{fn} - state: {state}, code: {code}, session: {session}')
if 'github_oauth2_state' in session:
session_state = session['github_oauth2_state']
else:
session_state = None
cla.log.warning(f'{fn} - github_oauth2_state not set in current session')
if state != session_state:
cla.log.warning(f'{fn} - invalid GitHub OAuth2 state {session_state} expecting {state}')
raise falcon.HTTPBadRequest('Invalid OAuth2 state', state)
# Get session information for this request.
cla.log.debug(f'{fn} - attempting to fetch OAuth2 token for state {state}')
installation_id = session.get('github_installation_id', None)
github_repository_id = session.get('github_repository_id', None)
change_request_id = session.get('github_change_request_id', None)
origin_url = session.get('github_origin_url', None)
state = session.get('github_oauth2_state')
token_url = cla.conf['GITHUB_OAUTH_TOKEN_URL']
client_id = os.environ['GH_OAUTH_CLIENT_ID']
client_secret = os.environ['GH_OAUTH_SECRET']
cla.log.debug(f'{fn} - fetching token using {client_id[0:5]}... with state={state}, token_url={token_url}, '
f'client_secret={client_secret[0:5]}, with code={code}')
token = self._fetch_token(client_id, state, token_url, client_secret, code)
cla.log.debug(f'{fn} - oauth2 token received for state {state}: {token} - storing token in session')
session['github_oauth2_token'] = token
cla.log.debug(f'{fn} - redirecting the user back to the console: {origin_url}')
return self.redirect_to_console(installation_id, github_repository_id, change_request_id, origin_url, request)
def redirect_to_console(self, installation_id, repository_id, pull_request_id, origin_url, request):
fn = 'github_models.redirect_to_console'
console_endpoint = cla.conf['CONTRIBUTOR_BASE_URL']
console_v2_endpoint = cla.conf['CONTRIBUTOR_V2_BASE_URL']
# Get repository using github's repository ID.
repository = Repository().get_repository_by_external_id(repository_id, "github")
if repository is None:
cla.log.warning(f'{fn} - Could not find repository with the following '
f'repository_id: {repository_id}')
return None
# Get project ID from this repository
project_id = repository.get_repository_project_id()
try:
project = get_project_instance()
project.load(str(project_id))
except DoesNotExist as err:
return {'errors': {'project_id': str(err)}}
user = self.get_or_create_user(request)
# Ensure user actually requires a signature for this project.
# TODO: Skipping this for now - we can do this for ICLAs but there's no easy way of doing
# the check for CCLAs as we need to know in advance what the company_id is that we're checking
# the CCLA signature for.
# We'll have to create a function that fetches the latest CCLA regardless of company_id.
# icla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user)
# ccla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user, company_id=?)
# try:
# document = cla.utils.get_project_latest_individual_document(project_id)
# except DoesNotExist:
# cla.log.debug('No ICLA for project %s' %project_id)
# if signature is not None and \
# signature.get_signature_document_major_version() == document.get_document_major_version():
# return cla.utils.redirect_user_by_signature(user, signature)
# Store repository and PR info so we can redirect the user back later.
cla.utils.set_active_signature_metadata(user.get_user_id(), project_id, repository_id, pull_request_id)
console_url = ''
# Temporary condition until all CLA Groups are ready for the v2 Contributor Console
if project.get_version() == 'v2':
# Generate url for the v2 console
console_url = 'https://' + console_v2_endpoint + \
'/#/cla/project/' + project_id + \
'/user/' + user.get_user_id() + \
'?redirect=' + origin_url
cla.log.debug(f'{fn} - redirecting to v2 console: {console_url}...')
else:
# Generate url for the v1 contributor console
console_url = 'https://' + console_endpoint + \
'/#/cla/project/' + project_id + \
'/user/' + user.get_user_id() + \
'?redirect=' + origin_url
cla.log.debug(f'{fn} - redirecting to v1 console: {console_url}...')
raise falcon.HTTPFound(console_url)
def _fetch_token(self, client_id, state, token_url, client_secret,
code): # pylint: disable=too-many-arguments,no-self-use
"""
Mockable method to fetch a OAuth2Session token.
"""
return cla.utils.fetch_token(client_id, state, token_url, client_secret, code)
def sign_workflow(self, installation_id, github_repository_id, pull_request_number, request):
"""
Once we have the 'github_oauth2_token' value in the user's session, we can initiate the
signing workflow.
"""
fn = 'sign_workflow'
cla.log.warning(f'{fn} - Initiating GitHub signing workflow for '
f'GitHub repo {github_repository_id} '
f'with PR: {pull_request_number}')
user = self.get_or_create_user(request)
signature = cla.utils.get_user_signature_by_github_repository(installation_id, user)
project_id = cla.utils.get_project_id_from_installation_id(installation_id)
document = cla.utils.get_project_latest_individual_document(project_id)
if signature is not None and \
signature.get_signature_document_major_version() == document.get_document_major_version():
return cla.utils.redirect_user_by_signature(user, signature)
else:
# Signature not found or older version, create new one and send user to sign.
cla.utils.request_individual_signature(installation_id, github_repository_id, user, pull_request_number)
def process_opened_pull_request(self, data):
"""
Helper method to handle a webhook fired from GitHub for an opened PR.
:param data: The data returned from GitHub on this webhook.
:type data: dict
"""
pull_request_id = data['pull_request']['number']
github_repository_id = data['repository']['id']
installation_id = data['installation']['id']
self.update_change_request(installation_id, github_repository_id, pull_request_id)
def process_easycla_command_comment(self, data):
"""
Processes easycla command comment if present
:param data: github issue comment webhook event payload : https://docs.github.com/en/free-pro-team@latest/developers/webhooks-and-events/webhook-events-and-payloads#issue_comment
:return:
"""
comment_str = data.get("comment", {}).get("body", "")
if not comment_str:
raise ValueError("missing comment body, ignoring the message")
if "/easycla" not in comment_str.split():
raise ValueError(f'unsupported comment supplied: {comment_str.split()}, '
'currently only the \'/easycla\' command is supported')
github_repository_id = data.get('repository', {}).get('id', None)
if not github_repository_id:
raise ValueError("missing github repository id in pull request comment")
cla.log.debug(f"comment trigger for github_repo : {github_repository_id}")
# turns out pull request id and issue is the same thing
pull_request_id = data.get("issue", {}).get("number", None)
if not pull_request_id:
raise ValueError("missing pull request id ")
cla.log.debug(f"comment trigger for pull_request_id : {pull_request_id}")
cla.log.debug("installation object : ", data.get('installation', {}))
installation_id = data.get('installation', {}).get('id', None)
if not installation_id:
raise ValueError("missing installation id in pull request comment")
cla.log.debug(f"comment trigger for installation_id : {installation_id}")
self.update_change_request(installation_id, github_repository_id, pull_request_id)
def get_return_url(self, github_repository_id, change_request_id, installation_id):
pull_request = self.get_pull_request(github_repository_id, change_request_id, installation_id)
return pull_request.html_url
def update_change_request(self, installation_id, github_repository_id, change_request_id):
fn = 'update_change_request'
# Queries GH for the complete pull request details, see:
# https://developer.github.com/v3/pulls/#response-1
try:
# check if change_request_id is a valid int
_ = int(change_request_id)
pull_request = self.get_pull_request(github_repository_id, change_request_id, installation_id)
except ValueError:
cla.log.error(f'{fn} - Invalid PR: {change_request_id} . (Unable to cast to integer) ')
return
cla.log.debug(f'{fn} - retrieved pull request: {pull_request}')
# Get all unique users/authors involved in this PR - returns a list of
# (commit_sha_string, (author_id, author_username, author_email) tuples
commit_authors = get_pull_request_commit_authors(pull_request)
try:
# Get existing repository info using the repository's external ID,
# which is the repository ID assigned by github.
cla.log.debug(f'{fn} - PR: {pull_request.number}, Loading GitHub repository by id: {github_repository_id}')
repository = Repository().get_repository_by_external_id(github_repository_id, "github")
if repository is None:
cla.log.warning(f'{fn} - PR: {pull_request.number}, Failed to load GitHub repository by '
f'id: {github_repository_id} in our DB - repository reference is None - '
'Is this org/repo configured in the Project Console?'
' Unable to update status.')
return
except DoesNotExist:
cla.log.warning(f'{fn} - PR: {pull_request.number}, could not find repository with the '
f'repository ID: {github_repository_id}')
cla.log.warning(f'{fn} - PR: {pull_request.number}, failed to update change request of '
f'repository {github_repository_id} - returning')
return
# Get Github Organization name that the repository is configured to.
organization_name = repository.get_repository_organization_name()
cla.log.debug(f'{fn} - PR: {pull_request.number}, determined github organization is: {organization_name}')
# Check that the Github Organization exists.
github_org = GitHubOrg()
try:
github_org.load(organization_name)
except DoesNotExist:
cla.log.warning(f'{fn} - PR: {pull_request.number}, Could not find Github Organization '
f'with the following organization name: {organization_name}')
cla.log.warning(f'{fn}- PR: {pull_request.number}, Failed to update change request of '
f'repository {github_repository_id} - returning')
return
# Ensure that installation ID for this organization matches the given installation ID
if github_org.get_organization_installation_id() != installation_id:
cla.log.warning(f'{fn} - PR: {pull_request.number}, '
f'the installation ID: {github_org.get_organization_installation_id()} '
f'of this organization does not match installation ID: {installation_id} '
'given by the pull request.')
cla.log.error(f'{fn} - PR: {pull_request.number}, Failed to update change request '
f'of repository {github_repository_id} - returning')
return
# Retrieve project ID from the repository.
project_id = repository.get_repository_project_id()
project = get_project_instance()
project.load(str(project_id))
# Find users who have signed and who have not signed.
signed = []
missing = []
cla.log.debug(f'{fn} - PR: {pull_request.number}, scanning users - '
'determining who has signed a CLA an who has not.')
for commit_sha, author_info in commit_authors:
# Extract the author info tuple details
if author_info:
author_id = author_info[0]
author_username = author_info[1]
author_email = author_info[2]
cla.log.debug(f'{fn} - PR: {pull_request.number}, '
f'processing sha: {commit_sha} '
f'from author id: {author_id}, username: {author_username}, email: {author_email}')
else:
cla.log.debug(
f'{fn} - PR: {pull_request.number}, processing sha: {commit_sha} with invalid author details')
handle_commit_from_user(project, commit_sha, author_info, signed, missing)
cla.log.debug(f'{fn} - PR: {pull_request.number}, '
f'updating github pull request for repo: {github_repository_id}, '
f'with signed authors: {signed} '
f'with missing authors: {missing}')
repository_name = repository.get_repository_name()
update_pull_request(
installation_id=installation_id,
github_repository_id=github_repository_id,
pull_request=pull_request,
repository_name=repository_name,
signed=signed,
missing=missing,
project_version=project.get_version())
def get_pull_request(self, github_repository_id, pull_request_number, installation_id):
"""
Helper method to get the pull request object from GitHub.
:param github_repository_id: The ID of the GitHub repository.
:type github_repository_id: int
:param pull_request_number: The number (not ID) of the GitHub PR.
:type pull_request_number: int
:param installation_id: The ID of the GitHub application installed on this repository.
:type installation_id: int | None
"""
cla.log.debug('Getting PR %s from GitHub repository %s', pull_request_number, github_repository_id)
if self.client is None:
self.client = get_github_integration_client(installation_id)
repo = self.client.get_repo(int(github_repository_id))
try:
return repo.get_pull(int(pull_request_number))
except UnknownObjectException:
cla.log.error('Could not find pull request %s for repository %s - ensure it '
'exists and that your personal access token has the "repo" scope enabled',
pull_request_number, github_repository_id)
except BadCredentialsException as err:
cla.log.error('Invalid GitHub credentials provided: %s', str(err))
def get_or_create_user(self, request):
"""
Helper method to either get or create a user based on the GitHub request made.
:param request: The hug request object for this API call.
:type request: Request
"""
fn = 'github_models.get_or_create_user'
session = self._get_request_session(request)
github_user = self.get_user_data(session, os.environ['GH_OAUTH_CLIENT_ID'])
if 'error' in github_user:
# Could not get GitHub user data - maybe user revoked CLA app permissions?
session = self._get_request_session(request)
del session['github_oauth2_state']
del session['github_oauth2_token']
cla.log.warning(f'{fn} - Deleted OAuth2 session data - retrying token exchange next time')
raise falcon.HTTPError('400 Bad Request', 'github_oauth2_token',
'Token permissions have been rejected, please try again')
emails = self.get_user_emails(session, os.environ['GH_OAUTH_CLIENT_ID'])
if len(emails) < 1:
cla.log.warning(f'{fn} - GitHub user has no verified email address: %s (%s)',
github_user['name'], github_user['login'])
raise falcon.HTTPError(
'412 Precondition Failed', 'email',
'Please verify at least one email address with GitHub')
cla.log.debug(f'{fn} - Trying to load GitHub user by GitHub ID: %s', github_user['id'])
users = cla.utils.get_user_instance().get_user_by_github_id(github_user['id'])
if users is not None:
# Users search can return more than one match - so it's an array - we set the first record value for now??
user = users[0]
cla.log.debug(f'{fn} - Loaded GitHub user by GitHub ID: %s - %s (%s)',
user.get_user_name(),
user.get_user_emails(),
user.get_user_github_id())
# update/set the github username if available
cla.utils.update_github_username(github_user, user)
user.set_user_emails(emails)
user.save()
return user
# User not found by GitHub ID, trying by email.
cla.log.debug(f'{fn} - Could not find GitHub user by GitHub ID: %s', github_user['id'])
# TODO: This is very slow and needs to be improved - may need a DB schema change.
users = None
user = cla.utils.get_user_instance()
for email in emails:
users = user.get_user_by_email(email)
if users is not None:
break
if users is not None:
# Users search can return more than one match - so it's an array - we set the first record value for now??
user = users[0]
# Found user by email, setting the GitHub ID
user.set_user_github_id(github_user['id'])
# update/set the github username if available
cla.utils.update_github_username(github_user, user)
user.set_user_emails(emails)
user.save()
cla.log.debug(f'{fn} - Loaded GitHub user by email: {user}')
return user
# User not found, create.
cla.log.debug(f'{fn} - Could not find GitHub user by email: {emails}')
cla.log.debug(f'{fn} - Creating new GitHub user {github_user['name']} - '
f'({github_user['id']}/{github_user['login']}), '
f'emails: {emails}')
user = cla.utils.get_user_instance()
user.set_user_id(str(uuid.uuid4()))
user.set_user_emails(emails)
user.set_user_name(github_user['name'])
user.set_user_github_id(github_user['id'])
user.set_user_github_username(github_user['login'])
user.save()
return user
def get_user_data(self, session, client_id): # pylint: disable=no-self-use
"""
Mockable method to get user data. Returns all GitHub user data we have
on the user based on the current OAuth2 session.
:param session: The current user session.
:type session: dict
:param client_id: The GitHub OAuth2 client ID.
:type client_id: string
"""
fn = 'cla.models.github_models.get_user_data'
token = session.get('github_oauth2_token')
if token is None:
cla.log.error(f'{fn} - unable to load github_oauth2_token from session, session is: {session}')
return {'error': 'could not get user data from session'}
oauth2 = OAuth2Session(client_id, token=token)
request = oauth2.get('https://api.github.com/user')
github_user = request.json()
cla.log.debug(f'{fn} - GitHub user data: %s', github_user)
if 'message' in github_user:
cla.log.error(f'{fn} - Could not get user data with OAuth2 token: {github_user['message']}')
return {'error': 'Could not get user data: %s' % github_user['message']}
return github_user
def get_user_emails(self, session: dict, client_id: str) -> Union[List[str], dict]: # pylint: disable=no-self-use
"""
Mockable method to get all user emails based on OAuth2 session.
:param session: The current user session.
:type session: dict
:param client_id: The GitHub OAuth2 client ID.
:type client_id: string
"""
emails = self._fetch_github_emails(session=session, client_id=client_id)
cla.log.debug('GitHub user emails: %s', emails)
if 'error' in emails:
return emails
verified_emails = [item['email'] for item in emails if item['verified']]
excluded_emails = [email for email in verified_emails
if any([email.endswith(e) for e in EXCLUDE_GITHUB_EMAILS])]
included_emails = [email for email in verified_emails
if not any([email.endswith(e) for e in EXCLUDE_GITHUB_EMAILS])]
if len(included_emails) > 0:
return included_emails
# something we're not very happy about but probably it can happen
return excluded_emails
def get_primary_user_email(self, request) -> Union[Optional[str], dict]:
"""
gets the user primary email from the registered emails from the github api
"""
fn = 'github_models.get_primary_user_email'
try:
cla.log.debug(f'{fn} - fetching Github primary email')
session = self._get_request_session(request)
client_id = os.environ['GH_OAUTH_CLIENT_ID']
emails = self._fetch_github_emails(session=session, client_id=client_id)
if "error" in emails:
return None
for email in emails:
if email.get("verified", False) and email.get("primary", False):
return email["email"]
except Exception as e:
cla.log.warning(f'{fn} - lookup failed - {e} - returning None')
return None
return None
def _fetch_github_emails(self, session: dict, client_id: str) -> Union[List[dict], dict]:
"""
Method is responsible for fetching the user emails from /user/emails endpoint
:param session:
:param client_id:
:return:
"""
fn = 'github_models._fetch_github_emails' # function name
# Use the user's token to fetch their public email(s) - don't use the system token as this endpoint won't work
# as expected
token = session.get('github_oauth2_token')
if token is None:
cla.log.warning(f'{fn} - unable to load github_oauth2_token from the session - session is empty')
oauth2 = OAuth2Session(client_id, token=token)
request = oauth2.get('https://api.github.com/user/emails')
resp = request.json()
if 'message' in resp:
cla.log.warning(f'{fn} - could not get user emails with OAuth2 token: {resp['message']}')
return {'error': 'Could not get user emails: %s' % resp['message']}
return resp
def process_reopened_pull_request(self, data):
"""
Helper method to process a re-opened GitHub PR.
Simply calls the self.process_opened_pull_request() method with the data provided.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
return self.process_opened_pull_request(data)
def process_closed_pull_request(self, data):
"""
Helper method to process a closed GitHub PR.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
pass
def process_synchronized_pull_request(self, data):
"""
Helper method to process a synchronized GitHub PR.
Should be called when a new commit comes through on the PR.
Simply calls the self.process_opened_pull_request() method with the data provided.
This should re-check all commits for author information.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
return self.process_opened_pull_request(data)
def create_repository(data):
"""
Helper method to create a repository object in the CLA database given PR data.
:param data: The data provided by the GitHub webhook.
:type data: dict
:return: The newly created repository object - already in the DB.
:rtype: cla.models.model_interfaces.Repository
"""
try:
repository = cla.utils.get_repository_instance()
repository.set_repository_id(str(uuid.uuid4()))
# TODO: Need to use an ID unique across all repository providers instead of namespace.
full_name = data['repository']['full_name']
namespace = full_name.split('/')[0]
repository.set_repository_project_id(namespace)
repository.set_repository_external_id(data['repository']['id'])
repository.set_repository_name(full_name)
repository.set_repository_type('github')
repository.set_repository_url(data['repository']['html_url'])
repository.save()
return repository
except Exception as err:
cla.log.warning('Could not create GitHub repository automatically: %s', str(err))
return None
def handle_commit_from_user(project, commit_sha, author_info, signed, missing): # pylint: disable=too-many-arguments
"""
Helper method to triage commits between signed and not-signed user signatures.
:param project: The project model for this github PR organization.
:type project: Project
:param commit_sha: Commit has as a string
:type commit_sha: string
:param author_info: the commit author details, including id, name, email (if available)
:type author_info: tuple of (author_id, author_username, author_email)
:param signed: Reference to a list of signed authors so far. Should be modified
in-place to add a signer if found.
:type signed: list of strings
:param missing: Reference to a list of authors who have not signed yet.
Should be modified in-place to add a missing signer if found.
:type missing: list of strings
"""
# handle edge case of non existant users
if author_info is None:
missing.append((commit_sha, []))
return
# Extract the author_info tuple details
author_id = author_info[0]
author_username = author_info[1]
author_email = author_info[2]
cla.log.debug(f'Looking up GitHub user (author_id: {author_id}, '
f'author_username: {author_username}, '
f'auth_email: {author_email})')
# attempt to lookup the user in our database by GH id -
# may return multiple users that match this author_id
users = cla.utils.get_user_instance().get_user_by_github_id(author_id)
if users is None:
# GitHub user not in system yet, signature does not exist for this user.
cla.log.debug(f'GitHub user (id: {author_id}, '
f'user: {author_username}, '
f'email: {author_email}) lookup by github id not found in our database, '
'attempting to looking up user by email...')
# Try looking up user by email as a fallback
users = cla.utils.get_user_instance().get_user_by_email(author_email)
# Got one or more records by searching the email
if users is not None:
cla.log.debug(f'Found {len(users)} GitHub user(s) matching github email: {author_email}')
for user in users:
cla.log.debug(f'GitHub user found in our database: {user}')
# For now, accept non-github users as legitimate users.
# Does this user have a signed signature for this project? If so, add to the signed list and return,
# no reason to continue looking
if cla.utils.user_signed_project_signature(user, project):
signed.append((commit_sha, author_username))
return
# Didn't find a signed signature for this project - add to our missing bucket list
# author_info consists of: [author_id, author_username, author_email]
missing.append((commit_sha, list(author_info)))
else:
# Not seen this user before - no record on file in our user's database
cla.log.debug(f'GitHub user (id: {author_id}, '
f'user: {author_username}, '
f'email: {author_email}) lookup by email in our database failed - not found')
# This bit of logic below needs to be reconsidered - query logic takes a very long time for large
# projects like CNCF which significantly delays updating the GH PR status.
# Revisit once we add more indexes to the table
# # Check to see if not found user is whitelisted to assist in triaging github comment
# # Search for the CCLA signatures for this project - wish we had a company ID to restrict the query...
# signatures = cla.utils.get_signature_instance().get_signatures_by_project(
# project.get_project_id(),
# signature_signed=True,
# signature_approved=True,
# signature_reference_type='company')
#
# list_author_info = list(author_info)
# for signature in signatures:
# if cla.utils.is_whitelisted(
# signature,
# email=author_email,
# github_id=author_id,
# github_username=author_username
# ):
# # Append whitelisted flag to the author info list
# cla.log.debug(f'Github user(id:{author_id}, '
# f'user: {author_username}, '
# f'email {author_email}) is whitelisted but not a CLA user')
# list_author_info.append(True)
# break
# missing.append((commit_sha, list_author_info))
# For now - we'll just return the author info as a list without the flag to indicate that they have been on
# the approved list for any company/signature
# author_info consists of: [author_id, author_username, author_email]
missing.append((commit_sha, list(author_info)))
else:
cla.log.debug(f'Found {len(users)} GitHub user(s) matching github id: {author_id} in our database')
if len(users) > 1:
cla.log.warning(f'more than 1 user found in our user database - user: {users} - '
f'will ONLY evaluate the first one')
# Just review the first user that we were able to fetch from our DB
user = users[0]
cla.log.debug(f'GitHub user found in our database: {user}')
# Does this user have a signed signature for this project? If so, add to the signed list and return,
# no reason to continue looking
if cla.utils.user_signed_project_signature(user, project):
signed.append((commit_sha, author_username))
return
list_author_info = list(author_info)
# If the user does not have a company ID assigned, then they have not been associated with a company as
# part of the Contributor console workflow
if user.get_user_company_id() is None:
missing.append((commit_sha, list_author_info))
return
# Perform a specific search for the user's project + company + CCLA
signatures = cla.utils.get_signature_instance().get_signatures_by_project(
project_id=project.get_project_id(),
signature_signed=True,
signature_approved=True,
signature_type='ccla',
signature_reference_type='company',
signature_reference_id=user.get_user_company_id(),
signature_user_ccla_company_id=None,
)
# Should only return one signature record
cla.log.debug(f'Found {len(signatures)} CCLA signatures for company: {user.get_user_company_id()}, '
f'project: {project.get_project_id()} in our database.')
# Should never happen - warn if we see this
if len(signatures) > 1:
cla.log.warning(f'more than 1 CCLA signature record found in our database - signatures: {signatures}')
for signature in signatures:
if cla.utils.is_approved(
signature,
email=author_email,
github_id=author_id,
github_username=author_username
):
# Append whitelisted flag to the author info list
cla.log.debug(f'Github user(id:{author_id}, '
f'user: {author_username}, '
f'email {author_email}) is on the approved list, '
'but not affiliated with a company')
list_author_info.append(True)
break
missing.append((commit_sha, list_author_info))
def get_pull_request_commit_authors(pull_request):
"""
Helper function to extract all committer information for a GitHub PR.
For pull_request data model, see:
https://developer.github.com/v3/pulls/
For commits on a pull request, see:
https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
For activity callback, see:
https://developer.github.com/v3/activity/events/types/#pullrequestevent
:param pull_request: A GitHub pull request to examine.
:type pull_request: GitHub.PullRequest
:return: A list of tuples containing a tuple of (commit_sha_string, (author_id, author_username, author_email)) -
the second item is another tuple of author info.
:rtype: [(commit_sha_string, (author_id, author_username, author_email)]
"""
cla.log.debug('Querying pull request commits for author information...')
commit_authors = []
for commit in pull_request.get_commits():
cla.log.debug('Processing commit while looking for authors, commit: {}'.format(commit.sha))
# Note: we can get the author info in two different ways:
if commit.author:
try:
# commit.author is a github.NamedUser.NamedUser type object
# https://pygithub.readthedocs.io/en/latest/github_objects/NamedUser.html
if commit.author.name is not None:
cla.log.debug('PR: {}, GitHub commit.author.name author found for commit SHA {}, '
'author id: {}, name: {}, email: {}'.
format(pull_request.number, commit.sha, commit.author.id,
commit.author.name, commit.author.email))
commit_authors.append((commit.sha, (commit.author.id, commit.author.name, commit.author.email)))
elif commit.author.login is not None:
cla.log.debug('PR: {}, GitHub commit.author.login author found for commit SHA {}, '
'author id: {}, login: {}, email: {}'.
format(pull_request.number, commit.sha, commit.author.id,
commit.author.login, commit.author.email))
commit_authors.append((commit.sha, (commit.author.id, commit.author.login, commit.author.email)))
else:
cla.log.debug(f'PR: {pull_request.number}, GitHub commit.author.name and commit.author.login '
f'author information NOT found for commit SHA {commit.sha}, '
f'author id: {commit.author.id}, '
f'name: {commit.author.name}, '
f'login: {commit.author.login}, '
f'email: {commit.author.email}')
commit_authors.append((commit.sha, None))
except (GithubException, IncompletableObject) as ex:
cla.log.debug(f'Commit sha: {commit.sha} exception: {ex}')
try:
cla.log.debug('github.GitAuthor.GitAuthor object: {}'.format(commit.commit.author))
# commit.commit.author is a github.GitAuthor.GitAuthor object type - object
# only has date, name and email attributes - no ID attribute/value
# https://pygithub.readthedocs.io/en/latest/github_objects/GitAuthor.html
cla.log.debug('PR: {}, GitHub NamedUser author NOT found for commit SHA {}, '
'however, found GitAuthor author id: None, name: {}, email: {}'.
format(pull_request.number, commit.sha,
commit.commit.author.name, commit.commit.author.email))
commit_authors.append((commit.sha, (None, commit.commit.author.name, commit.commit.author.email)))
except (GithubException, IncompletableObject):
cla.log.warning(
'PR: {}, could not find any commit author for SHA {}'.format(pull_request.number, commit.sha))
commit_authors.append((commit.sha, None))
else:
cla.log.warning('PR: {}, could not find any commit author for SHA {}'.
format(pull_request.number, commit.sha))
commit_authors.append((commit.sha, None))
return commit_authors
def has_check_previously_failed(pull_request: PullRequest):
"""
Review the status updates in the PR. Identify 1 or more previous failed
updates from the EasyCLA bot. If we fine one, return True with the comment, otherwise
return False, None
:param pull_request: the GitHub pull request object
:return: True with the comment if the EasyCLA bot check previously failed, otherwise return False, None
"""
comments = pull_request.get_issue_comments()
# Look through all the comments
for comment in comments:
# Our bot comments include the following text
# A previously failed check has 'not authorized' somewhere in the body
if 'is not authorized under a signed CLA' in comment.body:
return True, comment
if 'they must confirm their affiliation' in comment.body:
return True, comment
if 'CLA Missing ID' in comment.body and 'is missing the User' in comment.body:
return True, comment
return False, None
def update_pull_request(installation_id, github_repository_id, pull_request, repository_name, signed,
missing, project_version): # pylint: disable=too-many-locals
"""
Helper function to update a PR's comment and status based on the list of signers.
:param installation_id: The ID of the GitHub installation
:type installation_id: int
:param github_repository_id: The ID of the GitHub repository this PR belongs to.
:type github_repository_id: int
:param pull_request: The GitHub PullRequest object for this PR.
:type pull_request: GitHub.PullRequest
:param repository_name: The GitHub repository name for this PR.
:type repository_name: string
:param signed: The list of (commit hash, author name) tuples that have signed an
signature for this PR.
:type signed: [(string, string)]
:param missing: The list of (commit hash, author name) tuples that have not signed
an signature for this PR.
:type missing: [(string, list)]
:param project_version: Project version associated with PR
:type missing: string
"""
notification = cla.conf['GITHUB_PR_NOTIFICATION']
both = notification == 'status+comment' or notification == 'comment+status'
last_commit = pull_request.get_commits().reversed[0]
# Here we update the PR status by adding/updating the PR body - this is the way the EasyCLA app
# knows if it is pass/fail.
# Create check run for users that haven't yet signed and/or affiliated
if missing:
text = ""
for authors in missing:
# Check for valid github id
if authors[1] is None or (authors[1] and authors[1][0] is None):
help_url = "https://help.github.com/en/github/committing-changes-to-your-project/why-are-my-commits-linked-to-the-wrong-user"
else:
help_url = cla.utils.get_full_sign_url('github', str(installation_id), github_repository_id,
pull_request.number, project_version)
client = GitHubInstallation(installation_id)
# check if unsigned user is whitelisted
commit_sha = authors[0]
if commit_sha != last_commit.sha:
continue
if authors[1]:
author_email = authors[1][2]
author_id = authors[1][0]
if author_id:
if len(authors[1]) == 4:
text += f'{author_email} must confirm corporate affiliation.\n'
else:
text += f'{author_email} is not authorized under a signed CLA.\n'
else:
text += f'{author_email} is not linked to this commit. \n'
else:
text += 'Invalid author details. \n'
payload = {
"name": "CLA check",
"head_sha": last_commit.sha,
"status": "completed",
"conclusion": "action_required",
"details_url": help_url,
"output": {
"title": "EasyCLA: Signed CLA not found",
"summary": "One or more committers are authorized under a signed CLA.",
"text": text,
},
}
client.create_check_run(repository_name, json.dumps(payload))
# Update the comment
if both or notification == 'comment':
body = cla.utils.assemble_cla_comment('github', str(installation_id), github_repository_id, pull_request.number,
signed, missing, project_version)
previously_failed, comment = has_check_previously_failed(pull_request)
if not missing:
# After Issue #167 wsa in place, they decided via Issue #289 that we
# DO want to update the comment, but only after we've previously failed
if previously_failed:
cla.log.debug('Found previously failed checks - updating CLA comment in PR.')
comment.edit(body)
cla.log.debug('EasyCLA App checks pass for PR: {} with authors: {}'.format(pull_request.number, signed))
else:
# Per Issue #167, only add a comment if check fails
# update_cla_comment(pull_request, body)
if previously_failed:
cla.log.debug('Found previously failed checks - updating CLA comment in PR.')
comment.edit(body)
else:
pull_request.create_issue_comment(body)
cla.log.debug('EasyCLA App checks fail for PR: {}. CLA signatures with signed authors: {} and '
'with missing authors: {}'.format(pull_request.number, signed, missing))
if both or notification == 'status':
context_name = os.environ.get('GH_STATUS_CTX_NAME')
if context_name is None:
context_name = 'communitybridge/cla'
# if we have ANY committers who have failed the check - update the status with overall failure
if missing is not None and len(missing) > 0:
state = 'failure'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=False)
sign_url = cla.utils.get_full_sign_url(
'github', str(installation_id), github_repository_id, pull_request.number, project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
elif signed is not None and len(signed) > 0:
state = 'success'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=True)
sign_url = cla.conf["CLA_LANDING_PAGE"] # Remove this once signature detail page ready.
sign_url = os.path.join(sign_url, "#/")
sign_url = append_project_version_to_url(address=sign_url, project_version=project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
else:
# error condition - should have a least one committer and they would be in one of the above
# lists: missing or signed
state = 'failure'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=False)
sign_url = cla.utils.get_full_sign_url(
'github', str(installation_id), github_repository_id, pull_request.number, project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
cla.log.warning('This is an error condition - should have at least one committer in one of these lists: '
f'{len(signed)} passed, {missing}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
def create_commit_status(pull_request, commit_hash, state, sign_url, body, context):
"""
Helper function to create a pull request commit status message given the PR and commit hash.
:param pull_request: The GitHub Pull Request object.
:type pull_request: github.PullRequest
:param commit_hash: The commit hash to post a status on.
:type commit_hash: string
:param state: The state of the status.
:type state: string
:param sign_url: The link the user will be taken to when clicking on the status message.
:type sign_url: string
:param body: The contents of the status message.
:type body: string
"""
try:
commit_obj = None
for commit in pull_request.get_commits():
if commit.sha == commit_hash:
commit_obj = commit
break
if commit_obj is None:
cla.log.error(f'Could not post status {state} on '
f'PR: {pull_request.number}, '
f'Commit: {commit_hash} not found')
return
# context is a string label to differentiate one signer status from another signer status.
# committer name is used as context label
cla.log.info(f'Updating status with state \'{state}\' on PR {pull_request.number} for commit {commit_hash}...')
# returns github.CommitStatus.CommitStatus
resp = commit_obj.create_status(state, sign_url, body, context)
cla.log.info(f'Successfully posted status \'{state}\' on PR {pull_request.number}: Commit {commit_hash} '
f'with SignUrl : {sign_url} with response: {resp}')
except GithubException as exc:
cla.log.error(f'Could not post status \'{state}\' on PR: {pull_request.number}, '
f'Commit: {commit_hash}, '
f'Response Code: {exc.status}, '
f'Message: {exc.data}')
# def update_cla_comment(pull_request, body):
# """
# Helper function to create/edit a comment on the GitHub PR.
#
# :param pull_request: The PR object in question.
# :type pull_request: GitHub.PullRequest
# :param body: The contents of the comment.
# :type body: string
# """
# comment = get_existing_cla_comment(pull_request)
# if comment is not None:
# cla.log.debug(f'Updating existing CLA comment for PR: {pull_request.number} with body: {body}')
# comment.edit(body)
# else:
# cla.log.debug(f'Creating a new CLA comment for PR: {pull_request.number} with body: {body}')
# pull_request.create_issue_comment(body)
# def get_existing_cla_comment(pull_request):
# """
# Helper function to get an existing comment from the CLA system in a GitHub PR.
#
# :param pull_request: The PR object in question.
# :type pull_request: GitHub.PullRequest
# """
# comments = pull_request.get_issue_comments()
# for comment in comments:
# if '[
# return comment
def get_github_integration_client(installation_id):
"""
GitHub App integration client used for authenticated client actions through an installed app.
"""
return GitHubInstallation(installation_id).api_object
def get_github_client(organization_id):
github_org = cla.utils.get_github_organization_instance()
github_org.load(organization_id)
installation_id = github_org.get_organization_installation_id()
return get_github_integration_client(installation_id)
class MockGitHub(GitHub):
"""
The GitHub repository service mock class for testing.
"""
def __init__(self, oauth2_token=False):
super().__init__()
self.oauth2_token = oauth2_token
def _get_github_client(self, username, token):
return MockGitHubClient(username, token)
def _get_authorization_url_and_state(self, client_id, redirect_uri, scope, authorize_url):
authorization_url = 'http://authorization.url'
state = 'random-state-here'
return authorization_url, state
def _fetch_token(self, client_id, state, token_url, client_secret, code): # pylint: disable=too-many-arguments
return 'random-token'
def _get_request_session(self, request) -> dict:
if self.oauth2_token:
return {'github_oauth2_token': 'random-token',
'github_oauth2_state': 'random-state',
'github_origin_url': 'http://github/origin/url',
'github_installation_id': 1}
return {}
def get_user_data(self, session, client_id) -> dict:
return {'email': 'test@user.com', 'name': 'Test User', 'id': 123}
def get_user_emails(self, session, client_id):
return [{'email': 'test@user.com', 'verified': True, 'primary': True, 'visibility': 'public'}]
def get_pull_request(self, github_repository_id, pull_request_number, installation_id):
return MockGitHubPullRequest(pull_request_number)
class MockGitHubClient(object): # pylint: disable=too-few-public-methods
"""
The GitHub Client object mock class for testing.
"""
def __init__(self, username, token):
self.username = username
self.token = token
def get_repo(self, repository_id): # pylint: disable=no-self-use
"""
Mock version of the GitHub Client object's get_repo method.
"""
return MockGitHubRepository(repository_id)
class MockGitHubRepository(object): # pylint: disable=too-few-public-methods
"""
The GitHub Repository object mock class for testing.
"""
def __init__(self, repository_id):
self.id = repository_id
def get_pull(self, pull_request_id): # pylint: disable=no-self-use
"""
Mock version of the GitHub Repository object's get_pull method.
"""
return MockGitHubPullRequest(pull_request_id)
class MockGitHubPullRequest(object): # pylint: disable=too-few-public-methods
"""
The GitHub PullRequest object mock class for testing.
"""
def __init__(self, pull_request_id):
self.number = pull_request_id
self.html_url = 'http://test-github.com/user/repo/' + str(self.number)
def get_commits(self): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's get_commits method.
"""
lst = MockPaginatedList()
lst._elements = [MockGitHubCommit()] # pylint: disable=protected-access
return lst
def get_issue_comments(self): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's get_issue_comments method.
"""
return [MockGitHubComment()]
def create_issue_comment(self, body): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's create_issue_comment method.
"""
pass
class MockGitHubComment(object): # pylint: disable=too-few-public-methods
"""
A GitHub mock issue comment object for testing.
"""
body = 'Test'
class MockPaginatedList(github.PaginatedList.PaginatedListBase): # pylint: disable=too-few-public-methods
"""Mock GitHub paginated list for testing purposes."""
def __init__(self):
super().__init__()
# Need to use our own elements list (self.__elements from PaginatedListBase does not
# work as expected).
self._elements = []
@property
def reversed(self):
"""Fake reversed property."""
return [MockGitHubCommit()]
def __iter__(self):
for element in self._elements:
yield element
class MockGitHubCommit(object): # pylint: disable=too-few-public-methods
"""
The GitHub Commit object mock class for testing.
"""
def __init__(self):
self.author = MockGitHubAuthor()
self.sha = 'sha-test-commit'
def create_status(self, state, sign_url, body):
"""
Mock version of the GitHub Commit object's create_status method.
"""
pass
class MockGitHubAuthor(object): # pylint: disable=too-few-public-methods
"""
The GitHub Author object mock class for testing.
"""
def __init__(self, author_id=1):
self.id = author_id
self.login = 'user'
self.email = 'user@github.com'
| # Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
"""
Holds the GitHub repository service.
"""
import json
import os
import uuid
from typing import List, Union, Optional
import falcon
import github
from github import PullRequest
from github.GithubException import UnknownObjectException, BadCredentialsException, GithubException, IncompletableObject
from requests_oauthlib import OAuth2Session
import cla
from cla.controllers.github_application import GitHubInstallation
from cla.models import repository_service_interface, DoesNotExist
from cla.models.dynamo_models import Repository, GitHubOrg
from cla.utils import get_project_instance, append_project_version_to_url
# some emails we want to exclude when we register the users
EXCLUDE_GITHUB_EMAILS = ["noreply.github.com"]
class GitHub(repository_service_interface.RepositoryService):
"""
The GitHub repository service.
"""
def __init__(self):
self.client = None
def initialize(self, config):
# username = config['GITHUB_USERNAME']
# token = config['GITHUB_TOKEN']
# self.client = self._get_github_client(username, token)
pass
def _get_github_client(self, username, token): # pylint: disable=no-self-use
return github.Github(username, token)
def get_repository_id(self, repo_name, installation_id=None):
"""
Helper method to get a GitHub repository ID based on repository name.
:param repo_name: The name of the repository, example: 'linuxfoundation/cla'.
:type repo_name: string
:param installation_id: The github installation id
:type installation_id: string
:return: The repository ID.
:rtype: integer
"""
if installation_id is not None:
self.client = get_github_integration_client(installation_id)
try:
return self.client.get_repo(repo_name).id
except github.GithubException as err:
cla.log.error('Could not find GitHub repository (%s), ensure it exists and that '
'your personal access token is configured with the repo scope', repo_name)
except Exception as err:
cla.log.error('Unknown error while getting GitHub repository ID for repository %s: %s',
repo_name, str(err))
def received_activity(self, data):
cla.log.debug('github_models.received_activity - Received GitHub activity: %s', data)
if 'pull_request' not in data:
cla.log.debug('github_models.received_activity - Activity not related to pull request - ignoring')
return {'message': 'Not a pull request - no action performed'}
if data['action'] == 'opened':
cla.log.debug('github_models.received_activity - Handling opened pull request')
return self.process_opened_pull_request(data)
elif data['action'] == 'reopened':
cla.log.debug('github_models.received_activity - Handling reopened pull request')
return self.process_reopened_pull_request(data)
elif data['action'] == 'closed':
cla.log.debug('github_models.received_activity - Handling closed pull request')
return self.process_closed_pull_request(data)
elif data['action'] == 'synchronize':
cla.log.debug('github_models.received_activity - Handling synchronized pull request')
return self.process_synchronized_pull_request(data)
else:
cla.log.debug('github_models.received_activity - Ignoring unsupported action: {}'.format(data['action']))
def sign_request(self, installation_id, github_repository_id, change_request_id, request):
"""
This method gets called when the OAuth2 app (NOT the GitHub App) needs to get info on the
user trying to sign. In this case we begin an OAuth2 exchange with the 'user:email' scope.
"""
fn = 'github_models.sign_request' # function name
cla.log.debug(f'{fn} - Initiating GitHub sign request for installation_id: {installation_id}, '
f'for repository {github_repository_id}, '
f'for PR: {change_request_id}')
# Not sure if we need a different token for each installation ID...
cla.log.debug(f'{fn} - Loading session from request: {request}...')
session = self._get_request_session(request)
cla.log.debug(f'{fn} - Adding github details to session: {session} which is type: {type(session)}...')
session['github_installation_id'] = installation_id
session['github_repository_id'] = github_repository_id
session['github_change_request_id'] = change_request_id
cla.log.debug(f'{fn} - Determining return URL from the inbound request...')
origin_url = self.get_return_url(github_repository_id, change_request_id, installation_id)
cla.log.debug(f'{fn} - Return URL from the inbound request is {origin_url}')
session['github_origin_url'] = origin_url
cla.log.debug(f'{fn} - Stored origin url in session as session["github_origin_url"] = {origin_url}')
if 'github_oauth2_token' in session:
cla.log.debug(f'{fn} - Using existing session GitHub OAuth2 token')
return self.redirect_to_console(
installation_id, github_repository_id, change_request_id,
origin_url, request)
else:
cla.log.debug(f'{fn} - No existing GitHub OAuth2 token - building authorization url and state')
authorization_url, state = self.get_authorization_url_and_state(installation_id,
github_repository_id,
int(change_request_id),
['user:email'])
cla.log.debug(f'{fn} - Obtained GitHub OAuth2 state from authorization - storing state in the session...')
session['github_oauth2_state'] = state
cla.log.debug(f'{fn} - GitHub OAuth2 request with state {state} - sending user to {authorization_url}')
raise falcon.HTTPFound(authorization_url)
def _get_request_session(self, request) -> dict: # pylint: disable=no-self-use
"""
Mockable method used to get the current user session.
"""
fn = 'cla.models.github_models._get_request_session'
session = request.context.get('session')
if session is None:
cla.log.warning(f'Session is empty for request: {request}')
cla.log.debug(f'{fn} - loaded session: {session}')
# Ensure session is a dict - getting issue where session is a string
if isinstance(session, str):
# convert string to a dict
cla.log.debug(f'{fn} - session is type: {type(session)} - converting to dict...')
session = json.loads(session)
# Reset the session now that we have converted it to a dict
request.context['session'] = session
cla.log.debug(f'{fn} - session: {session} which is now type: {type(session)}...')
return session
def get_authorization_url_and_state(self, installation_id, github_repository_id, pull_request_number, scope):
"""
Helper method to get the GitHub OAuth2 authorization URL and state.
This will be used to get the user's emails from GitHub.
:TODO: Update comments.
:param repository_id: The ID of the repository this request was initiated in.
:type repository_id: int
:param pull_request_number: The PR number this request was generated in.
:type pull_request_number: int
:param scope: The list of OAuth2 scopes to request from GitHub.
:type scope: [string]
"""
# Get the PR's html_url property.
# origin = self.get_return_url(github_repository_id, pull_request_number, installation_id)
# Add origin to user's session here?
fn = 'github_models.get_authorization_url_and_state'
redirect_uri = os.environ.get('CLA_API_BASE', '').strip() + "/v2/github/installation"
github_oauth_url = cla.conf['GITHUB_OAUTH_AUTHORIZE_URL']
github_oauth_client_id = os.environ['GH_OAUTH_CLIENT_ID']
cla.log.debug(f'{fn} - Directing user to the github authorization url: {github_oauth_url} via '
f'our github installation flow: {redirect_uri} '
f'using the github oauth client id: {github_oauth_client_id[0:5]} '
f'with scope: {scope}')
return self._get_authorization_url_and_state(client_id=github_oauth_client_id,
redirect_uri=redirect_uri,
scope=scope,
authorize_url=github_oauth_url)
def _get_authorization_url_and_state(self, client_id, redirect_uri, scope, authorize_url):
"""
Mockable helper method to do the fetching of the authorization URL and state from GitHub.
"""
return cla.utils.get_authorization_url_and_state(client_id, redirect_uri, scope, authorize_url)
def oauth2_redirect(self, state, code, request): # pylint: disable=too-many-arguments
"""
This is where the user will end up after having authorized the CLA system
to get information such as email address.
It will handle storing the OAuth2 session information for this user for
further requests and initiate the signing workflow.
"""
fn = 'github_models.oauth2_redirect'
cla.log.debug(f'{fn} - handling GitHub OAuth2 redirect with request: {dir(request)}')
session = self._get_request_session(request) # request.context['session']
cla.log.debug(f'{fn} - state: {state}, code: {code}, session: {session}')
if 'github_oauth2_state' in session:
session_state = session['github_oauth2_state']
else:
session_state = None
cla.log.warning(f'{fn} - github_oauth2_state not set in current session')
if state != session_state:
cla.log.warning(f'{fn} - invalid GitHub OAuth2 state {session_state} expecting {state}')
raise falcon.HTTPBadRequest('Invalid OAuth2 state', state)
# Get session information for this request.
cla.log.debug(f'{fn} - attempting to fetch OAuth2 token for state {state}')
installation_id = session.get('github_installation_id', None)
github_repository_id = session.get('github_repository_id', None)
change_request_id = session.get('github_change_request_id', None)
origin_url = session.get('github_origin_url', None)
state = session.get('github_oauth2_state')
token_url = cla.conf['GITHUB_OAUTH_TOKEN_URL']
client_id = os.environ['GH_OAUTH_CLIENT_ID']
client_secret = os.environ['GH_OAUTH_SECRET']
cla.log.debug(f'{fn} - fetching token using {client_id[0:5]}... with state={state}, token_url={token_url}, '
f'client_secret={client_secret[0:5]}, with code={code}')
token = self._fetch_token(client_id, state, token_url, client_secret, code)
cla.log.debug(f'{fn} - oauth2 token received for state {state}: {token} - storing token in session')
session['github_oauth2_token'] = token
cla.log.debug(f'{fn} - redirecting the user back to the console: {origin_url}')
return self.redirect_to_console(installation_id, github_repository_id, change_request_id, origin_url, request)
def redirect_to_console(self, installation_id, repository_id, pull_request_id, origin_url, request):
fn = 'github_models.redirect_to_console'
console_endpoint = cla.conf['CONTRIBUTOR_BASE_URL']
console_v2_endpoint = cla.conf['CONTRIBUTOR_V2_BASE_URL']
# Get repository using github's repository ID.
repository = Repository().get_repository_by_external_id(repository_id, "github")
if repository is None:
cla.log.warning(f'{fn} - Could not find repository with the following '
f'repository_id: {repository_id}')
return None
# Get project ID from this repository
project_id = repository.get_repository_project_id()
try:
project = get_project_instance()
project.load(str(project_id))
except DoesNotExist as err:
return {'errors': {'project_id': str(err)}}
user = self.get_or_create_user(request)
# Ensure user actually requires a signature for this project.
# TODO: Skipping this for now - we can do this for ICLAs but there's no easy way of doing
# the check for CCLAs as we need to know in advance what the company_id is that we're checking
# the CCLA signature for.
# We'll have to create a function that fetches the latest CCLA regardless of company_id.
# icla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user)
# ccla_signature = cla.utils.get_user_signature_by_github_repository(installation_id, user, company_id=?)
# try:
# document = cla.utils.get_project_latest_individual_document(project_id)
# except DoesNotExist:
# cla.log.debug('No ICLA for project %s' %project_id)
# if signature is not None and \
# signature.get_signature_document_major_version() == document.get_document_major_version():
# return cla.utils.redirect_user_by_signature(user, signature)
# Store repository and PR info so we can redirect the user back later.
cla.utils.set_active_signature_metadata(user.get_user_id(), project_id, repository_id, pull_request_id)
console_url = ''
# Temporary condition until all CLA Groups are ready for the v2 Contributor Console
if project.get_version() == 'v2':
# Generate url for the v2 console
console_url = 'https://' + console_v2_endpoint + \
'/#/cla/project/' + project_id + \
'/user/' + user.get_user_id() + \
'?redirect=' + origin_url
cla.log.debug(f'{fn} - redirecting to v2 console: {console_url}...')
else:
# Generate url for the v1 contributor console
console_url = 'https://' + console_endpoint + \
'/#/cla/project/' + project_id + \
'/user/' + user.get_user_id() + \
'?redirect=' + origin_url
cla.log.debug(f'{fn} - redirecting to v1 console: {console_url}...')
raise falcon.HTTPFound(console_url)
def _fetch_token(self, client_id, state, token_url, client_secret,
code): # pylint: disable=too-many-arguments,no-self-use
"""
Mockable method to fetch a OAuth2Session token.
"""
return cla.utils.fetch_token(client_id, state, token_url, client_secret, code)
def sign_workflow(self, installation_id, github_repository_id, pull_request_number, request):
"""
Once we have the 'github_oauth2_token' value in the user's session, we can initiate the
signing workflow.
"""
fn = 'sign_workflow'
cla.log.warning(f'{fn} - Initiating GitHub signing workflow for '
f'GitHub repo {github_repository_id} '
f'with PR: {pull_request_number}')
user = self.get_or_create_user(request)
signature = cla.utils.get_user_signature_by_github_repository(installation_id, user)
project_id = cla.utils.get_project_id_from_installation_id(installation_id)
document = cla.utils.get_project_latest_individual_document(project_id)
if signature is not None and \
signature.get_signature_document_major_version() == document.get_document_major_version():
return cla.utils.redirect_user_by_signature(user, signature)
else:
# Signature not found or older version, create new one and send user to sign.
cla.utils.request_individual_signature(installation_id, github_repository_id, user, pull_request_number)
def process_opened_pull_request(self, data):
"""
Helper method to handle a webhook fired from GitHub for an opened PR.
:param data: The data returned from GitHub on this webhook.
:type data: dict
"""
pull_request_id = data['pull_request']['number']
github_repository_id = data['repository']['id']
installation_id = data['installation']['id']
self.update_change_request(installation_id, github_repository_id, pull_request_id)
def process_easycla_command_comment(self, data):
"""
Processes easycla command comment if present
:param data: github issue comment webhook event payload : https://docs.github.com/en/free-pro-team@latest/developers/webhooks-and-events/webhook-events-and-payloads#issue_comment
:return:
"""
comment_str = data.get("comment", {}).get("body", "")
if not comment_str:
raise ValueError("missing comment body, ignoring the message")
if "/easycla" not in comment_str.split():
raise ValueError(f'unsupported comment supplied: {comment_str.split()}, '
'currently only the \'/easycla\' command is supported')
github_repository_id = data.get('repository', {}).get('id', None)
if not github_repository_id:
raise ValueError("missing github repository id in pull request comment")
cla.log.debug(f"comment trigger for github_repo : {github_repository_id}")
# turns out pull request id and issue is the same thing
pull_request_id = data.get("issue", {}).get("number", None)
if not pull_request_id:
raise ValueError("missing pull request id ")
cla.log.debug(f"comment trigger for pull_request_id : {pull_request_id}")
cla.log.debug("installation object : ", data.get('installation', {}))
installation_id = data.get('installation', {}).get('id', None)
if not installation_id:
raise ValueError("missing installation id in pull request comment")
cla.log.debug(f"comment trigger for installation_id : {installation_id}")
self.update_change_request(installation_id, github_repository_id, pull_request_id)
def get_return_url(self, github_repository_id, change_request_id, installation_id):
pull_request = self.get_pull_request(github_repository_id, change_request_id, installation_id)
return pull_request.html_url
def update_change_request(self, installation_id, github_repository_id, change_request_id):
fn = 'update_change_request'
# Queries GH for the complete pull request details, see:
# https://developer.github.com/v3/pulls/#response-1
try:
# check if change_request_id is a valid int
_ = int(change_request_id)
pull_request = self.get_pull_request(github_repository_id, change_request_id, installation_id)
except ValueError:
cla.log.error(f'{fn} - Invalid PR: {change_request_id} . (Unable to cast to integer) ')
return
cla.log.debug(f'{fn} - retrieved pull request: {pull_request}')
# Get all unique users/authors involved in this PR - returns a list of
# (commit_sha_string, (author_id, author_username, author_email) tuples
commit_authors = get_pull_request_commit_authors(pull_request)
try:
# Get existing repository info using the repository's external ID,
# which is the repository ID assigned by github.
cla.log.debug(f'{fn} - PR: {pull_request.number}, Loading GitHub repository by id: {github_repository_id}')
repository = Repository().get_repository_by_external_id(github_repository_id, "github")
if repository is None:
cla.log.warning(f'{fn} - PR: {pull_request.number}, Failed to load GitHub repository by '
f'id: {github_repository_id} in our DB - repository reference is None - '
'Is this org/repo configured in the Project Console?'
' Unable to update status.')
return
except DoesNotExist:
cla.log.warning(f'{fn} - PR: {pull_request.number}, could not find repository with the '
f'repository ID: {github_repository_id}')
cla.log.warning(f'{fn} - PR: {pull_request.number}, failed to update change request of '
f'repository {github_repository_id} - returning')
return
# Get Github Organization name that the repository is configured to.
organization_name = repository.get_repository_organization_name()
cla.log.debug(f'{fn} - PR: {pull_request.number}, determined github organization is: {organization_name}')
# Check that the Github Organization exists.
github_org = GitHubOrg()
try:
github_org.load(organization_name)
except DoesNotExist:
cla.log.warning(f'{fn} - PR: {pull_request.number}, Could not find Github Organization '
f'with the following organization name: {organization_name}')
cla.log.warning(f'{fn}- PR: {pull_request.number}, Failed to update change request of '
f'repository {github_repository_id} - returning')
return
# Ensure that installation ID for this organization matches the given installation ID
if github_org.get_organization_installation_id() != installation_id:
cla.log.warning(f'{fn} - PR: {pull_request.number}, '
f'the installation ID: {github_org.get_organization_installation_id()} '
f'of this organization does not match installation ID: {installation_id} '
'given by the pull request.')
cla.log.error(f'{fn} - PR: {pull_request.number}, Failed to update change request '
f'of repository {github_repository_id} - returning')
return
# Retrieve project ID from the repository.
project_id = repository.get_repository_project_id()
project = get_project_instance()
project.load(str(project_id))
# Find users who have signed and who have not signed.
signed = []
missing = []
cla.log.debug(f'{fn} - PR: {pull_request.number}, scanning users - '
'determining who has signed a CLA an who has not.')
for commit_sha, author_info in commit_authors:
# Extract the author info tuple details
if author_info:
author_id = author_info[0]
author_username = author_info[1]
author_email = author_info[2]
cla.log.debug(f'{fn} - PR: {pull_request.number}, '
f'processing sha: {commit_sha} '
f'from author id: {author_id}, username: {author_username}, email: {author_email}')
else:
cla.log.debug(
f'{fn} - PR: {pull_request.number}, processing sha: {commit_sha} with invalid author details')
handle_commit_from_user(project, commit_sha, author_info, signed, missing)
cla.log.debug(f'{fn} - PR: {pull_request.number}, '
f'updating github pull request for repo: {github_repository_id}, '
f'with signed authors: {signed} '
f'with missing authors: {missing}')
repository_name = repository.get_repository_name()
update_pull_request(
installation_id=installation_id,
github_repository_id=github_repository_id,
pull_request=pull_request,
repository_name=repository_name,
signed=signed,
missing=missing,
project_version=project.get_version())
def get_pull_request(self, github_repository_id, pull_request_number, installation_id):
"""
Helper method to get the pull request object from GitHub.
:param github_repository_id: The ID of the GitHub repository.
:type github_repository_id: int
:param pull_request_number: The number (not ID) of the GitHub PR.
:type pull_request_number: int
:param installation_id: The ID of the GitHub application installed on this repository.
:type installation_id: int | None
"""
cla.log.debug('Getting PR %s from GitHub repository %s', pull_request_number, github_repository_id)
if self.client is None:
self.client = get_github_integration_client(installation_id)
repo = self.client.get_repo(int(github_repository_id))
try:
return repo.get_pull(int(pull_request_number))
except UnknownObjectException:
cla.log.error('Could not find pull request %s for repository %s - ensure it '
'exists and that your personal access token has the "repo" scope enabled',
pull_request_number, github_repository_id)
except BadCredentialsException as err:
cla.log.error('Invalid GitHub credentials provided: %s', str(err))
def get_or_create_user(self, request):
"""
Helper method to either get or create a user based on the GitHub request made.
:param request: The hug request object for this API call.
:type request: Request
"""
fn = 'github_models.get_or_create_user'
session = self._get_request_session(request)
github_user = self.get_user_data(session, os.environ['GH_OAUTH_CLIENT_ID'])
if 'error' in github_user:
# Could not get GitHub user data - maybe user revoked CLA app permissions?
session = self._get_request_session(request)
del session['github_oauth2_state']
del session['github_oauth2_token']
cla.log.warning(f'{fn} - Deleted OAuth2 session data - retrying token exchange next time')
raise falcon.HTTPError('400 Bad Request', 'github_oauth2_token',
'Token permissions have been rejected, please try again')
emails = self.get_user_emails(session, os.environ['GH_OAUTH_CLIENT_ID'])
if len(emails) < 1:
cla.log.warning(f'{fn} - GitHub user has no verified email address: %s (%s)',
github_user['name'], github_user['login'])
raise falcon.HTTPError(
'412 Precondition Failed', 'email',
'Please verify at least one email address with GitHub')
cla.log.debug(f'{fn} - Trying to load GitHub user by GitHub ID: %s', github_user['id'])
users = cla.utils.get_user_instance().get_user_by_github_id(github_user['id'])
if users is not None:
# Users search can return more than one match - so it's an array - we set the first record value for now??
user = users[0]
cla.log.debug(f'{fn} - Loaded GitHub user by GitHub ID: %s - %s (%s)',
user.get_user_name(),
user.get_user_emails(),
user.get_user_github_id())
# update/set the github username if available
cla.utils.update_github_username(github_user, user)
user.set_user_emails(emails)
user.save()
return user
# User not found by GitHub ID, trying by email.
cla.log.debug(f'{fn} - Could not find GitHub user by GitHub ID: %s', github_user['id'])
# TODO: This is very slow and needs to be improved - may need a DB schema change.
users = None
user = cla.utils.get_user_instance()
for email in emails:
users = user.get_user_by_email(email)
if users is not None:
break
if users is not None:
# Users search can return more than one match - so it's an array - we set the first record value for now??
user = users[0]
# Found user by email, setting the GitHub ID
user.set_user_github_id(github_user['id'])
# update/set the github username if available
cla.utils.update_github_username(github_user, user)
user.set_user_emails(emails)
user.save()
cla.log.debug(f'{fn} - Loaded GitHub user by email: {user}')
return user
# User not found, create.
cla.log.debug(f'{fn} - Could not find GitHub user by email: {emails}')
cla.log.debug(f'{fn} - Creating new GitHub user {github_user["name"]} - '
f'({github_user["id"]}/{github_user["login"]}), '
f'emails: {emails}')
user = cla.utils.get_user_instance()
user.set_user_id(str(uuid.uuid4()))
user.set_user_emails(emails)
user.set_user_name(github_user['name'])
user.set_user_github_id(github_user['id'])
user.set_user_github_username(github_user['login'])
user.save()
return user
def get_user_data(self, session, client_id): # pylint: disable=no-self-use
"""
Mockable method to get user data. Returns all GitHub user data we have
on the user based on the current OAuth2 session.
:param session: The current user session.
:type session: dict
:param client_id: The GitHub OAuth2 client ID.
:type client_id: string
"""
fn = 'cla.models.github_models.get_user_data'
token = session.get('github_oauth2_token')
if token is None:
cla.log.error(f'{fn} - unable to load github_oauth2_token from session, session is: {session}')
return {'error': 'could not get user data from session'}
oauth2 = OAuth2Session(client_id, token=token)
request = oauth2.get('https://api.github.com/user')
github_user = request.json()
cla.log.debug(f'{fn} - GitHub user data: %s', github_user)
if 'message' in github_user:
cla.log.error(f'{fn} - Could not get user data with OAuth2 token: {github_user["message"]}')
return {'error': 'Could not get user data: %s' % github_user['message']}
return github_user
def get_user_emails(self, session: dict, client_id: str) -> Union[List[str], dict]: # pylint: disable=no-self-use
"""
Mockable method to get all user emails based on OAuth2 session.
:param session: The current user session.
:type session: dict
:param client_id: The GitHub OAuth2 client ID.
:type client_id: string
"""
emails = self._fetch_github_emails(session=session, client_id=client_id)
cla.log.debug('GitHub user emails: %s', emails)
if 'error' in emails:
return emails
verified_emails = [item['email'] for item in emails if item['verified']]
excluded_emails = [email for email in verified_emails
if any([email.endswith(e) for e in EXCLUDE_GITHUB_EMAILS])]
included_emails = [email for email in verified_emails
if not any([email.endswith(e) for e in EXCLUDE_GITHUB_EMAILS])]
if len(included_emails) > 0:
return included_emails
# something we're not very happy about but probably it can happen
return excluded_emails
def get_primary_user_email(self, request) -> Union[Optional[str], dict]:
"""
gets the user primary email from the registered emails from the github api
"""
fn = 'github_models.get_primary_user_email'
try:
cla.log.debug(f'{fn} - fetching Github primary email')
session = self._get_request_session(request)
client_id = os.environ['GH_OAUTH_CLIENT_ID']
emails = self._fetch_github_emails(session=session, client_id=client_id)
if "error" in emails:
return None
for email in emails:
if email.get("verified", False) and email.get("primary", False):
return email["email"]
except Exception as e:
cla.log.warning(f'{fn} - lookup failed - {e} - returning None')
return None
return None
def _fetch_github_emails(self, session: dict, client_id: str) -> Union[List[dict], dict]:
"""
Method is responsible for fetching the user emails from /user/emails endpoint
:param session:
:param client_id:
:return:
"""
fn = 'github_models._fetch_github_emails' # function name
# Use the user's token to fetch their public email(s) - don't use the system token as this endpoint won't work
# as expected
token = session.get('github_oauth2_token')
if token is None:
cla.log.warning(f'{fn} - unable to load github_oauth2_token from the session - session is empty')
oauth2 = OAuth2Session(client_id, token=token)
request = oauth2.get('https://api.github.com/user/emails')
resp = request.json()
if 'message' in resp:
cla.log.warning(f'{fn} - could not get user emails with OAuth2 token: {resp["message"]}')
return {'error': 'Could not get user emails: %s' % resp['message']}
return resp
def process_reopened_pull_request(self, data):
"""
Helper method to process a re-opened GitHub PR.
Simply calls the self.process_opened_pull_request() method with the data provided.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
return self.process_opened_pull_request(data)
def process_closed_pull_request(self, data):
"""
Helper method to process a closed GitHub PR.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
pass
def process_synchronized_pull_request(self, data):
"""
Helper method to process a synchronized GitHub PR.
Should be called when a new commit comes through on the PR.
Simply calls the self.process_opened_pull_request() method with the data provided.
This should re-check all commits for author information.
:param data: The data provided by the GitHub webhook.
:type data: dict
"""
return self.process_opened_pull_request(data)
def create_repository(data):
"""
Helper method to create a repository object in the CLA database given PR data.
:param data: The data provided by the GitHub webhook.
:type data: dict
:return: The newly created repository object - already in the DB.
:rtype: cla.models.model_interfaces.Repository
"""
try:
repository = cla.utils.get_repository_instance()
repository.set_repository_id(str(uuid.uuid4()))
# TODO: Need to use an ID unique across all repository providers instead of namespace.
full_name = data['repository']['full_name']
namespace = full_name.split('/')[0]
repository.set_repository_project_id(namespace)
repository.set_repository_external_id(data['repository']['id'])
repository.set_repository_name(full_name)
repository.set_repository_type('github')
repository.set_repository_url(data['repository']['html_url'])
repository.save()
return repository
except Exception as err:
cla.log.warning('Could not create GitHub repository automatically: %s', str(err))
return None
def handle_commit_from_user(project, commit_sha, author_info, signed, missing): # pylint: disable=too-many-arguments
"""
Helper method to triage commits between signed and not-signed user signatures.
:param project: The project model for this github PR organization.
:type project: Project
:param commit_sha: Commit has as a string
:type commit_sha: string
:param author_info: the commit author details, including id, name, email (if available)
:type author_info: tuple of (author_id, author_username, author_email)
:param signed: Reference to a list of signed authors so far. Should be modified
in-place to add a signer if found.
:type signed: list of strings
:param missing: Reference to a list of authors who have not signed yet.
Should be modified in-place to add a missing signer if found.
:type missing: list of strings
"""
# handle edge case of non existant users
if author_info is None:
missing.append((commit_sha, []))
return
# Extract the author_info tuple details
author_id = author_info[0]
author_username = author_info[1]
author_email = author_info[2]
cla.log.debug(f'Looking up GitHub user (author_id: {author_id}, '
f'author_username: {author_username}, '
f'auth_email: {author_email})')
# attempt to lookup the user in our database by GH id -
# may return multiple users that match this author_id
users = cla.utils.get_user_instance().get_user_by_github_id(author_id)
if users is None:
# GitHub user not in system yet, signature does not exist for this user.
cla.log.debug(f'GitHub user (id: {author_id}, '
f'user: {author_username}, '
f'email: {author_email}) lookup by github id not found in our database, '
'attempting to looking up user by email...')
# Try looking up user by email as a fallback
users = cla.utils.get_user_instance().get_user_by_email(author_email)
# Got one or more records by searching the email
if users is not None:
cla.log.debug(f'Found {len(users)} GitHub user(s) matching github email: {author_email}')
for user in users:
cla.log.debug(f'GitHub user found in our database: {user}')
# For now, accept non-github users as legitimate users.
# Does this user have a signed signature for this project? If so, add to the signed list and return,
# no reason to continue looking
if cla.utils.user_signed_project_signature(user, project):
signed.append((commit_sha, author_username))
return
# Didn't find a signed signature for this project - add to our missing bucket list
# author_info consists of: [author_id, author_username, author_email]
missing.append((commit_sha, list(author_info)))
else:
# Not seen this user before - no record on file in our user's database
cla.log.debug(f'GitHub user (id: {author_id}, '
f'user: {author_username}, '
f'email: {author_email}) lookup by email in our database failed - not found')
# This bit of logic below needs to be reconsidered - query logic takes a very long time for large
# projects like CNCF which significantly delays updating the GH PR status.
# Revisit once we add more indexes to the table
# # Check to see if not found user is whitelisted to assist in triaging github comment
# # Search for the CCLA signatures for this project - wish we had a company ID to restrict the query...
# signatures = cla.utils.get_signature_instance().get_signatures_by_project(
# project.get_project_id(),
# signature_signed=True,
# signature_approved=True,
# signature_reference_type='company')
#
# list_author_info = list(author_info)
# for signature in signatures:
# if cla.utils.is_whitelisted(
# signature,
# email=author_email,
# github_id=author_id,
# github_username=author_username
# ):
# # Append whitelisted flag to the author info list
# cla.log.debug(f'Github user(id:{author_id}, '
# f'user: {author_username}, '
# f'email {author_email}) is whitelisted but not a CLA user')
# list_author_info.append(True)
# break
# missing.append((commit_sha, list_author_info))
# For now - we'll just return the author info as a list without the flag to indicate that they have been on
# the approved list for any company/signature
# author_info consists of: [author_id, author_username, author_email]
missing.append((commit_sha, list(author_info)))
else:
cla.log.debug(f'Found {len(users)} GitHub user(s) matching github id: {author_id} in our database')
if len(users) > 1:
cla.log.warning(f'more than 1 user found in our user database - user: {users} - '
f'will ONLY evaluate the first one')
# Just review the first user that we were able to fetch from our DB
user = users[0]
cla.log.debug(f'GitHub user found in our database: {user}')
# Does this user have a signed signature for this project? If so, add to the signed list and return,
# no reason to continue looking
if cla.utils.user_signed_project_signature(user, project):
signed.append((commit_sha, author_username))
return
list_author_info = list(author_info)
# If the user does not have a company ID assigned, then they have not been associated with a company as
# part of the Contributor console workflow
if user.get_user_company_id() is None:
missing.append((commit_sha, list_author_info))
return
# Perform a specific search for the user's project + company + CCLA
signatures = cla.utils.get_signature_instance().get_signatures_by_project(
project_id=project.get_project_id(),
signature_signed=True,
signature_approved=True,
signature_type='ccla',
signature_reference_type='company',
signature_reference_id=user.get_user_company_id(),
signature_user_ccla_company_id=None,
)
# Should only return one signature record
cla.log.debug(f'Found {len(signatures)} CCLA signatures for company: {user.get_user_company_id()}, '
f'project: {project.get_project_id()} in our database.')
# Should never happen - warn if we see this
if len(signatures) > 1:
cla.log.warning(f'more than 1 CCLA signature record found in our database - signatures: {signatures}')
for signature in signatures:
if cla.utils.is_approved(
signature,
email=author_email,
github_id=author_id,
github_username=author_username
):
# Append whitelisted flag to the author info list
cla.log.debug(f'Github user(id:{author_id}, '
f'user: {author_username}, '
f'email {author_email}) is on the approved list, '
'but not affiliated with a company')
list_author_info.append(True)
break
missing.append((commit_sha, list_author_info))
def get_pull_request_commit_authors(pull_request):
"""
Helper function to extract all committer information for a GitHub PR.
For pull_request data model, see:
https://developer.github.com/v3/pulls/
For commits on a pull request, see:
https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
For activity callback, see:
https://developer.github.com/v3/activity/events/types/#pullrequestevent
:param pull_request: A GitHub pull request to examine.
:type pull_request: GitHub.PullRequest
:return: A list of tuples containing a tuple of (commit_sha_string, (author_id, author_username, author_email)) -
the second item is another tuple of author info.
:rtype: [(commit_sha_string, (author_id, author_username, author_email)]
"""
cla.log.debug('Querying pull request commits for author information...')
commit_authors = []
for commit in pull_request.get_commits():
cla.log.debug('Processing commit while looking for authors, commit: {}'.format(commit.sha))
# Note: we can get the author info in two different ways:
if commit.author:
try:
# commit.author is a github.NamedUser.NamedUser type object
# https://pygithub.readthedocs.io/en/latest/github_objects/NamedUser.html
if commit.author.name is not None:
cla.log.debug('PR: {}, GitHub commit.author.name author found for commit SHA {}, '
'author id: {}, name: {}, email: {}'.
format(pull_request.number, commit.sha, commit.author.id,
commit.author.name, commit.author.email))
commit_authors.append((commit.sha, (commit.author.id, commit.author.name, commit.author.email)))
elif commit.author.login is not None:
cla.log.debug('PR: {}, GitHub commit.author.login author found for commit SHA {}, '
'author id: {}, login: {}, email: {}'.
format(pull_request.number, commit.sha, commit.author.id,
commit.author.login, commit.author.email))
commit_authors.append((commit.sha, (commit.author.id, commit.author.login, commit.author.email)))
else:
cla.log.debug(f'PR: {pull_request.number}, GitHub commit.author.name and commit.author.login '
f'author information NOT found for commit SHA {commit.sha}, '
f'author id: {commit.author.id}, '
f'name: {commit.author.name}, '
f'login: {commit.author.login}, '
f'email: {commit.author.email}')
commit_authors.append((commit.sha, None))
except (GithubException, IncompletableObject) as ex:
cla.log.debug(f'Commit sha: {commit.sha} exception: {ex}')
try:
cla.log.debug('github.GitAuthor.GitAuthor object: {}'.format(commit.commit.author))
# commit.commit.author is a github.GitAuthor.GitAuthor object type - object
# only has date, name and email attributes - no ID attribute/value
# https://pygithub.readthedocs.io/en/latest/github_objects/GitAuthor.html
cla.log.debug('PR: {}, GitHub NamedUser author NOT found for commit SHA {}, '
'however, found GitAuthor author id: None, name: {}, email: {}'.
format(pull_request.number, commit.sha,
commit.commit.author.name, commit.commit.author.email))
commit_authors.append((commit.sha, (None, commit.commit.author.name, commit.commit.author.email)))
except (GithubException, IncompletableObject):
cla.log.warning(
'PR: {}, could not find any commit author for SHA {}'.format(pull_request.number, commit.sha))
commit_authors.append((commit.sha, None))
else:
cla.log.warning('PR: {}, could not find any commit author for SHA {}'.
format(pull_request.number, commit.sha))
commit_authors.append((commit.sha, None))
return commit_authors
def has_check_previously_failed(pull_request: PullRequest):
"""
Review the status updates in the PR. Identify 1 or more previous failed
updates from the EasyCLA bot. If we fine one, return True with the comment, otherwise
return False, None
:param pull_request: the GitHub pull request object
:return: True with the comment if the EasyCLA bot check previously failed, otherwise return False, None
"""
comments = pull_request.get_issue_comments()
# Look through all the comments
for comment in comments:
# Our bot comments include the following text
# A previously failed check has 'not authorized' somewhere in the body
if 'is not authorized under a signed CLA' in comment.body:
return True, comment
if 'they must confirm their affiliation' in comment.body:
return True, comment
if 'CLA Missing ID' in comment.body and 'is missing the User' in comment.body:
return True, comment
return False, None
def update_pull_request(installation_id, github_repository_id, pull_request, repository_name, signed,
missing, project_version): # pylint: disable=too-many-locals
"""
Helper function to update a PR's comment and status based on the list of signers.
:param installation_id: The ID of the GitHub installation
:type installation_id: int
:param github_repository_id: The ID of the GitHub repository this PR belongs to.
:type github_repository_id: int
:param pull_request: The GitHub PullRequest object for this PR.
:type pull_request: GitHub.PullRequest
:param repository_name: The GitHub repository name for this PR.
:type repository_name: string
:param signed: The list of (commit hash, author name) tuples that have signed an
signature for this PR.
:type signed: [(string, string)]
:param missing: The list of (commit hash, author name) tuples that have not signed
an signature for this PR.
:type missing: [(string, list)]
:param project_version: Project version associated with PR
:type missing: string
"""
notification = cla.conf['GITHUB_PR_NOTIFICATION']
both = notification == 'status+comment' or notification == 'comment+status'
last_commit = pull_request.get_commits().reversed[0]
# Here we update the PR status by adding/updating the PR body - this is the way the EasyCLA app
# knows if it is pass/fail.
# Create check run for users that haven't yet signed and/or affiliated
if missing:
text = ""
for authors in missing:
# Check for valid github id
if authors[1] is None or (authors[1] and authors[1][0] is None):
help_url = "https://help.github.com/en/github/committing-changes-to-your-project/why-are-my-commits-linked-to-the-wrong-user"
else:
help_url = cla.utils.get_full_sign_url('github', str(installation_id), github_repository_id,
pull_request.number, project_version)
client = GitHubInstallation(installation_id)
# check if unsigned user is whitelisted
commit_sha = authors[0]
if commit_sha != last_commit.sha:
continue
if authors[1]:
author_email = authors[1][2]
author_id = authors[1][0]
if author_id:
if len(authors[1]) == 4:
text += f'{author_email} must confirm corporate affiliation.\n'
else:
text += f'{author_email} is not authorized under a signed CLA.\n'
else:
text += f'{author_email} is not linked to this commit. \n'
else:
text += 'Invalid author details. \n'
payload = {
"name": "CLA check",
"head_sha": last_commit.sha,
"status": "completed",
"conclusion": "action_required",
"details_url": help_url,
"output": {
"title": "EasyCLA: Signed CLA not found",
"summary": "One or more committers are authorized under a signed CLA.",
"text": text,
},
}
client.create_check_run(repository_name, json.dumps(payload))
# Update the comment
if both or notification == 'comment':
body = cla.utils.assemble_cla_comment('github', str(installation_id), github_repository_id, pull_request.number,
signed, missing, project_version)
previously_failed, comment = has_check_previously_failed(pull_request)
if not missing:
# After Issue #167 wsa in place, they decided via Issue #289 that we
# DO want to update the comment, but only after we've previously failed
if previously_failed:
cla.log.debug('Found previously failed checks - updating CLA comment in PR.')
comment.edit(body)
cla.log.debug('EasyCLA App checks pass for PR: {} with authors: {}'.format(pull_request.number, signed))
else:
# Per Issue #167, only add a comment if check fails
# update_cla_comment(pull_request, body)
if previously_failed:
cla.log.debug('Found previously failed checks - updating CLA comment in PR.')
comment.edit(body)
else:
pull_request.create_issue_comment(body)
cla.log.debug('EasyCLA App checks fail for PR: {}. CLA signatures with signed authors: {} and '
'with missing authors: {}'.format(pull_request.number, signed, missing))
if both or notification == 'status':
context_name = os.environ.get('GH_STATUS_CTX_NAME')
if context_name is None:
context_name = 'communitybridge/cla'
# if we have ANY committers who have failed the check - update the status with overall failure
if missing is not None and len(missing) > 0:
state = 'failure'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=False)
sign_url = cla.utils.get_full_sign_url(
'github', str(installation_id), github_repository_id, pull_request.number, project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
elif signed is not None and len(signed) > 0:
state = 'success'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=True)
sign_url = cla.conf["CLA_LANDING_PAGE"] # Remove this once signature detail page ready.
sign_url = os.path.join(sign_url, "#/")
sign_url = append_project_version_to_url(address=sign_url, project_version=project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
else:
# error condition - should have a least one committer and they would be in one of the above
# lists: missing or signed
state = 'failure'
# For status, we change the context from author_name to 'communitybridge/cla' or the
# specified default value per issue #166
context, body = cla.utils.assemble_cla_status(context_name, signed=False)
sign_url = cla.utils.get_full_sign_url(
'github', str(installation_id), github_repository_id, pull_request.number, project_version)
cla.log.debug(f'Creating new CLA \'{state}\' status - {len(signed)} passed, {missing} failed, '
f'signing url: {sign_url}')
cla.log.warning('This is an error condition - should have at least one committer in one of these lists: '
f'{len(signed)} passed, {missing}')
create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context)
def create_commit_status(pull_request, commit_hash, state, sign_url, body, context):
"""
Helper function to create a pull request commit status message given the PR and commit hash.
:param pull_request: The GitHub Pull Request object.
:type pull_request: github.PullRequest
:param commit_hash: The commit hash to post a status on.
:type commit_hash: string
:param state: The state of the status.
:type state: string
:param sign_url: The link the user will be taken to when clicking on the status message.
:type sign_url: string
:param body: The contents of the status message.
:type body: string
"""
try:
commit_obj = None
for commit in pull_request.get_commits():
if commit.sha == commit_hash:
commit_obj = commit
break
if commit_obj is None:
cla.log.error(f'Could not post status {state} on '
f'PR: {pull_request.number}, '
f'Commit: {commit_hash} not found')
return
# context is a string label to differentiate one signer status from another signer status.
# committer name is used as context label
cla.log.info(f'Updating status with state \'{state}\' on PR {pull_request.number} for commit {commit_hash}...')
# returns github.CommitStatus.CommitStatus
resp = commit_obj.create_status(state, sign_url, body, context)
cla.log.info(f'Successfully posted status \'{state}\' on PR {pull_request.number}: Commit {commit_hash} '
f'with SignUrl : {sign_url} with response: {resp}')
except GithubException as exc:
cla.log.error(f'Could not post status \'{state}\' on PR: {pull_request.number}, '
f'Commit: {commit_hash}, '
f'Response Code: {exc.status}, '
f'Message: {exc.data}')
# def update_cla_comment(pull_request, body):
# """
# Helper function to create/edit a comment on the GitHub PR.
#
# :param pull_request: The PR object in question.
# :type pull_request: GitHub.PullRequest
# :param body: The contents of the comment.
# :type body: string
# """
# comment = get_existing_cla_comment(pull_request)
# if comment is not None:
# cla.log.debug(f'Updating existing CLA comment for PR: {pull_request.number} with body: {body}')
# comment.edit(body)
# else:
# cla.log.debug(f'Creating a new CLA comment for PR: {pull_request.number} with body: {body}')
# pull_request.create_issue_comment(body)
# def get_existing_cla_comment(pull_request):
# """
# Helper function to get an existing comment from the CLA system in a GitHub PR.
#
# :param pull_request: The PR object in question.
# :type pull_request: GitHub.PullRequest
# """
# comments = pull_request.get_issue_comments()
# for comment in comments:
# if '[
# return comment
def get_github_integration_client(installation_id):
"""
GitHub App integration client used for authenticated client actions through an installed app.
"""
return GitHubInstallation(installation_id).api_object
def get_github_client(organization_id):
github_org = cla.utils.get_github_organization_instance()
github_org.load(organization_id)
installation_id = github_org.get_organization_installation_id()
return get_github_integration_client(installation_id)
class MockGitHub(GitHub):
"""
The GitHub repository service mock class for testing.
"""
def __init__(self, oauth2_token=False):
super().__init__()
self.oauth2_token = oauth2_token
def _get_github_client(self, username, token):
return MockGitHubClient(username, token)
def _get_authorization_url_and_state(self, client_id, redirect_uri, scope, authorize_url):
authorization_url = 'http://authorization.url'
state = 'random-state-here'
return authorization_url, state
def _fetch_token(self, client_id, state, token_url, client_secret, code): # pylint: disable=too-many-arguments
return 'random-token'
def _get_request_session(self, request) -> dict:
if self.oauth2_token:
return {'github_oauth2_token': 'random-token',
'github_oauth2_state': 'random-state',
'github_origin_url': 'http://github/origin/url',
'github_installation_id': 1}
return {}
def get_user_data(self, session, client_id) -> dict:
return {'email': 'test@user.com', 'name': 'Test User', 'id': 123}
def get_user_emails(self, session, client_id):
return [{'email': 'test@user.com', 'verified': True, 'primary': True, 'visibility': 'public'}]
def get_pull_request(self, github_repository_id, pull_request_number, installation_id):
return MockGitHubPullRequest(pull_request_number)
class MockGitHubClient(object): # pylint: disable=too-few-public-methods
"""
The GitHub Client object mock class for testing.
"""
def __init__(self, username, token):
self.username = username
self.token = token
def get_repo(self, repository_id): # pylint: disable=no-self-use
"""
Mock version of the GitHub Client object's get_repo method.
"""
return MockGitHubRepository(repository_id)
class MockGitHubRepository(object): # pylint: disable=too-few-public-methods
"""
The GitHub Repository object mock class for testing.
"""
def __init__(self, repository_id):
self.id = repository_id
def get_pull(self, pull_request_id): # pylint: disable=no-self-use
"""
Mock version of the GitHub Repository object's get_pull method.
"""
return MockGitHubPullRequest(pull_request_id)
class MockGitHubPullRequest(object): # pylint: disable=too-few-public-methods
"""
The GitHub PullRequest object mock class for testing.
"""
def __init__(self, pull_request_id):
self.number = pull_request_id
self.html_url = 'http://test-github.com/user/repo/' + str(self.number)
def get_commits(self): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's get_commits method.
"""
lst = MockPaginatedList()
lst._elements = [MockGitHubCommit()] # pylint: disable=protected-access
return lst
def get_issue_comments(self): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's get_issue_comments method.
"""
return [MockGitHubComment()]
def create_issue_comment(self, body): # pylint: disable=no-self-use
"""
Mock version of the GitHub PullRequest object's create_issue_comment method.
"""
pass
class MockGitHubComment(object): # pylint: disable=too-few-public-methods
"""
A GitHub mock issue comment object for testing.
"""
body = 'Test'
class MockPaginatedList(github.PaginatedList.PaginatedListBase): # pylint: disable=too-few-public-methods
"""Mock GitHub paginated list for testing purposes."""
def __init__(self):
super().__init__()
# Need to use our own elements list (self.__elements from PaginatedListBase does not
# work as expected).
self._elements = []
@property
def reversed(self):
"""Fake reversed property."""
return [MockGitHubCommit()]
def __iter__(self):
for element in self._elements:
yield element
class MockGitHubCommit(object): # pylint: disable=too-few-public-methods
"""
The GitHub Commit object mock class for testing.
"""
def __init__(self):
self.author = MockGitHubAuthor()
self.sha = 'sha-test-commit'
def create_status(self, state, sign_url, body):
"""
Mock version of the GitHub Commit object's create_status method.
"""
pass
class MockGitHubAuthor(object): # pylint: disable=too-few-public-methods
"""
The GitHub Author object mock class for testing.
"""
def __init__(self, author_id=1):
self.id = author_id
self.login = 'user'
self.email = 'user@github.com'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
from closeio_api import APIError, Client as CloseIO_API
parser = argparse.ArgumentParser(
description='Assigns tasks or opportunities from one user to another'
)
group_from = parser.add_mutually_exclusive_group(required=True)
group_from.add_argument('--from-user-id', '-f', type=str, help='')
group_from.add_argument('--from-user-email', type=str, help='')
group_to = parser.add_mutually_exclusive_group(required=True)
group_to.add_argument('--to-user-id', '-t', type=str, help='')
group_to.add_argument('--to-user-email', type=str, help='')
parser.add_argument('--api-key', '-k', required=True, help='API key')
parser.add_argument(
'--confirmed',
'-c',
action='store_true',
help='Without this flag, the script will do a dry run without actually updating any data.',
)
parser.add_argument(
'--continue-on-error',
'-s',
action='store_true',
help='Do not abort after first error',
)
group = parser.add_argument_group()
group.add_argument(
'--tasks',
'-T',
action='store_true',
help='reassign only non complete tasks',
)
group.add_argument(
'--all-tasks', action='store_true', help='reassign all tasks'
)
group.add_argument(
'--opportunities',
'-O',
action='store_true',
help='reassign only active opportunities',
)
group.add_argument(
'--all-opportunities',
action='store_true',
help='reassign all opportunities',
)
args = parser.parse_args()
full_tasks = []
full_opps = []
if not any(
[args.tasks, args.opportunities, args.all_tasks, args.all_opportunities]
):
parser.error("at least one option required")
log_format = "[%(asctime)s] %(levelname)s %(message)s"
if not args.confirmed:
log_format = 'DRY RUN: ' + log_format
logging.basicConfig(level=logging.INFO, format=log_format)
logging.debug(f'parameters: {vars(args)}')
api = CloseIO_API(args.api_key)
emails_to_ids = {}
if any([args.from_user_email, args.to_user_email]):
has_more = True
offset = 0
while has_more:
resp = api.get('user', params={'_skip': offset})
for user in resp['data']:
emails_to_ids[user['email']] = user['id']
offset += len(resp['data'])
has_more = resp['has_more']
logging.debug(emails_to_ids)
if args.from_user_email:
from_user_id = emails_to_ids[args.from_user_email]
else:
# for exception, if user_id is not present in the database
resp = api.get('user/' + args.from_user_id, params={'_fields': 'id,email'})
from_user_id = resp['id']
emails_to_ids[resp['email']] = resp['id']
if args.to_user_email:
to_user_id = emails_to_ids[args.to_user_email]
else:
resp = api.get('user/' + args.to_user_id, params={'_fields': 'id,email'})
to_user_id = resp['id']
emails_to_ids[resp['email']] = resp['id']
ids_to_emails = dict((v, k) for k, v in emails_to_ids.items())
logging.info(f'from user_id {from_user_id} ({ids_to_emails[from_user_id]})')
logging.info(f'to user_id: {to_user_id} ({ids_to_emails[to_user_id]})')
assert from_user_id != to_user_id, 'equal user codes'
opportunities_errors = 0
tasks_errors = 0
try:
# tasks
updated_tasks = 0
if args.tasks or args.all_tasks:
has_more = True
offset = 0
while has_more:
payload = {
'assigned_to': from_user_id,
'_order_by': 'date_created',
'_skip': offset,
'_fields': 'id',
}
if not args.all_tasks:
payload['is_complete'] = False
resp = api.get('task', params=payload)
tasks = resp['data']
for task in tasks:
if args.confirmed:
full_tasks.append(task['id'])
else:
logging.info(f'updated {task['id']}')
updated_tasks += 1
offset += len(tasks)
has_more = resp['has_more']
for task_id in full_tasks:
try:
api.put('task/' + task_id, data={'assigned_to': to_user_id})
logging.info(f'updated {task_id}')
updated_tasks += 1
except APIError as e:
tasks_errors += 1
if not args.continue_on_error:
raise e
logging.error(f'task {task['id']} skipped with error {str(e)}')
# opportunities
updated_opportunities = 0
if args.opportunities or args.all_opportunities:
has_more = True
offset = 0
while has_more:
payload = {
'user_id': from_user_id,
'_order_by': 'date_created',
'_skip': offset,
'_fields': 'id',
}
if not args.all_opportunities:
payload['status_type'] = 'active'
resp = api.get('opportunity', params=payload)
opportunities = resp['data']
for opportunity in opportunities:
if args.confirmed:
full_opps.append(opportunity['id'])
else:
logging.info(f'updated {opportunity['id']}')
updated_opportunities += 1
offset += len(opportunities)
has_more = resp['has_more']
for opp_id in full_opps:
try:
api.put('opportunity/' + opp_id, data={'user_id': to_user_id})
logging.info(f'updated {opp_id}')
updated_opportunities += 1
except APIError as e:
opportunities_errors += 1
if not args.continue_on_error:
raise e
logging.error(
f'opportunity {opportunity['id']} skipped with error {str(e)}'
)
except APIError as e:
logging.error(f'stopped on error {str(e)}')
logging.info(
f'summary: updated tasks {updated_tasks}, updated opportunities {updated_opportunities}'
)
if opportunities_errors or tasks_errors:
logging.info(
f'summary: tasks errors: {tasks_errors}, opportunities errors {opportunities_errors}'
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
from closeio_api import APIError, Client as CloseIO_API
parser = argparse.ArgumentParser(
description='Assigns tasks or opportunities from one user to another'
)
group_from = parser.add_mutually_exclusive_group(required=True)
group_from.add_argument('--from-user-id', '-f', type=str, help='')
group_from.add_argument('--from-user-email', type=str, help='')
group_to = parser.add_mutually_exclusive_group(required=True)
group_to.add_argument('--to-user-id', '-t', type=str, help='')
group_to.add_argument('--to-user-email', type=str, help='')
parser.add_argument('--api-key', '-k', required=True, help='API key')
parser.add_argument(
'--confirmed',
'-c',
action='store_true',
help='Without this flag, the script will do a dry run without actually updating any data.',
)
parser.add_argument(
'--continue-on-error',
'-s',
action='store_true',
help='Do not abort after first error',
)
group = parser.add_argument_group()
group.add_argument(
'--tasks',
'-T',
action='store_true',
help='reassign only non complete tasks',
)
group.add_argument(
'--all-tasks', action='store_true', help='reassign all tasks'
)
group.add_argument(
'--opportunities',
'-O',
action='store_true',
help='reassign only active opportunities',
)
group.add_argument(
'--all-opportunities',
action='store_true',
help='reassign all opportunities',
)
args = parser.parse_args()
full_tasks = []
full_opps = []
if not any(
[args.tasks, args.opportunities, args.all_tasks, args.all_opportunities]
):
parser.error("at least one option required")
log_format = "[%(asctime)s] %(levelname)s %(message)s"
if not args.confirmed:
log_format = 'DRY RUN: ' + log_format
logging.basicConfig(level=logging.INFO, format=log_format)
logging.debug(f'parameters: {vars(args)}')
api = CloseIO_API(args.api_key)
emails_to_ids = {}
if any([args.from_user_email, args.to_user_email]):
has_more = True
offset = 0
while has_more:
resp = api.get('user', params={'_skip': offset})
for user in resp['data']:
emails_to_ids[user['email']] = user['id']
offset += len(resp['data'])
has_more = resp['has_more']
logging.debug(emails_to_ids)
if args.from_user_email:
from_user_id = emails_to_ids[args.from_user_email]
else:
# for exception, if user_id is not present in the database
resp = api.get('user/' + args.from_user_id, params={'_fields': 'id,email'})
from_user_id = resp['id']
emails_to_ids[resp['email']] = resp['id']
if args.to_user_email:
to_user_id = emails_to_ids[args.to_user_email]
else:
resp = api.get('user/' + args.to_user_id, params={'_fields': 'id,email'})
to_user_id = resp['id']
emails_to_ids[resp['email']] = resp['id']
ids_to_emails = dict((v, k) for k, v in emails_to_ids.items())
logging.info(f'from user_id {from_user_id} ({ids_to_emails[from_user_id]})')
logging.info(f'to user_id: {to_user_id} ({ids_to_emails[to_user_id]})')
assert from_user_id != to_user_id, 'equal user codes'
opportunities_errors = 0
tasks_errors = 0
try:
# tasks
updated_tasks = 0
if args.tasks or args.all_tasks:
has_more = True
offset = 0
while has_more:
payload = {
'assigned_to': from_user_id,
'_order_by': 'date_created',
'_skip': offset,
'_fields': 'id',
}
if not args.all_tasks:
payload['is_complete'] = False
resp = api.get('task', params=payload)
tasks = resp['data']
for task in tasks:
if args.confirmed:
full_tasks.append(task['id'])
else:
logging.info(f'updated {task["id"]}')
updated_tasks += 1
offset += len(tasks)
has_more = resp['has_more']
for task_id in full_tasks:
try:
api.put('task/' + task_id, data={'assigned_to': to_user_id})
logging.info(f'updated {task_id}')
updated_tasks += 1
except APIError as e:
tasks_errors += 1
if not args.continue_on_error:
raise e
logging.error(f'task {task["id"]} skipped with error {str(e)}')
# opportunities
updated_opportunities = 0
if args.opportunities or args.all_opportunities:
has_more = True
offset = 0
while has_more:
payload = {
'user_id': from_user_id,
'_order_by': 'date_created',
'_skip': offset,
'_fields': 'id',
}
if not args.all_opportunities:
payload['status_type'] = 'active'
resp = api.get('opportunity', params=payload)
opportunities = resp['data']
for opportunity in opportunities:
if args.confirmed:
full_opps.append(opportunity['id'])
else:
logging.info(f'updated {opportunity["id"]}')
updated_opportunities += 1
offset += len(opportunities)
has_more = resp['has_more']
for opp_id in full_opps:
try:
api.put('opportunity/' + opp_id, data={'user_id': to_user_id})
logging.info(f'updated {opp_id}')
updated_opportunities += 1
except APIError as e:
opportunities_errors += 1
if not args.continue_on_error:
raise e
logging.error(
f'opportunity {opportunity["id"]} skipped with error {str(e)}'
)
except APIError as e:
logging.error(f'stopped on error {str(e)}')
logging.info(
f'summary: updated tasks {updated_tasks}, updated opportunities {updated_opportunities}'
)
if opportunities_errors or tasks_errors:
logging.info(
f'summary: tasks errors: {tasks_errors}, opportunities errors {opportunities_errors}'
)
|
#!/usr/bin/env python3
import sys, os
from subprocess import Popen, PIPE
import yaml
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# let snakemake read job_properties
from snakemake.utils import read_job_properties
jobscript = sys.argv[1]
job_properties = read_job_properties(jobscript)
#default paramters defined in cluster_spec (accessed via snakemake read_job_properties)
cluster_param= job_properties["cluster"]
if job_properties["type"]=='single':
cluster_param['name'] = job_properties['rule']
elif job_properties["type"]=='group':
cluster_param['name'] = job_properties['groupid']
else:
raise NotImplementedError(f"Don't know what to do with job_properties['type']=={job_properties["type"]}")
# don't overwrite default parameters if defined in rule (or config file)
cluster_param["threads"] = job_properties["threads"]
for res in ['time','mem']:
if (res in job_properties["resources"]) and (res not in cluster_param):
cluster_param[res] = job_properties["resources"][res]
# time in hours
if "time" in cluster_param:
cluster_param["time"]=int(cluster_param["time"]*60)
# check which system you are on and load command command_options
key_mapping_file=os.path.join(os.path.dirname(__file__),"key_mapping.yaml")
command_options=yaml.load(open(key_mapping_file),
Loader=yaml.BaseLoader)
command= command_options[command_options['system']]['command']
key_mapping= command_options[command_options['system']]['key_mapping']
# construct command:
for key in key_mapping:
if key in cluster_param:
if key == "highp":
if "highp" == cluster_param[key]:
command+=" "
command+=key_mapping[key].format(cluster_param[key])
else:
command+=" "
command+=key_mapping[key].format(cluster_param[key])
command+=' {}'.format(jobscript)
eprint("submit command: "+command)
p = Popen(command.split(' '), stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0:
raise Exception("Job can't be submitted\n"+output.decode("utf-8")+error.decode("utf-8"))
else:
res= output.decode("utf-8")
jobid= int(res.strip().split()[2])
print(jobid)
| #!/usr/bin/env python3
import sys, os
from subprocess import Popen, PIPE
import yaml
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# let snakemake read job_properties
from snakemake.utils import read_job_properties
jobscript = sys.argv[1]
job_properties = read_job_properties(jobscript)
#default paramters defined in cluster_spec (accessed via snakemake read_job_properties)
cluster_param= job_properties["cluster"]
if job_properties["type"]=='single':
cluster_param['name'] = job_properties['rule']
elif job_properties["type"]=='group':
cluster_param['name'] = job_properties['groupid']
else:
raise NotImplementedError(f"Don't know what to do with job_properties['type']=={job_properties['type']}")
# don't overwrite default parameters if defined in rule (or config file)
cluster_param["threads"] = job_properties["threads"]
for res in ['time','mem']:
if (res in job_properties["resources"]) and (res not in cluster_param):
cluster_param[res] = job_properties["resources"][res]
# time in hours
if "time" in cluster_param:
cluster_param["time"]=int(cluster_param["time"]*60)
# check which system you are on and load command command_options
key_mapping_file=os.path.join(os.path.dirname(__file__),"key_mapping.yaml")
command_options=yaml.load(open(key_mapping_file),
Loader=yaml.BaseLoader)
command= command_options[command_options['system']]['command']
key_mapping= command_options[command_options['system']]['key_mapping']
# construct command:
for key in key_mapping:
if key in cluster_param:
if key == "highp":
if "highp" == cluster_param[key]:
command+=" "
command+=key_mapping[key].format(cluster_param[key])
else:
command+=" "
command+=key_mapping[key].format(cluster_param[key])
command+=' {}'.format(jobscript)
eprint("submit command: "+command)
p = Popen(command.split(' '), stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0:
raise Exception("Job can't be submitted\n"+output.decode("utf-8")+error.decode("utf-8"))
else:
res= output.decode("utf-8")
jobid= int(res.strip().split()[2])
print(jobid)
|
# -*- coding: utf-8 -*-
#
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Juergen Dammers <j.dammers@fz-juelich.de>
#
# License: BSD (3-clause)
from inspect import isfunction
from collections import namedtuple
from copy import deepcopy
from numbers import Integral
from time import time
import math
import os
import json
import numpy as np
from .ecg import (qrs_detector, _get_ecg_channel_index, _make_ecg,
create_ecg_epochs)
from .eog import _find_eog_events, _get_eog_channel_index
from .infomax_ import infomax
from ..cov import compute_whitener
from .. import Covariance, Evoked
from ..io.pick import (pick_types, pick_channels, pick_info,
_picks_to_idx, _get_channel_types, _DATA_CH_TYPES_SPLIT)
from ..io.proj import make_projector
from ..io.write import (write_double_matrix, write_string,
write_name_list, write_int, start_block,
end_block)
from ..io.tree import dir_tree_find
from ..io.open import fiff_open
from ..io.tag import read_tag
from ..io.meas_info import write_meas_info, read_meas_info
from ..io.constants import FIFF
from ..io.base import BaseRaw
from ..io.eeglab.eeglab import _get_info, _check_load_mat
from ..epochs import BaseEpochs
from ..viz import (plot_ica_components, plot_ica_scores,
plot_ica_sources, plot_ica_overlay)
from ..viz.ica import plot_ica_properties
from ..viz.topomap import _plot_corrmap
from ..channels.channels import _contains_ch_type, ContainsMixin
from ..io.write import start_file, end_file, write_id
from ..utils import (check_version, logger, check_fname, verbose,
_reject_data_segments, check_random_state, _validate_type,
compute_corr, _get_inst_data, _ensure_int,
copy_function_doc_to_method_doc, _pl, warn, Bunch,
_check_preload, _check_compensation_grade, fill_doc,
_check_option, _PCA, int_like,
_check_all_same_channel_names)
from ..fixes import _get_args, _safe_svd
from ..filter import filter_data
from .bads import _find_outliers
from .ctps_ import ctps
from ..io.pick import pick_channels_regexp
__all__ = ('ICA', 'ica_find_ecg_events', 'ica_find_eog_events',
'get_score_funcs', 'read_ica', 'read_ica_eeglab')
def _make_xy_sfunc(func, ndim_output=False):
"""Aux function."""
if ndim_output:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])[:, 0]
else:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])
sfunc.__name__ = '.'.join(['score_func', func.__module__, func.__name__])
sfunc.__doc__ = func.__doc__
return sfunc
# Violate our assumption that the output is 1D so can't be used.
# Could eventually be added but probably not worth the effort unless someone
# requests it.
_BLOCKLIST = {'somersd'}
# makes score funcs attr accessible for users
def get_score_funcs():
"""Get the score functions.
Returns
-------
score_funcs : dict
The score functions.
"""
from scipy import stats
from scipy.spatial import distance
score_funcs = Bunch()
xy_arg_dist_funcs = [(n, f) for n, f in vars(distance).items()
if isfunction(f) and not n.startswith('_') and
n not in _BLOCKLIST]
xy_arg_stats_funcs = [(n, f) for n, f in vars(stats).items()
if isfunction(f) and not n.startswith('_') and
n not in _BLOCKLIST]
score_funcs.update({n: _make_xy_sfunc(f)
for n, f in xy_arg_dist_funcs
if _get_args(f) == ['u', 'v']})
score_funcs.update({n: _make_xy_sfunc(f, ndim_output=True)
for n, f in xy_arg_stats_funcs
if _get_args(f) == ['x', 'y']})
return score_funcs
def _check_for_unsupported_ica_channels(picks, info, allow_ref_meg=False):
"""Check for channels in picks that are not considered valid channels.
Accepted channels are the data channels
('seeg', 'dbs', 'ecog', 'eeg', 'hbo', 'hbr', 'mag', and 'grad'), 'eog'
and 'ref_meg'.
This prevents the program from crashing without
feedback when a bad channel is provided to ICA whitening.
"""
types = _DATA_CH_TYPES_SPLIT + ('eog',)
types += ('ref_meg',) if allow_ref_meg else ()
chs = _get_channel_types(info, picks, unique=True, only_data_chs=False)
check = all([ch in types for ch in chs])
if not check:
raise ValueError('Invalid channel type%s passed for ICA: %s.'
'Only the following types are supported: %s'
% (_pl(chs), chs, types))
_KNOWN_ICA_METHODS = ('fastica', 'infomax', 'picard')
@fill_doc
class ICA(ContainsMixin):
u"""Data decomposition using Independent Component Analysis (ICA).
This object estimates independent components from :class:`mne.io.Raw`,
:class:`mne.Epochs`, or :class:`mne.Evoked` objects. Components can
optionally be removed (for artifact repair) prior to signal reconstruction.
.. warning:: ICA is sensitive to low-frequency drifts and therefore
requires the data to be high-pass filtered prior to fitting.
Typically, a cutoff frequency of 1 Hz is recommended.
Parameters
----------
n_components : int | float | None
Number of principal components (from the pre-whitening PCA step) that
are passed to the ICA algorithm during fitting:
- :class:`int`
Must be greater than 1 and less than or equal to the number of
channels.
- :class:`float` between 0 and 1 (exclusive)
Will select the smallest number of components required to explain
the cumulative variance of the data greater than ``n_components``.
Consider this hypothetical example: we have 3 components, the first
explaining 70%%, the second 20%%, and the third the remaining 10%%
of the variance. Passing 0.8 here (corresponding to 80%% of
explained variance) would yield the first two components,
explaining 90%% of the variance: only by using both components the
requested threshold of 80%% explained variance can be exceeded. The
third component, on the other hand, would be excluded.
- ``None``
``0.999999`` will be used. This is done to avoid numerical
stability problems when whitening, particularly when working with
rank-deficient data.
Defaults to ``None``. The actual number used when executing the
:meth:`ICA.fit` method will be stored in the attribute
``n_components_`` (note the trailing underscore).
.. versionchanged:: 0.22
For a :class:`python:float`, the number of components will account
for *greater than* the given variance level instead of *less than or
equal to* it. The default (None) will also take into account the
rank deficiency of the data.
noise_cov : None | instance of Covariance
Noise covariance used for pre-whitening. If None (default), channels
are scaled to unit variance ("z-standardized") as a group by channel
type prior to the whitening by PCA.
%(random_state)s
As estimation can be non-deterministic it can be useful to fix the
random state to have reproducible results.
method : {'fastica', 'infomax', 'picard'}
The ICA method to use in the fit method. Use the fit_params argument to
set additional parameters. Specifically, if you want Extended Infomax,
set method='infomax' and fit_params=dict(extended=True) (this also
works for method='picard'). Defaults to 'fastica'. For reference, see
:footcite:`Hyvarinen1999,BellSejnowski1995,LeeEtAl1999,AblinEtAl2018`.
fit_params : dict | None
Additional parameters passed to the ICA estimator as specified by
``method``.
max_iter : int
Maximum number of iterations during fit. Defaults to 200. The actual
number of iterations it took :meth:`ICA.fit` to complete will be stored
in the ``n_iter_`` attribute.
allow_ref_meg : bool
Allow ICA on MEG reference channels. Defaults to False.
.. versionadded:: 0.18
%(verbose)s
Attributes
----------
current_fit : str
Flag informing about which data type (raw or epochs) was used for the
fit.
ch_names : list-like
Channel names resulting from initial picking.
n_components_ : int
If fit, the actual number of PCA components used for ICA decomposition.
pre_whitener_ : ndarray, shape (n_channels, 1) or (n_channels, n_channels)
If fit, array used to pre-whiten the data prior to PCA.
pca_components_ : ndarray, shape ``(n_channels, n_channels)``
If fit, the PCA components.
pca_mean_ : ndarray, shape (n_channels,)
If fit, the mean vector used to center the data before doing the PCA.
pca_explained_variance_ : ndarray, shape ``(n_channels,)``
If fit, the variance explained by each PCA component.
mixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened mixing matrix to go back from ICA space to PCA
space.
It is, in combination with the ``pca_components_``, used by
:meth:`ICA.apply` and :meth:`ICA.get_components` to re-mix/project
a subset of the ICA components into the observed channel space.
The former method also removes the pre-whitening (z-scaling) and the
de-meaning.
unmixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened matrix to go from PCA space to ICA space.
Used, in combination with the ``pca_components_``, by the methods
:meth:`ICA.get_sources` and :meth:`ICA.apply` to unmix the observed
data.
exclude : array-like of int
List or np.array of sources indices to exclude when re-mixing the data
in the :meth:`ICA.apply` method, i.e. artifactual ICA components.
The components identified manually and by the various automatic
artifact detection methods should be (manually) appended
(e.g. ``ica.exclude.extend(eog_inds)``).
(There is also an ``exclude`` parameter in the :meth:`ICA.apply`
method.) To scrap all marked components, set this attribute to an empty
list.
info : None | instance of Info
The measurement info copied from the object fitted.
n_samples_ : int
The number of samples used on fit.
labels_ : dict
A dictionary of independent component indices, grouped by types of
independent components. This attribute is set by some of the artifact
detection functions.
n_iter_ : int
If fit, the number of iterations required to complete ICA.
Notes
-----
A trailing ``_`` in an attribute name signifies that the attribute was
added to the object during fitting, consistent with standard scikit-learn
practice.
ICA :meth:`fit` in MNE proceeds in two steps:
1. :term:`Whitening <whitening>` the data by means of a pre-whitening step
(using ``noise_cov`` if provided, or the standard deviation of each
channel type) and then principal component analysis (PCA).
2. Passing the ``n_components`` largest-variance components to the ICA
algorithm to obtain the unmixing matrix (and by pseudoinversion, the
mixing matrix).
ICA :meth:`apply` then:
1. Unmixes the data with the ``unmixing_matrix_``.
2. Includes ICA components based on ``ica.include`` and ``ica.exclude``.
3. Re-mixes the data with ``mixing_matrix_``.
4. Restores any data not passed to the ICA algorithm, i.e., the PCA
components between ``n_components`` and ``n_pca_components``.
``n_pca_components`` determines how many PCA components will be kept when
reconstructing the data when calling :meth:`apply`. This parameter can be
used for dimensionality reduction of the data, or dealing with low-rank
data (such as those with projections, or MEG data processed by SSS). It is
important to remove any numerically-zero-variance components in the data,
otherwise numerical instability causes problems when computing the mixing
matrix. Alternatively, using ``n_components`` as a float will also avoid
numerical stability problems.
The ``n_components`` parameter determines how many components out of
the ``n_channels`` PCA components the ICA algorithm will actually fit.
This is not typically used for EEG data, but for MEG data, it's common to
use ``n_components < n_channels``. For example, full-rank
306-channel MEG data might use ``n_components=40`` to find (and
later exclude) only large, dominating artifacts in the data, but still
reconstruct the data using all 306 PCA components. Setting
``n_pca_components=40``, on the other hand, would actually reduce the
rank of the reconstructed data to 40, which is typically undesirable.
If you are migrating from EEGLAB and intend to reduce dimensionality via
PCA, similarly to EEGLAB's ``runica(..., 'pca', n)`` functionality,
pass ``n_components=n`` during initialization and then
``n_pca_components=n`` during :meth:`apply`. The resulting reconstructed
data after :meth:`apply` will have rank ``n``.
.. note:: Commonly used for reasons of i) computational efficiency and
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease the
reliability and stability of the ICA, at least for EEG data and
especially during preprocessing :footcite:`ArtoniEtAl2018`.
(But see also :footcite:`Montoya-MartinezEtAl2017` for a
possibly confounding effect of the different whitening/sphering
methods used in this paper (ZCA vs. PCA).)
On the other hand, for rank-deficient data such as EEG data after
average reference or interpolation, it is recommended to reduce
the dimensionality (by 1 for average reference and 1 for each
interpolated channel) for optimal ICA performance (see the
`EEGLAB wiki <eeglab_wiki_>`_).
Caveat! If supplying a noise covariance, keep track of the projections
available in the cov or in the raw object. For example, if you are
interested in EOG or ECG artifacts, EOG and ECG projections should be
temporally removed before fitting ICA, for example::
>> projs, raw.info['projs'] = raw.info['projs'], []
>> ica.fit(raw)
>> raw.info['projs'] = projs
Methods currently implemented are FastICA (default), Infomax, and Picard.
Standard Infomax can be quite sensitive to differences in floating point
arithmetic. Extended Infomax seems to be more stable in this respect,
enhancing reproducibility and stability of results; use Extended Infomax
via ``method='infomax', fit_params=dict(extended=True)``. Allowed entries
in ``fit_params`` are determined by the various algorithm implementations:
see :class:`~sklearn.decomposition.FastICA`, :func:`~picard.picard`,
:func:`~mne.preprocessing.infomax`.
.. note:: Picard can be used to solve the same problems as FastICA,
Infomax, and extended Infomax, but typically converges faster
than either of those methods. To make use of Picard's speed while
still obtaining the same solution as with other algorithms, you
need to specify ``method='picard'`` and ``fit_params`` as a
dictionary with the following combination of keys:
- ``dict(ortho=False, extended=False)`` for Infomax
- ``dict(ortho=False, extended=True)`` for extended Infomax
- ``dict(ortho=True, extended=True)`` for FastICA
Reducing the tolerance (set in ``fit_params``) speeds up estimation at the
cost of consistency of the obtained results. It is difficult to directly
compare tolerance levels between Infomax and Picard, but for Picard and
FastICA a good rule of thumb is ``tol_fastica == tol_picard ** 2``.
.. _eeglab_wiki: https://sccn.ucsd.edu/wiki/Chapter_09:_Decomposing_Data_Using_ICA#Issue:_ICA_returns_near-identical_components_with_opposite_polarities
References
----------
.. footbibliography::
""" # noqa: E501
@verbose
def __init__(self, n_components=None, *, noise_cov=None,
random_state=None, method='fastica', fit_params=None,
max_iter=200, allow_ref_meg=False,
verbose=None): # noqa: D102
_validate_type(method, str, 'method')
_validate_type(n_components, (float, 'int-like', None))
if method != 'imported_eeglab': # internal use only
_check_option('method', method, _KNOWN_ICA_METHODS)
if method == 'fastica' and not check_version('sklearn'):
raise ImportError(
'The scikit-learn package is required for method="fastica".')
if method == 'picard' and not check_version('picard'):
raise ImportError(
'The python-picard package is required for method="picard".')
self.noise_cov = noise_cov
for (kind, val) in [('n_components', n_components)]:
if isinstance(val, float) and not 0 < val < 1:
raise ValueError('Selecting ICA components by explained '
'variance needs values between 0.0 and 1.0 '
f'(exclusive), got {kind}={val}')
if isinstance(val, int_like) and val == 1:
raise ValueError(
f'Selecting one component with {kind}={val} is not '
'supported')
self.current_fit = 'unfitted'
self.verbose = verbose
self.n_components = n_components
# In newer ICAs this should always be None, but keep it for
# backward compat with older versions of MNE that used it
self._max_pca_components = None
self.n_pca_components = None
self.ch_names = None
self.random_state = random_state
if fit_params is None:
fit_params = {}
fit_params = deepcopy(fit_params) # avoid side effects
if method == 'fastica':
update = {'algorithm': 'parallel', 'fun': 'logcosh',
'fun_args': None}
fit_params.update({k: v for k, v in update.items() if k
not in fit_params})
elif method == 'infomax':
# extended=True is default in underlying function, but we want
# default False here unless user specified True:
fit_params.setdefault('extended', False)
fit_params.setdefault('max_iter', max_iter)
self.max_iter = max_iter
self.fit_params = fit_params
self.exclude = []
self.info = None
self.method = method
self.labels_ = dict()
self.allow_ref_meg = allow_ref_meg
def __repr__(self):
"""ICA fit information."""
if self.current_fit == 'unfitted':
s = 'no'
elif self.current_fit == 'raw':
s = 'raw data'
else:
s = 'epochs'
s += ' decomposition, '
s += 'fit (%s): %s samples, ' % (self.method,
str(getattr(self, 'n_samples_', '')))
s += ('%s components' % str(self.n_components_) if
hasattr(self, 'n_components_') else
'no dimension reduction')
if self.info is not None:
ch_fit = ['"%s"' % c for c in _DATA_CH_TYPES_SPLIT if c in self]
s += ', channels used: {}'.format('; '.join(ch_fit))
if self.exclude:
s += ', %i sources marked for exclusion' % len(self.exclude)
return '<ICA | %s>' % s
@verbose
def fit(self, inst, picks=None, start=None, stop=None, decim=None,
reject=None, flat=None, tstep=2.0, reject_by_annotation=True,
verbose=None):
"""Run the ICA decomposition on raw data.
Caveat! If supplying a noise covariance keep track of the projections
available in the cov, the raw or the epochs object. For example,
if you are interested in EOG or ECG artifacts, EOG and ECG projections
should be temporally removed before fitting the ICA.
Parameters
----------
inst : instance of Raw or Epochs
Raw measurements to be decomposed.
%(picks_good_data_noref)s
This selection remains throughout the initialized ICA solution.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
decim : int | None
Increment for selecting each nth time slice. If None, all samples
within ``start`` and ``stop`` are used.
reject : dict | None
Rejection parameters based on peak-to-peak amplitude.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',
'ecg', 'hbo', 'hbr'.
If reject is None then no rejection is done. Example::
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=40e-6, # V (EEG channels)
eog=250e-6 # V (EOG channels)
)
It only applies if ``inst`` is of type Raw.
flat : dict | None
Rejection parameters based on flatness of signal.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',
'ecg', 'hbo', 'hbr'.
Values are floats that set the minimum acceptable peak-to-peak
amplitude. If flat is None then no rejection is done.
It only applies if ``inst`` is of type Raw.
tstep : float
Length of data chunks for artifact rejection in seconds.
It only applies if ``inst`` is of type Raw.
%(reject_by_annotation_raw)s
.. versionadded:: 0.14.0
%(verbose_meth)s
Returns
-------
self : instance of ICA
Returns the modified instance.
"""
_validate_type(inst, (BaseRaw, BaseEpochs), 'inst', 'Raw or Epochs')
picks = _picks_to_idx(inst.info, picks, allow_empty=False,
with_ref_meg=self.allow_ref_meg)
_check_for_unsupported_ica_channels(
picks, inst.info, allow_ref_meg=self.allow_ref_meg)
# Actually start fitting
t_start = time()
if self.current_fit != 'unfitted':
self._reset()
logger.info('Fitting ICA to data using %i channels '
'(please be patient, this may take a while)' % len(picks))
# n_components could be float 0 < x < 1, but that's okay here
if self.n_components is not None and self.n_components > len(picks):
raise ValueError(
f'ica.n_components ({self.n_components}) cannot '
f'be greater than len(picks) ({len(picks)})')
# filter out all the channels the raw wouldn't have initialized
self.info = pick_info(inst.info, picks)
if self.info['comps']:
self.info['comps'] = []
self.ch_names = self.info['ch_names']
if isinstance(inst, BaseRaw):
self._fit_raw(inst, picks, start, stop, decim, reject, flat,
tstep, reject_by_annotation, verbose)
else:
assert isinstance(inst, BaseEpochs)
self._fit_epochs(inst, picks, decim, verbose)
# sort ICA components by explained variance
var = _ica_explained_variance(self, inst)
var_ord = var.argsort()[::-1]
_sort_components(self, var_ord, copy=False)
t_stop = time()
logger.info("Fitting ICA took {:.1f}s.".format(t_stop - t_start))
return self
def _reset(self):
"""Aux method."""
for key in ('pre_whitener_', 'unmixing_matrix_', 'mixing_matrix_',
'n_components_', 'n_samples_', 'pca_components_',
'pca_explained_variance_',
'pca_mean_', 'n_iter_', 'drop_inds_', 'reject_'):
if hasattr(self, key):
delattr(self, key)
def _fit_raw(self, raw, picks, start, stop, decim, reject, flat, tstep,
reject_by_annotation, verbose):
"""Aux method."""
start, stop = _check_start_stop(raw, start, stop)
reject_by_annotation = 'omit' if reject_by_annotation else None
# this will be a copy
data = raw.get_data(picks, start, stop, reject_by_annotation)
# this will be a view
if decim is not None:
data = data[:, ::decim]
# this will make a copy
if (reject is not None) or (flat is not None):
self.reject_ = reject
data, self.drop_inds_ = _reject_data_segments(data, reject, flat,
decim, self.info,
tstep)
self.n_samples_ = data.shape[1]
self._fit(data, 'raw')
return self
def _fit_epochs(self, epochs, picks, decim, verbose):
"""Aux method."""
if epochs.events.size == 0:
raise RuntimeError('Tried to fit ICA with epochs, but none were '
'found: epochs.events is "{}".'
.format(epochs.events))
# this should be a copy (picks a list of int)
data = epochs.get_data()[:, picks]
# this will be a view
if decim is not None:
data = data[:, :, ::decim]
self.n_samples_ = data.shape[0] * data.shape[2]
# This will make at least one copy (one from hstack, maybe one
# more from _pre_whiten)
data = np.hstack(data)
self._fit(data, 'epochs')
return self
def _compute_pre_whitener(self, data):
"""Aux function."""
data = self._do_proj(data, log_suffix='(pre-whitener computation)')
if self.noise_cov is None:
# use standardization as whitener
# Scale (z-score) the data by channel type
info = self.info
pre_whitener = np.empty([len(data), 1])
for ch_type in _DATA_CH_TYPES_SPLIT + ('eog', "ref_meg"):
if _contains_ch_type(info, ch_type):
if ch_type == 'seeg':
this_picks = pick_types(info, meg=False, seeg=True)
elif ch_type == 'dbs':
this_picks = pick_types(info, meg=False, dbs=True)
elif ch_type == 'ecog':
this_picks = pick_types(info, meg=False, ecog=True)
elif ch_type == 'eeg':
this_picks = pick_types(info, meg=False, eeg=True)
elif ch_type in ('mag', 'grad'):
this_picks = pick_types(info, meg=ch_type)
elif ch_type == 'eog':
this_picks = pick_types(info, meg=False, eog=True)
elif ch_type in ('hbo', 'hbr'):
this_picks = pick_types(info, meg=False, fnirs=ch_type)
elif ch_type == 'ref_meg':
this_picks = pick_types(info, meg=False, ref_meg=True)
else:
raise RuntimeError('Should not be reached.'
'Unsupported channel {}'
.format(ch_type))
pre_whitener[this_picks] = np.std(data[this_picks])
else:
pre_whitener, _ = compute_whitener(self.noise_cov, self.info)
assert data.shape[0] == pre_whitener.shape[1]
self.pre_whitener_ = pre_whitener
def _do_proj(self, data, log_suffix=''):
if self.info is not None and self.info['projs']:
proj, nproj, _ = make_projector(
[p for p in self.info['projs'] if p['active']],
self.info['ch_names'], include_active=True)
if nproj:
logger.info(
f' Applying projection operator with {nproj} '
f'vector{_pl(nproj)}'
f'{' ' if log_suffix else ''}{log_suffix}')
if self.noise_cov is None: # otherwise it's in pre_whitener_
data = proj @ data
return data
def _pre_whiten(self, data):
data = self._do_proj(data, log_suffix='(pre-whitener application)')
if self.noise_cov is None:
data /= self.pre_whitener_
else:
data = self.pre_whitener_ @ data
return data
def _fit(self, data, fit_type):
"""Aux function."""
random_state = check_random_state(self.random_state)
n_channels, n_samples = data.shape
self._compute_pre_whitener(data)
data = self._pre_whiten(data)
pca = _PCA(n_components=self._max_pca_components, whiten=True)
data = pca.fit_transform(data.T)
use_ev = pca.explained_variance_ratio_
n_pca = self.n_pca_components
if isinstance(n_pca, float):
n_pca = int(_exp_var_ncomp(use_ev, n_pca)[0])
elif n_pca is None:
n_pca = len(use_ev)
assert isinstance(n_pca, (int, np.int_))
# If user passed a float, select the PCA components explaining the
# given cumulative variance. This information will later be used to
# only submit the corresponding parts of the data to ICA.
if self.n_components is None:
# None case: check if n_pca_components or 0.999999 yields smaller
msg = 'Selecting by non-zero PCA components'
self.n_components_ = min(
n_pca, _exp_var_ncomp(use_ev, 0.999999)[0])
elif isinstance(self.n_components, float):
self.n_components_, ev = _exp_var_ncomp(use_ev, self.n_components)
if self.n_components_ == 1:
raise RuntimeError(
'One PCA component captures most of the '
f'explained variance ({100 * ev}%), your threshold '
'results in 1 component. You should select '
'a higher value.')
msg = 'Selecting by explained variance'
else:
msg = 'Selecting by number'
self.n_components_ = _ensure_int(self.n_components)
# check to make sure something okay happened
if self.n_components_ > n_pca:
ev = np.cumsum(use_ev)
ev /= ev[-1]
evs = 100 * ev[[self.n_components_ - 1, n_pca - 1]]
raise RuntimeError(
f'n_components={self.n_components} requires '
f'{self.n_components_} PCA values (EV={evs[0]:0.1f}%) but '
f'n_pca_components ({self.n_pca_components}) results in '
f'only {n_pca} components (EV={evs[1]:0.1f}%)')
logger.info('%s: %s components' % (msg, self.n_components_))
# the things to store for PCA
self.pca_mean_ = pca.mean_
self.pca_components_ = pca.components_
self.pca_explained_variance_ = pca.explained_variance_
del pca
# update number of components
self._update_ica_names()
if self.n_pca_components is not None and \
self.n_pca_components > len(self.pca_components_):
raise ValueError(
f'n_pca_components ({self.n_pca_components}) is greater than '
f'the number of PCA components ({len(self.pca_components_)})')
# take care of ICA
sel = slice(0, self.n_components_)
if self.method == 'fastica':
from sklearn.decomposition import FastICA
ica = FastICA(
whiten=False, random_state=random_state, **self.fit_params)
ica.fit(data[:, sel])
self.unmixing_matrix_ = ica.components_
self.n_iter_ = ica.n_iter_
elif self.method in ('infomax', 'extended-infomax'):
unmixing_matrix, n_iter = infomax(
data[:, sel], random_state=random_state, return_n_iter=True,
**self.fit_params)
self.unmixing_matrix_ = unmixing_matrix
self.n_iter_ = n_iter
del unmixing_matrix, n_iter
elif self.method == 'picard':
from picard import picard
_, W, _, n_iter = picard(
data[:, sel].T, whiten=False, return_n_iter=True,
random_state=random_state, **self.fit_params)
self.unmixing_matrix_ = W
self.n_iter_ = n_iter + 1 # picard() starts counting at 0
del _, n_iter
assert self.unmixing_matrix_.shape == (self.n_components_,) * 2
norms = self.pca_explained_variance_
stable = norms / norms[0] > 1e-6 # to be stable during pinv
norms = norms[:self.n_components_]
if not stable[self.n_components_ - 1]:
max_int = np.where(stable)[0][-1] + 1
warn(f'Using n_components={self.n_components} (resulting in '
f'n_components_={self.n_components_}) may lead to an '
f'unstable mixing matrix estimation because the ratio '
f'between the largest ({norms[0]:0.2g}) and smallest '
f'({norms[-1]:0.2g}) variances is too large (> 1e6); '
f'consider setting n_components=0.999999 or an '
f'integer <= {max_int}')
norms = np.sqrt(norms)
norms[norms == 0] = 1.
self.unmixing_matrix_ /= norms # whitening
self._update_mixing_matrix()
self.current_fit = fit_type
def _update_mixing_matrix(self):
from scipy import linalg
self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
def _update_ica_names(self):
"""Update ICA names when n_components_ is set."""
self._ica_names = ['ICA%03d' % ii for ii in range(self.n_components_)]
def _transform(self, data):
"""Compute sources from data (operates inplace)."""
data = self._pre_whiten(data)
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
# Apply first PCA
pca_data = np.dot(self.pca_components_[:self.n_components_], data)
# Apply unmixing to low dimension PCA
sources = np.dot(self.unmixing_matrix_, pca_data)
return sources
def _transform_raw(self, raw, start, stop, reject_by_annotation=False):
"""Transform raw data."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
start, stop = _check_start_stop(raw, start, stop)
picks = pick_types(raw.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Raw doesn\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Raw compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
reject = 'omit' if reject_by_annotation else None
data = raw.get_data(picks, start, stop, reject)
return self._transform(data)
def _transform_epochs(self, epochs, concatenate):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
picks = pick_types(epochs.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
# special case where epochs come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Epochs don\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Epochs compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data = np.hstack(epochs.get_data()[:, picks])
sources = self._transform(data)
if not concatenate:
# Put the data back in 3D
sources = np.array(np.split(sources, len(epochs.events), 1))
return sources
def _transform_evoked(self, evoked):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
picks = pick_types(evoked.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Evoked doesn\'t match fitted data: %i channels'
' fitted but %i channels supplied. \nPlease '
'provide Evoked compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
sources = self._transform(evoked.data[picks])
return sources
def get_components(self):
"""Get ICA topomap for components as numpy arrays.
Returns
-------
components : array, shape (n_channels, n_components)
The ICA components (maps).
"""
return np.dot(self.mixing_matrix_[:, :self.n_components_].T,
self.pca_components_[:self.n_components_]).T
def get_sources(self, inst, add_channels=None, start=None, stop=None):
"""Estimate sources given the unmixing matrix.
This method will return the sources in the container format passed.
Typical usecases:
1. pass Raw object to use `raw.plot <mne.io.Raw.plot>` for ICA sources
2. pass Epochs object to compute trial-based statistics in ICA space
3. pass Evoked object to investigate time-locking in ICA space
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from and to represent sources in.
add_channels : None | list of str
Additional channels to be added. Useful to e.g. compare sources
with some reference. Defaults to None.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
Returns
-------
sources : instance of Raw, Epochs or Evoked
The ICA sources time series.
"""
if isinstance(inst, BaseRaw):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',
ch_names=self.ch_names)
sources = self._sources_as_raw(inst, add_channels, start, stop)
elif isinstance(inst, BaseEpochs):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',
ch_names=self.ch_names)
sources = self._sources_as_epochs(inst, add_channels, False)
elif isinstance(inst, Evoked):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',
ch_names=self.ch_names)
sources = self._sources_as_evoked(inst, add_channels)
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
return sources
def _sources_as_raw(self, raw, add_channels, start, stop):
"""Aux method."""
# merge copied instance and picked data with sources
start, stop = _check_start_stop(raw, start, stop)
data_ = self._transform_raw(raw, start=start, stop=stop)
assert data_.shape[1] == stop - start
if raw.preload: # get data and temporarily delete
data = raw._data
del raw._data
out = raw.copy() # copy and reappend
if raw.preload:
raw._data = data
# populate copied raw.
if add_channels is not None and len(add_channels):
picks = pick_channels(raw.ch_names, add_channels)
data_ = np.concatenate([
data_, raw.get_data(picks, start=start, stop=stop)])
out._data = data_
out._filenames = [None]
out.preload = True
out._first_samps[:] = [out.first_samp + start]
out._last_samps[:] = [out.first_samp + data_.shape[1] - 1]
out._projector = None
self._export_info(out.info, raw, add_channels)
return out
def _sources_as_epochs(self, epochs, add_channels, concatenate):
"""Aux method."""
out = epochs.copy()
sources = self._transform_epochs(epochs, concatenate)
if add_channels is not None:
picks = [epochs.ch_names.index(k) for k in add_channels]
else:
picks = []
out._data = np.concatenate([sources, epochs.get_data()[:, picks]],
axis=1) if len(picks) > 0 else sources
self._export_info(out.info, epochs, add_channels)
out.preload = True
out._raw = None
out._projector = None
return out
def _sources_as_evoked(self, evoked, add_channels):
"""Aux method."""
if add_channels is not None:
picks = [evoked.ch_names.index(k) for k in add_channels]
else:
picks = []
sources = self._transform_evoked(evoked)
if len(picks) > 1:
data = np.r_[sources, evoked.data[picks]]
else:
data = sources
out = evoked.copy()
out.data = data
self._export_info(out.info, evoked, add_channels)
return out
def _export_info(self, info, container, add_channels):
"""Aux method."""
# set channel names and info
ch_names = []
ch_info = info['chs'] = []
for ii, name in enumerate(self._ica_names):
ch_names.append(name)
ch_info.append(dict(
ch_name=name, cal=1, logno=ii + 1,
coil_type=FIFF.FIFFV_COIL_NONE, kind=FIFF.FIFFV_MISC_CH,
coord_frame=FIFF.FIFFV_COORD_UNKNOWN, unit=FIFF.FIFF_UNIT_NONE,
loc=np.zeros(12, dtype='f4'),
range=1.0, scanno=ii + 1, unit_mul=0))
if add_channels is not None:
# re-append additionally picked ch_names
ch_names += add_channels
# re-append additionally picked ch_info
ch_info += [k for k in container.info['chs'] if k['ch_name'] in
add_channels]
info['bads'] = [ch_names[k] for k in self.exclude]
info['projs'] = [] # make sure projections are removed.
info._update_redundant()
info._check_consistency()
@verbose
def score_sources(self, inst, target=None, score_func='pearsonr',
start=None, stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, verbose=None):
"""Assign score to components based on statistic or metric.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
The object to reconstruct the sources from.
target : array-like | str | None
Signal to which the sources shall be compared. It has to be of
the same shape as the sources. If str, a routine will try to find
a matching channel name. If None, a score
function expecting only one input-array argument must be used,
for instance, scipy.stats.skew (default).
score_func : callable | str
Callable taking as arguments either two input arrays
(e.g. Pearson correlation) or one input
array (e. g. skewness) and returns a float. For convenience the
most common score_funcs are available via string labels:
Currently, all distance metrics from scipy.spatial and All
functions from scipy.stats taking compatible input arguments are
supported. These function have been modified to support iteration
over the rows of a 2D array.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
%(verbose_meth)s
Returns
-------
scores : ndarray
Scores for each source as returned from score_func.
"""
if isinstance(inst, BaseRaw):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',
ch_names=self.ch_names)
sources = self._transform_raw(inst, start, stop,
reject_by_annotation)
elif isinstance(inst, BaseEpochs):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',
ch_names=self.ch_names)
sources = self._transform_epochs(inst, concatenate=True)
elif isinstance(inst, Evoked):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',
ch_names=self.ch_names)
sources = self._transform_evoked(inst)
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
if target is not None: # we can have univariate metrics without target
target = self._check_target(target, inst, start, stop,
reject_by_annotation)
if sources.shape[-1] != target.shape[-1]:
raise ValueError('Sources and target do not have the same '
'number of time slices.')
# auto target selection
if isinstance(inst, BaseRaw):
# We pass inst, not self, because the sfreq of the data we
# use for scoring components can be different:
sources, target = _band_pass_filter(inst, sources, target,
l_freq, h_freq)
scores = _find_sources(sources, target, score_func)
return scores
def _check_target(self, target, inst, start, stop,
reject_by_annotation=False):
"""Aux Method."""
if isinstance(inst, BaseRaw):
reject_by_annotation = 'omit' if reject_by_annotation else None
start, stop = _check_start_stop(inst, start, stop)
if hasattr(target, 'ndim'):
if target.ndim < 2:
target = target.reshape(1, target.shape[-1])
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.get_data(pick, start, stop, reject_by_annotation)
elif isinstance(inst, BaseEpochs):
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.get_data()[:, pick]
if hasattr(target, 'ndim'):
if target.ndim == 3 and min(target.shape) == 1:
target = target.ravel()
elif isinstance(inst, Evoked):
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.data[pick]
return target
def _find_bads_ch(self, inst, chs, threshold=3.0, start=None,
stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, prefix='chs',
measure='zscore'):
"""Compute ExG/ref components.
See find_bads_ecg, find_bads_eog, and find_bads_ref for details.
"""
scores, idx = [], []
# some magic we need inevitably ...
# get targets before equalizing
targets = [self._check_target(
ch, inst, start, stop, reject_by_annotation) for ch in chs]
# assign names, if targets are arrays instead of strings
target_names = []
for ch in chs:
if not isinstance(ch, str):
if prefix == "ecg":
target_names.append('ECG-MAG')
else:
target_names.append(prefix)
else:
target_names.append(ch)
for ii, (ch, target) in enumerate(zip(target_names, targets)):
scores += [self.score_sources(
inst, target=target, score_func='pearsonr', start=start,
stop=stop, l_freq=l_freq, h_freq=h_freq,
reject_by_annotation=reject_by_annotation)]
# pick last scores
if measure == "zscore":
this_idx = _find_outliers(scores[-1], threshold=threshold)
elif measure == "correlation":
this_idx = np.where(abs(scores[-1]) > threshold)[0]
else:
raise ValueError("Unknown measure {}".format(measure))
idx += [this_idx]
self.labels_['%s/%i/' % (prefix, ii) + ch] = list(this_idx)
# remove duplicates but keep order by score, even across multiple
# ref channels
scores_ = np.concatenate([scores[ii][inds]
for ii, inds in enumerate(idx)])
idx_ = np.concatenate(idx)[np.abs(scores_).argsort()[::-1]]
idx_unique = list(np.unique(idx_))
idx = []
for i in idx_:
if i in idx_unique:
idx.append(i)
idx_unique.remove(i)
if len(scores) == 1:
scores = scores[0]
labels = list(idx)
return labels, scores
def _get_ctps_threshold(self, pk_threshold=20):
"""Automatically decide the threshold of Kuiper index for CTPS method.
This function finds the threshold of Kuiper index based on the
threshold of pk. Kuiper statistic that minimizes the difference between
pk and the pk threshold (defaults to 20 [1]) is returned. It is assumed
that the data are appropriately filtered and bad data are rejected at
least based on peak-to-peak amplitude when/before running the ICA
decomposition on data.
References
----------
[1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,
M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude
and phase statistics for complete artifact removal in independent
components of neuromagnetic recordings. Biomedical
Engineering, IEEE Transactions on 55 (10), pp.2356.
"""
N = self.info['sfreq']
Vs = np.arange(1, 100) / 100
C = math.sqrt(N) + 0.155 + 0.24 / math.sqrt(N)
# in formula (13), when k gets large, only k=1 matters for the
# summation. k*V*C thus becomes V*C
Pks = 2 * (4 * (Vs * C)**2 - 1) * (np.exp(-2 * (Vs * C)**2))
# NOTE: the threshold of pk is transformed to Pk for comparison
# pk = -log10(Pk)
return Vs[np.argmin(np.abs(Pks - 10**(-pk_threshold)))]
@verbose
def find_bads_ecg(self, inst, ch_name=None, threshold='auto', start=None,
stop=None, l_freq=8, h_freq=16, method='ctps',
reject_by_annotation=True, measure='zscore',
verbose=None):
"""Detect ECG related components.
Cross-trial phase statistics (default) or Pearson correlation can be
used for detection.
.. note:: If no ECG channel is available, routine attempts to create
an artificial ECG based on cross-channel averaging.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from.
ch_name : str
The name of the channel to use for ECG peak detection.
The argument is mandatory if the dataset contains no ECG
channels.
threshold : float | str
The value above which a feature is classified as outlier. If 'auto'
and method is 'ctps', automatically compute the threshold. If
'auto' and method is 'correlation', defaults to 3.0. The default
translates to 0.25 for 'ctps' and 3.0 for 'correlation' in version
0.21 but will change to 'auto' in version 0.22.
.. versionchanged:: 0.21
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
method : {'ctps', 'correlation'}
The method used for detection. If 'ctps', cross-trial phase
statistics [1] are used to detect ECG related components.
Thresholding is then based on the significance value of a Kuiper
statistic.
If 'correlation', detection is based on Pearson correlation
between the filtered data and the filtered ECG channel.
Thresholding is based on iterative z-scoring. The above
threshold components will be masked and the z-score will
be recomputed until no supra-threshold component remains.
Defaults to 'ctps'.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
ecg_idx : list of int
The indices of ECG-related components.
scores : np.ndarray of float, shape (``n_components_``)
If method is 'ctps', the normalized Kuiper index scores. If method
is 'correlation', the correlation scores.
See Also
--------
find_bads_eog, find_bads_ref
References
----------
[1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,
M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude
and phase statistics for complete artifact removal in independent
components of neuromagnetic recordings. Biomedical
Engineering, IEEE Transactions on 55 (10), 2353-2362.
"""
idx_ecg = _get_ecg_channel_index(ch_name, inst)
if idx_ecg is None:
ecg, times = _make_ecg(inst, start, stop,
reject_by_annotation=reject_by_annotation)
else:
ecg = inst.ch_names[idx_ecg]
_validate_type(threshold, (str, 'numeric'), 'threshold')
if isinstance(threshold, str):
_check_option('threshold', threshold, ('auto',), extra='when str')
if method == 'ctps':
if threshold == 'auto':
threshold = self._get_ctps_threshold()
logger.info('Using threshold: %.2f for CTPS ECG detection'
% threshold)
if isinstance(inst, BaseRaw):
sources = self.get_sources(create_ecg_epochs(
inst, ch_name, l_freq=l_freq, h_freq=h_freq,
keep_ecg=False,
reject_by_annotation=reject_by_annotation)).get_data()
if sources.shape[0] == 0:
warn('No ECG activity detected. Consider changing '
'the input parameters.')
elif isinstance(inst, BaseEpochs):
sources = self.get_sources(inst).get_data()
else:
raise ValueError('With `ctps` only Raw and Epochs input is '
'supported')
_, p_vals, _ = ctps(sources)
scores = p_vals.max(-1)
ecg_idx = np.where(scores >= threshold)[0]
# sort indices by scores
ecg_idx = ecg_idx[np.abs(scores[ecg_idx]).argsort()[::-1]]
self.labels_['ecg'] = list(ecg_idx)
if ch_name is None:
ch_name = 'ECG-MAG'
self.labels_['ecg/%s' % ch_name] = list(ecg_idx)
elif method == 'correlation':
if threshold == 'auto':
threshold = 3.0
self.labels_['ecg'], scores = self._find_bads_ch(
inst, [ecg], threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix="ecg",
reject_by_annotation=reject_by_annotation, measure=measure)
else:
raise ValueError('Method "%s" not supported.' % method)
return self.labels_['ecg'], scores
@verbose
def find_bads_ref(self, inst, ch_name=None, threshold=3.0, start=None,
stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, method='together',
measure="zscore", verbose=None):
"""Detect MEG reference related components using correlation.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from. Should contain at least one channel
i.e. component derived from MEG reference channels.
ch_name : list of str
Which MEG reference components to use. If None, then all channels
that begin with REF_ICA.
threshold : int | float
The value above which a feature is classified as outlier.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
method : 'together' | 'separate'
Method to use to identify reference channel related components.
Defaults to ``'together'``. See notes.
.. versionadded:: 0.21
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
ref_idx : list of int
The indices of MEG reference related components, sorted by score.
scores : np.ndarray of float, shape (``n_components_``) | list of array
The correlation scores.
See Also
--------
find_bads_ecg, find_bads_eog
Notes
-----
ICA decomposition on MEG reference channels is used to assess external
magnetic noise and remove it from the MEG. Two methods are supported:
With the "together" method, only one ICA fit is used, which
encompasses both MEG and reference channels together. Components which
have particularly strong weights on the reference channels may be
thresholded and marked for removal.
With "separate," selected components from a separate ICA decomposition
on the reference channels are used as a ground truth for identifying
bad components in an ICA fit done on MEG channels only. The logic here
is similar to an EOG/ECG, with reference components replacing the
EOG/ECG channels. Recommended procedure is to perform ICA separately
on reference channels, extract them using .get_sources(), and then
append them to the inst using :meth:`~mne.io.Raw.add_channels`,
preferably with the prefix ``REF_ICA`` so that they can be
automatically detected.
Thresholding in both cases is based on adaptive z-scoring:
The above-threshold components will be masked and the z-score will be
recomputed until no supra-threshold component remains.
Validation and further documentation for this technique can be found
in :footcite:`HannaEtAl2020`.
.. versionadded:: 0.18
References
----------
.. footbibliography::
"""
if method == "separate":
if not ch_name:
inds = pick_channels_regexp(inst.ch_names, 'REF_ICA*')
else:
inds = pick_channels(inst.ch_names, ch_name)
# regexp returns list, pick_channels returns numpy
inds = list(inds)
if not inds:
raise ValueError('No valid channels available.')
ref_chs = [inst.ch_names[k] for k in inds]
self.labels_['ref_meg'], scores = self._find_bads_ch(
inst, ref_chs, threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix='ref_meg',
reject_by_annotation=reject_by_annotation,
measure=measure)
elif method == 'together':
meg_picks = pick_types(self.info, meg=True, ref_meg=False)
ref_picks = pick_types(self.info, meg=False, ref_meg=True)
if not any(meg_picks) or not any(ref_picks):
raise ValueError('ICA solution must contain both reference and\
MEG channels.')
weights = self.get_components()
# take norm of component weights on reference channels for each
# component, divide them by the norm on the standard channels,
# log transform to approximate normal distribution
normrats = np.linalg.norm(weights[ref_picks],
axis=0) / np.linalg.norm(weights[meg_picks], # noqa
axis=0)
scores = np.log(normrats)
self.labels_['ref_meg'] = list(_find_outliers(scores,
threshold=threshold,
tail=1))
else:
raise ValueError('Method "%s" not supported.' % method)
return self.labels_['ref_meg'], scores
@verbose
def find_bads_eog(self, inst, ch_name=None, threshold=3.0, start=None,
stop=None, l_freq=1, h_freq=10,
reject_by_annotation=True, measure='zscore',
verbose=None):
"""Detect EOG related components using correlation.
Detection is based on Pearson correlation between the
filtered data and the filtered EOG channel.
Thresholding is based on adaptive z-scoring. The above threshold
components will be masked and the z-score will be recomputed
until no supra-threshold component remains.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from.
ch_name : str
The name of the channel to use for EOG peak detection.
The argument is mandatory if the dataset contains no EOG
channels.
threshold : int | float
The value above which a feature is classified as outlier.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
eog_idx : list of int
The indices of EOG related components, sorted by score.
scores : np.ndarray of float, shape (``n_components_``) | list of array
The correlation scores.
See Also
--------
find_bads_ecg, find_bads_ref
"""
eog_inds = _get_eog_channel_index(ch_name, inst)
eog_chs = [inst.ch_names[k] for k in eog_inds]
self.labels_['eog'], scores = self._find_bads_ch(
inst, eog_chs, threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix="eog",
reject_by_annotation=reject_by_annotation, measure=measure)
return self.labels_['eog'], scores
@verbose
def apply(self, inst, include=None, exclude=None, n_pca_components=None,
start=None, stop=None, verbose=None):
"""Remove selected components from the signal.
Given the unmixing matrix, transform data,
zero out components, and inverse transform the data.
This procedure will reconstruct M/EEG signals from which
the dynamics described by the excluded components is subtracted.
The data is processed in place.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
The data to be processed. The instance is modified inplace.
include : array_like of int
The indices referring to columns in the ummixing matrix. The
components to be kept.
exclude : array_like of int
The indices referring to columns in the ummixing matrix. The
components to be zeroed out.
%(n_pca_components_apply)s
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
%(verbose_meth)s
Returns
-------
out : instance of Raw, Epochs or Evoked
The processed data.
"""
_validate_type(inst, (BaseRaw, BaseEpochs, Evoked), 'inst',
'Raw, Epochs, or Evoked')
kwargs = dict(include=include, exclude=exclude,
n_pca_components=n_pca_components)
if isinstance(inst, BaseRaw):
kind, meth = 'Raw', self._apply_raw
kwargs.update(raw=inst, start=start, stop=stop)
elif isinstance(inst, BaseEpochs):
kind, meth = 'Epochs', self._apply_epochs
kwargs.update(epochs=inst)
else: # isinstance(inst, Evoked):
kind, meth = 'Evoked', self._apply_evoked
kwargs.update(evoked=inst)
_check_compensation_grade(self.info, inst.info, 'ICA', kind,
ch_names=self.ch_names)
logger.info(f'Applying ICA to {kind} instance')
return meth(**kwargs)
def _check_exclude(self, exclude):
if exclude is None:
return list(set(self.exclude))
else:
# Allow both self.exclude and exclude to be array-like:
return list(set(self.exclude).union(set(exclude)))
def _apply_raw(self, raw, include, exclude, n_pca_components, start, stop):
"""Aux method."""
_check_preload(raw, "ica.apply")
start, stop = _check_start_stop(raw, start, stop)
picks = pick_types(raw.info, meg=False, include=self.ch_names,
exclude='bads', ref_meg=False)
data = raw[picks, start:stop][0]
data = self._pick_sources(data, include, exclude, n_pca_components)
raw[picks, start:stop] = data
return raw
def _apply_epochs(self, epochs, include, exclude, n_pca_components):
"""Aux method."""
_check_preload(epochs, "ica.apply")
picks = pick_types(epochs.info, meg=False, ref_meg=False,
include=self.ch_names,
exclude='bads')
# special case where epochs come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Epochs don\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Epochs compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data = np.hstack(epochs.get_data(picks))
data = self._pick_sources(data, include, exclude, n_pca_components)
# restore epochs, channels, tsl order
epochs._data[:, picks] = np.array(
np.split(data, len(epochs.events), 1))
epochs.preload = True
return epochs
def _apply_evoked(self, evoked, include, exclude, n_pca_components):
"""Aux method."""
picks = pick_types(evoked.info, meg=False, ref_meg=False,
include=self.ch_names,
exclude='bads')
# special case where evoked come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Evoked does not match fitted data: %i channels'
' fitted but %i channels supplied. \nPlease '
'provide an Evoked object that\'s compatible '
'with ica.ch_names' % (len(self.ch_names),
len(picks)))
data = evoked.data[picks]
data = self._pick_sources(data, include, exclude, n_pca_components)
# restore evoked
evoked.data[picks] = data
return evoked
def _pick_sources(self, data, include, exclude, n_pca_components):
"""Aux function."""
if n_pca_components is None:
n_pca_components = self.n_pca_components
data = self._pre_whiten(data)
exclude = self._check_exclude(exclude)
_n_pca_comp = self._check_n_pca_components(n_pca_components)
n_ch, _ = data.shape
max_pca_components = self.pca_components_.shape[0]
if not self.n_components_ <= _n_pca_comp <= max_pca_components:
raise ValueError(
f'n_pca_components ({_n_pca_comp}) must be >= '
f'n_components_ ({self.n_components_}) and <= '
'the total number of PCA components '
f'({max_pca_components}).')
logger.info(f' Transforming to ICA space ({self.n_components_} '
f'component{_pl(self.n_components_)})')
# Apply first PCA
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
sel_keep = np.arange(self.n_components_)
if include not in (None, []):
sel_keep = np.unique(include)
elif exclude not in (None, []):
sel_keep = np.setdiff1d(np.arange(self.n_components_), exclude)
n_zero = self.n_components_ - len(sel_keep)
logger.info(f' Zeroing out {n_zero} ICA component{_pl(n_zero)}')
# Mixing and unmixing should both be shape (self.n_components_, 2),
# and we need to put these into the upper left part of larger mixing
# and unmixing matrices of shape (n_ch, _n_pca_comp)
pca_components = self.pca_components_[:_n_pca_comp]
assert pca_components.shape == (_n_pca_comp, n_ch)
assert self.unmixing_matrix_.shape == \
self.mixing_matrix_.shape == \
(self.n_components_,) * 2
unmixing = np.eye(_n_pca_comp)
unmixing[:self.n_components_, :self.n_components_] = \
self.unmixing_matrix_
unmixing = np.dot(unmixing, pca_components)
logger.info(f' Projecting back using {_n_pca_comp} '
f'PCA component{_pl(_n_pca_comp)}')
mixing = np.eye(_n_pca_comp)
mixing[:self.n_components_, :self.n_components_] = \
self.mixing_matrix_
mixing = pca_components.T @ mixing
assert mixing.shape == unmixing.shape[::-1] == (n_ch, _n_pca_comp)
# keep requested components plus residuals (if any)
sel_keep = np.concatenate(
(sel_keep, np.arange(self.n_components_, _n_pca_comp)))
proj_mat = np.dot(mixing[:, sel_keep], unmixing[sel_keep, :])
data = np.dot(proj_mat, data)
assert proj_mat.shape == (n_ch,) * 2
if self.pca_mean_ is not None:
data += self.pca_mean_[:, None]
# restore scaling
if self.noise_cov is None: # revert standardization
data *= self.pre_whitener_
else:
data = np.linalg.pinv(self.pre_whitener_, rcond=1e-14) @ data
return data
@verbose
def save(self, fname, verbose=None):
"""Store ICA solution into a fiff file.
Parameters
----------
fname : str
The absolute path of the file name to save the ICA solution into.
The file name should end with -ica.fif or -ica.fif.gz.
%(verbose_meth)s
Returns
-------
ica : instance of ICA
The object.
See Also
--------
read_ica
"""
if self.current_fit == 'unfitted':
raise RuntimeError('No fit available. Please first fit ICA')
check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',
'_ica.fif', '_ica.fif.gz'))
logger.info('Writing ICA solution to %s...' % fname)
fid = start_file(fname)
try:
_write_ica(fid, self)
end_file(fid)
except Exception:
end_file(fid)
os.remove(fname)
raise
return self
def copy(self):
"""Copy the ICA object.
Returns
-------
ica : instance of ICA
The copied object.
"""
return deepcopy(self)
@copy_function_doc_to_method_doc(plot_ica_components)
def plot_components(self, picks=None, ch_type=None, res=64,
vmin=None, vmax=None, cmap='RdBu_r', sensors=True,
colorbar=False, title=None, show=True, outlines='head',
contours=6, image_interp='bilinear',
inst=None, plot_std=True, topomap_args=None,
image_args=None, psd_args=None, reject='auto',
sphere=None, verbose=None):
return plot_ica_components(self, picks=picks, ch_type=ch_type,
res=res, vmin=vmin,
vmax=vmax, cmap=cmap, sensors=sensors,
colorbar=colorbar, title=title, show=show,
outlines=outlines, contours=contours,
image_interp=image_interp,
inst=inst, plot_std=plot_std,
topomap_args=topomap_args,
image_args=image_args, psd_args=psd_args,
reject=reject, sphere=sphere,
verbose=verbose)
@copy_function_doc_to_method_doc(plot_ica_properties)
def plot_properties(self, inst, picks=None, axes=None, dB=True,
plot_std=True, topomap_args=None, image_args=None,
psd_args=None, figsize=None, show=True, reject='auto',
reject_by_annotation=True, *, verbose=None):
return plot_ica_properties(self, inst, picks=picks, axes=axes,
dB=dB, plot_std=plot_std,
topomap_args=topomap_args,
image_args=image_args, psd_args=psd_args,
figsize=figsize, show=show, reject=reject,
reject_by_annotation=reject_by_annotation,
verbose=verbose)
@copy_function_doc_to_method_doc(plot_ica_sources)
def plot_sources(self, inst, picks=None, start=None,
stop=None, title=None, show=True, block=False,
show_first_samp=False, show_scrollbars=True):
return plot_ica_sources(self, inst=inst, picks=picks,
start=start, stop=stop, title=title, show=show,
block=block, show_first_samp=show_first_samp,
show_scrollbars=show_scrollbars)
@copy_function_doc_to_method_doc(plot_ica_scores)
def plot_scores(self, scores, exclude=None, labels=None, axhline=None,
title='ICA component scores', figsize=None, n_cols=None,
show=True):
return plot_ica_scores(
ica=self, scores=scores, exclude=exclude, labels=labels,
axhline=axhline, title=title, figsize=figsize, n_cols=n_cols,
show=show)
@copy_function_doc_to_method_doc(plot_ica_overlay)
def plot_overlay(self, inst, exclude=None, picks=None, start=None,
stop=None, title=None, show=True, n_pca_components=None):
return plot_ica_overlay(self, inst=inst, exclude=exclude, picks=picks,
start=start, stop=stop, title=title, show=show,
n_pca_components=n_pca_components)
def detect_artifacts(self, raw, start_find=None, stop_find=None,
ecg_ch=None, ecg_score_func='pearsonr',
ecg_criterion=0.1, eog_ch=None,
eog_score_func='pearsonr',
eog_criterion=0.1, skew_criterion=0,
kurt_criterion=0, var_criterion=-1,
add_nodes=None):
"""Run ICA artifacts detection workflow.
Note. This is still experimental and will most likely change over
the next releases. For maximum control use the workflow exposed in
the examples.
Hints and caveats:
- It is highly recommended to bandpass filter ECG and EOG
data and pass them instead of the channel names as ecg_ch and eog_ch
arguments.
- please check your results. Detection by kurtosis and variance
may be powerful but misclassification of brain signals as
noise cannot be precluded.
- Consider using shorter times for start_find and stop_find than
for start and stop. It can save you much time.
Example invocation (taking advantage of the defaults)::
ica.detect_artifacts(ecg_channel='MEG 1531', eog_channel='EOG 061')
Parameters
----------
raw : instance of Raw
Raw object to draw sources from. No components are actually removed
here, i.e. ica is not applied to raw in this function. Use
`ica.apply() <ICA.apply>` for this after inspection of the
identified components.
start_find : int | float | None
First sample to include for artifact search. If float, data will be
interpreted as time in seconds. If None, data will be used from the
first sample.
stop_find : int | float | None
Last sample to not include for artifact search. If float, data will
be interpreted as time in seconds. If None, data will be used to
the last sample.
ecg_ch : str | ndarray | None
The ``target`` argument passed to ica.find_sources_raw. Either the
name of the ECG channel or the ECG time series. If None, this step
will be skipped.
ecg_score_func : str | callable
The ``score_func`` argument passed to ica.find_sources_raw. Either
the name of function supported by ICA or a custom function.
ecg_criterion : float | int | list-like | slice
The indices of the sorted ecg scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
eog_ch : list | str | ndarray | None
The ``target`` argument or the list of target arguments
subsequently passed to ica.find_sources_raw. Either the name of the
vertical EOG channel or the corresponding EOG time series. If None,
this step will be skipped.
eog_score_func : str | callable
The ``score_func`` argument passed to ica.find_sources_raw. Either
the name of function supported by ICA or a custom function.
eog_criterion : float | int | list-like | slice
The indices of the sorted eog scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
skew_criterion : float | int | list-like | slice
The indices of the sorted skewness scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
kurt_criterion : float | int | list-like | slice
The indices of the sorted kurtosis scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
var_criterion : float | int | list-like | slice
The indices of the sorted variance scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
add_nodes : list of tuple
Additional list if tuples carrying the following parameters
of ica nodes:
(name : str, target : str | array, score_func : callable,
criterion : float | int | list-like | slice). This parameter is a
generalization of the artifact specific parameters above and has
the same structure. Example::
add_nodes=('ECG phase lock', ECG 01',
my_phase_lock_function, 0.5)
Returns
-------
self : instance of ICA
The ICA object with the detected artifact indices marked for
exclusion.
"""
logger.info(' Searching for artifacts...')
_detect_artifacts(self, raw=raw, start_find=start_find,
stop_find=stop_find, ecg_ch=ecg_ch,
ecg_score_func=ecg_score_func,
ecg_criterion=ecg_criterion,
eog_ch=eog_ch, eog_score_func=eog_score_func,
eog_criterion=eog_criterion,
skew_criterion=skew_criterion,
kurt_criterion=kurt_criterion,
var_criterion=var_criterion,
add_nodes=add_nodes)
return self
@verbose
def _check_n_pca_components(self, _n_pca_comp, verbose=None):
"""Aux function."""
if isinstance(_n_pca_comp, float):
n, ev = _exp_var_ncomp(
self.pca_explained_variance_, _n_pca_comp)
logger.info(f' Selected {n} PCA components by explained '
f'variance ({100 * ev}≥{100 * _n_pca_comp}%)')
_n_pca_comp = n
elif _n_pca_comp is None:
_n_pca_comp = self._max_pca_components
if _n_pca_comp is None:
_n_pca_comp = self.pca_components_.shape[0]
elif _n_pca_comp < self.n_components_:
_n_pca_comp = self.n_components_
return _n_pca_comp
def _exp_var_ncomp(var, n):
cvar = np.asarray(var, dtype=np.float64)
cvar = cvar.cumsum()
cvar /= cvar[-1]
# We allow 1., which would give us N+1
n = min((cvar <= n).sum() + 1, len(cvar))
return n, cvar[n - 1]
def _check_start_stop(raw, start, stop):
"""Aux function."""
out = list()
for st, none_ in ((start, 0), (stop, raw.n_times)):
if st is None:
out.append(none_)
else:
try:
out.append(_ensure_int(st))
except TypeError: # not int-like
out.append(raw.time_as_index(st)[0])
return out
@verbose
def ica_find_ecg_events(raw, ecg_source, event_id=999,
tstart=0.0, l_freq=5, h_freq=35, qrs_threshold='auto',
verbose=None):
"""Find ECG peaks from one selected ICA source.
Parameters
----------
raw : instance of Raw
Raw object to draw sources from.
ecg_source : ndarray
ICA source resembling ECG to find peaks from.
event_id : int
The index to assign to found events.
tstart : float
Start detection after tstart seconds. Useful when beginning
of run is noisy.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
qrs_threshold : float | str
Between 0 and 1. qrs detection threshold. Can also be "auto" to
automatically choose the threshold that generates a reasonable
number of heartbeats (40-160 beats / min).
%(verbose)s
Returns
-------
ecg_events : array
Events.
ch_ECG : string
Name of channel used.
average_pulse : float.
Estimated average pulse.
"""
logger.info('Using ICA source to identify heart beats')
# detecting QRS and generating event file
ecg_events = qrs_detector(raw.info['sfreq'], ecg_source.ravel(),
tstart=tstart, thresh_value=qrs_threshold,
l_freq=l_freq, h_freq=h_freq)
n_events = len(ecg_events)
ecg_events = np.c_[ecg_events + raw.first_samp, np.zeros(n_events),
event_id * np.ones(n_events)]
return ecg_events
@verbose
def ica_find_eog_events(raw, eog_source=None, event_id=998, l_freq=1,
h_freq=10, verbose=None):
"""Locate EOG artifacts from one selected ICA source.
Parameters
----------
raw : instance of Raw
The raw data.
eog_source : ndarray
ICA source resembling EOG to find peaks from.
event_id : int
The index to assign to found events.
l_freq : float
Low cut-off frequency in Hz.
h_freq : float
High cut-off frequency in Hz.
%(verbose)s
Returns
-------
eog_events : array
Events.
"""
eog_events = _find_eog_events(eog_source[np.newaxis], event_id=event_id,
l_freq=l_freq, h_freq=h_freq,
sampling_rate=raw.info['sfreq'],
first_samp=raw.first_samp)
return eog_events
def _get_target_ch(container, target):
"""Aux function."""
# auto target selection
picks = pick_channels(container.ch_names, include=[target])
ref_picks = pick_types(container.info, meg=False, eeg=False, ref_meg=True)
if len(ref_picks) > 0:
picks = list(set(picks) - set(ref_picks))
if len(picks) == 0:
raise ValueError('%s not in channel list (%s)' %
(target, container.ch_names))
return picks
def _find_sources(sources, target, score_func):
"""Aux function."""
if isinstance(score_func, str):
score_func = get_score_funcs().get(score_func, score_func)
if not callable(score_func):
raise ValueError('%s is not a valid score_func.' % score_func)
scores = (score_func(sources, target) if target is not None
else score_func(sources, 1))
return scores
def _ica_explained_variance(ica, inst, normalize=False):
"""Check variance accounted for by each component in supplied data.
Parameters
----------
ica : ICA
Instance of `mne.preprocessing.ICA`.
inst : Raw | Epochs | Evoked
Data to explain with ICA. Instance of Raw, Epochs or Evoked.
normalize : bool
Whether to normalize the variance.
Returns
-------
var : array
Variance explained by each component.
"""
# check if ica is ICA and whether inst is Raw or Epochs
if not isinstance(ica, ICA):
raise TypeError('first argument must be an instance of ICA.')
if not isinstance(inst, (BaseRaw, BaseEpochs, Evoked)):
raise TypeError('second argument must an instance of either Raw, '
'Epochs or Evoked.')
source_data = _get_inst_data(ica.get_sources(inst))
# if epochs - reshape to channels x timesamples
if isinstance(inst, BaseEpochs):
n_epochs, n_chan, n_samp = source_data.shape
source_data = source_data.transpose(1, 0, 2).reshape(
(n_chan, n_epochs * n_samp))
n_chan, n_samp = source_data.shape
var = np.sum(ica.mixing_matrix_ ** 2, axis=0) * np.sum(
source_data ** 2, axis=1) / (n_chan * n_samp - 1)
if normalize:
var /= var.sum()
return var
def _sort_components(ica, order, copy=True):
"""Change the order of components in ica solution."""
assert ica.n_components_ == len(order)
if copy:
ica = ica.copy()
# reorder components
ica.mixing_matrix_ = ica.mixing_matrix_[:, order]
ica.unmixing_matrix_ = ica.unmixing_matrix_[order, :]
# reorder labels, excludes etc.
if isinstance(order, np.ndarray):
order = list(order)
if ica.exclude:
ica.exclude = [order.index(ic) for ic in ica.exclude]
for k in ica.labels_.keys():
ica.labels_[k] = [order.index(ic) for ic in ica.labels_[k]]
return ica
def _serialize(dict_, outer_sep=';', inner_sep=':'):
"""Aux function."""
s = []
for key, value in dict_.items():
if callable(value):
value = value.__name__
elif isinstance(value, Integral):
value = int(value)
elif isinstance(value, dict):
# py35 json does not support numpy int64
for subkey, subvalue in value.items():
if isinstance(subvalue, list):
if len(subvalue) > 0:
if isinstance(subvalue[0], (int, np.integer)):
value[subkey] = [int(i) for i in subvalue]
for cls in (np.random.RandomState, Covariance):
if isinstance(value, cls):
value = cls.__name__
s.append(key + inner_sep + json.dumps(value))
return outer_sep.join(s)
def _deserialize(str_, outer_sep=';', inner_sep=':'):
"""Aux Function."""
out = {}
for mapping in str_.split(outer_sep):
k, v = mapping.split(inner_sep, 1)
out[k] = json.loads(v)
return out
def _write_ica(fid, ica):
"""Write an ICA object.
Parameters
----------
fid: file
The file descriptor
ica:
The instance of ICA to write
"""
ica_init = dict(noise_cov=ica.noise_cov,
n_components=ica.n_components,
n_pca_components=ica.n_pca_components,
max_pca_components=ica._max_pca_components,
current_fit=ica.current_fit,
allow_ref_meg=ica.allow_ref_meg)
if ica.info is not None:
start_block(fid, FIFF.FIFFB_MEAS)
write_id(fid, FIFF.FIFF_BLOCK_ID)
if ica.info['meas_id'] is not None:
write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, ica.info['meas_id'])
# Write measurement info
write_meas_info(fid, ica.info)
end_block(fid, FIFF.FIFFB_MEAS)
start_block(fid, FIFF.FIFFB_MNE_ICA)
# ICA interface params
write_string(fid, FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS,
_serialize(ica_init))
# Channel names
if ica.ch_names is not None:
write_name_list(fid, FIFF.FIFF_MNE_ROW_NAMES, ica.ch_names)
# samples on fit
n_samples = getattr(ica, 'n_samples_', None)
ica_misc = {'n_samples_': (None if n_samples is None else int(n_samples)),
'labels_': getattr(ica, 'labels_', None),
'method': getattr(ica, 'method', None),
'n_iter_': getattr(ica, 'n_iter_', None),
'fit_params': getattr(ica, 'fit_params', None)}
# ICA misc params
write_string(fid, FIFF.FIFF_MNE_ICA_MISC_PARAMS,
_serialize(ica_misc))
# Whitener
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_WHITENER, ica.pre_whitener_)
# PCA components_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_COMPONENTS,
ica.pca_components_)
# PCA mean_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_MEAN, ica.pca_mean_)
# PCA explained_variance_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR,
ica.pca_explained_variance_)
# ICA unmixing
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_MATRIX, ica.unmixing_matrix_)
# Write bad components
write_int(fid, FIFF.FIFF_MNE_ICA_BADS, list(ica.exclude))
# Done!
end_block(fid, FIFF.FIFFB_MNE_ICA)
@verbose
def read_ica(fname, verbose=None):
"""Restore ICA solution from fif file.
Parameters
----------
fname : str
Absolute path to fif file containing ICA matrices.
The file name should end with -ica.fif or -ica.fif.gz.
%(verbose)s
Returns
-------
ica : instance of ICA
The ICA estimator.
"""
check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',
'_ica.fif', '_ica.fif.gz'))
logger.info('Reading %s ...' % fname)
fid, tree, _ = fiff_open(fname)
try:
# we used to store bads that weren't part of the info...
info, _ = read_meas_info(fid, tree, clean_bads=True)
except ValueError:
logger.info('Could not find the measurement info. \n'
'Functionality requiring the info won\'t be'
' available.')
info = None
ica_data = dir_tree_find(tree, FIFF.FIFFB_MNE_ICA)
if len(ica_data) == 0:
ica_data = dir_tree_find(tree, 123) # Constant 123 Used before v 0.11
if len(ica_data) == 0:
fid.close()
raise ValueError('Could not find ICA data')
my_ica_data = ica_data[0]
for d in my_ica_data['directory']:
kind = d.kind
pos = d.pos
if kind == FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS:
tag = read_tag(fid, pos)
ica_init = tag.data
elif kind == FIFF.FIFF_MNE_ROW_NAMES:
tag = read_tag(fid, pos)
ch_names = tag.data
elif kind == FIFF.FIFF_MNE_ICA_WHITENER:
tag = read_tag(fid, pos)
pre_whitener = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_COMPONENTS:
tag = read_tag(fid, pos)
pca_components = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR:
tag = read_tag(fid, pos)
pca_explained_variance = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_MEAN:
tag = read_tag(fid, pos)
pca_mean = tag.data
elif kind == FIFF.FIFF_MNE_ICA_MATRIX:
tag = read_tag(fid, pos)
unmixing_matrix = tag.data
elif kind == FIFF.FIFF_MNE_ICA_BADS:
tag = read_tag(fid, pos)
exclude = tag.data
elif kind == FIFF.FIFF_MNE_ICA_MISC_PARAMS:
tag = read_tag(fid, pos)
ica_misc = tag.data
fid.close()
ica_init, ica_misc = [_deserialize(k) for k in (ica_init, ica_misc)]
n_pca_components = ica_init.pop('n_pca_components')
current_fit = ica_init.pop('current_fit')
max_pca_components = ica_init.pop('max_pca_components')
method = ica_misc.get('method', 'fastica')
if method in _KNOWN_ICA_METHODS:
ica_init['method'] = method
if ica_init['noise_cov'] == Covariance.__name__:
logger.info('Reading whitener drawn from noise covariance ...')
logger.info('Now restoring ICA solution ...')
# make sure dtypes are np.float64 to satisfy fast_dot
def f(x):
return x.astype(np.float64)
ica_init = {k: v for k, v in ica_init.items()
if k in _get_args(ICA.__init__)}
ica = ICA(**ica_init)
ica.current_fit = current_fit
ica.ch_names = ch_names.split(':')
if n_pca_components is not None and \
not isinstance(n_pca_components, int_like):
n_pca_components = np.float64(n_pca_components)
ica.n_pca_components = n_pca_components
ica.pre_whitener_ = f(pre_whitener)
ica.pca_mean_ = f(pca_mean)
ica.pca_components_ = f(pca_components)
ica.n_components_ = unmixing_matrix.shape[0]
ica._max_pca_components = max_pca_components
ica._update_ica_names()
ica.pca_explained_variance_ = f(pca_explained_variance)
ica.unmixing_matrix_ = f(unmixing_matrix)
ica._update_mixing_matrix()
ica.exclude = [] if exclude is None else list(exclude)
ica.info = info
if 'n_samples_' in ica_misc:
ica.n_samples_ = ica_misc['n_samples_']
if 'labels_' in ica_misc:
labels_ = ica_misc['labels_']
if labels_ is not None:
ica.labels_ = labels_
if 'method' in ica_misc:
ica.method = ica_misc['method']
if 'n_iter_' in ica_misc:
ica.n_iter_ = ica_misc['n_iter_']
if 'fit_params' in ica_misc:
ica.fit_params = ica_misc['fit_params']
logger.info('Ready.')
return ica
_ica_node = namedtuple('Node', 'name target score_func criterion')
def _detect_artifacts(ica, raw, start_find, stop_find, ecg_ch, ecg_score_func,
ecg_criterion, eog_ch, eog_score_func, eog_criterion,
skew_criterion, kurt_criterion, var_criterion,
add_nodes):
"""Aux Function."""
from scipy import stats
nodes = []
if ecg_ch is not None:
nodes += [_ica_node('ECG', ecg_ch, ecg_score_func, ecg_criterion)]
if eog_ch not in [None, []]:
if not isinstance(eog_ch, list):
eog_ch = [eog_ch]
for idx, ch in enumerate(eog_ch):
nodes += [_ica_node('EOG %02d' % idx, ch, eog_score_func,
eog_criterion)]
if skew_criterion is not None:
nodes += [_ica_node('skewness', None, stats.skew, skew_criterion)]
if kurt_criterion is not None:
nodes += [_ica_node('kurtosis', None, stats.kurtosis, kurt_criterion)]
if var_criterion is not None:
nodes += [_ica_node('variance', None, np.var, var_criterion)]
if add_nodes is not None:
nodes.extend(add_nodes)
for node in nodes:
scores = ica.score_sources(raw, start=start_find, stop=stop_find,
target=node.target,
score_func=node.score_func)
if isinstance(node.criterion, float):
found = list(np.where(np.abs(scores) > node.criterion)[0])
else:
# Sort in descending order; use (-abs()), rather than [::-1] to
# keep any NaN values in the end (and also keep the order of same
# values):
found = list(np.atleast_1d((-np.abs(scores)).argsort()
[node.criterion]))
case = (len(found), _pl(found), node.name)
logger.info(' found %s artifact%s by %s' % case)
ica.exclude = list(ica.exclude) + found
logger.info('Artifact indices found:\n ' + str(ica.exclude).strip('[]'))
if len(set(ica.exclude)) != len(ica.exclude):
logger.info(' Removing duplicate indices...')
ica.exclude = list(set(ica.exclude))
logger.info('Ready.')
@verbose
def _band_pass_filter(inst, sources, target, l_freq, h_freq, verbose=None):
"""Optionally band-pass filter the data."""
if l_freq is not None and h_freq is not None:
logger.info('... filtering ICA sources')
# use FIR here, steeper is better
kw = dict(phase='zero-double', filter_length='10s', fir_window='hann',
l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,
fir_design='firwin2')
sources = filter_data(sources, inst.info['sfreq'], l_freq, h_freq,
**kw)
logger.info('... filtering target')
target = filter_data(target, inst.info['sfreq'], l_freq, h_freq, **kw)
elif l_freq is not None or h_freq is not None:
raise ValueError('Must specify both pass bands')
return sources, target
# #############################################################################
# CORRMAP
def _find_max_corrs(all_maps, target, threshold):
"""Compute correlations between template and target components."""
all_corrs = [compute_corr(target, subj.T) for subj in all_maps]
abs_corrs = [np.abs(a) for a in all_corrs]
corr_polarities = [np.sign(a) for a in all_corrs]
if threshold <= 1:
max_corrs = [list(np.nonzero(s_corr > threshold)[0])
for s_corr in abs_corrs]
else:
max_corrs = [list(_find_outliers(s_corr, threshold=threshold))
for s_corr in abs_corrs]
am = [l_[i] for l_, i_s in zip(abs_corrs, max_corrs)
for i in i_s]
median_corr_with_target = np.median(am) if len(am) > 0 else 0
polarities = [l_[i] for l_, i_s in zip(corr_polarities, max_corrs)
for i in i_s]
maxmaps = [l_[i] for l_, i_s in zip(all_maps, max_corrs)
for i in i_s]
if len(maxmaps) == 0:
return [], 0, 0, []
newtarget = np.zeros(maxmaps[0].size)
std_of_maps = np.std(np.asarray(maxmaps))
mean_of_maps = np.std(np.asarray(maxmaps))
for maxmap, polarity in zip(maxmaps, polarities):
newtarget += (maxmap / std_of_maps - mean_of_maps) * polarity
newtarget /= len(maxmaps)
newtarget *= std_of_maps
sim_i_o = np.abs(np.corrcoef(target, newtarget)[1, 0])
return newtarget, median_corr_with_target, sim_i_o, max_corrs
@verbose
def corrmap(icas, template, threshold="auto", label=None, ch_type="eeg",
plot=True, show=True, outlines='head',
sensors=True, contours=6, cmap=None, sphere=None, verbose=None):
"""Find similar Independent Components across subjects by map similarity.
Corrmap (Viola et al. 2009 Clin Neurophysiol) identifies the best group
match to a supplied template. Typically, feed it a list of fitted ICAs and
a template IC, for example, the blink for the first subject, to identify
specific ICs across subjects.
The specific procedure consists of two iterations. In a first step, the
maps best correlating with the template are identified. In the next step,
the analysis is repeated with the mean of the maps identified in the first
stage.
Run with ``plot`` and ``show`` set to ``True`` and ``label=False`` to find
good parameters. Then, run with labelling enabled to apply the
labelling in the IC objects. (Running with both ``plot`` and ``labels``
off does nothing.)
Outputs a list of fitted ICAs with the indices of the marked ICs in a
specified field.
The original Corrmap website: www.debener.de/corrmap/corrmapplugin1.html
Parameters
----------
icas : list of mne.preprocessing.ICA
A list of fitted ICA objects.
template : tuple | np.ndarray, shape (n_components,)
Either a tuple with two elements (int, int) representing the list
indices of the set from which the template should be chosen, and the
template. E.g., if template=(1, 0), the first IC of the 2nd ICA object
is used.
Or a numpy array whose size corresponds to each IC map from the
supplied maps, in which case this map is chosen as the template.
threshold : "auto" | list of float | float
Correlation threshold for identifying ICs
If "auto", search for the best map by trying all correlations between
0.6 and 0.95. In the original proposal, lower values are considered,
but this is not yet implemented.
If list of floats, search for the best map in the specified range of
correlation strengths. As correlation values, must be between 0 and 1
If float > 0, select ICs correlating better than this.
If float > 1, use z-scoring to identify ICs within subjects (not in
original Corrmap)
Defaults to "auto".
label : None | str
If not None, categorised ICs are stored in a dictionary ``labels_``
under the given name. Preexisting entries will be appended to
(excluding repeats), not overwritten. If None, a dry run is performed
and the supplied ICs are not changed.
ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
The channel type to plot. Defaults to 'eeg'.
plot : bool
Should constructed template and selected maps be plotted? Defaults
to True.
show : bool
Show figures if True.
%(topomap_outlines)s
sensors : bool | str
Add markers for sensor locations to the plot. Accepts matplotlib plot
format string (e.g., 'r+' for red plusses). If True, a circle will be
used (via .add_artist). Defaults to True.
contours : int | array of float
The number of contour lines to draw. If 0, no contours will be drawn.
When an integer, matplotlib ticker locator is used to find suitable
values for the contour thresholds (may sometimes be inaccurate, use
array for accuracy). If an array, the values represent the levels for
the contours. Defaults to 6.
cmap : None | matplotlib colormap
Colormap for the plot. If ``None``, defaults to 'Reds_r' for norm data,
otherwise to 'RdBu_r'.
%(topomap_sphere_auto)s
%(verbose)s
Returns
-------
template_fig : Figure
Figure showing the template.
labelled_ics : Figure
Figure showing the labelled ICs in all ICA decompositions.
"""
if not isinstance(plot, bool):
raise ValueError("`plot` must be of type `bool`")
same_chans = _check_all_same_channel_names(icas)
if same_chans is False:
raise ValueError("Not all ICA instances have the same channel names. "
"Corrmap requires all instances to have the same "
"montage. Consider interpolating bad channels before "
"running ICA.")
threshold_extra = ''
if threshold == 'auto':
threshold = np.arange(60, 95, dtype=np.float64) / 100.
threshold_extra = ' ("auto")'
all_maps = [ica.get_components().T for ica in icas]
# check if template is an index to one IC in one ICA object, or an array
if len(template) == 2:
target = all_maps[template[0]][template[1]]
is_subject = True
elif template.ndim == 1 and len(template) == all_maps[0].shape[1]:
target = template
is_subject = False
else:
raise ValueError("`template` must be a length-2 tuple or an array the "
"size of the ICA maps.")
template_fig, labelled_ics = None, None
if plot is True:
if is_subject: # plotting from an ICA object
ttl = 'Template from subj. {}'.format(str(template[0]))
template_fig = icas[template[0]].plot_components(
picks=template[1], ch_type=ch_type, title=ttl,
outlines=outlines, cmap=cmap, contours=contours,
show=show, topomap_args=dict(sphere=sphere))
else: # plotting an array
template_fig = _plot_corrmap([template], [0], [0], ch_type,
icas[0].copy(), "Template",
outlines=outlines, cmap=cmap,
contours=contours,
show=show, template=True,
sphere=sphere)
template_fig.subplots_adjust(top=0.8)
template_fig.canvas.draw()
# first run: use user-selected map
threshold = np.atleast_1d(np.array(threshold, float)).ravel()
threshold_err = ('No component detected using when z-scoring '
'threshold%s %s, consider using a more lenient '
'threshold' % (threshold_extra, threshold))
if len(all_maps) == 0:
raise RuntimeError(threshold_err)
paths = [_find_max_corrs(all_maps, target, t) for t in threshold]
# find iteration with highest avg correlation with target
new_target, _, _, _ = paths[np.argmax([path[2] for path in paths])]
# second run: use output from first run
if len(all_maps) == 0 or len(new_target) == 0:
raise RuntimeError(threshold_err)
paths = [_find_max_corrs(all_maps, new_target, t) for t in threshold]
del new_target
# find iteration with highest avg correlation with target
_, median_corr, _, max_corrs = paths[
np.argmax([path[1] for path in paths])]
allmaps, indices, subjs, nones = [list() for _ in range(4)]
logger.info('Median correlation with constructed map: %0.3f' % median_corr)
del median_corr
if plot is True:
logger.info('Displaying selected ICs per subject.')
for ii, (ica, max_corr) in enumerate(zip(icas, max_corrs)):
if len(max_corr) > 0:
if isinstance(max_corr[0], np.ndarray):
max_corr = max_corr[0]
if label is not None:
ica.labels_[label] = list(set(list(max_corr) +
ica.labels_.get(label, list())))
if plot is True:
allmaps.extend(ica.get_components()[:, max_corr].T)
subjs.extend([ii] * len(max_corr))
indices.extend(max_corr)
else:
if (label is not None) and (label not in ica.labels_):
ica.labels_[label] = list()
nones.append(ii)
if len(nones) == 0:
logger.info('At least 1 IC detected for each subject.')
else:
logger.info('No maps selected for subject%s %s, '
'consider a more liberal threshold.'
% (_pl(nones), nones))
if plot is True:
labelled_ics = _plot_corrmap(allmaps, subjs, indices, ch_type, ica,
label, outlines=outlines, cmap=cmap,
contours=contours,
show=show, sphere=sphere)
return template_fig, labelled_ics
else:
return None
@verbose
def read_ica_eeglab(fname, *, verbose=None):
"""Load ICA information saved in an EEGLAB .set file.
Parameters
----------
fname : str
Complete path to a .set EEGLAB file that contains an ICA object.
%(verbose)s
Returns
-------
ica : instance of ICA
An ICA object based on the information contained in the input file.
"""
from scipy import linalg
eeg = _check_load_mat(fname, None)
info, eeg_montage, _ = _get_info(eeg)
info.set_montage(eeg_montage)
pick_info(info, np.round(eeg['icachansind']).astype(int) - 1, copy=False)
rank = eeg.icasphere.shape[0]
n_components = eeg.icaweights.shape[0]
ica = ICA(method='imported_eeglab', n_components=n_components)
ica.current_fit = "eeglab"
ica.ch_names = info["ch_names"]
ica.n_pca_components = None
ica.n_components_ = n_components
n_ch = len(ica.ch_names)
assert len(eeg.icachansind) == n_ch
ica.pre_whitener_ = np.ones((n_ch, 1))
ica.pca_mean_ = np.zeros(n_ch)
assert eeg.icasphere.shape[1] == n_ch
assert eeg.icaweights.shape == (n_components, rank)
# When PCA reduction is used in EEGLAB, runica returns
# weights= weights*sphere*eigenvectors(:,1:ncomps)';
# sphere = eye(urchans). When PCA reduction is not used, we have:
#
# eeg.icawinv == pinv(eeg.icaweights @ eeg.icasphere)
#
# So in either case, we can use SVD to get our square whitened
# weights matrix (u * s) and our PCA vectors (v) back:
use = eeg.icaweights @ eeg.icasphere
use_check = linalg.pinv(eeg.icawinv)
if not np.allclose(use, use_check, rtol=1e-6):
warn('Mismatch between icawinv and icaweights @ icasphere from EEGLAB '
'possibly due to ICA component removal, assuming icawinv is '
'correct')
use = use_check
u, s, v = _safe_svd(use, full_matrices=False)
ica.unmixing_matrix_ = u * s
ica.pca_components_ = v
ica.pca_explained_variance_ = s * s
ica.info = info
ica._update_mixing_matrix()
ica._update_ica_names()
return ica
| # -*- coding: utf-8 -*-
#
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Juergen Dammers <j.dammers@fz-juelich.de>
#
# License: BSD (3-clause)
from inspect import isfunction
from collections import namedtuple
from copy import deepcopy
from numbers import Integral
from time import time
import math
import os
import json
import numpy as np
from .ecg import (qrs_detector, _get_ecg_channel_index, _make_ecg,
create_ecg_epochs)
from .eog import _find_eog_events, _get_eog_channel_index
from .infomax_ import infomax
from ..cov import compute_whitener
from .. import Covariance, Evoked
from ..io.pick import (pick_types, pick_channels, pick_info,
_picks_to_idx, _get_channel_types, _DATA_CH_TYPES_SPLIT)
from ..io.proj import make_projector
from ..io.write import (write_double_matrix, write_string,
write_name_list, write_int, start_block,
end_block)
from ..io.tree import dir_tree_find
from ..io.open import fiff_open
from ..io.tag import read_tag
from ..io.meas_info import write_meas_info, read_meas_info
from ..io.constants import FIFF
from ..io.base import BaseRaw
from ..io.eeglab.eeglab import _get_info, _check_load_mat
from ..epochs import BaseEpochs
from ..viz import (plot_ica_components, plot_ica_scores,
plot_ica_sources, plot_ica_overlay)
from ..viz.ica import plot_ica_properties
from ..viz.topomap import _plot_corrmap
from ..channels.channels import _contains_ch_type, ContainsMixin
from ..io.write import start_file, end_file, write_id
from ..utils import (check_version, logger, check_fname, verbose,
_reject_data_segments, check_random_state, _validate_type,
compute_corr, _get_inst_data, _ensure_int,
copy_function_doc_to_method_doc, _pl, warn, Bunch,
_check_preload, _check_compensation_grade, fill_doc,
_check_option, _PCA, int_like,
_check_all_same_channel_names)
from ..fixes import _get_args, _safe_svd
from ..filter import filter_data
from .bads import _find_outliers
from .ctps_ import ctps
from ..io.pick import pick_channels_regexp
__all__ = ('ICA', 'ica_find_ecg_events', 'ica_find_eog_events',
'get_score_funcs', 'read_ica', 'read_ica_eeglab')
def _make_xy_sfunc(func, ndim_output=False):
"""Aux function."""
if ndim_output:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])[:, 0]
else:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])
sfunc.__name__ = '.'.join(['score_func', func.__module__, func.__name__])
sfunc.__doc__ = func.__doc__
return sfunc
# Violate our assumption that the output is 1D so can't be used.
# Could eventually be added but probably not worth the effort unless someone
# requests it.
_BLOCKLIST = {'somersd'}
# makes score funcs attr accessible for users
def get_score_funcs():
"""Get the score functions.
Returns
-------
score_funcs : dict
The score functions.
"""
from scipy import stats
from scipy.spatial import distance
score_funcs = Bunch()
xy_arg_dist_funcs = [(n, f) for n, f in vars(distance).items()
if isfunction(f) and not n.startswith('_') and
n not in _BLOCKLIST]
xy_arg_stats_funcs = [(n, f) for n, f in vars(stats).items()
if isfunction(f) and not n.startswith('_') and
n not in _BLOCKLIST]
score_funcs.update({n: _make_xy_sfunc(f)
for n, f in xy_arg_dist_funcs
if _get_args(f) == ['u', 'v']})
score_funcs.update({n: _make_xy_sfunc(f, ndim_output=True)
for n, f in xy_arg_stats_funcs
if _get_args(f) == ['x', 'y']})
return score_funcs
def _check_for_unsupported_ica_channels(picks, info, allow_ref_meg=False):
"""Check for channels in picks that are not considered valid channels.
Accepted channels are the data channels
('seeg', 'dbs', 'ecog', 'eeg', 'hbo', 'hbr', 'mag', and 'grad'), 'eog'
and 'ref_meg'.
This prevents the program from crashing without
feedback when a bad channel is provided to ICA whitening.
"""
types = _DATA_CH_TYPES_SPLIT + ('eog',)
types += ('ref_meg',) if allow_ref_meg else ()
chs = _get_channel_types(info, picks, unique=True, only_data_chs=False)
check = all([ch in types for ch in chs])
if not check:
raise ValueError('Invalid channel type%s passed for ICA: %s.'
'Only the following types are supported: %s'
% (_pl(chs), chs, types))
_KNOWN_ICA_METHODS = ('fastica', 'infomax', 'picard')
@fill_doc
class ICA(ContainsMixin):
u"""Data decomposition using Independent Component Analysis (ICA).
This object estimates independent components from :class:`mne.io.Raw`,
:class:`mne.Epochs`, or :class:`mne.Evoked` objects. Components can
optionally be removed (for artifact repair) prior to signal reconstruction.
.. warning:: ICA is sensitive to low-frequency drifts and therefore
requires the data to be high-pass filtered prior to fitting.
Typically, a cutoff frequency of 1 Hz is recommended.
Parameters
----------
n_components : int | float | None
Number of principal components (from the pre-whitening PCA step) that
are passed to the ICA algorithm during fitting:
- :class:`int`
Must be greater than 1 and less than or equal to the number of
channels.
- :class:`float` between 0 and 1 (exclusive)
Will select the smallest number of components required to explain
the cumulative variance of the data greater than ``n_components``.
Consider this hypothetical example: we have 3 components, the first
explaining 70%%, the second 20%%, and the third the remaining 10%%
of the variance. Passing 0.8 here (corresponding to 80%% of
explained variance) would yield the first two components,
explaining 90%% of the variance: only by using both components the
requested threshold of 80%% explained variance can be exceeded. The
third component, on the other hand, would be excluded.
- ``None``
``0.999999`` will be used. This is done to avoid numerical
stability problems when whitening, particularly when working with
rank-deficient data.
Defaults to ``None``. The actual number used when executing the
:meth:`ICA.fit` method will be stored in the attribute
``n_components_`` (note the trailing underscore).
.. versionchanged:: 0.22
For a :class:`python:float`, the number of components will account
for *greater than* the given variance level instead of *less than or
equal to* it. The default (None) will also take into account the
rank deficiency of the data.
noise_cov : None | instance of Covariance
Noise covariance used for pre-whitening. If None (default), channels
are scaled to unit variance ("z-standardized") as a group by channel
type prior to the whitening by PCA.
%(random_state)s
As estimation can be non-deterministic it can be useful to fix the
random state to have reproducible results.
method : {'fastica', 'infomax', 'picard'}
The ICA method to use in the fit method. Use the fit_params argument to
set additional parameters. Specifically, if you want Extended Infomax,
set method='infomax' and fit_params=dict(extended=True) (this also
works for method='picard'). Defaults to 'fastica'. For reference, see
:footcite:`Hyvarinen1999,BellSejnowski1995,LeeEtAl1999,AblinEtAl2018`.
fit_params : dict | None
Additional parameters passed to the ICA estimator as specified by
``method``.
max_iter : int
Maximum number of iterations during fit. Defaults to 200. The actual
number of iterations it took :meth:`ICA.fit` to complete will be stored
in the ``n_iter_`` attribute.
allow_ref_meg : bool
Allow ICA on MEG reference channels. Defaults to False.
.. versionadded:: 0.18
%(verbose)s
Attributes
----------
current_fit : str
Flag informing about which data type (raw or epochs) was used for the
fit.
ch_names : list-like
Channel names resulting from initial picking.
n_components_ : int
If fit, the actual number of PCA components used for ICA decomposition.
pre_whitener_ : ndarray, shape (n_channels, 1) or (n_channels, n_channels)
If fit, array used to pre-whiten the data prior to PCA.
pca_components_ : ndarray, shape ``(n_channels, n_channels)``
If fit, the PCA components.
pca_mean_ : ndarray, shape (n_channels,)
If fit, the mean vector used to center the data before doing the PCA.
pca_explained_variance_ : ndarray, shape ``(n_channels,)``
If fit, the variance explained by each PCA component.
mixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened mixing matrix to go back from ICA space to PCA
space.
It is, in combination with the ``pca_components_``, used by
:meth:`ICA.apply` and :meth:`ICA.get_components` to re-mix/project
a subset of the ICA components into the observed channel space.
The former method also removes the pre-whitening (z-scaling) and the
de-meaning.
unmixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened matrix to go from PCA space to ICA space.
Used, in combination with the ``pca_components_``, by the methods
:meth:`ICA.get_sources` and :meth:`ICA.apply` to unmix the observed
data.
exclude : array-like of int
List or np.array of sources indices to exclude when re-mixing the data
in the :meth:`ICA.apply` method, i.e. artifactual ICA components.
The components identified manually and by the various automatic
artifact detection methods should be (manually) appended
(e.g. ``ica.exclude.extend(eog_inds)``).
(There is also an ``exclude`` parameter in the :meth:`ICA.apply`
method.) To scrap all marked components, set this attribute to an empty
list.
info : None | instance of Info
The measurement info copied from the object fitted.
n_samples_ : int
The number of samples used on fit.
labels_ : dict
A dictionary of independent component indices, grouped by types of
independent components. This attribute is set by some of the artifact
detection functions.
n_iter_ : int
If fit, the number of iterations required to complete ICA.
Notes
-----
A trailing ``_`` in an attribute name signifies that the attribute was
added to the object during fitting, consistent with standard scikit-learn
practice.
ICA :meth:`fit` in MNE proceeds in two steps:
1. :term:`Whitening <whitening>` the data by means of a pre-whitening step
(using ``noise_cov`` if provided, or the standard deviation of each
channel type) and then principal component analysis (PCA).
2. Passing the ``n_components`` largest-variance components to the ICA
algorithm to obtain the unmixing matrix (and by pseudoinversion, the
mixing matrix).
ICA :meth:`apply` then:
1. Unmixes the data with the ``unmixing_matrix_``.
2. Includes ICA components based on ``ica.include`` and ``ica.exclude``.
3. Re-mixes the data with ``mixing_matrix_``.
4. Restores any data not passed to the ICA algorithm, i.e., the PCA
components between ``n_components`` and ``n_pca_components``.
``n_pca_components`` determines how many PCA components will be kept when
reconstructing the data when calling :meth:`apply`. This parameter can be
used for dimensionality reduction of the data, or dealing with low-rank
data (such as those with projections, or MEG data processed by SSS). It is
important to remove any numerically-zero-variance components in the data,
otherwise numerical instability causes problems when computing the mixing
matrix. Alternatively, using ``n_components`` as a float will also avoid
numerical stability problems.
The ``n_components`` parameter determines how many components out of
the ``n_channels`` PCA components the ICA algorithm will actually fit.
This is not typically used for EEG data, but for MEG data, it's common to
use ``n_components < n_channels``. For example, full-rank
306-channel MEG data might use ``n_components=40`` to find (and
later exclude) only large, dominating artifacts in the data, but still
reconstruct the data using all 306 PCA components. Setting
``n_pca_components=40``, on the other hand, would actually reduce the
rank of the reconstructed data to 40, which is typically undesirable.
If you are migrating from EEGLAB and intend to reduce dimensionality via
PCA, similarly to EEGLAB's ``runica(..., 'pca', n)`` functionality,
pass ``n_components=n`` during initialization and then
``n_pca_components=n`` during :meth:`apply`. The resulting reconstructed
data after :meth:`apply` will have rank ``n``.
.. note:: Commonly used for reasons of i) computational efficiency and
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease the
reliability and stability of the ICA, at least for EEG data and
especially during preprocessing :footcite:`ArtoniEtAl2018`.
(But see also :footcite:`Montoya-MartinezEtAl2017` for a
possibly confounding effect of the different whitening/sphering
methods used in this paper (ZCA vs. PCA).)
On the other hand, for rank-deficient data such as EEG data after
average reference or interpolation, it is recommended to reduce
the dimensionality (by 1 for average reference and 1 for each
interpolated channel) for optimal ICA performance (see the
`EEGLAB wiki <eeglab_wiki_>`_).
Caveat! If supplying a noise covariance, keep track of the projections
available in the cov or in the raw object. For example, if you are
interested in EOG or ECG artifacts, EOG and ECG projections should be
temporally removed before fitting ICA, for example::
>> projs, raw.info['projs'] = raw.info['projs'], []
>> ica.fit(raw)
>> raw.info['projs'] = projs
Methods currently implemented are FastICA (default), Infomax, and Picard.
Standard Infomax can be quite sensitive to differences in floating point
arithmetic. Extended Infomax seems to be more stable in this respect,
enhancing reproducibility and stability of results; use Extended Infomax
via ``method='infomax', fit_params=dict(extended=True)``. Allowed entries
in ``fit_params`` are determined by the various algorithm implementations:
see :class:`~sklearn.decomposition.FastICA`, :func:`~picard.picard`,
:func:`~mne.preprocessing.infomax`.
.. note:: Picard can be used to solve the same problems as FastICA,
Infomax, and extended Infomax, but typically converges faster
than either of those methods. To make use of Picard's speed while
still obtaining the same solution as with other algorithms, you
need to specify ``method='picard'`` and ``fit_params`` as a
dictionary with the following combination of keys:
- ``dict(ortho=False, extended=False)`` for Infomax
- ``dict(ortho=False, extended=True)`` for extended Infomax
- ``dict(ortho=True, extended=True)`` for FastICA
Reducing the tolerance (set in ``fit_params``) speeds up estimation at the
cost of consistency of the obtained results. It is difficult to directly
compare tolerance levels between Infomax and Picard, but for Picard and
FastICA a good rule of thumb is ``tol_fastica == tol_picard ** 2``.
.. _eeglab_wiki: https://sccn.ucsd.edu/wiki/Chapter_09:_Decomposing_Data_Using_ICA#Issue:_ICA_returns_near-identical_components_with_opposite_polarities
References
----------
.. footbibliography::
""" # noqa: E501
@verbose
def __init__(self, n_components=None, *, noise_cov=None,
random_state=None, method='fastica', fit_params=None,
max_iter=200, allow_ref_meg=False,
verbose=None): # noqa: D102
_validate_type(method, str, 'method')
_validate_type(n_components, (float, 'int-like', None))
if method != 'imported_eeglab': # internal use only
_check_option('method', method, _KNOWN_ICA_METHODS)
if method == 'fastica' and not check_version('sklearn'):
raise ImportError(
'The scikit-learn package is required for method="fastica".')
if method == 'picard' and not check_version('picard'):
raise ImportError(
'The python-picard package is required for method="picard".')
self.noise_cov = noise_cov
for (kind, val) in [('n_components', n_components)]:
if isinstance(val, float) and not 0 < val < 1:
raise ValueError('Selecting ICA components by explained '
'variance needs values between 0.0 and 1.0 '
f'(exclusive), got {kind}={val}')
if isinstance(val, int_like) and val == 1:
raise ValueError(
f'Selecting one component with {kind}={val} is not '
'supported')
self.current_fit = 'unfitted'
self.verbose = verbose
self.n_components = n_components
# In newer ICAs this should always be None, but keep it for
# backward compat with older versions of MNE that used it
self._max_pca_components = None
self.n_pca_components = None
self.ch_names = None
self.random_state = random_state
if fit_params is None:
fit_params = {}
fit_params = deepcopy(fit_params) # avoid side effects
if method == 'fastica':
update = {'algorithm': 'parallel', 'fun': 'logcosh',
'fun_args': None}
fit_params.update({k: v for k, v in update.items() if k
not in fit_params})
elif method == 'infomax':
# extended=True is default in underlying function, but we want
# default False here unless user specified True:
fit_params.setdefault('extended', False)
fit_params.setdefault('max_iter', max_iter)
self.max_iter = max_iter
self.fit_params = fit_params
self.exclude = []
self.info = None
self.method = method
self.labels_ = dict()
self.allow_ref_meg = allow_ref_meg
def __repr__(self):
"""ICA fit information."""
if self.current_fit == 'unfitted':
s = 'no'
elif self.current_fit == 'raw':
s = 'raw data'
else:
s = 'epochs'
s += ' decomposition, '
s += 'fit (%s): %s samples, ' % (self.method,
str(getattr(self, 'n_samples_', '')))
s += ('%s components' % str(self.n_components_) if
hasattr(self, 'n_components_') else
'no dimension reduction')
if self.info is not None:
ch_fit = ['"%s"' % c for c in _DATA_CH_TYPES_SPLIT if c in self]
s += ', channels used: {}'.format('; '.join(ch_fit))
if self.exclude:
s += ', %i sources marked for exclusion' % len(self.exclude)
return '<ICA | %s>' % s
@verbose
def fit(self, inst, picks=None, start=None, stop=None, decim=None,
reject=None, flat=None, tstep=2.0, reject_by_annotation=True,
verbose=None):
"""Run the ICA decomposition on raw data.
Caveat! If supplying a noise covariance keep track of the projections
available in the cov, the raw or the epochs object. For example,
if you are interested in EOG or ECG artifacts, EOG and ECG projections
should be temporally removed before fitting the ICA.
Parameters
----------
inst : instance of Raw or Epochs
Raw measurements to be decomposed.
%(picks_good_data_noref)s
This selection remains throughout the initialized ICA solution.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
decim : int | None
Increment for selecting each nth time slice. If None, all samples
within ``start`` and ``stop`` are used.
reject : dict | None
Rejection parameters based on peak-to-peak amplitude.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',
'ecg', 'hbo', 'hbr'.
If reject is None then no rejection is done. Example::
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=40e-6, # V (EEG channels)
eog=250e-6 # V (EOG channels)
)
It only applies if ``inst`` is of type Raw.
flat : dict | None
Rejection parameters based on flatness of signal.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'dbs', 'ecog', 'eog',
'ecg', 'hbo', 'hbr'.
Values are floats that set the minimum acceptable peak-to-peak
amplitude. If flat is None then no rejection is done.
It only applies if ``inst`` is of type Raw.
tstep : float
Length of data chunks for artifact rejection in seconds.
It only applies if ``inst`` is of type Raw.
%(reject_by_annotation_raw)s
.. versionadded:: 0.14.0
%(verbose_meth)s
Returns
-------
self : instance of ICA
Returns the modified instance.
"""
_validate_type(inst, (BaseRaw, BaseEpochs), 'inst', 'Raw or Epochs')
picks = _picks_to_idx(inst.info, picks, allow_empty=False,
with_ref_meg=self.allow_ref_meg)
_check_for_unsupported_ica_channels(
picks, inst.info, allow_ref_meg=self.allow_ref_meg)
# Actually start fitting
t_start = time()
if self.current_fit != 'unfitted':
self._reset()
logger.info('Fitting ICA to data using %i channels '
'(please be patient, this may take a while)' % len(picks))
# n_components could be float 0 < x < 1, but that's okay here
if self.n_components is not None and self.n_components > len(picks):
raise ValueError(
f'ica.n_components ({self.n_components}) cannot '
f'be greater than len(picks) ({len(picks)})')
# filter out all the channels the raw wouldn't have initialized
self.info = pick_info(inst.info, picks)
if self.info['comps']:
self.info['comps'] = []
self.ch_names = self.info['ch_names']
if isinstance(inst, BaseRaw):
self._fit_raw(inst, picks, start, stop, decim, reject, flat,
tstep, reject_by_annotation, verbose)
else:
assert isinstance(inst, BaseEpochs)
self._fit_epochs(inst, picks, decim, verbose)
# sort ICA components by explained variance
var = _ica_explained_variance(self, inst)
var_ord = var.argsort()[::-1]
_sort_components(self, var_ord, copy=False)
t_stop = time()
logger.info("Fitting ICA took {:.1f}s.".format(t_stop - t_start))
return self
def _reset(self):
"""Aux method."""
for key in ('pre_whitener_', 'unmixing_matrix_', 'mixing_matrix_',
'n_components_', 'n_samples_', 'pca_components_',
'pca_explained_variance_',
'pca_mean_', 'n_iter_', 'drop_inds_', 'reject_'):
if hasattr(self, key):
delattr(self, key)
def _fit_raw(self, raw, picks, start, stop, decim, reject, flat, tstep,
reject_by_annotation, verbose):
"""Aux method."""
start, stop = _check_start_stop(raw, start, stop)
reject_by_annotation = 'omit' if reject_by_annotation else None
# this will be a copy
data = raw.get_data(picks, start, stop, reject_by_annotation)
# this will be a view
if decim is not None:
data = data[:, ::decim]
# this will make a copy
if (reject is not None) or (flat is not None):
self.reject_ = reject
data, self.drop_inds_ = _reject_data_segments(data, reject, flat,
decim, self.info,
tstep)
self.n_samples_ = data.shape[1]
self._fit(data, 'raw')
return self
def _fit_epochs(self, epochs, picks, decim, verbose):
"""Aux method."""
if epochs.events.size == 0:
raise RuntimeError('Tried to fit ICA with epochs, but none were '
'found: epochs.events is "{}".'
.format(epochs.events))
# this should be a copy (picks a list of int)
data = epochs.get_data()[:, picks]
# this will be a view
if decim is not None:
data = data[:, :, ::decim]
self.n_samples_ = data.shape[0] * data.shape[2]
# This will make at least one copy (one from hstack, maybe one
# more from _pre_whiten)
data = np.hstack(data)
self._fit(data, 'epochs')
return self
def _compute_pre_whitener(self, data):
"""Aux function."""
data = self._do_proj(data, log_suffix='(pre-whitener computation)')
if self.noise_cov is None:
# use standardization as whitener
# Scale (z-score) the data by channel type
info = self.info
pre_whitener = np.empty([len(data), 1])
for ch_type in _DATA_CH_TYPES_SPLIT + ('eog', "ref_meg"):
if _contains_ch_type(info, ch_type):
if ch_type == 'seeg':
this_picks = pick_types(info, meg=False, seeg=True)
elif ch_type == 'dbs':
this_picks = pick_types(info, meg=False, dbs=True)
elif ch_type == 'ecog':
this_picks = pick_types(info, meg=False, ecog=True)
elif ch_type == 'eeg':
this_picks = pick_types(info, meg=False, eeg=True)
elif ch_type in ('mag', 'grad'):
this_picks = pick_types(info, meg=ch_type)
elif ch_type == 'eog':
this_picks = pick_types(info, meg=False, eog=True)
elif ch_type in ('hbo', 'hbr'):
this_picks = pick_types(info, meg=False, fnirs=ch_type)
elif ch_type == 'ref_meg':
this_picks = pick_types(info, meg=False, ref_meg=True)
else:
raise RuntimeError('Should not be reached.'
'Unsupported channel {}'
.format(ch_type))
pre_whitener[this_picks] = np.std(data[this_picks])
else:
pre_whitener, _ = compute_whitener(self.noise_cov, self.info)
assert data.shape[0] == pre_whitener.shape[1]
self.pre_whitener_ = pre_whitener
def _do_proj(self, data, log_suffix=''):
if self.info is not None and self.info['projs']:
proj, nproj, _ = make_projector(
[p for p in self.info['projs'] if p['active']],
self.info['ch_names'], include_active=True)
if nproj:
logger.info(
f' Applying projection operator with {nproj} '
f'vector{_pl(nproj)}'
f'{" " if log_suffix else ""}{log_suffix}')
if self.noise_cov is None: # otherwise it's in pre_whitener_
data = proj @ data
return data
def _pre_whiten(self, data):
data = self._do_proj(data, log_suffix='(pre-whitener application)')
if self.noise_cov is None:
data /= self.pre_whitener_
else:
data = self.pre_whitener_ @ data
return data
def _fit(self, data, fit_type):
"""Aux function."""
random_state = check_random_state(self.random_state)
n_channels, n_samples = data.shape
self._compute_pre_whitener(data)
data = self._pre_whiten(data)
pca = _PCA(n_components=self._max_pca_components, whiten=True)
data = pca.fit_transform(data.T)
use_ev = pca.explained_variance_ratio_
n_pca = self.n_pca_components
if isinstance(n_pca, float):
n_pca = int(_exp_var_ncomp(use_ev, n_pca)[0])
elif n_pca is None:
n_pca = len(use_ev)
assert isinstance(n_pca, (int, np.int_))
# If user passed a float, select the PCA components explaining the
# given cumulative variance. This information will later be used to
# only submit the corresponding parts of the data to ICA.
if self.n_components is None:
# None case: check if n_pca_components or 0.999999 yields smaller
msg = 'Selecting by non-zero PCA components'
self.n_components_ = min(
n_pca, _exp_var_ncomp(use_ev, 0.999999)[0])
elif isinstance(self.n_components, float):
self.n_components_, ev = _exp_var_ncomp(use_ev, self.n_components)
if self.n_components_ == 1:
raise RuntimeError(
'One PCA component captures most of the '
f'explained variance ({100 * ev}%), your threshold '
'results in 1 component. You should select '
'a higher value.')
msg = 'Selecting by explained variance'
else:
msg = 'Selecting by number'
self.n_components_ = _ensure_int(self.n_components)
# check to make sure something okay happened
if self.n_components_ > n_pca:
ev = np.cumsum(use_ev)
ev /= ev[-1]
evs = 100 * ev[[self.n_components_ - 1, n_pca - 1]]
raise RuntimeError(
f'n_components={self.n_components} requires '
f'{self.n_components_} PCA values (EV={evs[0]:0.1f}%) but '
f'n_pca_components ({self.n_pca_components}) results in '
f'only {n_pca} components (EV={evs[1]:0.1f}%)')
logger.info('%s: %s components' % (msg, self.n_components_))
# the things to store for PCA
self.pca_mean_ = pca.mean_
self.pca_components_ = pca.components_
self.pca_explained_variance_ = pca.explained_variance_
del pca
# update number of components
self._update_ica_names()
if self.n_pca_components is not None and \
self.n_pca_components > len(self.pca_components_):
raise ValueError(
f'n_pca_components ({self.n_pca_components}) is greater than '
f'the number of PCA components ({len(self.pca_components_)})')
# take care of ICA
sel = slice(0, self.n_components_)
if self.method == 'fastica':
from sklearn.decomposition import FastICA
ica = FastICA(
whiten=False, random_state=random_state, **self.fit_params)
ica.fit(data[:, sel])
self.unmixing_matrix_ = ica.components_
self.n_iter_ = ica.n_iter_
elif self.method in ('infomax', 'extended-infomax'):
unmixing_matrix, n_iter = infomax(
data[:, sel], random_state=random_state, return_n_iter=True,
**self.fit_params)
self.unmixing_matrix_ = unmixing_matrix
self.n_iter_ = n_iter
del unmixing_matrix, n_iter
elif self.method == 'picard':
from picard import picard
_, W, _, n_iter = picard(
data[:, sel].T, whiten=False, return_n_iter=True,
random_state=random_state, **self.fit_params)
self.unmixing_matrix_ = W
self.n_iter_ = n_iter + 1 # picard() starts counting at 0
del _, n_iter
assert self.unmixing_matrix_.shape == (self.n_components_,) * 2
norms = self.pca_explained_variance_
stable = norms / norms[0] > 1e-6 # to be stable during pinv
norms = norms[:self.n_components_]
if not stable[self.n_components_ - 1]:
max_int = np.where(stable)[0][-1] + 1
warn(f'Using n_components={self.n_components} (resulting in '
f'n_components_={self.n_components_}) may lead to an '
f'unstable mixing matrix estimation because the ratio '
f'between the largest ({norms[0]:0.2g}) and smallest '
f'({norms[-1]:0.2g}) variances is too large (> 1e6); '
f'consider setting n_components=0.999999 or an '
f'integer <= {max_int}')
norms = np.sqrt(norms)
norms[norms == 0] = 1.
self.unmixing_matrix_ /= norms # whitening
self._update_mixing_matrix()
self.current_fit = fit_type
def _update_mixing_matrix(self):
from scipy import linalg
self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
def _update_ica_names(self):
"""Update ICA names when n_components_ is set."""
self._ica_names = ['ICA%03d' % ii for ii in range(self.n_components_)]
def _transform(self, data):
"""Compute sources from data (operates inplace)."""
data = self._pre_whiten(data)
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
# Apply first PCA
pca_data = np.dot(self.pca_components_[:self.n_components_], data)
# Apply unmixing to low dimension PCA
sources = np.dot(self.unmixing_matrix_, pca_data)
return sources
def _transform_raw(self, raw, start, stop, reject_by_annotation=False):
"""Transform raw data."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
start, stop = _check_start_stop(raw, start, stop)
picks = pick_types(raw.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Raw doesn\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Raw compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
reject = 'omit' if reject_by_annotation else None
data = raw.get_data(picks, start, stop, reject)
return self._transform(data)
def _transform_epochs(self, epochs, concatenate):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
picks = pick_types(epochs.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
# special case where epochs come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Epochs don\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Epochs compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data = np.hstack(epochs.get_data()[:, picks])
sources = self._transform(data)
if not concatenate:
# Put the data back in 3D
sources = np.array(np.split(sources, len(epochs.events), 1))
return sources
def _transform_evoked(self, evoked):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
picks = pick_types(evoked.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Evoked doesn\'t match fitted data: %i channels'
' fitted but %i channels supplied. \nPlease '
'provide Evoked compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
sources = self._transform(evoked.data[picks])
return sources
def get_components(self):
"""Get ICA topomap for components as numpy arrays.
Returns
-------
components : array, shape (n_channels, n_components)
The ICA components (maps).
"""
return np.dot(self.mixing_matrix_[:, :self.n_components_].T,
self.pca_components_[:self.n_components_]).T
def get_sources(self, inst, add_channels=None, start=None, stop=None):
"""Estimate sources given the unmixing matrix.
This method will return the sources in the container format passed.
Typical usecases:
1. pass Raw object to use `raw.plot <mne.io.Raw.plot>` for ICA sources
2. pass Epochs object to compute trial-based statistics in ICA space
3. pass Evoked object to investigate time-locking in ICA space
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from and to represent sources in.
add_channels : None | list of str
Additional channels to be added. Useful to e.g. compare sources
with some reference. Defaults to None.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
Returns
-------
sources : instance of Raw, Epochs or Evoked
The ICA sources time series.
"""
if isinstance(inst, BaseRaw):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',
ch_names=self.ch_names)
sources = self._sources_as_raw(inst, add_channels, start, stop)
elif isinstance(inst, BaseEpochs):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',
ch_names=self.ch_names)
sources = self._sources_as_epochs(inst, add_channels, False)
elif isinstance(inst, Evoked):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',
ch_names=self.ch_names)
sources = self._sources_as_evoked(inst, add_channels)
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
return sources
def _sources_as_raw(self, raw, add_channels, start, stop):
"""Aux method."""
# merge copied instance and picked data with sources
start, stop = _check_start_stop(raw, start, stop)
data_ = self._transform_raw(raw, start=start, stop=stop)
assert data_.shape[1] == stop - start
if raw.preload: # get data and temporarily delete
data = raw._data
del raw._data
out = raw.copy() # copy and reappend
if raw.preload:
raw._data = data
# populate copied raw.
if add_channels is not None and len(add_channels):
picks = pick_channels(raw.ch_names, add_channels)
data_ = np.concatenate([
data_, raw.get_data(picks, start=start, stop=stop)])
out._data = data_
out._filenames = [None]
out.preload = True
out._first_samps[:] = [out.first_samp + start]
out._last_samps[:] = [out.first_samp + data_.shape[1] - 1]
out._projector = None
self._export_info(out.info, raw, add_channels)
return out
def _sources_as_epochs(self, epochs, add_channels, concatenate):
"""Aux method."""
out = epochs.copy()
sources = self._transform_epochs(epochs, concatenate)
if add_channels is not None:
picks = [epochs.ch_names.index(k) for k in add_channels]
else:
picks = []
out._data = np.concatenate([sources, epochs.get_data()[:, picks]],
axis=1) if len(picks) > 0 else sources
self._export_info(out.info, epochs, add_channels)
out.preload = True
out._raw = None
out._projector = None
return out
def _sources_as_evoked(self, evoked, add_channels):
"""Aux method."""
if add_channels is not None:
picks = [evoked.ch_names.index(k) for k in add_channels]
else:
picks = []
sources = self._transform_evoked(evoked)
if len(picks) > 1:
data = np.r_[sources, evoked.data[picks]]
else:
data = sources
out = evoked.copy()
out.data = data
self._export_info(out.info, evoked, add_channels)
return out
def _export_info(self, info, container, add_channels):
"""Aux method."""
# set channel names and info
ch_names = []
ch_info = info['chs'] = []
for ii, name in enumerate(self._ica_names):
ch_names.append(name)
ch_info.append(dict(
ch_name=name, cal=1, logno=ii + 1,
coil_type=FIFF.FIFFV_COIL_NONE, kind=FIFF.FIFFV_MISC_CH,
coord_frame=FIFF.FIFFV_COORD_UNKNOWN, unit=FIFF.FIFF_UNIT_NONE,
loc=np.zeros(12, dtype='f4'),
range=1.0, scanno=ii + 1, unit_mul=0))
if add_channels is not None:
# re-append additionally picked ch_names
ch_names += add_channels
# re-append additionally picked ch_info
ch_info += [k for k in container.info['chs'] if k['ch_name'] in
add_channels]
info['bads'] = [ch_names[k] for k in self.exclude]
info['projs'] = [] # make sure projections are removed.
info._update_redundant()
info._check_consistency()
@verbose
def score_sources(self, inst, target=None, score_func='pearsonr',
start=None, stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, verbose=None):
"""Assign score to components based on statistic or metric.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
The object to reconstruct the sources from.
target : array-like | str | None
Signal to which the sources shall be compared. It has to be of
the same shape as the sources. If str, a routine will try to find
a matching channel name. If None, a score
function expecting only one input-array argument must be used,
for instance, scipy.stats.skew (default).
score_func : callable | str
Callable taking as arguments either two input arrays
(e.g. Pearson correlation) or one input
array (e. g. skewness) and returns a float. For convenience the
most common score_funcs are available via string labels:
Currently, all distance metrics from scipy.spatial and All
functions from scipy.stats taking compatible input arguments are
supported. These function have been modified to support iteration
over the rows of a 2D array.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
%(verbose_meth)s
Returns
-------
scores : ndarray
Scores for each source as returned from score_func.
"""
if isinstance(inst, BaseRaw):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',
ch_names=self.ch_names)
sources = self._transform_raw(inst, start, stop,
reject_by_annotation)
elif isinstance(inst, BaseEpochs):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',
ch_names=self.ch_names)
sources = self._transform_epochs(inst, concatenate=True)
elif isinstance(inst, Evoked):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',
ch_names=self.ch_names)
sources = self._transform_evoked(inst)
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
if target is not None: # we can have univariate metrics without target
target = self._check_target(target, inst, start, stop,
reject_by_annotation)
if sources.shape[-1] != target.shape[-1]:
raise ValueError('Sources and target do not have the same '
'number of time slices.')
# auto target selection
if isinstance(inst, BaseRaw):
# We pass inst, not self, because the sfreq of the data we
# use for scoring components can be different:
sources, target = _band_pass_filter(inst, sources, target,
l_freq, h_freq)
scores = _find_sources(sources, target, score_func)
return scores
def _check_target(self, target, inst, start, stop,
reject_by_annotation=False):
"""Aux Method."""
if isinstance(inst, BaseRaw):
reject_by_annotation = 'omit' if reject_by_annotation else None
start, stop = _check_start_stop(inst, start, stop)
if hasattr(target, 'ndim'):
if target.ndim < 2:
target = target.reshape(1, target.shape[-1])
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.get_data(pick, start, stop, reject_by_annotation)
elif isinstance(inst, BaseEpochs):
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.get_data()[:, pick]
if hasattr(target, 'ndim'):
if target.ndim == 3 and min(target.shape) == 1:
target = target.ravel()
elif isinstance(inst, Evoked):
if isinstance(target, str):
pick = _get_target_ch(inst, target)
target = inst.data[pick]
return target
def _find_bads_ch(self, inst, chs, threshold=3.0, start=None,
stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, prefix='chs',
measure='zscore'):
"""Compute ExG/ref components.
See find_bads_ecg, find_bads_eog, and find_bads_ref for details.
"""
scores, idx = [], []
# some magic we need inevitably ...
# get targets before equalizing
targets = [self._check_target(
ch, inst, start, stop, reject_by_annotation) for ch in chs]
# assign names, if targets are arrays instead of strings
target_names = []
for ch in chs:
if not isinstance(ch, str):
if prefix == "ecg":
target_names.append('ECG-MAG')
else:
target_names.append(prefix)
else:
target_names.append(ch)
for ii, (ch, target) in enumerate(zip(target_names, targets)):
scores += [self.score_sources(
inst, target=target, score_func='pearsonr', start=start,
stop=stop, l_freq=l_freq, h_freq=h_freq,
reject_by_annotation=reject_by_annotation)]
# pick last scores
if measure == "zscore":
this_idx = _find_outliers(scores[-1], threshold=threshold)
elif measure == "correlation":
this_idx = np.where(abs(scores[-1]) > threshold)[0]
else:
raise ValueError("Unknown measure {}".format(measure))
idx += [this_idx]
self.labels_['%s/%i/' % (prefix, ii) + ch] = list(this_idx)
# remove duplicates but keep order by score, even across multiple
# ref channels
scores_ = np.concatenate([scores[ii][inds]
for ii, inds in enumerate(idx)])
idx_ = np.concatenate(idx)[np.abs(scores_).argsort()[::-1]]
idx_unique = list(np.unique(idx_))
idx = []
for i in idx_:
if i in idx_unique:
idx.append(i)
idx_unique.remove(i)
if len(scores) == 1:
scores = scores[0]
labels = list(idx)
return labels, scores
def _get_ctps_threshold(self, pk_threshold=20):
"""Automatically decide the threshold of Kuiper index for CTPS method.
This function finds the threshold of Kuiper index based on the
threshold of pk. Kuiper statistic that minimizes the difference between
pk and the pk threshold (defaults to 20 [1]) is returned. It is assumed
that the data are appropriately filtered and bad data are rejected at
least based on peak-to-peak amplitude when/before running the ICA
decomposition on data.
References
----------
[1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,
M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude
and phase statistics for complete artifact removal in independent
components of neuromagnetic recordings. Biomedical
Engineering, IEEE Transactions on 55 (10), pp.2356.
"""
N = self.info['sfreq']
Vs = np.arange(1, 100) / 100
C = math.sqrt(N) + 0.155 + 0.24 / math.sqrt(N)
# in formula (13), when k gets large, only k=1 matters for the
# summation. k*V*C thus becomes V*C
Pks = 2 * (4 * (Vs * C)**2 - 1) * (np.exp(-2 * (Vs * C)**2))
# NOTE: the threshold of pk is transformed to Pk for comparison
# pk = -log10(Pk)
return Vs[np.argmin(np.abs(Pks - 10**(-pk_threshold)))]
@verbose
def find_bads_ecg(self, inst, ch_name=None, threshold='auto', start=None,
stop=None, l_freq=8, h_freq=16, method='ctps',
reject_by_annotation=True, measure='zscore',
verbose=None):
"""Detect ECG related components.
Cross-trial phase statistics (default) or Pearson correlation can be
used for detection.
.. note:: If no ECG channel is available, routine attempts to create
an artificial ECG based on cross-channel averaging.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from.
ch_name : str
The name of the channel to use for ECG peak detection.
The argument is mandatory if the dataset contains no ECG
channels.
threshold : float | str
The value above which a feature is classified as outlier. If 'auto'
and method is 'ctps', automatically compute the threshold. If
'auto' and method is 'correlation', defaults to 3.0. The default
translates to 0.25 for 'ctps' and 3.0 for 'correlation' in version
0.21 but will change to 'auto' in version 0.22.
.. versionchanged:: 0.21
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
method : {'ctps', 'correlation'}
The method used for detection. If 'ctps', cross-trial phase
statistics [1] are used to detect ECG related components.
Thresholding is then based on the significance value of a Kuiper
statistic.
If 'correlation', detection is based on Pearson correlation
between the filtered data and the filtered ECG channel.
Thresholding is based on iterative z-scoring. The above
threshold components will be masked and the z-score will
be recomputed until no supra-threshold component remains.
Defaults to 'ctps'.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
ecg_idx : list of int
The indices of ECG-related components.
scores : np.ndarray of float, shape (``n_components_``)
If method is 'ctps', the normalized Kuiper index scores. If method
is 'correlation', the correlation scores.
See Also
--------
find_bads_eog, find_bads_ref
References
----------
[1] Dammers, J., Schiek, M., Boers, F., Silex, C., Zvyagintsev,
M., Pietrzyk, U., Mathiak, K., 2008. Integration of amplitude
and phase statistics for complete artifact removal in independent
components of neuromagnetic recordings. Biomedical
Engineering, IEEE Transactions on 55 (10), 2353-2362.
"""
idx_ecg = _get_ecg_channel_index(ch_name, inst)
if idx_ecg is None:
ecg, times = _make_ecg(inst, start, stop,
reject_by_annotation=reject_by_annotation)
else:
ecg = inst.ch_names[idx_ecg]
_validate_type(threshold, (str, 'numeric'), 'threshold')
if isinstance(threshold, str):
_check_option('threshold', threshold, ('auto',), extra='when str')
if method == 'ctps':
if threshold == 'auto':
threshold = self._get_ctps_threshold()
logger.info('Using threshold: %.2f for CTPS ECG detection'
% threshold)
if isinstance(inst, BaseRaw):
sources = self.get_sources(create_ecg_epochs(
inst, ch_name, l_freq=l_freq, h_freq=h_freq,
keep_ecg=False,
reject_by_annotation=reject_by_annotation)).get_data()
if sources.shape[0] == 0:
warn('No ECG activity detected. Consider changing '
'the input parameters.')
elif isinstance(inst, BaseEpochs):
sources = self.get_sources(inst).get_data()
else:
raise ValueError('With `ctps` only Raw and Epochs input is '
'supported')
_, p_vals, _ = ctps(sources)
scores = p_vals.max(-1)
ecg_idx = np.where(scores >= threshold)[0]
# sort indices by scores
ecg_idx = ecg_idx[np.abs(scores[ecg_idx]).argsort()[::-1]]
self.labels_['ecg'] = list(ecg_idx)
if ch_name is None:
ch_name = 'ECG-MAG'
self.labels_['ecg/%s' % ch_name] = list(ecg_idx)
elif method == 'correlation':
if threshold == 'auto':
threshold = 3.0
self.labels_['ecg'], scores = self._find_bads_ch(
inst, [ecg], threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix="ecg",
reject_by_annotation=reject_by_annotation, measure=measure)
else:
raise ValueError('Method "%s" not supported.' % method)
return self.labels_['ecg'], scores
@verbose
def find_bads_ref(self, inst, ch_name=None, threshold=3.0, start=None,
stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, method='together',
measure="zscore", verbose=None):
"""Detect MEG reference related components using correlation.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from. Should contain at least one channel
i.e. component derived from MEG reference channels.
ch_name : list of str
Which MEG reference components to use. If None, then all channels
that begin with REF_ICA.
threshold : int | float
The value above which a feature is classified as outlier.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
method : 'together' | 'separate'
Method to use to identify reference channel related components.
Defaults to ``'together'``. See notes.
.. versionadded:: 0.21
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
ref_idx : list of int
The indices of MEG reference related components, sorted by score.
scores : np.ndarray of float, shape (``n_components_``) | list of array
The correlation scores.
See Also
--------
find_bads_ecg, find_bads_eog
Notes
-----
ICA decomposition on MEG reference channels is used to assess external
magnetic noise and remove it from the MEG. Two methods are supported:
With the "together" method, only one ICA fit is used, which
encompasses both MEG and reference channels together. Components which
have particularly strong weights on the reference channels may be
thresholded and marked for removal.
With "separate," selected components from a separate ICA decomposition
on the reference channels are used as a ground truth for identifying
bad components in an ICA fit done on MEG channels only. The logic here
is similar to an EOG/ECG, with reference components replacing the
EOG/ECG channels. Recommended procedure is to perform ICA separately
on reference channels, extract them using .get_sources(), and then
append them to the inst using :meth:`~mne.io.Raw.add_channels`,
preferably with the prefix ``REF_ICA`` so that they can be
automatically detected.
Thresholding in both cases is based on adaptive z-scoring:
The above-threshold components will be masked and the z-score will be
recomputed until no supra-threshold component remains.
Validation and further documentation for this technique can be found
in :footcite:`HannaEtAl2020`.
.. versionadded:: 0.18
References
----------
.. footbibliography::
"""
if method == "separate":
if not ch_name:
inds = pick_channels_regexp(inst.ch_names, 'REF_ICA*')
else:
inds = pick_channels(inst.ch_names, ch_name)
# regexp returns list, pick_channels returns numpy
inds = list(inds)
if not inds:
raise ValueError('No valid channels available.')
ref_chs = [inst.ch_names[k] for k in inds]
self.labels_['ref_meg'], scores = self._find_bads_ch(
inst, ref_chs, threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix='ref_meg',
reject_by_annotation=reject_by_annotation,
measure=measure)
elif method == 'together':
meg_picks = pick_types(self.info, meg=True, ref_meg=False)
ref_picks = pick_types(self.info, meg=False, ref_meg=True)
if not any(meg_picks) or not any(ref_picks):
raise ValueError('ICA solution must contain both reference and\
MEG channels.')
weights = self.get_components()
# take norm of component weights on reference channels for each
# component, divide them by the norm on the standard channels,
# log transform to approximate normal distribution
normrats = np.linalg.norm(weights[ref_picks],
axis=0) / np.linalg.norm(weights[meg_picks], # noqa
axis=0)
scores = np.log(normrats)
self.labels_['ref_meg'] = list(_find_outliers(scores,
threshold=threshold,
tail=1))
else:
raise ValueError('Method "%s" not supported.' % method)
return self.labels_['ref_meg'], scores
@verbose
def find_bads_eog(self, inst, ch_name=None, threshold=3.0, start=None,
stop=None, l_freq=1, h_freq=10,
reject_by_annotation=True, measure='zscore',
verbose=None):
"""Detect EOG related components using correlation.
Detection is based on Pearson correlation between the
filtered data and the filtered EOG channel.
Thresholding is based on adaptive z-scoring. The above threshold
components will be masked and the z-score will be recomputed
until no supra-threshold component remains.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from.
ch_name : str
The name of the channel to use for EOG peak detection.
The argument is mandatory if the dataset contains no EOG
channels.
threshold : int | float
The value above which a feature is classified as outlier.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
%(reject_by_annotation_all)s
.. versionadded:: 0.14.0
measure : 'zscore' | 'correlation'
Which method to use for finding outliers. ``'zscore'`` (default) is
the iterated Z-scoring method, and ``'correlation'`` is an absolute
raw correlation threshold with a range of 0 to 1.
.. versionadded:: 0.21
%(verbose_meth)s
Returns
-------
eog_idx : list of int
The indices of EOG related components, sorted by score.
scores : np.ndarray of float, shape (``n_components_``) | list of array
The correlation scores.
See Also
--------
find_bads_ecg, find_bads_ref
"""
eog_inds = _get_eog_channel_index(ch_name, inst)
eog_chs = [inst.ch_names[k] for k in eog_inds]
self.labels_['eog'], scores = self._find_bads_ch(
inst, eog_chs, threshold=threshold, start=start, stop=stop,
l_freq=l_freq, h_freq=h_freq, prefix="eog",
reject_by_annotation=reject_by_annotation, measure=measure)
return self.labels_['eog'], scores
@verbose
def apply(self, inst, include=None, exclude=None, n_pca_components=None,
start=None, stop=None, verbose=None):
"""Remove selected components from the signal.
Given the unmixing matrix, transform data,
zero out components, and inverse transform the data.
This procedure will reconstruct M/EEG signals from which
the dynamics described by the excluded components is subtracted.
The data is processed in place.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
The data to be processed. The instance is modified inplace.
include : array_like of int
The indices referring to columns in the ummixing matrix. The
components to be kept.
exclude : array_like of int
The indices referring to columns in the ummixing matrix. The
components to be zeroed out.
%(n_pca_components_apply)s
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
%(verbose_meth)s
Returns
-------
out : instance of Raw, Epochs or Evoked
The processed data.
"""
_validate_type(inst, (BaseRaw, BaseEpochs, Evoked), 'inst',
'Raw, Epochs, or Evoked')
kwargs = dict(include=include, exclude=exclude,
n_pca_components=n_pca_components)
if isinstance(inst, BaseRaw):
kind, meth = 'Raw', self._apply_raw
kwargs.update(raw=inst, start=start, stop=stop)
elif isinstance(inst, BaseEpochs):
kind, meth = 'Epochs', self._apply_epochs
kwargs.update(epochs=inst)
else: # isinstance(inst, Evoked):
kind, meth = 'Evoked', self._apply_evoked
kwargs.update(evoked=inst)
_check_compensation_grade(self.info, inst.info, 'ICA', kind,
ch_names=self.ch_names)
logger.info(f'Applying ICA to {kind} instance')
return meth(**kwargs)
def _check_exclude(self, exclude):
if exclude is None:
return list(set(self.exclude))
else:
# Allow both self.exclude and exclude to be array-like:
return list(set(self.exclude).union(set(exclude)))
def _apply_raw(self, raw, include, exclude, n_pca_components, start, stop):
"""Aux method."""
_check_preload(raw, "ica.apply")
start, stop = _check_start_stop(raw, start, stop)
picks = pick_types(raw.info, meg=False, include=self.ch_names,
exclude='bads', ref_meg=False)
data = raw[picks, start:stop][0]
data = self._pick_sources(data, include, exclude, n_pca_components)
raw[picks, start:stop] = data
return raw
def _apply_epochs(self, epochs, include, exclude, n_pca_components):
"""Aux method."""
_check_preload(epochs, "ica.apply")
picks = pick_types(epochs.info, meg=False, ref_meg=False,
include=self.ch_names,
exclude='bads')
# special case where epochs come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Epochs don\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Epochs compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data = np.hstack(epochs.get_data(picks))
data = self._pick_sources(data, include, exclude, n_pca_components)
# restore epochs, channels, tsl order
epochs._data[:, picks] = np.array(
np.split(data, len(epochs.events), 1))
epochs.preload = True
return epochs
def _apply_evoked(self, evoked, include, exclude, n_pca_components):
"""Aux method."""
picks = pick_types(evoked.info, meg=False, ref_meg=False,
include=self.ch_names,
exclude='bads')
# special case where evoked come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Evoked does not match fitted data: %i channels'
' fitted but %i channels supplied. \nPlease '
'provide an Evoked object that\'s compatible '
'with ica.ch_names' % (len(self.ch_names),
len(picks)))
data = evoked.data[picks]
data = self._pick_sources(data, include, exclude, n_pca_components)
# restore evoked
evoked.data[picks] = data
return evoked
def _pick_sources(self, data, include, exclude, n_pca_components):
"""Aux function."""
if n_pca_components is None:
n_pca_components = self.n_pca_components
data = self._pre_whiten(data)
exclude = self._check_exclude(exclude)
_n_pca_comp = self._check_n_pca_components(n_pca_components)
n_ch, _ = data.shape
max_pca_components = self.pca_components_.shape[0]
if not self.n_components_ <= _n_pca_comp <= max_pca_components:
raise ValueError(
f'n_pca_components ({_n_pca_comp}) must be >= '
f'n_components_ ({self.n_components_}) and <= '
'the total number of PCA components '
f'({max_pca_components}).')
logger.info(f' Transforming to ICA space ({self.n_components_} '
f'component{_pl(self.n_components_)})')
# Apply first PCA
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
sel_keep = np.arange(self.n_components_)
if include not in (None, []):
sel_keep = np.unique(include)
elif exclude not in (None, []):
sel_keep = np.setdiff1d(np.arange(self.n_components_), exclude)
n_zero = self.n_components_ - len(sel_keep)
logger.info(f' Zeroing out {n_zero} ICA component{_pl(n_zero)}')
# Mixing and unmixing should both be shape (self.n_components_, 2),
# and we need to put these into the upper left part of larger mixing
# and unmixing matrices of shape (n_ch, _n_pca_comp)
pca_components = self.pca_components_[:_n_pca_comp]
assert pca_components.shape == (_n_pca_comp, n_ch)
assert self.unmixing_matrix_.shape == \
self.mixing_matrix_.shape == \
(self.n_components_,) * 2
unmixing = np.eye(_n_pca_comp)
unmixing[:self.n_components_, :self.n_components_] = \
self.unmixing_matrix_
unmixing = np.dot(unmixing, pca_components)
logger.info(f' Projecting back using {_n_pca_comp} '
f'PCA component{_pl(_n_pca_comp)}')
mixing = np.eye(_n_pca_comp)
mixing[:self.n_components_, :self.n_components_] = \
self.mixing_matrix_
mixing = pca_components.T @ mixing
assert mixing.shape == unmixing.shape[::-1] == (n_ch, _n_pca_comp)
# keep requested components plus residuals (if any)
sel_keep = np.concatenate(
(sel_keep, np.arange(self.n_components_, _n_pca_comp)))
proj_mat = np.dot(mixing[:, sel_keep], unmixing[sel_keep, :])
data = np.dot(proj_mat, data)
assert proj_mat.shape == (n_ch,) * 2
if self.pca_mean_ is not None:
data += self.pca_mean_[:, None]
# restore scaling
if self.noise_cov is None: # revert standardization
data *= self.pre_whitener_
else:
data = np.linalg.pinv(self.pre_whitener_, rcond=1e-14) @ data
return data
@verbose
def save(self, fname, verbose=None):
"""Store ICA solution into a fiff file.
Parameters
----------
fname : str
The absolute path of the file name to save the ICA solution into.
The file name should end with -ica.fif or -ica.fif.gz.
%(verbose_meth)s
Returns
-------
ica : instance of ICA
The object.
See Also
--------
read_ica
"""
if self.current_fit == 'unfitted':
raise RuntimeError('No fit available. Please first fit ICA')
check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',
'_ica.fif', '_ica.fif.gz'))
logger.info('Writing ICA solution to %s...' % fname)
fid = start_file(fname)
try:
_write_ica(fid, self)
end_file(fid)
except Exception:
end_file(fid)
os.remove(fname)
raise
return self
def copy(self):
"""Copy the ICA object.
Returns
-------
ica : instance of ICA
The copied object.
"""
return deepcopy(self)
@copy_function_doc_to_method_doc(plot_ica_components)
def plot_components(self, picks=None, ch_type=None, res=64,
vmin=None, vmax=None, cmap='RdBu_r', sensors=True,
colorbar=False, title=None, show=True, outlines='head',
contours=6, image_interp='bilinear',
inst=None, plot_std=True, topomap_args=None,
image_args=None, psd_args=None, reject='auto',
sphere=None, verbose=None):
return plot_ica_components(self, picks=picks, ch_type=ch_type,
res=res, vmin=vmin,
vmax=vmax, cmap=cmap, sensors=sensors,
colorbar=colorbar, title=title, show=show,
outlines=outlines, contours=contours,
image_interp=image_interp,
inst=inst, plot_std=plot_std,
topomap_args=topomap_args,
image_args=image_args, psd_args=psd_args,
reject=reject, sphere=sphere,
verbose=verbose)
@copy_function_doc_to_method_doc(plot_ica_properties)
def plot_properties(self, inst, picks=None, axes=None, dB=True,
plot_std=True, topomap_args=None, image_args=None,
psd_args=None, figsize=None, show=True, reject='auto',
reject_by_annotation=True, *, verbose=None):
return plot_ica_properties(self, inst, picks=picks, axes=axes,
dB=dB, plot_std=plot_std,
topomap_args=topomap_args,
image_args=image_args, psd_args=psd_args,
figsize=figsize, show=show, reject=reject,
reject_by_annotation=reject_by_annotation,
verbose=verbose)
@copy_function_doc_to_method_doc(plot_ica_sources)
def plot_sources(self, inst, picks=None, start=None,
stop=None, title=None, show=True, block=False,
show_first_samp=False, show_scrollbars=True):
return plot_ica_sources(self, inst=inst, picks=picks,
start=start, stop=stop, title=title, show=show,
block=block, show_first_samp=show_first_samp,
show_scrollbars=show_scrollbars)
@copy_function_doc_to_method_doc(plot_ica_scores)
def plot_scores(self, scores, exclude=None, labels=None, axhline=None,
title='ICA component scores', figsize=None, n_cols=None,
show=True):
return plot_ica_scores(
ica=self, scores=scores, exclude=exclude, labels=labels,
axhline=axhline, title=title, figsize=figsize, n_cols=n_cols,
show=show)
@copy_function_doc_to_method_doc(plot_ica_overlay)
def plot_overlay(self, inst, exclude=None, picks=None, start=None,
stop=None, title=None, show=True, n_pca_components=None):
return plot_ica_overlay(self, inst=inst, exclude=exclude, picks=picks,
start=start, stop=stop, title=title, show=show,
n_pca_components=n_pca_components)
def detect_artifacts(self, raw, start_find=None, stop_find=None,
ecg_ch=None, ecg_score_func='pearsonr',
ecg_criterion=0.1, eog_ch=None,
eog_score_func='pearsonr',
eog_criterion=0.1, skew_criterion=0,
kurt_criterion=0, var_criterion=-1,
add_nodes=None):
"""Run ICA artifacts detection workflow.
Note. This is still experimental and will most likely change over
the next releases. For maximum control use the workflow exposed in
the examples.
Hints and caveats:
- It is highly recommended to bandpass filter ECG and EOG
data and pass them instead of the channel names as ecg_ch and eog_ch
arguments.
- please check your results. Detection by kurtosis and variance
may be powerful but misclassification of brain signals as
noise cannot be precluded.
- Consider using shorter times for start_find and stop_find than
for start and stop. It can save you much time.
Example invocation (taking advantage of the defaults)::
ica.detect_artifacts(ecg_channel='MEG 1531', eog_channel='EOG 061')
Parameters
----------
raw : instance of Raw
Raw object to draw sources from. No components are actually removed
here, i.e. ica is not applied to raw in this function. Use
`ica.apply() <ICA.apply>` for this after inspection of the
identified components.
start_find : int | float | None
First sample to include for artifact search. If float, data will be
interpreted as time in seconds. If None, data will be used from the
first sample.
stop_find : int | float | None
Last sample to not include for artifact search. If float, data will
be interpreted as time in seconds. If None, data will be used to
the last sample.
ecg_ch : str | ndarray | None
The ``target`` argument passed to ica.find_sources_raw. Either the
name of the ECG channel or the ECG time series. If None, this step
will be skipped.
ecg_score_func : str | callable
The ``score_func`` argument passed to ica.find_sources_raw. Either
the name of function supported by ICA or a custom function.
ecg_criterion : float | int | list-like | slice
The indices of the sorted ecg scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
eog_ch : list | str | ndarray | None
The ``target`` argument or the list of target arguments
subsequently passed to ica.find_sources_raw. Either the name of the
vertical EOG channel or the corresponding EOG time series. If None,
this step will be skipped.
eog_score_func : str | callable
The ``score_func`` argument passed to ica.find_sources_raw. Either
the name of function supported by ICA or a custom function.
eog_criterion : float | int | list-like | slice
The indices of the sorted eog scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
skew_criterion : float | int | list-like | slice
The indices of the sorted skewness scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
kurt_criterion : float | int | list-like | slice
The indices of the sorted kurtosis scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
var_criterion : float | int | list-like | slice
The indices of the sorted variance scores. If float, sources with
absolute scores greater than the criterion will be dropped. Else,
the absolute scores sorted in descending order will be indexed
accordingly. E.g. range(2) would return the two sources with the
highest absolute score. If None, this step will be skipped.
add_nodes : list of tuple
Additional list if tuples carrying the following parameters
of ica nodes:
(name : str, target : str | array, score_func : callable,
criterion : float | int | list-like | slice). This parameter is a
generalization of the artifact specific parameters above and has
the same structure. Example::
add_nodes=('ECG phase lock', ECG 01',
my_phase_lock_function, 0.5)
Returns
-------
self : instance of ICA
The ICA object with the detected artifact indices marked for
exclusion.
"""
logger.info(' Searching for artifacts...')
_detect_artifacts(self, raw=raw, start_find=start_find,
stop_find=stop_find, ecg_ch=ecg_ch,
ecg_score_func=ecg_score_func,
ecg_criterion=ecg_criterion,
eog_ch=eog_ch, eog_score_func=eog_score_func,
eog_criterion=eog_criterion,
skew_criterion=skew_criterion,
kurt_criterion=kurt_criterion,
var_criterion=var_criterion,
add_nodes=add_nodes)
return self
@verbose
def _check_n_pca_components(self, _n_pca_comp, verbose=None):
"""Aux function."""
if isinstance(_n_pca_comp, float):
n, ev = _exp_var_ncomp(
self.pca_explained_variance_, _n_pca_comp)
logger.info(f' Selected {n} PCA components by explained '
f'variance ({100 * ev}≥{100 * _n_pca_comp}%)')
_n_pca_comp = n
elif _n_pca_comp is None:
_n_pca_comp = self._max_pca_components
if _n_pca_comp is None:
_n_pca_comp = self.pca_components_.shape[0]
elif _n_pca_comp < self.n_components_:
_n_pca_comp = self.n_components_
return _n_pca_comp
def _exp_var_ncomp(var, n):
cvar = np.asarray(var, dtype=np.float64)
cvar = cvar.cumsum()
cvar /= cvar[-1]
# We allow 1., which would give us N+1
n = min((cvar <= n).sum() + 1, len(cvar))
return n, cvar[n - 1]
def _check_start_stop(raw, start, stop):
"""Aux function."""
out = list()
for st, none_ in ((start, 0), (stop, raw.n_times)):
if st is None:
out.append(none_)
else:
try:
out.append(_ensure_int(st))
except TypeError: # not int-like
out.append(raw.time_as_index(st)[0])
return out
@verbose
def ica_find_ecg_events(raw, ecg_source, event_id=999,
tstart=0.0, l_freq=5, h_freq=35, qrs_threshold='auto',
verbose=None):
"""Find ECG peaks from one selected ICA source.
Parameters
----------
raw : instance of Raw
Raw object to draw sources from.
ecg_source : ndarray
ICA source resembling ECG to find peaks from.
event_id : int
The index to assign to found events.
tstart : float
Start detection after tstart seconds. Useful when beginning
of run is noisy.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
qrs_threshold : float | str
Between 0 and 1. qrs detection threshold. Can also be "auto" to
automatically choose the threshold that generates a reasonable
number of heartbeats (40-160 beats / min).
%(verbose)s
Returns
-------
ecg_events : array
Events.
ch_ECG : string
Name of channel used.
average_pulse : float.
Estimated average pulse.
"""
logger.info('Using ICA source to identify heart beats')
# detecting QRS and generating event file
ecg_events = qrs_detector(raw.info['sfreq'], ecg_source.ravel(),
tstart=tstart, thresh_value=qrs_threshold,
l_freq=l_freq, h_freq=h_freq)
n_events = len(ecg_events)
ecg_events = np.c_[ecg_events + raw.first_samp, np.zeros(n_events),
event_id * np.ones(n_events)]
return ecg_events
@verbose
def ica_find_eog_events(raw, eog_source=None, event_id=998, l_freq=1,
h_freq=10, verbose=None):
"""Locate EOG artifacts from one selected ICA source.
Parameters
----------
raw : instance of Raw
The raw data.
eog_source : ndarray
ICA source resembling EOG to find peaks from.
event_id : int
The index to assign to found events.
l_freq : float
Low cut-off frequency in Hz.
h_freq : float
High cut-off frequency in Hz.
%(verbose)s
Returns
-------
eog_events : array
Events.
"""
eog_events = _find_eog_events(eog_source[np.newaxis], event_id=event_id,
l_freq=l_freq, h_freq=h_freq,
sampling_rate=raw.info['sfreq'],
first_samp=raw.first_samp)
return eog_events
def _get_target_ch(container, target):
"""Aux function."""
# auto target selection
picks = pick_channels(container.ch_names, include=[target])
ref_picks = pick_types(container.info, meg=False, eeg=False, ref_meg=True)
if len(ref_picks) > 0:
picks = list(set(picks) - set(ref_picks))
if len(picks) == 0:
raise ValueError('%s not in channel list (%s)' %
(target, container.ch_names))
return picks
def _find_sources(sources, target, score_func):
"""Aux function."""
if isinstance(score_func, str):
score_func = get_score_funcs().get(score_func, score_func)
if not callable(score_func):
raise ValueError('%s is not a valid score_func.' % score_func)
scores = (score_func(sources, target) if target is not None
else score_func(sources, 1))
return scores
def _ica_explained_variance(ica, inst, normalize=False):
"""Check variance accounted for by each component in supplied data.
Parameters
----------
ica : ICA
Instance of `mne.preprocessing.ICA`.
inst : Raw | Epochs | Evoked
Data to explain with ICA. Instance of Raw, Epochs or Evoked.
normalize : bool
Whether to normalize the variance.
Returns
-------
var : array
Variance explained by each component.
"""
# check if ica is ICA and whether inst is Raw or Epochs
if not isinstance(ica, ICA):
raise TypeError('first argument must be an instance of ICA.')
if not isinstance(inst, (BaseRaw, BaseEpochs, Evoked)):
raise TypeError('second argument must an instance of either Raw, '
'Epochs or Evoked.')
source_data = _get_inst_data(ica.get_sources(inst))
# if epochs - reshape to channels x timesamples
if isinstance(inst, BaseEpochs):
n_epochs, n_chan, n_samp = source_data.shape
source_data = source_data.transpose(1, 0, 2).reshape(
(n_chan, n_epochs * n_samp))
n_chan, n_samp = source_data.shape
var = np.sum(ica.mixing_matrix_ ** 2, axis=0) * np.sum(
source_data ** 2, axis=1) / (n_chan * n_samp - 1)
if normalize:
var /= var.sum()
return var
def _sort_components(ica, order, copy=True):
"""Change the order of components in ica solution."""
assert ica.n_components_ == len(order)
if copy:
ica = ica.copy()
# reorder components
ica.mixing_matrix_ = ica.mixing_matrix_[:, order]
ica.unmixing_matrix_ = ica.unmixing_matrix_[order, :]
# reorder labels, excludes etc.
if isinstance(order, np.ndarray):
order = list(order)
if ica.exclude:
ica.exclude = [order.index(ic) for ic in ica.exclude]
for k in ica.labels_.keys():
ica.labels_[k] = [order.index(ic) for ic in ica.labels_[k]]
return ica
def _serialize(dict_, outer_sep=';', inner_sep=':'):
"""Aux function."""
s = []
for key, value in dict_.items():
if callable(value):
value = value.__name__
elif isinstance(value, Integral):
value = int(value)
elif isinstance(value, dict):
# py35 json does not support numpy int64
for subkey, subvalue in value.items():
if isinstance(subvalue, list):
if len(subvalue) > 0:
if isinstance(subvalue[0], (int, np.integer)):
value[subkey] = [int(i) for i in subvalue]
for cls in (np.random.RandomState, Covariance):
if isinstance(value, cls):
value = cls.__name__
s.append(key + inner_sep + json.dumps(value))
return outer_sep.join(s)
def _deserialize(str_, outer_sep=';', inner_sep=':'):
"""Aux Function."""
out = {}
for mapping in str_.split(outer_sep):
k, v = mapping.split(inner_sep, 1)
out[k] = json.loads(v)
return out
def _write_ica(fid, ica):
"""Write an ICA object.
Parameters
----------
fid: file
The file descriptor
ica:
The instance of ICA to write
"""
ica_init = dict(noise_cov=ica.noise_cov,
n_components=ica.n_components,
n_pca_components=ica.n_pca_components,
max_pca_components=ica._max_pca_components,
current_fit=ica.current_fit,
allow_ref_meg=ica.allow_ref_meg)
if ica.info is not None:
start_block(fid, FIFF.FIFFB_MEAS)
write_id(fid, FIFF.FIFF_BLOCK_ID)
if ica.info['meas_id'] is not None:
write_id(fid, FIFF.FIFF_PARENT_BLOCK_ID, ica.info['meas_id'])
# Write measurement info
write_meas_info(fid, ica.info)
end_block(fid, FIFF.FIFFB_MEAS)
start_block(fid, FIFF.FIFFB_MNE_ICA)
# ICA interface params
write_string(fid, FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS,
_serialize(ica_init))
# Channel names
if ica.ch_names is not None:
write_name_list(fid, FIFF.FIFF_MNE_ROW_NAMES, ica.ch_names)
# samples on fit
n_samples = getattr(ica, 'n_samples_', None)
ica_misc = {'n_samples_': (None if n_samples is None else int(n_samples)),
'labels_': getattr(ica, 'labels_', None),
'method': getattr(ica, 'method', None),
'n_iter_': getattr(ica, 'n_iter_', None),
'fit_params': getattr(ica, 'fit_params', None)}
# ICA misc params
write_string(fid, FIFF.FIFF_MNE_ICA_MISC_PARAMS,
_serialize(ica_misc))
# Whitener
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_WHITENER, ica.pre_whitener_)
# PCA components_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_COMPONENTS,
ica.pca_components_)
# PCA mean_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_MEAN, ica.pca_mean_)
# PCA explained_variance_
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR,
ica.pca_explained_variance_)
# ICA unmixing
write_double_matrix(fid, FIFF.FIFF_MNE_ICA_MATRIX, ica.unmixing_matrix_)
# Write bad components
write_int(fid, FIFF.FIFF_MNE_ICA_BADS, list(ica.exclude))
# Done!
end_block(fid, FIFF.FIFFB_MNE_ICA)
@verbose
def read_ica(fname, verbose=None):
"""Restore ICA solution from fif file.
Parameters
----------
fname : str
Absolute path to fif file containing ICA matrices.
The file name should end with -ica.fif or -ica.fif.gz.
%(verbose)s
Returns
-------
ica : instance of ICA
The ICA estimator.
"""
check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz',
'_ica.fif', '_ica.fif.gz'))
logger.info('Reading %s ...' % fname)
fid, tree, _ = fiff_open(fname)
try:
# we used to store bads that weren't part of the info...
info, _ = read_meas_info(fid, tree, clean_bads=True)
except ValueError:
logger.info('Could not find the measurement info. \n'
'Functionality requiring the info won\'t be'
' available.')
info = None
ica_data = dir_tree_find(tree, FIFF.FIFFB_MNE_ICA)
if len(ica_data) == 0:
ica_data = dir_tree_find(tree, 123) # Constant 123 Used before v 0.11
if len(ica_data) == 0:
fid.close()
raise ValueError('Could not find ICA data')
my_ica_data = ica_data[0]
for d in my_ica_data['directory']:
kind = d.kind
pos = d.pos
if kind == FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS:
tag = read_tag(fid, pos)
ica_init = tag.data
elif kind == FIFF.FIFF_MNE_ROW_NAMES:
tag = read_tag(fid, pos)
ch_names = tag.data
elif kind == FIFF.FIFF_MNE_ICA_WHITENER:
tag = read_tag(fid, pos)
pre_whitener = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_COMPONENTS:
tag = read_tag(fid, pos)
pca_components = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR:
tag = read_tag(fid, pos)
pca_explained_variance = tag.data
elif kind == FIFF.FIFF_MNE_ICA_PCA_MEAN:
tag = read_tag(fid, pos)
pca_mean = tag.data
elif kind == FIFF.FIFF_MNE_ICA_MATRIX:
tag = read_tag(fid, pos)
unmixing_matrix = tag.data
elif kind == FIFF.FIFF_MNE_ICA_BADS:
tag = read_tag(fid, pos)
exclude = tag.data
elif kind == FIFF.FIFF_MNE_ICA_MISC_PARAMS:
tag = read_tag(fid, pos)
ica_misc = tag.data
fid.close()
ica_init, ica_misc = [_deserialize(k) for k in (ica_init, ica_misc)]
n_pca_components = ica_init.pop('n_pca_components')
current_fit = ica_init.pop('current_fit')
max_pca_components = ica_init.pop('max_pca_components')
method = ica_misc.get('method', 'fastica')
if method in _KNOWN_ICA_METHODS:
ica_init['method'] = method
if ica_init['noise_cov'] == Covariance.__name__:
logger.info('Reading whitener drawn from noise covariance ...')
logger.info('Now restoring ICA solution ...')
# make sure dtypes are np.float64 to satisfy fast_dot
def f(x):
return x.astype(np.float64)
ica_init = {k: v for k, v in ica_init.items()
if k in _get_args(ICA.__init__)}
ica = ICA(**ica_init)
ica.current_fit = current_fit
ica.ch_names = ch_names.split(':')
if n_pca_components is not None and \
not isinstance(n_pca_components, int_like):
n_pca_components = np.float64(n_pca_components)
ica.n_pca_components = n_pca_components
ica.pre_whitener_ = f(pre_whitener)
ica.pca_mean_ = f(pca_mean)
ica.pca_components_ = f(pca_components)
ica.n_components_ = unmixing_matrix.shape[0]
ica._max_pca_components = max_pca_components
ica._update_ica_names()
ica.pca_explained_variance_ = f(pca_explained_variance)
ica.unmixing_matrix_ = f(unmixing_matrix)
ica._update_mixing_matrix()
ica.exclude = [] if exclude is None else list(exclude)
ica.info = info
if 'n_samples_' in ica_misc:
ica.n_samples_ = ica_misc['n_samples_']
if 'labels_' in ica_misc:
labels_ = ica_misc['labels_']
if labels_ is not None:
ica.labels_ = labels_
if 'method' in ica_misc:
ica.method = ica_misc['method']
if 'n_iter_' in ica_misc:
ica.n_iter_ = ica_misc['n_iter_']
if 'fit_params' in ica_misc:
ica.fit_params = ica_misc['fit_params']
logger.info('Ready.')
return ica
_ica_node = namedtuple('Node', 'name target score_func criterion')
def _detect_artifacts(ica, raw, start_find, stop_find, ecg_ch, ecg_score_func,
ecg_criterion, eog_ch, eog_score_func, eog_criterion,
skew_criterion, kurt_criterion, var_criterion,
add_nodes):
"""Aux Function."""
from scipy import stats
nodes = []
if ecg_ch is not None:
nodes += [_ica_node('ECG', ecg_ch, ecg_score_func, ecg_criterion)]
if eog_ch not in [None, []]:
if not isinstance(eog_ch, list):
eog_ch = [eog_ch]
for idx, ch in enumerate(eog_ch):
nodes += [_ica_node('EOG %02d' % idx, ch, eog_score_func,
eog_criterion)]
if skew_criterion is not None:
nodes += [_ica_node('skewness', None, stats.skew, skew_criterion)]
if kurt_criterion is not None:
nodes += [_ica_node('kurtosis', None, stats.kurtosis, kurt_criterion)]
if var_criterion is not None:
nodes += [_ica_node('variance', None, np.var, var_criterion)]
if add_nodes is not None:
nodes.extend(add_nodes)
for node in nodes:
scores = ica.score_sources(raw, start=start_find, stop=stop_find,
target=node.target,
score_func=node.score_func)
if isinstance(node.criterion, float):
found = list(np.where(np.abs(scores) > node.criterion)[0])
else:
# Sort in descending order; use (-abs()), rather than [::-1] to
# keep any NaN values in the end (and also keep the order of same
# values):
found = list(np.atleast_1d((-np.abs(scores)).argsort()
[node.criterion]))
case = (len(found), _pl(found), node.name)
logger.info(' found %s artifact%s by %s' % case)
ica.exclude = list(ica.exclude) + found
logger.info('Artifact indices found:\n ' + str(ica.exclude).strip('[]'))
if len(set(ica.exclude)) != len(ica.exclude):
logger.info(' Removing duplicate indices...')
ica.exclude = list(set(ica.exclude))
logger.info('Ready.')
@verbose
def _band_pass_filter(inst, sources, target, l_freq, h_freq, verbose=None):
"""Optionally band-pass filter the data."""
if l_freq is not None and h_freq is not None:
logger.info('... filtering ICA sources')
# use FIR here, steeper is better
kw = dict(phase='zero-double', filter_length='10s', fir_window='hann',
l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,
fir_design='firwin2')
sources = filter_data(sources, inst.info['sfreq'], l_freq, h_freq,
**kw)
logger.info('... filtering target')
target = filter_data(target, inst.info['sfreq'], l_freq, h_freq, **kw)
elif l_freq is not None or h_freq is not None:
raise ValueError('Must specify both pass bands')
return sources, target
# #############################################################################
# CORRMAP
def _find_max_corrs(all_maps, target, threshold):
"""Compute correlations between template and target components."""
all_corrs = [compute_corr(target, subj.T) for subj in all_maps]
abs_corrs = [np.abs(a) for a in all_corrs]
corr_polarities = [np.sign(a) for a in all_corrs]
if threshold <= 1:
max_corrs = [list(np.nonzero(s_corr > threshold)[0])
for s_corr in abs_corrs]
else:
max_corrs = [list(_find_outliers(s_corr, threshold=threshold))
for s_corr in abs_corrs]
am = [l_[i] for l_, i_s in zip(abs_corrs, max_corrs)
for i in i_s]
median_corr_with_target = np.median(am) if len(am) > 0 else 0
polarities = [l_[i] for l_, i_s in zip(corr_polarities, max_corrs)
for i in i_s]
maxmaps = [l_[i] for l_, i_s in zip(all_maps, max_corrs)
for i in i_s]
if len(maxmaps) == 0:
return [], 0, 0, []
newtarget = np.zeros(maxmaps[0].size)
std_of_maps = np.std(np.asarray(maxmaps))
mean_of_maps = np.std(np.asarray(maxmaps))
for maxmap, polarity in zip(maxmaps, polarities):
newtarget += (maxmap / std_of_maps - mean_of_maps) * polarity
newtarget /= len(maxmaps)
newtarget *= std_of_maps
sim_i_o = np.abs(np.corrcoef(target, newtarget)[1, 0])
return newtarget, median_corr_with_target, sim_i_o, max_corrs
@verbose
def corrmap(icas, template, threshold="auto", label=None, ch_type="eeg",
plot=True, show=True, outlines='head',
sensors=True, contours=6, cmap=None, sphere=None, verbose=None):
"""Find similar Independent Components across subjects by map similarity.
Corrmap (Viola et al. 2009 Clin Neurophysiol) identifies the best group
match to a supplied template. Typically, feed it a list of fitted ICAs and
a template IC, for example, the blink for the first subject, to identify
specific ICs across subjects.
The specific procedure consists of two iterations. In a first step, the
maps best correlating with the template are identified. In the next step,
the analysis is repeated with the mean of the maps identified in the first
stage.
Run with ``plot`` and ``show`` set to ``True`` and ``label=False`` to find
good parameters. Then, run with labelling enabled to apply the
labelling in the IC objects. (Running with both ``plot`` and ``labels``
off does nothing.)
Outputs a list of fitted ICAs with the indices of the marked ICs in a
specified field.
The original Corrmap website: www.debener.de/corrmap/corrmapplugin1.html
Parameters
----------
icas : list of mne.preprocessing.ICA
A list of fitted ICA objects.
template : tuple | np.ndarray, shape (n_components,)
Either a tuple with two elements (int, int) representing the list
indices of the set from which the template should be chosen, and the
template. E.g., if template=(1, 0), the first IC of the 2nd ICA object
is used.
Or a numpy array whose size corresponds to each IC map from the
supplied maps, in which case this map is chosen as the template.
threshold : "auto" | list of float | float
Correlation threshold for identifying ICs
If "auto", search for the best map by trying all correlations between
0.6 and 0.95. In the original proposal, lower values are considered,
but this is not yet implemented.
If list of floats, search for the best map in the specified range of
correlation strengths. As correlation values, must be between 0 and 1
If float > 0, select ICs correlating better than this.
If float > 1, use z-scoring to identify ICs within subjects (not in
original Corrmap)
Defaults to "auto".
label : None | str
If not None, categorised ICs are stored in a dictionary ``labels_``
under the given name. Preexisting entries will be appended to
(excluding repeats), not overwritten. If None, a dry run is performed
and the supplied ICs are not changed.
ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
The channel type to plot. Defaults to 'eeg'.
plot : bool
Should constructed template and selected maps be plotted? Defaults
to True.
show : bool
Show figures if True.
%(topomap_outlines)s
sensors : bool | str
Add markers for sensor locations to the plot. Accepts matplotlib plot
format string (e.g., 'r+' for red plusses). If True, a circle will be
used (via .add_artist). Defaults to True.
contours : int | array of float
The number of contour lines to draw. If 0, no contours will be drawn.
When an integer, matplotlib ticker locator is used to find suitable
values for the contour thresholds (may sometimes be inaccurate, use
array for accuracy). If an array, the values represent the levels for
the contours. Defaults to 6.
cmap : None | matplotlib colormap
Colormap for the plot. If ``None``, defaults to 'Reds_r' for norm data,
otherwise to 'RdBu_r'.
%(topomap_sphere_auto)s
%(verbose)s
Returns
-------
template_fig : Figure
Figure showing the template.
labelled_ics : Figure
Figure showing the labelled ICs in all ICA decompositions.
"""
if not isinstance(plot, bool):
raise ValueError("`plot` must be of type `bool`")
same_chans = _check_all_same_channel_names(icas)
if same_chans is False:
raise ValueError("Not all ICA instances have the same channel names. "
"Corrmap requires all instances to have the same "
"montage. Consider interpolating bad channels before "
"running ICA.")
threshold_extra = ''
if threshold == 'auto':
threshold = np.arange(60, 95, dtype=np.float64) / 100.
threshold_extra = ' ("auto")'
all_maps = [ica.get_components().T for ica in icas]
# check if template is an index to one IC in one ICA object, or an array
if len(template) == 2:
target = all_maps[template[0]][template[1]]
is_subject = True
elif template.ndim == 1 and len(template) == all_maps[0].shape[1]:
target = template
is_subject = False
else:
raise ValueError("`template` must be a length-2 tuple or an array the "
"size of the ICA maps.")
template_fig, labelled_ics = None, None
if plot is True:
if is_subject: # plotting from an ICA object
ttl = 'Template from subj. {}'.format(str(template[0]))
template_fig = icas[template[0]].plot_components(
picks=template[1], ch_type=ch_type, title=ttl,
outlines=outlines, cmap=cmap, contours=contours,
show=show, topomap_args=dict(sphere=sphere))
else: # plotting an array
template_fig = _plot_corrmap([template], [0], [0], ch_type,
icas[0].copy(), "Template",
outlines=outlines, cmap=cmap,
contours=contours,
show=show, template=True,
sphere=sphere)
template_fig.subplots_adjust(top=0.8)
template_fig.canvas.draw()
# first run: use user-selected map
threshold = np.atleast_1d(np.array(threshold, float)).ravel()
threshold_err = ('No component detected using when z-scoring '
'threshold%s %s, consider using a more lenient '
'threshold' % (threshold_extra, threshold))
if len(all_maps) == 0:
raise RuntimeError(threshold_err)
paths = [_find_max_corrs(all_maps, target, t) for t in threshold]
# find iteration with highest avg correlation with target
new_target, _, _, _ = paths[np.argmax([path[2] for path in paths])]
# second run: use output from first run
if len(all_maps) == 0 or len(new_target) == 0:
raise RuntimeError(threshold_err)
paths = [_find_max_corrs(all_maps, new_target, t) for t in threshold]
del new_target
# find iteration with highest avg correlation with target
_, median_corr, _, max_corrs = paths[
np.argmax([path[1] for path in paths])]
allmaps, indices, subjs, nones = [list() for _ in range(4)]
logger.info('Median correlation with constructed map: %0.3f' % median_corr)
del median_corr
if plot is True:
logger.info('Displaying selected ICs per subject.')
for ii, (ica, max_corr) in enumerate(zip(icas, max_corrs)):
if len(max_corr) > 0:
if isinstance(max_corr[0], np.ndarray):
max_corr = max_corr[0]
if label is not None:
ica.labels_[label] = list(set(list(max_corr) +
ica.labels_.get(label, list())))
if plot is True:
allmaps.extend(ica.get_components()[:, max_corr].T)
subjs.extend([ii] * len(max_corr))
indices.extend(max_corr)
else:
if (label is not None) and (label not in ica.labels_):
ica.labels_[label] = list()
nones.append(ii)
if len(nones) == 0:
logger.info('At least 1 IC detected for each subject.')
else:
logger.info('No maps selected for subject%s %s, '
'consider a more liberal threshold.'
% (_pl(nones), nones))
if plot is True:
labelled_ics = _plot_corrmap(allmaps, subjs, indices, ch_type, ica,
label, outlines=outlines, cmap=cmap,
contours=contours,
show=show, sphere=sphere)
return template_fig, labelled_ics
else:
return None
@verbose
def read_ica_eeglab(fname, *, verbose=None):
"""Load ICA information saved in an EEGLAB .set file.
Parameters
----------
fname : str
Complete path to a .set EEGLAB file that contains an ICA object.
%(verbose)s
Returns
-------
ica : instance of ICA
An ICA object based on the information contained in the input file.
"""
from scipy import linalg
eeg = _check_load_mat(fname, None)
info, eeg_montage, _ = _get_info(eeg)
info.set_montage(eeg_montage)
pick_info(info, np.round(eeg['icachansind']).astype(int) - 1, copy=False)
rank = eeg.icasphere.shape[0]
n_components = eeg.icaweights.shape[0]
ica = ICA(method='imported_eeglab', n_components=n_components)
ica.current_fit = "eeglab"
ica.ch_names = info["ch_names"]
ica.n_pca_components = None
ica.n_components_ = n_components
n_ch = len(ica.ch_names)
assert len(eeg.icachansind) == n_ch
ica.pre_whitener_ = np.ones((n_ch, 1))
ica.pca_mean_ = np.zeros(n_ch)
assert eeg.icasphere.shape[1] == n_ch
assert eeg.icaweights.shape == (n_components, rank)
# When PCA reduction is used in EEGLAB, runica returns
# weights= weights*sphere*eigenvectors(:,1:ncomps)';
# sphere = eye(urchans). When PCA reduction is not used, we have:
#
# eeg.icawinv == pinv(eeg.icaweights @ eeg.icasphere)
#
# So in either case, we can use SVD to get our square whitened
# weights matrix (u * s) and our PCA vectors (v) back:
use = eeg.icaweights @ eeg.icasphere
use_check = linalg.pinv(eeg.icawinv)
if not np.allclose(use, use_check, rtol=1e-6):
warn('Mismatch between icawinv and icaweights @ icasphere from EEGLAB '
'possibly due to ICA component removal, assuming icawinv is '
'correct')
use = use_check
u, s, v = _safe_svd(use, full_matrices=False)
ica.unmixing_matrix_ = u * s
ica.pca_components_ = v
ica.pca_explained_variance_ = s * s
ica.info = info
ica._update_mixing_matrix()
ica._update_ica_names()
return ica
|
import hashlib
import json
import logging
import os
from datetime import datetime
from pathlib import Path
import pandas as pd
from airflow import DAG
from airflow.models import Variable
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator, PythonOperator
from ckan_operators.datastore_operator import (
BackupDatastoreResourceOperator, DeleteDatastoreResourceRecordsOperator,
InsertDatastoreResourceRecordsOperator,
RestoreDatastoreResourceBackupOperator)
from ckan_operators.package_operator import GetPackageOperator
from ckan_operators.resource_operator import (GetOrCreateResourceOperator,
ResourceAndFileOperator)
from dateutil import parser
from utils import agol_utils, airflow_utils
from utils_operators.directory_operator import CreateLocalDirectoryOperator
from utils_operators.file_operators import DownloadFileOperator
from utils_operators.slack_operators import task_success_slack_alert, task_failure_slack_alert, GenericSlackOperator
SRC_URL = "http://opendata.toronto.ca/childrens.services/licensed-child-care-centres/child-care.csv" # noqa: E501
PACKAGE_NAME = "licensed-child-care-centres"
RESOURCE_NAME = "Child care centres"
EXPECTED_COLUMNS = [
"LOC_ID",
"LOC_NAME",
"AUSPICE",
"ADDRESS",
"PCODE",
"ward",
"PHONE",
"bldg_type",
"BLDGNAME",
"IGSPACE",
"TGSPACE",
"PGSPACE",
"KGSPACE",
"SGSPACE",
"TOTSPACE",
"subsidy",
"run_date",
"latitude",
"longitude",
]
def send_failure_msg():
airflow_utils.message_slack(
name=PACKAGE_NAME,
message_type="error",
msg="Job not finished",
active_env=Variable.get("active_env"),
prod_webhook=Variable.get("active_env") == "prod",
)
with DAG(
PACKAGE_NAME,
default_args=airflow_utils.get_default_args(
{
"on_failure_callback": task_failure_slack_alert,
"start_date": datetime(2020, 11, 24, 13, 35, 0),
"retries": 0,
# "retry_delay": timedelta(minutes=3),
}
),
description="Take data from opendata.toronto.ca (CSV) and put into datastore",
schedule_interval="0 17 * * *",
catchup=False,
tags=["dataset"],
) as dag:
def is_resource_new(**kwargs):
package = kwargs["ti"].xcom_pull(task_ids="get_package")
logging.info(f"resources found: {[r["name"] for r in package["resources"]]}")
is_new = RESOURCE_NAME not in [r["name"] for r in package["resources"]]
if is_new:
return "resource_is_new"
return "resource_is_not_new"
def is_data_new(**kwargs):
ti = kwargs["ti"]
fields = ti.xcom_pull(task_ids="get_fields")
if fields is not None:
return "data_is_new"
backups_dir = Path(ti.xcom_pull(task_ids="backups_dir"))
backup_data = ti.xcom_pull(task_ids="backup_data")
df = pd.read_parquet(backup_data["data"])
if df.shape[0] == 0:
return "data_is_new"
checksum = hashlib.md5()
checksum.update(df.sort_values(by="LOC_ID").to_csv(index=False).encode("utf-8"))
checksum = checksum.hexdigest()
for f in os.listdir(backups_dir):
if not os.path.isfile(backups_dir / f):
continue
logging.info(f"File in backups: {f}")
if os.path.isfile(backups_dir / f) and checksum in f:
logging.info(f"Data has already been loaded, ID: {checksum}")
return "data_is_not_new"
logging.info(f"Data has not been loaded, new ID: {checksum}")
return "data_is_new"
def transform_data(**kwargs):
ti = kwargs.pop("ti")
tmp_dir = Path(ti.xcom_pull(task_ids="tmp_dir"))
data_fp = Path(ti.xcom_pull(task_ids="get_data")["path"])
data = pd.read_csv(data_fp)
data["geometry"] = data.apply(
lambda x: json.dumps(
{"type": "Point", "coordinates": [x["longitude"], x["latitude"]]}
)
if x["longitude"] and x["latitude"]
else "",
axis=1,
)
data = agol_utils.remove_geo_columns(data)
filename = "new_data_transformed"
filepath = tmp_dir / f"{filename}.parquet"
data.to_parquet(filepath, engine="fastparquet", compression=None)
return filepath
def validate_expected_columns(**kwargs):
ti = kwargs["ti"]
data_fp = Path(ti.xcom_pull(task_ids="get_data")["path"])
df = pd.read_csv(data_fp)
for col in df.columns.values:
assert col in EXPECTED_COLUMNS, f"{col} not in list of expected columns"
for col in EXPECTED_COLUMNS:
assert col in df.columns.values, f"Expected column {col} not in data file"
def is_file_new(**kwargs):
ti = kwargs["ti"]
data_file_info = ti.xcom_pull(task_ids="get_data")
resource = ti.xcom_pull(task_ids="get_or_create_resource")
logging.info(f"resource: {resource} | data_file_info: {data_file_info}")
last_modified_string = data_file_info["last_modified"]
file_last_modified = parser.parse(last_modified_string)
last_modified_attr = resource["last_modified"]
if not last_modified_attr:
last_modified_attr = resource["created"]
resource_last_modified = parser.parse(last_modified_attr + " UTC")
difference_in_seconds = (
file_last_modified.timestamp() - resource_last_modified.timestamp()
)
logging.info(
f"{difference_in_seconds}secs between file and resource last modified times"
)
if difference_in_seconds == 0:
return "file_is_not_new"
return "file_is_new"
def build_data_dict(**kwargs):
data_fp = Path(kwargs["ti"].xcom_pull(task_ids="transform_data"))
data = pd.read_parquet(Path(data_fp))
fields = []
for field, dtype in data.dtypes.iteritems():
ckan_type_map = {"int64": "int", "object": "text", "float64": "float"}
fields.append({"type": ckan_type_map[dtype.name], "id": field})
return fields
def build_message(**kwargs):
ti = kwargs["id"]
records_inserted = ti.xcom_pull("records_inserted")
if records_inserted is None:
resource = ti.xcom_pull("update_resource_last_modified")
last_modified = parser.parse(resource["last_modified"]).strftime(
"%Y-%m-%d %H:%M"
)
return (
f"New file, no new data. New last modified timestamp: {last_modified}"
)
new_data_fp = Path(ti.xcom_pull("transform_data"))
new_data = pd.read_parquet(new_data_fp)
return f"Refreshed: {new_data.shape[0]} records"
def get_fields(**kwargs):
ti = kwargs["ti"]
backup_data = ti.xcom_pull(task_ids="backup_data")
if backup_data is not None:
with open(Path(backup_data["fields_file_path"]), "r") as f:
fields = json.load(f)
else:
fields = ti.xcom_pull(task_ids="create_data_dictionary")
assert fields is not None, "No fields"
return fields
def were_records_loaded(**kwargs):
inserted_records_count = kwargs["ti"].xcom_pull(task_ids="insert_records")
if inserted_records_count is not None and inserted_records_count > 0:
return "new_records_notification"
return "no_new_data_notification"
def send_new_records_notification(**kwargs):
count = kwargs["ti"].xcom_pull("insert_records")
airflow_utils.message_slack(
PACKAGE_NAME,
f"Refreshed {count} records",
"success",
Variable.get("active_env") == "prod",
Variable.get("active_env"),
)
ckan_creds = Variable.get("ckan_credentials_secret", deserialize_json=True)
active_env = Variable.get("active_env")
ckan_address = ckan_creds[active_env]["address"]
ckan_apikey = ckan_creds[active_env]["apikey"]
tmp_dir = CreateLocalDirectoryOperator(
task_id="tmp_dir", path=Path(Variable.get("tmp_dir")) / PACKAGE_NAME,
)
backups_dir = CreateLocalDirectoryOperator(
task_id="backups_dir", path=Path(Variable.get("backups_dir")) / PACKAGE_NAME,
)
src = DownloadFileOperator(
task_id="get_data",
file_url=SRC_URL,
dir =Path(Variable.get("tmp_dir")) / PACKAGE_NAME,
filename="src_data.csv",
)
package = GetPackageOperator(
task_id="get_package",
address=ckan_address,
apikey=ckan_apikey,
package_name_or_id=PACKAGE_NAME,
)
new_resource_branch = BranchPythonOperator(
task_id="new_resource_branch", python_callable=is_resource_new,
)
transformed_data = PythonOperator(
task_id="transform_data", python_callable=transform_data,
)
create_data_dictionary = PythonOperator(
task_id="create_data_dictionary", python_callable=build_data_dict,
)
get_or_create_resource = GetOrCreateResourceOperator(
task_id="get_or_create_resource",
address=ckan_address,
apikey=ckan_apikey,
package_name_or_id=PACKAGE_NAME,
resource_name=RESOURCE_NAME,
resource_attributes=dict(
format="geojson",
is_preview=True,
url_type="datastore",
extract_job=f"Airflow: {PACKAGE_NAME}",
),
)
backup_data = BackupDatastoreResourceOperator(
task_id="backup_data",
address=ckan_address,
apikey=ckan_apikey,
resource_task_id="get_or_create_resource",
dir_task_id="backups_dir",
sort_columns=["LOC_ID"],
)
fields = PythonOperator(
task_id="get_fields", python_callable=get_fields, trigger_rule="none_failed"
)
file_new_branch = BranchPythonOperator(
task_id="file_new_branch", python_callable=is_file_new,
)
new_data_branch = BranchPythonOperator(
task_id="is_data_new", python_callable=is_data_new,
)
delete_tmp_data = PythonOperator(
task_id="delete_tmp_data",
python_callable=airflow_utils.delete_tmp_data_dir,
op_kwargs={"dag_id": PACKAGE_NAME, "recursively": True},
trigger_rule="one_success",
)
sync_timestamp = ResourceAndFileOperator(
task_id="sync_timestamp",
address=ckan_address,
apikey=ckan_apikey,
download_file_task_id="get_data",
resource_task_id="get_or_create_resource",
upload_to_ckan=False,
sync_timestamp=True,
trigger_rule="one_success",
)
send_nothing_notification = PythonOperator(
task_id="send_nothing_notification",
python_callable=airflow_utils.message_slack,
op_args=(
PACKAGE_NAME,
"No new data file",
"success",
active_env == "prod",
active_env,
),
)
delete_records = DeleteDatastoreResourceRecordsOperator(
task_id="delete_records",
address=ckan_address,
apikey=ckan_apikey,
backup_task_id="backup_data",
)
insert_records = InsertDatastoreResourceRecordsOperator(
task_id="insert_records",
address=ckan_address,
apikey=ckan_apikey,
parquet_filepath_task_id="transform_data",
resource_task_id="get_or_create_resource",
)
new_records_notification = PythonOperator(
task_id="new_records_notification",
python_callable=send_new_records_notification,
)
no_new_data_notification = PythonOperator(
task_id="no_new_data_notification",
python_callable=airflow_utils.message_slack,
op_args=(
PACKAGE_NAME,
"Updated resource last_modified time only: new file but no new data",
"success",
active_env == "prod",
active_env,
),
)
records_loaded_branch = BranchPythonOperator(
task_id="were_records_loaded", python_callable=were_records_loaded,
)
restore_backup = RestoreDatastoreResourceBackupOperator(
task_id="restore_backup",
address=ckan_address,
apikey=ckan_apikey,
backup_task_id="backup_data",
trigger_rule="all_failed",
)
validated_columns = PythonOperator(
task_id="validate_expected_columns", python_callable=validate_expected_columns,
)
backups_dir >> backup_data
tmp_dir >> src >> validated_columns >> transformed_data >> file_new_branch
package >> get_or_create_resource >> [file_new_branch, new_resource_branch]
new_resource_branch >> DummyOperator(
task_id="resource_is_new"
) >> create_data_dictionary >> fields
new_resource_branch >> DummyOperator(
task_id="resource_is_not_new"
) >> backup_data >> fields
file_new_branch >> DummyOperator(task_id="file_is_new") >> new_data_branch
file_new_branch >> DummyOperator(
task_id="file_is_not_new"
) >> send_nothing_notification
fields >> new_data_branch
new_data_branch >> DummyOperator(
task_id="data_is_new"
) >> delete_records >> insert_records >> sync_timestamp
new_data_branch >> DummyOperator(task_id="data_is_not_new") >> sync_timestamp
sync_timestamp >> records_loaded_branch
records_loaded_branch >> new_records_notification
records_loaded_branch >> no_new_data_notification
[
no_new_data_notification,
new_records_notification,
send_nothing_notification,
] >> delete_tmp_data
[delete_records, insert_records] >> restore_backup
| import hashlib
import json
import logging
import os
from datetime import datetime
from pathlib import Path
import pandas as pd
from airflow import DAG
from airflow.models import Variable
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator, PythonOperator
from ckan_operators.datastore_operator import (
BackupDatastoreResourceOperator, DeleteDatastoreResourceRecordsOperator,
InsertDatastoreResourceRecordsOperator,
RestoreDatastoreResourceBackupOperator)
from ckan_operators.package_operator import GetPackageOperator
from ckan_operators.resource_operator import (GetOrCreateResourceOperator,
ResourceAndFileOperator)
from dateutil import parser
from utils import agol_utils, airflow_utils
from utils_operators.directory_operator import CreateLocalDirectoryOperator
from utils_operators.file_operators import DownloadFileOperator
from utils_operators.slack_operators import task_success_slack_alert, task_failure_slack_alert, GenericSlackOperator
SRC_URL = "http://opendata.toronto.ca/childrens.services/licensed-child-care-centres/child-care.csv" # noqa: E501
PACKAGE_NAME = "licensed-child-care-centres"
RESOURCE_NAME = "Child care centres"
EXPECTED_COLUMNS = [
"LOC_ID",
"LOC_NAME",
"AUSPICE",
"ADDRESS",
"PCODE",
"ward",
"PHONE",
"bldg_type",
"BLDGNAME",
"IGSPACE",
"TGSPACE",
"PGSPACE",
"KGSPACE",
"SGSPACE",
"TOTSPACE",
"subsidy",
"run_date",
"latitude",
"longitude",
]
def send_failure_msg():
airflow_utils.message_slack(
name=PACKAGE_NAME,
message_type="error",
msg="Job not finished",
active_env=Variable.get("active_env"),
prod_webhook=Variable.get("active_env") == "prod",
)
with DAG(
PACKAGE_NAME,
default_args=airflow_utils.get_default_args(
{
"on_failure_callback": task_failure_slack_alert,
"start_date": datetime(2020, 11, 24, 13, 35, 0),
"retries": 0,
# "retry_delay": timedelta(minutes=3),
}
),
description="Take data from opendata.toronto.ca (CSV) and put into datastore",
schedule_interval="0 17 * * *",
catchup=False,
tags=["dataset"],
) as dag:
def is_resource_new(**kwargs):
package = kwargs["ti"].xcom_pull(task_ids="get_package")
logging.info(f"resources found: {[r['name'] for r in package['resources']]}")
is_new = RESOURCE_NAME not in [r["name"] for r in package["resources"]]
if is_new:
return "resource_is_new"
return "resource_is_not_new"
def is_data_new(**kwargs):
ti = kwargs["ti"]
fields = ti.xcom_pull(task_ids="get_fields")
if fields is not None:
return "data_is_new"
backups_dir = Path(ti.xcom_pull(task_ids="backups_dir"))
backup_data = ti.xcom_pull(task_ids="backup_data")
df = pd.read_parquet(backup_data["data"])
if df.shape[0] == 0:
return "data_is_new"
checksum = hashlib.md5()
checksum.update(df.sort_values(by="LOC_ID").to_csv(index=False).encode("utf-8"))
checksum = checksum.hexdigest()
for f in os.listdir(backups_dir):
if not os.path.isfile(backups_dir / f):
continue
logging.info(f"File in backups: {f}")
if os.path.isfile(backups_dir / f) and checksum in f:
logging.info(f"Data has already been loaded, ID: {checksum}")
return "data_is_not_new"
logging.info(f"Data has not been loaded, new ID: {checksum}")
return "data_is_new"
def transform_data(**kwargs):
ti = kwargs.pop("ti")
tmp_dir = Path(ti.xcom_pull(task_ids="tmp_dir"))
data_fp = Path(ti.xcom_pull(task_ids="get_data")["path"])
data = pd.read_csv(data_fp)
data["geometry"] = data.apply(
lambda x: json.dumps(
{"type": "Point", "coordinates": [x["longitude"], x["latitude"]]}
)
if x["longitude"] and x["latitude"]
else "",
axis=1,
)
data = agol_utils.remove_geo_columns(data)
filename = "new_data_transformed"
filepath = tmp_dir / f"{filename}.parquet"
data.to_parquet(filepath, engine="fastparquet", compression=None)
return filepath
def validate_expected_columns(**kwargs):
ti = kwargs["ti"]
data_fp = Path(ti.xcom_pull(task_ids="get_data")["path"])
df = pd.read_csv(data_fp)
for col in df.columns.values:
assert col in EXPECTED_COLUMNS, f"{col} not in list of expected columns"
for col in EXPECTED_COLUMNS:
assert col in df.columns.values, f"Expected column {col} not in data file"
def is_file_new(**kwargs):
ti = kwargs["ti"]
data_file_info = ti.xcom_pull(task_ids="get_data")
resource = ti.xcom_pull(task_ids="get_or_create_resource")
logging.info(f"resource: {resource} | data_file_info: {data_file_info}")
last_modified_string = data_file_info["last_modified"]
file_last_modified = parser.parse(last_modified_string)
last_modified_attr = resource["last_modified"]
if not last_modified_attr:
last_modified_attr = resource["created"]
resource_last_modified = parser.parse(last_modified_attr + " UTC")
difference_in_seconds = (
file_last_modified.timestamp() - resource_last_modified.timestamp()
)
logging.info(
f"{difference_in_seconds}secs between file and resource last modified times"
)
if difference_in_seconds == 0:
return "file_is_not_new"
return "file_is_new"
def build_data_dict(**kwargs):
data_fp = Path(kwargs["ti"].xcom_pull(task_ids="transform_data"))
data = pd.read_parquet(Path(data_fp))
fields = []
for field, dtype in data.dtypes.iteritems():
ckan_type_map = {"int64": "int", "object": "text", "float64": "float"}
fields.append({"type": ckan_type_map[dtype.name], "id": field})
return fields
def build_message(**kwargs):
ti = kwargs["id"]
records_inserted = ti.xcom_pull("records_inserted")
if records_inserted is None:
resource = ti.xcom_pull("update_resource_last_modified")
last_modified = parser.parse(resource["last_modified"]).strftime(
"%Y-%m-%d %H:%M"
)
return (
f"New file, no new data. New last modified timestamp: {last_modified}"
)
new_data_fp = Path(ti.xcom_pull("transform_data"))
new_data = pd.read_parquet(new_data_fp)
return f"Refreshed: {new_data.shape[0]} records"
def get_fields(**kwargs):
ti = kwargs["ti"]
backup_data = ti.xcom_pull(task_ids="backup_data")
if backup_data is not None:
with open(Path(backup_data["fields_file_path"]), "r") as f:
fields = json.load(f)
else:
fields = ti.xcom_pull(task_ids="create_data_dictionary")
assert fields is not None, "No fields"
return fields
def were_records_loaded(**kwargs):
inserted_records_count = kwargs["ti"].xcom_pull(task_ids="insert_records")
if inserted_records_count is not None and inserted_records_count > 0:
return "new_records_notification"
return "no_new_data_notification"
def send_new_records_notification(**kwargs):
count = kwargs["ti"].xcom_pull("insert_records")
airflow_utils.message_slack(
PACKAGE_NAME,
f"Refreshed {count} records",
"success",
Variable.get("active_env") == "prod",
Variable.get("active_env"),
)
ckan_creds = Variable.get("ckan_credentials_secret", deserialize_json=True)
active_env = Variable.get("active_env")
ckan_address = ckan_creds[active_env]["address"]
ckan_apikey = ckan_creds[active_env]["apikey"]
tmp_dir = CreateLocalDirectoryOperator(
task_id="tmp_dir", path=Path(Variable.get("tmp_dir")) / PACKAGE_NAME,
)
backups_dir = CreateLocalDirectoryOperator(
task_id="backups_dir", path=Path(Variable.get("backups_dir")) / PACKAGE_NAME,
)
src = DownloadFileOperator(
task_id="get_data",
file_url=SRC_URL,
dir =Path(Variable.get("tmp_dir")) / PACKAGE_NAME,
filename="src_data.csv",
)
package = GetPackageOperator(
task_id="get_package",
address=ckan_address,
apikey=ckan_apikey,
package_name_or_id=PACKAGE_NAME,
)
new_resource_branch = BranchPythonOperator(
task_id="new_resource_branch", python_callable=is_resource_new,
)
transformed_data = PythonOperator(
task_id="transform_data", python_callable=transform_data,
)
create_data_dictionary = PythonOperator(
task_id="create_data_dictionary", python_callable=build_data_dict,
)
get_or_create_resource = GetOrCreateResourceOperator(
task_id="get_or_create_resource",
address=ckan_address,
apikey=ckan_apikey,
package_name_or_id=PACKAGE_NAME,
resource_name=RESOURCE_NAME,
resource_attributes=dict(
format="geojson",
is_preview=True,
url_type="datastore",
extract_job=f"Airflow: {PACKAGE_NAME}",
),
)
backup_data = BackupDatastoreResourceOperator(
task_id="backup_data",
address=ckan_address,
apikey=ckan_apikey,
resource_task_id="get_or_create_resource",
dir_task_id="backups_dir",
sort_columns=["LOC_ID"],
)
fields = PythonOperator(
task_id="get_fields", python_callable=get_fields, trigger_rule="none_failed"
)
file_new_branch = BranchPythonOperator(
task_id="file_new_branch", python_callable=is_file_new,
)
new_data_branch = BranchPythonOperator(
task_id="is_data_new", python_callable=is_data_new,
)
delete_tmp_data = PythonOperator(
task_id="delete_tmp_data",
python_callable=airflow_utils.delete_tmp_data_dir,
op_kwargs={"dag_id": PACKAGE_NAME, "recursively": True},
trigger_rule="one_success",
)
sync_timestamp = ResourceAndFileOperator(
task_id="sync_timestamp",
address=ckan_address,
apikey=ckan_apikey,
download_file_task_id="get_data",
resource_task_id="get_or_create_resource",
upload_to_ckan=False,
sync_timestamp=True,
trigger_rule="one_success",
)
send_nothing_notification = PythonOperator(
task_id="send_nothing_notification",
python_callable=airflow_utils.message_slack,
op_args=(
PACKAGE_NAME,
"No new data file",
"success",
active_env == "prod",
active_env,
),
)
delete_records = DeleteDatastoreResourceRecordsOperator(
task_id="delete_records",
address=ckan_address,
apikey=ckan_apikey,
backup_task_id="backup_data",
)
insert_records = InsertDatastoreResourceRecordsOperator(
task_id="insert_records",
address=ckan_address,
apikey=ckan_apikey,
parquet_filepath_task_id="transform_data",
resource_task_id="get_or_create_resource",
)
new_records_notification = PythonOperator(
task_id="new_records_notification",
python_callable=send_new_records_notification,
)
no_new_data_notification = PythonOperator(
task_id="no_new_data_notification",
python_callable=airflow_utils.message_slack,
op_args=(
PACKAGE_NAME,
"Updated resource last_modified time only: new file but no new data",
"success",
active_env == "prod",
active_env,
),
)
records_loaded_branch = BranchPythonOperator(
task_id="were_records_loaded", python_callable=were_records_loaded,
)
restore_backup = RestoreDatastoreResourceBackupOperator(
task_id="restore_backup",
address=ckan_address,
apikey=ckan_apikey,
backup_task_id="backup_data",
trigger_rule="all_failed",
)
validated_columns = PythonOperator(
task_id="validate_expected_columns", python_callable=validate_expected_columns,
)
backups_dir >> backup_data
tmp_dir >> src >> validated_columns >> transformed_data >> file_new_branch
package >> get_or_create_resource >> [file_new_branch, new_resource_branch]
new_resource_branch >> DummyOperator(
task_id="resource_is_new"
) >> create_data_dictionary >> fields
new_resource_branch >> DummyOperator(
task_id="resource_is_not_new"
) >> backup_data >> fields
file_new_branch >> DummyOperator(task_id="file_is_new") >> new_data_branch
file_new_branch >> DummyOperator(
task_id="file_is_not_new"
) >> send_nothing_notification
fields >> new_data_branch
new_data_branch >> DummyOperator(
task_id="data_is_new"
) >> delete_records >> insert_records >> sync_timestamp
new_data_branch >> DummyOperator(task_id="data_is_not_new") >> sync_timestamp
sync_timestamp >> records_loaded_branch
records_loaded_branch >> new_records_notification
records_loaded_branch >> no_new_data_notification
[
no_new_data_notification,
new_records_notification,
send_nothing_notification,
] >> delete_tmp_data
[delete_records, insert_records] >> restore_backup
|
#!/usr/bin/env python
# Copyright 2019 ARC Centre of Excellence for Climate Extremes
# author: Paola Petrelli <paola.petrelli@utas.edu.au>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
import pandas as pd
import pkg_resources
import json
from bs4 import BeautifulSoup
from datetime import date
def esdoc_urls(dataset_ids):
"""
:input: datasets_ids (list of str) dataset_ids returned by query
:return: esdoc_urls (list of dict), each dictionary contains the related esdoc urls for a dataset_id,
the keys are the urls and the values are extracts from the linked information
"""
esdoc_urls=[]
for did in dataset_ids:
urls={}
#attrs = did.split(".")
#urls['model_url'] = get_model_doc(attrs[2],attrs[3])
wdcc_url, urls['wdcc_url'] = get_wdcc(did)
urls['exp_url'] = ''
#exp_url = get_exp_doc()
esdoc_urls.append(urls)
return esdoc_urls
def get_wdcc(dataset_id):
'''Retrieve metadata documentation from WDCC site, this is less detailed than esdoc but often more readable
:input: dataset_id (str) the simulation dataset_id
:return: wdcc_url (str) the wdcc_url for the document
:return: r.json() (dict) the web response as json
'''
wdcc_root = 'https://cera-www.dkrz.de/WDCC/ui/cerasearch/'
settings = 'select?rows=1&wt=json'
project=dataset_id.split(".")[0]
if project == 'cmip5':
entry="*".join(dataset_id.split(".")[0:4])
wdcc_url = wdcc_root + f'solr/{settings}&q=entry_name_s:{entry}'
elif project == 'CMIP6':
entry=".".join(dataset_id.split(".")[0:5])
#wdcc_url = wdcc_root + f'cerarest/exportcmip6?input={entry}'
wdcc_url = wdcc_root + f'cerarest/cmip6?input={entry}'
else:
print('No wdcc documents available for this project')
return None, None
r = requests.get(wdcc_url)
return wdcc_url, r
def print_model(tables):
''' Print out esdoc CIM2 model document
:input: tables (str) html tables downloaded from web interface
'''
dfs = pd.read_html(str(tables[0]))
df = dfs[0]
for i in range(0, df.shape[0]):
print(df.iloc[i,0] +' > ' + df.iloc[i,1])
for table in tables[1:]:
dfs = pd.read_html(str(table))
df = dfs[0]
print(f'{df.iloc[0,0].replace('>','-')} > {df.iloc[2,1]}')
return
def print_doc(tables, dtype):
''' Print out esdoc document, all types except model
:input: tables (str?) html tables downloaded from web interface
:input: dtype (str) - the kind of document (i.e. experiment, mip)
'''
for table in tables:
dfs = pd.read_html(str(table))
df = dfs[0]
for i in range(0, df.shape[0]):
if df.iloc[i,0] != 'Keywords' and df.iloc[i,1] != '--':
print(df.iloc[i,0] +' > ' + df.iloc[i,1])
return
def get_doc(dtype, name, project='CMIP6'):
'''Retrieve esdoc document and then call function to print it to screen
:input: project (str) - ESGF project
:input: dtype (str) - the kind of document (i.e. experiment, mip)
:input: name (str) - the canonical name of the related document, usually model/experiment/mip name works
'''
stype = {'model': 'CIM.2.SCIENCE.MODEL', 'mip': 'cim.2.designing.Project',
'experiment': 'cim.2.designing.NumericalExperiment'}
service = ('https://api.es-doc.org/2/document/search-name?client=ESDOC-VIEWER-DEMO&encoding=html'+
f'&project={project}&name={name}&type={stype[dtype]}')
r = requests.get(service)
soup = BeautifulSoup(r.text,'lxml')
tables = soup.findAll("table")
if dtype == 'model':
print_model(tables)
else:
print_doc(tables, dtype)
return service
def errata(tracking_id):
'''Return errata uids connected to a tracking id
'''
service = 'https://errata.es-doc.org/1/resolve/pid?pids='
r = requests.get(service + tracking_id.split(":")[1])
try:
uids = r.json()['errata'][0][1][0][0]
if uids:
return [x for x in uids.split(';')]
else:
return None
except KeyError:
print(f'Issue with handle: {tracking_id}')
print(r.json()["errorMessage"])
return None
def retrieve_error(uid):
''' Accept error uid and return errata as json plus webpage to view error '''
view = 'https://errata.es-doc.org/static/view.html?uid='
service = 'https://errata.es-doc.org/1/issue/retrieve?uid='
r = requests.get(service + uid)
error = {view+uid: r.json()['issue']}
return error
def print_error(uid):
error = retrieve_error(uid)
for k in error.keys():
print(f'You can view the full report online:\n{k}')
print(f'Title: {error[k]['title']}')
print(f'Status: {error[k]['status']}')
print(f'Description: {error[k]['description']}')
def citation(dids):
'''Retrieve citations for a list of CMIP6 dataset ids'''
citations = []
url = 'https://cera-www.dkrz.de/WDCC/ui/cerasearch/cmip6?input='
#fexp = pkg_resources.resource_filename(__name__, 'data/CMIP6_exp_act.json')
#with open(fexp, 'r') as f:
# data = json.loads(f.read())
for did in dids:
# get facets from did to build correct url
did_bits = did.split(".")
version = did_bits[9]
newdid = ".".join(did_bits[0:5])
response = requests.get(url+newdid, headers={"User-Agent": "Requests"})
soup = BeautifulSoup(response.content, 'lxml')
el = soup.find('dt', text="Citation")
cite = el.next_sibling.text.replace(" BibTeX RIS","")
if version == 'none':
now = date.today()
citations.append(cite.replace("Version YYYYMMDD[1]",f'Accessed on {now}'))
else:
citations.append(cite.replace("YYYYMMDD[1].",f"{version}. "))
return citations
def write_cite(citations):
"""Write citations to file
"""
if len(citations) == 0:
print(f'Nothing to write to file')
return
out_file = "cmip_citations.txt"
try:
with open(out_file, 'w') as f:
f.write('\n'.join(citations))
print(f'Saving to {out_file}')
except IOError:
print("I/O error")
| #!/usr/bin/env python
# Copyright 2019 ARC Centre of Excellence for Climate Extremes
# author: Paola Petrelli <paola.petrelli@utas.edu.au>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
import pandas as pd
import pkg_resources
import json
from bs4 import BeautifulSoup
from datetime import date
def esdoc_urls(dataset_ids):
"""
:input: datasets_ids (list of str) dataset_ids returned by query
:return: esdoc_urls (list of dict), each dictionary contains the related esdoc urls for a dataset_id,
the keys are the urls and the values are extracts from the linked information
"""
esdoc_urls=[]
for did in dataset_ids:
urls={}
#attrs = did.split(".")
#urls['model_url'] = get_model_doc(attrs[2],attrs[3])
wdcc_url, urls['wdcc_url'] = get_wdcc(did)
urls['exp_url'] = ''
#exp_url = get_exp_doc()
esdoc_urls.append(urls)
return esdoc_urls
def get_wdcc(dataset_id):
'''Retrieve metadata documentation from WDCC site, this is less detailed than esdoc but often more readable
:input: dataset_id (str) the simulation dataset_id
:return: wdcc_url (str) the wdcc_url for the document
:return: r.json() (dict) the web response as json
'''
wdcc_root = 'https://cera-www.dkrz.de/WDCC/ui/cerasearch/'
settings = 'select?rows=1&wt=json'
project=dataset_id.split(".")[0]
if project == 'cmip5':
entry="*".join(dataset_id.split(".")[0:4])
wdcc_url = wdcc_root + f'solr/{settings}&q=entry_name_s:{entry}'
elif project == 'CMIP6':
entry=".".join(dataset_id.split(".")[0:5])
#wdcc_url = wdcc_root + f'cerarest/exportcmip6?input={entry}'
wdcc_url = wdcc_root + f'cerarest/cmip6?input={entry}'
else:
print('No wdcc documents available for this project')
return None, None
r = requests.get(wdcc_url)
return wdcc_url, r
def print_model(tables):
''' Print out esdoc CIM2 model document
:input: tables (str) html tables downloaded from web interface
'''
dfs = pd.read_html(str(tables[0]))
df = dfs[0]
for i in range(0, df.shape[0]):
print(df.iloc[i,0] +' > ' + df.iloc[i,1])
for table in tables[1:]:
dfs = pd.read_html(str(table))
df = dfs[0]
print(f'{df.iloc[0,0].replace(">","-")} > {df.iloc[2,1]}')
return
def print_doc(tables, dtype):
''' Print out esdoc document, all types except model
:input: tables (str?) html tables downloaded from web interface
:input: dtype (str) - the kind of document (i.e. experiment, mip)
'''
for table in tables:
dfs = pd.read_html(str(table))
df = dfs[0]
for i in range(0, df.shape[0]):
if df.iloc[i,0] != 'Keywords' and df.iloc[i,1] != '--':
print(df.iloc[i,0] +' > ' + df.iloc[i,1])
return
def get_doc(dtype, name, project='CMIP6'):
'''Retrieve esdoc document and then call function to print it to screen
:input: project (str) - ESGF project
:input: dtype (str) - the kind of document (i.e. experiment, mip)
:input: name (str) - the canonical name of the related document, usually model/experiment/mip name works
'''
stype = {'model': 'CIM.2.SCIENCE.MODEL', 'mip': 'cim.2.designing.Project',
'experiment': 'cim.2.designing.NumericalExperiment'}
service = ('https://api.es-doc.org/2/document/search-name?client=ESDOC-VIEWER-DEMO&encoding=html'+
f'&project={project}&name={name}&type={stype[dtype]}')
r = requests.get(service)
soup = BeautifulSoup(r.text,'lxml')
tables = soup.findAll("table")
if dtype == 'model':
print_model(tables)
else:
print_doc(tables, dtype)
return service
def errata(tracking_id):
'''Return errata uids connected to a tracking id
'''
service = 'https://errata.es-doc.org/1/resolve/pid?pids='
r = requests.get(service + tracking_id.split(":")[1])
try:
uids = r.json()['errata'][0][1][0][0]
if uids:
return [x for x in uids.split(';')]
else:
return None
except KeyError:
print(f'Issue with handle: {tracking_id}')
print(r.json()["errorMessage"])
return None
def retrieve_error(uid):
''' Accept error uid and return errata as json plus webpage to view error '''
view = 'https://errata.es-doc.org/static/view.html?uid='
service = 'https://errata.es-doc.org/1/issue/retrieve?uid='
r = requests.get(service + uid)
error = {view+uid: r.json()['issue']}
return error
def print_error(uid):
error = retrieve_error(uid)
for k in error.keys():
print(f'You can view the full report online:\n{k}')
print(f'Title: {error[k]["title"]}')
print(f'Status: {error[k]["status"]}')
print(f'Description: {error[k]["description"]}')
def citation(dids):
'''Retrieve citations for a list of CMIP6 dataset ids'''
citations = []
url = 'https://cera-www.dkrz.de/WDCC/ui/cerasearch/cmip6?input='
#fexp = pkg_resources.resource_filename(__name__, 'data/CMIP6_exp_act.json')
#with open(fexp, 'r') as f:
# data = json.loads(f.read())
for did in dids:
# get facets from did to build correct url
did_bits = did.split(".")
version = did_bits[9]
newdid = ".".join(did_bits[0:5])
response = requests.get(url+newdid, headers={"User-Agent": "Requests"})
soup = BeautifulSoup(response.content, 'lxml')
el = soup.find('dt', text="Citation")
cite = el.next_sibling.text.replace(" BibTeX RIS","")
if version == 'none':
now = date.today()
citations.append(cite.replace("Version YYYYMMDD[1]",f'Accessed on {now}'))
else:
citations.append(cite.replace("YYYYMMDD[1].",f"{version}. "))
return citations
def write_cite(citations):
"""Write citations to file
"""
if len(citations) == 0:
print(f'Nothing to write to file')
return
out_file = "cmip_citations.txt"
try:
with open(out_file, 'w') as f:
f.write('\n'.join(citations))
print(f'Saving to {out_file}')
except IOError:
print("I/O error")
|
# -*- coding: utf-8 -*-
"""
mslib.msui.mpl_map
~~~~~~~~~~~~~~~~~~
Map canvas for the top view.
As Matplotlib's Basemap is primarily designed to produce static plots,
we derived a class MapCanvas to allow for a certain degree of
interactivity. MapCanvas extends Basemap by functionality to, for
instance, automatically draw a graticule. It also keeps references to
plotted map elements to allow the user to toggle their visibility, or
to redraw when map section (zoom/pan) or projection have been changed.
This file is part of mss.
:copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.
:copyright: Copyright 2011-2014 Marc Rautenhaus (mr)
:copyright: Copyright 2016-2021 by the mss team, see AUTHORS.
:license: APACHE-2.0, see LICENSE for details.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import copy
import numpy as np
from shapely.geometry import Polygon
import matplotlib
from matplotlib.cm import get_cmap
import matplotlib.path as mpath
import matplotlib.patches as mpatches
from matplotlib.collections import PolyCollection
import mpl_toolkits.basemap as basemap
try:
import mpl_toolkits.basemap.pyproj as pyproj
except ImportError:
logging.debug("Failed to pyproj from mpl_toolkits.basemap")
import pyproj
from mslib.msui import mpl_pathinteractor as mpl_pi
from mslib.utils.airdata import get_airports, get_airspaces
OPENAIP_NOTICE = "Airspace data used comes from openAIP.\n" \
"Visit openAIP.net and contribute to better aviation data, free for everyone to use and share."
OURAIRPORTS_NOTICE = "Airports provided by OurAirports."
class MapCanvas(basemap.Basemap):
"""
Derivative of mpl_toolkits.basemap, providing additional methods to
automatically draw a graticule and to redraw specific map elements.
"""
def __init__(self, identifier=None, CRS=None, BBOX_UNITS=None, OPERATION_NAME=None,
appearance=None, **kwargs):
"""
New constructor automatically adds coastlines, continents, and
a graticule to the map.
Keyword arguments are the same as for mpl_toolkits.basemap.
Additional arguments:
CRS -- string describing the coordinate reference system of the map.
BBOX_UNITS -- string describing the units of the map coordinates.
OPERATION_NAME -- string with operation name
"""
# Coordinate reference system identifier and coordinate system units.
self.crs = CRS if CRS is not None else self.crs if hasattr(self, "crs") else None
if BBOX_UNITS is not None:
self.bbox_units = BBOX_UNITS
else:
self.bbox_units = getattr(self, "bbox_units", None)
self.operation_name = OPERATION_NAME if OPERATION_NAME is not None else self.operation_name \
if hasattr(self, "operation_name") else None
# Dictionary containing map appearance settings.
if appearance is not None:
param_appearance = appearance
else:
param_appearance = getattr(self, "appearance", {})
default_appearance = {"draw_graticule": True,
"draw_coastlines": True,
"fill_waterbodies": True,
"fill_continents": True,
"colour_water": ((153 / 255.), (255 / 255.), (255 / 255.), (255 / 255.)),
"colour_land": ((204 / 255.), (153 / 255.), (102 / 255.), (255 / 255.))}
default_appearance.update(param_appearance)
self.appearance = default_appearance
# Identifier of this map canvas (used to query data structures that
# are observed by different views).
if identifier is not None:
self.identifier = identifier
else:
self.identifier = getattr(self, "identifier", None)
# Call the Basemap constructor. If a cylindrical projection was used
# before, Basemap stores an EPSG code that will not be changed if
# the Basemap constructor is called a second time. Hence, we have to
# delete the attribute (mr, 08Feb2013).
if hasattr(self, "epsg"):
del self.epsg
super().__init__(**kwargs)
self.gc = pyproj.Geod(a=self.rmajor, b=self.rminor)
self.kwargs = kwargs
# Set up the map appearance.
if self.appearance["draw_coastlines"]:
if len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0:
self.map_coastlines = self.drawcoastlines(zorder=3)
self.map_countries = self.drawcountries(zorder=3)
else:
self.map_coastlines = None
self.map_countries = None
if self.appearance["fill_waterbodies"]:
self.map_boundary = self.drawmapboundary(fill_color=self.appearance["colour_water"])
else:
self.map_boundary = None
# zorder = 0 is necessary to paint over the filled continents with
# scatter() for drawing the flight tracks and trajectories.
# Curiously, plot() works fine without this setting, but scatter()
# doesn't.
if self.appearance["fill_continents"]:
self.map_continents = self.fillcontinents(
color=self.appearance["colour_land"], lake_color=self.appearance["colour_water"], zorder=1)
else:
self.map_continents = None
self.image = None
# Print project name and CRS identifier into figure.
crs_text = ""
if self.operation_name is not None:
crs_text += self.operation_name
if self.crs is not None:
if len(crs_text) > 0:
crs_text += "\n"
crs_text += self.crs
if hasattr(self, "crs_text"): # update existing textbox
self.crs_text.set_text(crs_text)
else:
self.crs_text = self.ax.figure.text(0, 0, crs_text)
if self.appearance["draw_graticule"]:
pass
# self._draw_auto_graticule() ; It's already called in mpl_qtwidget.py in MplTopviewCanvas init_map().
else:
self.map_parallels = None
self.map_meridians = None
# self.warpimage() # disable fillcontinents when loading bluemarble
self.ax.set_autoscale_on(False)
if not hasattr(self, "airports") or not self.airports:
self.airports = None
self.airtext = None
if not hasattr(self, "airspaces") or not self.airspaces:
self.airspaces = None
self.airspacetext = None
def set_identifier(self, identifier):
self.identifier = identifier
def set_axes_limits(self, ax=None):
"""
See Basemap.set_axes_limits() for documentation.
This function is overridden in MapCanvas as a workaround to a problem
in Basemap.set_axes_limits() that occurs in interactive matplotlib
mode. If matplotlib.is_interactive() is True, Basemap.set_axes_limits()
tries to redraw the canvas by accessing the pylab figure manager.
If the matplotlib object is embedded in a Qt application, this manager
is not available and an exception is raised. Hence, the interactive
mode is disabled here before the original Basemap.set_axes_limits()
method is called. It is restored afterwards.
"""
intact = matplotlib.is_interactive()
matplotlib.interactive(False)
super(MapCanvas, self).set_axes_limits(ax=ax)
matplotlib.interactive(intact)
def _draw_auto_graticule(self, font_size=None):
"""
Draw an automatically spaced graticule on the map.
"""
# Compute some map coordinates that are required below for the automatic
# determination of which meridians and parallels to draw.
axis = self.ax.axis()
upperLeftCornerLon, upperLeftCornerLat = self.__call__(
axis[0], axis[3], inverse=True)
lowerRightCornerLon, lowerRightCornerLat = self.__call__(
axis[1], axis[2], inverse=True)
middleUpperBoundaryLon, middleUpperBoundaryLat = self.__call__(
np.mean([axis[0], axis[1]]), axis[3], inverse=True)
middleLowerBoundaryLon, middleLowerBoundaryLat = self.__call__(
np.mean([axis[0], axis[1]]), axis[2], inverse=True)
# Determine which parallels and meridians should be drawn.
# a) determine which are the minimum and maximum visible
# longitudes and latitudes, respectively. These
# values depend on the map projection.
if self.projection in ['npstere', 'spstere', 'stere', 'lcc']:
# For stereographic projections: Draw meridians from the minimum
# longitude contained in the map at one of the four corners to the
# maximum longitude at one of these corner points. If
# the southern or norther pole is contained in the map, draw all
# meridians around the globe.
# Draw parallels from the min latitude contained in the map at
# one of the four corners OR the middle top or bottom to the
# maximum latitude at one of these six points.
# If the map centre in contained in the map, replace either
# start or end latitude by the centre latitude (whichever is
# smaller/larger).
# check if centre point of projection is contained in the map,
# use projection coordinates for this test
centre_x = self.projparams["x_0"]
centre_y = self.projparams["y_0"]
centre_lon, centre_lat = self.__call__(centre_x, centre_y, inverse=True)
if centre_lat > 0:
pole_lon, pole_lat = 0, 90
else:
pole_lon, pole_lat = 0, -90
pole_x, pole_y = self.__call__(pole_lon, pole_lat)
if self.urcrnrx > self.llcrnrx:
contains_pole = (self.llcrnrx <= pole_x <= self.urcrnrx)
else:
contains_pole = (self.llcrnrx >= pole_x >= self.urcrnrx)
if self.urcrnry > self.llcrnry:
contains_pole = contains_pole and (self.llcrnry <= pole_y <= self.urcrnry)
else:
contains_pole = contains_pole and (self.llcrnry >= pole_y >= self.urcrnry)
# merdidians
if contains_pole:
mapLonStart = -180.
mapLonStop = 180.
else:
mapLonStart = min(upperLeftCornerLon, self.llcrnrlon,
self.urcrnrlon, lowerRightCornerLon)
mapLonStop = max(upperLeftCornerLon, self.llcrnrlon,
self.urcrnrlon, lowerRightCornerLon)
# parallels
mapLatStart = min(middleLowerBoundaryLat, lowerRightCornerLat,
self.llcrnrlat,
middleUpperBoundaryLat, upperLeftCornerLat,
self.urcrnrlat)
mapLatStop = max(middleLowerBoundaryLat, lowerRightCornerLat,
self.llcrnrlat,
middleUpperBoundaryLat, upperLeftCornerLat,
self.urcrnrlat)
if contains_pole:
centre_lat = self.projparams["lat_0"]
mapLatStart = min(mapLatStart, centre_lat)
mapLatStop = max(mapLatStop, centre_lat)
else:
# for other projections (preliminary): difference between the
# lower left and the upper right corner.
mapLonStart = self.llcrnrlon
mapLonStop = self.urcrnrlon
mapLatStart = self.llcrnrlat
mapLatStop = self.urcrnrlat
# b) parallels and meridians can be drawn with a spacing of
# >spacingValues< degrees. Determine the appropriate
# spacing for the lon/lat differences: about 10 lines
# should be drawn in each direction. (The following lines
# filter the spacingValues list for all spacing values
# that are larger than lat/lon difference / 10, then
# take the first value (first values that's larger)).
spacingValues = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 40]
deltaLon = mapLonStop - mapLonStart
deltaLat = mapLatStop - mapLatStart
spacingLon = ([i for i in spacingValues if i > (deltaLon / 11.)] + [60])[0]
spacingLat = ([i for i in spacingValues if i > (deltaLat / 11.)] + [60])[0]
# c) parallels and meridians start at the first value in the
# spacingLon/Lat grid that's smaller than the lon/lat of the
# lower left corner; they stop at the first values in the
# grid that's larger than the lon/lat of the upper right corner.
lonStart = np.floor((mapLonStart / spacingLon)) * spacingLon
lonStop = np.ceil((mapLonStop / spacingLon)) * spacingLon
latStart = np.floor((mapLatStart / spacingLat)) * spacingLat
latStop = np.ceil((mapLatStop / spacingLat)) * spacingLat
# d) call the basemap methods to draw the lines in the determined
# range.
self.map_parallels = self.drawparallels(np.arange(latStart, latStop,
spacingLat),
labels=[1, 1, 0, 0], fontsize=font_size, zorder=3)
self.map_meridians = self.drawmeridians(np.arange(lonStart, lonStop,
spacingLon),
labels=[0, 0, 0, 1], fontsize=font_size, zorder=3)
def set_graticule_visible(self, visible=True):
"""
Set the visibily of the graticule.
Removes a currently visible graticule by deleting internally stored
line and text objects representing graticule lines and labels, then
redrawing the map canvas.
See http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg09349.html
"""
self.appearance["draw_graticule"] = visible
if visible and self.map_parallels is None and self.map_meridians is None:
# Draw new graticule if visible is True and no current graticule
# exists.
self._draw_auto_graticule()
# Update the figure canvas.
self.ax.figure.canvas.draw()
elif not visible and self.map_parallels is not None and self.map_meridians is not None:
# If visible if False, remove current graticule if one exists.
# Every item in self.map_parallels and self.map_meridians is
# a tuple of a list of lines and a list of text labels.
for item in self.map_parallels.values():
for line in item[0]:
line.remove()
for text in item[1]:
text.remove()
for item in self.map_meridians.values():
for line in item[0]:
line.remove()
for text in item[1]:
text.remove()
self.map_parallels = None
self.map_meridians = None
# Update the figure canvas.
self.ax.figure.canvas.draw()
def set_draw_airports(self, value, port_type=["small_airport"], reload=True):
"""
Sets airports to visible or not visible
"""
if (reload or not value or len(port_type) == 0) and self.airports:
if OURAIRPORTS_NOTICE in self.crs_text.get_text():
self.crs_text.set_text(self.crs_text.get_text().replace(f"{OURAIRPORTS_NOTICE}\n", ""))
self.airports.remove()
self.airtext.remove()
self.airports = None
self.airtext = None
self.ax.figure.canvas.mpl_disconnect(self.airports_event)
if value and len(port_type) > 0:
self.draw_airports(port_type)
def set_draw_airspaces(self, value, airspaces=[], range_km=None, reload=True):
"""
Sets airspaces to visible or not visible
"""
if (reload or not value or len(airspaces) == 0) and self.airspaces:
if OPENAIP_NOTICE in self.crs_text.get_text():
self.crs_text.set_text(self.crs_text.get_text().replace(f"{OPENAIP_NOTICE}\n", ""))
self.airspaces.remove()
self.airspacetext.remove()
self.airspaces = None
self.airspacetext = None
self.ax.figure.canvas.mpl_disconnect(self.airspace_event)
if value and len(airspaces) > 0:
country_codes = [airspace.split(" ")[-1] for airspace in airspaces]
self.draw_airspaces(country_codes, range_km)
def draw_airspaces(self, countries=[], range_km=None):
"""
Load and draw airspace data
"""
if not self.airspaces:
airspaces = copy.deepcopy(get_airspaces(countries))
if not airspaces:
logging.error("Tried to draw airspaces without asp files.")
return
for i, airspace in enumerate(airspaces):
airspaces[i]["polygon"] = list(zip(*self.projtran(*list(zip(*airspace["polygon"])))))
map_polygon = Polygon([(self.llcrnrx, self.llcrnry), (self.urcrnrx, self.llcrnry),
(self.urcrnrx, self.urcrnry), (self.llcrnrx, self.urcrnry)])
airspaces = [airspace for airspace in airspaces if
(not range_km or range_km[0] <= airspace["bottom"] <= range_km[1]) and
Polygon(airspace["polygon"]).intersects(map_polygon)]
if not airspaces:
return
if OPENAIP_NOTICE not in self.crs_text.get_text():
self.crs_text.set_text(f"{OPENAIP_NOTICE}\n" + self.crs_text.get_text())
airspaces.sort(key=lambda x: (x["bottom"], x["top"] - x["bottom"]))
max_height = max(airspaces[-1]["bottom"], 0.001)
cmap = get_cmap("Blues")
airspace_colors = [cmap(1 - airspaces[i]["bottom"] / max_height) for i in range(len(airspaces))]
collection = PolyCollection([airspace["polygon"] for airspace in airspaces], alpha=0.5, edgecolor="black",
zorder=5, facecolors=airspace_colors)
collection.set_pickradius(0)
self.airspaces = self.ax.add_collection(collection)
self.airspacetext = self.ax.annotate(airspaces[0]["name"], xy=airspaces[0]["polygon"][0], xycoords="data",
bbox={"boxstyle": "round", "facecolor": "w",
"edgecolor": "0.5", "alpha": 0.9}, zorder=7)
self.airspacetext.set_visible(False)
def update_text(index, xydata):
self.airspacetext.xy = xydata
self.airspacetext.set_position(xydata)
self.airspacetext.set_text("\n".join([f"{airspaces[i]["name"]}, {airspaces[i]["bottom"]} - "
f"{airspaces[i]["top"]}km" for i in index["ind"]]))
highlight_cmap = get_cmap("YlGn")
for i in index["ind"]:
airspace_colors[i] = highlight_cmap(1 - airspaces[i]["bottom"] / max_height)
self.airspaces.set_facecolor(airspace_colors)
for i in index["ind"]:
airspace_colors[i] = cmap(1 - airspaces[i]["bottom"] / max_height)
def on_move(event):
if self.airspaces and event.inaxes == self.ax:
cont, ind = self.airspaces.contains(event)
if cont:
update_text(ind, (event.xdata, event.ydata))
self.airspacetext.set_visible(True)
self.ax.figure.canvas.draw_idle()
elif self.airspacetext.get_visible():
self.airspacetext.set_visible(False)
self.airspaces.set_facecolor(airspace_colors)
self.ax.figure.canvas.draw_idle()
self.airspace_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)
def draw_airports(self, port_type):
"""
Load and draw airports and their respective name on hover
"""
if not self.airports:
airports = get_airports()
if not airports:
logging.error("Tried to draw airports but none were found. Try redownloading.")
return
lons, lats = self.projtran(*zip(*[(float(airport["longitude_deg"]),
float(airport["latitude_deg"])) for airport in airports]))
for i, airport in enumerate(airports):
airports[i]["longitude_deg"] = lons[i]
airports[i]["latitude_deg"] = lats[i]
airports = [airport for airport in airports if airport["type"] in port_type and
self.llcrnrx <= float(airport["longitude_deg"]) <= self.urcrnrx and
self.llcrnry <= float(airport["latitude_deg"]) <= self.urcrnry]
lons = [float(airport["longitude_deg"]) for airport in airports]
lats = [float(airport["latitude_deg"]) for airport in airports]
annotations = [airport["name"] for airport in airports]
if not airports:
return
if OURAIRPORTS_NOTICE not in self.crs_text.get_text():
self.crs_text.set_text(f"{OURAIRPORTS_NOTICE}\n" + self.crs_text.get_text())
self.airports = self.ax.scatter(lons, lats, marker="o", color="r", linewidth=1, s=9, edgecolor="black",
zorder=6)
self.airports.set_pickradius(1)
self.airtext = self.ax.annotate(annotations[0], xy=(lons[0], lats[0]), xycoords="data",
bbox={"boxstyle": "round", "facecolor": "w",
"edgecolor": "0.5", "alpha": 0.9}, zorder=8)
self.airtext.set_visible(False)
def update_text(index):
pos = self.airports.get_offsets()[index["ind"][0]]
self.airtext.xy = pos
self.airtext.set_position(pos)
self.airtext.set_text("\n".join([annotations[i] for i in index["ind"]]))
def on_move(event):
if self.airports and event.inaxes == self.ax:
cont, ind = self.airports.contains(event)
if cont:
update_text(ind)
self.airtext.set_visible(True)
self.ax.figure.canvas.draw_idle()
elif self.airtext.get_visible():
self.airtext.set_visible(False)
self.ax.figure.canvas.draw_idle()
self.airports_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)
def set_fillcontinents_visible(self, visible=True, land_color=None,
lake_color=None):
"""
Set the visibility of continent fillings.
"""
if land_color is not None:
self.appearance["colour_land"] = land_color
if lake_color is not None:
self.appearance["colour_water"] = lake_color
self.appearance["fill_continents"] = visible
if visible and self.map_continents is None:
# zorder = 0 is necessary to paint over the filled continents with
# scatter() for drawing the flight tracks and trajectories.
# Curiously, plot() works fine without this setting, but scatter()
# doesn't.
self.map_continents = self.fillcontinents(color=self.appearance["colour_land"],
lake_color=self.appearance["colour_water"],
zorder=1)
self.ax.figure.canvas.draw()
elif not visible and self.map_continents is not None:
# Remove current fills. They are stored as a list of polygon patches
# in self.map_continents.
for patch in self.map_continents:
patch.remove()
self.map_continents = None
self.ax.figure.canvas.draw()
elif visible and self.map_continents is not None:
# Colours have changed: Remove the old fill and redraw.
for patch in self.map_continents:
patch.remove()
self.map_continents = self.fillcontinents(color=self.appearance["colour_land"],
lake_color=self.appearance["colour_water"],
zorder=1)
self.ax.figure.canvas.draw()
def set_coastlines_visible(self, visible=True):
"""
Set the visibility of coastlines and country borders.
"""
self.appearance["draw_coastlines"] = visible
if visible and self.map_coastlines is None and self.map_countries is None:
self.map_coastlines = self.drawcoastlines(zorder=3)
self.map_countries = self.drawcountries(zorder=3)
self.ax.figure.canvas.draw()
elif not visible and self.map_coastlines is not None and self.map_countries is not None:
self.map_coastlines.remove()
self.map_countries.remove()
del self.cntrysegs
self.map_coastlines = None
self.map_countries = None
self.ax.figure.canvas.draw()
def set_mapboundary_visible(self, visible=True, bg_color='#99ffff'):
"""
"""
# TODO: This doesn't work. Removing the map background only makes sense
# if there's a second image underneath this map. Maybe we should work
# with alpha values instead.
self.appearance["fill_waterbodies"] = visible
self.appearance["colour_water"] = bg_color
if not visible and self.map_boundary is not None:
try:
self.map_boundary.remove()
except NotImplementedError as ex:
logging.debug("%s", ex)
self.map_boundary = None
self.ax.figure.canvas.draw()
elif visible:
self.map_boundary = self.drawmapboundary(fill_color=bg_color)
self.ax.figure.canvas.draw()
def update_with_coordinate_change(self, kwargs_update=None):
"""
Redraws the entire map. This is necessary after zoom/pan operations.
Determines corner coordinates of the current axes, removes all items
belonging the the current map and draws a new one by calling
self.__init__().
DRAWBACK of this approach is that the map coordinate system changes, as
basemap always takes the lower left axis corner as (0,0). This means
that all other objects on the matplotlib canvas (flight track, markers,
..) will be incorrectly placed after a redraw. Their coordinates need
to be adjusted by 1) transforming their coordinates to lat/lon BEFORE
the map is redrawn, 2) redrawing the map, 3) transforming the stored
lat/lon coordinates to the new map coordinates.
"""
# Convert the current axis corners to lat/lon coordinates.
axis = self.ax.axis()
self.kwargs['llcrnrlon'], self.kwargs['llcrnrlat'] = \
self.__call__(axis[0], axis[2], inverse=True)
self.kwargs['urcrnrlon'], self.kwargs['urcrnrlat'] = \
self.__call__(axis[1], axis[3], inverse=True)
logging.debug("corner coordinates (lat/lon): ll(%.2f,%.2f), ur(%.2f,%.2f)",
self.kwargs['llcrnrlat'], self.kwargs['llcrnrlon'],
self.kwargs['urcrnrlat'], self.kwargs['urcrnrlon'])
if (self.kwargs.get("projection") in ["cyl"] or
self.kwargs.get("epsg") in ["4326"]):
# Latitudes in cylindrical projection need to be within -90..90.
self.kwargs['llcrnrlat'] = max(self.kwargs['llcrnrlat'], -90)
self.kwargs['urcrnrlat'] = max(self.kwargs['urcrnrlat'], -89)
self.kwargs['llcrnrlat'] = min(self.kwargs['llcrnrlat'], 89)
self.kwargs['urcrnrlat'] = min(self.kwargs['urcrnrlat'], 90)
# Longitudes in cylindrical projection need to be within -360..540.
self.kwargs["llcrnrlon"] = max(self.kwargs["llcrnrlon"], -360)
self.kwargs["urcrnrlon"] = max(self.kwargs["urcrnrlon"], -359)
self.kwargs["llcrnrlon"] = min(self.kwargs["llcrnrlon"], 539)
self.kwargs["urcrnrlon"] = min(self.kwargs["urcrnrlon"], 540)
# Remove the current map artists.
grat_vis = self.appearance["draw_graticule"]
self.set_graticule_visible(False)
self.appearance["draw_graticule"] = grat_vis
if self.map_coastlines is not None and (len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0):
self.map_coastlines.remove()
if self.image is not None:
self.image.remove()
self.image = None
# Refer to Basemap.drawcountries() on how to remove country borders.
# In addition to the matplotlib lines, the loaded country segment data
# needs to be loaded. THE SAME NEEDS TO BE DONE WITH RIVERS ETC.
if self.map_countries is not None:
self.map_countries.remove()
del self.cntrysegs
# map_boundary is None for rectangular projections (basemap simply sets
# the background colour).
if self.map_boundary is not None:
try:
self.map_boundary.remove()
except NotImplementedError as ex:
logging.debug("%s", ex)
self.map_boundary = None
cont_vis = self.appearance["fill_continents"]
self.set_fillcontinents_visible(False)
self.appearance["fill_continents"] = cont_vis
# POSSIBILITY A): Call self.__init__ again with stored keywords.
# Update kwargs if new parameters such as the map region have been
# given.
if kwargs_update:
proj_keys = ["epsg", "projection"]
if any(_x in kwargs_update for _x in proj_keys):
for key in (_x for _x in proj_keys if _x in self.kwargs):
del self.kwargs[key]
self.kwargs.update(kwargs_update)
self.__init__(**self.kwargs)
# TODO: HOW TO MAKE THIS MORE EFFICIENT.
# POSSIBILITY B): Only set the Basemap parameters that influence the
# plot (corner lat/lon, x/y, width/height, ..) and re-define the
# polygons that represent the coastlines etc. In Basemap, they are
# defined in __init__(), at the very bottom (the code that comes
# with the comments
# >> read in coastline polygons, only keeping those that
# >> intersect map boundary polygon.
# ). Basemap only loads the coastline data that is actually displayed.
# If we only change llcrnrlon etc. here and replot coastlines etc.,
# the polygons and the map extent will remain the same.
# However, it should be possible to make a map change WITHOUT changing
# coordinates.
#
# self.llcrnrlon = llcrnrlon
# self.llcrnrlat = llcrnrlat
# self.urcrnrlon = urcrnrlon
# self.urcrnrlat = urcrnrlat
# self.llcrnrx = axis[0]
# self.llcrnry = axis[2]
# self.urcrnrx = axis[1]
# self.urcrnry = axis[3]
def imshow(self, X, **kwargs):
"""
Overloads basemap.imshow(). Deletes any existing image and
redraws the figure after the new image has been plotted.
"""
if self.image is not None:
self.image.remove()
self.image = super(MapCanvas, self).imshow(X, zorder=2, **kwargs)
self.ax.figure.canvas.draw()
return self.image
def gcpoints2(self, lon0, lat0, lon1, lat1, del_s=100., map_coords=True):
"""
The same as basemap.gcpoints(), but takes a distance interval del_s
to space the points instead of a number of points.
"""
# use great circle formula for a perfect sphere.
_, _, dist = self.gc.inv(lon0, lat0, lon1, lat1)
npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))
lonlats = self.gc.npts(lon0, lat0, lon1, lat1, npoints)
lons = [lon0]
lats = [lat0]
for lon, lat in lonlats:
lons.append(lon)
lats.append(lat)
lons.append(lon1)
lats.append(lat1)
if map_coords:
x, y = self(lons, lats)
else:
x, y = (lons, lats)
return x, y
def gcpoints_path(self, lons, lats, del_s=100., map_coords=True):
"""
Same as gcpoints2, but for an entire path, i.e. multiple
line segments. lons and lats are lists of waypoint coordinates.
"""
# use great circle formula for a perfect sphere.
assert len(lons) == len(lats)
assert len(lons) > 1
gclons = [lons[0]]
gclats = [lats[0]]
for i in range(len(lons) - 1):
_, _, dist = self.gc.inv(lons[i], lats[i], lons[i + 1], lats[i + 1])
npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))
lonlats = []
if npoints > 0:
lonlats = self.gc.npts(lons[i], lats[i], lons[i + 1], lats[i + 1], npoints)
for lon, lat in lonlats:
gclons.append(lon)
gclats.append(lat)
gclons.append(lons[i + 1])
gclats.append(lats[i + 1])
if self.projection == "cyl": # hack for wraparound
lon_min, lon_max = self.llcrnrlon, self.urcrnrlon
gclons = np.array(gclons)
gclons[gclons < lon_min] += 360
gclons[gclons > lon_max] -= 360
idcs = np.where(abs(np.diff(gclons)) > 300)[0]
gclons[idcs] = np.nan
if map_coords:
x, y = self(gclons, gclats)
else:
x, y = (gclons, gclats)
return x, y
def drawgreatcircle_path(self, lons, lats, del_s=100., **kwargs):
"""
"""
x, y = self.gcpoints_path(lons, lats, del_s=del_s)
return self.plot(x, y, **kwargs)
class SatelliteOverpassPatch(object):
"""
Represents a satellite overpass on the top view map (satellite
track and, if available, swath).
"""
# TODO: Derive this class from some Matplotlib actor class? Or create
# a new abstract base class for objects that can be drawn on the
# map -- they all should provide methods remove(), update(),
# etc. update() should automatically remap the object to new map
# coordinates.
def __init__(self, mapcanvas, segment):
"""
"""
self.map = mapcanvas
self.segment = segment
# Filter those time elements that correspond to masked positions -- this
# way the indexes in self.utc correspond to those in self.sat.
# np.ma.getmaskarray is necessary as ..mask only returns a scalar
# "False" if the array contains no masked entries.
self.utc = segment["utc"][~np.ma.getmaskarray(segment["satpos"])[:, 0]]
self.sat = np.ma.compress_rows(segment["satpos"])
self.sw_l = np.ma.compress_rows(segment["swath_left"])
self.sw_r = np.ma.compress_rows(segment["swath_right"])
self.trackline = None
self.patch = None
self.texts = []
self.draw()
def draw(self):
"""
Do the actual plotting of the patch.
"""
# Plot satellite track.
sat = np.copy(self.sat)
sat[:, 0], sat[:, 1] = self.map(sat[:, 0], sat[:, 1])
self.trackline = self.map.plot(sat[:, 0], sat[:, 1], zorder=10,
marker='+', markerfacecolor='g')
# Plot polygon patch that represents the swath of the sensor.
sw_l = self.sw_l
sw_r = self.sw_r
Path = mpath.Path
pathdata = [(Path.MOVETO, self.map(sw_l[0, 0], sw_l[0, 1]))]
for point in sw_l[1:]:
pathdata.append((Path.LINETO, self.map(point[0], point[1])))
for point in sw_r[::-1]:
pathdata.append((Path.LINETO, self.map(point[0], point[1])))
codes, verts = list(zip(*pathdata))
path = mpl_pi.PathH(verts, codes, map=self.map)
patch = mpatches.PathPatch(path, facecolor='yellow',
edgecolor='yellow', alpha=0.4, zorder=10)
self.patch = patch
self.map.ax.add_patch(patch)
# Draw text labels.
self.texts.append(self.map.ax.text(sat[0, 0], sat[0, 1],
self.utc[0].strftime("%H:%M:%S"),
zorder=10,
bbox=dict(facecolor='white',
alpha=0.5,
edgecolor='none')))
self.texts.append(self.map.ax.text(sat[-1, 0], sat[-1, 1],
self.utc[-1].strftime("%H:%M:%S"),
zorder=10,
bbox=dict(facecolor='white',
alpha=0.5,
edgecolor='none')))
self.map.ax.figure.canvas.draw()
def update(self):
"""
Removes the current plot of the patch and redraws the patch.
This is necessary, for instance, when the map projection and/or
extent has been changed.
"""
self.remove()
self.draw()
def remove(self):
"""
Remove this satellite patch from the map canvas.
"""
if self.trackline is not None:
for element in self.trackline:
element.remove()
self.trackline = None
if self.patch is not None:
self.patch.remove()
self.patch = None
for element in self.texts:
# Removal of text elements sometimes fails. I don't know why,
# the plots look fine nevertheless.
try:
element.remove()
except Exception as ex:
logging.error("Wildcard exception caught: %s %s", type(ex), ex)
| # -*- coding: utf-8 -*-
"""
mslib.msui.mpl_map
~~~~~~~~~~~~~~~~~~
Map canvas for the top view.
As Matplotlib's Basemap is primarily designed to produce static plots,
we derived a class MapCanvas to allow for a certain degree of
interactivity. MapCanvas extends Basemap by functionality to, for
instance, automatically draw a graticule. It also keeps references to
plotted map elements to allow the user to toggle their visibility, or
to redraw when map section (zoom/pan) or projection have been changed.
This file is part of mss.
:copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.
:copyright: Copyright 2011-2014 Marc Rautenhaus (mr)
:copyright: Copyright 2016-2021 by the mss team, see AUTHORS.
:license: APACHE-2.0, see LICENSE for details.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import copy
import numpy as np
from shapely.geometry import Polygon
import matplotlib
from matplotlib.cm import get_cmap
import matplotlib.path as mpath
import matplotlib.patches as mpatches
from matplotlib.collections import PolyCollection
import mpl_toolkits.basemap as basemap
try:
import mpl_toolkits.basemap.pyproj as pyproj
except ImportError:
logging.debug("Failed to pyproj from mpl_toolkits.basemap")
import pyproj
from mslib.msui import mpl_pathinteractor as mpl_pi
from mslib.utils.airdata import get_airports, get_airspaces
OPENAIP_NOTICE = "Airspace data used comes from openAIP.\n" \
"Visit openAIP.net and contribute to better aviation data, free for everyone to use and share."
OURAIRPORTS_NOTICE = "Airports provided by OurAirports."
class MapCanvas(basemap.Basemap):
"""
Derivative of mpl_toolkits.basemap, providing additional methods to
automatically draw a graticule and to redraw specific map elements.
"""
def __init__(self, identifier=None, CRS=None, BBOX_UNITS=None, OPERATION_NAME=None,
appearance=None, **kwargs):
"""
New constructor automatically adds coastlines, continents, and
a graticule to the map.
Keyword arguments are the same as for mpl_toolkits.basemap.
Additional arguments:
CRS -- string describing the coordinate reference system of the map.
BBOX_UNITS -- string describing the units of the map coordinates.
OPERATION_NAME -- string with operation name
"""
# Coordinate reference system identifier and coordinate system units.
self.crs = CRS if CRS is not None else self.crs if hasattr(self, "crs") else None
if BBOX_UNITS is not None:
self.bbox_units = BBOX_UNITS
else:
self.bbox_units = getattr(self, "bbox_units", None)
self.operation_name = OPERATION_NAME if OPERATION_NAME is not None else self.operation_name \
if hasattr(self, "operation_name") else None
# Dictionary containing map appearance settings.
if appearance is not None:
param_appearance = appearance
else:
param_appearance = getattr(self, "appearance", {})
default_appearance = {"draw_graticule": True,
"draw_coastlines": True,
"fill_waterbodies": True,
"fill_continents": True,
"colour_water": ((153 / 255.), (255 / 255.), (255 / 255.), (255 / 255.)),
"colour_land": ((204 / 255.), (153 / 255.), (102 / 255.), (255 / 255.))}
default_appearance.update(param_appearance)
self.appearance = default_appearance
# Identifier of this map canvas (used to query data structures that
# are observed by different views).
if identifier is not None:
self.identifier = identifier
else:
self.identifier = getattr(self, "identifier", None)
# Call the Basemap constructor. If a cylindrical projection was used
# before, Basemap stores an EPSG code that will not be changed if
# the Basemap constructor is called a second time. Hence, we have to
# delete the attribute (mr, 08Feb2013).
if hasattr(self, "epsg"):
del self.epsg
super().__init__(**kwargs)
self.gc = pyproj.Geod(a=self.rmajor, b=self.rminor)
self.kwargs = kwargs
# Set up the map appearance.
if self.appearance["draw_coastlines"]:
if len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0:
self.map_coastlines = self.drawcoastlines(zorder=3)
self.map_countries = self.drawcountries(zorder=3)
else:
self.map_coastlines = None
self.map_countries = None
if self.appearance["fill_waterbodies"]:
self.map_boundary = self.drawmapboundary(fill_color=self.appearance["colour_water"])
else:
self.map_boundary = None
# zorder = 0 is necessary to paint over the filled continents with
# scatter() for drawing the flight tracks and trajectories.
# Curiously, plot() works fine without this setting, but scatter()
# doesn't.
if self.appearance["fill_continents"]:
self.map_continents = self.fillcontinents(
color=self.appearance["colour_land"], lake_color=self.appearance["colour_water"], zorder=1)
else:
self.map_continents = None
self.image = None
# Print project name and CRS identifier into figure.
crs_text = ""
if self.operation_name is not None:
crs_text += self.operation_name
if self.crs is not None:
if len(crs_text) > 0:
crs_text += "\n"
crs_text += self.crs
if hasattr(self, "crs_text"): # update existing textbox
self.crs_text.set_text(crs_text)
else:
self.crs_text = self.ax.figure.text(0, 0, crs_text)
if self.appearance["draw_graticule"]:
pass
# self._draw_auto_graticule() ; It's already called in mpl_qtwidget.py in MplTopviewCanvas init_map().
else:
self.map_parallels = None
self.map_meridians = None
# self.warpimage() # disable fillcontinents when loading bluemarble
self.ax.set_autoscale_on(False)
if not hasattr(self, "airports") or not self.airports:
self.airports = None
self.airtext = None
if not hasattr(self, "airspaces") or not self.airspaces:
self.airspaces = None
self.airspacetext = None
def set_identifier(self, identifier):
self.identifier = identifier
def set_axes_limits(self, ax=None):
"""
See Basemap.set_axes_limits() for documentation.
This function is overridden in MapCanvas as a workaround to a problem
in Basemap.set_axes_limits() that occurs in interactive matplotlib
mode. If matplotlib.is_interactive() is True, Basemap.set_axes_limits()
tries to redraw the canvas by accessing the pylab figure manager.
If the matplotlib object is embedded in a Qt application, this manager
is not available and an exception is raised. Hence, the interactive
mode is disabled here before the original Basemap.set_axes_limits()
method is called. It is restored afterwards.
"""
intact = matplotlib.is_interactive()
matplotlib.interactive(False)
super(MapCanvas, self).set_axes_limits(ax=ax)
matplotlib.interactive(intact)
def _draw_auto_graticule(self, font_size=None):
"""
Draw an automatically spaced graticule on the map.
"""
# Compute some map coordinates that are required below for the automatic
# determination of which meridians and parallels to draw.
axis = self.ax.axis()
upperLeftCornerLon, upperLeftCornerLat = self.__call__(
axis[0], axis[3], inverse=True)
lowerRightCornerLon, lowerRightCornerLat = self.__call__(
axis[1], axis[2], inverse=True)
middleUpperBoundaryLon, middleUpperBoundaryLat = self.__call__(
np.mean([axis[0], axis[1]]), axis[3], inverse=True)
middleLowerBoundaryLon, middleLowerBoundaryLat = self.__call__(
np.mean([axis[0], axis[1]]), axis[2], inverse=True)
# Determine which parallels and meridians should be drawn.
# a) determine which are the minimum and maximum visible
# longitudes and latitudes, respectively. These
# values depend on the map projection.
if self.projection in ['npstere', 'spstere', 'stere', 'lcc']:
# For stereographic projections: Draw meridians from the minimum
# longitude contained in the map at one of the four corners to the
# maximum longitude at one of these corner points. If
# the southern or norther pole is contained in the map, draw all
# meridians around the globe.
# Draw parallels from the min latitude contained in the map at
# one of the four corners OR the middle top or bottom to the
# maximum latitude at one of these six points.
# If the map centre in contained in the map, replace either
# start or end latitude by the centre latitude (whichever is
# smaller/larger).
# check if centre point of projection is contained in the map,
# use projection coordinates for this test
centre_x = self.projparams["x_0"]
centre_y = self.projparams["y_0"]
centre_lon, centre_lat = self.__call__(centre_x, centre_y, inverse=True)
if centre_lat > 0:
pole_lon, pole_lat = 0, 90
else:
pole_lon, pole_lat = 0, -90
pole_x, pole_y = self.__call__(pole_lon, pole_lat)
if self.urcrnrx > self.llcrnrx:
contains_pole = (self.llcrnrx <= pole_x <= self.urcrnrx)
else:
contains_pole = (self.llcrnrx >= pole_x >= self.urcrnrx)
if self.urcrnry > self.llcrnry:
contains_pole = contains_pole and (self.llcrnry <= pole_y <= self.urcrnry)
else:
contains_pole = contains_pole and (self.llcrnry >= pole_y >= self.urcrnry)
# merdidians
if contains_pole:
mapLonStart = -180.
mapLonStop = 180.
else:
mapLonStart = min(upperLeftCornerLon, self.llcrnrlon,
self.urcrnrlon, lowerRightCornerLon)
mapLonStop = max(upperLeftCornerLon, self.llcrnrlon,
self.urcrnrlon, lowerRightCornerLon)
# parallels
mapLatStart = min(middleLowerBoundaryLat, lowerRightCornerLat,
self.llcrnrlat,
middleUpperBoundaryLat, upperLeftCornerLat,
self.urcrnrlat)
mapLatStop = max(middleLowerBoundaryLat, lowerRightCornerLat,
self.llcrnrlat,
middleUpperBoundaryLat, upperLeftCornerLat,
self.urcrnrlat)
if contains_pole:
centre_lat = self.projparams["lat_0"]
mapLatStart = min(mapLatStart, centre_lat)
mapLatStop = max(mapLatStop, centre_lat)
else:
# for other projections (preliminary): difference between the
# lower left and the upper right corner.
mapLonStart = self.llcrnrlon
mapLonStop = self.urcrnrlon
mapLatStart = self.llcrnrlat
mapLatStop = self.urcrnrlat
# b) parallels and meridians can be drawn with a spacing of
# >spacingValues< degrees. Determine the appropriate
# spacing for the lon/lat differences: about 10 lines
# should be drawn in each direction. (The following lines
# filter the spacingValues list for all spacing values
# that are larger than lat/lon difference / 10, then
# take the first value (first values that's larger)).
spacingValues = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 30, 40]
deltaLon = mapLonStop - mapLonStart
deltaLat = mapLatStop - mapLatStart
spacingLon = ([i for i in spacingValues if i > (deltaLon / 11.)] + [60])[0]
spacingLat = ([i for i in spacingValues if i > (deltaLat / 11.)] + [60])[0]
# c) parallels and meridians start at the first value in the
# spacingLon/Lat grid that's smaller than the lon/lat of the
# lower left corner; they stop at the first values in the
# grid that's larger than the lon/lat of the upper right corner.
lonStart = np.floor((mapLonStart / spacingLon)) * spacingLon
lonStop = np.ceil((mapLonStop / spacingLon)) * spacingLon
latStart = np.floor((mapLatStart / spacingLat)) * spacingLat
latStop = np.ceil((mapLatStop / spacingLat)) * spacingLat
# d) call the basemap methods to draw the lines in the determined
# range.
self.map_parallels = self.drawparallels(np.arange(latStart, latStop,
spacingLat),
labels=[1, 1, 0, 0], fontsize=font_size, zorder=3)
self.map_meridians = self.drawmeridians(np.arange(lonStart, lonStop,
spacingLon),
labels=[0, 0, 0, 1], fontsize=font_size, zorder=3)
def set_graticule_visible(self, visible=True):
"""
Set the visibily of the graticule.
Removes a currently visible graticule by deleting internally stored
line and text objects representing graticule lines and labels, then
redrawing the map canvas.
See http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg09349.html
"""
self.appearance["draw_graticule"] = visible
if visible and self.map_parallels is None and self.map_meridians is None:
# Draw new graticule if visible is True and no current graticule
# exists.
self._draw_auto_graticule()
# Update the figure canvas.
self.ax.figure.canvas.draw()
elif not visible and self.map_parallels is not None and self.map_meridians is not None:
# If visible if False, remove current graticule if one exists.
# Every item in self.map_parallels and self.map_meridians is
# a tuple of a list of lines and a list of text labels.
for item in self.map_parallels.values():
for line in item[0]:
line.remove()
for text in item[1]:
text.remove()
for item in self.map_meridians.values():
for line in item[0]:
line.remove()
for text in item[1]:
text.remove()
self.map_parallels = None
self.map_meridians = None
# Update the figure canvas.
self.ax.figure.canvas.draw()
def set_draw_airports(self, value, port_type=["small_airport"], reload=True):
"""
Sets airports to visible or not visible
"""
if (reload or not value or len(port_type) == 0) and self.airports:
if OURAIRPORTS_NOTICE in self.crs_text.get_text():
self.crs_text.set_text(self.crs_text.get_text().replace(f"{OURAIRPORTS_NOTICE}\n", ""))
self.airports.remove()
self.airtext.remove()
self.airports = None
self.airtext = None
self.ax.figure.canvas.mpl_disconnect(self.airports_event)
if value and len(port_type) > 0:
self.draw_airports(port_type)
def set_draw_airspaces(self, value, airspaces=[], range_km=None, reload=True):
"""
Sets airspaces to visible or not visible
"""
if (reload or not value or len(airspaces) == 0) and self.airspaces:
if OPENAIP_NOTICE in self.crs_text.get_text():
self.crs_text.set_text(self.crs_text.get_text().replace(f"{OPENAIP_NOTICE}\n", ""))
self.airspaces.remove()
self.airspacetext.remove()
self.airspaces = None
self.airspacetext = None
self.ax.figure.canvas.mpl_disconnect(self.airspace_event)
if value and len(airspaces) > 0:
country_codes = [airspace.split(" ")[-1] for airspace in airspaces]
self.draw_airspaces(country_codes, range_km)
def draw_airspaces(self, countries=[], range_km=None):
"""
Load and draw airspace data
"""
if not self.airspaces:
airspaces = copy.deepcopy(get_airspaces(countries))
if not airspaces:
logging.error("Tried to draw airspaces without asp files.")
return
for i, airspace in enumerate(airspaces):
airspaces[i]["polygon"] = list(zip(*self.projtran(*list(zip(*airspace["polygon"])))))
map_polygon = Polygon([(self.llcrnrx, self.llcrnry), (self.urcrnrx, self.llcrnry),
(self.urcrnrx, self.urcrnry), (self.llcrnrx, self.urcrnry)])
airspaces = [airspace for airspace in airspaces if
(not range_km or range_km[0] <= airspace["bottom"] <= range_km[1]) and
Polygon(airspace["polygon"]).intersects(map_polygon)]
if not airspaces:
return
if OPENAIP_NOTICE not in self.crs_text.get_text():
self.crs_text.set_text(f"{OPENAIP_NOTICE}\n" + self.crs_text.get_text())
airspaces.sort(key=lambda x: (x["bottom"], x["top"] - x["bottom"]))
max_height = max(airspaces[-1]["bottom"], 0.001)
cmap = get_cmap("Blues")
airspace_colors = [cmap(1 - airspaces[i]["bottom"] / max_height) for i in range(len(airspaces))]
collection = PolyCollection([airspace["polygon"] for airspace in airspaces], alpha=0.5, edgecolor="black",
zorder=5, facecolors=airspace_colors)
collection.set_pickradius(0)
self.airspaces = self.ax.add_collection(collection)
self.airspacetext = self.ax.annotate(airspaces[0]["name"], xy=airspaces[0]["polygon"][0], xycoords="data",
bbox={"boxstyle": "round", "facecolor": "w",
"edgecolor": "0.5", "alpha": 0.9}, zorder=7)
self.airspacetext.set_visible(False)
def update_text(index, xydata):
self.airspacetext.xy = xydata
self.airspacetext.set_position(xydata)
self.airspacetext.set_text("\n".join([f"{airspaces[i]['name']}, {airspaces[i]['bottom']} - "
f"{airspaces[i]['top']}km" for i in index["ind"]]))
highlight_cmap = get_cmap("YlGn")
for i in index["ind"]:
airspace_colors[i] = highlight_cmap(1 - airspaces[i]["bottom"] / max_height)
self.airspaces.set_facecolor(airspace_colors)
for i in index["ind"]:
airspace_colors[i] = cmap(1 - airspaces[i]["bottom"] / max_height)
def on_move(event):
if self.airspaces and event.inaxes == self.ax:
cont, ind = self.airspaces.contains(event)
if cont:
update_text(ind, (event.xdata, event.ydata))
self.airspacetext.set_visible(True)
self.ax.figure.canvas.draw_idle()
elif self.airspacetext.get_visible():
self.airspacetext.set_visible(False)
self.airspaces.set_facecolor(airspace_colors)
self.ax.figure.canvas.draw_idle()
self.airspace_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)
def draw_airports(self, port_type):
"""
Load and draw airports and their respective name on hover
"""
if not self.airports:
airports = get_airports()
if not airports:
logging.error("Tried to draw airports but none were found. Try redownloading.")
return
lons, lats = self.projtran(*zip(*[(float(airport["longitude_deg"]),
float(airport["latitude_deg"])) for airport in airports]))
for i, airport in enumerate(airports):
airports[i]["longitude_deg"] = lons[i]
airports[i]["latitude_deg"] = lats[i]
airports = [airport for airport in airports if airport["type"] in port_type and
self.llcrnrx <= float(airport["longitude_deg"]) <= self.urcrnrx and
self.llcrnry <= float(airport["latitude_deg"]) <= self.urcrnry]
lons = [float(airport["longitude_deg"]) for airport in airports]
lats = [float(airport["latitude_deg"]) for airport in airports]
annotations = [airport["name"] for airport in airports]
if not airports:
return
if OURAIRPORTS_NOTICE not in self.crs_text.get_text():
self.crs_text.set_text(f"{OURAIRPORTS_NOTICE}\n" + self.crs_text.get_text())
self.airports = self.ax.scatter(lons, lats, marker="o", color="r", linewidth=1, s=9, edgecolor="black",
zorder=6)
self.airports.set_pickradius(1)
self.airtext = self.ax.annotate(annotations[0], xy=(lons[0], lats[0]), xycoords="data",
bbox={"boxstyle": "round", "facecolor": "w",
"edgecolor": "0.5", "alpha": 0.9}, zorder=8)
self.airtext.set_visible(False)
def update_text(index):
pos = self.airports.get_offsets()[index["ind"][0]]
self.airtext.xy = pos
self.airtext.set_position(pos)
self.airtext.set_text("\n".join([annotations[i] for i in index["ind"]]))
def on_move(event):
if self.airports and event.inaxes == self.ax:
cont, ind = self.airports.contains(event)
if cont:
update_text(ind)
self.airtext.set_visible(True)
self.ax.figure.canvas.draw_idle()
elif self.airtext.get_visible():
self.airtext.set_visible(False)
self.ax.figure.canvas.draw_idle()
self.airports_event = self.ax.figure.canvas.mpl_connect('motion_notify_event', on_move)
def set_fillcontinents_visible(self, visible=True, land_color=None,
lake_color=None):
"""
Set the visibility of continent fillings.
"""
if land_color is not None:
self.appearance["colour_land"] = land_color
if lake_color is not None:
self.appearance["colour_water"] = lake_color
self.appearance["fill_continents"] = visible
if visible and self.map_continents is None:
# zorder = 0 is necessary to paint over the filled continents with
# scatter() for drawing the flight tracks and trajectories.
# Curiously, plot() works fine without this setting, but scatter()
# doesn't.
self.map_continents = self.fillcontinents(color=self.appearance["colour_land"],
lake_color=self.appearance["colour_water"],
zorder=1)
self.ax.figure.canvas.draw()
elif not visible and self.map_continents is not None:
# Remove current fills. They are stored as a list of polygon patches
# in self.map_continents.
for patch in self.map_continents:
patch.remove()
self.map_continents = None
self.ax.figure.canvas.draw()
elif visible and self.map_continents is not None:
# Colours have changed: Remove the old fill and redraw.
for patch in self.map_continents:
patch.remove()
self.map_continents = self.fillcontinents(color=self.appearance["colour_land"],
lake_color=self.appearance["colour_water"],
zorder=1)
self.ax.figure.canvas.draw()
def set_coastlines_visible(self, visible=True):
"""
Set the visibility of coastlines and country borders.
"""
self.appearance["draw_coastlines"] = visible
if visible and self.map_coastlines is None and self.map_countries is None:
self.map_coastlines = self.drawcoastlines(zorder=3)
self.map_countries = self.drawcountries(zorder=3)
self.ax.figure.canvas.draw()
elif not visible and self.map_coastlines is not None and self.map_countries is not None:
self.map_coastlines.remove()
self.map_countries.remove()
del self.cntrysegs
self.map_coastlines = None
self.map_countries = None
self.ax.figure.canvas.draw()
def set_mapboundary_visible(self, visible=True, bg_color='#99ffff'):
"""
"""
# TODO: This doesn't work. Removing the map background only makes sense
# if there's a second image underneath this map. Maybe we should work
# with alpha values instead.
self.appearance["fill_waterbodies"] = visible
self.appearance["colour_water"] = bg_color
if not visible and self.map_boundary is not None:
try:
self.map_boundary.remove()
except NotImplementedError as ex:
logging.debug("%s", ex)
self.map_boundary = None
self.ax.figure.canvas.draw()
elif visible:
self.map_boundary = self.drawmapboundary(fill_color=bg_color)
self.ax.figure.canvas.draw()
def update_with_coordinate_change(self, kwargs_update=None):
"""
Redraws the entire map. This is necessary after zoom/pan operations.
Determines corner coordinates of the current axes, removes all items
belonging the the current map and draws a new one by calling
self.__init__().
DRAWBACK of this approach is that the map coordinate system changes, as
basemap always takes the lower left axis corner as (0,0). This means
that all other objects on the matplotlib canvas (flight track, markers,
..) will be incorrectly placed after a redraw. Their coordinates need
to be adjusted by 1) transforming their coordinates to lat/lon BEFORE
the map is redrawn, 2) redrawing the map, 3) transforming the stored
lat/lon coordinates to the new map coordinates.
"""
# Convert the current axis corners to lat/lon coordinates.
axis = self.ax.axis()
self.kwargs['llcrnrlon'], self.kwargs['llcrnrlat'] = \
self.__call__(axis[0], axis[2], inverse=True)
self.kwargs['urcrnrlon'], self.kwargs['urcrnrlat'] = \
self.__call__(axis[1], axis[3], inverse=True)
logging.debug("corner coordinates (lat/lon): ll(%.2f,%.2f), ur(%.2f,%.2f)",
self.kwargs['llcrnrlat'], self.kwargs['llcrnrlon'],
self.kwargs['urcrnrlat'], self.kwargs['urcrnrlon'])
if (self.kwargs.get("projection") in ["cyl"] or
self.kwargs.get("epsg") in ["4326"]):
# Latitudes in cylindrical projection need to be within -90..90.
self.kwargs['llcrnrlat'] = max(self.kwargs['llcrnrlat'], -90)
self.kwargs['urcrnrlat'] = max(self.kwargs['urcrnrlat'], -89)
self.kwargs['llcrnrlat'] = min(self.kwargs['llcrnrlat'], 89)
self.kwargs['urcrnrlat'] = min(self.kwargs['urcrnrlat'], 90)
# Longitudes in cylindrical projection need to be within -360..540.
self.kwargs["llcrnrlon"] = max(self.kwargs["llcrnrlon"], -360)
self.kwargs["urcrnrlon"] = max(self.kwargs["urcrnrlon"], -359)
self.kwargs["llcrnrlon"] = min(self.kwargs["llcrnrlon"], 539)
self.kwargs["urcrnrlon"] = min(self.kwargs["urcrnrlon"], 540)
# Remove the current map artists.
grat_vis = self.appearance["draw_graticule"]
self.set_graticule_visible(False)
self.appearance["draw_graticule"] = grat_vis
if self.map_coastlines is not None and (len(self.coastsegs) > 0 and len(self.coastsegs[0]) > 0):
self.map_coastlines.remove()
if self.image is not None:
self.image.remove()
self.image = None
# Refer to Basemap.drawcountries() on how to remove country borders.
# In addition to the matplotlib lines, the loaded country segment data
# needs to be loaded. THE SAME NEEDS TO BE DONE WITH RIVERS ETC.
if self.map_countries is not None:
self.map_countries.remove()
del self.cntrysegs
# map_boundary is None for rectangular projections (basemap simply sets
# the background colour).
if self.map_boundary is not None:
try:
self.map_boundary.remove()
except NotImplementedError as ex:
logging.debug("%s", ex)
self.map_boundary = None
cont_vis = self.appearance["fill_continents"]
self.set_fillcontinents_visible(False)
self.appearance["fill_continents"] = cont_vis
# POSSIBILITY A): Call self.__init__ again with stored keywords.
# Update kwargs if new parameters such as the map region have been
# given.
if kwargs_update:
proj_keys = ["epsg", "projection"]
if any(_x in kwargs_update for _x in proj_keys):
for key in (_x for _x in proj_keys if _x in self.kwargs):
del self.kwargs[key]
self.kwargs.update(kwargs_update)
self.__init__(**self.kwargs)
# TODO: HOW TO MAKE THIS MORE EFFICIENT.
# POSSIBILITY B): Only set the Basemap parameters that influence the
# plot (corner lat/lon, x/y, width/height, ..) and re-define the
# polygons that represent the coastlines etc. In Basemap, they are
# defined in __init__(), at the very bottom (the code that comes
# with the comments
# >> read in coastline polygons, only keeping those that
# >> intersect map boundary polygon.
# ). Basemap only loads the coastline data that is actually displayed.
# If we only change llcrnrlon etc. here and replot coastlines etc.,
# the polygons and the map extent will remain the same.
# However, it should be possible to make a map change WITHOUT changing
# coordinates.
#
# self.llcrnrlon = llcrnrlon
# self.llcrnrlat = llcrnrlat
# self.urcrnrlon = urcrnrlon
# self.urcrnrlat = urcrnrlat
# self.llcrnrx = axis[0]
# self.llcrnry = axis[2]
# self.urcrnrx = axis[1]
# self.urcrnry = axis[3]
def imshow(self, X, **kwargs):
"""
Overloads basemap.imshow(). Deletes any existing image and
redraws the figure after the new image has been plotted.
"""
if self.image is not None:
self.image.remove()
self.image = super(MapCanvas, self).imshow(X, zorder=2, **kwargs)
self.ax.figure.canvas.draw()
return self.image
def gcpoints2(self, lon0, lat0, lon1, lat1, del_s=100., map_coords=True):
"""
The same as basemap.gcpoints(), but takes a distance interval del_s
to space the points instead of a number of points.
"""
# use great circle formula for a perfect sphere.
_, _, dist = self.gc.inv(lon0, lat0, lon1, lat1)
npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))
lonlats = self.gc.npts(lon0, lat0, lon1, lat1, npoints)
lons = [lon0]
lats = [lat0]
for lon, lat in lonlats:
lons.append(lon)
lats.append(lat)
lons.append(lon1)
lats.append(lat1)
if map_coords:
x, y = self(lons, lats)
else:
x, y = (lons, lats)
return x, y
def gcpoints_path(self, lons, lats, del_s=100., map_coords=True):
"""
Same as gcpoints2, but for an entire path, i.e. multiple
line segments. lons and lats are lists of waypoint coordinates.
"""
# use great circle formula for a perfect sphere.
assert len(lons) == len(lats)
assert len(lons) > 1
gclons = [lons[0]]
gclats = [lats[0]]
for i in range(len(lons) - 1):
_, _, dist = self.gc.inv(lons[i], lats[i], lons[i + 1], lats[i + 1])
npoints = int((dist + 0.5 * 1000. * del_s) / (1000. * del_s))
lonlats = []
if npoints > 0:
lonlats = self.gc.npts(lons[i], lats[i], lons[i + 1], lats[i + 1], npoints)
for lon, lat in lonlats:
gclons.append(lon)
gclats.append(lat)
gclons.append(lons[i + 1])
gclats.append(lats[i + 1])
if self.projection == "cyl": # hack for wraparound
lon_min, lon_max = self.llcrnrlon, self.urcrnrlon
gclons = np.array(gclons)
gclons[gclons < lon_min] += 360
gclons[gclons > lon_max] -= 360
idcs = np.where(abs(np.diff(gclons)) > 300)[0]
gclons[idcs] = np.nan
if map_coords:
x, y = self(gclons, gclats)
else:
x, y = (gclons, gclats)
return x, y
def drawgreatcircle_path(self, lons, lats, del_s=100., **kwargs):
"""
"""
x, y = self.gcpoints_path(lons, lats, del_s=del_s)
return self.plot(x, y, **kwargs)
class SatelliteOverpassPatch(object):
"""
Represents a satellite overpass on the top view map (satellite
track and, if available, swath).
"""
# TODO: Derive this class from some Matplotlib actor class? Or create
# a new abstract base class for objects that can be drawn on the
# map -- they all should provide methods remove(), update(),
# etc. update() should automatically remap the object to new map
# coordinates.
def __init__(self, mapcanvas, segment):
"""
"""
self.map = mapcanvas
self.segment = segment
# Filter those time elements that correspond to masked positions -- this
# way the indexes in self.utc correspond to those in self.sat.
# np.ma.getmaskarray is necessary as ..mask only returns a scalar
# "False" if the array contains no masked entries.
self.utc = segment["utc"][~np.ma.getmaskarray(segment["satpos"])[:, 0]]
self.sat = np.ma.compress_rows(segment["satpos"])
self.sw_l = np.ma.compress_rows(segment["swath_left"])
self.sw_r = np.ma.compress_rows(segment["swath_right"])
self.trackline = None
self.patch = None
self.texts = []
self.draw()
def draw(self):
"""
Do the actual plotting of the patch.
"""
# Plot satellite track.
sat = np.copy(self.sat)
sat[:, 0], sat[:, 1] = self.map(sat[:, 0], sat[:, 1])
self.trackline = self.map.plot(sat[:, 0], sat[:, 1], zorder=10,
marker='+', markerfacecolor='g')
# Plot polygon patch that represents the swath of the sensor.
sw_l = self.sw_l
sw_r = self.sw_r
Path = mpath.Path
pathdata = [(Path.MOVETO, self.map(sw_l[0, 0], sw_l[0, 1]))]
for point in sw_l[1:]:
pathdata.append((Path.LINETO, self.map(point[0], point[1])))
for point in sw_r[::-1]:
pathdata.append((Path.LINETO, self.map(point[0], point[1])))
codes, verts = list(zip(*pathdata))
path = mpl_pi.PathH(verts, codes, map=self.map)
patch = mpatches.PathPatch(path, facecolor='yellow',
edgecolor='yellow', alpha=0.4, zorder=10)
self.patch = patch
self.map.ax.add_patch(patch)
# Draw text labels.
self.texts.append(self.map.ax.text(sat[0, 0], sat[0, 1],
self.utc[0].strftime("%H:%M:%S"),
zorder=10,
bbox=dict(facecolor='white',
alpha=0.5,
edgecolor='none')))
self.texts.append(self.map.ax.text(sat[-1, 0], sat[-1, 1],
self.utc[-1].strftime("%H:%M:%S"),
zorder=10,
bbox=dict(facecolor='white',
alpha=0.5,
edgecolor='none')))
self.map.ax.figure.canvas.draw()
def update(self):
"""
Removes the current plot of the patch and redraws the patch.
This is necessary, for instance, when the map projection and/or
extent has been changed.
"""
self.remove()
self.draw()
def remove(self):
"""
Remove this satellite patch from the map canvas.
"""
if self.trackline is not None:
for element in self.trackline:
element.remove()
self.trackline = None
if self.patch is not None:
self.patch.remove()
self.patch = None
for element in self.texts:
# Removal of text elements sometimes fails. I don't know why,
# the plots look fine nevertheless.
try:
element.remove()
except Exception as ex:
logging.error("Wildcard exception caught: %s %s", type(ex), ex)
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=not-callable
import re
import unittest
from unittest import mock
import pytest
from google.cloud.bigquery import DEFAULT_RETRY, DatasetReference, Table, TableReference
from google.cloud.bigquery.dataset import AccessEntry, Dataset, DatasetListItem
from google.cloud.exceptions import NotFound
from parameterized import parameterized
from airflow import AirflowException
from airflow.providers.google.cloud.hooks.bigquery import (
BigQueryCursor,
BigQueryHook,
_api_resource_configs_duplication_check,
_cleanse_time_partitioning,
_split_tablename,
_validate_src_fmt_configs,
_validate_value,
)
PROJECT_ID = "bq-project"
CREDENTIALS = "bq-credentials"
DATASET_ID = "bq_dataset"
TABLE_ID = "bq_table"
PARTITION_ID = "20200101"
VIEW_ID = 'bq_view'
JOB_ID = "1234"
LOCATION = 'europe-north1'
TABLE_REFERENCE_REPR = {
'tableId': TABLE_ID,
'datasetId': DATASET_ID,
'projectId': PROJECT_ID,
}
TABLE_REFERENCE = TableReference.from_api_repr(TABLE_REFERENCE_REPR)
class _BigQueryBaseTestClass(unittest.TestCase):
def setUp(self) -> None:
class MockedBigQueryHook(BigQueryHook):
def _get_credentials_and_project_id(self):
return CREDENTIALS, PROJECT_ID
self.hook = MockedBigQueryHook()
class TestBigQueryHookMethods(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryConnection")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook._authorize")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.build")
def test_bigquery_client_creation(self, mock_build, mock_authorize, mock_bigquery_connection):
result = self.hook.get_conn()
mock_build.assert_called_once_with(
'bigquery', 'v2', http=mock_authorize.return_value, cache_discovery=False
)
mock_bigquery_connection.assert_called_once_with(
service=mock_build.return_value,
project_id=PROJECT_ID,
hook=self.hook,
use_legacy_sql=self.hook.use_legacy_sql,
location=self.hook.location,
num_retries=self.hook.num_retries,
)
assert mock_bigquery_connection.return_value == result
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__")
def test_bigquery_bigquery_conn_id_deprecation_warning(
self,
mock_base_hook_init,
):
bigquery_conn_id = "bigquery conn id"
warning_message = (
"The bigquery_conn_id parameter has been deprecated. "
"You should pass the gcp_conn_id parameter."
)
with pytest.warns(DeprecationWarning) as warnings:
BigQueryHook(bigquery_conn_id=bigquery_conn_id)
mock_base_hook_init.assert_called_once_with(
delegate_to=None,
gcp_conn_id='bigquery conn id',
impersonation_chain=None,
)
assert warning_message == str(warnings[0].message)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_location_propagates_properly(self, run_with_config, _):
# TODO: this creates side effect
assert self.hook.location is None
self.hook.run_query(sql='select 1', location='US')
assert run_with_config.call_count == 1
assert self.hook.location == 'US'
def test_bigquery_insert_rows_not_implemented(self):
with pytest.raises(NotImplementedError):
self.hook.insert_rows(table="table", rows=[1, 2])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_exists_true(self, mock_client):
result = self.hook.table_exists(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_exists_false(self, mock_client):
mock_client.return_value.get_table.side_effect = NotFound("Dataset not found")
result = self.hook.table_exists(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_true(self, mock_client):
mock_client.return_value.list_partitions.return_value = [PARTITION_ID]
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_false_no_table(self, mock_client):
mock_client.return_value.get_table.side_effect = NotFound("Dataset not found")
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_false_no_partition(self, mock_client):
mock_client.return_value.list_partitions.return_value = []
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch('airflow.providers.google.cloud.hooks.bigquery.read_gbq')
def test_get_pandas_df(self, mock_read_gbq):
self.hook.get_pandas_df('select 1')
mock_read_gbq.assert_called_once_with(
'select 1', credentials=CREDENTIALS, dialect='legacy', project_id=PROJECT_ID, verbose=False
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_schema_update_options(self, mock_get_service):
with pytest.raises(
Exception,
match=(
r"\['THIS IS NOT VALID'\] contains invalid schema update options."
r"Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]"
),
):
self.hook.run_load(
"test.test",
"test_schema.json",
["test_data.json"],
schema_update_options=["THIS IS NOT VALID"],
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_schema_update_and_write_disposition(self, mock_get_service):
with pytest.raises(
Exception,
match="schema_update_options is only allowed if"
" write_disposition is 'WRITE_APPEND' or 'WRITE_TRUNCATE'.",
):
self.hook.run_load(
"test.test",
"test_schema.json",
["test_data.json"],
schema_update_options=['ALLOW_FIELD_ADDITION'],
write_disposition='WRITE_EMPTY',
)
@mock.patch(
"airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete",
side_effect=[False, True],
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_cancel_queries(self, mock_client, mock_poll_job_complete):
running_job_id = 3
self.hook.running_job_id = running_job_id
self.hook.cancel_query()
mock_poll_job_complete.has_calls(mock.call(running_job_id), mock.call(running_job_id))
mock_client.assert_called_once_with(project_id=PROJECT_ID, location=None)
mock_client.return_value.cancel_job.assert_called_once_with(job_id=running_job_id)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect_default(
self,
mock_insert,
_,
):
self.hook.run_query('query')
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect(self, mock_insert, _):
self.hook.run_query('query', use_legacy_sql=False)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect_legacy_with_query_params(self, mock_insert, _):
params = [
{
'name': "param_name",
'parameterType': {'type': "STRING"},
'parameterValue': {'value': "param_value"},
}
]
self.hook.run_query('query', use_legacy_sql=False, query_params=params)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_sql_dialect_legacy_with_query_params_fails(self, _):
params = [
{
'name': "param_name",
'parameterType': {'type': "STRING"},
'parameterValue': {'value': "param_value"},
}
]
with pytest.raises(ValueError, match="Query parameters are not allowed when using legacy SQL"):
self.hook.run_query('query', use_legacy_sql=True, query_params=params)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_without_sql_fails(self, _):
with pytest.raises(
TypeError, match=r"`BigQueryBaseCursor.run_query` missing 1 required positional argument: `sql`"
):
self.hook.run_query(sql=None)
@parameterized.expand(
[
(['ALLOW_FIELD_ADDITION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_RELAXATION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_ADDITION'], 'WRITE_TRUNCATE'),
(['ALLOW_FIELD_RELAXATION'], 'WRITE_TRUNCATE'),
(['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'], 'WRITE_TRUNCATE'),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_schema_update_options(
self,
schema_update_options,
write_disposition,
mock_insert,
mock_get_service,
):
self.hook.run_query(
sql='query',
destination_dataset_table='my_dataset.my_table',
schema_update_options=schema_update_options,
write_disposition=write_disposition,
)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['schemaUpdateOptions'] == schema_update_options
assert kwargs['configuration']['query']['writeDisposition'] == write_disposition
@parameterized.expand(
[
(
['INCORRECT_OPTION'],
None,
r"\['INCORRECT_OPTION'\] contains invalid schema update options\. "
r"Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]",
),
(
['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION', 'INCORRECT_OPTION'],
None,
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION', 'INCORRECT_OPTION'\] contains invalid "
r"schema update options\. Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]",
),
(
['ALLOW_FIELD_ADDITION'],
None,
r"schema_update_options is only allowed if write_disposition is "
r"'WRITE_APPEND' or 'WRITE_TRUNCATE'",
),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_schema_update_options_incorrect(
self,
schema_update_options,
write_disposition,
expected_regex,
mock_get_service,
):
with pytest.raises(ValueError, match=expected_regex):
self.hook.run_query(
sql='query',
destination_dataset_table='my_dataset.my_table',
schema_update_options=schema_update_options,
write_disposition=write_disposition,
)
@parameterized.expand([(True,), (False,)])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_api_resource_configs(
self,
bool_val,
mock_insert,
_,
):
self.hook.run_query('query', api_resource_configs={'query': {'useQueryCache': bool_val}})
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useQueryCache'] is bool_val
assert kwargs["configuration"]['query']['useLegacySql'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_api_resource_configs_duplication_warning(self, mock_get_service):
with pytest.raises(
ValueError,
match=(
r"Values of useLegacySql param are duplicated\. api_resource_configs "
r"contained useLegacySql param in `query` config and useLegacySql was "
r"also provided with arg to run_query\(\) method\. Please remove duplicates\."
),
):
self.hook.run_query(
'query', use_legacy_sql=True, api_resource_configs={'query': {'useLegacySql': False}}
)
def test_validate_value(self):
with pytest.raises(
TypeError, match="case_1 argument must have a type <class 'dict'> not <class 'str'>"
):
_validate_value("case_1", "a", dict)
assert _validate_value("case_2", 0, int) is None
def test_duplication_check(self):
with pytest.raises(
ValueError,
match=r"Values of key_one param are duplicated. api_resource_configs contained key_one param in"
r" `query` config and key_one was also provided with arg to run_query\(\) method. "
r"Please remove duplicates.",
):
key_one = True
_api_resource_configs_duplication_check("key_one", key_one, {"key_one": False})
assert _api_resource_configs_duplication_check("key_one", key_one, {"key_one": True}) is None
def test_validate_src_fmt_configs(self):
source_format = "test_format"
valid_configs = ["test_config_known", "compatibility_val"]
backward_compatibility_configs = {"compatibility_val": "val"}
with pytest.raises(
ValueError, match="test_config_unknown is not a valid src_fmt_configs for type test_format."
):
# This config should raise a value error.
src_fmt_configs = {"test_config_unknown": "val"}
_validate_src_fmt_configs(
source_format, src_fmt_configs, valid_configs, backward_compatibility_configs
)
src_fmt_configs = {"test_config_known": "val"}
src_fmt_configs = _validate_src_fmt_configs(
source_format, src_fmt_configs, valid_configs, backward_compatibility_configs
)
assert (
"test_config_known" in src_fmt_configs
), "src_fmt_configs should contain al known src_fmt_configs"
assert (
"compatibility_val" in src_fmt_configs
), "_validate_src_fmt_configs should add backward_compatibility config"
@parameterized.expand([("AVRO",), ("PARQUET",), ("NEWLINE_DELIMITED_JSON",), ("DATASTORE_BACKUP",)])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_non_csv_as_src_fmt(self, fmt, _):
try:
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
source_uris=[],
source_format=fmt,
autodetect=True,
)
except ValueError:
self.fail("run_load() raised ValueError unexpectedly!")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_extract(self, mock_insert):
source_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
destination_cloud_storage_uris = ["gs://bucket/file.csv"]
expected_configuration = {
"extract": {
"sourceTable": {
"projectId": PROJECT_ID,
"datasetId": DATASET_ID,
"tableId": TABLE_ID,
},
"compression": "NONE",
"destinationUris": destination_cloud_storage_uris,
"destinationFormat": "CSV",
"fieldDelimiter": ",",
"printHeader": True,
}
}
self.hook.run_extract(
source_project_dataset_table=source_project_dataset_table,
destination_cloud_storage_uris=destination_cloud_storage_uris,
)
mock_insert.assert_called_once_with(configuration=expected_configuration, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.SchemaField")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_list_rows(self, mock_client, mock_schema, mock_table):
self.hook.list_rows(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
max_results=10,
selected_fields=["field_1", "field_2"],
page_token="page123",
start_index=5,
location=LOCATION,
)
mock_table.from_api_repr.assert_called_once_with({"tableReference": TABLE_REFERENCE_REPR})
mock_schema.has_calls([mock.call(x, "") for x in ["field_1", "field_2"]])
mock_client.return_value.list_rows.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
max_results=10,
selected_fields=mock.ANY,
page_token='page123',
start_index=5,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_list_rows_with_empty_selected_fields(self, mock_client, mock_table):
self.hook.list_rows(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
max_results=10,
page_token="page123",
selected_fields=[],
start_index=5,
location=LOCATION,
)
mock_table.from_api_repr.assert_called_once_with({"tableReference": TABLE_REFERENCE_REPR})
mock_client.return_value.list_rows.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
max_results=10,
page_token='page123',
selected_fields=None,
start_index=5,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_run_table_delete(self, mock_client, mock_table):
source_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
self.hook.run_table_delete(source_project_dataset_table, ignore_if_missing=False)
mock_table.from_string.assert_called_once_with(source_project_dataset_table)
mock_client.return_value.delete_table.assert_called_once_with(
table=mock_table.from_string.return_value, not_found_ok=False
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset_tables")
def test_table_upsert_create_new_table(self, mock_get, mock_create):
table_resource = {"tableReference": {"tableId": TABLE_ID}}
mock_get.return_value = []
self.hook.run_table_upsert(dataset_id=DATASET_ID, table_resource=table_resource)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
mock_create.assert_called_once_with(table_resource=table_resource, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset_tables")
def test_table_upsert_already_exists(self, mock_get, mock_update):
table_resource = {"tableReference": {"tableId": TABLE_ID}}
mock_get.return_value = [{"tableId": TABLE_ID}]
self.hook.run_table_upsert(dataset_id=DATASET_ID, table_resource=table_resource)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
mock_update.assert_called_once_with(table_resource=table_resource)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_dataset")
def test_run_grant_dataset_view_access_granting(self, mock_update, mock_get):
view_table = f"{TABLE_ID}_view"
view_dataset = f"{DATASET_ID}_view"
view_access = AccessEntry(
role=None,
entity_type="view",
entity_id={'projectId': PROJECT_ID, 'datasetId': view_dataset, 'tableId': view_table},
)
dataset = Dataset(DatasetReference.from_string(DATASET_ID, PROJECT_ID))
dataset.access_entries = []
mock_get.return_value = dataset
self.hook.run_grant_dataset_view_access(
source_dataset=DATASET_ID, view_dataset=view_dataset, view_table=view_table
)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
assert view_access in dataset.access_entries
mock_update.assert_called_once_with(
fields=["access"],
dataset_resource=dataset.to_api_repr(),
project_id=PROJECT_ID,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_dataset")
def test_run_grant_dataset_view_access_already_granted(self, mock_update, mock_get):
view_table = f"{TABLE_ID}_view"
view_dataset = f"{DATASET_ID}_view"
view_access = AccessEntry(
role=None,
entity_type="view",
entity_id={'projectId': PROJECT_ID, 'datasetId': view_dataset, 'tableId': view_table},
)
dataset = Dataset(DatasetReference.from_string(DATASET_ID, PROJECT_ID))
dataset.access_entries = [view_access]
mock_get.return_value = dataset
self.hook.run_grant_dataset_view_access(
source_dataset=DATASET_ID, view_dataset=view_dataset, view_table=view_table
)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
assert len(mock_update.calls) == 0
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_dataset_tables_list(self, mock_client):
table_list = [
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "a-1"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "b-1"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "a-2"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "b-2"},
]
table_list_response = [Table.from_api_repr({"tableReference": t}) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables_list(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference, max_results=None
)
assert table_list == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_poll_job_complete(self, mock_client):
self.hook.poll_job_complete(job_id=JOB_ID, location=LOCATION, project_id=PROJECT_ID)
mock_client.assert_called_once_with(location=LOCATION, project_id=PROJECT_ID)
mock_client.return_value.get_job.assert_called_once_with(job_id=JOB_ID)
mock_client.return_value.get_job.return_value.done.assert_called_once_with(retry=DEFAULT_RETRY)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("logging.Logger.info")
def test_cancel_query_jobs_to_cancel(
self,
mock_logger_info,
poll_job_complete,
):
poll_job_complete.return_value = True
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
poll_job_complete.assert_called_once_with(job_id=JOB_ID)
mock_logger_info.has_call(mock.call("No running BigQuery jobs to cancel."))
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("time.sleep")
@mock.patch("logging.Logger.info")
def test_cancel_query_cancel_timeout(
self,
mock_logger_info,
mock_sleep,
poll_job_complete,
mock_client,
):
poll_job_complete.side_effect = [False] * 13
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
mock_client.return_value.cancel_job.assert_called_once_with(job_id=JOB_ID)
assert poll_job_complete.call_count == 13
assert mock_sleep.call_count == 11
mock_logger_info.has_call(
mock.call(
f"Stopping polling due to timeout. Job with id {JOB_ID} "
"has not completed cancel and may or may not finish."
)
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("time.sleep")
@mock.patch("logging.Logger.info")
def test_cancel_query_cancel_completed(
self,
mock_logger_info,
mock_sleep,
poll_job_complete,
mock_client,
):
poll_job_complete.side_effect = [False] * 12 + [True]
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
mock_client.return_value.cancel_job.assert_called_once_with(job_id=JOB_ID)
assert poll_job_complete.call_count == 13
assert mock_sleep.call_count == 11
mock_logger_info.has_call(mock.call(f"Job successfully canceled: {PROJECT_ID}, {PROJECT_ID}"))
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_schema(self, mock_client):
table = {
"tableReference": TABLE_REFERENCE_REPR,
"schema": {
"fields": [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
]
},
}
mock_client.return_value.get_table.return_value = Table.from_api_repr(table)
result = self.hook.get_schema(dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
assert "fields" in result
assert len(result["fields"]) == 2
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_source_format(self, mock_get_service):
with pytest.raises(
Exception,
match=r"JSON is not a valid source format. Please use one of the following types: \['CSV', "
r"'NEWLINE_DELIMITED_JSON', 'AVRO', 'GOOGLE_SHEETS', 'DATASTORE_BACKUP', 'PARQUET'\]",
):
self.hook.run_load("test.test", "test_schema.json", ["test_data.json"], source_format="json")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_insert_all_succeed(self, mock_client):
rows = [{"json": {"a_key": "a_value_0"}}]
self.hook.insert_all(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
rows=rows,
ignore_unknown_values=True,
skip_invalid_rows=True,
)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.return_value.insert_rows.assert_called_once_with(
table=mock_client.return_value.get_table.return_value,
rows=rows,
ignore_unknown_values=True,
skip_invalid_rows=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_insert_all_fail(self, mock_client):
rows = [{"json": {"a_key": "a_value_0"}}]
mock_client.return_value.insert_rows.return_value = ["some", "errors"]
with pytest.raises(AirflowException, match="insert error"):
self.hook.insert_all(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, rows=rows, fail_on_error=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table='my_dataset.my_table',
labels={'label1': 'test1', 'label2': 'test2'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['labels'] == {'label1': 'test1', 'label2': 'test2'}
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.QueryJob")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_insert_job(self, mock_client, mock_query_job):
job_conf = {
"query": {
"query": "SELECT * FROM test",
"useLegacySql": "False",
}
}
mock_query_job._JOB_TYPE = "query"
self.hook.insert_job(
configuration=job_conf,
job_id=JOB_ID,
project_id=PROJECT_ID,
location=LOCATION,
)
mock_client.assert_called_once_with(
project_id=PROJECT_ID,
location=LOCATION,
)
mock_query_job.from_api_repr.assert_called_once_with(
{
'configuration': job_conf,
'jobReference': {'jobId': JOB_ID, 'projectId': PROJECT_ID, 'location': LOCATION},
},
mock_client.return_value,
)
mock_query_job.from_api_repr.return_value.result.assert_called_once_with()
class TestBigQueryTableSplitter(unittest.TestCase):
def test_internal_need_default_project(self):
with pytest.raises(Exception, match="INTERNAL: No default project is specified"):
_split_tablename("dataset.table", None)
@parameterized.expand(
[
("project", "dataset", "table", "dataset.table"),
("alternative", "dataset", "table", "alternative:dataset.table"),
("alternative", "dataset", "table", "alternative.dataset.table"),
("alt1:alt", "dataset", "table", "alt1:alt.dataset.table"),
("alt1:alt", "dataset", "table", "alt1:alt:dataset.table"),
]
)
def test_split_tablename(self, project_expected, dataset_expected, table_expected, table_input):
default_project_id = "project"
project, dataset, table = _split_tablename(table_input, default_project_id)
assert project_expected == project
assert dataset_expected == dataset
assert table_expected == table
@parameterized.expand(
[
("alt1:alt2:alt3:dataset.table", None, "Use either : or . to specify project got {}"),
(
"alt1.alt.dataset.table",
None,
r"Expect format of \(<project\.\|<project\:\)<dataset>\.<table>, got {}",
),
(
"alt1:alt2:alt.dataset.table",
"var_x",
"Format exception for var_x: Use either : or . to specify project got {}",
),
(
"alt1:alt2:alt:dataset.table",
"var_x",
"Format exception for var_x: Use either : or . to specify project got {}",
),
(
"alt1.alt.dataset.table",
"var_x",
r"Format exception for var_x: Expect format of "
r"\(<project\.\|<project:\)<dataset>.<table>, got {}",
),
]
)
def test_invalid_syntax(self, table_input, var_name, exception_message):
default_project_id = "project"
with pytest.raises(Exception, match=exception_message.format(table_input)):
_split_tablename(table_input, default_project_id, var_name)
class TestTableOperations(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_view(self, mock_bq_client, mock_table):
view = {
'query': 'SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*`',
"useLegacySql": False,
}
self.hook.create_empty_table(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, view=view, retry=DEFAULT_RETRY
)
body = {'tableReference': TABLE_REFERENCE_REPR, 'view': view}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_patch_table(self, mock_client, mock_table):
description_patched = 'Test description.'
expiration_time_patched = 2524608000000
friendly_name_patched = 'Test friendly name.'
labels_patched = {'label1': 'test1', 'label2': 'test2'}
schema_patched = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'balance', 'type': 'FLOAT', 'mode': 'NULLABLE'},
{'name': 'new_field', 'type': 'STRING', 'mode': 'NULLABLE'},
]
time_partitioning_patched = {'expirationMs': 10000000}
require_partition_filter_patched = True
view_patched = {
'query': "SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*` LIMIT 500",
'useLegacySql': False,
}
self.hook.patch_table(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
project_id=PROJECT_ID,
description=description_patched,
expiration_time=expiration_time_patched,
friendly_name=friendly_name_patched,
labels=labels_patched,
schema=schema_patched,
time_partitioning=time_partitioning_patched,
require_partition_filter=require_partition_filter_patched,
view=view_patched,
)
body = {
"description": description_patched,
"expirationTime": expiration_time_patched,
"friendlyName": friendly_name_patched,
"labels": labels_patched,
"schema": {"fields": schema_patched},
"timePartitioning": time_partitioning_patched,
"view": view_patched,
"requirePartitionFilter": require_partition_filter_patched,
}
fields = list(body.keys())
body["tableReference"] = TABLE_REFERENCE_REPR
mock_table.from_api_repr.assert_called_once_with(body)
mock_client.return_value.update_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, fields=fields
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_succeed(self, mock_bq_client, mock_table):
self.hook.create_empty_table(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
body = {
'tableReference': {
'tableId': TABLE_ID,
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
}
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, exists_ok=True, retry=DEFAULT_RETRY
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_with_extras_succeed(self, mock_bq_client, mock_table):
schema_fields = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'created', 'type': 'DATE', 'mode': 'REQUIRED'},
]
time_partitioning = {"field": "created", "type": "DAY"}
cluster_fields = ['name']
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
schema_fields=schema_fields,
time_partitioning=time_partitioning,
cluster_fields=cluster_fields,
)
body = {
'tableReference': {
'tableId': TABLE_ID,
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
},
'schema': {'fields': schema_fields},
'timePartitioning': time_partitioning,
'clustering': {'fields': cluster_fields},
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, exists_ok=True, retry=DEFAULT_RETRY
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_tables_list(self, mock_client):
table_list = [
{
"kind": "bigquery#table",
"id": "your-project:your_dataset.table1",
"tableReference": {
"projectId": "your-project",
"datasetId": "your_dataset",
"tableId": "table1",
},
"type": "TABLE",
"creationTime": "1565781859261",
},
{
"kind": "bigquery#table",
"id": "your-project:your_dataset.table2",
"tableReference": {
"projectId": "your-project",
"datasetId": "your_dataset",
"tableId": "table2",
},
"type": "TABLE",
"creationTime": "1565782713480",
},
]
table_list_response = [Table.from_api_repr(t) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference,
max_results=None,
retry=DEFAULT_RETRY,
)
for res, exp in zip(result, table_list):
assert res["tableId"] == exp["tableReference"]["tableId"]
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_materialized_view(self, mock_bq_client, mock_table):
query = """
SELECT product, SUM(amount)
FROM `test-project-id.test_dataset_id.test_table_prefix*`
GROUP BY product
"""
materialized_view = {
'query': query,
'enableRefresh': True,
'refreshIntervalMs': 2000000,
}
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
materialized_view=materialized_view,
retry=DEFAULT_RETRY,
)
body = {'tableReference': TABLE_REFERENCE_REPR, 'materializedView': materialized_view}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
class TestBigQueryCursor(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_execute_with_parameters(self, mock_insert, _):
bq_cursor = self.hook.get_cursor()
bq_cursor.execute("SELECT %(foo)s", {"foo": "bar"})
conf = {
'query': {
'query': "SELECT 'bar'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
}
mock_insert.assert_called_once_with(configuration=conf, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_execute_many(self, mock_insert, _):
bq_cursor = self.hook.get_cursor()
bq_cursor.executemany("SELECT %(foo)s", [{"foo": "bar"}, {"foo": "baz"}])
assert mock_insert.call_count == 2
assert mock_insert.has_calls(
mock.call(
configuration={
'query': {
'query': "SELECT 'bar'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
},
project_id=PROJECT_ID,
),
mock.call(
configuration={
'query': {
'query': "SELECT 'baz'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
},
project_id=PROJECT_ID,
),
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_description(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
with pytest.raises(NotImplementedError):
bq_cursor.description
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_close(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.close() # pylint: disable=assignment-from-no-return
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_rowcount(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.rowcount
assert -1 == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.next")
def test_fetchone(self, mock_next, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.fetchone()
mock_next.call_count == 1
assert mock_next.return_value == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch(
"airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.fetchone", side_effect=[1, 2, 3, None]
)
def test_fetchall(self, mock_fetchone, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.fetchall()
assert [1, 2, 3] == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.fetchone")
def test_fetchmany(self, mock_fetchone, mock_get_service):
side_effect_values = [1, 2, 3, None]
bq_cursor = self.hook.get_cursor()
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany()
assert [1] == result
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany(2)
assert [1, 2] == result
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany(5)
assert [1, 2, 3] == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next_no_jobid(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = None
result = bq_cursor.next()
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next_buffer(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
bq_cursor.buffer = [1, 2]
result = bq_cursor.next()
assert 1 == result
result = bq_cursor.next()
assert 2 == result
bq_cursor.all_pages_loaded = True
result = bq_cursor.next()
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next(self, mock_get_service):
mock_get_query_results = mock_get_service.return_value.jobs.return_value.getQueryResults
mock_execute = mock_get_query_results.return_value.execute
mock_execute.return_value = {
"rows": [
{"f": [{"v": "one"}, {"v": 1}]},
{"f": [{"v": "two"}, {"v": 2}]},
],
"pageToken": None,
"schema": {
"fields": [
{"name": "field_1", "type": "STRING"},
{"name": "field_2", "type": "INTEGER"},
]
},
}
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
bq_cursor.location = LOCATION
result = bq_cursor.next()
assert ['one', 1] == result
result = bq_cursor.next()
assert ['two', 2] == result
mock_get_query_results.assert_called_once_with(
jobId=JOB_ID, location=LOCATION, pageToken=None, projectId='bq-project'
)
mock_execute.assert_called_once_with(num_retries=bq_cursor.num_retries)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.flush_results")
def test_next_no_rows(self, mock_flush_results, mock_get_service):
mock_get_query_results = mock_get_service.return_value.jobs.return_value.getQueryResults
mock_execute = mock_get_query_results.return_value.execute
mock_execute.return_value = {}
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
result = bq_cursor.next()
assert result is None
mock_get_query_results.assert_called_once_with(
jobId=JOB_ID, location=None, pageToken=None, projectId='bq-project'
)
mock_execute.assert_called_once_with(num_retries=bq_cursor.num_retries)
assert mock_flush_results.call_count == 1
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.flush_results")
def test_flush_cursor_in_execute(self, _, mock_insert, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.execute("SELECT %(foo)s", {"foo": "bar"})
assert mock_insert.call_count == 1
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_flush_cursor(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.page_token = '456dcea9-fcbf-4f02-b570-83f5297c685e'
bq_cursor.job_id = 'c0a79ae4-0e72-4593-a0d0-7dbbf726f193'
bq_cursor.all_pages_loaded = True
bq_cursor.buffer = [('a', 100, 200), ('b', 200, 300)]
bq_cursor.flush_results()
assert bq_cursor.page_token is None
assert bq_cursor.job_id is None
assert not bq_cursor.all_pages_loaded
assert bq_cursor.buffer == []
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_arraysize(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
assert bq_cursor.buffersize is None
assert bq_cursor.arraysize == 1
bq_cursor.set_arraysize(10)
assert bq_cursor.buffersize == 10
assert bq_cursor.arraysize == 10
class TestDatasetsOperations(_BigQueryBaseTestClass):
def test_create_empty_dataset_no_dataset_id_err(self):
with pytest.raises(ValueError, match=r"Please specify `datasetId`"):
self.hook.create_empty_dataset(dataset_id=None, project_id=None)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_with_params(self, mock_client, mock_dataset):
self.hook.create_empty_dataset(project_id=PROJECT_ID, dataset_id=DATASET_ID, location=LOCATION)
expected_body = {
"location": LOCATION,
"datasetReference": {"datasetId": DATASET_ID, "projectId": PROJECT_ID},
}
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(expected_body)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_with_object(self, mock_client, mock_dataset):
dataset = {
"location": "LOCATION",
"datasetReference": {"datasetId": "DATASET_ID", "projectId": "PROJECT_ID"},
}
self.hook.create_empty_dataset(dataset_reference=dataset)
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(dataset)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_use_values_from_object(self, mock_client, mock_dataset):
dataset = {
"location": "LOCATION",
"datasetReference": {"datasetId": "DATASET_ID", "projectId": "PROJECT_ID"},
}
self.hook.create_empty_dataset(
dataset_reference=dataset,
location="Unknown location",
dataset_id="Fashionable Dataset",
project_id="Amazing Project",
)
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(dataset)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_dataset(self, mock_client):
_expected_result = {
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
}
expected_result = Dataset.from_api_repr(_expected_result)
mock_client.return_value.get_dataset.return_value = expected_result
result = self.hook.get_dataset(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.get_dataset.assert_called_once_with(
dataset_ref=DatasetReference(PROJECT_ID, DATASET_ID)
)
assert result == expected_result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_datasets_list(self, mock_client):
datasets = [
{
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
},
{
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_1_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_1_test"},
},
]
return_value = [DatasetListItem(d) for d in datasets]
mock_client.return_value.list_datasets.return_value = return_value
result = self.hook.get_datasets_list(project_id=PROJECT_ID)
mock_client.return_value.list_datasets.assert_called_once_with(
project=PROJECT_ID,
include_all=False,
filter=None,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
)
for exp, res in zip(datasets, result):
assert res.full_dataset_id == exp["id"]
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_delete_dataset(self, mock_client):
delete_contents = True
self.hook.delete_dataset(
project_id=PROJECT_ID, dataset_id=DATASET_ID, delete_contents=delete_contents
)
mock_client.return_value.delete_dataset.assert_called_once_with(
dataset=DatasetReference(PROJECT_ID, DATASET_ID),
delete_contents=delete_contents,
retry=DEFAULT_RETRY,
not_found_ok=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_patch_dataset(self, mock_get_service):
dataset_resource = {"access": [{"role": "WRITER", "groupByEmail": "cloud-logs@google.com"}]}
method = mock_get_service.return_value.datasets.return_value.patch
self.hook.patch_dataset(
dataset_id=DATASET_ID, project_id=PROJECT_ID, dataset_resource=dataset_resource
)
method.assert_called_once_with(projectId=PROJECT_ID, datasetId=DATASET_ID, body=dataset_resource)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_update_dataset(self, mock_client, mock_dataset):
dataset_resource = {
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
}
method = mock_client.return_value.update_dataset
dataset = Dataset.from_api_repr(dataset_resource)
mock_dataset.from_api_repr.return_value = dataset
method.return_value = dataset
result = self.hook.update_dataset(
dataset_id=DATASET_ID,
project_id=PROJECT_ID,
dataset_resource=dataset_resource,
fields=["location"],
)
mock_dataset.from_api_repr.assert_called_once_with(dataset_resource)
method.assert_called_once_with(
dataset=dataset,
fields=["location"],
retry=DEFAULT_RETRY,
)
assert result == dataset
class TestTimePartitioningInRunJob(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_default(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load'].get('timePartitioning') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_with_auto_detect(self, mock_insert):
destination_project_dataset_table = "autodetect.table"
self.hook.run_load(destination_project_dataset_table, [], [], autodetect=True)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['autodetect'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_arg(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table=f"{DATASET_ID}.{TABLE_ID}",
schema_fields=[],
source_uris=[],
time_partitioning={'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
)
configuration = {
'load': {
'autodetect': False,
'createDisposition': 'CREATE_IF_NEEDED',
'destinationTable': {'projectId': PROJECT_ID, 'datasetId': DATASET_ID, 'tableId': TABLE_ID},
'sourceFormat': 'CSV',
'sourceUris': [],
'writeDisposition': 'WRITE_EMPTY',
'ignoreUnknownValues': False,
'timePartitioning': {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
'skipLeadingRows': 0,
'fieldDelimiter': ',',
'quote': None,
'allowQuotedNewlines': False,
'encoding': 'UTF-8',
}
}
mock_insert.assert_called_once_with(configuration=configuration, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table=f"{DATASET_ID}.{TABLE_ID}",
time_partitioning={'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
)
configuration = {
'query': {
'query': 'select 1',
'priority': 'INTERACTIVE',
'useLegacySql': True,
'timePartitioning': {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
'schemaUpdateOptions': [],
'destinationTable': {'projectId': PROJECT_ID, 'datasetId': DATASET_ID, 'tableId': TABLE_ID},
'allowLargeResults': False,
'flattenResults': None,
'writeDisposition': 'WRITE_EMPTY',
'createDisposition': 'CREATE_IF_NEEDED',
}
}
mock_insert.assert_called_once_with(configuration=configuration, project_id=PROJECT_ID)
def test_dollar_makes_partition(self):
tp_out = _cleanse_time_partitioning('test.teast$20170101', {})
expect = {'type': 'DAY'}
assert tp_out == expect
def test_extra_time_partitioning_options(self):
tp_out = _cleanse_time_partitioning(
'test.teast', {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000}
)
expect = {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000}
assert tp_out == expect
class TestClusteringInRunJob(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_default(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load'].get('clustering') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_arg(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
cluster_fields=['field1', 'field2'],
time_partitioning={'type': 'DAY'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['clustering'] == {'fields': ['field1', 'field2']}
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_default(self, mock_insert):
self.hook.run_query(sql='select 1')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query'].get('clustering') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table='my_dataset.my_table',
cluster_fields=['field1', 'field2'],
time_partitioning={'type': 'DAY'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['clustering'] == {'fields': ['field1', 'field2']}
class TestBigQueryHookLegacySql(_BigQueryBaseTestClass):
"""Ensure `use_legacy_sql` param in `BigQueryHook` propagates properly."""
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_hook_uses_legacy_sql_by_default(self, mock_insert, _):
self.hook.get_first('query')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useLegacySql'] is True
@mock.patch(
'airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials_and_project_id',
return_value=(CREDENTIALS, PROJECT_ID),
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_legacy_sql_override_propagates_properly(
self, mock_insert, mock_get_service, mock_get_creds_and_proj_id
):
bq_hook = BigQueryHook(use_legacy_sql=False)
bq_hook.get_first('query')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useLegacySql'] is False
class TestBigQueryHookRunWithConfiguration(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.LoadJob")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_run_with_configuration_location(self, mock_client, mock_job):
running_job_id = 'job_vjdi28vskdui2onru23'
location = 'asia-east1'
mock_job._JOB_TYPE = "load"
conf = {"load": {}}
self.hook.running_job_id = running_job_id
self.hook.location = location
self.hook.run_with_configuration(conf)
mock_client.assert_called_once_with(project_id=PROJECT_ID, location=location)
mock_job.from_api_repr.assert_called_once_with(
{
"configuration": conf,
"jobReference": {"jobId": mock.ANY, "projectId": PROJECT_ID, "location": location},
},
mock_client.return_value,
)
class TestBigQueryWithKMS(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_with_kms(self, mock_bq_client, mock_table):
schema_fields = [{"name": "id", "type": "STRING", "mode": "REQUIRED"}]
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
schema_fields=schema_fields,
encryption_configuration=encryption_configuration,
)
body = {
"tableReference": {"tableId": TABLE_ID, 'projectId': PROJECT_ID, 'datasetId': DATASET_ID},
"schema": {"fields": schema_fields},
"encryptionConfiguration": encryption_configuration,
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
# pylint: disable=too-many-locals
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_with_kms(self, mock_create):
external_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
source_uris = ['test_data.csv']
source_format = 'CSV'
autodetect = False
compression = 'NONE'
ignore_unknown_values = False
max_bad_records = 10
skip_leading_rows = 1
field_delimiter = ','
quote_character = None
allow_quoted_newlines = False
allow_jagged_rows = False
encoding = "UTF-8"
labels = {'label1': 'test1', 'label2': 'test2'}
schema_fields = [{'mode': 'REQUIRED', 'name': 'id', 'type': 'STRING', 'description': None}]
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.create_external_table(
external_project_dataset_table=external_project_dataset_table,
source_uris=source_uris,
source_format=source_format,
autodetect=autodetect,
compression=compression,
ignore_unknown_values=ignore_unknown_values,
max_bad_records=max_bad_records,
skip_leading_rows=skip_leading_rows,
field_delimiter=field_delimiter,
quote_character=quote_character,
allow_jagged_rows=allow_jagged_rows,
encoding=encoding,
allow_quoted_newlines=allow_quoted_newlines,
labels=labels,
schema_fields=schema_fields,
encryption_configuration=encryption_configuration,
)
body = {
'externalDataConfiguration': {
'autodetect': autodetect,
'sourceFormat': source_format,
'sourceUris': source_uris,
'compression': compression,
'ignoreUnknownValues': ignore_unknown_values,
'schema': {'fields': schema_fields},
'maxBadRecords': max_bad_records,
'csvOptions': {
'skipLeadingRows': skip_leading_rows,
'fieldDelimiter': field_delimiter,
'quote': quote_character,
'allowQuotedNewlines': allow_quoted_newlines,
'allowJaggedRows': allow_jagged_rows,
'encoding': encoding,
},
},
'tableReference': {
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
'tableId': TABLE_ID,
},
'labels': labels,
"encryptionConfiguration": encryption_configuration,
}
mock_create.assert_called_once_with(
table_resource=body,
project_id=PROJECT_ID,
location=None,
exists_ok=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_update_table(self, mock_client, mock_table):
description_patched = 'Test description.'
expiration_time_patched = 2524608000000
friendly_name_patched = 'Test friendly name.'
labels_patched = {'label1': 'test1', 'label2': 'test2'}
schema_patched = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'balance', 'type': 'FLOAT', 'mode': 'NULLABLE'},
{'name': 'new_field', 'type': 'STRING', 'mode': 'NULLABLE'},
]
time_partitioning_patched = {'expirationMs': 10000000}
require_partition_filter_patched = True
view_patched = {
'query': "SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*` LIMIT 500",
'useLegacySql': False,
}
body = {
"tableReference": {
"projectId": PROJECT_ID,
"datasetId": DATASET_ID,
"tableId": TABLE_ID,
},
"description": description_patched,
"expirationTime": expiration_time_patched,
"friendlyName": friendly_name_patched,
"labels": labels_patched,
"schema": {"fields": schema_patched},
"timePartitioning": time_partitioning_patched,
"view": view_patched,
"requirePartitionFilter": require_partition_filter_patched,
}
fields = list(body.keys())
self.hook.update_table(
table_resource=body,
fields=fields,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
project_id=PROJECT_ID,
)
mock_table.from_api_repr.assert_called_once_with(body)
mock_client.return_value.update_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, fields=fields
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_query(sql='query', encryption_configuration=encryption_configuration)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['query']['destinationEncryptionConfiguration'] is encryption_configuration
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_copy_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_copy(
source_project_dataset_tables='p.d.st',
destination_project_dataset_table='p.d.dt',
encryption_configuration=encryption_configuration,
)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['copy']['destinationEncryptionConfiguration'] is encryption_configuration
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_load(
destination_project_dataset_table='p.d.dt',
source_uris=['abc.csv'],
autodetect=True,
encryption_configuration=encryption_configuration,
)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['load']['destinationEncryptionConfiguration'] is encryption_configuration
)
class TestBigQueryBaseCursorMethodsDeprecationWarning(unittest.TestCase):
@parameterized.expand(
[
("create_empty_table",),
("create_empty_dataset",),
("get_dataset_tables",),
("delete_dataset",),
("create_external_table",),
("patch_table",),
("insert_all",),
("update_dataset",),
("patch_dataset",),
("get_dataset_tables_list",),
("get_datasets_list",),
("get_dataset",),
("run_grant_dataset_view_access",),
("run_table_upsert",),
("run_table_delete",),
("get_tabledata",),
("get_schema",),
("poll_job_complete",),
("cancel_query",),
("run_with_configuration",),
("run_load",),
("run_copy",),
("run_extract",),
("run_query",),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook")
def test_deprecation_warning(self, func_name, mock_bq_hook):
args, kwargs = [1], {"param1": "val1"}
new_path = re.escape(f"`airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.{func_name}`")
message_pattern = fr"This method is deprecated\.\s+Please use {new_path}"
message_regex = re.compile(message_pattern, re.MULTILINE)
mocked_func = getattr(mock_bq_hook, func_name)
bq_cursor = BigQueryCursor(mock.MagicMock(), PROJECT_ID, mock_bq_hook)
func = getattr(bq_cursor, func_name)
with pytest.warns(DeprecationWarning, match=message_regex):
_ = func(*args, **kwargs)
mocked_func.assert_called_once_with(*args, **kwargs)
assert re.search(f".*{new_path}.*", func.__doc__)
class TestBigQueryWithLabelsAndDescription(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_labels(self, mock_insert):
labels = {'label1': 'test1', 'label2': 'test2'}
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
labels=labels,
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['destinationTableProperties']['labels'] is labels
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_description(self, mock_insert):
description = "Test Description"
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
description=description,
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['destinationTableProperties']['description'] is description
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_labels(self, mock_create):
labels = {'label1': 'test1', 'label2': 'test2'}
self.hook.create_external_table(
external_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
labels=labels,
)
_, kwargs = mock_create.call_args
self.assertDictEqual(kwargs['table_resource']['labels'], labels)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_description(self, mock_create):
description = "Test Description"
self.hook.create_external_table(
external_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
description=description,
)
_, kwargs = mock_create.call_args
assert kwargs['table_resource']['description'] is description
| #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=not-callable
import re
import unittest
from unittest import mock
import pytest
from google.cloud.bigquery import DEFAULT_RETRY, DatasetReference, Table, TableReference
from google.cloud.bigquery.dataset import AccessEntry, Dataset, DatasetListItem
from google.cloud.exceptions import NotFound
from parameterized import parameterized
from airflow import AirflowException
from airflow.providers.google.cloud.hooks.bigquery import (
BigQueryCursor,
BigQueryHook,
_api_resource_configs_duplication_check,
_cleanse_time_partitioning,
_split_tablename,
_validate_src_fmt_configs,
_validate_value,
)
PROJECT_ID = "bq-project"
CREDENTIALS = "bq-credentials"
DATASET_ID = "bq_dataset"
TABLE_ID = "bq_table"
PARTITION_ID = "20200101"
VIEW_ID = 'bq_view'
JOB_ID = "1234"
LOCATION = 'europe-north1'
TABLE_REFERENCE_REPR = {
'tableId': TABLE_ID,
'datasetId': DATASET_ID,
'projectId': PROJECT_ID,
}
TABLE_REFERENCE = TableReference.from_api_repr(TABLE_REFERENCE_REPR)
class _BigQueryBaseTestClass(unittest.TestCase):
def setUp(self) -> None:
class MockedBigQueryHook(BigQueryHook):
def _get_credentials_and_project_id(self):
return CREDENTIALS, PROJECT_ID
self.hook = MockedBigQueryHook()
class TestBigQueryHookMethods(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryConnection")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook._authorize")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.build")
def test_bigquery_client_creation(self, mock_build, mock_authorize, mock_bigquery_connection):
result = self.hook.get_conn()
mock_build.assert_called_once_with(
'bigquery', 'v2', http=mock_authorize.return_value, cache_discovery=False
)
mock_bigquery_connection.assert_called_once_with(
service=mock_build.return_value,
project_id=PROJECT_ID,
hook=self.hook,
use_legacy_sql=self.hook.use_legacy_sql,
location=self.hook.location,
num_retries=self.hook.num_retries,
)
assert mock_bigquery_connection.return_value == result
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__")
def test_bigquery_bigquery_conn_id_deprecation_warning(
self,
mock_base_hook_init,
):
bigquery_conn_id = "bigquery conn id"
warning_message = (
"The bigquery_conn_id parameter has been deprecated. "
"You should pass the gcp_conn_id parameter."
)
with pytest.warns(DeprecationWarning) as warnings:
BigQueryHook(bigquery_conn_id=bigquery_conn_id)
mock_base_hook_init.assert_called_once_with(
delegate_to=None,
gcp_conn_id='bigquery conn id',
impersonation_chain=None,
)
assert warning_message == str(warnings[0].message)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_location_propagates_properly(self, run_with_config, _):
# TODO: this creates side effect
assert self.hook.location is None
self.hook.run_query(sql='select 1', location='US')
assert run_with_config.call_count == 1
assert self.hook.location == 'US'
def test_bigquery_insert_rows_not_implemented(self):
with pytest.raises(NotImplementedError):
self.hook.insert_rows(table="table", rows=[1, 2])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_exists_true(self, mock_client):
result = self.hook.table_exists(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_exists_false(self, mock_client):
mock_client.return_value.get_table.side_effect = NotFound("Dataset not found")
result = self.hook.table_exists(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_true(self, mock_client):
mock_client.return_value.list_partitions.return_value = [PARTITION_ID]
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_false_no_table(self, mock_client):
mock_client.return_value.get_table.side_effect = NotFound("Dataset not found")
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_bigquery_table_partition_exists_false_no_partition(self, mock_client):
mock_client.return_value.list_partitions.return_value = []
result = self.hook.table_partition_exists(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, partition_id=PARTITION_ID
)
mock_client.return_value.list_partitions.assert_called_once_with(TABLE_REFERENCE)
mock_client.assert_called_once_with(project_id=PROJECT_ID)
assert result is False
@mock.patch('airflow.providers.google.cloud.hooks.bigquery.read_gbq')
def test_get_pandas_df(self, mock_read_gbq):
self.hook.get_pandas_df('select 1')
mock_read_gbq.assert_called_once_with(
'select 1', credentials=CREDENTIALS, dialect='legacy', project_id=PROJECT_ID, verbose=False
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_schema_update_options(self, mock_get_service):
with pytest.raises(
Exception,
match=(
r"\['THIS IS NOT VALID'\] contains invalid schema update options."
r"Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]"
),
):
self.hook.run_load(
"test.test",
"test_schema.json",
["test_data.json"],
schema_update_options=["THIS IS NOT VALID"],
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_schema_update_and_write_disposition(self, mock_get_service):
with pytest.raises(
Exception,
match="schema_update_options is only allowed if"
" write_disposition is 'WRITE_APPEND' or 'WRITE_TRUNCATE'.",
):
self.hook.run_load(
"test.test",
"test_schema.json",
["test_data.json"],
schema_update_options=['ALLOW_FIELD_ADDITION'],
write_disposition='WRITE_EMPTY',
)
@mock.patch(
"airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete",
side_effect=[False, True],
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_cancel_queries(self, mock_client, mock_poll_job_complete):
running_job_id = 3
self.hook.running_job_id = running_job_id
self.hook.cancel_query()
mock_poll_job_complete.has_calls(mock.call(running_job_id), mock.call(running_job_id))
mock_client.assert_called_once_with(project_id=PROJECT_ID, location=None)
mock_client.return_value.cancel_job.assert_called_once_with(job_id=running_job_id)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect_default(
self,
mock_insert,
_,
):
self.hook.run_query('query')
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect(self, mock_insert, _):
self.hook.run_query('query', use_legacy_sql=False)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_sql_dialect_legacy_with_query_params(self, mock_insert, _):
params = [
{
'name': "param_name",
'parameterType': {'type': "STRING"},
'parameterValue': {'value': "param_value"},
}
]
self.hook.run_query('query', use_legacy_sql=False, query_params=params)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['useLegacySql'] is False
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_sql_dialect_legacy_with_query_params_fails(self, _):
params = [
{
'name': "param_name",
'parameterType': {'type': "STRING"},
'parameterValue': {'value': "param_value"},
}
]
with pytest.raises(ValueError, match="Query parameters are not allowed when using legacy SQL"):
self.hook.run_query('query', use_legacy_sql=True, query_params=params)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_without_sql_fails(self, _):
with pytest.raises(
TypeError, match=r"`BigQueryBaseCursor.run_query` missing 1 required positional argument: `sql`"
):
self.hook.run_query(sql=None)
@parameterized.expand(
[
(['ALLOW_FIELD_ADDITION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_RELAXATION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'], 'WRITE_APPEND'),
(['ALLOW_FIELD_ADDITION'], 'WRITE_TRUNCATE'),
(['ALLOW_FIELD_RELAXATION'], 'WRITE_TRUNCATE'),
(['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'], 'WRITE_TRUNCATE'),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_schema_update_options(
self,
schema_update_options,
write_disposition,
mock_insert,
mock_get_service,
):
self.hook.run_query(
sql='query',
destination_dataset_table='my_dataset.my_table',
schema_update_options=schema_update_options,
write_disposition=write_disposition,
)
_, kwargs = mock_insert.call_args
assert kwargs['configuration']['query']['schemaUpdateOptions'] == schema_update_options
assert kwargs['configuration']['query']['writeDisposition'] == write_disposition
@parameterized.expand(
[
(
['INCORRECT_OPTION'],
None,
r"\['INCORRECT_OPTION'\] contains invalid schema update options\. "
r"Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]",
),
(
['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION', 'INCORRECT_OPTION'],
None,
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION', 'INCORRECT_OPTION'\] contains invalid "
r"schema update options\. Please only use one or more of the following options: "
r"\['ALLOW_FIELD_ADDITION', 'ALLOW_FIELD_RELAXATION'\]",
),
(
['ALLOW_FIELD_ADDITION'],
None,
r"schema_update_options is only allowed if write_disposition is "
r"'WRITE_APPEND' or 'WRITE_TRUNCATE'",
),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_run_query_schema_update_options_incorrect(
self,
schema_update_options,
write_disposition,
expected_regex,
mock_get_service,
):
with pytest.raises(ValueError, match=expected_regex):
self.hook.run_query(
sql='query',
destination_dataset_table='my_dataset.my_table',
schema_update_options=schema_update_options,
write_disposition=write_disposition,
)
@parameterized.expand([(True,), (False,)])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_api_resource_configs(
self,
bool_val,
mock_insert,
_,
):
self.hook.run_query('query', api_resource_configs={'query': {'useQueryCache': bool_val}})
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useQueryCache'] is bool_val
assert kwargs["configuration"]['query']['useLegacySql'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_api_resource_configs_duplication_warning(self, mock_get_service):
with pytest.raises(
ValueError,
match=(
r"Values of useLegacySql param are duplicated\. api_resource_configs "
r"contained useLegacySql param in `query` config and useLegacySql was "
r"also provided with arg to run_query\(\) method\. Please remove duplicates\."
),
):
self.hook.run_query(
'query', use_legacy_sql=True, api_resource_configs={'query': {'useLegacySql': False}}
)
def test_validate_value(self):
with pytest.raises(
TypeError, match="case_1 argument must have a type <class 'dict'> not <class 'str'>"
):
_validate_value("case_1", "a", dict)
assert _validate_value("case_2", 0, int) is None
def test_duplication_check(self):
with pytest.raises(
ValueError,
match=r"Values of key_one param are duplicated. api_resource_configs contained key_one param in"
r" `query` config and key_one was also provided with arg to run_query\(\) method. "
r"Please remove duplicates.",
):
key_one = True
_api_resource_configs_duplication_check("key_one", key_one, {"key_one": False})
assert _api_resource_configs_duplication_check("key_one", key_one, {"key_one": True}) is None
def test_validate_src_fmt_configs(self):
source_format = "test_format"
valid_configs = ["test_config_known", "compatibility_val"]
backward_compatibility_configs = {"compatibility_val": "val"}
with pytest.raises(
ValueError, match="test_config_unknown is not a valid src_fmt_configs for type test_format."
):
# This config should raise a value error.
src_fmt_configs = {"test_config_unknown": "val"}
_validate_src_fmt_configs(
source_format, src_fmt_configs, valid_configs, backward_compatibility_configs
)
src_fmt_configs = {"test_config_known": "val"}
src_fmt_configs = _validate_src_fmt_configs(
source_format, src_fmt_configs, valid_configs, backward_compatibility_configs
)
assert (
"test_config_known" in src_fmt_configs
), "src_fmt_configs should contain al known src_fmt_configs"
assert (
"compatibility_val" in src_fmt_configs
), "_validate_src_fmt_configs should add backward_compatibility config"
@parameterized.expand([("AVRO",), ("PARQUET",), ("NEWLINE_DELIMITED_JSON",), ("DATASTORE_BACKUP",)])
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_non_csv_as_src_fmt(self, fmt, _):
try:
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
source_uris=[],
source_format=fmt,
autodetect=True,
)
except ValueError:
self.fail("run_load() raised ValueError unexpectedly!")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_extract(self, mock_insert):
source_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
destination_cloud_storage_uris = ["gs://bucket/file.csv"]
expected_configuration = {
"extract": {
"sourceTable": {
"projectId": PROJECT_ID,
"datasetId": DATASET_ID,
"tableId": TABLE_ID,
},
"compression": "NONE",
"destinationUris": destination_cloud_storage_uris,
"destinationFormat": "CSV",
"fieldDelimiter": ",",
"printHeader": True,
}
}
self.hook.run_extract(
source_project_dataset_table=source_project_dataset_table,
destination_cloud_storage_uris=destination_cloud_storage_uris,
)
mock_insert.assert_called_once_with(configuration=expected_configuration, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.SchemaField")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_list_rows(self, mock_client, mock_schema, mock_table):
self.hook.list_rows(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
max_results=10,
selected_fields=["field_1", "field_2"],
page_token="page123",
start_index=5,
location=LOCATION,
)
mock_table.from_api_repr.assert_called_once_with({"tableReference": TABLE_REFERENCE_REPR})
mock_schema.has_calls([mock.call(x, "") for x in ["field_1", "field_2"]])
mock_client.return_value.list_rows.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
max_results=10,
selected_fields=mock.ANY,
page_token='page123',
start_index=5,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_list_rows_with_empty_selected_fields(self, mock_client, mock_table):
self.hook.list_rows(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
max_results=10,
page_token="page123",
selected_fields=[],
start_index=5,
location=LOCATION,
)
mock_table.from_api_repr.assert_called_once_with({"tableReference": TABLE_REFERENCE_REPR})
mock_client.return_value.list_rows.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
max_results=10,
page_token='page123',
selected_fields=None,
start_index=5,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_run_table_delete(self, mock_client, mock_table):
source_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
self.hook.run_table_delete(source_project_dataset_table, ignore_if_missing=False)
mock_table.from_string.assert_called_once_with(source_project_dataset_table)
mock_client.return_value.delete_table.assert_called_once_with(
table=mock_table.from_string.return_value, not_found_ok=False
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset_tables")
def test_table_upsert_create_new_table(self, mock_get, mock_create):
table_resource = {"tableReference": {"tableId": TABLE_ID}}
mock_get.return_value = []
self.hook.run_table_upsert(dataset_id=DATASET_ID, table_resource=table_resource)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
mock_create.assert_called_once_with(table_resource=table_resource, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset_tables")
def test_table_upsert_already_exists(self, mock_get, mock_update):
table_resource = {"tableReference": {"tableId": TABLE_ID}}
mock_get.return_value = [{"tableId": TABLE_ID}]
self.hook.run_table_upsert(dataset_id=DATASET_ID, table_resource=table_resource)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
mock_update.assert_called_once_with(table_resource=table_resource)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_dataset")
def test_run_grant_dataset_view_access_granting(self, mock_update, mock_get):
view_table = f"{TABLE_ID}_view"
view_dataset = f"{DATASET_ID}_view"
view_access = AccessEntry(
role=None,
entity_type="view",
entity_id={'projectId': PROJECT_ID, 'datasetId': view_dataset, 'tableId': view_table},
)
dataset = Dataset(DatasetReference.from_string(DATASET_ID, PROJECT_ID))
dataset.access_entries = []
mock_get.return_value = dataset
self.hook.run_grant_dataset_view_access(
source_dataset=DATASET_ID, view_dataset=view_dataset, view_table=view_table
)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
assert view_access in dataset.access_entries
mock_update.assert_called_once_with(
fields=["access"],
dataset_resource=dataset.to_api_repr(),
project_id=PROJECT_ID,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.update_dataset")
def test_run_grant_dataset_view_access_already_granted(self, mock_update, mock_get):
view_table = f"{TABLE_ID}_view"
view_dataset = f"{DATASET_ID}_view"
view_access = AccessEntry(
role=None,
entity_type="view",
entity_id={'projectId': PROJECT_ID, 'datasetId': view_dataset, 'tableId': view_table},
)
dataset = Dataset(DatasetReference.from_string(DATASET_ID, PROJECT_ID))
dataset.access_entries = [view_access]
mock_get.return_value = dataset
self.hook.run_grant_dataset_view_access(
source_dataset=DATASET_ID, view_dataset=view_dataset, view_table=view_table
)
mock_get.assert_called_once_with(project_id=PROJECT_ID, dataset_id=DATASET_ID)
assert len(mock_update.calls) == 0
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_dataset_tables_list(self, mock_client):
table_list = [
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "a-1"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "b-1"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "a-2"},
{"projectId": PROJECT_ID, "datasetId": DATASET_ID, "tableId": "b-2"},
]
table_list_response = [Table.from_api_repr({"tableReference": t}) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables_list(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference, max_results=None
)
assert table_list == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_poll_job_complete(self, mock_client):
self.hook.poll_job_complete(job_id=JOB_ID, location=LOCATION, project_id=PROJECT_ID)
mock_client.assert_called_once_with(location=LOCATION, project_id=PROJECT_ID)
mock_client.return_value.get_job.assert_called_once_with(job_id=JOB_ID)
mock_client.return_value.get_job.return_value.done.assert_called_once_with(retry=DEFAULT_RETRY)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("logging.Logger.info")
def test_cancel_query_jobs_to_cancel(
self,
mock_logger_info,
poll_job_complete,
):
poll_job_complete.return_value = True
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
poll_job_complete.assert_called_once_with(job_id=JOB_ID)
mock_logger_info.has_call(mock.call("No running BigQuery jobs to cancel."))
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("time.sleep")
@mock.patch("logging.Logger.info")
def test_cancel_query_cancel_timeout(
self,
mock_logger_info,
mock_sleep,
poll_job_complete,
mock_client,
):
poll_job_complete.side_effect = [False] * 13
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
mock_client.return_value.cancel_job.assert_called_once_with(job_id=JOB_ID)
assert poll_job_complete.call_count == 13
assert mock_sleep.call_count == 11
mock_logger_info.has_call(
mock.call(
f"Stopping polling due to timeout. Job with id {JOB_ID} "
"has not completed cancel and may or may not finish."
)
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.poll_job_complete")
@mock.patch("time.sleep")
@mock.patch("logging.Logger.info")
def test_cancel_query_cancel_completed(
self,
mock_logger_info,
mock_sleep,
poll_job_complete,
mock_client,
):
poll_job_complete.side_effect = [False] * 12 + [True]
self.hook.running_job_id = JOB_ID
self.hook.cancel_query()
mock_client.return_value.cancel_job.assert_called_once_with(job_id=JOB_ID)
assert poll_job_complete.call_count == 13
assert mock_sleep.call_count == 11
mock_logger_info.has_call(mock.call(f"Job successfully canceled: {PROJECT_ID}, {PROJECT_ID}"))
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_schema(self, mock_client):
table = {
"tableReference": TABLE_REFERENCE_REPR,
"schema": {
"fields": [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
]
},
}
mock_client.return_value.get_table.return_value = Table.from_api_repr(table)
result = self.hook.get_schema(dataset_id=DATASET_ID, table_id=TABLE_ID)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
assert "fields" in result
assert len(result["fields"]) == 2
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_invalid_source_format(self, mock_get_service):
with pytest.raises(
Exception,
match=r"JSON is not a valid source format. Please use one of the following types: \['CSV', "
r"'NEWLINE_DELIMITED_JSON', 'AVRO', 'GOOGLE_SHEETS', 'DATASTORE_BACKUP', 'PARQUET'\]",
):
self.hook.run_load("test.test", "test_schema.json", ["test_data.json"], source_format="json")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_insert_all_succeed(self, mock_client):
rows = [{"json": {"a_key": "a_value_0"}}]
self.hook.insert_all(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
rows=rows,
ignore_unknown_values=True,
skip_invalid_rows=True,
)
mock_client.return_value.get_table.assert_called_once_with(TABLE_REFERENCE)
mock_client.return_value.insert_rows.assert_called_once_with(
table=mock_client.return_value.get_table.return_value,
rows=rows,
ignore_unknown_values=True,
skip_invalid_rows=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_insert_all_fail(self, mock_client):
rows = [{"json": {"a_key": "a_value_0"}}]
mock_client.return_value.insert_rows.return_value = ["some", "errors"]
with pytest.raises(AirflowException, match="insert error"):
self.hook.insert_all(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, rows=rows, fail_on_error=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table='my_dataset.my_table',
labels={'label1': 'test1', 'label2': 'test2'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['labels'] == {'label1': 'test1', 'label2': 'test2'}
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.QueryJob")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_insert_job(self, mock_client, mock_query_job):
job_conf = {
"query": {
"query": "SELECT * FROM test",
"useLegacySql": "False",
}
}
mock_query_job._JOB_TYPE = "query"
self.hook.insert_job(
configuration=job_conf,
job_id=JOB_ID,
project_id=PROJECT_ID,
location=LOCATION,
)
mock_client.assert_called_once_with(
project_id=PROJECT_ID,
location=LOCATION,
)
mock_query_job.from_api_repr.assert_called_once_with(
{
'configuration': job_conf,
'jobReference': {'jobId': JOB_ID, 'projectId': PROJECT_ID, 'location': LOCATION},
},
mock_client.return_value,
)
mock_query_job.from_api_repr.return_value.result.assert_called_once_with()
class TestBigQueryTableSplitter(unittest.TestCase):
def test_internal_need_default_project(self):
with pytest.raises(Exception, match="INTERNAL: No default project is specified"):
_split_tablename("dataset.table", None)
@parameterized.expand(
[
("project", "dataset", "table", "dataset.table"),
("alternative", "dataset", "table", "alternative:dataset.table"),
("alternative", "dataset", "table", "alternative.dataset.table"),
("alt1:alt", "dataset", "table", "alt1:alt.dataset.table"),
("alt1:alt", "dataset", "table", "alt1:alt:dataset.table"),
]
)
def test_split_tablename(self, project_expected, dataset_expected, table_expected, table_input):
default_project_id = "project"
project, dataset, table = _split_tablename(table_input, default_project_id)
assert project_expected == project
assert dataset_expected == dataset
assert table_expected == table
@parameterized.expand(
[
("alt1:alt2:alt3:dataset.table", None, "Use either : or . to specify project got {}"),
(
"alt1.alt.dataset.table",
None,
r"Expect format of \(<project\.\|<project\:\)<dataset>\.<table>, got {}",
),
(
"alt1:alt2:alt.dataset.table",
"var_x",
"Format exception for var_x: Use either : or . to specify project got {}",
),
(
"alt1:alt2:alt:dataset.table",
"var_x",
"Format exception for var_x: Use either : or . to specify project got {}",
),
(
"alt1.alt.dataset.table",
"var_x",
r"Format exception for var_x: Expect format of "
r"\(<project\.\|<project:\)<dataset>.<table>, got {}",
),
]
)
def test_invalid_syntax(self, table_input, var_name, exception_message):
default_project_id = "project"
with pytest.raises(Exception, match=exception_message.format(table_input)):
_split_tablename(table_input, default_project_id, var_name)
class TestTableOperations(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_view(self, mock_bq_client, mock_table):
view = {
'query': 'SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*`',
"useLegacySql": False,
}
self.hook.create_empty_table(
project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID, view=view, retry=DEFAULT_RETRY
)
body = {'tableReference': TABLE_REFERENCE_REPR, 'view': view}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_patch_table(self, mock_client, mock_table):
description_patched = 'Test description.'
expiration_time_patched = 2524608000000
friendly_name_patched = 'Test friendly name.'
labels_patched = {'label1': 'test1', 'label2': 'test2'}
schema_patched = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'balance', 'type': 'FLOAT', 'mode': 'NULLABLE'},
{'name': 'new_field', 'type': 'STRING', 'mode': 'NULLABLE'},
]
time_partitioning_patched = {'expirationMs': 10000000}
require_partition_filter_patched = True
view_patched = {
'query': "SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*` LIMIT 500",
'useLegacySql': False,
}
self.hook.patch_table(
dataset_id=DATASET_ID,
table_id=TABLE_ID,
project_id=PROJECT_ID,
description=description_patched,
expiration_time=expiration_time_patched,
friendly_name=friendly_name_patched,
labels=labels_patched,
schema=schema_patched,
time_partitioning=time_partitioning_patched,
require_partition_filter=require_partition_filter_patched,
view=view_patched,
)
body = {
"description": description_patched,
"expirationTime": expiration_time_patched,
"friendlyName": friendly_name_patched,
"labels": labels_patched,
"schema": {"fields": schema_patched},
"timePartitioning": time_partitioning_patched,
"view": view_patched,
"requirePartitionFilter": require_partition_filter_patched,
}
fields = list(body.keys())
body["tableReference"] = TABLE_REFERENCE_REPR
mock_table.from_api_repr.assert_called_once_with(body)
mock_client.return_value.update_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, fields=fields
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_succeed(self, mock_bq_client, mock_table):
self.hook.create_empty_table(project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID)
body = {
'tableReference': {
'tableId': TABLE_ID,
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
}
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, exists_ok=True, retry=DEFAULT_RETRY
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_with_extras_succeed(self, mock_bq_client, mock_table):
schema_fields = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'created', 'type': 'DATE', 'mode': 'REQUIRED'},
]
time_partitioning = {"field": "created", "type": "DAY"}
cluster_fields = ['name']
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
schema_fields=schema_fields,
time_partitioning=time_partitioning,
cluster_fields=cluster_fields,
)
body = {
'tableReference': {
'tableId': TABLE_ID,
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
},
'schema': {'fields': schema_fields},
'timePartitioning': time_partitioning,
'clustering': {'fields': cluster_fields},
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, exists_ok=True, retry=DEFAULT_RETRY
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_tables_list(self, mock_client):
table_list = [
{
"kind": "bigquery#table",
"id": "your-project:your_dataset.table1",
"tableReference": {
"projectId": "your-project",
"datasetId": "your_dataset",
"tableId": "table1",
},
"type": "TABLE",
"creationTime": "1565781859261",
},
{
"kind": "bigquery#table",
"id": "your-project:your_dataset.table2",
"tableReference": {
"projectId": "your-project",
"datasetId": "your_dataset",
"tableId": "table2",
},
"type": "TABLE",
"creationTime": "1565782713480",
},
]
table_list_response = [Table.from_api_repr(t) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference,
max_results=None,
retry=DEFAULT_RETRY,
)
for res, exp in zip(result, table_list):
assert res["tableId"] == exp["tableReference"]["tableId"]
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_materialized_view(self, mock_bq_client, mock_table):
query = """
SELECT product, SUM(amount)
FROM `test-project-id.test_dataset_id.test_table_prefix*`
GROUP BY product
"""
materialized_view = {
'query': query,
'enableRefresh': True,
'refreshIntervalMs': 2000000,
}
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
materialized_view=materialized_view,
retry=DEFAULT_RETRY,
)
body = {'tableReference': TABLE_REFERENCE_REPR, 'materializedView': materialized_view}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
class TestBigQueryCursor(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_execute_with_parameters(self, mock_insert, _):
bq_cursor = self.hook.get_cursor()
bq_cursor.execute("SELECT %(foo)s", {"foo": "bar"})
conf = {
'query': {
'query': "SELECT 'bar'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
}
mock_insert.assert_called_once_with(configuration=conf, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_execute_many(self, mock_insert, _):
bq_cursor = self.hook.get_cursor()
bq_cursor.executemany("SELECT %(foo)s", [{"foo": "bar"}, {"foo": "baz"}])
assert mock_insert.call_count == 2
assert mock_insert.has_calls(
mock.call(
configuration={
'query': {
'query': "SELECT 'bar'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
},
project_id=PROJECT_ID,
),
mock.call(
configuration={
'query': {
'query': "SELECT 'baz'",
'priority': 'INTERACTIVE',
'useLegacySql': True,
'schemaUpdateOptions': [],
}
},
project_id=PROJECT_ID,
),
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_description(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
with pytest.raises(NotImplementedError):
bq_cursor.description
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_close(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.close() # pylint: disable=assignment-from-no-return
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_rowcount(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.rowcount
assert -1 == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.next")
def test_fetchone(self, mock_next, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.fetchone()
mock_next.call_count == 1
assert mock_next.return_value == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch(
"airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.fetchone", side_effect=[1, 2, 3, None]
)
def test_fetchall(self, mock_fetchone, mock_get_service):
bq_cursor = self.hook.get_cursor()
result = bq_cursor.fetchall()
assert [1, 2, 3] == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.fetchone")
def test_fetchmany(self, mock_fetchone, mock_get_service):
side_effect_values = [1, 2, 3, None]
bq_cursor = self.hook.get_cursor()
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany()
assert [1] == result
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany(2)
assert [1, 2] == result
mock_fetchone.side_effect = side_effect_values
result = bq_cursor.fetchmany(5)
assert [1, 2, 3] == result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next_no_jobid(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = None
result = bq_cursor.next()
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next_buffer(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
bq_cursor.buffer = [1, 2]
result = bq_cursor.next()
assert 1 == result
result = bq_cursor.next()
assert 2 == result
bq_cursor.all_pages_loaded = True
result = bq_cursor.next()
assert result is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_next(self, mock_get_service):
mock_get_query_results = mock_get_service.return_value.jobs.return_value.getQueryResults
mock_execute = mock_get_query_results.return_value.execute
mock_execute.return_value = {
"rows": [
{"f": [{"v": "one"}, {"v": 1}]},
{"f": [{"v": "two"}, {"v": 2}]},
],
"pageToken": None,
"schema": {
"fields": [
{"name": "field_1", "type": "STRING"},
{"name": "field_2", "type": "INTEGER"},
]
},
}
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
bq_cursor.location = LOCATION
result = bq_cursor.next()
assert ['one', 1] == result
result = bq_cursor.next()
assert ['two', 2] == result
mock_get_query_results.assert_called_once_with(
jobId=JOB_ID, location=LOCATION, pageToken=None, projectId='bq-project'
)
mock_execute.assert_called_once_with(num_retries=bq_cursor.num_retries)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.flush_results")
def test_next_no_rows(self, mock_flush_results, mock_get_service):
mock_get_query_results = mock_get_service.return_value.jobs.return_value.getQueryResults
mock_execute = mock_get_query_results.return_value.execute
mock_execute.return_value = {}
bq_cursor = self.hook.get_cursor()
bq_cursor.job_id = JOB_ID
result = bq_cursor.next()
assert result is None
mock_get_query_results.assert_called_once_with(
jobId=JOB_ID, location=None, pageToken=None, projectId='bq-project'
)
mock_execute.assert_called_once_with(num_retries=bq_cursor.num_retries)
assert mock_flush_results.call_count == 1
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryCursor.flush_results")
def test_flush_cursor_in_execute(self, _, mock_insert, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.execute("SELECT %(foo)s", {"foo": "bar"})
assert mock_insert.call_count == 1
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_flush_cursor(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
bq_cursor.page_token = '456dcea9-fcbf-4f02-b570-83f5297c685e'
bq_cursor.job_id = 'c0a79ae4-0e72-4593-a0d0-7dbbf726f193'
bq_cursor.all_pages_loaded = True
bq_cursor.buffer = [('a', 100, 200), ('b', 200, 300)]
bq_cursor.flush_results()
assert bq_cursor.page_token is None
assert bq_cursor.job_id is None
assert not bq_cursor.all_pages_loaded
assert bq_cursor.buffer == []
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_arraysize(self, mock_get_service):
bq_cursor = self.hook.get_cursor()
assert bq_cursor.buffersize is None
assert bq_cursor.arraysize == 1
bq_cursor.set_arraysize(10)
assert bq_cursor.buffersize == 10
assert bq_cursor.arraysize == 10
class TestDatasetsOperations(_BigQueryBaseTestClass):
def test_create_empty_dataset_no_dataset_id_err(self):
with pytest.raises(ValueError, match=r"Please specify `datasetId`"):
self.hook.create_empty_dataset(dataset_id=None, project_id=None)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_with_params(self, mock_client, mock_dataset):
self.hook.create_empty_dataset(project_id=PROJECT_ID, dataset_id=DATASET_ID, location=LOCATION)
expected_body = {
"location": LOCATION,
"datasetReference": {"datasetId": DATASET_ID, "projectId": PROJECT_ID},
}
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(expected_body)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_with_object(self, mock_client, mock_dataset):
dataset = {
"location": "LOCATION",
"datasetReference": {"datasetId": "DATASET_ID", "projectId": "PROJECT_ID"},
}
self.hook.create_empty_dataset(dataset_reference=dataset)
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(dataset)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_dataset_use_values_from_object(self, mock_client, mock_dataset):
dataset = {
"location": "LOCATION",
"datasetReference": {"datasetId": "DATASET_ID", "projectId": "PROJECT_ID"},
}
self.hook.create_empty_dataset(
dataset_reference=dataset,
location="Unknown location",
dataset_id="Fashionable Dataset",
project_id="Amazing Project",
)
api_repr = mock_dataset.from_api_repr
api_repr.assert_called_once_with(dataset)
mock_client.return_value.create_dataset.assert_called_once_with(
dataset=api_repr.return_value, exists_ok=True
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_dataset(self, mock_client):
_expected_result = {
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
}
expected_result = Dataset.from_api_repr(_expected_result)
mock_client.return_value.get_dataset.return_value = expected_result
result = self.hook.get_dataset(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.get_dataset.assert_called_once_with(
dataset_ref=DatasetReference(PROJECT_ID, DATASET_ID)
)
assert result == expected_result
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_get_datasets_list(self, mock_client):
datasets = [
{
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
},
{
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_1_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_1_test"},
},
]
return_value = [DatasetListItem(d) for d in datasets]
mock_client.return_value.list_datasets.return_value = return_value
result = self.hook.get_datasets_list(project_id=PROJECT_ID)
mock_client.return_value.list_datasets.assert_called_once_with(
project=PROJECT_ID,
include_all=False,
filter=None,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
)
for exp, res in zip(datasets, result):
assert res.full_dataset_id == exp["id"]
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_delete_dataset(self, mock_client):
delete_contents = True
self.hook.delete_dataset(
project_id=PROJECT_ID, dataset_id=DATASET_ID, delete_contents=delete_contents
)
mock_client.return_value.delete_dataset.assert_called_once_with(
dataset=DatasetReference(PROJECT_ID, DATASET_ID),
delete_contents=delete_contents,
retry=DEFAULT_RETRY,
not_found_ok=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
def test_patch_dataset(self, mock_get_service):
dataset_resource = {"access": [{"role": "WRITER", "groupByEmail": "cloud-logs@google.com"}]}
method = mock_get_service.return_value.datasets.return_value.patch
self.hook.patch_dataset(
dataset_id=DATASET_ID, project_id=PROJECT_ID, dataset_resource=dataset_resource
)
method.assert_called_once_with(projectId=PROJECT_ID, datasetId=DATASET_ID, body=dataset_resource)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Dataset")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_update_dataset(self, mock_client, mock_dataset):
dataset_resource = {
"kind": "bigquery#dataset",
"location": "US",
"id": "your-project:dataset_2_test",
"datasetReference": {"projectId": "your-project", "datasetId": "dataset_2_test"},
}
method = mock_client.return_value.update_dataset
dataset = Dataset.from_api_repr(dataset_resource)
mock_dataset.from_api_repr.return_value = dataset
method.return_value = dataset
result = self.hook.update_dataset(
dataset_id=DATASET_ID,
project_id=PROJECT_ID,
dataset_resource=dataset_resource,
fields=["location"],
)
mock_dataset.from_api_repr.assert_called_once_with(dataset_resource)
method.assert_called_once_with(
dataset=dataset,
fields=["location"],
retry=DEFAULT_RETRY,
)
assert result == dataset
class TestTimePartitioningInRunJob(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_default(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load'].get('timePartitioning') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_with_auto_detect(self, mock_insert):
destination_project_dataset_table = "autodetect.table"
self.hook.run_load(destination_project_dataset_table, [], [], autodetect=True)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['autodetect'] is True
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_arg(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table=f"{DATASET_ID}.{TABLE_ID}",
schema_fields=[],
source_uris=[],
time_partitioning={'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
)
configuration = {
'load': {
'autodetect': False,
'createDisposition': 'CREATE_IF_NEEDED',
'destinationTable': {'projectId': PROJECT_ID, 'datasetId': DATASET_ID, 'tableId': TABLE_ID},
'sourceFormat': 'CSV',
'sourceUris': [],
'writeDisposition': 'WRITE_EMPTY',
'ignoreUnknownValues': False,
'timePartitioning': {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
'skipLeadingRows': 0,
'fieldDelimiter': ',',
'quote': None,
'allowQuotedNewlines': False,
'encoding': 'UTF-8',
}
}
mock_insert.assert_called_once_with(configuration=configuration, project_id=PROJECT_ID)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table=f"{DATASET_ID}.{TABLE_ID}",
time_partitioning={'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
)
configuration = {
'query': {
'query': 'select 1',
'priority': 'INTERACTIVE',
'useLegacySql': True,
'timePartitioning': {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000},
'schemaUpdateOptions': [],
'destinationTable': {'projectId': PROJECT_ID, 'datasetId': DATASET_ID, 'tableId': TABLE_ID},
'allowLargeResults': False,
'flattenResults': None,
'writeDisposition': 'WRITE_EMPTY',
'createDisposition': 'CREATE_IF_NEEDED',
}
}
mock_insert.assert_called_once_with(configuration=configuration, project_id=PROJECT_ID)
def test_dollar_makes_partition(self):
tp_out = _cleanse_time_partitioning('test.teast$20170101', {})
expect = {'type': 'DAY'}
assert tp_out == expect
def test_extra_time_partitioning_options(self):
tp_out = _cleanse_time_partitioning(
'test.teast', {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000}
)
expect = {'type': 'DAY', 'field': 'test_field', 'expirationMs': 1000}
assert tp_out == expect
class TestClusteringInRunJob(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_default(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load'].get('clustering') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_arg(self, mock_insert):
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
cluster_fields=['field1', 'field2'],
time_partitioning={'type': 'DAY'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['clustering'] == {'fields': ['field1', 'field2']}
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_default(self, mock_insert):
self.hook.run_query(sql='select 1')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query'].get('clustering') is None
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_arg(self, mock_insert):
self.hook.run_query(
sql='select 1',
destination_dataset_table='my_dataset.my_table',
cluster_fields=['field1', 'field2'],
time_partitioning={'type': 'DAY'},
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['clustering'] == {'fields': ['field1', 'field2']}
class TestBigQueryHookLegacySql(_BigQueryBaseTestClass):
"""Ensure `use_legacy_sql` param in `BigQueryHook` propagates properly."""
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_hook_uses_legacy_sql_by_default(self, mock_insert, _):
self.hook.get_first('query')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useLegacySql'] is True
@mock.patch(
'airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials_and_project_id',
return_value=(CREDENTIALS, PROJECT_ID),
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_service")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_legacy_sql_override_propagates_properly(
self, mock_insert, mock_get_service, mock_get_creds_and_proj_id
):
bq_hook = BigQueryHook(use_legacy_sql=False)
bq_hook.get_first('query')
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['query']['useLegacySql'] is False
class TestBigQueryHookRunWithConfiguration(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.LoadJob")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.get_client")
def test_run_with_configuration_location(self, mock_client, mock_job):
running_job_id = 'job_vjdi28vskdui2onru23'
location = 'asia-east1'
mock_job._JOB_TYPE = "load"
conf = {"load": {}}
self.hook.running_job_id = running_job_id
self.hook.location = location
self.hook.run_with_configuration(conf)
mock_client.assert_called_once_with(project_id=PROJECT_ID, location=location)
mock_job.from_api_repr.assert_called_once_with(
{
"configuration": conf,
"jobReference": {"jobId": mock.ANY, "projectId": PROJECT_ID, "location": location},
},
mock_client.return_value,
)
class TestBigQueryWithKMS(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_create_empty_table_with_kms(self, mock_bq_client, mock_table):
schema_fields = [{"name": "id", "type": "STRING", "mode": "REQUIRED"}]
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.create_empty_table(
project_id=PROJECT_ID,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
schema_fields=schema_fields,
encryption_configuration=encryption_configuration,
)
body = {
"tableReference": {"tableId": TABLE_ID, 'projectId': PROJECT_ID, 'datasetId': DATASET_ID},
"schema": {"fields": schema_fields},
"encryptionConfiguration": encryption_configuration,
}
mock_table.from_api_repr.assert_called_once_with(body)
mock_bq_client.return_value.create_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value,
exists_ok=True,
retry=DEFAULT_RETRY,
)
# pylint: disable=too-many-locals
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_with_kms(self, mock_create):
external_project_dataset_table = f"{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}"
source_uris = ['test_data.csv']
source_format = 'CSV'
autodetect = False
compression = 'NONE'
ignore_unknown_values = False
max_bad_records = 10
skip_leading_rows = 1
field_delimiter = ','
quote_character = None
allow_quoted_newlines = False
allow_jagged_rows = False
encoding = "UTF-8"
labels = {'label1': 'test1', 'label2': 'test2'}
schema_fields = [{'mode': 'REQUIRED', 'name': 'id', 'type': 'STRING', 'description': None}]
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.create_external_table(
external_project_dataset_table=external_project_dataset_table,
source_uris=source_uris,
source_format=source_format,
autodetect=autodetect,
compression=compression,
ignore_unknown_values=ignore_unknown_values,
max_bad_records=max_bad_records,
skip_leading_rows=skip_leading_rows,
field_delimiter=field_delimiter,
quote_character=quote_character,
allow_jagged_rows=allow_jagged_rows,
encoding=encoding,
allow_quoted_newlines=allow_quoted_newlines,
labels=labels,
schema_fields=schema_fields,
encryption_configuration=encryption_configuration,
)
body = {
'externalDataConfiguration': {
'autodetect': autodetect,
'sourceFormat': source_format,
'sourceUris': source_uris,
'compression': compression,
'ignoreUnknownValues': ignore_unknown_values,
'schema': {'fields': schema_fields},
'maxBadRecords': max_bad_records,
'csvOptions': {
'skipLeadingRows': skip_leading_rows,
'fieldDelimiter': field_delimiter,
'quote': quote_character,
'allowQuotedNewlines': allow_quoted_newlines,
'allowJaggedRows': allow_jagged_rows,
'encoding': encoding,
},
},
'tableReference': {
'projectId': PROJECT_ID,
'datasetId': DATASET_ID,
'tableId': TABLE_ID,
},
'labels': labels,
"encryptionConfiguration": encryption_configuration,
}
mock_create.assert_called_once_with(
table_resource=body,
project_id=PROJECT_ID,
location=None,
exists_ok=True,
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Table")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.Client")
def test_update_table(self, mock_client, mock_table):
description_patched = 'Test description.'
expiration_time_patched = 2524608000000
friendly_name_patched = 'Test friendly name.'
labels_patched = {'label1': 'test1', 'label2': 'test2'}
schema_patched = [
{'name': 'id', 'type': 'STRING', 'mode': 'REQUIRED'},
{'name': 'name', 'type': 'STRING', 'mode': 'NULLABLE'},
{'name': 'balance', 'type': 'FLOAT', 'mode': 'NULLABLE'},
{'name': 'new_field', 'type': 'STRING', 'mode': 'NULLABLE'},
]
time_partitioning_patched = {'expirationMs': 10000000}
require_partition_filter_patched = True
view_patched = {
'query': "SELECT * FROM `test-project-id.test_dataset_id.test_table_prefix*` LIMIT 500",
'useLegacySql': False,
}
body = {
"tableReference": {
"projectId": PROJECT_ID,
"datasetId": DATASET_ID,
"tableId": TABLE_ID,
},
"description": description_patched,
"expirationTime": expiration_time_patched,
"friendlyName": friendly_name_patched,
"labels": labels_patched,
"schema": {"fields": schema_patched},
"timePartitioning": time_partitioning_patched,
"view": view_patched,
"requirePartitionFilter": require_partition_filter_patched,
}
fields = list(body.keys())
self.hook.update_table(
table_resource=body,
fields=fields,
dataset_id=DATASET_ID,
table_id=TABLE_ID,
project_id=PROJECT_ID,
)
mock_table.from_api_repr.assert_called_once_with(body)
mock_client.return_value.update_table.assert_called_once_with(
table=mock_table.from_api_repr.return_value, fields=fields
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_query_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_query(sql='query', encryption_configuration=encryption_configuration)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['query']['destinationEncryptionConfiguration'] is encryption_configuration
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_copy_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_copy(
source_project_dataset_tables='p.d.st',
destination_project_dataset_table='p.d.dt',
encryption_configuration=encryption_configuration,
)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['copy']['destinationEncryptionConfiguration'] is encryption_configuration
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_with_kms(self, mock_insert):
encryption_configuration = {"kms_key_name": "projects/p/locations/l/keyRings/k/cryptoKeys/c"}
self.hook.run_load(
destination_project_dataset_table='p.d.dt',
source_uris=['abc.csv'],
autodetect=True,
encryption_configuration=encryption_configuration,
)
_, kwargs = mock_insert.call_args
assert (
kwargs["configuration"]['load']['destinationEncryptionConfiguration'] is encryption_configuration
)
class TestBigQueryBaseCursorMethodsDeprecationWarning(unittest.TestCase):
@parameterized.expand(
[
("create_empty_table",),
("create_empty_dataset",),
("get_dataset_tables",),
("delete_dataset",),
("create_external_table",),
("patch_table",),
("insert_all",),
("update_dataset",),
("patch_dataset",),
("get_dataset_tables_list",),
("get_datasets_list",),
("get_dataset",),
("run_grant_dataset_view_access",),
("run_table_upsert",),
("run_table_delete",),
("get_tabledata",),
("get_schema",),
("poll_job_complete",),
("cancel_query",),
("run_with_configuration",),
("run_load",),
("run_copy",),
("run_extract",),
("run_query",),
]
)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook")
def test_deprecation_warning(self, func_name, mock_bq_hook):
args, kwargs = [1], {"param1": "val1"}
new_path = re.escape(f"`airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.{func_name}`")
message_pattern = fr"This method is deprecated\.\s+Please use {new_path}"
message_regex = re.compile(message_pattern, re.MULTILINE)
mocked_func = getattr(mock_bq_hook, func_name)
bq_cursor = BigQueryCursor(mock.MagicMock(), PROJECT_ID, mock_bq_hook)
func = getattr(bq_cursor, func_name)
with pytest.warns(DeprecationWarning, match=message_regex):
_ = func(*args, **kwargs)
mocked_func.assert_called_once_with(*args, **kwargs)
assert re.search(f".*{new_path}.*", func.__doc__)
class TestBigQueryWithLabelsAndDescription(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_labels(self, mock_insert):
labels = {'label1': 'test1', 'label2': 'test2'}
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
labels=labels,
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['destinationTableProperties']['labels'] is labels
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.insert_job")
def test_run_load_description(self, mock_insert):
description = "Test Description"
self.hook.run_load(
destination_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
description=description,
)
_, kwargs = mock_insert.call_args
assert kwargs["configuration"]['load']['destinationTableProperties']['description'] is description
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_labels(self, mock_create):
labels = {'label1': 'test1', 'label2': 'test2'}
self.hook.create_external_table(
external_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
labels=labels,
)
_, kwargs = mock_create.call_args
self.assertDictEqual(kwargs['table_resource']['labels'], labels)
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook.create_empty_table")
def test_create_external_table_description(self, mock_create):
description = "Test Description"
self.hook.create_external_table(
external_project_dataset_table='my_dataset.my_table',
schema_fields=[],
source_uris=[],
description=description,
)
_, kwargs = mock_create.call_args
assert kwargs['table_resource']['description'] is description
|
# -*- coding: utf-8 -*-
"""
Portions of this code have been taken and modified from the "asciidag" project.
Access Date:
Commit: 7c1eefe3895630dc3906bbe9d553e0169202756a
PermalinkURL
URL: https://github.com/sambrightman/asciidag/
File: asciidag/graph.py
Commit: 7c1eefe3895630dc3906bbe9d553e0169202756a
Accessed: 25 MAR 2019
asciidag License
-------------------------------------------------------------------------------
License: Mozilla Public License 2.0
URL: https://github.com/sambrightman/asciidag/blob/7c1eefe3895630dc3906bbe9d553e0169202756a/LICENSE
"""
import sys
import time
from enum import Enum
__all__ = ('Graph',)
COLOR_NORMAL = ""
COLOR_RESET = "\033[m"
COLOR_BOLD = "\033[1m"
COLOR_RED = "\033[31m"
COLOR_GREEN = "\033[32m"
COLOR_YELLOW = "\033[33m"
COLOR_BLUE = "\033[34m"
COLOR_MAGENTA = "\033[35m"
COLOR_CYAN = "\033[36m"
COLOR_BOLD_RED = "\033[1;31m"
COLOR_BOLD_GREEN = "\033[1;32m"
COLOR_BOLD_YELLOW = "\033[1;33m"
COLOR_BOLD_BLUE = "\033[1;34m"
COLOR_BOLD_MAGENTA = "\033[1;35m"
COLOR_BOLD_CYAN = "\033[1;36m"
COLOR_BG_RED = "\033[41m"
COLOR_BG_GREEN = "\033[42m"
COLOR_BG_YELLOW = "\033[43m"
COLOR_BG_BLUE = "\033[44m"
COLOR_BG_MAGENTA = "\033[45m"
COLOR_BG_CYAN = "\033[46m"
COLUMN_COLORS_ANSI = [
COLOR_BOLD_RED,
COLOR_BOLD_GREEN,
COLOR_BOLD_YELLOW,
COLOR_BOLD_BLUE,
COLOR_BOLD_MAGENTA,
COLOR_BOLD_CYAN,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW,
COLOR_BLUE,
COLOR_MAGENTA,
COLOR_CYAN,
COLOR_RESET,
]
class Column(object): # pylint: disable=too-few-public-methods
"""A single column of output.
Attributes:
commit -- The parent commit of this column.
color -- The color to (optionally) print this column in.
This is an index into column_colors.
"""
def __init__(self, commit, color):
self.commit = commit
self.color = color
class GraphState(Enum): # pylint: disable=too-few-public-methods
PADDING = 0
SKIP = 1
PRE_COMMIT = 2
COMMIT = 3
POST_MERGE = 4
COLLAPSING = 5
class Graph(object): # pragma: no cover
"""
The commit currently being processed
struct commit *commit
The number of interesting parents that this commit has. Note that this is
not the same as the actual number of parents. This count excludes parents
that won't be printed in the graph output, as determined by
is_interesting().
int num_parents
The width of the graph output for this commit. All rows for this commit are
padded to this width, so that messages printed after the graph output are
aligned.
int width
The next expansion row to print when state is GraphState.PRE_COMMIT
int expansion_row
The current output state. This tells us what kind of line next_line()
should output.
enum graph_state state
The output state for the previous line of output. This is primarily used to
determine how the first merge line should appear, based on the last line of
the previous commit.
enum graph_state prev_state
The index of the column that refers to this commit. If none of the incoming
columns refer to this commit, this will be equal to num_columns.
int commit_index
The commit_index for the previously displayed commit. This is used to
determine how the first line of a merge graph output should appear, based
on the last line of the previous commit.
int prev_commit_index
The maximum number of columns that can be stored in the columns and
new_columns arrays. This is also half the number of entries that can be
stored in the mapping and new_mapping arrays.
int column_capacity
The number of columns (also called "branch lines" in some places)
int num_columns
The number of columns in the new_columns array
int num_new_columns
The number of entries in the mapping array
int mapping_size
The column state before we output the current commit.
struct column *columns
The new column state after we output the current commit. Only valid when
state is GraphState.COLLAPSING.
struct column *new_columns
An array that tracks the current state of each character in the output line
during state GraphState.COLLAPSING. Each entry is -1 if this character is
empty, or a non-negative integer if the character contains a branch line.
The value of the integer indicates the target position for this branch
line. (I.e., this array maps the current column positions to their desired
positions.)
The maximum capacity of this array is always sizeof(int) * 2 *
column_capacity.
int *mapping
A temporary array for computing the next mapping state while we are
outputting a mapping line. This is stored as part of the git_graph simply
so we don't have to allocate a new temporary array each time we have to
output a collapsing line.
int *new_mapping
The current default column color being used. This is stored as an index
into the array column_colors.
unsigned short default_column_color
"""
def __init__(self,
fh=None,
first_parent_only=False,
use_color=True,
column_colors=None):
"""State machine for processing DAG nodes into ASCII graphs.
show_nodes() deals with sorting the nodes from tips down into
topological order. It then displays them line-by-line.
"""
self.commit = None
self.buf = ''
if fh is None:
self.outfile = sys.stdout
else:
self.outfile = fh
self.first_parent_only = first_parent_only
self.use_color = use_color
if column_colors is None:
self.column_colors = COLUMN_COLORS_ANSI
else:
self.column_colors = column_colors
self.num_parents = 0
self.width = 0
self.expansion_row = 0
self.state = GraphState.PADDING
self.prev_state = GraphState.PADDING
self.commit_index = 0
self.prev_commit_index = 0
self.num_columns = 0
self.num_new_columns = 0
self.mapping_size = 0
# Start the column color at the maximum value, since we'll always
# increment it for the first commit we output. This way we start at 0
# for the first commit.
self.default_column_color = len(self.column_colors) - 1
self.columns = {}
self.new_columns = {}
self.mapping = {}
self.new_mapping = {}
def show_nodes(self, dag, spec, branch, start, order, stop='',
*, show_time=True, show_user=True):
"""Printing function that displays a DAG representing the commit history
Print a revision history alongside a revision graph drawn with ASCII
characters. Nodes printed as an * character are parents of the working
directory. Any unreachable (but referenced nodes) are displayed at +
Parameters
----------
dag : dict
directed acyclic graph of nodes and connections in commits. No more than
2 connections per node
spec: dict
dictionary of commit specification (user name, email, message, etc).
branch : dict
dict of commit hash -> list of branch names whose HEAD commit is at
that key.
start : string
commit hash to act as the top of the topological sort.
order: list
time based ordering of commit hashs
stop : str, optional
commit hash to stop generating the graph at if the DAG contains more
history than is needed (the default is '', which is the "parent" of
the initial repository commit.)
"""
if start == stop:
return
fmtSpec = {}
for cmt, cmtspec in spec.items():
if show_time:
t = f"({time.strftime("%d%b%Y %H:%M:%S", time.gmtime(cmtspec["commit_time"]))})"
else:
t = ''
if show_user:
u = f"({cmtspec["commit_user"]})"
else:
u = ''
m = cmtspec['commit_message']
br = ' '
if cmt in branch:
for branchName in branch[cmt]:
if self.use_color is True:
br = f'{br}({COLOR_BOLD_RED}{branchName}{COLOR_RESET}) '
else:
br = f'{br}({branchName}) '
fmtSpec[cmt] = f'{cmt}{br}{t}{u}: {m}'
for rev in order:
parents = dag[rev]
self._update(rev, parents)
self._show_commit()
self.outfile.write(fmtSpec[rev])
if not self._is_commit_finished():
self.outfile.write('\n')
self._show_remainder()
self.outfile.write('\n')
def _write_column(self, col, col_char):
if col.color is not None:
self.buf += self.column_colors[col.color]
self.buf += col_char
if col.color is not None:
self.buf += self.column_colors[-1]
def _update_state(self, state):
self.prev_state = self.state
self.state = state
def _interesting_parents(self):
for parent in self.commit_parents:
yield parent
if self.first_parent_only:
break
def _get_current_column_color(self):
if not self.use_color:
return None
return self.default_column_color
def _increment_column_color(self):
self.default_column_color = ((self.default_column_color + 1)
% len(self.column_colors))
def _find_commit_color(self, commit):
for i in range(self.num_columns):
if self.columns[i].commit == commit:
return self.columns[i].color
return self._get_current_column_color()
def _insert_into_new_columns(self, commit, mapping_index):
"""
If the commit is already in the new_columns list, we don't need to add
it. Just update the mapping correctly.
"""
for i in range(self.num_new_columns):
if self.new_columns[i].commit == commit:
self.mapping[mapping_index] = i
return mapping_index + 2
# This commit isn't already in new_columns. Add it.
column = Column(commit, self._find_commit_color(commit))
self.new_columns[self.num_new_columns] = column
self.mapping[mapping_index] = self.num_new_columns
self.num_new_columns += 1
return mapping_index + 2
def _update_width(self, is_commit_in_existing_columns):
"""
Compute the width needed to display the graph for this commit. This is
the maximum width needed for any row. All other rows will be padded to
this width.
Compute the number of columns in the widest row: Count each existing
column (self.num_columns), and each new column added by this commit.
"""
max_cols = self.num_columns + self.num_parents
# Even if the current commit has no parents to be printed, it still
# takes up a column for itself.
if self.num_parents < 1:
max_cols += 1
# We added a column for the current commit as part of self.num_parents.
# If the current commit was already in self.columns, then we have double
# counted it.
if is_commit_in_existing_columns:
max_cols -= 1
# Each column takes up 2 spaces
self.width = max_cols * 2
def _update_columns(self):
"""
Swap self.columns with self.new_columns self.columns contains the state
for the previous commit, and new_columns now contains the state for our
commit.
We'll re-use the old columns array as storage to compute the new columns
list for the commit after this one.
"""
self.columns, self.new_columns = self.new_columns, self.columns
self.num_columns = self.num_new_columns
self.num_new_columns = 0
# Now update new_columns and mapping with the information for the commit
# after this one.
#
# First, make sure we have enough room. At most, there will be
# self.num_columns + self.num_parents columns for the next commit.
max_new_columns = self.num_columns + self.num_parents
# Clear out self.mapping
self.mapping_size = 2 * max_new_columns
for i in range(self.mapping_size):
self.mapping[i] = -1
# Populate self.new_columns and self.mapping
#
# Some of the parents of this commit may already be in self.columns. If
# so, self.new_columns should only contain a single entry for each such
# commit. self.mapping should contain information about where each
# current branch line is supposed to end up after the collapsing is
# performed.
seen_this = False
mapping_idx = 0
is_commit_in_columns = True
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
is_commit_in_columns = False
col_commit = self.commit
else:
col_commit = self.columns[i].commit
if col_commit == self.commit:
old_mapping_idx = mapping_idx
seen_this = True
self.commit_index = i
for parent in self._interesting_parents():
# If this is a merge, or the start of a new childless
# column, increment the current color.
if self.num_parents > 1 or not is_commit_in_columns:
self._increment_column_color()
mapping_idx = self._insert_into_new_columns(
parent,
mapping_idx)
# We always need to increment mapping_idx by at least 2, even if
# it has no interesting parents. The current commit always takes
# up at least 2 spaces.
if mapping_idx == old_mapping_idx:
mapping_idx += 2
else:
mapping_idx = self._insert_into_new_columns(col_commit,
mapping_idx)
# Shrink mapping_size to be the minimum necessary
while (self.mapping_size > 1 and
self.mapping[self.mapping_size - 1] < 0):
self.mapping_size -= 1
# Compute self.width for this commit
self._update_width(is_commit_in_columns)
def _update(self, commit, parents):
self.commit = commit
self.commit_parents = parents
self.num_parents = len(list(self._interesting_parents()))
# Store the old commit_index in prev_commit_index.
# update_columns() will update self.commit_index for this commit.
self.prev_commit_index = self.commit_index
# Call update_columns() to update
# columns, new_columns, and mapping.
self._update_columns()
self.expansion_row = 0
# Update self.state.
# Note that we don't call update_state() here, since we don't want to
# update self.prev_state. No line for self.state was ever printed.
#
# If the previous commit didn't get to the GraphState.PADDING state, it
# never finished its output. Goto GraphState.SKIP, to print out a line
# to indicate that portion of the graph is missing.
#
# If there are 3 or more parents, we may need to print extra rows before
# the commit, to expand the branch lines around it and make room for it.
# We need to do this only if there is a branch row (or more) to the
# right of this commit.
#
# If less than 3 parents, we can immediately print the commit line.
if self.state != GraphState.PADDING:
self.state = GraphState.SKIP
elif (self.num_parents >= 3 and
self.commit_index < (self.num_columns - 1)):
self.state = GraphState.PRE_COMMIT # noqa: E501 pylint: disable=redefined-variable-type
else:
self.state = GraphState.COMMIT
def _is_mapping_correct(self):
"""
The mapping is up to date if each entry is at its target, or is 1
greater than its target. (If it is 1 greater than the target, '/' will
be printed, so it will look correct on the next row.)
"""
for i in range(self.mapping_size):
target = self.mapping[i]
if target < 0:
continue
if target == i // 2:
continue
return False
return True
def _pad_horizontally(self, chars_written):
"""Add spaces to string end so all lines of a commit have the same width.
This way, fields printed to the right of the graph will remain aligned
for the entire commit.
"""
if chars_written >= self.width:
return
extra = self.width - chars_written
self.buf += ' ' * extra
def _output_padding_line(self):
"""Output a padding row, that leaves all branch lines unchanged
"""
for i in range(self.num_new_columns):
self._write_column(self.new_columns[i], '|')
self.buf += ' '
self._pad_horizontally(self.num_new_columns * 2)
def _output_skip_line(self):
"""Output an ellipsis to indicate that a portion of the graph is missing.
"""
self.buf += '...'
self._pad_horizontally(3)
if self.num_parents >= 3 and self.commit_index < self.num_columns - 1:
self._update_state(GraphState.PRE_COMMIT)
else:
self._update_state(GraphState.COMMIT)
def _output_pre_commit_line(self):
"""Formats a row with increased space around a commit with multiple parents.
This is done in order to make room for the commit. It should only be
called when there are 3 or more parents. We need 2 extra rows for every
parent over 2.
"""
assert self.num_parents >= 3, 'not enough parents to add expansion row'
num_expansion_rows = (self.num_parents - 2) * 2
# self.expansion_row tracks the current expansion row we are on.
# It should be in the range [0, num_expansion_rows - 1]
assert (0 <= self.expansion_row < num_expansion_rows), \
'wrong number of expansion rows'
# Output the row
seen_this = False
chars_written = 0
for i in range(self.num_columns):
col = self.columns[i]
if col.commit == self.commit:
seen_this = True
self._write_column(col, '|')
self.buf += ' ' * self.expansion_row
chars_written += 1 + self.expansion_row
elif seen_this and (self.expansion_row == 0):
# This is the first line of the pre-commit output. If the
# previous commit was a merge commit and ended in the
# GraphState.POST_MERGE state, all branch lines after
# self.prev_commit_index were printed as "\" on the previous
# line. Continue to print them as "\" on this line. Otherwise,
# print the branch lines as "|".
if (self.prev_state == GraphState.POST_MERGE and
self.prev_commit_index < i):
self._write_column(col, '\\')
else:
self._write_column(col, '|')
chars_written += 1
elif seen_this and (self.expansion_row > 0):
self._write_column(col, '\\')
chars_written += 1
else:
self._write_column(col, '|')
chars_written += 1
self.buf += ' '
chars_written += 1
self._pad_horizontally(chars_written)
# Increment self.expansion_row, and move to state GraphState.COMMIT if
# necessary
self.expansion_row += 1
if self.expansion_row >= num_expansion_rows:
self._update_state(GraphState.COMMIT)
# Draw an octopus merge and return the number of characters written.
def _draw_octopus_merge(self):
"""
Here dashless_commits represents the number of parents which don't
need to have dashes (because their edges fit neatly under the commit).
"""
dashless_commits = 2
num_dashes = ((self.num_parents - dashless_commits) * 2) - 1
for i in range(num_dashes):
col_num = i // 2 + dashless_commits + self.commit_index
self._write_column(self.new_columns[col_num], '-')
col_num = num_dashes // 2 + dashless_commits + self.commit_index
self._write_column(self.new_columns[col_num], '.')
return num_dashes + 1
def _output_commit_line(self): # noqa: C901, E501 pylint: disable=too-many-branches
"""
Output the row containing this commit Iterate up to and including
self.num_columns, since the current commit may not be in any of the
existing columns. (This happens when the current commit doesn't have
any children that we have already processed.)
"""
seen_this = False
chars_written = 0
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
col_commit = self.commit
else:
col = self.columns[i]
col_commit = self.columns[i].commit
if col_commit == self.commit:
seen_this = True
self.buf += '*'
chars_written += 1
if self.num_parents > 2:
chars_written += self._draw_octopus_merge()
elif seen_this and self.num_parents > 2:
self._write_column(col, '\\')
chars_written += 1
elif seen_this and self.num_parents == 2:
# This is a 2-way merge commit. There is no
# GraphState.PRE_COMMIT stage for 2-way merges, so this is the
# first line of output for this commit. Check to see what the
# previous line of output was.
#
# If it was GraphState.POST_MERGE, the branch line coming into
# this commit may have been '\', and not '|' or '/'. If so,
# output the branch line as '\' on this line, instead of '|'.
# This makes the output look nicer.
if (self.prev_state == GraphState.POST_MERGE and
self.prev_commit_index < i):
self._write_column(col, '\\')
else:
self._write_column(col, '|')
chars_written += 1
else:
self._write_column(col, '|')
chars_written += 1
self.buf += ' '
chars_written += 1
self._pad_horizontally(chars_written)
if self.num_parents > 1:
self._update_state(GraphState.POST_MERGE)
elif self._is_mapping_correct():
self._update_state(GraphState.PADDING)
else:
self._update_state(GraphState.COLLAPSING)
def _find_new_column_by_commit(self, commit):
for i in range(self.num_new_columns):
if self.new_columns[i].commit == commit:
return self.new_columns[i]
return None
def _output_post_merge_line(self):
seen_this = False
chars_written = 0
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
col_commit = self.commit
else:
col = self.columns[i]
col_commit = col.commit
if col_commit == self.commit:
# Since the current commit is a merge find the columns for the
# parent commits in new_columns and use those to format the
# edges.
seen_this = True
parents = self._interesting_parents()
assert parents, 'merge has no parents'
par_column = self._find_new_column_by_commit(next(parents))
assert par_column, 'parent column not found'
self._write_column(par_column, '|')
chars_written += 1
for parent in parents:
assert parent, 'parent is not valid'
par_column = self._find_new_column_by_commit(parent)
assert par_column, 'parent column not found'
self._write_column(par_column, '\\')
self.buf += ' '
chars_written += (self.num_parents - 1) * 2
elif seen_this:
self._write_column(col, '\\')
self.buf += ' '
chars_written += 2
else:
self._write_column(col, '|')
self.buf += ' '
chars_written += 2
self._pad_horizontally(chars_written)
if self._is_mapping_correct():
self._update_state(GraphState.PADDING)
else:
self._update_state(GraphState.COLLAPSING)
def _output_collapsing_line(self): # noqa: C901, E501 pylint: disable=too-many-branches
used_horizontal = False
horizontal_edge = -1
horizontal_edge_target = -1
# Clear out the new_mapping array
for i in range(self.mapping_size):
self.new_mapping[i] = -1
for i in range(self.mapping_size):
target = self.mapping[i]
if target < 0:
continue
# Since update_columns() always inserts the leftmost column first,
# each branch's target location should always be either its current
# location or to the left of its current location.
#
# We never have to move branches to the right. This makes the graph
# much more legible, since whenever branches cross, only one is
# moving directions.
assert target * 2 <= i, \
'position {} targetting column {}'.format(i, target * 2)
if target * 2 == i:
# This column is already in the correct place
assert self.new_mapping[i] == -1
self.new_mapping[i] = target
elif self.new_mapping[i - 1] < 0:
# Nothing is to the left. Move to the left by one.
self.new_mapping[i - 1] = target
# If there isn't already an edge moving horizontally select this one.
if horizontal_edge == -1:
horizontal_edge = i
horizontal_edge_target = target
# The variable target is the index of the graph column, and
# therefore target * 2 + 3 is the actual screen column of
# the first horizontal line.
for j in range((target * 2) + 3, i - 2, 2):
self.new_mapping[j] = target
elif self.new_mapping[i - 1] == target:
# There is a branch line to our left already, and it is our
# target. We combine with this line, since we share the same
# parent commit.
#
# We don't have to add anything to the output or new_mapping,
# since the existing branch line has already taken care of it.
pass
else:
# There is a branch line to our left, but it isn't our target.
# We need to cross over it.
#
# The space just to the left of this branch should always be empty.
#
# The branch to the left of that space should be our eventual target.
assert self.new_mapping[i - 1] > target
assert self.new_mapping[i - 2] < 0
assert self.new_mapping[i - 3] == target
self.new_mapping[i - 2] = target
# Mark this branch as the horizontal edge to prevent any other
# edges from moving horizontally.
if horizontal_edge == -1:
horizontal_edge = i
# The new mapping may be 1 smaller than the old mapping
if self.new_mapping[self.mapping_size - 1] < 0:
self.mapping_size -= 1
# Output a line based on the new mapping info
for i in range(self.mapping_size):
target = self.new_mapping[i]
if target < 0:
self.buf += ' '
elif target * 2 == i:
self._write_column(self.new_columns[target], '|')
elif target == horizontal_edge_target and i != horizontal_edge - 1:
# Set the mappings for all but the first segment to -1 so that
# they won't continue into the next line.
if i != (target * 2) + 3:
self.new_mapping[i] = -1
used_horizontal = True
self._write_column(self.new_columns[target], '_')
else:
if used_horizontal and i < horizontal_edge:
self.new_mapping[i] = -1
self._write_column(self.new_columns[target], '/')
self._pad_horizontally(self.mapping_size)
self.mapping, self.new_mapping = self.new_mapping, self.mapping
# If self.mapping indicates that all of the branch lines are already in
# the correct positions, we are done. Otherwise, we need to collapse
# some branch lines together.
if self._is_mapping_correct():
self._update_state(GraphState.PADDING)
def _next_line(self): # pylint: disable=too-many-return-statements
if self.state == GraphState.PADDING:
self._output_padding_line()
return False
elif self.state == GraphState.SKIP:
self._output_skip_line()
return False
elif self.state == GraphState.PRE_COMMIT:
self._output_pre_commit_line()
return False
elif self.state == GraphState.COMMIT:
self._output_commit_line()
return True
elif self.state == GraphState.POST_MERGE:
self._output_post_merge_line()
return False
elif self.state == GraphState.COLLAPSING:
self._output_collapsing_line()
return False
else:
return False
def _padding_line(self):
"""Output a padding line in the graph.
This is similar to next_line(). However, it is guaranteed to never print
the current commit line. Instead, if the commit line is next, it will
simply output a line of vertical padding, extending the branch lines
downwards, but leaving them otherwise unchanged.
"""
if self.state != GraphState.COMMIT:
self._next_line()
return
# Output the row containing this commit
# Iterate up to and including self.num_columns, since the current commit
# may not be in any of the existing columns. (This happens when the
# current commit doesn't have any children that we have already
# processed.)
for i in range(self.num_columns):
col = self.columns[i]
self._write_column(col, '|')
if col.commit == self.commit and self.num_parents > 2:
self.buf += ' ' * (self.num_parents - 2) * 2
else:
self.buf += ' '
self._pad_horizontally(self.num_columns)
# Update self.prev_state since we have output a padding line
self.prev_state = GraphState.PADDING
def _is_commit_finished(self):
return self.state == GraphState.PADDING
def _show_commit(self):
shown_commit_line = False
# When showing a diff of a merge against each of its parents, we are
# called once for each parent without update having been called. In this
# case, simply output a single padding line.
if self._is_commit_finished():
self._show_padding()
shown_commit_line = True
while not shown_commit_line and not self._is_commit_finished():
shown_commit_line = self._next_line()
self.outfile.write(self.buf)
if not shown_commit_line:
self.outfile.write('\n')
self.buf = ''
def _show_padding(self):
self._padding_line()
self.outfile.write(self.buf)
self.buf = ''
def _show_remainder(self):
shown = False
if self._is_commit_finished():
return False
while True:
self._next_line()
self.outfile.write(self.buf)
self.buf = ''
shown = True
if not self._is_commit_finished():
self.outfile.write('\n')
else:
break
return shown
| # -*- coding: utf-8 -*-
"""
Portions of this code have been taken and modified from the "asciidag" project.
Access Date:
Commit: 7c1eefe3895630dc3906bbe9d553e0169202756a
PermalinkURL
URL: https://github.com/sambrightman/asciidag/
File: asciidag/graph.py
Commit: 7c1eefe3895630dc3906bbe9d553e0169202756a
Accessed: 25 MAR 2019
asciidag License
-------------------------------------------------------------------------------
License: Mozilla Public License 2.0
URL: https://github.com/sambrightman/asciidag/blob/7c1eefe3895630dc3906bbe9d553e0169202756a/LICENSE
"""
import sys
import time
from enum import Enum
__all__ = ('Graph',)
COLOR_NORMAL = ""
COLOR_RESET = "\033[m"
COLOR_BOLD = "\033[1m"
COLOR_RED = "\033[31m"
COLOR_GREEN = "\033[32m"
COLOR_YELLOW = "\033[33m"
COLOR_BLUE = "\033[34m"
COLOR_MAGENTA = "\033[35m"
COLOR_CYAN = "\033[36m"
COLOR_BOLD_RED = "\033[1;31m"
COLOR_BOLD_GREEN = "\033[1;32m"
COLOR_BOLD_YELLOW = "\033[1;33m"
COLOR_BOLD_BLUE = "\033[1;34m"
COLOR_BOLD_MAGENTA = "\033[1;35m"
COLOR_BOLD_CYAN = "\033[1;36m"
COLOR_BG_RED = "\033[41m"
COLOR_BG_GREEN = "\033[42m"
COLOR_BG_YELLOW = "\033[43m"
COLOR_BG_BLUE = "\033[44m"
COLOR_BG_MAGENTA = "\033[45m"
COLOR_BG_CYAN = "\033[46m"
COLUMN_COLORS_ANSI = [
COLOR_BOLD_RED,
COLOR_BOLD_GREEN,
COLOR_BOLD_YELLOW,
COLOR_BOLD_BLUE,
COLOR_BOLD_MAGENTA,
COLOR_BOLD_CYAN,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW,
COLOR_BLUE,
COLOR_MAGENTA,
COLOR_CYAN,
COLOR_RESET,
]
class Column(object): # pylint: disable=too-few-public-methods
"""A single column of output.
Attributes:
commit -- The parent commit of this column.
color -- The color to (optionally) print this column in.
This is an index into column_colors.
"""
def __init__(self, commit, color):
self.commit = commit
self.color = color
class GraphState(Enum): # pylint: disable=too-few-public-methods
PADDING = 0
SKIP = 1
PRE_COMMIT = 2
COMMIT = 3
POST_MERGE = 4
COLLAPSING = 5
class Graph(object): # pragma: no cover
"""
The commit currently being processed
struct commit *commit
The number of interesting parents that this commit has. Note that this is
not the same as the actual number of parents. This count excludes parents
that won't be printed in the graph output, as determined by
is_interesting().
int num_parents
The width of the graph output for this commit. All rows for this commit are
padded to this width, so that messages printed after the graph output are
aligned.
int width
The next expansion row to print when state is GraphState.PRE_COMMIT
int expansion_row
The current output state. This tells us what kind of line next_line()
should output.
enum graph_state state
The output state for the previous line of output. This is primarily used to
determine how the first merge line should appear, based on the last line of
the previous commit.
enum graph_state prev_state
The index of the column that refers to this commit. If none of the incoming
columns refer to this commit, this will be equal to num_columns.
int commit_index
The commit_index for the previously displayed commit. This is used to
determine how the first line of a merge graph output should appear, based
on the last line of the previous commit.
int prev_commit_index
The maximum number of columns that can be stored in the columns and
new_columns arrays. This is also half the number of entries that can be
stored in the mapping and new_mapping arrays.
int column_capacity
The number of columns (also called "branch lines" in some places)
int num_columns
The number of columns in the new_columns array
int num_new_columns
The number of entries in the mapping array
int mapping_size
The column state before we output the current commit.
struct column *columns
The new column state after we output the current commit. Only valid when
state is GraphState.COLLAPSING.
struct column *new_columns
An array that tracks the current state of each character in the output line
during state GraphState.COLLAPSING. Each entry is -1 if this character is
empty, or a non-negative integer if the character contains a branch line.
The value of the integer indicates the target position for this branch
line. (I.e., this array maps the current column positions to their desired
positions.)
The maximum capacity of this array is always sizeof(int) * 2 *
column_capacity.
int *mapping
A temporary array for computing the next mapping state while we are
outputting a mapping line. This is stored as part of the git_graph simply
so we don't have to allocate a new temporary array each time we have to
output a collapsing line.
int *new_mapping
The current default column color being used. This is stored as an index
into the array column_colors.
unsigned short default_column_color
"""
def __init__(self,
fh=None,
first_parent_only=False,
use_color=True,
column_colors=None):
"""State machine for processing DAG nodes into ASCII graphs.
show_nodes() deals with sorting the nodes from tips down into
topological order. It then displays them line-by-line.
"""
self.commit = None
self.buf = ''
if fh is None:
self.outfile = sys.stdout
else:
self.outfile = fh
self.first_parent_only = first_parent_only
self.use_color = use_color
if column_colors is None:
self.column_colors = COLUMN_COLORS_ANSI
else:
self.column_colors = column_colors
self.num_parents = 0
self.width = 0
self.expansion_row = 0
self.state = GraphState.PADDING
self.prev_state = GraphState.PADDING
self.commit_index = 0
self.prev_commit_index = 0
self.num_columns = 0
self.num_new_columns = 0
self.mapping_size = 0
# Start the column color at the maximum value, since we'll always
# increment it for the first commit we output. This way we start at 0
# for the first commit.
self.default_column_color = len(self.column_colors) - 1
self.columns = {}
self.new_columns = {}
self.mapping = {}
self.new_mapping = {}
def show_nodes(self, dag, spec, branch, start, order, stop='',
*, show_time=True, show_user=True):
"""Printing function that displays a DAG representing the commit history
Print a revision history alongside a revision graph drawn with ASCII
characters. Nodes printed as an * character are parents of the working
directory. Any unreachable (but referenced nodes) are displayed at +
Parameters
----------
dag : dict
directed acyclic graph of nodes and connections in commits. No more than
2 connections per node
spec: dict
dictionary of commit specification (user name, email, message, etc).
branch : dict
dict of commit hash -> list of branch names whose HEAD commit is at
that key.
start : string
commit hash to act as the top of the topological sort.
order: list
time based ordering of commit hashs
stop : str, optional
commit hash to stop generating the graph at if the DAG contains more
history than is needed (the default is '', which is the "parent" of
the initial repository commit.)
"""
if start == stop:
return
fmtSpec = {}
for cmt, cmtspec in spec.items():
if show_time:
t = f"({time.strftime('%d%b%Y %H:%M:%S', time.gmtime(cmtspec['commit_time']))})"
else:
t = ''
if show_user:
u = f"({cmtspec['commit_user']})"
else:
u = ''
m = cmtspec['commit_message']
br = ' '
if cmt in branch:
for branchName in branch[cmt]:
if self.use_color is True:
br = f'{br}({COLOR_BOLD_RED}{branchName}{COLOR_RESET}) '
else:
br = f'{br}({branchName}) '
fmtSpec[cmt] = f'{cmt}{br}{t}{u}: {m}'
for rev in order:
parents = dag[rev]
self._update(rev, parents)
self._show_commit()
self.outfile.write(fmtSpec[rev])
if not self._is_commit_finished():
self.outfile.write('\n')
self._show_remainder()
self.outfile.write('\n')
def _write_column(self, col, col_char):
if col.color is not None:
self.buf += self.column_colors[col.color]
self.buf += col_char
if col.color is not None:
self.buf += self.column_colors[-1]
def _update_state(self, state):
self.prev_state = self.state
self.state = state
def _interesting_parents(self):
for parent in self.commit_parents:
yield parent
if self.first_parent_only:
break
def _get_current_column_color(self):
if not self.use_color:
return None
return self.default_column_color
def _increment_column_color(self):
self.default_column_color = ((self.default_column_color + 1)
% len(self.column_colors))
def _find_commit_color(self, commit):
for i in range(self.num_columns):
if self.columns[i].commit == commit:
return self.columns[i].color
return self._get_current_column_color()
def _insert_into_new_columns(self, commit, mapping_index):
"""
If the commit is already in the new_columns list, we don't need to add
it. Just update the mapping correctly.
"""
for i in range(self.num_new_columns):
if self.new_columns[i].commit == commit:
self.mapping[mapping_index] = i
return mapping_index + 2
# This commit isn't already in new_columns. Add it.
column = Column(commit, self._find_commit_color(commit))
self.new_columns[self.num_new_columns] = column
self.mapping[mapping_index] = self.num_new_columns
self.num_new_columns += 1
return mapping_index + 2
def _update_width(self, is_commit_in_existing_columns):
"""
Compute the width needed to display the graph for this commit. This is
the maximum width needed for any row. All other rows will be padded to
this width.
Compute the number of columns in the widest row: Count each existing
column (self.num_columns), and each new column added by this commit.
"""
max_cols = self.num_columns + self.num_parents
# Even if the current commit has no parents to be printed, it still
# takes up a column for itself.
if self.num_parents < 1:
max_cols += 1
# We added a column for the current commit as part of self.num_parents.
# If the current commit was already in self.columns, then we have double
# counted it.
if is_commit_in_existing_columns:
max_cols -= 1
# Each column takes up 2 spaces
self.width = max_cols * 2
def _update_columns(self):
"""
Swap self.columns with self.new_columns self.columns contains the state
for the previous commit, and new_columns now contains the state for our
commit.
We'll re-use the old columns array as storage to compute the new columns
list for the commit after this one.
"""
self.columns, self.new_columns = self.new_columns, self.columns
self.num_columns = self.num_new_columns
self.num_new_columns = 0
# Now update new_columns and mapping with the information for the commit
# after this one.
#
# First, make sure we have enough room. At most, there will be
# self.num_columns + self.num_parents columns for the next commit.
max_new_columns = self.num_columns + self.num_parents
# Clear out self.mapping
self.mapping_size = 2 * max_new_columns
for i in range(self.mapping_size):
self.mapping[i] = -1
# Populate self.new_columns and self.mapping
#
# Some of the parents of this commit may already be in self.columns. If
# so, self.new_columns should only contain a single entry for each such
# commit. self.mapping should contain information about where each
# current branch line is supposed to end up after the collapsing is
# performed.
seen_this = False
mapping_idx = 0
is_commit_in_columns = True
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
is_commit_in_columns = False
col_commit = self.commit
else:
col_commit = self.columns[i].commit
if col_commit == self.commit:
old_mapping_idx = mapping_idx
seen_this = True
self.commit_index = i
for parent in self._interesting_parents():
# If this is a merge, or the start of a new childless
# column, increment the current color.
if self.num_parents > 1 or not is_commit_in_columns:
self._increment_column_color()
mapping_idx = self._insert_into_new_columns(
parent,
mapping_idx)
# We always need to increment mapping_idx by at least 2, even if
# it has no interesting parents. The current commit always takes
# up at least 2 spaces.
if mapping_idx == old_mapping_idx:
mapping_idx += 2
else:
mapping_idx = self._insert_into_new_columns(col_commit,
mapping_idx)
# Shrink mapping_size to be the minimum necessary
while (self.mapping_size > 1 and
self.mapping[self.mapping_size - 1] < 0):
self.mapping_size -= 1
# Compute self.width for this commit
self._update_width(is_commit_in_columns)
def _update(self, commit, parents):
self.commit = commit
self.commit_parents = parents
self.num_parents = len(list(self._interesting_parents()))
# Store the old commit_index in prev_commit_index.
# update_columns() will update self.commit_index for this commit.
self.prev_commit_index = self.commit_index
# Call update_columns() to update
# columns, new_columns, and mapping.
self._update_columns()
self.expansion_row = 0
# Update self.state.
# Note that we don't call update_state() here, since we don't want to
# update self.prev_state. No line for self.state was ever printed.
#
# If the previous commit didn't get to the GraphState.PADDING state, it
# never finished its output. Goto GraphState.SKIP, to print out a line
# to indicate that portion of the graph is missing.
#
# If there are 3 or more parents, we may need to print extra rows before
# the commit, to expand the branch lines around it and make room for it.
# We need to do this only if there is a branch row (or more) to the
# right of this commit.
#
# If less than 3 parents, we can immediately print the commit line.
if self.state != GraphState.PADDING:
self.state = GraphState.SKIP
elif (self.num_parents >= 3 and
self.commit_index < (self.num_columns - 1)):
self.state = GraphState.PRE_COMMIT # noqa: E501 pylint: disable=redefined-variable-type
else:
self.state = GraphState.COMMIT
def _is_mapping_correct(self):
"""
The mapping is up to date if each entry is at its target, or is 1
greater than its target. (If it is 1 greater than the target, '/' will
be printed, so it will look correct on the next row.)
"""
for i in range(self.mapping_size):
target = self.mapping[i]
if target < 0:
continue
if target == i // 2:
continue
return False
return True
def _pad_horizontally(self, chars_written):
"""Add spaces to string end so all lines of a commit have the same width.
This way, fields printed to the right of the graph will remain aligned
for the entire commit.
"""
if chars_written >= self.width:
return
extra = self.width - chars_written
self.buf += ' ' * extra
def _output_padding_line(self):
"""Output a padding row, that leaves all branch lines unchanged
"""
for i in range(self.num_new_columns):
self._write_column(self.new_columns[i], '|')
self.buf += ' '
self._pad_horizontally(self.num_new_columns * 2)
def _output_skip_line(self):
"""Output an ellipsis to indicate that a portion of the graph is missing.
"""
self.buf += '...'
self._pad_horizontally(3)
if self.num_parents >= 3 and self.commit_index < self.num_columns - 1:
self._update_state(GraphState.PRE_COMMIT)
else:
self._update_state(GraphState.COMMIT)
def _output_pre_commit_line(self):
"""Formats a row with increased space around a commit with multiple parents.
This is done in order to make room for the commit. It should only be
called when there are 3 or more parents. We need 2 extra rows for every
parent over 2.
"""
assert self.num_parents >= 3, 'not enough parents to add expansion row'
num_expansion_rows = (self.num_parents - 2) * 2
# self.expansion_row tracks the current expansion row we are on.
# It should be in the range [0, num_expansion_rows - 1]
assert (0 <= self.expansion_row < num_expansion_rows), \
'wrong number of expansion rows'
# Output the row
seen_this = False
chars_written = 0
for i in range(self.num_columns):
col = self.columns[i]
if col.commit == self.commit:
seen_this = True
self._write_column(col, '|')
self.buf += ' ' * self.expansion_row
chars_written += 1 + self.expansion_row
elif seen_this and (self.expansion_row == 0):
# This is the first line of the pre-commit output. If the
# previous commit was a merge commit and ended in the
# GraphState.POST_MERGE state, all branch lines after
# self.prev_commit_index were printed as "\" on the previous
# line. Continue to print them as "\" on this line. Otherwise,
# print the branch lines as "|".
if (self.prev_state == GraphState.POST_MERGE and
self.prev_commit_index < i):
self._write_column(col, '\\')
else:
self._write_column(col, '|')
chars_written += 1
elif seen_this and (self.expansion_row > 0):
self._write_column(col, '\\')
chars_written += 1
else:
self._write_column(col, '|')
chars_written += 1
self.buf += ' '
chars_written += 1
self._pad_horizontally(chars_written)
# Increment self.expansion_row, and move to state GraphState.COMMIT if
# necessary
self.expansion_row += 1
if self.expansion_row >= num_expansion_rows:
self._update_state(GraphState.COMMIT)
# Draw an octopus merge and return the number of characters written.
def _draw_octopus_merge(self):
"""
Here dashless_commits represents the number of parents which don't
need to have dashes (because their edges fit neatly under the commit).
"""
dashless_commits = 2
num_dashes = ((self.num_parents - dashless_commits) * 2) - 1
for i in range(num_dashes):
col_num = i // 2 + dashless_commits + self.commit_index
self._write_column(self.new_columns[col_num], '-')
col_num = num_dashes // 2 + dashless_commits + self.commit_index
self._write_column(self.new_columns[col_num], '.')
return num_dashes + 1
def _output_commit_line(self): # noqa: C901, E501 pylint: disable=too-many-branches
"""
Output the row containing this commit Iterate up to and including
self.num_columns, since the current commit may not be in any of the
existing columns. (This happens when the current commit doesn't have
any children that we have already processed.)
"""
seen_this = False
chars_written = 0
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
col_commit = self.commit
else:
col = self.columns[i]
col_commit = self.columns[i].commit
if col_commit == self.commit:
seen_this = True
self.buf += '*'
chars_written += 1
if self.num_parents > 2:
chars_written += self._draw_octopus_merge()
elif seen_this and self.num_parents > 2:
self._write_column(col, '\\')
chars_written += 1
elif seen_this and self.num_parents == 2:
# This is a 2-way merge commit. There is no
# GraphState.PRE_COMMIT stage for 2-way merges, so this is the
# first line of output for this commit. Check to see what the
# previous line of output was.
#
# If it was GraphState.POST_MERGE, the branch line coming into
# this commit may have been '\', and not '|' or '/'. If so,
# output the branch line as '\' on this line, instead of '|'.
# This makes the output look nicer.
if (self.prev_state == GraphState.POST_MERGE and
self.prev_commit_index < i):
self._write_column(col, '\\')
else:
self._write_column(col, '|')
chars_written += 1
else:
self._write_column(col, '|')
chars_written += 1
self.buf += ' '
chars_written += 1
self._pad_horizontally(chars_written)
if self.num_parents > 1:
self._update_state(GraphState.POST_MERGE)
elif self._is_mapping_correct():
self._update_state(GraphState.PADDING)
else:
self._update_state(GraphState.COLLAPSING)
def _find_new_column_by_commit(self, commit):
for i in range(self.num_new_columns):
if self.new_columns[i].commit == commit:
return self.new_columns[i]
return None
def _output_post_merge_line(self):
seen_this = False
chars_written = 0
for i in range(self.num_columns + 1):
if i == self.num_columns:
if seen_this:
break
col_commit = self.commit
else:
col = self.columns[i]
col_commit = col.commit
if col_commit == self.commit:
# Since the current commit is a merge find the columns for the
# parent commits in new_columns and use those to format the
# edges.
seen_this = True
parents = self._interesting_parents()
assert parents, 'merge has no parents'
par_column = self._find_new_column_by_commit(next(parents))
assert par_column, 'parent column not found'
self._write_column(par_column, '|')
chars_written += 1
for parent in parents:
assert parent, 'parent is not valid'
par_column = self._find_new_column_by_commit(parent)
assert par_column, 'parent column not found'
self._write_column(par_column, '\\')
self.buf += ' '
chars_written += (self.num_parents - 1) * 2
elif seen_this:
self._write_column(col, '\\')
self.buf += ' '
chars_written += 2
else:
self._write_column(col, '|')
self.buf += ' '
chars_written += 2
self._pad_horizontally(chars_written)
if self._is_mapping_correct():
self._update_state(GraphState.PADDING)
else:
self._update_state(GraphState.COLLAPSING)
def _output_collapsing_line(self): # noqa: C901, E501 pylint: disable=too-many-branches
used_horizontal = False
horizontal_edge = -1
horizontal_edge_target = -1
# Clear out the new_mapping array
for i in range(self.mapping_size):
self.new_mapping[i] = -1
for i in range(self.mapping_size):
target = self.mapping[i]
if target < 0:
continue
# Since update_columns() always inserts the leftmost column first,
# each branch's target location should always be either its current
# location or to the left of its current location.
#
# We never have to move branches to the right. This makes the graph
# much more legible, since whenever branches cross, only one is
# moving directions.
assert target * 2 <= i, \
'position {} targetting column {}'.format(i, target * 2)
if target * 2 == i:
# This column is already in the correct place
assert self.new_mapping[i] == -1
self.new_mapping[i] = target
elif self.new_mapping[i - 1] < 0:
# Nothing is to the left. Move to the left by one.
self.new_mapping[i - 1] = target
# If there isn't already an edge moving horizontally select this one.
if horizontal_edge == -1:
horizontal_edge = i
horizontal_edge_target = target
# The variable target is the index of the graph column, and
# therefore target * 2 + 3 is the actual screen column of
# the first horizontal line.
for j in range((target * 2) + 3, i - 2, 2):
self.new_mapping[j] = target
elif self.new_mapping[i - 1] == target:
# There is a branch line to our left already, and it is our
# target. We combine with this line, since we share the same
# parent commit.
#
# We don't have to add anything to the output or new_mapping,
# since the existing branch line has already taken care of it.
pass
else:
# There is a branch line to our left, but it isn't our target.
# We need to cross over it.
#
# The space just to the left of this branch should always be empty.
#
# The branch to the left of that space should be our eventual target.
assert self.new_mapping[i - 1] > target
assert self.new_mapping[i - 2] < 0
assert self.new_mapping[i - 3] == target
self.new_mapping[i - 2] = target
# Mark this branch as the horizontal edge to prevent any other
# edges from moving horizontally.
if horizontal_edge == -1:
horizontal_edge = i
# The new mapping may be 1 smaller than the old mapping
if self.new_mapping[self.mapping_size - 1] < 0:
self.mapping_size -= 1
# Output a line based on the new mapping info
for i in range(self.mapping_size):
target = self.new_mapping[i]
if target < 0:
self.buf += ' '
elif target * 2 == i:
self._write_column(self.new_columns[target], '|')
elif target == horizontal_edge_target and i != horizontal_edge - 1:
# Set the mappings for all but the first segment to -1 so that
# they won't continue into the next line.
if i != (target * 2) + 3:
self.new_mapping[i] = -1
used_horizontal = True
self._write_column(self.new_columns[target], '_')
else:
if used_horizontal and i < horizontal_edge:
self.new_mapping[i] = -1
self._write_column(self.new_columns[target], '/')
self._pad_horizontally(self.mapping_size)
self.mapping, self.new_mapping = self.new_mapping, self.mapping
# If self.mapping indicates that all of the branch lines are already in
# the correct positions, we are done. Otherwise, we need to collapse
# some branch lines together.
if self._is_mapping_correct():
self._update_state(GraphState.PADDING)
def _next_line(self): # pylint: disable=too-many-return-statements
if self.state == GraphState.PADDING:
self._output_padding_line()
return False
elif self.state == GraphState.SKIP:
self._output_skip_line()
return False
elif self.state == GraphState.PRE_COMMIT:
self._output_pre_commit_line()
return False
elif self.state == GraphState.COMMIT:
self._output_commit_line()
return True
elif self.state == GraphState.POST_MERGE:
self._output_post_merge_line()
return False
elif self.state == GraphState.COLLAPSING:
self._output_collapsing_line()
return False
else:
return False
def _padding_line(self):
"""Output a padding line in the graph.
This is similar to next_line(). However, it is guaranteed to never print
the current commit line. Instead, if the commit line is next, it will
simply output a line of vertical padding, extending the branch lines
downwards, but leaving them otherwise unchanged.
"""
if self.state != GraphState.COMMIT:
self._next_line()
return
# Output the row containing this commit
# Iterate up to and including self.num_columns, since the current commit
# may not be in any of the existing columns. (This happens when the
# current commit doesn't have any children that we have already
# processed.)
for i in range(self.num_columns):
col = self.columns[i]
self._write_column(col, '|')
if col.commit == self.commit and self.num_parents > 2:
self.buf += ' ' * (self.num_parents - 2) * 2
else:
self.buf += ' '
self._pad_horizontally(self.num_columns)
# Update self.prev_state since we have output a padding line
self.prev_state = GraphState.PADDING
def _is_commit_finished(self):
return self.state == GraphState.PADDING
def _show_commit(self):
shown_commit_line = False
# When showing a diff of a merge against each of its parents, we are
# called once for each parent without update having been called. In this
# case, simply output a single padding line.
if self._is_commit_finished():
self._show_padding()
shown_commit_line = True
while not shown_commit_line and not self._is_commit_finished():
shown_commit_line = self._next_line()
self.outfile.write(self.buf)
if not shown_commit_line:
self.outfile.write('\n')
self.buf = ''
def _show_padding(self):
self._padding_line()
self.outfile.write(self.buf)
self.buf = ''
def _show_remainder(self):
shown = False
if self._is_commit_finished():
return False
while True:
self._next_line()
self.outfile.write(self.buf)
self.buf = ''
shown = True
if not self._is_commit_finished():
self.outfile.write('\n')
else:
break
return shown
|
"""jsonld admin routes."""
from aiohttp import web
from aiohttp_apispec import docs, request_schema, response_schema
from marshmallow import INCLUDE, Schema, fields
from pydid import VerificationMethod
from ...admin.request_context import AdminRequestContext
from ...config.base import InjectionError
from ...resolver.base import ResolverError
from ...resolver.did_resolver import DIDResolver
from ...wallet.error import WalletError
from ..models.openapi import OpenAPISchema
from .credential import sign_credential, verify_credential
from .error import (
BaseJSONLDMessagingError,
InvalidVerificationMethod,
MissingVerificationMethodError,
)
class SignatureOptionsSchema(Schema):
"""Schema for LD signature options."""
type = fields.Str(required=False)
verificationMethod = fields.Str(required=True)
proofPurpose = fields.Str(required=True)
challenge = fields.Str(required=False)
domain = fields.Str(required=False)
class DocSchema(OpenAPISchema):
"""Schema for LD doc to sign."""
credential = fields.Dict(
required=True,
description="Credential to sign",
)
options = fields.Nested(
SignatureOptionsSchema,
required=True,
description="Signature options",
)
class SignRequestSchema(OpenAPISchema):
"""Request schema for signing a jsonld doc."""
verkey = fields.Str(required=True, description="Verkey to use for signing")
doc = fields.Nested(
DocSchema,
required=True,
)
class SignResponseSchema(OpenAPISchema):
"""Response schema for a signed jsonld doc."""
signed_doc = fields.Dict(description="Signed document", required=False)
error = fields.Str(description="Error text", required=False)
@docs(tags=["jsonld"], summary="Sign a JSON-LD structure and return it")
@request_schema(SignRequestSchema())
@response_schema(SignResponseSchema(), 200, description="")
async def sign(request: web.BaseRequest):
"""
Request handler for signing a jsonld doc.
Args:
request: aiohttp request object
"""
response = {}
body = await request.json()
doc = body.get("doc")
try:
context: AdminRequestContext = request["context"]
async with context.session() as session:
doc_with_proof = await sign_credential(
session, doc.get("credential"), doc.get("options"), body.get("verkey")
)
response["signed_doc"] = doc_with_proof
except (BaseJSONLDMessagingError) as err:
response["error"] = str(err)
except (WalletError, InjectionError):
raise web.HTTPForbidden(reason="No wallet available")
return web.json_response(response)
class SignedDocSchema(OpenAPISchema):
"""Verifiable doc schema."""
class Meta:
"""Keep unknown values."""
unknown = INCLUDE
proof = fields.Nested(
SignatureOptionsSchema,
unknown=INCLUDE,
required=True,
description="Linked data proof",
)
class VerifyRequestSchema(OpenAPISchema):
"""Request schema for signing a jsonld doc."""
verkey = fields.Str(
required=False, description="Verkey to use for doc verification"
)
doc = fields.Nested(SignedDocSchema, required=True, description="Signed document")
class VerifyResponseSchema(OpenAPISchema):
"""Response schema for verification result."""
valid = fields.Bool(required=True)
error = fields.Str(description="Error text", required=False)
@docs(tags=["jsonld"], summary="Verify a JSON-LD structure.")
@request_schema(VerifyRequestSchema())
@response_schema(VerifyResponseSchema(), 200, description="")
async def verify(request: web.BaseRequest):
"""
Request handler for signing a jsonld doc.
Args:
request: aiohttp request object
"""
response = {"valid": False}
try:
context: AdminRequestContext = request["context"]
profile = context.profile
body = await request.json()
verkey = body.get("verkey")
doc = body.get("doc")
async with context.session() as session:
if verkey is None:
resolver = session.inject(DIDResolver)
ver_meth_expanded = await resolver.dereference(
profile, doc["proof"]["verificationMethod"]
)
if ver_meth_expanded is None:
raise MissingVerificationMethodError(
f"Verification method "
f"{doc["proof"]["verificationMethod"]} not found."
)
if not isinstance(ver_meth_expanded, VerificationMethod):
raise InvalidVerificationMethod(
"verificationMethod does not identify a valid verification method"
)
verkey = ver_meth_expanded.material
valid = await verify_credential(session, doc, verkey)
response["valid"] = valid
except (
BaseJSONLDMessagingError,
ResolverError,
) as error:
response["error"] = str(error)
except (WalletError, InjectionError):
raise web.HTTPForbidden(reason="No wallet available")
return web.json_response(response)
async def register(app: web.Application):
"""Register routes."""
app.add_routes([web.post("/jsonld/sign", sign), web.post("/jsonld/verify", verify)])
def post_process_routes(app: web.Application):
"""Amend swagger API."""
# Add top-level tags description
if "tags" not in app._state["swagger_dict"]:
app._state["swagger_dict"]["tags"] = []
app._state["swagger_dict"]["tags"].append(
{
"name": "jsonld",
"description": "Sign and verify json-ld data",
"externalDocs": {
"description": "Specification",
"url": "https://tools.ietf.org/html/rfc7515",
},
}
)
| """jsonld admin routes."""
from aiohttp import web
from aiohttp_apispec import docs, request_schema, response_schema
from marshmallow import INCLUDE, Schema, fields
from pydid import VerificationMethod
from ...admin.request_context import AdminRequestContext
from ...config.base import InjectionError
from ...resolver.base import ResolverError
from ...resolver.did_resolver import DIDResolver
from ...wallet.error import WalletError
from ..models.openapi import OpenAPISchema
from .credential import sign_credential, verify_credential
from .error import (
BaseJSONLDMessagingError,
InvalidVerificationMethod,
MissingVerificationMethodError,
)
class SignatureOptionsSchema(Schema):
"""Schema for LD signature options."""
type = fields.Str(required=False)
verificationMethod = fields.Str(required=True)
proofPurpose = fields.Str(required=True)
challenge = fields.Str(required=False)
domain = fields.Str(required=False)
class DocSchema(OpenAPISchema):
"""Schema for LD doc to sign."""
credential = fields.Dict(
required=True,
description="Credential to sign",
)
options = fields.Nested(
SignatureOptionsSchema,
required=True,
description="Signature options",
)
class SignRequestSchema(OpenAPISchema):
"""Request schema for signing a jsonld doc."""
verkey = fields.Str(required=True, description="Verkey to use for signing")
doc = fields.Nested(
DocSchema,
required=True,
)
class SignResponseSchema(OpenAPISchema):
"""Response schema for a signed jsonld doc."""
signed_doc = fields.Dict(description="Signed document", required=False)
error = fields.Str(description="Error text", required=False)
@docs(tags=["jsonld"], summary="Sign a JSON-LD structure and return it")
@request_schema(SignRequestSchema())
@response_schema(SignResponseSchema(), 200, description="")
async def sign(request: web.BaseRequest):
"""
Request handler for signing a jsonld doc.
Args:
request: aiohttp request object
"""
response = {}
body = await request.json()
doc = body.get("doc")
try:
context: AdminRequestContext = request["context"]
async with context.session() as session:
doc_with_proof = await sign_credential(
session, doc.get("credential"), doc.get("options"), body.get("verkey")
)
response["signed_doc"] = doc_with_proof
except (BaseJSONLDMessagingError) as err:
response["error"] = str(err)
except (WalletError, InjectionError):
raise web.HTTPForbidden(reason="No wallet available")
return web.json_response(response)
class SignedDocSchema(OpenAPISchema):
"""Verifiable doc schema."""
class Meta:
"""Keep unknown values."""
unknown = INCLUDE
proof = fields.Nested(
SignatureOptionsSchema,
unknown=INCLUDE,
required=True,
description="Linked data proof",
)
class VerifyRequestSchema(OpenAPISchema):
"""Request schema for signing a jsonld doc."""
verkey = fields.Str(
required=False, description="Verkey to use for doc verification"
)
doc = fields.Nested(SignedDocSchema, required=True, description="Signed document")
class VerifyResponseSchema(OpenAPISchema):
"""Response schema for verification result."""
valid = fields.Bool(required=True)
error = fields.Str(description="Error text", required=False)
@docs(tags=["jsonld"], summary="Verify a JSON-LD structure.")
@request_schema(VerifyRequestSchema())
@response_schema(VerifyResponseSchema(), 200, description="")
async def verify(request: web.BaseRequest):
"""
Request handler for signing a jsonld doc.
Args:
request: aiohttp request object
"""
response = {"valid": False}
try:
context: AdminRequestContext = request["context"]
profile = context.profile
body = await request.json()
verkey = body.get("verkey")
doc = body.get("doc")
async with context.session() as session:
if verkey is None:
resolver = session.inject(DIDResolver)
ver_meth_expanded = await resolver.dereference(
profile, doc["proof"]["verificationMethod"]
)
if ver_meth_expanded is None:
raise MissingVerificationMethodError(
f"Verification method "
f"{doc['proof']['verificationMethod']} not found."
)
if not isinstance(ver_meth_expanded, VerificationMethod):
raise InvalidVerificationMethod(
"verificationMethod does not identify a valid verification method"
)
verkey = ver_meth_expanded.material
valid = await verify_credential(session, doc, verkey)
response["valid"] = valid
except (
BaseJSONLDMessagingError,
ResolverError,
) as error:
response["error"] = str(error)
except (WalletError, InjectionError):
raise web.HTTPForbidden(reason="No wallet available")
return web.json_response(response)
async def register(app: web.Application):
"""Register routes."""
app.add_routes([web.post("/jsonld/sign", sign), web.post("/jsonld/verify", verify)])
def post_process_routes(app: web.Application):
"""Amend swagger API."""
# Add top-level tags description
if "tags" not in app._state["swagger_dict"]:
app._state["swagger_dict"]["tags"] = []
app._state["swagger_dict"]["tags"].append(
{
"name": "jsonld",
"description": "Sign and verify json-ld data",
"externalDocs": {
"description": "Specification",
"url": "https://tools.ietf.org/html/rfc7515",
},
}
)
|
from typing import Union, List
from .workers_cheapening import * # noqa
from ..base import OptionsGroup
from ..typehints import Strlist
from ..utils import listify
class MuleFarm:
"""Represents a mule farm."""
def __init__(self, name: str, mule_numbers: Union[int, List[int]]):
"""
:param name: Farm alias.
:param mule_numbers: Total mules on farm count,
or a list of mule numbers.
"""
# todo http://uwsgi-docs.readthedocs.io/en/latest/Signals.html#signals-targets
self.name = name
self.mule_numbers = mule_numbers
def __str__(self):
return f"{self.name}:{",".join(map(str, self.mule_numbers))}"
class Workers(OptionsGroup):
"""Workers aka [working] processes."""
mule_farm = MuleFarm
def set_basic_params(
self,
count: int = None,
touch_reload: Strlist = None,
touch_chain_reload: Strlist = None,
zombie_reaper: bool = None,
limit_addr_space: int = None,
limit_count: int = None,
cpu_affinity: int = None
):
"""
:param count: Spawn the specified number of workers (processes).
Set the number of workers for preforking mode.
This is the base for easy and safe concurrency in your app.
More workers you add, more concurrent requests you can manage.
Each worker corresponds to a system process, so it consumes memory,
choose carefully the right number. You can easily drop your system
to its knees by setting a too high value.
Setting ``workers`` to a ridiculously high number will **not**
magically make your application web scale - quite the contrary.
:param touch_reload: Trigger reload of (and only) workers
if the specified file is modified/touched.
:param touch_chain_reload: Trigger chain workers reload on file touch.
When in lazy/lazy_apps mode, you can simply destroy a worker to force it to reload the application code.
A new reloading system named "chain reload", allows you to reload one worker at time
(opposed to the standard way where all of the workers are destroyed in bulk)
* http://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html#chain-reloading-lazy-apps
:param zombie_reaper: Call waitpid(-1,...) after each request to get rid of zombies.
Enables reaper mode. After each request the server will call ``waitpid(-1)``
to get rid of zombie processes.
If you spawn subprocesses in your app and you happen to end up with zombie processes
all over the place you can enable this option. (It really would be better
if you could fix your application's process spawning usage though.)
:param limit_addr_space: Limit process address space (vsz) (in megabytes)
Limits the address space usage of each uWSGI (worker) process using POSIX/UNIX ``setrlimit()``.
For example, ``limit-as 256`` will disallow uWSGI processes to grow over 256MB of address space.
Address space is the virtual memory a process has access to. It does *not* correspond to physical memory.
Read and understand this page before enabling this option: http://en.wikipedia.org/wiki/Virtual_memory
:param limit_count: Limit the number of spawnable processes.
:param cpu_affinity: number of cores for each worker (Linux only)
Set the number of cores (CPUs) to allocate to each worker process.
* 4 workers, 4 CPUs, affinity is 1,
each worker is allocated one CPU.
* 4 workers, 2 CPUs, affinity is 1,
workers get one CPU each (0; 1; 0; 1).
* 4 workers, 4 CPUs, affinity is 2,
workers get two CPUs each in a round-robin fashion (0, 1; 2, 3; 0, 1; 2; 3).
* 8 workers, 4 CPUs, affinity is 3,
workers get three CPUs each in a round-robin fashion
(0, 1, 2; 3, 0, 1; 2, 3, 0; 1, 2, 3; 0, 1, 2; 3, 0, 1; 2, 3, 0; 1, 2, 3).
"""
# todo map socket to a worker - map-socket = 0:1
# networking.register_socket - workers_binding
self.set_count_auto(count)
self._set('touch-workers-reload', touch_reload, multi=True)
self._set('touch-chain-reload', touch_chain_reload, multi=True)
self._set('reaper', zombie_reaper, cast=bool)
self._set('limit-as', limit_addr_space)
self._set('limit-nproc', limit_count)
self._set('cpu-affinity', cpu_affinity)
return self._section
def run_command_as_worker(self, command: str, after_post_fork_hook: bool = False):
"""Run the specified command as worker.
:param command:
:param after_post_fork_hook: Whether to run it after `post_fork` hook.
"""
self._set('worker-exec2' if after_post_fork_hook else 'worker-exec', command, multi=True)
return self._section
def set_count_auto(self, count: int = None):
"""Sets workers count.
By default sets it to detected number of available cores
:param count:
"""
count = count or self._section.vars.CPU_CORES
self._set('workers', count)
return self._section
def set_thread_params(
self,
enable: bool = None,
count: int = None,
count_offload: int = None,
stack_size: int = None,
no_wait: bool = None
):
"""Sets threads related params.
:param enable: Enable threads in the embedded languages.
This will allow to spawn threads in your app.
.. warning:: Threads will simply *not work* if this option is not enabled.
There will likely be no error, just no execution of your thread code.
:param count: Run each worker in prethreaded mode with the specified number
of threads per worker.
.. warning:: Do not use with ``gevent``.
.. note:: Enables threads automatically.
:param count_offload: Set the number of threads (per-worker) to spawn
for offloading. Default: 0.
These threads run such tasks in a non-blocking/evented way allowing
for a huge amount of concurrency. Various components of the uWSGI stack
are offload-friendly.
.. note:: Try to set it to the number of CPU cores to take advantage of SMP.
* http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html
:param stack_size: Set threads stacksize.
:param no_wait: Do not wait for threads cancellation on quit/reload.
"""
self._set('enable-threads', enable, cast=bool)
self._set('no-threads-wait', no_wait, cast=bool)
self._set('threads', count)
self._set('offload-threads', count_offload)
if count:
self._section.print_out(f'Threads per worker: {count}')
self._set('threads-stacksize', stack_size)
return self._section
def set_mules_params(
self,
mules: Union[int, List[int]] = None,
touch_reload: Strlist = None,
harakiri_timeout: int = None,
farms: List[MuleFarm] = None,
reload_mercy: int = None,
msg_buffer: int = None,
msg_buffer_recv: int = None
):
"""Sets mules related params.
http://uwsgi.readthedocs.io/en/latest/Mules.html
Mules are worker processes living in the uWSGI stack but not reachable via socket connections,
that can be used as a generic subsystem to offload tasks.
:param mules: Add the specified mules or number of mules.
:param touch_reload: Reload mules if the specified file is modified/touched.
:param harakiri_timeout: Set harakiri timeout for mule tasks.
:param farms: Mule farms list.
Examples:
* cls_mule_farm('first', 2)
* cls_mule_farm('first', [4, 5])
:param reload_mercy: Set the maximum time (in seconds) a mule can take
to reload/shutdown. Default: 60.
:param msg_buffer: Set mule message buffer size (bytes) given
for mule message queue.
:param msg_buffer: Set mule message recv buffer size (bytes).
"""
farms = farms or []
next_mule_number = 1
farm_mules_count = 0
for farm in farms:
if isinstance(farm.mule_numbers, int):
farm.mule_numbers = list(range(next_mule_number, next_mule_number + farm.mule_numbers))
next_mule_number = farm.mule_numbers[-1] + 1
farm_mules_count += len(farm.mule_numbers)
self._set('farm', farm, multi=True)
if mules is None and farm_mules_count:
mules = farm_mules_count
if isinstance(mules, int):
self._set('mules', mules)
elif isinstance(mules, list):
for mule in mules:
self._set('mule', mule, multi=True)
self._set('touch-mules-reload', touch_reload, multi=True)
self._set('mule-harakiri', harakiri_timeout)
self._set('mule-reload-mercy', reload_mercy)
self._set('mule-msg-size', msg_buffer)
self._set('mule-msg-recv-size', msg_buffer_recv)
return self._section
def set_reload_params(
self,
min_lifetime: int = None,
max_lifetime: int = None,
max_requests: int = None,
max_requests_delta: int = None,
max_addr_space: int = None,
max_rss: int = None,
max_uss: int = None,
max_pss: int = None,
max_addr_space_forced: int = None,
max_rss_forced: int = None,
watch_interval_forced: int = None,
mercy: int = None
):
"""Sets workers reload parameters.
:param min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive
for N seconds (default 60). This is an anti-fork-bomb measure.
Since 1.9
:param max_lifetime: Reload workers after this many seconds. Disabled by default.
Since 1.9
:param max_requests: Reload workers after the specified amount of managed
requests (avoid memory leaks).
When a worker reaches this number of requests it will get recycled (killed and restarted).
You can use this option to "dumb fight" memory leaks.
Also take a look at the ``reload-on-as`` and ``reload-on-rss`` options
as they are more useful for memory leaks.
.. warning:: The default min-worker-lifetime 60 seconds takes priority over `max-requests`.
Do not use with benchmarking as you'll get stalls
such as `worker respawning too fast !!! i have to sleep a bit (2 seconds)...`
:param max_requests_delta: Add (worker_id * delta) to the max_requests value of each worker.
:param max_addr_space: Reload a worker if its address space usage is higher
than the specified value in megabytes.
:param max_rss: Reload a worker if its physical unshared memory (resident set size) is higher
than the specified value (in megabytes).
:param max_uss: Reload a worker if Unique Set Size is higher
than the specified value in megabytes.
.. note:: Linux only.
:param max_pss: Reload a worker if Proportional Set Size is higher
than the specified value in megabytes.
.. note:: Linux only.
:param max_addr_space_forced: Force the master to reload a worker if its address space is higher
than specified megabytes (in megabytes).
:param max_rss_forced: Force the master to reload a worker
if its resident set size memory is higher than specified in megabytes.
:param watch_interval_forced: The memory collector [per-worker] thread memeory watch
interval (seconds) used for forced reloads. Default: 3.
:param mercy: Set the maximum time (in seconds) a worker can take
before reload/shutdown. Default: 60.
"""
self._set('max-requests', max_requests)
self._set('max-requests-delta', max_requests_delta)
self._set('min-worker-lifetime', min_lifetime)
self._set('max-worker-lifetime', max_lifetime)
self._set('reload-on-as', max_addr_space)
self._set('reload-on-rss', max_rss)
self._set('reload-on-uss', max_uss)
self._set('reload-on-pss', max_pss)
self._set('evil-reload-on-as', max_addr_space_forced)
self._set('evil-reload-on-rss', max_rss_forced)
self._set('mem-collector-freq', watch_interval_forced)
self._set('worker-reload-mercy', mercy)
return self._section
def set_reload_on_exception_params(
self,
do_reload: bool = None,
etype: str = None,
evalue: str = None,
erepr: str = None
):
"""Sets workers reload on exceptions parameters.
:param do_reload: Reload a worker when an exception is raised.
:param etype: Reload a worker when a specific exception type is raised.
:param evalue: Reload a worker when a specific exception value is raised.
:param erepr: Reload a worker when a specific exception type+value (language-specific) is raised.
"""
self._set('reload-on-exception', do_reload, cast=bool)
self._set('reload-on-exception-type', etype)
self._set('reload-on-exception-value', evalue)
self._set('reload-on-exception-repr', erepr)
return self._section
def set_harakiri_params(self, timeout: int = None, verbose: bool = None, disable_for_arh: bool = None):
"""Sets workers harakiri parameters.
:param timeout: Harakiri timeout in seconds.
Every request that will take longer than the seconds specified
in the harakiri timeout will be dropped and the corresponding
worker is thereafter recycled.
:param verbose: Harakiri verbose mode.
When a request is killed by Harakiri you will get a message in the uWSGI log.
Enabling this option will print additional info (for example,
the current syscall will be reported on Linux platforms).
:param disable_for_arh: Disallow Harakiri killings during after-request hook methods.
"""
self._set('harakiri', timeout)
self._set('harakiri-verbose', verbose, cast=bool)
self._set('harakiri-no-arh', disable_for_arh, cast=bool)
return self._section
def set_zerg_server_params(self, socket: str, clients_socket_pool: Strlist = None):
"""Zerg mode. Zerg server params.
When your site load is variable, it would be nice to be able to add
workers dynamically. Enabling Zerg mode you can allow zerg clients to attach
to your already running server and help it in the work.
* http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html
:param socket: Unix socket to bind server to.
Examples:
* unix socket - ``/var/run/mutalisk``
* Linux abstract namespace - ``@nydus``
:param clients_socket_pool: This enables Zerg Pools.
.. note:: Expects master process.
Accepts sockets that will be mapped to Zerg socket.
* http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html#zerg-pools
"""
if clients_socket_pool:
self._set('zergpool', f"{socket}:{",".join(listify(clients_socket_pool))}", multi=True)
else:
self._set('zerg-server', socket)
return self._section
def set_zerg_client_params(self, server_sockets: Strlist, use_fallback_socket: bool = None):
"""Zerg mode. Zergs params.
:param server_sockets: Attaches zerg to a zerg server.
:param use_fallback_socket: Fallback to normal sockets if the zerg server is not available
"""
self._set('zerg', server_sockets, multi=True)
if use_fallback_socket is not None:
self._set('zerg-fallback', use_fallback_socket, cast=bool)
for socket in listify(server_sockets):
self._section.networking.register_socket(self._section.networking.sockets.default(socket))
return self._section
| from typing import Union, List
from .workers_cheapening import * # noqa
from ..base import OptionsGroup
from ..typehints import Strlist
from ..utils import listify
class MuleFarm:
"""Represents a mule farm."""
def __init__(self, name: str, mule_numbers: Union[int, List[int]]):
"""
:param name: Farm alias.
:param mule_numbers: Total mules on farm count,
or a list of mule numbers.
"""
# todo http://uwsgi-docs.readthedocs.io/en/latest/Signals.html#signals-targets
self.name = name
self.mule_numbers = mule_numbers
def __str__(self):
return f"{self.name}:{','.join(map(str, self.mule_numbers))}"
class Workers(OptionsGroup):
"""Workers aka [working] processes."""
mule_farm = MuleFarm
def set_basic_params(
self,
count: int = None,
touch_reload: Strlist = None,
touch_chain_reload: Strlist = None,
zombie_reaper: bool = None,
limit_addr_space: int = None,
limit_count: int = None,
cpu_affinity: int = None
):
"""
:param count: Spawn the specified number of workers (processes).
Set the number of workers for preforking mode.
This is the base for easy and safe concurrency in your app.
More workers you add, more concurrent requests you can manage.
Each worker corresponds to a system process, so it consumes memory,
choose carefully the right number. You can easily drop your system
to its knees by setting a too high value.
Setting ``workers`` to a ridiculously high number will **not**
magically make your application web scale - quite the contrary.
:param touch_reload: Trigger reload of (and only) workers
if the specified file is modified/touched.
:param touch_chain_reload: Trigger chain workers reload on file touch.
When in lazy/lazy_apps mode, you can simply destroy a worker to force it to reload the application code.
A new reloading system named "chain reload", allows you to reload one worker at time
(opposed to the standard way where all of the workers are destroyed in bulk)
* http://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html#chain-reloading-lazy-apps
:param zombie_reaper: Call waitpid(-1,...) after each request to get rid of zombies.
Enables reaper mode. After each request the server will call ``waitpid(-1)``
to get rid of zombie processes.
If you spawn subprocesses in your app and you happen to end up with zombie processes
all over the place you can enable this option. (It really would be better
if you could fix your application's process spawning usage though.)
:param limit_addr_space: Limit process address space (vsz) (in megabytes)
Limits the address space usage of each uWSGI (worker) process using POSIX/UNIX ``setrlimit()``.
For example, ``limit-as 256`` will disallow uWSGI processes to grow over 256MB of address space.
Address space is the virtual memory a process has access to. It does *not* correspond to physical memory.
Read and understand this page before enabling this option: http://en.wikipedia.org/wiki/Virtual_memory
:param limit_count: Limit the number of spawnable processes.
:param cpu_affinity: number of cores for each worker (Linux only)
Set the number of cores (CPUs) to allocate to each worker process.
* 4 workers, 4 CPUs, affinity is 1,
each worker is allocated one CPU.
* 4 workers, 2 CPUs, affinity is 1,
workers get one CPU each (0; 1; 0; 1).
* 4 workers, 4 CPUs, affinity is 2,
workers get two CPUs each in a round-robin fashion (0, 1; 2, 3; 0, 1; 2; 3).
* 8 workers, 4 CPUs, affinity is 3,
workers get three CPUs each in a round-robin fashion
(0, 1, 2; 3, 0, 1; 2, 3, 0; 1, 2, 3; 0, 1, 2; 3, 0, 1; 2, 3, 0; 1, 2, 3).
"""
# todo map socket to a worker - map-socket = 0:1
# networking.register_socket - workers_binding
self.set_count_auto(count)
self._set('touch-workers-reload', touch_reload, multi=True)
self._set('touch-chain-reload', touch_chain_reload, multi=True)
self._set('reaper', zombie_reaper, cast=bool)
self._set('limit-as', limit_addr_space)
self._set('limit-nproc', limit_count)
self._set('cpu-affinity', cpu_affinity)
return self._section
def run_command_as_worker(self, command: str, after_post_fork_hook: bool = False):
"""Run the specified command as worker.
:param command:
:param after_post_fork_hook: Whether to run it after `post_fork` hook.
"""
self._set('worker-exec2' if after_post_fork_hook else 'worker-exec', command, multi=True)
return self._section
def set_count_auto(self, count: int = None):
"""Sets workers count.
By default sets it to detected number of available cores
:param count:
"""
count = count or self._section.vars.CPU_CORES
self._set('workers', count)
return self._section
def set_thread_params(
self,
enable: bool = None,
count: int = None,
count_offload: int = None,
stack_size: int = None,
no_wait: bool = None
):
"""Sets threads related params.
:param enable: Enable threads in the embedded languages.
This will allow to spawn threads in your app.
.. warning:: Threads will simply *not work* if this option is not enabled.
There will likely be no error, just no execution of your thread code.
:param count: Run each worker in prethreaded mode with the specified number
of threads per worker.
.. warning:: Do not use with ``gevent``.
.. note:: Enables threads automatically.
:param count_offload: Set the number of threads (per-worker) to spawn
for offloading. Default: 0.
These threads run such tasks in a non-blocking/evented way allowing
for a huge amount of concurrency. Various components of the uWSGI stack
are offload-friendly.
.. note:: Try to set it to the number of CPU cores to take advantage of SMP.
* http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html
:param stack_size: Set threads stacksize.
:param no_wait: Do not wait for threads cancellation on quit/reload.
"""
self._set('enable-threads', enable, cast=bool)
self._set('no-threads-wait', no_wait, cast=bool)
self._set('threads', count)
self._set('offload-threads', count_offload)
if count:
self._section.print_out(f'Threads per worker: {count}')
self._set('threads-stacksize', stack_size)
return self._section
def set_mules_params(
self,
mules: Union[int, List[int]] = None,
touch_reload: Strlist = None,
harakiri_timeout: int = None,
farms: List[MuleFarm] = None,
reload_mercy: int = None,
msg_buffer: int = None,
msg_buffer_recv: int = None
):
"""Sets mules related params.
http://uwsgi.readthedocs.io/en/latest/Mules.html
Mules are worker processes living in the uWSGI stack but not reachable via socket connections,
that can be used as a generic subsystem to offload tasks.
:param mules: Add the specified mules or number of mules.
:param touch_reload: Reload mules if the specified file is modified/touched.
:param harakiri_timeout: Set harakiri timeout for mule tasks.
:param farms: Mule farms list.
Examples:
* cls_mule_farm('first', 2)
* cls_mule_farm('first', [4, 5])
:param reload_mercy: Set the maximum time (in seconds) a mule can take
to reload/shutdown. Default: 60.
:param msg_buffer: Set mule message buffer size (bytes) given
for mule message queue.
:param msg_buffer: Set mule message recv buffer size (bytes).
"""
farms = farms or []
next_mule_number = 1
farm_mules_count = 0
for farm in farms:
if isinstance(farm.mule_numbers, int):
farm.mule_numbers = list(range(next_mule_number, next_mule_number + farm.mule_numbers))
next_mule_number = farm.mule_numbers[-1] + 1
farm_mules_count += len(farm.mule_numbers)
self._set('farm', farm, multi=True)
if mules is None and farm_mules_count:
mules = farm_mules_count
if isinstance(mules, int):
self._set('mules', mules)
elif isinstance(mules, list):
for mule in mules:
self._set('mule', mule, multi=True)
self._set('touch-mules-reload', touch_reload, multi=True)
self._set('mule-harakiri', harakiri_timeout)
self._set('mule-reload-mercy', reload_mercy)
self._set('mule-msg-size', msg_buffer)
self._set('mule-msg-recv-size', msg_buffer_recv)
return self._section
def set_reload_params(
self,
min_lifetime: int = None,
max_lifetime: int = None,
max_requests: int = None,
max_requests_delta: int = None,
max_addr_space: int = None,
max_rss: int = None,
max_uss: int = None,
max_pss: int = None,
max_addr_space_forced: int = None,
max_rss_forced: int = None,
watch_interval_forced: int = None,
mercy: int = None
):
"""Sets workers reload parameters.
:param min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive
for N seconds (default 60). This is an anti-fork-bomb measure.
Since 1.9
:param max_lifetime: Reload workers after this many seconds. Disabled by default.
Since 1.9
:param max_requests: Reload workers after the specified amount of managed
requests (avoid memory leaks).
When a worker reaches this number of requests it will get recycled (killed and restarted).
You can use this option to "dumb fight" memory leaks.
Also take a look at the ``reload-on-as`` and ``reload-on-rss`` options
as they are more useful for memory leaks.
.. warning:: The default min-worker-lifetime 60 seconds takes priority over `max-requests`.
Do not use with benchmarking as you'll get stalls
such as `worker respawning too fast !!! i have to sleep a bit (2 seconds)...`
:param max_requests_delta: Add (worker_id * delta) to the max_requests value of each worker.
:param max_addr_space: Reload a worker if its address space usage is higher
than the specified value in megabytes.
:param max_rss: Reload a worker if its physical unshared memory (resident set size) is higher
than the specified value (in megabytes).
:param max_uss: Reload a worker if Unique Set Size is higher
than the specified value in megabytes.
.. note:: Linux only.
:param max_pss: Reload a worker if Proportional Set Size is higher
than the specified value in megabytes.
.. note:: Linux only.
:param max_addr_space_forced: Force the master to reload a worker if its address space is higher
than specified megabytes (in megabytes).
:param max_rss_forced: Force the master to reload a worker
if its resident set size memory is higher than specified in megabytes.
:param watch_interval_forced: The memory collector [per-worker] thread memeory watch
interval (seconds) used for forced reloads. Default: 3.
:param mercy: Set the maximum time (in seconds) a worker can take
before reload/shutdown. Default: 60.
"""
self._set('max-requests', max_requests)
self._set('max-requests-delta', max_requests_delta)
self._set('min-worker-lifetime', min_lifetime)
self._set('max-worker-lifetime', max_lifetime)
self._set('reload-on-as', max_addr_space)
self._set('reload-on-rss', max_rss)
self._set('reload-on-uss', max_uss)
self._set('reload-on-pss', max_pss)
self._set('evil-reload-on-as', max_addr_space_forced)
self._set('evil-reload-on-rss', max_rss_forced)
self._set('mem-collector-freq', watch_interval_forced)
self._set('worker-reload-mercy', mercy)
return self._section
def set_reload_on_exception_params(
self,
do_reload: bool = None,
etype: str = None,
evalue: str = None,
erepr: str = None
):
"""Sets workers reload on exceptions parameters.
:param do_reload: Reload a worker when an exception is raised.
:param etype: Reload a worker when a specific exception type is raised.
:param evalue: Reload a worker when a specific exception value is raised.
:param erepr: Reload a worker when a specific exception type+value (language-specific) is raised.
"""
self._set('reload-on-exception', do_reload, cast=bool)
self._set('reload-on-exception-type', etype)
self._set('reload-on-exception-value', evalue)
self._set('reload-on-exception-repr', erepr)
return self._section
def set_harakiri_params(self, timeout: int = None, verbose: bool = None, disable_for_arh: bool = None):
"""Sets workers harakiri parameters.
:param timeout: Harakiri timeout in seconds.
Every request that will take longer than the seconds specified
in the harakiri timeout will be dropped and the corresponding
worker is thereafter recycled.
:param verbose: Harakiri verbose mode.
When a request is killed by Harakiri you will get a message in the uWSGI log.
Enabling this option will print additional info (for example,
the current syscall will be reported on Linux platforms).
:param disable_for_arh: Disallow Harakiri killings during after-request hook methods.
"""
self._set('harakiri', timeout)
self._set('harakiri-verbose', verbose, cast=bool)
self._set('harakiri-no-arh', disable_for_arh, cast=bool)
return self._section
def set_zerg_server_params(self, socket: str, clients_socket_pool: Strlist = None):
"""Zerg mode. Zerg server params.
When your site load is variable, it would be nice to be able to add
workers dynamically. Enabling Zerg mode you can allow zerg clients to attach
to your already running server and help it in the work.
* http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html
:param socket: Unix socket to bind server to.
Examples:
* unix socket - ``/var/run/mutalisk``
* Linux abstract namespace - ``@nydus``
:param clients_socket_pool: This enables Zerg Pools.
.. note:: Expects master process.
Accepts sockets that will be mapped to Zerg socket.
* http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html#zerg-pools
"""
if clients_socket_pool:
self._set('zergpool', f"{socket}:{','.join(listify(clients_socket_pool))}", multi=True)
else:
self._set('zerg-server', socket)
return self._section
def set_zerg_client_params(self, server_sockets: Strlist, use_fallback_socket: bool = None):
"""Zerg mode. Zergs params.
:param server_sockets: Attaches zerg to a zerg server.
:param use_fallback_socket: Fallback to normal sockets if the zerg server is not available
"""
self._set('zerg', server_sockets, multi=True)
if use_fallback_socket is not None:
self._set('zerg-fallback', use_fallback_socket, cast=bool)
for socket in listify(server_sockets):
self._section.networking.register_socket(self._section.networking.sockets.default(socket))
return self._section
|
#!/usr/bin/env python
###############################################################################
#
# String Encrypt WebApi interface usage example.
#
# In this example we will encrypt sample file with default options.
#
# Version : v1.0
# Language : Python
# Author : Bartosz Wójcik
# Project page : https://www.stringencrypt.com
# Web page : https://www.pelock.com
#
###############################################################################
#
# include StringEncrypt module
#
from stringencrypt import StringEncrypt
#
# if you don't want to use Python module, you can import it directly from the file
#
#from stringencrypt.stringencrypt import StringEncrypt
#
# create StringEncrypt class instance (we are using our activation code)
#
myStringEncrypt = StringEncrypt("ABCD-ABCD-ABCD-ABCD")
#
# encrypt current script file using all the default options
#
result = myStringEncrypt.encrypt_file_contents(__file__, "label_file_encrypted")
#
# result[] array holds the encryption results as well as other information
#
# result["error"] (int) - error code
# result["error_string"] (string) - error code as a string
# result["source"] (string) - decryptor source code
# result["expired"] (boolean) - expiration flag
# result["credits_left"] (int) - number of credits left
# result["credits_total"] (int) - initial number of credits
if result and "error" in result:
if result["error"] == StringEncrypt.ErrorCodes.ERROR_SUCCESS:
# display source code of the decryption function
print(result["source"])
# we can even exec() it (block of code), to run it and
# display decrypted label, which contains this script
# source code
exec(result["source"])
# label is declared at this point, display its content
print(label_file_encrypted)
else:
print(f'An error occurred, error code: {result['error']} ({result['error_string']})')
else:
print("Something unexpected happen while trying to encrypt the string.")
| #!/usr/bin/env python
###############################################################################
#
# String Encrypt WebApi interface usage example.
#
# In this example we will encrypt sample file with default options.
#
# Version : v1.0
# Language : Python
# Author : Bartosz Wójcik
# Project page : https://www.stringencrypt.com
# Web page : https://www.pelock.com
#
###############################################################################
#
# include StringEncrypt module
#
from stringencrypt import StringEncrypt
#
# if you don't want to use Python module, you can import it directly from the file
#
#from stringencrypt.stringencrypt import StringEncrypt
#
# create StringEncrypt class instance (we are using our activation code)
#
myStringEncrypt = StringEncrypt("ABCD-ABCD-ABCD-ABCD")
#
# encrypt current script file using all the default options
#
result = myStringEncrypt.encrypt_file_contents(__file__, "label_file_encrypted")
#
# result[] array holds the encryption results as well as other information
#
# result["error"] (int) - error code
# result["error_string"] (string) - error code as a string
# result["source"] (string) - decryptor source code
# result["expired"] (boolean) - expiration flag
# result["credits_left"] (int) - number of credits left
# result["credits_total"] (int) - initial number of credits
if result and "error" in result:
if result["error"] == StringEncrypt.ErrorCodes.ERROR_SUCCESS:
# display source code of the decryption function
print(result["source"])
# we can even exec() it (block of code), to run it and
# display decrypted label, which contains this script
# source code
exec(result["source"])
# label is declared at this point, display its content
print(label_file_encrypted)
else:
print(f'An error occurred, error code: {result["error"]} ({result["error_string"]})')
else:
print("Something unexpected happen while trying to encrypt the string.")
|
"""This module contains some common functions for both folium and ipyleaflet.
"""
import csv
import os
import requests
import shutil
import tarfile
import urllib.request
import zipfile
import folium
import ipyleaflet
import ipywidgets as widgets
import whitebox
from IPython.display import display, IFrame
class TitilerEndpoint:
"""This class contains the methods for the titiler endpoint."""
def __init__(
self,
endpoint="https://titiler.xyz",
name="stac",
TileMatrixSetId="WebMercatorQuad",
):
"""Initialize the TitilerEndpoint object.
Args:
endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://titiler.xyz".
name (str, optional): The name to be used in the file path. Defaults to "stac".
TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
"""
self.endpoint = endpoint
self.name = name
self.TileMatrixSetId = TileMatrixSetId
def url_for_stac_item(self):
return f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/tilejson.json"
def url_for_stac_assets(self):
return f"{self.endpoint}/{self.name}/assets"
def url_for_stac_bounds(self):
return f"{self.endpoint}/{self.name}/bounds"
def url_for_stac_info(self):
return f"{self.endpoint}/{self.name}/info"
def url_for_stac_info_geojson(self):
return f"{self.endpoint}/{self.name}/info.geojson"
def url_for_stac_statistics(self):
return f"{self.endpoint}/{self.name}/statistics"
def url_for_stac_pixel_value(self, lon, lat):
return f"{self.endpoint}/{self.name}/point/{lon},{lat}"
def url_for_stac_wmts(self):
return (
f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/WMTSCapabilities.xml"
)
class PlanetaryComputerEndpoint(TitilerEndpoint):
"""This class contains the methods for the Microsoft Planetary Computer endpoint."""
def __init__(
self,
endpoint="https://planetarycomputer.microsoft.com/api/data/v1",
name="item",
TileMatrixSetId="WebMercatorQuad",
):
"""Initialize the PlanetaryComputerEndpoint object.
Args:
endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://planetarycomputer.microsoft.com/api/data/v1".
name (str, optional): The name to be used in the file path. Defaults to "item".
TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
"""
super().__init__(endpoint, name, TileMatrixSetId)
def url_for_stac_collection(self):
return f"{self.endpoint}/collection/{self.TileMatrixSetId}/tilejson.json"
def url_for_collection_assets(self):
return f"{self.endpoint}/collection/assets"
def url_for_collection_bounds(self):
return f"{self.endpoint}/collection/bounds"
def url_for_collection_info(self):
return f"{self.endpoint}/collection/info"
def url_for_collection_info_geojson(self):
return f"{self.endpoint}/collection/info.geojson"
def url_for_collection_pixel_value(self, lon, lat):
return f"{self.endpoint}/collection/point/{lon},{lat}"
def url_for_collection_wmts(self):
return f"{self.endpoint}/collection/{self.TileMatrixSetId}/WMTSCapabilities.xml"
def url_for_collection_lat_lon_assets(self, lng, lat):
return f"{self.endpoint}/collection/{lng},{lat}/assets"
def url_for_collection_bbox_assets(self, minx, miny, maxx, maxy):
return f"{self.endpoint}/collection/{minx},{miny},{maxx},{maxy}/assets"
def url_for_stac_mosaic(self, searchid):
return f"{self.endpoint}/mosaic/{searchid}/{self.TileMatrixSetId}/tilejson.json"
def url_for_mosaic_info(self, searchid):
return f"{self.endpoint}/mosaic/{searchid}/info"
def url_for_mosaic_lat_lon_assets(self, searchid, lon, lat):
return f"{self.endpoint}/mosaic/{searchid}/{lon},{lat}/assets"
def check_titiler_endpoint(titiler_endpoint=None):
"""Returns the default titiler endpoint.
Returns:
object: A titiler endpoint.
"""
if titiler_endpoint is None:
if os.environ.get("TITILER_ENDPOINT") == "planetary-computer":
titiler_endpoint = PlanetaryComputerEndpoint()
else:
titiler_endpoint = TitilerEndpoint()
elif titiler_endpoint in ["planetary-computer", "pc"]:
titiler_endpoint = PlanetaryComputerEndpoint()
return titiler_endpoint
class WhiteboxTools(whitebox.WhiteboxTools):
"""This class inherits the whitebox WhiteboxTools class."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def whiteboxgui(verbose=True, tree=False, reset=False, sandbox_path=None):
"""Shows the WhiteboxTools GUI.
Args:
verbose (bool, optional): Whether to show progress info when the tool is running. Defaults to True.
tree (bool, optional): Whether to use the tree mode toolbox built using ipytree rather than ipywidgets. Defaults to False.
reset (bool, optional): Whether to regenerate the json file with the dictionary containing the information for all tools. Defaults to False.
sandbox_path (str, optional): The path to the sandbox folder. Defaults to None.
Returns:
object: A toolbox GUI.
"""
import whiteboxgui
return whiteboxgui.show(verbose, tree, reset, sandbox_path)
def _in_colab_shell():
"""Tests if the code is being executed within Google Colab."""
import sys
if "google.colab" in sys.modules:
return True
else:
return False
def _is_drive_mounted():
"""Checks whether Google Drive is mounted in Google Colab.
Returns:
bool: Returns True if Google Drive is mounted, False otherwise.
"""
drive_path = "/content/drive/My Drive"
if os.path.exists(drive_path):
return True
else:
return False
def set_proxy(port=1080, ip="http://127.0.0.1"):
"""Sets proxy if needed. This is only needed for countries where Google services are not available.
Args:
port (int, optional): The proxy port number. Defaults to 1080.
ip (str, optional): The IP address. Defaults to 'http://127.0.0.1'.
"""
try:
if not ip.startswith("http"):
ip = "http://" + ip
proxy = "{}:{}".format(ip, port)
os.environ["HTTP_PROXY"] = proxy
os.environ["HTTPS_PROXY"] = proxy
a = requests.get("https://google.com")
if a.status_code != 200:
print(
"Failed to connect to Google services. Please double check the port number and ip address."
)
except Exception as e:
raise Exception(e)
def _check_install(package):
"""Checks whether a package is installed. If not, it will install the package.
Args:
package (str): The name of the package to check.
"""
import subprocess
try:
__import__(package)
# print('{} is already installed.'.format(package))
except ImportError:
print("{} is not installed. Installing ...".format(package))
try:
subprocess.check_call(["python", "-m", "pip", "install", package])
except Exception as e:
print("Failed to install {}".format(package))
print(e)
print("{} has been installed successfully.".format(package))
def update_package():
"""Updates the leafmap package from the leafmap GitHub repository without the need to use pip or conda.
In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package.
"""
try:
download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
if not os.path.exists(download_dir):
os.makedirs(download_dir)
_clone_repo(out_dir=download_dir)
pkg_dir = os.path.join(download_dir, "leafmap-master")
work_dir = os.getcwd()
os.chdir(pkg_dir)
if shutil.which("pip") is None:
cmd = "pip3 install ."
else:
cmd = "pip install ."
os.system(cmd)
os.chdir(work_dir)
print(
"\nPlease comment out 'leafmap.update_package()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output"
)
except Exception as e:
raise Exception(e)
def check_package(name, URL=""):
try:
__import__(name.lower())
except Exception:
raise ImportError(
f"{name} is not installed. Please install it before proceeding. {URL}"
)
def _clone_repo(out_dir=".", unzip=True):
"""Clones the leafmap GitHub repository.
Args:
out_dir (str, optional): Output folder for the repo. Defaults to '.'.
unzip (bool, optional): Whether to unzip the repository. Defaults to True.
"""
url = "https://github.com/giswqs/leafmap/archive/master.zip"
filename = "leafmap-master.zip"
download_from_url(url, out_file_name=filename, out_dir=out_dir, unzip=unzip)
def __install_from_github(url):
"""Install a package from a GitHub repository.
Args:
url (str): The URL of the GitHub repository.
"""
try:
download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
if not os.path.exists(download_dir):
os.makedirs(download_dir)
repo_name = os.path.basename(url)
zip_url = os.path.join(url, "archive/master.zip")
filename = repo_name + "-master.zip"
download_from_url(
url=zip_url, out_file_name=filename, out_dir=download_dir, unzip=True
)
pkg_dir = os.path.join(download_dir, repo_name + "-master")
pkg_name = os.path.basename(url)
work_dir = os.getcwd()
os.chdir(pkg_dir)
print("Installing {}...".format(pkg_name))
cmd = "pip install ."
os.system(cmd)
os.chdir(work_dir)
print("{} has been installed successfully.".format(pkg_name))
# print("\nPlease comment out 'install_from_github()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output")
except Exception as e:
raise Exception(e)
def _check_git_install():
"""Checks if Git is installed.
Returns:
bool: Returns True if Git is installed, otherwise returns False.
"""
import webbrowser
cmd = "git --version"
output = os.popen(cmd).read()
if "git version" in output:
return True
else:
url = "https://git-scm.com/downloads"
print(
"Git is not installed. Please download Git from {} and install it.".format(
url
)
)
webbrowser.open_new_tab(url)
return False
def _clone_github_repo(url, out_dir):
"""Clones a GitHub repository.
Args:
url (str): The link to the GitHub repository
out_dir (str): The output directory for the cloned repository.
"""
repo_name = os.path.basename(url)
# url_zip = os.path.join(url, 'archive/master.zip')
url_zip = url + "/archive/master.zip"
if os.path.exists(out_dir):
print(
"The specified output directory already exists. Please choose a new directory."
)
return
parent_dir = os.path.dirname(out_dir)
out_file_path = os.path.join(parent_dir, repo_name + ".zip")
try:
urllib.request.urlretrieve(url_zip, out_file_path)
except Exception:
print("The provided URL is invalid. Please double check the URL.")
return
with zipfile.ZipFile(out_file_path, "r") as zip_ref:
zip_ref.extractall(parent_dir)
src = out_file_path.replace(".zip", "-master")
os.rename(src, out_dir)
os.remove(out_file_path)
def _is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
return shutil.which(name) is not None
def random_string(string_length=3):
"""Generates a random string of fixed length.
Args:
string_length (int, optional): Fixed length. Defaults to 3.
Returns:
str: A random string
"""
import random
import string
# random.seed(1001)
letters = string.ascii_lowercase
return "".join(random.choice(letters) for i in range(string_length))
def open_image_from_url(url):
"""Loads an image from the specified URL.
Args:
url (str): URL of the image.
Returns:
object: Image object.
"""
from PIL import Image
from io import BytesIO
# from urllib.parse import urlparse
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
return img
except Exception as e:
print(e)
def show_image(img_path, width=None, height=None):
"""Shows an image within Jupyter notebook.
Args:
img_path (str): The image file path.
width (int, optional): Width of the image in pixels. Defaults to None.
height (int, optional): Height of the image in pixels. Defaults to None.
"""
from IPython.display import display
try:
out = widgets.Output()
# layout={'border': '1px solid black'})
# layout={'border': '1px solid black', 'width': str(width + 20) + 'px', 'height': str(height + 10) + 'px'},)
out.clear_output(wait=True)
display(out)
with out:
file = open(img_path, "rb")
image = file.read()
if (width is None) and (height is None):
display(widgets.Image(value=image))
elif (width is not None) and (height is not None):
display(widgets.Image(value=image, width=width, height=height))
else:
print("You need set both width and height.")
return
except Exception as e:
raise Exception(e)
def has_transparency(img):
"""Checks whether an image has transparency.
Args:
img (object): a PIL Image object.
Returns:
bool: True if it has transparency, False otherwise.
"""
if img.mode == "P":
transparent = img.info.get("transparency", -1)
for _, index in img.getcolors():
if index == transparent:
return True
elif img.mode == "RGBA":
extrema = img.getextrema()
if extrema[3][0] < 255:
return True
return False
def upload_to_imgur(in_gif):
"""Uploads an image to imgur.com
Args:
in_gif (str): The file path to the image.
"""
import subprocess
pkg_name = "imgur-uploader"
if not _is_tool(pkg_name):
_check_install(pkg_name)
try:
IMGUR_API_ID = os.environ.get("IMGUR_API_ID", None)
IMGUR_API_SECRET = os.environ.get("IMGUR_API_SECRET", None)
credentials_path = os.path.join(
os.path.expanduser("~"), ".config/imgur_uploader/uploader.cfg"
)
if (
(IMGUR_API_ID is not None) and (IMGUR_API_SECRET is not None)
) or os.path.exists(credentials_path):
proc = subprocess.Popen(["imgur-uploader", in_gif], stdout=subprocess.PIPE)
for _ in range(0, 2):
line = proc.stdout.readline()
print(line.rstrip().decode("utf-8"))
# while True:
# line = proc.stdout.readline()
# if not line:
# break
# print(line.rstrip().decode("utf-8"))
else:
print(
"Imgur API credentials could not be found. Please check https://pypi.org/project/imgur-uploader/ for instructions on how to get Imgur API credentials"
)
return
except Exception as e:
raise Exception(e)
def rgb_to_hex(rgb=(255, 255, 255)):
"""Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255.
Args:
rgb (tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255).
Returns:
str: hex color code
"""
return "%02x%02x%02x" % rgb
def hex_to_rgb(value="FFFFFF"):
"""Converts hex color to RGB color.
Args:
value (str, optional): Hex color code as a string. Defaults to 'FFFFFF'.
Returns:
tuple: RGB color as a tuple.
"""
value = value.lstrip("#")
lv = len(value)
return tuple(int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3))
def check_color(in_color):
"""Checks the input color and returns the corresponding hex color code.
Args:
in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00') or tuple (e.g., (255, 127, 0)).
Returns:
str: A hex color code.
"""
import colour
out_color = "#000000" # default black color
if isinstance(in_color, tuple) and len(in_color) == 3:
if all(isinstance(item, int) for item in in_color):
rescaled_color = [x / 255.0 for x in in_color]
out_color = colour.Color(rgb=tuple(rescaled_color))
return out_color.hex_l
else:
print(
"RGB color must be a tuple with three integer values ranging from 0 to 255."
)
return
else:
try:
out_color = colour.Color(in_color)
return out_color.hex_l
except Exception as e:
print("The provided color is invalid. Using the default black color.")
print(e)
return out_color
def system_fonts(show_full_path=False):
"""Gets a list of system fonts
# Common font locations:
# Linux: /usr/share/fonts/TTF/
# Windows: C:/Windows/Fonts
# macOS: System > Library > Fonts
Args:
show_full_path (bool, optional): Whether to show the full path of each system font. Defaults to False.
Returns:
list: A list of system fonts.
"""
try:
import matplotlib.font_manager
font_list = matplotlib.font_manager.findSystemFonts(
fontpaths=None, fontext="ttf"
)
font_list.sort()
font_names = [os.path.basename(f) for f in font_list]
font_names.sort()
if show_full_path:
return font_list
else:
return font_names
except Exception as e:
raise Exception(e)
def download_from_url(url, out_file_name=None, out_dir=".", unzip=True, verbose=True):
"""Download a file from a URL (e.g., https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip)
Args:
url (str): The HTTP URL to download.
out_file_name (str, optional): The output file name to use. Defaults to None.
out_dir (str, optional): The output directory to use. Defaults to '.'.
unzip (bool, optional): Whether to unzip the downloaded file if it is a zip file. Defaults to True.
verbose (bool, optional): Whether to display or not the output of the function
"""
in_file_name = os.path.basename(url)
if out_file_name is None:
out_file_name = in_file_name
out_file_path = os.path.join(os.path.abspath(out_dir), out_file_name)
if verbose:
print("Downloading {} ...".format(url))
try:
urllib.request.urlretrieve(url, out_file_path)
except Exception:
raise Exception("The URL is invalid. Please double check the URL.")
final_path = out_file_path
if unzip:
# if it is a zip file
if ".zip" in out_file_name:
if verbose:
print("Unzipping {} ...".format(out_file_name))
with zipfile.ZipFile(out_file_path, "r") as zip_ref:
zip_ref.extractall(out_dir)
final_path = os.path.join(
os.path.abspath(out_dir), out_file_name.replace(".zip", "")
)
# if it is a tar file
if ".tar" in out_file_name:
if verbose:
print("Unzipping {} ...".format(out_file_name))
with tarfile.open(out_file_path, "r") as tar_ref:
tar_ref.extractall(out_dir)
final_path = os.path.join(
os.path.abspath(out_dir), out_file_name.replace(".tart", "")
)
if verbose:
print("Data downloaded to: {}".format(final_path))
def download_from_gdrive(gfile_url, file_name, out_dir=".", unzip=True, verbose=True):
"""Download a file shared via Google Drive
(e.g., https://drive.google.com/file/d/18SUo_HcDGltuWYZs1s7PpOmOq_FvFn04/view?usp=sharing)
Args:
gfile_url (str): The Google Drive shared file URL
file_name (str): The output file name to use.
out_dir (str, optional): The output directory. Defaults to '.'.
unzip (bool, optional): Whether to unzip the output file if it is a zip file. Defaults to True.
verbose (bool, optional): Whether to display or not the output of the function
"""
from google_drive_downloader import GoogleDriveDownloader as gdd
file_id = gfile_url.split("/")[5]
if verbose:
print("Google Drive file id: {}".format(file_id))
dest_path = os.path.join(out_dir, file_name)
gdd.download_file_from_google_drive(file_id, dest_path, True, unzip)
def create_download_link(filename, title="Click here to download: "):
"""Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578
Args:
filename (str): The file path to the file to download
title (str, optional): str. Defaults to "Click here to download: ".
Returns:
str: HTML download URL.
"""
import base64
from IPython.display import HTML
data = open(filename, "rb").read()
b64 = base64.b64encode(data)
payload = b64.decode()
basename = os.path.basename(filename)
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" style="color:#0000FF;" target="_blank">{title}</a>'
html = html.format(payload=payload, title=title + f" {basename}", filename=basename)
return HTML(html)
def edit_download_html(htmlWidget, filename, title="Click here to download: "):
"""Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578#issuecomment-617668058
Args:
htmlWidget (object): The HTML widget to display the URL.
filename (str): File path to download.
title (str, optional): Download description. Defaults to "Click here to download: ".
"""
# from IPython.display import HTML
# import ipywidgets as widgets
import base64
# Change widget html temporarily to a font-awesome spinner
htmlWidget.value = '<i class="fa fa-spinner fa-spin fa-2x fa-fw"></i><span class="sr-only">Loading...</span>'
# Process raw data
data = open(filename, "rb").read()
b64 = base64.b64encode(data)
payload = b64.decode()
basename = os.path.basename(filename)
# Create and assign html to widget
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>'
htmlWidget.value = html.format(
payload=payload, title=title + basename, filename=basename
)
def csv_points_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
"""Converts a csv file containing points (latitude, longitude) into a shapefile.
Args:
in_csv (str): File path or HTTP URL to the input csv file. For example, https://raw.githubusercontent.com/giswqs/data/main/world/world_cities.csv
out_shp (str): File path to the output shapefile.
latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'.
longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'.
"""
if in_csv.startswith("http") and in_csv.endswith(".csv"):
out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
out_name = os.path.basename(in_csv)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
download_from_url(in_csv, out_dir=out_dir)
in_csv = os.path.join(out_dir, out_name)
wbt = whitebox.WhiteboxTools()
in_csv = os.path.abspath(in_csv)
out_shp = os.path.abspath(out_shp)
if not os.path.exists(in_csv):
raise Exception("The provided csv file does not exist.")
with open(in_csv, encoding="utf-8") as csv_file:
reader = csv.DictReader(csv_file)
fields = reader.fieldnames
xfield = fields.index(longitude)
yfield = fields.index(latitude)
wbt.csv_points_to_vector(in_csv, out_shp, xfield=xfield, yfield=yfield, epsg=4326)
def csv_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
"""Converts a csv file with latlon info to a point shapefile.
Args:
in_csv (str): The input csv file containing longitude and latitude columns.
out_shp (str): The file path to the output shapefile.
latitude (str, optional): The column name of the latitude column. Defaults to 'latitude'.
longitude (str, optional): The column name of the longitude column. Defaults to 'longitude'.
"""
import shapefile as shp
if in_csv.startswith("http") and in_csv.endswith(".csv"):
out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
out_name = os.path.basename(in_csv)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
download_from_url(in_csv, out_dir=out_dir)
in_csv = os.path.join(out_dir, out_name)
out_dir = os.path.dirname(out_shp)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
try:
points = shp.Writer(out_shp, shapeType=shp.POINT)
with open(in_csv, encoding="utf-8") as csvfile:
csvreader = csv.DictReader(csvfile)
header = csvreader.fieldnames
[points.field(field) for field in header]
for row in csvreader:
points.point((float(row[longitude])), (float(row[latitude])))
points.record(*tuple([row[f] for f in header]))
out_prj = out_shp.replace(".shp", ".prj")
with open(out_prj, "w") as f:
prj_str = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]] '
f.write(prj_str)
except Exception as e:
raise Exception(e)
def pandas_to_geojson(
df,
out_geojson=None,
latitude="latitude",
longitude="longitude",
encoding="utf-8",
):
"""Creates points for a Pandas DataFrame and exports data as a GeoJSON.
Args:
df (pandas.DataFrame): The input Pandas DataFrame.
out_geojson (str): The file path to the exported GeoJSON. Default to None.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
"""
import json
from geojson import Feature, FeatureCollection, Point
if out_geojson is not None:
out_dir = os.path.dirname(os.path.abspath(out_geojson))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
features = df.apply(
lambda row: Feature(
geometry=Point((float(row[longitude]), float(row[latitude]))),
properties=dict(row),
),
axis=1,
).tolist()
geojson = FeatureCollection(features=features)
if out_geojson is None:
return geojson
else:
with open(out_geojson, "w", encoding=encoding) as f:
f.write(json.dumps(geojson))
def csv_to_geojson(
in_csv,
out_geojson=None,
latitude="latitude",
longitude="longitude",
encoding="utf-8",
):
"""Creates points for a CSV file and exports data as a GeoJSON.
Args:
in_csv (str): The file path to the input CSV file.
out_geojson (str): The file path to the exported GeoJSON. Default to None.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
"""
import json
import pandas as pd
if out_geojson is not None:
out_dir = os.path.dirname(os.path.abspath(out_geojson))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
df = pd.read_csv(in_csv)
geojson = pandas_to_geojson(
df, latitude=latitude, longitude=longitude, encoding=encoding
)
if out_geojson is None:
return geojson
else:
with open(out_geojson, "w", encoding=encoding) as f:
f.write(json.dumps(geojson))
def csv_to_gdf(in_csv, latitude="latitude", longitude="longitude", encoding="utf-8"):
"""Creates points for a CSV file and converts them to a GeoDataFrame.
Args:
in_csv (str): The file path to the input CSV file.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
Returns:
object: GeoDataFrame.
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
out_dir = os.getcwd()
out_geojson = os.path.join(out_dir, random_string() + ".geojson")
csv_to_geojson(in_csv, out_geojson, latitude, longitude, encoding)
gdf = gpd.read_file(out_geojson)
os.remove(out_geojson)
return gdf
def create_code_cell(code="", where="below"):
"""Creates a code cell in the IPython Notebook.
Args:
code (str, optional): Code to fill the new code cell with. Defaults to ''.
where (str, optional): Where to add the new code cell. It can be one of the following: above, below, at_bottom. Defaults to 'below'.
"""
import base64
from IPython.display import Javascript, display
encoded_code = (base64.b64encode(str.encode(code))).decode()
display(
Javascript(
"""
var code = IPython.notebook.insert_cell_{0}('code');
code.set_text(atob("{1}"));
""".format(
where, encoded_code
)
)
)
def cog_tile(url, titiler_endpoint="https://titiler.xyz", **kwargs):
"""Get a tile layer from a Cloud Optimized GeoTIFF (COG).
Source code adapted from https://developmentseed.org/titiler/examples/notebooks/Working_with_CloudOptimizedGeoTIFF_simple/
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
tuple: Returns the COG Tile layer URL and bounds.
"""
kwargs["url"] = url
TileMatrixSetId = "WebMercatorQuad"
if "TileMatrixSetId" in kwargs.keys():
TileMatrixSetId = kwargs["TileMatrixSetId"]
kwargs.pop("TileMatrixSetId")
r = requests.get(
f"{titiler_endpoint}/cog/{TileMatrixSetId}/tilejson.json", params=kwargs
).json()
return r["tiles"][0]
def cog_mosaic(
links,
titiler_endpoint="https://titiler.xyz",
username="anonymous",
layername=None,
overwrite=False,
verbose=True,
**kwargs,
):
"""Creates a COG mosaic from a list of COG URLs.
Args:
links (list): A list containing COG HTTP URLs.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
layername ([type], optional): Layer name to use. Defaults to None.
overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
verbose (bool, optional): Whether to print out descriptive information. Defaults to True.
Raises:
Exception: If the COG mosaic fails to create.
Returns:
str: The tile URL for the COG mosaic.
"""
if layername is None:
layername = "layer_" + random_string(5)
try:
if verbose:
print("Creating COG masaic ...")
# Create token
r = requests.post(
f"{titiler_endpoint}/tokens/create",
json={"username": username, "scope": ["mosaic:read", "mosaic:create"]},
).json()
token = r["token"]
# Create mosaic
requests.post(
f"{titiler_endpoint}/mosaicjson/create",
json={
"username": username,
"layername": layername,
"files": links,
# "overwrite": overwrite
},
params={
"access_token": token,
},
).json()
r2 = requests.get(
f"{titiler_endpoint}/mosaicjson/{username}.{layername}/tilejson.json",
).json()
return r2["tiles"][0]
except Exception as e:
raise Exception(e)
def cog_mosaic_from_file(
filepath,
skip_rows=0,
titiler_endpoint="https://titiler.xyz",
username="anonymous",
layername=None,
overwrite=False,
verbose=True,
**kwargs,
):
"""Creates a COG mosaic from a csv/txt file stored locally for through HTTP URL.
Args:
filepath (str): Local path or HTTP URL to the csv/txt file containing COG URLs.
skip_rows (int, optional): The number of rows to skip in the file. Defaults to 0.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
layername ([type], optional): Layer name to use. Defaults to None.
overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
verbose (bool, optional): Whether to print out descriptive information. Defaults to True.
Returns:
str: The tile URL for the COG mosaic.
"""
import urllib
links = []
if filepath.startswith("http"):
data = urllib.request.urlopen(filepath)
for line in data:
links.append(line.decode("utf-8").strip())
else:
with open(filepath) as f:
links = [line.strip() for line in f.readlines()]
links = links[skip_rows:]
# print(links)
mosaic = cog_mosaic(
links, titiler_endpoint, username, layername, overwrite, verbose, **kwargs
)
return mosaic
def cog_bounds(url, titiler_endpoint="https://titiler.xyz"):
"""Get the bounding box of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A list of values representing [left, bottom, right, top]
"""
r = requests.get(f"{titiler_endpoint}/cog/bounds", params={"url": url}).json()
if "bounds" in r.keys():
bounds = r["bounds"]
else:
bounds = None
return bounds
def cog_center(url, titiler_endpoint="https://titiler.xyz"):
"""Get the centroid of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
tuple: A tuple representing (longitude, latitude)
"""
bounds = cog_bounds(url, titiler_endpoint)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lat, lon)
return center
def cog_bands(url, titiler_endpoint="https://titiler.xyz"):
"""Get band names of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A list of band names
"""
r = requests.get(
f"{titiler_endpoint}/cog/info",
params={
"url": url,
},
).json()
bands = [b[0] for b in r["band_descriptions"]]
return bands
def cog_stats(url, titiler_endpoint="https://titiler.xyz"):
"""Get band statistics of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A dictionary of band statistics.
"""
r = requests.get(
f"{titiler_endpoint}/cog/statistics",
params={
"url": url,
},
).json()
return r
def cog_info(url, titiler_endpoint="https://titiler.xyz", return_geojson=False):
"""Get band statistics of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A dictionary of band info.
"""
info = "info"
if return_geojson:
info = "info.geojson"
r = requests.get(
f"{titiler_endpoint}/cog/{info}",
params={
"url": url,
},
).json()
return r
def cog_pixel_value(
lon,
lat,
url,
bidx=None,
titiler_endpoint="https://titiler.xyz",
verbose=True,
**kwargs,
):
"""Get pixel value from COG.
Args:
lon (float): Longitude of the pixel.
lat (float): Latitude of the pixel.
url (str): HTTP URL to a COG, e.g., 'https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif'
bidx (str, optional): Dataset band indexes (e.g bidx=1, bidx=1&bidx=2&bidx=3). Defaults to None.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
verbose (bool, optional): Print status messages. Defaults to True.
Returns:
list: A dictionary of band info.
"""
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
kwargs["url"] = url
if bidx is not None:
kwargs["bidx"] = bidx
r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
bands = cog_bands(url, titiler_endpoint)
# if isinstance(titiler_endpoint, str):
# r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
# else:
# r = requests.get(
# titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
# ).json()
if "detail" in r:
if verbose:
print(r["detail"])
return None
else:
values = r["values"]
result = dict(zip(bands, values))
return result
def stac_tile(
url=None,
collection=None,
items=None,
assets=None,
bands=None,
titiler_endpoint=None,
**kwargs,
):
"""Get a tile layer from a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.
Returns:
str: Returns the STAC Tile layer URL.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, PlanetaryComputerEndpoint):
if isinstance(bands, list):
bands = ",".join(bands)
if isinstance(assets, list):
assets = ",".join(assets)
if assets is None and (bands is not None):
assets = bands
else:
kwargs["bidx"] = bands
kwargs["assets"] = assets
if ("expression" in kwargs) and ("rescale" not in kwargs):
stats = stac_stats(
collection=collection,
items=items,
expression=kwargs["expression"],
titiler_endpoint=titiler_endpoint,
)
kwargs[
"rescale"
] = f"{stats[0]["percentile_2"]},{stats[0]["percentile_98"]}"
if ("asset_expression" in kwargs) and ("rescale" not in kwargs):
stats = stac_stats(
collection=collection,
items=items,
expression=kwargs["asset_expression"],
titiler_endpoint=titiler_endpoint,
)
kwargs[
"rescale"
] = f"{stats[0]["percentile_2"]},{stats[0]["percentile_98"]}"
if (
(assets is not None)
and ("asset_expression" not in kwargs)
and ("expression" not in kwargs)
and ("rescale" not in kwargs)
):
stats = stac_stats(
collection=collection,
items=items,
assets=assets,
titiler_endpoint=titiler_endpoint,
)
percentile_2 = min([s["percentile_2"] for s in stats])
percentile_98 = max([s["percentile_98"] for s in stats])
kwargs["rescale"] = f"{percentile_2},{percentile_98}"
else:
if isinstance(bands, str):
bands = bands.split(",")
if isinstance(assets, str):
assets = assets.split(",")
if assets is None and (bands is not None):
assets = bands
else:
kwargs["asset_bidx"] = bands
kwargs["assets"] = assets
TileMatrixSetId = "WebMercatorQuad"
if "TileMatrixSetId" in kwargs.keys():
TileMatrixSetId = kwargs["TileMatrixSetId"]
kwargs.pop("TileMatrixSetId")
if isinstance(titiler_endpoint, str):
r = requests.get(
f"{titiler_endpoint}/stac/{TileMatrixSetId}/tilejson.json",
params=kwargs,
).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_item(), params=kwargs).json()
return r["tiles"][0]
def stac_bounds(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get the bounding box of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of values representing [left, bottom, right, top]
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/bounds", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_bounds(), params=kwargs).json()
bounds = r["bounds"]
return bounds
def stac_center(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get the centroid of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
tuple: A tuple representing (longitude, latitude)
"""
bounds = stac_bounds(url, collection, items, titiler_endpoint, **kwargs)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lon, lat)
return center
def stac_bands(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get band names of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of band names
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_assets(), params=kwargs).json()
return r
def stac_stats(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band statistics of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band statistics.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/statistics", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_statistics(), params=kwargs
).json()
return r
def stac_info(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band info of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band info.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/info", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_info(), params=kwargs).json()
return r
def stac_info_geojson(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band info of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band info.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/info.geojson", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_info_geojson(), params=kwargs
).json()
return r
def stac_assets(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get all assets of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of assets.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_assets(), params=kwargs).json()
return r
def stac_pixel_value(
lon,
lat,
url=None,
collection=None,
items=None,
assets=None,
titiler_endpoint=None,
verbose=True,
**kwargs,
):
"""Get pixel value from STAC assets.
Args:
lon (float): Longitude of the pixel.
lat (float): Latitude of the pixel.
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
verbose (bool, optional): Print out the error message. Defaults to True.
Returns:
list: A dictionary of pixel values for each asset.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is None:
assets = stac_assets(
url=url,
collection=collection,
items=items,
titiler_endpoint=titiler_endpoint,
)
assets = ",".join(assets)
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/{lon},{lat}", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
).json()
if "detail" in r:
if verbose:
print(r["detail"])
return None
else:
values = [v[0] for v in r["values"]]
result = dict(zip(assets.split(","), values))
return result
def bbox_to_geojson(bounds):
"""Convert coordinates of a bounding box to a geojson.
Args:
bounds (list): A list of coordinates representing [left, bottom, right, top].
Returns:
dict: A geojson feature.
"""
return {
"geometry": {
"type": "Polygon",
"coordinates": [
[
[bounds[0], bounds[3]],
[bounds[0], bounds[1]],
[bounds[2], bounds[1]],
[bounds[2], bounds[3]],
[bounds[0], bounds[3]],
]
],
},
"type": "Feature",
}
def coords_to_geojson(coords):
"""Convert a list of bbox coordinates representing [left, bottom, right, top] to geojson FeatureCollection.
Args:
coords (list): A list of bbox coordinates representing [left, bottom, right, top].
Returns:
dict: A geojson FeatureCollection.
"""
features = []
for bbox in coords:
features.append(bbox_to_geojson(bbox))
return {"type": "FeatureCollection", "features": features}
def explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield
coordinate tuples. As long as the input is conforming, the type of
the geometry doesn't matter. From Fiona 1.4.8
Args:
coords (list): A list of coordinates.
Yields:
[type]: [description]
"""
for e in coords:
if isinstance(e, (float, int)):
yield coords
break
else:
for f in explode(e):
yield f
def get_bounds(geometry, north_up=True, transform=None):
"""Bounding box of a GeoJSON geometry, GeometryCollection, or FeatureCollection.
left, bottom, right, top
*not* xmin, ymin, xmax, ymax
If not north_up, y will be switched to guarantee the above.
Source code adapted from https://github.com/mapbox/rasterio/blob/master/rasterio/features.py#L361
Args:
geometry (dict): A GeoJSON dict.
north_up (bool, optional): . Defaults to True.
transform ([type], optional): . Defaults to None.
Returns:
list: A list of coordinates representing [left, bottom, right, top]
"""
if "bbox" in geometry:
return tuple(geometry["bbox"])
geometry = geometry.get("geometry") or geometry
# geometry must be a geometry, GeometryCollection, or FeatureCollection
if not (
"coordinates" in geometry or "geometries" in geometry or "features" in geometry
):
raise ValueError(
"geometry must be a GeoJSON-like geometry, GeometryCollection, "
"or FeatureCollection"
)
if "features" in geometry:
# Input is a FeatureCollection
xmins = []
ymins = []
xmaxs = []
ymaxs = []
for feature in geometry["features"]:
xmin, ymin, xmax, ymax = get_bounds(feature["geometry"])
xmins.append(xmin)
ymins.append(ymin)
xmaxs.append(xmax)
ymaxs.append(ymax)
if north_up:
return min(xmins), min(ymins), max(xmaxs), max(ymaxs)
else:
return min(xmins), max(ymaxs), max(xmaxs), min(ymins)
elif "geometries" in geometry:
# Input is a geometry collection
xmins = []
ymins = []
xmaxs = []
ymaxs = []
for geometry in geometry["geometries"]:
xmin, ymin, xmax, ymax = get_bounds(geometry)
xmins.append(xmin)
ymins.append(ymin)
xmaxs.append(xmax)
ymaxs.append(ymax)
if north_up:
return min(xmins), min(ymins), max(xmaxs), max(ymaxs)
else:
return min(xmins), max(ymaxs), max(xmaxs), min(ymins)
elif "coordinates" in geometry:
# Input is a singular geometry object
if transform is not None:
xyz = list(explode(geometry["coordinates"]))
xyz_px = [transform * point for point in xyz]
xyz = tuple(zip(*xyz_px))
return min(xyz[0]), max(xyz[1]), max(xyz[0]), min(xyz[1])
else:
xyz = tuple(zip(*list(explode(geometry["coordinates"]))))
if north_up:
return min(xyz[0]), min(xyz[1]), max(xyz[0]), max(xyz[1])
else:
return min(xyz[0]), max(xyz[1]), max(xyz[0]), min(xyz[1])
# all valid inputs returned above, so whatever falls through is an error
raise ValueError(
"geometry must be a GeoJSON-like geometry, GeometryCollection, "
"or FeatureCollection"
)
def get_center(geometry, north_up=True, transform=None):
"""Get the centroid of a GeoJSON.
Args:
geometry (dict): A GeoJSON dict.
north_up (bool, optional): . Defaults to True.
transform ([type], optional): . Defaults to None.
Returns:
list: [lon, lat]
"""
bounds = get_bounds(geometry, north_up, transform)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lat, lon)
return center
def adjust_longitude(in_fc):
"""Adjusts longitude if it is less than -180 or greater than 180.
Args:
in_fc (dict): The input dictionary containing coordinates.
Returns:
dict: A dictionary containing the converted longitudes
"""
try:
keys = in_fc.keys()
if "geometry" in keys:
coordinates = in_fc["geometry"]["coordinates"]
if in_fc["geometry"]["type"] == "Point":
longitude = coordinates[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][0] = longitude
elif in_fc["geometry"]["type"] == "Polygon":
for index1, item in enumerate(coordinates):
for index2, element in enumerate(item):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][index1][index2][0] = longitude
elif in_fc["geometry"]["type"] == "LineString":
for index, element in enumerate(coordinates):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][index][0] = longitude
elif "type" in keys:
coordinates = in_fc["coordinates"]
if in_fc["type"] == "Point":
longitude = coordinates[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][0] = longitude
elif in_fc["type"] == "Polygon":
for index1, item in enumerate(coordinates):
for index2, element in enumerate(item):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][index1][index2][0] = longitude
elif in_fc["type"] == "LineString":
for index, element in enumerate(coordinates):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][index][0] = longitude
return in_fc
except Exception as e:
print(e)
return None
def is_GCS(in_shp):
import warnings
import pycrs
if not os.path.exists(in_shp):
raise FileNotFoundError("The input shapefile could not be found.")
if not in_shp.endswith(".shp"):
raise TypeError("The input shapefile is invalid.")
in_prj = in_shp.replace(".shp", ".prj")
if not os.path.exists(in_prj):
warnings.warn(
f"The projection file {in_prj} could not be found. Assuming the dataset is in a geographic coordinate system (GCS)."
)
return True
else:
with open(in_prj) as f:
esri_wkt = f.read()
epsg4326 = pycrs.parse.from_epsg_code(4326).to_proj4()
try:
crs = pycrs.parse.from_esri_wkt(esri_wkt).to_proj4()
if crs == epsg4326:
return True
else:
return False
except Exception:
return False
def kml_to_shp(in_kml, out_shp):
"""Converts a KML to shapefile.
Args:
in_kml (str): The file path to the input KML.
out_shp (str): The file path to the output shapefile.
Raises:
FileNotFoundError: The input KML could not be found.
TypeError: The output must be a shapefile.
"""
import warnings
warnings.filterwarnings("ignore")
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The input KML could not be found.")
out_shp = os.path.abspath(out_shp)
if not out_shp.endswith(".shp"):
raise TypeError("The output must be a shapefile.")
out_dir = os.path.dirname(out_shp)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
# import fiona
# print(fiona.supported_drivers)
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
df = gpd.read_file(in_kml, driver="KML")
df.to_file(out_shp)
def kml_to_geojson(in_kml, out_geojson=None):
"""Converts a KML to GeoJSON.
Args:
in_kml (str): The file path to the input KML.
out_geojson (str): The file path to the output GeoJSON. Defaults to None.
Raises:
FileNotFoundError: The input KML could not be found.
TypeError: The output must be a GeoJSON.
"""
import warnings
warnings.filterwarnings("ignore")
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The input KML could not be found.")
if out_geojson is not None:
out_geojson = os.path.abspath(out_geojson)
ext = os.path.splitext(out_geojson)[1].lower()
if ext not in [".json", ".geojson"]:
raise TypeError("The output file must be a GeoJSON.")
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
# import fiona
# print(fiona.supported_drivers)
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(in_kml, driver="KML")
if out_geojson is not None:
gdf.to_file(out_geojson, driver="GeoJSON")
else:
return gdf.__geo_interface__
def csv_to_pandas(in_csv, **kwargs):
"""Converts a CSV file to pandas dataframe.
Args:
in_csv (str): File path to the input CSV.
Returns:
pd.DataFrame: pandas DataFrame
"""
import pandas as pd
try:
return pd.read_csv(in_csv, **kwargs)
except Exception as e:
raise Exception(e)
def shp_to_gdf(in_shp):
"""Converts a shapefile to Geopandas dataframe.
Args:
in_shp (str): File path to the input shapefile.
Raises:
FileNotFoundError: The provided shp could not be found.
Returns:
gpd.GeoDataFrame: geopandas.GeoDataFrame
"""
import warnings
warnings.filterwarnings("ignore")
in_shp = os.path.abspath(in_shp)
if not os.path.exists(in_shp):
raise FileNotFoundError("The provided shp could not be found.")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
try:
return gpd.read_file(in_shp)
except Exception as e:
raise Exception(e)
def shp_to_geojson(in_shp, out_json=None, **kwargs):
"""Converts a shapefile to GeoJSON.
Args:
in_shp (str): File path of the input shapefile.
out_json (str, optional): File path of the output GeoJSON. Defaults to None.
Returns:
object: The json object representing the shapefile.
"""
try:
import shapefile
from datetime import date
in_shp = os.path.abspath(in_shp)
if out_json is not None:
ext = os.path.splitext(out_json)[1]
print(ext)
if ext.lower() not in [".json", ".geojson"]:
raise TypeError("The output file extension must the .json or .geojson.")
if not os.path.exists(os.path.dirname(out_json)):
os.makedirs(os.path.dirname(out_json))
if not is_GCS(in_shp):
try:
import geopandas as gpd
except Exception:
raise ImportError(
"Geopandas is required to perform reprojection of the data. See https://geopandas.org/install.html"
)
try:
in_gdf = gpd.read_file(in_shp)
out_gdf = in_gdf.to_crs(epsg="4326")
out_shp = in_shp.replace(".shp", "_gcs.shp")
out_gdf.to_file(out_shp)
in_shp = out_shp
except Exception as e:
raise Exception(e)
if "encoding" in kwargs:
reader = shapefile.Reader(in_shp, encoding=kwargs.pop("encoding"))
else:
reader = shapefile.Reader(in_shp)
out_dict = reader.__geo_interface__
if out_json is not None:
import json
with open(out_json, "w") as geojson:
geojson.write(json.dumps(out_dict, indent=2) + "\n")
else:
return out_dict
except Exception as e:
raise Exception(e)
def delete_shp(in_shp, verbose=False):
"""Deletes a shapefile.
Args:
in_shp (str): The input shapefile to delete.
verbose (bool, optional): Whether to print out descriptive text. Defaults to True.
"""
from pathlib import Path
in_shp = os.path.abspath(in_shp)
in_dir = os.path.dirname(in_shp)
basename = os.path.basename(in_shp).replace(".shp", "")
files = Path(in_dir).rglob(basename + ".*")
for file in files:
filepath = os.path.join(in_dir, str(file))
os.remove(filepath)
if verbose:
print(f"Deleted {filepath}")
def vector_to_geojson(
filename, out_geojson=None, bbox=None, mask=None, rows=None, epsg="4326", **kwargs
):
"""Converts any geopandas-supported vector dataset to GeoJSON.
Args:
filename (str): Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).
out_geojson (str, optional): The file path to the output GeoJSON. Defaults to None.
bbox (tuple | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.
mask (dict | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.
rows (int or slice, optional): Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.
epsg (str, optional): The EPSG number to convert to. Defaults to "4326".
Raises:
ValueError: When the output file path is invalid.
Returns:
dict: A dictionary containing the GeoJSON.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
if not filename.startswith("http"):
filename = os.path.abspath(filename)
if filename.endswith(".zip"):
filename = "zip://" + filename
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
df = gpd.read_file(
filename, bbox=bbox, mask=mask, rows=rows, driver="KML", **kwargs
)
else:
df = gpd.read_file(filename, bbox=bbox, mask=mask, rows=rows, **kwargs)
gdf = df.to_crs(epsg=epsg)
if out_geojson is not None:
if not out_geojson.lower().endswith(".geojson"):
raise ValueError("The output file must have a geojson file extension.")
out_geojson = os.path.abspath(out_geojson)
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
gdf.to_file(out_geojson, driver="GeoJSON")
else:
return gdf.__geo_interface__
def screen_capture(outfile, monitor=1):
"""Takes a full screenshot of the selected monitor.
Args:
outfile (str): The output file path to the screenshot.
monitor (int, optional): The monitor to take the screenshot. Defaults to 1.
"""
from mss import mss
out_dir = os.path.dirname(outfile)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
if not isinstance(monitor, int):
print("The monitor number must be an integer.")
return
try:
with mss() as sct:
sct.shot(output=outfile, mon=monitor)
return outfile
except Exception as e:
raise Exception(e)
def gdf_to_geojson(gdf, out_geojson=None, epsg=None):
"""Converts a GeoDataFame to GeoJSON.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
out_geojson (str, optional): File path to he output GeoJSON. Defaults to None.
epsg (str, optional): An EPSG string, e.g., "4326". Defaults to None.
Raises:
TypeError: When the output file extension is incorrect.
Exception: When the conversion fails.
Returns:
dict: When the out_json is None returns a dict.
"""
check_package(name="geopandas", URL="https://geopandas.org")
try:
if epsg is not None:
gdf = gdf.to_crs(epsg=epsg)
geojson = gdf.__geo_interface__
if out_geojson is None:
return geojson
else:
ext = os.path.splitext(out_geojson)[1]
if ext.lower() not in [".json", ".geojson"]:
raise TypeError(
"The output file extension must be either .json or .geojson"
)
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
gdf.to_file(out_geojson, driver="GeoJSON")
except Exception as e:
raise Exception(e)
def connect_postgis(
database, host="localhost", user=None, password=None, port=5432, use_env_var=False
):
"""Connects to a PostGIS database.
Args:
database (str): Name of the database
host (str, optional): Hosting server for the database. Defaults to "localhost".
user (str, optional): User name to access the database. Defaults to None.
password (str, optional): Password to access the database. Defaults to None.
port (int, optional): Port number to connect to at the server host. Defaults to 5432.
use_env_var (bool, optional): Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False.
Raises:
ValueError: If user is not specified.
ValueError: If password is not specified.
Returns:
[type]: [description]
"""
check_package(name="geopandas", URL="https://geopandas.org")
check_package(
name="sqlalchemy",
URL="https://docs.sqlalchemy.org/en/14/intro.html#installation",
)
from sqlalchemy import create_engine
if use_env_var:
if user is not None:
user = os.getenv(user)
else:
user = os.getenv("SQL_USER")
if password is not None:
password = os.getenv(password)
else:
password = os.getenv("SQL_PASSWORD")
if user is None:
raise ValueError("user is not specified.")
if password is None:
raise ValueError("password is not specified.")
connection_string = f"postgresql://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(connection_string)
return engine
def read_postgis(sql, con, geom_col="geom", crs=None, **kwargs):
"""Reads data from a PostGIS database and returns a GeoDataFrame.
Args:
sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database.
con (sqlalchemy.engine.Engine): Active connection to the database to query.
geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom".
crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None.
Returns:
[type]: [description]
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
gdf = gpd.read_postgis(sql, con, geom_col, crs, **kwargs)
return gdf
def vector_col_names(filename, **kwargs):
"""Retrieves the column names of a vector attribute table.
Args:
filename (str): The input file path.
Returns:
list: The list of column names.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
if not filename.startswith("http"):
filename = os.path.abspath(filename)
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(filename, driver="KML", **kwargs)
else:
gdf = gpd.read_file(filename, **kwargs)
col_names = gdf.columns.values.tolist()
return col_names
def get_api_key(token_name, m=None):
"""Retrieves an API key based on a system environmen variable.
Args:
token_name (str): The token name.
m (ipyleaflet.Map | folium.Map, optional): A Map instance. Defaults to None.
Returns:
str: The API key.
"""
api_key = os.environ.get(token_name)
if m is not None and token_name in m.api_keys:
api_key = m.api_keys[token_name]
return api_key
def set_api_key(token_name, api_key, m=None):
"""Sets an API key as an environment variable.
Args:
token_name (str): The token name.
api_key (str): The API key.
m (ipyleaflet.Map | folium.Map, optional): A Map instance.. Defaults to None.
"""
os.environ[token_name] = api_key
if m is not None:
m.api_keys[token_name] = api_key
def planet_monthly_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
links = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2020, year_now + 1):
for month in range(1, 13):
m_str = str(year) + "-" + str(month).zfill(2)
if year == 2020 and month < 9:
continue
if year == year_now and month >= month_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
links.append(url)
return links
def planet_biannual_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
dates = [
"2015-12_2016-05",
"2016-06_2016-11",
"2016-12_2017-05",
"2017-06_2017-11",
"2017-12_2018-05",
"2018-06_2018-11",
"2018-12_2019-05",
"2019-06_2019-11",
"2019-12_2020-05",
"2020-06_2020-08",
]
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for d in dates:
url = f"{prefix}{d}{subfix}{api_key}"
link.append(url)
return link
def planet_catalog_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Returns:
list: A list of tile URLs.
"""
biannual = planet_biannual_tropical(api_key, token_name)
monthly = planet_monthly_tropical(api_key, token_name)
return biannual + monthly
def planet_monthly_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_monthly_tropical(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 7]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_biannual_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet bi-annual imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_biannual_tropical(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 15]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
catalog = {}
biannul = planet_biannual_tiles_tropical(api_key, token_name, tile_format)
monthly = planet_monthly_tiles_tropical(api_key, token_name, tile_format)
for key in biannul:
catalog[key] = biannul[key]
for key in monthly:
catalog[key] = monthly[key]
return catalog
def planet_monthly(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet monthly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2016, year_now + 1):
for month in range(1, 13):
m_str = str(year) + "_" + str(month).zfill(2)
if year == year_now and month >= month_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
link.append(url)
return link
def planet_quarterly(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet quarterly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
quarter_now = (month_now - 1) // 3 + 1
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2016, year_now + 1):
for quarter in range(1, 5):
m_str = str(year) + "q" + str(quarter)
if year == year_now and quarter >= quarter_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
link.append(url)
return link
def planet_catalog(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Returns:
list: A list of tile URLs.
"""
quarterly = planet_quarterly(api_key, token_name)
monthly = planet_monthly(api_key, token_name)
return quarterly + monthly
def planet_monthly_tiles(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_monthly(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 7]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_quarterly_tiles(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
links = planet_quarterly(api_key, token_name)
for url in links:
index = url.find("20")
name = "Planet_" + url[index : index + 6]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_tiles(api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"):
"""Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
catalog = {}
quarterly = planet_quarterly_tiles(api_key, token_name, tile_format)
monthly = planet_monthly_tiles(api_key, token_name, tile_format)
for key in quarterly:
catalog[key] = quarterly[key]
for key in monthly:
catalog[key] = monthly[key]
return catalog
def planet_by_quarter(
year=2016,
quarter=1,
api_key=None,
token_name="PLANET_API_KEY",
):
"""Gets Planet global mosaic tile url by quarter. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: The Planet API key is not provided.
ValueError: The year is invalid.
ValueError: The quarter is invalid.
ValueError: The quarter is invalid.
Returns:
str: A Planet global mosaic tile url.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
quarter_now = (month_now - 1) // 3 + 1
if year > year_now:
raise ValueError(f"Year must be between 2016 and {year_now}.")
elif year == year_now and quarter >= quarter_now:
raise ValueError(f"Quarter must be less than {quarter_now} for year {year_now}")
if quarter < 1 or quarter > 4:
raise ValueError("Quarter must be between 1 and 4.")
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
m_str = str(year) + "q" + str(quarter)
url = f"{prefix}{m_str}{subfix}{api_key}"
return url
def planet_by_month(
year=2016,
month=1,
api_key=None,
token_name="PLANET_API_KEY",
):
"""Gets Planet global mosaic tile url by month. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: The Planet API key is not provided.
ValueError: The year is invalid.
ValueError: The month is invalid.
ValueError: The month is invalid.
Returns:
str: A Planet global mosaic tile url.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
# quarter_now = (month_now - 1) // 3 + 1
if year > year_now:
raise ValueError(f"Year must be between 2016 and {year_now}.")
elif year == year_now and month >= month_now:
raise ValueError(f"Month must be less than {month_now} for year {year_now}")
if month < 1 or month > 12:
raise ValueError("Month must be between 1 and 12.")
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
m_str = str(year) + "_" + str(month).zfill(2)
url = f"{prefix}{m_str}{subfix}{api_key}"
return url
def planet_tile_by_quarter(
year=2016,
quarter=1,
name=None,
api_key=None,
token_name="PLANET_API_KEY",
tile_format="ipyleaflet",
):
"""Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
url = planet_by_quarter(year, quarter, api_key, token_name)
if name is None:
name = "Planet_" + str(year) + "_q" + str(quarter)
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
return tile
def planet_tile_by_month(
year=2016,
month=1,
name=None,
api_key=None,
token_name="PLANET_API_KEY",
tile_format="ipyleaflet",
):
"""Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
url = planet_by_month(year, month, api_key, token_name)
if name is None:
name = "Planet_" + str(year) + "_" + str(month).zfill(2)
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
return tile
def basemap_xyz_tiles():
"""Returns a dictionary containing a set of basemaps that are XYZ tile layers.
Returns:
dict: A dictionary of XYZ tile layers.
"""
from .leafmap import leafmap_basemaps
layers_dict = {}
keys = dict(leafmap_basemaps).keys()
for key in keys:
if isinstance(leafmap_basemaps[key], ipyleaflet.WMSLayer):
pass
else:
layers_dict[key] = leafmap_basemaps[key]
return layers_dict
def to_hex_colors(colors):
"""Adds # to a list of hex color codes.
Args:
colors (list): A list of hex color codes.
Returns:
list: A list of hex color codes prefixed with #.
"""
result = all([len(color.strip()) == 6 for color in colors])
if result:
return ["#" + color.strip() for color in colors]
else:
return colors
def display_html(src, width=950, height=600):
"""Display an HTML file in a Jupyter Notebook.
Args
src (str): File path to HTML file.
width (int, optional): Width of the map. Defaults to 950.
height (int, optional): Height of the map. Defaults to 600.
"""
if not os.path.isfile(src):
raise ValueError(f"{src} is not a valid file path.")
display(IFrame(src=src, width=width, height=height))
def get_census_dict(reset=False):
"""Returns a dictionary of Census data.
Args:
reset (bool, optional): Reset the dictionary. Defaults to False.
Returns:
dict: A dictionary of Census data.
"""
import json
import pkg_resources
pkg_dir = os.path.dirname(pkg_resources.resource_filename("leafmap", "leafmap.py"))
census_data = os.path.join(pkg_dir, "data/census_data.json")
if reset:
from owslib.wms import WebMapService
census_dict = {}
names = [
"Current",
"ACS 2021",
"ACS 2019",
"ACS 2018",
"ACS 2017",
"ACS 2016",
"ACS 2015",
"ACS 2014",
"ACS 2013",
"ACS 2012",
"ECON 2012",
"Census 2020",
"Census 2010",
"Physical Features",
"Decennial Census 2020",
"Decennial Census 2010",
"Decennial Census 2000",
"Decennial Physical Features",
]
links = {}
print("Retrieving data. Please wait ...")
for name in names:
if "Decennial" not in name:
links[
name
] = f"https://tigerweb.geo.census.gov/arcgis/services/TIGERweb/tigerWMS_{name.replace(" ", "")}/MapServer/WMSServer"
else:
links[
name
] = f"https://tigerweb.geo.census.gov/arcgis/services/Census2020/tigerWMS_{name.replace("Decennial", "").replace(" ", "")}/MapServer/WMSServer"
wms = WebMapService(links[name], timeout=300)
layers = list(wms.contents)
layers.sort()
census_dict[name] = {
"url": links[name],
"layers": layers,
# "title": wms.identification.title,
# "abstract": wms.identification.abstract,
}
with open(census_data, "w") as f:
json.dump(census_dict, f, indent=4)
else:
with open(census_data, "r") as f:
census_dict = json.load(f)
return census_dict
def search_xyz_services(keyword, name=None, list_only=True, add_prefix=True):
"""Search for XYZ tile providers from xyzservices.
Args:
keyword (str): The keyword to search for.
name (str, optional): The name of the xyz tile. Defaults to None.
list_only (bool, optional): If True, only the list of services will be returned. Defaults to True.
add_prefix (bool, optional): If True, the prefix "xyz." will be added to the service name. Defaults to True.
Returns:
list: A list of XYZ tile providers.
"""
import xyzservices.providers as xyz
if name is None:
providers = xyz.filter(keyword=keyword).flatten()
else:
providers = xyz.filter(name=name).flatten()
if list_only:
if add_prefix:
return ["xyz." + provider for provider in providers]
else:
return [provider for provider in providers]
else:
return providers
def search_qms(keyword, limit=10, list_only=True, add_prefix=True):
"""Search for QMS tile providers from Quick Map Services.
Args:
keyword (str): The keyword to search for.
limit (int, optional): The maximum number of results to return. Defaults to 10.
list_only (bool, optional): If True, only the list of services will be returned. Defaults to True.
add_prefix (bool, optional): If True, the prefix "qms." will be added to the service name. Defaults to True.
Returns:
list: A list of QMS tile providers.
"""
QMS_API = "https://qms.nextgis.com/api/v1/geoservices"
services = requests.get(
f"{QMS_API}/?search={keyword}&type=tms&epsg=3857&limit={limit}"
)
services = services.json()
if services["results"]:
providers = services["results"]
if list_only:
if add_prefix:
return ["qms." + provider["name"] for provider in providers]
else:
return [provider["name"] for provider in providers]
else:
return providers
else:
return None
def get_wms_layers(url):
"""Returns a list of WMS layers from a WMS service.
Args:
url (str): The URL of the WMS service.
Returns:
list: A list of WMS layers.
"""
from owslib.wms import WebMapService
wms = WebMapService(url)
layers = list(wms.contents)
layers.sort()
return layers
def create_legend(
legend_title="Legend",
legend_dict=None,
legend_keys=None,
legend_colors=None,
builtin_legend=None,
**kwargs,
):
"""Create a custom legend.
Args:
legend_title (str, optional): Title of the legend. Defaults to 'Legend'.
legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
legend_keys (list, optional): A list of legend keys. Defaults to None.
legend_colors (list, optional): A list of legend colors. Defaults to None.
builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
"""
import pkg_resources
from .legends import builtin_legends
pkg_dir = os.path.dirname(pkg_resources.resource_filename("leafmap", "leafmap.py"))
legend_template = os.path.join(pkg_dir, "data/template/legend.html")
if "min_width" not in kwargs.keys():
min_width = None
if "max_width" not in kwargs.keys():
max_width = None
else:
max_width = kwargs["max_width"]
if "min_height" not in kwargs.keys():
min_height = None
else:
min_height = kwargs["min_height"]
if "max_height" not in kwargs.keys():
max_height = None
else:
max_height = kwargs["max_height"]
if "height" not in kwargs.keys():
height = None
else:
height = kwargs["height"]
if "width" not in kwargs.keys():
width = None
else:
width = kwargs["width"]
if width is None:
max_width = "300px"
if height is None:
max_height = "400px"
if not os.path.exists(legend_template):
print("The legend template does not exist.")
return
if legend_keys is not None:
if not isinstance(legend_keys, list):
print("The legend keys must be a list.")
return
else:
legend_keys = ["One", "Two", "Three", "Four", "etc"]
if legend_colors is not None:
if not isinstance(legend_colors, list):
print("The legend colors must be a list.")
return
elif all(isinstance(item, tuple) for item in legend_colors):
try:
legend_colors = [rgb_to_hex(x) for x in legend_colors]
except Exception as e:
print(e)
elif all((item.startswith("#") and len(item) == 7) for item in legend_colors):
pass
elif all((len(item) == 6) for item in legend_colors):
pass
else:
print("The legend colors must be a list of tuples.")
return
else:
legend_colors = [
"#8DD3C7",
"#FFFFB3",
"#BEBADA",
"#FB8072",
"#80B1D3",
]
if len(legend_keys) != len(legend_colors):
print("The legend keys and values must be the same length.")
return
allowed_builtin_legends = builtin_legends.keys()
if builtin_legend is not None:
if builtin_legend not in allowed_builtin_legends:
print(
"The builtin legend must be one of the following: {}".format(
", ".join(allowed_builtin_legends)
)
)
return
else:
legend_dict = builtin_legends[builtin_legend]
legend_keys = list(legend_dict.keys())
legend_colors = list(legend_dict.values())
if legend_dict is not None:
if not isinstance(legend_dict, dict):
print("The legend dict must be a dictionary.")
return
else:
legend_keys = list(legend_dict.keys())
legend_colors = list(legend_dict.values())
if all(isinstance(item, tuple) for item in legend_colors):
try:
legend_colors = [rgb_to_hex(x) for x in legend_colors]
except Exception as e:
print(e)
header = []
content = []
footer = []
with open(legend_template) as f:
lines = f.readlines()
lines[3] = lines[3].replace("Legend", legend_title)
header = lines[:6]
footer = lines[11:]
for index, key in enumerate(legend_keys):
color = legend_colors[index]
if not color.startswith("#"):
color = "#" + color
item = " <li><span style='background:{};'></span>{}</li>\n".format(
color, key
)
content.append(item)
legend_html = header + content + footer
legend_text = "".join(legend_html)
return legend_text
def streamlit_legend(html, width=None, height=None, scrolling=True):
"""Streamlit function to display a legend.
Args:
html (str): The HTML string of the legend.
width (str, optional): The width of the legend. Defaults to None.
height (str, optional): The height of the legend. Defaults to None.
scrolling (bool, optional): Whether to allow scrolling in the legend. Defaults to True.
"""
try:
import streamlit.components.v1 as components
components.html(html, width=width, height=height, scrolling=scrolling)
except ImportError:
print("Streamlit is not installed. Please run 'pip install streamlit'.")
return
def read_file_from_url(url, return_type="list", encoding="utf-8"):
"""Reads a file from a URL.
Args:
url (str): The URL of the file.
return_type (str, optional): The return type, can either be string or list. Defaults to "list".
encoding (str, optional): The encoding of the file. Defaults to "utf-8".
Raises:
ValueError: The return type must be either list or string.
Returns:
str | list: The contents of the file.
"""
from urllib.request import urlopen
if return_type == "list":
return [line.decode(encoding).rstrip() for line in urlopen(url).readlines()]
elif return_type == "string":
return urlopen(url).read().decode(encoding)
else:
raise ValueError("The return type must be either list or string.")
def st_download_button(
label,
data,
file_name=None,
mime=None,
key=None,
help=None,
on_click=None,
args=None,
csv_sep=",",
**kwargs,
):
"""Streamlit function to create a download button.
Args:
label (str): A short label explaining to the user what this button is for..
data (str | list): The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily.
file_name (str, optional): An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None.
mime (str, optional): The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None.
key (str, optional): An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None.
help (str, optional): An optional tooltip that gets displayed when the button is hovered over. Defaults to None.
on_click (str, optional): An optional callback invoked when this button is clicked. Defaults to None.
args (list, optional): An optional tuple of args to pass to the callback. Defaults to None.
kwargs (dict, optional): An optional tuple of args to pass to the callback.
"""
try:
import streamlit as st
import pandas as pd
if isinstance(data, str):
if file_name is None:
file_name = data.split("/")[-1]
if data.endswith(".csv"):
data = pd.read_csv(data).to_csv(sep=csv_sep, index=False)
if mime is None:
mime = "text/csv"
return st.download_button(
label, data, file_name, mime, key, help, on_click, args, **kwargs
)
elif (
data.endswith(".gif") or data.endswith(".png") or data.endswith(".jpg")
):
if mime is None:
mime = f"image/{os.path.splitext(data)[1][1:]}"
with open(data, "rb") as file:
return st.download_button(
label,
file,
file_name,
mime,
key,
help,
on_click,
args,
**kwargs,
)
elif isinstance(data, pd.DataFrame):
if file_name is None:
file_name = "data.csv"
data = data.to_csv(sep=csv_sep, index=False)
if mime is None:
mime = "text/csv"
return st.download_button(
label, data, file_name, mime, key, help, on_click, args, **kwargs
)
else:
# if mime is None:
# mime = "application/pdf"
return st.download_button(
label,
data,
file_name,
mime,
key,
help,
on_click,
args,
**kwargs,
)
except ImportError:
print("Streamlit is not installed. Please run 'pip install streamlit'.")
return
except Exception as e:
raise Exception(e)
def save_data(data, file_ext=None, file_name=None):
"""Save data in the memory to a file.
Args:
data (object): The data to be saved.
file_ext (str): The file extension of the file.
file_name (str, optional): The name of the file to be saved. Defaults to None.
Returns:
str: The path of the file.
"""
import tempfile
import uuid
try:
if file_ext is None:
if hasattr(data, "name"):
_, file_ext = os.path.splitext(data.name)
else:
if not file_ext.startswith("."):
file_ext = "." + file_ext
if file_name is not None:
file_path = os.path.abspath(file_name)
if not file_path.endswith(file_ext):
file_path = file_path + file_ext
else:
file_id = str(uuid.uuid4())
file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_ext}")
with open(file_path, "wb") as file:
file.write(data.getbuffer())
return file_path
except Exception as e:
print(e)
return None
def temp_file_path(extension):
"""Returns a temporary file path.
Args:
extension (str): The file extension.
Returns:
str: The temporary file path.
"""
import tempfile
import os
import uuid
if not extension.startswith("."):
extension = "." + extension
file_id = str(uuid.uuid4())
file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}")
return file_path
def get_local_tile_layer(
source,
port="default",
debug=False,
projection="EPSG:3857",
band=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
tile_format="ipyleaflet",
layer_name=None,
get_center=False,
get_bounds=False,
**kwargs,
):
"""Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG).
Args:
source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.
port (str, optional): The port to use for the server. Defaults to "default".
debug (bool, optional): If True, the server will be started in debug mode. Defaults to False.
projection (str, optional): The projection of the GeoTIFF. Defaults to "EPSG:3857".
band (int, optional): The band to use. Band indexing starts at 1. Defaults to None.
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet".
layer_name (str, optional): The layer name to use. Defaults to None.
get_center (bool, optional): If True, the center of the layer will be returned. Defaults to False.
get_bounds (bool, optional): If True, the bounds [minx, miny, maxx, maxy] of the layer will be returned. Defaults to False.
Returns:
ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer.
"""
check_package(
"localtileserver", URL="https://github.com/banesullivan/localtileserver"
)
from localtileserver import (
get_leaflet_tile_layer,
get_folium_tile_layer,
TileClient,
)
if isinstance(source, str):
if not source.startswith("http"):
source = os.path.abspath(source)
if not os.path.exists(source):
raise ValueError("The source path does not exist.")
else:
raise ValueError("The source must either be a string or TileClient")
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
if layer_name is None:
if source.startswith("http"):
layer_name = "RemoteTile_" + random_string(3)
else:
layer_name = "LocalTile_" + random_string(3)
tile_client = TileClient(source, port=port, debug=debug)
if tile_format == "ipyleaflet":
tile_layer = get_leaflet_tile_layer(
tile_client,
port=port,
debug=debug,
projection=projection,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
name=layer_name,
**kwargs,
)
else:
tile_layer = get_folium_tile_layer(
tile_client,
port=port,
debug=debug,
projection=projection,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attr=attribution,
overlay=True,
name=layer_name,
**kwargs,
)
center = tile_client.center()
bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax]
bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy]
if get_center and get_bounds:
return tile_layer, center, bounds
elif get_center:
return tile_layer, center
elif get_bounds:
return tile_layer, bounds
else:
return tile_layer
def get_palettable(types=None):
"""Get a list of palettable color palettes.
Args:
types (list, optional): A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None.
Returns:
list: A list of palettable color palettes.
"""
import palettable
if types is not None and (not isinstance(types, list)):
raise ValueError("The types must be a list.")
allowed_palettes = [
"cartocolors",
"cmocean",
"colorbrewer",
"cubehelix",
"lightbartlein",
"matplotlib",
"mycarta",
"scientific",
"tableau",
"wesanderson",
]
if types is None:
types = allowed_palettes[:]
if all(x in allowed_palettes for x in types):
pass
else:
raise ValueError(
"The types must be one of the following: " + ", ".join(allowed_palettes)
)
palettes = []
if "cartocolors" in types:
cartocolors_diverging = [
f"cartocolors.diverging.{c}"
for c in dir(palettable.cartocolors.diverging)[:-19]
]
cartocolors_qualitative = [
f"cartocolors.qualitative.{c}"
for c in dir(palettable.cartocolors.qualitative)[:-19]
]
cartocolors_sequential = [
f"cartocolors.sequential.{c}"
for c in dir(palettable.cartocolors.sequential)[:-41]
]
palettes = (
palettes
+ cartocolors_diverging
+ cartocolors_qualitative
+ cartocolors_sequential
)
if "cmocean" in types:
cmocean_diverging = [
f"cmocean.diverging.{c}" for c in dir(palettable.cmocean.diverging)[:-19]
]
cmocean_sequential = [
f"cmocean.sequential.{c}" for c in dir(palettable.cmocean.sequential)[:-19]
]
palettes = palettes + cmocean_diverging + cmocean_sequential
if "colorbrewer" in types:
colorbrewer_diverging = [
f"colorbrewer.diverging.{c}"
for c in dir(palettable.colorbrewer.diverging)[:-19]
]
colorbrewer_qualitative = [
f"colorbrewer.qualitative.{c}"
for c in dir(palettable.colorbrewer.qualitative)[:-19]
]
colorbrewer_sequential = [
f"colorbrewer.sequential.{c}"
for c in dir(palettable.colorbrewer.sequential)[:-41]
]
palettes = (
palettes
+ colorbrewer_diverging
+ colorbrewer_qualitative
+ colorbrewer_sequential
)
if "cubehelix" in types:
cubehelix = [
"classic_16",
"cubehelix1_16",
"cubehelix2_16",
"cubehelix3_16",
"jim_special_16",
"perceptual_rainbow_16",
"purple_16",
"red_16",
]
cubehelix = [f"cubehelix.{c}" for c in cubehelix]
palettes = palettes + cubehelix
if "lightbartlein" in types:
lightbartlein_diverging = [
f"lightbartlein.diverging.{c}"
for c in dir(palettable.lightbartlein.diverging)[:-19]
]
lightbartlein_sequential = [
f"lightbartlein.sequential.{c}"
for c in dir(palettable.lightbartlein.sequential)[:-19]
]
palettes = palettes + lightbartlein_diverging + lightbartlein_sequential
if "matplotlib" in types:
matplotlib_colors = [
f"matplotlib.{c}" for c in dir(palettable.matplotlib)[:-16]
]
palettes = palettes + matplotlib_colors
if "mycarta" in types:
mycarta = [f"mycarta.{c}" for c in dir(palettable.mycarta)[:-16]]
palettes = palettes + mycarta
if "scientific" in types:
scientific_diverging = [
f"scientific.diverging.{c}"
for c in dir(palettable.scientific.diverging)[:-19]
]
scientific_sequential = [
f"scientific.sequential.{c}"
for c in dir(palettable.scientific.sequential)[:-19]
]
palettes = palettes + scientific_diverging + scientific_sequential
if "tableau" in types:
tableau = [f"tableau.{c}" for c in dir(palettable.tableau)[:-14]]
palettes = palettes + tableau
return palettes
def points_from_xy(data, x="longitude", y="latitude", z=None, crs=None, **kwargs):
"""Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values.
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
z (str, optional): The column name for the z values. Defaults to None.
crs (str | int, optional): The coordinate reference system for the GeoDataFrame. Defaults to None.
Returns:
geopandas.GeoDataFrame: A GeoPandas GeoDataFrame containing x, y, z values.
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
import pandas as pd
if crs is None:
crs = "epsg:4326"
if isinstance(data, pd.DataFrame):
df = data
elif isinstance(data, str):
if not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data, **kwargs)
else:
raise TypeError("The data must be a pandas DataFrame or a csv file path.")
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[x], df[y], z=z, crs=crs))
return gdf
def html_to_streamlit(
html,
width=800,
height=600,
responsive=True,
scrolling=False,
token_name=None,
token_value=None,
**kwargs,
):
"""Renders an HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.
Args:
html (str): The HTML file to render. It can a local file path or a URL.
width (int, optional): Width of the map. Defaults to 800.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False.
token_name (str, optional): The name of the token in the HTML file to be replaced. Defaults to None.
token_value (str, optional): The value of the token to pass to the HTML file. Defaults to None.
Returns:
streamlit.components: components.html object.
"""
try:
import streamlit as st
import streamlit.components.v1 as components
if isinstance(html, str):
temp_path = None
if html.startswith("http") and html.endswith(".html"):
temp_path = temp_file_path(".html")
out_file = os.path.basename(temp_path)
out_dir = os.path.dirname(temp_path)
download_from_url(html, out_file, out_dir)
html = temp_path
elif not os.path.exists(html):
raise FileNotFoundError("The specified input html does not exist.")
with open(html) as f:
lines = f.readlines()
if (token_name is not None) and (token_value is not None):
lines = [line.replace(token_name, token_value) for line in lines]
html_str = "".join(lines)
if temp_path is not None:
os.remove(temp_path)
if responsive:
make_map_responsive = """
<style>
[title~="st.iframe"] { width: 100%}
</style>
"""
st.markdown(make_map_responsive, unsafe_allow_html=True)
return components.html(
html_str, width=width, height=height, scrolling=scrolling
)
else:
raise TypeError("The html must be a string.")
except Exception as e:
raise Exception(e)
def cesium_to_streamlit(
html,
width=800,
height=600,
responsive=True,
scrolling=False,
token_name=None,
token_value=None,
**kwargs,
):
"""Renders an cesium HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.
Args:
html (str): The HTML file to render. It can a local file path or a URL.
width (int, optional): Width of the map. Defaults to 800.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False.
token_name (str, optional): The name of the token in the HTML file to be replaced. Defaults to None.
token_value (str, optional): The value of the token to pass to the HTML file. Defaults to None.
Returns:
streamlit.components: components.html object.
"""
if token_name is None:
token_name = "your_access_token"
if token_value is None:
token_value = os.environ.get("CESIUM_TOKEN")
html_to_streamlit(
html, width, height, responsive, scrolling, token_name, token_value
)
def geom_type(in_geojson, encoding="utf-8"):
"""Returns the geometry type of a GeoJSON object.
Args:
in_geojson (dict): A GeoJSON object.
encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8".
Returns:
str: The geometry type of the GeoJSON object.
"""
import json
try:
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
data = requests.get(in_geojson).json()
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError(
"The provided GeoJSON file could not be found."
)
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
else:
raise TypeError("The input geojson must be a type of str or dict.")
return data["features"][0]["geometry"]["type"]
except Exception as e:
raise Exception(e)
def geojson_to_df(in_geojson, encoding="utf-8"):
"""Converts a GeoJSON object to a pandas DataFrame.
Args:
in_geojson (str | dict): The input GeoJSON file or dict.
encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8".
Raises:
FileNotFoundError: If the input GeoJSON file could not be found.
Returns:
pd.DataFrame: A pandas DataFrame containing the GeoJSON object.
"""
import json
import pandas as pd
from urllib.request import urlopen
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
with urlopen(in_geojson) as f:
data = json.load(f)
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError("The provided GeoJSON file could not be found.")
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
df = pd.json_normalize(data["features"])
df.columns = [col.replace("properties.", "") for col in df.columns]
return df
def bbox_to_gdf(bbox, crs="EPSG:4326"):
"""Converts a bounding box to a GeoDataFrame.
Args:
bbox (tuple): A bounding box in the form of a tuple (minx, miny, maxx, maxy).
crs (str, optional): The coordinate reference system of the bounding box to convert to. Defaults to "EPSG:4326".
Returns:
geopandas.GeoDataFrame: A GeoDataFrame containing the bounding box.
"""
check_package(name="geopandas", URL="https://geopandas.org")
from shapely.geometry import box
from geopandas import GeoDataFrame
minx, miny, maxx, maxy = bbox
geometry = box(minx, miny, maxx, maxy)
d = {"geometry": [geometry]}
gdf = GeoDataFrame(d, crs="EPSG:4326")
gdf.to_crs(crs=crs, inplace=True)
return gdf
| """This module contains some common functions for both folium and ipyleaflet.
"""
import csv
import os
import requests
import shutil
import tarfile
import urllib.request
import zipfile
import folium
import ipyleaflet
import ipywidgets as widgets
import whitebox
from IPython.display import display, IFrame
class TitilerEndpoint:
"""This class contains the methods for the titiler endpoint."""
def __init__(
self,
endpoint="https://titiler.xyz",
name="stac",
TileMatrixSetId="WebMercatorQuad",
):
"""Initialize the TitilerEndpoint object.
Args:
endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://titiler.xyz".
name (str, optional): The name to be used in the file path. Defaults to "stac".
TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
"""
self.endpoint = endpoint
self.name = name
self.TileMatrixSetId = TileMatrixSetId
def url_for_stac_item(self):
return f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/tilejson.json"
def url_for_stac_assets(self):
return f"{self.endpoint}/{self.name}/assets"
def url_for_stac_bounds(self):
return f"{self.endpoint}/{self.name}/bounds"
def url_for_stac_info(self):
return f"{self.endpoint}/{self.name}/info"
def url_for_stac_info_geojson(self):
return f"{self.endpoint}/{self.name}/info.geojson"
def url_for_stac_statistics(self):
return f"{self.endpoint}/{self.name}/statistics"
def url_for_stac_pixel_value(self, lon, lat):
return f"{self.endpoint}/{self.name}/point/{lon},{lat}"
def url_for_stac_wmts(self):
return (
f"{self.endpoint}/{self.name}/{self.TileMatrixSetId}/WMTSCapabilities.xml"
)
class PlanetaryComputerEndpoint(TitilerEndpoint):
"""This class contains the methods for the Microsoft Planetary Computer endpoint."""
def __init__(
self,
endpoint="https://planetarycomputer.microsoft.com/api/data/v1",
name="item",
TileMatrixSetId="WebMercatorQuad",
):
"""Initialize the PlanetaryComputerEndpoint object.
Args:
endpoint (str, optional): The endpoint of the titiler server. Defaults to "https://planetarycomputer.microsoft.com/api/data/v1".
name (str, optional): The name to be used in the file path. Defaults to "item".
TileMatrixSetId (str, optional): The TileMatrixSetId to be used in the file path. Defaults to "WebMercatorQuad".
"""
super().__init__(endpoint, name, TileMatrixSetId)
def url_for_stac_collection(self):
return f"{self.endpoint}/collection/{self.TileMatrixSetId}/tilejson.json"
def url_for_collection_assets(self):
return f"{self.endpoint}/collection/assets"
def url_for_collection_bounds(self):
return f"{self.endpoint}/collection/bounds"
def url_for_collection_info(self):
return f"{self.endpoint}/collection/info"
def url_for_collection_info_geojson(self):
return f"{self.endpoint}/collection/info.geojson"
def url_for_collection_pixel_value(self, lon, lat):
return f"{self.endpoint}/collection/point/{lon},{lat}"
def url_for_collection_wmts(self):
return f"{self.endpoint}/collection/{self.TileMatrixSetId}/WMTSCapabilities.xml"
def url_for_collection_lat_lon_assets(self, lng, lat):
return f"{self.endpoint}/collection/{lng},{lat}/assets"
def url_for_collection_bbox_assets(self, minx, miny, maxx, maxy):
return f"{self.endpoint}/collection/{minx},{miny},{maxx},{maxy}/assets"
def url_for_stac_mosaic(self, searchid):
return f"{self.endpoint}/mosaic/{searchid}/{self.TileMatrixSetId}/tilejson.json"
def url_for_mosaic_info(self, searchid):
return f"{self.endpoint}/mosaic/{searchid}/info"
def url_for_mosaic_lat_lon_assets(self, searchid, lon, lat):
return f"{self.endpoint}/mosaic/{searchid}/{lon},{lat}/assets"
def check_titiler_endpoint(titiler_endpoint=None):
"""Returns the default titiler endpoint.
Returns:
object: A titiler endpoint.
"""
if titiler_endpoint is None:
if os.environ.get("TITILER_ENDPOINT") == "planetary-computer":
titiler_endpoint = PlanetaryComputerEndpoint()
else:
titiler_endpoint = TitilerEndpoint()
elif titiler_endpoint in ["planetary-computer", "pc"]:
titiler_endpoint = PlanetaryComputerEndpoint()
return titiler_endpoint
class WhiteboxTools(whitebox.WhiteboxTools):
"""This class inherits the whitebox WhiteboxTools class."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def whiteboxgui(verbose=True, tree=False, reset=False, sandbox_path=None):
"""Shows the WhiteboxTools GUI.
Args:
verbose (bool, optional): Whether to show progress info when the tool is running. Defaults to True.
tree (bool, optional): Whether to use the tree mode toolbox built using ipytree rather than ipywidgets. Defaults to False.
reset (bool, optional): Whether to regenerate the json file with the dictionary containing the information for all tools. Defaults to False.
sandbox_path (str, optional): The path to the sandbox folder. Defaults to None.
Returns:
object: A toolbox GUI.
"""
import whiteboxgui
return whiteboxgui.show(verbose, tree, reset, sandbox_path)
def _in_colab_shell():
"""Tests if the code is being executed within Google Colab."""
import sys
if "google.colab" in sys.modules:
return True
else:
return False
def _is_drive_mounted():
"""Checks whether Google Drive is mounted in Google Colab.
Returns:
bool: Returns True if Google Drive is mounted, False otherwise.
"""
drive_path = "/content/drive/My Drive"
if os.path.exists(drive_path):
return True
else:
return False
def set_proxy(port=1080, ip="http://127.0.0.1"):
"""Sets proxy if needed. This is only needed for countries where Google services are not available.
Args:
port (int, optional): The proxy port number. Defaults to 1080.
ip (str, optional): The IP address. Defaults to 'http://127.0.0.1'.
"""
try:
if not ip.startswith("http"):
ip = "http://" + ip
proxy = "{}:{}".format(ip, port)
os.environ["HTTP_PROXY"] = proxy
os.environ["HTTPS_PROXY"] = proxy
a = requests.get("https://google.com")
if a.status_code != 200:
print(
"Failed to connect to Google services. Please double check the port number and ip address."
)
except Exception as e:
raise Exception(e)
def _check_install(package):
"""Checks whether a package is installed. If not, it will install the package.
Args:
package (str): The name of the package to check.
"""
import subprocess
try:
__import__(package)
# print('{} is already installed.'.format(package))
except ImportError:
print("{} is not installed. Installing ...".format(package))
try:
subprocess.check_call(["python", "-m", "pip", "install", package])
except Exception as e:
print("Failed to install {}".format(package))
print(e)
print("{} has been installed successfully.".format(package))
def update_package():
"""Updates the leafmap package from the leafmap GitHub repository without the need to use pip or conda.
In this way, I don't have to keep updating pypi and conda-forge with every minor update of the package.
"""
try:
download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
if not os.path.exists(download_dir):
os.makedirs(download_dir)
_clone_repo(out_dir=download_dir)
pkg_dir = os.path.join(download_dir, "leafmap-master")
work_dir = os.getcwd()
os.chdir(pkg_dir)
if shutil.which("pip") is None:
cmd = "pip3 install ."
else:
cmd = "pip install ."
os.system(cmd)
os.chdir(work_dir)
print(
"\nPlease comment out 'leafmap.update_package()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output"
)
except Exception as e:
raise Exception(e)
def check_package(name, URL=""):
try:
__import__(name.lower())
except Exception:
raise ImportError(
f"{name} is not installed. Please install it before proceeding. {URL}"
)
def _clone_repo(out_dir=".", unzip=True):
"""Clones the leafmap GitHub repository.
Args:
out_dir (str, optional): Output folder for the repo. Defaults to '.'.
unzip (bool, optional): Whether to unzip the repository. Defaults to True.
"""
url = "https://github.com/giswqs/leafmap/archive/master.zip"
filename = "leafmap-master.zip"
download_from_url(url, out_file_name=filename, out_dir=out_dir, unzip=unzip)
def __install_from_github(url):
"""Install a package from a GitHub repository.
Args:
url (str): The URL of the GitHub repository.
"""
try:
download_dir = os.path.join(os.path.expanduser("~"), "Downloads")
if not os.path.exists(download_dir):
os.makedirs(download_dir)
repo_name = os.path.basename(url)
zip_url = os.path.join(url, "archive/master.zip")
filename = repo_name + "-master.zip"
download_from_url(
url=zip_url, out_file_name=filename, out_dir=download_dir, unzip=True
)
pkg_dir = os.path.join(download_dir, repo_name + "-master")
pkg_name = os.path.basename(url)
work_dir = os.getcwd()
os.chdir(pkg_dir)
print("Installing {}...".format(pkg_name))
cmd = "pip install ."
os.system(cmd)
os.chdir(work_dir)
print("{} has been installed successfully.".format(pkg_name))
# print("\nPlease comment out 'install_from_github()' and restart the kernel to take effect:\nJupyter menu -> Kernel -> Restart & Clear Output")
except Exception as e:
raise Exception(e)
def _check_git_install():
"""Checks if Git is installed.
Returns:
bool: Returns True if Git is installed, otherwise returns False.
"""
import webbrowser
cmd = "git --version"
output = os.popen(cmd).read()
if "git version" in output:
return True
else:
url = "https://git-scm.com/downloads"
print(
"Git is not installed. Please download Git from {} and install it.".format(
url
)
)
webbrowser.open_new_tab(url)
return False
def _clone_github_repo(url, out_dir):
"""Clones a GitHub repository.
Args:
url (str): The link to the GitHub repository
out_dir (str): The output directory for the cloned repository.
"""
repo_name = os.path.basename(url)
# url_zip = os.path.join(url, 'archive/master.zip')
url_zip = url + "/archive/master.zip"
if os.path.exists(out_dir):
print(
"The specified output directory already exists. Please choose a new directory."
)
return
parent_dir = os.path.dirname(out_dir)
out_file_path = os.path.join(parent_dir, repo_name + ".zip")
try:
urllib.request.urlretrieve(url_zip, out_file_path)
except Exception:
print("The provided URL is invalid. Please double check the URL.")
return
with zipfile.ZipFile(out_file_path, "r") as zip_ref:
zip_ref.extractall(parent_dir)
src = out_file_path.replace(".zip", "-master")
os.rename(src, out_dir)
os.remove(out_file_path)
def _is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
return shutil.which(name) is not None
def random_string(string_length=3):
"""Generates a random string of fixed length.
Args:
string_length (int, optional): Fixed length. Defaults to 3.
Returns:
str: A random string
"""
import random
import string
# random.seed(1001)
letters = string.ascii_lowercase
return "".join(random.choice(letters) for i in range(string_length))
def open_image_from_url(url):
"""Loads an image from the specified URL.
Args:
url (str): URL of the image.
Returns:
object: Image object.
"""
from PIL import Image
from io import BytesIO
# from urllib.parse import urlparse
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
return img
except Exception as e:
print(e)
def show_image(img_path, width=None, height=None):
"""Shows an image within Jupyter notebook.
Args:
img_path (str): The image file path.
width (int, optional): Width of the image in pixels. Defaults to None.
height (int, optional): Height of the image in pixels. Defaults to None.
"""
from IPython.display import display
try:
out = widgets.Output()
# layout={'border': '1px solid black'})
# layout={'border': '1px solid black', 'width': str(width + 20) + 'px', 'height': str(height + 10) + 'px'},)
out.clear_output(wait=True)
display(out)
with out:
file = open(img_path, "rb")
image = file.read()
if (width is None) and (height is None):
display(widgets.Image(value=image))
elif (width is not None) and (height is not None):
display(widgets.Image(value=image, width=width, height=height))
else:
print("You need set both width and height.")
return
except Exception as e:
raise Exception(e)
def has_transparency(img):
"""Checks whether an image has transparency.
Args:
img (object): a PIL Image object.
Returns:
bool: True if it has transparency, False otherwise.
"""
if img.mode == "P":
transparent = img.info.get("transparency", -1)
for _, index in img.getcolors():
if index == transparent:
return True
elif img.mode == "RGBA":
extrema = img.getextrema()
if extrema[3][0] < 255:
return True
return False
def upload_to_imgur(in_gif):
"""Uploads an image to imgur.com
Args:
in_gif (str): The file path to the image.
"""
import subprocess
pkg_name = "imgur-uploader"
if not _is_tool(pkg_name):
_check_install(pkg_name)
try:
IMGUR_API_ID = os.environ.get("IMGUR_API_ID", None)
IMGUR_API_SECRET = os.environ.get("IMGUR_API_SECRET", None)
credentials_path = os.path.join(
os.path.expanduser("~"), ".config/imgur_uploader/uploader.cfg"
)
if (
(IMGUR_API_ID is not None) and (IMGUR_API_SECRET is not None)
) or os.path.exists(credentials_path):
proc = subprocess.Popen(["imgur-uploader", in_gif], stdout=subprocess.PIPE)
for _ in range(0, 2):
line = proc.stdout.readline()
print(line.rstrip().decode("utf-8"))
# while True:
# line = proc.stdout.readline()
# if not line:
# break
# print(line.rstrip().decode("utf-8"))
else:
print(
"Imgur API credentials could not be found. Please check https://pypi.org/project/imgur-uploader/ for instructions on how to get Imgur API credentials"
)
return
except Exception as e:
raise Exception(e)
def rgb_to_hex(rgb=(255, 255, 255)):
"""Converts RGB to hex color. In RGB color R stands for Red, G stands for Green, and B stands for Blue, and it ranges from the decimal value of 0 – 255.
Args:
rgb (tuple, optional): RGB color code as a tuple of (red, green, blue). Defaults to (255, 255, 255).
Returns:
str: hex color code
"""
return "%02x%02x%02x" % rgb
def hex_to_rgb(value="FFFFFF"):
"""Converts hex color to RGB color.
Args:
value (str, optional): Hex color code as a string. Defaults to 'FFFFFF'.
Returns:
tuple: RGB color as a tuple.
"""
value = value.lstrip("#")
lv = len(value)
return tuple(int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3))
def check_color(in_color):
"""Checks the input color and returns the corresponding hex color code.
Args:
in_color (str or tuple): It can be a string (e.g., 'red', '#ffff00') or tuple (e.g., (255, 127, 0)).
Returns:
str: A hex color code.
"""
import colour
out_color = "#000000" # default black color
if isinstance(in_color, tuple) and len(in_color) == 3:
if all(isinstance(item, int) for item in in_color):
rescaled_color = [x / 255.0 for x in in_color]
out_color = colour.Color(rgb=tuple(rescaled_color))
return out_color.hex_l
else:
print(
"RGB color must be a tuple with three integer values ranging from 0 to 255."
)
return
else:
try:
out_color = colour.Color(in_color)
return out_color.hex_l
except Exception as e:
print("The provided color is invalid. Using the default black color.")
print(e)
return out_color
def system_fonts(show_full_path=False):
"""Gets a list of system fonts
# Common font locations:
# Linux: /usr/share/fonts/TTF/
# Windows: C:/Windows/Fonts
# macOS: System > Library > Fonts
Args:
show_full_path (bool, optional): Whether to show the full path of each system font. Defaults to False.
Returns:
list: A list of system fonts.
"""
try:
import matplotlib.font_manager
font_list = matplotlib.font_manager.findSystemFonts(
fontpaths=None, fontext="ttf"
)
font_list.sort()
font_names = [os.path.basename(f) for f in font_list]
font_names.sort()
if show_full_path:
return font_list
else:
return font_names
except Exception as e:
raise Exception(e)
def download_from_url(url, out_file_name=None, out_dir=".", unzip=True, verbose=True):
"""Download a file from a URL (e.g., https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip)
Args:
url (str): The HTTP URL to download.
out_file_name (str, optional): The output file name to use. Defaults to None.
out_dir (str, optional): The output directory to use. Defaults to '.'.
unzip (bool, optional): Whether to unzip the downloaded file if it is a zip file. Defaults to True.
verbose (bool, optional): Whether to display or not the output of the function
"""
in_file_name = os.path.basename(url)
if out_file_name is None:
out_file_name = in_file_name
out_file_path = os.path.join(os.path.abspath(out_dir), out_file_name)
if verbose:
print("Downloading {} ...".format(url))
try:
urllib.request.urlretrieve(url, out_file_path)
except Exception:
raise Exception("The URL is invalid. Please double check the URL.")
final_path = out_file_path
if unzip:
# if it is a zip file
if ".zip" in out_file_name:
if verbose:
print("Unzipping {} ...".format(out_file_name))
with zipfile.ZipFile(out_file_path, "r") as zip_ref:
zip_ref.extractall(out_dir)
final_path = os.path.join(
os.path.abspath(out_dir), out_file_name.replace(".zip", "")
)
# if it is a tar file
if ".tar" in out_file_name:
if verbose:
print("Unzipping {} ...".format(out_file_name))
with tarfile.open(out_file_path, "r") as tar_ref:
tar_ref.extractall(out_dir)
final_path = os.path.join(
os.path.abspath(out_dir), out_file_name.replace(".tart", "")
)
if verbose:
print("Data downloaded to: {}".format(final_path))
def download_from_gdrive(gfile_url, file_name, out_dir=".", unzip=True, verbose=True):
"""Download a file shared via Google Drive
(e.g., https://drive.google.com/file/d/18SUo_HcDGltuWYZs1s7PpOmOq_FvFn04/view?usp=sharing)
Args:
gfile_url (str): The Google Drive shared file URL
file_name (str): The output file name to use.
out_dir (str, optional): The output directory. Defaults to '.'.
unzip (bool, optional): Whether to unzip the output file if it is a zip file. Defaults to True.
verbose (bool, optional): Whether to display or not the output of the function
"""
from google_drive_downloader import GoogleDriveDownloader as gdd
file_id = gfile_url.split("/")[5]
if verbose:
print("Google Drive file id: {}".format(file_id))
dest_path = os.path.join(out_dir, file_name)
gdd.download_file_from_google_drive(file_id, dest_path, True, unzip)
def create_download_link(filename, title="Click here to download: "):
"""Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578
Args:
filename (str): The file path to the file to download
title (str, optional): str. Defaults to "Click here to download: ".
Returns:
str: HTML download URL.
"""
import base64
from IPython.display import HTML
data = open(filename, "rb").read()
b64 = base64.b64encode(data)
payload = b64.decode()
basename = os.path.basename(filename)
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" style="color:#0000FF;" target="_blank">{title}</a>'
html = html.format(payload=payload, title=title + f" {basename}", filename=basename)
return HTML(html)
def edit_download_html(htmlWidget, filename, title="Click here to download: "):
"""Downloads a file from voila. Adopted from https://github.com/voila-dashboards/voila/issues/578#issuecomment-617668058
Args:
htmlWidget (object): The HTML widget to display the URL.
filename (str): File path to download.
title (str, optional): Download description. Defaults to "Click here to download: ".
"""
# from IPython.display import HTML
# import ipywidgets as widgets
import base64
# Change widget html temporarily to a font-awesome spinner
htmlWidget.value = '<i class="fa fa-spinner fa-spin fa-2x fa-fw"></i><span class="sr-only">Loading...</span>'
# Process raw data
data = open(filename, "rb").read()
b64 = base64.b64encode(data)
payload = b64.decode()
basename = os.path.basename(filename)
# Create and assign html to widget
html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>'
htmlWidget.value = html.format(
payload=payload, title=title + basename, filename=basename
)
def csv_points_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
"""Converts a csv file containing points (latitude, longitude) into a shapefile.
Args:
in_csv (str): File path or HTTP URL to the input csv file. For example, https://raw.githubusercontent.com/giswqs/data/main/world/world_cities.csv
out_shp (str): File path to the output shapefile.
latitude (str, optional): Column name for the latitude column. Defaults to 'latitude'.
longitude (str, optional): Column name for the longitude column. Defaults to 'longitude'.
"""
if in_csv.startswith("http") and in_csv.endswith(".csv"):
out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
out_name = os.path.basename(in_csv)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
download_from_url(in_csv, out_dir=out_dir)
in_csv = os.path.join(out_dir, out_name)
wbt = whitebox.WhiteboxTools()
in_csv = os.path.abspath(in_csv)
out_shp = os.path.abspath(out_shp)
if not os.path.exists(in_csv):
raise Exception("The provided csv file does not exist.")
with open(in_csv, encoding="utf-8") as csv_file:
reader = csv.DictReader(csv_file)
fields = reader.fieldnames
xfield = fields.index(longitude)
yfield = fields.index(latitude)
wbt.csv_points_to_vector(in_csv, out_shp, xfield=xfield, yfield=yfield, epsg=4326)
def csv_to_shp(in_csv, out_shp, latitude="latitude", longitude="longitude"):
"""Converts a csv file with latlon info to a point shapefile.
Args:
in_csv (str): The input csv file containing longitude and latitude columns.
out_shp (str): The file path to the output shapefile.
latitude (str, optional): The column name of the latitude column. Defaults to 'latitude'.
longitude (str, optional): The column name of the longitude column. Defaults to 'longitude'.
"""
import shapefile as shp
if in_csv.startswith("http") and in_csv.endswith(".csv"):
out_dir = os.path.join(os.path.expanduser("~"), "Downloads")
out_name = os.path.basename(in_csv)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
download_from_url(in_csv, out_dir=out_dir)
in_csv = os.path.join(out_dir, out_name)
out_dir = os.path.dirname(out_shp)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
try:
points = shp.Writer(out_shp, shapeType=shp.POINT)
with open(in_csv, encoding="utf-8") as csvfile:
csvreader = csv.DictReader(csvfile)
header = csvreader.fieldnames
[points.field(field) for field in header]
for row in csvreader:
points.point((float(row[longitude])), (float(row[latitude])))
points.record(*tuple([row[f] for f in header]))
out_prj = out_shp.replace(".shp", ".prj")
with open(out_prj, "w") as f:
prj_str = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]] '
f.write(prj_str)
except Exception as e:
raise Exception(e)
def pandas_to_geojson(
df,
out_geojson=None,
latitude="latitude",
longitude="longitude",
encoding="utf-8",
):
"""Creates points for a Pandas DataFrame and exports data as a GeoJSON.
Args:
df (pandas.DataFrame): The input Pandas DataFrame.
out_geojson (str): The file path to the exported GeoJSON. Default to None.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
"""
import json
from geojson import Feature, FeatureCollection, Point
if out_geojson is not None:
out_dir = os.path.dirname(os.path.abspath(out_geojson))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
features = df.apply(
lambda row: Feature(
geometry=Point((float(row[longitude]), float(row[latitude]))),
properties=dict(row),
),
axis=1,
).tolist()
geojson = FeatureCollection(features=features)
if out_geojson is None:
return geojson
else:
with open(out_geojson, "w", encoding=encoding) as f:
f.write(json.dumps(geojson))
def csv_to_geojson(
in_csv,
out_geojson=None,
latitude="latitude",
longitude="longitude",
encoding="utf-8",
):
"""Creates points for a CSV file and exports data as a GeoJSON.
Args:
in_csv (str): The file path to the input CSV file.
out_geojson (str): The file path to the exported GeoJSON. Default to None.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
"""
import json
import pandas as pd
if out_geojson is not None:
out_dir = os.path.dirname(os.path.abspath(out_geojson))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
df = pd.read_csv(in_csv)
geojson = pandas_to_geojson(
df, latitude=latitude, longitude=longitude, encoding=encoding
)
if out_geojson is None:
return geojson
else:
with open(out_geojson, "w", encoding=encoding) as f:
f.write(json.dumps(geojson))
def csv_to_gdf(in_csv, latitude="latitude", longitude="longitude", encoding="utf-8"):
"""Creates points for a CSV file and converts them to a GeoDataFrame.
Args:
in_csv (str): The file path to the input CSV file.
latitude (str, optional): The name of the column containing latitude coordinates. Defaults to "latitude".
longitude (str, optional): The name of the column containing longitude coordinates. Defaults to "longitude".
encoding (str, optional): The encoding of characters. Defaults to "utf-8".
Returns:
object: GeoDataFrame.
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
out_dir = os.getcwd()
out_geojson = os.path.join(out_dir, random_string() + ".geojson")
csv_to_geojson(in_csv, out_geojson, latitude, longitude, encoding)
gdf = gpd.read_file(out_geojson)
os.remove(out_geojson)
return gdf
def create_code_cell(code="", where="below"):
"""Creates a code cell in the IPython Notebook.
Args:
code (str, optional): Code to fill the new code cell with. Defaults to ''.
where (str, optional): Where to add the new code cell. It can be one of the following: above, below, at_bottom. Defaults to 'below'.
"""
import base64
from IPython.display import Javascript, display
encoded_code = (base64.b64encode(str.encode(code))).decode()
display(
Javascript(
"""
var code = IPython.notebook.insert_cell_{0}('code');
code.set_text(atob("{1}"));
""".format(
where, encoded_code
)
)
)
def cog_tile(url, titiler_endpoint="https://titiler.xyz", **kwargs):
"""Get a tile layer from a Cloud Optimized GeoTIFF (COG).
Source code adapted from https://developmentseed.org/titiler/examples/notebooks/Working_with_CloudOptimizedGeoTIFF_simple/
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
tuple: Returns the COG Tile layer URL and bounds.
"""
kwargs["url"] = url
TileMatrixSetId = "WebMercatorQuad"
if "TileMatrixSetId" in kwargs.keys():
TileMatrixSetId = kwargs["TileMatrixSetId"]
kwargs.pop("TileMatrixSetId")
r = requests.get(
f"{titiler_endpoint}/cog/{TileMatrixSetId}/tilejson.json", params=kwargs
).json()
return r["tiles"][0]
def cog_mosaic(
links,
titiler_endpoint="https://titiler.xyz",
username="anonymous",
layername=None,
overwrite=False,
verbose=True,
**kwargs,
):
"""Creates a COG mosaic from a list of COG URLs.
Args:
links (list): A list containing COG HTTP URLs.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
layername ([type], optional): Layer name to use. Defaults to None.
overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
verbose (bool, optional): Whether to print out descriptive information. Defaults to True.
Raises:
Exception: If the COG mosaic fails to create.
Returns:
str: The tile URL for the COG mosaic.
"""
if layername is None:
layername = "layer_" + random_string(5)
try:
if verbose:
print("Creating COG masaic ...")
# Create token
r = requests.post(
f"{titiler_endpoint}/tokens/create",
json={"username": username, "scope": ["mosaic:read", "mosaic:create"]},
).json()
token = r["token"]
# Create mosaic
requests.post(
f"{titiler_endpoint}/mosaicjson/create",
json={
"username": username,
"layername": layername,
"files": links,
# "overwrite": overwrite
},
params={
"access_token": token,
},
).json()
r2 = requests.get(
f"{titiler_endpoint}/mosaicjson/{username}.{layername}/tilejson.json",
).json()
return r2["tiles"][0]
except Exception as e:
raise Exception(e)
def cog_mosaic_from_file(
filepath,
skip_rows=0,
titiler_endpoint="https://titiler.xyz",
username="anonymous",
layername=None,
overwrite=False,
verbose=True,
**kwargs,
):
"""Creates a COG mosaic from a csv/txt file stored locally for through HTTP URL.
Args:
filepath (str): Local path or HTTP URL to the csv/txt file containing COG URLs.
skip_rows (int, optional): The number of rows to skip in the file. Defaults to 0.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
username (str, optional): User name for the titiler endpoint. Defaults to "anonymous".
layername ([type], optional): Layer name to use. Defaults to None.
overwrite (bool, optional): Whether to overwrite the layer name if existing. Defaults to False.
verbose (bool, optional): Whether to print out descriptive information. Defaults to True.
Returns:
str: The tile URL for the COG mosaic.
"""
import urllib
links = []
if filepath.startswith("http"):
data = urllib.request.urlopen(filepath)
for line in data:
links.append(line.decode("utf-8").strip())
else:
with open(filepath) as f:
links = [line.strip() for line in f.readlines()]
links = links[skip_rows:]
# print(links)
mosaic = cog_mosaic(
links, titiler_endpoint, username, layername, overwrite, verbose, **kwargs
)
return mosaic
def cog_bounds(url, titiler_endpoint="https://titiler.xyz"):
"""Get the bounding box of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A list of values representing [left, bottom, right, top]
"""
r = requests.get(f"{titiler_endpoint}/cog/bounds", params={"url": url}).json()
if "bounds" in r.keys():
bounds = r["bounds"]
else:
bounds = None
return bounds
def cog_center(url, titiler_endpoint="https://titiler.xyz"):
"""Get the centroid of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
tuple: A tuple representing (longitude, latitude)
"""
bounds = cog_bounds(url, titiler_endpoint)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lat, lon)
return center
def cog_bands(url, titiler_endpoint="https://titiler.xyz"):
"""Get band names of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A list of band names
"""
r = requests.get(
f"{titiler_endpoint}/cog/info",
params={
"url": url,
},
).json()
bands = [b[0] for b in r["band_descriptions"]]
return bands
def cog_stats(url, titiler_endpoint="https://titiler.xyz"):
"""Get band statistics of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A dictionary of band statistics.
"""
r = requests.get(
f"{titiler_endpoint}/cog/statistics",
params={
"url": url,
},
).json()
return r
def cog_info(url, titiler_endpoint="https://titiler.xyz", return_geojson=False):
"""Get band statistics of a Cloud Optimized GeoTIFF (COG).
Args:
url (str): HTTP URL to a COG, e.g., https://opendata.digitalglobe.com/events/mauritius-oil-spill/post-event/2020-08-12/105001001F1B5B00/105001001F1B5B00.tif
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
Returns:
list: A dictionary of band info.
"""
info = "info"
if return_geojson:
info = "info.geojson"
r = requests.get(
f"{titiler_endpoint}/cog/{info}",
params={
"url": url,
},
).json()
return r
def cog_pixel_value(
lon,
lat,
url,
bidx=None,
titiler_endpoint="https://titiler.xyz",
verbose=True,
**kwargs,
):
"""Get pixel value from COG.
Args:
lon (float): Longitude of the pixel.
lat (float): Latitude of the pixel.
url (str): HTTP URL to a COG, e.g., 'https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif'
bidx (str, optional): Dataset band indexes (e.g bidx=1, bidx=1&bidx=2&bidx=3). Defaults to None.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
verbose (bool, optional): Print status messages. Defaults to True.
Returns:
list: A dictionary of band info.
"""
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
kwargs["url"] = url
if bidx is not None:
kwargs["bidx"] = bidx
r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
bands = cog_bands(url, titiler_endpoint)
# if isinstance(titiler_endpoint, str):
# r = requests.get(f"{titiler_endpoint}/cog/point/{lon},{lat}", params=kwargs).json()
# else:
# r = requests.get(
# titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
# ).json()
if "detail" in r:
if verbose:
print(r["detail"])
return None
else:
values = r["values"]
result = dict(zip(bands, values))
return result
def stac_tile(
url=None,
collection=None,
items=None,
assets=None,
bands=None,
titiler_endpoint=None,
**kwargs,
):
"""Get a tile layer from a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "https://planetarycomputer.microsoft.com/api/data/v1", "planetary-computer", "pc". Defaults to None.
Returns:
str: Returns the STAC Tile layer URL.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, PlanetaryComputerEndpoint):
if isinstance(bands, list):
bands = ",".join(bands)
if isinstance(assets, list):
assets = ",".join(assets)
if assets is None and (bands is not None):
assets = bands
else:
kwargs["bidx"] = bands
kwargs["assets"] = assets
if ("expression" in kwargs) and ("rescale" not in kwargs):
stats = stac_stats(
collection=collection,
items=items,
expression=kwargs["expression"],
titiler_endpoint=titiler_endpoint,
)
kwargs[
"rescale"
] = f"{stats[0]['percentile_2']},{stats[0]['percentile_98']}"
if ("asset_expression" in kwargs) and ("rescale" not in kwargs):
stats = stac_stats(
collection=collection,
items=items,
expression=kwargs["asset_expression"],
titiler_endpoint=titiler_endpoint,
)
kwargs[
"rescale"
] = f"{stats[0]['percentile_2']},{stats[0]['percentile_98']}"
if (
(assets is not None)
and ("asset_expression" not in kwargs)
and ("expression" not in kwargs)
and ("rescale" not in kwargs)
):
stats = stac_stats(
collection=collection,
items=items,
assets=assets,
titiler_endpoint=titiler_endpoint,
)
percentile_2 = min([s["percentile_2"] for s in stats])
percentile_98 = max([s["percentile_98"] for s in stats])
kwargs["rescale"] = f"{percentile_2},{percentile_98}"
else:
if isinstance(bands, str):
bands = bands.split(",")
if isinstance(assets, str):
assets = assets.split(",")
if assets is None and (bands is not None):
assets = bands
else:
kwargs["asset_bidx"] = bands
kwargs["assets"] = assets
TileMatrixSetId = "WebMercatorQuad"
if "TileMatrixSetId" in kwargs.keys():
TileMatrixSetId = kwargs["TileMatrixSetId"]
kwargs.pop("TileMatrixSetId")
if isinstance(titiler_endpoint, str):
r = requests.get(
f"{titiler_endpoint}/stac/{TileMatrixSetId}/tilejson.json",
params=kwargs,
).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_item(), params=kwargs).json()
return r["tiles"][0]
def stac_bounds(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get the bounding box of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of values representing [left, bottom, right, top]
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/bounds", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_bounds(), params=kwargs).json()
bounds = r["bounds"]
return bounds
def stac_center(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get the centroid of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
tuple: A tuple representing (longitude, latitude)
"""
bounds = stac_bounds(url, collection, items, titiler_endpoint, **kwargs)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lon, lat)
return center
def stac_bands(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get band names of a single SpatialTemporal Asset Catalog (STAC) item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of band names
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_assets(), params=kwargs).json()
return r
def stac_stats(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band statistics of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band statistics.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/statistics", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_statistics(), params=kwargs
).json()
return r
def stac_info(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band info of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band info.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/info", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_info(), params=kwargs).json()
return r
def stac_info_geojson(
url=None, collection=None, items=None, assets=None, titiler_endpoint=None, **kwargs
):
"""Get band info of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A dictionary of band info.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is not None:
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/info.geojson", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_info_geojson(), params=kwargs
).json()
return r
def stac_assets(url=None, collection=None, items=None, titiler_endpoint=None, **kwargs):
"""Get all assets of a STAC item.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
Returns:
list: A list of assets.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/assets", params=kwargs).json()
else:
r = requests.get(titiler_endpoint.url_for_stac_assets(), params=kwargs).json()
return r
def stac_pixel_value(
lon,
lat,
url=None,
collection=None,
items=None,
assets=None,
titiler_endpoint=None,
verbose=True,
**kwargs,
):
"""Get pixel value from STAC assets.
Args:
lon (float): Longitude of the pixel.
lat (float): Latitude of the pixel.
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
items (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
verbose (bool, optional): Print out the error message. Defaults to True.
Returns:
list: A dictionary of pixel values for each asset.
"""
if url is None and collection is None:
raise ValueError("Either url or collection must be specified.")
if collection is not None and titiler_endpoint is None:
titiler_endpoint = "planetary-computer"
if url is not None:
kwargs["url"] = url
if collection is not None:
kwargs["collection"] = collection
if items is not None:
kwargs["items"] = items
if assets is None:
assets = stac_assets(
url=url,
collection=collection,
items=items,
titiler_endpoint=titiler_endpoint,
)
assets = ",".join(assets)
kwargs["assets"] = assets
titiler_endpoint = check_titiler_endpoint(titiler_endpoint)
if isinstance(titiler_endpoint, str):
r = requests.get(f"{titiler_endpoint}/stac/{lon},{lat}", params=kwargs).json()
else:
r = requests.get(
titiler_endpoint.url_for_stac_pixel_value(lon, lat), params=kwargs
).json()
if "detail" in r:
if verbose:
print(r["detail"])
return None
else:
values = [v[0] for v in r["values"]]
result = dict(zip(assets.split(","), values))
return result
def bbox_to_geojson(bounds):
"""Convert coordinates of a bounding box to a geojson.
Args:
bounds (list): A list of coordinates representing [left, bottom, right, top].
Returns:
dict: A geojson feature.
"""
return {
"geometry": {
"type": "Polygon",
"coordinates": [
[
[bounds[0], bounds[3]],
[bounds[0], bounds[1]],
[bounds[2], bounds[1]],
[bounds[2], bounds[3]],
[bounds[0], bounds[3]],
]
],
},
"type": "Feature",
}
def coords_to_geojson(coords):
"""Convert a list of bbox coordinates representing [left, bottom, right, top] to geojson FeatureCollection.
Args:
coords (list): A list of bbox coordinates representing [left, bottom, right, top].
Returns:
dict: A geojson FeatureCollection.
"""
features = []
for bbox in coords:
features.append(bbox_to_geojson(bbox))
return {"type": "FeatureCollection", "features": features}
def explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield
coordinate tuples. As long as the input is conforming, the type of
the geometry doesn't matter. From Fiona 1.4.8
Args:
coords (list): A list of coordinates.
Yields:
[type]: [description]
"""
for e in coords:
if isinstance(e, (float, int)):
yield coords
break
else:
for f in explode(e):
yield f
def get_bounds(geometry, north_up=True, transform=None):
"""Bounding box of a GeoJSON geometry, GeometryCollection, or FeatureCollection.
left, bottom, right, top
*not* xmin, ymin, xmax, ymax
If not north_up, y will be switched to guarantee the above.
Source code adapted from https://github.com/mapbox/rasterio/blob/master/rasterio/features.py#L361
Args:
geometry (dict): A GeoJSON dict.
north_up (bool, optional): . Defaults to True.
transform ([type], optional): . Defaults to None.
Returns:
list: A list of coordinates representing [left, bottom, right, top]
"""
if "bbox" in geometry:
return tuple(geometry["bbox"])
geometry = geometry.get("geometry") or geometry
# geometry must be a geometry, GeometryCollection, or FeatureCollection
if not (
"coordinates" in geometry or "geometries" in geometry or "features" in geometry
):
raise ValueError(
"geometry must be a GeoJSON-like geometry, GeometryCollection, "
"or FeatureCollection"
)
if "features" in geometry:
# Input is a FeatureCollection
xmins = []
ymins = []
xmaxs = []
ymaxs = []
for feature in geometry["features"]:
xmin, ymin, xmax, ymax = get_bounds(feature["geometry"])
xmins.append(xmin)
ymins.append(ymin)
xmaxs.append(xmax)
ymaxs.append(ymax)
if north_up:
return min(xmins), min(ymins), max(xmaxs), max(ymaxs)
else:
return min(xmins), max(ymaxs), max(xmaxs), min(ymins)
elif "geometries" in geometry:
# Input is a geometry collection
xmins = []
ymins = []
xmaxs = []
ymaxs = []
for geometry in geometry["geometries"]:
xmin, ymin, xmax, ymax = get_bounds(geometry)
xmins.append(xmin)
ymins.append(ymin)
xmaxs.append(xmax)
ymaxs.append(ymax)
if north_up:
return min(xmins), min(ymins), max(xmaxs), max(ymaxs)
else:
return min(xmins), max(ymaxs), max(xmaxs), min(ymins)
elif "coordinates" in geometry:
# Input is a singular geometry object
if transform is not None:
xyz = list(explode(geometry["coordinates"]))
xyz_px = [transform * point for point in xyz]
xyz = tuple(zip(*xyz_px))
return min(xyz[0]), max(xyz[1]), max(xyz[0]), min(xyz[1])
else:
xyz = tuple(zip(*list(explode(geometry["coordinates"]))))
if north_up:
return min(xyz[0]), min(xyz[1]), max(xyz[0]), max(xyz[1])
else:
return min(xyz[0]), max(xyz[1]), max(xyz[0]), min(xyz[1])
# all valid inputs returned above, so whatever falls through is an error
raise ValueError(
"geometry must be a GeoJSON-like geometry, GeometryCollection, "
"or FeatureCollection"
)
def get_center(geometry, north_up=True, transform=None):
"""Get the centroid of a GeoJSON.
Args:
geometry (dict): A GeoJSON dict.
north_up (bool, optional): . Defaults to True.
transform ([type], optional): . Defaults to None.
Returns:
list: [lon, lat]
"""
bounds = get_bounds(geometry, north_up, transform)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2) # (lat, lon)
return center
def adjust_longitude(in_fc):
"""Adjusts longitude if it is less than -180 or greater than 180.
Args:
in_fc (dict): The input dictionary containing coordinates.
Returns:
dict: A dictionary containing the converted longitudes
"""
try:
keys = in_fc.keys()
if "geometry" in keys:
coordinates = in_fc["geometry"]["coordinates"]
if in_fc["geometry"]["type"] == "Point":
longitude = coordinates[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][0] = longitude
elif in_fc["geometry"]["type"] == "Polygon":
for index1, item in enumerate(coordinates):
for index2, element in enumerate(item):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][index1][index2][0] = longitude
elif in_fc["geometry"]["type"] == "LineString":
for index, element in enumerate(coordinates):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["geometry"]["coordinates"][index][0] = longitude
elif "type" in keys:
coordinates = in_fc["coordinates"]
if in_fc["type"] == "Point":
longitude = coordinates[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][0] = longitude
elif in_fc["type"] == "Polygon":
for index1, item in enumerate(coordinates):
for index2, element in enumerate(item):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][index1][index2][0] = longitude
elif in_fc["type"] == "LineString":
for index, element in enumerate(coordinates):
longitude = element[0]
if longitude < -180:
longitude = 360 + longitude
elif longitude > 180:
longitude = longitude - 360
in_fc["coordinates"][index][0] = longitude
return in_fc
except Exception as e:
print(e)
return None
def is_GCS(in_shp):
import warnings
import pycrs
if not os.path.exists(in_shp):
raise FileNotFoundError("The input shapefile could not be found.")
if not in_shp.endswith(".shp"):
raise TypeError("The input shapefile is invalid.")
in_prj = in_shp.replace(".shp", ".prj")
if not os.path.exists(in_prj):
warnings.warn(
f"The projection file {in_prj} could not be found. Assuming the dataset is in a geographic coordinate system (GCS)."
)
return True
else:
with open(in_prj) as f:
esri_wkt = f.read()
epsg4326 = pycrs.parse.from_epsg_code(4326).to_proj4()
try:
crs = pycrs.parse.from_esri_wkt(esri_wkt).to_proj4()
if crs == epsg4326:
return True
else:
return False
except Exception:
return False
def kml_to_shp(in_kml, out_shp):
"""Converts a KML to shapefile.
Args:
in_kml (str): The file path to the input KML.
out_shp (str): The file path to the output shapefile.
Raises:
FileNotFoundError: The input KML could not be found.
TypeError: The output must be a shapefile.
"""
import warnings
warnings.filterwarnings("ignore")
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The input KML could not be found.")
out_shp = os.path.abspath(out_shp)
if not out_shp.endswith(".shp"):
raise TypeError("The output must be a shapefile.")
out_dir = os.path.dirname(out_shp)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
# import fiona
# print(fiona.supported_drivers)
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
df = gpd.read_file(in_kml, driver="KML")
df.to_file(out_shp)
def kml_to_geojson(in_kml, out_geojson=None):
"""Converts a KML to GeoJSON.
Args:
in_kml (str): The file path to the input KML.
out_geojson (str): The file path to the output GeoJSON. Defaults to None.
Raises:
FileNotFoundError: The input KML could not be found.
TypeError: The output must be a GeoJSON.
"""
import warnings
warnings.filterwarnings("ignore")
in_kml = os.path.abspath(in_kml)
if not os.path.exists(in_kml):
raise FileNotFoundError("The input KML could not be found.")
if out_geojson is not None:
out_geojson = os.path.abspath(out_geojson)
ext = os.path.splitext(out_geojson)[1].lower()
if ext not in [".json", ".geojson"]:
raise TypeError("The output file must be a GeoJSON.")
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
# import fiona
# print(fiona.supported_drivers)
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(in_kml, driver="KML")
if out_geojson is not None:
gdf.to_file(out_geojson, driver="GeoJSON")
else:
return gdf.__geo_interface__
def csv_to_pandas(in_csv, **kwargs):
"""Converts a CSV file to pandas dataframe.
Args:
in_csv (str): File path to the input CSV.
Returns:
pd.DataFrame: pandas DataFrame
"""
import pandas as pd
try:
return pd.read_csv(in_csv, **kwargs)
except Exception as e:
raise Exception(e)
def shp_to_gdf(in_shp):
"""Converts a shapefile to Geopandas dataframe.
Args:
in_shp (str): File path to the input shapefile.
Raises:
FileNotFoundError: The provided shp could not be found.
Returns:
gpd.GeoDataFrame: geopandas.GeoDataFrame
"""
import warnings
warnings.filterwarnings("ignore")
in_shp = os.path.abspath(in_shp)
if not os.path.exists(in_shp):
raise FileNotFoundError("The provided shp could not be found.")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
try:
return gpd.read_file(in_shp)
except Exception as e:
raise Exception(e)
def shp_to_geojson(in_shp, out_json=None, **kwargs):
"""Converts a shapefile to GeoJSON.
Args:
in_shp (str): File path of the input shapefile.
out_json (str, optional): File path of the output GeoJSON. Defaults to None.
Returns:
object: The json object representing the shapefile.
"""
try:
import shapefile
from datetime import date
in_shp = os.path.abspath(in_shp)
if out_json is not None:
ext = os.path.splitext(out_json)[1]
print(ext)
if ext.lower() not in [".json", ".geojson"]:
raise TypeError("The output file extension must the .json or .geojson.")
if not os.path.exists(os.path.dirname(out_json)):
os.makedirs(os.path.dirname(out_json))
if not is_GCS(in_shp):
try:
import geopandas as gpd
except Exception:
raise ImportError(
"Geopandas is required to perform reprojection of the data. See https://geopandas.org/install.html"
)
try:
in_gdf = gpd.read_file(in_shp)
out_gdf = in_gdf.to_crs(epsg="4326")
out_shp = in_shp.replace(".shp", "_gcs.shp")
out_gdf.to_file(out_shp)
in_shp = out_shp
except Exception as e:
raise Exception(e)
if "encoding" in kwargs:
reader = shapefile.Reader(in_shp, encoding=kwargs.pop("encoding"))
else:
reader = shapefile.Reader(in_shp)
out_dict = reader.__geo_interface__
if out_json is not None:
import json
with open(out_json, "w") as geojson:
geojson.write(json.dumps(out_dict, indent=2) + "\n")
else:
return out_dict
except Exception as e:
raise Exception(e)
def delete_shp(in_shp, verbose=False):
"""Deletes a shapefile.
Args:
in_shp (str): The input shapefile to delete.
verbose (bool, optional): Whether to print out descriptive text. Defaults to True.
"""
from pathlib import Path
in_shp = os.path.abspath(in_shp)
in_dir = os.path.dirname(in_shp)
basename = os.path.basename(in_shp).replace(".shp", "")
files = Path(in_dir).rglob(basename + ".*")
for file in files:
filepath = os.path.join(in_dir, str(file))
os.remove(filepath)
if verbose:
print(f"Deleted {filepath}")
def vector_to_geojson(
filename, out_geojson=None, bbox=None, mask=None, rows=None, epsg="4326", **kwargs
):
"""Converts any geopandas-supported vector dataset to GeoJSON.
Args:
filename (str): Either the absolute or relative path to the file or URL to be opened, or any object with a read() method (such as an open file or StringIO).
out_geojson (str, optional): The file path to the output GeoJSON. Defaults to None.
bbox (tuple | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask. Defaults to None.
mask (dict | GeoDataFrame or GeoSeries | shapely Geometry, optional): Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox. Defaults to None.
rows (int or slice, optional): Load in specific rows by passing an integer (first n rows) or a slice() object.. Defaults to None.
epsg (str, optional): The EPSG number to convert to. Defaults to "4326".
Raises:
ValueError: When the output file path is invalid.
Returns:
dict: A dictionary containing the GeoJSON.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
if not filename.startswith("http"):
filename = os.path.abspath(filename)
if filename.endswith(".zip"):
filename = "zip://" + filename
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
df = gpd.read_file(
filename, bbox=bbox, mask=mask, rows=rows, driver="KML", **kwargs
)
else:
df = gpd.read_file(filename, bbox=bbox, mask=mask, rows=rows, **kwargs)
gdf = df.to_crs(epsg=epsg)
if out_geojson is not None:
if not out_geojson.lower().endswith(".geojson"):
raise ValueError("The output file must have a geojson file extension.")
out_geojson = os.path.abspath(out_geojson)
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
gdf.to_file(out_geojson, driver="GeoJSON")
else:
return gdf.__geo_interface__
def screen_capture(outfile, monitor=1):
"""Takes a full screenshot of the selected monitor.
Args:
outfile (str): The output file path to the screenshot.
monitor (int, optional): The monitor to take the screenshot. Defaults to 1.
"""
from mss import mss
out_dir = os.path.dirname(outfile)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
if not isinstance(monitor, int):
print("The monitor number must be an integer.")
return
try:
with mss() as sct:
sct.shot(output=outfile, mon=monitor)
return outfile
except Exception as e:
raise Exception(e)
def gdf_to_geojson(gdf, out_geojson=None, epsg=None):
"""Converts a GeoDataFame to GeoJSON.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
out_geojson (str, optional): File path to he output GeoJSON. Defaults to None.
epsg (str, optional): An EPSG string, e.g., "4326". Defaults to None.
Raises:
TypeError: When the output file extension is incorrect.
Exception: When the conversion fails.
Returns:
dict: When the out_json is None returns a dict.
"""
check_package(name="geopandas", URL="https://geopandas.org")
try:
if epsg is not None:
gdf = gdf.to_crs(epsg=epsg)
geojson = gdf.__geo_interface__
if out_geojson is None:
return geojson
else:
ext = os.path.splitext(out_geojson)[1]
if ext.lower() not in [".json", ".geojson"]:
raise TypeError(
"The output file extension must be either .json or .geojson"
)
out_dir = os.path.dirname(out_geojson)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
gdf.to_file(out_geojson, driver="GeoJSON")
except Exception as e:
raise Exception(e)
def connect_postgis(
database, host="localhost", user=None, password=None, port=5432, use_env_var=False
):
"""Connects to a PostGIS database.
Args:
database (str): Name of the database
host (str, optional): Hosting server for the database. Defaults to "localhost".
user (str, optional): User name to access the database. Defaults to None.
password (str, optional): Password to access the database. Defaults to None.
port (int, optional): Port number to connect to at the server host. Defaults to 5432.
use_env_var (bool, optional): Whether to use environment variables. It set to True, user and password are treated as an environment variables with default values user="SQL_USER" and password="SQL_PASSWORD". Defaults to False.
Raises:
ValueError: If user is not specified.
ValueError: If password is not specified.
Returns:
[type]: [description]
"""
check_package(name="geopandas", URL="https://geopandas.org")
check_package(
name="sqlalchemy",
URL="https://docs.sqlalchemy.org/en/14/intro.html#installation",
)
from sqlalchemy import create_engine
if use_env_var:
if user is not None:
user = os.getenv(user)
else:
user = os.getenv("SQL_USER")
if password is not None:
password = os.getenv(password)
else:
password = os.getenv("SQL_PASSWORD")
if user is None:
raise ValueError("user is not specified.")
if password is None:
raise ValueError("password is not specified.")
connection_string = f"postgresql://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(connection_string)
return engine
def read_postgis(sql, con, geom_col="geom", crs=None, **kwargs):
"""Reads data from a PostGIS database and returns a GeoDataFrame.
Args:
sql (str): SQL query to execute in selecting entries from database, or name of the table to read from the database.
con (sqlalchemy.engine.Engine): Active connection to the database to query.
geom_col (str, optional): Column name to convert to shapely geometries. Defaults to "geom".
crs (str | dict, optional): CRS to use for the returned GeoDataFrame; if not set, tries to determine CRS from the SRID associated with the first geometry in the database, and assigns that to all geometries. Defaults to None.
Returns:
[type]: [description]
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
gdf = gpd.read_postgis(sql, con, geom_col, crs, **kwargs)
return gdf
def vector_col_names(filename, **kwargs):
"""Retrieves the column names of a vector attribute table.
Args:
filename (str): The input file path.
Returns:
list: The list of column names.
"""
import warnings
warnings.filterwarnings("ignore")
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
if not filename.startswith("http"):
filename = os.path.abspath(filename)
ext = os.path.splitext(filename)[1].lower()
if ext == ".kml":
gpd.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
gdf = gpd.read_file(filename, driver="KML", **kwargs)
else:
gdf = gpd.read_file(filename, **kwargs)
col_names = gdf.columns.values.tolist()
return col_names
def get_api_key(token_name, m=None):
"""Retrieves an API key based on a system environmen variable.
Args:
token_name (str): The token name.
m (ipyleaflet.Map | folium.Map, optional): A Map instance. Defaults to None.
Returns:
str: The API key.
"""
api_key = os.environ.get(token_name)
if m is not None and token_name in m.api_keys:
api_key = m.api_keys[token_name]
return api_key
def set_api_key(token_name, api_key, m=None):
"""Sets an API key as an environment variable.
Args:
token_name (str): The token name.
api_key (str): The API key.
m (ipyleaflet.Map | folium.Map, optional): A Map instance.. Defaults to None.
"""
os.environ[token_name] = api_key
if m is not None:
m.api_keys[token_name] = api_key
def planet_monthly_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
links = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2020, year_now + 1):
for month in range(1, 13):
m_str = str(year) + "-" + str(month).zfill(2)
if year == 2020 and month < 9:
continue
if year == year_now and month >= month_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
links.append(url)
return links
def planet_biannual_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
dates = [
"2015-12_2016-05",
"2016-06_2016-11",
"2016-12_2017-05",
"2017-06_2017-11",
"2017-12_2018-05",
"2018-06_2018-11",
"2018-12_2019-05",
"2019-06_2019-11",
"2019-12_2020-05",
"2020-06_2020-08",
]
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/planet_medres_normalized_analytic_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for d in dates:
url = f"{prefix}{d}{subfix}{api_key}"
link.append(url)
return link
def planet_catalog_tropical(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Returns:
list: A list of tile URLs.
"""
biannual = planet_biannual_tropical(api_key, token_name)
monthly = planet_monthly_tropical(api_key, token_name)
return biannual + monthly
def planet_monthly_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_monthly_tropical(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 7]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_biannual_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet bi-annual imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_biannual_tropical(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 15]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_tiles_tropical(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
catalog = {}
biannul = planet_biannual_tiles_tropical(api_key, token_name, tile_format)
monthly = planet_monthly_tiles_tropical(api_key, token_name, tile_format)
for key in biannul:
catalog[key] = biannul[key]
for key in monthly:
catalog[key] = monthly[key]
return catalog
def planet_monthly(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet monthly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2016, year_now + 1):
for month in range(1, 13):
m_str = str(year) + "_" + str(month).zfill(2)
if year == year_now and month >= month_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
link.append(url)
return link
def planet_quarterly(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet quarterly imagery URLs based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: If the API key could not be found.
Returns:
list: A list of tile URLs.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
quarter_now = (month_now - 1) // 3 + 1
link = []
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
for year in range(2016, year_now + 1):
for quarter in range(1, 5):
m_str = str(year) + "q" + str(quarter)
if year == year_now and quarter >= quarter_now:
break
url = f"{prefix}{m_str}{subfix}{api_key}"
link.append(url)
return link
def planet_catalog(api_key=None, token_name="PLANET_API_KEY"):
"""Generates Planet bi-annual and monthly imagery URLs based on an API key. See https://assets.planet.com/docs/NICFI_UserGuidesFAQ.pdf
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Returns:
list: A list of tile URLs.
"""
quarterly = planet_quarterly(api_key, token_name)
monthly = planet_monthly(api_key, token_name)
return quarterly + monthly
def planet_monthly_tiles(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
link = planet_monthly(api_key, token_name)
for url in link:
index = url.find("20")
name = "Planet_" + url[index : index + 7]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_quarterly_tiles(
api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"
):
"""Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
tiles = {}
links = planet_quarterly(api_key, token_name)
for url in links:
index = url.find("20")
name = "Planet_" + url[index : index + 6]
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
tiles[name] = tile
return tiles
def planet_tiles(api_key=None, token_name="PLANET_API_KEY", tile_format="ipyleaflet"):
"""Generates Planet imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
catalog = {}
quarterly = planet_quarterly_tiles(api_key, token_name, tile_format)
monthly = planet_monthly_tiles(api_key, token_name, tile_format)
for key in quarterly:
catalog[key] = quarterly[key]
for key in monthly:
catalog[key] = monthly[key]
return catalog
def planet_by_quarter(
year=2016,
quarter=1,
api_key=None,
token_name="PLANET_API_KEY",
):
"""Gets Planet global mosaic tile url by quarter. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: The Planet API key is not provided.
ValueError: The year is invalid.
ValueError: The quarter is invalid.
ValueError: The quarter is invalid.
Returns:
str: A Planet global mosaic tile url.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
quarter_now = (month_now - 1) // 3 + 1
if year > year_now:
raise ValueError(f"Year must be between 2016 and {year_now}.")
elif year == year_now and quarter >= quarter_now:
raise ValueError(f"Quarter must be less than {quarter_now} for year {year_now}")
if quarter < 1 or quarter > 4:
raise ValueError("Quarter must be between 1 and 4.")
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_quarterly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
m_str = str(year) + "q" + str(quarter)
url = f"{prefix}{m_str}{subfix}{api_key}"
return url
def planet_by_month(
year=2016,
month=1,
api_key=None,
token_name="PLANET_API_KEY",
):
"""Gets Planet global mosaic tile url by month. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
Raises:
ValueError: The Planet API key is not provided.
ValueError: The year is invalid.
ValueError: The month is invalid.
ValueError: The month is invalid.
Returns:
str: A Planet global mosaic tile url.
"""
from datetime import date
if api_key is None:
api_key = os.environ.get(token_name)
if api_key is None:
raise ValueError("The Planet API Key must be provided.")
today = date.today()
year_now = int(today.strftime("%Y"))
month_now = int(today.strftime("%m"))
# quarter_now = (month_now - 1) // 3 + 1
if year > year_now:
raise ValueError(f"Year must be between 2016 and {year_now}.")
elif year == year_now and month >= month_now:
raise ValueError(f"Month must be less than {month_now} for year {year_now}")
if month < 1 or month > 12:
raise ValueError("Month must be between 1 and 12.")
prefix = "https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_"
subfix = "_mosaic/gmap/{z}/{x}/{y}.png?api_key="
m_str = str(year) + "_" + str(month).zfill(2)
url = f"{prefix}{m_str}{subfix}{api_key}"
return url
def planet_tile_by_quarter(
year=2016,
quarter=1,
name=None,
api_key=None,
token_name="PLANET_API_KEY",
tile_format="ipyleaflet",
):
"""Generates Planet quarterly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
quarter (int, optional): The quarter of Planet global mosaic, must be 1-4. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
url = planet_by_quarter(year, quarter, api_key, token_name)
if name is None:
name = "Planet_" + str(year) + "_q" + str(quarter)
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
return tile
def planet_tile_by_month(
year=2016,
month=1,
name=None,
api_key=None,
token_name="PLANET_API_KEY",
tile_format="ipyleaflet",
):
"""Generates Planet monthly imagery TileLayer based on an API key. To get a Planet API key, see https://developers.planet.com/quickstart/apis
Args:
year (int, optional): The year of Planet global mosaic, must be >=2016. Defaults to 2016.
month (int, optional): The month of Planet global mosaic, must be 1-12. Defaults to 1.
name (str, optional): The layer name to use. Defaults to None.
api_key (str, optional): The Planet API key. Defaults to None.
token_name (str, optional): The environment variable name of the API key. Defaults to "PLANET_API_KEY".
tile_format (str, optional): The TileLayer format, can be either ipyleaflet or folium. Defaults to "ipyleaflet".
Raises:
ValueError: If the tile layer format is invalid.
Returns:
dict: A dictionary of TileLayer.
"""
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
url = planet_by_month(year, month, api_key, token_name)
if name is None:
name = "Planet_" + str(year) + "_" + str(month).zfill(2)
if tile_format == "ipyleaflet":
tile = ipyleaflet.TileLayer(url=url, attribution="Planet", name=name)
else:
tile = folium.TileLayer(
tiles=url,
attr="Planet",
name=name,
overlay=True,
control=True,
)
return tile
def basemap_xyz_tiles():
"""Returns a dictionary containing a set of basemaps that are XYZ tile layers.
Returns:
dict: A dictionary of XYZ tile layers.
"""
from .leafmap import leafmap_basemaps
layers_dict = {}
keys = dict(leafmap_basemaps).keys()
for key in keys:
if isinstance(leafmap_basemaps[key], ipyleaflet.WMSLayer):
pass
else:
layers_dict[key] = leafmap_basemaps[key]
return layers_dict
def to_hex_colors(colors):
"""Adds # to a list of hex color codes.
Args:
colors (list): A list of hex color codes.
Returns:
list: A list of hex color codes prefixed with #.
"""
result = all([len(color.strip()) == 6 for color in colors])
if result:
return ["#" + color.strip() for color in colors]
else:
return colors
def display_html(src, width=950, height=600):
"""Display an HTML file in a Jupyter Notebook.
Args
src (str): File path to HTML file.
width (int, optional): Width of the map. Defaults to 950.
height (int, optional): Height of the map. Defaults to 600.
"""
if not os.path.isfile(src):
raise ValueError(f"{src} is not a valid file path.")
display(IFrame(src=src, width=width, height=height))
def get_census_dict(reset=False):
"""Returns a dictionary of Census data.
Args:
reset (bool, optional): Reset the dictionary. Defaults to False.
Returns:
dict: A dictionary of Census data.
"""
import json
import pkg_resources
pkg_dir = os.path.dirname(pkg_resources.resource_filename("leafmap", "leafmap.py"))
census_data = os.path.join(pkg_dir, "data/census_data.json")
if reset:
from owslib.wms import WebMapService
census_dict = {}
names = [
"Current",
"ACS 2021",
"ACS 2019",
"ACS 2018",
"ACS 2017",
"ACS 2016",
"ACS 2015",
"ACS 2014",
"ACS 2013",
"ACS 2012",
"ECON 2012",
"Census 2020",
"Census 2010",
"Physical Features",
"Decennial Census 2020",
"Decennial Census 2010",
"Decennial Census 2000",
"Decennial Physical Features",
]
links = {}
print("Retrieving data. Please wait ...")
for name in names:
if "Decennial" not in name:
links[
name
] = f"https://tigerweb.geo.census.gov/arcgis/services/TIGERweb/tigerWMS_{name.replace(' ', '')}/MapServer/WMSServer"
else:
links[
name
] = f"https://tigerweb.geo.census.gov/arcgis/services/Census2020/tigerWMS_{name.replace('Decennial', '').replace(' ', '')}/MapServer/WMSServer"
wms = WebMapService(links[name], timeout=300)
layers = list(wms.contents)
layers.sort()
census_dict[name] = {
"url": links[name],
"layers": layers,
# "title": wms.identification.title,
# "abstract": wms.identification.abstract,
}
with open(census_data, "w") as f:
json.dump(census_dict, f, indent=4)
else:
with open(census_data, "r") as f:
census_dict = json.load(f)
return census_dict
def search_xyz_services(keyword, name=None, list_only=True, add_prefix=True):
"""Search for XYZ tile providers from xyzservices.
Args:
keyword (str): The keyword to search for.
name (str, optional): The name of the xyz tile. Defaults to None.
list_only (bool, optional): If True, only the list of services will be returned. Defaults to True.
add_prefix (bool, optional): If True, the prefix "xyz." will be added to the service name. Defaults to True.
Returns:
list: A list of XYZ tile providers.
"""
import xyzservices.providers as xyz
if name is None:
providers = xyz.filter(keyword=keyword).flatten()
else:
providers = xyz.filter(name=name).flatten()
if list_only:
if add_prefix:
return ["xyz." + provider for provider in providers]
else:
return [provider for provider in providers]
else:
return providers
def search_qms(keyword, limit=10, list_only=True, add_prefix=True):
"""Search for QMS tile providers from Quick Map Services.
Args:
keyword (str): The keyword to search for.
limit (int, optional): The maximum number of results to return. Defaults to 10.
list_only (bool, optional): If True, only the list of services will be returned. Defaults to True.
add_prefix (bool, optional): If True, the prefix "qms." will be added to the service name. Defaults to True.
Returns:
list: A list of QMS tile providers.
"""
QMS_API = "https://qms.nextgis.com/api/v1/geoservices"
services = requests.get(
f"{QMS_API}/?search={keyword}&type=tms&epsg=3857&limit={limit}"
)
services = services.json()
if services["results"]:
providers = services["results"]
if list_only:
if add_prefix:
return ["qms." + provider["name"] for provider in providers]
else:
return [provider["name"] for provider in providers]
else:
return providers
else:
return None
def get_wms_layers(url):
"""Returns a list of WMS layers from a WMS service.
Args:
url (str): The URL of the WMS service.
Returns:
list: A list of WMS layers.
"""
from owslib.wms import WebMapService
wms = WebMapService(url)
layers = list(wms.contents)
layers.sort()
return layers
def create_legend(
legend_title="Legend",
legend_dict=None,
legend_keys=None,
legend_colors=None,
builtin_legend=None,
**kwargs,
):
"""Create a custom legend.
Args:
legend_title (str, optional): Title of the legend. Defaults to 'Legend'.
legend_dict (dict, optional): A dictionary containing legend items as keys and color as values. If provided, legend_keys and legend_colors will be ignored. Defaults to None.
legend_keys (list, optional): A list of legend keys. Defaults to None.
legend_colors (list, optional): A list of legend colors. Defaults to None.
builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
"""
import pkg_resources
from .legends import builtin_legends
pkg_dir = os.path.dirname(pkg_resources.resource_filename("leafmap", "leafmap.py"))
legend_template = os.path.join(pkg_dir, "data/template/legend.html")
if "min_width" not in kwargs.keys():
min_width = None
if "max_width" not in kwargs.keys():
max_width = None
else:
max_width = kwargs["max_width"]
if "min_height" not in kwargs.keys():
min_height = None
else:
min_height = kwargs["min_height"]
if "max_height" not in kwargs.keys():
max_height = None
else:
max_height = kwargs["max_height"]
if "height" not in kwargs.keys():
height = None
else:
height = kwargs["height"]
if "width" not in kwargs.keys():
width = None
else:
width = kwargs["width"]
if width is None:
max_width = "300px"
if height is None:
max_height = "400px"
if not os.path.exists(legend_template):
print("The legend template does not exist.")
return
if legend_keys is not None:
if not isinstance(legend_keys, list):
print("The legend keys must be a list.")
return
else:
legend_keys = ["One", "Two", "Three", "Four", "etc"]
if legend_colors is not None:
if not isinstance(legend_colors, list):
print("The legend colors must be a list.")
return
elif all(isinstance(item, tuple) for item in legend_colors):
try:
legend_colors = [rgb_to_hex(x) for x in legend_colors]
except Exception as e:
print(e)
elif all((item.startswith("#") and len(item) == 7) for item in legend_colors):
pass
elif all((len(item) == 6) for item in legend_colors):
pass
else:
print("The legend colors must be a list of tuples.")
return
else:
legend_colors = [
"#8DD3C7",
"#FFFFB3",
"#BEBADA",
"#FB8072",
"#80B1D3",
]
if len(legend_keys) != len(legend_colors):
print("The legend keys and values must be the same length.")
return
allowed_builtin_legends = builtin_legends.keys()
if builtin_legend is not None:
if builtin_legend not in allowed_builtin_legends:
print(
"The builtin legend must be one of the following: {}".format(
", ".join(allowed_builtin_legends)
)
)
return
else:
legend_dict = builtin_legends[builtin_legend]
legend_keys = list(legend_dict.keys())
legend_colors = list(legend_dict.values())
if legend_dict is not None:
if not isinstance(legend_dict, dict):
print("The legend dict must be a dictionary.")
return
else:
legend_keys = list(legend_dict.keys())
legend_colors = list(legend_dict.values())
if all(isinstance(item, tuple) for item in legend_colors):
try:
legend_colors = [rgb_to_hex(x) for x in legend_colors]
except Exception as e:
print(e)
header = []
content = []
footer = []
with open(legend_template) as f:
lines = f.readlines()
lines[3] = lines[3].replace("Legend", legend_title)
header = lines[:6]
footer = lines[11:]
for index, key in enumerate(legend_keys):
color = legend_colors[index]
if not color.startswith("#"):
color = "#" + color
item = " <li><span style='background:{};'></span>{}</li>\n".format(
color, key
)
content.append(item)
legend_html = header + content + footer
legend_text = "".join(legend_html)
return legend_text
def streamlit_legend(html, width=None, height=None, scrolling=True):
"""Streamlit function to display a legend.
Args:
html (str): The HTML string of the legend.
width (str, optional): The width of the legend. Defaults to None.
height (str, optional): The height of the legend. Defaults to None.
scrolling (bool, optional): Whether to allow scrolling in the legend. Defaults to True.
"""
try:
import streamlit.components.v1 as components
components.html(html, width=width, height=height, scrolling=scrolling)
except ImportError:
print("Streamlit is not installed. Please run 'pip install streamlit'.")
return
def read_file_from_url(url, return_type="list", encoding="utf-8"):
"""Reads a file from a URL.
Args:
url (str): The URL of the file.
return_type (str, optional): The return type, can either be string or list. Defaults to "list".
encoding (str, optional): The encoding of the file. Defaults to "utf-8".
Raises:
ValueError: The return type must be either list or string.
Returns:
str | list: The contents of the file.
"""
from urllib.request import urlopen
if return_type == "list":
return [line.decode(encoding).rstrip() for line in urlopen(url).readlines()]
elif return_type == "string":
return urlopen(url).read().decode(encoding)
else:
raise ValueError("The return type must be either list or string.")
def st_download_button(
label,
data,
file_name=None,
mime=None,
key=None,
help=None,
on_click=None,
args=None,
csv_sep=",",
**kwargs,
):
"""Streamlit function to create a download button.
Args:
label (str): A short label explaining to the user what this button is for..
data (str | list): The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily.
file_name (str, optional): An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. Defaults to None.
mime (str, optional): The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). Defaults to None.
key (str, optional): An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. Defaults to None.
help (str, optional): An optional tooltip that gets displayed when the button is hovered over. Defaults to None.
on_click (str, optional): An optional callback invoked when this button is clicked. Defaults to None.
args (list, optional): An optional tuple of args to pass to the callback. Defaults to None.
kwargs (dict, optional): An optional tuple of args to pass to the callback.
"""
try:
import streamlit as st
import pandas as pd
if isinstance(data, str):
if file_name is None:
file_name = data.split("/")[-1]
if data.endswith(".csv"):
data = pd.read_csv(data).to_csv(sep=csv_sep, index=False)
if mime is None:
mime = "text/csv"
return st.download_button(
label, data, file_name, mime, key, help, on_click, args, **kwargs
)
elif (
data.endswith(".gif") or data.endswith(".png") or data.endswith(".jpg")
):
if mime is None:
mime = f"image/{os.path.splitext(data)[1][1:]}"
with open(data, "rb") as file:
return st.download_button(
label,
file,
file_name,
mime,
key,
help,
on_click,
args,
**kwargs,
)
elif isinstance(data, pd.DataFrame):
if file_name is None:
file_name = "data.csv"
data = data.to_csv(sep=csv_sep, index=False)
if mime is None:
mime = "text/csv"
return st.download_button(
label, data, file_name, mime, key, help, on_click, args, **kwargs
)
else:
# if mime is None:
# mime = "application/pdf"
return st.download_button(
label,
data,
file_name,
mime,
key,
help,
on_click,
args,
**kwargs,
)
except ImportError:
print("Streamlit is not installed. Please run 'pip install streamlit'.")
return
except Exception as e:
raise Exception(e)
def save_data(data, file_ext=None, file_name=None):
"""Save data in the memory to a file.
Args:
data (object): The data to be saved.
file_ext (str): The file extension of the file.
file_name (str, optional): The name of the file to be saved. Defaults to None.
Returns:
str: The path of the file.
"""
import tempfile
import uuid
try:
if file_ext is None:
if hasattr(data, "name"):
_, file_ext = os.path.splitext(data.name)
else:
if not file_ext.startswith("."):
file_ext = "." + file_ext
if file_name is not None:
file_path = os.path.abspath(file_name)
if not file_path.endswith(file_ext):
file_path = file_path + file_ext
else:
file_id = str(uuid.uuid4())
file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{file_ext}")
with open(file_path, "wb") as file:
file.write(data.getbuffer())
return file_path
except Exception as e:
print(e)
return None
def temp_file_path(extension):
"""Returns a temporary file path.
Args:
extension (str): The file extension.
Returns:
str: The temporary file path.
"""
import tempfile
import os
import uuid
if not extension.startswith("."):
extension = "." + extension
file_id = str(uuid.uuid4())
file_path = os.path.join(tempfile.gettempdir(), f"{file_id}{extension}")
return file_path
def get_local_tile_layer(
source,
port="default",
debug=False,
projection="EPSG:3857",
band=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
tile_format="ipyleaflet",
layer_name=None,
get_center=False,
get_bounds=False,
**kwargs,
):
"""Generate an ipyleaflet/folium TileLayer from a local raster dataset or remote Cloud Optimized GeoTIFF (COG).
Args:
source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.
port (str, optional): The port to use for the server. Defaults to "default".
debug (bool, optional): If True, the server will be started in debug mode. Defaults to False.
projection (str, optional): The projection of the GeoTIFF. Defaults to "EPSG:3857".
band (int, optional): The band to use. Band indexing starts at 1. Defaults to None.
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
tile_format (str, optional): The tile layer format. Can be either ipyleaflet or folium. Defaults to "ipyleaflet".
layer_name (str, optional): The layer name to use. Defaults to None.
get_center (bool, optional): If True, the center of the layer will be returned. Defaults to False.
get_bounds (bool, optional): If True, the bounds [minx, miny, maxx, maxy] of the layer will be returned. Defaults to False.
Returns:
ipyleaflet.TileLayer | folium.TileLayer: An ipyleaflet.TileLayer or folium.TileLayer.
"""
check_package(
"localtileserver", URL="https://github.com/banesullivan/localtileserver"
)
from localtileserver import (
get_leaflet_tile_layer,
get_folium_tile_layer,
TileClient,
)
if isinstance(source, str):
if not source.startswith("http"):
source = os.path.abspath(source)
if not os.path.exists(source):
raise ValueError("The source path does not exist.")
else:
raise ValueError("The source must either be a string or TileClient")
if tile_format not in ["ipyleaflet", "folium"]:
raise ValueError("The tile format must be either ipyleaflet or folium.")
if layer_name is None:
if source.startswith("http"):
layer_name = "RemoteTile_" + random_string(3)
else:
layer_name = "LocalTile_" + random_string(3)
tile_client = TileClient(source, port=port, debug=debug)
if tile_format == "ipyleaflet":
tile_layer = get_leaflet_tile_layer(
tile_client,
port=port,
debug=debug,
projection=projection,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
name=layer_name,
**kwargs,
)
else:
tile_layer = get_folium_tile_layer(
tile_client,
port=port,
debug=debug,
projection=projection,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attr=attribution,
overlay=True,
name=layer_name,
**kwargs,
)
center = tile_client.center()
bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax]
bounds = (bounds[2], bounds[0], bounds[3], bounds[1]) # [minx, miny, maxx, maxy]
if get_center and get_bounds:
return tile_layer, center, bounds
elif get_center:
return tile_layer, center
elif get_bounds:
return tile_layer, bounds
else:
return tile_layer
def get_palettable(types=None):
"""Get a list of palettable color palettes.
Args:
types (list, optional): A list of palettable types to return, e.g., types=['matplotlib', 'cartocolors']. Defaults to None.
Returns:
list: A list of palettable color palettes.
"""
import palettable
if types is not None and (not isinstance(types, list)):
raise ValueError("The types must be a list.")
allowed_palettes = [
"cartocolors",
"cmocean",
"colorbrewer",
"cubehelix",
"lightbartlein",
"matplotlib",
"mycarta",
"scientific",
"tableau",
"wesanderson",
]
if types is None:
types = allowed_palettes[:]
if all(x in allowed_palettes for x in types):
pass
else:
raise ValueError(
"The types must be one of the following: " + ", ".join(allowed_palettes)
)
palettes = []
if "cartocolors" in types:
cartocolors_diverging = [
f"cartocolors.diverging.{c}"
for c in dir(palettable.cartocolors.diverging)[:-19]
]
cartocolors_qualitative = [
f"cartocolors.qualitative.{c}"
for c in dir(palettable.cartocolors.qualitative)[:-19]
]
cartocolors_sequential = [
f"cartocolors.sequential.{c}"
for c in dir(palettable.cartocolors.sequential)[:-41]
]
palettes = (
palettes
+ cartocolors_diverging
+ cartocolors_qualitative
+ cartocolors_sequential
)
if "cmocean" in types:
cmocean_diverging = [
f"cmocean.diverging.{c}" for c in dir(palettable.cmocean.diverging)[:-19]
]
cmocean_sequential = [
f"cmocean.sequential.{c}" for c in dir(palettable.cmocean.sequential)[:-19]
]
palettes = palettes + cmocean_diverging + cmocean_sequential
if "colorbrewer" in types:
colorbrewer_diverging = [
f"colorbrewer.diverging.{c}"
for c in dir(palettable.colorbrewer.diverging)[:-19]
]
colorbrewer_qualitative = [
f"colorbrewer.qualitative.{c}"
for c in dir(palettable.colorbrewer.qualitative)[:-19]
]
colorbrewer_sequential = [
f"colorbrewer.sequential.{c}"
for c in dir(palettable.colorbrewer.sequential)[:-41]
]
palettes = (
palettes
+ colorbrewer_diverging
+ colorbrewer_qualitative
+ colorbrewer_sequential
)
if "cubehelix" in types:
cubehelix = [
"classic_16",
"cubehelix1_16",
"cubehelix2_16",
"cubehelix3_16",
"jim_special_16",
"perceptual_rainbow_16",
"purple_16",
"red_16",
]
cubehelix = [f"cubehelix.{c}" for c in cubehelix]
palettes = palettes + cubehelix
if "lightbartlein" in types:
lightbartlein_diverging = [
f"lightbartlein.diverging.{c}"
for c in dir(palettable.lightbartlein.diverging)[:-19]
]
lightbartlein_sequential = [
f"lightbartlein.sequential.{c}"
for c in dir(palettable.lightbartlein.sequential)[:-19]
]
palettes = palettes + lightbartlein_diverging + lightbartlein_sequential
if "matplotlib" in types:
matplotlib_colors = [
f"matplotlib.{c}" for c in dir(palettable.matplotlib)[:-16]
]
palettes = palettes + matplotlib_colors
if "mycarta" in types:
mycarta = [f"mycarta.{c}" for c in dir(palettable.mycarta)[:-16]]
palettes = palettes + mycarta
if "scientific" in types:
scientific_diverging = [
f"scientific.diverging.{c}"
for c in dir(palettable.scientific.diverging)[:-19]
]
scientific_sequential = [
f"scientific.sequential.{c}"
for c in dir(palettable.scientific.sequential)[:-19]
]
palettes = palettes + scientific_diverging + scientific_sequential
if "tableau" in types:
tableau = [f"tableau.{c}" for c in dir(palettable.tableau)[:-14]]
palettes = palettes + tableau
return palettes
def points_from_xy(data, x="longitude", y="latitude", z=None, crs=None, **kwargs):
"""Create a GeoPandas GeoDataFrame from a csv or Pandas DataFrame containing x, y, z values.
Args:
data (str | pd.DataFrame): A csv or Pandas DataFrame containing x, y, z values.
x (str, optional): The column name for the x values. Defaults to "longitude".
y (str, optional): The column name for the y values. Defaults to "latitude".
z (str, optional): The column name for the z values. Defaults to None.
crs (str | int, optional): The coordinate reference system for the GeoDataFrame. Defaults to None.
Returns:
geopandas.GeoDataFrame: A GeoPandas GeoDataFrame containing x, y, z values.
"""
check_package(name="geopandas", URL="https://geopandas.org")
import geopandas as gpd
import pandas as pd
if crs is None:
crs = "epsg:4326"
if isinstance(data, pd.DataFrame):
df = data
elif isinstance(data, str):
if not data.startswith("http") and (not os.path.exists(data)):
raise FileNotFoundError("The specified input csv does not exist.")
else:
df = pd.read_csv(data, **kwargs)
else:
raise TypeError("The data must be a pandas DataFrame or a csv file path.")
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[x], df[y], z=z, crs=crs))
return gdf
def html_to_streamlit(
html,
width=800,
height=600,
responsive=True,
scrolling=False,
token_name=None,
token_value=None,
**kwargs,
):
"""Renders an HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.
Args:
html (str): The HTML file to render. It can a local file path or a URL.
width (int, optional): Width of the map. Defaults to 800.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False.
token_name (str, optional): The name of the token in the HTML file to be replaced. Defaults to None.
token_value (str, optional): The value of the token to pass to the HTML file. Defaults to None.
Returns:
streamlit.components: components.html object.
"""
try:
import streamlit as st
import streamlit.components.v1 as components
if isinstance(html, str):
temp_path = None
if html.startswith("http") and html.endswith(".html"):
temp_path = temp_file_path(".html")
out_file = os.path.basename(temp_path)
out_dir = os.path.dirname(temp_path)
download_from_url(html, out_file, out_dir)
html = temp_path
elif not os.path.exists(html):
raise FileNotFoundError("The specified input html does not exist.")
with open(html) as f:
lines = f.readlines()
if (token_name is not None) and (token_value is not None):
lines = [line.replace(token_name, token_value) for line in lines]
html_str = "".join(lines)
if temp_path is not None:
os.remove(temp_path)
if responsive:
make_map_responsive = """
<style>
[title~="st.iframe"] { width: 100%}
</style>
"""
st.markdown(make_map_responsive, unsafe_allow_html=True)
return components.html(
html_str, width=width, height=height, scrolling=scrolling
)
else:
raise TypeError("The html must be a string.")
except Exception as e:
raise Exception(e)
def cesium_to_streamlit(
html,
width=800,
height=600,
responsive=True,
scrolling=False,
token_name=None,
token_value=None,
**kwargs,
):
"""Renders an cesium HTML file in a Streamlit app. This method is a static Streamlit Component, meaning, no information is passed back from Leaflet on browser interaction.
Args:
html (str): The HTML file to render. It can a local file path or a URL.
width (int, optional): Width of the map. Defaults to 800.
height (int, optional): Height of the map. Defaults to 600.
responsive (bool, optional): Whether to make the map responsive. Defaults to True.
scrolling (bool, optional): Whether to allow the map to scroll. Defaults to False.
token_name (str, optional): The name of the token in the HTML file to be replaced. Defaults to None.
token_value (str, optional): The value of the token to pass to the HTML file. Defaults to None.
Returns:
streamlit.components: components.html object.
"""
if token_name is None:
token_name = "your_access_token"
if token_value is None:
token_value = os.environ.get("CESIUM_TOKEN")
html_to_streamlit(
html, width, height, responsive, scrolling, token_name, token_value
)
def geom_type(in_geojson, encoding="utf-8"):
"""Returns the geometry type of a GeoJSON object.
Args:
in_geojson (dict): A GeoJSON object.
encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8".
Returns:
str: The geometry type of the GeoJSON object.
"""
import json
try:
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
data = requests.get(in_geojson).json()
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError(
"The provided GeoJSON file could not be found."
)
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
else:
raise TypeError("The input geojson must be a type of str or dict.")
return data["features"][0]["geometry"]["type"]
except Exception as e:
raise Exception(e)
def geojson_to_df(in_geojson, encoding="utf-8"):
"""Converts a GeoJSON object to a pandas DataFrame.
Args:
in_geojson (str | dict): The input GeoJSON file or dict.
encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8".
Raises:
FileNotFoundError: If the input GeoJSON file could not be found.
Returns:
pd.DataFrame: A pandas DataFrame containing the GeoJSON object.
"""
import json
import pandas as pd
from urllib.request import urlopen
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
with urlopen(in_geojson) as f:
data = json.load(f)
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError("The provided GeoJSON file could not be found.")
with open(in_geojson, encoding=encoding) as f:
data = json.load(f)
elif isinstance(in_geojson, dict):
data = in_geojson
df = pd.json_normalize(data["features"])
df.columns = [col.replace("properties.", "") for col in df.columns]
return df
def bbox_to_gdf(bbox, crs="EPSG:4326"):
"""Converts a bounding box to a GeoDataFrame.
Args:
bbox (tuple): A bounding box in the form of a tuple (minx, miny, maxx, maxy).
crs (str, optional): The coordinate reference system of the bounding box to convert to. Defaults to "EPSG:4326".
Returns:
geopandas.GeoDataFrame: A GeoDataFrame containing the bounding box.
"""
check_package(name="geopandas", URL="https://geopandas.org")
from shapely.geometry import box
from geopandas import GeoDataFrame
minx, miny, maxx, maxy = bbox
geometry = box(minx, miny, maxx, maxy)
d = {"geometry": [geometry]}
gdf = GeoDataFrame(d, crs="EPSG:4326")
gdf.to_crs(crs=crs, inplace=True)
return gdf
|
import json
import logging
import os
import uuid
from collections import namedtuple
from typing import (
Dict,
List,
Optional,
)
from gxformat2 import (
from_galaxy_native,
ImporterGalaxyInterface,
ImportOptions,
python_to_workflow,
)
from pydantic import BaseModel
from sqlalchemy import and_
from sqlalchemy.orm import joinedload, subqueryload
from galaxy import (
exceptions,
model,
util
)
from galaxy.jobs.actions.post import ActionBox
from galaxy.model.item_attrs import UsesAnnotations
from galaxy.structured_app import MinimalManagerApp
from galaxy.tools.parameters import (
params_to_incoming,
visit_input_values
)
from galaxy.tools.parameters.basic import (
DataCollectionToolParameter,
DataToolParameter,
RuntimeValue,
workflow_building_modes
)
from galaxy.util.json import (
safe_dumps,
safe_loads,
)
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web import url_for
from galaxy.workflow.modules import (
is_tool_module_type,
module_factory,
ToolModule,
WorkflowModuleInjector
)
from galaxy.workflow.refactor.execute import WorkflowRefactorExecutor
from galaxy.workflow.refactor.schema import (
RefactorActionExecution,
RefactorActions,
)
from galaxy.workflow.reports import generate_report
from galaxy.workflow.resources import get_resource_mapper_function
from galaxy.workflow.steps import attach_ordered_steps
from .base import decode_id
from .executables import artifact_class
log = logging.getLogger(__name__)
class WorkflowsManager:
""" Handle CRUD type operations related to workflows. More interesting
stuff regarding workflow execution, step sorting, etc... can be found in
the galaxy.workflow module.
"""
def __init__(self, app: MinimalManagerApp):
self.app = app
def get_stored_workflow(self, trans, workflow_id, by_stored_id=True):
""" Use a supplied ID (UUID or encoded stored workflow ID) to find
a workflow.
"""
if util.is_uuid(workflow_id):
# see if they have passed in the UUID for a workflow that is attached to a stored workflow
workflow_uuid = uuid.UUID(workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).filter(and_(
trans.app.model.StoredWorkflow.id == trans.app.model.Workflow.stored_workflow_id,
trans.app.model.Workflow.uuid == workflow_uuid
))
elif by_stored_id:
workflow_id = decode_id(self.app, workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).\
filter(trans.app.model.StoredWorkflow.id == workflow_id)
else:
workflow_id = decode_id(self.app, workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).filter(and_(
trans.app.model.StoredWorkflow.id == trans.app.model.Workflow.stored_workflow_id,
trans.app.model.Workflow.id == workflow_id
))
stored_workflow = workflow_query.options(joinedload('annotations'),
joinedload('tags'),
subqueryload('latest_workflow').joinedload('steps').joinedload('*')).first()
if stored_workflow is None:
if not by_stored_id:
# May have a subworkflow without attached StoredWorkflow object, this was the default prior to 20.09 release.
workflow = trans.sa_session.query(trans.app.model.Workflow).get(workflow_id)
stored_workflow = self.attach_stored_workflow(trans=trans, workflow=workflow)
if stored_workflow:
return stored_workflow
raise exceptions.ObjectNotFound("No such workflow found.")
return stored_workflow
def get_stored_accessible_workflow(self, trans, workflow_id, by_stored_id=True):
""" Get a stored workflow from a encoded stored workflow id and
make sure it accessible to the user.
"""
stored_workflow = self.get_stored_workflow(trans, workflow_id, by_stored_id=by_stored_id)
# check to see if user has permissions to selected workflow
if stored_workflow.user != trans.user and not trans.user_is_admin and not stored_workflow.published:
if trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
message = "Workflow is not owned by or shared with current user"
raise exceptions.ItemAccessibilityException(message)
return stored_workflow
def attach_stored_workflow(self, trans, workflow):
"""Attach and return stored workflow if possible."""
# Imported Subworkflows are not created with a StoredWorkflow association
# To properly serialize them we do need a StoredWorkflow, so we create and attach one here.
# We hide the new StoredWorkflow to avoid cluttering the default workflow view.
if workflow and workflow.stored_workflow is None and self.check_security(trans, has_workflow=workflow):
stored_workflow = trans.app.model.StoredWorkflow(user=trans.user, name=workflow.name, workflow=workflow, hidden=True)
trans.sa_session.add(stored_workflow)
trans.sa_session.flush()
return stored_workflow
def get_owned_workflow(self, trans, encoded_workflow_id):
""" Get a workflow (non-stored) from a encoded workflow id and
make sure it accessible to the user.
"""
workflow_id = decode_id(self.app, encoded_workflow_id)
workflow = trans.sa_session.query(model.Workflow).get(workflow_id)
self.check_security(trans, workflow, check_ownership=True)
return workflow
def check_security(self, trans, has_workflow, check_ownership=True, check_accessible=True):
""" check accessibility or ownership of workflows, storedworkflows, and
workflowinvocations. Throw an exception or returns True if user has
needed level of access.
"""
if not check_ownership and not check_accessible:
return True
# If given an invocation verify ownership of invocation
if isinstance(has_workflow, model.WorkflowInvocation):
# We use the the owner of the history that is associated to the invocation as a proxy
# for the owner of the invocation.
if trans.user != has_workflow.history.user and not trans.user_is_admin:
raise exceptions.ItemOwnershipException()
else:
return True
# stored workflow contains security stuff - follow that workflow to
# that unless given a stored workflow.
if isinstance(has_workflow, model.Workflow):
stored_workflow = has_workflow.top_level_stored_workflow
else:
stored_workflow = has_workflow
if stored_workflow.user != trans.user and not trans.user_is_admin:
if check_ownership:
raise exceptions.ItemOwnershipException()
# else check_accessible...
if trans.sa_session.query(model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
raise exceptions.ItemAccessibilityException()
return True
def get_invocation(self, trans, decoded_invocation_id, eager=False):
q = trans.sa_session.query(
self.app.model.WorkflowInvocation
)
if eager:
q = q.options(subqueryload(self.app.model.WorkflowInvocation.steps).joinedload(
'implicit_collection_jobs').joinedload(
'jobs').joinedload(
'job').joinedload(
'input_datasets')
)
workflow_invocation = q.get(decoded_invocation_id)
if not workflow_invocation:
encoded_wfi_id = trans.security.encode_id(decoded_invocation_id)
message = f"'{encoded_wfi_id}' is not a valid workflow invocation id"
raise exceptions.ObjectNotFound(message)
self.check_security(trans, workflow_invocation, check_ownership=True, check_accessible=False)
return workflow_invocation
def get_invocation_report(self, trans, invocation_id, **kwd):
decoded_workflow_invocation_id = trans.security.decode_id(invocation_id)
workflow_invocation = self.get_invocation(trans, decoded_workflow_invocation_id)
generator_plugin_type = kwd.get("generator_plugin_type")
runtime_report_config_json = kwd.get("runtime_report_config_json")
invocation_markdown = kwd.get("invocation_markdown", None)
target_format = kwd.get("format", "json")
if invocation_markdown:
runtime_report_config_json = {"markdown": invocation_markdown}
return generate_report(
trans, workflow_invocation,
runtime_report_config_json=runtime_report_config_json,
plugin_type=generator_plugin_type,
target_format=target_format,
)
def cancel_invocation(self, trans, decoded_invocation_id):
workflow_invocation = self.get_invocation(trans, decoded_invocation_id)
cancelled = workflow_invocation.cancel()
if cancelled:
trans.sa_session.add(workflow_invocation)
trans.sa_session.flush()
else:
# TODO: More specific exception?
raise exceptions.MessageException("Cannot cancel an inactive workflow invocation.")
return workflow_invocation
def get_invocation_step(self, trans, decoded_workflow_invocation_step_id):
try:
workflow_invocation_step = trans.sa_session.query(
model.WorkflowInvocationStep
).get(decoded_workflow_invocation_step_id)
except Exception:
raise exceptions.ObjectNotFound()
self.check_security(trans, workflow_invocation_step.workflow_invocation, check_ownership=True, check_accessible=False)
return workflow_invocation_step
def update_invocation_step(self, trans, decoded_workflow_invocation_step_id, action):
if action is None:
raise exceptions.RequestParameterMissingException("Updating workflow invocation step requires an action parameter. ")
workflow_invocation_step = self.get_invocation_step(trans, decoded_workflow_invocation_step_id)
workflow_invocation = workflow_invocation_step.workflow_invocation
if not workflow_invocation.active:
raise exceptions.RequestParameterInvalidException("Attempting to modify the state of a completed workflow invocation.")
step = workflow_invocation_step.workflow_step
module = module_factory.from_workflow_step(trans, step)
performed_action = module.do_invocation_step_action(step, action)
workflow_invocation_step.action = performed_action
trans.sa_session.add(workflow_invocation_step)
trans.sa_session.flush()
return workflow_invocation_step
def build_invocations_query(self, trans, stored_workflow_id=None, history_id=None, job_id=None, user_id=None,
include_terminal=True, limit=None):
"""Get invocations owned by the current user."""
sa_session = trans.sa_session
invocations_query = sa_session.query(model.WorkflowInvocation).order_by(model.WorkflowInvocation.table.c.id.desc())
if stored_workflow_id is not None:
stored_workflow = sa_session.query(model.StoredWorkflow).get(stored_workflow_id)
if not stored_workflow:
raise exceptions.ObjectNotFound()
invocations_query = invocations_query.join(
model.Workflow
).filter(
model.Workflow.table.c.stored_workflow_id == stored_workflow_id
)
if user_id is not None:
invocations_query = invocations_query.join(
model.History
).filter(
model.History.table.c.user_id == user_id
)
if history_id is not None:
invocations_query = invocations_query.filter(
model.WorkflowInvocation.table.c.history_id == history_id
)
if job_id is not None:
invocations_query = invocations_query.join(
model.WorkflowInvocationStep
).filter(model.WorkflowInvocationStep.table.c.job_id == job_id)
if not include_terminal:
invocations_query = invocations_query.filter(
model.WorkflowInvocation.table.c.state.in_(model.WorkflowInvocation.non_terminal_states)
)
if limit is not None:
invocations_query = invocations_query.limit(limit)
return [inv for inv in invocations_query if self.check_security(trans,
inv,
check_ownership=True,
check_accessible=False)]
def serialize_workflow_invocation(self, invocation, **kwd):
app = self.app
view = kwd.get("view", "element")
step_details = util.string_as_bool(kwd.get('step_details', False))
legacy_job_state = util.string_as_bool(kwd.get('legacy_job_state', False))
as_dict = invocation.to_dict(view, step_details=step_details, legacy_job_state=legacy_job_state)
return app.security.encode_all_ids(as_dict, recursive=True)
def serialize_workflow_invocations(self, invocations, **kwd):
if "view" not in kwd:
kwd["view"] = "collection"
return list(map(lambda i: self.serialize_workflow_invocation(i, **kwd), invocations))
CreatedWorkflow = namedtuple("CreatedWorkflow", ["stored_workflow", "workflow", "missing_tools"])
class WorkflowContentsManager(UsesAnnotations):
def __init__(self, app: MinimalManagerApp):
self.app = app
self._resource_mapper_function = get_resource_mapper_function(app)
def ensure_raw_description(self, dict_or_raw_description):
if not isinstance(dict_or_raw_description, RawWorkflowDescription):
dict_or_raw_description = RawWorkflowDescription(dict_or_raw_description)
return dict_or_raw_description
def normalize_workflow_format(self, trans, as_dict):
"""Process incoming workflow descriptions for consumption by other methods.
Currently this mostly means converting format 2 workflows into standard Galaxy
workflow JSON for consumption for the rest of this module. In the future we will
want to be a lot more precise about this - preserve the original description along
side the data model and apply updates in a way that largely preserves YAML structure
so workflows can be extracted.
"""
workflow_directory = None
workflow_path = None
if as_dict.get("src", None) == "from_path":
if not trans.user_is_admin:
raise exceptions.AdminRequiredException()
workflow_path = as_dict.get("path")
workflow_directory = os.path.normpath(os.path.dirname(workflow_path))
workflow_class, as_dict, object_id = artifact_class(trans, as_dict)
if workflow_class == "GalaxyWorkflow" or "yaml_content" in as_dict:
# Format 2 Galaxy workflow.
galaxy_interface = Format2ConverterGalaxyInterface()
import_options = ImportOptions()
import_options.deduplicate_subworkflows = True
as_dict = python_to_workflow(as_dict, galaxy_interface, workflow_directory=workflow_directory, import_options=import_options)
return RawWorkflowDescription(as_dict, workflow_path)
def build_workflow_from_raw_description(
self,
trans,
raw_workflow_description,
workflow_create_options,
source=None,
add_to_menu=False,
hidden=False,
):
data = raw_workflow_description.as_dict
# Put parameters in workflow mode
trans.workflow_building_mode = workflow_building_modes.ENABLED
# If there's a source, put it in the workflow name.
if 'name' not in data:
raise exceptions.RequestParameterInvalidException(f"Invalid workflow format detected [{data}]")
workflow_input_name = data['name']
imported_sufix = f"(imported from {source})"
if source and imported_sufix not in workflow_input_name:
name = f"{workflow_input_name} {imported_sufix}"
else:
name = workflow_input_name
workflow, missing_tool_tups = self._workflow_from_raw_description(
trans,
raw_workflow_description,
workflow_create_options,
name=name,
)
if 'uuid' in data:
workflow.uuid = data['uuid']
# Connect up
stored = model.StoredWorkflow()
stored.from_path = raw_workflow_description.workflow_path
stored.name = workflow.name
workflow.stored_workflow = stored
stored.latest_workflow = workflow
stored.user = trans.user
stored.published = workflow_create_options.publish
stored.hidden = hidden
if data['annotation']:
annotation = sanitize_html(data['annotation'])
self.add_item_annotation(trans.sa_session, stored.user, stored, annotation)
workflow_tags = data.get('tags', [])
trans.app.tag_handler.set_tags_from_list(user=trans.user, item=stored, new_tags_list=workflow_tags)
# Persist
trans.sa_session.add(stored)
if add_to_menu:
if trans.user.stored_workflow_menu_entries is None:
trans.user.stored_workflow_menu_entries = []
menuEntry = model.StoredWorkflowMenuEntry()
menuEntry.stored_workflow = stored
trans.user.stored_workflow_menu_entries.append(menuEntry)
trans.sa_session.flush()
return CreatedWorkflow(
stored_workflow=stored,
workflow=workflow,
missing_tools=missing_tool_tups
)
def update_workflow_from_raw_description(self, trans, stored_workflow, raw_workflow_description, workflow_update_options):
raw_workflow_description = self.ensure_raw_description(raw_workflow_description)
# Put parameters in workflow mode
trans.workflow_building_mode = workflow_building_modes.ENABLED
dry_run = workflow_update_options.dry_run
workflow, missing_tool_tups = self._workflow_from_raw_description(
trans,
raw_workflow_description,
workflow_update_options,
name=stored_workflow.name,
dry_run=dry_run,
)
if missing_tool_tups and not workflow_update_options.allow_missing_tools:
errors = []
for missing_tool_tup in missing_tool_tups:
errors.append("Step %i: Requires tool '%s'." % (int(missing_tool_tup[3]) + 1, missing_tool_tup[0]))
raise MissingToolsException(workflow, errors)
# Connect up
if not dry_run:
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
else:
stored_workflow = model.StoredWorkflow() # detached
stored_workflow.latest_workflow = workflow
workflow.stored_workflow = stored_workflow
if workflow_update_options.update_stored_workflow_attributes:
update_dict = raw_workflow_description.as_dict
if 'name' in update_dict:
sanitized_name = sanitize_html(update_dict['name'])
workflow.name = sanitized_name
stored_workflow.name = sanitized_name
if 'annotation' in update_dict:
newAnnotation = sanitize_html(update_dict['annotation'])
sa_session = None if dry_run else trans.sa_session
self.add_item_annotation(sa_session, stored_workflow.user, stored_workflow, newAnnotation)
# Persist
if not dry_run:
trans.sa_session.flush()
if stored_workflow.from_path:
self._sync_stored_workflow(trans, stored_workflow)
# Return something informative
errors = []
if workflow.has_errors:
errors.append("Some steps in this workflow have validation errors")
if workflow.has_cycles:
errors.append("This workflow contains cycles")
return workflow, errors
def _workflow_from_raw_description(self, trans, raw_workflow_description, workflow_state_resolution_options, name, **kwds):
# don't commit the workflow or attach its part to the sa session - just build a
# a transient model to operate on or render.
dry_run = kwds.pop("dry_run", False)
data = raw_workflow_description.as_dict
if isinstance(data, str):
data = json.loads(data)
# Create new workflow from source data
workflow = model.Workflow()
workflow.name = name
if 'report' in data:
workflow.reports_config = data['report']
workflow.license = data.get('license')
workflow.creator_metadata = data.get('creator')
if 'license' in data:
workflow.license = data['license']
if 'creator' in data:
workflow.creator_metadata = data['creator']
# Assume no errors until we find a step that has some
workflow.has_errors = False
# Create each step
steps = []
# The editor will provide ids for each step that we don't need to save,
# but do need to use to make connections
steps_by_external_id = {}
# Preload dependent workflows with locally defined content_ids.
subworkflows = data.get("subworkflows")
subworkflow_id_map = None
if subworkflows:
subworkflow_id_map = {}
for key, subworkflow_dict in subworkflows.items():
subworkflow = self.__build_embedded_subworkflow(trans, subworkflow_dict, workflow_state_resolution_options)
subworkflow_id_map[key] = subworkflow
# Keep track of tools required by the workflow that are not available in
# the local Galaxy instance. Each tuple in the list of missing_tool_tups
# will be ( tool_id, tool_name, tool_version ).
missing_tool_tups = []
for step_dict in self.__walk_step_dicts(data):
if not dry_run:
self.__load_subworkflows(trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=dry_run)
module_kwds = workflow_state_resolution_options.dict()
module_kwds.update(kwds) # TODO: maybe drop this?
for step_dict in self.__walk_step_dicts(data):
module, step = self.__module_from_dict(trans, steps, steps_by_external_id, step_dict, **module_kwds)
is_tool = is_tool_module_type(module.type)
if is_tool and module.tool is None:
missing_tool_tup = (module.tool_id, module.get_name(), module.tool_version, step_dict['id'])
if missing_tool_tup not in missing_tool_tups:
missing_tool_tups.append(missing_tool_tup)
if module.get_errors():
workflow.has_errors = True
# Second pass to deal with connections between steps
self.__connect_workflow_steps(steps, steps_by_external_id, dry_run)
# Order the steps if possible
attach_ordered_steps(workflow, steps)
return workflow, missing_tool_tups
def workflow_to_dict(self, trans, stored, style="export", version=None, history=None):
""" Export the workflow contents to a dictionary ready for JSON-ification and to be
sent out via API for instance. There are three styles of export allowed 'export', 'instance', and
'editor'. The Galaxy team will do its best to preserve the backward compatibility of the
'export' style - this is the export method meant to be portable across Galaxy instances and over
time. The 'editor' style is subject to rapid and unannounced changes. The 'instance' export
option describes the workflow in a context more tied to the current Galaxy instance and includes
fields like 'url' and 'url' and actual unencoded step ids instead of 'order_index'.
"""
def to_format_2(wf_dict, **kwds):
return from_galaxy_native(wf_dict, None, **kwds)
if version == '':
version = None
if version is not None:
version = int(version)
workflow = stored.get_internal_version(version)
if style == "export":
style = self.app.config.default_workflow_export_format
if style == "editor":
wf_dict = self._workflow_to_dict_editor(trans, stored, workflow)
elif style == "legacy":
wf_dict = self._workflow_to_dict_instance(stored, workflow=workflow, legacy=True)
elif style == "instance":
wf_dict = self._workflow_to_dict_instance(stored, workflow=workflow, legacy=False)
elif style == "run":
wf_dict = self._workflow_to_dict_run(trans, stored, workflow=workflow, history=history or trans.history)
elif style == "preview":
wf_dict = self._workflow_to_dict_preview(trans, workflow=workflow)
elif style == "format2":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
wf_dict = to_format_2(wf_dict)
elif style == "format2_wrapped_yaml":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
wf_dict = to_format_2(wf_dict, json_wrapper=True)
elif style == "ga":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
else:
raise exceptions.RequestParameterInvalidException(f'Unknown workflow style {style}')
if version is not None:
wf_dict['version'] = version
else:
wf_dict['version'] = len(stored.workflows) - 1
return wf_dict
def _sync_stored_workflow(self, trans, stored_workflow):
workflow_path = stored_workflow.from_path
workflow = stored_workflow.latest_workflow
with open(workflow_path, "w") as f:
if workflow_path.endswith(".ga"):
wf_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow)
json.dump(wf_dict, f, indent=4)
else:
wf_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow)
wf_dict = from_galaxy_native(wf_dict, None, json_wrapper=True)
f.write(wf_dict["yaml_content"])
def _workflow_to_dict_run(self, trans, stored, workflow, history=None):
"""
Builds workflow dictionary used by run workflow form
"""
if len(workflow.steps) == 0:
raise exceptions.MessageException('Workflow cannot be run because it does not have any steps.')
if attach_ordered_steps(workflow, workflow.steps):
raise exceptions.MessageException('Workflow cannot be run because it contains cycles.')
trans.workflow_building_mode = workflow_building_modes.USE_HISTORY
module_injector = WorkflowModuleInjector(trans)
has_upgrade_messages = False
step_version_changes = []
missing_tools = []
errors = {}
for step in workflow.steps:
try:
module_injector.inject(step, steps=workflow.steps, exact_tools=False)
except exceptions.ToolMissingException as e:
# FIXME: if a subworkflow lacks multiple tools we report only the first missing tool
if e.tool_id not in missing_tools:
missing_tools.append(e.tool_id)
continue
if step.upgrade_messages:
has_upgrade_messages = True
if step.type == 'tool' or step.type is None:
if step.module.version_changes:
step_version_changes.extend(step.module.version_changes)
step_errors = step.module.get_errors()
if step_errors:
errors[step.id] = step_errors
if missing_tools:
workflow.annotation = self.get_item_annotation_str(trans.sa_session, trans.user, workflow)
raise exceptions.MessageException(f"Following tools missing: {", ".join(missing_tools)}")
workflow.annotation = self.get_item_annotation_str(trans.sa_session, trans.user, workflow)
step_order_indices = {}
for step in workflow.steps:
step_order_indices[step.id] = step.order_index
step_models = []
for step in workflow.steps:
step_model = None
if step.type == 'tool':
incoming = {}
tool = trans.app.toolbox.get_tool(step.tool_id, tool_version=step.tool_version, tool_uuid=step.tool_uuid)
params_to_incoming(incoming, tool.inputs, step.state.inputs, trans.app)
step_model = tool.to_json(trans, incoming, workflow_building_mode=workflow_building_modes.USE_HISTORY, history=history)
step_model['post_job_actions'] = [{
'short_str': ActionBox.get_short_str(pja),
'action_type': pja.action_type,
'output_name': pja.output_name,
'action_arguments': pja.action_arguments
} for pja in step.post_job_actions]
else:
inputs = step.module.get_runtime_inputs(connections=step.output_connections)
step_model = {
'inputs': [input.to_dict(trans) for input in inputs.values()]
}
step_model['replacement_parameters'] = step.module.get_replacement_parameters(step)
step_model['step_type'] = step.type
step_model['step_label'] = step.label
step_model['step_name'] = step.module.get_name()
step_model['step_version'] = step.module.get_version()
step_model['step_index'] = step.order_index
step_model['output_connections'] = [{
'input_step_index': step_order_indices.get(oc.input_step_id),
'output_step_index': step_order_indices.get(oc.output_step_id),
'input_name': oc.input_name,
'output_name': oc.output_name
} for oc in step.output_connections]
if step.annotations:
step_model['annotation'] = step.annotations[0].annotation
if step.upgrade_messages:
step_model['messages'] = step.upgrade_messages
step_models.append(step_model)
return {
'id': trans.app.security.encode_id(stored.id),
'history_id': trans.app.security.encode_id(history.id) if history else None,
'name': stored.name,
'steps': step_models,
'step_version_changes': step_version_changes,
'has_upgrade_messages': has_upgrade_messages,
'workflow_resource_parameters': self._workflow_resource_parameters(trans, stored, workflow),
}
def _workflow_to_dict_preview(self, trans, workflow):
"""
Builds workflow dictionary containing input labels and values.
Used to create embedded workflow previews.
"""
if len(workflow.steps) == 0:
raise exceptions.MessageException('Workflow cannot be run because it does not have any steps.')
if attach_ordered_steps(workflow, workflow.steps):
raise exceptions.MessageException('Workflow cannot be run because it contains cycles.')
# Ensure that the user has a history
trans.get_history(most_recent=True, create=True)
def row_for_param(input_dict, param, raw_value, other_values, prefix, step):
input_dict["label"] = param.get_label()
value = None
if isinstance(param, DataToolParameter) or isinstance(param, DataCollectionToolParameter):
if (prefix + param.name) in step.input_connections_by_name:
conns = step.input_connections_by_name[prefix + param.name]
if not isinstance(conns, list):
conns = [conns]
value = ["Output '%s' from Step %d." % (conn.output_name, int(conn.output_step.order_index) + 1) for conn in conns]
value = ",".join(value)
else:
value = "Select at Runtime."
else:
value = param.value_to_display_text(raw_value) or 'Unavailable.'
input_dict["value"] = value
if hasattr(step, 'upgrade_messages') and step.upgrade_messages and param.name in step.upgrade_messages:
input_dict["upgrade_messages"] = step.upgrade_messages[param.name]
def do_inputs(inputs, values, prefix, step, other_values=None):
input_dicts = []
for input in inputs.values():
input_dict = {}
input_dict["type"] = input.type
if input.type == "repeat":
repeat_values = values[input.name]
if len(repeat_values) > 0:
input_dict["title"] = input.title_plural
nested_input_dicts = []
for i in range(len(repeat_values)):
nested_input_dict = {}
index = repeat_values[i]['__index__']
nested_input_dict["title"] = "%i. %s" % (i + 1, input.title)
nested_input_dict["inputs"] = do_inputs(input.inputs, repeat_values[i], f"{prefix + input.name}_{str(index)}|", step, other_values)
nested_input_dicts.append(nested_input_dict)
input_dict["inputs"] = nested_input_dicts
elif input.type == "conditional":
group_values = values[input.name]
current_case = group_values['__current_case__']
new_prefix = f"{prefix + input.name}|"
row_for_param(input_dict, input.test_param, group_values[input.test_param.name], other_values, prefix, step)
input_dict["inputs"] = do_inputs(input.cases[current_case].inputs, group_values, new_prefix, step, other_values)
elif input.type == "section":
new_prefix = f"{prefix + input.name}|"
group_values = values[input.name]
input_dict["title"] = input.title
input_dict["inputs"] = do_inputs(input.inputs, group_values, new_prefix, step, other_values)
else:
row_for_param(input_dict, input, values[input.name], other_values, prefix, step)
input_dicts.append(input_dict)
return input_dicts
step_dicts = []
for step in workflow.steps:
module_injector = WorkflowModuleInjector(trans)
step_dict = {}
step_dict["order_index"] = step.order_index
if hasattr(step, "annotation") and step.annotation is not None:
step_dict["annotation"] = step.annotation
try:
module_injector.inject(step, steps=workflow.steps, exact_tools=False)
except exceptions.ToolMissingException as e:
step_dict["label"] = f"Unknown Tool with id '{e.tool_id}'"
step_dicts.append(step_dict)
continue
if step.type == 'tool' or step.type is None:
tool = trans.app.toolbox.get_tool(step.tool_id)
if tool:
step_dict["label"] = step.label or tool.name
else:
step_dict["label"] = f"Unknown Tool with id '{step.tool_id}'"
step_dict["inputs"] = do_inputs(tool.inputs, step.state.inputs, "", step)
elif step.type == 'subworkflow':
step_dict["label"] = step.label or (step.subworkflow.name if step.subworkflow else "Missing workflow.")
errors = step.module.get_errors()
if errors:
step_dict["errors"] = errors
subworkflow_dict = self._workflow_to_dict_preview(trans, step.subworkflow)
step_dict["inputs"] = subworkflow_dict["steps"]
else:
module = step.module
step_dict["label"] = module.name
step_dict["inputs"] = do_inputs(module.get_runtime_inputs(), step.state.inputs, "", step)
step_dicts.append(step_dict)
return {
"steps": step_dicts,
}
def _workflow_resource_parameters(self, trans, stored, workflow):
"""Get workflow scheduling resource parameters for this user and workflow or None if not configured.
"""
return self._resource_mapper_function(trans=trans, stored_workflow=stored, workflow=workflow)
def _workflow_to_dict_editor(self, trans, stored, workflow, tooltip=True, is_subworkflow=False):
# Pack workflow data into a dictionary and return
data = {}
data['name'] = workflow.name
data['steps'] = {}
data['upgrade_messages'] = {}
data['report'] = workflow.reports_config or {}
data['license'] = workflow.license
data['creator'] = workflow.creator_metadata
data['annotation'] = self.get_item_annotation_str(trans.sa_session, trans.user, stored) or ''
output_label_index = set()
input_step_types = set(workflow.input_step_types)
# For each step, rebuild the form and encode the state
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step, exact_tools=False)
if not module:
raise exceptions.MessageException(f'Unrecognized step type: {step.type}')
# Load label from state of data input modules, necessary for backward compatibility
self.__set_default_label(step, module, step.tool_inputs)
# Fix any missing parameters
upgrade_message_dict = module.check_and_update_state() or {}
if hasattr(module, "version_changes") and module.version_changes:
upgrade_message_dict[module.tool.name] = "\n".join(module.version_changes)
# Get user annotation.
config_form = module.get_config_form(step=step)
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, step) or ''
# Pack attributes into plain dictionary
step_dict = {
'id': step.order_index,
'type': module.type,
'label': module.label,
'content_id': module.get_content_id(),
'name': module.get_name(),
'tool_state': module.get_tool_state(),
'errors': module.get_errors(),
'inputs': module.get_all_inputs(connectable_only=True),
'outputs': module.get_all_outputs(),
'config_form': config_form,
'annotation': annotation_str,
'post_job_actions': {},
'uuid': str(step.uuid) if step.uuid else None,
'workflow_outputs': []
}
if tooltip:
step_dict['tooltip'] = module.get_tooltip(static_path=url_for('/static'))
# Connections
input_connections = step.input_connections
input_connections_type = {}
multiple_input = {} # Boolean value indicating if this can be multiple
if (step.type is None or step.type == 'tool') and module.tool:
# Determine full (prefixed) names of valid input datasets
data_input_names = {}
def callback(input, prefixed_name, **kwargs):
if isinstance(input, DataToolParameter) or isinstance(input, DataCollectionToolParameter):
data_input_names[prefixed_name] = True
multiple_input[prefixed_name] = input.multiple
if isinstance(input, DataToolParameter):
input_connections_type[input.name] = "dataset"
if isinstance(input, DataCollectionToolParameter):
input_connections_type[input.name] = "dataset_collection"
visit_input_values(module.tool.inputs, module.state.inputs, callback)
# post_job_actions
pja_dict = {}
for pja in step.post_job_actions:
pja_dict[pja.action_type + pja.output_name] = dict(
action_type=pja.action_type,
output_name=pja.output_name,
action_arguments=pja.action_arguments
)
step_dict['post_job_actions'] = pja_dict
# workflow outputs
outputs = []
output_label_duplicate = set()
for output in step.unique_workflow_outputs:
if output.workflow_step.type not in input_step_types:
output_label = output.label
output_name = output.output_name
output_uuid = str(output.uuid) if output.uuid else None
outputs.append({"output_name": output_name,
"uuid": output_uuid,
"label": output_label})
if output_label is not None:
if output_label in output_label_index:
if output_label not in output_label_duplicate:
output_label_duplicate.add(output_label)
else:
output_label_index.add(output_label)
step_dict['workflow_outputs'] = outputs
if len(output_label_duplicate) > 0:
output_label_duplicate_string = ", ".join(output_label_duplicate)
upgrade_message_dict['output_label_duplicate'] = f"Ignoring duplicate labels: {output_label_duplicate_string}."
if upgrade_message_dict:
data['upgrade_messages'][step.order_index] = upgrade_message_dict
# Encode input connections as dictionary
input_conn_dict = {}
for conn in input_connections:
input_type = "dataset"
if conn.input_name in input_connections_type:
input_type = input_connections_type[conn.input_name]
conn_dict = dict(id=conn.output_step.order_index, output_name=conn.output_name, input_type=input_type)
if conn.input_name in multiple_input:
if conn.input_name in input_conn_dict:
input_conn_dict[conn.input_name].append(conn_dict)
else:
input_conn_dict[conn.input_name] = [conn_dict]
else:
input_conn_dict[conn.input_name] = conn_dict
step_dict['input_connections'] = input_conn_dict
# Position
step_dict['position'] = step.position
# Add to return value
data['steps'][step.order_index] = step_dict
if is_subworkflow:
data['steps'] = self._resolve_collection_type(data['steps'])
return data
@staticmethod
def get_step_map_over(current_step, steps):
"""
Given a tool step and its input steps guess that maximum level of mapping over.
All data outputs of a step need to be mapped over to this level.
"""
max_map_over = ''
for input_name, input_connections in current_step['input_connections'].items():
if isinstance(input_connections, dict):
# if input does not accept multiple inputs
input_connections = [input_connections]
for input_value in input_connections:
current_data_input = None
for current_input in current_step['inputs']:
if current_input['name'] == input_name:
current_data_input = current_input
# we've got one of the tools' input data definitions
break
input_step = steps[input_value['id']]
for input_step_data_output in input_step['outputs']:
if input_step_data_output['name'] == input_value['output_name']:
collection_type = input_step_data_output.get('collection_type')
# This is the defined incoming collection type, in reality there may be additional
# mapping over of the workflows' data input, but this should be taken care of by the workflow editor /
# outer workflow.
if collection_type:
if current_data_input.get('input_type') == 'dataset' and current_data_input.get('multiple'):
# We reduce the innermost collection
if ':' in collection_type:
# more than one layer of nesting and multiple="true" input,
# we consume the innermost collection
collection_type = ":".join(collection_type.rsplit(':')[:-1])
else:
# We've reduced a list or a pair
collection_type = None
elif current_data_input.get('input_type') == 'dataset_collection':
current_collection_types = current_data_input['collection_types']
if not current_collection_types:
# Accepts any input dataset collection, no mapping
collection_type = None
elif collection_type in current_collection_types:
# incoming collection type is an exact match, no mapping over
collection_type = None
else:
outer_map_over = collection_type
for accepted_collection_type in current_data_input['collection_types']:
# need to find the lowest level of mapping over,
# for collection_type = 'list:list:list' and accepted_collection_type = ['list:list', 'list']
# it'd be outer_map_over == 'list'
if collection_type.endswith(accepted_collection_type):
_outer_map_over = collection_type[:-(len(accepted_collection_type) + 1)]
if len(_outer_map_over.split(':')) < len(outer_map_over.split(':')):
outer_map_over = _outer_map_over
collection_type = outer_map_over
# If there is mapping over, we're going to assume it is linked, everything else is (probably)
# too hard to display in the workflow editor. With this assumption we should be able to
# set the maximum mapping over level to the most deeply nested map_over
if collection_type and len(collection_type.split(':')) >= len(max_map_over.split(':')):
max_map_over = collection_type
if max_map_over:
return max_map_over
return None
def _resolve_collection_type(self, steps):
"""
Fill in collection type for step outputs.
This can either be via collection_type_source and / or "inherited" from the step's input.
This information is only needed in the workflow editor.
"""
for order_index in sorted(steps):
step = steps[order_index]
if step['type'] == 'tool' and not step.get('errors'):
map_over = self.get_step_map_over(step, steps)
for step_data_output in step['outputs']:
if step_data_output.get('collection_type_source') and step_data_output['collection_type'] is None:
collection_type_source = step_data_output['collection_type_source']
for input_connection in step['input_connections'].get(collection_type_source, []):
input_step = steps[input_connection['id']]
for input_step_data_output in input_step['outputs']:
if input_step_data_output['name'] == input_connection['output_name']:
step_data_output['collection_type'] = input_step_data_output.get('collection_type')
if map_over:
collection_type = map_over
step_data_output['collection'] = True
if step_data_output.get('collection_type'):
collection_type = f"{map_over}:{step_data_output["collection_type"]}"
step_data_output['collection_type'] = collection_type
return steps
def _workflow_to_dict_export(self, trans, stored=None, workflow=None, internal=False):
""" Export the workflow contents to a dictionary ready for JSON-ification and export.
If internal, use content_ids instead subworkflow definitions.
"""
annotation_str = ""
tag_str = ""
if stored is not None:
if stored.id:
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, stored) or ''
tag_str = stored.make_tag_string_list()
else:
# dry run with flushed workflow objects, just use the annotation
annotations = stored.annotations
if annotations and len(annotations) > 0:
annotation_str = util.unicodify(annotations[0].annotation)
# Pack workflow data into a dictionary and return
data = {}
data['a_galaxy_workflow'] = 'true' # Placeholder for identifying galaxy workflow
data['format-version'] = "0.1"
data['name'] = workflow.name
data['annotation'] = annotation_str
data['tags'] = tag_str
if workflow.uuid is not None:
data['uuid'] = str(workflow.uuid)
data['steps'] = {}
if workflow.reports_config:
data['report'] = workflow.reports_config
if workflow.creator_metadata:
data['creator'] = workflow.creator_metadata
if workflow.license:
data['license'] = workflow.license
# For each step, rebuild the form and encode the state
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step)
if not module:
raise exceptions.MessageException(f'Unrecognized step type: {step.type}')
# Get user annotation.
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, step) or ''
content_id = module.get_content_id()
# Export differences for backward compatibility
tool_state = module.get_export_state()
# Step info
step_dict = {
'id': step.order_index,
'type': module.type,
'content_id': content_id,
'tool_id': content_id, # For workflows exported to older Galaxies,
# eliminate after a few years...
'tool_version': step.tool_version,
'name': module.get_name(),
'tool_state': json.dumps(tool_state),
'errors': module.get_errors(),
'uuid': str(step.uuid),
'label': step.label or None,
'annotation': annotation_str
}
# Add tool shed repository information and post-job actions to step dict.
if module.type == 'tool':
if module.tool and module.tool.tool_shed:
step_dict["tool_shed_repository"] = {
'name': module.tool.repository_name,
'owner': module.tool.repository_owner,
'changeset_revision': module.tool.changeset_revision,
'tool_shed': module.tool.tool_shed
}
tool_representation = None
dynamic_tool = step.dynamic_tool
if dynamic_tool:
tool_representation = dynamic_tool.value
step_dict['tool_representation'] = tool_representation
if util.is_uuid(step_dict['content_id']):
step_dict['content_id'] = None
step_dict['tool_id'] = None
pja_dict = {}
for pja in step.post_job_actions:
pja_dict[pja.action_type + pja.output_name] = dict(
action_type=pja.action_type,
output_name=pja.output_name,
action_arguments=pja.action_arguments)
step_dict['post_job_actions'] = pja_dict
if module.type == 'subworkflow' and not internal:
del step_dict['content_id']
del step_dict['errors']
del step_dict['tool_version']
del step_dict['tool_state']
subworkflow = step.subworkflow
subworkflow_as_dict = self._workflow_to_dict_export(
trans,
stored=None,
workflow=subworkflow
)
step_dict['subworkflow'] = subworkflow_as_dict
# Data inputs, legacy section not used anywhere within core
input_dicts = []
step_state = module.state.inputs or {}
if module.type != 'tool':
name = step_state.get("name") or module.label
if name:
input_dicts.append({"name": name, "description": annotation_str})
for name, val in step_state.items():
input_type = type(val)
if input_type == RuntimeValue:
input_dicts.append({"name": name, "description": f"runtime parameter for tool {module.get_name()}"})
elif input_type == dict:
# Input type is described by a dict, e.g. indexed parameters.
for partval in val.values():
if type(partval) == RuntimeValue:
input_dicts.append({"name": name, "description": f"runtime parameter for tool {module.get_name()}"})
step_dict['inputs'] = input_dicts
# User outputs
workflow_outputs_dicts = []
for workflow_output in step.unique_workflow_outputs:
workflow_output_dict = dict(
output_name=workflow_output.output_name,
label=workflow_output.label,
uuid=str(workflow_output.uuid) if workflow_output.uuid is not None else None,
)
workflow_outputs_dicts.append(workflow_output_dict)
step_dict['workflow_outputs'] = workflow_outputs_dicts
# All step outputs
step_dict['outputs'] = []
if type(module) is ToolModule:
for output in module.get_data_outputs():
step_dict['outputs'].append({'name': output['name'], 'type': output['extensions'][0]})
step_in = {}
for step_input in step.inputs:
if step_input.default_value_set:
step_in[step_input.name] = {"default": step_input.default_value}
if step_in:
step_dict["in"] = step_in
# Connections
input_connections = step.input_connections
if step.type is None or step.type == 'tool':
# Determine full (prefixed) names of valid input datasets
data_input_names = {}
def callback(input, prefixed_name, **kwargs):
if isinstance(input, DataToolParameter) or isinstance(input, DataCollectionToolParameter):
data_input_names[prefixed_name] = True
# FIXME: this updates modules silently right now; messages from updates should be provided.
module.check_and_update_state()
if module.tool:
# If the tool is installed we attempt to verify input values
# and connections, otherwise the last known state will be dumped without modifications.
visit_input_values(module.tool.inputs, module.state.inputs, callback)
# Encode input connections as dictionary
input_conn_dict = {}
unique_input_names = {conn.input_name for conn in input_connections}
for input_name in unique_input_names:
input_conn_dicts = []
for conn in input_connections:
if conn.input_name != input_name:
continue
input_conn = dict(
id=conn.output_step.order_index,
output_name=conn.output_name
)
if conn.input_subworkflow_step is not None:
subworkflow_step_id = conn.input_subworkflow_step.order_index
input_conn["input_subworkflow_step_id"] = subworkflow_step_id
input_conn_dicts.append(input_conn)
input_conn_dict[input_name] = input_conn_dicts
# Preserve backward compatibility. Previously Galaxy
# assumed input connections would be dictionaries not
# lists of dictionaries, so replace any singleton list
# with just the dictionary so that workflows exported from
# newer Galaxy instances can be used with older Galaxy
# instances if they do no include multiple input
# tools. This should be removed at some point. Mirrored
# hack in _workflow_from_raw_description should never be removed so
# existing workflow exports continue to function.
for input_name, input_conn in dict(input_conn_dict).items():
if len(input_conn) == 1:
input_conn_dict[input_name] = input_conn[0]
step_dict['input_connections'] = input_conn_dict
# Position
step_dict['position'] = step.position
# Add to return value
data['steps'][step.order_index] = step_dict
return data
def _workflow_to_dict_instance(self, stored, workflow, legacy=True):
encode = self.app.security.encode_id
sa_session = self.app.model.context
item = stored.to_dict(view='element', value_mapper={'id': encode})
item['name'] = workflow.name
item['url'] = url_for('workflow', id=item['id'])
item['owner'] = stored.user.username
inputs = {}
for step in workflow.input_steps:
step_type = step.type
step_label = step.label or step.tool_inputs.get('name')
if step_label:
label = step_label
elif step_type == "data_input":
label = "Input Dataset"
elif step_type == "data_collection_input":
label = "Input Dataset Collection"
elif step_type == 'parameter_input':
label = "Input Parameter"
else:
raise ValueError(f"Invalid step_type {step_type}")
if legacy:
index = step.id
else:
index = step.order_index
step_uuid = str(step.uuid) if step.uuid else None
inputs[index] = {'label': label, 'value': '', 'uuid': step_uuid}
item['inputs'] = inputs
item['annotation'] = self.get_item_annotation_str(sa_session, stored.user, stored)
item['license'] = workflow.license
item['creator'] = workflow.creator_metadata
steps = {}
steps_to_order_index = {}
for step in workflow.steps:
steps_to_order_index[step.id] = step.order_index
for step in workflow.steps:
step_id = step.id if legacy else step.order_index
step_type = step.type
step_dict = {'id': step_id,
'type': step_type,
'tool_id': step.tool_id,
'tool_version': step.tool_version,
'annotation': self.get_item_annotation_str(sa_session, stored.user, step),
'tool_inputs': step.tool_inputs,
'input_steps': {}}
if step_type == 'subworkflow':
del step_dict['tool_id']
del step_dict['tool_version']
del step_dict['tool_inputs']
step_dict['workflow_id'] = encode(step.subworkflow.id)
for conn in step.input_connections:
step_id = step.id if legacy else step.order_index
source_id = conn.output_step_id
source_step = source_id if legacy else steps_to_order_index[source_id]
step_dict['input_steps'][conn.input_name] = {'source_step': source_step,
'step_output': conn.output_name}
steps[step_id] = step_dict
item['steps'] = steps
return item
def __walk_step_dicts(self, data):
""" Walk over the supplied step dictionaries and return them in a way
designed to preserve step order when possible.
"""
supplied_steps = data['steps']
# Try to iterate through imported workflow in such a way as to
# preserve step order.
step_indices = list(supplied_steps.keys())
try:
step_indices = sorted(step_indices, key=int)
except ValueError:
# to defensive, were these ever or will they ever not be integers?
pass
discovered_labels = set()
discovered_uuids = set()
discovered_output_labels = set()
discovered_output_uuids = set()
# First pass to build step objects and populate basic values
for step_index in step_indices:
step_dict = supplied_steps[step_index]
uuid = step_dict.get("uuid", None)
if uuid and uuid != "None":
if uuid in discovered_uuids:
raise exceptions.DuplicatedIdentifierException("Duplicate step UUID in request.")
discovered_uuids.add(uuid)
label = step_dict.get("label", None)
if label:
if label in discovered_labels:
raise exceptions.DuplicatedIdentifierException("Duplicated step label in request.")
discovered_labels.add(label)
if 'workflow_outputs' in step_dict:
outputs = step_dict['workflow_outputs']
# outputs may be list of name (deprecated legacy behavior)
# or dictionary of names to {uuid: <uuid>, label: <label>}
if isinstance(outputs, dict):
for output_name in outputs:
output_dict = outputs[output_name]
output_label = output_dict.get("label", None)
if output_label:
if label in discovered_output_labels:
raise exceptions.DuplicatedIdentifierException("Duplicated workflow output label in request.")
discovered_output_labels.add(label)
output_uuid = step_dict.get("output_uuid", None)
if output_uuid:
if output_uuid in discovered_output_uuids:
raise exceptions.DuplicatedIdentifierException("Duplicate workflow output UUID in request.")
discovered_output_uuids.add(uuid)
yield step_dict
def __load_subworkflows(self, trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=False):
step_type = step_dict.get("type", None)
if step_type == "subworkflow":
subworkflow = self.__load_subworkflow_from_step_dict(
trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=dry_run
)
step_dict["subworkflow"] = subworkflow
def __module_from_dict(self, trans, steps, steps_by_external_id, step_dict, **kwds):
""" Create a WorkflowStep model object and corresponding module
representing type-specific functionality from the incoming dictionary.
"""
dry_run = kwds.get("dry_run", False)
step = model.WorkflowStep()
step.position = step_dict.get('position', model.WorkflowStep.DEFAULT_POSITION)
if step_dict.get("uuid", None) and step_dict['uuid'] != "None":
step.uuid = step_dict["uuid"]
if "label" in step_dict:
step.label = step_dict["label"]
module = module_factory.from_dict(trans, step_dict, detached=dry_run, **kwds)
self.__set_default_label(step, module, step_dict.get('tool_state'))
module.save_to_step(step, detached=dry_run)
annotation = step_dict.get('annotation')
if annotation:
annotation = sanitize_html(annotation)
sa_session = None if dry_run else trans.sa_session
self.add_item_annotation(sa_session, trans.get_user(), step, annotation)
# Stick this in the step temporarily
step.temp_input_connections = step_dict.get('input_connections', {})
# Create the model class for the step
steps.append(step)
external_id = step_dict["id"]
steps_by_external_id[external_id] = step
if 'workflow_outputs' in step_dict:
workflow_outputs = step_dict['workflow_outputs']
found_output_names = set()
for workflow_output in workflow_outputs:
# Allow workflow outputs as list of output_names for backward compatibility.
if not isinstance(workflow_output, dict):
workflow_output = {"output_name": workflow_output}
output_name = workflow_output["output_name"]
if output_name in found_output_names:
raise exceptions.ObjectAttributeInvalidException(f"Duplicate workflow outputs with name [{output_name}] found.")
if not output_name:
raise exceptions.ObjectAttributeInvalidException("Workflow output with empty name encountered.")
found_output_names.add(output_name)
uuid = workflow_output.get("uuid", None)
label = workflow_output.get("label", None)
m = step.create_or_update_workflow_output(
output_name=output_name,
uuid=uuid,
label=label,
)
if not dry_run:
trans.sa_session.add(m)
if "in" in step_dict:
for input_name, input_dict in step_dict["in"].items():
step_input = step.get_or_add_input(input_name)
NO_DEFAULT_DEFINED = object()
default = input_dict.get("default", NO_DEFAULT_DEFINED)
if default is not NO_DEFAULT_DEFINED:
step_input.default_value = default
step_input.default_value_set = True
if dry_run and step in trans.sa_session:
trans.sa_session.expunge(step)
return module, step
def __load_subworkflow_from_step_dict(self, trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=False):
embedded_subworkflow = step_dict.get("subworkflow", None)
subworkflow_id = step_dict.get("content_id", None)
if embedded_subworkflow and subworkflow_id:
raise Exception("Subworkflow step defines both subworkflow and content_id, only one may be specified.")
if not embedded_subworkflow and not subworkflow_id:
raise Exception("Subworkflow step must define either subworkflow or content_id.")
if embedded_subworkflow:
assert not dry_run
subworkflow = self.__build_embedded_subworkflow(trans, embedded_subworkflow, workflow_state_resolution_options)
elif subworkflow_id_map is not None:
assert not dry_run
# Interpret content_id as a workflow local thing.
subworkflow = subworkflow_id_map[subworkflow_id[1:]]
else:
subworkflow = self.app.workflow_manager.get_owned_workflow(
trans, subworkflow_id
)
return subworkflow
def __build_embedded_subworkflow(self, trans, data, workflow_state_resolution_options):
raw_workflow_description = self.ensure_raw_description(data)
subworkflow = self.build_workflow_from_raw_description(
trans, raw_workflow_description, workflow_state_resolution_options, hidden=True
).workflow
return subworkflow
def __connect_workflow_steps(self, steps, steps_by_external_id, dry_run):
""" Second pass to deal with connections between steps.
Create workflow connection objects using externally specified ids
using during creation or update.
"""
for step in steps:
# Input connections
for input_name, conn_list in step.temp_input_connections.items():
if not conn_list:
continue
if not isinstance(conn_list, list): # Older style singleton connection
conn_list = [conn_list]
for conn_dict in conn_list:
if 'output_name' not in conn_dict or 'id' not in conn_dict:
template = "Invalid connection [%s] - must be dict with output_name and id fields."
message = template % conn_dict
raise exceptions.MessageException(message)
external_id = conn_dict['id']
if external_id not in steps_by_external_id:
raise KeyError(f"Failed to find external id {external_id} in {steps_by_external_id.keys()}")
output_step = steps_by_external_id[external_id]
output_name = conn_dict["output_name"]
input_subworkflow_step_index = conn_dict.get('input_subworkflow_step_id', None)
if dry_run:
input_subworkflow_step_index = None
step.add_connection(input_name, output_name, output_step, input_subworkflow_step_index)
del step.temp_input_connections
def __set_default_label(self, step, module, state):
""" Previously data input modules had a `name` attribute to rename individual steps. Here, this value is transferred
to the actual `label` attribute which is available for all module types, unique, and mapped to its own database column.
"""
if not module.label and module.type in ['data_input', 'data_collection_input']:
new_state = safe_loads(state)
default_label = new_state.get('name')
if default_label and util.unicodify(default_label).lower() not in ['input dataset', 'input dataset collection']:
step.label = module.label = default_label
def do_refactor(self, trans, stored_workflow, refactor_request):
"""Apply supplied actions to stored_workflow.latest_workflow to build a new version.
"""
workflow = stored_workflow.latest_workflow
as_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow, internal=True)
raw_workflow_description = self.normalize_workflow_format(trans, as_dict)
workflow_update_options = WorkflowUpdateOptions(
fill_defaults=False,
allow_missing_tools=True,
dry_run=refactor_request.dry_run,
)
module_injector = WorkflowModuleInjector(trans)
refactor_executor = WorkflowRefactorExecutor(raw_workflow_description, workflow, module_injector)
action_executions = refactor_executor.refactor(refactor_request)
refactored_workflow, errors = self.update_workflow_from_raw_description(
trans,
stored_workflow,
raw_workflow_description,
workflow_update_options,
)
# errors could be three things:
# - we allow missing tools so it won't be that.
# - might have cycles or might have state validation issues, but it still saved...
# so this is really more of a warning - we disregard it the other two places
# it is used also. These same messages will appear in the dictified version we
# we send back anyway
return refactored_workflow, action_executions
def refactor(self, trans, stored_workflow, refactor_request):
refactored_workflow, action_executions = self.do_refactor(trans, stored_workflow, refactor_request)
return RefactorResponse(
action_executions=action_executions,
workflow=self.workflow_to_dict(trans, refactored_workflow.stored_workflow, style=refactor_request.style),
dry_run=refactor_request.dry_run,
)
def get_all_tool_ids(self, workflow):
tool_ids = set()
for step in workflow.steps:
if step.type == 'tool':
if step.tool_id:
tool_ids.add(step.tool_id)
elif step.type == 'subworkflow':
tool_ids.update(self.get_all_tool_ids(step.subworkflow))
return tool_ids
class RefactorRequest(RefactorActions):
style: str = "export"
class RefactorResponse(BaseModel):
action_executions: List[RefactorActionExecution]
workflow: dict
dry_run: bool
class Config:
# Workflows have dictionaries with integer keys, which pydantic doesn't coerce to strings.
# Integer object keys aren't valid JSON, so the client fails.
json_dumps = safe_dumps
class WorkflowStateResolutionOptions(BaseModel):
# fill in default tool state when updating, may change tool_state
fill_defaults: bool = False
# If True, assume all tool state coming from generated form instead of potentially simpler json stored in DB/exported
from_tool_form: bool = False
# If False, allow running with less exact tool versions
exact_tools: bool = True
class WorkflowUpdateOptions(WorkflowStateResolutionOptions):
# Only used internally, don't set. If using the API assume updating the workflows
# representation with name or annotation for instance, updates the corresponding
# stored workflow
update_stored_workflow_attributes: bool = True
allow_missing_tools: bool = False
dry_run: bool = False
# Workflow update options but with some different defaults - we allow creating
# workflows with missing tools by default but not updating.
class WorkflowCreateOptions(WorkflowStateResolutionOptions):
import_tools: bool = False
publish: bool = False
# true or false, effectively defaults to ``publish`` if None/unset
importable: Optional[bool] = None
# following are install options, only used if import_tools is true
install_repository_dependencies: bool = False
install_resolver_dependencies: bool = False
install_tool_dependencies: bool = False
new_tool_panel_section_label: str = ''
tool_panel_section_id: str = ''
tool_panel_section_mapping: Dict = {}
shed_tool_conf: Optional[str] = None
@property
def is_importable(self):
# if self.importable is None, use self.publish that has a default.
if self.importable is None:
return self.publish
else:
return self.importable
@property
def install_options(self):
return {
'install_repository_dependencies': self.install_repository_dependencies,
'install_resolver_dependencies': self.install_resolver_dependencies,
'install_tool_dependencies': self.install_tool_dependencies,
'new_tool_panel_section_label': self.new_tool_panel_section_label,
'tool_panel_section_id': self.tool_panel_section_id,
'tool_panel_section_mapping': self.tool_panel_section_mapping,
'shed_tool_conf': self.shed_tool_conf
}
class MissingToolsException(exceptions.MessageException):
def __init__(self, workflow, errors):
self.workflow = workflow
self.errors = errors
class RawWorkflowDescription:
def __init__(self, as_dict, workflow_path=None):
self.as_dict = as_dict
self.workflow_path = workflow_path
class Format2ConverterGalaxyInterface(ImporterGalaxyInterface):
def import_workflow(self, workflow, **kwds):
raise NotImplementedError("Direct format 2 import of nested workflows is not yet implemented, use bioblend client.")
| import json
import logging
import os
import uuid
from collections import namedtuple
from typing import (
Dict,
List,
Optional,
)
from gxformat2 import (
from_galaxy_native,
ImporterGalaxyInterface,
ImportOptions,
python_to_workflow,
)
from pydantic import BaseModel
from sqlalchemy import and_
from sqlalchemy.orm import joinedload, subqueryload
from galaxy import (
exceptions,
model,
util
)
from galaxy.jobs.actions.post import ActionBox
from galaxy.model.item_attrs import UsesAnnotations
from galaxy.structured_app import MinimalManagerApp
from galaxy.tools.parameters import (
params_to_incoming,
visit_input_values
)
from galaxy.tools.parameters.basic import (
DataCollectionToolParameter,
DataToolParameter,
RuntimeValue,
workflow_building_modes
)
from galaxy.util.json import (
safe_dumps,
safe_loads,
)
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web import url_for
from galaxy.workflow.modules import (
is_tool_module_type,
module_factory,
ToolModule,
WorkflowModuleInjector
)
from galaxy.workflow.refactor.execute import WorkflowRefactorExecutor
from galaxy.workflow.refactor.schema import (
RefactorActionExecution,
RefactorActions,
)
from galaxy.workflow.reports import generate_report
from galaxy.workflow.resources import get_resource_mapper_function
from galaxy.workflow.steps import attach_ordered_steps
from .base import decode_id
from .executables import artifact_class
log = logging.getLogger(__name__)
class WorkflowsManager:
""" Handle CRUD type operations related to workflows. More interesting
stuff regarding workflow execution, step sorting, etc... can be found in
the galaxy.workflow module.
"""
def __init__(self, app: MinimalManagerApp):
self.app = app
def get_stored_workflow(self, trans, workflow_id, by_stored_id=True):
""" Use a supplied ID (UUID or encoded stored workflow ID) to find
a workflow.
"""
if util.is_uuid(workflow_id):
# see if they have passed in the UUID for a workflow that is attached to a stored workflow
workflow_uuid = uuid.UUID(workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).filter(and_(
trans.app.model.StoredWorkflow.id == trans.app.model.Workflow.stored_workflow_id,
trans.app.model.Workflow.uuid == workflow_uuid
))
elif by_stored_id:
workflow_id = decode_id(self.app, workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).\
filter(trans.app.model.StoredWorkflow.id == workflow_id)
else:
workflow_id = decode_id(self.app, workflow_id)
workflow_query = trans.sa_session.query(trans.app.model.StoredWorkflow).filter(and_(
trans.app.model.StoredWorkflow.id == trans.app.model.Workflow.stored_workflow_id,
trans.app.model.Workflow.id == workflow_id
))
stored_workflow = workflow_query.options(joinedload('annotations'),
joinedload('tags'),
subqueryload('latest_workflow').joinedload('steps').joinedload('*')).first()
if stored_workflow is None:
if not by_stored_id:
# May have a subworkflow without attached StoredWorkflow object, this was the default prior to 20.09 release.
workflow = trans.sa_session.query(trans.app.model.Workflow).get(workflow_id)
stored_workflow = self.attach_stored_workflow(trans=trans, workflow=workflow)
if stored_workflow:
return stored_workflow
raise exceptions.ObjectNotFound("No such workflow found.")
return stored_workflow
def get_stored_accessible_workflow(self, trans, workflow_id, by_stored_id=True):
""" Get a stored workflow from a encoded stored workflow id and
make sure it accessible to the user.
"""
stored_workflow = self.get_stored_workflow(trans, workflow_id, by_stored_id=by_stored_id)
# check to see if user has permissions to selected workflow
if stored_workflow.user != trans.user and not trans.user_is_admin and not stored_workflow.published:
if trans.sa_session.query(trans.app.model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
message = "Workflow is not owned by or shared with current user"
raise exceptions.ItemAccessibilityException(message)
return stored_workflow
def attach_stored_workflow(self, trans, workflow):
"""Attach and return stored workflow if possible."""
# Imported Subworkflows are not created with a StoredWorkflow association
# To properly serialize them we do need a StoredWorkflow, so we create and attach one here.
# We hide the new StoredWorkflow to avoid cluttering the default workflow view.
if workflow and workflow.stored_workflow is None and self.check_security(trans, has_workflow=workflow):
stored_workflow = trans.app.model.StoredWorkflow(user=trans.user, name=workflow.name, workflow=workflow, hidden=True)
trans.sa_session.add(stored_workflow)
trans.sa_session.flush()
return stored_workflow
def get_owned_workflow(self, trans, encoded_workflow_id):
""" Get a workflow (non-stored) from a encoded workflow id and
make sure it accessible to the user.
"""
workflow_id = decode_id(self.app, encoded_workflow_id)
workflow = trans.sa_session.query(model.Workflow).get(workflow_id)
self.check_security(trans, workflow, check_ownership=True)
return workflow
def check_security(self, trans, has_workflow, check_ownership=True, check_accessible=True):
""" check accessibility or ownership of workflows, storedworkflows, and
workflowinvocations. Throw an exception or returns True if user has
needed level of access.
"""
if not check_ownership and not check_accessible:
return True
# If given an invocation verify ownership of invocation
if isinstance(has_workflow, model.WorkflowInvocation):
# We use the the owner of the history that is associated to the invocation as a proxy
# for the owner of the invocation.
if trans.user != has_workflow.history.user and not trans.user_is_admin:
raise exceptions.ItemOwnershipException()
else:
return True
# stored workflow contains security stuff - follow that workflow to
# that unless given a stored workflow.
if isinstance(has_workflow, model.Workflow):
stored_workflow = has_workflow.top_level_stored_workflow
else:
stored_workflow = has_workflow
if stored_workflow.user != trans.user and not trans.user_is_admin:
if check_ownership:
raise exceptions.ItemOwnershipException()
# else check_accessible...
if trans.sa_session.query(model.StoredWorkflowUserShareAssociation).filter_by(user=trans.user, stored_workflow=stored_workflow).count() == 0:
raise exceptions.ItemAccessibilityException()
return True
def get_invocation(self, trans, decoded_invocation_id, eager=False):
q = trans.sa_session.query(
self.app.model.WorkflowInvocation
)
if eager:
q = q.options(subqueryload(self.app.model.WorkflowInvocation.steps).joinedload(
'implicit_collection_jobs').joinedload(
'jobs').joinedload(
'job').joinedload(
'input_datasets')
)
workflow_invocation = q.get(decoded_invocation_id)
if not workflow_invocation:
encoded_wfi_id = trans.security.encode_id(decoded_invocation_id)
message = f"'{encoded_wfi_id}' is not a valid workflow invocation id"
raise exceptions.ObjectNotFound(message)
self.check_security(trans, workflow_invocation, check_ownership=True, check_accessible=False)
return workflow_invocation
def get_invocation_report(self, trans, invocation_id, **kwd):
decoded_workflow_invocation_id = trans.security.decode_id(invocation_id)
workflow_invocation = self.get_invocation(trans, decoded_workflow_invocation_id)
generator_plugin_type = kwd.get("generator_plugin_type")
runtime_report_config_json = kwd.get("runtime_report_config_json")
invocation_markdown = kwd.get("invocation_markdown", None)
target_format = kwd.get("format", "json")
if invocation_markdown:
runtime_report_config_json = {"markdown": invocation_markdown}
return generate_report(
trans, workflow_invocation,
runtime_report_config_json=runtime_report_config_json,
plugin_type=generator_plugin_type,
target_format=target_format,
)
def cancel_invocation(self, trans, decoded_invocation_id):
workflow_invocation = self.get_invocation(trans, decoded_invocation_id)
cancelled = workflow_invocation.cancel()
if cancelled:
trans.sa_session.add(workflow_invocation)
trans.sa_session.flush()
else:
# TODO: More specific exception?
raise exceptions.MessageException("Cannot cancel an inactive workflow invocation.")
return workflow_invocation
def get_invocation_step(self, trans, decoded_workflow_invocation_step_id):
try:
workflow_invocation_step = trans.sa_session.query(
model.WorkflowInvocationStep
).get(decoded_workflow_invocation_step_id)
except Exception:
raise exceptions.ObjectNotFound()
self.check_security(trans, workflow_invocation_step.workflow_invocation, check_ownership=True, check_accessible=False)
return workflow_invocation_step
def update_invocation_step(self, trans, decoded_workflow_invocation_step_id, action):
if action is None:
raise exceptions.RequestParameterMissingException("Updating workflow invocation step requires an action parameter. ")
workflow_invocation_step = self.get_invocation_step(trans, decoded_workflow_invocation_step_id)
workflow_invocation = workflow_invocation_step.workflow_invocation
if not workflow_invocation.active:
raise exceptions.RequestParameterInvalidException("Attempting to modify the state of a completed workflow invocation.")
step = workflow_invocation_step.workflow_step
module = module_factory.from_workflow_step(trans, step)
performed_action = module.do_invocation_step_action(step, action)
workflow_invocation_step.action = performed_action
trans.sa_session.add(workflow_invocation_step)
trans.sa_session.flush()
return workflow_invocation_step
def build_invocations_query(self, trans, stored_workflow_id=None, history_id=None, job_id=None, user_id=None,
include_terminal=True, limit=None):
"""Get invocations owned by the current user."""
sa_session = trans.sa_session
invocations_query = sa_session.query(model.WorkflowInvocation).order_by(model.WorkflowInvocation.table.c.id.desc())
if stored_workflow_id is not None:
stored_workflow = sa_session.query(model.StoredWorkflow).get(stored_workflow_id)
if not stored_workflow:
raise exceptions.ObjectNotFound()
invocations_query = invocations_query.join(
model.Workflow
).filter(
model.Workflow.table.c.stored_workflow_id == stored_workflow_id
)
if user_id is not None:
invocations_query = invocations_query.join(
model.History
).filter(
model.History.table.c.user_id == user_id
)
if history_id is not None:
invocations_query = invocations_query.filter(
model.WorkflowInvocation.table.c.history_id == history_id
)
if job_id is not None:
invocations_query = invocations_query.join(
model.WorkflowInvocationStep
).filter(model.WorkflowInvocationStep.table.c.job_id == job_id)
if not include_terminal:
invocations_query = invocations_query.filter(
model.WorkflowInvocation.table.c.state.in_(model.WorkflowInvocation.non_terminal_states)
)
if limit is not None:
invocations_query = invocations_query.limit(limit)
return [inv for inv in invocations_query if self.check_security(trans,
inv,
check_ownership=True,
check_accessible=False)]
def serialize_workflow_invocation(self, invocation, **kwd):
app = self.app
view = kwd.get("view", "element")
step_details = util.string_as_bool(kwd.get('step_details', False))
legacy_job_state = util.string_as_bool(kwd.get('legacy_job_state', False))
as_dict = invocation.to_dict(view, step_details=step_details, legacy_job_state=legacy_job_state)
return app.security.encode_all_ids(as_dict, recursive=True)
def serialize_workflow_invocations(self, invocations, **kwd):
if "view" not in kwd:
kwd["view"] = "collection"
return list(map(lambda i: self.serialize_workflow_invocation(i, **kwd), invocations))
CreatedWorkflow = namedtuple("CreatedWorkflow", ["stored_workflow", "workflow", "missing_tools"])
class WorkflowContentsManager(UsesAnnotations):
def __init__(self, app: MinimalManagerApp):
self.app = app
self._resource_mapper_function = get_resource_mapper_function(app)
def ensure_raw_description(self, dict_or_raw_description):
if not isinstance(dict_or_raw_description, RawWorkflowDescription):
dict_or_raw_description = RawWorkflowDescription(dict_or_raw_description)
return dict_or_raw_description
def normalize_workflow_format(self, trans, as_dict):
"""Process incoming workflow descriptions for consumption by other methods.
Currently this mostly means converting format 2 workflows into standard Galaxy
workflow JSON for consumption for the rest of this module. In the future we will
want to be a lot more precise about this - preserve the original description along
side the data model and apply updates in a way that largely preserves YAML structure
so workflows can be extracted.
"""
workflow_directory = None
workflow_path = None
if as_dict.get("src", None) == "from_path":
if not trans.user_is_admin:
raise exceptions.AdminRequiredException()
workflow_path = as_dict.get("path")
workflow_directory = os.path.normpath(os.path.dirname(workflow_path))
workflow_class, as_dict, object_id = artifact_class(trans, as_dict)
if workflow_class == "GalaxyWorkflow" or "yaml_content" in as_dict:
# Format 2 Galaxy workflow.
galaxy_interface = Format2ConverterGalaxyInterface()
import_options = ImportOptions()
import_options.deduplicate_subworkflows = True
as_dict = python_to_workflow(as_dict, galaxy_interface, workflow_directory=workflow_directory, import_options=import_options)
return RawWorkflowDescription(as_dict, workflow_path)
def build_workflow_from_raw_description(
self,
trans,
raw_workflow_description,
workflow_create_options,
source=None,
add_to_menu=False,
hidden=False,
):
data = raw_workflow_description.as_dict
# Put parameters in workflow mode
trans.workflow_building_mode = workflow_building_modes.ENABLED
# If there's a source, put it in the workflow name.
if 'name' not in data:
raise exceptions.RequestParameterInvalidException(f"Invalid workflow format detected [{data}]")
workflow_input_name = data['name']
imported_sufix = f"(imported from {source})"
if source and imported_sufix not in workflow_input_name:
name = f"{workflow_input_name} {imported_sufix}"
else:
name = workflow_input_name
workflow, missing_tool_tups = self._workflow_from_raw_description(
trans,
raw_workflow_description,
workflow_create_options,
name=name,
)
if 'uuid' in data:
workflow.uuid = data['uuid']
# Connect up
stored = model.StoredWorkflow()
stored.from_path = raw_workflow_description.workflow_path
stored.name = workflow.name
workflow.stored_workflow = stored
stored.latest_workflow = workflow
stored.user = trans.user
stored.published = workflow_create_options.publish
stored.hidden = hidden
if data['annotation']:
annotation = sanitize_html(data['annotation'])
self.add_item_annotation(trans.sa_session, stored.user, stored, annotation)
workflow_tags = data.get('tags', [])
trans.app.tag_handler.set_tags_from_list(user=trans.user, item=stored, new_tags_list=workflow_tags)
# Persist
trans.sa_session.add(stored)
if add_to_menu:
if trans.user.stored_workflow_menu_entries is None:
trans.user.stored_workflow_menu_entries = []
menuEntry = model.StoredWorkflowMenuEntry()
menuEntry.stored_workflow = stored
trans.user.stored_workflow_menu_entries.append(menuEntry)
trans.sa_session.flush()
return CreatedWorkflow(
stored_workflow=stored,
workflow=workflow,
missing_tools=missing_tool_tups
)
def update_workflow_from_raw_description(self, trans, stored_workflow, raw_workflow_description, workflow_update_options):
raw_workflow_description = self.ensure_raw_description(raw_workflow_description)
# Put parameters in workflow mode
trans.workflow_building_mode = workflow_building_modes.ENABLED
dry_run = workflow_update_options.dry_run
workflow, missing_tool_tups = self._workflow_from_raw_description(
trans,
raw_workflow_description,
workflow_update_options,
name=stored_workflow.name,
dry_run=dry_run,
)
if missing_tool_tups and not workflow_update_options.allow_missing_tools:
errors = []
for missing_tool_tup in missing_tool_tups:
errors.append("Step %i: Requires tool '%s'." % (int(missing_tool_tup[3]) + 1, missing_tool_tup[0]))
raise MissingToolsException(workflow, errors)
# Connect up
if not dry_run:
workflow.stored_workflow = stored_workflow
stored_workflow.latest_workflow = workflow
else:
stored_workflow = model.StoredWorkflow() # detached
stored_workflow.latest_workflow = workflow
workflow.stored_workflow = stored_workflow
if workflow_update_options.update_stored_workflow_attributes:
update_dict = raw_workflow_description.as_dict
if 'name' in update_dict:
sanitized_name = sanitize_html(update_dict['name'])
workflow.name = sanitized_name
stored_workflow.name = sanitized_name
if 'annotation' in update_dict:
newAnnotation = sanitize_html(update_dict['annotation'])
sa_session = None if dry_run else trans.sa_session
self.add_item_annotation(sa_session, stored_workflow.user, stored_workflow, newAnnotation)
# Persist
if not dry_run:
trans.sa_session.flush()
if stored_workflow.from_path:
self._sync_stored_workflow(trans, stored_workflow)
# Return something informative
errors = []
if workflow.has_errors:
errors.append("Some steps in this workflow have validation errors")
if workflow.has_cycles:
errors.append("This workflow contains cycles")
return workflow, errors
def _workflow_from_raw_description(self, trans, raw_workflow_description, workflow_state_resolution_options, name, **kwds):
# don't commit the workflow or attach its part to the sa session - just build a
# a transient model to operate on or render.
dry_run = kwds.pop("dry_run", False)
data = raw_workflow_description.as_dict
if isinstance(data, str):
data = json.loads(data)
# Create new workflow from source data
workflow = model.Workflow()
workflow.name = name
if 'report' in data:
workflow.reports_config = data['report']
workflow.license = data.get('license')
workflow.creator_metadata = data.get('creator')
if 'license' in data:
workflow.license = data['license']
if 'creator' in data:
workflow.creator_metadata = data['creator']
# Assume no errors until we find a step that has some
workflow.has_errors = False
# Create each step
steps = []
# The editor will provide ids for each step that we don't need to save,
# but do need to use to make connections
steps_by_external_id = {}
# Preload dependent workflows with locally defined content_ids.
subworkflows = data.get("subworkflows")
subworkflow_id_map = None
if subworkflows:
subworkflow_id_map = {}
for key, subworkflow_dict in subworkflows.items():
subworkflow = self.__build_embedded_subworkflow(trans, subworkflow_dict, workflow_state_resolution_options)
subworkflow_id_map[key] = subworkflow
# Keep track of tools required by the workflow that are not available in
# the local Galaxy instance. Each tuple in the list of missing_tool_tups
# will be ( tool_id, tool_name, tool_version ).
missing_tool_tups = []
for step_dict in self.__walk_step_dicts(data):
if not dry_run:
self.__load_subworkflows(trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=dry_run)
module_kwds = workflow_state_resolution_options.dict()
module_kwds.update(kwds) # TODO: maybe drop this?
for step_dict in self.__walk_step_dicts(data):
module, step = self.__module_from_dict(trans, steps, steps_by_external_id, step_dict, **module_kwds)
is_tool = is_tool_module_type(module.type)
if is_tool and module.tool is None:
missing_tool_tup = (module.tool_id, module.get_name(), module.tool_version, step_dict['id'])
if missing_tool_tup not in missing_tool_tups:
missing_tool_tups.append(missing_tool_tup)
if module.get_errors():
workflow.has_errors = True
# Second pass to deal with connections between steps
self.__connect_workflow_steps(steps, steps_by_external_id, dry_run)
# Order the steps if possible
attach_ordered_steps(workflow, steps)
return workflow, missing_tool_tups
def workflow_to_dict(self, trans, stored, style="export", version=None, history=None):
""" Export the workflow contents to a dictionary ready for JSON-ification and to be
sent out via API for instance. There are three styles of export allowed 'export', 'instance', and
'editor'. The Galaxy team will do its best to preserve the backward compatibility of the
'export' style - this is the export method meant to be portable across Galaxy instances and over
time. The 'editor' style is subject to rapid and unannounced changes. The 'instance' export
option describes the workflow in a context more tied to the current Galaxy instance and includes
fields like 'url' and 'url' and actual unencoded step ids instead of 'order_index'.
"""
def to_format_2(wf_dict, **kwds):
return from_galaxy_native(wf_dict, None, **kwds)
if version == '':
version = None
if version is not None:
version = int(version)
workflow = stored.get_internal_version(version)
if style == "export":
style = self.app.config.default_workflow_export_format
if style == "editor":
wf_dict = self._workflow_to_dict_editor(trans, stored, workflow)
elif style == "legacy":
wf_dict = self._workflow_to_dict_instance(stored, workflow=workflow, legacy=True)
elif style == "instance":
wf_dict = self._workflow_to_dict_instance(stored, workflow=workflow, legacy=False)
elif style == "run":
wf_dict = self._workflow_to_dict_run(trans, stored, workflow=workflow, history=history or trans.history)
elif style == "preview":
wf_dict = self._workflow_to_dict_preview(trans, workflow=workflow)
elif style == "format2":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
wf_dict = to_format_2(wf_dict)
elif style == "format2_wrapped_yaml":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
wf_dict = to_format_2(wf_dict, json_wrapper=True)
elif style == "ga":
wf_dict = self._workflow_to_dict_export(trans, stored, workflow=workflow)
else:
raise exceptions.RequestParameterInvalidException(f'Unknown workflow style {style}')
if version is not None:
wf_dict['version'] = version
else:
wf_dict['version'] = len(stored.workflows) - 1
return wf_dict
def _sync_stored_workflow(self, trans, stored_workflow):
workflow_path = stored_workflow.from_path
workflow = stored_workflow.latest_workflow
with open(workflow_path, "w") as f:
if workflow_path.endswith(".ga"):
wf_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow)
json.dump(wf_dict, f, indent=4)
else:
wf_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow)
wf_dict = from_galaxy_native(wf_dict, None, json_wrapper=True)
f.write(wf_dict["yaml_content"])
def _workflow_to_dict_run(self, trans, stored, workflow, history=None):
"""
Builds workflow dictionary used by run workflow form
"""
if len(workflow.steps) == 0:
raise exceptions.MessageException('Workflow cannot be run because it does not have any steps.')
if attach_ordered_steps(workflow, workflow.steps):
raise exceptions.MessageException('Workflow cannot be run because it contains cycles.')
trans.workflow_building_mode = workflow_building_modes.USE_HISTORY
module_injector = WorkflowModuleInjector(trans)
has_upgrade_messages = False
step_version_changes = []
missing_tools = []
errors = {}
for step in workflow.steps:
try:
module_injector.inject(step, steps=workflow.steps, exact_tools=False)
except exceptions.ToolMissingException as e:
# FIXME: if a subworkflow lacks multiple tools we report only the first missing tool
if e.tool_id not in missing_tools:
missing_tools.append(e.tool_id)
continue
if step.upgrade_messages:
has_upgrade_messages = True
if step.type == 'tool' or step.type is None:
if step.module.version_changes:
step_version_changes.extend(step.module.version_changes)
step_errors = step.module.get_errors()
if step_errors:
errors[step.id] = step_errors
if missing_tools:
workflow.annotation = self.get_item_annotation_str(trans.sa_session, trans.user, workflow)
raise exceptions.MessageException(f"Following tools missing: {', '.join(missing_tools)}")
workflow.annotation = self.get_item_annotation_str(trans.sa_session, trans.user, workflow)
step_order_indices = {}
for step in workflow.steps:
step_order_indices[step.id] = step.order_index
step_models = []
for step in workflow.steps:
step_model = None
if step.type == 'tool':
incoming = {}
tool = trans.app.toolbox.get_tool(step.tool_id, tool_version=step.tool_version, tool_uuid=step.tool_uuid)
params_to_incoming(incoming, tool.inputs, step.state.inputs, trans.app)
step_model = tool.to_json(trans, incoming, workflow_building_mode=workflow_building_modes.USE_HISTORY, history=history)
step_model['post_job_actions'] = [{
'short_str': ActionBox.get_short_str(pja),
'action_type': pja.action_type,
'output_name': pja.output_name,
'action_arguments': pja.action_arguments
} for pja in step.post_job_actions]
else:
inputs = step.module.get_runtime_inputs(connections=step.output_connections)
step_model = {
'inputs': [input.to_dict(trans) for input in inputs.values()]
}
step_model['replacement_parameters'] = step.module.get_replacement_parameters(step)
step_model['step_type'] = step.type
step_model['step_label'] = step.label
step_model['step_name'] = step.module.get_name()
step_model['step_version'] = step.module.get_version()
step_model['step_index'] = step.order_index
step_model['output_connections'] = [{
'input_step_index': step_order_indices.get(oc.input_step_id),
'output_step_index': step_order_indices.get(oc.output_step_id),
'input_name': oc.input_name,
'output_name': oc.output_name
} for oc in step.output_connections]
if step.annotations:
step_model['annotation'] = step.annotations[0].annotation
if step.upgrade_messages:
step_model['messages'] = step.upgrade_messages
step_models.append(step_model)
return {
'id': trans.app.security.encode_id(stored.id),
'history_id': trans.app.security.encode_id(history.id) if history else None,
'name': stored.name,
'steps': step_models,
'step_version_changes': step_version_changes,
'has_upgrade_messages': has_upgrade_messages,
'workflow_resource_parameters': self._workflow_resource_parameters(trans, stored, workflow),
}
def _workflow_to_dict_preview(self, trans, workflow):
"""
Builds workflow dictionary containing input labels and values.
Used to create embedded workflow previews.
"""
if len(workflow.steps) == 0:
raise exceptions.MessageException('Workflow cannot be run because it does not have any steps.')
if attach_ordered_steps(workflow, workflow.steps):
raise exceptions.MessageException('Workflow cannot be run because it contains cycles.')
# Ensure that the user has a history
trans.get_history(most_recent=True, create=True)
def row_for_param(input_dict, param, raw_value, other_values, prefix, step):
input_dict["label"] = param.get_label()
value = None
if isinstance(param, DataToolParameter) or isinstance(param, DataCollectionToolParameter):
if (prefix + param.name) in step.input_connections_by_name:
conns = step.input_connections_by_name[prefix + param.name]
if not isinstance(conns, list):
conns = [conns]
value = ["Output '%s' from Step %d." % (conn.output_name, int(conn.output_step.order_index) + 1) for conn in conns]
value = ",".join(value)
else:
value = "Select at Runtime."
else:
value = param.value_to_display_text(raw_value) or 'Unavailable.'
input_dict["value"] = value
if hasattr(step, 'upgrade_messages') and step.upgrade_messages and param.name in step.upgrade_messages:
input_dict["upgrade_messages"] = step.upgrade_messages[param.name]
def do_inputs(inputs, values, prefix, step, other_values=None):
input_dicts = []
for input in inputs.values():
input_dict = {}
input_dict["type"] = input.type
if input.type == "repeat":
repeat_values = values[input.name]
if len(repeat_values) > 0:
input_dict["title"] = input.title_plural
nested_input_dicts = []
for i in range(len(repeat_values)):
nested_input_dict = {}
index = repeat_values[i]['__index__']
nested_input_dict["title"] = "%i. %s" % (i + 1, input.title)
nested_input_dict["inputs"] = do_inputs(input.inputs, repeat_values[i], f"{prefix + input.name}_{str(index)}|", step, other_values)
nested_input_dicts.append(nested_input_dict)
input_dict["inputs"] = nested_input_dicts
elif input.type == "conditional":
group_values = values[input.name]
current_case = group_values['__current_case__']
new_prefix = f"{prefix + input.name}|"
row_for_param(input_dict, input.test_param, group_values[input.test_param.name], other_values, prefix, step)
input_dict["inputs"] = do_inputs(input.cases[current_case].inputs, group_values, new_prefix, step, other_values)
elif input.type == "section":
new_prefix = f"{prefix + input.name}|"
group_values = values[input.name]
input_dict["title"] = input.title
input_dict["inputs"] = do_inputs(input.inputs, group_values, new_prefix, step, other_values)
else:
row_for_param(input_dict, input, values[input.name], other_values, prefix, step)
input_dicts.append(input_dict)
return input_dicts
step_dicts = []
for step in workflow.steps:
module_injector = WorkflowModuleInjector(trans)
step_dict = {}
step_dict["order_index"] = step.order_index
if hasattr(step, "annotation") and step.annotation is not None:
step_dict["annotation"] = step.annotation
try:
module_injector.inject(step, steps=workflow.steps, exact_tools=False)
except exceptions.ToolMissingException as e:
step_dict["label"] = f"Unknown Tool with id '{e.tool_id}'"
step_dicts.append(step_dict)
continue
if step.type == 'tool' or step.type is None:
tool = trans.app.toolbox.get_tool(step.tool_id)
if tool:
step_dict["label"] = step.label or tool.name
else:
step_dict["label"] = f"Unknown Tool with id '{step.tool_id}'"
step_dict["inputs"] = do_inputs(tool.inputs, step.state.inputs, "", step)
elif step.type == 'subworkflow':
step_dict["label"] = step.label or (step.subworkflow.name if step.subworkflow else "Missing workflow.")
errors = step.module.get_errors()
if errors:
step_dict["errors"] = errors
subworkflow_dict = self._workflow_to_dict_preview(trans, step.subworkflow)
step_dict["inputs"] = subworkflow_dict["steps"]
else:
module = step.module
step_dict["label"] = module.name
step_dict["inputs"] = do_inputs(module.get_runtime_inputs(), step.state.inputs, "", step)
step_dicts.append(step_dict)
return {
"steps": step_dicts,
}
def _workflow_resource_parameters(self, trans, stored, workflow):
"""Get workflow scheduling resource parameters for this user and workflow or None if not configured.
"""
return self._resource_mapper_function(trans=trans, stored_workflow=stored, workflow=workflow)
def _workflow_to_dict_editor(self, trans, stored, workflow, tooltip=True, is_subworkflow=False):
# Pack workflow data into a dictionary and return
data = {}
data['name'] = workflow.name
data['steps'] = {}
data['upgrade_messages'] = {}
data['report'] = workflow.reports_config or {}
data['license'] = workflow.license
data['creator'] = workflow.creator_metadata
data['annotation'] = self.get_item_annotation_str(trans.sa_session, trans.user, stored) or ''
output_label_index = set()
input_step_types = set(workflow.input_step_types)
# For each step, rebuild the form and encode the state
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step, exact_tools=False)
if not module:
raise exceptions.MessageException(f'Unrecognized step type: {step.type}')
# Load label from state of data input modules, necessary for backward compatibility
self.__set_default_label(step, module, step.tool_inputs)
# Fix any missing parameters
upgrade_message_dict = module.check_and_update_state() or {}
if hasattr(module, "version_changes") and module.version_changes:
upgrade_message_dict[module.tool.name] = "\n".join(module.version_changes)
# Get user annotation.
config_form = module.get_config_form(step=step)
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, step) or ''
# Pack attributes into plain dictionary
step_dict = {
'id': step.order_index,
'type': module.type,
'label': module.label,
'content_id': module.get_content_id(),
'name': module.get_name(),
'tool_state': module.get_tool_state(),
'errors': module.get_errors(),
'inputs': module.get_all_inputs(connectable_only=True),
'outputs': module.get_all_outputs(),
'config_form': config_form,
'annotation': annotation_str,
'post_job_actions': {},
'uuid': str(step.uuid) if step.uuid else None,
'workflow_outputs': []
}
if tooltip:
step_dict['tooltip'] = module.get_tooltip(static_path=url_for('/static'))
# Connections
input_connections = step.input_connections
input_connections_type = {}
multiple_input = {} # Boolean value indicating if this can be multiple
if (step.type is None or step.type == 'tool') and module.tool:
# Determine full (prefixed) names of valid input datasets
data_input_names = {}
def callback(input, prefixed_name, **kwargs):
if isinstance(input, DataToolParameter) or isinstance(input, DataCollectionToolParameter):
data_input_names[prefixed_name] = True
multiple_input[prefixed_name] = input.multiple
if isinstance(input, DataToolParameter):
input_connections_type[input.name] = "dataset"
if isinstance(input, DataCollectionToolParameter):
input_connections_type[input.name] = "dataset_collection"
visit_input_values(module.tool.inputs, module.state.inputs, callback)
# post_job_actions
pja_dict = {}
for pja in step.post_job_actions:
pja_dict[pja.action_type + pja.output_name] = dict(
action_type=pja.action_type,
output_name=pja.output_name,
action_arguments=pja.action_arguments
)
step_dict['post_job_actions'] = pja_dict
# workflow outputs
outputs = []
output_label_duplicate = set()
for output in step.unique_workflow_outputs:
if output.workflow_step.type not in input_step_types:
output_label = output.label
output_name = output.output_name
output_uuid = str(output.uuid) if output.uuid else None
outputs.append({"output_name": output_name,
"uuid": output_uuid,
"label": output_label})
if output_label is not None:
if output_label in output_label_index:
if output_label not in output_label_duplicate:
output_label_duplicate.add(output_label)
else:
output_label_index.add(output_label)
step_dict['workflow_outputs'] = outputs
if len(output_label_duplicate) > 0:
output_label_duplicate_string = ", ".join(output_label_duplicate)
upgrade_message_dict['output_label_duplicate'] = f"Ignoring duplicate labels: {output_label_duplicate_string}."
if upgrade_message_dict:
data['upgrade_messages'][step.order_index] = upgrade_message_dict
# Encode input connections as dictionary
input_conn_dict = {}
for conn in input_connections:
input_type = "dataset"
if conn.input_name in input_connections_type:
input_type = input_connections_type[conn.input_name]
conn_dict = dict(id=conn.output_step.order_index, output_name=conn.output_name, input_type=input_type)
if conn.input_name in multiple_input:
if conn.input_name in input_conn_dict:
input_conn_dict[conn.input_name].append(conn_dict)
else:
input_conn_dict[conn.input_name] = [conn_dict]
else:
input_conn_dict[conn.input_name] = conn_dict
step_dict['input_connections'] = input_conn_dict
# Position
step_dict['position'] = step.position
# Add to return value
data['steps'][step.order_index] = step_dict
if is_subworkflow:
data['steps'] = self._resolve_collection_type(data['steps'])
return data
@staticmethod
def get_step_map_over(current_step, steps):
"""
Given a tool step and its input steps guess that maximum level of mapping over.
All data outputs of a step need to be mapped over to this level.
"""
max_map_over = ''
for input_name, input_connections in current_step['input_connections'].items():
if isinstance(input_connections, dict):
# if input does not accept multiple inputs
input_connections = [input_connections]
for input_value in input_connections:
current_data_input = None
for current_input in current_step['inputs']:
if current_input['name'] == input_name:
current_data_input = current_input
# we've got one of the tools' input data definitions
break
input_step = steps[input_value['id']]
for input_step_data_output in input_step['outputs']:
if input_step_data_output['name'] == input_value['output_name']:
collection_type = input_step_data_output.get('collection_type')
# This is the defined incoming collection type, in reality there may be additional
# mapping over of the workflows' data input, but this should be taken care of by the workflow editor /
# outer workflow.
if collection_type:
if current_data_input.get('input_type') == 'dataset' and current_data_input.get('multiple'):
# We reduce the innermost collection
if ':' in collection_type:
# more than one layer of nesting and multiple="true" input,
# we consume the innermost collection
collection_type = ":".join(collection_type.rsplit(':')[:-1])
else:
# We've reduced a list or a pair
collection_type = None
elif current_data_input.get('input_type') == 'dataset_collection':
current_collection_types = current_data_input['collection_types']
if not current_collection_types:
# Accepts any input dataset collection, no mapping
collection_type = None
elif collection_type in current_collection_types:
# incoming collection type is an exact match, no mapping over
collection_type = None
else:
outer_map_over = collection_type
for accepted_collection_type in current_data_input['collection_types']:
# need to find the lowest level of mapping over,
# for collection_type = 'list:list:list' and accepted_collection_type = ['list:list', 'list']
# it'd be outer_map_over == 'list'
if collection_type.endswith(accepted_collection_type):
_outer_map_over = collection_type[:-(len(accepted_collection_type) + 1)]
if len(_outer_map_over.split(':')) < len(outer_map_over.split(':')):
outer_map_over = _outer_map_over
collection_type = outer_map_over
# If there is mapping over, we're going to assume it is linked, everything else is (probably)
# too hard to display in the workflow editor. With this assumption we should be able to
# set the maximum mapping over level to the most deeply nested map_over
if collection_type and len(collection_type.split(':')) >= len(max_map_over.split(':')):
max_map_over = collection_type
if max_map_over:
return max_map_over
return None
def _resolve_collection_type(self, steps):
"""
Fill in collection type for step outputs.
This can either be via collection_type_source and / or "inherited" from the step's input.
This information is only needed in the workflow editor.
"""
for order_index in sorted(steps):
step = steps[order_index]
if step['type'] == 'tool' and not step.get('errors'):
map_over = self.get_step_map_over(step, steps)
for step_data_output in step['outputs']:
if step_data_output.get('collection_type_source') and step_data_output['collection_type'] is None:
collection_type_source = step_data_output['collection_type_source']
for input_connection in step['input_connections'].get(collection_type_source, []):
input_step = steps[input_connection['id']]
for input_step_data_output in input_step['outputs']:
if input_step_data_output['name'] == input_connection['output_name']:
step_data_output['collection_type'] = input_step_data_output.get('collection_type')
if map_over:
collection_type = map_over
step_data_output['collection'] = True
if step_data_output.get('collection_type'):
collection_type = f"{map_over}:{step_data_output['collection_type']}"
step_data_output['collection_type'] = collection_type
return steps
def _workflow_to_dict_export(self, trans, stored=None, workflow=None, internal=False):
""" Export the workflow contents to a dictionary ready for JSON-ification and export.
If internal, use content_ids instead subworkflow definitions.
"""
annotation_str = ""
tag_str = ""
if stored is not None:
if stored.id:
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, stored) or ''
tag_str = stored.make_tag_string_list()
else:
# dry run with flushed workflow objects, just use the annotation
annotations = stored.annotations
if annotations and len(annotations) > 0:
annotation_str = util.unicodify(annotations[0].annotation)
# Pack workflow data into a dictionary and return
data = {}
data['a_galaxy_workflow'] = 'true' # Placeholder for identifying galaxy workflow
data['format-version'] = "0.1"
data['name'] = workflow.name
data['annotation'] = annotation_str
data['tags'] = tag_str
if workflow.uuid is not None:
data['uuid'] = str(workflow.uuid)
data['steps'] = {}
if workflow.reports_config:
data['report'] = workflow.reports_config
if workflow.creator_metadata:
data['creator'] = workflow.creator_metadata
if workflow.license:
data['license'] = workflow.license
# For each step, rebuild the form and encode the state
for step in workflow.steps:
# Load from database representation
module = module_factory.from_workflow_step(trans, step)
if not module:
raise exceptions.MessageException(f'Unrecognized step type: {step.type}')
# Get user annotation.
annotation_str = self.get_item_annotation_str(trans.sa_session, trans.user, step) or ''
content_id = module.get_content_id()
# Export differences for backward compatibility
tool_state = module.get_export_state()
# Step info
step_dict = {
'id': step.order_index,
'type': module.type,
'content_id': content_id,
'tool_id': content_id, # For workflows exported to older Galaxies,
# eliminate after a few years...
'tool_version': step.tool_version,
'name': module.get_name(),
'tool_state': json.dumps(tool_state),
'errors': module.get_errors(),
'uuid': str(step.uuid),
'label': step.label or None,
'annotation': annotation_str
}
# Add tool shed repository information and post-job actions to step dict.
if module.type == 'tool':
if module.tool and module.tool.tool_shed:
step_dict["tool_shed_repository"] = {
'name': module.tool.repository_name,
'owner': module.tool.repository_owner,
'changeset_revision': module.tool.changeset_revision,
'tool_shed': module.tool.tool_shed
}
tool_representation = None
dynamic_tool = step.dynamic_tool
if dynamic_tool:
tool_representation = dynamic_tool.value
step_dict['tool_representation'] = tool_representation
if util.is_uuid(step_dict['content_id']):
step_dict['content_id'] = None
step_dict['tool_id'] = None
pja_dict = {}
for pja in step.post_job_actions:
pja_dict[pja.action_type + pja.output_name] = dict(
action_type=pja.action_type,
output_name=pja.output_name,
action_arguments=pja.action_arguments)
step_dict['post_job_actions'] = pja_dict
if module.type == 'subworkflow' and not internal:
del step_dict['content_id']
del step_dict['errors']
del step_dict['tool_version']
del step_dict['tool_state']
subworkflow = step.subworkflow
subworkflow_as_dict = self._workflow_to_dict_export(
trans,
stored=None,
workflow=subworkflow
)
step_dict['subworkflow'] = subworkflow_as_dict
# Data inputs, legacy section not used anywhere within core
input_dicts = []
step_state = module.state.inputs or {}
if module.type != 'tool':
name = step_state.get("name") or module.label
if name:
input_dicts.append({"name": name, "description": annotation_str})
for name, val in step_state.items():
input_type = type(val)
if input_type == RuntimeValue:
input_dicts.append({"name": name, "description": f"runtime parameter for tool {module.get_name()}"})
elif input_type == dict:
# Input type is described by a dict, e.g. indexed parameters.
for partval in val.values():
if type(partval) == RuntimeValue:
input_dicts.append({"name": name, "description": f"runtime parameter for tool {module.get_name()}"})
step_dict['inputs'] = input_dicts
# User outputs
workflow_outputs_dicts = []
for workflow_output in step.unique_workflow_outputs:
workflow_output_dict = dict(
output_name=workflow_output.output_name,
label=workflow_output.label,
uuid=str(workflow_output.uuid) if workflow_output.uuid is not None else None,
)
workflow_outputs_dicts.append(workflow_output_dict)
step_dict['workflow_outputs'] = workflow_outputs_dicts
# All step outputs
step_dict['outputs'] = []
if type(module) is ToolModule:
for output in module.get_data_outputs():
step_dict['outputs'].append({'name': output['name'], 'type': output['extensions'][0]})
step_in = {}
for step_input in step.inputs:
if step_input.default_value_set:
step_in[step_input.name] = {"default": step_input.default_value}
if step_in:
step_dict["in"] = step_in
# Connections
input_connections = step.input_connections
if step.type is None or step.type == 'tool':
# Determine full (prefixed) names of valid input datasets
data_input_names = {}
def callback(input, prefixed_name, **kwargs):
if isinstance(input, DataToolParameter) or isinstance(input, DataCollectionToolParameter):
data_input_names[prefixed_name] = True
# FIXME: this updates modules silently right now; messages from updates should be provided.
module.check_and_update_state()
if module.tool:
# If the tool is installed we attempt to verify input values
# and connections, otherwise the last known state will be dumped without modifications.
visit_input_values(module.tool.inputs, module.state.inputs, callback)
# Encode input connections as dictionary
input_conn_dict = {}
unique_input_names = {conn.input_name for conn in input_connections}
for input_name in unique_input_names:
input_conn_dicts = []
for conn in input_connections:
if conn.input_name != input_name:
continue
input_conn = dict(
id=conn.output_step.order_index,
output_name=conn.output_name
)
if conn.input_subworkflow_step is not None:
subworkflow_step_id = conn.input_subworkflow_step.order_index
input_conn["input_subworkflow_step_id"] = subworkflow_step_id
input_conn_dicts.append(input_conn)
input_conn_dict[input_name] = input_conn_dicts
# Preserve backward compatibility. Previously Galaxy
# assumed input connections would be dictionaries not
# lists of dictionaries, so replace any singleton list
# with just the dictionary so that workflows exported from
# newer Galaxy instances can be used with older Galaxy
# instances if they do no include multiple input
# tools. This should be removed at some point. Mirrored
# hack in _workflow_from_raw_description should never be removed so
# existing workflow exports continue to function.
for input_name, input_conn in dict(input_conn_dict).items():
if len(input_conn) == 1:
input_conn_dict[input_name] = input_conn[0]
step_dict['input_connections'] = input_conn_dict
# Position
step_dict['position'] = step.position
# Add to return value
data['steps'][step.order_index] = step_dict
return data
def _workflow_to_dict_instance(self, stored, workflow, legacy=True):
encode = self.app.security.encode_id
sa_session = self.app.model.context
item = stored.to_dict(view='element', value_mapper={'id': encode})
item['name'] = workflow.name
item['url'] = url_for('workflow', id=item['id'])
item['owner'] = stored.user.username
inputs = {}
for step in workflow.input_steps:
step_type = step.type
step_label = step.label or step.tool_inputs.get('name')
if step_label:
label = step_label
elif step_type == "data_input":
label = "Input Dataset"
elif step_type == "data_collection_input":
label = "Input Dataset Collection"
elif step_type == 'parameter_input':
label = "Input Parameter"
else:
raise ValueError(f"Invalid step_type {step_type}")
if legacy:
index = step.id
else:
index = step.order_index
step_uuid = str(step.uuid) if step.uuid else None
inputs[index] = {'label': label, 'value': '', 'uuid': step_uuid}
item['inputs'] = inputs
item['annotation'] = self.get_item_annotation_str(sa_session, stored.user, stored)
item['license'] = workflow.license
item['creator'] = workflow.creator_metadata
steps = {}
steps_to_order_index = {}
for step in workflow.steps:
steps_to_order_index[step.id] = step.order_index
for step in workflow.steps:
step_id = step.id if legacy else step.order_index
step_type = step.type
step_dict = {'id': step_id,
'type': step_type,
'tool_id': step.tool_id,
'tool_version': step.tool_version,
'annotation': self.get_item_annotation_str(sa_session, stored.user, step),
'tool_inputs': step.tool_inputs,
'input_steps': {}}
if step_type == 'subworkflow':
del step_dict['tool_id']
del step_dict['tool_version']
del step_dict['tool_inputs']
step_dict['workflow_id'] = encode(step.subworkflow.id)
for conn in step.input_connections:
step_id = step.id if legacy else step.order_index
source_id = conn.output_step_id
source_step = source_id if legacy else steps_to_order_index[source_id]
step_dict['input_steps'][conn.input_name] = {'source_step': source_step,
'step_output': conn.output_name}
steps[step_id] = step_dict
item['steps'] = steps
return item
def __walk_step_dicts(self, data):
""" Walk over the supplied step dictionaries and return them in a way
designed to preserve step order when possible.
"""
supplied_steps = data['steps']
# Try to iterate through imported workflow in such a way as to
# preserve step order.
step_indices = list(supplied_steps.keys())
try:
step_indices = sorted(step_indices, key=int)
except ValueError:
# to defensive, were these ever or will they ever not be integers?
pass
discovered_labels = set()
discovered_uuids = set()
discovered_output_labels = set()
discovered_output_uuids = set()
# First pass to build step objects and populate basic values
for step_index in step_indices:
step_dict = supplied_steps[step_index]
uuid = step_dict.get("uuid", None)
if uuid and uuid != "None":
if uuid in discovered_uuids:
raise exceptions.DuplicatedIdentifierException("Duplicate step UUID in request.")
discovered_uuids.add(uuid)
label = step_dict.get("label", None)
if label:
if label in discovered_labels:
raise exceptions.DuplicatedIdentifierException("Duplicated step label in request.")
discovered_labels.add(label)
if 'workflow_outputs' in step_dict:
outputs = step_dict['workflow_outputs']
# outputs may be list of name (deprecated legacy behavior)
# or dictionary of names to {uuid: <uuid>, label: <label>}
if isinstance(outputs, dict):
for output_name in outputs:
output_dict = outputs[output_name]
output_label = output_dict.get("label", None)
if output_label:
if label in discovered_output_labels:
raise exceptions.DuplicatedIdentifierException("Duplicated workflow output label in request.")
discovered_output_labels.add(label)
output_uuid = step_dict.get("output_uuid", None)
if output_uuid:
if output_uuid in discovered_output_uuids:
raise exceptions.DuplicatedIdentifierException("Duplicate workflow output UUID in request.")
discovered_output_uuids.add(uuid)
yield step_dict
def __load_subworkflows(self, trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=False):
step_type = step_dict.get("type", None)
if step_type == "subworkflow":
subworkflow = self.__load_subworkflow_from_step_dict(
trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=dry_run
)
step_dict["subworkflow"] = subworkflow
def __module_from_dict(self, trans, steps, steps_by_external_id, step_dict, **kwds):
""" Create a WorkflowStep model object and corresponding module
representing type-specific functionality from the incoming dictionary.
"""
dry_run = kwds.get("dry_run", False)
step = model.WorkflowStep()
step.position = step_dict.get('position', model.WorkflowStep.DEFAULT_POSITION)
if step_dict.get("uuid", None) and step_dict['uuid'] != "None":
step.uuid = step_dict["uuid"]
if "label" in step_dict:
step.label = step_dict["label"]
module = module_factory.from_dict(trans, step_dict, detached=dry_run, **kwds)
self.__set_default_label(step, module, step_dict.get('tool_state'))
module.save_to_step(step, detached=dry_run)
annotation = step_dict.get('annotation')
if annotation:
annotation = sanitize_html(annotation)
sa_session = None if dry_run else trans.sa_session
self.add_item_annotation(sa_session, trans.get_user(), step, annotation)
# Stick this in the step temporarily
step.temp_input_connections = step_dict.get('input_connections', {})
# Create the model class for the step
steps.append(step)
external_id = step_dict["id"]
steps_by_external_id[external_id] = step
if 'workflow_outputs' in step_dict:
workflow_outputs = step_dict['workflow_outputs']
found_output_names = set()
for workflow_output in workflow_outputs:
# Allow workflow outputs as list of output_names for backward compatibility.
if not isinstance(workflow_output, dict):
workflow_output = {"output_name": workflow_output}
output_name = workflow_output["output_name"]
if output_name in found_output_names:
raise exceptions.ObjectAttributeInvalidException(f"Duplicate workflow outputs with name [{output_name}] found.")
if not output_name:
raise exceptions.ObjectAttributeInvalidException("Workflow output with empty name encountered.")
found_output_names.add(output_name)
uuid = workflow_output.get("uuid", None)
label = workflow_output.get("label", None)
m = step.create_or_update_workflow_output(
output_name=output_name,
uuid=uuid,
label=label,
)
if not dry_run:
trans.sa_session.add(m)
if "in" in step_dict:
for input_name, input_dict in step_dict["in"].items():
step_input = step.get_or_add_input(input_name)
NO_DEFAULT_DEFINED = object()
default = input_dict.get("default", NO_DEFAULT_DEFINED)
if default is not NO_DEFAULT_DEFINED:
step_input.default_value = default
step_input.default_value_set = True
if dry_run and step in trans.sa_session:
trans.sa_session.expunge(step)
return module, step
def __load_subworkflow_from_step_dict(self, trans, step_dict, subworkflow_id_map, workflow_state_resolution_options, dry_run=False):
embedded_subworkflow = step_dict.get("subworkflow", None)
subworkflow_id = step_dict.get("content_id", None)
if embedded_subworkflow and subworkflow_id:
raise Exception("Subworkflow step defines both subworkflow and content_id, only one may be specified.")
if not embedded_subworkflow and not subworkflow_id:
raise Exception("Subworkflow step must define either subworkflow or content_id.")
if embedded_subworkflow:
assert not dry_run
subworkflow = self.__build_embedded_subworkflow(trans, embedded_subworkflow, workflow_state_resolution_options)
elif subworkflow_id_map is not None:
assert not dry_run
# Interpret content_id as a workflow local thing.
subworkflow = subworkflow_id_map[subworkflow_id[1:]]
else:
subworkflow = self.app.workflow_manager.get_owned_workflow(
trans, subworkflow_id
)
return subworkflow
def __build_embedded_subworkflow(self, trans, data, workflow_state_resolution_options):
raw_workflow_description = self.ensure_raw_description(data)
subworkflow = self.build_workflow_from_raw_description(
trans, raw_workflow_description, workflow_state_resolution_options, hidden=True
).workflow
return subworkflow
def __connect_workflow_steps(self, steps, steps_by_external_id, dry_run):
""" Second pass to deal with connections between steps.
Create workflow connection objects using externally specified ids
using during creation or update.
"""
for step in steps:
# Input connections
for input_name, conn_list in step.temp_input_connections.items():
if not conn_list:
continue
if not isinstance(conn_list, list): # Older style singleton connection
conn_list = [conn_list]
for conn_dict in conn_list:
if 'output_name' not in conn_dict or 'id' not in conn_dict:
template = "Invalid connection [%s] - must be dict with output_name and id fields."
message = template % conn_dict
raise exceptions.MessageException(message)
external_id = conn_dict['id']
if external_id not in steps_by_external_id:
raise KeyError(f"Failed to find external id {external_id} in {steps_by_external_id.keys()}")
output_step = steps_by_external_id[external_id]
output_name = conn_dict["output_name"]
input_subworkflow_step_index = conn_dict.get('input_subworkflow_step_id', None)
if dry_run:
input_subworkflow_step_index = None
step.add_connection(input_name, output_name, output_step, input_subworkflow_step_index)
del step.temp_input_connections
def __set_default_label(self, step, module, state):
""" Previously data input modules had a `name` attribute to rename individual steps. Here, this value is transferred
to the actual `label` attribute which is available for all module types, unique, and mapped to its own database column.
"""
if not module.label and module.type in ['data_input', 'data_collection_input']:
new_state = safe_loads(state)
default_label = new_state.get('name')
if default_label and util.unicodify(default_label).lower() not in ['input dataset', 'input dataset collection']:
step.label = module.label = default_label
def do_refactor(self, trans, stored_workflow, refactor_request):
"""Apply supplied actions to stored_workflow.latest_workflow to build a new version.
"""
workflow = stored_workflow.latest_workflow
as_dict = self._workflow_to_dict_export(trans, stored_workflow, workflow=workflow, internal=True)
raw_workflow_description = self.normalize_workflow_format(trans, as_dict)
workflow_update_options = WorkflowUpdateOptions(
fill_defaults=False,
allow_missing_tools=True,
dry_run=refactor_request.dry_run,
)
module_injector = WorkflowModuleInjector(trans)
refactor_executor = WorkflowRefactorExecutor(raw_workflow_description, workflow, module_injector)
action_executions = refactor_executor.refactor(refactor_request)
refactored_workflow, errors = self.update_workflow_from_raw_description(
trans,
stored_workflow,
raw_workflow_description,
workflow_update_options,
)
# errors could be three things:
# - we allow missing tools so it won't be that.
# - might have cycles or might have state validation issues, but it still saved...
# so this is really more of a warning - we disregard it the other two places
# it is used also. These same messages will appear in the dictified version we
# we send back anyway
return refactored_workflow, action_executions
def refactor(self, trans, stored_workflow, refactor_request):
refactored_workflow, action_executions = self.do_refactor(trans, stored_workflow, refactor_request)
return RefactorResponse(
action_executions=action_executions,
workflow=self.workflow_to_dict(trans, refactored_workflow.stored_workflow, style=refactor_request.style),
dry_run=refactor_request.dry_run,
)
def get_all_tool_ids(self, workflow):
tool_ids = set()
for step in workflow.steps:
if step.type == 'tool':
if step.tool_id:
tool_ids.add(step.tool_id)
elif step.type == 'subworkflow':
tool_ids.update(self.get_all_tool_ids(step.subworkflow))
return tool_ids
class RefactorRequest(RefactorActions):
style: str = "export"
class RefactorResponse(BaseModel):
action_executions: List[RefactorActionExecution]
workflow: dict
dry_run: bool
class Config:
# Workflows have dictionaries with integer keys, which pydantic doesn't coerce to strings.
# Integer object keys aren't valid JSON, so the client fails.
json_dumps = safe_dumps
class WorkflowStateResolutionOptions(BaseModel):
# fill in default tool state when updating, may change tool_state
fill_defaults: bool = False
# If True, assume all tool state coming from generated form instead of potentially simpler json stored in DB/exported
from_tool_form: bool = False
# If False, allow running with less exact tool versions
exact_tools: bool = True
class WorkflowUpdateOptions(WorkflowStateResolutionOptions):
# Only used internally, don't set. If using the API assume updating the workflows
# representation with name or annotation for instance, updates the corresponding
# stored workflow
update_stored_workflow_attributes: bool = True
allow_missing_tools: bool = False
dry_run: bool = False
# Workflow update options but with some different defaults - we allow creating
# workflows with missing tools by default but not updating.
class WorkflowCreateOptions(WorkflowStateResolutionOptions):
import_tools: bool = False
publish: bool = False
# true or false, effectively defaults to ``publish`` if None/unset
importable: Optional[bool] = None
# following are install options, only used if import_tools is true
install_repository_dependencies: bool = False
install_resolver_dependencies: bool = False
install_tool_dependencies: bool = False
new_tool_panel_section_label: str = ''
tool_panel_section_id: str = ''
tool_panel_section_mapping: Dict = {}
shed_tool_conf: Optional[str] = None
@property
def is_importable(self):
# if self.importable is None, use self.publish that has a default.
if self.importable is None:
return self.publish
else:
return self.importable
@property
def install_options(self):
return {
'install_repository_dependencies': self.install_repository_dependencies,
'install_resolver_dependencies': self.install_resolver_dependencies,
'install_tool_dependencies': self.install_tool_dependencies,
'new_tool_panel_section_label': self.new_tool_panel_section_label,
'tool_panel_section_id': self.tool_panel_section_id,
'tool_panel_section_mapping': self.tool_panel_section_mapping,
'shed_tool_conf': self.shed_tool_conf
}
class MissingToolsException(exceptions.MessageException):
def __init__(self, workflow, errors):
self.workflow = workflow
self.errors = errors
class RawWorkflowDescription:
def __init__(self, as_dict, workflow_path=None):
self.as_dict = as_dict
self.workflow_path = workflow_path
class Format2ConverterGalaxyInterface(ImporterGalaxyInterface):
def import_workflow(self, workflow, **kwds):
raise NotImplementedError("Direct format 2 import of nested workflows is not yet implemented, use bioblend client.")
|
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls.base import reverse
from django.views.generic import ListView
from django.core.mail import send_mail
from . models import Post, Comment
from . form import EmailForm, CommentForm
def post_list(request):
posts = Post.objects.all()
return render(
request,
'bookblog/list.html',
{
'posts': posts,
'title': 'all posts',
}
)
class ListViewPublish(ListView):
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['title'] = 'My Title'
return ctx
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'bookblog/list.html'
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
publish__year=year, publish__month=month, publish__day=day)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
return HttpResponseRedirect(reverse('bookblog:post_detail', args=[year, month, day, post.slug]))
else:
comment_form = CommentForm()
return render(
request,
'bookblog/detail.html',
{
'post': post,
'title': 'detail posts',
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form,
}
)
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id)
send = False
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(
post.get_absolute_url()
)
subject = f"{cd["name"]} recomend to read {post.title}"
message = f"Read: {post.title} at {post_url}"
send_mail(subject, message, 'korea60@abv.bg', [cd['to']])
send = True
# return HttpResponse("Email send successfull")
else:
form = EmailForm()
return render(request, 'bookblog/share.html', {'post': post, 'form': form, 'send': send})
| from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls.base import reverse
from django.views.generic import ListView
from django.core.mail import send_mail
from . models import Post, Comment
from . form import EmailForm, CommentForm
def post_list(request):
posts = Post.objects.all()
return render(
request,
'bookblog/list.html',
{
'posts': posts,
'title': 'all posts',
}
)
class ListViewPublish(ListView):
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['title'] = 'My Title'
return ctx
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'bookblog/list.html'
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
publish__year=year, publish__month=month, publish__day=day)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
return HttpResponseRedirect(reverse('bookblog:post_detail', args=[year, month, day, post.slug]))
else:
comment_form = CommentForm()
return render(
request,
'bookblog/detail.html',
{
'post': post,
'title': 'detail posts',
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form,
}
)
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id)
send = False
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(
post.get_absolute_url()
)
subject = f"{cd['name']} recomend to read {post.title}"
message = f"Read: {post.title} at {post_url}"
send_mail(subject, message, 'korea60@abv.bg', [cd['to']])
send = True
# return HttpResponse("Email send successfull")
else:
form = EmailForm()
return render(request, 'bookblog/share.html', {'post': post, 'form': form, 'send': send})
|
from datetime import datetime
CDN_BASE_URL = "https://pod-cdn.timbrook.tech"
def populate_episode(doc, data):
item = doc.new_tag("item")
bare_tags = {
"title": data["name"],
"itunes:duration": data["duration"],
"description": data["description"],
"itunes:subtitle": data["description"],
"itunes:summary": data["description"],
}
for t, v in bare_tags.items():
tag = doc.new_tag(t)
tag.string = v if v is not None else ""
item.append(tag)
guid = doc.new_tag("guid", isPermaLink="false")
guid.string = data["storage_key"]
item.append(guid)
url = f"{CDN_BASE_URL}/{data["storage_key"]}"
item.append(doc.new_tag("enclosure", url=url, type="audio/mpeg"))
return item
def populate_podcast(doc, channel, podcast):
# basics
bare_tags = {
"title": podcast["name"],
"description": podcast["description"],
"language": "en-us",
"docs": "http://www.rssboard.org/rss-specification",
"generator": "myself",
"lastBuildDate": datetime.now().ctime(),
}
for t, v in bare_tags.items():
tag = doc.new_tag(t)
tag.string = v
channel.append(tag)
# Links
link = podcast["url"]
lt = doc.new_tag("link")
lt.string = link
channel.append(lt)
lta = doc.new_tag("atom:link", href=link, rel="self")
channel.append(lta)
# iTunes category and friends
cat = doc.new_tag("itunes:category", text="Technology")
cat.append(doc.new_tag("itunes:category", text="Podcasting"))
channel.append(cat)
channel.append(
doc.new_tag(
"itunes:image",
href="https://timbrook-podcast.sfo2.digitaloceanspaces.com/podcover.png",
)
)
expl = doc.new_tag("itunes:explicit")
expl.string = "yes"
channel.append(expl)
# Episodes
for ep in podcast["episodes"]:
channel.append(populate_episode(doc, ep))
return channel
| from datetime import datetime
CDN_BASE_URL = "https://pod-cdn.timbrook.tech"
def populate_episode(doc, data):
item = doc.new_tag("item")
bare_tags = {
"title": data["name"],
"itunes:duration": data["duration"],
"description": data["description"],
"itunes:subtitle": data["description"],
"itunes:summary": data["description"],
}
for t, v in bare_tags.items():
tag = doc.new_tag(t)
tag.string = v if v is not None else ""
item.append(tag)
guid = doc.new_tag("guid", isPermaLink="false")
guid.string = data["storage_key"]
item.append(guid)
url = f"{CDN_BASE_URL}/{data['storage_key']}"
item.append(doc.new_tag("enclosure", url=url, type="audio/mpeg"))
return item
def populate_podcast(doc, channel, podcast):
# basics
bare_tags = {
"title": podcast["name"],
"description": podcast["description"],
"language": "en-us",
"docs": "http://www.rssboard.org/rss-specification",
"generator": "myself",
"lastBuildDate": datetime.now().ctime(),
}
for t, v in bare_tags.items():
tag = doc.new_tag(t)
tag.string = v
channel.append(tag)
# Links
link = podcast["url"]
lt = doc.new_tag("link")
lt.string = link
channel.append(lt)
lta = doc.new_tag("atom:link", href=link, rel="self")
channel.append(lta)
# iTunes category and friends
cat = doc.new_tag("itunes:category", text="Technology")
cat.append(doc.new_tag("itunes:category", text="Podcasting"))
channel.append(cat)
channel.append(
doc.new_tag(
"itunes:image",
href="https://timbrook-podcast.sfo2.digitaloceanspaces.com/podcover.png",
)
)
expl = doc.new_tag("itunes:explicit")
expl.string = "yes"
channel.append(expl)
# Episodes
for ep in podcast["episodes"]:
channel.append(populate_episode(doc, ep))
return channel
|
from functools import partial
from typing import Dict, List, Optional, Tuple
from qtpy import QtCore, QtGui, QtWidgets
from .signal import Signal
from .utils import is_concrete_schema, iter_layout_widgets, state_property
from ...._qt.widgets.qt_plugin_sorter import QtPluginSorter
class SchemaWidgetMixin:
on_changed = Signal()
VALID_COLOUR = '#ffffff'
INVALID_COLOUR = '#f6989d'
def __init__(
self,
schema: dict,
ui_schema: dict,
# note: need to figure out how the following works
widget_builder: 'WidgetBuilder', # noqa: F821
**kwargs,
):
super().__init__(**kwargs)
self.schema = schema
self.ui_schema = ui_schema
self.widget_builder = widget_builder
self.on_changed.connect(lambda _: self.clear_error())
self.configure()
def configure(self):
pass
@state_property
def state(self):
raise NotImplementedError(f"{self.__class__.__name__}.state")
@state.setter
def state(self, state):
raise NotImplementedError(f"{self.__class__.__name__}.state")
def handle_error(self, path: Tuple[str], err: Exception):
if path:
raise ValueError("Cannot handle nested error by default")
self._set_valid_state(err)
def clear_error(self):
self._set_valid_state(None)
def _set_valid_state(self, error: Exception = None):
palette = self.palette()
colour = QtGui.QColor()
colour.setNamedColor(
self.VALID_COLOUR if error is None else self.INVALID_COLOUR
)
palette.setColor(self.backgroundRole(), colour)
self.setPalette(palette)
self.setToolTip("" if error is None else error.message) # TODO
class TextSchemaWidget(SchemaWidgetMixin, QtWidgets.QLineEdit):
def configure(self):
self.textChanged.connect(self.on_changed.emit)
@state_property
def state(self) -> str:
return str(self.text())
@state.setter
def state(self, state: str):
self.setText(state)
class PasswordWidget(TextSchemaWidget):
def configure(self):
super().configure()
self.setEchoMode(self.Password)
class TextAreaSchemaWidget(SchemaWidgetMixin, QtWidgets.QTextEdit):
@state_property
def state(self) -> str:
return str(self.toPlainText())
@state.setter
def state(self, state: str):
self.setPlainText(state)
def configure(self):
self.textChanged.connect(lambda: self.on_changed.emit(self.state))
class CheckboxSchemaWidget(SchemaWidgetMixin, QtWidgets.QCheckBox):
@state_property
def state(self) -> bool:
return self.isChecked()
@state.setter
def state(self, checked: bool):
self.setChecked(checked)
def configure(self):
self.stateChanged.connect(lambda _: self.on_changed.emit(self.state))
class SpinDoubleSchemaWidget(SchemaWidgetMixin, QtWidgets.QDoubleSpinBox):
@state_property
def state(self) -> float:
return self.value()
@state.setter
def state(self, state: float):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
class PluginWidget(SchemaWidgetMixin, QtPluginSorter):
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
return None
# self.setValue(state)
def configure(self):
self.hook_list.order_changed.connect(self.on_changed.emit)
class SpinSchemaWidget(SchemaWidgetMixin, QtWidgets.QSpinBox):
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
class IntegerRangeSchemaWidget(SchemaWidgetMixin, QtWidgets.QSlider):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(
schema, ui_schema, widget_builder, orientation=QtCore.Qt.Horizontal
)
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
minimum = 0
if "minimum" in self.schema:
minimum = self.schema["minimum"]
if self.schema.get("exclusiveMinimum"):
minimum += 1
maximum = 0
if "maximum" in self.schema:
maximum = self.schema["maximum"]
if self.schema.get("exclusiveMaximum"):
maximum -= 1
if "multipleOf" in self.schema:
self.setTickInterval(self.schema["multipleOf"])
self.setSingleStep(self.schema["multipleOf"])
self.setTickPosition(self.TicksBothSides)
self.setRange(minimum, maximum)
class QColorButton(QtWidgets.QPushButton):
"""Color picker widget QPushButton subclass.
Implementation derived from https://martinfitzpatrick.name/article/qcolorbutton-a-color-selector-tool-for-pyqt/
"""
colorChanged = QtCore.Signal()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._color = None
self.pressed.connect(self.onColorPicker)
def color(self):
return self._color
def setColor(self, color):
if color != self._color:
self._color = color
self.colorChanged.emit()
if self._color:
self.setStyleSheet("background-color: %s;" % self._color)
else:
self.setStyleSheet("")
def onColorPicker(self):
dlg = QtWidgets.QColorDialog(self)
if self._color:
dlg.setCurrentColor(QtGui.QColor(self._color))
if dlg.exec_():
self.setColor(dlg.currentColor().name())
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
self.setColor(None)
return super().mousePressEvent(event)
class ColorSchemaWidget(SchemaWidgetMixin, QColorButton):
"""Widget representation of a string with the 'color' format keyword."""
def configure(self):
self.colorChanged.connect(lambda: self.on_changed.emit(self.state))
@state_property
def state(self) -> str:
return self.color()
@state.setter
def state(self, data: str):
self.setColor(data)
class FilepathSchemaWidget(SchemaWidgetMixin, QtWidgets.QWidget):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(schema, ui_schema, widget_builder)
layout = QtWidgets.QHBoxLayout()
self.setLayout(layout)
self.path_widget = QtWidgets.QLineEdit()
self.button_widget = QtWidgets.QPushButton("Browse")
layout.addWidget(self.path_widget)
layout.addWidget(self.button_widget)
self.button_widget.clicked.connect(self._on_clicked)
self.path_widget.textChanged.connect(self.on_changed.emit)
def _on_clicked(self, flag):
path, filter = QtWidgets.QFileDialog.getOpenFileName()
self.path_widget.setText(path)
@state_property
def state(self) -> str:
return self.path_widget.text()
@state.setter
def state(self, state: str):
self.path_widget.setText(state)
class ArrayControlsWidget(QtWidgets.QWidget):
on_delete = QtCore.Signal()
on_move_up = QtCore.Signal()
on_move_down = QtCore.Signal()
def __init__(self):
super().__init__()
style = self.style()
self.up_button = QtWidgets.QPushButton()
self.up_button.setIcon(style.standardIcon(QtWidgets.QStyle.SP_ArrowUp))
self.up_button.clicked.connect(lambda _: self.on_move_up.emit())
self.delete_button = QtWidgets.QPushButton()
self.delete_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_DialogCancelButton)
)
self.delete_button.clicked.connect(lambda _: self.on_delete.emit())
self.down_button = QtWidgets.QPushButton()
self.down_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_ArrowDown)
)
self.down_button.clicked.connect(lambda _: self.on_move_down.emit())
group_layout = QtWidgets.QHBoxLayout()
self.setLayout(group_layout)
group_layout.addWidget(self.up_button)
group_layout.addWidget(self.down_button)
group_layout.addWidget(self.delete_button)
group_layout.setSpacing(0)
group_layout.addStretch(0)
class ArrayRowWidget(QtWidgets.QWidget):
def __init__(
self, widget: QtWidgets.QWidget, controls: ArrayControlsWidget
):
super().__init__()
layout = QtWidgets.QHBoxLayout()
layout.addWidget(widget)
layout.addWidget(controls)
self.setLayout(layout)
self.widget = widget
self.controls = controls
class ArraySchemaWidget(SchemaWidgetMixin, QtWidgets.QWidget):
@property
def rows(self) -> List[ArrayRowWidget]:
return [*iter_layout_widgets(self.array_layout)]
@state_property
def state(self) -> list:
return [r.widget.state for r in self.rows]
@state.setter
def state(self, state: list):
for row in self.rows:
self._remove_item(row)
for item in state:
self._add_item(item)
self.on_changed.emit(self.state)
def handle_error(self, path: Tuple[str], err: Exception):
index, *tail = path
self.rows[index].widget.handle_error(tail, err)
def configure(self):
layout = QtWidgets.QVBoxLayout()
style = self.style()
self.add_button = QtWidgets.QPushButton()
self.add_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_FileIcon)
)
self.add_button.clicked.connect(lambda _: self.add_item())
self.array_layout = QtWidgets.QVBoxLayout()
array_widget = QtWidgets.QWidget(self)
array_widget.setLayout(self.array_layout)
self.on_changed.connect(self._on_updated)
layout.addWidget(self.add_button)
layout.addWidget(array_widget)
self.setLayout(layout)
def _on_updated(self, state):
# Update add button
disabled = self.next_item_schema is None
self.add_button.setEnabled(not disabled)
previous_row = None
for i, row in enumerate(self.rows):
if previous_row:
can_exchange_previous = (
previous_row.widget.schema == row.widget.schema
)
row.controls.up_button.setEnabled(can_exchange_previous)
previous_row.controls.down_button.setEnabled(
can_exchange_previous
)
else:
row.controls.up_button.setEnabled(False)
row.controls.delete_button.setEnabled(not self.is_fixed_schema(i))
previous_row = row
if previous_row:
previous_row.controls.down_button.setEnabled(False)
def is_fixed_schema(self, index: int) -> bool:
schema = self.schema['items']
if isinstance(schema, dict):
return False
return index < len(schema)
@property
def next_item_schema(self) -> Optional[dict]:
item_schema = self.schema['items']
if isinstance(item_schema, dict):
return item_schema
index = len(self.rows)
try:
item_schema = item_schema[index]
except IndexError:
item_schema = self.schema.get("additionalItems", {})
if isinstance(item_schema, bool):
return None
if not is_concrete_schema(item_schema):
return None
return item_schema
def add_item(self, item_state=None):
self._add_item(item_state)
self.on_changed.emit(self.state)
def remove_item(self, row: ArrayRowWidget):
self._remove_item(row)
self.on_changed.emit(self.state)
def move_item_up(self, row: ArrayRowWidget):
index = self.rows.index(row)
self.array_layout.insertWidget(max(0, index - 1), row)
self.on_changed.emit(self.state)
def move_item_down(self, row: ArrayRowWidget):
index = self.rows.index(row)
self.array_layout.insertWidget(min(len(self.rows) - 1, index + 1), row)
self.on_changed.emit(self.state)
def _add_item(self, item_state=None):
item_schema = self.next_item_schema
# Create widget
item_ui_schema = self.ui_schema.get("items", {})
widget = self.widget_builder.create_widget(
item_schema, item_ui_schema, item_state
)
controls = ArrayControlsWidget()
# Create row
row = ArrayRowWidget(widget, controls)
self.array_layout.addWidget(row)
# Setup callbacks
widget.on_changed.connect(partial(self.widget_on_changed, row))
controls.on_delete.connect(partial(self.remove_item, row))
controls.on_move_up.connect(partial(self.move_item_up, row))
controls.on_move_down.connect(partial(self.move_item_down, row))
return row
def _remove_item(self, row: ArrayRowWidget):
self.array_layout.removeWidget(row)
row.deleteLater()
def widget_on_changed(self, row: ArrayRowWidget, value):
self.state[self.rows.index(row)] = value
self.on_changed.emit(self.state)
class ObjectSchemaWidget(SchemaWidgetMixin, QtWidgets.QGroupBox):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(schema, ui_schema, widget_builder)
self.widgets = self.populate_from_schema(
schema, ui_schema, widget_builder
)
@state_property
def state(self) -> dict:
return {k: w.state for k, w in self.widgets.items()}
@state.setter
def state(self, state: dict):
for name, value in state.items():
self.widgets[name].state = value
def handle_error(self, path: Tuple[str], err: Exception):
name, *tail = path
self.widgets[name].handle_error(tail, err)
def widget_on_changed(self, name: str, value):
self.state[name] = value
self.on_changed.emit(self.state)
def populate_from_schema(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
) -> Dict[str, QtWidgets.QWidget]:
layout = QtWidgets.QFormLayout()
self.setLayout(layout)
layout.setAlignment(QtCore.Qt.AlignTop)
self.setFlat(False)
if 'title' in schema:
self.setTitle(schema['title'])
if 'description' in schema:
self.setToolTip(schema['description'])
# Populate rows
widgets = {}
layout.setFieldGrowthPolicy(QtWidgets.QFormLayout.FieldGrowthPolicy(1))
for name, sub_schema in schema['properties'].items():
sub_ui_schema = ui_schema.get(name, {})
widget = widget_builder.create_widget(
sub_schema, sub_ui_schema
) # TODO onchanged
widget.on_changed.connect(partial(self.widget_on_changed, name))
label = sub_schema.get("title", name)
layout.addRow(label, widget)
widgets[name] = widget
return widgets
class EnumSchemaWidget(SchemaWidgetMixin, QtWidgets.QComboBox):
@state_property
def state(self):
return self.itemData(self.currentIndex())
@state.setter
def state(self, value):
index = self.findData(value)
if index == -1:
raise ValueError(value)
self.setCurrentIndex(index)
def configure(self):
options = self.schema["enum"]
for i, opt in enumerate(options):
self.addItem(str(opt))
self.setItemData(i, opt)
self.currentIndexChanged.connect(
lambda _: self.on_changed.emit(self.state)
)
def _index_changed(self, index: int):
self.on_changed.emit(self.state)
class FormWidget(QtWidgets.QWidget):
def __init__(self, widget: SchemaWidgetMixin):
super().__init__()
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
self.error_widget = QtWidgets.QGroupBox()
self.error_widget.setTitle("Errors")
self.error_layout = QtWidgets.QVBoxLayout()
self.error_widget.setLayout(self.error_layout)
self.error_widget.hide()
layout.addWidget(self.error_widget)
layout.addWidget(widget)
self.widget = widget
def display_errors(self, errors: List[Exception]):
self.error_widget.show()
layout = self.error_widget.layout()
while True:
item = layout.takeAt(0)
if not item:
break
item.widget().deleteLater()
for err in errors:
widget = QtWidgets.QLabel(
f"<b>.{".".join(err.path)}</b> {err.message}"
)
layout.addWidget(widget)
def clear_errors(self):
self.error_widget.hide()
class MyMainWindow(QtWidgets.QDialog):
def __init__(self, widget: SchemaWidgetMixin, parent=None):
super().__init__(parent)
self.form_widget = FormWidget(widget)
self.setWindowTitle("Preferences")
self.widget = self.form_widget
self.setCentralWidget(self.widget)
| from functools import partial
from typing import Dict, List, Optional, Tuple
from qtpy import QtCore, QtGui, QtWidgets
from .signal import Signal
from .utils import is_concrete_schema, iter_layout_widgets, state_property
from ...._qt.widgets.qt_plugin_sorter import QtPluginSorter
class SchemaWidgetMixin:
on_changed = Signal()
VALID_COLOUR = '#ffffff'
INVALID_COLOUR = '#f6989d'
def __init__(
self,
schema: dict,
ui_schema: dict,
# note: need to figure out how the following works
widget_builder: 'WidgetBuilder', # noqa: F821
**kwargs,
):
super().__init__(**kwargs)
self.schema = schema
self.ui_schema = ui_schema
self.widget_builder = widget_builder
self.on_changed.connect(lambda _: self.clear_error())
self.configure()
def configure(self):
pass
@state_property
def state(self):
raise NotImplementedError(f"{self.__class__.__name__}.state")
@state.setter
def state(self, state):
raise NotImplementedError(f"{self.__class__.__name__}.state")
def handle_error(self, path: Tuple[str], err: Exception):
if path:
raise ValueError("Cannot handle nested error by default")
self._set_valid_state(err)
def clear_error(self):
self._set_valid_state(None)
def _set_valid_state(self, error: Exception = None):
palette = self.palette()
colour = QtGui.QColor()
colour.setNamedColor(
self.VALID_COLOUR if error is None else self.INVALID_COLOUR
)
palette.setColor(self.backgroundRole(), colour)
self.setPalette(palette)
self.setToolTip("" if error is None else error.message) # TODO
class TextSchemaWidget(SchemaWidgetMixin, QtWidgets.QLineEdit):
def configure(self):
self.textChanged.connect(self.on_changed.emit)
@state_property
def state(self) -> str:
return str(self.text())
@state.setter
def state(self, state: str):
self.setText(state)
class PasswordWidget(TextSchemaWidget):
def configure(self):
super().configure()
self.setEchoMode(self.Password)
class TextAreaSchemaWidget(SchemaWidgetMixin, QtWidgets.QTextEdit):
@state_property
def state(self) -> str:
return str(self.toPlainText())
@state.setter
def state(self, state: str):
self.setPlainText(state)
def configure(self):
self.textChanged.connect(lambda: self.on_changed.emit(self.state))
class CheckboxSchemaWidget(SchemaWidgetMixin, QtWidgets.QCheckBox):
@state_property
def state(self) -> bool:
return self.isChecked()
@state.setter
def state(self, checked: bool):
self.setChecked(checked)
def configure(self):
self.stateChanged.connect(lambda _: self.on_changed.emit(self.state))
class SpinDoubleSchemaWidget(SchemaWidgetMixin, QtWidgets.QDoubleSpinBox):
@state_property
def state(self) -> float:
return self.value()
@state.setter
def state(self, state: float):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
class PluginWidget(SchemaWidgetMixin, QtPluginSorter):
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
return None
# self.setValue(state)
def configure(self):
self.hook_list.order_changed.connect(self.on_changed.emit)
class SpinSchemaWidget(SchemaWidgetMixin, QtWidgets.QSpinBox):
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
class IntegerRangeSchemaWidget(SchemaWidgetMixin, QtWidgets.QSlider):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(
schema, ui_schema, widget_builder, orientation=QtCore.Qt.Horizontal
)
@state_property
def state(self) -> int:
return self.value()
@state.setter
def state(self, state: int):
self.setValue(state)
def configure(self):
self.valueChanged.connect(self.on_changed.emit)
minimum = 0
if "minimum" in self.schema:
minimum = self.schema["minimum"]
if self.schema.get("exclusiveMinimum"):
minimum += 1
maximum = 0
if "maximum" in self.schema:
maximum = self.schema["maximum"]
if self.schema.get("exclusiveMaximum"):
maximum -= 1
if "multipleOf" in self.schema:
self.setTickInterval(self.schema["multipleOf"])
self.setSingleStep(self.schema["multipleOf"])
self.setTickPosition(self.TicksBothSides)
self.setRange(minimum, maximum)
class QColorButton(QtWidgets.QPushButton):
"""Color picker widget QPushButton subclass.
Implementation derived from https://martinfitzpatrick.name/article/qcolorbutton-a-color-selector-tool-for-pyqt/
"""
colorChanged = QtCore.Signal()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._color = None
self.pressed.connect(self.onColorPicker)
def color(self):
return self._color
def setColor(self, color):
if color != self._color:
self._color = color
self.colorChanged.emit()
if self._color:
self.setStyleSheet("background-color: %s;" % self._color)
else:
self.setStyleSheet("")
def onColorPicker(self):
dlg = QtWidgets.QColorDialog(self)
if self._color:
dlg.setCurrentColor(QtGui.QColor(self._color))
if dlg.exec_():
self.setColor(dlg.currentColor().name())
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
self.setColor(None)
return super().mousePressEvent(event)
class ColorSchemaWidget(SchemaWidgetMixin, QColorButton):
"""Widget representation of a string with the 'color' format keyword."""
def configure(self):
self.colorChanged.connect(lambda: self.on_changed.emit(self.state))
@state_property
def state(self) -> str:
return self.color()
@state.setter
def state(self, data: str):
self.setColor(data)
class FilepathSchemaWidget(SchemaWidgetMixin, QtWidgets.QWidget):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(schema, ui_schema, widget_builder)
layout = QtWidgets.QHBoxLayout()
self.setLayout(layout)
self.path_widget = QtWidgets.QLineEdit()
self.button_widget = QtWidgets.QPushButton("Browse")
layout.addWidget(self.path_widget)
layout.addWidget(self.button_widget)
self.button_widget.clicked.connect(self._on_clicked)
self.path_widget.textChanged.connect(self.on_changed.emit)
def _on_clicked(self, flag):
path, filter = QtWidgets.QFileDialog.getOpenFileName()
self.path_widget.setText(path)
@state_property
def state(self) -> str:
return self.path_widget.text()
@state.setter
def state(self, state: str):
self.path_widget.setText(state)
class ArrayControlsWidget(QtWidgets.QWidget):
on_delete = QtCore.Signal()
on_move_up = QtCore.Signal()
on_move_down = QtCore.Signal()
def __init__(self):
super().__init__()
style = self.style()
self.up_button = QtWidgets.QPushButton()
self.up_button.setIcon(style.standardIcon(QtWidgets.QStyle.SP_ArrowUp))
self.up_button.clicked.connect(lambda _: self.on_move_up.emit())
self.delete_button = QtWidgets.QPushButton()
self.delete_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_DialogCancelButton)
)
self.delete_button.clicked.connect(lambda _: self.on_delete.emit())
self.down_button = QtWidgets.QPushButton()
self.down_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_ArrowDown)
)
self.down_button.clicked.connect(lambda _: self.on_move_down.emit())
group_layout = QtWidgets.QHBoxLayout()
self.setLayout(group_layout)
group_layout.addWidget(self.up_button)
group_layout.addWidget(self.down_button)
group_layout.addWidget(self.delete_button)
group_layout.setSpacing(0)
group_layout.addStretch(0)
class ArrayRowWidget(QtWidgets.QWidget):
def __init__(
self, widget: QtWidgets.QWidget, controls: ArrayControlsWidget
):
super().__init__()
layout = QtWidgets.QHBoxLayout()
layout.addWidget(widget)
layout.addWidget(controls)
self.setLayout(layout)
self.widget = widget
self.controls = controls
class ArraySchemaWidget(SchemaWidgetMixin, QtWidgets.QWidget):
@property
def rows(self) -> List[ArrayRowWidget]:
return [*iter_layout_widgets(self.array_layout)]
@state_property
def state(self) -> list:
return [r.widget.state for r in self.rows]
@state.setter
def state(self, state: list):
for row in self.rows:
self._remove_item(row)
for item in state:
self._add_item(item)
self.on_changed.emit(self.state)
def handle_error(self, path: Tuple[str], err: Exception):
index, *tail = path
self.rows[index].widget.handle_error(tail, err)
def configure(self):
layout = QtWidgets.QVBoxLayout()
style = self.style()
self.add_button = QtWidgets.QPushButton()
self.add_button.setIcon(
style.standardIcon(QtWidgets.QStyle.SP_FileIcon)
)
self.add_button.clicked.connect(lambda _: self.add_item())
self.array_layout = QtWidgets.QVBoxLayout()
array_widget = QtWidgets.QWidget(self)
array_widget.setLayout(self.array_layout)
self.on_changed.connect(self._on_updated)
layout.addWidget(self.add_button)
layout.addWidget(array_widget)
self.setLayout(layout)
def _on_updated(self, state):
# Update add button
disabled = self.next_item_schema is None
self.add_button.setEnabled(not disabled)
previous_row = None
for i, row in enumerate(self.rows):
if previous_row:
can_exchange_previous = (
previous_row.widget.schema == row.widget.schema
)
row.controls.up_button.setEnabled(can_exchange_previous)
previous_row.controls.down_button.setEnabled(
can_exchange_previous
)
else:
row.controls.up_button.setEnabled(False)
row.controls.delete_button.setEnabled(not self.is_fixed_schema(i))
previous_row = row
if previous_row:
previous_row.controls.down_button.setEnabled(False)
def is_fixed_schema(self, index: int) -> bool:
schema = self.schema['items']
if isinstance(schema, dict):
return False
return index < len(schema)
@property
def next_item_schema(self) -> Optional[dict]:
item_schema = self.schema['items']
if isinstance(item_schema, dict):
return item_schema
index = len(self.rows)
try:
item_schema = item_schema[index]
except IndexError:
item_schema = self.schema.get("additionalItems", {})
if isinstance(item_schema, bool):
return None
if not is_concrete_schema(item_schema):
return None
return item_schema
def add_item(self, item_state=None):
self._add_item(item_state)
self.on_changed.emit(self.state)
def remove_item(self, row: ArrayRowWidget):
self._remove_item(row)
self.on_changed.emit(self.state)
def move_item_up(self, row: ArrayRowWidget):
index = self.rows.index(row)
self.array_layout.insertWidget(max(0, index - 1), row)
self.on_changed.emit(self.state)
def move_item_down(self, row: ArrayRowWidget):
index = self.rows.index(row)
self.array_layout.insertWidget(min(len(self.rows) - 1, index + 1), row)
self.on_changed.emit(self.state)
def _add_item(self, item_state=None):
item_schema = self.next_item_schema
# Create widget
item_ui_schema = self.ui_schema.get("items", {})
widget = self.widget_builder.create_widget(
item_schema, item_ui_schema, item_state
)
controls = ArrayControlsWidget()
# Create row
row = ArrayRowWidget(widget, controls)
self.array_layout.addWidget(row)
# Setup callbacks
widget.on_changed.connect(partial(self.widget_on_changed, row))
controls.on_delete.connect(partial(self.remove_item, row))
controls.on_move_up.connect(partial(self.move_item_up, row))
controls.on_move_down.connect(partial(self.move_item_down, row))
return row
def _remove_item(self, row: ArrayRowWidget):
self.array_layout.removeWidget(row)
row.deleteLater()
def widget_on_changed(self, row: ArrayRowWidget, value):
self.state[self.rows.index(row)] = value
self.on_changed.emit(self.state)
class ObjectSchemaWidget(SchemaWidgetMixin, QtWidgets.QGroupBox):
def __init__(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
):
super().__init__(schema, ui_schema, widget_builder)
self.widgets = self.populate_from_schema(
schema, ui_schema, widget_builder
)
@state_property
def state(self) -> dict:
return {k: w.state for k, w in self.widgets.items()}
@state.setter
def state(self, state: dict):
for name, value in state.items():
self.widgets[name].state = value
def handle_error(self, path: Tuple[str], err: Exception):
name, *tail = path
self.widgets[name].handle_error(tail, err)
def widget_on_changed(self, name: str, value):
self.state[name] = value
self.on_changed.emit(self.state)
def populate_from_schema(
self,
schema: dict,
ui_schema: dict,
widget_builder: 'WidgetBuilder', # noqa: F821
) -> Dict[str, QtWidgets.QWidget]:
layout = QtWidgets.QFormLayout()
self.setLayout(layout)
layout.setAlignment(QtCore.Qt.AlignTop)
self.setFlat(False)
if 'title' in schema:
self.setTitle(schema['title'])
if 'description' in schema:
self.setToolTip(schema['description'])
# Populate rows
widgets = {}
layout.setFieldGrowthPolicy(QtWidgets.QFormLayout.FieldGrowthPolicy(1))
for name, sub_schema in schema['properties'].items():
sub_ui_schema = ui_schema.get(name, {})
widget = widget_builder.create_widget(
sub_schema, sub_ui_schema
) # TODO onchanged
widget.on_changed.connect(partial(self.widget_on_changed, name))
label = sub_schema.get("title", name)
layout.addRow(label, widget)
widgets[name] = widget
return widgets
class EnumSchemaWidget(SchemaWidgetMixin, QtWidgets.QComboBox):
@state_property
def state(self):
return self.itemData(self.currentIndex())
@state.setter
def state(self, value):
index = self.findData(value)
if index == -1:
raise ValueError(value)
self.setCurrentIndex(index)
def configure(self):
options = self.schema["enum"]
for i, opt in enumerate(options):
self.addItem(str(opt))
self.setItemData(i, opt)
self.currentIndexChanged.connect(
lambda _: self.on_changed.emit(self.state)
)
def _index_changed(self, index: int):
self.on_changed.emit(self.state)
class FormWidget(QtWidgets.QWidget):
def __init__(self, widget: SchemaWidgetMixin):
super().__init__()
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
self.error_widget = QtWidgets.QGroupBox()
self.error_widget.setTitle("Errors")
self.error_layout = QtWidgets.QVBoxLayout()
self.error_widget.setLayout(self.error_layout)
self.error_widget.hide()
layout.addWidget(self.error_widget)
layout.addWidget(widget)
self.widget = widget
def display_errors(self, errors: List[Exception]):
self.error_widget.show()
layout = self.error_widget.layout()
while True:
item = layout.takeAt(0)
if not item:
break
item.widget().deleteLater()
for err in errors:
widget = QtWidgets.QLabel(
f"<b>.{'.'.join(err.path)}</b> {err.message}"
)
layout.addWidget(widget)
def clear_errors(self):
self.error_widget.hide()
class MyMainWindow(QtWidgets.QDialog):
def __init__(self, widget: SchemaWidgetMixin, parent=None):
super().__init__(parent)
self.form_widget = FormWidget(widget)
self.setWindowTitle("Preferences")
self.widget = self.form_widget
self.setCentralWidget(self.widget)
|
import csv
import matplotlib.pyplot as plt
import numpy as np
from collections import OrderedDict
import matplotlib as mpl
# import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator
from matplotlib.ticker import StrMethodFormatter
import matplotlib.font_manager as font_manager
from matplotlib.patches import Patch
import string
from netCDF4 import Dataset
import json
from cartopy.feature import NaturalEarthFeature
import cartopy.crs as crs
import pickle
from wrf import (to_np, getvar, smooth2d, get_cartopy, cartopy_xlim,
cartopy_ylim, latlon_coords)
import cartopy
import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
map_location = "C:/Users/limgr/.spyder-py3/Map"
os.environ["CARTOPY_USER_BACKGROUNDS"] = map_location
# List the colors that will be used for tracing the track.
csfont = {'fontname':'Times New Roman'}
font = font_manager.FontProperties(family='Times New Roman', size=25)
fontbar = font_manager.FontProperties(family='Times New Roman', size=12)
font_wt = font_manager.FontProperties(family='Times New Roman', size=20)
colors = ['k','green','purple','darkblue', 'deepskyblue', 'tomato', \
'blue', 'gray', 'lightcoral', 'turquoise','red','blue','green','pink']
patterns = ['-', '--','-.','-',':',':','--','--', ':','-', '--', ':','-', '--', ':',\
'-.', '-.', '-.', ':', '--', '-']
markers = ['s','D','^','o','*','>','+','x','X','D','^','<','>','v']
sizes = [7, 7, 7, 7, 7, 7, 4, 3, 3, 3, 3, 3, 6,5,4,3,2,2]
options = ["Best Track",\
"WRF-MYJ",\
"WRF-YSU-0",\
"WRF-COAWST",\
"WRF-YSU-1",\
"WRF-YSU-2"]
models = ["WRF-MYJ",\
"WRF-YSU-0",\
"WRF-COAWST",\
"WRF-YSU-1",\
"WRF-YSU-2"]
hurricanes = ["Katrina",\
"Maria",\
"Irma",\
"Dorian",\
"Lorenzo"]
# subplot positions
position = [[0,0,2],[0,2,4],[0,4,6],[1,0,2],[1,2,4]]
position2 = [[0,4,0,7],[0,4,8,15],[0,4,16,23],[5,9,0,7],[5,9,8,15]]
linestyles = OrderedDict(
[('solid', (0, ())),
('dashdotted', (0, (3, 3, 1, 3))),
('dashdotdotted', (0, (3, 2, 1, 2, 1, 2))),
('dashed', (0, (3, 3))),
('dotted', (0, (1, 3))),
('dashed', (0, (3, 3))),
('loosely dashed', (0, (5, 5))),
('loosely dotted', (0, (1, 10))),
('densely dotted', (0, (1, 1))),
('densely dashed', (0, (5, 1))),
('loosely dashdotted', (0, (3, 10, 1, 10))),
('densely dashdotted', (0, (3, 1, 1, 1))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])
R = 6373.0 # approxiamte radius of earth in km
# folder for wi and wt files
dir_wi = ['C:/Users/limgr/Desktop/Katrina_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Maria_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Irma_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_wind_intensity_16km.csv']
dir_wt = ['C:/Users/limgr/Desktop/Katrina_track_16km.txt',\
'C:/Users/limgr/Desktop/Maria_track_16km.txt',\
'C:/Users/limgr/Desktop/Irma_track_16km.txt',\
'C:/Users/limgr/Desktop/Dorian_track_16km.txt',\
'C:/Users/limgr/Desktop/Lorenzo_track_16km.txt']
dir_p = ['C:/Users/limgr/Desktop/Katrina_16km.p',\
'C:/Users/limgr/Desktop/Maria_16km.p',\
'C:/Users/limgr/Desktop/Irma_16km.p',\
'C:/Users/limgr/Desktop/Dorian_16km.p',\
'C:/Users/limgr/Desktop/Lorenzo_16km.p']
dir_znt_eye = ['C:/Users/limgr/Desktop/Katrina_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Maria_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Irma_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_ZNT_eye_16km.csv']
dir_znt_eyewall = ['C:/Users/limgr/Desktop/Katrina_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Maria_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Irma_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_ZNT_eyewall_16km.csv']
lat_log_bound = [[-90.5, -84.5, 23, 29],\
[-74, -68, 19.5, 25.5],\
[-47, -39, 14, 22],\
[-76.5, -70.5, 23, 29],\
[-45.5, -39.5, 16.5, 22.5]]
lat_log_bound = [[-93, -83, 24, 34],\
[-77, -67, 19, 29],\
[-51, -39, 14, 22],\
[-80, -69, 23, 29],\
[-47, -40, 16.5, 25.5]]
lat_log_bound = [[-91, -85, 24, 30],\
[-77, -67, 19, 29],\
[-51, -39, 14, 22],\
[-78, -70, 23, 29],\
[-47, -40, 16.5, 25.5]]
def Calculate_Distance_Haversine1(x):
return (np.sin(x[0]/2))**2
def Calculate_Distance_Haversine2(x):
return np.cos(x[0])
def Calculate_Distance_Haversine3(x):
return (np.sin(x[1]/2))**2
#########################################
# Plot normalized intensity time series #
#########################################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_wi[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {', '.join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
# for i in range(0,line_count-1):
# if i==0:
# tmp=[float(i)*0.5144444 for i in values[i]]
# #tmp=[float(i) for i in values[i]]
# # elif (i!=2 and i!=3):
# else:
# tmp=[float(i) for i in values[i]]
# else:
# continue
# print('tmp')
# print(tmp)
for i in range(0,line_count-1):
if i==0:
tmp=[float(i)*0.5144444 for i in values[i]]
#tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
if c==0:
plt.plot( Times0[:5], tmp[:5], color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0[:5], tmp[:5], color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([25, 80])
elif hurricanes[kk]=='Dorian':
if c==0:
plt.plot( Times0[:-2], tmp[:-2], color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0[:-2], tmp[:-2], color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([25, 80])
else:
if c==0:
plt.plot( Times0, tmp, color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0, tmp, color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([25, 80])
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'Intensity (m/s)', **csfont, fontsize=35)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wind_intensity_A.png', dpi=500)
plt.show()
########################
# Plot ZNT time series #
########################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_znt_eye[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {', '.join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
for i in range(0,line_count-1):
if i==0:
#tmp=[float(i)*0.5144444 for i in values[i]]
tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
plt.plot( Times0[:5], tmp[:5], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
elif hurricanes[kk]=='Dorian':
plt.plot( Times0[:-2], tmp[:-2], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
else:
plt.plot( Times0, tmp, color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([1e-5, 0.05])
plt.yscale('log')
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(models, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'$Z_0$ (m)', **csfont, fontsize=30)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_ZNT_eye.png', dpi=500)
plt.show()
########################
# Plot ZNT time series #
########################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_znt_eyewall[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {', '.join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
for i in range(0,line_count-1):
if i==0:
#tmp=[float(i)*0.5144444 for i in values[i]]
tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
plt.plot( Times0[:5], tmp[:5], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
elif hurricanes[kk]=='Dorian':
plt.plot( Times0[:-2], tmp[:-2], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
else:
plt.plot( Times0, tmp, color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([1e-5, 0.05])
plt.yscale('log')
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(models, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'$Z_0$ (m)', **csfont, fontsize=30)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_ZNT_eyewall.png', dpi=500)
plt.show()
########################
# Plot hurricane track #
########################
fig = plt.figure(figsize=(15,10))
spec = mpl.gridspec.GridSpec(ncols=6, nrows=2)
for kk in range(len(hurricanes)):
if hurricanes[kk]=='Katrina':
cons=6
elif hurricanes[kk]=='Dorian':
cons=8
else:
cons=10
real1=[]
oussama1=[]
wrf1=[]
simu1=[]
with open( dir_wt[kk], 'r' ) as f :
data0 = f.read()
data = json.loads('[' + data0.replace('}{', '},{') + ']')
for i in range(0,len(data)):
data2 = list(data[i].values())
data3 = [e for sl in data2 for e in sl]
for j in range(len(data3)):
data3[j].pop(0)
if i==0:
real1.append(data3)
# elif i==1:
# oussama1.append(data3)
# elif i==2:
# wrf1.append(data3)
else:
simu1.append(data3)
real1 = np.array(real1, dtype=np.float32)
simu1 = np.array(simu1, dtype=np.float32)
real_r = np.radians(real1)
simu_r = np.radians(simu1)
term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
# ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]])
# ax.text(0.05, 0.9, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
# size=30)
slp2D = pickle.load( open( dir_p[kk], "rb" ) )
lats, lons = latlon_coords(slp2D)
# Get the cartopy mapping object (use original data, rather than any processed data)
cart_proj = get_cartopy(slp2D)
# Set the GeoAxes to the projection used by WRF
#ax = plt.axes(projection=cart_proj)
ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]], projection=cart_proj)
# ax.stock_img()
# Download and add the states and coastlines
states = NaturalEarthFeature(category="cultural", scale="50m",
facecolor="none",
name="admin_1_states_provinces_shp")
ax.add_feature(states, linewidth=.5, edgecolor="black")
ax.coastlines('50m', linewidth=0.8)
# Set the map bounds
# ax.set_xlim(cartopy_xlim(slp2D))
# ax.set_ylim(cartopy_ylim(slp2D))
ax.set_extent(lat_log_bound[kk])
ax.background_img(name='SR', resolution='high')
# Show grid lines.
gl = ax.gridlines(crs=crs.PlateCarree(), draw_labels=True,
linewidth=1.5, color='gray', alpha=0.8, linestyle=':')
gl.xlabel_style = {'size': 15, 'color': 'k','fontname':'Times New Roman'}
gl.ylabel_style = {'size': 15, 'color': 'k','fontname':'Times New Roman'}
gl.xlabels_top = False
gl.ylabels_right = False
c=0
ll=[]
rr=[]
for i in range(real1.shape[0]):
for j in range(real1.shape[1]):
if j<cons:
ll.append(real1[i][j][0])
rr.append(real1[i][j][1])
ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, \
linestyle=list(linestyles.values())[0],\
markersize=sizes[c], transform=crs.PlateCarree())
c+=1
ll=[]
rr=[]
for i in range(simu1.shape[0]):
for j in range(simu1.shape[1]):
if j<cons:
ll.append(simu1[i][j][0])
rr.append(simu1[i][j][1])
ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, \
linestyle=list(linestyles.values())[i+1],\
markersize=sizes[c], transform=crs.PlateCarree())
c+=1
ll=[]
rr=[]
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(15)
fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font_wt, \
frameon=False)
plt.title(hurricanes[kk], {'size': 25}, **csfont)
# plt.legend(['Real track','C0.0001', 'C0.01', 'C1', 'C100'],\
# loc = "upper right", prop={'size': 7})
# plt.xlabel("Lon", fontsize=135)
# plt.ylabel("Lat", fontsize=135)
# plt.title(hurricanes[kk], {'size': 35}, **csfont)
# plt.show()
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wt.png', dpi=500)
plt.show()
# fig = plt.figure(figsize=(15,10))
# spec = mpl.gridspec.GridSpec(ncols=6, nrows=2)
# for kk in range(len(hurricanes)):
# real1=[]
# oussama1=[]
# wrf1=[]
# simu1=[]
# with open( dir_wt[kk], 'r' ) as f :
# data0 = f.read()
# data = json.loads('[' + data0.replace('}{', '},{') + ']')
# for i in range(0,len(data)):
# data2 = list(data[i].values())
# data3 = [e for sl in data2 for e in sl]
# for j in range(len(data3)):
# data3[j].pop(0)
# if i==0:
# real1.append(data3)
# # elif i==1:
# # oussama1.append(data3)
# # elif i==2:
# # wrf1.append(data3)
# else:
# simu1.append(data3)
# real1 = np.array(real1, dtype=np.float32)
# simu1 = np.array(simu1, dtype=np.float32)
# real_r = np.radians(real1)
# simu_r = np.radians(simu1)
# term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
# term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
# np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
# np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
# simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
# m = Basemap(projection='merc', llcrnrlat=lat_log_bound[kk][2],\
# urcrnrlat=lat_log_bound[kk][3], \
# llcrnrlon=lat_log_bound[kk][0], \
# urcrnrlon=lat_log_bound[kk][1], resolution= 'f' )
# m.drawstates()
# m.drawmeridians([-100, -90, -80, -70, -60, -50, -40, ], color='k', textcolor='k', linewidth=1.5,
# zorder=None, dashes=[6, 1000], labels=[1, 0, 0, 1], labelstyle=None, fmt='%g', xoffset=None,
# yoffset=None, ax=None, latmax=None, fontsize=12)
# m.drawparallels([10, 15, 20, 25, 30, 35], color='k', textcolor='k', linewidth=1.5, zorder=None, dashes=[6, 1000],
# labels=[1, 0, 0, 1], labelstyle=None, fmt='%g', xoffset=None, yoffset=None, ax=None, latmax=None, fontsize=12)
# m.drawmapscale(-101, 8, -96, 8, 1000, barstyle='fancy', units='km', fontsize=8)
# m.drawcoastlines(linewidth=0.7, linestyle='solid', color='grey')
# m.drawcountries()
# m.shadedrelief()
# m.drawmapboundary()
# # ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]])
# # ax.text(0.05, 0.9, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
# # size=30)
# slp2D = pickle.load( open( dir_p[kk], "rb" ) )
# lats, lons = latlon_coords(slp2D)
# # Get the cartopy mapping object (use original data, rather than any processed data)
# cart_proj = get_cartopy(slp2D)
# # Set the GeoAxes to the projection used by WRF
# #ax = plt.axes(projection=cart_proj)
# ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]], projection=cart_proj)
# ax.stock_img()
# # Download and add the states and coastlines
# states = NaturalEarthFeature(category="cultural", scale="50m",
# facecolor="none",
# name="admin_1_states_provinces_shp")
# ax.add_feature(states, linewidth=.5, edgecolor="black")
# ax.coastlines('50m', linewidth=0.8)
# # Set the map bounds
# # ax.set_xlim(cartopy_xlim(slp2D))
# # ax.set_ylim(cartopy_ylim(slp2D))
# ax.set_extent(lat_log_bound[kk])
# # Show grid lines.
# gl = ax.gridlines(crs=crs.PlateCarree(), draw_labels=True,
# linewidth=1.5, color='gray', alpha=0.8, linestyle=':')
# gl.xlabel_style = {'size': 15, 'color': 'k'}
# gl.ylabel_style = {'size': 15, 'color': 'k'}
# gl.xlabels_top = False
# gl.ylabels_right = False
# c=0
# ll=[]
# rr=[]
# for i in range(real1.shape[0]):
# for j in range(real1.shape[1]):
# if j<6:
# ll.append(real1[i][j][0])
# rr.append(real1[i][j][1])
# ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, linestyle=patterns[c],\
# markersize=sizes[c], transform=crs.PlateCarree())
# c+=1
# ll=[]
# rr=[]
# for i in range(simu1.shape[0]):
# for j in range(simu1.shape[1]):
# if j<6:
# ll.append(simu1[i][j][0])
# rr.append(simu1[i][j][1])
# ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, linestyle=patterns[c],\
# markersize=sizes[c], transform=crs.PlateCarree())
# c+=1
# ll=[]
# rr=[]
# for axis in ['top','bottom','left','right']:
# ax.spines[axis].set_linewidth(15)
# fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font_wt, \
# frameon=False)
# plt.title(hurricanes[kk], {'size': 25}, **csfont)
# # plt.legend(['Real track','C0.0001', 'C0.01', 'C1', 'C100'],\
# # loc = "upper right", prop={'size': 7})
# # plt.xlabel("Lon", fontsize=135)
# # plt.ylabel("Lat", fontsize=135)
# # plt.title(hurricanes[kk], {'size': 35}, **csfont)
# # plt.show()
# plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wt.png', dpi=500)
# plt.show()
###################
# Plot error bars #
###################
simu_error = []
for kk in range(len(hurricanes)):
rows1=[]
Times1=[]
Times1=[]
values1=[]
real1_track=[]
with open(dir_wi[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
sim_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {', '.join(row)}')
Times1.append(list(row.keys()))
real1_track.append(list(row.values()))
line_count += 1
else:
rows1.append(row)
values1.append(list(row.values()))
line_count += 1
print('There is totally ',(line_count-1)*(len(row)),' data points')
simu1=np.array(values1, dtype=np.float32)
real1=np.array(real1_track, dtype=np.float32)
real1=real1*0.5144444
real1=real1
simu_error1=abs(simu1-real1[:,None])/real1[:,None]#/((line_count-3)*(len(row)))
print('absolute pressure error')
print(abs(simu1-real1[:,None]))
simu_error.append(simu_error1)
par1_error_wi=np.zeros((4, 9))
par2_error_wi=np.zeros((4, 9))
par3_erro_wir=np.zeros((4, 9))
par4_error_wi=np.zeros((4, 9))
par5_error_wi=np.zeros((4, 9))
simu_error1 = simu_error[0]
simu_error2 = simu_error[1]
simu_error3 = simu_error[2]
simu_error4 = simu_error[3]
simu_error5 = simu_error[4]
par1_error_wi=np.concatenate((simu_error1[0][0][0:5],simu_error2[0][0][:],\
simu_error3[0][0][:],simu_error4[0][0][:-2],simu_error5[0][0][:]))
par1_error_wi=par1_error_wi.flatten()
par1_error_wi_mean=np.mean(par1_error_wi)
par1_error_wi_std=np.std(par1_error_wi)
par1_error_wi_low=np.percentile(par1_error_wi, 20)
par1_error_wi_hgh=np.percentile(par1_error_wi, 80)
par2_error_wi=np.concatenate((simu_error1[0][1][0:5],simu_error2[0][1][:],\
simu_error3[0][1][:],simu_error4[0][1][:-2],simu_error5[0][1][:]))
par2_error_wi=par2_error_wi.flatten()
par2_error_wi_mean=np.mean(par2_error_wi)
par2_error_wi_std=np.std(par2_error_wi)
par2_error_wi_low=np.percentile(par2_error_wi, 20)
par2_error_wi_hgh=np.percentile(par2_error_wi, 80)
par3_error_wi=np.concatenate((simu_error1[0][2][0:5],simu_error2[0][2][:],\
simu_error3[0][2][:],simu_error4[0][2][:-2],simu_error5[0][2][:]))
par3_error_wi=par3_error_wi.flatten()
par3_error_wi_mean=np.mean(par3_error_wi)
par3_error_wi_std=np.std(par3_error_wi)
par3_error_wi_low=np.percentile(par3_error_wi, 20)
par3_error_wi_hgh=np.percentile(par3_error_wi, 80)
par4_error_wi=np.concatenate((simu_error1[0][3][0:5],simu_error2[0][3][:],\
simu_error3[0][3][:],simu_error4[0][3][:-2],simu_error5[0][3][:]))
par4_error_wi=par4_error_wi.flatten()
par4_error_wi_mean=np.mean(par4_error_wi)
par4_error_wi_std=np.std(par4_error_wi)
par4_error_wi_low=np.percentile(par4_error_wi, 20)
par4_error_wi_hgh=np.percentile(par4_error_wi, 80)
par5_error_wi=np.concatenate((simu_error1[0][4][0:5],simu_error2[0][4][:],\
simu_error3[0][4][:],simu_error4[0][4][:-2],simu_error5[0][4][:]))
par5_error_wi=par5_error_wi.flatten()
par5_error_wi_mean=np.mean(par5_error_wi)
par5_error_wi_std=np.std(par5_error_wi)
par5_error_wi_low=np.percentile(par5_error_wi, 20)
par5_error_wi_hgh=np.percentile(par5_error_wi, 80)
simu_error = []
for kk in range(len(hurricanes)):
real1=[]
oussama1=[]
wrf1=[]
simu1=[]
with open( dir_wt[kk], 'r' ) as f :
data0 = f.read()
data = json.loads('[' + data0.replace('}{', '},{') + ']')
for i in range(0,len(data)):
data2 = list(data[i].values())
data3 = [e for sl in data2 for e in sl]
for j in range(len(data3)):
data3[j].pop(0)
if i==0:
real1.append(data3)
# elif i==1:
# oussama1.append(data3)
# elif i==2:
# wrf1.append(data3)
else:
simu1.append(data3)
real1 = np.array(real1, dtype=np.float32)
simu1 = np.array(simu1, dtype=np.float32)
real_r = np.radians(real1)
simu_r = np.radians(simu1)
term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
simu_error.append(simu_error1)
par1_error=np.zeros((4, 9))
par2_error=np.zeros((4, 9))
par3_error=np.zeros((4, 9))
par4_error=np.zeros((4, 9))
par5_error=np.zeros((4, 9))
simu_error1 = simu_error[0]
simu_error2 = simu_error[1]
simu_error3 = simu_error[2]
simu_error4 = simu_error[3]
simu_error5 = simu_error[4]
par1_error_wt=np.concatenate((simu_error1[0][0:5],\
simu_error2[0][:],simu_error3[0][:],\
simu_error4[0][:-2],simu_error5[0][:]))
par1_error_wt=par1_error_wt.flatten()
par1_error_wt_mean=np.mean(par1_error_wt)
par1_error_wt_std=np.std(par1_error_wt)
par1_error_wt_low=np.percentile(par1_error_wt, 20)
par1_error_wt_hgh=np.percentile(par1_error_wt, 80)
par2_error_wt=np.concatenate((simu_error1[1][0:5],\
simu_error2[1][:],simu_error3[1][:],\
simu_error4[1][:-2],simu_error5[1][:]))
par2_error_wt=par2_error_wt.flatten()
par2_error_wt_mean=np.mean(par2_error_wt)
par2_error_wt_std=np.std(par2_error_wt)
par2_error_wt_low=np.percentile(par2_error_wt, 20)
par2_error_wt_hgh=np.percentile(par2_error_wt, 80)
par3_error_wt=np.concatenate((simu_error1[2][0:5],\
simu_error2[2][:],simu_error3[2][:],\
simu_error4[2][:-2],simu_error5[2][:]))
par3_error_wt=par3_error_wt.flatten()
par3_error_wt_mean=np.mean(par3_error_wt)
par3_error_wt_std=np.std(par3_error_wt)
par3_error_wt_low=np.percentile(par2_error_wt, 20)
par3_error_wt_hgh=np.percentile(par2_error_wt, 80)
par4_error_wt=np.concatenate((simu_error1[3][0:5],\
simu_error2[3][:],simu_error3[3][:],\
simu_error4[3][:-2],simu_error5[3][:]))
par4_error_wt=par4_error_wt.flatten()
par4_error_wt_mean=np.mean(par4_error_wt)
par4_error_wt_std=np.std(par4_error_wt)
par4_error_wt_low=np.percentile(par4_error_wt, 20)
par4_error_wt_hgh=np.percentile(par4_error_wt, 80)
par5_error_wt=np.concatenate((simu_error1[4][0:5],\
simu_error2[4][:],simu_error3[4][:],\
simu_error4[4][:-2],simu_error5[4][:]))
par5_error_wt=par5_error_wt.flatten()
par5_error_wt_mean=np.mean(par5_error_wt)
par5_error_wt_std=np.std(par5_error_wt)
par5_error_wt_low=np.percentile(par5_error_wt, 20)
par5_error_wt_hgh=np.percentile(par5_error_wt, 80)
x_pos = np.arange(len(models))
CTEs_wi = [par1_error_wi_mean,\
par2_error_wi_mean,par3_error_wi_mean,par4_error_wi_mean,par5_error_wi_mean]
errors_wi = [par1_error_wi_std,\
par2_error_wi_std,par3_error_wi_std,par4_error_wi_std,par5_error_wi_std]
percentile_10_wi = np.array([par1_error_wi_mean-par1_error_wi_low,\
par2_error_wi_mean-par2_error_wi_low,par3_error_wi_mean-par3_error_wi_low, \
par4_error_wi_mean-par4_error_wi_low,par5_error_wi_mean-par5_error_wi_low])
percentile_90_wi = np.array([par1_error_wi_hgh-par1_error_wi_mean,\
par2_error_wi_hgh-par2_error_wi_mean,par3_error_wi_hgh-par3_error_wi_mean, \
par4_error_wi_hgh-par4_error_wi_mean,par5_error_wi_hgh-par5_error_wi_mean])
err_wi = np.vstack((percentile_10_wi, percentile_90_wi))
CTEs_wt = [par1_error_wt_mean,\
par2_error_wt_mean,par3_error_wt_mean,par4_error_wt_mean,par5_error_wt_mean]
errors_wt = [par1_error_wt_std,\
par2_error_wt_std,par3_error_wt_std,par4_error_wt_std,par5_error_wt_std]
percentile_10_wt = np.array([par1_error_wt_mean-par1_error_wt_low,\
par2_error_wt_mean-par2_error_wt_low,par3_error_wt_mean-par3_error_wt_low, \
par4_error_wt_mean-par4_error_wt_low,par5_error_wt_mean-par5_error_wt_low])
percentile_90_wt = np.array([par1_error_wt_hgh-par1_error_wt_mean,\
par2_error_wt_hgh-par2_error_wt_mean,par3_error_wt_hgh-par3_error_wt_mean, \
par4_error_wt_hgh-par4_error_wt_mean,par5_error_wt_hgh-par5_error_wt_mean])
print(percentile_90_wt)
err_wt = np.vstack((percentile_10_wt, percentile_90_wt))
# fig, ax = plt.subplots(1, 2, figsize=(40, 8), sharex=True)
fig = plt.figure(figsize=(8,5))
spec = mpl.gridspec.GridSpec(ncols=8, nrows=5)
ax = fig.add_subplot(spec[1:,0:4])
ax.text(0.7, 0.9, '('+string.ascii_lowercase[0]+')', transform=ax.transAxes,
size=15, **csfont)
bars = ax.bar(x_pos, CTEs_wi, yerr=err_wi, align='center', \
color=['green','purple','darkblue', 'deepskyblue', 'tomato'], alpha=0.8,\
ecolor='k', capsize=10, edgecolor='k', linewidth=3)
for i in range(len(x_pos)):
bars[i].set(linestyle=list(linestyles.values())[0])
ax.set_ylabel(r'Normalized Intensity', **csfont, fontsize=15)
vals = ax.get_yticks()
print(vals)
ax.set_yticklabels(['{:,.0%}'.format(x) for x in vals])
ax.set_xticks(x_pos)
ax.set_xticklabels(models, **csfont, fontsize=10)
#ax.set_title(r'COAWST', **csfont, fontsize=20)
ax.yaxis.grid(True)
# ax.set_ylim([0, 0.5])
ax = fig.add_subplot(spec[1:,4:])
ax.text(0.7, 0.9, '('+string.ascii_lowercase[1]+')', transform=ax.transAxes,
size=15, **csfont)
bars = ax.bar(x_pos, CTEs_wt, yerr=err_wt, align='center', \
color=['green','purple','darkblue', 'deepskyblue', 'tomato'], alpha=0.8,\
ecolor='k', capsize=10, edgecolor='k', linewidth=3)
for i in range(len(x_pos)):
bars[i].set(linestyle=list(linestyles.values())[0])
ax.set_ylabel(r'Track Error (km)', **csfont, fontsize=15)
vals = ax.get_yticks()
ax.set_yticklabels(['{}'.format(x) for x in vals])
ax.set_xticks(x_pos)
ax.set_xticklabels(models, **csfont, fontsize=10)
#ax.set_title(r'COAWST', **csfont, fontsize=20)
ax.yaxis.grid(True)
# ax.set_ylim([0, 110])
ax = fig.add_subplot(spec[0,0:])
handles = [plt.Rectangle((0,0),1,1, facecolor=colors[i+1], \
linestyle=list(linestyles.values())[0], edgecolor = 'k', linewidth=1.5\
) for i in range(len(models))]
plt.legend(handles, models, ncol=3, bbox_to_anchor=(0.85, 0.8), prop=fontbar, \
frameon=False)
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
ax.set_yticks([])
ax.set_yticklabels([])
ax.set_xticks([])
ax.set_xticklabels([])
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_visible(False)
# for i, v in enumerate(CTEs):
# ax.text(i, v+0.02, str(round(v, 3)), color='red', fontweight='bold')
# Save the figure and show
fig.autofmt_xdate()
plt.tight_layout()
#plt.savefig('wind_intensity_bar_plot.png')
plt.savefig('C:/Users/limgr/Desktop/wi_wt_bar_plots.png', dpi=500)
plt.show()
| import csv
import matplotlib.pyplot as plt
import numpy as np
from collections import OrderedDict
import matplotlib as mpl
# import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator
from matplotlib.ticker import StrMethodFormatter
import matplotlib.font_manager as font_manager
from matplotlib.patches import Patch
import string
from netCDF4 import Dataset
import json
from cartopy.feature import NaturalEarthFeature
import cartopy.crs as crs
import pickle
from wrf import (to_np, getvar, smooth2d, get_cartopy, cartopy_xlim,
cartopy_ylim, latlon_coords)
import cartopy
import os
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
map_location = "C:/Users/limgr/.spyder-py3/Map"
os.environ["CARTOPY_USER_BACKGROUNDS"] = map_location
# List the colors that will be used for tracing the track.
csfont = {'fontname':'Times New Roman'}
font = font_manager.FontProperties(family='Times New Roman', size=25)
fontbar = font_manager.FontProperties(family='Times New Roman', size=12)
font_wt = font_manager.FontProperties(family='Times New Roman', size=20)
colors = ['k','green','purple','darkblue', 'deepskyblue', 'tomato', \
'blue', 'gray', 'lightcoral', 'turquoise','red','blue','green','pink']
patterns = ['-', '--','-.','-',':',':','--','--', ':','-', '--', ':','-', '--', ':',\
'-.', '-.', '-.', ':', '--', '-']
markers = ['s','D','^','o','*','>','+','x','X','D','^','<','>','v']
sizes = [7, 7, 7, 7, 7, 7, 4, 3, 3, 3, 3, 3, 6,5,4,3,2,2]
options = ["Best Track",\
"WRF-MYJ",\
"WRF-YSU-0",\
"WRF-COAWST",\
"WRF-YSU-1",\
"WRF-YSU-2"]
models = ["WRF-MYJ",\
"WRF-YSU-0",\
"WRF-COAWST",\
"WRF-YSU-1",\
"WRF-YSU-2"]
hurricanes = ["Katrina",\
"Maria",\
"Irma",\
"Dorian",\
"Lorenzo"]
# subplot positions
position = [[0,0,2],[0,2,4],[0,4,6],[1,0,2],[1,2,4]]
position2 = [[0,4,0,7],[0,4,8,15],[0,4,16,23],[5,9,0,7],[5,9,8,15]]
linestyles = OrderedDict(
[('solid', (0, ())),
('dashdotted', (0, (3, 3, 1, 3))),
('dashdotdotted', (0, (3, 2, 1, 2, 1, 2))),
('dashed', (0, (3, 3))),
('dotted', (0, (1, 3))),
('dashed', (0, (3, 3))),
('loosely dashed', (0, (5, 5))),
('loosely dotted', (0, (1, 10))),
('densely dotted', (0, (1, 1))),
('densely dashed', (0, (5, 1))),
('loosely dashdotted', (0, (3, 10, 1, 10))),
('densely dashdotted', (0, (3, 1, 1, 1))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])
R = 6373.0 # approxiamte radius of earth in km
# folder for wi and wt files
dir_wi = ['C:/Users/limgr/Desktop/Katrina_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Maria_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Irma_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_wind_intensity_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_wind_intensity_16km.csv']
dir_wt = ['C:/Users/limgr/Desktop/Katrina_track_16km.txt',\
'C:/Users/limgr/Desktop/Maria_track_16km.txt',\
'C:/Users/limgr/Desktop/Irma_track_16km.txt',\
'C:/Users/limgr/Desktop/Dorian_track_16km.txt',\
'C:/Users/limgr/Desktop/Lorenzo_track_16km.txt']
dir_p = ['C:/Users/limgr/Desktop/Katrina_16km.p',\
'C:/Users/limgr/Desktop/Maria_16km.p',\
'C:/Users/limgr/Desktop/Irma_16km.p',\
'C:/Users/limgr/Desktop/Dorian_16km.p',\
'C:/Users/limgr/Desktop/Lorenzo_16km.p']
dir_znt_eye = ['C:/Users/limgr/Desktop/Katrina_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Maria_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Irma_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_ZNT_eye_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_ZNT_eye_16km.csv']
dir_znt_eyewall = ['C:/Users/limgr/Desktop/Katrina_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Maria_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Irma_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Dorian_ZNT_eyewall_16km.csv',\
'C:/Users/limgr/Desktop/Lorenzo_ZNT_eyewall_16km.csv']
lat_log_bound = [[-90.5, -84.5, 23, 29],\
[-74, -68, 19.5, 25.5],\
[-47, -39, 14, 22],\
[-76.5, -70.5, 23, 29],\
[-45.5, -39.5, 16.5, 22.5]]
lat_log_bound = [[-93, -83, 24, 34],\
[-77, -67, 19, 29],\
[-51, -39, 14, 22],\
[-80, -69, 23, 29],\
[-47, -40, 16.5, 25.5]]
lat_log_bound = [[-91, -85, 24, 30],\
[-77, -67, 19, 29],\
[-51, -39, 14, 22],\
[-78, -70, 23, 29],\
[-47, -40, 16.5, 25.5]]
def Calculate_Distance_Haversine1(x):
return (np.sin(x[0]/2))**2
def Calculate_Distance_Haversine2(x):
return np.cos(x[0])
def Calculate_Distance_Haversine3(x):
return (np.sin(x[1]/2))**2
#########################################
# Plot normalized intensity time series #
#########################################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_wi[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
# for i in range(0,line_count-1):
# if i==0:
# tmp=[float(i)*0.5144444 for i in values[i]]
# #tmp=[float(i) for i in values[i]]
# # elif (i!=2 and i!=3):
# else:
# tmp=[float(i) for i in values[i]]
# else:
# continue
# print('tmp')
# print(tmp)
for i in range(0,line_count-1):
if i==0:
tmp=[float(i)*0.5144444 for i in values[i]]
#tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
if c==0:
plt.plot( Times0[:5], tmp[:5], color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0[:5], tmp[:5], color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([25, 80])
elif hurricanes[kk]=='Dorian':
if c==0:
plt.plot( Times0[:-2], tmp[:-2], color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0[:-2], tmp[:-2], color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([25, 80])
else:
if c==0:
plt.plot( Times0, tmp, color = colors[c], \
linestyle=list(linestyles.values())[0],\
linewidth=5, markersize=sizes[c])
else:
plt.plot( Times0, tmp, color = colors[c], \
linestyle=list(linestyles.values())[i],\
linewidth=5, markersize=sizes[c])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([25, 80])
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'Intensity (m/s)', **csfont, fontsize=35)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wind_intensity_A.png', dpi=500)
plt.show()
########################
# Plot ZNT time series #
########################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_znt_eye[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
for i in range(0,line_count-1):
if i==0:
#tmp=[float(i)*0.5144444 for i in values[i]]
tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
plt.plot( Times0[:5], tmp[:5], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
elif hurricanes[kk]=='Dorian':
plt.plot( Times0[:-2], tmp[:-2], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
else:
plt.plot( Times0, tmp, color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([1e-5, 0.05])
plt.yscale('log')
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(models, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'$Z_0$ (m)', **csfont, fontsize=30)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_ZNT_eye.png', dpi=500)
plt.show()
########################
# Plot ZNT time series #
########################
fig = plt.figure(figsize=(20,13))
spec = mpl.gridspec.GridSpec(ncols=23, nrows=9)
for kk in range(len(hurricanes)):
c=0
rows=[]
Times=[]
Times=[]
values=[]
with open(dir_znt_eyewall[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
Times.append(list(row.keys()))
line_count += 1
#print(row)
rows.append(row)
values.append(list(row.values()))
line_count += 1
print(f'Processed {line_count} lines.')
Times0=Times[0]
print(Times0)
print(values[0])
print(position[kk])
ax = fig.add_subplot(spec[position2[kk][0]:position2[kk][1],\
position2[kk][2]:position2[kk][3]])
ax.text(0.05, 0.85, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
size=30, **csfont)
for i in range(0,line_count-1):
if i==0:
#tmp=[float(i)*0.5144444 for i in values[i]]
tmp=[float(i) for i in values[i]]
# elif (i!=2 and i!=3):
else:
tmp=[float(i) for i in values[i]]
# else:
# continue
if hurricanes[kk]=='Katrina':
plt.plot( Times0[:5], tmp[:5], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
elif hurricanes[kk]=='Dorian':
plt.plot( Times0[:-2], tmp[:-2], color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.ylim([1e-5, 0.05])
plt.yscale('log')
else:
plt.plot( Times0, tmp, color = colors[c+1], \
linestyle=list(linestyles.values())[i+1],\
linewidth=5, markersize=sizes[c+1])
plt.xticks(fontsize=25, **csfont)
plt.yticks(fontsize=25, **csfont)
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))
plt.ylim([1e-5, 0.05])
plt.yscale('log')
c+=1
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(2)
ax.tick_params(length=5, width=2)
fig.legend(models, bbox_to_anchor=(0.87, 0.42), prop=font, \
frameon=False)
if kk==0 or kk==3:
plt.ylabel(r'$Z_0$ (m)', **csfont, fontsize=30)
if kk==2 or kk==3 or kk==4:
plt.xlabel(r"Time Series (hr)", fontsize=30, **csfont)
plt.title(hurricanes[kk], {'size': 30}, **csfont)
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_ZNT_eyewall.png', dpi=500)
plt.show()
########################
# Plot hurricane track #
########################
fig = plt.figure(figsize=(15,10))
spec = mpl.gridspec.GridSpec(ncols=6, nrows=2)
for kk in range(len(hurricanes)):
if hurricanes[kk]=='Katrina':
cons=6
elif hurricanes[kk]=='Dorian':
cons=8
else:
cons=10
real1=[]
oussama1=[]
wrf1=[]
simu1=[]
with open( dir_wt[kk], 'r' ) as f :
data0 = f.read()
data = json.loads('[' + data0.replace('}{', '},{') + ']')
for i in range(0,len(data)):
data2 = list(data[i].values())
data3 = [e for sl in data2 for e in sl]
for j in range(len(data3)):
data3[j].pop(0)
if i==0:
real1.append(data3)
# elif i==1:
# oussama1.append(data3)
# elif i==2:
# wrf1.append(data3)
else:
simu1.append(data3)
real1 = np.array(real1, dtype=np.float32)
simu1 = np.array(simu1, dtype=np.float32)
real_r = np.radians(real1)
simu_r = np.radians(simu1)
term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
# ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]])
# ax.text(0.05, 0.9, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
# size=30)
slp2D = pickle.load( open( dir_p[kk], "rb" ) )
lats, lons = latlon_coords(slp2D)
# Get the cartopy mapping object (use original data, rather than any processed data)
cart_proj = get_cartopy(slp2D)
# Set the GeoAxes to the projection used by WRF
#ax = plt.axes(projection=cart_proj)
ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]], projection=cart_proj)
# ax.stock_img()
# Download and add the states and coastlines
states = NaturalEarthFeature(category="cultural", scale="50m",
facecolor="none",
name="admin_1_states_provinces_shp")
ax.add_feature(states, linewidth=.5, edgecolor="black")
ax.coastlines('50m', linewidth=0.8)
# Set the map bounds
# ax.set_xlim(cartopy_xlim(slp2D))
# ax.set_ylim(cartopy_ylim(slp2D))
ax.set_extent(lat_log_bound[kk])
ax.background_img(name='SR', resolution='high')
# Show grid lines.
gl = ax.gridlines(crs=crs.PlateCarree(), draw_labels=True,
linewidth=1.5, color='gray', alpha=0.8, linestyle=':')
gl.xlabel_style = {'size': 15, 'color': 'k','fontname':'Times New Roman'}
gl.ylabel_style = {'size': 15, 'color': 'k','fontname':'Times New Roman'}
gl.xlabels_top = False
gl.ylabels_right = False
c=0
ll=[]
rr=[]
for i in range(real1.shape[0]):
for j in range(real1.shape[1]):
if j<cons:
ll.append(real1[i][j][0])
rr.append(real1[i][j][1])
ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, \
linestyle=list(linestyles.values())[0],\
markersize=sizes[c], transform=crs.PlateCarree())
c+=1
ll=[]
rr=[]
for i in range(simu1.shape[0]):
for j in range(simu1.shape[1]):
if j<cons:
ll.append(simu1[i][j][0])
rr.append(simu1[i][j][1])
ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, \
linestyle=list(linestyles.values())[i+1],\
markersize=sizes[c], transform=crs.PlateCarree())
c+=1
ll=[]
rr=[]
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(15)
fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font_wt, \
frameon=False)
plt.title(hurricanes[kk], {'size': 25}, **csfont)
# plt.legend(['Real track','C0.0001', 'C0.01', 'C1', 'C100'],\
# loc = "upper right", prop={'size': 7})
# plt.xlabel("Lon", fontsize=135)
# plt.ylabel("Lat", fontsize=135)
# plt.title(hurricanes[kk], {'size': 35}, **csfont)
# plt.show()
plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wt.png', dpi=500)
plt.show()
# fig = plt.figure(figsize=(15,10))
# spec = mpl.gridspec.GridSpec(ncols=6, nrows=2)
# for kk in range(len(hurricanes)):
# real1=[]
# oussama1=[]
# wrf1=[]
# simu1=[]
# with open( dir_wt[kk], 'r' ) as f :
# data0 = f.read()
# data = json.loads('[' + data0.replace('}{', '},{') + ']')
# for i in range(0,len(data)):
# data2 = list(data[i].values())
# data3 = [e for sl in data2 for e in sl]
# for j in range(len(data3)):
# data3[j].pop(0)
# if i==0:
# real1.append(data3)
# # elif i==1:
# # oussama1.append(data3)
# # elif i==2:
# # wrf1.append(data3)
# else:
# simu1.append(data3)
# real1 = np.array(real1, dtype=np.float32)
# simu1 = np.array(simu1, dtype=np.float32)
# real_r = np.radians(real1)
# simu_r = np.radians(simu1)
# term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
# term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
# np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
# np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
# simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
# m = Basemap(projection='merc', llcrnrlat=lat_log_bound[kk][2],\
# urcrnrlat=lat_log_bound[kk][3], \
# llcrnrlon=lat_log_bound[kk][0], \
# urcrnrlon=lat_log_bound[kk][1], resolution= 'f' )
# m.drawstates()
# m.drawmeridians([-100, -90, -80, -70, -60, -50, -40, ], color='k', textcolor='k', linewidth=1.5,
# zorder=None, dashes=[6, 1000], labels=[1, 0, 0, 1], labelstyle=None, fmt='%g', xoffset=None,
# yoffset=None, ax=None, latmax=None, fontsize=12)
# m.drawparallels([10, 15, 20, 25, 30, 35], color='k', textcolor='k', linewidth=1.5, zorder=None, dashes=[6, 1000],
# labels=[1, 0, 0, 1], labelstyle=None, fmt='%g', xoffset=None, yoffset=None, ax=None, latmax=None, fontsize=12)
# m.drawmapscale(-101, 8, -96, 8, 1000, barstyle='fancy', units='km', fontsize=8)
# m.drawcoastlines(linewidth=0.7, linestyle='solid', color='grey')
# m.drawcountries()
# m.shadedrelief()
# m.drawmapboundary()
# # ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]])
# # ax.text(0.05, 0.9, '('+string.ascii_lowercase[kk]+')', transform=ax.transAxes,
# # size=30)
# slp2D = pickle.load( open( dir_p[kk], "rb" ) )
# lats, lons = latlon_coords(slp2D)
# # Get the cartopy mapping object (use original data, rather than any processed data)
# cart_proj = get_cartopy(slp2D)
# # Set the GeoAxes to the projection used by WRF
# #ax = plt.axes(projection=cart_proj)
# ax = fig.add_subplot(spec[position[kk][0],position[kk][1]:position[kk][2]], projection=cart_proj)
# ax.stock_img()
# # Download and add the states and coastlines
# states = NaturalEarthFeature(category="cultural", scale="50m",
# facecolor="none",
# name="admin_1_states_provinces_shp")
# ax.add_feature(states, linewidth=.5, edgecolor="black")
# ax.coastlines('50m', linewidth=0.8)
# # Set the map bounds
# # ax.set_xlim(cartopy_xlim(slp2D))
# # ax.set_ylim(cartopy_ylim(slp2D))
# ax.set_extent(lat_log_bound[kk])
# # Show grid lines.
# gl = ax.gridlines(crs=crs.PlateCarree(), draw_labels=True,
# linewidth=1.5, color='gray', alpha=0.8, linestyle=':')
# gl.xlabel_style = {'size': 15, 'color': 'k'}
# gl.ylabel_style = {'size': 15, 'color': 'k'}
# gl.xlabels_top = False
# gl.ylabels_right = False
# c=0
# ll=[]
# rr=[]
# for i in range(real1.shape[0]):
# for j in range(real1.shape[1]):
# if j<6:
# ll.append(real1[i][j][0])
# rr.append(real1[i][j][1])
# ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, linestyle=patterns[c],\
# markersize=sizes[c], transform=crs.PlateCarree())
# c+=1
# ll=[]
# rr=[]
# for i in range(simu1.shape[0]):
# for j in range(simu1.shape[1]):
# if j<6:
# ll.append(simu1[i][j][0])
# rr.append(simu1[i][j][1])
# ax.plot( rr, ll, color = colors[c], marker=markers[c],linewidth=2, linestyle=patterns[c],\
# markersize=sizes[c], transform=crs.PlateCarree())
# c+=1
# ll=[]
# rr=[]
# for axis in ['top','bottom','left','right']:
# ax.spines[axis].set_linewidth(15)
# fig.legend(options, bbox_to_anchor=(0.87, 0.42), prop=font_wt, \
# frameon=False)
# plt.title(hurricanes[kk], {'size': 25}, **csfont)
# # plt.legend(['Real track','C0.0001', 'C0.01', 'C1', 'C100'],\
# # loc = "upper right", prop={'size': 7})
# # plt.xlabel("Lon", fontsize=135)
# # plt.ylabel("Lat", fontsize=135)
# # plt.title(hurricanes[kk], {'size': 35}, **csfont)
# # plt.show()
# plt.savefig('C:/Users/limgr/Desktop/'+hurricanes[kk]+'_wt.png', dpi=500)
# plt.show()
###################
# Plot error bars #
###################
simu_error = []
for kk in range(len(hurricanes)):
rows1=[]
Times1=[]
Times1=[]
values1=[]
real1_track=[]
with open(dir_wi[kk], mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
line_count = 0
sim_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
Times1.append(list(row.keys()))
real1_track.append(list(row.values()))
line_count += 1
else:
rows1.append(row)
values1.append(list(row.values()))
line_count += 1
print('There is totally ',(line_count-1)*(len(row)),' data points')
simu1=np.array(values1, dtype=np.float32)
real1=np.array(real1_track, dtype=np.float32)
real1=real1*0.5144444
real1=real1
simu_error1=abs(simu1-real1[:,None])/real1[:,None]#/((line_count-3)*(len(row)))
print('absolute pressure error')
print(abs(simu1-real1[:,None]))
simu_error.append(simu_error1)
par1_error_wi=np.zeros((4, 9))
par2_error_wi=np.zeros((4, 9))
par3_erro_wir=np.zeros((4, 9))
par4_error_wi=np.zeros((4, 9))
par5_error_wi=np.zeros((4, 9))
simu_error1 = simu_error[0]
simu_error2 = simu_error[1]
simu_error3 = simu_error[2]
simu_error4 = simu_error[3]
simu_error5 = simu_error[4]
par1_error_wi=np.concatenate((simu_error1[0][0][0:5],simu_error2[0][0][:],\
simu_error3[0][0][:],simu_error4[0][0][:-2],simu_error5[0][0][:]))
par1_error_wi=par1_error_wi.flatten()
par1_error_wi_mean=np.mean(par1_error_wi)
par1_error_wi_std=np.std(par1_error_wi)
par1_error_wi_low=np.percentile(par1_error_wi, 20)
par1_error_wi_hgh=np.percentile(par1_error_wi, 80)
par2_error_wi=np.concatenate((simu_error1[0][1][0:5],simu_error2[0][1][:],\
simu_error3[0][1][:],simu_error4[0][1][:-2],simu_error5[0][1][:]))
par2_error_wi=par2_error_wi.flatten()
par2_error_wi_mean=np.mean(par2_error_wi)
par2_error_wi_std=np.std(par2_error_wi)
par2_error_wi_low=np.percentile(par2_error_wi, 20)
par2_error_wi_hgh=np.percentile(par2_error_wi, 80)
par3_error_wi=np.concatenate((simu_error1[0][2][0:5],simu_error2[0][2][:],\
simu_error3[0][2][:],simu_error4[0][2][:-2],simu_error5[0][2][:]))
par3_error_wi=par3_error_wi.flatten()
par3_error_wi_mean=np.mean(par3_error_wi)
par3_error_wi_std=np.std(par3_error_wi)
par3_error_wi_low=np.percentile(par3_error_wi, 20)
par3_error_wi_hgh=np.percentile(par3_error_wi, 80)
par4_error_wi=np.concatenate((simu_error1[0][3][0:5],simu_error2[0][3][:],\
simu_error3[0][3][:],simu_error4[0][3][:-2],simu_error5[0][3][:]))
par4_error_wi=par4_error_wi.flatten()
par4_error_wi_mean=np.mean(par4_error_wi)
par4_error_wi_std=np.std(par4_error_wi)
par4_error_wi_low=np.percentile(par4_error_wi, 20)
par4_error_wi_hgh=np.percentile(par4_error_wi, 80)
par5_error_wi=np.concatenate((simu_error1[0][4][0:5],simu_error2[0][4][:],\
simu_error3[0][4][:],simu_error4[0][4][:-2],simu_error5[0][4][:]))
par5_error_wi=par5_error_wi.flatten()
par5_error_wi_mean=np.mean(par5_error_wi)
par5_error_wi_std=np.std(par5_error_wi)
par5_error_wi_low=np.percentile(par5_error_wi, 20)
par5_error_wi_hgh=np.percentile(par5_error_wi, 80)
simu_error = []
for kk in range(len(hurricanes)):
real1=[]
oussama1=[]
wrf1=[]
simu1=[]
with open( dir_wt[kk], 'r' ) as f :
data0 = f.read()
data = json.loads('[' + data0.replace('}{', '},{') + ']')
for i in range(0,len(data)):
data2 = list(data[i].values())
data3 = [e for sl in data2 for e in sl]
for j in range(len(data3)):
data3[j].pop(0)
if i==0:
real1.append(data3)
# elif i==1:
# oussama1.append(data3)
# elif i==2:
# wrf1.append(data3)
else:
simu1.append(data3)
real1 = np.array(real1, dtype=np.float32)
simu1 = np.array(simu1, dtype=np.float32)
real_r = np.radians(real1)
simu_r = np.radians(simu1)
term1=np.apply_along_axis(Calculate_Distance_Haversine1, 2, simu_r-real_r)
term2=np.apply_along_axis(Calculate_Distance_Haversine2, 2, simu_r)* \
np.apply_along_axis(Calculate_Distance_Haversine2, 2, real_r)* \
np.apply_along_axis(Calculate_Distance_Haversine3, 2, simu_r-real_r)
simu_error1=2*R*np.arcsin(np.sqrt(term1+term2))
simu_error.append(simu_error1)
par1_error=np.zeros((4, 9))
par2_error=np.zeros((4, 9))
par3_error=np.zeros((4, 9))
par4_error=np.zeros((4, 9))
par5_error=np.zeros((4, 9))
simu_error1 = simu_error[0]
simu_error2 = simu_error[1]
simu_error3 = simu_error[2]
simu_error4 = simu_error[3]
simu_error5 = simu_error[4]
par1_error_wt=np.concatenate((simu_error1[0][0:5],\
simu_error2[0][:],simu_error3[0][:],\
simu_error4[0][:-2],simu_error5[0][:]))
par1_error_wt=par1_error_wt.flatten()
par1_error_wt_mean=np.mean(par1_error_wt)
par1_error_wt_std=np.std(par1_error_wt)
par1_error_wt_low=np.percentile(par1_error_wt, 20)
par1_error_wt_hgh=np.percentile(par1_error_wt, 80)
par2_error_wt=np.concatenate((simu_error1[1][0:5],\
simu_error2[1][:],simu_error3[1][:],\
simu_error4[1][:-2],simu_error5[1][:]))
par2_error_wt=par2_error_wt.flatten()
par2_error_wt_mean=np.mean(par2_error_wt)
par2_error_wt_std=np.std(par2_error_wt)
par2_error_wt_low=np.percentile(par2_error_wt, 20)
par2_error_wt_hgh=np.percentile(par2_error_wt, 80)
par3_error_wt=np.concatenate((simu_error1[2][0:5],\
simu_error2[2][:],simu_error3[2][:],\
simu_error4[2][:-2],simu_error5[2][:]))
par3_error_wt=par3_error_wt.flatten()
par3_error_wt_mean=np.mean(par3_error_wt)
par3_error_wt_std=np.std(par3_error_wt)
par3_error_wt_low=np.percentile(par2_error_wt, 20)
par3_error_wt_hgh=np.percentile(par2_error_wt, 80)
par4_error_wt=np.concatenate((simu_error1[3][0:5],\
simu_error2[3][:],simu_error3[3][:],\
simu_error4[3][:-2],simu_error5[3][:]))
par4_error_wt=par4_error_wt.flatten()
par4_error_wt_mean=np.mean(par4_error_wt)
par4_error_wt_std=np.std(par4_error_wt)
par4_error_wt_low=np.percentile(par4_error_wt, 20)
par4_error_wt_hgh=np.percentile(par4_error_wt, 80)
par5_error_wt=np.concatenate((simu_error1[4][0:5],\
simu_error2[4][:],simu_error3[4][:],\
simu_error4[4][:-2],simu_error5[4][:]))
par5_error_wt=par5_error_wt.flatten()
par5_error_wt_mean=np.mean(par5_error_wt)
par5_error_wt_std=np.std(par5_error_wt)
par5_error_wt_low=np.percentile(par5_error_wt, 20)
par5_error_wt_hgh=np.percentile(par5_error_wt, 80)
x_pos = np.arange(len(models))
CTEs_wi = [par1_error_wi_mean,\
par2_error_wi_mean,par3_error_wi_mean,par4_error_wi_mean,par5_error_wi_mean]
errors_wi = [par1_error_wi_std,\
par2_error_wi_std,par3_error_wi_std,par4_error_wi_std,par5_error_wi_std]
percentile_10_wi = np.array([par1_error_wi_mean-par1_error_wi_low,\
par2_error_wi_mean-par2_error_wi_low,par3_error_wi_mean-par3_error_wi_low, \
par4_error_wi_mean-par4_error_wi_low,par5_error_wi_mean-par5_error_wi_low])
percentile_90_wi = np.array([par1_error_wi_hgh-par1_error_wi_mean,\
par2_error_wi_hgh-par2_error_wi_mean,par3_error_wi_hgh-par3_error_wi_mean, \
par4_error_wi_hgh-par4_error_wi_mean,par5_error_wi_hgh-par5_error_wi_mean])
err_wi = np.vstack((percentile_10_wi, percentile_90_wi))
CTEs_wt = [par1_error_wt_mean,\
par2_error_wt_mean,par3_error_wt_mean,par4_error_wt_mean,par5_error_wt_mean]
errors_wt = [par1_error_wt_std,\
par2_error_wt_std,par3_error_wt_std,par4_error_wt_std,par5_error_wt_std]
percentile_10_wt = np.array([par1_error_wt_mean-par1_error_wt_low,\
par2_error_wt_mean-par2_error_wt_low,par3_error_wt_mean-par3_error_wt_low, \
par4_error_wt_mean-par4_error_wt_low,par5_error_wt_mean-par5_error_wt_low])
percentile_90_wt = np.array([par1_error_wt_hgh-par1_error_wt_mean,\
par2_error_wt_hgh-par2_error_wt_mean,par3_error_wt_hgh-par3_error_wt_mean, \
par4_error_wt_hgh-par4_error_wt_mean,par5_error_wt_hgh-par5_error_wt_mean])
print(percentile_90_wt)
err_wt = np.vstack((percentile_10_wt, percentile_90_wt))
# fig, ax = plt.subplots(1, 2, figsize=(40, 8), sharex=True)
fig = plt.figure(figsize=(8,5))
spec = mpl.gridspec.GridSpec(ncols=8, nrows=5)
ax = fig.add_subplot(spec[1:,0:4])
ax.text(0.7, 0.9, '('+string.ascii_lowercase[0]+')', transform=ax.transAxes,
size=15, **csfont)
bars = ax.bar(x_pos, CTEs_wi, yerr=err_wi, align='center', \
color=['green','purple','darkblue', 'deepskyblue', 'tomato'], alpha=0.8,\
ecolor='k', capsize=10, edgecolor='k', linewidth=3)
for i in range(len(x_pos)):
bars[i].set(linestyle=list(linestyles.values())[0])
ax.set_ylabel(r'Normalized Intensity', **csfont, fontsize=15)
vals = ax.get_yticks()
print(vals)
ax.set_yticklabels(['{:,.0%}'.format(x) for x in vals])
ax.set_xticks(x_pos)
ax.set_xticklabels(models, **csfont, fontsize=10)
#ax.set_title(r'COAWST', **csfont, fontsize=20)
ax.yaxis.grid(True)
# ax.set_ylim([0, 0.5])
ax = fig.add_subplot(spec[1:,4:])
ax.text(0.7, 0.9, '('+string.ascii_lowercase[1]+')', transform=ax.transAxes,
size=15, **csfont)
bars = ax.bar(x_pos, CTEs_wt, yerr=err_wt, align='center', \
color=['green','purple','darkblue', 'deepskyblue', 'tomato'], alpha=0.8,\
ecolor='k', capsize=10, edgecolor='k', linewidth=3)
for i in range(len(x_pos)):
bars[i].set(linestyle=list(linestyles.values())[0])
ax.set_ylabel(r'Track Error (km)', **csfont, fontsize=15)
vals = ax.get_yticks()
ax.set_yticklabels(['{}'.format(x) for x in vals])
ax.set_xticks(x_pos)
ax.set_xticklabels(models, **csfont, fontsize=10)
#ax.set_title(r'COAWST', **csfont, fontsize=20)
ax.yaxis.grid(True)
# ax.set_ylim([0, 110])
ax = fig.add_subplot(spec[0,0:])
handles = [plt.Rectangle((0,0),1,1, facecolor=colors[i+1], \
linestyle=list(linestyles.values())[0], edgecolor = 'k', linewidth=1.5\
) for i in range(len(models))]
plt.legend(handles, models, ncol=3, bbox_to_anchor=(0.85, 0.8), prop=fontbar, \
frameon=False)
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
ax.set_yticks([])
ax.set_yticklabels([])
ax.set_xticks([])
ax.set_xticklabels([])
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_visible(False)
# for i, v in enumerate(CTEs):
# ax.text(i, v+0.02, str(round(v, 3)), color='red', fontweight='bold')
# Save the figure and show
fig.autofmt_xdate()
plt.tight_layout()
#plt.savefig('wind_intensity_bar_plot.png')
plt.savefig('C:/Users/limgr/Desktop/wi_wt_bar_plots.png', dpi=500)
plt.show()
|
import json
import logging
import asyncio
import aiohttp
import base64
import traceback
from hailtop.utils import (
time_msecs, sleep_and_backoff, is_transient_error,
time_msecs_str, humanize_timedelta_msecs)
from hailtop.tls import in_cluster_ssl_client_session
from gear import transaction
from .globals import complete_states, tasks, STATUS_FORMAT_VERSION
from .batch_configuration import KUBERNETES_TIMEOUT_IN_SECONDS, \
KUBERNETES_SERVER_URL
from .batch_format_version import BatchFormatVersion
from .spec_writer import SpecWriter
from .exceptions import NonExistentBatchError, OpenBatchError
log = logging.getLogger('batch')
def batch_record_to_dict(record):
format_version = BatchFormatVersion(record['format_version'])
if record['state'] == 'open':
state = 'open'
elif record['n_failed'] > 0:
state = 'failure'
elif record['cancelled'] or record['n_cancelled'] > 0:
state = 'cancelled'
elif record['state'] == 'complete':
assert record['n_succeeded'] == record['n_jobs']
state = 'success'
else:
state = 'running'
def _time_msecs_str(t):
if t:
return time_msecs_str(t)
return None
time_created = _time_msecs_str(record['time_created'])
time_closed = _time_msecs_str(record['time_closed'])
time_completed = _time_msecs_str(record['time_completed'])
if record['time_closed'] and record['time_completed']:
duration = humanize_timedelta_msecs(record['time_completed'] - record['time_closed'])
else:
duration = None
d = {
'id': record['id'],
'billing_project': record['billing_project'],
'state': state,
'complete': record['state'] == 'complete',
'closed': record['state'] != 'open',
'n_jobs': record['n_jobs'],
'n_completed': record['n_completed'],
'n_succeeded': record['n_succeeded'],
'n_failed': record['n_failed'],
'n_cancelled': record['n_cancelled'],
'time_created': time_created,
'time_closed': time_closed,
'time_completed': time_completed,
'duration': duration
}
attributes = json.loads(record['attributes'])
if attributes:
d['attributes'] = attributes
msec_mcpu = record['msec_mcpu']
d['msec_mcpu'] = msec_mcpu
cost = format_version.cost(record['msec_mcpu'], record['cost'])
d['cost'] = cost
return d
async def cancel_batch_in_db(db, batch_id, user):
@transaction(db)
async def cancel(tx):
record = await tx.execute_and_fetchone('''
SELECT `state` FROM batches
WHERE user = %s AND id = %s AND NOT deleted
FOR UPDATE;
''',
(user, batch_id))
if not record:
raise NonExistentBatchError(batch_id)
if record['state'] == 'open':
raise OpenBatchError(batch_id)
await tx.just_execute(
'CALL cancel_batch(%s);', (batch_id,))
await cancel() # pylint: disable=no-value-for-parameter
async def notify_batch_job_complete(db, batch_id):
record = await db.select_and_fetchone(
'''
SELECT batches.*, SUM(`usage` * rate) AS cost
FROM batches
LEFT JOIN aggregated_batch_resources
ON batches.id = aggregated_batch_resources.batch_id
LEFT JOIN resources
ON aggregated_batch_resources.resource = resources.resource
WHERE id = %s AND NOT deleted AND callback IS NOT NULL AND
batches.`state` = 'complete'
GROUP BY batches.id;
''',
(batch_id,))
if not record:
return
callback = record['callback']
log.info(f'making callback for batch {batch_id}: {callback}')
if record['user'] == 'ci':
# only jobs from CI may use batch's TLS identity
make_client_session = in_cluster_ssl_client_session
else:
make_client_session = aiohttp.ClientSession
try:
async with make_client_session(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=5)) as session:
await session.post(callback, json=batch_record_to_dict(record))
log.info(f'callback for batch {batch_id} successful')
except Exception:
log.exception(f'callback for batch {batch_id} failed, will not retry.')
async def add_attempt_resources(db, batch_id, job_id, attempt_id, resources):
if attempt_id:
try:
resource_args = [(batch_id, job_id, attempt_id, resource['name'], resource['quantity'])
for resource in resources]
await db.execute_many('''
INSERT INTO `attempt_resources` (batch_id, job_id, attempt_id, resource, quantity)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE quantity = quantity;
''',
resource_args)
except Exception:
log.exception(f'error while inserting resources for job {id}, attempt {attempt_id}')
raise
async def mark_job_complete(app, batch_id, job_id, attempt_id, instance_name, new_state,
status, start_time, end_time, reason, resources):
scheduler_state_changed = app['scheduler_state_changed']
cancel_ready_state_changed = app['cancel_ready_state_changed']
db = app['db']
inst_pool = app['inst_pool']
id = (batch_id, job_id)
log.info(f'marking job {id} complete new_state {new_state}')
now = time_msecs()
try:
rv = await db.execute_and_fetchone(
'CALL mark_job_complete(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);',
(batch_id, job_id, attempt_id, instance_name, new_state,
json.dumps(status) if status is not None else None,
start_time, end_time, reason, now))
except Exception:
log.exception(f'error while marking job {id} complete on instance {instance_name}')
raise
scheduler_state_changed.set()
cancel_ready_state_changed.set()
if instance_name:
instance = inst_pool.name_instance.get(instance_name)
if instance:
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
# may also create scheduling opportunities, set above
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
else:
log.warning(f'mark_complete for job {id} from unknown {instance}')
await add_attempt_resources(db, batch_id, job_id, attempt_id, resources)
if rv['rc'] != 0:
log.info(f'mark_job_complete returned {rv} for job {id}')
return
old_state = rv['old_state']
if old_state in complete_states:
log.info(f'old_state {old_state} complete for job {id}, doing nothing')
# already complete, do nothing
return
log.info(f'job {id} changed state: {rv['old_state']} => {new_state}')
await notify_batch_job_complete(db, batch_id)
async def mark_job_started(app, batch_id, job_id, attempt_id, instance, start_time, resources):
db = app['db']
id = (batch_id, job_id)
log.info(f'mark job {id} started')
try:
rv = await db.execute_and_fetchone(
'''
CALL mark_job_started(%s, %s, %s, %s, %s);
''',
(batch_id, job_id, attempt_id, instance.name, start_time))
except Exception:
log.exception(f'error while marking job {id} started on {instance}')
raise
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
await add_attempt_resources(db, batch_id, job_id, attempt_id, resources)
def job_record_to_dict(record, name):
format_version = BatchFormatVersion(record['format_version'])
db_status = record['status']
if db_status:
db_status = json.loads(db_status)
exit_code, duration = format_version.get_status_exit_code_duration(db_status)
else:
exit_code = None
duration = None
result = {
'batch_id': record['batch_id'],
'job_id': record['job_id'],
'name': name,
'state': record['state'],
'exit_code': exit_code,
'duration': duration
}
msec_mcpu = record['msec_mcpu']
result['msec_mcpu'] = msec_mcpu
cost = format_version.cost(record['msec_mcpu'], record['cost'])
result['cost'] = cost
return result
async def unschedule_job(app, record):
cancel_ready_state_changed = app['cancel_ready_state_changed']
scheduler_state_changed = app['scheduler_state_changed']
db = app['db']
inst_pool = app['inst_pool']
batch_id = record['batch_id']
job_id = record['job_id']
attempt_id = record['attempt_id']
id = (batch_id, job_id)
instance_name = record['instance_name']
assert instance_name is not None
log.info(f'unscheduling job {id}, attempt {attempt_id} from instance {instance_name}')
end_time = time_msecs()
try:
rv = await db.execute_and_fetchone(
'CALL unschedule_job(%s, %s, %s, %s, %s, %s);',
(batch_id, job_id, attempt_id, instance_name, end_time, 'cancelled'))
except Exception:
log.exception(f'error while unscheduling job {id} on instance {instance_name}')
raise
log.info(f'unschedule job {id}: updated database {rv}')
# job that was running is now ready to be cancelled
cancel_ready_state_changed.set()
instance = inst_pool.name_instance.get(instance_name)
if not instance:
log.warning(f'unschedule job {id}, attempt {attempt_id}: unknown instance {instance_name}')
return
if rv['delta_cores_mcpu'] and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
scheduler_state_changed.set()
log.info(f'unschedule job {id}, attempt {attempt_id}: updated {instance} free cores')
url = (f'http://{instance.ip_address}:5000'
f'/api/v1alpha/batches/{batch_id}/jobs/{job_id}/delete')
delay = 0.1
while True:
if instance.state in ('inactive', 'deleted'):
break
try:
async with aiohttp.ClientSession(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=60)) as session:
await session.delete(url)
await instance.mark_healthy()
break
except Exception as e:
if (isinstance(e, aiohttp.ClientResponseError)
and e.status == 404): # pylint: disable=no-member
await instance.mark_healthy()
break
await instance.incr_failed_request_count()
if is_transient_error(e):
pass
else:
raise
delay = await sleep_and_backoff(delay)
log.info(f'unschedule job {id}, attempt {attempt_id}: called delete job')
async def job_config(app, record, attempt_id):
k8s_cache = app['k8s_cache']
db = app['db']
format_version = BatchFormatVersion(record['format_version'])
batch_id = record['batch_id']
job_id = record['job_id']
db_spec = json.loads(record['spec'])
if format_version.has_full_spec_in_gcs():
job_spec = {
'secrets': format_version.get_spec_secrets(db_spec),
'service_account': format_version.get_spec_service_account(db_spec)
}
else:
job_spec = db_spec
job_spec['attempt_id'] = attempt_id
userdata = json.loads(record['userdata'])
secrets = job_spec.get('secrets', [])
k8s_secrets = await asyncio.gather(*[
k8s_cache.read_secret(
secret['name'], secret['namespace'],
KUBERNETES_TIMEOUT_IN_SECONDS)
for secret in secrets
])
gsa_key = None
for secret, k8s_secret in zip(secrets, k8s_secrets):
if secret['name'] == userdata['gsa_key_secret_name']:
gsa_key = k8s_secret.data
secret['data'] = k8s_secret.data
assert gsa_key
service_account = job_spec.get('service_account')
if service_account:
namespace = service_account['namespace']
name = service_account['name']
sa = await k8s_cache.read_service_account(
name, namespace, KUBERNETES_TIMEOUT_IN_SECONDS)
assert len(sa.secrets) == 1
token_secret_name = sa.secrets[0].name
secret = await k8s_cache.read_secret(
token_secret_name, namespace, KUBERNETES_TIMEOUT_IN_SECONDS)
token = base64.b64decode(secret.data['token']).decode()
cert = secret.data['ca.crt']
kube_config = f'''
apiVersion: v1
clusters:
- cluster:
certificate-authority: /.kube/ca.crt
server: {KUBERNETES_SERVER_URL}
name: default-cluster
contexts:
- context:
cluster: default-cluster
user: {namespace}-{name}
namespace: {namespace}
name: default-context
current-context: default-context
kind: Config
preferences: {{}}
users:
- name: {namespace}-{name}
user:
token: {token}
'''
job_spec['secrets'].append({
'name': 'kube-config',
'mount_path': '/.kube',
'data': {'config': base64.b64encode(kube_config.encode()).decode(),
'ca.crt': cert}
})
env = job_spec.get('env')
if not env:
env = []
job_spec['env'] = env
env.append({'name': 'KUBECONFIG',
'value': '/.kube/config'})
if format_version.has_full_spec_in_gcs():
token, start_job_id = await SpecWriter.get_token_start_id(db, batch_id, job_id)
else:
token = None
start_job_id = None
return {
'batch_id': batch_id,
'job_id': job_id,
'format_version': format_version.format_version,
'token': token,
'start_job_id': start_job_id,
'user': record['user'],
'gsa_key': gsa_key,
'job_spec': job_spec
}
async def schedule_job(app, record, instance):
assert instance.state == 'active'
log_store = app['log_store']
db = app['db']
batch_id = record['batch_id']
job_id = record['job_id']
attempt_id = record['attempt_id']
format_version = BatchFormatVersion(record['format_version'])
id = (batch_id, job_id)
try:
try:
body = await job_config(app, record, attempt_id)
except Exception:
log.exception('while making job config')
status = {
'version': STATUS_FORMAT_VERSION,
'worker': None,
'batch_id': batch_id,
'job_id': job_id,
'attempt_id': attempt_id,
'user': record['user'],
'state': 'error',
'error': traceback.format_exc(),
'container_statuses': {k: {} for k in tasks}
}
if format_version.has_full_status_in_gcs():
await log_store.write_status_file(batch_id, job_id, attempt_id, json.dumps(status))
db_status = format_version.db_status(status)
resources = []
await mark_job_complete(app, batch_id, job_id, attempt_id, instance.name,
'Error', db_status, None, None, 'error', resources)
raise
log.info(f'schedule job {id} on {instance}: made job config')
try:
async with aiohttp.ClientSession(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=2)) as session:
url = (f'http://{instance.ip_address}:5000'
f'/api/v1alpha/batches/jobs/create')
await session.post(url, json=body)
await instance.mark_healthy()
except aiohttp.ClientResponseError as e:
await instance.mark_healthy()
if e.status == 403:
log.info(f'attempt already exists for job {id} on {instance}, aborting')
raise e
except Exception:
await instance.incr_failed_request_count()
raise
log.info(f'schedule job {id} on {instance}: called create job')
rv = await db.execute_and_fetchone(
'''
CALL schedule_job(%s, %s, %s, %s);
''',
(batch_id, job_id, attempt_id, instance.name))
except Exception:
log.exception(f'error while scheduling job {id} on {instance}')
if instance.state == 'active':
instance.adjust_free_cores_in_memory(record['cores_mcpu'])
return
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
log.info(f'schedule job {id} on {instance}: updated database')
if rv['rc'] != 0:
log.info(f'could not schedule job {id}, attempt {attempt_id} on {instance}, {rv}')
return
log.info(f'success scheduling job {id} on {instance}')
| import json
import logging
import asyncio
import aiohttp
import base64
import traceback
from hailtop.utils import (
time_msecs, sleep_and_backoff, is_transient_error,
time_msecs_str, humanize_timedelta_msecs)
from hailtop.tls import in_cluster_ssl_client_session
from gear import transaction
from .globals import complete_states, tasks, STATUS_FORMAT_VERSION
from .batch_configuration import KUBERNETES_TIMEOUT_IN_SECONDS, \
KUBERNETES_SERVER_URL
from .batch_format_version import BatchFormatVersion
from .spec_writer import SpecWriter
from .exceptions import NonExistentBatchError, OpenBatchError
log = logging.getLogger('batch')
def batch_record_to_dict(record):
format_version = BatchFormatVersion(record['format_version'])
if record['state'] == 'open':
state = 'open'
elif record['n_failed'] > 0:
state = 'failure'
elif record['cancelled'] or record['n_cancelled'] > 0:
state = 'cancelled'
elif record['state'] == 'complete':
assert record['n_succeeded'] == record['n_jobs']
state = 'success'
else:
state = 'running'
def _time_msecs_str(t):
if t:
return time_msecs_str(t)
return None
time_created = _time_msecs_str(record['time_created'])
time_closed = _time_msecs_str(record['time_closed'])
time_completed = _time_msecs_str(record['time_completed'])
if record['time_closed'] and record['time_completed']:
duration = humanize_timedelta_msecs(record['time_completed'] - record['time_closed'])
else:
duration = None
d = {
'id': record['id'],
'billing_project': record['billing_project'],
'state': state,
'complete': record['state'] == 'complete',
'closed': record['state'] != 'open',
'n_jobs': record['n_jobs'],
'n_completed': record['n_completed'],
'n_succeeded': record['n_succeeded'],
'n_failed': record['n_failed'],
'n_cancelled': record['n_cancelled'],
'time_created': time_created,
'time_closed': time_closed,
'time_completed': time_completed,
'duration': duration
}
attributes = json.loads(record['attributes'])
if attributes:
d['attributes'] = attributes
msec_mcpu = record['msec_mcpu']
d['msec_mcpu'] = msec_mcpu
cost = format_version.cost(record['msec_mcpu'], record['cost'])
d['cost'] = cost
return d
async def cancel_batch_in_db(db, batch_id, user):
@transaction(db)
async def cancel(tx):
record = await tx.execute_and_fetchone('''
SELECT `state` FROM batches
WHERE user = %s AND id = %s AND NOT deleted
FOR UPDATE;
''',
(user, batch_id))
if not record:
raise NonExistentBatchError(batch_id)
if record['state'] == 'open':
raise OpenBatchError(batch_id)
await tx.just_execute(
'CALL cancel_batch(%s);', (batch_id,))
await cancel() # pylint: disable=no-value-for-parameter
async def notify_batch_job_complete(db, batch_id):
record = await db.select_and_fetchone(
'''
SELECT batches.*, SUM(`usage` * rate) AS cost
FROM batches
LEFT JOIN aggregated_batch_resources
ON batches.id = aggregated_batch_resources.batch_id
LEFT JOIN resources
ON aggregated_batch_resources.resource = resources.resource
WHERE id = %s AND NOT deleted AND callback IS NOT NULL AND
batches.`state` = 'complete'
GROUP BY batches.id;
''',
(batch_id,))
if not record:
return
callback = record['callback']
log.info(f'making callback for batch {batch_id}: {callback}')
if record['user'] == 'ci':
# only jobs from CI may use batch's TLS identity
make_client_session = in_cluster_ssl_client_session
else:
make_client_session = aiohttp.ClientSession
try:
async with make_client_session(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=5)) as session:
await session.post(callback, json=batch_record_to_dict(record))
log.info(f'callback for batch {batch_id} successful')
except Exception:
log.exception(f'callback for batch {batch_id} failed, will not retry.')
async def add_attempt_resources(db, batch_id, job_id, attempt_id, resources):
if attempt_id:
try:
resource_args = [(batch_id, job_id, attempt_id, resource['name'], resource['quantity'])
for resource in resources]
await db.execute_many('''
INSERT INTO `attempt_resources` (batch_id, job_id, attempt_id, resource, quantity)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE quantity = quantity;
''',
resource_args)
except Exception:
log.exception(f'error while inserting resources for job {id}, attempt {attempt_id}')
raise
async def mark_job_complete(app, batch_id, job_id, attempt_id, instance_name, new_state,
status, start_time, end_time, reason, resources):
scheduler_state_changed = app['scheduler_state_changed']
cancel_ready_state_changed = app['cancel_ready_state_changed']
db = app['db']
inst_pool = app['inst_pool']
id = (batch_id, job_id)
log.info(f'marking job {id} complete new_state {new_state}')
now = time_msecs()
try:
rv = await db.execute_and_fetchone(
'CALL mark_job_complete(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);',
(batch_id, job_id, attempt_id, instance_name, new_state,
json.dumps(status) if status is not None else None,
start_time, end_time, reason, now))
except Exception:
log.exception(f'error while marking job {id} complete on instance {instance_name}')
raise
scheduler_state_changed.set()
cancel_ready_state_changed.set()
if instance_name:
instance = inst_pool.name_instance.get(instance_name)
if instance:
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
# may also create scheduling opportunities, set above
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
else:
log.warning(f'mark_complete for job {id} from unknown {instance}')
await add_attempt_resources(db, batch_id, job_id, attempt_id, resources)
if rv['rc'] != 0:
log.info(f'mark_job_complete returned {rv} for job {id}')
return
old_state = rv['old_state']
if old_state in complete_states:
log.info(f'old_state {old_state} complete for job {id}, doing nothing')
# already complete, do nothing
return
log.info(f'job {id} changed state: {rv["old_state"]} => {new_state}')
await notify_batch_job_complete(db, batch_id)
async def mark_job_started(app, batch_id, job_id, attempt_id, instance, start_time, resources):
db = app['db']
id = (batch_id, job_id)
log.info(f'mark job {id} started')
try:
rv = await db.execute_and_fetchone(
'''
CALL mark_job_started(%s, %s, %s, %s, %s);
''',
(batch_id, job_id, attempt_id, instance.name, start_time))
except Exception:
log.exception(f'error while marking job {id} started on {instance}')
raise
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
await add_attempt_resources(db, batch_id, job_id, attempt_id, resources)
def job_record_to_dict(record, name):
format_version = BatchFormatVersion(record['format_version'])
db_status = record['status']
if db_status:
db_status = json.loads(db_status)
exit_code, duration = format_version.get_status_exit_code_duration(db_status)
else:
exit_code = None
duration = None
result = {
'batch_id': record['batch_id'],
'job_id': record['job_id'],
'name': name,
'state': record['state'],
'exit_code': exit_code,
'duration': duration
}
msec_mcpu = record['msec_mcpu']
result['msec_mcpu'] = msec_mcpu
cost = format_version.cost(record['msec_mcpu'], record['cost'])
result['cost'] = cost
return result
async def unschedule_job(app, record):
cancel_ready_state_changed = app['cancel_ready_state_changed']
scheduler_state_changed = app['scheduler_state_changed']
db = app['db']
inst_pool = app['inst_pool']
batch_id = record['batch_id']
job_id = record['job_id']
attempt_id = record['attempt_id']
id = (batch_id, job_id)
instance_name = record['instance_name']
assert instance_name is not None
log.info(f'unscheduling job {id}, attempt {attempt_id} from instance {instance_name}')
end_time = time_msecs()
try:
rv = await db.execute_and_fetchone(
'CALL unschedule_job(%s, %s, %s, %s, %s, %s);',
(batch_id, job_id, attempt_id, instance_name, end_time, 'cancelled'))
except Exception:
log.exception(f'error while unscheduling job {id} on instance {instance_name}')
raise
log.info(f'unschedule job {id}: updated database {rv}')
# job that was running is now ready to be cancelled
cancel_ready_state_changed.set()
instance = inst_pool.name_instance.get(instance_name)
if not instance:
log.warning(f'unschedule job {id}, attempt {attempt_id}: unknown instance {instance_name}')
return
if rv['delta_cores_mcpu'] and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
scheduler_state_changed.set()
log.info(f'unschedule job {id}, attempt {attempt_id}: updated {instance} free cores')
url = (f'http://{instance.ip_address}:5000'
f'/api/v1alpha/batches/{batch_id}/jobs/{job_id}/delete')
delay = 0.1
while True:
if instance.state in ('inactive', 'deleted'):
break
try:
async with aiohttp.ClientSession(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=60)) as session:
await session.delete(url)
await instance.mark_healthy()
break
except Exception as e:
if (isinstance(e, aiohttp.ClientResponseError)
and e.status == 404): # pylint: disable=no-member
await instance.mark_healthy()
break
await instance.incr_failed_request_count()
if is_transient_error(e):
pass
else:
raise
delay = await sleep_and_backoff(delay)
log.info(f'unschedule job {id}, attempt {attempt_id}: called delete job')
async def job_config(app, record, attempt_id):
k8s_cache = app['k8s_cache']
db = app['db']
format_version = BatchFormatVersion(record['format_version'])
batch_id = record['batch_id']
job_id = record['job_id']
db_spec = json.loads(record['spec'])
if format_version.has_full_spec_in_gcs():
job_spec = {
'secrets': format_version.get_spec_secrets(db_spec),
'service_account': format_version.get_spec_service_account(db_spec)
}
else:
job_spec = db_spec
job_spec['attempt_id'] = attempt_id
userdata = json.loads(record['userdata'])
secrets = job_spec.get('secrets', [])
k8s_secrets = await asyncio.gather(*[
k8s_cache.read_secret(
secret['name'], secret['namespace'],
KUBERNETES_TIMEOUT_IN_SECONDS)
for secret in secrets
])
gsa_key = None
for secret, k8s_secret in zip(secrets, k8s_secrets):
if secret['name'] == userdata['gsa_key_secret_name']:
gsa_key = k8s_secret.data
secret['data'] = k8s_secret.data
assert gsa_key
service_account = job_spec.get('service_account')
if service_account:
namespace = service_account['namespace']
name = service_account['name']
sa = await k8s_cache.read_service_account(
name, namespace, KUBERNETES_TIMEOUT_IN_SECONDS)
assert len(sa.secrets) == 1
token_secret_name = sa.secrets[0].name
secret = await k8s_cache.read_secret(
token_secret_name, namespace, KUBERNETES_TIMEOUT_IN_SECONDS)
token = base64.b64decode(secret.data['token']).decode()
cert = secret.data['ca.crt']
kube_config = f'''
apiVersion: v1
clusters:
- cluster:
certificate-authority: /.kube/ca.crt
server: {KUBERNETES_SERVER_URL}
name: default-cluster
contexts:
- context:
cluster: default-cluster
user: {namespace}-{name}
namespace: {namespace}
name: default-context
current-context: default-context
kind: Config
preferences: {{}}
users:
- name: {namespace}-{name}
user:
token: {token}
'''
job_spec['secrets'].append({
'name': 'kube-config',
'mount_path': '/.kube',
'data': {'config': base64.b64encode(kube_config.encode()).decode(),
'ca.crt': cert}
})
env = job_spec.get('env')
if not env:
env = []
job_spec['env'] = env
env.append({'name': 'KUBECONFIG',
'value': '/.kube/config'})
if format_version.has_full_spec_in_gcs():
token, start_job_id = await SpecWriter.get_token_start_id(db, batch_id, job_id)
else:
token = None
start_job_id = None
return {
'batch_id': batch_id,
'job_id': job_id,
'format_version': format_version.format_version,
'token': token,
'start_job_id': start_job_id,
'user': record['user'],
'gsa_key': gsa_key,
'job_spec': job_spec
}
async def schedule_job(app, record, instance):
assert instance.state == 'active'
log_store = app['log_store']
db = app['db']
batch_id = record['batch_id']
job_id = record['job_id']
attempt_id = record['attempt_id']
format_version = BatchFormatVersion(record['format_version'])
id = (batch_id, job_id)
try:
try:
body = await job_config(app, record, attempt_id)
except Exception:
log.exception('while making job config')
status = {
'version': STATUS_FORMAT_VERSION,
'worker': None,
'batch_id': batch_id,
'job_id': job_id,
'attempt_id': attempt_id,
'user': record['user'],
'state': 'error',
'error': traceback.format_exc(),
'container_statuses': {k: {} for k in tasks}
}
if format_version.has_full_status_in_gcs():
await log_store.write_status_file(batch_id, job_id, attempt_id, json.dumps(status))
db_status = format_version.db_status(status)
resources = []
await mark_job_complete(app, batch_id, job_id, attempt_id, instance.name,
'Error', db_status, None, None, 'error', resources)
raise
log.info(f'schedule job {id} on {instance}: made job config')
try:
async with aiohttp.ClientSession(
raise_for_status=True, timeout=aiohttp.ClientTimeout(total=2)) as session:
url = (f'http://{instance.ip_address}:5000'
f'/api/v1alpha/batches/jobs/create')
await session.post(url, json=body)
await instance.mark_healthy()
except aiohttp.ClientResponseError as e:
await instance.mark_healthy()
if e.status == 403:
log.info(f'attempt already exists for job {id} on {instance}, aborting')
raise e
except Exception:
await instance.incr_failed_request_count()
raise
log.info(f'schedule job {id} on {instance}: called create job')
rv = await db.execute_and_fetchone(
'''
CALL schedule_job(%s, %s, %s, %s);
''',
(batch_id, job_id, attempt_id, instance.name))
except Exception:
log.exception(f'error while scheduling job {id} on {instance}')
if instance.state == 'active':
instance.adjust_free_cores_in_memory(record['cores_mcpu'])
return
if rv['delta_cores_mcpu'] != 0 and instance.state == 'active':
instance.adjust_free_cores_in_memory(rv['delta_cores_mcpu'])
log.info(f'schedule job {id} on {instance}: updated database')
if rv['rc'] != 0:
log.info(f'could not schedule job {id}, attempt {attempt_id} on {instance}, {rv}')
return
log.info(f'success scheduling job {id} on {instance}')
|
# coding: utf-8
__author__ = 'cleardusk'
import sys
import argparse
import cv2
import yaml
import os
import json
# from FaceBoxes import FaceBoxes
from TDDFA import TDDFA
from utils.render import render
from utils.render_ctypes import render # faster
from utils.depth import depth
# from utils.pncc import pncc
# from utils.uv import uv_tex
# from utils.pose import viz_pose
from utils.serialization import ser_to_ply, ser_to_obj
from utils.functions import draw_landmarks, get_suffix
from utils.tddfa_util import str2bool
def read_image(image_path):
"""
Read an image from input path
params:
- image_local_path (str): the path of image.
return:
- image: Required image.
"""
LOCAL_ROOT = '/frdata/CAS/CELEBA_SPOOF_DATASET/CelebA_Spoof/'
# image_path = LOCAL_ROOT + image_path
crop_path = image_path[:-4]+"_crop"+image_path[-4:]
wfp = image_path[:-4]+"_depth_3DDFA"+image_path[-4:]
img = cv2.imread(image_path)
if img is None:
print("Image None!!")
real_h,real_w,c = img.shape
assert os.path.exists(image_path[:-4] + '_BB.txt'),'path not exists' + ' ' + image_path
crop_path = image_path[:-4]+"_crop"+image_path[-4:]
# if os.path.exists(crop_path):
# return None, None, None
with open(image_path[:-4] + '_BB.txt','r') as f:
material = f.readline()
try:
x,y,w,h,score = material.strip().split(' ')
except:
logging.info('Bounding Box of' + ' ' + image_path + ' ' + 'is wrong')
try:
w = int(float(w))
h = int(float(h))
x = int(float(x))
y = int(float(y))
w = int(w*(real_w / 224))
h = int(h*(real_h / 224))
x = int(x*(real_w / 224))
y = int(y*(real_h / 224))
# Crop face based on its bounding box
y1 = 0 if y < 0 else y
x1 = 0 if x < 0 else x
y2 = real_h if y1 + h > real_h else y + h
x2 = real_w if x1 + w > real_w else x + w
boxes = [[x1, y1, x2, y2, 100.0]]
# img = img[y1:y2,x1:x2,:]
except:
logging.info('Cropping Bounding Box of' + ' ' + image_path + ' ' + 'goes wrong')
return img, wfp, boxes
def main(args):
cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
# Init FaceBoxes and TDDFA, recommend using onnx flag
if args.onnx:
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ['OMP_NUM_THREADS'] = '4'
# from FaceBoxes.FaceBoxes_ONNX import FaceBoxes_ONNX
from TDDFA_ONNX import TDDFA_ONNX
# face_boxes = FaceBoxes_ONNX()
tddfa = TDDFA_ONNX(**cfg)
else:
gpu_mode = args.mode == 'gpu'
tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)
# face_boxes = FaceBoxes()
# Given a still image path and load to BGR channel
LOCAL_ROOT = '/frdata/CAS/CELEBA_SPOOF_DATASET/CelebA_Spoof/'
LOCAL_IMAGE_LIST_PATH = 'metas/intra_test/test_label.json'
with open(LOCAL_ROOT+LOCAL_IMAGE_LIST_PATH) as f:
image_list = json.load(f)
print("got local image list, {} image".format(len(image_list.keys())))
#Batch_size = 1024
#logging.info("Batch_size=, {}".format(Batch_size))
n=0
# image_list = ['/media/zpartialartist/Shared/JioVSE_color/JioFAS/3DDFA_V2/5966/spoof/497050.png']
for idx,image_id in enumerate(image_list):
# for image_id in (image_list):
print("image_id = ", image_id)
# get image from local file
if n==5:
break
try:
n += 1
print(image_id)
print(n)
img, wfp, boxes = read_image(image_id)
if img is None:
print("Nones recieved in read_image")
continue
param_lst, roi_box_lst = tddfa(img, boxes)
# Visualization and serialization
# new_suffix = args.opt
# if new_suffix not in ('ply', 'obj'):
# new_suffix = '.jpg'
# wfp = f'examples/results/{args.img_fp.split('/')[-1].replace(old_suffix, '')}_{args.opt}' + new_suffix
# wfp = image_path[:-4]+"_depth_3DDFA"+image_path[-4:]
ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag='depth')
depth(img, ver_lst, tddfa.tri, show_flag=args.show_flag, wfp=wfp, with_bg_flag=False)
# else:
# raise ValueError(f'Unknown opt {args.opt}')
except:
# logging.info("Failed to read image: {}".format(image_id))
raise
# img = cv2.imread(args.img_fp)
# Detect faces, get 3DMM params and roi boxes
# boxes = face_boxes(img)
# n = len(boxes)
# if n == 0:
# print(f'No face detected, exit')
# sys.exit(-1)
# print(f'Detect {n} faces')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='The demo of still image of 3DDFA_V2')
parser.add_argument('-c', '--config', type=str, default='configs/mb1_120x120.yml')
parser.add_argument('-f', '--img_fp', type=str, default='examples/inputs/trump_hillary.jpg')
parser.add_argument('-m', '--mode', type=str, default='gpu', help='gpu or cpu mode')
parser.add_argument('-o', '--opt', type=str, default='depth',
choices=['2d_sparse', '2d_dense', '3d', 'depth', 'pncc', 'uv_tex', 'pose', 'ply', 'obj'])
parser.add_argument('--show_flag', type=str2bool, default='False', help='whether to show the visualization result')
parser.add_argument('--onnx', action='store_true', default=False)
args = parser.parse_args()
main(args)
| # coding: utf-8
__author__ = 'cleardusk'
import sys
import argparse
import cv2
import yaml
import os
import json
# from FaceBoxes import FaceBoxes
from TDDFA import TDDFA
from utils.render import render
from utils.render_ctypes import render # faster
from utils.depth import depth
# from utils.pncc import pncc
# from utils.uv import uv_tex
# from utils.pose import viz_pose
from utils.serialization import ser_to_ply, ser_to_obj
from utils.functions import draw_landmarks, get_suffix
from utils.tddfa_util import str2bool
def read_image(image_path):
"""
Read an image from input path
params:
- image_local_path (str): the path of image.
return:
- image: Required image.
"""
LOCAL_ROOT = '/frdata/CAS/CELEBA_SPOOF_DATASET/CelebA_Spoof/'
# image_path = LOCAL_ROOT + image_path
crop_path = image_path[:-4]+"_crop"+image_path[-4:]
wfp = image_path[:-4]+"_depth_3DDFA"+image_path[-4:]
img = cv2.imread(image_path)
if img is None:
print("Image None!!")
real_h,real_w,c = img.shape
assert os.path.exists(image_path[:-4] + '_BB.txt'),'path not exists' + ' ' + image_path
crop_path = image_path[:-4]+"_crop"+image_path[-4:]
# if os.path.exists(crop_path):
# return None, None, None
with open(image_path[:-4] + '_BB.txt','r') as f:
material = f.readline()
try:
x,y,w,h,score = material.strip().split(' ')
except:
logging.info('Bounding Box of' + ' ' + image_path + ' ' + 'is wrong')
try:
w = int(float(w))
h = int(float(h))
x = int(float(x))
y = int(float(y))
w = int(w*(real_w / 224))
h = int(h*(real_h / 224))
x = int(x*(real_w / 224))
y = int(y*(real_h / 224))
# Crop face based on its bounding box
y1 = 0 if y < 0 else y
x1 = 0 if x < 0 else x
y2 = real_h if y1 + h > real_h else y + h
x2 = real_w if x1 + w > real_w else x + w
boxes = [[x1, y1, x2, y2, 100.0]]
# img = img[y1:y2,x1:x2,:]
except:
logging.info('Cropping Bounding Box of' + ' ' + image_path + ' ' + 'goes wrong')
return img, wfp, boxes
def main(args):
cfg = yaml.load(open(args.config), Loader=yaml.SafeLoader)
# Init FaceBoxes and TDDFA, recommend using onnx flag
if args.onnx:
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ['OMP_NUM_THREADS'] = '4'
# from FaceBoxes.FaceBoxes_ONNX import FaceBoxes_ONNX
from TDDFA_ONNX import TDDFA_ONNX
# face_boxes = FaceBoxes_ONNX()
tddfa = TDDFA_ONNX(**cfg)
else:
gpu_mode = args.mode == 'gpu'
tddfa = TDDFA(gpu_mode=gpu_mode, **cfg)
# face_boxes = FaceBoxes()
# Given a still image path and load to BGR channel
LOCAL_ROOT = '/frdata/CAS/CELEBA_SPOOF_DATASET/CelebA_Spoof/'
LOCAL_IMAGE_LIST_PATH = 'metas/intra_test/test_label.json'
with open(LOCAL_ROOT+LOCAL_IMAGE_LIST_PATH) as f:
image_list = json.load(f)
print("got local image list, {} image".format(len(image_list.keys())))
#Batch_size = 1024
#logging.info("Batch_size=, {}".format(Batch_size))
n=0
# image_list = ['/media/zpartialartist/Shared/JioVSE_color/JioFAS/3DDFA_V2/5966/spoof/497050.png']
for idx,image_id in enumerate(image_list):
# for image_id in (image_list):
print("image_id = ", image_id)
# get image from local file
if n==5:
break
try:
n += 1
print(image_id)
print(n)
img, wfp, boxes = read_image(image_id)
if img is None:
print("Nones recieved in read_image")
continue
param_lst, roi_box_lst = tddfa(img, boxes)
# Visualization and serialization
# new_suffix = args.opt
# if new_suffix not in ('ply', 'obj'):
# new_suffix = '.jpg'
# wfp = f'examples/results/{args.img_fp.split("/")[-1].replace(old_suffix, "")}_{args.opt}' + new_suffix
# wfp = image_path[:-4]+"_depth_3DDFA"+image_path[-4:]
ver_lst = tddfa.recon_vers(param_lst, roi_box_lst, dense_flag='depth')
depth(img, ver_lst, tddfa.tri, show_flag=args.show_flag, wfp=wfp, with_bg_flag=False)
# else:
# raise ValueError(f'Unknown opt {args.opt}')
except:
# logging.info("Failed to read image: {}".format(image_id))
raise
# img = cv2.imread(args.img_fp)
# Detect faces, get 3DMM params and roi boxes
# boxes = face_boxes(img)
# n = len(boxes)
# if n == 0:
# print(f'No face detected, exit')
# sys.exit(-1)
# print(f'Detect {n} faces')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='The demo of still image of 3DDFA_V2')
parser.add_argument('-c', '--config', type=str, default='configs/mb1_120x120.yml')
parser.add_argument('-f', '--img_fp', type=str, default='examples/inputs/trump_hillary.jpg')
parser.add_argument('-m', '--mode', type=str, default='gpu', help='gpu or cpu mode')
parser.add_argument('-o', '--opt', type=str, default='depth',
choices=['2d_sparse', '2d_dense', '3d', 'depth', 'pncc', 'uv_tex', 'pose', 'ply', 'obj'])
parser.add_argument('--show_flag', type=str2bool, default='False', help='whether to show the visualization result')
parser.add_argument('--onnx', action='store_true', default=False)
args = parser.parse_args()
main(args)
|
import logging
import re
from pathlib import Path
from typing import Any, Dict, List
from hyperstyle.src.python.review.common.subprocess_runner import run_in_subprocess
from hyperstyle.src.python.review.inspectors.base_inspector import BaseInspector
from hyperstyle.src.python.review.inspectors.common import convert_percentage_of_value_to_lack_of_value
from hyperstyle.src.python.review.inspectors.flake8.issue_types import CODE_PREFIX_TO_ISSUE_TYPE, CODE_TO_ISSUE_TYPE
from hyperstyle.src.python.review.inspectors.inspector_type import InspectorType
from hyperstyle.src.python.review.inspectors.issue import (
BaseIssue,
CodeIssue,
CohesionIssue,
CyclomaticComplexityIssue,
IssueData,
IssueDifficulty,
IssueType,
LineLenIssue,
)
from hyperstyle.src.python.review.inspectors.tips import (
get_cohesion_tip, get_cyclomatic_complexity_tip, get_line_len_tip, get_magic_number_tip,
)
logger = logging.getLogger(__name__)
PATH_FLAKE8_CONFIG = Path(__file__).parent / '.flake8'
# To make the whitelist, a list of words was examined based on students' solutions
# that were flagged by flake8-spellcheck as erroneous. In general, the whitelist included those words
# that belonged to library methods and which were common abbreviations.
PATH_FLAKE8_SPELLCHECK_WHITELIST = Path(__file__).parent / 'whitelist.txt'
FORMAT = '%(path)s:%(row)d:%(col)d:%(code)s:%(text)s'
INSPECTOR_NAME = 'flake8'
class Flake8Inspector(BaseInspector):
inspector_type = InspectorType.FLAKE8
@classmethod
def inspect(cls, path: Path, config: Dict[str, Any]) -> List[BaseIssue]:
command = [
'flake8',
f'--format={FORMAT}',
f'--config={PATH_FLAKE8_CONFIG}',
f'--whitelist={PATH_FLAKE8_SPELLCHECK_WHITELIST}',
'--max-complexity', '0',
'--cohesion-below', '100',
path,
]
output = run_in_subprocess(command)
return cls.parse(output)
@classmethod
def parse(cls, output: str) -> List[BaseIssue]:
row_re = re.compile(r'^(.*):(\d+):(\d+):([A-Z]+\d{3}):(.*)$', re.M)
cc_description_re = re.compile(r"'(.+)' is too complex \((\d+)\)")
cohesion_description_re = re.compile(r"class has low \((\d*\.?\d*)%\) cohesion")
line_len_description_re = re.compile(r"line too long \((\d+) > \d+ characters\)")
issues: List[BaseIssue] = []
for groups in row_re.findall(output):
description = groups[4]
origin_class = groups[3]
cc_match = cc_description_re.match(description)
cohesion_match = cohesion_description_re.match(description)
line_len_match = line_len_description_re.match(description)
file_path = Path(groups[0])
line_no = int(groups[1])
column_number = int(groups[2]) if int(groups[2]) > 0 else 1
issue_data = IssueData.get_base_issue_data_dict(file_path,
cls.inspector_type,
line_number=line_no,
column_number=column_number,
origin_class=origin_class)
if cc_match is not None: # mccabe: cyclomatic complexity
issue_type = IssueType.CYCLOMATIC_COMPLEXITY
issue_data[IssueData.DESCRIPTION.value] = get_cyclomatic_complexity_tip()
issue_data[IssueData.CYCLOMATIC_COMPLEXITY.value] = int(cc_match.groups()[1])
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(CyclomaticComplexityIssue(**issue_data))
elif cohesion_match is not None: # flake8-cohesion
issue_type = IssueType.COHESION
issue_data[IssueData.DESCRIPTION.value] = f'{get_cohesion_tip(f'{description.capitalize()}.')}'
issue_data[IssueData.COHESION_LACK.value] = convert_percentage_of_value_to_lack_of_value(
float(cohesion_match.group(1)),
)
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(CohesionIssue(**issue_data))
elif line_len_match is not None:
issue_type = IssueType.LINE_LEN
issue_data[IssueData.DESCRIPTION.value] = get_line_len_tip()
issue_data[IssueData.LINE_LEN.value] = int(line_len_match.groups()[0])
issue_data[IssueData.ISSUE_TYPE.value] = IssueType.LINE_LEN
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(LineLenIssue(**issue_data))
else:
issue_type = cls.choose_issue_type(origin_class)
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
# Magic number
if origin_class == 'WPS432':
issue_data[IssueData.DESCRIPTION.value] = get_magic_number_tip(description)
else:
issue_data[IssueData.DESCRIPTION.value] = description
issues.append(CodeIssue(**issue_data))
return issues
@staticmethod
def choose_issue_type(code: str) -> IssueType:
# Handling individual codes
if code in CODE_TO_ISSUE_TYPE:
return CODE_TO_ISSUE_TYPE[code]
regex_match = re.match(r'^([A-Z]+)(\d)\d*$', code, re.IGNORECASE)
code_prefix = regex_match.group(1)
first_code_number = regex_match.group(2)
# Handling other issues
issue_type = (CODE_PREFIX_TO_ISSUE_TYPE.get(code_prefix + first_code_number)
or CODE_PREFIX_TO_ISSUE_TYPE.get(code_prefix))
if not issue_type:
logger.warning(f'flake8: {code} - unknown error code')
return IssueType.BEST_PRACTICES
return issue_type
| import logging
import re
from pathlib import Path
from typing import Any, Dict, List
from hyperstyle.src.python.review.common.subprocess_runner import run_in_subprocess
from hyperstyle.src.python.review.inspectors.base_inspector import BaseInspector
from hyperstyle.src.python.review.inspectors.common import convert_percentage_of_value_to_lack_of_value
from hyperstyle.src.python.review.inspectors.flake8.issue_types import CODE_PREFIX_TO_ISSUE_TYPE, CODE_TO_ISSUE_TYPE
from hyperstyle.src.python.review.inspectors.inspector_type import InspectorType
from hyperstyle.src.python.review.inspectors.issue import (
BaseIssue,
CodeIssue,
CohesionIssue,
CyclomaticComplexityIssue,
IssueData,
IssueDifficulty,
IssueType,
LineLenIssue,
)
from hyperstyle.src.python.review.inspectors.tips import (
get_cohesion_tip, get_cyclomatic_complexity_tip, get_line_len_tip, get_magic_number_tip,
)
logger = logging.getLogger(__name__)
PATH_FLAKE8_CONFIG = Path(__file__).parent / '.flake8'
# To make the whitelist, a list of words was examined based on students' solutions
# that were flagged by flake8-spellcheck as erroneous. In general, the whitelist included those words
# that belonged to library methods and which were common abbreviations.
PATH_FLAKE8_SPELLCHECK_WHITELIST = Path(__file__).parent / 'whitelist.txt'
FORMAT = '%(path)s:%(row)d:%(col)d:%(code)s:%(text)s'
INSPECTOR_NAME = 'flake8'
class Flake8Inspector(BaseInspector):
inspector_type = InspectorType.FLAKE8
@classmethod
def inspect(cls, path: Path, config: Dict[str, Any]) -> List[BaseIssue]:
command = [
'flake8',
f'--format={FORMAT}',
f'--config={PATH_FLAKE8_CONFIG}',
f'--whitelist={PATH_FLAKE8_SPELLCHECK_WHITELIST}',
'--max-complexity', '0',
'--cohesion-below', '100',
path,
]
output = run_in_subprocess(command)
return cls.parse(output)
@classmethod
def parse(cls, output: str) -> List[BaseIssue]:
row_re = re.compile(r'^(.*):(\d+):(\d+):([A-Z]+\d{3}):(.*)$', re.M)
cc_description_re = re.compile(r"'(.+)' is too complex \((\d+)\)")
cohesion_description_re = re.compile(r"class has low \((\d*\.?\d*)%\) cohesion")
line_len_description_re = re.compile(r"line too long \((\d+) > \d+ characters\)")
issues: List[BaseIssue] = []
for groups in row_re.findall(output):
description = groups[4]
origin_class = groups[3]
cc_match = cc_description_re.match(description)
cohesion_match = cohesion_description_re.match(description)
line_len_match = line_len_description_re.match(description)
file_path = Path(groups[0])
line_no = int(groups[1])
column_number = int(groups[2]) if int(groups[2]) > 0 else 1
issue_data = IssueData.get_base_issue_data_dict(file_path,
cls.inspector_type,
line_number=line_no,
column_number=column_number,
origin_class=origin_class)
if cc_match is not None: # mccabe: cyclomatic complexity
issue_type = IssueType.CYCLOMATIC_COMPLEXITY
issue_data[IssueData.DESCRIPTION.value] = get_cyclomatic_complexity_tip()
issue_data[IssueData.CYCLOMATIC_COMPLEXITY.value] = int(cc_match.groups()[1])
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(CyclomaticComplexityIssue(**issue_data))
elif cohesion_match is not None: # flake8-cohesion
issue_type = IssueType.COHESION
issue_data[IssueData.DESCRIPTION.value] = f'{get_cohesion_tip(f"{description.capitalize()}.")}'
issue_data[IssueData.COHESION_LACK.value] = convert_percentage_of_value_to_lack_of_value(
float(cohesion_match.group(1)),
)
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(CohesionIssue(**issue_data))
elif line_len_match is not None:
issue_type = IssueType.LINE_LEN
issue_data[IssueData.DESCRIPTION.value] = get_line_len_tip()
issue_data[IssueData.LINE_LEN.value] = int(line_len_match.groups()[0])
issue_data[IssueData.ISSUE_TYPE.value] = IssueType.LINE_LEN
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
issues.append(LineLenIssue(**issue_data))
else:
issue_type = cls.choose_issue_type(origin_class)
issue_data[IssueData.ISSUE_TYPE.value] = issue_type
issue_data[IssueData.DIFFICULTY.value] = IssueDifficulty.get_by_issue_type(issue_type)
# Magic number
if origin_class == 'WPS432':
issue_data[IssueData.DESCRIPTION.value] = get_magic_number_tip(description)
else:
issue_data[IssueData.DESCRIPTION.value] = description
issues.append(CodeIssue(**issue_data))
return issues
@staticmethod
def choose_issue_type(code: str) -> IssueType:
# Handling individual codes
if code in CODE_TO_ISSUE_TYPE:
return CODE_TO_ISSUE_TYPE[code]
regex_match = re.match(r'^([A-Z]+)(\d)\d*$', code, re.IGNORECASE)
code_prefix = regex_match.group(1)
first_code_number = regex_match.group(2)
# Handling other issues
issue_type = (CODE_PREFIX_TO_ISSUE_TYPE.get(code_prefix + first_code_number)
or CODE_PREFIX_TO_ISSUE_TYPE.get(code_prefix))
if not issue_type:
logger.warning(f'flake8: {code} - unknown error code')
return IssueType.BEST_PRACTICES
return issue_type
|
import csv
import pickle
import os
import logging
from tqdm import tqdm, trange
from torch.utils.data import TensorDataset
import torch.nn.functional as F
import numpy as np
import torch
from collections import OrderedDict
from transformers.utils.dummy_tokenizers_objects import BertTokenizerFast
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt = '%m/%d/%Y %H:%M:%S',
level = logging.INFO)
logger = logging.getLogger(__name__)
# 这就是包内引用吗
import json
import re
from transformers import AutoTokenizer
keyword_files = ["keyword_train.txt", "keyword_dev.txt", "keyword_test.txt"]
def tokenize(text, tokenizer):
# berts tokenize ways
# tokenize the [unused12345678910]
D = [f"[unused{i}]" for i in range(10)]
textraw = [text]
for delimiter in D:
ntextraw = []
for i in range(len(textraw)):
t = textraw[i].split(delimiter)
for j in range(len(t)):
ntextraw += [t[j]]
if j != len(t)-1:
ntextraw += [delimiter]
textraw = ntextraw
text = []
for t in textraw:
if t in D:
text += [t]
else:
tokens = tokenizer.tokenize(t, add_special_tokens=False)
for tok in tokens:
text += [tok]
for idx, t in enumerate(text):
if idx + 3 < len(text) and t == "[" and text[idx+1] == "[UNK]" and text[idx+2] == "]":
text = text[:idx] + ["[MASK]"] + text[idx+3:]
return text
n_class = 1
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None, text_c=None, entity=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.text_c = text_c
self.label = label
self.entity = entity
class InputExampleSST2(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None, text_c=None, entity=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeaturesSST2(object):
"""A single set of features of data."""
def __init__(self, input_ids, attention_mask, token_type_ids, label_id):
self.input_ids = input_ids
self.attention_mask = attention_mask
self.token_type_ids = token_type_ids
self.label_id = label_id
class InputExampleWiki80(object):
"""A single training/test example for span pair classification."""
def __init__(self, guid, sentence, span1, span2, ner1, ner2, label):
self.guid = guid
self.sentence = sentence
self.span1 = span1
self.span2 = span2
self.ner1 = ner1
self.ner2 = ner2
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_id, entity=None):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.entity = entity
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_tsv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, "r") as f:
reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines
class Sst2Processor(DataProcessor):
"""Processor for the SST-2 data set (GLUE version)."""
def __init__(self, data_dir, a):
super().__init__()
self.data_dir = data_dir
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence"].numpy().decode("utf-8"),
None,
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
text_index = 0
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = line[text_index]
label = line[1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, text_c=None, label=label))
return examples
class relossProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
prompt = f"what is the relation between {h} and {t} ? {t} is the [MASK] {h} ."
d = [
prompt + d,
h,
t,
rid,
t
]
self.D[sid] += [d]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2], entity=data[i][4]))
return examples
class bertProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
sample_idx = 0
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
if use_prompt:
prompt = f"{h} is the [MASK] {t} ."
else:
prompt = f"what is the relation between {h} and {t} ?"
sample_idx += 1
d = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [d]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2]))
return examples
class ptuneProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False, ptune_k=6):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
"""
TODO, add new samples, every sample if there is a trigger then mask trigger and replace the origin mask with right token,
if no trigger in the sentence, random mask a word in the sentence and replace the origin mask with the right token.
"""
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
sample_idx = 0
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
unused_word = " ".join([f"[unused{i}]" for i in range(3, ptune_k+3)])
# st 3,4 ; ed 5,6
st = [f"[unused{i}]" for i in range(3,5)]
ed = [f"[unused{i}]" for i in range(5,7)]
# 789 as prompt
prompt = f"[sub] {st[0]} {h} {st[1]} [sub] [unused7] [unused8] [MASK] [unused9] [obj] {ed[0]} {t} {ed[1]} [obj]."
# for temp_i in range(10):
# d = d.replace(f"speaker {temp_i}:", f"[speaker{temp_i}]")
sample_idx += 1
sample = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [sample]
# multi labels, add more data in the training set
if i == 0:
for idx,trigger in enumerate(data[i][1][j]['t']):
if trigger != "":
label_token = f"[class{data[i][1][j]["rid"][idx]+1}]"
prompt = prompt.replace("[MASK]", label_token)
# first assume the model predict the same output in the trigger, ...
d = d.replace(trigger, "[MASK]", 1)
sample = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [sample]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2]))
return examples
class wiki80Processor(DataProcessor):
"""Processor for the TACRED data set."""
def __init__(self, data_path, use_prompt):
super().__init__()
self.data_dir = data_path
@classmethod
def _read_json(cls, input_file):
data = []
with open(input_file, "r", encoding='utf-8') as reader:
all_lines = reader.readlines()
for line in all_lines:
ins = eval(line)
data.append(ins)
return data
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.txt")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "val.txt")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.txt")), "test")
def get_labels(self, negative_label="no_relation"):
data_dir = self.data_dir
"""See base class."""
# if 'k-shot' in self.data_dir:
# data_dir = os.path.abspath(os.path.join(self.data_dir, "../.."))
# else:
# data_dir = self.data_dir
with open(os.path.join(data_dir,'rel2id.json'), "r", encoding='utf-8') as reader:
re2id = json.load(reader)
return re2id
def _create_examples(self, dataset, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for example in dataset:
sentence = example['token']
examples.append(InputExampleWiki80(guid=None,
sentence=sentence,
# maybe some bugs here, I don't -1
span1=(example['h']['pos'][0], example['h']['pos'][1]),
span2=(example['t']['pos'][0], example['t']['pos'][1]),
ner1=None,
ner2=None,
label=example['relation']))
return examples
def convert_examples_to_features_for_loss(examples, max_seq_length, tokenizer):
print("#examples", len(examples))
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenize(example.text_a, tokenizer)
tokens_b = tokenize(example.text_b, tokenizer)
tokens_c = tokenize(example.text_c, tokenizer)
# t_tokens = tokenize(example.entity, tokenizer)
t_tokens = tokenizer(example.entity, add_special_tokens=False)["input_ids"]
_truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_seq_length - 4)
tokens_b = tokens_b + ["[SEP]"] + tokens_c
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = example.label
len_t = len(t_tokens)
normal_input_ids = input_ids[:]
for idx, input_id in enumerate(input_ids):
if idx + len_t < len(input_ids) and input_ids[idx:idx+len_t] == t_tokens:
# [MASK] id = 103
for j in range(len_t):
input_ids[j+idx] = 103
# append 1 sample with 2 input
features.append(
[InputFeatures(
input_ids=normal_input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
entity = t_tokens
),
InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
entity = t_tokens
)]
)
print('#features', len(features))
return features
def convert_examples_to_features_normal(examples, max_seq_length, tokenizer):
print("#examples", len(examples))
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenize(example.text_a, tokenizer)
tokens_b = tokenize(example.text_b, tokenizer)
tokens_c = tokenize(example.text_c, tokenizer)
_truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_seq_length - 4)
tokens_b = tokens_b + ["[SEP]"] + tokens_c
inputs = tokenizer(
example.text_a,
example.text_b + tokenizer.sep_token + example.text_c,
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
# tokens = []
# segment_ids = []
# tokens.append("[CLS]")
# segment_ids.append(0)
# for token in tokens_a:
# tokens.append(token)
# segment_ids.append(0)
# tokens.append("[SEP]")
# segment_ids.append(0)
# for token in tokens_b:
# tokens.append(token)
# segment_ids.append(1)
# tokens.append("[SEP]")
# segment_ids.append(1)
# input_ids = tokenizer.convert_tokens_to_ids(tokens)
# # The mask has 1 for real tokens and 0 for padding tokens. Only real
# # tokens are attended to.
# input_mask = [1] * len(input_ids)
# # Zero-pad up to the sequence length.
# while len(input_ids) < max_seq_length:
# input_ids.append(0)
# input_mask.append(0)
# segment_ids.append(0)
# assert(inputs['input_ids'] == input_ids), print(inputs['input_ids'])
# assert len(input_ids) == max_seq_length
# assert len(input_mask) == max_seq_length
# assert len(segment_ids) == max_seq_length
label_id = example.label
if ex_index == 0:
logger.info(f"input_text : {tokens_a} {tokens_b} {tokens_c}")
logger.info(f"input_ids : {inputs["input_ids"]}")
logger.info(f"token_type_ids : {inputs["token_type_ids"]}")
# inputs = {}
# inputs['input_ids'] = input_ids
# inputs['attention_mask'] = input_mask
# inputs['token_type_ids'] = segment_ids
# append 1 sample with 2 input
features.append(
InputFeatures(
input_ids=inputs['input_ids'],
input_mask=inputs['attention_mask'],
segment_ids=inputs['token_type_ids'],
label_id=label_id,
)
)
print('#features', len(features))
return features
def convert_examples_to_features(examples, max_seq_length, tokenizer, args, rel2id):
"""Loads a data file into a list of `InputBatch`s."""
save_file = "data/cached_wiki80.pkl"
mode = "text"
num_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
instances = []
use_bert = "BertTokenizer" in tokenizer.__class__.__name__
use_gpt = "GPT" in tokenizer.__class__.__name__
assert not (use_bert and use_gpt), "model cannot be gpt and bert together"
if False:
with open(file=save_file, mode='rb') as fr:
instances = pickle.load(fr)
print('load preprocessed data from {}.'.format(save_file))
else:
print('loading..')
for (ex_index, example) in enumerate(examples):
"""
the relation between SUBJECT and OBJECT is .
"""
if ex_index % 10000 == 0:
logger.info("Writing example %d of %d" % (ex_index, len(examples)))
tokens = []
SUBJECT_START = "[subject_start]"
SUBJECT_END = "[subject_end]"
OBJECT_START = "[object_start]"
OBJECT_END = "[object_end]"
if mode.startswith("text"):
for i, token in enumerate(example.sentence):
if i == example.span1[0]:
tokens.append(SUBJECT_START)
if i == example.span2[0]:
tokens.append(OBJECT_START)
# for sub_token in tokenizer.tokenize(token):
# tokens.append(sub_token)
if i == example.span1[1]:
tokens.append(SUBJECT_END)
if i == example.span2[1]:
tokens.append(OBJECT_END)
tokens.append(token)
SUBJECT = " ".join(example.sentence[example.span1[0]: example.span1[1]])
OBJECT = " ".join(example.sentence[example.span2[0]: example.span2[1]])
SUBJECT_ids = tokenizer(" "+SUBJECT, add_special_tokens=False)['input_ids']
OBJECT_ids = tokenizer(" "+OBJECT, add_special_tokens=False)['input_ids']
if use_gpt:
if args.CT_CL:
prompt = f"[T1] [T2] [T3] [sub] {OBJECT} [sub] [T4] [obj] {SUBJECT} [obj] [T5] {tokenizer.cls_token}"
else:
prompt = f"The relation between [sub] {SUBJECT} [sub] and [obj] {OBJECT} [obj] is {tokenizer.cls_token} ."
else:
# add prompt [T_n] and entity marker [obj] to enrich the context.
prompt = f"[sub] {SUBJECT} [sub] {tokenizer.mask_token} [obj] {OBJECT} [obj] ."
if ex_index == 0:
input_text = " ".join(tokens)
logger.info(f"input text : {input_text}")
logger.info(f"prompt : {prompt}")
logger.info(f"label : {example.label}")
inputs = tokenizer(
prompt,
" ".join(tokens),
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
if use_gpt: cls_token_location = inputs['input_ids'].index(tokenizer.cls_token_id)
# find the subject and object tokens, choose the first ones
sub_st = sub_ed = obj_st = obj_ed = -1
for i in range(len(inputs['input_ids'])):
if sub_st == -1 and inputs['input_ids'][i:i+len(SUBJECT_ids)] == SUBJECT_ids:
sub_st = i
sub_ed = i + len(SUBJECT_ids)
if obj_st == -1 and inputs['input_ids'][i:i+len(OBJECT_ids)] == OBJECT_ids:
obj_st = i
obj_ed = i + len(OBJECT_ids)
assert sub_st != -1 and obj_st != -1
num_tokens += sum(inputs['attention_mask'])
if sum(inputs['attention_mask']) > max_seq_length:
pass
# tokens = tokens[:max_seq_length]
else:
num_fit_examples += 1
x = OrderedDict()
x['input_ids'] = inputs['input_ids']
if use_bert: x['token_type_ids'] = inputs['token_type_ids']
x['attention_mask'] = inputs['attention_mask']
x['label'] = rel2id[example.label]
if use_gpt: x['cls_token_location'] = cls_token_location
x['so'] =[sub_st, sub_ed, obj_st, obj_ed]
instances.append(x)
with open(file=save_file, mode='wb') as fw:
pickle.dump(instances, fw)
print('Finish save preprocessed data to {}.'.format( save_file))
input_ids = [o['input_ids'] for o in instances]
attention_mask = [o['attention_mask'] for o in instances]
if use_bert: token_type_ids = [o['token_type_ids'] for o in instances]
if use_gpt: cls_idx = [o['cls_token_location'] for o in instances]
labels = [o['label'] for o in instances]
so = torch.tensor([o['so'] for o in instances])
input_ids = torch.tensor(input_ids)
attention_mask = torch.tensor(attention_mask)
if use_gpt: cls_idx = torch.tensor(cls_idx)
if use_bert: token_type_ids = torch.tensor(token_type_ids)
labels = torch.tensor(labels)
logger.info("Average #tokens: %.2f" % (num_tokens * 1.0 / len(examples)))
logger.info("%d (%.2f %%) examples can fit max_seq_length = %d" % (num_fit_examples,
num_fit_examples * 100.0 / len(examples), max_seq_length))
if use_gpt:
dataset = TensorDataset(input_ids, attention_mask, cls_idx, labels)
elif use_bert:
dataset = TensorDataset(input_ids, attention_mask, token_type_ids, labels, so)
else:
dataset = TensorDataset(input_ids, attention_mask, labels)
return dataset
def convert_examples_to_feature_sst2(examples, max_seq_length, tokenizer, args, rel2id):
"""Loads a data file into a list of `InputBatch`s."""
save_file = "data/cached_wiki80.pkl"
mode = "text"
num_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
instances = []
if False:
with open(file=save_file, mode='rb') as fr:
instances = pickle.load(fr)
print('load preprocessed data from {}.'.format(save_file))
else:
print('loading..')
for (ex_index, example) in enumerate(examples):
try:
prompt = f"[T1] [T2] {tokenizer.mask_token} ."
inputs = tokenizer(
example.text_a + prompt,
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
x = OrderedDict()
x['input_ids'] = inputs['input_ids']
x['attention_mask'] = inputs['attention_mask']
if "roberta" not in args.model_name_or_path:
x['token_type_ids'] = inputs['token_type_ids']
x['label'] = int(example.label)
instances.append(x)
except Exception as e:
print(e)
with open(file=save_file, mode='wb') as fw:
pickle.dump(instances, fw)
print('Finish save preprocessed data to {}.'.format( save_file))
input_ids = [o['input_ids'] for o in instances]
attention_mask = [o['attention_mask'] for o in instances]
if "roberta" not in args.model_name_or_path:
token_type_ids = [o['token_type_ids'] for o in instances]
token_type_ids = torch.tensor(token_type_ids)
labels = [o['label'] for o in instances]
input_ids = torch.tensor(input_ids)
attention_mask = torch.tensor(attention_mask)
labels = torch.tensor(labels)
logger.info("Average #tokens: %.2f" % (num_tokens * 1.0 / len(examples)))
logger.info("%d (%.2f %%) examples can fit max_seq_length = %d" % (num_fit_examples,
num_fit_examples * 100.0 / len(examples), max_seq_length))
if "roberta" not in args.model_name_or_path:
dataset = TensorDataset(input_ids, attention_mask, token_type_ids, labels)
else:
dataset = TensorDataset(input_ids, attention_mask, labels)
return dataset
def _truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_length):
"""Truncates a sequence tuple in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b) + len(tokens_c)
if total_length <= max_length:
break
if len(tokens_a) >= len(tokens_b) and len(tokens_a) >= len(tokens_c):
tokens_a.pop()
elif len(tokens_b) >= len(tokens_a) and len(tokens_b) >= len(tokens_c):
tokens_b.pop()
else:
tokens_c.pop()
def get_dataset(mode, args, tokenizer, processor):
if mode == "train":
examples = processor.get_train_examples(args.data_dir)
elif mode == "dev":
examples = processor.get_dev_examples(args.data_dir)
elif mode == "test":
examples = processor.get_test_examples(args.data_dir)
else:
raise Exception("mode must be in choice [trian, dev, test]")
gpt_mode = "wiki80" in args.task_name
if "wiki80" in args.task_name:
# normal relation extraction task
dataset = convert_examples_to_features(
examples, args.max_seq_length, tokenizer, args, processor.get_labels()
)
return dataset
elif "sst" in args.task_name:
dataset = convert_examples_to_feature_sst2(
examples, args.max_seq_length, tokenizer, args, None
)
return dataset
else:
train_features = convert_examples_to_features_normal(
examples, args.max_seq_length, tokenizer
)
input_ids = []
input_mask = []
segment_ids = []
label_id = []
entity_id = []
for f in train_features:
input_ids.append(f.input_ids)
input_mask.append(f.input_mask)
segment_ids.append(f.segment_ids)
label_id.append(f.label_id)
all_input_ids = torch.tensor(input_ids, dtype=torch.long)
all_input_mask = torch.tensor(input_mask, dtype=torch.long)
all_segment_ids = torch.tensor(segment_ids, dtype=torch.long)
all_label_ids = torch.tensor(label_id, dtype=torch.float)
train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
return train_data
def collate_fn(batch):
pass
processors = {"normal": bertProcessor, "reloss": relossProcessor , "ptune": ptuneProcessor, "wiki80": wiki80Processor,
"sst-2": Sst2Processor
} | import csv
import pickle
import os
import logging
from tqdm import tqdm, trange
from torch.utils.data import TensorDataset
import torch.nn.functional as F
import numpy as np
import torch
from collections import OrderedDict
from transformers.utils.dummy_tokenizers_objects import BertTokenizerFast
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt = '%m/%d/%Y %H:%M:%S',
level = logging.INFO)
logger = logging.getLogger(__name__)
# 这就是包内引用吗
import json
import re
from transformers import AutoTokenizer
keyword_files = ["keyword_train.txt", "keyword_dev.txt", "keyword_test.txt"]
def tokenize(text, tokenizer):
# berts tokenize ways
# tokenize the [unused12345678910]
D = [f"[unused{i}]" for i in range(10)]
textraw = [text]
for delimiter in D:
ntextraw = []
for i in range(len(textraw)):
t = textraw[i].split(delimiter)
for j in range(len(t)):
ntextraw += [t[j]]
if j != len(t)-1:
ntextraw += [delimiter]
textraw = ntextraw
text = []
for t in textraw:
if t in D:
text += [t]
else:
tokens = tokenizer.tokenize(t, add_special_tokens=False)
for tok in tokens:
text += [tok]
for idx, t in enumerate(text):
if idx + 3 < len(text) and t == "[" and text[idx+1] == "[UNK]" and text[idx+2] == "]":
text = text[:idx] + ["[MASK]"] + text[idx+3:]
return text
n_class = 1
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None, text_c=None, entity=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.text_c = text_c
self.label = label
self.entity = entity
class InputExampleSST2(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text_a, text_b=None, label=None, text_c=None, entity=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
Only must be specified for sequence pair tasks.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeaturesSST2(object):
"""A single set of features of data."""
def __init__(self, input_ids, attention_mask, token_type_ids, label_id):
self.input_ids = input_ids
self.attention_mask = attention_mask
self.token_type_ids = token_type_ids
self.label_id = label_id
class InputExampleWiki80(object):
"""A single training/test example for span pair classification."""
def __init__(self, guid, sentence, span1, span2, ner1, ner2, label):
self.guid = guid
self.sentence = sentence
self.span1 = span1
self.span2 = span2
self.ner1 = ner1
self.ner2 = ner2
self.label = label
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self, input_ids, input_mask, segment_ids, label_id, entity=None):
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.label_id = label_id
self.entity = entity
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def _read_tsv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, "r") as f:
reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines
class Sst2Processor(DataProcessor):
"""Processor for the SST-2 data set (GLUE version)."""
def __init__(self, data_dir, a):
super().__init__()
self.data_dir = data_dir
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence"].numpy().decode("utf-8"),
None,
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["0", "1"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
text_index = 0
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, i)
text_a = line[text_index]
label = line[1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, text_c=None, label=label))
return examples
class relossProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
prompt = f"what is the relation between {h} and {t} ? {t} is the [MASK] {h} ."
d = [
prompt + d,
h,
t,
rid,
t
]
self.D[sid] += [d]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2], entity=data[i][4]))
return examples
class bertProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
sample_idx = 0
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
if use_prompt:
prompt = f"{h} is the [MASK] {t} ."
else:
prompt = f"what is the relation between {h} and {t} ?"
sample_idx += 1
d = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [d]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2]))
return examples
class ptuneProcessor(DataProcessor): #bert_s
def __init__(self, data_path="data", use_prompt=False, ptune_k=6):
def is_speaker(a):
a = a.split()
return len(a) == 2 and a[0] == "speaker" and a[1].isdigit()
# replace the speaker with [unused] token
def rename(d, x, y):
d = d.replace("’","'")
d = d.replace("im","i")
d = d.replace("...",".")
unused = ["[unused1]", "[unused2]"]
a = []
if is_speaker(x):
a += [x]
else:
a += [None]
if x != y and is_speaker(y):
a += [y]
else:
a += [None]
for i in range(len(a)):
if a[i] is None:
continue
d = d.replace(a[i] + ":", unused[i] + " :")
if x == a[i]:
x = unused[i]
if y == a[i]:
y = unused[i]
return d, x, y
self.D = [[], [], []]
"""
TODO, add new samples, every sample if there is a trigger then mask trigger and replace the origin mask with right token,
if no trigger in the sentence, random mask a word in the sentence and replace the origin mask with the right token.
"""
for sid in range(3):
# 分成三个数据集
with open(data_path + "/"+["train.json", "dev.json", "test.json"][sid], "r", encoding="utf8") as f:
data = json.load(f)
sample_idx = 0
for i in range(len(data)):
for j in range(len(data[i][1])):
rid = []
for k in range(36):
if k+1 in data[i][1][j]["rid"]:
rid += [1]
else:
rid += [0]
d, h, t = rename(' '.join(data[i][0]).lower(), data[i][1][j]["x"].lower(), data[i][1][j]["y"].lower())
unused_word = " ".join([f"[unused{i}]" for i in range(3, ptune_k+3)])
# st 3,4 ; ed 5,6
st = [f"[unused{i}]" for i in range(3,5)]
ed = [f"[unused{i}]" for i in range(5,7)]
# 789 as prompt
prompt = f"[sub] {st[0]} {h} {st[1]} [sub] [unused7] [unused8] [MASK] [unused9] [obj] {ed[0]} {t} {ed[1]} [obj]."
# for temp_i in range(10):
# d = d.replace(f"speaker {temp_i}:", f"[speaker{temp_i}]")
sample_idx += 1
sample = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [sample]
# multi labels, add more data in the training set
if i == 0:
for idx,trigger in enumerate(data[i][1][j]['t']):
if trigger != "":
label_token = f"[class{data[i][1][j]['rid'][idx]+1}]"
prompt = prompt.replace("[MASK]", label_token)
# first assume the model predict the same output in the trigger, ...
d = d.replace(trigger, "[MASK]", 1)
sample = [
prompt + d,
h,
t,
rid,
]
self.D[sid] += [sample]
logger.info(str(len(self.D[0])) + "," + str(len(self.D[1])) + "," + str(len(self.D[2])))
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[0], "train")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[2], "test")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self.D[1], "dev")
def get_labels(self):
"""See base class."""
return [str(x) for x in range(36)]
def _create_examples(self, data, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, d) in enumerate(data):
guid = "%s-%s" % (set_type, i)
examples.append(InputExample(guid=guid, text_a=data[i][0], text_b=data[i][1], label=data[i][3], text_c=data[i][2]))
return examples
class wiki80Processor(DataProcessor):
"""Processor for the TACRED data set."""
def __init__(self, data_path, use_prompt):
super().__init__()
self.data_dir = data_path
@classmethod
def _read_json(cls, input_file):
data = []
with open(input_file, "r", encoding='utf-8') as reader:
all_lines = reader.readlines()
for line in all_lines:
ins = eval(line)
data.append(ins)
return data
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "train.txt")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "val.txt")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_json(os.path.join(data_dir, "test.txt")), "test")
def get_labels(self, negative_label="no_relation"):
data_dir = self.data_dir
"""See base class."""
# if 'k-shot' in self.data_dir:
# data_dir = os.path.abspath(os.path.join(self.data_dir, "../.."))
# else:
# data_dir = self.data_dir
with open(os.path.join(data_dir,'rel2id.json'), "r", encoding='utf-8') as reader:
re2id = json.load(reader)
return re2id
def _create_examples(self, dataset, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for example in dataset:
sentence = example['token']
examples.append(InputExampleWiki80(guid=None,
sentence=sentence,
# maybe some bugs here, I don't -1
span1=(example['h']['pos'][0], example['h']['pos'][1]),
span2=(example['t']['pos'][0], example['t']['pos'][1]),
ner1=None,
ner2=None,
label=example['relation']))
return examples
def convert_examples_to_features_for_loss(examples, max_seq_length, tokenizer):
print("#examples", len(examples))
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenize(example.text_a, tokenizer)
tokens_b = tokenize(example.text_b, tokenizer)
tokens_c = tokenize(example.text_c, tokenizer)
# t_tokens = tokenize(example.entity, tokenizer)
t_tokens = tokenizer(example.entity, add_special_tokens=False)["input_ids"]
_truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_seq_length - 4)
tokens_b = tokens_b + ["[SEP]"] + tokens_c
tokens = []
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for token in tokens_b:
tokens.append(token)
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
label_id = example.label
len_t = len(t_tokens)
normal_input_ids = input_ids[:]
for idx, input_id in enumerate(input_ids):
if idx + len_t < len(input_ids) and input_ids[idx:idx+len_t] == t_tokens:
# [MASK] id = 103
for j in range(len_t):
input_ids[j+idx] = 103
# append 1 sample with 2 input
features.append(
[InputFeatures(
input_ids=normal_input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
entity = t_tokens
),
InputFeatures(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
label_id=label_id,
entity = t_tokens
)]
)
print('#features', len(features))
return features
def convert_examples_to_features_normal(examples, max_seq_length, tokenizer):
print("#examples", len(examples))
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenize(example.text_a, tokenizer)
tokens_b = tokenize(example.text_b, tokenizer)
tokens_c = tokenize(example.text_c, tokenizer)
_truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_seq_length - 4)
tokens_b = tokens_b + ["[SEP]"] + tokens_c
inputs = tokenizer(
example.text_a,
example.text_b + tokenizer.sep_token + example.text_c,
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
# tokens = []
# segment_ids = []
# tokens.append("[CLS]")
# segment_ids.append(0)
# for token in tokens_a:
# tokens.append(token)
# segment_ids.append(0)
# tokens.append("[SEP]")
# segment_ids.append(0)
# for token in tokens_b:
# tokens.append(token)
# segment_ids.append(1)
# tokens.append("[SEP]")
# segment_ids.append(1)
# input_ids = tokenizer.convert_tokens_to_ids(tokens)
# # The mask has 1 for real tokens and 0 for padding tokens. Only real
# # tokens are attended to.
# input_mask = [1] * len(input_ids)
# # Zero-pad up to the sequence length.
# while len(input_ids) < max_seq_length:
# input_ids.append(0)
# input_mask.append(0)
# segment_ids.append(0)
# assert(inputs['input_ids'] == input_ids), print(inputs['input_ids'])
# assert len(input_ids) == max_seq_length
# assert len(input_mask) == max_seq_length
# assert len(segment_ids) == max_seq_length
label_id = example.label
if ex_index == 0:
logger.info(f"input_text : {tokens_a} {tokens_b} {tokens_c}")
logger.info(f"input_ids : {inputs['input_ids']}")
logger.info(f"token_type_ids : {inputs['token_type_ids']}")
# inputs = {}
# inputs['input_ids'] = input_ids
# inputs['attention_mask'] = input_mask
# inputs['token_type_ids'] = segment_ids
# append 1 sample with 2 input
features.append(
InputFeatures(
input_ids=inputs['input_ids'],
input_mask=inputs['attention_mask'],
segment_ids=inputs['token_type_ids'],
label_id=label_id,
)
)
print('#features', len(features))
return features
def convert_examples_to_features(examples, max_seq_length, tokenizer, args, rel2id):
"""Loads a data file into a list of `InputBatch`s."""
save_file = "data/cached_wiki80.pkl"
mode = "text"
num_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
instances = []
use_bert = "BertTokenizer" in tokenizer.__class__.__name__
use_gpt = "GPT" in tokenizer.__class__.__name__
assert not (use_bert and use_gpt), "model cannot be gpt and bert together"
if False:
with open(file=save_file, mode='rb') as fr:
instances = pickle.load(fr)
print('load preprocessed data from {}.'.format(save_file))
else:
print('loading..')
for (ex_index, example) in enumerate(examples):
"""
the relation between SUBJECT and OBJECT is .
"""
if ex_index % 10000 == 0:
logger.info("Writing example %d of %d" % (ex_index, len(examples)))
tokens = []
SUBJECT_START = "[subject_start]"
SUBJECT_END = "[subject_end]"
OBJECT_START = "[object_start]"
OBJECT_END = "[object_end]"
if mode.startswith("text"):
for i, token in enumerate(example.sentence):
if i == example.span1[0]:
tokens.append(SUBJECT_START)
if i == example.span2[0]:
tokens.append(OBJECT_START)
# for sub_token in tokenizer.tokenize(token):
# tokens.append(sub_token)
if i == example.span1[1]:
tokens.append(SUBJECT_END)
if i == example.span2[1]:
tokens.append(OBJECT_END)
tokens.append(token)
SUBJECT = " ".join(example.sentence[example.span1[0]: example.span1[1]])
OBJECT = " ".join(example.sentence[example.span2[0]: example.span2[1]])
SUBJECT_ids = tokenizer(" "+SUBJECT, add_special_tokens=False)['input_ids']
OBJECT_ids = tokenizer(" "+OBJECT, add_special_tokens=False)['input_ids']
if use_gpt:
if args.CT_CL:
prompt = f"[T1] [T2] [T3] [sub] {OBJECT} [sub] [T4] [obj] {SUBJECT} [obj] [T5] {tokenizer.cls_token}"
else:
prompt = f"The relation between [sub] {SUBJECT} [sub] and [obj] {OBJECT} [obj] is {tokenizer.cls_token} ."
else:
# add prompt [T_n] and entity marker [obj] to enrich the context.
prompt = f"[sub] {SUBJECT} [sub] {tokenizer.mask_token} [obj] {OBJECT} [obj] ."
if ex_index == 0:
input_text = " ".join(tokens)
logger.info(f"input text : {input_text}")
logger.info(f"prompt : {prompt}")
logger.info(f"label : {example.label}")
inputs = tokenizer(
prompt,
" ".join(tokens),
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
if use_gpt: cls_token_location = inputs['input_ids'].index(tokenizer.cls_token_id)
# find the subject and object tokens, choose the first ones
sub_st = sub_ed = obj_st = obj_ed = -1
for i in range(len(inputs['input_ids'])):
if sub_st == -1 and inputs['input_ids'][i:i+len(SUBJECT_ids)] == SUBJECT_ids:
sub_st = i
sub_ed = i + len(SUBJECT_ids)
if obj_st == -1 and inputs['input_ids'][i:i+len(OBJECT_ids)] == OBJECT_ids:
obj_st = i
obj_ed = i + len(OBJECT_ids)
assert sub_st != -1 and obj_st != -1
num_tokens += sum(inputs['attention_mask'])
if sum(inputs['attention_mask']) > max_seq_length:
pass
# tokens = tokens[:max_seq_length]
else:
num_fit_examples += 1
x = OrderedDict()
x['input_ids'] = inputs['input_ids']
if use_bert: x['token_type_ids'] = inputs['token_type_ids']
x['attention_mask'] = inputs['attention_mask']
x['label'] = rel2id[example.label]
if use_gpt: x['cls_token_location'] = cls_token_location
x['so'] =[sub_st, sub_ed, obj_st, obj_ed]
instances.append(x)
with open(file=save_file, mode='wb') as fw:
pickle.dump(instances, fw)
print('Finish save preprocessed data to {}.'.format( save_file))
input_ids = [o['input_ids'] for o in instances]
attention_mask = [o['attention_mask'] for o in instances]
if use_bert: token_type_ids = [o['token_type_ids'] for o in instances]
if use_gpt: cls_idx = [o['cls_token_location'] for o in instances]
labels = [o['label'] for o in instances]
so = torch.tensor([o['so'] for o in instances])
input_ids = torch.tensor(input_ids)
attention_mask = torch.tensor(attention_mask)
if use_gpt: cls_idx = torch.tensor(cls_idx)
if use_bert: token_type_ids = torch.tensor(token_type_ids)
labels = torch.tensor(labels)
logger.info("Average #tokens: %.2f" % (num_tokens * 1.0 / len(examples)))
logger.info("%d (%.2f %%) examples can fit max_seq_length = %d" % (num_fit_examples,
num_fit_examples * 100.0 / len(examples), max_seq_length))
if use_gpt:
dataset = TensorDataset(input_ids, attention_mask, cls_idx, labels)
elif use_bert:
dataset = TensorDataset(input_ids, attention_mask, token_type_ids, labels, so)
else:
dataset = TensorDataset(input_ids, attention_mask, labels)
return dataset
def convert_examples_to_feature_sst2(examples, max_seq_length, tokenizer, args, rel2id):
"""Loads a data file into a list of `InputBatch`s."""
save_file = "data/cached_wiki80.pkl"
mode = "text"
num_tokens = 0
num_fit_examples = 0
num_shown_examples = 0
instances = []
if False:
with open(file=save_file, mode='rb') as fr:
instances = pickle.load(fr)
print('load preprocessed data from {}.'.format(save_file))
else:
print('loading..')
for (ex_index, example) in enumerate(examples):
try:
prompt = f"[T1] [T2] {tokenizer.mask_token} ."
inputs = tokenizer(
example.text_a + prompt,
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
add_special_tokens=True
)
x = OrderedDict()
x['input_ids'] = inputs['input_ids']
x['attention_mask'] = inputs['attention_mask']
if "roberta" not in args.model_name_or_path:
x['token_type_ids'] = inputs['token_type_ids']
x['label'] = int(example.label)
instances.append(x)
except Exception as e:
print(e)
with open(file=save_file, mode='wb') as fw:
pickle.dump(instances, fw)
print('Finish save preprocessed data to {}.'.format( save_file))
input_ids = [o['input_ids'] for o in instances]
attention_mask = [o['attention_mask'] for o in instances]
if "roberta" not in args.model_name_or_path:
token_type_ids = [o['token_type_ids'] for o in instances]
token_type_ids = torch.tensor(token_type_ids)
labels = [o['label'] for o in instances]
input_ids = torch.tensor(input_ids)
attention_mask = torch.tensor(attention_mask)
labels = torch.tensor(labels)
logger.info("Average #tokens: %.2f" % (num_tokens * 1.0 / len(examples)))
logger.info("%d (%.2f %%) examples can fit max_seq_length = %d" % (num_fit_examples,
num_fit_examples * 100.0 / len(examples), max_seq_length))
if "roberta" not in args.model_name_or_path:
dataset = TensorDataset(input_ids, attention_mask, token_type_ids, labels)
else:
dataset = TensorDataset(input_ids, attention_mask, labels)
return dataset
def _truncate_seq_tuple(tokens_a, tokens_b, tokens_c, max_length):
"""Truncates a sequence tuple in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b) + len(tokens_c)
if total_length <= max_length:
break
if len(tokens_a) >= len(tokens_b) and len(tokens_a) >= len(tokens_c):
tokens_a.pop()
elif len(tokens_b) >= len(tokens_a) and len(tokens_b) >= len(tokens_c):
tokens_b.pop()
else:
tokens_c.pop()
def get_dataset(mode, args, tokenizer, processor):
if mode == "train":
examples = processor.get_train_examples(args.data_dir)
elif mode == "dev":
examples = processor.get_dev_examples(args.data_dir)
elif mode == "test":
examples = processor.get_test_examples(args.data_dir)
else:
raise Exception("mode must be in choice [trian, dev, test]")
gpt_mode = "wiki80" in args.task_name
if "wiki80" in args.task_name:
# normal relation extraction task
dataset = convert_examples_to_features(
examples, args.max_seq_length, tokenizer, args, processor.get_labels()
)
return dataset
elif "sst" in args.task_name:
dataset = convert_examples_to_feature_sst2(
examples, args.max_seq_length, tokenizer, args, None
)
return dataset
else:
train_features = convert_examples_to_features_normal(
examples, args.max_seq_length, tokenizer
)
input_ids = []
input_mask = []
segment_ids = []
label_id = []
entity_id = []
for f in train_features:
input_ids.append(f.input_ids)
input_mask.append(f.input_mask)
segment_ids.append(f.segment_ids)
label_id.append(f.label_id)
all_input_ids = torch.tensor(input_ids, dtype=torch.long)
all_input_mask = torch.tensor(input_mask, dtype=torch.long)
all_segment_ids = torch.tensor(segment_ids, dtype=torch.long)
all_label_ids = torch.tensor(label_id, dtype=torch.float)
train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
return train_data
def collate_fn(batch):
pass
processors = {"normal": bertProcessor, "reloss": relossProcessor , "ptune": ptuneProcessor, "wiki80": wiki80Processor,
"sst-2": Sst2Processor
} |
import io
import os
import sys
import django
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "infomate.settings")
django.setup()
import re
import logging
from datetime import timedelta, datetime
from urllib.parse import urlparse
from time import mktime
import threading
import queue
import requests
import click
import feedparser
from bs4 import BeautifulSoup
from requests import RequestException
from newspaper import Article as NewspaperArticle, ArticleException
from boards.models import BoardFeed, Article, Board
from scripts.common import DEFAULT_REQUEST_HEADERS, DEFAULT_REQUEST_TIMEOUT, MAX_PARSABLE_CONTENT_LENGTH
DEFAULT_NUM_WORKER_THREADS = 5
DEFAULT_ENTRIES_LIMIT = 100
MIN_REFRESH_DELTA = timedelta(minutes=30)
log = logging.getLogger()
queue = queue.Queue()
@click.command()
@click.option("--num-workers", default=DEFAULT_NUM_WORKER_THREADS, help="Number of parser threads")
@click.option("--force", is_flag=True, help="Force to update all existing feeds")
@click.option("--feed", help="To update one particular feed")
def update(num_workers, force, feed):
if feed:
need_to_update_feeds = BoardFeed.objects.filter(rss=feed)
else:
never_updated_feeds = BoardFeed.objects.filter(refreshed_at__isnull=True)
if not force:
need_to_update_feeds = BoardFeed.objects.filter(
rss__isnull=False,
refreshed_at__lte=datetime.utcnow() - MIN_REFRESH_DELTA
)
else:
need_to_update_feeds = BoardFeed.objects.filter(rss__isnull=False)
need_to_update_feeds = list(never_updated_feeds) + list(need_to_update_feeds)
tasks = []
for feed in need_to_update_feeds:
tasks.append({
"id": feed.id,
"board_id": feed.board_id,
"name": feed.name,
"rss": feed.rss,
"conditions": feed.conditions,
"is_parsable": feed.is_parsable,
})
threads = []
for i in range(num_workers):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
# put tasks to the queue
for item in tasks:
queue.put(item)
# wait until tasks are done
queue.join()
# update timestamps
updated_boards = {feed.board_id for feed in need_to_update_feeds}
Board.objects.filter(id__in=updated_boards).update(refreshed_at=datetime.utcnow())
# stop workers
for i in range(num_workers):
queue.put(None)
for t in threads:
t.join()
def worker():
while True:
task = queue.get()
if task is None:
break
try:
refresh_feed(task)
except Exception:
# catch all to avoid infinite wait in .join()
log.exception("Error refreshing feed")
queue.task_done()
def refresh_feed(item):
print(f"Updating feed {item["name"]}...")
feed = feedparser.parse(item['rss'])
print(f"Entries found: {len(feed.entries)}")
for entry in feed.entries[:DEFAULT_ENTRIES_LIMIT]:
entry_title = parse_title(entry)
entry_link = parse_link(entry)
if not entry_title or not entry_link:
print("No entry title or link. Skipped")
continue
print(f"- article: '{entry_title}' {entry_link}")
conditions = item.get("conditions")
if conditions:
is_valid = check_conditions(conditions, entry)
if not is_valid:
print(f"Condition {conditions} does not match. Skipped")
continue
article, is_created = Article.objects.get_or_create(
board_id=item["board_id"],
feed_id=item["id"],
uniq_id=entry.get("id") or entry.get("guid") or entry_link,
defaults=dict(
url=entry_link[:2000],
domain=parse_domain(entry_link)[:256],
created_at=parse_datetime(entry),
updated_at=datetime.utcnow(),
title=entry_title[:256],
image=str(parse_rss_image(entry) or "")[:512],
description=entry.get("summary"),
)
)
if is_created:
# parse heavy info
text, lead_image = parse_rss_text_and_image(entry)
if text:
article.description = text[:1000]
if lead_image:
article.image = lead_image[:512]
# get real url
real_url, content_type, content_length = resolve_url(entry_link)
# load and summarize article
if item["is_parsable"] and content_length <= MAX_PARSABLE_CONTENT_LENGTH \
and content_type.startswith("text/"): # to not try to parse podcasts :D
if real_url:
article.url = real_url[:2000]
article.domain = parse_domain(real_url)[:256]
try:
summary, summary_image = load_and_parse_full_article_text_and_image(article.url)
except ArticleException:
summary = None
summary_image = None
if summary:
article.summary = summary
if summary_image:
article.image = summary_image[:512]
article.save()
week_ago = datetime.utcnow() - timedelta(days=7)
frequency = Article.objects.filter(feed_id=item["id"], created_at__gte=week_ago).count()
last_article = Article.objects.filter(feed_id=item["id"]).order_by("-created_at").first()
BoardFeed.objects.filter(id=item["id"]).update(
refreshed_at=datetime.utcnow(),
last_article_at=last_article.created_at if last_article else None,
frequency=frequency or 0
)
def check_conditions(conditions, entry):
if not conditions:
return True
for condition in conditions:
if condition["type"] == "in":
if condition["in"] not in entry[condition["field"]]:
return False
return True
def resolve_url(entry_link):
url = str(entry_link)
content_type = None
content_length = MAX_PARSABLE_CONTENT_LENGTH + 1 # don't parse null content-types
depth = 10
while depth > 0:
depth -= 1
try:
response = requests.head(url, timeout=DEFAULT_REQUEST_TIMEOUT, verify=False, stream=True)
except RequestException:
log.warning(f"Failed to resolve URL: {url}")
return None, content_type, content_length
if 300 < response.status_code < 400:
url = response.headers["location"] # follow redirect
else:
content_type = response.headers.get("content-type")
content_length = int(response.headers.get("content-length") or 0)
break
return url, content_type, content_length
def parse_domain(url):
domain = urlparse(url).netloc
if domain.startswith("www."):
domain = domain[4:]
return domain
def parse_datetime(entry):
published_time = entry.get("published_parsed") or entry.get("updated_parsed")
if published_time:
return datetime.fromtimestamp(mktime(published_time))
return datetime.utcnow()
def parse_title(entry):
title = entry.get("title") or entry.get("description") or entry.get("summary")
return re.sub("<[^<]+?>", "", title).strip()
def parse_link(entry):
if entry.get("link"):
return entry["link"]
if entry.get("links"):
return entry["links"][0]["href"]
return None
def parse_rss_image(entry):
if entry.get("media_content"):
images = [m["url"] for m in entry["media_content"] if m.get("medium") == "image" and m.get("url")]
if images:
return images[0]
if entry.get("image"):
if isinstance(entry["image"], dict):
return entry["image"].get("href")
return entry["image"]
return None
def parse_rss_text_and_image(entry):
if not entry.get("summary"):
return "", ""
bs = BeautifulSoup(entry["summary"], features="lxml")
text = re.sub(r"\s\s+", " ", bs.text or "").strip()
img_tags = bs.findAll("img")
for img_tag in img_tags:
src = img_tag.get("src", None)
if src:
return text, src
return text, ""
def load_page_safe(url):
try:
response = requests.get(
url=url,
timeout=DEFAULT_REQUEST_TIMEOUT,
headers=DEFAULT_REQUEST_HEADERS,
stream=True # the most important part — stream response to prevent loading everything into memory
)
except RequestException as ex:
log.warning(f"Error parsing the page: {url} {ex}")
return ""
html = io.StringIO()
total_bytes = 0
for chunk in response.iter_content(chunk_size=100 * 1024, decode_unicode=True):
total_bytes += len(chunk)
if total_bytes >= MAX_PARSABLE_CONTENT_LENGTH:
return "" # reject too big pages
html.write(chunk)
return html.getvalue()
def load_and_parse_full_article_text_and_image(url):
article = NewspaperArticle(url)
article.set_html(load_page_safe(url)) # safer than article.download()
article.parse()
article.nlp()
return article.summary, article.top_image
if __name__ == '__main__':
update()
| import io
import os
import sys
import django
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "infomate.settings")
django.setup()
import re
import logging
from datetime import timedelta, datetime
from urllib.parse import urlparse
from time import mktime
import threading
import queue
import requests
import click
import feedparser
from bs4 import BeautifulSoup
from requests import RequestException
from newspaper import Article as NewspaperArticle, ArticleException
from boards.models import BoardFeed, Article, Board
from scripts.common import DEFAULT_REQUEST_HEADERS, DEFAULT_REQUEST_TIMEOUT, MAX_PARSABLE_CONTENT_LENGTH
DEFAULT_NUM_WORKER_THREADS = 5
DEFAULT_ENTRIES_LIMIT = 100
MIN_REFRESH_DELTA = timedelta(minutes=30)
log = logging.getLogger()
queue = queue.Queue()
@click.command()
@click.option("--num-workers", default=DEFAULT_NUM_WORKER_THREADS, help="Number of parser threads")
@click.option("--force", is_flag=True, help="Force to update all existing feeds")
@click.option("--feed", help="To update one particular feed")
def update(num_workers, force, feed):
if feed:
need_to_update_feeds = BoardFeed.objects.filter(rss=feed)
else:
never_updated_feeds = BoardFeed.objects.filter(refreshed_at__isnull=True)
if not force:
need_to_update_feeds = BoardFeed.objects.filter(
rss__isnull=False,
refreshed_at__lte=datetime.utcnow() - MIN_REFRESH_DELTA
)
else:
need_to_update_feeds = BoardFeed.objects.filter(rss__isnull=False)
need_to_update_feeds = list(never_updated_feeds) + list(need_to_update_feeds)
tasks = []
for feed in need_to_update_feeds:
tasks.append({
"id": feed.id,
"board_id": feed.board_id,
"name": feed.name,
"rss": feed.rss,
"conditions": feed.conditions,
"is_parsable": feed.is_parsable,
})
threads = []
for i in range(num_workers):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
# put tasks to the queue
for item in tasks:
queue.put(item)
# wait until tasks are done
queue.join()
# update timestamps
updated_boards = {feed.board_id for feed in need_to_update_feeds}
Board.objects.filter(id__in=updated_boards).update(refreshed_at=datetime.utcnow())
# stop workers
for i in range(num_workers):
queue.put(None)
for t in threads:
t.join()
def worker():
while True:
task = queue.get()
if task is None:
break
try:
refresh_feed(task)
except Exception:
# catch all to avoid infinite wait in .join()
log.exception("Error refreshing feed")
queue.task_done()
def refresh_feed(item):
print(f"Updating feed {item['name']}...")
feed = feedparser.parse(item['rss'])
print(f"Entries found: {len(feed.entries)}")
for entry in feed.entries[:DEFAULT_ENTRIES_LIMIT]:
entry_title = parse_title(entry)
entry_link = parse_link(entry)
if not entry_title or not entry_link:
print("No entry title or link. Skipped")
continue
print(f"- article: '{entry_title}' {entry_link}")
conditions = item.get("conditions")
if conditions:
is_valid = check_conditions(conditions, entry)
if not is_valid:
print(f"Condition {conditions} does not match. Skipped")
continue
article, is_created = Article.objects.get_or_create(
board_id=item["board_id"],
feed_id=item["id"],
uniq_id=entry.get("id") or entry.get("guid") or entry_link,
defaults=dict(
url=entry_link[:2000],
domain=parse_domain(entry_link)[:256],
created_at=parse_datetime(entry),
updated_at=datetime.utcnow(),
title=entry_title[:256],
image=str(parse_rss_image(entry) or "")[:512],
description=entry.get("summary"),
)
)
if is_created:
# parse heavy info
text, lead_image = parse_rss_text_and_image(entry)
if text:
article.description = text[:1000]
if lead_image:
article.image = lead_image[:512]
# get real url
real_url, content_type, content_length = resolve_url(entry_link)
# load and summarize article
if item["is_parsable"] and content_length <= MAX_PARSABLE_CONTENT_LENGTH \
and content_type.startswith("text/"): # to not try to parse podcasts :D
if real_url:
article.url = real_url[:2000]
article.domain = parse_domain(real_url)[:256]
try:
summary, summary_image = load_and_parse_full_article_text_and_image(article.url)
except ArticleException:
summary = None
summary_image = None
if summary:
article.summary = summary
if summary_image:
article.image = summary_image[:512]
article.save()
week_ago = datetime.utcnow() - timedelta(days=7)
frequency = Article.objects.filter(feed_id=item["id"], created_at__gte=week_ago).count()
last_article = Article.objects.filter(feed_id=item["id"]).order_by("-created_at").first()
BoardFeed.objects.filter(id=item["id"]).update(
refreshed_at=datetime.utcnow(),
last_article_at=last_article.created_at if last_article else None,
frequency=frequency or 0
)
def check_conditions(conditions, entry):
if not conditions:
return True
for condition in conditions:
if condition["type"] == "in":
if condition["in"] not in entry[condition["field"]]:
return False
return True
def resolve_url(entry_link):
url = str(entry_link)
content_type = None
content_length = MAX_PARSABLE_CONTENT_LENGTH + 1 # don't parse null content-types
depth = 10
while depth > 0:
depth -= 1
try:
response = requests.head(url, timeout=DEFAULT_REQUEST_TIMEOUT, verify=False, stream=True)
except RequestException:
log.warning(f"Failed to resolve URL: {url}")
return None, content_type, content_length
if 300 < response.status_code < 400:
url = response.headers["location"] # follow redirect
else:
content_type = response.headers.get("content-type")
content_length = int(response.headers.get("content-length") or 0)
break
return url, content_type, content_length
def parse_domain(url):
domain = urlparse(url).netloc
if domain.startswith("www."):
domain = domain[4:]
return domain
def parse_datetime(entry):
published_time = entry.get("published_parsed") or entry.get("updated_parsed")
if published_time:
return datetime.fromtimestamp(mktime(published_time))
return datetime.utcnow()
def parse_title(entry):
title = entry.get("title") or entry.get("description") or entry.get("summary")
return re.sub("<[^<]+?>", "", title).strip()
def parse_link(entry):
if entry.get("link"):
return entry["link"]
if entry.get("links"):
return entry["links"][0]["href"]
return None
def parse_rss_image(entry):
if entry.get("media_content"):
images = [m["url"] for m in entry["media_content"] if m.get("medium") == "image" and m.get("url")]
if images:
return images[0]
if entry.get("image"):
if isinstance(entry["image"], dict):
return entry["image"].get("href")
return entry["image"]
return None
def parse_rss_text_and_image(entry):
if not entry.get("summary"):
return "", ""
bs = BeautifulSoup(entry["summary"], features="lxml")
text = re.sub(r"\s\s+", " ", bs.text or "").strip()
img_tags = bs.findAll("img")
for img_tag in img_tags:
src = img_tag.get("src", None)
if src:
return text, src
return text, ""
def load_page_safe(url):
try:
response = requests.get(
url=url,
timeout=DEFAULT_REQUEST_TIMEOUT,
headers=DEFAULT_REQUEST_HEADERS,
stream=True # the most important part — stream response to prevent loading everything into memory
)
except RequestException as ex:
log.warning(f"Error parsing the page: {url} {ex}")
return ""
html = io.StringIO()
total_bytes = 0
for chunk in response.iter_content(chunk_size=100 * 1024, decode_unicode=True):
total_bytes += len(chunk)
if total_bytes >= MAX_PARSABLE_CONTENT_LENGTH:
return "" # reject too big pages
html.write(chunk)
return html.getvalue()
def load_and_parse_full_article_text_and_image(url):
article = NewspaperArticle(url)
article.set_html(load_page_safe(url)) # safer than article.download()
article.parse()
article.nlp()
return article.summary, article.top_image
if __name__ == '__main__':
update()
|
"""Binary Sensor platform for Advantage Air integration."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
)
from .const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from .entity import AdvantageAirEntity
PARALLEL_UPDATES = 0
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up AdvantageAir motion platform."""
instance = hass.data[ADVANTAGE_AIR_DOMAIN][config_entry.entry_id]
entities = []
for ac_key, ac_device in instance["coordinator"].data["aircons"].items():
entities.append(AdvantageAirZoneFilter(instance, ac_key))
for zone_key, zone in ac_device["zones"].items():
# Only add motion sensor when motion is enabled
if zone["motionConfig"] >= 2:
entities.append(AdvantageAirZoneMotion(instance, ac_key, zone_key))
# Only add MyZone if it is available
if zone["type"] != 0:
entities.append(AdvantageAirZoneMyZone(instance, ac_key, zone_key))
async_add_entities(entities)
class AdvantageAirZoneFilter(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Filter."""
@property
def name(self):
"""Return the name."""
return f'{self._ac['name']} Filter'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data['system']['rid']}-{self.ac_key}-filter'
@property
def device_class(self):
"""Return the device class of the vent."""
return DEVICE_CLASS_PROBLEM
@property
def is_on(self):
"""Return if filter needs cleaning."""
return self._ac["filterCleanStatus"]
class AdvantageAirZoneMotion(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Zone Motion."""
@property
def name(self):
"""Return the name."""
return f'{self._zone['name']} Motion'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data['system']['rid']}-{self.ac_key}-{self.zone_key}-motion'
@property
def device_class(self):
"""Return the device class of the vent."""
return DEVICE_CLASS_MOTION
@property
def is_on(self):
"""Return if motion is detect."""
return self._zone["motion"]
class AdvantageAirZoneMyZone(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Zone MyZone."""
@property
def name(self):
"""Return the name."""
return f'{self._zone['name']} MyZone'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data['system']['rid']}-{self.ac_key}-{self.zone_key}-myzone'
@property
def is_on(self):
"""Return if this zone is the myZone."""
return self._zone["number"] == self._ac["myZone"]
@property
def entity_registry_enabled_default(self):
"""Return false to disable this entity by default."""
return False
| """Binary Sensor platform for Advantage Air integration."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_PROBLEM,
BinarySensorEntity,
)
from .const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from .entity import AdvantageAirEntity
PARALLEL_UPDATES = 0
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up AdvantageAir motion platform."""
instance = hass.data[ADVANTAGE_AIR_DOMAIN][config_entry.entry_id]
entities = []
for ac_key, ac_device in instance["coordinator"].data["aircons"].items():
entities.append(AdvantageAirZoneFilter(instance, ac_key))
for zone_key, zone in ac_device["zones"].items():
# Only add motion sensor when motion is enabled
if zone["motionConfig"] >= 2:
entities.append(AdvantageAirZoneMotion(instance, ac_key, zone_key))
# Only add MyZone if it is available
if zone["type"] != 0:
entities.append(AdvantageAirZoneMyZone(instance, ac_key, zone_key))
async_add_entities(entities)
class AdvantageAirZoneFilter(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Filter."""
@property
def name(self):
"""Return the name."""
return f'{self._ac["name"]} Filter'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}-filter'
@property
def device_class(self):
"""Return the device class of the vent."""
return DEVICE_CLASS_PROBLEM
@property
def is_on(self):
"""Return if filter needs cleaning."""
return self._ac["filterCleanStatus"]
class AdvantageAirZoneMotion(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Zone Motion."""
@property
def name(self):
"""Return the name."""
return f'{self._zone["name"]} Motion'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}-{self.zone_key}-motion'
@property
def device_class(self):
"""Return the device class of the vent."""
return DEVICE_CLASS_MOTION
@property
def is_on(self):
"""Return if motion is detect."""
return self._zone["motion"]
class AdvantageAirZoneMyZone(AdvantageAirEntity, BinarySensorEntity):
"""Advantage Air Zone MyZone."""
@property
def name(self):
"""Return the name."""
return f'{self._zone["name"]} MyZone'
@property
def unique_id(self):
"""Return a unique id."""
return f'{self.coordinator.data["system"]["rid"]}-{self.ac_key}-{self.zone_key}-myzone'
@property
def is_on(self):
"""Return if this zone is the myZone."""
return self._zone["number"] == self._ac["myZone"]
@property
def entity_registry_enabled_default(self):
"""Return false to disable this entity by default."""
return False
|
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
path = "path/to/chromedriver.exe" # You need to change this
def parser():
driver = webdriver.Chrome(path, chrome_options=options)
driver.get('https://yandex.ru/pogoda/213')
weather = driver.find_element_by_xpath(
'/html/body/div[1]/div[3]/div[2]/div[1]/div[5]/a/div[1]/span[2]').text
city_full_text = driver.find_element_by_xpath('//*[@id="main_title"]').text
term_value = driver.find_element_by_xpath(
'/html/body/div[1]/div[3]/div[2]/div[1]/div[7]/div[2]/div[2]').text
city = city_full_text.replace("е", "а")
print(
f'Город: {city.replace('Погода в ', '')}\nТемпература: {weather}°\nВлажность: {term_value}')
parser()
| # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
path = "path/to/chromedriver.exe" # You need to change this
def parser():
driver = webdriver.Chrome(path, chrome_options=options)
driver.get('https://yandex.ru/pogoda/213')
weather = driver.find_element_by_xpath(
'/html/body/div[1]/div[3]/div[2]/div[1]/div[5]/a/div[1]/span[2]').text
city_full_text = driver.find_element_by_xpath('//*[@id="main_title"]').text
term_value = driver.find_element_by_xpath(
'/html/body/div[1]/div[3]/div[2]/div[1]/div[7]/div[2]/div[2]').text
city = city_full_text.replace("е", "а")
print(
f'Город: {city.replace("Погода в ", "")}\nТемпература: {weather}°\nВлажность: {term_value}')
parser()
|
import re
import time
import json
import traceback
from os import environ
from hashlib import md5
from typing import List, Union
from flask import (Flask, make_response, redirect, render_template,
request, send_from_directory, Response)
from duty.utils import gen_secret
from microvk import VkApi, VkApiResponseException
from logger import get_writer
from duty.objects import db
DEBUG = (environ.get('FLASK_ENV') == 'development')
app = Flask(__name__)
logger = get_writer('Веб-приложение')
class ReturnResponse(Exception):
response: Response
def __init__(self, response: Response):
self.response = response
def get_mask(token: str) -> str:
if len(token) != 85:
return 'Не установлен'
return token[:4] + "*" * 77 + token[81:]
def login_check(request) -> None:
if DEBUG:
return
if not db.installed:
raise ReturnResponse(redirect('/install'))
if request.cookies.get('auth') == db.auth_token:
if time.time() - db.auth_token_date < 86400:
return
raise ReturnResponse(int_error(
'Ошибка авторизации, попробуй очистить cookies или перелогиниться'
))
def format_tokens(tokens: list) -> List[Union[str, None]]:
for i in range(len(tokens)):
token = re.search(r'access_token=[a-z0-9]{85}', tokens[i])
if token:
token = token[0][13:]
elif len(tokens[i]) == 85:
token = tokens[i]
else:
token = None
tokens[i] = token
return tokens
def check_tokens(tokens: list):
user_ids = []
for i in range(len(tokens)):
try:
user_ids.append(
VkApi(tokens[i], raise_excepts=True)('users.get')[0]['id']
)
time.sleep(0.4)
except VkApiResponseException:
raise ReturnResponse(int_error("Неверный токен, попробуй снова"))
return user_ids
@app.route('/')
def index():
if db.installed:
return redirect('/admin')
return redirect('/install')
@app.route('/auth', methods=["POST"])
def do_auth():
user_id = check_tokens(format_tokens([request.form.get('access_token')]))
if type(user_id) != list:
return user_id
if user_id[0] != db.owner_id:
return int_error(
'Вставлен токен от другого аккаунта. Проверь авторизацию ВК'
)
response = make_response()
db.auth_token = md5(gen_secret().encode()).hexdigest()
db.auth_token_date = int(time.time())
response.set_cookie("auth", value=db.auth_token)
response.headers['location'] = "/"
db.sync()
return response, 302
@app.route('/favicon.ico')
def favicon():
return send_from_directory('static/img', 'favicon.png')
@app.route('/install')
def install():
if db.installed:
return redirect('/')
return render_template('pages/install.html')
@app.route('/api/setup_cb', methods=["POST"])
def setup():
if db.installed:
return redirect('/')
tokens = format_tokens([
request.form.get('access_token')
])
user_id = check_tokens(tokens)[0]
if type(user_id) != int:
return user_id
db.owner_id = user_id
db.access_token = tokens[0]
db.secret = gen_secret()
db.host = "https://" + request.host
db.installed = True
db.trusted_users.append(db.owner_id)
protocol = 'https' if 'pythonanywhere' in request.host else 'http'
VkApi(db.access_token).msg_op(
1, -174105461, f'+api {db.secret} {protocol}://{request.host}/callback'
)
return do_auth()
@app.route('/api/<string:method>', methods=["POST"])
def api(method: str):
login_check(request)
handler = globals().get(f'app_method_{method}', lambda: None)
result = handler()
db.sync()
return result or redirect('/')
def app_method_edit_current_user():
tokens = format_tokens([
request.form.get('access_token', ''),
request.form.get('me_token', '')
])
if tokens[0]:
db.access_token = tokens[0]
if tokens[1]:
db.me_token = tokens[1]
def app_method_connect_to_iris():
try:
protocol = 'https' if 'pythonanywhere' in request.host else 'http'
VkApi(db.access_token, raise_excepts=True)(
'messages.send',
peer_id=-174105461,
message=f'+api {db.secret} {protocol}://{request.host}/callback',
random_id=0
)
except VkApiResponseException as e:
return int_error(f'Ошибка VK #{e.error_code}: {e.error_msg}')
def app_method_edit_responses():
for key, response in request.form.items():
if response:
db.responses[key] = response
return redirect('/admin#Responses')
def app_method_edit_dyntemplates():
name = request.form['temp_name']
length = int(request.form['length'])
i = 0
frames = []
while True:
if i >= length:
break
frame = request.form.get(f'frame{i}')
if frame:
frames.append(frame)
elif i < length:
frames.append('Пустой кадр')
else:
break
i += 1
temp = {'name': request.form['new_name'].lower(),
'frames': frames, 'speed': float(request.form['speed'])}
for i in range(len(db.anims)):
if db.anims[i]['name'] == name:
db.anims[i].update(temp)
break
return redirect('/admin#DynTemplates')
def app_method_add_dyntemplate():
db.anims.append({'name': 'анимка',
'frames': ['Отсутствует'], 'speed': 1.0})
return redirect('/admin#DynTemplates')
def app_method_delete_anim():
name = request.form['name']
for i in range(len(db.anims)):
if db.anims[i]['name'] == name:
del(db.anims[i])
return redirect('/admin#DynTemplates')
@app.route('/admin')
def admin():
login_check(request)
if not db.installed:
return redirect('/install')
warning = None
users = VkApi(db.access_token)('users.get', user_ids=db.owner_id)
if type(users) == dict:
username = 'НЕИЗВЕСТНЫЙ ПОЛЬЗОВАТЕЛЬ'
warning = {'type': 'danger', 'text': 'Ошибка доступа, смени токены'}
else:
username = f"{users[0]["first_name"]} {users[0]["last_name"]}"
access_token = get_mask(db.access_token)
me_token = get_mask(db.me_token)
return render_template('pages/admin.html', db=db, access_token=access_token,
users=users, warn=warning, username=username,
me_token=me_token)
@app.route('/login')
def login():
if not db.installed:
return redirect('/')
return render_template('pages/login.html')
@app.errorhandler(404)
def page_not_found(_):
return render_template('errors/404.html'), 404
@app.errorhandler(405)
def method_not_allowed(_):
return render_template('errors/404.html'), 405
@app.errorhandler(500)
def int_error(e):
return render_template('errors/500.html', error=e), 500
@app.errorhandler(ReturnResponse)
def oops(e: ReturnResponse):
return e.response
@app.errorhandler(Exception)
def on_error(e: Exception):
logger.error(f'Ошибка при обработке запроса:\n' +
traceback.format_exc())
return f'Неизвестная ошибка:\n{e.__class__.__name__}: {e}'
@app.errorhandler(json.decoder.JSONDecodeError)
def decode_error(e):
logger.error(f'Ошибка при декодировании данных:\n{e}\n{traceback.format_exc()}') # noqa
return ('Произошла ошибка при декодировании JSON (скорее всего в файлах '
' БД), проверь файлы в ICAD/database<br>Место, где споткнулся '
f'декодер: {e}')
| import re
import time
import json
import traceback
from os import environ
from hashlib import md5
from typing import List, Union
from flask import (Flask, make_response, redirect, render_template,
request, send_from_directory, Response)
from duty.utils import gen_secret
from microvk import VkApi, VkApiResponseException
from logger import get_writer
from duty.objects import db
DEBUG = (environ.get('FLASK_ENV') == 'development')
app = Flask(__name__)
logger = get_writer('Веб-приложение')
class ReturnResponse(Exception):
response: Response
def __init__(self, response: Response):
self.response = response
def get_mask(token: str) -> str:
if len(token) != 85:
return 'Не установлен'
return token[:4] + "*" * 77 + token[81:]
def login_check(request) -> None:
if DEBUG:
return
if not db.installed:
raise ReturnResponse(redirect('/install'))
if request.cookies.get('auth') == db.auth_token:
if time.time() - db.auth_token_date < 86400:
return
raise ReturnResponse(int_error(
'Ошибка авторизации, попробуй очистить cookies или перелогиниться'
))
def format_tokens(tokens: list) -> List[Union[str, None]]:
for i in range(len(tokens)):
token = re.search(r'access_token=[a-z0-9]{85}', tokens[i])
if token:
token = token[0][13:]
elif len(tokens[i]) == 85:
token = tokens[i]
else:
token = None
tokens[i] = token
return tokens
def check_tokens(tokens: list):
user_ids = []
for i in range(len(tokens)):
try:
user_ids.append(
VkApi(tokens[i], raise_excepts=True)('users.get')[0]['id']
)
time.sleep(0.4)
except VkApiResponseException:
raise ReturnResponse(int_error("Неверный токен, попробуй снова"))
return user_ids
@app.route('/')
def index():
if db.installed:
return redirect('/admin')
return redirect('/install')
@app.route('/auth', methods=["POST"])
def do_auth():
user_id = check_tokens(format_tokens([request.form.get('access_token')]))
if type(user_id) != list:
return user_id
if user_id[0] != db.owner_id:
return int_error(
'Вставлен токен от другого аккаунта. Проверь авторизацию ВК'
)
response = make_response()
db.auth_token = md5(gen_secret().encode()).hexdigest()
db.auth_token_date = int(time.time())
response.set_cookie("auth", value=db.auth_token)
response.headers['location'] = "/"
db.sync()
return response, 302
@app.route('/favicon.ico')
def favicon():
return send_from_directory('static/img', 'favicon.png')
@app.route('/install')
def install():
if db.installed:
return redirect('/')
return render_template('pages/install.html')
@app.route('/api/setup_cb', methods=["POST"])
def setup():
if db.installed:
return redirect('/')
tokens = format_tokens([
request.form.get('access_token')
])
user_id = check_tokens(tokens)[0]
if type(user_id) != int:
return user_id
db.owner_id = user_id
db.access_token = tokens[0]
db.secret = gen_secret()
db.host = "https://" + request.host
db.installed = True
db.trusted_users.append(db.owner_id)
protocol = 'https' if 'pythonanywhere' in request.host else 'http'
VkApi(db.access_token).msg_op(
1, -174105461, f'+api {db.secret} {protocol}://{request.host}/callback'
)
return do_auth()
@app.route('/api/<string:method>', methods=["POST"])
def api(method: str):
login_check(request)
handler = globals().get(f'app_method_{method}', lambda: None)
result = handler()
db.sync()
return result or redirect('/')
def app_method_edit_current_user():
tokens = format_tokens([
request.form.get('access_token', ''),
request.form.get('me_token', '')
])
if tokens[0]:
db.access_token = tokens[0]
if tokens[1]:
db.me_token = tokens[1]
def app_method_connect_to_iris():
try:
protocol = 'https' if 'pythonanywhere' in request.host else 'http'
VkApi(db.access_token, raise_excepts=True)(
'messages.send',
peer_id=-174105461,
message=f'+api {db.secret} {protocol}://{request.host}/callback',
random_id=0
)
except VkApiResponseException as e:
return int_error(f'Ошибка VK #{e.error_code}: {e.error_msg}')
def app_method_edit_responses():
for key, response in request.form.items():
if response:
db.responses[key] = response
return redirect('/admin#Responses')
def app_method_edit_dyntemplates():
name = request.form['temp_name']
length = int(request.form['length'])
i = 0
frames = []
while True:
if i >= length:
break
frame = request.form.get(f'frame{i}')
if frame:
frames.append(frame)
elif i < length:
frames.append('Пустой кадр')
else:
break
i += 1
temp = {'name': request.form['new_name'].lower(),
'frames': frames, 'speed': float(request.form['speed'])}
for i in range(len(db.anims)):
if db.anims[i]['name'] == name:
db.anims[i].update(temp)
break
return redirect('/admin#DynTemplates')
def app_method_add_dyntemplate():
db.anims.append({'name': 'анимка',
'frames': ['Отсутствует'], 'speed': 1.0})
return redirect('/admin#DynTemplates')
def app_method_delete_anim():
name = request.form['name']
for i in range(len(db.anims)):
if db.anims[i]['name'] == name:
del(db.anims[i])
return redirect('/admin#DynTemplates')
@app.route('/admin')
def admin():
login_check(request)
if not db.installed:
return redirect('/install')
warning = None
users = VkApi(db.access_token)('users.get', user_ids=db.owner_id)
if type(users) == dict:
username = 'НЕИЗВЕСТНЫЙ ПОЛЬЗОВАТЕЛЬ'
warning = {'type': 'danger', 'text': 'Ошибка доступа, смени токены'}
else:
username = f"{users[0]['first_name']} {users[0]['last_name']}"
access_token = get_mask(db.access_token)
me_token = get_mask(db.me_token)
return render_template('pages/admin.html', db=db, access_token=access_token,
users=users, warn=warning, username=username,
me_token=me_token)
@app.route('/login')
def login():
if not db.installed:
return redirect('/')
return render_template('pages/login.html')
@app.errorhandler(404)
def page_not_found(_):
return render_template('errors/404.html'), 404
@app.errorhandler(405)
def method_not_allowed(_):
return render_template('errors/404.html'), 405
@app.errorhandler(500)
def int_error(e):
return render_template('errors/500.html', error=e), 500
@app.errorhandler(ReturnResponse)
def oops(e: ReturnResponse):
return e.response
@app.errorhandler(Exception)
def on_error(e: Exception):
logger.error(f'Ошибка при обработке запроса:\n' +
traceback.format_exc())
return f'Неизвестная ошибка:\n{e.__class__.__name__}: {e}'
@app.errorhandler(json.decoder.JSONDecodeError)
def decode_error(e):
logger.error(f'Ошибка при декодировании данных:\n{e}\n{traceback.format_exc()}') # noqa
return ('Произошла ошибка при декодировании JSON (скорее всего в файлах '
' БД), проверь файлы в ICAD/database<br>Место, где споткнулся '
f'декодер: {e}')
|
import base64
import json
import re
import uuid
from pyDes import des, CBC, PAD_PKCS5
from requests_toolbelt import MultipartEncoder
from todayLoginService import TodayLoginService
class AutoSign:
# 初始化签到类
def __init__(self, todayLoginService: TodayLoginService, userInfo):
self.session = todayLoginService.session
self.host = todayLoginService.host
self.userInfo = userInfo
self.taskInfo = None
self.task = None
self.form = {}
self.fileName = None
# 获取未签到的任务
def getUnSignTask(self):
headers = self.session.headers
headers['Content-Type'] = 'application/json'
# 第一次请求接口获取cookies(MOD_AUTH_CAS)
url = f'{self.host}wec-counselor-sign-apps/stu/sign/getStuSignInfosInOneDay'
self.session.post(url, headers=headers, data=json.dumps({}), verify=False)
# 第二次请求接口,真正的拿到具体任务
res = self.session.post(url, headers=headers, data=json.dumps({}), verify=False)
if res.status_code == 404:
raise Exception('您没有任何签到任务,请检查自己的任务类型!')
res = res.json()
if len(res['datas']['unSignedTasks']) < 1:
raise Exception('当前暂时没有未签到的任务哦!')
# 获取最后的一个任务
latestTask = res['datas']['unSignedTasks'][0]
self.taskInfo = {
'signInstanceWid': latestTask['signInstanceWid'],
'signWid': latestTask['signWid']
}
# 获取具体的签到任务详情
def getDetailTask(self):
url = f'{self.host}wec-counselor-sign-apps/stu/sign/detailSignInstance'
headers = self.session.headers
headers['Content-Type'] = 'application/json'
res = self.session.post(url, headers=headers, data=json.dumps(self.taskInfo), verify=False).json()
self.task = res['datas']
# 上传图片到阿里云oss
def uploadPicture(self):
url = f'{self.host}wec-counselor-sign-apps/stu/oss/getUploadPolicy'
res = self.session.post(url=url, headers={'content-type': 'application/json'}, data=json.dumps({'fileType': 1}),
verify=False)
datas = res.json().get('datas')
fileName = datas.get('fileName')
policy = datas.get('policy')
accessKeyId = datas.get('accessid')
signature = datas.get('signature')
policyHost = datas.get('host')
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'
}
multipart_encoder = MultipartEncoder(
fields={ # 这里根据需要进行参数格式设置
'key': fileName, 'policy': policy, 'OSSAccessKeyId': accessKeyId, 'success_action_status': '200',
'signature': signature,
'file': ('blob', open(self.userInfo['photo'], 'rb'), 'image/jpg')
})
headers['Content-Type'] = multipart_encoder.content_type
self.session.post(url=policyHost,
headers=headers,
data=multipart_encoder)
self.fileName = fileName
# 获取图片上传位置
def getPictureUrl(self):
url = f'{self.host}wec-counselor-sign-apps/stu/sign/previewAttachment'
params = {'ossKey': self.fileName}
res = self.session.post(url=url, headers={'content-type': 'application/json'}, data=json.dumps(params),
verify=False)
photoUrl = res.json().get('datas')
return photoUrl
# 填充表单
def fillForm(self):
# 判断签到是否需要照片
if self.task['isPhoto'] == 1:
self.uploadPicture()
self.form['signPhotoUrl'] = self.getPictureUrl()
else:
self.form['signPhotoUrl'] = ''
self.form['isNeedExtra'] = self.task['isNeedExtra']
if self.task['isNeedExtra'] == 1:
extraFields = self.task['extraField']
userItems = self.userInfo['forms']
extraFieldItemValues = []
for i in range(len(extraFields)):
if i >= len(userItems):
raise Exception("您的config表单中form字段不够,请检查")
userItem = userItems[i]['form']
extraField = extraFields[i]
if self.userInfo['checkTitle'] == 1:
if userItem['title'].strip() != extraField['title'].strip():
raise Exception(
f'\r\n第{i + 1}个配置出错了\r\n您的标题为:{userItem['title']}\r\n系统的标题为:{extraField['title']}')
extraFieldItems = extraField['extraFieldItems']
flag = False
data = []
# 遍历所有的选项
for extraFieldItem in extraFieldItems:
# 如果当前选项为历史选项,将临时保存一下以便config未找到对应值时输出
if extraFieldItem['isSelected']:
data.append(extraFieldItem['content'])
# 初始化局部变量 并初始化数据字典的key
extraFieldItemValue = {}
extraFieldItemValue.setdefault('extraFieldItemValue', None)
extraFieldItemValue.setdefault('extraFieldItemWid', None)
# 如果表单的选项值和配置的值相等
if extraFieldItem['content'] == userItem['value']:
extraFieldItemValue['extraFieldItemWid'] = extraFieldItem['wid']
# 如果是其它字段(other字段)
if extraFieldItem['isOtherItems'] == 1:
if 'other' in userItem:
flag = True
extraFieldItemValue['extraFieldItemValue'] = userItem['other']
else:
raise Exception(
f'\r\n第{i + 1}个配置项的选项不正确,该字段存在“other”字段,请在配置文件“title,value”下添加一行“other”字段并且填上对应的值'
)
# 如果不是其它字段
else:
flag = True
extraFieldItemValue['extraFieldItemValue'] = userItem['value']
extraFieldItemValues.append(extraFieldItemValue)
if not flag:
raise Exception(f'\r\n第{ i + 1 }个配置出错了\r\n表单未找到你设置的值:{userItem['value']}\r\n,你上次系统选的值为:{ ','.join(data) }')
self.form['extraFieldItems'] = extraFieldItemValues
self.form['signInstanceWid'] = self.task['signInstanceWid']
self.form['longitude'] = self.userInfo['lon']
self.form['latitude'] = self.userInfo['lat']
self.form['isMalposition'] = self.task['isMalposition']
self.form['abnormalReason'] = self.userInfo['abnormalReason']
self.form['position'] = self.userInfo['address']
self.form['uaIsCpadaily'] = True
self.form['signVersion'] ='1.0.0'
# DES加密
def DESEncrypt(self, s, key='b3L26XNL'):
key = key
iv = b"\x01\x02\x03\x04\x05\x06\x07\x08"
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
encrypt_str = k.encrypt(s)
return base64.b64encode(encrypt_str).decode()
# 提交签到信息
def submitForm(self):
extension = {
"lon": self.userInfo['lon'],
"model": "OPPO R11 Plus",
"appVersion": "8.1.14",
"systemVersion": "4.4.4",
"userId": self.userInfo['username'],
"systemName": "android",
"lat": self.userInfo['lat'],
"deviceId": str(uuid.uuid1())
}
headers = {
'User-Agent': self.session.headers['User-Agent'],
'CpdailyStandAlone': '0',
'extension': '1',
'Cpdaily-Extension': self.DESEncrypt(json.dumps(extension)),
'Content-Type': 'application/json; charset=utf-8',
'Accept-Encoding': 'gzip',
'Host': re.findall('//(.*?)/', self.host)[0],
'Connection': 'Keep-Alive'
}
# print(json.dumps(self.form))
res = self.session.post(f'{self.host}wec-counselor-sign-apps/stu/sign/submitSign', headers=headers,
data=json.dumps(self.form), verify=False).json()
return res['message']
| import base64
import json
import re
import uuid
from pyDes import des, CBC, PAD_PKCS5
from requests_toolbelt import MultipartEncoder
from todayLoginService import TodayLoginService
class AutoSign:
# 初始化签到类
def __init__(self, todayLoginService: TodayLoginService, userInfo):
self.session = todayLoginService.session
self.host = todayLoginService.host
self.userInfo = userInfo
self.taskInfo = None
self.task = None
self.form = {}
self.fileName = None
# 获取未签到的任务
def getUnSignTask(self):
headers = self.session.headers
headers['Content-Type'] = 'application/json'
# 第一次请求接口获取cookies(MOD_AUTH_CAS)
url = f'{self.host}wec-counselor-sign-apps/stu/sign/getStuSignInfosInOneDay'
self.session.post(url, headers=headers, data=json.dumps({}), verify=False)
# 第二次请求接口,真正的拿到具体任务
res = self.session.post(url, headers=headers, data=json.dumps({}), verify=False)
if res.status_code == 404:
raise Exception('您没有任何签到任务,请检查自己的任务类型!')
res = res.json()
if len(res['datas']['unSignedTasks']) < 1:
raise Exception('当前暂时没有未签到的任务哦!')
# 获取最后的一个任务
latestTask = res['datas']['unSignedTasks'][0]
self.taskInfo = {
'signInstanceWid': latestTask['signInstanceWid'],
'signWid': latestTask['signWid']
}
# 获取具体的签到任务详情
def getDetailTask(self):
url = f'{self.host}wec-counselor-sign-apps/stu/sign/detailSignInstance'
headers = self.session.headers
headers['Content-Type'] = 'application/json'
res = self.session.post(url, headers=headers, data=json.dumps(self.taskInfo), verify=False).json()
self.task = res['datas']
# 上传图片到阿里云oss
def uploadPicture(self):
url = f'{self.host}wec-counselor-sign-apps/stu/oss/getUploadPolicy'
res = self.session.post(url=url, headers={'content-type': 'application/json'}, data=json.dumps({'fileType': 1}),
verify=False)
datas = res.json().get('datas')
fileName = datas.get('fileName')
policy = datas.get('policy')
accessKeyId = datas.get('accessid')
signature = datas.get('signature')
policyHost = datas.get('host')
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'
}
multipart_encoder = MultipartEncoder(
fields={ # 这里根据需要进行参数格式设置
'key': fileName, 'policy': policy, 'OSSAccessKeyId': accessKeyId, 'success_action_status': '200',
'signature': signature,
'file': ('blob', open(self.userInfo['photo'], 'rb'), 'image/jpg')
})
headers['Content-Type'] = multipart_encoder.content_type
self.session.post(url=policyHost,
headers=headers,
data=multipart_encoder)
self.fileName = fileName
# 获取图片上传位置
def getPictureUrl(self):
url = f'{self.host}wec-counselor-sign-apps/stu/sign/previewAttachment'
params = {'ossKey': self.fileName}
res = self.session.post(url=url, headers={'content-type': 'application/json'}, data=json.dumps(params),
verify=False)
photoUrl = res.json().get('datas')
return photoUrl
# 填充表单
def fillForm(self):
# 判断签到是否需要照片
if self.task['isPhoto'] == 1:
self.uploadPicture()
self.form['signPhotoUrl'] = self.getPictureUrl()
else:
self.form['signPhotoUrl'] = ''
self.form['isNeedExtra'] = self.task['isNeedExtra']
if self.task['isNeedExtra'] == 1:
extraFields = self.task['extraField']
userItems = self.userInfo['forms']
extraFieldItemValues = []
for i in range(len(extraFields)):
if i >= len(userItems):
raise Exception("您的config表单中form字段不够,请检查")
userItem = userItems[i]['form']
extraField = extraFields[i]
if self.userInfo['checkTitle'] == 1:
if userItem['title'].strip() != extraField['title'].strip():
raise Exception(
f'\r\n第{i + 1}个配置出错了\r\n您的标题为:{userItem["title"]}\r\n系统的标题为:{extraField["title"]}')
extraFieldItems = extraField['extraFieldItems']
flag = False
data = []
# 遍历所有的选项
for extraFieldItem in extraFieldItems:
# 如果当前选项为历史选项,将临时保存一下以便config未找到对应值时输出
if extraFieldItem['isSelected']:
data.append(extraFieldItem['content'])
# 初始化局部变量 并初始化数据字典的key
extraFieldItemValue = {}
extraFieldItemValue.setdefault('extraFieldItemValue', None)
extraFieldItemValue.setdefault('extraFieldItemWid', None)
# 如果表单的选项值和配置的值相等
if extraFieldItem['content'] == userItem['value']:
extraFieldItemValue['extraFieldItemWid'] = extraFieldItem['wid']
# 如果是其它字段(other字段)
if extraFieldItem['isOtherItems'] == 1:
if 'other' in userItem:
flag = True
extraFieldItemValue['extraFieldItemValue'] = userItem['other']
else:
raise Exception(
f'\r\n第{i + 1}个配置项的选项不正确,该字段存在“other”字段,请在配置文件“title,value”下添加一行“other”字段并且填上对应的值'
)
# 如果不是其它字段
else:
flag = True
extraFieldItemValue['extraFieldItemValue'] = userItem['value']
extraFieldItemValues.append(extraFieldItemValue)
if not flag:
raise Exception(f'\r\n第{ i + 1 }个配置出错了\r\n表单未找到你设置的值:{userItem["value"]}\r\n,你上次系统选的值为:{ ",".join(data) }')
self.form['extraFieldItems'] = extraFieldItemValues
self.form['signInstanceWid'] = self.task['signInstanceWid']
self.form['longitude'] = self.userInfo['lon']
self.form['latitude'] = self.userInfo['lat']
self.form['isMalposition'] = self.task['isMalposition']
self.form['abnormalReason'] = self.userInfo['abnormalReason']
self.form['position'] = self.userInfo['address']
self.form['uaIsCpadaily'] = True
self.form['signVersion'] ='1.0.0'
# DES加密
def DESEncrypt(self, s, key='b3L26XNL'):
key = key
iv = b"\x01\x02\x03\x04\x05\x06\x07\x08"
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
encrypt_str = k.encrypt(s)
return base64.b64encode(encrypt_str).decode()
# 提交签到信息
def submitForm(self):
extension = {
"lon": self.userInfo['lon'],
"model": "OPPO R11 Plus",
"appVersion": "8.1.14",
"systemVersion": "4.4.4",
"userId": self.userInfo['username'],
"systemName": "android",
"lat": self.userInfo['lat'],
"deviceId": str(uuid.uuid1())
}
headers = {
'User-Agent': self.session.headers['User-Agent'],
'CpdailyStandAlone': '0',
'extension': '1',
'Cpdaily-Extension': self.DESEncrypt(json.dumps(extension)),
'Content-Type': 'application/json; charset=utf-8',
'Accept-Encoding': 'gzip',
'Host': re.findall('//(.*?)/', self.host)[0],
'Connection': 'Keep-Alive'
}
# print(json.dumps(self.form))
res = self.session.post(f'{self.host}wec-counselor-sign-apps/stu/sign/submitSign', headers=headers,
data=json.dumps(self.form), verify=False).json()
return res['message']
|
import gym
import os
import numpy as np
import lanro
import argparse
import glfw
DEBUG = int("DEBUG" in os.environ and os.environ["DEBUG"])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interactive', action='store_true', dest='interactive', help='Start interactive mode')
parser.add_argument('-t', '--test', action='store_true', dest='test', help='Start test mode')
parser.add_argument('-r', '--reward', action='store_true', dest='reward', help='Print the reward.')
parser.add_argument('-a', '--action', action='store_true', dest='action', help='Print the action.')
parser.add_argument('--full', action='store_true', dest='full', help='Print everything')
parser.add_argument('--keyboard',
action='store_true',
dest='keyboard_control',
help='Activates keyboard control for interactive mode.')
parser.add_argument('--metrics', action='store_true', help='Print environment metrics.')
parser.add_argument('--action_type', type=str, default='absolute_joints', help='Action type to control the robot.')
parser.add_argument(
'-e',
'--env',
default='PandaNLReach2-v0',
help=
f"Available envs: {", ".join([envspec.id for envspec in gym.envs.registry.all() if "Panda" in envspec.id or "UR5" in envspec.id])}"
)
return parser.parse_args()
def log_step(env, action, args):
obs, reward, done, info = env.step(action)
if args.reward:
print(f"reward: {reward} success: {info["is_success"]}")
if args.action:
print(action)
if args.full:
print(obs, reward, done, info)
if args.metrics:
print(env.get_metrics())
if DEBUG and info['is_success'] or 'hindsight_instruction' in info.keys():
import ipdb
ipdb.set_trace()
return done or info['is_success']
def test(env, args):
for _ in range(100):
env.reset()
done = False
while not done:
action = env.action_space.sample()
done = log_step(env, action, args)
env.render(mode="human")
key_events = {
65297: "forward",
65298: "backward",
65295: "straight_left",
65296: "straight_right",
glfw.KEY_MINUS: "close_gripper",
glfw.KEY_5: "open_gripper",
43: "open_gripper",
glfw.KEY_8: "up",
glfw.KEY_2: "down",
glfw.KEY_1: "yaw_left",
glfw.KEY_3: "yaw_right",
glfw.KEY_6: "pitch_right",
glfw.KEY_4: "pitch_left",
glfw.KEY_7: "roll_left",
glfw.KEY_9: "roll_right",
}
def interactive(args):
env = gym.make(args.env, render=True, action_type=args.action_type)
if not args.keyboard_control:
controls = env.robot.get_xyz_rpy_controls()
for _ in range(10):
env.reset()
done = False
action = np.zeros(shape=env.action_space.shape)
key_control_gain = 0.01
for idx, val in enumerate(env.robot.get_default_controls().values()):
if len(action) > idx:
action[idx] = val
while True:
if args.keyboard_control:
keys = env.getKeyboardEvents()
if keys:
key_str = ''.join(
[key_events[_pressed] for _pressed in keys.keys() if _pressed in key_events.keys()])
if "forward" in key_str:
action[3] += 1 * key_control_gain
if "backward" in key_str:
action[3] += -1 * key_control_gain
if "straight_left" in key_str:
action[0] += 1 * key_control_gain
if "straight_right" in key_str:
action[0] += -1 * key_control_gain
if "up" in key_str:
action[1] += -1 * key_control_gain
if "down" in key_str:
action[1] += 1 * key_control_gain
if not env.robot.fixed_gripper:
if "close_gripper" in key_str:
action[-1] += 1 * key_control_gain
if "open_gripper" in key_str:
action[-1] += -1 * key_control_gain
if env.action_space.shape[0] > 4:
if "roll_left" in key_str:
action[2] += 1 * key_control_gain
if "roll_right" in key_str:
action[2] += -1 * key_control_gain
if "pitch_left" in key_str:
action[4] += 1 * key_control_gain
if "pitch_right" in key_str:
action[4] += -1 * key_control_gain
if "yaw_left" in key_str:
action[5] += -1 * key_control_gain
if "yaw_right" in key_str:
action[5] += 1 * key_control_gain
else:
action = np.zeros(shape=env.action_space.shape)
for idx, ctrl_id in enumerate(controls):
try:
action[idx] = env.sim.bclient.readUserDebugParameter(ctrl_id)
except Exception as e:
print(e)
continue
done = log_step(env, np.array(action), args)
env.render(mode='human')
if args.metrics and done:
break
def main():
args = parse_args()
if args.test:
env = gym.make(args.env, render=True)
env.reset()
test(env, args)
env.close()
elif args.interactive:
interactive(args)
else:
raise ValueError("No valid mode found: use -t/--test (test mode) or -i/--interactive (interactive mode)")
if __name__ == '__main__':
main()
| import gym
import os
import numpy as np
import lanro
import argparse
import glfw
DEBUG = int("DEBUG" in os.environ and os.environ["DEBUG"])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interactive', action='store_true', dest='interactive', help='Start interactive mode')
parser.add_argument('-t', '--test', action='store_true', dest='test', help='Start test mode')
parser.add_argument('-r', '--reward', action='store_true', dest='reward', help='Print the reward.')
parser.add_argument('-a', '--action', action='store_true', dest='action', help='Print the action.')
parser.add_argument('--full', action='store_true', dest='full', help='Print everything')
parser.add_argument('--keyboard',
action='store_true',
dest='keyboard_control',
help='Activates keyboard control for interactive mode.')
parser.add_argument('--metrics', action='store_true', help='Print environment metrics.')
parser.add_argument('--action_type', type=str, default='absolute_joints', help='Action type to control the robot.')
parser.add_argument(
'-e',
'--env',
default='PandaNLReach2-v0',
help=
f"Available envs: {', '.join([envspec.id for envspec in gym.envs.registry.all() if 'Panda' in envspec.id or 'UR5' in envspec.id])}"
)
return parser.parse_args()
def log_step(env, action, args):
obs, reward, done, info = env.step(action)
if args.reward:
print(f"reward: {reward} success: {info['is_success']}")
if args.action:
print(action)
if args.full:
print(obs, reward, done, info)
if args.metrics:
print(env.get_metrics())
if DEBUG and info['is_success'] or 'hindsight_instruction' in info.keys():
import ipdb
ipdb.set_trace()
return done or info['is_success']
def test(env, args):
for _ in range(100):
env.reset()
done = False
while not done:
action = env.action_space.sample()
done = log_step(env, action, args)
env.render(mode="human")
key_events = {
65297: "forward",
65298: "backward",
65295: "straight_left",
65296: "straight_right",
glfw.KEY_MINUS: "close_gripper",
glfw.KEY_5: "open_gripper",
43: "open_gripper",
glfw.KEY_8: "up",
glfw.KEY_2: "down",
glfw.KEY_1: "yaw_left",
glfw.KEY_3: "yaw_right",
glfw.KEY_6: "pitch_right",
glfw.KEY_4: "pitch_left",
glfw.KEY_7: "roll_left",
glfw.KEY_9: "roll_right",
}
def interactive(args):
env = gym.make(args.env, render=True, action_type=args.action_type)
if not args.keyboard_control:
controls = env.robot.get_xyz_rpy_controls()
for _ in range(10):
env.reset()
done = False
action = np.zeros(shape=env.action_space.shape)
key_control_gain = 0.01
for idx, val in enumerate(env.robot.get_default_controls().values()):
if len(action) > idx:
action[idx] = val
while True:
if args.keyboard_control:
keys = env.getKeyboardEvents()
if keys:
key_str = ''.join(
[key_events[_pressed] for _pressed in keys.keys() if _pressed in key_events.keys()])
if "forward" in key_str:
action[3] += 1 * key_control_gain
if "backward" in key_str:
action[3] += -1 * key_control_gain
if "straight_left" in key_str:
action[0] += 1 * key_control_gain
if "straight_right" in key_str:
action[0] += -1 * key_control_gain
if "up" in key_str:
action[1] += -1 * key_control_gain
if "down" in key_str:
action[1] += 1 * key_control_gain
if not env.robot.fixed_gripper:
if "close_gripper" in key_str:
action[-1] += 1 * key_control_gain
if "open_gripper" in key_str:
action[-1] += -1 * key_control_gain
if env.action_space.shape[0] > 4:
if "roll_left" in key_str:
action[2] += 1 * key_control_gain
if "roll_right" in key_str:
action[2] += -1 * key_control_gain
if "pitch_left" in key_str:
action[4] += 1 * key_control_gain
if "pitch_right" in key_str:
action[4] += -1 * key_control_gain
if "yaw_left" in key_str:
action[5] += -1 * key_control_gain
if "yaw_right" in key_str:
action[5] += 1 * key_control_gain
else:
action = np.zeros(shape=env.action_space.shape)
for idx, ctrl_id in enumerate(controls):
try:
action[idx] = env.sim.bclient.readUserDebugParameter(ctrl_id)
except Exception as e:
print(e)
continue
done = log_step(env, np.array(action), args)
env.render(mode='human')
if args.metrics and done:
break
def main():
args = parse_args()
if args.test:
env = gym.make(args.env, render=True)
env.reset()
test(env, args)
env.close()
elif args.interactive:
interactive(args)
else:
raise ValueError("No valid mode found: use -t/--test (test mode) or -i/--interactive (interactive mode)")
if __name__ == '__main__':
main()
|
import argparse
import os
from pathlib import Path
import gym
import gym_puddle # noqa f401
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from utils.utils import minmax_normalization_ab
matplotlib.rcParams.update({"font.size": 24})
sns.set()
parser = argparse.ArgumentParser()
parser.add_argument("--num_obs", type=int, required=True)
parser.add_argument("--env_id", type=str, required=True)
parser.add_argument("--discount_rate", type=float, required=True)
parser.add_argument("--policy_name", type=str, required=True)
parser.add_argument("--problem", type=str, required=True)
args = parser.parse_args()
save_rootpath = Path(f"{os.environ.get("SCRATCH")}") / args.problem
num_obs = args.num_obs
env_id = args.env_id
discount_rate = args.discount_rate
policy_name = args.policy_name
observations = np.load(save_rootpath / "S.npy")
env = gym.make(env_id)
# Plot states S
plt.figure()
plt.scatter(observations[:, 0], observations[:, 1], alpha=0.15)
plt.xlim((env.observation_space.low[0], env.observation_space.high[0]))
plt.ylim((env.observation_space.low[1], env.observation_space.high[1]))
plt.savefig((Path(save_rootpath) / "observation_space"))
# Plot true values
filename = f"true_values-discount_rate_{discount_rate}".replace(".", "_")
true_values = np.load(Path(save_rootpath) / f"{filename}.npy")
colors = minmax_normalization_ab(
true_values,
true_values.min(),
true_values.max(),
true_values.min(),
true_values.max(),
)
plt.figure()
sc = plt.scatter(observations[:, 0], observations[:, 1], c=colors, cmap="hot")
plt.xlim((env.observation_space.low[0], env.observation_space.high[0]))
plt.ylim((env.observation_space.low[1], env.observation_space.high[1]))
plt.colorbar(sc)
plt.title(f"{env_id} {policy_name} Prediction")
plt.tight_layout()
plt.savefig(
(
Path(save_rootpath)
/ f"true_values-discount_rate_{discount_rate}".replace(".", "_")
)
)
| import argparse
import os
from pathlib import Path
import gym
import gym_puddle # noqa f401
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from utils.utils import minmax_normalization_ab
matplotlib.rcParams.update({"font.size": 24})
sns.set()
parser = argparse.ArgumentParser()
parser.add_argument("--num_obs", type=int, required=True)
parser.add_argument("--env_id", type=str, required=True)
parser.add_argument("--discount_rate", type=float, required=True)
parser.add_argument("--policy_name", type=str, required=True)
parser.add_argument("--problem", type=str, required=True)
args = parser.parse_args()
save_rootpath = Path(f"{os.environ.get('SCRATCH')}") / args.problem
num_obs = args.num_obs
env_id = args.env_id
discount_rate = args.discount_rate
policy_name = args.policy_name
observations = np.load(save_rootpath / "S.npy")
env = gym.make(env_id)
# Plot states S
plt.figure()
plt.scatter(observations[:, 0], observations[:, 1], alpha=0.15)
plt.xlim((env.observation_space.low[0], env.observation_space.high[0]))
plt.ylim((env.observation_space.low[1], env.observation_space.high[1]))
plt.savefig((Path(save_rootpath) / "observation_space"))
# Plot true values
filename = f"true_values-discount_rate_{discount_rate}".replace(".", "_")
true_values = np.load(Path(save_rootpath) / f"{filename}.npy")
colors = minmax_normalization_ab(
true_values,
true_values.min(),
true_values.max(),
true_values.min(),
true_values.max(),
)
plt.figure()
sc = plt.scatter(observations[:, 0], observations[:, 1], c=colors, cmap="hot")
plt.xlim((env.observation_space.low[0], env.observation_space.high[0]))
plt.ylim((env.observation_space.low[1], env.observation_space.high[1]))
plt.colorbar(sc)
plt.title(f"{env_id} {policy_name} Prediction")
plt.tight_layout()
plt.savefig(
(
Path(save_rootpath)
/ f"true_values-discount_rate_{discount_rate}".replace(".", "_")
)
)
|
# Copyright (c) 2020 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from openstack import exceptions as os_exc
from os_vif import objects as os_obj
from oslo_config import cfg
from kuryr_kubernetes import constants
from kuryr_kubernetes.controller.drivers import multi_vif
from kuryr_kubernetes.controller.handlers import kuryrport
from kuryr_kubernetes import exceptions as k_exc
from kuryr_kubernetes.tests import base as test_base
from kuryr_kubernetes.tests.unit import kuryr_fixtures as k_fix
from kuryr_kubernetes import utils
CONF = cfg.CONF
class TestKuryrPortHandler(test_base.TestCase):
def setUp(self):
super().setUp()
self._project_id = mock.sentinel.project_id
self._subnets = mock.sentinel.subnets
self._security_groups = mock.sentinel.security_groups
self._host = mock.sentinel.hostname
self._pod_version = mock.sentinel.pod_version
self._pod_link = mock.sentinel.pod_link
self._kp_version = mock.sentinel.kp_version
self._kp_namespace = mock.sentinel.namespace
self._kp_uid = mock.sentinel.kp_uid
self._kp_name = 'pod1'
self._pod = {'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {'resourceVersion': self._pod_version,
'name': self._kp_name,
'deletionTimestamp': mock.sentinel.date,
'namespace': self._kp_namespace},
'spec': {'nodeName': self._host}}
self._kp = {
'apiVersion': 'openstack.org/v1',
'kind': 'KuryrPort',
'metadata': {
'resourceVersion': self._kp_version,
'name': self._kp_name,
'namespace': self._kp_namespace,
'labels': {
constants.KURYRPORT_LABEL: self._host
}
},
'spec': {
'podUid': 'deadbeef',
'podNodeName': self._host
},
'status': {'vifs': {}}
}
self._vif1 = os_obj.vif.VIFBase()
self._vif2 = os_obj.vif.VIFBase()
self._vif1.active = False
self._vif2.active = False
self._vif1.plugin = 'object'
self._vif2.plugin = 'object'
self._vif1_primitive = self._vif1.obj_to_primitive()
self._vif2_primitive = self._vif2.obj_to_primitive()
self._vifs_primitive = {'eth0': {'default': True,
'vif': self._vif1_primitive},
'eth1': {'default': False,
'vif': self._vif2_primitive}}
self._vifs = {'eth0': {'default': True,
'vif': self._vif1},
'eth1': {'default': False,
'vif': self._vif2}}
self._pod_uri = (f"{constants.K8S_API_NAMESPACES}"
f"/{self._kp["metadata"]["namespace"]}/pods/"
f"{self._kp["metadata"]["name"]}")
self.useFixture(k_fix.MockNetworkClient())
self._driver = multi_vif.NoopMultiVIFDriver()
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler.get_vifs')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_no_vifs_create(self, ged, get_k8s_client, get_vifs):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
get_vifs.return_value = True
kp.on_present(self._kp)
get_vifs.assert_called_once_with(self._kp)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler.get_vifs')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_getting_vifs_failed(self, ged, get_k8s_client,
get_vifs):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
get_vifs.return_value = False
self.assertFalse(kp.on_present(self._kp))
get_vifs.assert_called_once_with(self._kp)
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present(self, ged, get_k8s_client, activate_vif,
update_crd, get_project):
ged.return_value = [mock.MagicMock]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=self._pod,
retry_info=mock.ANY),
mock.call(self._vif2, pod=self._pod,
retry_info=mock.ANY)])
update_crd.assert_called_once_with(self._kp, self._vifs)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_active(self, ged, get_k8s_client):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._vif1.active = True
self._vif2.active = True
self._kp['status']['vifs'] = {
'eth0': {'default': True,
'vif': self._vif1.obj_to_primitive()},
'eth1': {'default': False,
'vif': self._vif2.obj_to_primitive()}}
kp.on_present(self._kp)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_port_not_found(self, ged, get_k8s_client, activate_vif,
update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
activate_vif.side_effect = os_exc.ResourceNotFound()
kp.on_present(self._kp)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=mock.ANY,
retry_info=mock.ANY),
mock.call(self._vif2, pod=mock.ANY,
retry_info=mock.ANY)])
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_pod_not_found(self, ged, get_k8s_client, activate_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertRaises(k_exc.K8sResourceNotFound, kp.on_present,
self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_fail_update_crd(self, ged, get_k8s_client,
activate_vif, update_crd, get_project,
get_sg, release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
update_crd.side_effect = k_exc.K8sResourceNotFound(self._kp)
get_project.return_value = self._project_id
get_sg.return_value = self._security_groups
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_exception_during_update_crd(self, ged, get_k8s_client,
activate_vif,
update_crd, get_project,
get_sg, release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
update_crd.side_effect = k_exc.K8sClientException()
get_project.return_value = self._project_id
get_sg.return_value = self._security_groups
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
self.assertRaises(k_exc.ResourceNotReady, kp.on_present, self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
update_crd.assert_called_once_with(self._kp, self._vifs)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'update_port_pci_info')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_sriov(self, ged, get_k8s_client, update_port_pci_info,
activate_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._vif2.plugin = constants.KURYR_VIF_TYPE_SRIOV
self._vif2.active = True
self._kp['status']['vifs'] = {
'eth0': {'default': True,
'vif': self._vif2.obj_to_primitive()},
'eth1': {'default': False,
'vif': self._vif1.obj_to_primitive()}}
CONF.set_override('enable_node_annotations', True, group='sriov')
self.addCleanup(CONF.clear_override, 'enable_node_annotations',
group='sriov')
activate_vif.side_effect = os_exc.ResourceNotFound()
kp.on_present(self._kp)
update_port_pci_info.assert_called_once_with(self._host, self._vif2)
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.get_services')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_services')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.create_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.base.'
'ServiceSecurityGroupsDriver.get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.base.LBaaSDriver.'
'get_instance')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'is_network_policy_enabled')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_np(self, ged, is_np_enabled, get_k8s_client,
activate_vif, update_crd, get_lb_instance,
get_sg_instance, create_sgr, update_services,
get_services, get_project):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=self._pod,
retry_info=mock.ANY),
mock.call(self._vif2, pod=self._pod,
retry_info=mock.ANY)])
update_crd.assert_called_once_with(self._kp, self._vifs)
create_sgr.assert_called_once_with(self._pod)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_exception_on_pod(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertIsNone(kp.on_finalize(self._kp))
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_called_once_with(
self._kp, constants.KURYRPORT_FINALIZER)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.delete_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_crd_sg_exceptions(self, ged, k8s, get_project,
delete_sg_rules, get_sg,
release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
delete_sg_rules.side_effect = k_exc.ResourceNotReady(self._pod)
get_sg.side_effect = k_exc.ResourceNotReady(self._pod)
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_finalize(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_has_calls(
[mock.call(self._pod, constants.POD_FINALIZER),
mock.call(self._kp, constants.KURYRPORT_FINALIZER)])
delete_sg_rules.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
release_vif.assert_has_calls([mock.call(self._pod, self._vif1,
self._project_id, []),
mock.call(self._pod, self._vif2,
self._project_id, [])])
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_services')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.get_services')
@mock.patch('kuryr_kubernetes.controller.drivers.base.'
'ServiceSecurityGroupsDriver.get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.base.LBaaSDriver.'
'get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'is_network_policy_enabled')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.delete_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_np(self, ged, k8s, get_project, delete_sg_rules,
get_sg, release_vif, is_np_enabled,
get_lb_instance, get_sg_instance, get_services,
update_services):
ged.return_value = [self._driver]
CONF.set_override('enforce_sg_rules', True, group='octavia_defaults')
self.addCleanup(CONF.clear_override, 'enforce_sg_rules',
group='octavia_defaults')
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
selector = mock.sentinel.selector
delete_sg_rules.return_value = selector
get_sg.return_value = self._security_groups
get_services.return_value = mock.sentinel.services
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_finalize(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_has_calls(
[mock.call(self._pod, constants.POD_FINALIZER),
mock.call(self._kp, constants.KURYRPORT_FINALIZER)])
delete_sg_rules.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
release_vif.assert_has_calls([mock.call(self._pod, self._vif1,
self._project_id,
self._security_groups),
mock.call(self._pod, self._vif2,
self._project_id,
self._security_groups)])
get_services.assert_called_once()
update_services.assert_called_once_with(mock.sentinel.services,
selector, self._project_id)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_pod_running(self, ged, k8s):
ged.return_value = [self._driver]
# copy, so it will not be affected by other tests run in parallel.
pod = dict(self._pod)
del(pod['metadata']['deletionTimestamp'])
kp = kuryrport.KuryrPortHandler()
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = pod
self.assertIsNone(kp.on_finalize(self._kp))
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs(self, ged, k8s, get_project, get_sg, get_subnets,
request_vif, update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{constants.DEFAULT_IFNAME:
{'default': True,
'vif': self._vif1}})
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_pod_not_found(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertRaises(k_exc.K8sResourceNotFound, kp.get_vifs, self._kp)
kp.k8s.get.assert_called_once_with(self._pod_uri)
kp.k8s.remove_finalizer.assert_called_once_with(
self._kp, constants.KURYRPORT_FINALIZER)
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_subnet_error(self, ged, k8s, get_project, get_sg,
get_subnets):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.side_effect = os_exc.ResourceNotFound()
self.assertFalse(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_no_vif(self, ged, k8s, get_project, get_sg, get_subnets,
request_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = None
self.assertFalse(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_resource_not_found(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.side_effect = os_exc.ResourceNotFound()
self.assertRaises(k_exc.ResourceNotReady, kp.get_vifs, self._kp)
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_with_additional_vif(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif,
update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
fake_driver = mock.MagicMock()
fake_driver.request_additional_vifs.return_value = [self._vif2]
kp._drv_multi_vif.append(fake_driver)
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{'eth0': {'default': True,
'vif': self._vif1},
'eth1': {'default': False,
'vif': self._vif2}})
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_exception_on_update_crd(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif, update_crd,
release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
update_crd.side_effect = k_exc.K8sClientException()
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{constants.DEFAULT_IFNAME:
{'default': True,
'vif': self._vif1}})
release_vif.assert_called_once_with(self._pod, self._vif1,
self._project_id,
self._security_groups)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_update_kuryrport_crd(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp._update_kuryrport_crd(self._kp, self._vifs)
self._vif1.obj_reset_changes()
self._vif2.obj_reset_changes()
vif1 = self._vif1.obj_to_primitive()
vif2 = self._vif2.obj_to_primitive()
arg = {'vifs': {'eth0': {'default': True, 'vif': vif1},
'eth1': {'default': False, 'vif': vif2}}}
kp.k8s.patch_crd.assert_called_once_with('status',
utils.get_res_link(self._kp),
arg)
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'service_matches_affected_pods')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_update_services(self, ged, k8s, smap):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp._drv_lbaas = mock.MagicMock()
kp._drv_svc_sg = mock.MagicMock()
kp._drv_svc_sg.get_security_groups.return_value = self._security_groups
smap.side_effect = [True, False]
services = {'items': ['service1', 'service2']}
kp._update_services(services, mock.sentinel.crd_pod_selectors,
self._project_id)
smap.assert_has_calls([mock.call('service1',
mock.sentinel.crd_pod_selectors),
mock.call('service2',
mock.sentinel.crd_pod_selectors)])
kp._drv_svc_sg.get_security_groups.assert_called_once_with(
'service1', self._project_id)
kp._drv_lbaas.update_lbaas_sg.assert_called_once_with(
'service1', self._security_groups)
| # Copyright (c) 2020 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from unittest import mock
from openstack import exceptions as os_exc
from os_vif import objects as os_obj
from oslo_config import cfg
from kuryr_kubernetes import constants
from kuryr_kubernetes.controller.drivers import multi_vif
from kuryr_kubernetes.controller.handlers import kuryrport
from kuryr_kubernetes import exceptions as k_exc
from kuryr_kubernetes.tests import base as test_base
from kuryr_kubernetes.tests.unit import kuryr_fixtures as k_fix
from kuryr_kubernetes import utils
CONF = cfg.CONF
class TestKuryrPortHandler(test_base.TestCase):
def setUp(self):
super().setUp()
self._project_id = mock.sentinel.project_id
self._subnets = mock.sentinel.subnets
self._security_groups = mock.sentinel.security_groups
self._host = mock.sentinel.hostname
self._pod_version = mock.sentinel.pod_version
self._pod_link = mock.sentinel.pod_link
self._kp_version = mock.sentinel.kp_version
self._kp_namespace = mock.sentinel.namespace
self._kp_uid = mock.sentinel.kp_uid
self._kp_name = 'pod1'
self._pod = {'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {'resourceVersion': self._pod_version,
'name': self._kp_name,
'deletionTimestamp': mock.sentinel.date,
'namespace': self._kp_namespace},
'spec': {'nodeName': self._host}}
self._kp = {
'apiVersion': 'openstack.org/v1',
'kind': 'KuryrPort',
'metadata': {
'resourceVersion': self._kp_version,
'name': self._kp_name,
'namespace': self._kp_namespace,
'labels': {
constants.KURYRPORT_LABEL: self._host
}
},
'spec': {
'podUid': 'deadbeef',
'podNodeName': self._host
},
'status': {'vifs': {}}
}
self._vif1 = os_obj.vif.VIFBase()
self._vif2 = os_obj.vif.VIFBase()
self._vif1.active = False
self._vif2.active = False
self._vif1.plugin = 'object'
self._vif2.plugin = 'object'
self._vif1_primitive = self._vif1.obj_to_primitive()
self._vif2_primitive = self._vif2.obj_to_primitive()
self._vifs_primitive = {'eth0': {'default': True,
'vif': self._vif1_primitive},
'eth1': {'default': False,
'vif': self._vif2_primitive}}
self._vifs = {'eth0': {'default': True,
'vif': self._vif1},
'eth1': {'default': False,
'vif': self._vif2}}
self._pod_uri = (f"{constants.K8S_API_NAMESPACES}"
f"/{self._kp['metadata']['namespace']}/pods/"
f"{self._kp['metadata']['name']}")
self.useFixture(k_fix.MockNetworkClient())
self._driver = multi_vif.NoopMultiVIFDriver()
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler.get_vifs')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_no_vifs_create(self, ged, get_k8s_client, get_vifs):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
get_vifs.return_value = True
kp.on_present(self._kp)
get_vifs.assert_called_once_with(self._kp)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler.get_vifs')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_getting_vifs_failed(self, ged, get_k8s_client,
get_vifs):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
get_vifs.return_value = False
self.assertFalse(kp.on_present(self._kp))
get_vifs.assert_called_once_with(self._kp)
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present(self, ged, get_k8s_client, activate_vif,
update_crd, get_project):
ged.return_value = [mock.MagicMock]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=self._pod,
retry_info=mock.ANY),
mock.call(self._vif2, pod=self._pod,
retry_info=mock.ANY)])
update_crd.assert_called_once_with(self._kp, self._vifs)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_active(self, ged, get_k8s_client):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._vif1.active = True
self._vif2.active = True
self._kp['status']['vifs'] = {
'eth0': {'default': True,
'vif': self._vif1.obj_to_primitive()},
'eth1': {'default': False,
'vif': self._vif2.obj_to_primitive()}}
kp.on_present(self._kp)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_port_not_found(self, ged, get_k8s_client, activate_vif,
update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
activate_vif.side_effect = os_exc.ResourceNotFound()
kp.on_present(self._kp)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=mock.ANY,
retry_info=mock.ANY),
mock.call(self._vif2, pod=mock.ANY,
retry_info=mock.ANY)])
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_pod_not_found(self, ged, get_k8s_client, activate_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertRaises(k_exc.K8sResourceNotFound, kp.on_present,
self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_fail_update_crd(self, ged, get_k8s_client,
activate_vif, update_crd, get_project,
get_sg, release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
update_crd.side_effect = k_exc.K8sResourceNotFound(self._kp)
get_project.return_value = self._project_id
get_sg.return_value = self._security_groups
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_exception_during_update_crd(self, ged, get_k8s_client,
activate_vif,
update_crd, get_project,
get_sg, release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
update_crd.side_effect = k_exc.K8sClientException()
get_project.return_value = self._project_id
get_sg.return_value = self._security_groups
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
self.assertRaises(k_exc.ResourceNotReady, kp.on_present, self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
update_crd.assert_called_once_with(self._kp, self._vifs)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'update_port_pci_info')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_sriov(self, ged, get_k8s_client, update_port_pci_info,
activate_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._vif2.plugin = constants.KURYR_VIF_TYPE_SRIOV
self._vif2.active = True
self._kp['status']['vifs'] = {
'eth0': {'default': True,
'vif': self._vif2.obj_to_primitive()},
'eth1': {'default': False,
'vif': self._vif1.obj_to_primitive()}}
CONF.set_override('enable_node_annotations', True, group='sriov')
self.addCleanup(CONF.clear_override, 'enable_node_annotations',
group='sriov')
activate_vif.side_effect = os_exc.ResourceNotFound()
kp.on_present(self._kp)
update_port_pci_info.assert_called_once_with(self._host, self._vif2)
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.get_services')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_services')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.create_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.base.'
'ServiceSecurityGroupsDriver.get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.base.LBaaSDriver.'
'get_instance')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'activate_vif')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'is_network_policy_enabled')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_present_np(self, ged, is_np_enabled, get_k8s_client,
activate_vif, update_crd, get_lb_instance,
get_sg_instance, create_sgr, update_services,
get_services, get_project):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_present(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
activate_vif.assert_has_calls([mock.call(self._vif1, pod=self._pod,
retry_info=mock.ANY),
mock.call(self._vif2, pod=self._pod,
retry_info=mock.ANY)])
update_crd.assert_called_once_with(self._kp, self._vifs)
create_sgr.assert_called_once_with(self._pod)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_exception_on_pod(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertIsNone(kp.on_finalize(self._kp))
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_called_once_with(
self._kp, constants.KURYRPORT_FINALIZER)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.delete_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_crd_sg_exceptions(self, ged, k8s, get_project,
delete_sg_rules, get_sg,
release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
delete_sg_rules.side_effect = k_exc.ResourceNotReady(self._pod)
get_sg.side_effect = k_exc.ResourceNotReady(self._pod)
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_finalize(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_has_calls(
[mock.call(self._pod, constants.POD_FINALIZER),
mock.call(self._kp, constants.KURYRPORT_FINALIZER)])
delete_sg_rules.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
release_vif.assert_has_calls([mock.call(self._pod, self._vif1,
self._project_id, []),
mock.call(self._pod, self._vif2,
self._project_id, [])])
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_services')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.get_services')
@mock.patch('kuryr_kubernetes.controller.drivers.base.'
'ServiceSecurityGroupsDriver.get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.base.LBaaSDriver.'
'get_instance')
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'is_network_policy_enabled')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.delete_sg_rules')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_np(self, ged, k8s, get_project, delete_sg_rules,
get_sg, release_vif, is_np_enabled,
get_lb_instance, get_sg_instance, get_services,
update_services):
ged.return_value = [self._driver]
CONF.set_override('enforce_sg_rules', True, group='octavia_defaults')
self.addCleanup(CONF.clear_override, 'enforce_sg_rules',
group='octavia_defaults')
kp = kuryrport.KuryrPortHandler()
self._kp['status']['vifs'] = self._vifs_primitive
get_project.return_value = self._project_id
selector = mock.sentinel.selector
delete_sg_rules.return_value = selector
get_sg.return_value = self._security_groups
get_services.return_value = mock.sentinel.services
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = self._pod
kp.on_finalize(self._kp)
k8s.get.assert_called_once_with(self._pod_uri)
k8s.remove_finalizer.assert_has_calls(
[mock.call(self._pod, constants.POD_FINALIZER),
mock.call(self._kp, constants.KURYRPORT_FINALIZER)])
delete_sg_rules.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
release_vif.assert_has_calls([mock.call(self._pod, self._vif1,
self._project_id,
self._security_groups),
mock.call(self._pod, self._vif2,
self._project_id,
self._security_groups)])
get_services.assert_called_once()
update_services.assert_called_once_with(mock.sentinel.services,
selector, self._project_id)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_on_finalize_pod_running(self, ged, k8s):
ged.return_value = [self._driver]
# copy, so it will not be affected by other tests run in parallel.
pod = dict(self._pod)
del(pod['metadata']['deletionTimestamp'])
kp = kuryrport.KuryrPortHandler()
with mock.patch.object(kp, 'k8s') as k8s:
k8s.get.return_value = pod
self.assertIsNone(kp.on_finalize(self._kp))
k8s.get.assert_called_once_with(self._pod_uri)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs(self, ged, k8s, get_project, get_sg, get_subnets,
request_vif, update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{constants.DEFAULT_IFNAME:
{'default': True,
'vif': self._vif1}})
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_pod_not_found(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.side_effect = k_exc.K8sResourceNotFound(self._pod)
self.assertRaises(k_exc.K8sResourceNotFound, kp.get_vifs, self._kp)
kp.k8s.get.assert_called_once_with(self._pod_uri)
kp.k8s.remove_finalizer.assert_called_once_with(
self._kp, constants.KURYRPORT_FINALIZER)
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_subnet_error(self, ged, k8s, get_project, get_sg,
get_subnets):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.side_effect = os_exc.ResourceNotFound()
self.assertFalse(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_no_vif(self, ged, k8s, get_project, get_sg, get_subnets,
request_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = None
self.assertFalse(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_resource_not_found(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.side_effect = os_exc.ResourceNotFound()
self.assertRaises(k_exc.ResourceNotReady, kp.get_vifs, self._kp)
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_vifs_with_additional_vif(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif,
update_crd):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
fake_driver = mock.MagicMock()
fake_driver.request_additional_vifs.return_value = [self._vif2]
kp._drv_multi_vif.append(fake_driver)
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{'eth0': {'default': True,
'vif': self._vif1},
'eth1': {'default': False,
'vif': self._vif2}})
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'release_vif')
@mock.patch('kuryr_kubernetes.controller.handlers.kuryrport.'
'KuryrPortHandler._update_kuryrport_crd')
@mock.patch('kuryr_kubernetes.controller.drivers.vif_pool.MultiVIFPool.'
'request_vif')
@mock.patch('kuryr_kubernetes.controller.drivers.default_subnet.'
'DefaultPodSubnetDriver.get_subnets')
@mock.patch('kuryr_kubernetes.controller.drivers.default_security_groups.'
'DefaultPodSecurityGroupsDriver.get_security_groups')
@mock.patch('kuryr_kubernetes.controller.drivers.default_project.'
'DefaultPodProjectDriver.get_project')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_get_exception_on_update_crd(self, ged, k8s, get_project, get_sg,
get_subnets, request_vif, update_crd,
release_vif):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp.k8s.get.return_value = self._pod
get_sg.return_value = self._security_groups
get_project.return_value = self._project_id
get_subnets.return_value = mock.sentinel.subnets
request_vif.return_value = self._vif1
update_crd.side_effect = k_exc.K8sClientException()
self.assertTrue(kp.get_vifs(self._kp))
kp.k8s.get.assert_called_once_with(self._pod_uri)
get_project.assert_called_once_with(self._pod)
get_sg.assert_called_once_with(self._pod, self._project_id)
get_subnets.assert_called_once_with(self._pod, self._project_id)
request_vif.assert_called_once_with(self._pod, self._project_id,
mock.sentinel.subnets,
self._security_groups)
update_crd.assert_called_once_with(self._kp,
{constants.DEFAULT_IFNAME:
{'default': True,
'vif': self._vif1}})
release_vif.assert_called_once_with(self._pod, self._vif1,
self._project_id,
self._security_groups)
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_update_kuryrport_crd(self, ged, k8s):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp._update_kuryrport_crd(self._kp, self._vifs)
self._vif1.obj_reset_changes()
self._vif2.obj_reset_changes()
vif1 = self._vif1.obj_to_primitive()
vif2 = self._vif2.obj_to_primitive()
arg = {'vifs': {'eth0': {'default': True, 'vif': vif1},
'eth1': {'default': False, 'vif': vif2}}}
kp.k8s.patch_crd.assert_called_once_with('status',
utils.get_res_link(self._kp),
arg)
@mock.patch('kuryr_kubernetes.controller.drivers.utils.'
'service_matches_affected_pods')
@mock.patch('kuryr_kubernetes.clients.get_kubernetes_client')
@mock.patch('kuryr_kubernetes.controller.drivers.base.MultiVIFDriver.'
'get_enabled_drivers')
def test_update_services(self, ged, k8s, smap):
ged.return_value = [self._driver]
kp = kuryrport.KuryrPortHandler()
kp._drv_lbaas = mock.MagicMock()
kp._drv_svc_sg = mock.MagicMock()
kp._drv_svc_sg.get_security_groups.return_value = self._security_groups
smap.side_effect = [True, False]
services = {'items': ['service1', 'service2']}
kp._update_services(services, mock.sentinel.crd_pod_selectors,
self._project_id)
smap.assert_has_calls([mock.call('service1',
mock.sentinel.crd_pod_selectors),
mock.call('service2',
mock.sentinel.crd_pod_selectors)])
kp._drv_svc_sg.get_security_groups.assert_called_once_with(
'service1', self._project_id)
kp._drv_lbaas.update_lbaas_sg.assert_called_once_with(
'service1', self._security_groups)
|
#!/usr/bin/env python
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import itertools
import operator
import sys
from collections import OrderedDict
from run_eval import datetime_now, run_generate
from utils import ROUGE_KEYS
# A table of supported tasks and the list of scores in the order of importance to be sorted by.
# To add a new task, simply list the score names that `run_eval.run_generate()` returns
task_score_names = {
"translation": ["bleu"],
"summarization": ROUGE_KEYS,
}
def parse_search_arg(search):
groups = search.split()
entries = {k: vs for k, vs in (g.split("=") for g in groups)}
entry_names = list(entries.keys())
sets = [list((f"--{k} {v}") for v in vs.split(":")) for k, vs in entries.items()]
matrix = [list(x) for x in itertools.product(*sets)]
return matrix, entry_names
def run_search():
"""
Run parametric search over the desired hparam space with help of ``run_eval.py``.
All the arguments except ``--search`` are passed to ``run_eval.py`` as is. The values inside of "--search" are parsed, reformatted and fed to ``run_eval.py`` as additional args.
The format for the ``--search`` value is a simple string with hparams and colon separated values to try, e.g.:
```
--search "num_beams=5:10 length_penalty=0.8:1.0:1.2 early_stopping=true:false"
```
which will generate ``12`` ``(2*3*2)`` searches for a product of each hparam. For example the example that was just used will invoke ``run_eval.py`` repeatedly with:
```
--num_beams 5 --length_penalty 0.8 --early_stopping true
--num_beams 5 --length_penalty 0.8 --early_stopping false
[...]
--num_beams 10 --length_penalty 1.2 --early_stopping false
```
On completion, this function prints a markdown table of the results sorted by the best BLEU score and the winning arguments.
"""
prog = sys.argv[0]
parser = argparse.ArgumentParser(
usage="\n\nImportant: this script accepts all arguments `run_eval.py` accepts and then a few extra, therefore refer to `run_eval.py -h` for the complete list."
)
parser.add_argument(
"--search",
type=str,
required=False,
help='param space to search, e.g. "num_beams=5:10 length_penalty=0.8:1.0:1.2"',
)
parser.add_argument(
"--bs", type=int, default=8, required=False, help="initial batch size (may get reduced if it's too big)"
)
parser.add_argument("--task", type=str, help="used for task_specific_params + metrics")
parser.add_argument(
"--info",
nargs="?",
type=str,
const=datetime_now(),
help="add custom notes to be printed before the results table. If no value is passed, the current datetime string will be used.",
)
args, args_main = parser.parse_known_args()
# we share some of the args
args_main.extend(["--task", args.task])
args_normal = [prog] + args_main
# to support variations like translation_en_to_de"
task = "translation" if "translation" in args.task else "summarization"
matrix, col_names = parse_search_arg(args.search)
col_names[0:0] = task_score_names[task] # score cols first
col_widths = {col: len(str(col)) for col in col_names}
results = []
for r in matrix:
hparams = {k: v for k, v in (x.replace("--", "").split() for x in r)}
args_exp = " ".join(r).split()
args_exp.extend(["--bs", str(args.bs)]) # in case we need to reduce its size due to CUDA OOM
sys.argv = args_normal + args_exp
# XXX: need to trap CUDA OOM and lower args.bs if that happens and retry
scores = run_generate(verbose=False)
# make sure scores are first in the table
result = OrderedDict()
for score in task_score_names[task]:
result[score] = scores[score]
result.update(hparams)
results.append(result)
# find widest entries
for k, v in result.items():
l = len(str(v))
if l > col_widths[k]:
col_widths[k] = l
results_sorted = sorted(results, key=operator.itemgetter(*task_score_names[task]), reverse=True)
print(" | ".join([f"{col:{col_widths[col]}}" for col in col_names]))
print(" | ".join([f"{"-"*col_widths[col]}" for col in col_names]))
for row in results_sorted:
print(" | ".join([f"{row[col]:{col_widths[col]}}" for col in col_names]))
best = results_sorted[0]
for score in task_score_names[task]:
del best[score]
best_args = [f"--{k} {v}" for k, v in best.items()]
dyn_args = ["--bs", str(args.bs)]
if args.info:
print(f"\nInfo: {args.info}")
print("\nBest score args:")
print(" ".join(args_main + best_args + dyn_args))
return results_sorted
if __name__ == "__main__":
# Usage:
# [normal-run_eval_search.py cmd plus] \
# --search="num_beams=1:5:10 length_penalty=0.8:1:1.2 early_stopping=true:false"
#
# Example:
# PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_NAME \
# $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target \
# --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation \
# --search="num_beams=1:5:10 length_penalty=0.8:1:1.2 early_stopping=true:false"
run_search()
| #!/usr/bin/env python
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import itertools
import operator
import sys
from collections import OrderedDict
from run_eval import datetime_now, run_generate
from utils import ROUGE_KEYS
# A table of supported tasks and the list of scores in the order of importance to be sorted by.
# To add a new task, simply list the score names that `run_eval.run_generate()` returns
task_score_names = {
"translation": ["bleu"],
"summarization": ROUGE_KEYS,
}
def parse_search_arg(search):
groups = search.split()
entries = {k: vs for k, vs in (g.split("=") for g in groups)}
entry_names = list(entries.keys())
sets = [list((f"--{k} {v}") for v in vs.split(":")) for k, vs in entries.items()]
matrix = [list(x) for x in itertools.product(*sets)]
return matrix, entry_names
def run_search():
"""
Run parametric search over the desired hparam space with help of ``run_eval.py``.
All the arguments except ``--search`` are passed to ``run_eval.py`` as is. The values inside of "--search" are parsed, reformatted and fed to ``run_eval.py`` as additional args.
The format for the ``--search`` value is a simple string with hparams and colon separated values to try, e.g.:
```
--search "num_beams=5:10 length_penalty=0.8:1.0:1.2 early_stopping=true:false"
```
which will generate ``12`` ``(2*3*2)`` searches for a product of each hparam. For example the example that was just used will invoke ``run_eval.py`` repeatedly with:
```
--num_beams 5 --length_penalty 0.8 --early_stopping true
--num_beams 5 --length_penalty 0.8 --early_stopping false
[...]
--num_beams 10 --length_penalty 1.2 --early_stopping false
```
On completion, this function prints a markdown table of the results sorted by the best BLEU score and the winning arguments.
"""
prog = sys.argv[0]
parser = argparse.ArgumentParser(
usage="\n\nImportant: this script accepts all arguments `run_eval.py` accepts and then a few extra, therefore refer to `run_eval.py -h` for the complete list."
)
parser.add_argument(
"--search",
type=str,
required=False,
help='param space to search, e.g. "num_beams=5:10 length_penalty=0.8:1.0:1.2"',
)
parser.add_argument(
"--bs", type=int, default=8, required=False, help="initial batch size (may get reduced if it's too big)"
)
parser.add_argument("--task", type=str, help="used for task_specific_params + metrics")
parser.add_argument(
"--info",
nargs="?",
type=str,
const=datetime_now(),
help="add custom notes to be printed before the results table. If no value is passed, the current datetime string will be used.",
)
args, args_main = parser.parse_known_args()
# we share some of the args
args_main.extend(["--task", args.task])
args_normal = [prog] + args_main
# to support variations like translation_en_to_de"
task = "translation" if "translation" in args.task else "summarization"
matrix, col_names = parse_search_arg(args.search)
col_names[0:0] = task_score_names[task] # score cols first
col_widths = {col: len(str(col)) for col in col_names}
results = []
for r in matrix:
hparams = {k: v for k, v in (x.replace("--", "").split() for x in r)}
args_exp = " ".join(r).split()
args_exp.extend(["--bs", str(args.bs)]) # in case we need to reduce its size due to CUDA OOM
sys.argv = args_normal + args_exp
# XXX: need to trap CUDA OOM and lower args.bs if that happens and retry
scores = run_generate(verbose=False)
# make sure scores are first in the table
result = OrderedDict()
for score in task_score_names[task]:
result[score] = scores[score]
result.update(hparams)
results.append(result)
# find widest entries
for k, v in result.items():
l = len(str(v))
if l > col_widths[k]:
col_widths[k] = l
results_sorted = sorted(results, key=operator.itemgetter(*task_score_names[task]), reverse=True)
print(" | ".join([f"{col:{col_widths[col]}}" for col in col_names]))
print(" | ".join([f"{'-'*col_widths[col]}" for col in col_names]))
for row in results_sorted:
print(" | ".join([f"{row[col]:{col_widths[col]}}" for col in col_names]))
best = results_sorted[0]
for score in task_score_names[task]:
del best[score]
best_args = [f"--{k} {v}" for k, v in best.items()]
dyn_args = ["--bs", str(args.bs)]
if args.info:
print(f"\nInfo: {args.info}")
print("\nBest score args:")
print(" ".join(args_main + best_args + dyn_args))
return results_sorted
if __name__ == "__main__":
# Usage:
# [normal-run_eval_search.py cmd plus] \
# --search="num_beams=1:5:10 length_penalty=0.8:1:1.2 early_stopping=true:false"
#
# Example:
# PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval_search.py $MODEL_NAME \
# $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target \
# --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation \
# --search="num_beams=1:5:10 length_penalty=0.8:1:1.2 early_stopping=true:false"
run_search()
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
cast,
)
import numpy as np
from gym import spaces
from gym.spaces.box import Box
from numpy import ndarray
if TYPE_CHECKING:
from torch import Tensor
import habitat_sim
from habitat.core.dataset import Episode
from habitat.core.registry import registry
from habitat.core.simulator import (
AgentState,
Config,
DepthSensor,
Observations,
RGBSensor,
SemanticSensor,
Sensor,
SensorSuite,
ShortestPathPoint,
Simulator,
VisualObservation,
)
from habitat.core.spaces import Space
RGBSENSOR_DIMENSION = 3
def overwrite_config(
config_from: Config, config_to: Any, ignore_keys: Optional[Set[str]] = None
) -> None:
r"""Takes Habitat Lab config and Habitat-Sim config structures. Overwrites
Habitat-Sim config with Habitat Lab values, where a field name is present
in lowercase. Mostly used to avoid :ref:`sim_cfg.field = hapi_cfg.FIELD`
code.
Args:
config_from: Habitat Lab config node.
config_to: Habitat-Sim config structure.
ignore_keys: Optional set of keys to ignore in config_to
"""
def if_config_to_lower(config):
if isinstance(config, Config):
return {key.lower(): val for key, val in config.items()}
else:
return config
for attr, value in config_from.items():
low_attr = attr.lower()
if ignore_keys is None or low_attr not in ignore_keys:
if hasattr(config_to, low_attr):
setattr(config_to, low_attr, if_config_to_lower(value))
else:
raise NameError(
f"""{low_attr} is not found on habitat_sim but is found on habitat_lab config.
It's also not in the list of keys to ignore: {ignore_keys}
Did you make a typo in the config?
If not the version of Habitat Sim may not be compatible with Habitat Lab version: {config_from}
"""
)
@registry.register_sensor
class HabitatSimRGBSensor(RGBSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
def __init__(self, config: Config) -> None:
self.sim_sensor_type = habitat_sim.SensorType.COLOR
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any) -> Box:
return spaces.Box(
low=0,
high=255,
shape=(self.config.HEIGHT, self.config.WIDTH, RGBSENSOR_DIMENSION),
dtype=np.uint8,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
# remove alpha channel
obs = obs[:, :, :RGBSENSOR_DIMENSION] # type: ignore[index]
return obs
@registry.register_sensor
class HabitatSimDepthSensor(DepthSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
min_depth_value: float
max_depth_value: float
def __init__(self, config: Config) -> None:
self.sim_sensor_type = habitat_sim.SensorType.DEPTH
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
if config.NORMALIZE_DEPTH:
self.min_depth_value = 0
self.max_depth_value = 1
else:
self.min_depth_value = config.MIN_DEPTH
self.max_depth_value = config.MAX_DEPTH
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any) -> Box:
return spaces.Box(
low=self.min_depth_value,
high=self.max_depth_value,
shape=(self.config.HEIGHT, self.config.WIDTH, 1),
dtype=np.float32,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
if isinstance(obs, np.ndarray):
obs = np.clip(obs, self.config.MIN_DEPTH, self.config.MAX_DEPTH)
obs = np.expand_dims(
obs, axis=2
) # make depth observation a 3D array
else:
obs = obs.clamp(self.config.MIN_DEPTH, self.config.MAX_DEPTH) # type: ignore[attr-defined]
obs = obs.unsqueeze(-1) # type: ignore[attr-defined]
if self.config.NORMALIZE_DEPTH:
# normalize depth observation to [0, 1]
obs = (obs - self.config.MIN_DEPTH) / (
self.config.MAX_DEPTH - self.config.MIN_DEPTH
)
return obs
@registry.register_sensor
class HabitatSimSemanticSensor(SemanticSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
def __init__(self, config):
self.sim_sensor_type = habitat_sim.SensorType.SEMANTIC
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any):
return spaces.Box(
low=np.iinfo(np.uint32).min,
high=np.iinfo(np.uint32).max,
shape=(self.config.HEIGHT, self.config.WIDTH),
dtype=np.uint32,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
return obs
def check_sim_obs(obs: ndarray, sensor: Sensor) -> None:
assert obs is not None, (
"Observation corresponding to {} not present in "
"simulator's observations".format(sensor.uuid)
)
HabitatSimVizSensors = Union[
HabitatSimRGBSensor, HabitatSimDepthSensor, HabitatSimSemanticSensor
]
@registry.register_simulator(name="Sim-v0")
class HabitatSim(habitat_sim.Simulator, Simulator):
r"""Simulator wrapper over habitat-sim
habitat-sim repo: https://github.com/facebookresearch/habitat-sim
Args:
config: configuration for initializing the simulator.
"""
def __init__(self, config: Config) -> None:
self.habitat_config = config
agent_config = self._get_agent_config()
sim_sensors = []
for sensor_name in agent_config.SENSORS:
sensor_cfg = getattr(self.habitat_config, sensor_name)
sensor_type = registry.get_sensor(sensor_cfg.TYPE)
assert sensor_type is not None, "invalid sensor type {}".format(
sensor_cfg.TYPE
)
sim_sensors.append(sensor_type(sensor_cfg))
self._sensor_suite = SensorSuite(sim_sensors)
self.sim_config = self.create_sim_config(self._sensor_suite)
self._current_scene = self.sim_config.sim_cfg.scene_id
super().__init__(self.sim_config)
self._action_space = spaces.Discrete(
len(self.sim_config.agents[0].action_space)
)
self._prev_sim_obs: Optional[Observations] = None
def create_sim_config(
self, _sensor_suite: SensorSuite
) -> habitat_sim.Configuration:
sim_config = habitat_sim.SimulatorConfiguration()
# Check if Habitat-Sim is post Scene Config Update
if not hasattr(sim_config, "scene_id"):
raise RuntimeError(
"Incompatible version of Habitat-Sim detected, please upgrade habitat_sim"
)
overwrite_config(
config_from=self.habitat_config.HABITAT_SIM_V0,
config_to=sim_config,
# Ignore key as it gets propogated to sensor below
ignore_keys={"gpu_gpu"},
)
sim_config.scene_id = self.habitat_config.SCENE
agent_config = habitat_sim.AgentConfiguration()
overwrite_config(
config_from=self._get_agent_config(),
config_to=agent_config,
# These keys are only used by Hab-Lab
ignore_keys={
"is_set_start_state",
# This is the Sensor Config. Unpacked below
"sensors",
"start_position",
"start_rotation",
},
)
sensor_specifications = []
VisualSensorTypeSet = {
habitat_sim.SensorType.COLOR,
habitat_sim.SensorType.DEPTH,
habitat_sim.SensorType.SEMANTIC,
}
CameraSensorSubTypeSet = {
habitat_sim.SensorSubType.PINHOLE,
habitat_sim.SensorSubType.ORTHOGRAPHIC,
}
for sensor in _sensor_suite.sensors.values():
# Check if type VisualSensorSpec, we know that Sensor is one of HabitatSimRGBSensor, HabitatSimDepthSensor, HabitatSimSemanticSensor
if (
getattr(sensor, "sim_sensor_type", [])
not in VisualSensorTypeSet
):
raise ValueError(
f"""{getattr(sensor, "sim_sensor_type", [])} is an illegal sensorType that is not implemented yet"""
)
# Check if type CameraSensorSpec
if (
getattr(sensor, "sim_sensor_subtype", [])
not in CameraSensorSubTypeSet
):
raise ValueError(
f"""{getattr(sensor, "sim_sensor_subtype", [])} is an illegal sensorSubType for a VisualSensor"""
)
# TODO: Implement checks for other types of SensorSpecs
sim_sensor_cfg = habitat_sim.CameraSensorSpec()
# TODO Handle configs for custom VisualSensors that might need
# their own ignore_keys. Maybe with special key / checking
# SensorType
overwrite_config(
config_from=sensor.config,
config_to=sim_sensor_cfg,
# These keys are only used by Hab-Lab
# or translated into the sensor config manually
ignore_keys={
"height",
"hfov",
"max_depth",
"min_depth",
"normalize_depth",
"type",
"width",
},
)
sim_sensor_cfg.uuid = sensor.uuid
sim_sensor_cfg.resolution = list(
sensor.observation_space.shape[:2]
)
# TODO(maksymets): Add configure method to Sensor API to avoid
# accessing child attributes through parent interface
# We know that the Sensor has to be one of these Sensors
sensor = cast(HabitatSimVizSensors, sensor)
sim_sensor_cfg.sensor_type = sensor.sim_sensor_type
sim_sensor_cfg.sensor_subtype = sensor.sim_sensor_subtype
sim_sensor_cfg.gpu2gpu_transfer = (
self.habitat_config.HABITAT_SIM_V0.GPU_GPU
)
sensor_specifications.append(sim_sensor_cfg)
agent_config.sensor_specifications = sensor_specifications
agent_config.action_space = registry.get_action_space_configuration(
self.habitat_config.ACTION_SPACE_CONFIG
)(self.habitat_config).get()
return habitat_sim.Configuration(sim_config, [agent_config])
@property
def sensor_suite(self) -> SensorSuite:
return self._sensor_suite
@property
def action_space(self) -> Space:
return self._action_space
def _update_agents_state(self) -> bool:
is_updated = False
for agent_id, _ in enumerate(self.habitat_config.AGENTS):
agent_cfg = self._get_agent_config(agent_id)
if agent_cfg.IS_SET_START_STATE:
self.set_agent_state(
agent_cfg.START_POSITION,
agent_cfg.START_ROTATION,
agent_id,
)
is_updated = True
return is_updated
def reset(self) -> Observations:
sim_obs = super().reset()
if self._update_agents_state():
sim_obs = self.get_sensor_observations()
self._prev_sim_obs = sim_obs
return self._sensor_suite.get_observations(sim_obs)
def step(self, action: Union[str, int]) -> Observations:
sim_obs = super().step(action)
self._prev_sim_obs = sim_obs
observations = self._sensor_suite.get_observations(sim_obs)
return observations
def render(self, mode: str = "rgb") -> Any:
r"""
Args:
mode: sensor whose observation is used for returning the frame,
eg: "rgb", "depth", "semantic"
Returns:
rendered frame according to the mode
"""
sim_obs = self.get_sensor_observations()
observations = self._sensor_suite.get_observations(sim_obs)
output = observations.get(mode)
assert output is not None, "mode {} sensor is not active".format(mode)
if not isinstance(output, np.ndarray):
# If it is not a numpy array, it is a torch tensor
# The function expects the result to be a numpy array
output = output.to("cpu").numpy()
return output
def reconfigure(self, habitat_config: Config) -> None:
# TODO(maksymets): Switch to Habitat-Sim more efficient caching
is_same_scene = habitat_config.SCENE == self._current_scene
self.habitat_config = habitat_config
self.sim_config = self.create_sim_config(self._sensor_suite)
if not is_same_scene:
self._current_scene = habitat_config.SCENE
self.close()
super().reconfigure(self.sim_config)
self._update_agents_state()
def geodesic_distance(
self,
position_a: Union[Sequence[float], ndarray],
position_b: Union[Sequence[float], Sequence[Sequence[float]]],
episode: Optional[Episode] = None,
) -> float:
if episode is None or episode._shortest_path_cache is None:
path = habitat_sim.MultiGoalShortestPath()
if isinstance(position_b[0], (Sequence, np.ndarray)):
path.requested_ends = np.array(position_b, dtype=np.float32)
else:
path.requested_ends = np.array(
[np.array(position_b, dtype=np.float32)]
)
else:
path = episode._shortest_path_cache
path.requested_start = np.array(position_a, dtype=np.float32)
self.pathfinder.find_path(path)
if episode is not None:
episode._shortest_path_cache = path
return path.geodesic_distance
def action_space_shortest_path(
self,
source: AgentState,
targets: Sequence[AgentState],
agent_id: int = 0,
) -> List[ShortestPathPoint]:
r"""
Returns:
List of agent states and actions along the shortest path from
source to the nearest target (both included). If one of the
target(s) is identical to the source, a list containing only
one node with the identical agent state is returned. Returns
an empty list in case none of the targets are reachable from
the source. For the last item in the returned list the action
will be None.
"""
raise NotImplementedError(
"This function is no longer implemented. Please use the greedy "
"follower instead"
)
@property
def up_vector(self) -> np.ndarray:
return np.array([0.0, 1.0, 0.0])
@property
def forward_vector(self) -> np.ndarray:
return -np.array([0.0, 0.0, 1.0])
def get_straight_shortest_path_points(self, position_a, position_b):
path = habitat_sim.ShortestPath()
path.requested_start = position_a
path.requested_end = position_b
self.pathfinder.find_path(path)
return path.points
def sample_navigable_point(self) -> List[float]:
return self.pathfinder.get_random_navigable_point().tolist()
def is_navigable(self, point: List[float]) -> bool:
return self.pathfinder.is_navigable(point)
def semantic_annotations(self):
r"""
Returns:
SemanticScene which is a three level hierarchy of semantic
annotations for the current scene. Specifically this method
returns a SemanticScene which contains a list of SemanticLevel's
where each SemanticLevel contains a list of SemanticRegion's where
each SemanticRegion contains a list of SemanticObject's.
SemanticScene has attributes: aabb(axis-aligned bounding box) which
has attributes aabb.center and aabb.sizes which are 3d vectors,
categories, levels, objects, regions.
SemanticLevel has attributes: id, aabb, objects and regions.
SemanticRegion has attributes: id, level, aabb, category (to get
name of category use category.name()) and objects.
SemanticObject has attributes: id, region, aabb, obb (oriented
bounding box) and category.
SemanticScene contains List[SemanticLevels]
SemanticLevel contains List[SemanticRegion]
SemanticRegion contains List[SemanticObject]
Example to loop through in a hierarchical fashion:
for level in semantic_scene.levels:
for region in level.regions:
for obj in region.objects:
"""
return self.semantic_scene
def _get_agent_config(self, agent_id: Optional[int] = None) -> Any:
if agent_id is None:
agent_id = self.habitat_config.DEFAULT_AGENT_ID
agent_name = self.habitat_config.AGENTS[agent_id]
agent_config = getattr(self.habitat_config, agent_name)
return agent_config
def get_agent_state(self, agent_id: int = 0) -> habitat_sim.AgentState:
assert agent_id == 0, "No support of multi agent in {} yet.".format(
self.__class__.__name__
)
return self.get_agent(agent_id).get_state()
def set_agent_state(
self,
position: List[float],
rotation: List[float],
agent_id: int = 0,
reset_sensors: bool = True,
) -> bool:
r"""Sets agent state similar to initialize_agent, but without agents
creation. On failure to place the agent in the proper position, it is
moved back to its previous pose.
Args:
position: list containing 3 entries for (x, y, z).
rotation: list with 4 entries for (x, y, z, w) elements of unit
quaternion (versor) representing agent 3D orientation,
(https://en.wikipedia.org/wiki/Versor)
agent_id: int identification of agent from multiagent setup.
reset_sensors: bool for if sensor changes (e.g. tilt) should be
reset).
Returns:
True if the set was successful else moves the agent back to its
original pose and returns false.
"""
agent = self.get_agent(agent_id)
new_state = self.get_agent_state(agent_id)
new_state.position = position
new_state.rotation = rotation
# NB: The agent state also contains the sensor states in _absolute_
# coordinates. In order to set the agent's body to a specific
# location and have the sensors follow, we must not provide any
# state for the sensors. This will cause them to follow the agent's
# body
new_state.sensor_states = {}
agent.set_state(new_state, reset_sensors)
return True
def get_observations_at(
self,
position: Optional[List[float]] = None,
rotation: Optional[List[float]] = None,
keep_agent_at_new_pose: bool = False,
) -> Optional[Observations]:
current_state = self.get_agent_state()
if position is None or rotation is None:
success = True
else:
success = self.set_agent_state(
position, rotation, reset_sensors=False
)
if success:
sim_obs = self.get_sensor_observations()
self._prev_sim_obs = sim_obs
observations = self._sensor_suite.get_observations(sim_obs)
if not keep_agent_at_new_pose:
self.set_agent_state(
current_state.position,
current_state.rotation,
reset_sensors=False,
)
return observations
else:
return None
def distance_to_closest_obstacle(
self, position: ndarray, max_search_radius: float = 2.0
) -> float:
return self.pathfinder.distance_to_closest_obstacle(
position, max_search_radius
)
def island_radius(self, position: Sequence[float]) -> float:
return self.pathfinder.island_radius(position)
@property
def previous_step_collided(self):
r"""Whether or not the previous step resulted in a collision
Returns:
bool: True if the previous step resulted in a collision, false otherwise
Warning:
This feild is only updated when :meth:`step`, :meth:`reset`, or :meth:`get_observations_at` are
called. It does not update when the agent is moved to a new loction. Furthermore, it
will _always_ be false after :meth:`reset` or :meth:`get_observations_at` as neither of those
result in an action (step) being taken.
"""
return self._prev_sim_obs.get("collided", False)
| #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
cast,
)
import numpy as np
from gym import spaces
from gym.spaces.box import Box
from numpy import ndarray
if TYPE_CHECKING:
from torch import Tensor
import habitat_sim
from habitat.core.dataset import Episode
from habitat.core.registry import registry
from habitat.core.simulator import (
AgentState,
Config,
DepthSensor,
Observations,
RGBSensor,
SemanticSensor,
Sensor,
SensorSuite,
ShortestPathPoint,
Simulator,
VisualObservation,
)
from habitat.core.spaces import Space
RGBSENSOR_DIMENSION = 3
def overwrite_config(
config_from: Config, config_to: Any, ignore_keys: Optional[Set[str]] = None
) -> None:
r"""Takes Habitat Lab config and Habitat-Sim config structures. Overwrites
Habitat-Sim config with Habitat Lab values, where a field name is present
in lowercase. Mostly used to avoid :ref:`sim_cfg.field = hapi_cfg.FIELD`
code.
Args:
config_from: Habitat Lab config node.
config_to: Habitat-Sim config structure.
ignore_keys: Optional set of keys to ignore in config_to
"""
def if_config_to_lower(config):
if isinstance(config, Config):
return {key.lower(): val for key, val in config.items()}
else:
return config
for attr, value in config_from.items():
low_attr = attr.lower()
if ignore_keys is None or low_attr not in ignore_keys:
if hasattr(config_to, low_attr):
setattr(config_to, low_attr, if_config_to_lower(value))
else:
raise NameError(
f"""{low_attr} is not found on habitat_sim but is found on habitat_lab config.
It's also not in the list of keys to ignore: {ignore_keys}
Did you make a typo in the config?
If not the version of Habitat Sim may not be compatible with Habitat Lab version: {config_from}
"""
)
@registry.register_sensor
class HabitatSimRGBSensor(RGBSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
def __init__(self, config: Config) -> None:
self.sim_sensor_type = habitat_sim.SensorType.COLOR
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any) -> Box:
return spaces.Box(
low=0,
high=255,
shape=(self.config.HEIGHT, self.config.WIDTH, RGBSENSOR_DIMENSION),
dtype=np.uint8,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
# remove alpha channel
obs = obs[:, :, :RGBSENSOR_DIMENSION] # type: ignore[index]
return obs
@registry.register_sensor
class HabitatSimDepthSensor(DepthSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
min_depth_value: float
max_depth_value: float
def __init__(self, config: Config) -> None:
self.sim_sensor_type = habitat_sim.SensorType.DEPTH
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
if config.NORMALIZE_DEPTH:
self.min_depth_value = 0
self.max_depth_value = 1
else:
self.min_depth_value = config.MIN_DEPTH
self.max_depth_value = config.MAX_DEPTH
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any) -> Box:
return spaces.Box(
low=self.min_depth_value,
high=self.max_depth_value,
shape=(self.config.HEIGHT, self.config.WIDTH, 1),
dtype=np.float32,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
if isinstance(obs, np.ndarray):
obs = np.clip(obs, self.config.MIN_DEPTH, self.config.MAX_DEPTH)
obs = np.expand_dims(
obs, axis=2
) # make depth observation a 3D array
else:
obs = obs.clamp(self.config.MIN_DEPTH, self.config.MAX_DEPTH) # type: ignore[attr-defined]
obs = obs.unsqueeze(-1) # type: ignore[attr-defined]
if self.config.NORMALIZE_DEPTH:
# normalize depth observation to [0, 1]
obs = (obs - self.config.MIN_DEPTH) / (
self.config.MAX_DEPTH - self.config.MIN_DEPTH
)
return obs
@registry.register_sensor
class HabitatSimSemanticSensor(SemanticSensor):
sim_sensor_type: habitat_sim.SensorType
sim_sensor_subtype: habitat_sim.SensorSubType
def __init__(self, config):
self.sim_sensor_type = habitat_sim.SensorType.SEMANTIC
self.sim_sensor_subtype = habitat_sim.SensorSubType.PINHOLE
super().__init__(config=config)
def _get_observation_space(self, *args: Any, **kwargs: Any):
return spaces.Box(
low=np.iinfo(np.uint32).min,
high=np.iinfo(np.uint32).max,
shape=(self.config.HEIGHT, self.config.WIDTH),
dtype=np.uint32,
)
def get_observation(
self, sim_obs: Dict[str, Union[ndarray, bool, "Tensor"]]
) -> VisualObservation:
obs = cast(Optional[VisualObservation], sim_obs.get(self.uuid, None))
check_sim_obs(obs, self)
return obs
def check_sim_obs(obs: ndarray, sensor: Sensor) -> None:
assert obs is not None, (
"Observation corresponding to {} not present in "
"simulator's observations".format(sensor.uuid)
)
HabitatSimVizSensors = Union[
HabitatSimRGBSensor, HabitatSimDepthSensor, HabitatSimSemanticSensor
]
@registry.register_simulator(name="Sim-v0")
class HabitatSim(habitat_sim.Simulator, Simulator):
r"""Simulator wrapper over habitat-sim
habitat-sim repo: https://github.com/facebookresearch/habitat-sim
Args:
config: configuration for initializing the simulator.
"""
def __init__(self, config: Config) -> None:
self.habitat_config = config
agent_config = self._get_agent_config()
sim_sensors = []
for sensor_name in agent_config.SENSORS:
sensor_cfg = getattr(self.habitat_config, sensor_name)
sensor_type = registry.get_sensor(sensor_cfg.TYPE)
assert sensor_type is not None, "invalid sensor type {}".format(
sensor_cfg.TYPE
)
sim_sensors.append(sensor_type(sensor_cfg))
self._sensor_suite = SensorSuite(sim_sensors)
self.sim_config = self.create_sim_config(self._sensor_suite)
self._current_scene = self.sim_config.sim_cfg.scene_id
super().__init__(self.sim_config)
self._action_space = spaces.Discrete(
len(self.sim_config.agents[0].action_space)
)
self._prev_sim_obs: Optional[Observations] = None
def create_sim_config(
self, _sensor_suite: SensorSuite
) -> habitat_sim.Configuration:
sim_config = habitat_sim.SimulatorConfiguration()
# Check if Habitat-Sim is post Scene Config Update
if not hasattr(sim_config, "scene_id"):
raise RuntimeError(
"Incompatible version of Habitat-Sim detected, please upgrade habitat_sim"
)
overwrite_config(
config_from=self.habitat_config.HABITAT_SIM_V0,
config_to=sim_config,
# Ignore key as it gets propogated to sensor below
ignore_keys={"gpu_gpu"},
)
sim_config.scene_id = self.habitat_config.SCENE
agent_config = habitat_sim.AgentConfiguration()
overwrite_config(
config_from=self._get_agent_config(),
config_to=agent_config,
# These keys are only used by Hab-Lab
ignore_keys={
"is_set_start_state",
# This is the Sensor Config. Unpacked below
"sensors",
"start_position",
"start_rotation",
},
)
sensor_specifications = []
VisualSensorTypeSet = {
habitat_sim.SensorType.COLOR,
habitat_sim.SensorType.DEPTH,
habitat_sim.SensorType.SEMANTIC,
}
CameraSensorSubTypeSet = {
habitat_sim.SensorSubType.PINHOLE,
habitat_sim.SensorSubType.ORTHOGRAPHIC,
}
for sensor in _sensor_suite.sensors.values():
# Check if type VisualSensorSpec, we know that Sensor is one of HabitatSimRGBSensor, HabitatSimDepthSensor, HabitatSimSemanticSensor
if (
getattr(sensor, "sim_sensor_type", [])
not in VisualSensorTypeSet
):
raise ValueError(
f"""{getattr(sensor, "sim_sensor_type", [])} is an illegal sensorType that is not implemented yet"""
)
# Check if type CameraSensorSpec
if (
getattr(sensor, "sim_sensor_subtype", [])
not in CameraSensorSubTypeSet
):
raise ValueError(
f"""{getattr(sensor, "sim_sensor_subtype", [])} is an illegal sensorSubType for a VisualSensor"""
)
# TODO: Implement checks for other types of SensorSpecs
sim_sensor_cfg = habitat_sim.CameraSensorSpec()
# TODO Handle configs for custom VisualSensors that might need
# their own ignore_keys. Maybe with special key / checking
# SensorType
overwrite_config(
config_from=sensor.config,
config_to=sim_sensor_cfg,
# These keys are only used by Hab-Lab
# or translated into the sensor config manually
ignore_keys={
"height",
"hfov",
"max_depth",
"min_depth",
"normalize_depth",
"type",
"width",
},
)
sim_sensor_cfg.uuid = sensor.uuid
sim_sensor_cfg.resolution = list(
sensor.observation_space.shape[:2]
)
# TODO(maksymets): Add configure method to Sensor API to avoid
# accessing child attributes through parent interface
# We know that the Sensor has to be one of these Sensors
sensor = cast(HabitatSimVizSensors, sensor)
sim_sensor_cfg.sensor_type = sensor.sim_sensor_type
sim_sensor_cfg.sensor_subtype = sensor.sim_sensor_subtype
sim_sensor_cfg.gpu2gpu_transfer = (
self.habitat_config.HABITAT_SIM_V0.GPU_GPU
)
sensor_specifications.append(sim_sensor_cfg)
agent_config.sensor_specifications = sensor_specifications
agent_config.action_space = registry.get_action_space_configuration(
self.habitat_config.ACTION_SPACE_CONFIG
)(self.habitat_config).get()
return habitat_sim.Configuration(sim_config, [agent_config])
@property
def sensor_suite(self) -> SensorSuite:
return self._sensor_suite
@property
def action_space(self) -> Space:
return self._action_space
def _update_agents_state(self) -> bool:
is_updated = False
for agent_id, _ in enumerate(self.habitat_config.AGENTS):
agent_cfg = self._get_agent_config(agent_id)
if agent_cfg.IS_SET_START_STATE:
self.set_agent_state(
agent_cfg.START_POSITION,
agent_cfg.START_ROTATION,
agent_id,
)
is_updated = True
return is_updated
def reset(self) -> Observations:
sim_obs = super().reset()
if self._update_agents_state():
sim_obs = self.get_sensor_observations()
self._prev_sim_obs = sim_obs
return self._sensor_suite.get_observations(sim_obs)
def step(self, action: Union[str, int]) -> Observations:
sim_obs = super().step(action)
self._prev_sim_obs = sim_obs
observations = self._sensor_suite.get_observations(sim_obs)
return observations
def render(self, mode: str = "rgb") -> Any:
r"""
Args:
mode: sensor whose observation is used for returning the frame,
eg: "rgb", "depth", "semantic"
Returns:
rendered frame according to the mode
"""
sim_obs = self.get_sensor_observations()
observations = self._sensor_suite.get_observations(sim_obs)
output = observations.get(mode)
assert output is not None, "mode {} sensor is not active".format(mode)
if not isinstance(output, np.ndarray):
# If it is not a numpy array, it is a torch tensor
# The function expects the result to be a numpy array
output = output.to("cpu").numpy()
return output
def reconfigure(self, habitat_config: Config) -> None:
# TODO(maksymets): Switch to Habitat-Sim more efficient caching
is_same_scene = habitat_config.SCENE == self._current_scene
self.habitat_config = habitat_config
self.sim_config = self.create_sim_config(self._sensor_suite)
if not is_same_scene:
self._current_scene = habitat_config.SCENE
self.close()
super().reconfigure(self.sim_config)
self._update_agents_state()
def geodesic_distance(
self,
position_a: Union[Sequence[float], ndarray],
position_b: Union[Sequence[float], Sequence[Sequence[float]]],
episode: Optional[Episode] = None,
) -> float:
if episode is None or episode._shortest_path_cache is None:
path = habitat_sim.MultiGoalShortestPath()
if isinstance(position_b[0], (Sequence, np.ndarray)):
path.requested_ends = np.array(position_b, dtype=np.float32)
else:
path.requested_ends = np.array(
[np.array(position_b, dtype=np.float32)]
)
else:
path = episode._shortest_path_cache
path.requested_start = np.array(position_a, dtype=np.float32)
self.pathfinder.find_path(path)
if episode is not None:
episode._shortest_path_cache = path
return path.geodesic_distance
def action_space_shortest_path(
self,
source: AgentState,
targets: Sequence[AgentState],
agent_id: int = 0,
) -> List[ShortestPathPoint]:
r"""
Returns:
List of agent states and actions along the shortest path from
source to the nearest target (both included). If one of the
target(s) is identical to the source, a list containing only
one node with the identical agent state is returned. Returns
an empty list in case none of the targets are reachable from
the source. For the last item in the returned list the action
will be None.
"""
raise NotImplementedError(
"This function is no longer implemented. Please use the greedy "
"follower instead"
)
@property
def up_vector(self) -> np.ndarray:
return np.array([0.0, 1.0, 0.0])
@property
def forward_vector(self) -> np.ndarray:
return -np.array([0.0, 0.0, 1.0])
def get_straight_shortest_path_points(self, position_a, position_b):
path = habitat_sim.ShortestPath()
path.requested_start = position_a
path.requested_end = position_b
self.pathfinder.find_path(path)
return path.points
def sample_navigable_point(self) -> List[float]:
return self.pathfinder.get_random_navigable_point().tolist()
def is_navigable(self, point: List[float]) -> bool:
return self.pathfinder.is_navigable(point)
def semantic_annotations(self):
r"""
Returns:
SemanticScene which is a three level hierarchy of semantic
annotations for the current scene. Specifically this method
returns a SemanticScene which contains a list of SemanticLevel's
where each SemanticLevel contains a list of SemanticRegion's where
each SemanticRegion contains a list of SemanticObject's.
SemanticScene has attributes: aabb(axis-aligned bounding box) which
has attributes aabb.center and aabb.sizes which are 3d vectors,
categories, levels, objects, regions.
SemanticLevel has attributes: id, aabb, objects and regions.
SemanticRegion has attributes: id, level, aabb, category (to get
name of category use category.name()) and objects.
SemanticObject has attributes: id, region, aabb, obb (oriented
bounding box) and category.
SemanticScene contains List[SemanticLevels]
SemanticLevel contains List[SemanticRegion]
SemanticRegion contains List[SemanticObject]
Example to loop through in a hierarchical fashion:
for level in semantic_scene.levels:
for region in level.regions:
for obj in region.objects:
"""
return self.semantic_scene
def _get_agent_config(self, agent_id: Optional[int] = None) -> Any:
if agent_id is None:
agent_id = self.habitat_config.DEFAULT_AGENT_ID
agent_name = self.habitat_config.AGENTS[agent_id]
agent_config = getattr(self.habitat_config, agent_name)
return agent_config
def get_agent_state(self, agent_id: int = 0) -> habitat_sim.AgentState:
assert agent_id == 0, "No support of multi agent in {} yet.".format(
self.__class__.__name__
)
return self.get_agent(agent_id).get_state()
def set_agent_state(
self,
position: List[float],
rotation: List[float],
agent_id: int = 0,
reset_sensors: bool = True,
) -> bool:
r"""Sets agent state similar to initialize_agent, but without agents
creation. On failure to place the agent in the proper position, it is
moved back to its previous pose.
Args:
position: list containing 3 entries for (x, y, z).
rotation: list with 4 entries for (x, y, z, w) elements of unit
quaternion (versor) representing agent 3D orientation,
(https://en.wikipedia.org/wiki/Versor)
agent_id: int identification of agent from multiagent setup.
reset_sensors: bool for if sensor changes (e.g. tilt) should be
reset).
Returns:
True if the set was successful else moves the agent back to its
original pose and returns false.
"""
agent = self.get_agent(agent_id)
new_state = self.get_agent_state(agent_id)
new_state.position = position
new_state.rotation = rotation
# NB: The agent state also contains the sensor states in _absolute_
# coordinates. In order to set the agent's body to a specific
# location and have the sensors follow, we must not provide any
# state for the sensors. This will cause them to follow the agent's
# body
new_state.sensor_states = {}
agent.set_state(new_state, reset_sensors)
return True
def get_observations_at(
self,
position: Optional[List[float]] = None,
rotation: Optional[List[float]] = None,
keep_agent_at_new_pose: bool = False,
) -> Optional[Observations]:
current_state = self.get_agent_state()
if position is None or rotation is None:
success = True
else:
success = self.set_agent_state(
position, rotation, reset_sensors=False
)
if success:
sim_obs = self.get_sensor_observations()
self._prev_sim_obs = sim_obs
observations = self._sensor_suite.get_observations(sim_obs)
if not keep_agent_at_new_pose:
self.set_agent_state(
current_state.position,
current_state.rotation,
reset_sensors=False,
)
return observations
else:
return None
def distance_to_closest_obstacle(
self, position: ndarray, max_search_radius: float = 2.0
) -> float:
return self.pathfinder.distance_to_closest_obstacle(
position, max_search_radius
)
def island_radius(self, position: Sequence[float]) -> float:
return self.pathfinder.island_radius(position)
@property
def previous_step_collided(self):
r"""Whether or not the previous step resulted in a collision
Returns:
bool: True if the previous step resulted in a collision, false otherwise
Warning:
This feild is only updated when :meth:`step`, :meth:`reset`, or :meth:`get_observations_at` are
called. It does not update when the agent is moved to a new loction. Furthermore, it
will _always_ be false after :meth:`reset` or :meth:`get_observations_at` as neither of those
result in an action (step) being taken.
"""
return self._prev_sim_obs.get("collided", False)
|
import os
from pathlib import Path
import pytest
import scrapli
from scrapli import Scrape
UNIT_TEST_DIR = f"{Path(scrapli.__file__).parents[1]}/tests/unit/"
def test__str():
conn = Scrape(host="myhost")
assert str(conn) == "Scrape Object for host myhost"
def test__repr():
conn = Scrape(host="myhost")
assert (
repr(conn)
== "Scrape(host='myhost', port=22, auth_username='', auth_password='', auth_private_key=b'', "
"auth_strict_key=True, timeout_socket=5, timeout_transport=5, timeout_ops=10, timeout_exit=True, "
"keepalive=False, keepalive_interval=30, keepalive_type='network', keepalive_pattern='\\x05', "
"comms_prompt_pattern='^[a-z0-9.\\\\-@()/:]{1,32}[#>$]\\\\s*$', comms_return_char='\\n', comms_ansi=False, "
"ssh_config_file='', ssh_known_hosts_file='', on_open=None, on_close=None, transport='system')"
)
@pytest.mark.parametrize(
"attr_setup",
[
("host", "", ValueError, "`host` should be a hostname/ip address, got nothing!"),
("port", "notanint", TypeError, "`port` should be int, got <class 'str'>"),
(
"auth_strict_key",
"notabool",
TypeError,
"`auth_strict_key` should be bool, got <class 'str'>",
),
(
"auth_private_key",
"notafile",
ValueError,
"Provided public key `notafile` is not a file",
),
("timeout_exit", "notabool", TypeError, "`timeout_exit` should be bool, got <class 'str'>"),
("keepalive", "notabool", TypeError, "`keepalive` should be bool, got <class 'str'>"),
(
"keepalive_type",
"notvalid",
ValueError,
"`notvalid` is an invalid keepalive_type; must be 'network' or 'standard'",
),
(
"comms_return_char",
True,
TypeError,
"`comms_return_char` should be str, got <class 'bool'>",
),
("comms_ansi", "notabool", TypeError, "`comms_ansi` should be bool, got <class 'str'>"),
("on_open", "notacallable", TypeError, "`on_open` must be a callable, got <class 'str'>"),
("on_close", "notacallable", TypeError, "`on_close` must be a callable, got <class 'str'>"),
(
"ssh_config_file",
None,
TypeError,
"`ssh_config_file` must be str or bool, got <class 'NoneType'>",
),
(
"ssh_known_hosts_file",
None,
TypeError,
"`ssh_known_hosts_file` must be str or bool, got <class 'NoneType'>",
),
(
"transport",
"notatransport",
ValueError,
"`transport` should be one of ssh2|paramiko|system|telnet, got `notatransport`",
),
],
ids=[
"host",
"port",
"auth_strict_key",
"auth_private_key",
"timeout_exit",
"keepalive",
"keepalive_type",
"comms_return_char",
"comms_ansi",
"on_open",
"on_close",
"ssh_config_file",
"ssh_known_hosts_file",
"transport",
],
)
def test_exceptions_raised(attr_setup):
attr_name = attr_setup[0]
attr_value = attr_setup[1]
attr_exc = attr_setup[2]
attr_msg = attr_setup[3]
args = {attr_name: attr_value}
if attr_name != "host":
args["host"] = "myhost"
with pytest.raises(attr_exc) as exc:
Scrape(**args)
assert str(exc.value) == attr_msg
@pytest.mark.parametrize(
"attr_setup",
[
("host", "myhost", "myhost"),
("host", "myhost ", "myhost"),
("port", 123, 123),
("auth_username", "tacocat", "tacocat"),
("auth_username", "tacocat ", "tacocat"),
("auth_password", "tacocat", "tacocat"),
("auth_password", "tacocat ", "tacocat"),
("auth_private_key", f"{UNIT_TEST_DIR}_ssh_config", f"{UNIT_TEST_DIR}_ssh_config".encode()),
("auth_strict_key", False, False),
("timeout_socket", 100, 100),
("timeout_transport", 100, 100),
("timeout_ops", 100, 100),
("timeout_exit", False, False),
("keepalive", True, True),
("keepalive_interval", 100, 100),
("keepalive_type", "standard", "standard"),
("keepalive_pattern", "tacocat", "tacocat"),
("comms_prompt_pattern", "tacocat", "tacocat"),
("comms_return_char", "tacocat", "tacocat"),
("comms_ansi", True, True),
("on_open", print, print),
("on_close", print, print),
("transport", "ssh2", "ssh2"),
],
ids=[
"host",
"host_strip",
"port",
"auth_username",
"auth_username_strip",
"auth_password",
"auth_password_strip",
"auth_private_key",
"auth_strict_key",
"timeout_socket",
"timeout_transport",
"timeout_ops",
"timeout_exit",
"keepalive",
"keepalive_interval",
"keepalive_type",
"keepalive_pattern",
"comms_prompt_pattern",
"comms_return_char",
"comms_ansi",
"on_open",
"on_close",
"transport",
],
)
def test_attr_assignment(attr_setup):
attr_name = attr_setup[0]
attr_value = attr_setup[1]
attr_expected = attr_setup[2]
args = {attr_name: attr_value}
if attr_name != "host":
args["host"] = "myhost"
conn = Scrape(**args)
if attr_name == "transport":
conn.transport_class == attr_expected
else:
assert conn._initialization_args.get(attr_name) == attr_expected
def test_valid_private_key_file():
auth_private_key = f"{UNIT_TEST_DIR}_ssh_private_key"
conn = Scrape(host="myhost", auth_private_key=auth_private_key)
assert (
conn._initialization_args["auth_private_key"] == f"{UNIT_TEST_DIR}_ssh_private_key".encode()
)
@pytest.mark.parametrize(
"ssh_file",
[
("ssh_config_file", True, "/etc/ssh/ssh_config", f"{UNIT_TEST_DIR}_ssh_config"),
(
"ssh_config_file",
True,
f"{os.path.expanduser("~")}/.ssh/config",
f"{UNIT_TEST_DIR}_ssh_config",
),
(
"ssh_config_file",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_config",
),
("ssh_config_file", "", "", "",),
(
"ssh_known_hosts_file",
True,
"/etc/ssh/ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
(
"ssh_known_hosts_file",
True,
f"{os.path.expanduser("~")}/.ssh/known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
(
"ssh_known_hosts_file",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
("ssh_known_hosts_file", "", "", "",),
],
ids=[
"config_file_etc",
"config_file_user",
"config_file_manual",
"config_file_not_found",
"known_hosts_file_etc",
"known_hosts_file_user",
"known_hosts_file_manual",
"known_hosts_file_not_found",
],
)
def test_ssh_files(fs, ssh_file):
attr_name = ssh_file[0]
attr_value = ssh_file[1]
attr_expected = ssh_file[2]
attr_src = ssh_file[3]
args = {attr_name: attr_value}
if attr_src and attr_expected:
fs.add_real_file(source_path=attr_src, target_path=attr_expected)
conn = Scrape(host="myhost", **args)
assert conn._initialization_args[attr_name] == attr_expected
def test_isalive(mocked_channel):
# mocked channel always returns true so this is not a great test
conn = mocked_channel([])
conn.open()
assert conn.isalive() is True
| import os
from pathlib import Path
import pytest
import scrapli
from scrapli import Scrape
UNIT_TEST_DIR = f"{Path(scrapli.__file__).parents[1]}/tests/unit/"
def test__str():
conn = Scrape(host="myhost")
assert str(conn) == "Scrape Object for host myhost"
def test__repr():
conn = Scrape(host="myhost")
assert (
repr(conn)
== "Scrape(host='myhost', port=22, auth_username='', auth_password='', auth_private_key=b'', "
"auth_strict_key=True, timeout_socket=5, timeout_transport=5, timeout_ops=10, timeout_exit=True, "
"keepalive=False, keepalive_interval=30, keepalive_type='network', keepalive_pattern='\\x05', "
"comms_prompt_pattern='^[a-z0-9.\\\\-@()/:]{1,32}[#>$]\\\\s*$', comms_return_char='\\n', comms_ansi=False, "
"ssh_config_file='', ssh_known_hosts_file='', on_open=None, on_close=None, transport='system')"
)
@pytest.mark.parametrize(
"attr_setup",
[
("host", "", ValueError, "`host` should be a hostname/ip address, got nothing!"),
("port", "notanint", TypeError, "`port` should be int, got <class 'str'>"),
(
"auth_strict_key",
"notabool",
TypeError,
"`auth_strict_key` should be bool, got <class 'str'>",
),
(
"auth_private_key",
"notafile",
ValueError,
"Provided public key `notafile` is not a file",
),
("timeout_exit", "notabool", TypeError, "`timeout_exit` should be bool, got <class 'str'>"),
("keepalive", "notabool", TypeError, "`keepalive` should be bool, got <class 'str'>"),
(
"keepalive_type",
"notvalid",
ValueError,
"`notvalid` is an invalid keepalive_type; must be 'network' or 'standard'",
),
(
"comms_return_char",
True,
TypeError,
"`comms_return_char` should be str, got <class 'bool'>",
),
("comms_ansi", "notabool", TypeError, "`comms_ansi` should be bool, got <class 'str'>"),
("on_open", "notacallable", TypeError, "`on_open` must be a callable, got <class 'str'>"),
("on_close", "notacallable", TypeError, "`on_close` must be a callable, got <class 'str'>"),
(
"ssh_config_file",
None,
TypeError,
"`ssh_config_file` must be str or bool, got <class 'NoneType'>",
),
(
"ssh_known_hosts_file",
None,
TypeError,
"`ssh_known_hosts_file` must be str or bool, got <class 'NoneType'>",
),
(
"transport",
"notatransport",
ValueError,
"`transport` should be one of ssh2|paramiko|system|telnet, got `notatransport`",
),
],
ids=[
"host",
"port",
"auth_strict_key",
"auth_private_key",
"timeout_exit",
"keepalive",
"keepalive_type",
"comms_return_char",
"comms_ansi",
"on_open",
"on_close",
"ssh_config_file",
"ssh_known_hosts_file",
"transport",
],
)
def test_exceptions_raised(attr_setup):
attr_name = attr_setup[0]
attr_value = attr_setup[1]
attr_exc = attr_setup[2]
attr_msg = attr_setup[3]
args = {attr_name: attr_value}
if attr_name != "host":
args["host"] = "myhost"
with pytest.raises(attr_exc) as exc:
Scrape(**args)
assert str(exc.value) == attr_msg
@pytest.mark.parametrize(
"attr_setup",
[
("host", "myhost", "myhost"),
("host", "myhost ", "myhost"),
("port", 123, 123),
("auth_username", "tacocat", "tacocat"),
("auth_username", "tacocat ", "tacocat"),
("auth_password", "tacocat", "tacocat"),
("auth_password", "tacocat ", "tacocat"),
("auth_private_key", f"{UNIT_TEST_DIR}_ssh_config", f"{UNIT_TEST_DIR}_ssh_config".encode()),
("auth_strict_key", False, False),
("timeout_socket", 100, 100),
("timeout_transport", 100, 100),
("timeout_ops", 100, 100),
("timeout_exit", False, False),
("keepalive", True, True),
("keepalive_interval", 100, 100),
("keepalive_type", "standard", "standard"),
("keepalive_pattern", "tacocat", "tacocat"),
("comms_prompt_pattern", "tacocat", "tacocat"),
("comms_return_char", "tacocat", "tacocat"),
("comms_ansi", True, True),
("on_open", print, print),
("on_close", print, print),
("transport", "ssh2", "ssh2"),
],
ids=[
"host",
"host_strip",
"port",
"auth_username",
"auth_username_strip",
"auth_password",
"auth_password_strip",
"auth_private_key",
"auth_strict_key",
"timeout_socket",
"timeout_transport",
"timeout_ops",
"timeout_exit",
"keepalive",
"keepalive_interval",
"keepalive_type",
"keepalive_pattern",
"comms_prompt_pattern",
"comms_return_char",
"comms_ansi",
"on_open",
"on_close",
"transport",
],
)
def test_attr_assignment(attr_setup):
attr_name = attr_setup[0]
attr_value = attr_setup[1]
attr_expected = attr_setup[2]
args = {attr_name: attr_value}
if attr_name != "host":
args["host"] = "myhost"
conn = Scrape(**args)
if attr_name == "transport":
conn.transport_class == attr_expected
else:
assert conn._initialization_args.get(attr_name) == attr_expected
def test_valid_private_key_file():
auth_private_key = f"{UNIT_TEST_DIR}_ssh_private_key"
conn = Scrape(host="myhost", auth_private_key=auth_private_key)
assert (
conn._initialization_args["auth_private_key"] == f"{UNIT_TEST_DIR}_ssh_private_key".encode()
)
@pytest.mark.parametrize(
"ssh_file",
[
("ssh_config_file", True, "/etc/ssh/ssh_config", f"{UNIT_TEST_DIR}_ssh_config"),
(
"ssh_config_file",
True,
f"{os.path.expanduser('~')}/.ssh/config",
f"{UNIT_TEST_DIR}_ssh_config",
),
(
"ssh_config_file",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_config",
),
("ssh_config_file", "", "", "",),
(
"ssh_known_hosts_file",
True,
"/etc/ssh/ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
(
"ssh_known_hosts_file",
True,
f"{os.path.expanduser('~')}/.ssh/known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
(
"ssh_known_hosts_file",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
f"{UNIT_TEST_DIR}_ssh_known_hosts",
),
("ssh_known_hosts_file", "", "", "",),
],
ids=[
"config_file_etc",
"config_file_user",
"config_file_manual",
"config_file_not_found",
"known_hosts_file_etc",
"known_hosts_file_user",
"known_hosts_file_manual",
"known_hosts_file_not_found",
],
)
def test_ssh_files(fs, ssh_file):
attr_name = ssh_file[0]
attr_value = ssh_file[1]
attr_expected = ssh_file[2]
attr_src = ssh_file[3]
args = {attr_name: attr_value}
if attr_src and attr_expected:
fs.add_real_file(source_path=attr_src, target_path=attr_expected)
conn = Scrape(host="myhost", **args)
assert conn._initialization_args[attr_name] == attr_expected
def test_isalive(mocked_channel):
# mocked channel always returns true so this is not a great test
conn = mocked_channel([])
conn.open()
assert conn.isalive() is True
|
#!/usr/bin/env python3
import logging
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from collections import defaultdict
from bleties.SharedFunctions import Gff, get_not_gaps
logger = logging.getLogger("Insert")
class Insert(object):
"""Insert IESs from GFF file and associated Fasta file to a reference
assembly to produce MAC+IES genome sequence"""
def __init__(self, refgenome, gff, iesfasta):
"""Initialize Insert object
Parameters
----------
refgenome : dict
dict of SeqRecord objects, keyed by sequence ID, representing the
MAC reference genome without IESs.
gff : Gff
GFF containing coordinates of IESs to be inserted into reference
iesfasta : dict
dict of SeqRecord objects, keyed by sequence ID, representing IES
sequences to be inserted into the reference MAC genome.
"""
self._refgenome = refgenome
# Make copy of refgenome to modify, otherwise original will also be
# modified
self._newgenome = {ctg: SeqRecord(Seq(str(refgenome[ctg].seq)),
id=ctg, name=refgenome[ctg].name,
description=refgenome[ctg].description)
for ctg in refgenome}
self._gff = gff
self._iesfasta = iesfasta
self._iesdict = defaultdict( # contig
lambda: defaultdict( # pos
dict)) # dict of gffid, seqlen, seq, newstart, newend
self._newgff = Gff() # Gff entries for IESs with updated coords
def _filterInserts(self):
"""Process GFF file and filter putative IESs to be inserted
If multiple inserts at the same location, choose the longer one
If sequence contains X or - characters, also reject
"""
for gffid in self._gff:
# Check for junctions only, i.e. start == end
start = self._gff.getValue(gffid, 'start')
end = self._gff.getValue(gffid, 'end')
if start == end:
ctg = self._gff.getValue(gffid, 'seqid')
if gffid in self._iesfasta:
seq = str(self._iesfasta[gffid].seq)
# reject if there are X or - characters
if 'X' in seq or '-' in seq:
logger.debug(
f"Skipping sequence {gffid} because of X and - characters")
else:
# if an insert already recorded, take the longer one
if self._iesdict[ctg][start]:
if len(seq) > self._iesdict[ctg][start]['seqlen']:
logger.debug(
f"More than one insert at location {ctg} {str(start)}, choosing the longer one {gffid}")
self._iesdict[ctg][start] = {
'seq': seq,
'seqlen': len(seq),
'gffid': gffid,
'oldstart': int(start),
'oldend': int(end) + len(seq),
'newstart': int(start),
'newend': int(end) + len(seq)
}
else:
self._iesdict[ctg][start] = {
'seq': seq,
'seqlen': len(seq),
'gffid': gffid,
'oldstart': int(start),
'oldend': int(start) + len(seq),
'newstart': int(start),
'newend': int(start) + len(seq)
}
else:
logger.warn(
f"Insert sequence ID {gffid} not in Fasta file!")
def _filterDeletions(self):
"""Process GFF file and filter putative IESs to be deleted
Overlapping regions will be skipped, only non-overlapping features
retained
Returns
-------
dict
Dict keyed by contig ID (seqid), values are lists of dicts, each
containing details on a specific deletion, with keys seqid, start
end, gffid. start and end are 0-based pythonic coordinates
"""
coords = defaultdict(list)
filtcoords = defaultdict(list)
# Get region features only
for gffid in self._gff:
# Check for junctions only, i.e. start == end
start = int(self._gff.getValue(gffid, 'start'))
end = int(self._gff.getValue(gffid, 'end'))
if start < end:
seqid = self._gff.getValue(gffid, 'seqid')
# Convert coords to 0-based python convention
coords[seqid].append(
{'seqid': seqid, 'start': start-1, 'end': end, 'gffid': gffid})
# Check for overlaps
for seqid in coords:
sortrecs = sorted(coords[seqid], key=lambda x: int(x['start']))
currend = None
for i in range(len(sortrecs)):
gffid = sortrecs[i]['gffid']
if currend:
if currend > int(sortrecs[i]['start']):
currend = max([currend, int(sortrecs[i]['end'])])
logger.debug(f"Overlapping record {gffid} skipped")
else:
currend = int(sortrecs[i]['end'])
if i < len(sortrecs) - 1:
if currend < int(sortrecs[i+1]['start']):
filtcoords[seqid].append(sortrecs[i])
else:
logger.debug(
f"Overlapping record {gffid} skipped")
else:
# Sweep up last entry
filtcoords[seqid].append(sortrecs[i])
else:
currend = int(sortrecs[i]['end'])
if i < len(sortrecs)-1:
if currend < int(sortrecs[i+1]['start']):
filtcoords[seqid].append(sortrecs[i])
else:
logger.debug(f"Overlapping record {gffid} skipped")
else:
# Sweet up last first entry
filtcoords[seqid].append(sortrecs[i])
return(filtcoords)
def _updatePositionsInserts(self):
"""After filtering inserts and recording them in iesdict, update their
coordinates after adding the sequences in
Run this after filterInserts()
"""
for ctg in self._iesdict:
sp = sorted(self._iesdict[ctg], key=lambda i: int(i))
for i in range(len(sp)):
seqlen = int(self._iesdict[ctg][sp[i]]['seqlen'])
for j in range(i, len(sp)):
gffid = self._iesdict[ctg][sp[j]]['gffid']
if j > i: # don't add if this is the same entry
# New coordinates in dict are 0-based [), python convention
self._iesdict[ctg][sp[j]]['newstart'] += seqlen
self._iesdict[ctg][sp[j]]['newend'] += seqlen
# Record new Gff entries with updated columns
# start coordinate needs to be changed to follow GFF
# convention
self._newgff.addEntry(self._gff.getEntry(gffid), gffid)
self._newgff.changeValue(gffid, 'start', self._iesdict[ctg][sp[j]]['newstart'] + 1)
self._newgff.changeValue(gffid, 'end', self._iesdict[ctg][sp[j]]['newend'])
def _updatePointerPositionsInserts(self):
"""After updating coordinates of inserts, check for IES features that
contain TA or pointer coordinates in attributes field, which may or may
not differ from the start/end position, and update these too.
Run this after _updatePositionsInserts()
"""
for ctg in self._iesdict:
for start in self._iesdict[ctg]:
gffid = self._iesdict[ctg][start]['gffid']
offset = int(self._iesdict[ctg][start]['newstart']) - int(self._iesdict[ctg][start]['oldstart'])
# print(gffid) # testing
# print(f"Offset {str(offset)}") # testing
#
# Check for TA or pointer coordinates in attributes of GFF and
# update with offset
tps = self._newgff.getAttr(gffid, 'ta_pointer_start')
pps = self._newgff.getAttr(gffid, 'pp_pointer_start')
newend = self._iesdict[ctg][start]['newend']
if tps:
# plus 1 to starts because 'newstart' and 'newend' are
# 0-based end exclusive coords, only converted to GFF
# convention in self._newgff
tps_offset = int(tps) - int(self._iesdict[ctg][start]['oldstart'])
# print(f"tps offset {str(tps_offset)}") # testing
# print(f"newstart {self._iesdict[ctg][start]["newstart"]}")
# print(f"newend {self._iesdict[ctg][start]["newend"]}")
self._newgff.changeAttr(gffid, 'ta_pointer_start', int(self._iesdict[ctg][start]['newstart']) + 1 + tps_offset)
self._newgff.changeAttr(gffid, 'ta_pointer_end', int(newend) + tps_offset)
if pps:
pps_offset = int(pps) - int(self._iesdict[ctg][start]['oldstart'])
self._newgff.changeAttr(gffid, 'pp_pointer_start', int(self._iesdict[ctg][start]['newstart']) + 1 + pps_offset)
self._newgff.changeAttr(gffid, 'pp_pointer_end', int(newend) + pps_offset)
def _updatePointerPositionsDeletions(self, dels):
"""After updating coordinates of deletions, check for IES features that
contain TA or pointer coordinates in attributes field, which may or may
not differ from the start/end position, and update these too.
Run this after _updatePositionsDeletions()
"""
for ctg in dels:
for i in dels[ctg]:
gffid = i['gffid']
offset = int(i['newpos']) - int(i['start'])
# Check for TA or pointer coordinates in attributes of GFF and
# update with offset
tps = self._newgff.getAttr(gffid, 'ta_pointer_start')
pps = self._newgff.getAttr(gffid, 'pp_pointer_start')
if tps:
# minus 1 because tps is with GFF coords and oldstart on python coords
tps_offset = int(tps) - int(i['start']) - 1
# print(f"tps_offset {str(tps_offset)}") # testing
self._newgff.changeAttr(gffid, 'ta_pointer_start', int(i['newpos']) + tps_offset)
# when IES is deleted, TA start == TA end because this is
# now a zero-length junction-type feature
self._newgff.changeAttr(gffid, 'ta_pointer_end', int(i['newpos']) + tps_offset)
if pps:
pps_offset = int(pps) - int(i['start']) - 1
self._newgff.changeAttr(gffid, 'pp_pointer_start', int(i['newpos']) + pps_offset)
self._newgff.changeAttr(gffid, 'pp_pointer_end', int(i['newpos']) + pps_offset)
def _updatePositionsDeletions(self, dels):
"""After filtering deletions and recording them, update their
coordinates in Gff object after removing the sequences from contigs
Run this after filterDeletions()
"""
for seqid in dels:
sortedrecs = sorted(dels[seqid], key=lambda x: int(x['start']))
for i in sortedrecs:
i['newpos'] = i['start']
for i in range(len(sortedrecs)):
inslen = sortedrecs[i]['end'] - sortedrecs[i]['start']
for j in range(i+1, len(sortedrecs)):
sortedrecs[j]['newpos'] = sortedrecs[j]['newpos'] - inslen
# Record new Gff entry and update coordinates
for i in sortedrecs:
self._newgff.addEntry(
self._gff.getEntry(i['gffid']), i['gffid'])
self._newgff.changeValue(i['gffid'], 'start', i['newpos'])
self._newgff.changeValue(i['gffid'], 'end', i['newpos'])
def _addSequences(self):
"""Insert IES sequences to the reference assembly
Run this after updatePositions()
"""
for ctg in self._iesdict:
sp = sorted(self._iesdict[ctg], key=lambda i: int(i))
for i in sp:
insseq = self._iesdict[ctg][i]['seq']
# Use coordinates from iesdict because these follow python
# convention
inspos = int(self._iesdict[ctg][i]['newstart'])
self._newgenome[ctg].seq = self._newgenome[ctg].seq[0:inspos] + \
insseq + self._newgenome[ctg].seq[inspos:]
def _deleteSequences(self, dels):
"""
Run this after filterDeletions()
Parameters
----------
dels : dict
Output from _filterDeletions()
"""
for seqid in dels:
gaps = [(i['start'], i['end']) for i in dels[seqid]]
end = len(self._refgenome[seqid].seq)
notgaps = get_not_gaps(0, end, gaps)
newseq = ""
for i in notgaps:
newseq += str(self._refgenome[seqid].seq[i[0]:i[1]])
self._newgenome[seqid].seq = Seq(newseq)
def reportInsertedReference(self):
"""Add IESs to reference genome, report modified MAC+IES assembly and
GFF file containing updated positions
Only IESs defined in the GFF as inserts (i.e. start == end) will be
added to the reference sequence. IES sequences containing gaps or
mismatches (- or X characters) will be skipped.
Returns
-------
dict
dict of SeqRecords representing modified reference genome
Gff
IES records with updated region coords. Only the start and end
columns are changed, and the attributes for adjusted coordinates
relative to putative pointers or TA junctions: ta_pointer_start,
ta_pointer_end, pp_pointer_start, pp_pointer_end.
All other columns are inherited from the original GFF records
"""
self._filterInserts()
self._updatePositionsInserts()
self._updatePointerPositionsInserts() # update ta_pointer... pp_pointer...
self._addSequences()
# Count difference in size
oldtotal = sum([len(self._refgenome[ctg].seq)
for ctg in self._refgenome])
newtotal = sum([len(self._newgenome[ctg].seq)
for ctg in self._newgenome])
addedlen = newtotal - oldtotal
logging.info(f"Original contigs total length: {str(oldtotal)}")
logging.info(f"Modified contigs total length: {str(newtotal)}")
logging.info(f"Total sequence length added: {str(addedlen)}")
return(self._newgenome, self._newgff)
def updateFeatureGff(self, feats, addsuffix=False):
"""Update coordinates of other annotations after filtering IES inserts
Run this after _updatePositionsInserts().This function only works with
insert mode, because in delete mode, the truncation or excision of
features with potential annotated functions must be curated manually by
the user.
Parameters
----------
feats : list
list of lists; each element represents single GFF3 line split on
tabs into columns
addsuffix : bool
Add suffix ".seg_#" to each split feature's ID?
Returns
-------
list
list of lists; each element represents single GFF3 line. Do not use
the SharedFunctions.Gff class because that implementation does not
account for multi-segment features with the same ID but split
across several lines.
"""
newgff = []
for ctg in self._iesdict:
for feat in [f for f in feats if f[0] == ctg]:
# Get ID from attributes
attrdict = {attr.strip().split('=')[0] : attr.strip().split('=')[1]
for attr in feat[8].split(';') if attr}
featid = attrdict['ID']
# add up all offsets before this feature
offset = sum([int(self._iesdict[ctg][i]['seqlen'])
for i in self._iesdict[ctg]
if int(i) < int(feat[3])])
# check if any IES inserts fall inside the feature
istart = int(feat[3])
iend = int(feat[4])
# get start positions of each IES feature that is inside
# this feature
iesinsides = [int(i) for i in self._iesdict[ctg]
if int(i) >= istart and int(i) < iend]
iesinsides = sorted(iesinsides)
insidelen = sum([int(self._iesdict[ctg][str(i)]['seqlen'])
for i in iesinsides])
# new start position
newints = [istart + offset]
# update coordinates with complement of new IES feature
# positions
for i in iesinsides: # already sorted
# the following are already in GFF-coordinates
newints.append(self._iesdict[ctg][str(i)]['newstart'])
newints.append(self._iesdict[ctg][str(i)]['newend'] + 1)
# new end position
newints.append(iend + insidelen + offset)
# split to tuples of start-end coords for non-IES complement
# ranges
newints_tuples = []
for i in range(int(len(newints)/2)):
newints_tuples.append((newints[i*2], newints[i*2 + 1]))
if len(newints_tuples) > 1:
# feature is interrupted by IESs, split into segments
for j in range(len(newints_tuples)):
newfeatid = featid
# Add suffix ".seg_#" if requested
if addsuffix:
newfeatid = featid + '.seg_' + str(j)
# Updates ID field if present, adds it if not
attrdict['ID'] = newfeatid
newattr = ';'.join([str(key) + '=' + str(attrdict[key])
for key in attrdict])
# new GFF entry as list
newfeat = feat[0:3] + \
[newints_tuples[j][0], newints_tuples[j][1]] + \
feat[5:8] + [newattr]
# add entry to new Gff object
newgff.append(newfeat)
else:
# new interval comprises only the new start and end,
# the feature is not broken up into segments
# feature ID remains the same
newfeat = feat[0:3] + \
[newints_tuples[0][0], newints_tuples[0][1]] + \
feat[5:9]
newgff.append(newfeat)
return(newgff)
def reportDeletedReference(self):
"""Remove IESs from reference MAC+IES genome, report modified MAC-IES
assembly and GFF file containing updated positions
Only IESs defined in the GFF as retentions (i.e. end > start) will be
removed from the reference sequence. IESs that overlap with each other
will be skipped: the input GFF should be manually curated to select
which region should actually be excised.
Returns
-------
dict
dict of SeqRecords representing modified reference genome
Gff
IES records with updated insert positions. Only the start and end
columns are changed, all other columns are inherited from the
original GFF records
"""
dels = self._filterDeletions()
self._updatePositionsDeletions(dels)
self._updatePointerPositionsDeletions(dels)
self._deleteSequences(dels)
# Count difference in size
oldtotal = sum([len(self._refgenome[ctg].seq)
for ctg in self._refgenome])
newtotal = sum([len(self._newgenome[ctg].seq)
for ctg in self._newgenome])
deletedlen = oldtotal - newtotal
logging.info(f"Original contigs total length: {str(oldtotal)}")
logging.info(f"Modified contigs total length: {str(newtotal)}")
logging.info(f"Total sequence length removed: {str(deletedlen)}")
return(self._newgenome, self._newgff)
| #!/usr/bin/env python3
import logging
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from collections import defaultdict
from bleties.SharedFunctions import Gff, get_not_gaps
logger = logging.getLogger("Insert")
class Insert(object):
"""Insert IESs from GFF file and associated Fasta file to a reference
assembly to produce MAC+IES genome sequence"""
def __init__(self, refgenome, gff, iesfasta):
"""Initialize Insert object
Parameters
----------
refgenome : dict
dict of SeqRecord objects, keyed by sequence ID, representing the
MAC reference genome without IESs.
gff : Gff
GFF containing coordinates of IESs to be inserted into reference
iesfasta : dict
dict of SeqRecord objects, keyed by sequence ID, representing IES
sequences to be inserted into the reference MAC genome.
"""
self._refgenome = refgenome
# Make copy of refgenome to modify, otherwise original will also be
# modified
self._newgenome = {ctg: SeqRecord(Seq(str(refgenome[ctg].seq)),
id=ctg, name=refgenome[ctg].name,
description=refgenome[ctg].description)
for ctg in refgenome}
self._gff = gff
self._iesfasta = iesfasta
self._iesdict = defaultdict( # contig
lambda: defaultdict( # pos
dict)) # dict of gffid, seqlen, seq, newstart, newend
self._newgff = Gff() # Gff entries for IESs with updated coords
def _filterInserts(self):
"""Process GFF file and filter putative IESs to be inserted
If multiple inserts at the same location, choose the longer one
If sequence contains X or - characters, also reject
"""
for gffid in self._gff:
# Check for junctions only, i.e. start == end
start = self._gff.getValue(gffid, 'start')
end = self._gff.getValue(gffid, 'end')
if start == end:
ctg = self._gff.getValue(gffid, 'seqid')
if gffid in self._iesfasta:
seq = str(self._iesfasta[gffid].seq)
# reject if there are X or - characters
if 'X' in seq or '-' in seq:
logger.debug(
f"Skipping sequence {gffid} because of X and - characters")
else:
# if an insert already recorded, take the longer one
if self._iesdict[ctg][start]:
if len(seq) > self._iesdict[ctg][start]['seqlen']:
logger.debug(
f"More than one insert at location {ctg} {str(start)}, choosing the longer one {gffid}")
self._iesdict[ctg][start] = {
'seq': seq,
'seqlen': len(seq),
'gffid': gffid,
'oldstart': int(start),
'oldend': int(end) + len(seq),
'newstart': int(start),
'newend': int(end) + len(seq)
}
else:
self._iesdict[ctg][start] = {
'seq': seq,
'seqlen': len(seq),
'gffid': gffid,
'oldstart': int(start),
'oldend': int(start) + len(seq),
'newstart': int(start),
'newend': int(start) + len(seq)
}
else:
logger.warn(
f"Insert sequence ID {gffid} not in Fasta file!")
def _filterDeletions(self):
"""Process GFF file and filter putative IESs to be deleted
Overlapping regions will be skipped, only non-overlapping features
retained
Returns
-------
dict
Dict keyed by contig ID (seqid), values are lists of dicts, each
containing details on a specific deletion, with keys seqid, start
end, gffid. start and end are 0-based pythonic coordinates
"""
coords = defaultdict(list)
filtcoords = defaultdict(list)
# Get region features only
for gffid in self._gff:
# Check for junctions only, i.e. start == end
start = int(self._gff.getValue(gffid, 'start'))
end = int(self._gff.getValue(gffid, 'end'))
if start < end:
seqid = self._gff.getValue(gffid, 'seqid')
# Convert coords to 0-based python convention
coords[seqid].append(
{'seqid': seqid, 'start': start-1, 'end': end, 'gffid': gffid})
# Check for overlaps
for seqid in coords:
sortrecs = sorted(coords[seqid], key=lambda x: int(x['start']))
currend = None
for i in range(len(sortrecs)):
gffid = sortrecs[i]['gffid']
if currend:
if currend > int(sortrecs[i]['start']):
currend = max([currend, int(sortrecs[i]['end'])])
logger.debug(f"Overlapping record {gffid} skipped")
else:
currend = int(sortrecs[i]['end'])
if i < len(sortrecs) - 1:
if currend < int(sortrecs[i+1]['start']):
filtcoords[seqid].append(sortrecs[i])
else:
logger.debug(
f"Overlapping record {gffid} skipped")
else:
# Sweep up last entry
filtcoords[seqid].append(sortrecs[i])
else:
currend = int(sortrecs[i]['end'])
if i < len(sortrecs)-1:
if currend < int(sortrecs[i+1]['start']):
filtcoords[seqid].append(sortrecs[i])
else:
logger.debug(f"Overlapping record {gffid} skipped")
else:
# Sweet up last first entry
filtcoords[seqid].append(sortrecs[i])
return(filtcoords)
def _updatePositionsInserts(self):
"""After filtering inserts and recording them in iesdict, update their
coordinates after adding the sequences in
Run this after filterInserts()
"""
for ctg in self._iesdict:
sp = sorted(self._iesdict[ctg], key=lambda i: int(i))
for i in range(len(sp)):
seqlen = int(self._iesdict[ctg][sp[i]]['seqlen'])
for j in range(i, len(sp)):
gffid = self._iesdict[ctg][sp[j]]['gffid']
if j > i: # don't add if this is the same entry
# New coordinates in dict are 0-based [), python convention
self._iesdict[ctg][sp[j]]['newstart'] += seqlen
self._iesdict[ctg][sp[j]]['newend'] += seqlen
# Record new Gff entries with updated columns
# start coordinate needs to be changed to follow GFF
# convention
self._newgff.addEntry(self._gff.getEntry(gffid), gffid)
self._newgff.changeValue(gffid, 'start', self._iesdict[ctg][sp[j]]['newstart'] + 1)
self._newgff.changeValue(gffid, 'end', self._iesdict[ctg][sp[j]]['newend'])
def _updatePointerPositionsInserts(self):
"""After updating coordinates of inserts, check for IES features that
contain TA or pointer coordinates in attributes field, which may or may
not differ from the start/end position, and update these too.
Run this after _updatePositionsInserts()
"""
for ctg in self._iesdict:
for start in self._iesdict[ctg]:
gffid = self._iesdict[ctg][start]['gffid']
offset = int(self._iesdict[ctg][start]['newstart']) - int(self._iesdict[ctg][start]['oldstart'])
# print(gffid) # testing
# print(f"Offset {str(offset)}") # testing
#
# Check for TA or pointer coordinates in attributes of GFF and
# update with offset
tps = self._newgff.getAttr(gffid, 'ta_pointer_start')
pps = self._newgff.getAttr(gffid, 'pp_pointer_start')
newend = self._iesdict[ctg][start]['newend']
if tps:
# plus 1 to starts because 'newstart' and 'newend' are
# 0-based end exclusive coords, only converted to GFF
# convention in self._newgff
tps_offset = int(tps) - int(self._iesdict[ctg][start]['oldstart'])
# print(f"tps offset {str(tps_offset)}") # testing
# print(f"newstart {self._iesdict[ctg][start]['newstart']}")
# print(f"newend {self._iesdict[ctg][start]['newend']}")
self._newgff.changeAttr(gffid, 'ta_pointer_start', int(self._iesdict[ctg][start]['newstart']) + 1 + tps_offset)
self._newgff.changeAttr(gffid, 'ta_pointer_end', int(newend) + tps_offset)
if pps:
pps_offset = int(pps) - int(self._iesdict[ctg][start]['oldstart'])
self._newgff.changeAttr(gffid, 'pp_pointer_start', int(self._iesdict[ctg][start]['newstart']) + 1 + pps_offset)
self._newgff.changeAttr(gffid, 'pp_pointer_end', int(newend) + pps_offset)
def _updatePointerPositionsDeletions(self, dels):
"""After updating coordinates of deletions, check for IES features that
contain TA or pointer coordinates in attributes field, which may or may
not differ from the start/end position, and update these too.
Run this after _updatePositionsDeletions()
"""
for ctg in dels:
for i in dels[ctg]:
gffid = i['gffid']
offset = int(i['newpos']) - int(i['start'])
# Check for TA or pointer coordinates in attributes of GFF and
# update with offset
tps = self._newgff.getAttr(gffid, 'ta_pointer_start')
pps = self._newgff.getAttr(gffid, 'pp_pointer_start')
if tps:
# minus 1 because tps is with GFF coords and oldstart on python coords
tps_offset = int(tps) - int(i['start']) - 1
# print(f"tps_offset {str(tps_offset)}") # testing
self._newgff.changeAttr(gffid, 'ta_pointer_start', int(i['newpos']) + tps_offset)
# when IES is deleted, TA start == TA end because this is
# now a zero-length junction-type feature
self._newgff.changeAttr(gffid, 'ta_pointer_end', int(i['newpos']) + tps_offset)
if pps:
pps_offset = int(pps) - int(i['start']) - 1
self._newgff.changeAttr(gffid, 'pp_pointer_start', int(i['newpos']) + pps_offset)
self._newgff.changeAttr(gffid, 'pp_pointer_end', int(i['newpos']) + pps_offset)
def _updatePositionsDeletions(self, dels):
"""After filtering deletions and recording them, update their
coordinates in Gff object after removing the sequences from contigs
Run this after filterDeletions()
"""
for seqid in dels:
sortedrecs = sorted(dels[seqid], key=lambda x: int(x['start']))
for i in sortedrecs:
i['newpos'] = i['start']
for i in range(len(sortedrecs)):
inslen = sortedrecs[i]['end'] - sortedrecs[i]['start']
for j in range(i+1, len(sortedrecs)):
sortedrecs[j]['newpos'] = sortedrecs[j]['newpos'] - inslen
# Record new Gff entry and update coordinates
for i in sortedrecs:
self._newgff.addEntry(
self._gff.getEntry(i['gffid']), i['gffid'])
self._newgff.changeValue(i['gffid'], 'start', i['newpos'])
self._newgff.changeValue(i['gffid'], 'end', i['newpos'])
def _addSequences(self):
"""Insert IES sequences to the reference assembly
Run this after updatePositions()
"""
for ctg in self._iesdict:
sp = sorted(self._iesdict[ctg], key=lambda i: int(i))
for i in sp:
insseq = self._iesdict[ctg][i]['seq']
# Use coordinates from iesdict because these follow python
# convention
inspos = int(self._iesdict[ctg][i]['newstart'])
self._newgenome[ctg].seq = self._newgenome[ctg].seq[0:inspos] + \
insseq + self._newgenome[ctg].seq[inspos:]
def _deleteSequences(self, dels):
"""
Run this after filterDeletions()
Parameters
----------
dels : dict
Output from _filterDeletions()
"""
for seqid in dels:
gaps = [(i['start'], i['end']) for i in dels[seqid]]
end = len(self._refgenome[seqid].seq)
notgaps = get_not_gaps(0, end, gaps)
newseq = ""
for i in notgaps:
newseq += str(self._refgenome[seqid].seq[i[0]:i[1]])
self._newgenome[seqid].seq = Seq(newseq)
def reportInsertedReference(self):
"""Add IESs to reference genome, report modified MAC+IES assembly and
GFF file containing updated positions
Only IESs defined in the GFF as inserts (i.e. start == end) will be
added to the reference sequence. IES sequences containing gaps or
mismatches (- or X characters) will be skipped.
Returns
-------
dict
dict of SeqRecords representing modified reference genome
Gff
IES records with updated region coords. Only the start and end
columns are changed, and the attributes for adjusted coordinates
relative to putative pointers or TA junctions: ta_pointer_start,
ta_pointer_end, pp_pointer_start, pp_pointer_end.
All other columns are inherited from the original GFF records
"""
self._filterInserts()
self._updatePositionsInserts()
self._updatePointerPositionsInserts() # update ta_pointer... pp_pointer...
self._addSequences()
# Count difference in size
oldtotal = sum([len(self._refgenome[ctg].seq)
for ctg in self._refgenome])
newtotal = sum([len(self._newgenome[ctg].seq)
for ctg in self._newgenome])
addedlen = newtotal - oldtotal
logging.info(f"Original contigs total length: {str(oldtotal)}")
logging.info(f"Modified contigs total length: {str(newtotal)}")
logging.info(f"Total sequence length added: {str(addedlen)}")
return(self._newgenome, self._newgff)
def updateFeatureGff(self, feats, addsuffix=False):
"""Update coordinates of other annotations after filtering IES inserts
Run this after _updatePositionsInserts().This function only works with
insert mode, because in delete mode, the truncation or excision of
features with potential annotated functions must be curated manually by
the user.
Parameters
----------
feats : list
list of lists; each element represents single GFF3 line split on
tabs into columns
addsuffix : bool
Add suffix ".seg_#" to each split feature's ID?
Returns
-------
list
list of lists; each element represents single GFF3 line. Do not use
the SharedFunctions.Gff class because that implementation does not
account for multi-segment features with the same ID but split
across several lines.
"""
newgff = []
for ctg in self._iesdict:
for feat in [f for f in feats if f[0] == ctg]:
# Get ID from attributes
attrdict = {attr.strip().split('=')[0] : attr.strip().split('=')[1]
for attr in feat[8].split(';') if attr}
featid = attrdict['ID']
# add up all offsets before this feature
offset = sum([int(self._iesdict[ctg][i]['seqlen'])
for i in self._iesdict[ctg]
if int(i) < int(feat[3])])
# check if any IES inserts fall inside the feature
istart = int(feat[3])
iend = int(feat[4])
# get start positions of each IES feature that is inside
# this feature
iesinsides = [int(i) for i in self._iesdict[ctg]
if int(i) >= istart and int(i) < iend]
iesinsides = sorted(iesinsides)
insidelen = sum([int(self._iesdict[ctg][str(i)]['seqlen'])
for i in iesinsides])
# new start position
newints = [istart + offset]
# update coordinates with complement of new IES feature
# positions
for i in iesinsides: # already sorted
# the following are already in GFF-coordinates
newints.append(self._iesdict[ctg][str(i)]['newstart'])
newints.append(self._iesdict[ctg][str(i)]['newend'] + 1)
# new end position
newints.append(iend + insidelen + offset)
# split to tuples of start-end coords for non-IES complement
# ranges
newints_tuples = []
for i in range(int(len(newints)/2)):
newints_tuples.append((newints[i*2], newints[i*2 + 1]))
if len(newints_tuples) > 1:
# feature is interrupted by IESs, split into segments
for j in range(len(newints_tuples)):
newfeatid = featid
# Add suffix ".seg_#" if requested
if addsuffix:
newfeatid = featid + '.seg_' + str(j)
# Updates ID field if present, adds it if not
attrdict['ID'] = newfeatid
newattr = ';'.join([str(key) + '=' + str(attrdict[key])
for key in attrdict])
# new GFF entry as list
newfeat = feat[0:3] + \
[newints_tuples[j][0], newints_tuples[j][1]] + \
feat[5:8] + [newattr]
# add entry to new Gff object
newgff.append(newfeat)
else:
# new interval comprises only the new start and end,
# the feature is not broken up into segments
# feature ID remains the same
newfeat = feat[0:3] + \
[newints_tuples[0][0], newints_tuples[0][1]] + \
feat[5:9]
newgff.append(newfeat)
return(newgff)
def reportDeletedReference(self):
"""Remove IESs from reference MAC+IES genome, report modified MAC-IES
assembly and GFF file containing updated positions
Only IESs defined in the GFF as retentions (i.e. end > start) will be
removed from the reference sequence. IESs that overlap with each other
will be skipped: the input GFF should be manually curated to select
which region should actually be excised.
Returns
-------
dict
dict of SeqRecords representing modified reference genome
Gff
IES records with updated insert positions. Only the start and end
columns are changed, all other columns are inherited from the
original GFF records
"""
dels = self._filterDeletions()
self._updatePositionsDeletions(dels)
self._updatePointerPositionsDeletions(dels)
self._deleteSequences(dels)
# Count difference in size
oldtotal = sum([len(self._refgenome[ctg].seq)
for ctg in self._refgenome])
newtotal = sum([len(self._newgenome[ctg].seq)
for ctg in self._newgenome])
deletedlen = oldtotal - newtotal
logging.info(f"Original contigs total length: {str(oldtotal)}")
logging.info(f"Modified contigs total length: {str(newtotal)}")
logging.info(f"Total sequence length removed: {str(deletedlen)}")
return(self._newgenome, self._newgff)
|
from abc import ABCMeta, abstractmethod
from datetime import datetime
from uuid import uuid4
from api.utils import all_subclasses
CTIM_DEFAULTS = {
'schema_version': '1.0.17',
}
RESOLVED_TO = 'Resolved_To'
class Mapping(metaclass=ABCMeta):
def __init__(self, observable):
self.observable = observable
@classmethod
def for_(cls, observable):
"""Return an instance of `Mapping` for the specified type."""
for subcls in all_subclasses(Mapping):
if subcls.type() == observable['type']:
return subcls(observable)
return None
@classmethod
@abstractmethod
def type(cls):
"""Return the observable type that the mapping is able to process."""
@staticmethod
@abstractmethod
def _aggregate(data):
"""Extract unique related observables and sightings count."""
@abstractmethod
def _resolved_to(self, related):
"""
Return TR resolved_to relation
depending on an observable and related types.
"""
@abstractmethod
def _description(self, *args):
"""Return description field depending on observable type."""
def _sighting(self, count, description, refer_link):
now = f'{datetime.now().isoformat(timespec='seconds')}Z'
return {
**CTIM_DEFAULTS,
'id': f'transient:sighting-{uuid4()}',
'type': 'sighting',
'source': 'SecurityTrails',
'title': 'Found in SecurityTrails',
'confidence': 'High',
'internal': False,
'count': count,
'observables': [self.observable],
'observed_time': {
'start_time': now,
'end_time': now,
},
'description': description,
'source_uri': refer_link
}
def extract_sighting(self, st_data, refer_link):
if not st_data.get('records'):
return
related, count = self._aggregate(st_data)
if related:
related = sorted(related)
description = self._description(st_data.get('type'))
sighting = self._sighting(count, description, refer_link)
sighting['relations'] = [self._resolved_to(r) for r in related]
return sighting
@staticmethod
def observable_relation(relation_type, source, related):
return {
"origin": "SecurityTrails Enrichment Module",
"relation": relation_type,
"source": source,
"related": related
}
class Domain(Mapping):
@classmethod
def type(cls):
return 'domain'
def _description(self, related_type):
related_type = f'IP{related_type[-2:]}'
return (f'{related_type} addresses that '
f'{self.observable['value']} resolves to')
@staticmethod
def _aggregate(st_data):
related = []
for r in st_data['records']:
related.extend(
v.get('ip') or v['ipv6'] for v in r['values']
)
related = set(related)
return related, len(related)
def _resolved_to(self, ip):
return self.observable_relation(
RESOLVED_TO,
source=self.observable,
related={
'value': ip,
'type': 'ipv6' if ':' in ip else 'ip'
}
)
class IP(Mapping):
@classmethod
def type(cls):
return 'ip'
def _description(self, *args):
return f'Domains that have resolved to {self.observable['value']}'
@staticmethod
def _aggregate(st_data):
related = [r['hostname'] for r in st_data['records']]
count = st_data['record_count']
return set(related), count
def _resolved_to(self, domain):
return self.observable_relation(
RESOLVED_TO,
source={'value': domain, 'type': 'domain'},
related=self.observable
)
class IPV6(IP):
@classmethod
def type(cls):
return 'ipv6'
| from abc import ABCMeta, abstractmethod
from datetime import datetime
from uuid import uuid4
from api.utils import all_subclasses
CTIM_DEFAULTS = {
'schema_version': '1.0.17',
}
RESOLVED_TO = 'Resolved_To'
class Mapping(metaclass=ABCMeta):
def __init__(self, observable):
self.observable = observable
@classmethod
def for_(cls, observable):
"""Return an instance of `Mapping` for the specified type."""
for subcls in all_subclasses(Mapping):
if subcls.type() == observable['type']:
return subcls(observable)
return None
@classmethod
@abstractmethod
def type(cls):
"""Return the observable type that the mapping is able to process."""
@staticmethod
@abstractmethod
def _aggregate(data):
"""Extract unique related observables and sightings count."""
@abstractmethod
def _resolved_to(self, related):
"""
Return TR resolved_to relation
depending on an observable and related types.
"""
@abstractmethod
def _description(self, *args):
"""Return description field depending on observable type."""
def _sighting(self, count, description, refer_link):
now = f'{datetime.now().isoformat(timespec="seconds")}Z'
return {
**CTIM_DEFAULTS,
'id': f'transient:sighting-{uuid4()}',
'type': 'sighting',
'source': 'SecurityTrails',
'title': 'Found in SecurityTrails',
'confidence': 'High',
'internal': False,
'count': count,
'observables': [self.observable],
'observed_time': {
'start_time': now,
'end_time': now,
},
'description': description,
'source_uri': refer_link
}
def extract_sighting(self, st_data, refer_link):
if not st_data.get('records'):
return
related, count = self._aggregate(st_data)
if related:
related = sorted(related)
description = self._description(st_data.get('type'))
sighting = self._sighting(count, description, refer_link)
sighting['relations'] = [self._resolved_to(r) for r in related]
return sighting
@staticmethod
def observable_relation(relation_type, source, related):
return {
"origin": "SecurityTrails Enrichment Module",
"relation": relation_type,
"source": source,
"related": related
}
class Domain(Mapping):
@classmethod
def type(cls):
return 'domain'
def _description(self, related_type):
related_type = f'IP{related_type[-2:]}'
return (f'{related_type} addresses that '
f'{self.observable["value"]} resolves to')
@staticmethod
def _aggregate(st_data):
related = []
for r in st_data['records']:
related.extend(
v.get('ip') or v['ipv6'] for v in r['values']
)
related = set(related)
return related, len(related)
def _resolved_to(self, ip):
return self.observable_relation(
RESOLVED_TO,
source=self.observable,
related={
'value': ip,
'type': 'ipv6' if ':' in ip else 'ip'
}
)
class IP(Mapping):
@classmethod
def type(cls):
return 'ip'
def _description(self, *args):
return f'Domains that have resolved to {self.observable["value"]}'
@staticmethod
def _aggregate(st_data):
related = [r['hostname'] for r in st_data['records']]
count = st_data['record_count']
return set(related), count
def _resolved_to(self, domain):
return self.observable_relation(
RESOLVED_TO,
source={'value': domain, 'type': 'domain'},
related=self.observable
)
class IPV6(IP):
@classmethod
def type(cls):
return 'ipv6'
|
import asyncio
import aiohttp
import pandas
from concurrent.futures import ThreadPoolExecutor
from fpl import FPL
from fpl.constants import API_URLS
from fpl.utils import fetch, logged_in
class FPLTransfers():
'''
'''
def __init__(self, email=None, password=None):
'''
Placeholder - the email and password will be sent to an authentication function in the future
once it is enabled.
'''
self._email = email
self._password = password
self._aio_pool = ThreadPoolExecutor(1)
self._aio_loop = asyncio.new_event_loop()
self._aio_pool.submit(asyncio.set_event_loop, self._aio_loop).result()
async def _call_api_async(self, func, login=False):
""" Calls the given FPL API function asynchronously.
Args:
func: The API function to execute.
requires_login: Whether the call requires authentication.
Returns:
The Future of the passed function.
"""
if login and self._email is None:
raise ValueError('Email is not provided, the functionality which has been called requires an email')
elif login and self._password is None:
raise ValueError('Password is not provided, the functionality which has been called requires a password')
async with aiohttp.ClientSession() as session:
fpl = FPL(session) #if self.__fpl is None else self.__fpl
if login:
await fpl.login(self._email, self._password)
return await func(fpl)
def _call_api(self, func, login=False):
""" Calls the given FPL API function synchronously.
Args:
func: The API function to execute.
Returns:
The result of the passed function.
"""
return self._aio_pool.submit(self._aio_loop.run_until_complete, self._call_api_async(func, login)).result()
def _get_team_dict(self, team_data):
'''
'''
team_dict = {}
for i, val in enumerate(team_data.iterrows()):
team_dict[team_data.loc[i+1, 'code']] = team_data.loc[i+1, 'name']
return team_dict
def _ensure_costs_work(self, money_left, it):
'''
Returns
-------
result: boolean
Returns True if the difference between actual money spent and total average money spent is
less than the tolerance defined by the exponential decay equation which reaches approximately
0 at x=15.
'''
def func(x):
return -1.35 * (0.8 ** ((1/15) + x)) + 1.05
tol = func(it)
if it == 13:
mean_money_left = 10
elif it == 14:
mean_money_left = 4.5
elif it == 15:
mean_money_left = 0.1
else:
mean_money_left = 100 - ((100 / 15) * it)
#print(money_left, mean_money_left, (mean_money_left/money_left), (1 - tol) + 1)
result = 0 < mean_money_left / money_left < (1 - tol) + 1
return result
def normalise(self, df=None):
'''
'''
max_vals = df.max()
df[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']] = \
df[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']] / \
max_vals[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']]
for i, val in enumerate(df.iterrows()):
overall = (df.loc[val[0], 'points'] * 0.2) + (df.loc[val[0], 'form'] * 0.3) + \
(df.loc[val[0], 'ppg'] * 0.15) + (df.loc[val[0], 'dreamteam'] * 0.1) + \
(df.loc[val[0], 'bps'] * 0.1) + (df.loc[val[0], 'av_difficulty'] * 0.15)
df.loc[val[0], 'overall'] = overall
return df
def _get_players(self, no_weeks):
'''
'''
json_data = self._call_api(lambda fpl: fpl.get_players(include_summary=True, return_json=True))
teams_data = self._call_api(lambda fpl: fpl.get_teams(return_json=True))
# Creates pandas dataframe from player attributes and cuts to only include required columns
data = pandas.DataFrame.from_records(json_data, index=['id'])
data = data[['first_name', 'second_name', 'element_type', 'team_code',
'total_points', 'form', 'points_per_game', 'dreamteam_count',
'now_cost', 'chance_of_playing_next_round', 'bps',
'selected_by_percent']]
self.original_attributes = list(data.columns)
new_cols = ['first_name', 'second_name', 'pos', 'team', 'points', 'form', 'ppg', 'dreamteam',
'cost', 'chance', 'bps', '%']
data.columns = new_cols
# Get all the future fixtures for players and sorts by player and "event"
fixtures_df = pandas.DataFrame()
for player in json_data:
player_df = pandas.DataFrame.from_records(player['fixtures'])
player_df['player_id'] = player['id']
fixtures_df = pandas.concat([fixtures_df, player_df], sort=False)
fixtures_df = fixtures_df.set_index(['player_id', 'event'])
# Creates teams pandas dataframe and finds the conversion for team IDs and their names
teams = pandas.DataFrame.from_records(teams_data, index=['id'])
team_dict = self._get_team_dict(teams)
# Changes team code to team name and puts in average difficulty for the next selected number of weeks
cur_week = fixtures_df.loc[1].index[0]
for i, val in enumerate(data.iterrows()):
data.loc[val[0], 'team'] = team_dict[data.loc[val[0], 'team']]
# Is there a better way to do this nested try except bracket?
try:
fixtures = fixtures_df.loc[val[0]][cur_week:cur_week+no_weeks]['difficulty']
except KeyError:
try:
fixtures = fixtures_df.loc[val[0]][cur_week:cur_week+no_weeks-1]['difficulty']
except KeyError:
try:
fixtures = fixtures_df.loc[val[0]][cur_week+1:cur_week+no_weeks]['difficulty']
except KeyError:
av_difficulty = 0
av_difficulty = 5 - (sum(fixtures) / (len(fixtures)))
data.loc[val[0], 'av_difficulty'] = av_difficulty
# This implementation is ugly and hard coded. Find a way to improve it if you can
data[['pos']] = data[['pos']].astype(str)
data[['points', 'dreamteam']] = data[['points', 'dreamteam']].astype(int)
data[['form', 'ppg', 'cost', 'bps', '%']] = data[['form', 'ppg', 'cost',
'bps', '%']].astype(float)
data['chance'] = data['chance'].fillna(100)
data[['cost']] = data[['cost']] / 10
self.data = data
def _get_user_team(self):
'''
'''
async def get_user_team_async(self, fpl=FPL, user_id=None):
response = await fetch(
self.session, API_URLS["user_team"].format(user_id))
return response
json_data = self._call_api(lambda fpl: fpl.get_user(return_json=True), login=True)
self._user_id = json_data['id']
self._bank = json_data['last_deadline_bank'] / 10
team = self._call_api(lambda fpl: get_user_team_async(fpl, user_id=self._user_id), login=True)
current_team = pandas.DataFrame.from_records(team['picks'], index=['element'])
return current_team
def _transfer_finder(self, cur_team, all_players):
'''
'''
idx = cur_team.index
pos = ['1', '2', '3', '4']
full_set = []
for i in pos:
pos_team = cur_team.loc[cur_team['pos'] == i]
player = pos_team.iloc[-1]
for j, val in all_players.loc[all_players['pos'] == i].iterrows():
if j not in idx and val.cost < (player.cost + self._bank) and player.overall < val.overall and val.chance > 51:
temp = {'existing player': player.first_name + ' ' + player.second_name,
'new player': val.first_name + ' ' + val.second_name,
'diff': val.overall - player.overall,
'ex_pl_id': player.name,
'n_pl_id': j}
full_set.append(temp)
break
return full_set
def single_transfer(self, no_weeks=5):
'''
Finds the best transfer to do based on the following methodology:
- Finds the lowest ranked player by position (based on "overall" metric)
- Finds the player with the highest "overall" rank in that position that is within cost
- Finds the difference in "overall" rank between existing player and new player
- Recommends the transfer with the highest difference
'''
user_team = self._get_user_team()
self._get_players(no_weeks=no_weeks)
data = self.normalise(df=self.data)
cur_team = data.loc[user_team.index].sort_values('overall', ascending=False)
data = data.sort_values('overall', ascending=False)
self.current_team = cur_team
full_set = self._transfer_finder(cur_team, data)
try:
diff_val = max([i['diff'] for i in full_set])
idx= [i['diff'] for i in full_set].index(diff_val)
print(f"Replace {full_set[idx]["existing player"]} with {full_set[idx]["new player"]}")
except ValueError:
print('No transfers to do this week')
def double_transfer(self, no_weeks=5):
'''
- Check first to see if any players are "chance" < 51 and find highest differential for those players.
- Otherwise do same as single transfer for first player.
- Remove first player transfer from current team and replacement from data
- Perform the same operation again
'''
user_team = self._get_user_team()
self._get_players(no_weeks=no_weeks)
data = self.normalise(df=self.data)
cur_team = data.loc[user_team.index].sort_values('overall', ascending=False)
data = data.sort_values('overall', ascending=False)
self.current_team = cur_team
# Run the _transfer_finder code twice, removing found player each time.
for i in range(2):
full_set = self._transfer_finder(cur_team, data)
try:
diff_val = max([i['diff'] for i in full_set])
idx = [i['diff'] for i in full_set].index(diff_val)
print(f"Replace {full_set[idx]["existing player"]} with {full_set[idx]["new player"]}")
data = data.drop(index=full_set[idx]['n_pl_id'])
cur_team = cur_team.drop(index=full_set[idx]['ex_pl_id'])
except ValueError:
print('No transfers to do this week')
def wildcard(self, no_weeks=5):
'''
Finds the best team to create using a wildcard based on the following methodology:
- Filters player list by those with >51% chance of playing next round and sorts by "overall" column
- Iterates through the list fifteen times to fill squad
- Checks the player is in a position which still needs to be filled and hasn't already been picked
- Checks whether the selected player is within a tolerance price
- If the player is within the tolerance price, moves on to find the next place in the squad
- If not, moves to the next player in the list to see if they fulfill all the criteria
'''
self._get_players(no_weeks)
data = self.data
data = self.normalise(df=data)
element_type = {'1': 2, '2': 5, '3': 5, '4': 3}
player_list = []
# This implementation is also messy - I have filtered both lists for players likely to play
# and sorted but "overall" rank. Need to figure out a way to do this without creating a separate list
eval_data = data.loc[data['chance'] > 51]
eval_data = eval_data.sort_values(by='overall', ascending=False).reset_index(drop=True)
data = data.loc[data['chance'] > 51]
data = data.sort_values(by='overall', ascending=False).reset_index(drop=True)
for i in range(16):
for j, val in enumerate(data.iterrows()):
if element_type[val[1]['pos']] >= 1 and not val[0] in player_list:
player_list.append(val[0])
players_temp = data.iloc[player_list]
try:
money_left = 100 - sum(players_temp['cost'])
except (AttributeError, NameError) as e:
money_left = 100
result = self._ensure_costs_work(money_left, i)
if result == True:
element_type[val[1]['pos']] -= 1
eval_data = eval_data.drop(val[0])
break
else:
player_list = player_list[:-1]
return data.iloc[player_list]
| import asyncio
import aiohttp
import pandas
from concurrent.futures import ThreadPoolExecutor
from fpl import FPL
from fpl.constants import API_URLS
from fpl.utils import fetch, logged_in
class FPLTransfers():
'''
'''
def __init__(self, email=None, password=None):
'''
Placeholder - the email and password will be sent to an authentication function in the future
once it is enabled.
'''
self._email = email
self._password = password
self._aio_pool = ThreadPoolExecutor(1)
self._aio_loop = asyncio.new_event_loop()
self._aio_pool.submit(asyncio.set_event_loop, self._aio_loop).result()
async def _call_api_async(self, func, login=False):
""" Calls the given FPL API function asynchronously.
Args:
func: The API function to execute.
requires_login: Whether the call requires authentication.
Returns:
The Future of the passed function.
"""
if login and self._email is None:
raise ValueError('Email is not provided, the functionality which has been called requires an email')
elif login and self._password is None:
raise ValueError('Password is not provided, the functionality which has been called requires a password')
async with aiohttp.ClientSession() as session:
fpl = FPL(session) #if self.__fpl is None else self.__fpl
if login:
await fpl.login(self._email, self._password)
return await func(fpl)
def _call_api(self, func, login=False):
""" Calls the given FPL API function synchronously.
Args:
func: The API function to execute.
Returns:
The result of the passed function.
"""
return self._aio_pool.submit(self._aio_loop.run_until_complete, self._call_api_async(func, login)).result()
def _get_team_dict(self, team_data):
'''
'''
team_dict = {}
for i, val in enumerate(team_data.iterrows()):
team_dict[team_data.loc[i+1, 'code']] = team_data.loc[i+1, 'name']
return team_dict
def _ensure_costs_work(self, money_left, it):
'''
Returns
-------
result: boolean
Returns True if the difference between actual money spent and total average money spent is
less than the tolerance defined by the exponential decay equation which reaches approximately
0 at x=15.
'''
def func(x):
return -1.35 * (0.8 ** ((1/15) + x)) + 1.05
tol = func(it)
if it == 13:
mean_money_left = 10
elif it == 14:
mean_money_left = 4.5
elif it == 15:
mean_money_left = 0.1
else:
mean_money_left = 100 - ((100 / 15) * it)
#print(money_left, mean_money_left, (mean_money_left/money_left), (1 - tol) + 1)
result = 0 < mean_money_left / money_left < (1 - tol) + 1
return result
def normalise(self, df=None):
'''
'''
max_vals = df.max()
df[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']] = \
df[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']] / \
max_vals[['points', 'dreamteam', 'bps', 'form', 'ppg', 'av_difficulty']]
for i, val in enumerate(df.iterrows()):
overall = (df.loc[val[0], 'points'] * 0.2) + (df.loc[val[0], 'form'] * 0.3) + \
(df.loc[val[0], 'ppg'] * 0.15) + (df.loc[val[0], 'dreamteam'] * 0.1) + \
(df.loc[val[0], 'bps'] * 0.1) + (df.loc[val[0], 'av_difficulty'] * 0.15)
df.loc[val[0], 'overall'] = overall
return df
def _get_players(self, no_weeks):
'''
'''
json_data = self._call_api(lambda fpl: fpl.get_players(include_summary=True, return_json=True))
teams_data = self._call_api(lambda fpl: fpl.get_teams(return_json=True))
# Creates pandas dataframe from player attributes and cuts to only include required columns
data = pandas.DataFrame.from_records(json_data, index=['id'])
data = data[['first_name', 'second_name', 'element_type', 'team_code',
'total_points', 'form', 'points_per_game', 'dreamteam_count',
'now_cost', 'chance_of_playing_next_round', 'bps',
'selected_by_percent']]
self.original_attributes = list(data.columns)
new_cols = ['first_name', 'second_name', 'pos', 'team', 'points', 'form', 'ppg', 'dreamteam',
'cost', 'chance', 'bps', '%']
data.columns = new_cols
# Get all the future fixtures for players and sorts by player and "event"
fixtures_df = pandas.DataFrame()
for player in json_data:
player_df = pandas.DataFrame.from_records(player['fixtures'])
player_df['player_id'] = player['id']
fixtures_df = pandas.concat([fixtures_df, player_df], sort=False)
fixtures_df = fixtures_df.set_index(['player_id', 'event'])
# Creates teams pandas dataframe and finds the conversion for team IDs and their names
teams = pandas.DataFrame.from_records(teams_data, index=['id'])
team_dict = self._get_team_dict(teams)
# Changes team code to team name and puts in average difficulty for the next selected number of weeks
cur_week = fixtures_df.loc[1].index[0]
for i, val in enumerate(data.iterrows()):
data.loc[val[0], 'team'] = team_dict[data.loc[val[0], 'team']]
# Is there a better way to do this nested try except bracket?
try:
fixtures = fixtures_df.loc[val[0]][cur_week:cur_week+no_weeks]['difficulty']
except KeyError:
try:
fixtures = fixtures_df.loc[val[0]][cur_week:cur_week+no_weeks-1]['difficulty']
except KeyError:
try:
fixtures = fixtures_df.loc[val[0]][cur_week+1:cur_week+no_weeks]['difficulty']
except KeyError:
av_difficulty = 0
av_difficulty = 5 - (sum(fixtures) / (len(fixtures)))
data.loc[val[0], 'av_difficulty'] = av_difficulty
# This implementation is ugly and hard coded. Find a way to improve it if you can
data[['pos']] = data[['pos']].astype(str)
data[['points', 'dreamteam']] = data[['points', 'dreamteam']].astype(int)
data[['form', 'ppg', 'cost', 'bps', '%']] = data[['form', 'ppg', 'cost',
'bps', '%']].astype(float)
data['chance'] = data['chance'].fillna(100)
data[['cost']] = data[['cost']] / 10
self.data = data
def _get_user_team(self):
'''
'''
async def get_user_team_async(self, fpl=FPL, user_id=None):
response = await fetch(
self.session, API_URLS["user_team"].format(user_id))
return response
json_data = self._call_api(lambda fpl: fpl.get_user(return_json=True), login=True)
self._user_id = json_data['id']
self._bank = json_data['last_deadline_bank'] / 10
team = self._call_api(lambda fpl: get_user_team_async(fpl, user_id=self._user_id), login=True)
current_team = pandas.DataFrame.from_records(team['picks'], index=['element'])
return current_team
def _transfer_finder(self, cur_team, all_players):
'''
'''
idx = cur_team.index
pos = ['1', '2', '3', '4']
full_set = []
for i in pos:
pos_team = cur_team.loc[cur_team['pos'] == i]
player = pos_team.iloc[-1]
for j, val in all_players.loc[all_players['pos'] == i].iterrows():
if j not in idx and val.cost < (player.cost + self._bank) and player.overall < val.overall and val.chance > 51:
temp = {'existing player': player.first_name + ' ' + player.second_name,
'new player': val.first_name + ' ' + val.second_name,
'diff': val.overall - player.overall,
'ex_pl_id': player.name,
'n_pl_id': j}
full_set.append(temp)
break
return full_set
def single_transfer(self, no_weeks=5):
'''
Finds the best transfer to do based on the following methodology:
- Finds the lowest ranked player by position (based on "overall" metric)
- Finds the player with the highest "overall" rank in that position that is within cost
- Finds the difference in "overall" rank between existing player and new player
- Recommends the transfer with the highest difference
'''
user_team = self._get_user_team()
self._get_players(no_weeks=no_weeks)
data = self.normalise(df=self.data)
cur_team = data.loc[user_team.index].sort_values('overall', ascending=False)
data = data.sort_values('overall', ascending=False)
self.current_team = cur_team
full_set = self._transfer_finder(cur_team, data)
try:
diff_val = max([i['diff'] for i in full_set])
idx= [i['diff'] for i in full_set].index(diff_val)
print(f"Replace {full_set[idx]['existing player']} with {full_set[idx]['new player']}")
except ValueError:
print('No transfers to do this week')
def double_transfer(self, no_weeks=5):
'''
- Check first to see if any players are "chance" < 51 and find highest differential for those players.
- Otherwise do same as single transfer for first player.
- Remove first player transfer from current team and replacement from data
- Perform the same operation again
'''
user_team = self._get_user_team()
self._get_players(no_weeks=no_weeks)
data = self.normalise(df=self.data)
cur_team = data.loc[user_team.index].sort_values('overall', ascending=False)
data = data.sort_values('overall', ascending=False)
self.current_team = cur_team
# Run the _transfer_finder code twice, removing found player each time.
for i in range(2):
full_set = self._transfer_finder(cur_team, data)
try:
diff_val = max([i['diff'] for i in full_set])
idx = [i['diff'] for i in full_set].index(diff_val)
print(f"Replace {full_set[idx]['existing player']} with {full_set[idx]['new player']}")
data = data.drop(index=full_set[idx]['n_pl_id'])
cur_team = cur_team.drop(index=full_set[idx]['ex_pl_id'])
except ValueError:
print('No transfers to do this week')
def wildcard(self, no_weeks=5):
'''
Finds the best team to create using a wildcard based on the following methodology:
- Filters player list by those with >51% chance of playing next round and sorts by "overall" column
- Iterates through the list fifteen times to fill squad
- Checks the player is in a position which still needs to be filled and hasn't already been picked
- Checks whether the selected player is within a tolerance price
- If the player is within the tolerance price, moves on to find the next place in the squad
- If not, moves to the next player in the list to see if they fulfill all the criteria
'''
self._get_players(no_weeks)
data = self.data
data = self.normalise(df=data)
element_type = {'1': 2, '2': 5, '3': 5, '4': 3}
player_list = []
# This implementation is also messy - I have filtered both lists for players likely to play
# and sorted but "overall" rank. Need to figure out a way to do this without creating a separate list
eval_data = data.loc[data['chance'] > 51]
eval_data = eval_data.sort_values(by='overall', ascending=False).reset_index(drop=True)
data = data.loc[data['chance'] > 51]
data = data.sort_values(by='overall', ascending=False).reset_index(drop=True)
for i in range(16):
for j, val in enumerate(data.iterrows()):
if element_type[val[1]['pos']] >= 1 and not val[0] in player_list:
player_list.append(val[0])
players_temp = data.iloc[player_list]
try:
money_left = 100 - sum(players_temp['cost'])
except (AttributeError, NameError) as e:
money_left = 100
result = self._ensure_costs_work(money_left, i)
if result == True:
element_type[val[1]['pos']] -= 1
eval_data = eval_data.drop(val[0])
break
else:
player_list = player_list[:-1]
return data.iloc[player_list]
|
import asyncio
import json
import os
import time
import warnings
import wave
from queue import Queue
from typing import Callable
import numpy as np
import pvporcupine
import sounddevice as sd
import vosk
from fluxhelper import osInterface
from speech_recognition import AudioFile, Recognizer, UnknownValueError
from tensorflow.keras.models import load_model
from vosk import SetLogLevel
RATE = 16000
DURATION = 0.5
CHANNELS = 1
CHUNK = 512
MAX_FREQ = 18
# Disable logging
warnings.filterwarnings("ignore")
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
SetLogLevel(-1)
class VAD:
"""
Main Voice activity detection class.
This uses deep learning to predict whether a piece of audio is considered a speech or not a speech.
Parameters
----------
`modelPath` : str
path to the model.h5 file.
`sensitivity : float
how sensitive the detection is.
Methods
-------
`isSpeech(stream: bytes)` :
returns True if the classified stream is a voice and False if not.
"""
def __init__(self, modelPath: str, sensitivity: float = 0.90):
self.model = load_model(modelPath)
self.buffer = []
self.sensitivity = sensitivity
async def _formatPredictions(self, predictions) -> list:
"""
Format the predictions into a more readable and easy to traverse format.
"""
predictions = [[i, float(r)] for i, r in enumerate(predictions)]
predictions.sort(key=lambda x: x[1], reverse=True)
return predictions
async def isSpeech(self, stream: bytes) -> bool:
"""
Makes a prediction from the given stream bytes.
Parameters
----------
`stream` : bytes
raw bytes stream (usually retrieved from pyaudio's .read function or sounddevice)
Returns True if the classified stream is a voice and False if not.
"""
# Convert the raw streams into a numpy array and get the decibels
arr = np.frombuffer(stream, dtype=np.int16)
db = 20 * np.log10(np.abs(np.fft.rfft(arr[:2048])))
# Collect decibel values from relevent frequencies (MAX_FREQ)
features = list(np.round(db[3:MAX_FREQ], 2))
self.buffer.append(features)
if len(self.buffer) == int(RATE / CHUNK * DURATION):
total = np.array([x for y in self.buffer for x in y])
self.buffer.clear()
# Make the prediction
predictions = self.model(np.array([total]))[0]
predictions = await self._formatPredictions(predictions)
index, probability = predictions[0]
if index == 1 and probability >= self.sensitivity:
# 1 is the index of speech and 0 is non speech
return True
return False
class SpeechRecognizer:
def __init__(
self,
wakewords: list,
wakewordSensitivities: list,
vadPath: str,
vadThreshold: float,
voskPath: str,
savePath: str,
callback: Callable,
loop: asyncio.BaseEventLoop,
offline: bool = False,
device: int = None,
**kwargs,
) -> None:
# Class parameters
self.wakewords = wakewords
self.offline = offline
self.savePath = savePath
self.voskPath = voskPath
self.device = device
self.loop = loop
self.sensitivities = wakewordSensitivities
self._callback = callback
# Class kwarg parameters
self.speechLengths = kwargs.get("speechLengths", (6.0, 0.9))
self.speechLengthMultiplier = kwargs.get("speechLengthMultiplier", 0.15)
self.beforeWokeBufferLimit = kwargs.get("beforeWokeBufferLimit", 200)
self.googleRecognizerKey = kwargs.get("googleRecognizerKey", None)
self.disableVosk = kwargs.get("disableVosk", False)
# Empty string convert to None
if self.googleRecognizerKey == "":
self.googleRecognizerKey = None
# Initialize vosk recognizer
if not self.disableVosk:
self.voskModel = vosk.Model(self.voskPath)
self.vosk = None
self.restartVosk()
# Initialize speechrecognition module
self.srRecognizer = Recognizer()
# Initialize other libraries
w = [x for x in self.wakewords if x in pvporcupine.KEYWORDS]
self.porcupine = None
if w:
self.porcupine = pvporcupine.create(
keywords=w, sensitivities=self.sensitivities
)
self.vad = VAD(vadPath, vadThreshold)
self.done = False
self.listen = True
self.woke = False
self._speechLength = self.speechLengths[0]
self._frames = {"beforeWoke": [], "afterWoke": []}
self._followup = False
self._q = Queue()
self._ready = False
self._speech = True
self._startSpeechLength = self.speechLengths[0]
self._realSpeechLength = self.speechLengths[1]
self._lastRecognizedTime = time.time()
self.__count = 0
self.__prevSpeaking = None
self.__length = 0
# User callback parameters
self.callbackParams = {}
def __callback(self, data, frames, time_, status) -> None:
self._q.put(bytes(data))
def _reset(self) -> None:
self._frames = {"beforeWoke": [], "afterWoke": []}
if not self.disableVosk:
self.vosk.FinalResult()
self.woke = False
self._speech = True
self._lastRecognizedTime = time.time()
self.__count = 0
self.__prevSpeaking = None
self.__length = 0
self._speechLength = self.speechLengths[0]
def multiplySpeechLength(self, multiplier: float) -> float:
"""
Dynamically update the speech length by multiplying it by a certain value.
"""
self._realSpeechLength = self.speechLengths[1] * multiplier
return self._realSpeechLength
def recognizeDone(self) -> None:
"""
Tells the recognizer that we are done recognizing.
"""
self._speech = False
def restartVosk(self) -> None:
"""
Restart just the Vosk recognizer.
"""
if not self.disableVosk:
self.vosk = vosk.KaldiRecognizer(self.voskModel, RATE)
async def recognize(self) -> dict:
if not self._speech:
if self.offline:
if not self.disableVosk:
text = json.loads(self.vosk.FinalResult())["text"]
return {"status": "recognized", "msg": text}
return {"status": "error", "msg": f"both disableVosk and offline is True. Can't recognize with nothing to recognize with.", "exception": None}
frames = self._frames["beforeWoke"][-10:] + self._frames["afterWoke"]
# First save the data gathered into a .wav file
wf = wave.open(self.savePath, "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
# Convert it into a AudioData object
try:
with AudioFile(self.savePath) as src:
audio = self.srRecognizer.record(src)
except Exception as e:
return {
"status": "error",
"msg": f"Failed to convert cache file to AudioData. ({e})",
"exception": e
}
# Finally attempt to recognize using google's recognizer from speechrecognition module
try:
content = self.srRecognizer.recognize_google(
audio, key=self.googleRecognizerKey
)
callback = {"status": "recognized", "msg": content}
except UnknownValueError:
callback = {"status": "unknown", "msg": "Unknown value."}
except Exception as e:
callback = {
"status": "error",
"msg": f"Failed to recognize audio. ({e})",
"exception": e
}
finally:
return callback
return {"status": "listening", "msg": "Appending frames."}
async def callback(self, *args, **kwargs) -> None:
await self._callback(*args, **kwargs, **self.callbackParams)
async def wakeUp(
self, followup: bool = False, emitCallback: bool = True, **kwargs
) -> None:
"""
Wake up the speech recognizer,
Parameters
----------
`followup` : bool
"""
self.woke = True
self._followup = followup
self.__prevSpeaking = time.time()
self.callbackParams = {"followup": followup, **kwargs}
if emitCallback:
await self.callback({"status": "woke", "msg": "woke"})
async def start(self, blocking: bool = False) -> None:
"""
Start the speech recognizer.
Parameters
----------
`blocking` : bool
if True, speech recognizer will block the program.
"""
if blocking:
return await self._start()
def f():
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(self._start())
osInterface.thread(f)
while not self._ready:
await asyncio.sleep(0.05)
async def wokeListen(self, data) -> bool:
"""
Starts listening for the provided wake words both using pvporcupine and vosk.
Vosk will not be used if self.disableVosk is True
"""
if not self.disableVosk:
# Get vosk information
self.vosk.AcceptWaveform(data)
partial = json.loads(self.vosk.PartialResult())
else:
partial = {"partial": ""}
# Get pvporcupine wake word information
p = -1
if self.porcupine:
p = self.porcupine.process(np.frombuffer(data, dtype=np.int16))
# Check if a wake word is recognized using both vosk and porcupine if porcupine is successfully initialized
if any(k in partial["partial"] for k in self.wakewords) or p >= 0:
if not self.disableVosk:
self.vosk.FinalResult()
return True
# Constantly collect before wake word frames
if len(self._frames["beforeWoke"]) > self.beforeWokeBufferLimit:
self._frames["beforeWoke"].pop(0)
self._frames["beforeWoke"].append(data)
if not self.disableVosk:
# Prevent active listening from getting way too big, will cause a memory leak if not implemented
if len(partial["partial"].split()) > 25:
self.vosk.FinalResult()
self.restartVosk()
vad = await self.vad.isSpeech(data)
if vad:
self.__prevSpeaking = time.time()
if not self.__prevSpeaking:
self.__prevSpeaking = time.time()
length = time.time() - self.__prevSpeaking
if length > 20.0:
if not self.disableVosk:
self.vosk.FinalResult()
self.restartVosk()
self.__prevSpeaking = time.time()
# Emit what the vosk recognizer is currently hearing
await self.callback(
{"status": "activeListeningPartial", "msg": partial["partial"]}
)
return False
async def _start(self) -> None:
with sd.RawInputStream(
samplerate=RATE,
blocksize=CHUNK,
device=self.device,
dtype="int16",
channels=CHANNELS,
callback=self.__callback,
):
self._ready = True
while not self.done:
data = self._q.get()
if self.listen:
# Wait for one of the wake words to be triggered
if not self.woke:
# There seems to be a bug wherein woke becomes True right after the speech is recognized, so we do a time check to prevent that. (pls fix) FIXME
woke = await self.wokeListen(data)
if (time.time() - self._lastRecognizedTime) < 1.8:
woke = False
# Now wake up the processor/recognizer
if woke and not self.woke:
await self.wakeUp()
if self.woke:
partial = None
if not self.disableVosk:
# Give vosk the speech data
self.vosk.AcceptWaveform(data)
# Realtime Partial data
partial = list(json.loads(self.vosk.PartialResult()).items())[
0
][1].strip()
if partial:
await self.callback(
{"status": "recognizedPartial", "msg": partial}
)
# Perform voice activity detection
vad = await self.vad.isSpeech(data)
if vad:
self.__count += 1
self.__prevSpeaking = time.time()
await self.callback(
{"status": "voiceActivity", "msg": "voiceActivity"}
)
# Perform previous voice activity checking.
if self.__prevSpeaking:
self.__length = time.time() - self.__prevSpeaking
comparator = self.__count == 0 or not partial
if self.disableVosk:
comparator = self.__count == 0
if comparator:
self._speechLength = self._startSpeechLength
else:
self._speechLength = self._realSpeechLength
# Current speech length has exceeded the provided speech length meaning we're done listening.
if self.__length > self._speechLength:
self.recognizeDone()
self._frames["afterWoke"].append(data)
recognized = await self.recognize()
await self.callback(recognized)
# Finally reset all the variables back to their default so that it can be ready for the next time the listener gets woke.
if not self._speech:
self._reset()
async def callback(data, *args, **kwargs) -> None:
status = data.get("status", "listening")
if status == "recognizedPartial":
print(f"> {data["msg"]} {recognizer._realSpeechLength}", end="\r")
if data["msg"].startswith("turn the lights off"):
recognizer.recognizeDone()
if data["msg"].endswith(("to", "two", "of", "and", "for")):
recognizer.multiplySpeechLength(2.8)
else:
recognizer.multiplySpeechLength(1)
if status == "recognized":
print(f"You: {data["msg"]}")
if status == "woke":
print(f"\nI'm listening...")
if status == "activeListeningPartial":
print(f"Active: {data["msg"]}", end="\r")
async def main(loop: asyncio.BaseEventLoop) -> None:
global recognizer
recognizer = SpeechRecognizer(
["jarvis"],
[1.0],
osInterface.joinPath("models/vad.h5"),
0.9,
osInterface.joinPath("models/vosk"),
osInterface.joinPath(".tmp/cache.wav"),
callback,
loop,
speechLengths=(5.0, 1.2),
offline=False,
disableVosk=True
)
await recognizer.start(blocking=True)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main(loop))
except KeyboardInterrupt:
loop.stop()
| import asyncio
import json
import os
import time
import warnings
import wave
from queue import Queue
from typing import Callable
import numpy as np
import pvporcupine
import sounddevice as sd
import vosk
from fluxhelper import osInterface
from speech_recognition import AudioFile, Recognizer, UnknownValueError
from tensorflow.keras.models import load_model
from vosk import SetLogLevel
RATE = 16000
DURATION = 0.5
CHANNELS = 1
CHUNK = 512
MAX_FREQ = 18
# Disable logging
warnings.filterwarnings("ignore")
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
SetLogLevel(-1)
class VAD:
"""
Main Voice activity detection class.
This uses deep learning to predict whether a piece of audio is considered a speech or not a speech.
Parameters
----------
`modelPath` : str
path to the model.h5 file.
`sensitivity : float
how sensitive the detection is.
Methods
-------
`isSpeech(stream: bytes)` :
returns True if the classified stream is a voice and False if not.
"""
def __init__(self, modelPath: str, sensitivity: float = 0.90):
self.model = load_model(modelPath)
self.buffer = []
self.sensitivity = sensitivity
async def _formatPredictions(self, predictions) -> list:
"""
Format the predictions into a more readable and easy to traverse format.
"""
predictions = [[i, float(r)] for i, r in enumerate(predictions)]
predictions.sort(key=lambda x: x[1], reverse=True)
return predictions
async def isSpeech(self, stream: bytes) -> bool:
"""
Makes a prediction from the given stream bytes.
Parameters
----------
`stream` : bytes
raw bytes stream (usually retrieved from pyaudio's .read function or sounddevice)
Returns True if the classified stream is a voice and False if not.
"""
# Convert the raw streams into a numpy array and get the decibels
arr = np.frombuffer(stream, dtype=np.int16)
db = 20 * np.log10(np.abs(np.fft.rfft(arr[:2048])))
# Collect decibel values from relevent frequencies (MAX_FREQ)
features = list(np.round(db[3:MAX_FREQ], 2))
self.buffer.append(features)
if len(self.buffer) == int(RATE / CHUNK * DURATION):
total = np.array([x for y in self.buffer for x in y])
self.buffer.clear()
# Make the prediction
predictions = self.model(np.array([total]))[0]
predictions = await self._formatPredictions(predictions)
index, probability = predictions[0]
if index == 1 and probability >= self.sensitivity:
# 1 is the index of speech and 0 is non speech
return True
return False
class SpeechRecognizer:
def __init__(
self,
wakewords: list,
wakewordSensitivities: list,
vadPath: str,
vadThreshold: float,
voskPath: str,
savePath: str,
callback: Callable,
loop: asyncio.BaseEventLoop,
offline: bool = False,
device: int = None,
**kwargs,
) -> None:
# Class parameters
self.wakewords = wakewords
self.offline = offline
self.savePath = savePath
self.voskPath = voskPath
self.device = device
self.loop = loop
self.sensitivities = wakewordSensitivities
self._callback = callback
# Class kwarg parameters
self.speechLengths = kwargs.get("speechLengths", (6.0, 0.9))
self.speechLengthMultiplier = kwargs.get("speechLengthMultiplier", 0.15)
self.beforeWokeBufferLimit = kwargs.get("beforeWokeBufferLimit", 200)
self.googleRecognizerKey = kwargs.get("googleRecognizerKey", None)
self.disableVosk = kwargs.get("disableVosk", False)
# Empty string convert to None
if self.googleRecognizerKey == "":
self.googleRecognizerKey = None
# Initialize vosk recognizer
if not self.disableVosk:
self.voskModel = vosk.Model(self.voskPath)
self.vosk = None
self.restartVosk()
# Initialize speechrecognition module
self.srRecognizer = Recognizer()
# Initialize other libraries
w = [x for x in self.wakewords if x in pvporcupine.KEYWORDS]
self.porcupine = None
if w:
self.porcupine = pvporcupine.create(
keywords=w, sensitivities=self.sensitivities
)
self.vad = VAD(vadPath, vadThreshold)
self.done = False
self.listen = True
self.woke = False
self._speechLength = self.speechLengths[0]
self._frames = {"beforeWoke": [], "afterWoke": []}
self._followup = False
self._q = Queue()
self._ready = False
self._speech = True
self._startSpeechLength = self.speechLengths[0]
self._realSpeechLength = self.speechLengths[1]
self._lastRecognizedTime = time.time()
self.__count = 0
self.__prevSpeaking = None
self.__length = 0
# User callback parameters
self.callbackParams = {}
def __callback(self, data, frames, time_, status) -> None:
self._q.put(bytes(data))
def _reset(self) -> None:
self._frames = {"beforeWoke": [], "afterWoke": []}
if not self.disableVosk:
self.vosk.FinalResult()
self.woke = False
self._speech = True
self._lastRecognizedTime = time.time()
self.__count = 0
self.__prevSpeaking = None
self.__length = 0
self._speechLength = self.speechLengths[0]
def multiplySpeechLength(self, multiplier: float) -> float:
"""
Dynamically update the speech length by multiplying it by a certain value.
"""
self._realSpeechLength = self.speechLengths[1] * multiplier
return self._realSpeechLength
def recognizeDone(self) -> None:
"""
Tells the recognizer that we are done recognizing.
"""
self._speech = False
def restartVosk(self) -> None:
"""
Restart just the Vosk recognizer.
"""
if not self.disableVosk:
self.vosk = vosk.KaldiRecognizer(self.voskModel, RATE)
async def recognize(self) -> dict:
if not self._speech:
if self.offline:
if not self.disableVosk:
text = json.loads(self.vosk.FinalResult())["text"]
return {"status": "recognized", "msg": text}
return {"status": "error", "msg": f"both disableVosk and offline is True. Can't recognize with nothing to recognize with.", "exception": None}
frames = self._frames["beforeWoke"][-10:] + self._frames["afterWoke"]
# First save the data gathered into a .wav file
wf = wave.open(self.savePath, "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
# Convert it into a AudioData object
try:
with AudioFile(self.savePath) as src:
audio = self.srRecognizer.record(src)
except Exception as e:
return {
"status": "error",
"msg": f"Failed to convert cache file to AudioData. ({e})",
"exception": e
}
# Finally attempt to recognize using google's recognizer from speechrecognition module
try:
content = self.srRecognizer.recognize_google(
audio, key=self.googleRecognizerKey
)
callback = {"status": "recognized", "msg": content}
except UnknownValueError:
callback = {"status": "unknown", "msg": "Unknown value."}
except Exception as e:
callback = {
"status": "error",
"msg": f"Failed to recognize audio. ({e})",
"exception": e
}
finally:
return callback
return {"status": "listening", "msg": "Appending frames."}
async def callback(self, *args, **kwargs) -> None:
await self._callback(*args, **kwargs, **self.callbackParams)
async def wakeUp(
self, followup: bool = False, emitCallback: bool = True, **kwargs
) -> None:
"""
Wake up the speech recognizer,
Parameters
----------
`followup` : bool
"""
self.woke = True
self._followup = followup
self.__prevSpeaking = time.time()
self.callbackParams = {"followup": followup, **kwargs}
if emitCallback:
await self.callback({"status": "woke", "msg": "woke"})
async def start(self, blocking: bool = False) -> None:
"""
Start the speech recognizer.
Parameters
----------
`blocking` : bool
if True, speech recognizer will block the program.
"""
if blocking:
return await self._start()
def f():
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(self._start())
osInterface.thread(f)
while not self._ready:
await asyncio.sleep(0.05)
async def wokeListen(self, data) -> bool:
"""
Starts listening for the provided wake words both using pvporcupine and vosk.
Vosk will not be used if self.disableVosk is True
"""
if not self.disableVosk:
# Get vosk information
self.vosk.AcceptWaveform(data)
partial = json.loads(self.vosk.PartialResult())
else:
partial = {"partial": ""}
# Get pvporcupine wake word information
p = -1
if self.porcupine:
p = self.porcupine.process(np.frombuffer(data, dtype=np.int16))
# Check if a wake word is recognized using both vosk and porcupine if porcupine is successfully initialized
if any(k in partial["partial"] for k in self.wakewords) or p >= 0:
if not self.disableVosk:
self.vosk.FinalResult()
return True
# Constantly collect before wake word frames
if len(self._frames["beforeWoke"]) > self.beforeWokeBufferLimit:
self._frames["beforeWoke"].pop(0)
self._frames["beforeWoke"].append(data)
if not self.disableVosk:
# Prevent active listening from getting way too big, will cause a memory leak if not implemented
if len(partial["partial"].split()) > 25:
self.vosk.FinalResult()
self.restartVosk()
vad = await self.vad.isSpeech(data)
if vad:
self.__prevSpeaking = time.time()
if not self.__prevSpeaking:
self.__prevSpeaking = time.time()
length = time.time() - self.__prevSpeaking
if length > 20.0:
if not self.disableVosk:
self.vosk.FinalResult()
self.restartVosk()
self.__prevSpeaking = time.time()
# Emit what the vosk recognizer is currently hearing
await self.callback(
{"status": "activeListeningPartial", "msg": partial["partial"]}
)
return False
async def _start(self) -> None:
with sd.RawInputStream(
samplerate=RATE,
blocksize=CHUNK,
device=self.device,
dtype="int16",
channels=CHANNELS,
callback=self.__callback,
):
self._ready = True
while not self.done:
data = self._q.get()
if self.listen:
# Wait for one of the wake words to be triggered
if not self.woke:
# There seems to be a bug wherein woke becomes True right after the speech is recognized, so we do a time check to prevent that. (pls fix) FIXME
woke = await self.wokeListen(data)
if (time.time() - self._lastRecognizedTime) < 1.8:
woke = False
# Now wake up the processor/recognizer
if woke and not self.woke:
await self.wakeUp()
if self.woke:
partial = None
if not self.disableVosk:
# Give vosk the speech data
self.vosk.AcceptWaveform(data)
# Realtime Partial data
partial = list(json.loads(self.vosk.PartialResult()).items())[
0
][1].strip()
if partial:
await self.callback(
{"status": "recognizedPartial", "msg": partial}
)
# Perform voice activity detection
vad = await self.vad.isSpeech(data)
if vad:
self.__count += 1
self.__prevSpeaking = time.time()
await self.callback(
{"status": "voiceActivity", "msg": "voiceActivity"}
)
# Perform previous voice activity checking.
if self.__prevSpeaking:
self.__length = time.time() - self.__prevSpeaking
comparator = self.__count == 0 or not partial
if self.disableVosk:
comparator = self.__count == 0
if comparator:
self._speechLength = self._startSpeechLength
else:
self._speechLength = self._realSpeechLength
# Current speech length has exceeded the provided speech length meaning we're done listening.
if self.__length > self._speechLength:
self.recognizeDone()
self._frames["afterWoke"].append(data)
recognized = await self.recognize()
await self.callback(recognized)
# Finally reset all the variables back to their default so that it can be ready for the next time the listener gets woke.
if not self._speech:
self._reset()
async def callback(data, *args, **kwargs) -> None:
status = data.get("status", "listening")
if status == "recognizedPartial":
print(f"> {data['msg']} {recognizer._realSpeechLength}", end="\r")
if data["msg"].startswith("turn the lights off"):
recognizer.recognizeDone()
if data["msg"].endswith(("to", "two", "of", "and", "for")):
recognizer.multiplySpeechLength(2.8)
else:
recognizer.multiplySpeechLength(1)
if status == "recognized":
print(f"You: {data['msg']}")
if status == "woke":
print(f"\nI'm listening...")
if status == "activeListeningPartial":
print(f"Active: {data['msg']}", end="\r")
async def main(loop: asyncio.BaseEventLoop) -> None:
global recognizer
recognizer = SpeechRecognizer(
["jarvis"],
[1.0],
osInterface.joinPath("models/vad.h5"),
0.9,
osInterface.joinPath("models/vosk"),
osInterface.joinPath(".tmp/cache.wav"),
callback,
loop,
speechLengths=(5.0, 1.2),
offline=False,
disableVosk=True
)
await recognizer.start(blocking=True)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main(loop))
except KeyboardInterrupt:
loop.stop()
|
# -----------------------------------------------------
# Copyright (c) Shanghai Jiao Tong University. All rights reserved.
# Written by Jiefeng Li (jeff.lee.sjtu@gmail.com)
# -----------------------------------------------------
import torch.nn as nn
from .builder import SPPE
from .layers.DUC import DUC
from .layers.SE_Resnet import SEResnet
@SPPE.register_module
class FastPose(nn.Module):
conv_dim = 128
def __init__(self, norm_layer=nn.BatchNorm2d, **cfg):
super(FastPose, self).__init__()
self._preset_cfg = cfg['PRESET']
if 'DCN' in cfg.keys():
stage_with_dcn = cfg['STAGE_WITH_DCN']
dcn = cfg['DCN']
self.preact = SEResnet(
f"resnet{cfg["NUM_LAYERS"]}", dcn=dcn, stage_with_dcn=stage_with_dcn)
else:
self.preact = SEResnet(f"resnet{cfg["NUM_LAYERS"]}")
# Imagenet pretrain model
import torchvision.models as tm # noqa: F401,F403
assert cfg['NUM_LAYERS'] in [18, 34, 50, 101, 152]
x = eval(f"tm.resnet{cfg["NUM_LAYERS"]}(pretrained=True)")
model_state = self.preact.state_dict()
state = {k: v for k, v in x.state_dict().items()
if k in self.preact.state_dict() and v.size() == self.preact.state_dict()[k].size()}
model_state.update(state)
self.preact.load_state_dict(model_state)
self.suffle1 = nn.PixelShuffle(2)
self.duc1 = DUC(512, 1024, upscale_factor=2, norm_layer=norm_layer)
self.duc2 = DUC(256, 512, upscale_factor=2, norm_layer=norm_layer)
self.conv_out = nn.Conv2d(
self.conv_dim, self._preset_cfg['NUM_JOINTS'], kernel_size=3, stride=1, padding=1)
def forward(self, x):
out = self.preact(x)
out = self.suffle1(out)
out = self.duc1(out)
out = self.duc2(out)
out = self.conv_out(out)
return out
def _initialize(self):
for m in self.conv_out.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
# logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))
# logger.info('=> init {}.bias as 0'.format(name))
nn.init.normal_(m.weight, std=0.001)
nn.init.constant_(m.bias, 0)
| # -----------------------------------------------------
# Copyright (c) Shanghai Jiao Tong University. All rights reserved.
# Written by Jiefeng Li (jeff.lee.sjtu@gmail.com)
# -----------------------------------------------------
import torch.nn as nn
from .builder import SPPE
from .layers.DUC import DUC
from .layers.SE_Resnet import SEResnet
@SPPE.register_module
class FastPose(nn.Module):
conv_dim = 128
def __init__(self, norm_layer=nn.BatchNorm2d, **cfg):
super(FastPose, self).__init__()
self._preset_cfg = cfg['PRESET']
if 'DCN' in cfg.keys():
stage_with_dcn = cfg['STAGE_WITH_DCN']
dcn = cfg['DCN']
self.preact = SEResnet(
f"resnet{cfg['NUM_LAYERS']}", dcn=dcn, stage_with_dcn=stage_with_dcn)
else:
self.preact = SEResnet(f"resnet{cfg['NUM_LAYERS']}")
# Imagenet pretrain model
import torchvision.models as tm # noqa: F401,F403
assert cfg['NUM_LAYERS'] in [18, 34, 50, 101, 152]
x = eval(f"tm.resnet{cfg['NUM_LAYERS']}(pretrained=True)")
model_state = self.preact.state_dict()
state = {k: v for k, v in x.state_dict().items()
if k in self.preact.state_dict() and v.size() == self.preact.state_dict()[k].size()}
model_state.update(state)
self.preact.load_state_dict(model_state)
self.suffle1 = nn.PixelShuffle(2)
self.duc1 = DUC(512, 1024, upscale_factor=2, norm_layer=norm_layer)
self.duc2 = DUC(256, 512, upscale_factor=2, norm_layer=norm_layer)
self.conv_out = nn.Conv2d(
self.conv_dim, self._preset_cfg['NUM_JOINTS'], kernel_size=3, stride=1, padding=1)
def forward(self, x):
out = self.preact(x)
out = self.suffle1(out)
out = self.duc1(out)
out = self.duc2(out)
out = self.conv_out(out)
return out
def _initialize(self):
for m in self.conv_out.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
# logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))
# logger.info('=> init {}.bias as 0'.format(name))
nn.init.normal_(m.weight, std=0.001)
nn.init.constant_(m.bias, 0)
|
from twocaptcha import TwoCaptcha
from scrapy import Selector
from src.core.request import RequestHandler
from src.core.captcha import CaptchaHandler
from src.core.logging import log
from src.settings import SPIDERS_SETTINGS, CAPTCHA
from src.utils.format import format_cpf
from src.utils.extract import extract_set_cookies
class SpiderLoginInterface(RequestHandler):
login_params = {}
login_data = {}
async def init_login(self, login_url):
_ = await self.session(url=login_url, allow_redirects=False)
response = self.get_response
self.login_data['login_cookies'] = extract_set_cookies(
self.get_response, ['Session_Gov_Br_Prod', 'INGRESSCOOKIE']
)
self.login_data['location'] = response.headers.get('location')
def format_username_data(self):
cpf = format_cpf(SPIDERS_SETTINGS["easydarf"]["USERNAME"])
return {
"_csrf": self.login_data['_csrf'],
"accountId": cpf,
"action": "enterAccountId"
}
def format_password_data(self):
cpf = format_cpf(SPIDERS_SETTINGS["easydarf"]["USERNAME"])
return {
'_csrf': self.login_data['_csrf'],
'accountId': cpf,
'password': SPIDERS_SETTINGS['easydarf']['PASSWORD'],
'g-recaptcha-response': self.login_params["captcha"],
'action': 'enterPassword'
}
@staticmethod
def extract_site_key(response):
selector = Selector(text=response)
return selector.xpath(
'//div[@id="login-password"]//'
'button[@id="submit-button"]/@data-sitekey'
).extract_first()
async def login_username(self):
response = await self.session(
url=self.login_data['init_url'],
method="POST",
headers={
'content-type': 'application/x-www-form-urlencoded',
},
cookies=self.login_data['login_cookies'],
data=self.format_username_data()
)
self.login_data['site_key_captcha'] = self.extract_site_key(response)
self.login_data['captcha_url'] = str(self.login_data['init_url'])
async def login_password(self, init_url):
_ = await self.session(
url=init_url,
method="POST",
headers={
'content-type': 'application/x-www-form-urlencoded',
},
cookies=self.login_data['login_cookies'],
data=self.format_password_data(),
allow_redirects=False
)
self.login_data['location'] = self.get_response.headers.get('location')
async def follow_redirect(self):
response = await self.session(
url=self.login_data['location'],
cookies=self.login_data['login_cookies']
)
selector = Selector(text=response)
self.login_data['_csrf'] = selector.xpath(
'//form[@id="loginData"]//input[@name="_csrf"]/@value'
).extract_first()
return self.get_response
async def authorize(self):
_ = await self.session(
url=self.login_data['location'],
cookies=self.login_data['login_cookies'],
allow_redirects=False
)
self.login_data['location'] = self.get_response.headers.get('location')
async def auth_login(self):
_ = await self.session(
url=self.login_data['location'],
allow_redirects=False
)
self.context['pos_login_cookies'] = extract_set_cookies(
self.get_response, ['ASP.NET_SessionId', 'COOKIECAV']
)
async def start_login(self, response):
selector = Selector(text=response)
login_url = selector.xpath(
'//form[@id="frmLoginCert"]//a/@href'
).extract_first()
await self.init_login(login_url)
init_response = await self.follow_redirect()
self.login_data['init_url'] = init_response.url
await self.login_username()
async def make_login(self):
log.info(msg="Spider captcha detected")
two_captcha = TwoCaptcha(**{
'apiKey': CAPTCHA['2CAPTCHA_API_KEY'],
'defaultTimeout': 60,
'recaptchaTimeout': 200,
'pollingInterval': 7
})
captcha_handler = CaptchaHandler(captcha_resolver=two_captcha)
log.info(
msg=f"Solving captcha - {self.login_data["site_key_captcha"]}"
)
captcha_result = await captcha_handler.broker_captcha(
site_key=self.login_data["site_key_captcha"],
site_url=self.login_data['captcha_url']
)
log.info(msg=f"Captcha solved: {captcha_result}")
self.login_params["captcha"] = captcha_result
await self.login_password(self.login_data['init_url'])
await self.authorize()
await self.auth_login()
| from twocaptcha import TwoCaptcha
from scrapy import Selector
from src.core.request import RequestHandler
from src.core.captcha import CaptchaHandler
from src.core.logging import log
from src.settings import SPIDERS_SETTINGS, CAPTCHA
from src.utils.format import format_cpf
from src.utils.extract import extract_set_cookies
class SpiderLoginInterface(RequestHandler):
login_params = {}
login_data = {}
async def init_login(self, login_url):
_ = await self.session(url=login_url, allow_redirects=False)
response = self.get_response
self.login_data['login_cookies'] = extract_set_cookies(
self.get_response, ['Session_Gov_Br_Prod', 'INGRESSCOOKIE']
)
self.login_data['location'] = response.headers.get('location')
def format_username_data(self):
cpf = format_cpf(SPIDERS_SETTINGS["easydarf"]["USERNAME"])
return {
"_csrf": self.login_data['_csrf'],
"accountId": cpf,
"action": "enterAccountId"
}
def format_password_data(self):
cpf = format_cpf(SPIDERS_SETTINGS["easydarf"]["USERNAME"])
return {
'_csrf': self.login_data['_csrf'],
'accountId': cpf,
'password': SPIDERS_SETTINGS['easydarf']['PASSWORD'],
'g-recaptcha-response': self.login_params["captcha"],
'action': 'enterPassword'
}
@staticmethod
def extract_site_key(response):
selector = Selector(text=response)
return selector.xpath(
'//div[@id="login-password"]//'
'button[@id="submit-button"]/@data-sitekey'
).extract_first()
async def login_username(self):
response = await self.session(
url=self.login_data['init_url'],
method="POST",
headers={
'content-type': 'application/x-www-form-urlencoded',
},
cookies=self.login_data['login_cookies'],
data=self.format_username_data()
)
self.login_data['site_key_captcha'] = self.extract_site_key(response)
self.login_data['captcha_url'] = str(self.login_data['init_url'])
async def login_password(self, init_url):
_ = await self.session(
url=init_url,
method="POST",
headers={
'content-type': 'application/x-www-form-urlencoded',
},
cookies=self.login_data['login_cookies'],
data=self.format_password_data(),
allow_redirects=False
)
self.login_data['location'] = self.get_response.headers.get('location')
async def follow_redirect(self):
response = await self.session(
url=self.login_data['location'],
cookies=self.login_data['login_cookies']
)
selector = Selector(text=response)
self.login_data['_csrf'] = selector.xpath(
'//form[@id="loginData"]//input[@name="_csrf"]/@value'
).extract_first()
return self.get_response
async def authorize(self):
_ = await self.session(
url=self.login_data['location'],
cookies=self.login_data['login_cookies'],
allow_redirects=False
)
self.login_data['location'] = self.get_response.headers.get('location')
async def auth_login(self):
_ = await self.session(
url=self.login_data['location'],
allow_redirects=False
)
self.context['pos_login_cookies'] = extract_set_cookies(
self.get_response, ['ASP.NET_SessionId', 'COOKIECAV']
)
async def start_login(self, response):
selector = Selector(text=response)
login_url = selector.xpath(
'//form[@id="frmLoginCert"]//a/@href'
).extract_first()
await self.init_login(login_url)
init_response = await self.follow_redirect()
self.login_data['init_url'] = init_response.url
await self.login_username()
async def make_login(self):
log.info(msg="Spider captcha detected")
two_captcha = TwoCaptcha(**{
'apiKey': CAPTCHA['2CAPTCHA_API_KEY'],
'defaultTimeout': 60,
'recaptchaTimeout': 200,
'pollingInterval': 7
})
captcha_handler = CaptchaHandler(captcha_resolver=two_captcha)
log.info(
msg=f"Solving captcha - {self.login_data['site_key_captcha']}"
)
captcha_result = await captcha_handler.broker_captcha(
site_key=self.login_data["site_key_captcha"],
site_url=self.login_data['captcha_url']
)
log.info(msg=f"Captcha solved: {captcha_result}")
self.login_params["captcha"] = captcha_result
await self.login_password(self.login_data['init_url'])
await self.authorize()
await self.auth_login()
|
# Lint as: python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities."""
# ==============================================================================
# Note: Avoid adding dependencies to py_utils beyond standard python packages
# and tensorflow.
# ==============================================================================
import collections as py_collections
import contextlib
import functools
import hashlib
import inspect
import math
import numbers
import os
import pkgutil
import re
import threading
import traceback
import typing
from typing import Optional, Union
import lingvo.compat as tf
from lingvo.core import cluster_factory
from lingvo.core import gshard_utils
from lingvo.core import hyperparams
from lingvo.core import nested_map
from lingvo.core import ops
from lingvo.core import py_utils_flags
from lingvo.core import retry
from lingvo.core import symbolic
from lingvo.core import thread_local_utils
from lingvo.core import tshape
import numpy as np
import six
# pylint: disable=g-direct-tensorflow-import
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import function
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.tf2 import enabled as tf2_enabled
from tensorflow.python.tpu import topology as tf_topology
from tensorflow.python.tpu import tpu_function
from tensorflow.python.util import deprecation
# pylint: enable=g-direct-tensorflow-import
FLAGS = tf.flags.FLAGS
# pylint: disable=protected-access
_FromGlobal = py_utils_flags._FromGlobal
# pylint: enable=protected-access
use_xla = py_utils_flags.use_xla
use_tpu = py_utils_flags.use_tpu
testonly_skip_norm_layers = py_utils_flags.testonly_skip_norm_layers
tpu_compat = py_utils_flags.tpu_compat
use_stateless_vars_init = py_utils_flags.use_stateless_vars_init
ENQUEUE_OPS = '__lingvo_enqueue_ops'
# pylint: disable=protected-access
deprecation._PRINT_DEPRECATION_WARNINGS = False
# pylint: enable=protected-access
ThreadLocalStack = thread_local_utils.ThreadLocalStack
ThreadLocalDict = thread_local_utils.ThreadLocalDict
NestedMap = nested_map.NestedMap
def Assert(condition, data, *args, **kwargs):
if py_utils_flags.enable_asserts():
return tf.Assert(condition, data, *args, **kwargs)
else:
return tf.no_op()
def assert_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_greater_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_greater(*args, **kwargs)
else:
return tf.no_op()
def assert_less_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_less_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_less(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_less(*args, **kwargs)
else:
return tf.no_op()
def assert_between(x, l, r, *args, **kwargs): # pylint: disable=invalid-name
x = tf.convert_to_tensor(x)
l = tf.cast(tf.convert_to_tensor(l), x.dtype)
r = tf.cast(tf.convert_to_tensor(r), x.dtype)
return tf.group([
assert_greater_equal(x, l, *args, **kwargs),
assert_less(x, r, *args, **kwargs)
])
def assert_shape_match(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
kwargs['msg'] = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(
r'.*/', '', filepath), line, func)
return ops.assert_shape_match(*args, **kwargs)
else:
return tf.no_op()
def assert_same_dim0(xs, *args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return ops.assert_same_dim0(xs, *args, **kwargs)
else:
return tf.no_op()
def assert_even_divide(denorm, num): # pylint: disable=invalid-name
"""Asserts that denorm is evenly divided by num."""
denorm = tf.convert_to_tensor(denorm)
num = tf.convert_to_tensor(num)
if denorm.dtype not in (tf.int32, tf.int64):
raise ValueError('denorminator.dtype is not tf.int32 or tf.int64.')
if num.dtype not in (tf.int32, tf.int64):
raise ValueError('numerator.dtype is not tf.int32 or tf.int64.')
num = HasShape(num, GetShape(denorm))
quo = denorm // num
return assert_equal(quo * num, denorm)
def AssertIdShape(expected_ids_shape_pattern, ids_shape, *args):
"""Asserts shape expected_ids_shape_pattern matches all other input shapes."""
def AssertFn(inputs):
dependencies = [
assert_shape_match(inputs.ids_shape, inputs.expected_ids_shape_pattern)
] + [
assert_shape_match(inputs.ids_shape, x_shape) for x_shape in inputs.args
]
return with_dependencies(dependencies, inputs.ids_shape)
inputs = NestedMap(
expected_ids_shape_pattern=expected_ids_shape_pattern,
ids_shape=ids_shape,
args=args)
return CallDefun(AssertFn, Transform(tf.convert_to_tensor, inputs))
def _CheckNumerics(x, message=None, *args, **kwargs):
if x.dtype.is_floating:
x_name = x.name if not tf.executing_eagerly() else '[eager]'
if 'name' not in kwargs:
kwargs['name'] = re.sub(r':\d+', '', x_name) + '_CheckNumerics'
return tf.debugging.check_numerics(x, message if message else x_name, *args,
**kwargs)
else:
return x
def CheckNumerics(inp, message=None, *args, **kwargs):
"""Check numerics for tensors in inp."""
if not py_utils_flags.enable_check_numerics():
return inp
if isinstance(inp, list):
return [_CheckNumerics(x, message, *args, **kwargs) for x in inp]
if isinstance(inp, tuple):
return tuple(_CheckNumerics(x, message, *args, **kwargs) for x in inp)
return _CheckNumerics(inp, message, *args, **kwargs)
def with_dependencies(dependencies, output_tensor): # pylint: disable=invalid-name
with tf.control_dependencies(dependencies):
return tf.identity(output_tensor)
def _VarInCollection(var, collection):
"""Return whether a variable `var` is in the given variable collection."""
# We use variable reference for comparison, since variable is not hashable in
# eager mode.
return var.ref() in [v.ref() for v in collection]
@contextlib.contextmanager
def _PrintOptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
def _Print(name, x):
with _PrintOptions(linewidth=1000):
tf.logging.info('%s = %s', name, np.array_repr(x))
def Log(value, prefix, **kwargs):
"""Prints out values of tensors.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Log(z, 'debug compute()', x=x, y=y)
Args:
value: A Tensor. Log happens after this tensor's computed.
prefix: Every tensor is logged with this prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
# Ensures tensors are printed in order.
last = value
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Print, [prefix + ' : ' + k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def Debug(tensor, message='', enabled=True, summarize=100, more=None):
"""Wrapper around tf.Print() and tf.logging.info() to simplify debug printing.
x = py_utils.Debug(x)
When the graph is built a regular log info line will be printed:
-DBG- py_utils_test.py:429 x=Tensor(...
Then when the tensor node is evaluated it will print lines like:
-DBG- py_utils_test.py:429 x Const:0[x.shape=][2 2][x=][[1 2][3 4]]
WARNING: The code that parses local variable names can fail. E.g. don't write
two Debug() calls on one line or a Debug() call that spans more than one line.
Args:
tensor: A tensor to print.
message: A message to print.
enabled: To enable the debugging.
summarize: Integer with number of tensor values to print.
more: An optional list of additional tensors.
Returns:
The tensor.
"""
if not enabled or _FromGlobal('disable_py_utils_debug'):
return tensor
if more is None:
more = []
stack = inspect.stack()[1][0]
caller = inspect.getframeinfo(stack)
caller_var = ''
caller_more_vars = []
if caller.code_context:
# Rough and likely to fail. But better than nothing.
match = re.compile(r'Debug\((.*?)(\)|,).*$').search(caller.code_context[0])
if match:
caller_var = match.groups()[0]
if more:
more_vars = re.compile(r'more=\[(.*?)\].*$').search(
caller.code_context[0]).groups()[0]
if more_vars:
caller_more_vars = more_vars.split(',')
the_class = ''
if 'self' in stack.f_locals:
the_class = stack.f_locals['self'].__class__.__name__
header = '-DBG- {}:{}:{}:{} {} '.format(
os.path.basename(caller.filename), the_class, caller.function,
caller.lineno, message)
info = '{}{}={}'.format(header, caller_var, tensor)
for name, val in zip(caller_more_vars, more):
info += ' {}={}'.format(name.strip(), val)
tf.logging.info(info)
if isinstance(tensor, tf.Tensor):
tensors = []
tensors += [tf.constant('{}.shape='.format(caller_var)), tf.shape(tensor)]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}.shape='.format(name.strip())), tf.shape(val)]
tensors += [tf.constant('{}='.format(caller_var)), tensor]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}='.format(name.strip())), val]
name = tensor.name if not tf.executing_eagerly() else '[eager]'
info = '{}{} {}'.format(header, caller_var, name)
return tf.identity(
tf.Print(tensor, tensors, info, summarize=summarize),
re.sub(':.*$', '', name))
return tensor
def _Save(steps, prefix, key, val):
filename = '%s.%08d.%s.npy' % (six.ensure_text(prefix), steps,
six.ensure_text(key))
with tf.io.gfile.GFile(filename, 'w') as outfile:
np.save(outfile, val)
def Save(value, filename_prefix, **kwargs):
"""Saves values of tensors into files.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Save(z, '/path/tmp', x=x, y=y, z=z)
Args:
value: A Tensor. Saving happens after this tensor is computed.
filename_prefix: Every tensor is saved with this filename prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
last = value
steps = GetGlobalStep()
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Save, [steps, filename_prefix, k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def HasRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has the expected rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims == expected_rank, (
'Ranks did not match, got %d, '
'expected %d') % (tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies([tf.assert_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def HasAtLeastRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has rank >= expected_rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims >= expected_rank, (
'Rank of tensor %d did not exceed the expected value %d.') % (
tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies(
[tf.debugging.assert_greater_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def GetRank(tensor):
"""Returns tensor's rank as an int if it's available, otherwise a Tensor.
Args:
tensor: The input tensor.
Returns:
Either an int or a Tensor for the rank of the input tensor.
"""
if tensor.shape.ndims is not None:
return tensor.shape.ndims # int
else:
return tf.rank(tensor) # Tensor
def GetShape(tensor, ndims=None):
"""Returns tensor's shape as a list which can be unpacked, unlike tf.shape.
Tries to return static shape if it's available. Note that this means
some of the outputs will be ints while the rest will be Tensors.
Args:
tensor: The input tensor.
ndims: If not None, returns the shapes for the first `ndims` dimensions.
"""
tensor = tf.convert_to_tensor(tensor)
dynamic_shape = tf.shape(tensor)
# Early exit for unranked tensor.
if tensor.shape.ndims is None:
if ndims is None:
return dynamic_shape
else:
return [dynamic_shape[x] for x in range(ndims)]
# Ranked tensor.
if ndims is None:
ndims = tensor.shape.ndims
else:
ndims = min(ndims, tensor.shape.ndims)
# Return mixture of static and dynamic dims.
static_shape = tensor.shape.as_list()
shapes = [
static_shape[x] if static_shape[x] is not None else dynamic_shape[x]
for x in range(ndims)
]
return shapes
def HasShape(tensor, expected_shape, ndims=None):
"""Syntactic sugar for asserting that tensor has the expected shape.
Args:
tensor: A Tensor.
expected_shape: A Python list or a 1D tensor. Elements of expected_shape can
be -1 which indicate that any size is valid for that dimension.
ndims: If not None, check only the first `ndims` dimensions of `tensor`.
Must be equal to the length of `expected_shape` if not None.
Returns:
The input `tensor` with control dependencies that will raise a runtime
error if dynamic shape checks fail.
Raises:
ValueError: A value error if the assertion fails at static shape checks.
"""
if not py_utils_flags.enable_asserts():
return tensor
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
msg = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(r'.*/', '',
filepath), line, func)
tensor_shape = GetShape(tensor)
if ndims is not None:
tensor_shape = tensor_shape[:ndims]
# TODO(jngiam): Attempt to switch back to tf.Assert after it has better
# support on GPUs.
assert_op = ops.assert_shape_match(tensor_shape, expected_shape, msg=msg)
# If expected_shape is a Tensor, then we are unable to perform static checks.
# In this case, we can do a dynamic check and return.
if isinstance(expected_shape, tf.Tensor):
return with_dependencies([assert_op], tensor)
# Infer ranks from the inputs.
expected_rank = len(expected_shape)
if isinstance(tensor_shape, tf.Tensor):
tensor_rank = tensor.shape.ndims
else:
tensor_rank = len(tensor_shape)
# If ndims is None, then either one of the ranks should not be None, or they
# should both match. If both ranks are None, then they are both tensors and
# should be caught by the earlier short-circuit.
if ndims is None:
if (tensor_rank is not None) and (expected_rank != tensor_rank):
raise ValueError('Tensor does not match rank of expected shape.\n'
'Tensor shape: {} Expected shape: {}'.format(
tensor_shape, expected_shape))
# Both tensors can be assumed to be of same rank.
ndims = expected_rank
else:
if (tensor_rank is not None) and (tensor_rank < ndims):
raise ValueError('Tensor has fewer dimensions than ndims.\n'
'Tensor shape: {} ndims: {}'.format(tensor_shape, ndims))
if expected_rank != ndims:
raise ValueError(
'Expected shape must have number of dimensions equal to ndims.\n'
'Expected shape: {} ndims: {}'.format(expected_shape, ndims))
# Ensure that both tensor_shape and expected_shape are both lists.
tensor_shape = tensor_shape[:ndims]
if isinstance(tensor_shape, tf.Tensor):
tensor_shape = tf.unstack(tensor_shape, num=ndims)
# Map tf.Dimension values to their held values.
tensor_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in tensor_shape
]
expected_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in expected_shape
]
all_static_checks = True
for idx, (dim, expected_dim) in enumerate(zip(tensor_shape, expected_shape)):
if isinstance(expected_dim, tf.Tensor):
all_static_checks = False
elif expected_dim == -1:
continue
elif isinstance(dim, tf.Tensor):
all_static_checks = False
elif dim != expected_dim:
raise ValueError('Tensor does not match expected shape on dimension {}.\n'
'Tensor shape: {} Expected shape: {}'.format(
idx, tensor_shape, expected_shape))
if all_static_checks:
return tf.convert_to_tensor(tensor)
else:
return with_dependencies([assert_op], tensor)
def HasSameShape(x, ref):
return HasShape(x, GetShape(ref))
def GetSize(tensor):
shape = GetShape(tensor)
if (isinstance(shape, tf.Tensor) or
any([isinstance(x, tf.Tensor) for x in shape])):
return tf.size(tensor)
return np.prod(shape)
def CausalSelfAttenPadding(seqlen, dtype):
"""Wraps tf.linalg.band_part() for tflite compatibility."""
if FLAGS.tflite_compatible:
# [N, 1]
rows = tf.expand_dims(tf.range(seqlen), -1)
# [1, N]
cols = tf.expand_dims(tf.range(seqlen), 0)
row_cols = rows - cols
return tf.where(row_cols < 0, tf.ones([seqlen, seqlen], dtype),
tf.zeros([seqlen, seqlen], tf.float32))
else:
return 1.0 - tf.linalg.band_part(
tf.ones([seqlen, seqlen], dtype=dtype), -1, 0)
def outside_all_rewrites(): # pylint: disable=invalid-name
return tf.control_dependencies(None)
# TODO(jamesqin): remove once b/147439702 is fixed.
_OUTSIDE_COMPILATION = threading.local()
def RunOnTpuHost(func, *args, **kwargs):
r"""Runs the given function call on TPU host.
Invokes func(\*args, \*\*kwargs) directly if not running on tpu.
Args:
func: the function to invoke.
*args: args of func
**kwargs: kwargs of func
Returns:
The function return value.
"""
if use_tpu() and not getattr(_OUTSIDE_COMPILATION, 'on', False):
_OUTSIDE_COMPILATION.on = True
res = tf.tpu.outside_compilation(func, *args, **kwargs)
_OUTSIDE_COMPILATION.on = False
else:
res = func(*args, **kwargs)
return res
def tpu_host(func): # pylint: disable=invalid-name
r"""Decorates a python function to only run on TPU hosts.
This function has no effect when running on CPU/GPU.
Example::
@py_utils.tpu_host()
def ComputeWER(self):
# Call a custom op computing WER.
Args:
func: the function to invoke
Returns:
A TPU-host only function
"""
def Wrapped(*args, **kwargs):
return RunOnTpuHost(func, *args, **kwargs)
return Wrapped
# Maps a TPU job name ('/job:xxx') to the job's DeviceAssignment object.
# When there is only a single TPU job, the key could be None.
_tpu_device_assignment_dict = dict()
def SetTpuDeviceAssignment(tpu_device_assignment, job=None):
if job in _tpu_device_assignment_dict:
tf.logging.warning('tpu_device_assignment was already set, '
'overwriting with new assignment.')
_tpu_device_assignment_dict[job] = tpu_device_assignment
# This function should called in unittest only.
def ClearTpuDevice():
global _tpu_device_assignment_dict
_tpu_device_assignment_dict = dict()
def GetTpuDeviceAssignment(job=None):
return _tpu_device_assignment_dict[job]
# Whether it's running in eager mode. This is different than
# tf.executing_eagerly(), which will return False inside a tf.function.
_IS_EAGER_MODE = False
def SetEagerMode(eager_mode=True):
global _IS_EAGER_MODE
_IS_EAGER_MODE = eager_mode
if eager_mode:
tf.enable_eager_execution()
tf.config.set_soft_device_placement(True)
else:
tf.disable_eager_execution()
def IsEagerMode():
return _IS_EAGER_MODE
# Maintains a tf.GradientTape stack.
_GRADIENT_TAPE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GradientTape(*args, **kwargs):
"""Creates a tf.GradientTape and use it for automatic differentiation."""
tape = tf.GradientTape(*args, **kwargs)
_GRADIENT_TAPE_STACK.stack.append(tape)
try:
with tape:
yield
finally:
_GRADIENT_TAPE_STACK.stack.pop()
# The tf.train.ExponentialMovingAverage singleton used by all subtasks in
# multi-task training with ExecutorTpu.
_EXECUTOR_EMA = None
def SetExponentialMovingAverage(ema):
global _EXECUTOR_EMA
assert ema
assert not _EXECUTOR_EMA, 'EMA was set before.'
_EXECUTOR_EMA = ema
def ExponentialMovingAverage():
return _EXECUTOR_EMA
def SessionConfig(soft_placement=True,
inline=True,
cluster_def=None,
disable_meta_optimizer=False):
"""Returns a session config proto.
Args:
soft_placement: Turns allow_soft_placement on iff True.
inline: Turns do_function_inlining on iff True.
cluster_def: A tf.train.ClusterDef describing the cluster.
disable_meta_optimizer: Turns off grappler/metagraph optimizer.
Returns:
A TF session config proto.
"""
session_config = tf.config_pb2.ConfigProto(
allow_soft_placement=soft_placement,
graph_options=tf.GraphOptions(
optimizer_options=tf.OptimizerOptions(
opt_level=tf.OptimizerOptions.L1, do_function_inlining=inline)),
cluster_def=cluster_def)
session_config.share_cluster_devices_in_session = True
if disable_meta_optimizer:
# Useful if start-up time is critical.
session_config.graph_options.rewrite_options.disable_meta_optimizer = True
# Disable layout optimizer which increases GPU memory usage.
session_config.graph_options.rewrite_options.layout_optimizer = (
rewriter_config_pb2.RewriterConfig.OFF)
return session_config
def AssertIsCompatible(a, b):
assert a.IsCompatible(b), ('%s vs %s' % (a, b))
def SetShapes(dst_nmap, src_nmap):
"""Set shapes in dst_nmap using those in src_nmap."""
AssertIsCompatible(src_nmap, dst_nmap)
for src, dst in zip(src_nmap.Flatten(), dst_nmap.Flatten()):
dst.set_shape(src.shape)
def Dtypes(nmap_list):
"""Returns all tensors' data types in a list."""
return [v.dtype for v in Flatten(nmap_list)]
def Flatten(x):
"""Flattens 'x' by extracting tensors from nested structures to a list."""
return tf.nest.flatten(x)
def Pack(tmpl, values):
"""Packs 'values' according to 'tmpl'."""
return tf.nest.pack_sequence_as(tmpl, values)
def Transform(fn, *v):
"""Replaces every nested value x in 'v' with fn(x) and returns the result."""
return tf.nest.map_structure(fn, *v)
def ConvertNoneGradientToZeros(xs, dxs):
"""Sanitize dxs so that None becomes zeros appropriately.
Args:
xs: A list of tensors.
dxs: A list of tensors. dxs[i] corresponds to xs[i]'s gradient.
Returns:
A `.NestedMap` same as dxs with None replaced by a zero tensor.
"""
fn = lambda x, dx: tf.zeros_like(x) if dx is None else dx
return Transform(fn, xs, dxs)
def IsCompatible(lhs, rhs):
"""Returns true if lhs and rhs are compatible."""
try:
tf.nest.assert_same_structure(lhs, rhs)
return True
except (ValueError, TypeError):
return False
class _Unique:
"""A helper to uniqify variables in a NestedMap."""
def __init__(self):
self._vset = set()
def __call__(self, v):
if (v is None) or (id(v) in self._vset):
return False
else:
self._vset.add(id(v))
return True
def ToUniqueList(nmap):
"""Returns the flattened `nmap` with duplicates removed."""
return nmap.Filter(_Unique()).Flatten()
def ReadOnlyAttrDictView(backing):
"""Wraps a dict to provide a read-only view of its contents.
Dict keys can also be accessed by attribute.
Args:
backing: Dict-like object to wrap.
Returns:
Read-only Mapping that can be accessed by index (['foo']) or attr (d.foo).
"""
class Wrapper:
"""Wrapper object."""
# Disable pytype attribute checking.
_HAS_DYNAMIC_ATTRIBUTES = True
def __getitem__(self, key):
return backing[key]
def __len__(self):
return len(backing)
def __iter__(self):
return iter(backing)
def __getattr__(self, key):
return backing[key]
def __hasattr__(self, key):
return key in backing
def __setattr__(self, key, value):
raise AttributeError('Dictionary is read-only.')
def __setitem__(self, key, value):
raise AttributeError('Dictionary is read-only.')
return Wrapper()
def ToStaticShape(shape):
"""Converts 'shape' to a static shape."""
if isinstance(shape, (list, tuple)):
shape = [
dim.value if isinstance(dim, tf.Dimension) else dim for dim in shape
]
static_shape = []
for dim in shape:
if symbolic.IsExpr(dim):
static_shape.append(symbolic.ToStatic(dim))
else:
static_shape.append(dim)
return static_shape
else:
return shape.value if isinstance(shape, tf.Dimension) else shape
def Zeros(shape, *args, **kwargs):
return tf.zeros(ToStaticShape(shape), *args, **kwargs)
class UniformSampler:
"""A reservoir sampler.
This class implements reservoir sampling: Given a limit of `num_samples` total
samples, this class maintains a uniform probability (1 / `num_samples`) of
keeping any item dynamically added to the sampler.
See https://en.wikipedia.org/wiki/Reservoir_sampling for details.
"""
def __init__(self, num_samples):
assert num_samples > 0
self._num_samples = num_samples
self._num_seen_items = 0
self._samples = []
def Add(self, item):
"""Add item to sampler."""
self._num_seen_items += 1
if len(self._samples) < self._num_samples:
self._samples.append(item)
return
index = np.random.randint(0, self._num_seen_items)
if index < self._num_samples:
self._samples[index] = item
@property
def samples(self):
"""Fetch the current samples from the sampler."""
return self._samples
class RNNCellStateInit:
"""State initialization functions for RNN cell init state."""
@staticmethod
def _Params(method, seed):
p = hyperparams.Params()
p.Define('method', method,
'Initialization method. Should be one of zeros, random_normal.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Freeze()
return p
@staticmethod
def Zeros():
"""tf.zeros()."""
return RNNCellStateInit._Params('zeros', seed=None)
@staticmethod
def RandomNormal(seed=None):
"""tf.random.normal()."""
return RNNCellStateInit._Params('random_normal', seed)
def DefaultRNNCellStateInit():
return RNNCellStateInit.Zeros()
def InitRNNCellState(shape, init=None, dtype=None, name=None, is_eval=False):
"""Initial state definitions for RNN cell implementations.
Args:
shape: A array of ints/symbols for specifying the shape of the state.
init: Hyperparameters as returned by one of the static implemetaitons in
RNNCellStateInit.
dtype: The dype of the states. Defaults to tf.float32.
name: A name for the operation. If --stateless_vars_init is set, this name
is used to generate a seed on a per-variable basis. Otherwise, this name
is optional.
is_eval: Bool, set to True if we need special behavior in eval mode.
Returns:
A Tensor of the specified shape, and sampled from the distribution as
defined by the init parameters.
"""
shape = ToStaticShape(shape)
if init is None:
init = DefaultRNNCellStateInit()
if dtype is None:
dtype = tf.float32
method = init.method
if ((method in ['zeros']) or (method in ['random_normal'] and is_eval)):
init_state = tf.zeros(shape=shape, dtype=dtype, name=name)
elif method in ['random_normal']:
if use_stateless_vars_init():
if name is None:
raise ValueError('InitRNNCellState() requires a `name` argument when '
'--stateless_vars_init is enabled.')
seed = _GenerateStatelessRngSeed(name, init.seed)
init_state = stateless_random_ops.stateless_random_normal(
shape=shape, dtype=dtype, name=name, seed=seed)
else:
init_state = tf.random.normal(
shape=shape, dtype=dtype, name=name, seed=init.seed)
else:
raise ValueError('Initialization method (%s) not supported.' % method)
return init_state
class WeightInit:
"""Static class providing weight initialization config params."""
@staticmethod
def _Params(method, scale, seed, custom_v_init=None):
"""Parameters of this class."""
p = hyperparams.Params()
p.Define('method', method, 'Initialization method.')
p.Define('scale', scale, 'Initialization scale.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Define('custom_v_init', custom_v_init,
'A custom tf.init_ops.Initializer instance.')
p.Freeze()
return p
@staticmethod
def Gaussian(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1.0)."""
return WeightInit._Params('gaussian', scale, seed)
@staticmethod
def Uniform(scale=1.0, seed=None):
"""scale * tf.random.uniform(-1.0, 1.0)."""
return WeightInit._Params('uniform', scale, seed)
@staticmethod
def UniformPositive(scale=1.0, seed=None):
"""scale * tf.random.uniform(0., 1.0)."""
return WeightInit._Params('uniform_positive', scale, seed)
@staticmethod
def Category(scale=2, seed=None):
"""tf.floor(scale * tf.random.uniform(0., 1.0))."""
return WeightInit._Params('category', scale, seed)
@staticmethod
def Xavier(scale=1.0, seed=None):
"""Xavier initialization (x = sqrt(6. / (in + out)); [-x, x])."""
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def XavierWithFixupParams(scale=1.0,
depth=1.0,
layers_per_residual_block=1.0,
seed=None):
"""Xavier initialization with Fixup."""
scale = scale * math.pow(depth, (-1.0 / (2 * layers_per_residual_block)))
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def GeoMeanXavier(scale=1.0, seed=None):
"""A variant of Xavier (x = sqrt(3. / sqrt(in * out)); [-x, x])."""
return WeightInit._Params('geo_mean_xavier', scale, seed)
@staticmethod
def Constant(scale=1.0):
"""scale."""
return WeightInit._Params('constant', scale, 0)
@staticmethod
def TruncatedGaussian(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1.0)."""
return WeightInit._Params('truncated_gaussian', scale, seed)
@staticmethod
def GaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('gaussian_sqrt_dim', scale, seed)
@staticmethod
def GaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('gaussian_sqrt_fanin', scale, seed)
@staticmethod
def GaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('gaussian_sqrt_fanout', scale, seed)
@staticmethod
def GaussianSqrtFanAvg(scale=1.0, seed=None):
"""tf.random.normal(0, sqrt(2.0 / (in + out)))."""
return WeightInit._Params('gaussian_sqrt_fanavg', scale, seed)
@staticmethod
def UniformSqrtDim(scale=1.0, seed=None):
"""scale * tf.uniform(-1 / sqrt(dim0), 1 / sqrt(dim0))."""
return WeightInit._Params('uniform_sqrt_dim', scale, seed)
@staticmethod
def UniformUnitScaling(scale=1.0, seed=None):
"""scale * sqrt(3) / sqrt(dim0) * tf.uniform(-1, 1)."""
return WeightInit._Params('uniform_unit_scaling', scale, seed)
@staticmethod
def UniformUnitScalingFanAvg(scale=1.0, seed=None):
"""Same as tf.variance_scaling_initializer() ...
Samples are drawn from a uniform distribution within [-limit, limit], with
limit = sqrt(3 * scale / n)
where
n = max(1., (fan_in + fan_out) / 2).
See tf.keras.initializers.VarianceScaling for details.
Args:
scale: A Python float.
seed: A Python int or None.
Returns:
A WeightInit param.
"""
return WeightInit._Params('uniform_unit_scaling_fan_avg', scale, seed)
@staticmethod
def TruncatedGaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('truncated_gaussian_sqrt_dim', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanin', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanout', scale, seed)
@staticmethod
def KaimingUniformFanInRelu(scale=1.0, seed=None):
return WeightInit._Params('kaiming_uniform_fanin_relu', scale, seed)
@staticmethod
def KaimingUniformFanInLeakyRelu(scale=np.sqrt(5.), seed=None):
return WeightInit._Params('kaiming_uniform_fanin_leakyrelu', scale, seed)
@staticmethod
def CustomVarInit(custom_v_init):
return WeightInit._Params('custom', 1.0, None, custom_v_init)
@staticmethod
def CustomConstantVarInit(custom_v_init):
return WeightInit._Params('custom_constant', 1.0, None, custom_v_init)
_DEFAULT_XAVIER_INIT = 1.000001
def DefaultParamInit():
# Here we use 1.000001 as a signature for user picking up the
# default param initializer.
return WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
# TODO(rpang, jonathanasdf): explore adding _is_default to hyperparams.Param.
def IsDefaultParamInit(p):
return (p.method == 'xavier' and
abs(p.scale - _DEFAULT_XAVIER_INIT) < 1e-7 and p.seed is None)
def WeightParams(shape,
init=None,
dtype=None,
collections=None,
device_mesh=None,
tensor_split_dims_mapping=None):
"""Returns a hyperparams for a weight variable given the shape/init/dtype."""
if init is None:
init = WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
if dtype is None:
dtype = tf.float32
if collections is None:
collections = []
if device_mesh is not None:
assert tensor_split_dims_mapping is not None
assert len(tensor_split_dims_mapping) == len(shape)
p = hyperparams.Params()
p.Define('dtype', dtype, 'The weight data type.')
p.Define('shape', shape, 'The weight shape.')
p.Define('init', init, 'Initialization method.')
p.Define('collections', collections,
'Variable collections this weight belongs to.')
p.Define(
'device_mesh', device_mesh,
'A numpy.ndarray describing the topology of a device mesh to partition'
' this variable onto. Each element in the np.ndarray is the ID of a'
' device in the topology. device_mesh and tensor_split_dims_mapping below'
' together specifies how this weight tensor should be sharded across'
' different tpu cores. If None, this variable is not sharded.'
' Here are examples: np.array([0, 1, 2, 3, 4, 5, 6, 7]) which is a 1d'
' mesh with 8 devices, np.array([[0, 1, 2, 3], [4, 5, 6, 7]]) which is'
' 2d matrix of 8 devices.')
p.Define(
'tensor_split_dims_mapping', tensor_split_dims_mapping,
'A list of integers that map each tensor axis to the device mesh axis'
' along which it is sharded. Its length is the tensor rank, and'
' split_dims_mapping[i] is device mesh axis for tensor dimension i. Use'
' -1 for tensor dimensions that are not sharded. If the list is set to'
' None and a device_mesh is specified, the sharding will be treated as'
' replicated. Here is a concrete examples: '
' device_mesh=np.array([[0, 1, 2, 3] [4, 5, 6, 7]]), of shape [2, 4]'
' shape=[x, y, z], so this is a 3d variable.'
' tensor_split_dims_mapping=[-1, -1, 1], in this case, the third dim'
' of the variable is split along the second dim of the mesh. Each '
' split of the variable is of the shape [x, y, z/4].')
# The following two flags are used in Jax only.
p.Define(
'repeat_prefix', None,
'If not None, the full shape of this var is repeat_prefix+shape. '
'For example, if repeat_prefix=[16, 2], and shape=[512, 1024], then '
'real shape of variable is [16, 2, 512, 1024]. "repeat_prefix" is '
'often used if a layer is to be used in a recurrent loop, where '
'logically there are n sub-layers, but for performance/hbm usage '
'reasons we stack all the variables in creating those n-layers.')
p.Define('repeat_prefix_split_dims_mapping', None,
'Tensor split dims mapping for the repeat_prefix dims.')
return p
def FindNeeded(endpoints):
"""List names of tensors and operations required to compute endpoints."""
names_seen = set()
queue = []
for e in Flatten(endpoints):
if isinstance(e, tf.Operation):
queue.append(e)
else:
queue.append(e.op)
while queue:
op = queue.pop()
name = op.name
if name not in names_seen:
names_seen.add(name)
names_seen.update((o.name for o in op.outputs))
queue.extend(i.op for i in op.inputs)
queue.extend(op.control_inputs)
return names_seen
class _CollectionGetter:
"""Get graph local value from a defined collection."""
def __init__(self, key, default_factory):
self._key = key
self._default_factory = default_factory
def __call__(self):
collection = tf.get_collection(self._key)
if collection:
assert len(collection) == 1
return collection[0]
value = self._default_factory()
tf.add_to_collection(self._key, value)
return value
def SanitizeScopeKey(key):
"""Removes invalid symbols from name_scope keys."""
if key.startswith('_'):
key = key[1:]
return key.replace('[', '_').replace(']', '')
# Maintain a session for unit tests (initialized in test_utils.py).
_SESSION_SCOPE = ThreadLocalStack()
@contextlib.contextmanager
def UnitTestSessionScope(sess):
_SESSION_SCOPE.stack.append(sess)
try:
yield
finally:
_SESSION_SCOPE.stack.pop()
def GetUnitTestSession():
"""Get the current variable reuse setting."""
return _SESSION_SCOPE.stack[-1] if _SESSION_SCOPE.stack else None
# Global variable to control multitask variable reuse
# If False (default) the default tf.get_variable is used, that is:
# - Reusing scopes only allow getting existing variables
# - Non-reusing scopes only allow getting new variables
# With GetOpportunisticVariableReuse() == True:
# - Reusing scopes only allow getting existing variables, as usual
# - Non-reusing scopes reuse new variables or get new ones
_OPPORTUNISTIC_VARIABLE_REUSE = ThreadLocalStack()
@contextlib.contextmanager
def OpportunisticVariableReuseScope(enable_opportunistic_reuse=True):
_OPPORTUNISTIC_VARIABLE_REUSE.stack.append(enable_opportunistic_reuse)
try:
yield
finally:
_OPPORTUNISTIC_VARIABLE_REUSE.stack.pop()
def GetOpportunisticVariableReuse():
"""Get the current variable reuse setting."""
return (_OPPORTUNISTIC_VARIABLE_REUSE.stack[-1]
if _OPPORTUNISTIC_VARIABLE_REUSE.stack else False)
_VARIABLE_RENAME_RULES = ThreadLocalStack()
# Global variable to track task calling scope.
# Currently only used for TPU Embedding purposes as a TPUEmbeddingLayer
# may be shared across tasks and the calling task needs to be known
# for tracking embedding activations for backprop.
_TASK_CALL_SCOPE = ThreadLocalStack()
def TaskCallScopeName(task):
"""Get a unique string identifying a task."""
return f'{task.params.name}_{id(task)}'
@contextlib.contextmanager
def TaskCallScope(task):
_TASK_CALL_SCOPE.stack.append(TaskCallScopeName(task))
try:
yield
finally:
_TASK_CALL_SCOPE.stack.pop()
def GetTaskCallScope():
"""Get the current task call scope."""
return _TASK_CALL_SCOPE.stack[-1] if _TASK_CALL_SCOPE.stack else None
@contextlib.contextmanager
def VariableRenameScope(renames):
"""Append the renaming rules to the stack of renames.
Args:
renames: pairs of (regexp, new_name_format). If the regexp matches, the
new_name_format will be interpolated using the matched groups.
Yields:
scope in which the renaming rules are applied
"""
_VARIABLE_RENAME_RULES.stack.append(renames)
try:
yield
finally:
_VARIABLE_RENAME_RULES.stack.pop()
def GetVariableName(name):
"""Get variable name after application of all renaming rules.
Args:
name: untransformed variable name with scope_name prepended
Returns:
name possibly modified using renaming rules
"""
matched = False
new_name = name
for renames in _VARIABLE_RENAME_RULES.stack:
tf.logging.log_first_n(
tf.logging.WARN,
('Renaming variables is not supported in eager mode. '
'Please look into migrating away from variable renaming.'), 1)
for regexp, name_format in renames:
match = re.match(regexp, name)
if match:
if matched:
tf.logging.warning('Multiple matches for: %s', name)
matched = True
new_name = name_format % match.groups()
if new_name != name:
tf.logging.info("WARNING!!! Renaming variable '%s' to '%s'", name, new_name)
return new_name
_LIST_REGEX_DTYPE = ThreadLocalStack()
@contextlib.contextmanager
def VariableListDtypeRegexScope(list_regex_dtypes):
"""Append the list of (regex, dtype) to override the dtype.
Args:
list_regex_dtypes: pairs of (regexp, dtype). If the regexp matches, the data
type of the variable will be changed by the corresponding dtype.
Yields:
scope in which the list of (regex, dtype) is applied.
"""
_LIST_REGEX_DTYPE.stack.append(list_regex_dtypes)
try:
yield
finally:
_LIST_REGEX_DTYPE.stack.pop()
def FindDataType(var_name):
"""Find the data type for var_name.
Args:
var_name: A string, name of the variable.
Returns:
The dtype of the first matched regex with var_name, or None if no matching
found.
"""
for regex_dtypes in _LIST_REGEX_DTYPE.stack:
for regex, data_type in regex_dtypes:
if re.match(regex, var_name):
return data_type
return None
def GenerateSeedFromName(name):
"""Generate a random seed from a name string.
Args:
name: A string.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
md5 = hashlib.md5()
md5.update(six.ensure_binary(name))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
def MaybeGenerateSeedFromScope():
"""Generate a random seed from the current name of the scope.
If running in eager mode, this returns 0.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if not tf.executing_eagerly():
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
return 0
def GenerateSeedFromId(obj_id):
"""Generate a random seed from the id of an object.
If deterministic execution (i.e. unit test), generate the seed from a fixed
unique name instead.
Args:
obj_id: id(object).
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
with tf.name_scope(''):
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
md5 = hashlib.md5()
md5.update(np.int64(obj_id))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
_VARIABLE_SHAPE_PREFIXES = ThreadLocalStack()
def GetVarLeadingDimsAsCombinedLayers(var):
"""Gets the number of leading dimensions of `var` marked as combined layers.
Such dimensions represent variables from different layers stacked together,
e.g., in RepeatLayer, and optimizers (which have shape-dependant behaviors)
can adjust its behavior based on this information to match the behavior for
separate layer variables.
Args:
var: A variable.
Returns:
An integer representing the number of leading dimensions.
"""
try:
return var.op.get_attr('_num_leading_dims_for_combined_layers')
except ValueError:
return 0
except AttributeError:
# AttributeError: 'DistributedVarOp' object has no attribute 'get_attr'.
return 0
@contextlib.contextmanager
def VariableShapePrefixContext(shape_prefix):
"""Add a shape prefix to variable created by CreateVariable().
This new dimension will be marked as combined-layers. See also comments for
GetVarLeadingDimsAsCombinedLayers().
Args:
shape_prefix: a positive integer of shape prefix.
Yields:
None.
"""
assert shape_prefix > 0, ('%s' % shape_prefix)
_VARIABLE_SHAPE_PREFIXES.stack.append(shape_prefix)
try:
yield
finally:
_VARIABLE_SHAPE_PREFIXES.stack.pop()
def GetVariableShapePrefixes():
"""Return the list of shape prefixes for CreateVariable()."""
return _VARIABLE_SHAPE_PREFIXES.stack
def GetVariableNumLeadingDimsForCombinedLayersContext():
"""Return the number of leading combined-layers dims for CreateVariable()."""
return len(_VARIABLE_SHAPE_PREFIXES.stack)
def GetFanInFanOut(shape, prefix_dims_to_skip):
"""Returns (fan_in, fan_out) of a weight variable of the give shape."""
if not shape:
return None, None
if len(shape) < prefix_dims_to_skip:
raise ValueError(f'Variable shape is {shape} but prefix_dims_to_skip is '
f'{prefix_dims_to_skip}, larger than the shape rank.')
adjusted_shape = shape[prefix_dims_to_skip:]
if len(adjusted_shape) < 1:
return 1, 1
elif len(adjusted_shape) == 1:
# Following _compute_fans() from TF's init_ops.py.
return adjusted_shape[0], adjusted_shape[0]
else:
receptive_field_size = 1
for s in adjusted_shape[:-2]:
receptive_field_size *= s
fan_in = adjusted_shape[-2] * receptive_field_size
fan_out = adjusted_shape[-1] * receptive_field_size
return fan_in, fan_out
_VARIABLE_STORE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def VariableStore():
"""Keeps track of {variable_name: (variable, var_params)}.
When CreateVariable would result in a variable name that exists in the store,
the existing variable is returned, or an error is raised, depending on whether
the variable scope supports reuse.
This mimics the behavior of tf.compat.v1.get_variable() with regards to
variable reuse, while functioning correctly in TF2 eager context. However, it
only applies to variables created via CreateVariable.
When there are nested VariableStore contexts, they all provide the same
variable store object. That is, the scope of the variable store is the
outermost context.
Yields:
A dictionary representing the variable store.
"""
store = _VARIABLE_STORE_STACK.stack[-1] if _VARIABLE_STORE_STACK.stack else {}
_VARIABLE_STORE_STACK.stack.append(store)
try:
yield store
finally:
_VARIABLE_STORE_STACK.stack.pop()
def _GetVariableStore():
return (_VARIABLE_STORE_STACK.stack[-1]
if _VARIABLE_STORE_STACK.stack else None)
def _DefaultVariableCreator(**kwargs):
kwargs.pop('var_name')
kwargs.pop('var_params')
return tf.get_variable(**kwargs)
_VARIABLE_CREATOR_STACK = ThreadLocalStack()
def _GetVariableCreator():
fn = _DefaultVariableCreator
for wrapper in reversed(_VARIABLE_CREATOR_STACK.stack):
fn = functools.partial(wrapper, fn)
return fn
@contextlib.contextmanager
def VariableCreatorScope(variable_creator):
"""Yields a context around a variable_creator, used by `CreateVariable()`.
The function must have the following signature::
def variable_creator(next_creator, **kwargs)
The function may delegate variable creation to the next variable creator, or
return its own tf.Variable.
This differs from tf.variable_creator_scope in that tf.variable_creator_scope
modifies a tf.Variable() call while this modifies a tf.get_variable() call. As
the code is migrated to TF2 and tf.get_variable() is deprecated, this may be
upgraded to using tf.variable_creator_scope instead.
This differs from tf.variable_scope(custom_getter=variable_creator) in that
the kwargs passed can be manipulated.
Variable creators are resolved from the outermost towards the innermost.
The innermost variable creator function is tf.get_variable.
The passed in kwargs must conform to what tf.get_variable accepts, with the
addition of `var_name` and `var_params`.
Args:
variable_creator: A variable creator function.
"""
_VARIABLE_CREATOR_STACK.stack.append(variable_creator)
try:
yield
finally:
_VARIABLE_CREATOR_STACK.stack.pop()
def PlaceOnTpuCore(core_id):
"""Returns a VariableCreatorScope that places variables on a given tpu core.
Only applies when running with TPUs.
Does not yet properly support model parallelism.
Args:
core_id: The tpu core id.
"""
def Creator(next_creator, **kwargs):
cluster = cluster_factory.Current()
if use_tpu():
device = cluster.WorkerDeviceInModelSplit(core_id)
elif (
tpu_compat() and
cluster.params.job in ('controller', 'trainer_client', 'executor_tpu')):
# The job is running in a fleet that uses tpu, but does not itself have
# access to the tpu, e.g. controller job. In this case, the returned
# device needs to be the cpu device on the tpu host for the given core.
# FIXME: the current implementation is wrong for large values of core_id.
device = cluster.ListDevices(cluster.params.worker)[0, 0]
else:
device = ''
with tf.device(device):
return next_creator(**kwargs)
return VariableCreatorScope(Creator)
# Variable creators.
def MaybeReuseFromVariableStore(next_creator, **kwargs):
"""Variable creator that attempts to reuse variables from variable store."""
var_name = kwargs['var_name']
p = kwargs['var_params']
store = _GetVariableStore()
if store is not None and var_name in store:
if tf.get_variable_scope().reuse:
var, cached_p = store[var_name]
tf.logging.info('Reusing var %s', var.name)
assert cached_p == p.ToText(), (
'Cached config:\n %s vs new config:\n %s' % (cached_p, p.ToText()))
return var
var = next_creator(**kwargs)
tf.logging.info('Creating var %s shape=%s on device %s', var.name, var.shape,
var.device)
for col in p.collections:
tf.add_to_collection(col, var)
if store is not None:
store[var_name] = (var, p.ToText())
return var
def MaybePinVarsToCpu(next_creator, **kwargs):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return next_creator(**kwargs)
return next_creator(**kwargs)
def MaybeOpportunisticVariableReuse(next_creator, **kwargs):
if GetOpportunisticVariableReuse():
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
return next_creator(**kwargs)
return next_creator(**kwargs)
# TODO(yonghui): Add support for partitioned Variables.
def CreateVariable(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES). Note that specifying a collections
argument in `params` does not override this collection; the caller must
set this field explicitly in the call to CreateVariable().
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
if use_stateless_vars_init():
return _CreateVariableStateless(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
else:
return _CreateVariableStateful(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
def _CreateVariableStateful(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateful RNGs according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
if seed is None:
if default_seed is not None:
seed = default_seed
else:
# We are not given a per-variable random seed. We use hash of
# variable name as a stable random seed.
seed = GenerateSeedFromName(var_name)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
# TODO(b/172827074): we do not natively support var initialization for
# int8 type except for constant initialization.
# NOTE: For int8, we initialize by scaling float32 random values to integer.
if init_dtype == tf.int8:
init_dtype = tf.float32
v_init = _CreateVarInitStateful(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
def ComplexWrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
# A more complex alternative may be to use the init function for
# magnitudes and uniform random for phases instead.
shape = [2] + shape
value = init(shape, init_dtype, partition_info)
return tf.complex(value[0], value[1])
return _Wrapper
v_init = ComplexWrapper(v_init)
if var_dtype == tf.int8:
def FloatToInt8Wrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
value = init(shape, init_dtype, partition_info)
scale = tf.math.maximum(
tf.math.reduce_min(value) / -127,
tf.math.reduce_max(value) / 127)
value = tf.divide(value, scale)
return tf.cast(value, tf.int8)
return _Wrapper
v_init = FloatToInt8Wrapper(v_init)
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybePinVarsToCpu, MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
if method == 'custom_constant':
call_shape = None
else:
call_shape = GetVariableShapePrefixes() + list(shape)
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=call_shape,
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _CreateVariableStateless(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateless RNGs according to `params`.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
user_seed = seed if seed is not None else default_seed
seed = _GenerateStatelessRngSeed(var_name, user_seed)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
v_init = _CreateVarInitStateless(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
raise TypeError(
'Stateless variable initialization does not support tf.complex64.')
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=GetVariableShapePrefixes() + list(shape),
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _RandomXavierUniformInitializer(method, scale, seed):
"""Creates a random Xavier uniform initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
return XavierUniform
def _CreateVarInitStateful(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateful RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = init_ops.random_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = init_ops.random_uniform_initializer(
minval=-scale, maxval=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_positive']:
v_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
elif method == 'category':
uniform_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
v_init = lambda *args, **kwargs: tf.floor(uniform_init(*args, **kwargs))
elif method in ['uniform_unit_scaling']:
v_init = init_ops.uniform_unit_scaling_initializer(
factor=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = tf.variance_scaling_initializer(
scale=scale,
mode='fan_avg',
distribution='uniform',
seed=seed,
dtype=init_dtype)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = init_ops.truncated_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError(
'\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
v_init = XavierUniform
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = init_ops.random_uniform_initializer(
minval=-bound, maxval=bound, seed=seed, dtype=init_dtype)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type `%s` not supported.' % method
return v_init
def _GenerateStatelessRngSeed(name, seed):
"""Generates a 2-tuple seed for a stateless variable initializer.
We want to ensure that different variables end up with different random values
even when they are passed the same seed and shape. To this aim, this function
generates a pseudo-unique seed by hashing the variable name and mapping it
into a scalar seed. More specifically, the returned value is a 2-tuple of
tf.int32 scalar, where the first element is the user-provided seed and the
second element is obtained by hashing the variable name.
Args:
name: The variable name for which to generate a stateless-like seed.
seed: The user-specified scalar seed.
Returns:
A 2-tuple seed of tf.int32 values (for TPU compatibility).
"""
seed0 = seed or 0
seed1 = GenerateSeedFromName(name)
return tf.constant([seed0, seed1], dtype=tf.int32)
def _DeterministicRandomNormalInitializer(seed, mean, stddev):
"""Creates a random normal initializer."""
def DeterministicNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicNormal
def _DeterministicRandomUniformInitializer(seed, minval, maxval):
"""Creates a random uniform initializer."""
def DeterministicUniform(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=minval, maxval=maxval, dtype=dtype)
return DeterministicUniform
def _DeterministicRandomTruncatedNormalInitializer(seed, mean, stddev):
"""Creates a random truncated normal initializer."""
def DeterministicTruncatedNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicTruncatedNormal
def _DeterministicRandomUniformUnitScalingInitializer(seed, factor):
"""Creates a random uniform unit scaling initializer."""
def DeterministicUniformUnitScaling(shape, dtype, partition_info):
# The following logic is originally from (UniformUnitScaling.__call__())
# in TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
input_size = 1.0
# Estimating input size is not possible to do perfectly, but we try.
# The estimate, obtained by multiplying all dimensions but the last one,
# is the right thing for matrix multiply and convolutions (see above).
for dim in scale_shape[:-1]:
input_size *= float(dim)
# Avoid errors when initializing zero-size tensors.
input_size = max(input_size, 1.0)
maxval = math.sqrt(3 / input_size) * factor
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-maxval, maxval=maxval, dtype=dtype)
return DeterministicUniformUnitScaling
def _DeterministicRandomVarianceScalingInitializer(scale, mode, distribution,
seed):
"""Creates a variance scaling initializer."""
if scale <= 0.:
raise ValueError('`scale` must be positive float.')
if mode not in {'fan_in', 'fan_out', 'fan_avg'}:
raise ValueError('Invalid `mode` argument:', mode)
distribution = distribution.lower()
if distribution not in {
'normal', 'uniform', 'truncated_normal', 'untruncated_normal'
}:
raise ValueError('Invalid `distribution` argument:', distribution)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def DeterministicVarianceScaling(shape, dtype, partition_info):
# This is originally from TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
# Handle special case of empty list as shape, since fan_in and fan_out
# are numerically added below. Without this, GetFanInFanOut() would
# return None, None instead.
if isinstance(scale_shape, (list, tuple)) and not scale_shape:
fan_in, fan_out = 1, 1
else:
fan_in, fan_out = GetFanInFanOut(scale_shape, combined_layers_dims)
if mode == 'fan_in':
scale_inner = scale / max(1., fan_in)
elif mode == 'fan_out':
scale_inner = scale / max(1., fan_out)
else:
scale_inner = scale / max(1., (fan_in + fan_out) / 2.)
if distribution == 'normal' or distribution == 'truncated_normal':
# constant taken from scipy.stats.truncnorm.std(
# a=-2, b=2, loc=0., scale=1.)
stddev = math.sqrt(scale_inner) / .87962566103423978
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
elif distribution == 'untruncated_normal':
stddev = math.sqrt(scale_inner)
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
else:
limit = math.sqrt(3.0 * scale_inner)
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-limit, maxval=limit, dtype=dtype)
return DeterministicVarianceScaling
def _DeterministicRandomXavierUniformInitializer(method, scale, seed):
"""Creates a variance scaling initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * stateless_random_ops.stateless_random_uniform(
shape, seed, -limit, limit, dtype)
return XavierUniform
def _CreateVarInitStateless(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateless RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = _DeterministicRandomNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-scale, maxval=scale)
elif method in ['uniform_positive']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=0., maxval=scale)
elif method in ['uniform_unit_scaling']:
v_init = _DeterministicRandomUniformUnitScalingInitializer(
seed=seed, factor=scale)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = _DeterministicRandomVarianceScalingInitializer(
scale=scale, mode='fan_avg', distribution='uniform', seed=seed)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = _DeterministicRandomTruncatedNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
v_init = _DeterministicRandomXavierUniformInitializer(method, scale, seed)
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-bound, maxval=bound)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type %s not supported.' % method
return v_init
_global_variable_scope = None
def GetGlobalVariableScope():
"""Gets the global variable scope (as if no variable_scope has been set).
Returns:
The VariableScope corresponding to as if no tf.variable_scope is in effect.
"""
if not _global_variable_scope:
# Each thread gets its own default global variable scope, and we take
# advantage of that in order to get a top-level scope. This avoids the
# need to call tf.get_variable_scope() at the module level, which allows
# this module to be imported without modifying global state (i.e. creating
# the default graph). It is important to not mutate the global state at
# module load time, because it let's us flip flags after import that affect
# core TensorFlow behavior.
def Initialize():
global _global_variable_scope
_global_variable_scope = tf.get_variable_scope()
t = threading.Thread(target=Initialize)
t.start()
t.join()
return _global_variable_scope
_GLOBAL_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GlobalStepContext(global_step_tensor):
_GLOBAL_STEP_STACK.stack.append(global_step_tensor)
try:
yield
finally:
_GLOBAL_STEP_STACK.stack.pop()
def GetGlobalStep():
"""Return the global_step."""
if _GLOBAL_STEP_STACK.stack:
return _GLOBAL_STEP_STACK.stack[-1]
return tf.train.get_global_step()
def GetOrCreateGlobalStepVar():
"""Return the global_step variable, creating it if it does not exist.
Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient.
Returns:
The global_step variable, or a new created one if it does not exist.
"""
with tf.variable_scope(GetGlobalVariableScope(), use_resource=True):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return tf.train.get_or_create_global_step()
else:
return tf.train.get_or_create_global_step()
def LogMultiLines(label, lines):
if not isinstance(lines, (list, tuple)):
lines = lines.split('\n')
for line in lines:
tf.logging.info('%s: %s', label, line)
def _LogPlacement(label, theta, copy):
"""Logs theta and its copy's device placement."""
def GetDevices(m):
"""Flatten a `.NestedMap` m and extracts each value's device."""
return [x.device for x in m.Flatten()]
tf.logging.info('=== %s ===', label)
LogMultiLines(
label,
theta.Pack([('%s -> %s' % (x[0], x[1]))
for x in zip(GetDevices(theta), GetDevices(copy))
]).DebugString())
tf.logging.info('==========')
def CreateLocalTheta(theta, device_list=None, label=None):
"""Creates local copy of theta and shards across devices device list.
Leaves variables intact.
Args:
theta: a `.NestedMap` of variables.
device_list: list of devices to shard across. If None, defaults to a list
[''].
label: Logging label.
Returns:
A `.NestedMap` of identity() wrapped theta
"""
class AddIdentity:
"""Helper class."""
def __init__(self, device_list):
self._list = device_list if device_list else ['']
self._index = 0
def __call__(self, x):
if isinstance(x, tf.Variable):
return x
with tf.device(self._list[self._index % len(self._list)]):
self._index += 1
return tf.identity(x)
copy = theta.Transform(AddIdentity(device_list))
_LogPlacement(label, theta, copy)
return copy
def _GetVarsToLoad(all_vars, variable_loading_rules, var_ignore_rules,
ckpt_path):
"""Determines variables to load and their names in checkpoint."""
# This list contains mappings from var names as they appear in the checkpoint
# to the vars in our model they correspond to.
unused_rules = {
regexp: name_format for regexp, name_format in variable_loading_rules
}
vars_to_load = []
for model_var in all_vars:
loaded = False
for regexp, name_format in variable_loading_rules:
match = re.match(regexp, model_var.name)
# Skip if var doesn't match the loading rules, or if it should be ignored.
if not match:
tf.logging.debug('Loading rules do not match %s.', model_var.name)
continue
elif any(re.match(r, model_var.name) for r in var_ignore_rules):
tf.logging.debug('Ignoring %s from loading.', model_var.name)
continue
checkpoint_var_name = name_format % match.groups()
if checkpoint_var_name.endswith(':0'):
checkpoint_var_name = checkpoint_var_name[:-2]
tf.logging.info('Loading %s from %s with regexp: %s', model_var.name,
checkpoint_var_name, regexp)
vars_to_load.append((checkpoint_var_name, model_var))
unused_rules.pop(regexp, None)
loaded = True
break
if not loaded:
tf.logging.info(
'Not loading model variable %s from %s as it does not match any rules'
' or matches ignored', model_var.name, ckpt_path)
for regexp, name_format in unused_rules.items():
tf.logging.warning(f'User provided rule matched no variables: ({regexp}, '
f'{name_format})')
return vars_to_load
def OverrideVarsFromCheckpoint(all_vars, checkpoint_path,
variable_loading_rules, var_ignore_rules):
"""Add TF graph ops to override variables from a provided checkpoint.
Args:
all_vars: List of all the parameters in the model.
checkpoint_path: A path to the checkpoints of a pretrained model.
variable_loading_rules: A list of tuples of strings defining (regex to match
parameter names in the model to override, format string to determine the
corresponding var in the checkpoint).
var_ignore_rules: A list consisting of a list of regexes to match parameter
names in the model which should not be overridden, even if they match
those in the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from the provided checkpoint.
"""
vars_to_load = _GetVarsToLoad(all_vars, variable_loading_rules,
var_ignore_rules, checkpoint_path)
if not vars_to_load:
all_rules_text = '\n'.join(
[f'{k} --> {v}' for k, v in variable_loading_rules])
raise ValueError(f'Variable loading rules {all_rules_text} '
f'did not match any of {len(all_vars)} vars.')
load_var_names = '\n'.join(sorted([v.name for _, v in vars_to_load]))
tf.logging.info(f'Overriding {len(vars_to_load)} vars from '
f'{checkpoint_path}:\n{load_var_names}')
savers = []
while vars_to_load:
# When restoring, it's possible the same value in the checkpoint
# can be restored to multiple variables (e.g. during
# distillation). However, tf.train.Saver, since it's used for
# both saving and restoring, requires the name in the checkpoint
# to be unique for each variable. So, we call it multiple times
# with a unique set of names each time.
unique_vars_to_load = {}
remaining_vars_to_load = []
for k, v in vars_to_load:
if k not in unique_vars_to_load:
unique_vars_to_load[k] = v
else:
remaining_vars_to_load.append((k, v))
savers.append(tf.train.Saver(var_list=unique_vars_to_load, sharded=True))
vars_to_load = remaining_vars_to_load
def _Restore(sess):
for saver in savers:
saver.restore(sess, checkpoint_path)
return _Restore
def OverrideVarsFromCheckpoints(all_vars, ckpts_loading_rules):
"""Add TF graph ops to override model variables from checkpoints.
Args:
all_vars: List of all the parameters in the model.
ckpts_loading_rules: A dictionary of checkpoint path: loading rules.
Checkpoint path must be a path to a pretrained model, and loading rules is
expected to be a tuple of two lists. The first consisting of tuples of
strings defining (regex to match parameter names in the model to override,
format string to determine the corresponding var in the checkpoint), and
the second list consisting of a list of regexes to match parameter names
in the model which should not be overridden, even if they match those in
the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from checkpoint and return a list of overwritten variables.
Raises:
ValueError: if colliding vars exist or loading rules is not a list.
"""
if len(ckpts_loading_rules) > 1:
tf.logging.info('Overriding vars from multiple checkpoints.')
var_refs_overridden = set()
var_names_overridden = set()
restore_fns = []
for ckpt_path, loading_rules in ckpts_loading_rules.items():
tf.logging.info('Overriding vars from checkpoint: %s', ckpt_path)
if not isinstance(loading_rules, tuple):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
if len(loading_rules) != 2 or not all(
isinstance(l, list) for l in loading_rules):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
# Filter the model variables to be overridden.
to_load_vars = _GetVarsToLoad(all_vars, loading_rules[0], loading_rules[1],
ckpt_path)
var_refs_to_override = [var[1].experimental_ref() for var in to_load_vars]
var_names_to_override = [var[1].name for var in to_load_vars]
overlap_refs = set.intersection(var_refs_overridden, var_refs_to_override)
if overlap_refs:
raise ValueError('Colliding variables to override: %s' % overlap_refs)
restore_fns.append(
OverrideVarsFromCheckpoint(all_vars, ckpt_path, loading_rules[0],
loading_rules[1]))
var_refs_overridden.update(var_refs_to_override)
var_names_overridden.update(var_names_to_override)
tf.logging.info('Model variables overridden: %s', var_refs_overridden)
def _Restore(sess):
for fn in restore_fns:
fn(sess)
return var_names_overridden
return _Restore
def ComputeGradientsSimple(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
activations_grad=None):
"""Compute gradients."""
tape = _GRADIENT_TAPE_STACK.stack[-1] if _GRADIENT_TAPE_STACK.stack else None
if IsEagerMode() and tape:
tf.logging.info('ComputeGradientsSimple: using gradient tape.')
if activations_grad is not None:
raise ValueError('GradientTape does not accept gradient input values.')
if grad_aggregation_method or colocate_gradients_with_ops or gate_gradients:
tf.logging.warning(
'When GradientTape is used, these field will be ignored: '
f'grad_aggregation_method ({grad_aggregation_method}), '
f'colocate_gradients_with_ops ({colocate_gradients_with_ops}), '
f'gate_gradients ({gate_gradients}).')
return tape.gradient(
loss_or_activations,
all_vars,
unconnected_gradients=tf.UnconnectedGradients.ZERO)
return tf.gradients(
loss_or_activations,
all_vars,
grad_ys=activations_grad,
aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients)
def _ComputeGradientsTpu(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients for local loss across whole TPU cluster.
This implementation specializes for the case where weight params maybe used
for different number of times in the forward computation, so that gradients
should be normalized by the actual number of times they are being computed.
TODO(yonghui): Maybe merge this implementation with the _ComputeGradientsTpu
one.
Args:
loss_or_activations: The loss or activations to backprop from.
all_vars: Vars with respect to which gradients are to be computed.
grad_aggregation_method: aggregation method to use when calling
tf.gradients.
colocate_gradients_with_ops: boolean, whether or not to colocate gradient op
with the original op.
gate_gradients: boolean, flag to be passed to tf.gradients.
skip_zero_gradients: whether to skip zero gradients during aggregation.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This helps reducing the number of gradient all-reduces
when doing gradient accumulation, which does gradient cross replica sum
only every k steps in a tf.cond. Currently this works only when
skip_zero_gradients is None.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
Gradients to be passed back. If tpu_embedding_activations is set, their
gradients will be placed at the end.
Raises:
ValueError: upon invalid arguments.
"""
if is_activations:
assert activations_grad is not None
if not skip_zero_gradients and not is_activations:
# Scale the loss to account for the full batch size.
shards = tpu_function.get_tpu_context().number_of_shards
assert shards
loss_or_activations *= tf.constant(
1.0 / shards, dtype=loss_or_activations.dtype)
else:
assert not tpu_embedding_activations, (
'Gradient computation for tpu embedding activations requires proper '
'loss scaling, and so is not compatible with skip_zero_gradients and '
'is_activations.')
# Computes the gradients.
# Sum the grads so that we can compute statistics across the whole batch.
all_grads = ComputeGradientsSimple(
loss_or_activations=loss_or_activations,
all_vars=all_vars +
(tpu_embedding_activations if tpu_embedding_activations else []),
grad_aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients,
activations_grad=activations_grad)
if tpu_embedding_activations:
# Note we don't need to aggregate TPU embedding gradients below.
tpu_embedding_grads = all_grads[len(all_vars):]
all_grads = all_grads[:len(all_vars)]
else:
tpu_embedding_grads = []
# NOTE: We can't use tpu_optimizer.CrossShardOptimizer since
# we need to scale the grads *after* the cross_replica_sum to
# match GPU version!
# TODO(cwhipkey): should we do something different here? - we could do
# some operations on the gradients before the aggregation (see comments in
# tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py - see compute_gradients -
# for some more details).
aggregated_grads = []
for g in all_grads:
if g is None:
aggregated_grads.append(None)
continue
if use_bf16_gradients_ar:
g = tf.cast(g, tf.bfloat16)
with tf.ops.colocate_with(g):
if skip_zero_gradients is None:
# loss is already scaled by 1/shards.
if defer_crs_to_apply_grad:
normalized_g = tf.convert_to_tensor(g)
else:
normalized_g = tf.tpu.cross_replica_sum(g)
else:
# Compute the cross-replica mean of 'g', skipping zero gradients.
# Q(yonghui): Is there a better way to detect a non-zero gradient?
# Note(yonghui): gradient of a weight can be zero if that
# weight is not used in the forward computation, e.g. as in
# switchable layers in neural architecture search, pruned by channel
# mask, or sparsified.
if skip_zero_gradients == 'weight':
# Same shape as 'g'.
g_is_non_zero = tf.cast(tf.math.abs(g) > 1e-8, g.dtype)
elif skip_zero_gradients == 'variable':
# A variable-wide 0/1 scalar.
g_is_non_zero = tf.cast(
tf.reduce_sum(tf.math.abs(g)) > 1e-24, g.dtype)
else:
raise ValueError('Unknown skip_zero_gradients: %s' %
skip_zero_gradients)
num_updates = tf.maximum(tf.tpu.cross_replica_sum(g_is_non_zero), 1.0)
normalized_g = tf.tpu.cross_replica_sum(g) / num_updates
aggregated_grads.append(normalized_g)
return aggregated_grads + tpu_embedding_grads
class _VarGrad(typing.NamedTuple):
var: tf.Tensor
grad: Union[tf.Tensor, tf.IndexedSlices]
scale: Optional[tf.Tensor] = None
class VarGrad:
"""A class that holds a variable and a gradient.
This does not inherit from namedtuple so that tf.nest operations do not
recurse into it.
"""
def __init__(self, *args, **kwargs):
self._var_grad = _VarGrad(*args, **kwargs)
def __getitem__(self, key):
return self._var_grad[key]
def __getattr__(self, key):
return getattr(self._var_grad, key)
def __iter__(self):
if self._var_grad.scale is None:
return iter((self._var_grad.var, self._var_grad.grad))
return iter(self._var_grad)
def __repr__(self):
return repr(self._var_grad)
def SkipNoneGradients(var_grads):
"""Removes pairs whose grad is None."""
for key, (_, g) in var_grads.FlattenItems():
if g is None:
tf.logging.info('ComputeGradients drops %s', key)
return var_grads.Filter(lambda var_grad: var_grad.grad is not None)
def ComputeGradients(
loss_or_activations,
vmap,
grad_aggregation_method=tf.AggregationMethod.EXPERIMENTAL_TREE,
colocate_gradients_with_ops=True,
gate_gradients=False,
compute_gradients_fn=None,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
skip_none_gradients=True,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients of variables in vmap w.r.t loss.
Args:
loss_or_activations: either the loss, which is a scalar tensor, or
activations, which could be a tensor or a list of tensors.
vmap: A `.NestedMap` of variables.
grad_aggregation_method: Specifies the method used to combine gradient
terms. Accepted values are constants defined in the class
AggregationMethod.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
gate_gradients: If True, add a tuple around the gradients returned for an
operations. This avoids some race conditions.
compute_gradients_fn: Function to use to compute gradients. If None, use
default. compute_gradients_fn should have the same signature as this
function, but without the last argument.
skip_zero_gradients: Whether to skip aggregating zero gradients. This helps
in case where some weights may not be used in forward computation, e.g.,
sparsely activated networks or switchable layers in neural architectural
search. Only applicable on TPU.
Possible values are:
- None: do not skip zero gradients;
- `variable`: skip if the entire variable's gradients are almost zero;
reduce_sum(abs(grads)) < 1e-8.
- `weight`: skip if the individual weight's gradients are almost zero:
abs(grad) < 1e-8.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce. This applies to TPU only.
skip_none_gradients: Whether to skip gradients that are None.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This applies to TPU only.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
var_grad - a `.NestedMap` of VarGrad. You can view
var_grad as an ordered list of (key, (var, grad)) tuples. Every
key of var_grad exists in vmap. Every variable in vmap that
contributes to loss must exist in var_grad. Every var of var_grad
must exist in vmap. grad is the corresponding gradient computed
for var. grad is guaranteed to be not None.
If tpu_embedding_activations is set, a sub `.NestedMap` named
tpu_embedding_var_grads will be used to store the VarGrads for the
activations. In this case, key is the feature name, and var in the VarGrad
is the activation tensor (not a real variable).
"""
if not is_activations:
loss_or_activations = HasRank(loss_or_activations, 0)
if not tpu_embedding_activations:
tpu_embedding_activations = NestedMap()
assert isinstance(tpu_embedding_activations, NestedMap)
assert isinstance(vmap, NestedMap)
assert skip_zero_gradients in (None, 'variable', 'weight')
# Uniqify and remove None.
filtered_vmap = vmap.Filter(_Unique())
assert filtered_vmap is not None
# Filter out variables not contributing to 'loss_or_activations'.
# This doesn't work if the training loop is wrapped inside a tf.function,
# since all variables will be lifted out and trainable_variables will be
# empty. In that case we skip the check.
trainable_variables = set(tf.trainable_variables())
if trainable_variables:
def Needed(v):
if isinstance(v, tf.Variable):
if v not in trainable_variables:
# Skip non-trainable variables. Otherwise,
# tf.Optimizer.apply_gradients throws up an exception instead
# of skipping the update.
return False
return True
filtered_vmap = filtered_vmap.Filter(Needed)
assert filtered_vmap is not None
filtered_vlist = filtered_vmap.Flatten()
# Use caller-supplied gradient function if supplied.
if compute_gradients_fn is not None:
assert not tpu_embedding_activations
take_grad = compute_gradients_fn
else:
# tpu vs non-tpu is slightly different.
if use_tpu():
take_grad = functools.partial(
_ComputeGradientsTpu,
skip_zero_gradients=skip_zero_gradients,
use_bf16_gradients_ar=use_bf16_gradients_ar,
defer_crs_to_apply_grad=defer_crs_to_apply_grad,
activations_grad=activations_grad,
is_activations=is_activations,
tpu_embedding_activations=tpu_embedding_activations.Flatten())
else:
assert not tpu_embedding_activations
take_grad = ComputeGradientsSimple
grads = take_grad(loss_or_activations, filtered_vlist,
grad_aggregation_method, colocate_gradients_with_ops,
gate_gradients)
if tpu_embedding_activations:
tpu_embedding_grads = grads[len(filtered_vlist):]
grads = grads[:len(filtered_vlist)]
else:
tpu_embedding_grads = None
# Formulate pairs of (var, grad) and pack them into the same
# structure as filtered_vmap.
var_grads = filtered_vmap.Pack(
[VarGrad(v, g) for v, g in zip(filtered_vlist, grads)])
if skip_none_gradients:
var_grads = SkipNoneGradients(var_grads)
if tpu_embedding_grads:
# Create VarGrads for TPU embedding activations in a dedicated sub map.
assert 'tpu_embedding_var_grads' not in var_grads
tpu_embedding_activation_list = tpu_embedding_activations.Flatten()
tpu_embedding_var_grads = [
VarGrad(v, g)
for v, g in zip(tpu_embedding_activation_list, tpu_embedding_grads)
]
tpu_embedding_var_grads = tpu_embedding_activations.Pack(
tpu_embedding_var_grads)
# Replace None gradients with zeros, since TPU embedding expect all
# activations to have gradients.
def _NoneToZeros(key, var_grad):
if var_grad.grad is None:
tf.logging.warning(
f'TPU embedding gradient for feature {key} is None. Replacing with '
'zeros.')
return VarGrad(var_grad.var, tf.zeros_like(var_grad.var))
return var_grad
var_grads.tpu_embedding_var_grads = (
tpu_embedding_var_grads.TransformWithKey(_NoneToZeros))
return var_grads
def MaskGradients(var_grad, grad_mask):
"""Computes gradients of non-masked variables in vmap w.r.t loss.
Args:
var_grad: A `.NestedMap` of (variable, gradient)
grad_mask: A dict of (variable name, mask).
Returns:
var_grad - a `.NestedMap` of (variable, mask * gradient).
"""
def ApplyMask(entry):
var, grad = entry
mask = grad_mask[var.name]
if isinstance(grad, tf.IndexedSlices):
return VarGrad(var, tf.IndexedSlices(grad.values * mask, grad.indices))
else:
return VarGrad(var, grad * mask)
return var_grad.Transform(ApplyMask)
def ApplyGradMultiplier(vs_gs, grad_scale=None):
"""Scale gradients by grad_scale on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
grad_scale: If None, each vs_gs entry has the scale. Otherwise, grad_scale
applies to every entry.
Returns:
A `.NestedMap` of (variable, gradient * grad_scale). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ScaleOrZero(var: tf.Tensor, grad: tf.Tensor,
scale: tf.Tensor) -> tf.Tensor:
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.where(
tf.equal(scale, 0.), tf.zeros_like(grad),
tf.cast(scale, grad.dtype) * grad)
def Scale(item: VarGrad) -> VarGrad:
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
if grad_scale is None:
scale = item.scale
else:
scale = grad_scale
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ScaleOrZero(var, grad.values, scale), grad.indices,
grad.dense_shape)
else:
grad = ScaleOrZero(var, grad, scale)
return VarGrad(var, grad)
return vs_gs.Transform(Scale)
def HasNanOrInf(x):
if isinstance(x, tf.IndexedSlices):
x = x.values
with tf.device(x.device):
if x.dtype.is_complex:
return tf.reduce_any(
[HasNanOrInf(tf.math.real(x)),
HasNanOrInf(tf.math.imag(x))])
return tf.reduce_any(
tf.math.logical_or(tf.math.is_nan(x), tf.math.is_inf(x)))
def HasNanOrInfGradient(var_grads):
"""Returns a bool tensor to indicate if `var_grads` contains NaNs or Infs.
Args:
var_grads: A `.NestedMap` with (var, grad) tuple as the map value.
Returns:
A bool scalar tensor to indicate if the `var_grads` contains NaNs or Infs.
"""
return tf.reduce_any([HasNanOrInf(g) for (_, g) in var_grads.Flatten()])
def ApplyGradNormClipping(vs_gs, norm=1.0):
"""Clip gradients to norm on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
norm: Each tensor's gradient will be scaled down to have a maximum L2-norm
value of `norm`.
Returns:
A `.NestedMap` of VarGrad(variable, scaled_gradient). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ClipByNorm(var, grad, norm):
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.clip_by_norm(grad, norm)
def Clip(item):
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ClipByNorm(var, grad.values, norm), grad.indices, grad.dense_shape)
else:
grad = ClipByNorm(var, grad, norm)
return VarGrad(var, grad)
return vs_gs.Transform(Clip)
SKIP_LP_REGULARIZATION = '__lingvo_skip_lp_regularization'
def AdjustGradientsWithLpLoss(var_grads, lp_regularizer_weight, p=2.0):
"""Adjusts the map of (var, grad) with Lp regularization, where p=1.0 or 2.0.
Args:
var_grads: a `.NestedMap` or list of (variable, gradient).
lp_regularizer_weight: Lp regularization weight.
p: For now we support 1.0 or 2.0.
Returns:
A tuple (lp_loss, var_grads).
- lp_loss: A scalar. The lp loss.
- var_grads: a `.NestedMap` or list of (variable, gradient) regulated by Lp.
"""
# TODO(yuancao): For now we support p=1 or 2, but this can be extended to
# lp-norm in general.
assert p in [2.0, 1.0], 'For now we only support L1/L2 regularization.'
def GetVar(item):
var, grad = item
if isinstance(grad, tf.IndexedSlices):
with tf.device(var.device):
ids = HasRank(grad.indices, 1)
uniq_ids = tf.unique(ids).y
return tf.gather(var, uniq_ids)
else:
return var
def ShouldAdjust(v):
return not _VarInCollection(v, tf.get_collection(SKIP_LP_REGULARIZATION))
filtered_var_grads = [
var_grad for var_grad in Flatten(var_grads) if ShouldAdjust(var_grad.var)
]
filtered_vars = Transform(GetVar, filtered_var_grads)
for v in filtered_vars:
tf.logging.info('AdjustGradientsWithLpLoss: %s', v.name)
if p == 2.0:
lp_loss = 0.5 * lp_regularizer_weight * SumSquared(filtered_vars)
elif p == 1.0:
lp_loss = lp_regularizer_weight * SumAbs(filtered_vars)
def LpGrad(var_grad):
"""Adjusts item's grad w/ Lp loss term."""
var, grad = var_grad
if isinstance(grad, tf.IndexedSlices):
# Question(rpang): do we apply Lp loss here even if 'var' is in
# SKIP_LP_REGULARIZATION?
#
# Note: IndexedSlces appears for embedding lookups.
# Embedding lookup ids can have duplicate. For duplicated ids, we
# only want to consider once for each ids.
with tf.device(var.device):
emb = HasRank(var, 2)
vocab_size = tf.shape(emb)[0]
ids = HasRank(grad.indices, 1)
values = tf.gather(emb, ids) # [#ids, dims]
with tf.device(grad.device):
# Counts is a vector of size vocab_size. counts[i] is i-th words
# occurrences in 'ids'.
counts = tf.math.unsorted_segment_sum(
tf.ones_like(ids, dtype=values.dtype), ids, vocab_size)
# Gradients for duplicated ids will be summed when they get
# applied, and hence we account for that by first dividing
# gradient resulting from lp loss by how many times the id is
# duplicated.
#
# For each id in 'ids', we know counts[id] is non-zero,
# hence, it's always safe to take reciprocal.
weights = tf.math.reciprocal(tf.gather(counts, ids))
weights = tf.expand_dims(weights, -1) # [#ids, 1]
if p == 2.0:
grad_v = values
elif p == 1.0:
grad_v = tf.sign(values)
delta = lp_regularizer_weight * weights * grad_v
grad = tf.IndexedSlices(grad.values + delta, ids)
elif not _VarInCollection(var, tf.get_collection(SKIP_LP_REGULARIZATION)):
with tf.device(var.device):
if p == 2.0:
grad_v = var
elif p == 1.0:
grad_v = tf.sign(var)
delta = lp_regularizer_weight * grad_v
with tf.device(grad.device):
grad += delta
return VarGrad(var, grad)
return lp_loss, Transform(LpGrad, var_grads)
def SplitRecursively(x, num_splits, axis=-1):
"""Splits Tensors in 'x' recursively.
Args:
x: a Tensor, or a list or NestMap containing Tensors to split.
num_splits: number of splits per Tensor.
axis: the split axis.
Returns:
A list of split values of length 'num_splits'.
- If 'x' is a Tensor, a list of split Tensors.
- If 'x' is a list, a list of lists, where each sublist has the same length
as 'x' and the k'th element in each sublist corresponds to a split of the
k'th element from 'x'.
- If 'x' is a `.NestedMap`, a list of `.NestedMap`, where each field
corresponds to a split from the same field of 'x'.
"""
if isinstance(x, tf.Tensor):
return tf.split(x, num_splits, axis=axis)
elif isinstance(x, list):
splits = [SplitRecursively(element, num_splits, axis) for element in x]
splits = list(zip(*splits))
return [list(t) for t in splits]
elif isinstance(x, NestedMap):
results = [NestedMap() for _ in range(num_splits)]
for key, val in x.items():
val_splits = SplitRecursively(val, num_splits, axis)
for i in range(num_splits):
results[i][key] = val_splits[i]
return results
else:
raise TypeError('Unexpected type for SplitRecursively: %s' % type(x))
def ConcatRecursively(splits, axis=-1):
"""Concatenates tensors from 'splits'.
This is the inverse function of SplitRecursively.
Args:
splits: a list of splits to concatenate, where elements can be Tensors,
lists, or `.NestedMap`. The elements must share the same type and
structure. For example, list elements must have the same length;
`.NestedMap` must have the same set of fields.
axis: the concatenation axis.
Returns:
Concatenated data.
- If input 'splits' are Tensors, returns a concatenated Tensor.
- If input 'splits' are lists, returns a list of the same length where the
k'th element represents concatenated data of the k'th element from each
split.
- If input 'splits' are `.NestedMap`, returns a `.NestedMap` with each field
concatenated from corresponding fields of input splits.
Raises:
TypeError: if 'splits' is not a list or elements of 'splits' do not have
known or matching types.
ValueError: if 'splits' is empty or elements of 'splits' do not have
matching structures.
"""
if not isinstance(splits, list):
raise TypeError('Non-list inputs for ConcatRecursively: %s' % splits)
if not splits:
raise ValueError('Empty inputs for ConcatRecursively: %s' % splits)
tmpl = splits[0]
if isinstance(tmpl, tf.Tensor):
return tf.concat(splits, axis=axis)
elif isinstance(tmpl, list):
if not all(isinstance(split, list) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
if not all(len(split) == len(tmpl) for split in splits):
raise ValueError('Length mismatch for ConcatRecursively: %s' % splits)
return [
ConcatRecursively([split[i]
for split in splits], axis)
for i in range(len(tmpl))
]
elif isinstance(tmpl, NestedMap):
if not all(isinstance(split, NestedMap) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
results = NestedMap()
for key in tmpl:
results[key] = ConcatRecursively([split[key] for split in splits], axis)
return results
else:
raise TypeError('Unexpected type for ConcatRecursively: %s' % type(splits))
def WeightedAvg(values, weights, sum_reduction_fn=tf.reduce_sum, name=''):
"""Computes weighted average of values from a tensor.
Args:
values: a tensor of values
weights: a tensor of weights
sum_reduction_fn: called to reduce the values and weights to single value
name: name of metric.
Returns:
A tuple (avg, total_weight).
- avg: weighted average value
- total_weight: sum of all weights
"""
msg = 'shape of values and weights tensors must match for metric ' + name
values = with_dependencies(
[assert_equal(tf.shape(values), tf.shape(weights), message=msg)], values)
total_weight = sum_reduction_fn(weights)
# divide_no_nan only supports tf.{float,complex}*.
dtype = values.dtype if values.dtype is tf.float64 else tf.float32
avg = tf.math.divide_no_nan(
sum_reduction_fn(tf.cast(values, dtype) * tf.cast(weights, dtype)),
tf.cast(total_weight, dtype))
return tf.cast(avg, values.dtype), total_weight
def WeightedAvgOfMetrics(metrics):
"""Computes the weighted average of metrics in the list.
Args:
metrics: list of dictionaries of metrics
Returns:
ret_dict - dictionary of weighted averages of each metrics.
"""
ret_dict = {}
lists_of_metrics = {}
for m in metrics:
for name, (value, weight) in m.items():
if name not in lists_of_metrics:
lists_of_metrics[name] = []
lists_of_metrics[name].append((value, weight))
for name, values_and_weights in sorted(lists_of_metrics.items()):
values = tf.stack([x[0] for x in values_and_weights])
weights = tf.stack([x[1] for x in values_and_weights])
ret_dict[name] = WeightedAvg(values, weights, tf.reduce_sum, name)
return ret_dict
def ConcatPerExampleTensors(per_example):
"""Concatenate per-example tensors from many hosts into one large block.
Args:
per_example: list of dictionaries of per-example tensors.
Returns:
ret_dict - string -> concatenated tensors.
"""
ret_dict = {}
lists_of_per_example = {}
for m in per_example:
for name, value in m.items():
if name not in lists_of_per_example:
lists_of_per_example[name] = []
lists_of_per_example[name].append(value)
for name, values in sorted(lists_of_per_example.items()):
ret_dict[name] = tf.concat(values, 0)
return ret_dict
def CombineMetrics(loss_metric_weight_pairs):
"""Combines metrics from `loss_metric_weight_pairs` according to weights.
Keys must either exist in all metrics, in which it will be processed as a
weighted sum, or exist in only one metrics, in which case it will be copied.
Args:
loss_metric_weight_pairs: a list of (metrics, weight) pairs, where each
weight is a float and each metrics is a dict with str keys and
(metric_value, target_weight) values.
Returns:
A dict with the same set of keys as input metrics and values of
(weighted_sum(metric_value), weighted_sum(target_weight)).
Raises:
ValueError: if there exists a metric that exists in more than one element
of `loss_metric_weight_pairs` but not in all of them.
"""
all_keys = set(
[k for loss_metrics, _ in loss_metric_weight_pairs for k in loss_metrics]) # pylint: disable=g-complex-comprehension
result = {}
for k in all_keys:
count = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
count += 1
if count > 1 and count != len(loss_metric_weight_pairs):
raise ValueError('Found metric %s which exists in more than one'
'but not all loss metrics.' % k)
total_val = 0
total_target_weight = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
val, target_weight = loss_metrics[k]
if count == 1:
# Single metric, don't multiply by weight.
total_val = val * target_weight
total_target_weight = target_weight
else:
# Total weighted sum of all predictions.
total_val += weight * val * target_weight
total_target_weight += weight * target_weight
result[k] = (total_val / total_target_weight, total_target_weight)
return result
def AddVN(p, x, per_step=False):
"""Add variational noise to x.
Args:
p: Layer params, with a `vn` subparam containing `VariationalNoiseParams`.
x: Input to add variational noise to.
per_step: Whether to add per_step noise.
Returns:
The input with variational noise added according to params.
"""
tensor_name = x.name if not tf.executing_eagerly() else '[eager]'
if per_step:
if not p.vn.per_step_vn:
tf.logging.info(
'p.vn.per_step_vn is not set. Not adding per-step vn to ' +
tensor_name)
return x
else:
if not p.vn.global_vn:
tf.logging.info('p.vn.global_vn is not set. Not adding global vn to ' +
tensor_name)
return x
tf.logging.info(
f"Add {"per-step" if per_step else "global"} vn to {tensor_name}: {p.vn}")
if p.vn.scale is None:
raise ValueError('VN scale must be set.')
if p.vn.deterministic:
noises = DeterministicVN(p, tf.shape(x), mean=0.0, std=1.0)
noises = tf.cast(noises, x.dtype)
else:
if per_step:
# recurrent.py does not support stateful random ops in cell_fn due to
# rematerialization.
raise ValueError('per_step vn requires deterministic=True.')
noises = tf.random.normal(
tf.shape(x), stddev=1.0, seed=p.vn.seed, dtype=x.dtype)
scale = tf.where(GetGlobalStep() >= p.vn.start_step, p.vn.scale, 0.0)
return x + tf.cast(scale, x.dtype) * noises
def VariationalNoiseParams(scale,
global_vn=False,
per_step_vn=False,
seed=None,
deterministic=None,
start_step=0):
"""Returns a hyperparams for variational noise."""
if deterministic is None:
deterministic = cluster_factory.Current().in_unit_test
p = hyperparams.Params()
p.Define(
'scale', scale,
'Std of the variational noise to apply . This can be a scalar,'
' or a scalar tensor.')
p.Define('global_vn', global_vn,
'Adds global variational noise every training setp iff True.')
p.Define('per_step_vn', per_step_vn,
'Adds per-timesetp variational noise iff True.')
p.Define('seed', seed, 'Random seed used to generate noise.')
p.Define(
'deterministic', deterministic, 'If true, generate noise using'
'stateless random ops that are compatible with TF functional ops.')
p.Define(
'start_step', start_step,
'Step starting from which variational noise is added during training.')
return p
def DefaultVN():
return VariationalNoiseParams(scale=None)
# To disable VN of a layer, we use 1.0 in the first input parameter
# of the following function because otherwise it is the same to DefaultVN()
# which will be updated by parent configuration in CopyBaseParams()
def DisableVN():
return VariationalNoiseParams(1.0, False, False)
# Step seed keyed by graph.
_STEP_SEED_DICT = ThreadLocalDict()
# The step seed will increment by np.prod(_STEP_SEED_INCREMENT.stack)
_STEP_SEED_INCREMENT = ThreadLocalStack()
@contextlib.contextmanager
def StepSeedIncrementContext(step):
"""Adds an element to _STEP_SEED_INCREMENT."""
assert step > 0, ('%s' % step)
_STEP_SEED_INCREMENT.stack.append(step)
try:
yield
finally:
_STEP_SEED_INCREMENT.stack.pop()
def GetStepSeed():
"""Gets step_seed."""
key = id(tf.get_default_graph())
if key not in _STEP_SEED_DICT.dict:
ResetStepSeed()
return _STEP_SEED_DICT.dict[key]
def ResetStepSeed(seed=0):
"""Resets step_seed to specified value."""
key = id(tf.get_default_graph())
_STEP_SEED_DICT.dict[key] = tf.convert_to_tensor(seed, dtype=tf.int64)
def MaybeResetStepSeedFromScope():
"""In graph mode, resets step_seed according to the current named scope.
This is used in graph mode to avoid "tensor is from a different graph"
errors that happen when we share random seend tensors too much.
See b/129159299 for more context.
Eager mode does not have this problem, so in eager mode we do nothing.
"""
if not tf.executing_eagerly():
ResetStepSeed(GenerateSeedFromName(tf.no_op(name='new_step_seed').name))
def MaybeResetStepSeed(seed):
"""If we're in graph mode, reset the step seed."""
if not tf.executing_eagerly():
ResetStepSeed(seed)
def GetIncStepSeed():
"""Returns and increments the step_seed."""
step_seed = GetStepSeed()
# TODO(lepikhin): introduce a routine filling a queue of uint32 random seeds
# independent of underlying PRNG used by tensorflow.
inc = np.prod(_STEP_SEED_INCREMENT.stack)
ResetStepSeed(step_seed + inc)
return step_seed
def GenerateStepSeedPair(p, op_seed=None):
"""Generates a seed pair for deterministic random operations in ...
functional loops.
This function retrieves a unique seed pair on each call, based off the current
global step and step seed. The step seed ensures this function returns a
unique seed pair on each call: calling this function automatically increments
the step seed. The step seed is automatically reset at the beginning of each
global step in the model's FProp and works transparently through recurrent.py.
Args:
p: A hyperparams.Params object, containing keys 'random_seed' and
'is_inference'.
op_seed: An additional operation-level seed to apply.
Returns:
A size 2 tensor of op seeds to use for stateless_random ops.
"""
seed_dtype = tf.int32 if use_tpu() else tf.int64
if p.is_inference and p.random_seed is None:
# Ensure GetIncStepSeed is called even inside the shortcut.
# This ensures if p.random_seed is set for other ops that use this function
# that they will get the same seed pair whether or not p.random_seed is set
# for this specific call.
GetIncStepSeed()
# Unlike tf.random*, stateless random ops are completely determined by the
# passed-in seeds. This means at inference time the same inputs will produce
# the same outputs, even if the model is supposed to have randomness such as
# dropout during inference. We inject additional randomness only during
# inference if the graph is exported with random_seed=None as a workaround.
return tf.random.uniform([2], maxval=seed_dtype.max, dtype=seed_dtype)
global_step = tf.cast(GetGlobalStep(), seed_dtype)
step_seed = tf.cast(GetIncStepSeed(), seed_dtype)
seeds = tf.stack([global_step, step_seed])
if p.random_seed is not None:
seeds += p.random_seed
if op_seed is not None:
op_seed = tf.cast(op_seed, seed_dtype)
seeds += op_seed
return seeds
def DeterministicDropout(x, keep_prob, seeds, noise_shape=None, name=None):
"""Similar to `tf.nn.dropout()`, but fully deterministic.
Args:
x: A float Tensor on which to apply dropout.
keep_prob: A scalar `Tensor` of keep probability.
seeds: A Tensor of shape [2]. 2 seeds for deterministic random number
generator.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated keep/drop flags.
name: An optional name for this operation.
Returns:
A Tensor with the same shape as `x`.
Raises:
InvalidArgumentError: if keep_prob is invalid.
"""
if isinstance(keep_prob, numbers.Real):
if keep_prob <= 0 or keep_prob > 1:
raise tf.errors.InvalidArgumentError(
'keep_prob must be in range (0, 1]. Value: {}'.format(keep_prob))
if keep_prob == 1:
return x
with tf.name_scope(name, 'dropout', [x]) as name:
if use_tpu():
seeds = tf.cast(seeds, tf.int32)
keep_prob = tf.convert_to_tensor(
keep_prob, dtype=tf.float32, name='keep_prob')
# uniform in [keep_prob, 1.0 + keep_prob)
# StatelessRandomUniform op does not support non-float (e.g. bfloat16) dtype
# and non-int32 seed types.
noise_shape = noise_shape or GetShape(x)
random_tensor = keep_prob + tf.random.stateless_uniform(
noise_shape, seed=seeds, dtype=tf.float32)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = tf.floor(random_tensor)
if x.dtype != tf.float32:
binary_tensor = tf.cast(binary_tensor, x.dtype)
keep_prob = tf.cast(keep_prob, dtype=x.dtype)
result = tf.div(x, keep_prob) * binary_tensor
result.set_shape(x.get_shape())
return result
def DeterministicVN(params, noise_shape, mean=0.0, std=1.0, name=None):
"""Produces Fully deterministic Gaussian noise from shape, mean and std.
Args:
params: Nested map of params.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated Gaussian noise.
mean: Mean for the Gaussian noise.
std: Standard deviation for noise.
name: An optional name for this operation.
Returns:
A Tensor with the shape noise_shape and type fprop_dtype.
"""
with tf.name_scope(name, 'gaussian_noise') as name:
seeds = GenerateStepSeedPair(params, params.vn.seed)
random_tensor = mean + (
std * tf.random.stateless_normal(noise_shape, seed=seeds))
if FPropDtype(params) != tf.float32:
random_tensor = tf.cast(random_tensor, FPropDtype(params))
return random_tensor
BATCH_NORM_UPDATES = 'batch_norm_updates'
_BATCH_NORM_UPDATES_DICT = '__batch_norm_update_dict'
_get_batch_norm_updates_dict = _CollectionGetter(_BATCH_NORM_UPDATES_DICT,
lambda: {})
def UpdateBatchNormVars(batch_norm_var, batch_norm_stats, decay):
"""Update batch normalization moving averages."""
with tf.name_scope(
'AssignMovingAvg', values=[
batch_norm_var,
batch_norm_stats,
decay,
]) as scope:
with tf.ops.colocate_with(batch_norm_var):
decay = tf.convert_to_tensor(
1.0 - decay, dtype=batch_norm_var.dtype.base_dtype)
update_delta = (batch_norm_var - tf.cast(
batch_norm_stats, batch_norm_var.dtype.base_dtype)) * decay
has_nan_or_inf = tf.reduce_any(
tf.math.logical_or(
tf.math.is_nan(update_delta), tf.math.is_inf(update_delta)))
update_delta = tf.where(has_nan_or_inf, tf.zeros_like(update_delta),
update_delta)
bn_update = tf.assign_sub(batch_norm_var, update_delta, name=scope)
tf.add_to_collection(BATCH_NORM_UPDATES, bn_update)
if not tf.executing_eagerly_outside_functions():
bn_update_dict = _get_batch_norm_updates_dict()
if bn_update.name in bn_update_dict:
raise ValueError(f'BN update {bn_update.name} already exists.')
bn_update_dict[bn_update.name] = (batch_norm_var, batch_norm_stats)
return bn_update
def FindRelevantBatchNormUpdates(loss, batch_norm_updates):
"""Finds and returns a list of relevant batch-normalization updates.
Args:
loss: The loss that is being optimized for. A tensor or a list of tensors.
batch_norm_updates: A list of batch normalization updates.
Returns:
A pair of lists. The first list contains all the batch normalization updates
that are relevant to the loss being optimized, and the second list contains
all in batch_norm_updates but not in the first list.
"""
if tf.executing_eagerly_outside_functions():
return [], []
dependent_ops_and_tensors = set(FindNeeded(loss))
relevant_updates = []
irrelevant_updates = []
bn_update_dict = _get_batch_norm_updates_dict()
for bn_update in batch_norm_updates:
assert bn_update.name in bn_update_dict, (
f'{bn_update.name} is probably not a valid batch normalization update '
'op. Make sure batch normalization is done through calling'
' the py_utils.UpdateBatchNormVars helper routine.')
bn_stat_name = bn_update_dict[bn_update.name][1].name
if bn_stat_name in dependent_ops_and_tensors:
# If a batch normalization stat is computed in the forward pass in
# computing loss, then the corresponding batch normalization update is
# relevant. Otherwise, it is not.
relevant_updates.append(bn_update)
else:
irrelevant_updates.append(bn_update)
return relevant_updates, irrelevant_updates
_SAMPLE_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def SampleStep(step):
"""A context for a sample step during decoding.
Example usage::
with py_utils.SampleStep(step):
sample = self.DecodeOneStep()
Args:
step: the step tensor.
Yields:
a context manager for the step scope.
"""
try:
_SAMPLE_STEP_STACK.stack.append(step)
yield step
finally:
_SAMPLE_STEP_STACK.stack.pop()
def _GetSampleStep():
return _SAMPLE_STEP_STACK.stack[-1] if _SAMPLE_STEP_STACK.stack else None
def AddDebugTensor(tensor, summarize=None, name=None):
"""Adds `tensor` to the debug collection.
Prints the tensor if `--print_debug_tensors` is True.
Args:
tensor: A tensor.
summarize: Only print this many entries of each tensor. If None, then a
maximum of 3 elements are printed per input tensor.
name: An optional name for the tensor.
Returns:
A Tensor that evaluates to the same value as the input tensor.
"""
if _FromGlobal('print_debug_tensors'):
step = _GetSampleStep()
tensors_to_print = ([] if step is None else [step]) + [tensor]
with tf.name_scope(name) as s:
tensor = tf.Print(
tensor,
tensors_to_print,
message='DEBUG tensor %s' % s,
name=name,
summarize=summarize)
return tensor
def ArgMax(inputs):
"""tf.argmax wrapper.
Args:
inputs: A tensor, whose last dimension is being reduced on.
Returns:
A tensor of rank tf.rank(logits)-1. If i == ret[indices],
logits[indices, i] is the maximum among logits[indices, :].
"""
if use_tpu():
return tf.argmax(inputs, axis=-1, output_type=tf.int32)
else:
return tf.argmax(inputs, axis=-1)
def _EnsureMatrixShape(x):
if x.shape.ndims is None:
x.set_shape([None, None])
else:
assert x.shape.ndims == 2
return x
def Matmul(x, y, *args, **kwargs):
"""tf.matmul wrapper expecting x and y are actually matrices."""
x = _EnsureMatrixShape(x)
y = _EnsureMatrixShape(y)
return tf.matmul(x, y, *args, **kwargs)
def clip_by_value(t, clip_value_min, clip_value_max, name=None): # pylint: disable=invalid-name
if t.dtype.is_complex:
return tf.complex(
tf.clip_by_value(
tf.math.real(t), clip_value_min, clip_value_max, '%s_real' % name),
tf.clip_by_value(
tf.math.imag(t), clip_value_min, clip_value_max, '%s_imag' % name))
return tf.clip_by_value(t, clip_value_min, clip_value_max, name)
def _TransformAndSum(tensor_list, transform):
with tf.name_scope('TransformAndSum'):
sum_transform = []
for t in tensor_list:
with tf.device(t.device):
if isinstance(t, tf.IndexedSlices):
sum_transform += [tf.reduce_sum(transform(t.values))]
else:
sum_transform += [tf.reduce_sum(transform(t))]
return tf.add_n(sum_transform)
def SumSquared(tensor_list):
return _TransformAndSum(tensor_list, lambda v: v**2)
def SumAbs(tensor_list):
return _TransformAndSum(tensor_list, tf.abs)
def ReduceRms(x: tf.Tensor) -> tf.Tensor:
"""Computes root mean square of tensor x with numerical stability."""
if not x.shape.is_fully_defined():
raise ValueError('Shape of x must be fully defined.')
if not x.shape.as_list():
return x
denom = functools.reduce((lambda x, y: x * y), x.shape.as_list())
if denom <= 1e8:
return tf.math.sqrt(tf.math.reduce_mean(tf.math.square(x)))
tf.logging.info('reduce_rms %s denom=%d', x, denom)
sum_square_x = tf.math.reduce_sum(tf.math.reduce_sum(tf.math.square(x), -1))
avg_square_x = sum_square_x / tf.constant(denom, dtype=sum_square_x.dtype)
return tf.math.sqrt(avg_square_x)
def PiecewiseConstant(x_in, boundaries, values, vdtype):
"""Returns the piecewise value of x_in."""
x_in = tf.cast(tf.convert_to_tensor(x_in), tf.float32)
assert len(values) == len(boundaries) + 1
assert sorted(boundaries) == list(boundaries)
bs = tf.convert_to_tensor(boundaries, dtype=tf.float32)
vs = tf.convert_to_tensor(values, dtype=vdtype)
# The following is equivalent to 'return vs[index]'.
index = tf.reduce_sum(tf.cast(tf.greater_equal(x_in, bs), tf.int32))
one_hot_vec = tf.one_hot(
tf.expand_dims(index, 0), depth=len(values), dtype=vdtype)
return Matmul(tf.reshape(vs, (1, -1)), tf.transpose(one_hot_vec))[0][0]
def PadSequenceDimension(x, length, pad_val, shape=None, axis=1):
"""Pads x to `length` using `pad_val` along the axis dim.
Assumes `x` is a tensor with rank >= 2, and it only pads `x` to `length`
along the axis dim. Explicitly sets the returned tensor shape to `shape` if
given. Raises runtime errors if x.shape[axis] > length or
x.shape[i] != shape[i] where i != axis.
Args:
x: the tensor to be padded with axis dimension being the time. E.g., x
usually has shape [batch, seq_len, ...], when axis=1.
length: an int to specify the length to pad x to.
pad_val: an int or float used to pad x.
shape: an int array specifying the shape of the padded tensor if specified.
axis: The dimension that x will be padded, default to 1.
Returns:
The padded tensor with shape [batch, seq_len, ...], where
ret[:, :seq_len, ...] == x, when axis=1, and similarly for other axes.
"""
if x.shape.ndims is not None:
rank = x.shape.ndims
assert rank >= 2
slen = GetShape(x, rank)[axis]
pad_len = length - slen
pad = [[0, 0] for _ in range(rank)]
pad[axis][1] = pad_len
else:
rank = tf.rank(x)
with tf.control_dependencies([assert_greater_equal(rank, 2)]):
slen = tf.shape(x)[axis]
pad_len = length - slen
pad = tf.scatter_nd([[axis, 1]], [pad_len], [rank, 2])
x = tf.pad(x, pad, constant_values=pad_val)
if x.shape.ndims is not None and isinstance(length, int):
static_shape = x.shape.as_list()
static_shape[axis] = length
x.set_shape(static_shape)
if shape:
if not isinstance(shape, (list, tuple)):
raise TypeError('Shape must be a list or tuple.')
x = HasRank(x, len(shape))
x = tf.ensure_shape(x, shape)
return x
def PadSequenceTo(xs, padding, length, pad_val):
"""Pads `xs` and `padding` to `length` using `pad_val` along the 2nd dim.
Pads `xs` to `length` using `pad_val`, and `padding` using 1.
Raise error if `x.shape[:2]` and `padding.shape` are not the same.
Args:
xs: A Tensor or a list of Tensors of shape [batch, seqlen] or [batch,
seqlen, ...].
padding: A 0/1 Tensor of shape [batch, seqlen]. 1 is for padded locations.
length: A Python int, the length to pad to.
pad_val: A Python numeric, used for padding x.
Returns:
A tuple of padded xs and padding.
"""
if not isinstance(xs, (list, tuple)):
new_xs = [xs]
else:
new_xs = xs
res = []
for x in new_xs:
batch, slen = GetShape(x, 2)
padding = HasRank(padding, 2)
padding = HasShape(padding, [batch, slen])
new_x = PadSequenceDimension(x, length, pad_val)
res.append(new_x)
padding = PadSequenceDimension(padding, length, tf.cast(1, padding.dtype))
if not isinstance(xs, (list, tuple)):
assert len(res) == 1
return res[0], padding
else:
return tuple(res), padding
def ApplyPadding(padding, x, padded=None, use_select=True, ensure_shape=True):
"""Applies padding to a tensor.
This is preferable to using arithmetic means for masking out padded values
such as::
# Equiv to ApplyPadding(padding, x)
x *= 1.0 - padding
# Equiv to ApplyPadding(padding, new, old)
new = old * padding + new * (1 - padding)
Aside from just being easier to read and reason about, using this function
is friendly to quantized representations because it does not mix arithmetic
on the padding values with the values in the tensor being padded (which can
have a very different range than the 0..1 padding tensor).
In addition, this works around issues in quantized schemes where we are
guaranteed to have an exact 0 but not necessarily any other number (i.e. 1).
Args:
padding: Tensor of padding values where 0 == keep and 1 == pad.
x: Tensor to apply padding to.
padded: Optional. Values to include for padded elements. Defaults to zeros.
Must have a shape broadcastable to 'x' if specified.
use_select: Controls whether padding is applied with a select-mask
(True/default) or arithmetically (False). Some platforms have a
sensitivity to one or the other and this is used to work around such
issues.
ensure_shape: If true, ensures the shape of the result is the same as of x.
Returns:
A tensor with the same shape as x with padded values masked.
"""
padding = with_dependencies([
Assert(
tf.reduce_all(
tf.math.logical_or(
tf.equal(padding, tf.zeros([], padding.dtype)),
tf.equal(padding, tf.ones([], padding.dtype)))), [padding])
], padding)
if use_select:
if padded is None:
padded = tf.zeros([], x.dtype)
if padding.dtype != tf.bool:
padding = padding > tf.zeros([], padding.dtype)
result = tf.where_v2(padding, padded, x)
else:
result = x * tf.cast(1.0 - tf.cast(padding, tf.float32), x.dtype)
if padded is not None:
result += padded * tf.cast(padding, padded.dtype)
if ensure_shape:
result = tf.ensure_shape(result, x.shape)
return result
def LengthsFromPaddings(paddings):
"""Computes lengths of each sequence in a batch, ignoring trailing padding.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x
Args:
paddings: a tensor with shape [batch, length].
Returns:
lengths tensor shaped [batch] containing the unpadded length of each
sequence in the batch.
"""
paddings = HasRank(paddings, 2)
paddings = tf.cast(paddings, tf.int32)
# Find the last unpadded value.
# Cannot just use tf.reduce_sum because there might be leading paddings.
# Everything after the last unpadded value has 1.0 - paddings == 0.0, so in
# the cumsum below they will have the same value.
cumsum = tf.cumsum(1 - paddings, axis=1)
same_as_last_element = tf.equal(cumsum, cumsum[:, -1:])
# Counting the number of elements with the same value gives us num_padded + 1
# and so counting the number that differs gives us num_padded - 1.
length = tf.reduce_sum(
1 - tf.cast(same_as_last_element, tf.int32), axis=1) + 1
# Special case for all 0 paddings.
all_zero_paddings = tf.equal(tf.reduce_sum(1 - paddings, axis=1), 0)
return tf.where(all_zero_paddings, tf.zeros_like(length), length)
def PaddingsFromLengths(lengths, maxlen=None):
"""Computes paddings Tensor from lengths.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x.
This method does not generate leading paddings.
Args:
lengths: A int32 Tensor of shape [B].
maxlen: None or a Python int or a scalar Tensor.
Returns:
A 0/1 valued Tensor of shape [B, maxlen or ?] where 1s are padded positions.
"""
lengths = HasRank(lengths, 1)
if maxlen is not None:
lengths = with_dependencies(
[assert_less_equal(tf.cast(tf.reduce_max(lengths), tf.int32), maxlen)],
lengths)
return 1. - tf.sequence_mask(lengths, maxlen=maxlen, dtype=tf.float32)
def TrimTrailingPaddings(inputs, paddings):
"""Trims trailing paddings from inputs.
Since the number of dimensions is not fixed, this will not work on TPU.
Args:
inputs: a tensor with shape [batch, length, ...].
paddings: a tensor with shape [batch, length].
Returns:
Trimmed inputs and paddings. For compatibility reasons, the trimmed tensors
will always have length at least 1.
"""
paddings = HasRank(paddings, 2)
max_length = tf.maximum(tf.reduce_max(LengthsFromPaddings(paddings)), 1)
output_shape = tf.shape(inputs)
output_shape = tf.concat([[output_shape[0], max_length], output_shape[2:]],
axis=0)
outputs = tf.slice(inputs, tf.zeros_like(output_shape), output_shape)
out_paddings = tf.slice(paddings, [0, 0],
tf.stack([output_shape[0], max_length]))
return outputs, out_paddings
def ReversePaddedSequence(inputs, paddings):
"""Reverse inputs based on paddings.
Only reverse the unpadded portion of `inputs`. It assumes inputs are only
padded in the end.
Args:
inputs: a tensor of [seq_length, batch_size, num_input_nodes].
paddings: a tensor of float32/float64 zero or one of shape [seq_length,
batch_size, 1].
Returns:
A reversed tensor of the same shape as `inputs`.
"""
inversed_paddings = 1.0 - tf.squeeze(paddings, 2)
inputs_length = tf.cast(
tf.math.rint(tf.reduce_sum(inversed_paddings, axis=0)), tf.int32)
return tf.reverse_sequence(inputs, inputs_length, seq_axis=0, batch_axis=1)
def ConcatenatePaddedSequences(input0, input1, padding0, padding1, seq_dim=1):
"""Concatenates input sequences with varying lengths as defined by paddings.
This is a helper function for concatenating 2 batches of input sequences,
where each example in the batch can have different lengths, as defined by
the corresponding paddings. To concatenate correctly, it makes use of
tf.reverse_sequence to partially reverse the sequences before
concatenating them together.
NOTE: We assume that the tensors have no leading paddings.
Args:
input0: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
input1: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
padding0: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input0.
padding1: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input1.
seq_dim: int, the time axis along which the tensors will be concatenated.
Should be 0 or 1. Assumes that batch_dim is 1 - seq_dim.
Returns:
The concatenation of input0 and input1, and the corresponding padding.
Raises:
tf.errors.InvalidArgumentError when seq_dim is not 0 or 1.
"""
if seq_dim != 0 and seq_dim != 1:
raise tf.errors.InvalidArgumentError(None, None, 'seq_dim must be 0 or 1.')
batch_dim = 1 - seq_dim
# inpu0 and input1 should have the same batch size and same rank.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim],
GetShape(input1)[batch_dim]),
assert_equal(GetRank(input0), GetRank(input1))
], input0)
batch_size = GetShape(padding0)[batch_dim]
# batch dimension of inputs and paddings should match.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim], batch_size),
assert_equal(GetShape(padding1)[batch_dim], batch_size)
], input0)
input0_seq_dim = tf.cast(
tf.tile([tf.shape(padding0)[seq_dim]], [batch_size]), dtype=tf.int32)
input1_seq_dim = tf.cast(
tf.tile([tf.shape(padding1)[seq_dim]], [batch_size]), dtype=tf.int32)
# LengthsFromPaddings assumes that paddings is of size [batch, max_length].
if seq_dim == 1:
seq_length0 = LengthsFromPaddings(padding0)
seq_length1 = LengthsFromPaddings(padding1)
else:
seq_length0 = LengthsFromPaddings(tf.transpose(padding0))
seq_length1 = LengthsFromPaddings(tf.transpose(padding1))
# We assume that the tensors have no leading paddings.
# TODO(arunnt): Concatenate tensors with leading paddings correctly.
seq_length0 = with_dependencies([
assert_equal(
seq_length0,
tf.cast(tf.reduce_sum(1.0 - padding0, seq_dim), dtype=tf.int32))
], seq_length0)
seq_length1 = with_dependencies([
assert_equal(
seq_length1,
tf.cast(tf.reduce_sum(1.0 - padding1, seq_dim), dtype=tf.int32))
], seq_length1)
# Concatenate input sequences.
reversed_input0 = tf.reverse_sequence(
input0, seq_length0, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_input1 = tf.reverse_sequence(
input1, input1_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat = tf.concat([reversed_input1, reversed_input0], axis=seq_dim)
concat_inputs = tf.reverse_sequence(
reversed_concat,
seq_length0 + input1_seq_dim,
seq_axis=seq_dim,
batch_axis=batch_dim)
# Concatenate paddings. Note that paddings are always a Tensor of 0s and 1s,
# so, unlike the inputs, we don't have to reverse padding1, we can simply
# concatenate reversed padding0 and padding1.
reversed_padding0 = tf.reverse_sequence(
padding0, input0_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat_padding = tf.concat([reversed_padding0, padding1],
axis=seq_dim)
concat_paddings = tf.reverse_sequence(
reversed_concat_padding,
input0_seq_dim + seq_length1,
seq_axis=seq_dim,
batch_axis=batch_dim)
return concat_inputs, concat_paddings
def ShiftLeft(tensor, shift_size, pad_val=0, axis=1):
"""Shifts the values in a tensor to the left along the axis dimension.
The first shift_size values are dropped, and the tensor is padded on the
right with pad_val.
Args:
tensor: the input tensor with the axis dim being time.
shift_size: the number of frames >= 0 to shift.
pad_val: the value to pad on the right of the tensor.
axis: The dimension along which the tensor will be shifted, default to 1.
Returns:
A left shifted tensor on dimension axis.
"""
rank = tensor.shape.rank
with tf.control_dependencies(
[assert_greater_equal(rank, 2),
assert_greater_equal(shift_size, 0)]):
time = GetShape(tensor)[axis]
begin = tf.scatter_nd([[axis]], [shift_size], [rank])
return PadSequenceDimension(
tf.slice(tensor, begin, size=[-1] * rank), time, pad_val, axis=axis)
def CreateIdsAndLabels(ids, paddings, sos_id=1, eos_id=2):
"""Creates ids and labels to be used as decoder targets.
Args:
ids: int Tensor of shape [batch, maxlen], without sos or eos.
paddings: float Tensor of shape [batch, maxlen].
sos_id: ID for the sos special token.
eos_id: ID for the eos special token.
Returns:
A NestedMap with:
- ids: int Tensor of shape [batch, maxlen + 1], with sos prepended.
- labels: int Tensor of shape [batch, maxlen + 1], with eos appended.
- paddings: float Tensor of shape [batch, maxlen + 1].
- weights: float Tensor of shape [batch, maxlen + 1].
"""
ids = tf.where(
tf.equal(paddings, 0.0), ids, tf.broadcast_to([[eos_id]], GetShape(ids)))
targets = NestedMap()
targets.ids = tf.pad(ids, [[0, 0], [1, 0]], constant_values=sos_id)
targets.labels = tf.pad(ids, [[0, 0], [0, 1]], constant_values=eos_id)
targets.paddings = tf.pad(paddings, [[0, 0], [1, 0]])
targets.weights = 1.0 - targets.paddings
return targets
def Retry(*args, **kwargs):
return retry.Retry(*args, **kwargs)
# FailedPreconditionError: variables are not initialized.
# AbortedError: processes restarts.
# UnavailableError: Bad hardware status: 0x1
transient_tf_errors = (tf.errors.FailedPreconditionError,
tf.errors.AbortedError, tf.errors.UnavailableError)
def RetryOnTransientTfError(*args, **kwargs):
return Retry(transient_tf_errors, *args, **kwargs)
def PadOrTrimTo(x, shape, pad_val=0, pad_after_contents=True):
"""Pad and slice x to the given shape.
Args:
x: A tensor.
shape: The shape of the returned tensor.
pad_val: An int or float used to pad x.
pad_after_contents: Whether to pad and trim after the original contents of
each dimension.
Returns:
'x' is padded with pad_val and sliced so that the result has the given
shape.
Raises:
ValueError: if shape is a tf.TensorShape and not fully defined.
"""
if isinstance(shape, (list, tuple)):
expected_rank = len(shape)
elif isinstance(shape, tf.TensorShape):
if not shape.is_fully_defined():
raise ValueError('shape %s padding %s must be fully defined.' %
(shape, x))
expected_rank = shape.rank
else:
shape = HasRank(shape, 1)
expected_rank = tf.size(shape)
x = HasRank(x, expected_rank)
pad = shape - tf.minimum(tf.shape(x), shape)
zeros = tf.zeros_like(pad)
if pad_after_contents:
# If dim_i is less than shape[i], pads after contents.
paddings = tf.stack([zeros, pad], axis=1)
# If dim_i is larger than shape[i], we slice [0:shape[i]] for dim_i.
slice_begin = zeros
else:
# If dim_i is less than shape[i], pads before contents.
paddings = tf.stack([pad, zeros], axis=1)
# If dim-i is larger than shape[i], we slice [dim_i - shape[i]:dim_i]
# for dim_i.
slice_begin = tf.shape(x) + pad - shape
x = tf.pad(x, paddings, constant_values=pad_val)
x = tf.slice(x, slice_begin, shape)
return tf.reshape(x, shape)
def RepeatDim(tensor, multiple, axis):
"""Copies elements in tensor's axis "multiple" times, like np.repeat."""
# x = [[1, 2, 3], [4, 5, 6]]
# RepeatDim(x, multiple=2, axis=1) gives:
# [[1, 1, 2, 2, 3, 3]. [4, 4, 5, 5, 6, 6]]
# As a comparison tf.tile(x, multiples=[1, 2]) gives:\
# [[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]
if multiple == 1:
return tensor
t_shape = tf.shape(tensor)
tensor_dims = tf.concat(
[t_shape[:axis], [t_shape[axis] * multiple], t_shape[axis + 1:]], 0)
multiple_dims = tf.concat([
tf.fill([axis + 1], 1), [multiple],
tf.fill([tf.rank(tensor) - axis - 1], 1)
], 0)
return tf.reshape(
tf.tile(tf.expand_dims(tensor, axis + 1), multiple_dims), tensor_dims)
def StackTensorsRecursively(values):
"""Recursively stacks Tensors in a list of `.NestedMap`.
Args:
values: a list of `.NestedMap` or Tensors to stacks.
Returns:
A `.NestedMap` with stacked values or a stacked Tensor.
"""
flatten = [w.Flatten() for w in values]
stacked = []
for i in range(len(flatten[0])):
stacked += [tf.stack([flatten[j][i] for j in range(len(flatten))])]
ret = values[0].Pack(stacked)
return ret
def MixByWeight(inputs, weights, seed=None):
"""Returns a weighted random choice and bprop type from the give inputs.
Args:
inputs: a list of callables, where each callable returns a tf.Tensor or a
nested structure containing tf.Tensor. Function return types must be
consistent across elements. The tf.Operation to compute the result tensor
will only be invoked for one input at a time. For example, if each fn
represents an input record stream, a record will be drawn only from a
selected stream while the other streams will remain unchanged.
weights: a 1D tensor of float > 0 of the same length as inputs.
seed: random seed.
Returns:
A probabilistic sample from the inputs proportional to the weights. The
return type will be the same as return type of individual 'fn' from the
inputs.
A one-hot vector of the source selected.
"""
weights = tf.convert_to_tensor(weights, dtype=tf.float32)
weights = with_dependencies([
assert_equal(tf.shape(weights), [len(inputs)]),
assert_greater_equal(tf.reduce_min(weights), 0.0)
], weights)
lower = tf.cumsum(weights, exclusive=True)
upper = tf.cumsum(weights, exclusive=False)
r = tf.random.uniform(shape=[], maxval=upper[-1], seed=seed)
return_input = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), inputs[i])
for i in range(len(inputs))],
exclusive=True)
selected_index = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), lambda i=i: i)
for i in range(len(inputs))],
exclusive=True)
bprop_index = tf.one_hot(selected_index, len(inputs), dtype=tf.float32)
return return_input, bprop_index
def CheckShapes(shapes):
"""Asserts that shapes is a tuple of NestedMap or tshape.Shape."""
assert isinstance(shapes, tuple), str(shapes)
for s in shapes:
if isinstance(s, NestedMap):
assert all([isinstance(t, tshape.Shape) for t in Flatten(s)
]), '{} contains non-tensor value.'.format(s)
else:
assert isinstance(s, tshape.Shape), '{}: {}'.format(type(s), s)
def FPropDtype(params):
return params.fprop_dtype if params.fprop_dtype is not None else params.dtype
def UpdateFpropDtype(params, fprop_dtype):
"""Recursively update the fprop_dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateFpropDtype(val, fprop_dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateFpropDtype(item, fprop_dtype)
elif key == 'fprop_dtype':
params.fprop_dtype = fprop_dtype
def UpdateDtype(params, dtype):
"""Recursively update the dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateDtype(val, dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateDtype(item, dtype)
elif key == 'dtype':
params.dtype = dtype
def NameScopeDecorator(name_scope):
"""Decorates a python function to introduce a tf.name_scope.
Example::
@py_utils.NameScopeDecorator('foobar')
def MyFoobarMethod(self):
# ... Do TF things
Args:
name_scope: The name scope to introduce.
Returns:
A function decorator.
"""
def Decorator(f):
def Wrapped(*args, **kwargs):
with tf.name_scope(name_scope):
return f(*args, **kwargs)
return Wrapped
return Decorator
def SequencesToDebugStrings(ids, lens, summarize=5):
"""Returns debug strings for the given sequences.
Args:
ids: int32 of [batch, len].
lens: int32 of [batch].
summarize: number of ids to summarize per sequence.
Returns:
A string tensor of [batch].
"""
num_seqs = tf.shape(lens)[0]
def _Body(i, result):
line = tf.strings.format('{}', ids[i, :lens[i]], summarize=summarize)
return i + 1, tf.concat([result, tf.reshape(line, [1])], axis=0)
i0 = tf.zeros(shape=[], dtype=tf.int32)
result0 = tf.constant('', shape=[0], dtype=tf.string)
_, strs = tf.while_loop(
lambda i, result: i < num_seqs,
_Body, (i0, result0),
shape_invariants=(i0.shape, tf.TensorShape([None])))
return strs
# TODO(jamesqin): follow suggestions in
# b/167460492#comment16
def RematerializeFn(fn, *xs):
"""Calls fn and rematerializes fn in the backward pass.
`fn(*xs) -> ys`, where xs and ys can be a single tensor or a tuple of tensors.
Args:
fn: A python function to be rematerialized in the backprop pass.
*xs: A single tensor or a list/tuple of tensors. `xs` are input args to the
fn function.
Returns:
`fn(*xs)`
"""
initial_step_seed = GetStepSeed()
final_step_seed = MaybeGenerateSeedFromScope()
def Backward(fwd_xs, fwd_ys, d_fwd_ys):
"""The backward function that rematerializes forward outputs."""
del fwd_ys
always_true = tf.random.uniform([]) < 2.0
# Alternatively, can do this:
# tf.where(tf.math.is_nan(x),
# tf.constant(float('nan'), dtype=x.dtype) * tf.ones_like(x),
# x)
bak_xs = [tf.where(always_true, x, tf.zeros_like(x)) for x in fwd_xs.xs]
for dst, src in zip(bak_xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(initial_step_seed)
ys = fn(*bak_xs)
MaybeResetStepSeed(final_step_seed)
dxs = tf.gradients(ys, bak_xs, grad_ys=d_fwd_ys)
dxs_final = []
for dx, x in zip(dxs, bak_xs):
if dx is None:
dxs_final.append(tf.zeros_like(x))
else:
dxs_final.append(dx)
assert len(dxs_final) == len(bak_xs)
return NestedMap(
initial_step_seed=tf.zeros_like(initial_step_seed), xs=dxs_final)
ys_shapes = []
# TODO(huangyp, yonghui): Check Forward doesn't use any stateful random ops.
def Forward(fwd_xs):
"""Forward function plus sanity checks."""
for dst, src in zip(fwd_xs.xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(fwd_xs.initial_step_seed)
ys = fn(*fwd_xs.xs)
# Some sanity check.
assert not GetExtraInputs()
assert not GetExtraArgs()
assert not GetExtraVars()
if isinstance(ys, tuple):
for y in ys:
assert isinstance(y, tf.Tensor)
ys_shapes.append(y.shape)
else:
assert isinstance(ys, tf.Tensor)
ys_shapes.append(ys.shape)
return ys
ys = CallDefun(
Forward,
NestedMap(initial_step_seed=initial_step_seed, xs=xs),
bak=Backward)
if isinstance(ys, tuple):
for y, s in zip(ys, ys_shapes):
y.set_shape(s)
else:
ys.set_shape(ys_shapes[0])
# TODO(b/129159299): The ResetStepSeed below is needed to work around this
# bug, which is a problem with global tensors being shared by different
# inference graphs. It should be replaced with the new step seed value
# returned from the Forward function when the bug is fixed.
MaybeResetStepSeed(final_step_seed)
return ys
# A set of names of stateful random number generator ops.
# See tensorflow/core/ops/random_ops.cc
_STATEFUL_RANDOM_OPS = frozenset({
# pyformat: disable
'RandomUniform',
'RandomUniformInt',
'RandomStandardNormal',
'ParameterizedTruncatedNormal',
'TruncatedNormal',
'RandomShuffle',
'Multinomial',
'RandomGamma',
'RandomPoisson',
'RandomPoissonV2',
# pyformat: enable
})
def StatefulRandomOpsInDefun(func, graph=None):
"""Checks whether the Defun depends on stateful random number ops.
Stateful random number generator ops should be avoid in Recurrent() call.
Otherwise, these ops produce inconsistent values between FProp and BProp.
Args:
func: a _DefinedFunction or ConcreteFunction to check.
graph: a Graph. Set None to use the default graph.
Returns:
A list of names of the stateful random ops.
Raises:
InvalidArgumentError: if the input func/graph is invalid.
"""
if graph is None:
graph = tf.get_default_graph()
func.add_to_graph(graph)
graph_def = graph.as_graph_def()
# A dict from function name to FunctionDef.
func_defs = {x.signature.name: x for x in graph_def.library.function}
if isinstance(func, function._DefinedFunction): # pylint: disable=protected-access
if func.definition.signature.name not in func_defs:
raise tf.errors.InvalidArgumentError(
None, None, 'Defun {} is not in the graph .'.format(
func.definition.signature.name))
nodes = py_collections.deque(func.definition.node_def)
else:
nodes = py_collections.deque(func.function_def.node_def)
stateful_ops = []
# Recursively search for stateful random op.
while nodes:
node = nodes.pop()
assert isinstance(node, node_def_pb2.NodeDef), node
if node.op in _STATEFUL_RANDOM_OPS:
stateful_ops.append(node.name)
continue
def _AddDefunNodes(func_name):
"""If the given func_name is a Defun, add its sub-nodes into nodes."""
if func_name in func_defs:
nodes.extend(func_defs[func_name].node_def)
# For functional.{While|For|If} ops, add their Defun attr into search.
if node.op == 'While':
_AddDefunNodes(node.attr['body'].func.name)
_AddDefunNodes(node.attr['cond'].func.name)
elif node.op == 'For':
_AddDefunNodes(node.attr['body'].func.name)
elif node.op == 'If':
_AddDefunNodes(node.attr['then_branch'].func.name)
_AddDefunNodes(node.attr['else_branch'].func.name)
elif node.op == 'StatefulPartitionedCall':
_AddDefunNodes(node.attr['f'].func.name)
elif node.op != 'PartitionedCall':
# For other op, check whether itself is a Defun op.
_AddDefunNodes(node.op)
return stateful_ops
def ToPlaceholders(nmap, dtype=None):
"""Converts every Tensor in nmap to a placeholder."""
def _ToPlacerholder(x):
shape = [None for _ in x.shape[:-1]] + [x.shape[-1]]
return tf.placeholder(dtype=dtype or x.dtype, shape=shape)
return nmap.Transform(_ToPlacerholder)
def Softmax(logits, axis=None, extra_logit=None, name=None):
"""Softmax with extra_logits, might be useful for large xformer LM."""
if extra_logit is None:
return tf.nn.softmax(logits, axis=axis, name=name)
axis = -1 if axis is None else axis
def ReduceLogSumExp(x):
max_logit = tf.math.reduce_max(
tf.stop_gradient(x), axis=axis, keepdims=True)
base_logit = tf.math.maximum(max_logit, extra_logit)
x -= base_logit
exp_x = tf.math.exp(x)
sum_exp_x = tf.math.reduce_sum(exp_x, axis=axis, keepdims=True)
sum_exp_x += tf.math.exp(extra_logit - base_logit)
return tf.math.log(sum_exp_x) + base_logit
def LogSoftmax(x):
return x - ReduceLogSumExp(x)
with tf.name_scope(name):
return tf.math.exp(LogSoftmax(logits))
def SoftmaxCrossEntropyFocalLoss(logits,
label_ids=None,
label_probs=None,
alpha=None,
gamma=None,
stop_gradient_on_focal_loss_coefficient=False):
u"""Focal loss for multinomial (softmax) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the multinomial logistic regression. C is the
number of classes.
label_ids: [...]. Each entry in labels must be an index in [0, C).
label_probs: [..., C]. Each vector along last dimension must be a valid
probability distribution.
alpha: [C]. The weighting factor alpha. Eq (3) in [1].
gamma: []. Tunable focusing parameter. Eq (4) in [1].
stop_gradient_on_focal_loss_coefficient: If true, stops gradient on the
focal loss coefficient (1-p)^gamma to stabilize the gradient.
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
def _ApplyFocalLossCoefficient(loss, log_probs):
if gamma is not None and gamma != 0:
probs = tf.exp(log_probs)
coefficient = tf.pow(1.0 - probs, gamma)
if stop_gradient_on_focal_loss_coefficient:
coefficient = tf.stop_gradient(coefficient)
loss *= coefficient
return loss
if label_probs is not None:
log_probs = tf.nn.log_softmax(logits)
loss = -(label_probs * log_probs)
loss = _ApplyFocalLossCoefficient(loss, log_probs)
if alpha is not None:
loss *= tf.reshape(
alpha, tf.concat([tf.ones(tf.rank(loss) - 1, tf.int32), [-1]],
axis=0))
loss = tf.reduce_sum(loss, axis=-1)
else:
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=label_ids, logits=logits)
loss = _ApplyFocalLossCoefficient(loss, -loss)
if alpha is not None:
loss *= tf.gather(alpha, label_ids)
return loss
def SigmoidCrossEntropyFocalLoss(logits, labels, alpha=None, gamma=None):
u"""Focal loss for binary (sigmoid) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the sigmoid logistic regression.
labels: [..., C]. 0/1 labels.
alpha: The weighting factor alpha. Eq (3) in [1].
gamma: Tunable focusing parameter. Eq (4) in [1].
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
# [1] Eq (4).
#
# The numerically-stable way to compute
# log(p) for positives;
# log(1 - p) for negatives.
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)
if gamma is not None and gamma != 0:
# The modulating factor. Note that
# (1 - p)ˠ = [1 - σ(x)]ˠ = [σ(-x)]ˠ, for positives.
# pˠ = [σ(x)]ˠ, for negatives.
loss *= tf.pow(tf.sigmoid(logits * (1 - labels * 2)), gamma)
if alpha is not None:
# [1] Eq (3)
loss *= (alpha * labels + (1 - alpha) * (1 - labels))
return loss
_RECORD_FORMAT_RE = re.compile('(^[A-Za-z_]+):(.*)')
def RecordFormatFromFilePattern(file_pattern):
"""Return the record format string for a Lingvo file pattern.
Lingvo file patterns take the form of:
tfrecord:/path/to/bar -> tfrecord is the record_format.
This function takes a file pattern and returns a string indicating
which format the filepattern implies.
Args:
file_pattern: String file pattern.
Returns:
Tuple (string, string):
- record_format: String record format, e.g., "tfrecord", etc.
- file_pattern: The file pattern without any prefixes.
"""
result = re.match(_RECORD_FORMAT_RE, file_pattern)
if result is None:
# TODO(vrv): Fix all callers so that file_pattern must contain
# the record format prefix.
return 'sstable', file_pattern
# regexp ensures that a match implies there are two groups:
# the record format and then the file pattern.
return result.groups()
def ReadFileLines(file_path):
"""Read a text file and return the lines.
If the file cannot be found at the given path, attempt to load it from the
Lingvo package (useful for data dependencies in par files).
Args:
file_path: path to file, either absolute or relative to the bazel workspace.
Returns:
A list of lines from the file.
"""
if not tf.io.gfile.exists(file_path):
try:
lines = pkgutil.get_data(
'lingvo', file_path.replace('lingvo/', '', 1))
if lines:
lines = lines.splitlines(True)
except IOError:
# If pkgutil can't find the file, continue and let GFile raise the error.
lines = None
else:
lines = None
if not lines:
with tf.io.gfile.GFile(file_path, 'r') as f:
lines = f.readlines()
return lines
# Partially borrowed from
# https://github.com/tensorflow/tensor2tensor/blob/32929305e1a4ec926eff24123758b794df35492b/tensor2tensor/layers/common_layers.py#L349
def CumSum(x, axis=0, exclusive=False, use_einsum=False):
"""A TPU efficient implementation of tf.cumsum().
This is equivalent to tf.cumsum and is faster on TPU as of 08/2019 unless
the axis dimension is very large. The current Tensorflow implementation is
based on scanning and reducing which is not efficient on TPU.
Args:
x: An input Tensor.
axis: An int for the axis.
exclusive: A bool for performing exclusive cumsum.
use_einsum: If true, use einsum on TPU.
Returns:
A Tensor of the same shape as x.
Raises:
ValueError: if the input axis is invalid.
"""
if x.dtype not in (tf.float32, tf.bfloat16) or not use_tpu():
# Fallback to tf.cumsum when inputs are not floats or not running on TPU.
return tf.cumsum(x, axis=axis, exclusive=exclusive)
rank = GetRank(x)
# Needs to know the rank for the final transpose if axis is not the last
# dimension. Otherwise, falls back to tf.cumsum.
if not isinstance(rank, int) and axis != -1:
return tf.cumsum(x, axis=axis, exclusive=exclusive)
if axis < -1:
if axis + rank < 0:
raise ValueError('Unexpected axis: %d (rank = %d)' % (axis, rank))
axis += rank
if use_einsum:
assert isinstance(rank, int) and rank < 26, rank
# Use einsum to avoid data formatting overhead.
a2z = ''.join([chr(i) for i in range(97, 123)]) # abc...xyz
src = a2z[:rank]
if axis == -1:
tgt = src[:-1] + 'z'
else:
tgt = src[:axis] + 'z' + src[axis + 1:]
length = GetShape(x)[axis]
causal_mask = tf.linalg.band_part(
tf.ones([length, length], dtype=x.dtype), 0, -1)
return tf.einsum(f'{src},{src[axis]}z->{tgt}', x, causal_mask)
length = GetShape(x)[axis]
my_range = tf.range(length)
comparator = tf.less if exclusive else tf.less_equal
mask = tf.cast(
comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)),
x.dtype)
result = tf.tensordot(x, mask, axes=[[axis], [0]])
if axis != -1 and axis != rank - 1:
result = tf.transpose(
result,
list(range(axis)) + [rank - 1] + list(range(axis, rank - 1)))
return result
def ProjectLastDim(inputs, weight, input_dim, output_dim):
"""Linear projection on the last dim of the input tensor.
This is a TPU efficient implementation to avoid reshaping inputs to Rank-2
tensor by using Einsum for the compute.
Args:
inputs: An input Tensor, the last dimension of which is input_dim.
weight: A weight matrix with shape [input_dim, output_dim].
input_dim: An integer or a symbolic dim, the last dimension of the inputs.
output_dim: An integer or a symbolic dim, the last dimension of the outputs.
Returns:
An output Tensor of the same rank as inputs, the last dimension is
output_dim.
"""
input_dim = int(
symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)
output_dim = int(
symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim
) else output_dim)
# Assert input_dim and output_dim
inputs = with_dependencies([assert_equal(GetShape(inputs)[-1], input_dim)],
inputs)
weight = with_dependencies([
assert_equal(GetShape(weight)[0], input_dim),
assert_equal(GetShape(weight)[-1], output_dim)
], weight)
if (use_tpu() and inputs.shape is not None and
inputs.shape.rank is not None and inputs.shape.rank < 26):
# Avoids reshape if feasible and uses Einsum.
if inputs.shape.rank == 2:
outputs = tf.matmul(inputs, weight)
else:
# This is equivalent to:
# outputs = tf.einsum('...y,yz->...z', inputs, weight)
# Unfortunately ... in einsum() leads to extra HBM usage.
s = ''.join([chr(x) for x in range(97, 123)]) # abc...xyz
r = inputs.shape.rank
outputs = tf.einsum('{0}y,yz->{0}z'.format(s[:r - 1]), inputs, weight)
else:
outputs = Matmul(tf.reshape(inputs, ToStaticShape([-1, input_dim])), weight)
outputs = tf.reshape(
outputs,
tf.concat([
tf.cast(GetShape(inputs)[:-1], tf.int32),
ToStaticShape([output_dim])
],
axis=0))
return outputs
@contextlib.contextmanager
def RemoveAssertContext(remove=True):
"""Hacks to replace certain unwanted tensorflow ops."""
# TODO(zhifengc/huangyp): Consider implementing assert_equal
# op replacement for lingvo. As assert_equal doesn't support String on GPUs.
# Hack to replace tf.assert_equal
# TODO(b/136040013): Remove this after migration to tf.function.
if remove:
saved_assert_equal = tf.check_ops.assert_equal
def NoOP(*args, **kwargs): # pylint: disable=unused-argument
return tf.no_op()
tf.check_ops.assert_equal = NoOP # Make assert_equal a no op.
try:
yield
finally:
tf.check_ops.assert_equal = saved_assert_equal
else:
yield
def _AssertInputsMatch(op, args, implicit_captures):
"""Assert that op's inputs match with args and implicit_captures.
Args:
op: The operation to check.
args: A nested structure representing the explicit arguments of 'op'.
implicit_captures: A nested structure representing the implicitly captured
inputs of 'op'.
Raises:
ValueError: if the number of inputs mismatch.
"""
expected_inputs = Flatten([args, implicit_captures])
expected_num_inputs = len(expected_inputs)
if len(op.inputs) > expected_num_inputs:
raise ValueError(('Too many inputs. The most likely cause is that fwd '
'captures additional tensors: extra inputs %r vs %r '
'captures=%r') % (list(op.inputs), list(expected_inputs),
list(Flatten(implicit_captures))))
if len(op.inputs) < expected_num_inputs:
raise ValueError(('Mismatched inputs to fwd: Found %d vs expected %d: %r'
'. Implicit captures(%d) = %r') %
(len(op.inputs), expected_num_inputs, list(op.inputs),
len(Flatten(implicit_captures)), implicit_captures))
def TensorSpecs(nmap, keep_shape=True):
"""Transforms tensors in the input nested structure to TensorSpecs."""
if nmap is None:
return None
fn = lambda t: tf.TensorSpec(t.shape if keep_shape else None, t.dtype)
return Transform(fn, nmap)
def _DefineDefun(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- output_dtypes: A nested structure compatible with the outputs of `fwd`
containing the corresponding output dtypes.
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
get_dtype = lambda x: x.dtype
arg_dtypes = Flatten(Transform(get_dtype, fwd_sig))
get_shape = lambda x: x.shape
arg_shapes = Flatten(Transform(get_shape, fwd_sig))
# Used to hold the backward function used by Grad, which will be defined if
# bak is set.
sigs = NestedMap()
# Output of this method.
res = NestedMap()
python_grad_func = None
if bak:
def Grad(op, *args):
"""Gradient function for the forward function.
Args:
op: The forward operation.
*args: Gradients wrt op.outputs.
Returns:
Tuple of derivatives.
"""
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs = op.inputs[:len(arg_dtypes)] # The rest are captures.
return sigs.backward(*Flatten([xs, op.outputs, args]))
python_grad_func = Grad
def _SetShape(dst_list, shape_list):
for dst, shape in zip(dst_list, shape_list):
if isinstance(dst, tf.Tensor):
dst.set_shape(shape)
@tf.Defun(*arg_dtypes, python_grad_func=python_grad_func, noinline=noinline)
def Forward(*args):
"""The forward function."""
_SetShape(args, arg_shapes)
with RemoveAssertContext(remove=noinline):
call = lambda: fwd(Pack(fwd_sig, args)) if args else fwd()
if device is None:
# Defun will handle the device assignment.
rets = call()
else:
with tf.device(device):
rets = call()
res.outputs = rets
return Flatten(rets)
forward = Forward
if not arg_dtypes:
# In this case Forward is an _OverloadedFunction, we need to instantiate it.
forward = Forward.instantiate([])
# Invokes fwd() to get res.outputs.
forward.add_to_graph(tf.get_default_graph())
res.func = forward
res.stateful_ops = forward.stateful_ops
res.captured_inputs = forward.captured_inputs
output_dtypes = Transform(get_dtype, res.outputs)
output_shapes = Transform(get_shape, res.outputs)
def Call(args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = forward()
else:
flat_rets = forward(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
_SetShape(flat_rets, Flatten(output_shapes))
return Pack(output_dtypes, flat_rets)
res.call = Call
if bak:
def Backward(*args):
"""The backward function."""
_SetShape(args, Flatten([arg_shapes, output_shapes, output_shapes]))
xs, ys, dys = Pack([fwd_sig, output_dtypes, output_dtypes], args)
with RemoveAssertContext(remove=noinline):
if device is None:
# Defun will handle the device assignment.
dxs = bak(xs, ys, dys)
else:
with tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
sigs.backward = tf.Defun(
*Flatten([arg_dtypes, output_dtypes, output_dtypes]),
noinline=noinline)(
Backward)
sigs.backward.add_to_graph(tf.get_default_graph())
else:
sigs.backward = Backward
return res
# Global variable to control rendezvous sharing in tf.function.
# If False (default) rendezvous sharing is disabled in tf.function, that is, the
# function body use a separate rendezvous and can't communicate with parent
# graph via send/recv.
# With _GetSharedRendezvous() == True, the function body share the same
# rendezvous with the parent graph and can talk to it using send/recv. This is
# useful for layers like StackedRecurrent.
_SHARED_RENDEZVOUS = ThreadLocalStack()
@contextlib.contextmanager
def _SharedRendezvousScope(shared_rendezvous=True):
_SHARED_RENDEZVOUS.stack.append(shared_rendezvous)
try:
yield
finally:
_SHARED_RENDEZVOUS.stack.pop()
def _GetSharedRendezvous():
"""Get the current rendezvous sharing setting."""
return _SHARED_RENDEZVOUS.stack[-1] if _SHARED_RENDEZVOUS.stack else False
def _ApplySharedRendezvous(func):
"""Apply the rendezvous sharing setting on the given tf.function func."""
# pylint: disable=protected-access
func._shared_rendezvous = _GetSharedRendezvous()
# pylint: enable=protected-access
def _WrapFunction(func=None, input_signature=None):
"""Wraps func as a tf.function."""
if input_signature is None:
input_signature = []
def Decorated(fn):
@tf.function(input_signature=input_signature, autograph=False)
def Fn(*args):
# TODO(b/163904067): mimic Defun' behavior and reset the step seed to
# avoid it being used as an implicit capture. This is not a desired
# behavior, it should take the step seed from parent graph instead.
ResetStepSeed()
# Mimic Defun and disable collection sharing.
graph = tf.get_default_graph()
# Don't share summaries collection with parent graph (b/168745134).
graph.clear_collection(tf.GraphKeys.SUMMARIES)
return fn(*args)
_ApplySharedRendezvous(Fn)
# Add the function to the graph so it'll be traced under the current
# context. This is necessary if the function body captures any non-tensor
# values from the environment, like symbolic maps.
cf = Fn.get_concrete_function()
cf.add_to_graph()
return cf
# For the `foo = _WrapFunction(foo, ...)` use case.
if func is not None:
return Decorated(func)
# For the `@_WrapFunction(...)` use case.
return Decorated
def _DefineFunction(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- outputs: The outputs of `fwd`. Used for reflection only (e.g. to get the
output dtypes, shapes, etc).
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
if device is None:
# Get the current device to mimic Defun's behavior.
# pylint: disable=protected-access
device_funcs = tf.get_default_graph()._device_functions_outer_to_inner
device = device_funcs[-1] if device_funcs else None
# pylint: enable=protected-access
# Output of this method.
res = NestedMap()
@_WrapFunction(input_signature=Flatten(fwd_sig))
def Forward(*args):
"""The forward function."""
with RemoveAssertContext(remove=noinline), tf.device(device):
if args:
xs = Pack(fwd_sig, args)
rets = fwd(xs)
else:
rets = fwd()
res.outputs = rets
return Flatten(rets)
res.captured_inputs = Forward.captured_inputs
# Get the stateful ops used in cell_fn. Logic borrowed from
# _EagerDefinedFunction.__init__().
graph = Forward.graph
input_ops = set(arg.op for arg in graph.inputs)
operations = [op for op in graph.get_operations() if op not in input_ops]
res.stateful_ops = [(o.name, o.type) for o in operations if o._is_stateful] # pylint: disable=protected-access
def Call(func, args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = func()
else:
flat_rets = func(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
return Pack(res.outputs, flat_rets)
if not bak:
res.func = Forward
res.call = lambda args=None: Call(Forward, args)
return res
shared_rendezvous = _GetSharedRendezvous()
ret_specs = TensorSpecs(res.outputs)
def Backward(*args):
xs, ys, dys = Pack([fwd_sig, ret_specs, ret_specs], args)
with RemoveAssertContext(remove=noinline), tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
backward_cf = _WrapFunction(
Backward, input_signature=Flatten([fwd_sig, ret_specs, ret_specs]))
else:
def BackwardWithSharedRendezvous(*args):
with _SharedRendezvousScope(shared_rendezvous):
return Backward(*args)
backward_cf = BackwardWithSharedRendezvous
@tf.custom_gradient
def ForwardWithGrad(*args):
"""Forward function and its custom gradient."""
# Note that `args` includes implicit captures. This is required by
# tf.custom_gradient so that when the Grad() outputs include gradients to
# implicit captures, they match the inputs to ForwardWithGrad().
#
# However, Forward doesn't take implicit captures as input, so we exclude
# them here.
fwd_args = args[:(len(args) - len(Flatten(res.captured_inputs)))]
op = NestedMap(inputs=args, outputs=Forward(*fwd_args))
def Grad(*args, **kwargs):
"""Gradient function for the forward function.
Args:
*args: Gradients wrt op.outputs.
**kwargs: Additional arguments from tf.custom_gradient.
Returns:
Tuple of derivatives.
"""
if kwargs:
tf.logging.warning(
'Ignoring additional arguments used by tf.custom_gradient: %s',
str(kwargs))
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs, _ = Pack([fwd_sig, res.captured_inputs], op.inputs)
return backward_cf(*Flatten([xs, op.outputs, args]))
return op.outputs, Grad
res.func = None
forward = lambda *xs: ForwardWithGrad(*Flatten([xs, res.captured_inputs]))
res.call = lambda args=None: Call(forward, args)
return res
# Global variable to control whether to use tf.function.
# If not set, the result is determined by tf2 status. See _UseTfFunction for
# details.
# TODO(laigd): remove after b/169869929 is fixed.
_USE_TF_FUNCTION = ThreadLocalStack()
# Constants for propagating framework tensors through Function.
_FRAMEWORK_TENSOR_GLOBAL_STEP = '_global_step'
@contextlib.contextmanager
def TfFunctionScope(use_tf_function=True):
_USE_TF_FUNCTION.stack.append(use_tf_function)
try:
yield
finally:
_USE_TF_FUNCTION.stack.pop()
def _UseTfFunction():
"""Whether to use tf.function instead of tf.Defun."""
if _USE_TF_FUNCTION.stack:
return _USE_TF_FUNCTION.stack[-1]
return tf2_enabled()
class Function(object):
"""Function builds a TensorFlow graph function from a callable.
In the high level this is similar to tf.Defun and tf.function. In fact this
relies on those as underlying implementations, but with specific configuration
so it's easier to use and can work well in some extreme cases in Lingvo.
Example usage:
- No inputs:
>>> @Function()
... def foo():
... return tf.constant(1.0)
>>> y = foo()
- Scalar input:
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32))
... def foo(x):
... return x * 2
>>> y = foo(1.0)
- List input:
>>> @Function(fwd_sig=[tf.TensorSpec(None, tf.float32) for _ in range(2)])
... def foo(xs):
... return xs[0] + xs[1]
>>> y = foo([1.0, 2.0])
- Nested input:
>>> @Function(fwd_sig=NestedMap(x=tf.TensorSpec(None, tf.float32)))
... def foo(nmap):
... return nmap.x * 2
>>> y = foo(NestedMap(x=1.0))
- With custom gradient function (other input types mentioned above are also
supported):
>>> def bar(x, y, dy):
... del y, dy
... return 4.0 * x * dy
>>>
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32), bak=bar)
... def foo(x):
... return 2.0 * x * x
- Used in control flow ops:
>>> then_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: x / 2)
>>> else_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: 3 * x + 1)
>>> y = tf.If(cond, inputs, then_branch.func, else_branch.func)
"""
# TODO(laigd): the use_tf_function option is added for backward compatibility
# reasons. Remove it after the migration.
def __init__(self,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Below we assume `fwd` is the input to `__call__` that is used to build the
TensorFlow graph function encapsulated by this object.
Args:
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
self._bak = bak
self._bak_as_function = bak_as_function
self._device = device
self._use_tf_function = use_tf_function
def __call__(self, fwd):
"""Creates a graph function.
Args:
fwd: a callable xs: Nested Structure -> ys: Nested Structure.
Returns:
A DefinedFunction object encapsulating `fwd` as a graph function.
"""
assert callable(fwd)
return DefinedFunction(fwd, self._fwd_sig, self._bak, self._bak_as_function,
self._device, self._use_tf_function)
class DefinedFunction(object):
"""Encapsulates a TensorFlow graph function and its properties."""
def __init__(self,
fwd,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure. Used to
build the TensorFlow graph function that this object encapsulates.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
wrapped_fwd_sig = fwd_sig
fwd_fn = fwd
bak_fn = bak
graph_random_seed = None
if tf.get_default_graph().seed is not None:
graph_random_seed = tf.get_default_graph().seed
# Wrap the forward function to propagate framework tensors like step_seed
# and global_step.
wrapped_fwd_sig = NestedMap()
self._added_global_step = False
if GetGlobalStep() is not None:
wrapped_fwd_sig[_FRAMEWORK_TENSOR_GLOBAL_STEP] = (
tf.TensorSpec([], tf.int64))
self._added_global_step = True
if fwd_sig is not None:
wrapped_fwd_sig.inputs = fwd_sig
elif not wrapped_fwd_sig:
wrapped_fwd_sig = None
def ForwardWrapped(wrapped_inputs=None):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
global_step = None
if wrapped_inputs:
assert isinstance(wrapped_inputs, NestedMap)
global_step = wrapped_inputs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)
with GlobalStepContext(global_step):
if wrapped_inputs and 'inputs' in wrapped_inputs:
result = fwd(wrapped_inputs.inputs)
else:
result = fwd()
return result
fwd_fn = ForwardWrapped
if bak:
# Wrap the backward function to return zero gradients for framework
# tensors like step_seed and global_step.
def BackwardWrapped(wrapped_xs, ys, dys):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
with GlobalStepContext(
wrapped_xs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)):
result = bak(wrapped_xs.inputs, ys, dys)
dxs = Transform(tf.zeros_like, wrapped_xs)
if isinstance(result, tuple) and len(result) == 2:
dxs.inputs, dcapture = result
return dxs, dcapture
else:
dxs.inputs = result
return dxs
bak_fn = BackwardWrapped
if use_tf_function is None:
use_tf_function = _UseTfFunction()
fn = _DefineFunction if use_tf_function else _DefineDefun
self._data = fn(
fwd=fwd_fn,
fwd_sig=wrapped_fwd_sig,
bak=bak_fn,
bak_as_function=bak_as_function,
device=device)
def __call__(self, args=None):
"""Invokes the graph function.
Args:
args: the inputs to the graph function, must be compatible with `fwd_sig`.
Returns:
The output tensors with the same structure as the output of `fwd`,
returned by a call to the graph function.
"""
assert IsCompatible(args,
self._fwd_sig), '{} vs {}'.format(args, self._fwd_sig)
return self._data.call(self.AddFrameworkInputs(args))
@property
def func(self):
"""The underlying TensorFlow graph function that this object encapsulates.
The returned graph function is created by tracing `fwd` during construction.
If not None, it will be a _DefinedFunction or ConcreteFunction that takes
flat inputs and returns flat outputs, and can be used by routines that
require a TensorFlow function object (e.g. tf.If, tf.While, etc).
If no backprop function is provided during construction, the result is
always not None.
"""
return self._data.func
def AddFrameworkInputs(self, inputs):
"""Add framework tensors like step_seed and global_step to inputs.
This is only necessary when using `func`, as wrapping is handled
automatically in __call__.
Args:
inputs: inputs to the function.
Returns:
Inputs wrapped with framework tensors suitable for use with `func`.
"""
result = NestedMap()
if self._added_global_step:
global_step = GetGlobalStep()
assert global_step is not None
result[_FRAMEWORK_TENSOR_GLOBAL_STEP] = tf.cast(global_step, tf.int64)
if inputs is not None:
result.inputs = inputs
return result if result else None
@property
def output_dtypes(self):
"""Output dtypes of the graph function.
The result will have the same structure as the outputs of `fwd` but contain
the corresponding output dtypes.
"""
return Transform(lambda x: x.dtype, self._data.outputs)
@property
def stateful_ops(self):
"""Stateful ops used by `fwd`, as a list of (op_name, op_type) tuples."""
return self._data.stateful_ops
@property
def captured_inputs(self):
"""Implicit input tensors captured by `fwd`."""
return self._data.captured_inputs
def CallDefun(fwd, args=None, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak and calls it with args.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
args: A Nested Structure of tf.Tensor or None.
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for fwd. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for bak.
device: the device on which to run fwd and bak.
Returns:
A Nested Structure equivalent to what fwd(args) computes.
"""
if args is not None:
args = Transform(tf.convert_to_tensor, args)
sigs = Function(
fwd_sig=TensorSpecs(args),
bak=bak,
bak_as_function=bak_as_function,
device=device)(
fwd=fwd)
if args is None:
return sigs()
else:
return sigs(args)
def If(cond, inputs, then_branch, else_branch):
"""Helper to construct an if/else statement.
Args:
cond: A scalar `Tensor` that can be converted to boolean.
inputs: A flattenable representing the input tensors of the if/else
statement. Can be None to represent no inputs.
then_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'else_branch' returns.
else_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'then_branch' returns.
Returns:
Output returned by the call to either 'then_branch' or 'else_branch'.
"""
fwd_sig = TensorSpecs(inputs)
then_sigs = Function(fwd_sig=fwd_sig)(fwd=then_branch)
else_sigs = Function(fwd_sig=fwd_sig)(fwd=else_branch)
assert IsCompatible(then_sigs.output_dtypes, else_sigs.output_dtypes), (
'Outputs of then_branch and else_branch are not compatible: {} vs {}'
.format(then_sigs.output_dtypes, else_sigs.output_dtypes))
if then_sigs.captured_inputs != else_sigs.captured_inputs:
raise ValueError('Differing captured inputs in then and else. '
'Ensure the same tensors are captured in the same order.')
ret = tf.If(
cond=cond,
inputs=Flatten(then_sigs.AddFrameworkInputs(inputs)) +
then_sigs.captured_inputs,
then_branch=then_sigs.func,
else_branch=else_sigs.func)
return Pack(then_sigs.output_dtypes, ret)
def _Itype():
"""Loop iterator data type."""
return tf.int32 if use_xla() else tf.int64
def WhileLoop(cond, body, loop_state):
"""Helper to construct a while loop.
Args:
cond: A callable NestedMap -> tf.bool.
body: A callable NestedMap -> NestedMap.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
fwd_sig = TensorSpecs(loop_state)
cond_sigs = Function(fwd_sig=fwd_sig)(fwd=cond)
def BodyWrapped(loop_state):
result = body(loop_state)
# loop_state is augmented with global tensors inside of DefinedFunction.
# WhileLoop needs to return the same structure as the inputs, so we augment
# the return value here to match.
result = cond_sigs.AddFrameworkInputs(result)
return result
body_sigs = Function(fwd_sig=fwd_sig)(fwd=BodyWrapped)
wrapped_inputs = body_sigs.AddFrameworkInputs(loop_state)
new_state = tf.While(
Flatten(wrapped_inputs), cond=cond_sigs.func, body=body_sigs.func)
# The functional `While` used above does not have a registered gradient.
# This was not a problem in Graph mode, however in Eager mode,
# GradientTape will attempt to call the gradient of the While op in the
# forward pass. `stop_gradient` is used to pretend the op is a constant
# in the forward pass. This also avoids calling the gradient of other ops in
# `While` in the forward pass.
# Details in https://www.tensorflow.org/api_docs/python/tf/custom_gradient.
# Guarded by 'IsEagerMode' to limit impact.
if IsEagerMode():
new_state = [tf.stop_gradient(t) for t in new_state]
return Pack(wrapped_inputs, new_state).inputs
def ForLoop(body, start, limit, delta, loop_state):
"""Helper to construct a for loop.
Args:
body: A callable (tf.int, NestedMap) -> NestedMap.
start: Loop variable's initial value.
limit: Loop variable's limit value.
delta: Loop variable's change per iteration.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
state = NestedMap(
iter=tf.cast(start, _Itype()),
limit=tf.cast(limit, _Itype()),
delta=tf.cast(delta, _Itype()),
loop_state=loop_state)
def LoopCond(state):
return tf.less(state.iter, state.limit)
def LoopBody(state):
state.loop_state = body(state.iter, state.loop_state)
state.iter = tf.add(state.iter, state.delta)
return state
return WhileLoop(LoopCond, LoopBody, state).loop_state
def TopK(x_in, k):
"""Equivalent to tf.math.top_k(x_in, k) but more efficient on tpu."""
assert k <= 2, 'This implementation is only efficient for small k.'
# TODO(yonghui): Try out an alternative idea where we first reshape x_in as a
# 2d tensor, then call tf.math.top_k, and then reshape back.
x_in_shape = x_in.shape
x_rank = x_in_shape.rank
assert x_rank and x_in_shape.as_list()[x_rank - 1] > 0
last_dim_size = x_in_shape.as_list()[x_rank - 1]
min_value = tf.math.reduce_min(x_in) - 1.0
out_indices = []
out_values = []
for unused_i in range(k):
index_i = tf.math.argmax(x_in, axis=-1, output_type=tf.int32)
mask_i = tf.one_hot(index_i, last_dim_size)
# TODO(yonghui): Would tf.gather be more efficient and numerically stable
# here?
value_i = tf.reduce_sum(mask_i * x_in, -1, keepdims=True)
x_in = (1.0 - mask_i) * x_in + mask_i * min_value
out_indices.append(tf.expand_dims(index_i, -1))
out_values.append(value_i)
if k == 1:
return out_values[0], out_indices[0]
else:
return tf.concat(out_values, x_rank - 1), tf.concat(out_indices, x_rank - 1)
def ReadVariable(var_op):
"""Returns the value of the given variable operation.
Args:
var_op: the `Operation` object for a VarHandleOp.
Raises:
TypeError: if var_op is not a VarHandleOp.
Returns:
A `Tensor` containing the value of the variable.
"""
if var_op.type != 'VarHandleOp':
raise TypeError('var_op should be a VarHandleOp, got %s' % str(var_op.type))
# Filter out the ReadVariableOps that have control dependencies to avoid
# side-effects when the user runs it.
filter_fn = lambda op: op.type == 'ReadVariableOp' and not op.control_inputs
var_readers = list(filter(filter_fn, var_op.outputs[0].consumers()))
assert var_readers
return var_readers[0].outputs[0]
_TPU_SUMMARY_TENSORS_KEY = ('__lingvo_tpu_summary_tensors')
_TPU_SUMMARY_CONTEXTS = ThreadLocalStack()
def _GetTpuSummaryTensor():
if _TPU_SUMMARY_CONTEXTS.stack:
return _TPU_SUMMARY_CONTEXTS.stack[-1]
return _CollectionGetter(_TPU_SUMMARY_TENSORS_KEY, lambda: [])()
@contextlib.contextmanager
def TpuSummaryTensorContext():
"""Creates a context where AddTpuSummaryTensor() will add tensors."""
_TPU_SUMMARY_CONTEXTS.stack.append([])
try:
yield
finally:
_TPU_SUMMARY_CONTEXTS.stack.pop()
def AddTpuSummaryTensor(name, value, weight=1.0):
"""Adds tensor to global collection of summaries, or a local context if any.
This needs to be used in situations where tf.summary() could be used but
currently tf.summary is not supported. Use py_utils.AddTpuSummaryTensor() in
low level code to add summary tensors to global collection of summaries.
Then recover all summary tensors from global collection by calling
py_utils.GetTpuSummaryTensors() from top level code (for example from
ComputeLoss method of BaseTask).
In addition to 'name' argument, current tensorflow name scope is also
captured and added to the metric name. This way for example summaries from
a repeated layer will appear as separate graphs in the tensorboard.
Weight argument is optional and defaults to 1.0. See BaseTask.ComputeLoss for
the exact definition of weight for eval metrics.
Args:
name: metric name
value: metric value tensor
weight: weight tensor for weighted metrics
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
x = NestedMap()
x.name = name
x.value = value, tf.convert_to_tensor(weight)
x.name_scope = tf.get_default_graph().get_name_scope()
tpu_summary_tensors.append(x)
def GetTpuSummaryTensors():
"""Returns summary tensors from global collection.
Returns:
A dict containing str keys and (metric, weight) pairs as values
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
return {
'%s/%s' % (x.name, SanitizeScopeKey(x.name_scope)): x.value
for x in tpu_summary_tensors
}
def ClearTpuSummaryTensors():
tpu_summary_tensors = _GetTpuSummaryTensor()
del tpu_summary_tensors[:]
def ComputationShape(split_size, topology=None):
"""Decides the computation shape based on the split_size.
Args:
split_size: number of accelerators to use per split.
topology: a serialized string of `tensorflow.tpu.TopologyProto`, or a
`tf.tpu.experimental.Topology` object, that describes the TPU cluster
topology. If not set, it'll use a default setting based on split_size.
Returns:
A 4-element list that describes the computation shape.
"""
if topology:
if isinstance(topology, tf.tpu.experimental.Topology):
topology_info = topology
else:
topology_info = tf_topology.Topology(serialized=topology)
computation_shape = None
if topology and functools.reduce(lambda a, b: a * b,
topology_info.mesh_shape) == split_size:
computation_shape = topology_info.mesh_shape
elif split_size == 1:
computation_shape = [1, 1, 1, 1]
elif topology and topology_info.mesh_shape[
-1] == 1 and split_size in topology_info.mesh_shape:
# For Megacore, if we find exact match on mesh shape, map split_size to it
computation_shape = [1, 1, 1, 1]
computation_shape[topology_info.mesh_shape.tolist().index(
split_size)] = split_size
else:
if topology:
cores_per_chip = topology_info.mesh_shape[-1]
else:
cores_per_chip = 2
assert split_size % cores_per_chip == 0
split_chips = split_size // cores_per_chip
if split_chips == 1:
computation_shape = [1, 1, 1, cores_per_chip]
elif split_chips == 2:
computation_shape = [1, 2, 1, cores_per_chip]
elif split_chips == 4:
computation_shape = [2, 2, 1, cores_per_chip]
elif split_chips == 8:
computation_shape = [4, 2, 1, cores_per_chip]
elif split_chips == 12:
computation_shape = [1, 1, 12, cores_per_chip]
elif split_chips == 16:
computation_shape = [4, 4, 1, cores_per_chip]
elif split_chips == 24:
computation_shape = [1, 2, 12, cores_per_chip]
elif split_chips == 32:
if topology and topology_info.mesh_shape[1] == 32:
# Fwd within-replica all-reduces is performed along column;
# Bwd gradient cross-replica all-reduces is performed along row.
# This currently has better performance than the strided patten.
computation_shape = [1, 32, 1, cores_per_chip]
else:
computation_shape = [4, 8, 1, cores_per_chip]
elif split_chips == 64:
computation_shape = [8, 8, 1, cores_per_chip]
elif split_chips == 128:
computation_shape = [8, 16, 1, cores_per_chip]
elif split_chips == 256:
computation_shape = [16, 16, 1, cores_per_chip]
elif split_chips == 512:
computation_shape = [16, 32, 1, cores_per_chip]
elif split_chips == 1024:
computation_shape = [32, 32, 1, cores_per_chip]
elif split_chips == 2048:
computation_shape = [64, 32, 1, cores_per_chip]
elif split_chips == 4096:
computation_shape = [128, 32, 1, cores_per_chip]
else:
assert False, ('Model parallelism with %d devices is currently not'
' supported.' % split_size)
assert computation_shape is not None
return computation_shape
def GetExtraVars():
"""Returns the captured variables by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.variable_captures
return function.get_extra_vars()
def GetExtraInputs():
"""Returns the captured input tensors by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.external_captures
return function.get_extra_inputs()
def GetExtraArgs():
"""Returns the corresponding function arguments for the captured inputs."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.internal_captures
return function.get_extra_args()
def ShardedFilePatternToGlob(file_pattern):
"""Converts a file pattern path@shards to path-?????-of-shards."""
if ',' in file_pattern:
raise ValueError(
'ShardedFilePatternToGlob does not support multiple file patterns.')
if '@' not in file_pattern:
return file_pattern
path, shards = file_pattern.split('@')
if shards == '*':
return f'{path}-?????-of-*'
return f'{path}-?????-of-{int(shards):05}'
def ComputeNceAndAuc(probs, targets, mask):
"""Compute normalized cross entropy and AUC of the PR curve for a batch.
Args:
probs: a tensor of shape [batch, time].
targets: a tensor of shape [batch, time], where each element is either 0 or
1 indicating wrong or correct.
mask: a tensor of shape [batch, time], a mask for hyp sequence.
Returns:
nce: a tensor of shape [1], the normalized cross entropy value.
auc: a tensor of shape [1], the AUC value.
"""
def LogWithClip(tensor, clip_value_min=1e-8):
"""Clip all elements of a tensor to a minimum before taking log."""
return tf.math.log(tf.clip_by_value(tensor, clip_value_min, 1.0))
bce = -targets * LogWithClip(probs) - (1 - targets) * LogWithClip(1 - probs)
num_cor = tf.reduce_sum(targets * mask)
num_tokens = tf.reduce_sum(mask)
wcr = num_cor / num_tokens
entropy = -wcr * LogWithClip(wcr) - (1 - wcr) * LogWithClip(1 - wcr)
avg_conditional_entropy = tf.reduce_mean(tf.boolean_mask(bce, mask))
nce = (entropy - avg_conditional_entropy) / entropy
auc = tf.metrics.auc(targets, probs, mask, curve='PR')[1]
return nce, auc
def GatherTensorValuesBySeqIndices(tensor, class_indices, keepdims=False):
"""Gather values from a 3d tensor according to sequences of indices.
Args:
tensor: a 3d tensor of [dim0, dim1, num_class], e.g. output from softmax.
class_indices: a 2d tensor of [dim0, dim1], where the second dim is a
sequence of class indices between 0 to num_class - 1, inclusive.
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
A tensor ret of [dim0, dim1], where
ret[b, t] = tensor[b, t, indices[b, t]].
If keepdims is True, then ret has shape [dim0, dim1, 1].
"""
tensor = HasRank(tensor, 3)
class_indices = HasRank(class_indices, 2)
tensor = HasShape(tensor, GetShape(class_indices), 2)
dim0 = GetShape(class_indices)[0]
dim1 = GetShape(class_indices)[1]
dim0_indices = tf.tile(tf.expand_dims(tf.range(dim0), axis=-1), [1, dim1])
dim1_indices = tf.tile(tf.expand_dims(tf.range(dim1), axis=0), [dim0, 1])
gather_indices = tf.stack([
tf.cast(dim0_indices, dtype=class_indices.dtype),
tf.cast(dim1_indices, dtype=class_indices.dtype), class_indices
],
axis=-1)
ret = tf.gather_nd(tensor, gather_indices)
if keepdims:
ret = tf.expand_dims(ret, axis=-1)
return ret
def GetSoftmaxProbsBySeqIndices(logits, indices, keepdims=False):
"""Get softmax probabilities from index sequences given logits sequences.
Args:
logits: a tensor of [batch, time, num_class] or [time, batch, num_class].
indices: a tensor of [batch, time] or [time, batch].
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
a tensor of [batch, time] or [time, batch] for the corresponding softmax
probabilities. If keepdims is True, returned tensor has a third dimension
of size 1.
"""
probs = tf.nn.softmax(logits)
return GatherTensorValuesBySeqIndices(probs, indices, keepdims)
def DivideNoNan(x, y):
"""Equivalent to tf.math.divide_no_nan but supports bfloat16."""
safe_y = tf.where(tf.equal(y, 0.), tf.ones_like(y), y)
return tf.where(tf.equal(y, 0.0), tf.zeros_like(x), x / safe_y)
def SequencePaddings(seqlen, maxlen=None):
mask = tf.sequence_mask(seqlen, maxlen, dtype=tf.float32)
return 1 - mask
def AppendDims(x, ndims):
return tf.reshape(x, GetShape(x) + [1] * ndims)
def MaybeSoftCapLogits(x, cap=0.0):
"""Caps logits x to be within a certain range.
Args:
x: A float tensor, the logit values to be capped.
cap: a float, the limit to cap x within. If cap <= 0.0, x is not capped.
Returns:
logits after capping.
"""
if cap <= 0.0:
return x
else:
return cap * tf.math.tanh(x / cap)
def GetTpuEmbeddingGraphCollection():
"""Return the graph collection that stores the TpuEmbeddingCollection."""
tpu_emb_graph_collection = tf.get_collection_ref('__tpu_embedding_collection')
assert len(tpu_emb_graph_collection) <= 1
return tpu_emb_graph_collection
class AuxLossContext:
"""Context that holds a list of aux-losses.
By default it is non-reentrant, but can be specified as reentrant explicitly
when creating an inner context.
"""
_global_stack = []
@classmethod
def Current(cls):
"""Returns current context or None."""
if cls._global_stack:
return cls._global_stack[-1]
else:
return None
def __init__(self, reentrant=False):
self.aux_loss_tensors = []
self._reentrant = reentrant
def AddLoss(self, loss):
self.aux_loss_tensors.append(loss)
@property
def aux_losses(self):
return self.aux_loss_tensors
def __enter__(self):
if not self._reentrant:
assert not self._global_stack, 'no re-entry'
self._global_stack.append(self)
return self
def __exit__(self, *args):
self._global_stack.pop()
def GetTrainableVariables(scope, bprop_variable_filter,
bprop_variable_exclusion, vmap):
"""Returns trainable vars.
Args:
scope: A Python str.
bprop_variable_filter: see BaseTask.Params().bprop_variable_filter.
bprop_variable_exclusion: see BaseTask.Params().bprop_variable_exclusion.
vmap: A NestedMap of var_path(str) -> tf Variable.
Returns:
A filtered NestedMap of var_path(str) -> trainable tf Variable.
"""
pos = re.compile(bprop_variable_filter) if bprop_variable_filter else None
neg = re.compile(
bprop_variable_exclusion) if bprop_variable_exclusion else None
def VariableFilter(v):
"""Returns True if variable v should be optimized by this learner."""
if not v.trainable:
return False
if pos and not pos.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_filter: %s', scope,
v.name)
return False
if neg and neg.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_exclusion: %s', scope,
v.name)
return False
return True
return vmap.Filter(VariableFilter)
| # Lint as: python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities."""
# ==============================================================================
# Note: Avoid adding dependencies to py_utils beyond standard python packages
# and tensorflow.
# ==============================================================================
import collections as py_collections
import contextlib
import functools
import hashlib
import inspect
import math
import numbers
import os
import pkgutil
import re
import threading
import traceback
import typing
from typing import Optional, Union
import lingvo.compat as tf
from lingvo.core import cluster_factory
from lingvo.core import gshard_utils
from lingvo.core import hyperparams
from lingvo.core import nested_map
from lingvo.core import ops
from lingvo.core import py_utils_flags
from lingvo.core import retry
from lingvo.core import symbolic
from lingvo.core import thread_local_utils
from lingvo.core import tshape
import numpy as np
import six
# pylint: disable=g-direct-tensorflow-import
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import function
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import stateless_random_ops
from tensorflow.python.tf2 import enabled as tf2_enabled
from tensorflow.python.tpu import topology as tf_topology
from tensorflow.python.tpu import tpu_function
from tensorflow.python.util import deprecation
# pylint: enable=g-direct-tensorflow-import
FLAGS = tf.flags.FLAGS
# pylint: disable=protected-access
_FromGlobal = py_utils_flags._FromGlobal
# pylint: enable=protected-access
use_xla = py_utils_flags.use_xla
use_tpu = py_utils_flags.use_tpu
testonly_skip_norm_layers = py_utils_flags.testonly_skip_norm_layers
tpu_compat = py_utils_flags.tpu_compat
use_stateless_vars_init = py_utils_flags.use_stateless_vars_init
ENQUEUE_OPS = '__lingvo_enqueue_ops'
# pylint: disable=protected-access
deprecation._PRINT_DEPRECATION_WARNINGS = False
# pylint: enable=protected-access
ThreadLocalStack = thread_local_utils.ThreadLocalStack
ThreadLocalDict = thread_local_utils.ThreadLocalDict
NestedMap = nested_map.NestedMap
def Assert(condition, data, *args, **kwargs):
if py_utils_flags.enable_asserts():
return tf.Assert(condition, data, *args, **kwargs)
else:
return tf.no_op()
def assert_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_greater_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_greater(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_greater(*args, **kwargs)
else:
return tf.no_op()
def assert_less_equal(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.debugging.assert_less_equal(*args, **kwargs)
else:
return tf.no_op()
def assert_less(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return tf.assert_less(*args, **kwargs)
else:
return tf.no_op()
def assert_between(x, l, r, *args, **kwargs): # pylint: disable=invalid-name
x = tf.convert_to_tensor(x)
l = tf.cast(tf.convert_to_tensor(l), x.dtype)
r = tf.cast(tf.convert_to_tensor(r), x.dtype)
return tf.group([
assert_greater_equal(x, l, *args, **kwargs),
assert_less(x, r, *args, **kwargs)
])
def assert_shape_match(*args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
kwargs['msg'] = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(
r'.*/', '', filepath), line, func)
return ops.assert_shape_match(*args, **kwargs)
else:
return tf.no_op()
def assert_same_dim0(xs, *args, **kwargs): # pylint: disable=invalid-name
if py_utils_flags.enable_asserts():
return ops.assert_same_dim0(xs, *args, **kwargs)
else:
return tf.no_op()
def assert_even_divide(denorm, num): # pylint: disable=invalid-name
"""Asserts that denorm is evenly divided by num."""
denorm = tf.convert_to_tensor(denorm)
num = tf.convert_to_tensor(num)
if denorm.dtype not in (tf.int32, tf.int64):
raise ValueError('denorminator.dtype is not tf.int32 or tf.int64.')
if num.dtype not in (tf.int32, tf.int64):
raise ValueError('numerator.dtype is not tf.int32 or tf.int64.')
num = HasShape(num, GetShape(denorm))
quo = denorm // num
return assert_equal(quo * num, denorm)
def AssertIdShape(expected_ids_shape_pattern, ids_shape, *args):
"""Asserts shape expected_ids_shape_pattern matches all other input shapes."""
def AssertFn(inputs):
dependencies = [
assert_shape_match(inputs.ids_shape, inputs.expected_ids_shape_pattern)
] + [
assert_shape_match(inputs.ids_shape, x_shape) for x_shape in inputs.args
]
return with_dependencies(dependencies, inputs.ids_shape)
inputs = NestedMap(
expected_ids_shape_pattern=expected_ids_shape_pattern,
ids_shape=ids_shape,
args=args)
return CallDefun(AssertFn, Transform(tf.convert_to_tensor, inputs))
def _CheckNumerics(x, message=None, *args, **kwargs):
if x.dtype.is_floating:
x_name = x.name if not tf.executing_eagerly() else '[eager]'
if 'name' not in kwargs:
kwargs['name'] = re.sub(r':\d+', '', x_name) + '_CheckNumerics'
return tf.debugging.check_numerics(x, message if message else x_name, *args,
**kwargs)
else:
return x
def CheckNumerics(inp, message=None, *args, **kwargs):
"""Check numerics for tensors in inp."""
if not py_utils_flags.enable_check_numerics():
return inp
if isinstance(inp, list):
return [_CheckNumerics(x, message, *args, **kwargs) for x in inp]
if isinstance(inp, tuple):
return tuple(_CheckNumerics(x, message, *args, **kwargs) for x in inp)
return _CheckNumerics(inp, message, *args, **kwargs)
def with_dependencies(dependencies, output_tensor): # pylint: disable=invalid-name
with tf.control_dependencies(dependencies):
return tf.identity(output_tensor)
def _VarInCollection(var, collection):
"""Return whether a variable `var` is in the given variable collection."""
# We use variable reference for comparison, since variable is not hashable in
# eager mode.
return var.ref() in [v.ref() for v in collection]
@contextlib.contextmanager
def _PrintOptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
def _Print(name, x):
with _PrintOptions(linewidth=1000):
tf.logging.info('%s = %s', name, np.array_repr(x))
def Log(value, prefix, **kwargs):
"""Prints out values of tensors.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Log(z, 'debug compute()', x=x, y=y)
Args:
value: A Tensor. Log happens after this tensor's computed.
prefix: Every tensor is logged with this prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
# Ensures tensors are printed in order.
last = value
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Print, [prefix + ' : ' + k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def Debug(tensor, message='', enabled=True, summarize=100, more=None):
"""Wrapper around tf.Print() and tf.logging.info() to simplify debug printing.
x = py_utils.Debug(x)
When the graph is built a regular log info line will be printed:
-DBG- py_utils_test.py:429 x=Tensor(...
Then when the tensor node is evaluated it will print lines like:
-DBG- py_utils_test.py:429 x Const:0[x.shape=][2 2][x=][[1 2][3 4]]
WARNING: The code that parses local variable names can fail. E.g. don't write
two Debug() calls on one line or a Debug() call that spans more than one line.
Args:
tensor: A tensor to print.
message: A message to print.
enabled: To enable the debugging.
summarize: Integer with number of tensor values to print.
more: An optional list of additional tensors.
Returns:
The tensor.
"""
if not enabled or _FromGlobal('disable_py_utils_debug'):
return tensor
if more is None:
more = []
stack = inspect.stack()[1][0]
caller = inspect.getframeinfo(stack)
caller_var = ''
caller_more_vars = []
if caller.code_context:
# Rough and likely to fail. But better than nothing.
match = re.compile(r'Debug\((.*?)(\)|,).*$').search(caller.code_context[0])
if match:
caller_var = match.groups()[0]
if more:
more_vars = re.compile(r'more=\[(.*?)\].*$').search(
caller.code_context[0]).groups()[0]
if more_vars:
caller_more_vars = more_vars.split(',')
the_class = ''
if 'self' in stack.f_locals:
the_class = stack.f_locals['self'].__class__.__name__
header = '-DBG- {}:{}:{}:{} {} '.format(
os.path.basename(caller.filename), the_class, caller.function,
caller.lineno, message)
info = '{}{}={}'.format(header, caller_var, tensor)
for name, val in zip(caller_more_vars, more):
info += ' {}={}'.format(name.strip(), val)
tf.logging.info(info)
if isinstance(tensor, tf.Tensor):
tensors = []
tensors += [tf.constant('{}.shape='.format(caller_var)), tf.shape(tensor)]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}.shape='.format(name.strip())), tf.shape(val)]
tensors += [tf.constant('{}='.format(caller_var)), tensor]
for name, val in zip(caller_more_vars, more):
tensors += [tf.constant('{}='.format(name.strip())), val]
name = tensor.name if not tf.executing_eagerly() else '[eager]'
info = '{}{} {}'.format(header, caller_var, name)
return tf.identity(
tf.Print(tensor, tensors, info, summarize=summarize),
re.sub(':.*$', '', name))
return tensor
def _Save(steps, prefix, key, val):
filename = '%s.%08d.%s.npy' % (six.ensure_text(prefix), steps,
six.ensure_text(key))
with tf.io.gfile.GFile(filename, 'w') as outfile:
np.save(outfile, val)
def Save(value, filename_prefix, **kwargs):
"""Saves values of tensors into files.
Useful for debugging. E.g.,
x = ... a tf.Tensor ...
y = ... a tf.Tensor ...
z = compute(x, y)
z = Save(z, '/path/tmp', x=x, y=y, z=z)
Args:
value: A Tensor. Saving happens after this tensor is computed.
filename_prefix: Every tensor is saved with this filename prefix.
**kwargs: keywords and tensors. Tensors are logged in the sort order of
these keywards.
Returns:
value is returned.
"""
last = value
steps = GetGlobalStep()
for k in sorted(kwargs):
with tf.control_dependencies([last]):
last = tf.py_func(_Save, [steps, filename_prefix, k, kwargs[k]], [])
with tf.control_dependencies([last]):
return tf.identity(value)
def HasRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has the expected rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims == expected_rank, (
'Ranks did not match, got %d, '
'expected %d') % (tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies([tf.assert_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def HasAtLeastRank(tensor, expected_rank):
"""Syntactic sugar for asserting that tensor has rank >= expected_rank."""
if tensor.shape.ndims is not None and isinstance(expected_rank, int):
assert tensor.shape.ndims >= expected_rank, (
'Rank of tensor %d did not exceed the expected value %d.') % (
tensor.shape.ndims, expected_rank)
return tensor
if py_utils_flags.enable_asserts():
return with_dependencies(
[tf.debugging.assert_greater_equal(tf.rank(tensor), expected_rank)],
tensor)
else:
return tensor
def GetRank(tensor):
"""Returns tensor's rank as an int if it's available, otherwise a Tensor.
Args:
tensor: The input tensor.
Returns:
Either an int or a Tensor for the rank of the input tensor.
"""
if tensor.shape.ndims is not None:
return tensor.shape.ndims # int
else:
return tf.rank(tensor) # Tensor
def GetShape(tensor, ndims=None):
"""Returns tensor's shape as a list which can be unpacked, unlike tf.shape.
Tries to return static shape if it's available. Note that this means
some of the outputs will be ints while the rest will be Tensors.
Args:
tensor: The input tensor.
ndims: If not None, returns the shapes for the first `ndims` dimensions.
"""
tensor = tf.convert_to_tensor(tensor)
dynamic_shape = tf.shape(tensor)
# Early exit for unranked tensor.
if tensor.shape.ndims is None:
if ndims is None:
return dynamic_shape
else:
return [dynamic_shape[x] for x in range(ndims)]
# Ranked tensor.
if ndims is None:
ndims = tensor.shape.ndims
else:
ndims = min(ndims, tensor.shape.ndims)
# Return mixture of static and dynamic dims.
static_shape = tensor.shape.as_list()
shapes = [
static_shape[x] if static_shape[x] is not None else dynamic_shape[x]
for x in range(ndims)
]
return shapes
def HasShape(tensor, expected_shape, ndims=None):
"""Syntactic sugar for asserting that tensor has the expected shape.
Args:
tensor: A Tensor.
expected_shape: A Python list or a 1D tensor. Elements of expected_shape can
be -1 which indicate that any size is valid for that dimension.
ndims: If not None, check only the first `ndims` dimensions of `tensor`.
Must be equal to the length of `expected_shape` if not None.
Returns:
The input `tensor` with control dependencies that will raise a runtime
error if dynamic shape checks fail.
Raises:
ValueError: A value error if the assertion fails at static shape checks.
"""
if not py_utils_flags.enable_asserts():
return tensor
filepath, line, func, _ = traceback.extract_stack(limit=3)[-2]
msg = 'LINGVO ASSERT %s:%s(%s)' % (re.sub(r'.*/', '',
filepath), line, func)
tensor_shape = GetShape(tensor)
if ndims is not None:
tensor_shape = tensor_shape[:ndims]
# TODO(jngiam): Attempt to switch back to tf.Assert after it has better
# support on GPUs.
assert_op = ops.assert_shape_match(tensor_shape, expected_shape, msg=msg)
# If expected_shape is a Tensor, then we are unable to perform static checks.
# In this case, we can do a dynamic check and return.
if isinstance(expected_shape, tf.Tensor):
return with_dependencies([assert_op], tensor)
# Infer ranks from the inputs.
expected_rank = len(expected_shape)
if isinstance(tensor_shape, tf.Tensor):
tensor_rank = tensor.shape.ndims
else:
tensor_rank = len(tensor_shape)
# If ndims is None, then either one of the ranks should not be None, or they
# should both match. If both ranks are None, then they are both tensors and
# should be caught by the earlier short-circuit.
if ndims is None:
if (tensor_rank is not None) and (expected_rank != tensor_rank):
raise ValueError('Tensor does not match rank of expected shape.\n'
'Tensor shape: {} Expected shape: {}'.format(
tensor_shape, expected_shape))
# Both tensors can be assumed to be of same rank.
ndims = expected_rank
else:
if (tensor_rank is not None) and (tensor_rank < ndims):
raise ValueError('Tensor has fewer dimensions than ndims.\n'
'Tensor shape: {} ndims: {}'.format(tensor_shape, ndims))
if expected_rank != ndims:
raise ValueError(
'Expected shape must have number of dimensions equal to ndims.\n'
'Expected shape: {} ndims: {}'.format(expected_shape, ndims))
# Ensure that both tensor_shape and expected_shape are both lists.
tensor_shape = tensor_shape[:ndims]
if isinstance(tensor_shape, tf.Tensor):
tensor_shape = tf.unstack(tensor_shape, num=ndims)
# Map tf.Dimension values to their held values.
tensor_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in tensor_shape
]
expected_shape = [
v.value if isinstance(v, tf.Dimension) else v for v in expected_shape
]
all_static_checks = True
for idx, (dim, expected_dim) in enumerate(zip(tensor_shape, expected_shape)):
if isinstance(expected_dim, tf.Tensor):
all_static_checks = False
elif expected_dim == -1:
continue
elif isinstance(dim, tf.Tensor):
all_static_checks = False
elif dim != expected_dim:
raise ValueError('Tensor does not match expected shape on dimension {}.\n'
'Tensor shape: {} Expected shape: {}'.format(
idx, tensor_shape, expected_shape))
if all_static_checks:
return tf.convert_to_tensor(tensor)
else:
return with_dependencies([assert_op], tensor)
def HasSameShape(x, ref):
return HasShape(x, GetShape(ref))
def GetSize(tensor):
shape = GetShape(tensor)
if (isinstance(shape, tf.Tensor) or
any([isinstance(x, tf.Tensor) for x in shape])):
return tf.size(tensor)
return np.prod(shape)
def CausalSelfAttenPadding(seqlen, dtype):
"""Wraps tf.linalg.band_part() for tflite compatibility."""
if FLAGS.tflite_compatible:
# [N, 1]
rows = tf.expand_dims(tf.range(seqlen), -1)
# [1, N]
cols = tf.expand_dims(tf.range(seqlen), 0)
row_cols = rows - cols
return tf.where(row_cols < 0, tf.ones([seqlen, seqlen], dtype),
tf.zeros([seqlen, seqlen], tf.float32))
else:
return 1.0 - tf.linalg.band_part(
tf.ones([seqlen, seqlen], dtype=dtype), -1, 0)
def outside_all_rewrites(): # pylint: disable=invalid-name
return tf.control_dependencies(None)
# TODO(jamesqin): remove once b/147439702 is fixed.
_OUTSIDE_COMPILATION = threading.local()
def RunOnTpuHost(func, *args, **kwargs):
r"""Runs the given function call on TPU host.
Invokes func(\*args, \*\*kwargs) directly if not running on tpu.
Args:
func: the function to invoke.
*args: args of func
**kwargs: kwargs of func
Returns:
The function return value.
"""
if use_tpu() and not getattr(_OUTSIDE_COMPILATION, 'on', False):
_OUTSIDE_COMPILATION.on = True
res = tf.tpu.outside_compilation(func, *args, **kwargs)
_OUTSIDE_COMPILATION.on = False
else:
res = func(*args, **kwargs)
return res
def tpu_host(func): # pylint: disable=invalid-name
r"""Decorates a python function to only run on TPU hosts.
This function has no effect when running on CPU/GPU.
Example::
@py_utils.tpu_host()
def ComputeWER(self):
# Call a custom op computing WER.
Args:
func: the function to invoke
Returns:
A TPU-host only function
"""
def Wrapped(*args, **kwargs):
return RunOnTpuHost(func, *args, **kwargs)
return Wrapped
# Maps a TPU job name ('/job:xxx') to the job's DeviceAssignment object.
# When there is only a single TPU job, the key could be None.
_tpu_device_assignment_dict = dict()
def SetTpuDeviceAssignment(tpu_device_assignment, job=None):
if job in _tpu_device_assignment_dict:
tf.logging.warning('tpu_device_assignment was already set, '
'overwriting with new assignment.')
_tpu_device_assignment_dict[job] = tpu_device_assignment
# This function should called in unittest only.
def ClearTpuDevice():
global _tpu_device_assignment_dict
_tpu_device_assignment_dict = dict()
def GetTpuDeviceAssignment(job=None):
return _tpu_device_assignment_dict[job]
# Whether it's running in eager mode. This is different than
# tf.executing_eagerly(), which will return False inside a tf.function.
_IS_EAGER_MODE = False
def SetEagerMode(eager_mode=True):
global _IS_EAGER_MODE
_IS_EAGER_MODE = eager_mode
if eager_mode:
tf.enable_eager_execution()
tf.config.set_soft_device_placement(True)
else:
tf.disable_eager_execution()
def IsEagerMode():
return _IS_EAGER_MODE
# Maintains a tf.GradientTape stack.
_GRADIENT_TAPE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GradientTape(*args, **kwargs):
"""Creates a tf.GradientTape and use it for automatic differentiation."""
tape = tf.GradientTape(*args, **kwargs)
_GRADIENT_TAPE_STACK.stack.append(tape)
try:
with tape:
yield
finally:
_GRADIENT_TAPE_STACK.stack.pop()
# The tf.train.ExponentialMovingAverage singleton used by all subtasks in
# multi-task training with ExecutorTpu.
_EXECUTOR_EMA = None
def SetExponentialMovingAverage(ema):
global _EXECUTOR_EMA
assert ema
assert not _EXECUTOR_EMA, 'EMA was set before.'
_EXECUTOR_EMA = ema
def ExponentialMovingAverage():
return _EXECUTOR_EMA
def SessionConfig(soft_placement=True,
inline=True,
cluster_def=None,
disable_meta_optimizer=False):
"""Returns a session config proto.
Args:
soft_placement: Turns allow_soft_placement on iff True.
inline: Turns do_function_inlining on iff True.
cluster_def: A tf.train.ClusterDef describing the cluster.
disable_meta_optimizer: Turns off grappler/metagraph optimizer.
Returns:
A TF session config proto.
"""
session_config = tf.config_pb2.ConfigProto(
allow_soft_placement=soft_placement,
graph_options=tf.GraphOptions(
optimizer_options=tf.OptimizerOptions(
opt_level=tf.OptimizerOptions.L1, do_function_inlining=inline)),
cluster_def=cluster_def)
session_config.share_cluster_devices_in_session = True
if disable_meta_optimizer:
# Useful if start-up time is critical.
session_config.graph_options.rewrite_options.disable_meta_optimizer = True
# Disable layout optimizer which increases GPU memory usage.
session_config.graph_options.rewrite_options.layout_optimizer = (
rewriter_config_pb2.RewriterConfig.OFF)
return session_config
def AssertIsCompatible(a, b):
assert a.IsCompatible(b), ('%s vs %s' % (a, b))
def SetShapes(dst_nmap, src_nmap):
"""Set shapes in dst_nmap using those in src_nmap."""
AssertIsCompatible(src_nmap, dst_nmap)
for src, dst in zip(src_nmap.Flatten(), dst_nmap.Flatten()):
dst.set_shape(src.shape)
def Dtypes(nmap_list):
"""Returns all tensors' data types in a list."""
return [v.dtype for v in Flatten(nmap_list)]
def Flatten(x):
"""Flattens 'x' by extracting tensors from nested structures to a list."""
return tf.nest.flatten(x)
def Pack(tmpl, values):
"""Packs 'values' according to 'tmpl'."""
return tf.nest.pack_sequence_as(tmpl, values)
def Transform(fn, *v):
"""Replaces every nested value x in 'v' with fn(x) and returns the result."""
return tf.nest.map_structure(fn, *v)
def ConvertNoneGradientToZeros(xs, dxs):
"""Sanitize dxs so that None becomes zeros appropriately.
Args:
xs: A list of tensors.
dxs: A list of tensors. dxs[i] corresponds to xs[i]'s gradient.
Returns:
A `.NestedMap` same as dxs with None replaced by a zero tensor.
"""
fn = lambda x, dx: tf.zeros_like(x) if dx is None else dx
return Transform(fn, xs, dxs)
def IsCompatible(lhs, rhs):
"""Returns true if lhs and rhs are compatible."""
try:
tf.nest.assert_same_structure(lhs, rhs)
return True
except (ValueError, TypeError):
return False
class _Unique:
"""A helper to uniqify variables in a NestedMap."""
def __init__(self):
self._vset = set()
def __call__(self, v):
if (v is None) or (id(v) in self._vset):
return False
else:
self._vset.add(id(v))
return True
def ToUniqueList(nmap):
"""Returns the flattened `nmap` with duplicates removed."""
return nmap.Filter(_Unique()).Flatten()
def ReadOnlyAttrDictView(backing):
"""Wraps a dict to provide a read-only view of its contents.
Dict keys can also be accessed by attribute.
Args:
backing: Dict-like object to wrap.
Returns:
Read-only Mapping that can be accessed by index (['foo']) or attr (d.foo).
"""
class Wrapper:
"""Wrapper object."""
# Disable pytype attribute checking.
_HAS_DYNAMIC_ATTRIBUTES = True
def __getitem__(self, key):
return backing[key]
def __len__(self):
return len(backing)
def __iter__(self):
return iter(backing)
def __getattr__(self, key):
return backing[key]
def __hasattr__(self, key):
return key in backing
def __setattr__(self, key, value):
raise AttributeError('Dictionary is read-only.')
def __setitem__(self, key, value):
raise AttributeError('Dictionary is read-only.')
return Wrapper()
def ToStaticShape(shape):
"""Converts 'shape' to a static shape."""
if isinstance(shape, (list, tuple)):
shape = [
dim.value if isinstance(dim, tf.Dimension) else dim for dim in shape
]
static_shape = []
for dim in shape:
if symbolic.IsExpr(dim):
static_shape.append(symbolic.ToStatic(dim))
else:
static_shape.append(dim)
return static_shape
else:
return shape.value if isinstance(shape, tf.Dimension) else shape
def Zeros(shape, *args, **kwargs):
return tf.zeros(ToStaticShape(shape), *args, **kwargs)
class UniformSampler:
"""A reservoir sampler.
This class implements reservoir sampling: Given a limit of `num_samples` total
samples, this class maintains a uniform probability (1 / `num_samples`) of
keeping any item dynamically added to the sampler.
See https://en.wikipedia.org/wiki/Reservoir_sampling for details.
"""
def __init__(self, num_samples):
assert num_samples > 0
self._num_samples = num_samples
self._num_seen_items = 0
self._samples = []
def Add(self, item):
"""Add item to sampler."""
self._num_seen_items += 1
if len(self._samples) < self._num_samples:
self._samples.append(item)
return
index = np.random.randint(0, self._num_seen_items)
if index < self._num_samples:
self._samples[index] = item
@property
def samples(self):
"""Fetch the current samples from the sampler."""
return self._samples
class RNNCellStateInit:
"""State initialization functions for RNN cell init state."""
@staticmethod
def _Params(method, seed):
p = hyperparams.Params()
p.Define('method', method,
'Initialization method. Should be one of zeros, random_normal.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Freeze()
return p
@staticmethod
def Zeros():
"""tf.zeros()."""
return RNNCellStateInit._Params('zeros', seed=None)
@staticmethod
def RandomNormal(seed=None):
"""tf.random.normal()."""
return RNNCellStateInit._Params('random_normal', seed)
def DefaultRNNCellStateInit():
return RNNCellStateInit.Zeros()
def InitRNNCellState(shape, init=None, dtype=None, name=None, is_eval=False):
"""Initial state definitions for RNN cell implementations.
Args:
shape: A array of ints/symbols for specifying the shape of the state.
init: Hyperparameters as returned by one of the static implemetaitons in
RNNCellStateInit.
dtype: The dype of the states. Defaults to tf.float32.
name: A name for the operation. If --stateless_vars_init is set, this name
is used to generate a seed on a per-variable basis. Otherwise, this name
is optional.
is_eval: Bool, set to True if we need special behavior in eval mode.
Returns:
A Tensor of the specified shape, and sampled from the distribution as
defined by the init parameters.
"""
shape = ToStaticShape(shape)
if init is None:
init = DefaultRNNCellStateInit()
if dtype is None:
dtype = tf.float32
method = init.method
if ((method in ['zeros']) or (method in ['random_normal'] and is_eval)):
init_state = tf.zeros(shape=shape, dtype=dtype, name=name)
elif method in ['random_normal']:
if use_stateless_vars_init():
if name is None:
raise ValueError('InitRNNCellState() requires a `name` argument when '
'--stateless_vars_init is enabled.')
seed = _GenerateStatelessRngSeed(name, init.seed)
init_state = stateless_random_ops.stateless_random_normal(
shape=shape, dtype=dtype, name=name, seed=seed)
else:
init_state = tf.random.normal(
shape=shape, dtype=dtype, name=name, seed=init.seed)
else:
raise ValueError('Initialization method (%s) not supported.' % method)
return init_state
class WeightInit:
"""Static class providing weight initialization config params."""
@staticmethod
def _Params(method, scale, seed, custom_v_init=None):
"""Parameters of this class."""
p = hyperparams.Params()
p.Define('method', method, 'Initialization method.')
p.Define('scale', scale, 'Initialization scale.')
p.Define('seed', seed, 'Random seed used to generate initial values.')
p.Define('custom_v_init', custom_v_init,
'A custom tf.init_ops.Initializer instance.')
p.Freeze()
return p
@staticmethod
def Gaussian(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1.0)."""
return WeightInit._Params('gaussian', scale, seed)
@staticmethod
def Uniform(scale=1.0, seed=None):
"""scale * tf.random.uniform(-1.0, 1.0)."""
return WeightInit._Params('uniform', scale, seed)
@staticmethod
def UniformPositive(scale=1.0, seed=None):
"""scale * tf.random.uniform(0., 1.0)."""
return WeightInit._Params('uniform_positive', scale, seed)
@staticmethod
def Category(scale=2, seed=None):
"""tf.floor(scale * tf.random.uniform(0., 1.0))."""
return WeightInit._Params('category', scale, seed)
@staticmethod
def Xavier(scale=1.0, seed=None):
"""Xavier initialization (x = sqrt(6. / (in + out)); [-x, x])."""
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def XavierWithFixupParams(scale=1.0,
depth=1.0,
layers_per_residual_block=1.0,
seed=None):
"""Xavier initialization with Fixup."""
scale = scale * math.pow(depth, (-1.0 / (2 * layers_per_residual_block)))
return WeightInit._Params('xavier', scale, seed)
@staticmethod
def GeoMeanXavier(scale=1.0, seed=None):
"""A variant of Xavier (x = sqrt(3. / sqrt(in * out)); [-x, x])."""
return WeightInit._Params('geo_mean_xavier', scale, seed)
@staticmethod
def Constant(scale=1.0):
"""scale."""
return WeightInit._Params('constant', scale, 0)
@staticmethod
def TruncatedGaussian(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1.0)."""
return WeightInit._Params('truncated_gaussian', scale, seed)
@staticmethod
def GaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('gaussian_sqrt_dim', scale, seed)
@staticmethod
def GaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('gaussian_sqrt_fanin', scale, seed)
@staticmethod
def GaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('gaussian_sqrt_fanout', scale, seed)
@staticmethod
def GaussianSqrtFanAvg(scale=1.0, seed=None):
"""tf.random.normal(0, sqrt(2.0 / (in + out)))."""
return WeightInit._Params('gaussian_sqrt_fanavg', scale, seed)
@staticmethod
def UniformSqrtDim(scale=1.0, seed=None):
"""scale * tf.uniform(-1 / sqrt(dim0), 1 / sqrt(dim0))."""
return WeightInit._Params('uniform_sqrt_dim', scale, seed)
@staticmethod
def UniformUnitScaling(scale=1.0, seed=None):
"""scale * sqrt(3) / sqrt(dim0) * tf.uniform(-1, 1)."""
return WeightInit._Params('uniform_unit_scaling', scale, seed)
@staticmethod
def UniformUnitScalingFanAvg(scale=1.0, seed=None):
"""Same as tf.variance_scaling_initializer() ...
Samples are drawn from a uniform distribution within [-limit, limit], with
limit = sqrt(3 * scale / n)
where
n = max(1., (fan_in + fan_out) / 2).
See tf.keras.initializers.VarianceScaling for details.
Args:
scale: A Python float.
seed: A Python int or None.
Returns:
A WeightInit param.
"""
return WeightInit._Params('uniform_unit_scaling_fan_avg', scale, seed)
@staticmethod
def TruncatedGaussianSqrtDim(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(dim0))."""
return WeightInit._Params('truncated_gaussian_sqrt_dim', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanIn(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_in))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanin', scale, seed)
@staticmethod
def TruncatedGaussianSqrtFanOut(scale=1.0, seed=None):
"""scale * tf.random.truncated_normal(0, 1 / sqrt(fan_out))."""
return WeightInit._Params('truncated_gaussian_sqrt_fanout', scale, seed)
@staticmethod
def KaimingUniformFanInRelu(scale=1.0, seed=None):
return WeightInit._Params('kaiming_uniform_fanin_relu', scale, seed)
@staticmethod
def KaimingUniformFanInLeakyRelu(scale=np.sqrt(5.), seed=None):
return WeightInit._Params('kaiming_uniform_fanin_leakyrelu', scale, seed)
@staticmethod
def CustomVarInit(custom_v_init):
return WeightInit._Params('custom', 1.0, None, custom_v_init)
@staticmethod
def CustomConstantVarInit(custom_v_init):
return WeightInit._Params('custom_constant', 1.0, None, custom_v_init)
_DEFAULT_XAVIER_INIT = 1.000001
def DefaultParamInit():
# Here we use 1.000001 as a signature for user picking up the
# default param initializer.
return WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
# TODO(rpang, jonathanasdf): explore adding _is_default to hyperparams.Param.
def IsDefaultParamInit(p):
return (p.method == 'xavier' and
abs(p.scale - _DEFAULT_XAVIER_INIT) < 1e-7 and p.seed is None)
def WeightParams(shape,
init=None,
dtype=None,
collections=None,
device_mesh=None,
tensor_split_dims_mapping=None):
"""Returns a hyperparams for a weight variable given the shape/init/dtype."""
if init is None:
init = WeightInit.Xavier(_DEFAULT_XAVIER_INIT)
if dtype is None:
dtype = tf.float32
if collections is None:
collections = []
if device_mesh is not None:
assert tensor_split_dims_mapping is not None
assert len(tensor_split_dims_mapping) == len(shape)
p = hyperparams.Params()
p.Define('dtype', dtype, 'The weight data type.')
p.Define('shape', shape, 'The weight shape.')
p.Define('init', init, 'Initialization method.')
p.Define('collections', collections,
'Variable collections this weight belongs to.')
p.Define(
'device_mesh', device_mesh,
'A numpy.ndarray describing the topology of a device mesh to partition'
' this variable onto. Each element in the np.ndarray is the ID of a'
' device in the topology. device_mesh and tensor_split_dims_mapping below'
' together specifies how this weight tensor should be sharded across'
' different tpu cores. If None, this variable is not sharded.'
' Here are examples: np.array([0, 1, 2, 3, 4, 5, 6, 7]) which is a 1d'
' mesh with 8 devices, np.array([[0, 1, 2, 3], [4, 5, 6, 7]]) which is'
' 2d matrix of 8 devices.')
p.Define(
'tensor_split_dims_mapping', tensor_split_dims_mapping,
'A list of integers that map each tensor axis to the device mesh axis'
' along which it is sharded. Its length is the tensor rank, and'
' split_dims_mapping[i] is device mesh axis for tensor dimension i. Use'
' -1 for tensor dimensions that are not sharded. If the list is set to'
' None and a device_mesh is specified, the sharding will be treated as'
' replicated. Here is a concrete examples: '
' device_mesh=np.array([[0, 1, 2, 3] [4, 5, 6, 7]]), of shape [2, 4]'
' shape=[x, y, z], so this is a 3d variable.'
' tensor_split_dims_mapping=[-1, -1, 1], in this case, the third dim'
' of the variable is split along the second dim of the mesh. Each '
' split of the variable is of the shape [x, y, z/4].')
# The following two flags are used in Jax only.
p.Define(
'repeat_prefix', None,
'If not None, the full shape of this var is repeat_prefix+shape. '
'For example, if repeat_prefix=[16, 2], and shape=[512, 1024], then '
'real shape of variable is [16, 2, 512, 1024]. "repeat_prefix" is '
'often used if a layer is to be used in a recurrent loop, where '
'logically there are n sub-layers, but for performance/hbm usage '
'reasons we stack all the variables in creating those n-layers.')
p.Define('repeat_prefix_split_dims_mapping', None,
'Tensor split dims mapping for the repeat_prefix dims.')
return p
def FindNeeded(endpoints):
"""List names of tensors and operations required to compute endpoints."""
names_seen = set()
queue = []
for e in Flatten(endpoints):
if isinstance(e, tf.Operation):
queue.append(e)
else:
queue.append(e.op)
while queue:
op = queue.pop()
name = op.name
if name not in names_seen:
names_seen.add(name)
names_seen.update((o.name for o in op.outputs))
queue.extend(i.op for i in op.inputs)
queue.extend(op.control_inputs)
return names_seen
class _CollectionGetter:
"""Get graph local value from a defined collection."""
def __init__(self, key, default_factory):
self._key = key
self._default_factory = default_factory
def __call__(self):
collection = tf.get_collection(self._key)
if collection:
assert len(collection) == 1
return collection[0]
value = self._default_factory()
tf.add_to_collection(self._key, value)
return value
def SanitizeScopeKey(key):
"""Removes invalid symbols from name_scope keys."""
if key.startswith('_'):
key = key[1:]
return key.replace('[', '_').replace(']', '')
# Maintain a session for unit tests (initialized in test_utils.py).
_SESSION_SCOPE = ThreadLocalStack()
@contextlib.contextmanager
def UnitTestSessionScope(sess):
_SESSION_SCOPE.stack.append(sess)
try:
yield
finally:
_SESSION_SCOPE.stack.pop()
def GetUnitTestSession():
"""Get the current variable reuse setting."""
return _SESSION_SCOPE.stack[-1] if _SESSION_SCOPE.stack else None
# Global variable to control multitask variable reuse
# If False (default) the default tf.get_variable is used, that is:
# - Reusing scopes only allow getting existing variables
# - Non-reusing scopes only allow getting new variables
# With GetOpportunisticVariableReuse() == True:
# - Reusing scopes only allow getting existing variables, as usual
# - Non-reusing scopes reuse new variables or get new ones
_OPPORTUNISTIC_VARIABLE_REUSE = ThreadLocalStack()
@contextlib.contextmanager
def OpportunisticVariableReuseScope(enable_opportunistic_reuse=True):
_OPPORTUNISTIC_VARIABLE_REUSE.stack.append(enable_opportunistic_reuse)
try:
yield
finally:
_OPPORTUNISTIC_VARIABLE_REUSE.stack.pop()
def GetOpportunisticVariableReuse():
"""Get the current variable reuse setting."""
return (_OPPORTUNISTIC_VARIABLE_REUSE.stack[-1]
if _OPPORTUNISTIC_VARIABLE_REUSE.stack else False)
_VARIABLE_RENAME_RULES = ThreadLocalStack()
# Global variable to track task calling scope.
# Currently only used for TPU Embedding purposes as a TPUEmbeddingLayer
# may be shared across tasks and the calling task needs to be known
# for tracking embedding activations for backprop.
_TASK_CALL_SCOPE = ThreadLocalStack()
def TaskCallScopeName(task):
"""Get a unique string identifying a task."""
return f'{task.params.name}_{id(task)}'
@contextlib.contextmanager
def TaskCallScope(task):
_TASK_CALL_SCOPE.stack.append(TaskCallScopeName(task))
try:
yield
finally:
_TASK_CALL_SCOPE.stack.pop()
def GetTaskCallScope():
"""Get the current task call scope."""
return _TASK_CALL_SCOPE.stack[-1] if _TASK_CALL_SCOPE.stack else None
@contextlib.contextmanager
def VariableRenameScope(renames):
"""Append the renaming rules to the stack of renames.
Args:
renames: pairs of (regexp, new_name_format). If the regexp matches, the
new_name_format will be interpolated using the matched groups.
Yields:
scope in which the renaming rules are applied
"""
_VARIABLE_RENAME_RULES.stack.append(renames)
try:
yield
finally:
_VARIABLE_RENAME_RULES.stack.pop()
def GetVariableName(name):
"""Get variable name after application of all renaming rules.
Args:
name: untransformed variable name with scope_name prepended
Returns:
name possibly modified using renaming rules
"""
matched = False
new_name = name
for renames in _VARIABLE_RENAME_RULES.stack:
tf.logging.log_first_n(
tf.logging.WARN,
('Renaming variables is not supported in eager mode. '
'Please look into migrating away from variable renaming.'), 1)
for regexp, name_format in renames:
match = re.match(regexp, name)
if match:
if matched:
tf.logging.warning('Multiple matches for: %s', name)
matched = True
new_name = name_format % match.groups()
if new_name != name:
tf.logging.info("WARNING!!! Renaming variable '%s' to '%s'", name, new_name)
return new_name
_LIST_REGEX_DTYPE = ThreadLocalStack()
@contextlib.contextmanager
def VariableListDtypeRegexScope(list_regex_dtypes):
"""Append the list of (regex, dtype) to override the dtype.
Args:
list_regex_dtypes: pairs of (regexp, dtype). If the regexp matches, the data
type of the variable will be changed by the corresponding dtype.
Yields:
scope in which the list of (regex, dtype) is applied.
"""
_LIST_REGEX_DTYPE.stack.append(list_regex_dtypes)
try:
yield
finally:
_LIST_REGEX_DTYPE.stack.pop()
def FindDataType(var_name):
"""Find the data type for var_name.
Args:
var_name: A string, name of the variable.
Returns:
The dtype of the first matched regex with var_name, or None if no matching
found.
"""
for regex_dtypes in _LIST_REGEX_DTYPE.stack:
for regex, data_type in regex_dtypes:
if re.match(regex, var_name):
return data_type
return None
def GenerateSeedFromName(name):
"""Generate a random seed from a name string.
Args:
name: A string.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
md5 = hashlib.md5()
md5.update(six.ensure_binary(name))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
def MaybeGenerateSeedFromScope():
"""Generate a random seed from the current name of the scope.
If running in eager mode, this returns 0.
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if not tf.executing_eagerly():
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
return 0
def GenerateSeedFromId(obj_id):
"""Generate a random seed from the id of an object.
If deterministic execution (i.e. unit test), generate the seed from a fixed
unique name instead.
Args:
obj_id: id(object).
Returns:
An integer seed in the range [0, 2**31 - 1).
"""
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
with tf.name_scope(''):
return GenerateSeedFromName(tf.no_op(name='new_step_seed').name)
md5 = hashlib.md5()
md5.update(np.int64(obj_id))
return np.int64(int(md5.hexdigest(), 16) % (2**31 - 1))
_VARIABLE_SHAPE_PREFIXES = ThreadLocalStack()
def GetVarLeadingDimsAsCombinedLayers(var):
"""Gets the number of leading dimensions of `var` marked as combined layers.
Such dimensions represent variables from different layers stacked together,
e.g., in RepeatLayer, and optimizers (which have shape-dependant behaviors)
can adjust its behavior based on this information to match the behavior for
separate layer variables.
Args:
var: A variable.
Returns:
An integer representing the number of leading dimensions.
"""
try:
return var.op.get_attr('_num_leading_dims_for_combined_layers')
except ValueError:
return 0
except AttributeError:
# AttributeError: 'DistributedVarOp' object has no attribute 'get_attr'.
return 0
@contextlib.contextmanager
def VariableShapePrefixContext(shape_prefix):
"""Add a shape prefix to variable created by CreateVariable().
This new dimension will be marked as combined-layers. See also comments for
GetVarLeadingDimsAsCombinedLayers().
Args:
shape_prefix: a positive integer of shape prefix.
Yields:
None.
"""
assert shape_prefix > 0, ('%s' % shape_prefix)
_VARIABLE_SHAPE_PREFIXES.stack.append(shape_prefix)
try:
yield
finally:
_VARIABLE_SHAPE_PREFIXES.stack.pop()
def GetVariableShapePrefixes():
"""Return the list of shape prefixes for CreateVariable()."""
return _VARIABLE_SHAPE_PREFIXES.stack
def GetVariableNumLeadingDimsForCombinedLayersContext():
"""Return the number of leading combined-layers dims for CreateVariable()."""
return len(_VARIABLE_SHAPE_PREFIXES.stack)
def GetFanInFanOut(shape, prefix_dims_to_skip):
"""Returns (fan_in, fan_out) of a weight variable of the give shape."""
if not shape:
return None, None
if len(shape) < prefix_dims_to_skip:
raise ValueError(f'Variable shape is {shape} but prefix_dims_to_skip is '
f'{prefix_dims_to_skip}, larger than the shape rank.')
adjusted_shape = shape[prefix_dims_to_skip:]
if len(adjusted_shape) < 1:
return 1, 1
elif len(adjusted_shape) == 1:
# Following _compute_fans() from TF's init_ops.py.
return adjusted_shape[0], adjusted_shape[0]
else:
receptive_field_size = 1
for s in adjusted_shape[:-2]:
receptive_field_size *= s
fan_in = adjusted_shape[-2] * receptive_field_size
fan_out = adjusted_shape[-1] * receptive_field_size
return fan_in, fan_out
_VARIABLE_STORE_STACK = ThreadLocalStack()
@contextlib.contextmanager
def VariableStore():
"""Keeps track of {variable_name: (variable, var_params)}.
When CreateVariable would result in a variable name that exists in the store,
the existing variable is returned, or an error is raised, depending on whether
the variable scope supports reuse.
This mimics the behavior of tf.compat.v1.get_variable() with regards to
variable reuse, while functioning correctly in TF2 eager context. However, it
only applies to variables created via CreateVariable.
When there are nested VariableStore contexts, they all provide the same
variable store object. That is, the scope of the variable store is the
outermost context.
Yields:
A dictionary representing the variable store.
"""
store = _VARIABLE_STORE_STACK.stack[-1] if _VARIABLE_STORE_STACK.stack else {}
_VARIABLE_STORE_STACK.stack.append(store)
try:
yield store
finally:
_VARIABLE_STORE_STACK.stack.pop()
def _GetVariableStore():
return (_VARIABLE_STORE_STACK.stack[-1]
if _VARIABLE_STORE_STACK.stack else None)
def _DefaultVariableCreator(**kwargs):
kwargs.pop('var_name')
kwargs.pop('var_params')
return tf.get_variable(**kwargs)
_VARIABLE_CREATOR_STACK = ThreadLocalStack()
def _GetVariableCreator():
fn = _DefaultVariableCreator
for wrapper in reversed(_VARIABLE_CREATOR_STACK.stack):
fn = functools.partial(wrapper, fn)
return fn
@contextlib.contextmanager
def VariableCreatorScope(variable_creator):
"""Yields a context around a variable_creator, used by `CreateVariable()`.
The function must have the following signature::
def variable_creator(next_creator, **kwargs)
The function may delegate variable creation to the next variable creator, or
return its own tf.Variable.
This differs from tf.variable_creator_scope in that tf.variable_creator_scope
modifies a tf.Variable() call while this modifies a tf.get_variable() call. As
the code is migrated to TF2 and tf.get_variable() is deprecated, this may be
upgraded to using tf.variable_creator_scope instead.
This differs from tf.variable_scope(custom_getter=variable_creator) in that
the kwargs passed can be manipulated.
Variable creators are resolved from the outermost towards the innermost.
The innermost variable creator function is tf.get_variable.
The passed in kwargs must conform to what tf.get_variable accepts, with the
addition of `var_name` and `var_params`.
Args:
variable_creator: A variable creator function.
"""
_VARIABLE_CREATOR_STACK.stack.append(variable_creator)
try:
yield
finally:
_VARIABLE_CREATOR_STACK.stack.pop()
def PlaceOnTpuCore(core_id):
"""Returns a VariableCreatorScope that places variables on a given tpu core.
Only applies when running with TPUs.
Does not yet properly support model parallelism.
Args:
core_id: The tpu core id.
"""
def Creator(next_creator, **kwargs):
cluster = cluster_factory.Current()
if use_tpu():
device = cluster.WorkerDeviceInModelSplit(core_id)
elif (
tpu_compat() and
cluster.params.job in ('controller', 'trainer_client', 'executor_tpu')):
# The job is running in a fleet that uses tpu, but does not itself have
# access to the tpu, e.g. controller job. In this case, the returned
# device needs to be the cpu device on the tpu host for the given core.
# FIXME: the current implementation is wrong for large values of core_id.
device = cluster.ListDevices(cluster.params.worker)[0, 0]
else:
device = ''
with tf.device(device):
return next_creator(**kwargs)
return VariableCreatorScope(Creator)
# Variable creators.
def MaybeReuseFromVariableStore(next_creator, **kwargs):
"""Variable creator that attempts to reuse variables from variable store."""
var_name = kwargs['var_name']
p = kwargs['var_params']
store = _GetVariableStore()
if store is not None and var_name in store:
if tf.get_variable_scope().reuse:
var, cached_p = store[var_name]
tf.logging.info('Reusing var %s', var.name)
assert cached_p == p.ToText(), (
'Cached config:\n %s vs new config:\n %s' % (cached_p, p.ToText()))
return var
var = next_creator(**kwargs)
tf.logging.info('Creating var %s shape=%s on device %s', var.name, var.shape,
var.device)
for col in p.collections:
tf.add_to_collection(col, var)
if store is not None:
store[var_name] = (var, p.ToText())
return var
def MaybePinVarsToCpu(next_creator, **kwargs):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return next_creator(**kwargs)
return next_creator(**kwargs)
def MaybeOpportunisticVariableReuse(next_creator, **kwargs):
if GetOpportunisticVariableReuse():
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
return next_creator(**kwargs)
return next_creator(**kwargs)
# TODO(yonghui): Add support for partitioned Variables.
def CreateVariable(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES). Note that specifying a collections
argument in `params` does not override this collection; the caller must
set this field explicitly in the call to CreateVariable().
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
if use_stateless_vars_init():
return _CreateVariableStateless(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
else:
return _CreateVariableStateful(name, params, reuse, trainable, collections,
default_seed, synchronization, aggregation)
def _CreateVariableStateful(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateful RNGs according to param_config.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
if tf.get_default_graph().seed is not None:
# We are in a program/test which need determistic randomization.
if seed is None:
if default_seed is not None:
seed = default_seed
else:
# We are not given a per-variable random seed. We use hash of
# variable name as a stable random seed.
seed = GenerateSeedFromName(var_name)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
# TODO(b/172827074): we do not natively support var initialization for
# int8 type except for constant initialization.
# NOTE: For int8, we initialize by scaling float32 random values to integer.
if init_dtype == tf.int8:
init_dtype = tf.float32
v_init = _CreateVarInitStateful(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
def ComplexWrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
# A more complex alternative may be to use the init function for
# magnitudes and uniform random for phases instead.
shape = [2] + shape
value = init(shape, init_dtype, partition_info)
return tf.complex(value[0], value[1])
return _Wrapper
v_init = ComplexWrapper(v_init)
if var_dtype == tf.int8:
def FloatToInt8Wrapper(init):
def _Wrapper(shape, dtype, partition_info):
del dtype
value = init(shape, init_dtype, partition_info)
scale = tf.math.maximum(
tf.math.reduce_min(value) / -127,
tf.math.reduce_max(value) / 127)
value = tf.divide(value, scale)
return tf.cast(value, tf.int8)
return _Wrapper
v_init = FloatToInt8Wrapper(v_init)
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybePinVarsToCpu, MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
if method == 'custom_constant':
call_shape = None
else:
call_shape = GetVariableShapePrefixes() + list(shape)
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=call_shape,
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _CreateVariableStateless(name,
params,
reuse=None,
trainable=True,
collections=None,
default_seed=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.VariableAggregation.NONE):
"""Creates tf.Variable using TF stateless RNGs according to `params`.
Args:
name: A string, name of the variable.
params: A WeightParams specifying the details of how this variable should be
constructed and initialized.
reuse: Whether or not to reuse an existing variable. It has the same
semantics as the reuse arg in tf.variable_scope.
trainable: Whether or not the variable is trainable.
collections: Override the default variable collection (
tf.GraphKeys.GLOBAL_VARIABLES).
default_seed: Seed to use for initialization if not specified in params.
Used for deterministic initialization in tests.
synchronization: Indicates when a distributed a variable will be aggregated.
Accepted values are constants defined in the class
tf.VariableSynchronization. By default the synchronization is set to AUTO
and the current DistributionStrategy chooses when to synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class tf.VariableAggregation.
Returns:
The created variable.
"""
p = params.Copy()
shape = tf.TensorShape(ToStaticShape(p.shape)).as_list()
if shape:
assert all([dim_size > 0 for dim_size in shape]), shape
dim0 = shape[0]
else:
dim0 = 1
assert p.init.method == 'constant' or np.all(np.asarray(p.init.scale) >= 0)
method = p.init.method
scale = p.init.scale
seed = p.init.seed
if IsDefaultParamInit(p.init):
tf.logging.warning(
'WARNING!!! var %s is using the default xavier initializer.'
' Make sure this is intended.', name)
with tf.variable_scope(name) as scope:
var_name = GetVariableName(scope.name)
user_seed = seed if seed is not None else default_seed
seed = _GenerateStatelessRngSeed(var_name, user_seed)
# If var_name matches a regex, then set the var_dtype; else use p.dtype.
var_dtype = FindDataType(var_name)
if var_dtype is None:
var_dtype = p.dtype
init_dtype = var_dtype.real_dtype
v_init = _CreateVarInitStateless(name, method, shape, dim0, seed, scale,
init_dtype, p.init.custom_v_init)
if var_dtype == tf.complex64:
raise TypeError(
'Stateless variable initialization does not support tf.complex64.')
def LingvoVariableCreator(next_creator, **kwargs):
"""Lingvo variable creator."""
# TODO(yonghui): Possibly get away from variable_scope and implement our own
# variable sharing mechanism.
with tf.variable_scope(name) as scope:
var_scope = tf.VariableScope(
scope.reuse,
custom_getter=scope.custom_getter,
caching_device=scope.caching_device,
use_resource=True)
with tf.variable_scope(var_scope), tf.variable_scope(var_name, reuse=reuse):
return next_creator(**kwargs)
with contextlib.ExitStack() as context_stack:
for variable_creator_fn in (LingvoVariableCreator,
MaybeOpportunisticVariableReuse,
MaybeReuseFromVariableStore):
context_stack.enter_context(VariableCreatorScope(variable_creator_fn))
var = _GetVariableCreator()(
var_name=var_name,
var_params=p,
name='var',
shape=GetVariableShapePrefixes() + list(shape),
dtype=var_dtype,
initializer=v_init,
collections=collections,
trainable=trainable,
validate_shape=True,
synchronization=synchronization,
aggregation=aggregation)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if combined_layers_dims > 0:
# pylint: disable=protected-access
var.op._set_attr('_num_leading_dims_for_combined_layers',
attr_value_pb2.AttrValue(i=combined_layers_dims))
# Shard the variable according to the sharding spec.
tensor_split_dims_mapping = p.tensor_split_dims_mapping
if tensor_split_dims_mapping is not None:
count = (
len(GetVariableShapePrefixes()) + len(shape) -
len(tensor_split_dims_mapping) -
len(gshard_utils.GetMeshSplitDimPrefixContext()))
tensor_split_dims_mapping = [-1] * count + tensor_split_dims_mapping
var = gshard_utils.MeshSplit(
var, p.device_mesh, tensor_split_dims_mapping, use_sharding_op=False)
return var
def _RandomXavierUniformInitializer(method, scale, seed):
"""Creates a random Xavier uniform initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
return XavierUniform
def _CreateVarInitStateful(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateful RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = init_ops.random_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = init_ops.random_uniform_initializer(
minval=-scale, maxval=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_positive']:
v_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
elif method == 'category':
uniform_init = init_ops.random_uniform_initializer(
minval=0.0, maxval=scale, seed=seed, dtype=init_dtype)
v_init = lambda *args, **kwargs: tf.floor(uniform_init(*args, **kwargs))
elif method in ['uniform_unit_scaling']:
v_init = init_ops.uniform_unit_scaling_initializer(
factor=scale, seed=seed, dtype=init_dtype)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = tf.variance_scaling_initializer(
scale=scale,
mode='fan_avg',
distribution='uniform',
seed=seed,
dtype=init_dtype)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = init_ops.truncated_normal_initializer(
mean=0.0, stddev=scale, seed=seed, dtype=init_dtype)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError(
'\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * tf.random.uniform(shape, -limit, limit, dtype, seed)
v_init = XavierUniform
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = init_ops.random_uniform_initializer(
minval=-bound, maxval=bound, seed=seed, dtype=init_dtype)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type `%s` not supported.' % method
return v_init
def _GenerateStatelessRngSeed(name, seed):
"""Generates a 2-tuple seed for a stateless variable initializer.
We want to ensure that different variables end up with different random values
even when they are passed the same seed and shape. To this aim, this function
generates a pseudo-unique seed by hashing the variable name and mapping it
into a scalar seed. More specifically, the returned value is a 2-tuple of
tf.int32 scalar, where the first element is the user-provided seed and the
second element is obtained by hashing the variable name.
Args:
name: The variable name for which to generate a stateless-like seed.
seed: The user-specified scalar seed.
Returns:
A 2-tuple seed of tf.int32 values (for TPU compatibility).
"""
seed0 = seed or 0
seed1 = GenerateSeedFromName(name)
return tf.constant([seed0, seed1], dtype=tf.int32)
def _DeterministicRandomNormalInitializer(seed, mean, stddev):
"""Creates a random normal initializer."""
def DeterministicNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicNormal
def _DeterministicRandomUniformInitializer(seed, minval, maxval):
"""Creates a random uniform initializer."""
def DeterministicUniform(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=minval, maxval=maxval, dtype=dtype)
return DeterministicUniform
def _DeterministicRandomTruncatedNormalInitializer(seed, mean, stddev):
"""Creates a random truncated normal initializer."""
def DeterministicTruncatedNormal(shape, dtype, partition_info):
del partition_info # Unused.
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=mean, stddev=stddev, dtype=dtype)
return DeterministicTruncatedNormal
def _DeterministicRandomUniformUnitScalingInitializer(seed, factor):
"""Creates a random uniform unit scaling initializer."""
def DeterministicUniformUnitScaling(shape, dtype, partition_info):
# The following logic is originally from (UniformUnitScaling.__call__())
# in TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
input_size = 1.0
# Estimating input size is not possible to do perfectly, but we try.
# The estimate, obtained by multiplying all dimensions but the last one,
# is the right thing for matrix multiply and convolutions (see above).
for dim in scale_shape[:-1]:
input_size *= float(dim)
# Avoid errors when initializing zero-size tensors.
input_size = max(input_size, 1.0)
maxval = math.sqrt(3 / input_size) * factor
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-maxval, maxval=maxval, dtype=dtype)
return DeterministicUniformUnitScaling
def _DeterministicRandomVarianceScalingInitializer(scale, mode, distribution,
seed):
"""Creates a variance scaling initializer."""
if scale <= 0.:
raise ValueError('`scale` must be positive float.')
if mode not in {'fan_in', 'fan_out', 'fan_avg'}:
raise ValueError('Invalid `mode` argument:', mode)
distribution = distribution.lower()
if distribution not in {
'normal', 'uniform', 'truncated_normal', 'untruncated_normal'
}:
raise ValueError('Invalid `distribution` argument:', distribution)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def DeterministicVarianceScaling(shape, dtype, partition_info):
# This is originally from TensorFlow: python/ops/init_ops.py
scale_shape = shape
if partition_info is not None:
scale_shape = partition_info.full_shape
# Handle special case of empty list as shape, since fan_in and fan_out
# are numerically added below. Without this, GetFanInFanOut() would
# return None, None instead.
if isinstance(scale_shape, (list, tuple)) and not scale_shape:
fan_in, fan_out = 1, 1
else:
fan_in, fan_out = GetFanInFanOut(scale_shape, combined_layers_dims)
if mode == 'fan_in':
scale_inner = scale / max(1., fan_in)
elif mode == 'fan_out':
scale_inner = scale / max(1., fan_out)
else:
scale_inner = scale / max(1., (fan_in + fan_out) / 2.)
if distribution == 'normal' or distribution == 'truncated_normal':
# constant taken from scipy.stats.truncnorm.std(
# a=-2, b=2, loc=0., scale=1.)
stddev = math.sqrt(scale_inner) / .87962566103423978
return stateless_random_ops.stateless_truncated_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
elif distribution == 'untruncated_normal':
stddev = math.sqrt(scale_inner)
return stateless_random_ops.stateless_random_normal(
shape=shape, seed=seed, mean=0.0, stddev=stddev, dtype=dtype)
else:
limit = math.sqrt(3.0 * scale_inner)
return stateless_random_ops.stateless_random_uniform(
shape=shape, seed=seed, minval=-limit, maxval=limit, dtype=dtype)
return DeterministicVarianceScaling
def _DeterministicRandomXavierUniformInitializer(method, scale, seed):
"""Creates a variance scaling initializer."""
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
def XavierUniform(shape, dtype, partition_info):
"""Xavier initialization (x = sqrt(6. / (in + out)); scale*[-x, x])."""
del partition_info # Unused.
if not shape:
raise ValueError('\'shape\' must not be \'None\' or 0 for XavierUniform')
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if method == 'xavier':
limit = math.sqrt(6. / (fan_in + fan_out))
elif method == 'geo_mean_xavier':
limit = math.sqrt(3. / math.sqrt(fan_in * fan_out))
return scale * stateless_random_ops.stateless_random_uniform(
shape, seed, -limit, limit, dtype)
return XavierUniform
def _CreateVarInitStateless(name,
method,
shape,
dim0,
seed,
scale,
init_dtype,
custom_v_init=None):
"""Creates variable initialization function for a stateless RNG."""
if (method in [
'gaussian_sqrt_dim', 'uniform_sqrt_dim', 'truncated_gaussian_sqrt_dim'
]):
if len(shape) > 2:
# This is probably not the right method to use when len(shape) > 2,
# e.g. dim0 will be 3 with a 3x3 conv2d kernel.
tf.logging.warning(
'Initializing %s of shape %s with method %s: dim0=%s. '
'Make sure that it is intended.', name, shape, method, dim0)
scale *= 1.0 / math.sqrt(dim0)
combined_layers_dims = GetVariableNumLeadingDimsForCombinedLayersContext()
if method in ['gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanin']:
fan_in, _ = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None:
scale *= 1.0 / math.sqrt(fan_in)
if method in ['gaussian_sqrt_fanout', 'truncated_gaussian_sqrt_fanout']:
_, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_out is not None:
scale *= 1.0 / math.sqrt(fan_out)
if method in ['gaussian_sqrt_fanavg']:
fan_in, fan_out = GetFanInFanOut(shape, combined_layers_dims)
if fan_in is not None and fan_out is not None:
scale *= math.sqrt(2.0 / (fan_in + fan_out))
if method in [
'gaussian', 'gaussian_sqrt_dim', 'gaussian_sqrt_fanin',
'gaussian_sqrt_fanout', 'gaussian_sqrt_fanavg'
]:
v_init = _DeterministicRandomNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['uniform', 'uniform_sqrt_dim']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-scale, maxval=scale)
elif method in ['uniform_positive']:
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=0., maxval=scale)
elif method in ['uniform_unit_scaling']:
v_init = _DeterministicRandomUniformUnitScalingInitializer(
seed=seed, factor=scale)
elif method in ['uniform_unit_scaling_fan_avg']:
v_init = _DeterministicRandomVarianceScalingInitializer(
scale=scale, mode='fan_avg', distribution='uniform', seed=seed)
elif method in [
'truncated_gaussian', 'truncated_gaussian_sqrt_dim',
'truncated_gaussian_sqrt_fanin', 'truncated_gaussian_sqrt_fanout'
]:
v_init = _DeterministicRandomTruncatedNormalInitializer(
seed=seed, mean=0., stddev=scale)
elif method in ['constant']:
v_init = init_ops.constant_initializer(value=scale, dtype=init_dtype)
elif method in ['xavier', 'geo_mean_xavier']:
v_init = _DeterministicRandomXavierUniformInitializer(method, scale, seed)
elif method in [
'kaiming_uniform_fanin_relu', 'kaiming_uniform_fanin_leakyrelu'
]:
fan_in = np.prod(shape[:-1])
if method == 'kaiming_uniform_fanin_leakyrelu':
# Assume the 'a' parameter is the 'scale' argument.
gain = np.sqrt(2. / (1 + scale**2))
else:
gain = np.sqrt(2.)
std_dev = gain / np.sqrt(fan_in)
bound = np.sqrt(3.0) * std_dev
v_init = _DeterministicRandomUniformInitializer(
seed=seed, minval=-bound, maxval=bound)
elif method in ['custom', 'custom_constant']:
v_init = custom_v_init
else:
assert False, 'init_type %s not supported.' % method
return v_init
_global_variable_scope = None
def GetGlobalVariableScope():
"""Gets the global variable scope (as if no variable_scope has been set).
Returns:
The VariableScope corresponding to as if no tf.variable_scope is in effect.
"""
if not _global_variable_scope:
# Each thread gets its own default global variable scope, and we take
# advantage of that in order to get a top-level scope. This avoids the
# need to call tf.get_variable_scope() at the module level, which allows
# this module to be imported without modifying global state (i.e. creating
# the default graph). It is important to not mutate the global state at
# module load time, because it let's us flip flags after import that affect
# core TensorFlow behavior.
def Initialize():
global _global_variable_scope
_global_variable_scope = tf.get_variable_scope()
t = threading.Thread(target=Initialize)
t.start()
t.join()
return _global_variable_scope
_GLOBAL_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def GlobalStepContext(global_step_tensor):
_GLOBAL_STEP_STACK.stack.append(global_step_tensor)
try:
yield
finally:
_GLOBAL_STEP_STACK.stack.pop()
def GetGlobalStep():
"""Return the global_step."""
if _GLOBAL_STEP_STACK.stack:
return _GLOBAL_STEP_STACK.stack[-1]
return tf.train.get_global_step()
def GetOrCreateGlobalStepVar():
"""Return the global_step variable, creating it if it does not exist.
Prefer GetGlobalStep if a tensor rather than a tf.Variable is sufficient.
Returns:
The global_step variable, or a new created one if it does not exist.
"""
with tf.variable_scope(GetGlobalVariableScope(), use_resource=True):
if _FromGlobal('pin_vars_to_cpu'):
with tf.device('/cpu:0'):
return tf.train.get_or_create_global_step()
else:
return tf.train.get_or_create_global_step()
def LogMultiLines(label, lines):
if not isinstance(lines, (list, tuple)):
lines = lines.split('\n')
for line in lines:
tf.logging.info('%s: %s', label, line)
def _LogPlacement(label, theta, copy):
"""Logs theta and its copy's device placement."""
def GetDevices(m):
"""Flatten a `.NestedMap` m and extracts each value's device."""
return [x.device for x in m.Flatten()]
tf.logging.info('=== %s ===', label)
LogMultiLines(
label,
theta.Pack([('%s -> %s' % (x[0], x[1]))
for x in zip(GetDevices(theta), GetDevices(copy))
]).DebugString())
tf.logging.info('==========')
def CreateLocalTheta(theta, device_list=None, label=None):
"""Creates local copy of theta and shards across devices device list.
Leaves variables intact.
Args:
theta: a `.NestedMap` of variables.
device_list: list of devices to shard across. If None, defaults to a list
[''].
label: Logging label.
Returns:
A `.NestedMap` of identity() wrapped theta
"""
class AddIdentity:
"""Helper class."""
def __init__(self, device_list):
self._list = device_list if device_list else ['']
self._index = 0
def __call__(self, x):
if isinstance(x, tf.Variable):
return x
with tf.device(self._list[self._index % len(self._list)]):
self._index += 1
return tf.identity(x)
copy = theta.Transform(AddIdentity(device_list))
_LogPlacement(label, theta, copy)
return copy
def _GetVarsToLoad(all_vars, variable_loading_rules, var_ignore_rules,
ckpt_path):
"""Determines variables to load and their names in checkpoint."""
# This list contains mappings from var names as they appear in the checkpoint
# to the vars in our model they correspond to.
unused_rules = {
regexp: name_format for regexp, name_format in variable_loading_rules
}
vars_to_load = []
for model_var in all_vars:
loaded = False
for regexp, name_format in variable_loading_rules:
match = re.match(regexp, model_var.name)
# Skip if var doesn't match the loading rules, or if it should be ignored.
if not match:
tf.logging.debug('Loading rules do not match %s.', model_var.name)
continue
elif any(re.match(r, model_var.name) for r in var_ignore_rules):
tf.logging.debug('Ignoring %s from loading.', model_var.name)
continue
checkpoint_var_name = name_format % match.groups()
if checkpoint_var_name.endswith(':0'):
checkpoint_var_name = checkpoint_var_name[:-2]
tf.logging.info('Loading %s from %s with regexp: %s', model_var.name,
checkpoint_var_name, regexp)
vars_to_load.append((checkpoint_var_name, model_var))
unused_rules.pop(regexp, None)
loaded = True
break
if not loaded:
tf.logging.info(
'Not loading model variable %s from %s as it does not match any rules'
' or matches ignored', model_var.name, ckpt_path)
for regexp, name_format in unused_rules.items():
tf.logging.warning(f'User provided rule matched no variables: ({regexp}, '
f'{name_format})')
return vars_to_load
def OverrideVarsFromCheckpoint(all_vars, checkpoint_path,
variable_loading_rules, var_ignore_rules):
"""Add TF graph ops to override variables from a provided checkpoint.
Args:
all_vars: List of all the parameters in the model.
checkpoint_path: A path to the checkpoints of a pretrained model.
variable_loading_rules: A list of tuples of strings defining (regex to match
parameter names in the model to override, format string to determine the
corresponding var in the checkpoint).
var_ignore_rules: A list consisting of a list of regexes to match parameter
names in the model which should not be overridden, even if they match
those in the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from the provided checkpoint.
"""
vars_to_load = _GetVarsToLoad(all_vars, variable_loading_rules,
var_ignore_rules, checkpoint_path)
if not vars_to_load:
all_rules_text = '\n'.join(
[f'{k} --> {v}' for k, v in variable_loading_rules])
raise ValueError(f'Variable loading rules {all_rules_text} '
f'did not match any of {len(all_vars)} vars.')
load_var_names = '\n'.join(sorted([v.name for _, v in vars_to_load]))
tf.logging.info(f'Overriding {len(vars_to_load)} vars from '
f'{checkpoint_path}:\n{load_var_names}')
savers = []
while vars_to_load:
# When restoring, it's possible the same value in the checkpoint
# can be restored to multiple variables (e.g. during
# distillation). However, tf.train.Saver, since it's used for
# both saving and restoring, requires the name in the checkpoint
# to be unique for each variable. So, we call it multiple times
# with a unique set of names each time.
unique_vars_to_load = {}
remaining_vars_to_load = []
for k, v in vars_to_load:
if k not in unique_vars_to_load:
unique_vars_to_load[k] = v
else:
remaining_vars_to_load.append((k, v))
savers.append(tf.train.Saver(var_list=unique_vars_to_load, sharded=True))
vars_to_load = remaining_vars_to_load
def _Restore(sess):
for saver in savers:
saver.restore(sess, checkpoint_path)
return _Restore
def OverrideVarsFromCheckpoints(all_vars, ckpts_loading_rules):
"""Add TF graph ops to override model variables from checkpoints.
Args:
all_vars: List of all the parameters in the model.
ckpts_loading_rules: A dictionary of checkpoint path: loading rules.
Checkpoint path must be a path to a pretrained model, and loading rules is
expected to be a tuple of two lists. The first consisting of tuples of
strings defining (regex to match parameter names in the model to override,
format string to determine the corresponding var in the checkpoint), and
the second list consisting of a list of regexes to match parameter names
in the model which should not be overridden, even if they match those in
the loading rules.
Returns:
A callable that, when called with a tf.Session, will restore the variables
from checkpoint and return a list of overwritten variables.
Raises:
ValueError: if colliding vars exist or loading rules is not a list.
"""
if len(ckpts_loading_rules) > 1:
tf.logging.info('Overriding vars from multiple checkpoints.')
var_refs_overridden = set()
var_names_overridden = set()
restore_fns = []
for ckpt_path, loading_rules in ckpts_loading_rules.items():
tf.logging.info('Overriding vars from checkpoint: %s', ckpt_path)
if not isinstance(loading_rules, tuple):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
if len(loading_rules) != 2 or not all(
isinstance(l, list) for l in loading_rules):
raise ValueError('Loading rules for %s must be a tuple of two lists!' %
ckpt_path)
# Filter the model variables to be overridden.
to_load_vars = _GetVarsToLoad(all_vars, loading_rules[0], loading_rules[1],
ckpt_path)
var_refs_to_override = [var[1].experimental_ref() for var in to_load_vars]
var_names_to_override = [var[1].name for var in to_load_vars]
overlap_refs = set.intersection(var_refs_overridden, var_refs_to_override)
if overlap_refs:
raise ValueError('Colliding variables to override: %s' % overlap_refs)
restore_fns.append(
OverrideVarsFromCheckpoint(all_vars, ckpt_path, loading_rules[0],
loading_rules[1]))
var_refs_overridden.update(var_refs_to_override)
var_names_overridden.update(var_names_to_override)
tf.logging.info('Model variables overridden: %s', var_refs_overridden)
def _Restore(sess):
for fn in restore_fns:
fn(sess)
return var_names_overridden
return _Restore
def ComputeGradientsSimple(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
activations_grad=None):
"""Compute gradients."""
tape = _GRADIENT_TAPE_STACK.stack[-1] if _GRADIENT_TAPE_STACK.stack else None
if IsEagerMode() and tape:
tf.logging.info('ComputeGradientsSimple: using gradient tape.')
if activations_grad is not None:
raise ValueError('GradientTape does not accept gradient input values.')
if grad_aggregation_method or colocate_gradients_with_ops or gate_gradients:
tf.logging.warning(
'When GradientTape is used, these field will be ignored: '
f'grad_aggregation_method ({grad_aggregation_method}), '
f'colocate_gradients_with_ops ({colocate_gradients_with_ops}), '
f'gate_gradients ({gate_gradients}).')
return tape.gradient(
loss_or_activations,
all_vars,
unconnected_gradients=tf.UnconnectedGradients.ZERO)
return tf.gradients(
loss_or_activations,
all_vars,
grad_ys=activations_grad,
aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients)
def _ComputeGradientsTpu(loss_or_activations,
all_vars,
grad_aggregation_method,
colocate_gradients_with_ops,
gate_gradients,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients for local loss across whole TPU cluster.
This implementation specializes for the case where weight params maybe used
for different number of times in the forward computation, so that gradients
should be normalized by the actual number of times they are being computed.
TODO(yonghui): Maybe merge this implementation with the _ComputeGradientsTpu
one.
Args:
loss_or_activations: The loss or activations to backprop from.
all_vars: Vars with respect to which gradients are to be computed.
grad_aggregation_method: aggregation method to use when calling
tf.gradients.
colocate_gradients_with_ops: boolean, whether or not to colocate gradient op
with the original op.
gate_gradients: boolean, flag to be passed to tf.gradients.
skip_zero_gradients: whether to skip zero gradients during aggregation.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This helps reducing the number of gradient all-reduces
when doing gradient accumulation, which does gradient cross replica sum
only every k steps in a tf.cond. Currently this works only when
skip_zero_gradients is None.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
Gradients to be passed back. If tpu_embedding_activations is set, their
gradients will be placed at the end.
Raises:
ValueError: upon invalid arguments.
"""
if is_activations:
assert activations_grad is not None
if not skip_zero_gradients and not is_activations:
# Scale the loss to account for the full batch size.
shards = tpu_function.get_tpu_context().number_of_shards
assert shards
loss_or_activations *= tf.constant(
1.0 / shards, dtype=loss_or_activations.dtype)
else:
assert not tpu_embedding_activations, (
'Gradient computation for tpu embedding activations requires proper '
'loss scaling, and so is not compatible with skip_zero_gradients and '
'is_activations.')
# Computes the gradients.
# Sum the grads so that we can compute statistics across the whole batch.
all_grads = ComputeGradientsSimple(
loss_or_activations=loss_or_activations,
all_vars=all_vars +
(tpu_embedding_activations if tpu_embedding_activations else []),
grad_aggregation_method=grad_aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
gate_gradients=gate_gradients,
activations_grad=activations_grad)
if tpu_embedding_activations:
# Note we don't need to aggregate TPU embedding gradients below.
tpu_embedding_grads = all_grads[len(all_vars):]
all_grads = all_grads[:len(all_vars)]
else:
tpu_embedding_grads = []
# NOTE: We can't use tpu_optimizer.CrossShardOptimizer since
# we need to scale the grads *after* the cross_replica_sum to
# match GPU version!
# TODO(cwhipkey): should we do something different here? - we could do
# some operations on the gradients before the aggregation (see comments in
# tensorflow/contrib/tpu/python/tpu/tpu_optimizer.py - see compute_gradients -
# for some more details).
aggregated_grads = []
for g in all_grads:
if g is None:
aggregated_grads.append(None)
continue
if use_bf16_gradients_ar:
g = tf.cast(g, tf.bfloat16)
with tf.ops.colocate_with(g):
if skip_zero_gradients is None:
# loss is already scaled by 1/shards.
if defer_crs_to_apply_grad:
normalized_g = tf.convert_to_tensor(g)
else:
normalized_g = tf.tpu.cross_replica_sum(g)
else:
# Compute the cross-replica mean of 'g', skipping zero gradients.
# Q(yonghui): Is there a better way to detect a non-zero gradient?
# Note(yonghui): gradient of a weight can be zero if that
# weight is not used in the forward computation, e.g. as in
# switchable layers in neural architecture search, pruned by channel
# mask, or sparsified.
if skip_zero_gradients == 'weight':
# Same shape as 'g'.
g_is_non_zero = tf.cast(tf.math.abs(g) > 1e-8, g.dtype)
elif skip_zero_gradients == 'variable':
# A variable-wide 0/1 scalar.
g_is_non_zero = tf.cast(
tf.reduce_sum(tf.math.abs(g)) > 1e-24, g.dtype)
else:
raise ValueError('Unknown skip_zero_gradients: %s' %
skip_zero_gradients)
num_updates = tf.maximum(tf.tpu.cross_replica_sum(g_is_non_zero), 1.0)
normalized_g = tf.tpu.cross_replica_sum(g) / num_updates
aggregated_grads.append(normalized_g)
return aggregated_grads + tpu_embedding_grads
class _VarGrad(typing.NamedTuple):
var: tf.Tensor
grad: Union[tf.Tensor, tf.IndexedSlices]
scale: Optional[tf.Tensor] = None
class VarGrad:
"""A class that holds a variable and a gradient.
This does not inherit from namedtuple so that tf.nest operations do not
recurse into it.
"""
def __init__(self, *args, **kwargs):
self._var_grad = _VarGrad(*args, **kwargs)
def __getitem__(self, key):
return self._var_grad[key]
def __getattr__(self, key):
return getattr(self._var_grad, key)
def __iter__(self):
if self._var_grad.scale is None:
return iter((self._var_grad.var, self._var_grad.grad))
return iter(self._var_grad)
def __repr__(self):
return repr(self._var_grad)
def SkipNoneGradients(var_grads):
"""Removes pairs whose grad is None."""
for key, (_, g) in var_grads.FlattenItems():
if g is None:
tf.logging.info('ComputeGradients drops %s', key)
return var_grads.Filter(lambda var_grad: var_grad.grad is not None)
def ComputeGradients(
loss_or_activations,
vmap,
grad_aggregation_method=tf.AggregationMethod.EXPERIMENTAL_TREE,
colocate_gradients_with_ops=True,
gate_gradients=False,
compute_gradients_fn=None,
skip_zero_gradients=None,
use_bf16_gradients_ar=False,
skip_none_gradients=True,
defer_crs_to_apply_grad=False,
activations_grad=None,
is_activations=False,
tpu_embedding_activations=None):
"""Computes gradients of variables in vmap w.r.t loss.
Args:
loss_or_activations: either the loss, which is a scalar tensor, or
activations, which could be a tensor or a list of tensors.
vmap: A `.NestedMap` of variables.
grad_aggregation_method: Specifies the method used to combine gradient
terms. Accepted values are constants defined in the class
AggregationMethod.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
gate_gradients: If True, add a tuple around the gradients returned for an
operations. This avoids some race conditions.
compute_gradients_fn: Function to use to compute gradients. If None, use
default. compute_gradients_fn should have the same signature as this
function, but without the last argument.
skip_zero_gradients: Whether to skip aggregating zero gradients. This helps
in case where some weights may not be used in forward computation, e.g.,
sparsely activated networks or switchable layers in neural architectural
search. Only applicable on TPU.
Possible values are:
- None: do not skip zero gradients;
- `variable`: skip if the entire variable's gradients are almost zero;
reduce_sum(abs(grads)) < 1e-8.
- `weight`: skip if the individual weight's gradients are almost zero:
abs(grad) < 1e-8.
use_bf16_gradients_ar: Whether to use bfloat16 dtype for gradients
all-reduce. This applies to TPU only.
skip_none_gradients: Whether to skip gradients that are None.
defer_crs_to_apply_grad: Whether to defer gradient cross replica sum to
apply_gradient. This applies to TPU only.
activations_grad: The gradients computed for activations.
is_activations: A boolean, whether the input is loss or activations.
tpu_embedding_activations: A `.NestedMap` of tpu embedding feature name ->
embedding feature tensor.
Returns:
var_grad - a `.NestedMap` of VarGrad. You can view
var_grad as an ordered list of (key, (var, grad)) tuples. Every
key of var_grad exists in vmap. Every variable in vmap that
contributes to loss must exist in var_grad. Every var of var_grad
must exist in vmap. grad is the corresponding gradient computed
for var. grad is guaranteed to be not None.
If tpu_embedding_activations is set, a sub `.NestedMap` named
tpu_embedding_var_grads will be used to store the VarGrads for the
activations. In this case, key is the feature name, and var in the VarGrad
is the activation tensor (not a real variable).
"""
if not is_activations:
loss_or_activations = HasRank(loss_or_activations, 0)
if not tpu_embedding_activations:
tpu_embedding_activations = NestedMap()
assert isinstance(tpu_embedding_activations, NestedMap)
assert isinstance(vmap, NestedMap)
assert skip_zero_gradients in (None, 'variable', 'weight')
# Uniqify and remove None.
filtered_vmap = vmap.Filter(_Unique())
assert filtered_vmap is not None
# Filter out variables not contributing to 'loss_or_activations'.
# This doesn't work if the training loop is wrapped inside a tf.function,
# since all variables will be lifted out and trainable_variables will be
# empty. In that case we skip the check.
trainable_variables = set(tf.trainable_variables())
if trainable_variables:
def Needed(v):
if isinstance(v, tf.Variable):
if v not in trainable_variables:
# Skip non-trainable variables. Otherwise,
# tf.Optimizer.apply_gradients throws up an exception instead
# of skipping the update.
return False
return True
filtered_vmap = filtered_vmap.Filter(Needed)
assert filtered_vmap is not None
filtered_vlist = filtered_vmap.Flatten()
# Use caller-supplied gradient function if supplied.
if compute_gradients_fn is not None:
assert not tpu_embedding_activations
take_grad = compute_gradients_fn
else:
# tpu vs non-tpu is slightly different.
if use_tpu():
take_grad = functools.partial(
_ComputeGradientsTpu,
skip_zero_gradients=skip_zero_gradients,
use_bf16_gradients_ar=use_bf16_gradients_ar,
defer_crs_to_apply_grad=defer_crs_to_apply_grad,
activations_grad=activations_grad,
is_activations=is_activations,
tpu_embedding_activations=tpu_embedding_activations.Flatten())
else:
assert not tpu_embedding_activations
take_grad = ComputeGradientsSimple
grads = take_grad(loss_or_activations, filtered_vlist,
grad_aggregation_method, colocate_gradients_with_ops,
gate_gradients)
if tpu_embedding_activations:
tpu_embedding_grads = grads[len(filtered_vlist):]
grads = grads[:len(filtered_vlist)]
else:
tpu_embedding_grads = None
# Formulate pairs of (var, grad) and pack them into the same
# structure as filtered_vmap.
var_grads = filtered_vmap.Pack(
[VarGrad(v, g) for v, g in zip(filtered_vlist, grads)])
if skip_none_gradients:
var_grads = SkipNoneGradients(var_grads)
if tpu_embedding_grads:
# Create VarGrads for TPU embedding activations in a dedicated sub map.
assert 'tpu_embedding_var_grads' not in var_grads
tpu_embedding_activation_list = tpu_embedding_activations.Flatten()
tpu_embedding_var_grads = [
VarGrad(v, g)
for v, g in zip(tpu_embedding_activation_list, tpu_embedding_grads)
]
tpu_embedding_var_grads = tpu_embedding_activations.Pack(
tpu_embedding_var_grads)
# Replace None gradients with zeros, since TPU embedding expect all
# activations to have gradients.
def _NoneToZeros(key, var_grad):
if var_grad.grad is None:
tf.logging.warning(
f'TPU embedding gradient for feature {key} is None. Replacing with '
'zeros.')
return VarGrad(var_grad.var, tf.zeros_like(var_grad.var))
return var_grad
var_grads.tpu_embedding_var_grads = (
tpu_embedding_var_grads.TransformWithKey(_NoneToZeros))
return var_grads
def MaskGradients(var_grad, grad_mask):
"""Computes gradients of non-masked variables in vmap w.r.t loss.
Args:
var_grad: A `.NestedMap` of (variable, gradient)
grad_mask: A dict of (variable name, mask).
Returns:
var_grad - a `.NestedMap` of (variable, mask * gradient).
"""
def ApplyMask(entry):
var, grad = entry
mask = grad_mask[var.name]
if isinstance(grad, tf.IndexedSlices):
return VarGrad(var, tf.IndexedSlices(grad.values * mask, grad.indices))
else:
return VarGrad(var, grad * mask)
return var_grad.Transform(ApplyMask)
def ApplyGradMultiplier(vs_gs, grad_scale=None):
"""Scale gradients by grad_scale on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
grad_scale: If None, each vs_gs entry has the scale. Otherwise, grad_scale
applies to every entry.
Returns:
A `.NestedMap` of (variable, gradient * grad_scale). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ScaleOrZero(var: tf.Tensor, grad: tf.Tensor,
scale: tf.Tensor) -> tf.Tensor:
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.where(
tf.equal(scale, 0.), tf.zeros_like(grad),
tf.cast(scale, grad.dtype) * grad)
def Scale(item: VarGrad) -> VarGrad:
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
if grad_scale is None:
scale = item.scale
else:
scale = grad_scale
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ScaleOrZero(var, grad.values, scale), grad.indices,
grad.dense_shape)
else:
grad = ScaleOrZero(var, grad, scale)
return VarGrad(var, grad)
return vs_gs.Transform(Scale)
def HasNanOrInf(x):
if isinstance(x, tf.IndexedSlices):
x = x.values
with tf.device(x.device):
if x.dtype.is_complex:
return tf.reduce_any(
[HasNanOrInf(tf.math.real(x)),
HasNanOrInf(tf.math.imag(x))])
return tf.reduce_any(
tf.math.logical_or(tf.math.is_nan(x), tf.math.is_inf(x)))
def HasNanOrInfGradient(var_grads):
"""Returns a bool tensor to indicate if `var_grads` contains NaNs or Infs.
Args:
var_grads: A `.NestedMap` with (var, grad) tuple as the map value.
Returns:
A bool scalar tensor to indicate if the `var_grads` contains NaNs or Infs.
"""
return tf.reduce_any([HasNanOrInf(g) for (_, g) in var_grads.Flatten()])
def ApplyGradNormClipping(vs_gs, norm=1.0):
"""Clip gradients to norm on same device as corresponding variables.
Args:
vs_gs: A `.NestedMap` of VarGrad.
norm: Each tensor's gradient will be scaled down to have a maximum L2-norm
value of `norm`.
Returns:
A `.NestedMap` of VarGrad(variable, scaled_gradient). In particular, if
grad_scale is 0, the result gradient is always 0, even if the input
gradient is inf or nan.
"""
def ClipByNorm(var, grad, norm):
grad = CheckNumerics(grad, 'Gradient for %s is not finite.' % var.name)
return tf.clip_by_norm(grad, norm)
def Clip(item):
"""Scales the gradient."""
var, grad = item
assert grad is not None, ('No grad found for ', var.name)
with tf.device(var.device):
if isinstance(grad, tf.IndexedSlices):
grad = tf.IndexedSlices(
ClipByNorm(var, grad.values, norm), grad.indices, grad.dense_shape)
else:
grad = ClipByNorm(var, grad, norm)
return VarGrad(var, grad)
return vs_gs.Transform(Clip)
SKIP_LP_REGULARIZATION = '__lingvo_skip_lp_regularization'
def AdjustGradientsWithLpLoss(var_grads, lp_regularizer_weight, p=2.0):
"""Adjusts the map of (var, grad) with Lp regularization, where p=1.0 or 2.0.
Args:
var_grads: a `.NestedMap` or list of (variable, gradient).
lp_regularizer_weight: Lp regularization weight.
p: For now we support 1.0 or 2.0.
Returns:
A tuple (lp_loss, var_grads).
- lp_loss: A scalar. The lp loss.
- var_grads: a `.NestedMap` or list of (variable, gradient) regulated by Lp.
"""
# TODO(yuancao): For now we support p=1 or 2, but this can be extended to
# lp-norm in general.
assert p in [2.0, 1.0], 'For now we only support L1/L2 regularization.'
def GetVar(item):
var, grad = item
if isinstance(grad, tf.IndexedSlices):
with tf.device(var.device):
ids = HasRank(grad.indices, 1)
uniq_ids = tf.unique(ids).y
return tf.gather(var, uniq_ids)
else:
return var
def ShouldAdjust(v):
return not _VarInCollection(v, tf.get_collection(SKIP_LP_REGULARIZATION))
filtered_var_grads = [
var_grad for var_grad in Flatten(var_grads) if ShouldAdjust(var_grad.var)
]
filtered_vars = Transform(GetVar, filtered_var_grads)
for v in filtered_vars:
tf.logging.info('AdjustGradientsWithLpLoss: %s', v.name)
if p == 2.0:
lp_loss = 0.5 * lp_regularizer_weight * SumSquared(filtered_vars)
elif p == 1.0:
lp_loss = lp_regularizer_weight * SumAbs(filtered_vars)
def LpGrad(var_grad):
"""Adjusts item's grad w/ Lp loss term."""
var, grad = var_grad
if isinstance(grad, tf.IndexedSlices):
# Question(rpang): do we apply Lp loss here even if 'var' is in
# SKIP_LP_REGULARIZATION?
#
# Note: IndexedSlces appears for embedding lookups.
# Embedding lookup ids can have duplicate. For duplicated ids, we
# only want to consider once for each ids.
with tf.device(var.device):
emb = HasRank(var, 2)
vocab_size = tf.shape(emb)[0]
ids = HasRank(grad.indices, 1)
values = tf.gather(emb, ids) # [#ids, dims]
with tf.device(grad.device):
# Counts is a vector of size vocab_size. counts[i] is i-th words
# occurrences in 'ids'.
counts = tf.math.unsorted_segment_sum(
tf.ones_like(ids, dtype=values.dtype), ids, vocab_size)
# Gradients for duplicated ids will be summed when they get
# applied, and hence we account for that by first dividing
# gradient resulting from lp loss by how many times the id is
# duplicated.
#
# For each id in 'ids', we know counts[id] is non-zero,
# hence, it's always safe to take reciprocal.
weights = tf.math.reciprocal(tf.gather(counts, ids))
weights = tf.expand_dims(weights, -1) # [#ids, 1]
if p == 2.0:
grad_v = values
elif p == 1.0:
grad_v = tf.sign(values)
delta = lp_regularizer_weight * weights * grad_v
grad = tf.IndexedSlices(grad.values + delta, ids)
elif not _VarInCollection(var, tf.get_collection(SKIP_LP_REGULARIZATION)):
with tf.device(var.device):
if p == 2.0:
grad_v = var
elif p == 1.0:
grad_v = tf.sign(var)
delta = lp_regularizer_weight * grad_v
with tf.device(grad.device):
grad += delta
return VarGrad(var, grad)
return lp_loss, Transform(LpGrad, var_grads)
def SplitRecursively(x, num_splits, axis=-1):
"""Splits Tensors in 'x' recursively.
Args:
x: a Tensor, or a list or NestMap containing Tensors to split.
num_splits: number of splits per Tensor.
axis: the split axis.
Returns:
A list of split values of length 'num_splits'.
- If 'x' is a Tensor, a list of split Tensors.
- If 'x' is a list, a list of lists, where each sublist has the same length
as 'x' and the k'th element in each sublist corresponds to a split of the
k'th element from 'x'.
- If 'x' is a `.NestedMap`, a list of `.NestedMap`, where each field
corresponds to a split from the same field of 'x'.
"""
if isinstance(x, tf.Tensor):
return tf.split(x, num_splits, axis=axis)
elif isinstance(x, list):
splits = [SplitRecursively(element, num_splits, axis) for element in x]
splits = list(zip(*splits))
return [list(t) for t in splits]
elif isinstance(x, NestedMap):
results = [NestedMap() for _ in range(num_splits)]
for key, val in x.items():
val_splits = SplitRecursively(val, num_splits, axis)
for i in range(num_splits):
results[i][key] = val_splits[i]
return results
else:
raise TypeError('Unexpected type for SplitRecursively: %s' % type(x))
def ConcatRecursively(splits, axis=-1):
"""Concatenates tensors from 'splits'.
This is the inverse function of SplitRecursively.
Args:
splits: a list of splits to concatenate, where elements can be Tensors,
lists, or `.NestedMap`. The elements must share the same type and
structure. For example, list elements must have the same length;
`.NestedMap` must have the same set of fields.
axis: the concatenation axis.
Returns:
Concatenated data.
- If input 'splits' are Tensors, returns a concatenated Tensor.
- If input 'splits' are lists, returns a list of the same length where the
k'th element represents concatenated data of the k'th element from each
split.
- If input 'splits' are `.NestedMap`, returns a `.NestedMap` with each field
concatenated from corresponding fields of input splits.
Raises:
TypeError: if 'splits' is not a list or elements of 'splits' do not have
known or matching types.
ValueError: if 'splits' is empty or elements of 'splits' do not have
matching structures.
"""
if not isinstance(splits, list):
raise TypeError('Non-list inputs for ConcatRecursively: %s' % splits)
if not splits:
raise ValueError('Empty inputs for ConcatRecursively: %s' % splits)
tmpl = splits[0]
if isinstance(tmpl, tf.Tensor):
return tf.concat(splits, axis=axis)
elif isinstance(tmpl, list):
if not all(isinstance(split, list) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
if not all(len(split) == len(tmpl) for split in splits):
raise ValueError('Length mismatch for ConcatRecursively: %s' % splits)
return [
ConcatRecursively([split[i]
for split in splits], axis)
for i in range(len(tmpl))
]
elif isinstance(tmpl, NestedMap):
if not all(isinstance(split, NestedMap) for split in splits):
raise TypeError('Type mismatch for ConcatRecursively: %s' % splits)
results = NestedMap()
for key in tmpl:
results[key] = ConcatRecursively([split[key] for split in splits], axis)
return results
else:
raise TypeError('Unexpected type for ConcatRecursively: %s' % type(splits))
def WeightedAvg(values, weights, sum_reduction_fn=tf.reduce_sum, name=''):
"""Computes weighted average of values from a tensor.
Args:
values: a tensor of values
weights: a tensor of weights
sum_reduction_fn: called to reduce the values and weights to single value
name: name of metric.
Returns:
A tuple (avg, total_weight).
- avg: weighted average value
- total_weight: sum of all weights
"""
msg = 'shape of values and weights tensors must match for metric ' + name
values = with_dependencies(
[assert_equal(tf.shape(values), tf.shape(weights), message=msg)], values)
total_weight = sum_reduction_fn(weights)
# divide_no_nan only supports tf.{float,complex}*.
dtype = values.dtype if values.dtype is tf.float64 else tf.float32
avg = tf.math.divide_no_nan(
sum_reduction_fn(tf.cast(values, dtype) * tf.cast(weights, dtype)),
tf.cast(total_weight, dtype))
return tf.cast(avg, values.dtype), total_weight
def WeightedAvgOfMetrics(metrics):
"""Computes the weighted average of metrics in the list.
Args:
metrics: list of dictionaries of metrics
Returns:
ret_dict - dictionary of weighted averages of each metrics.
"""
ret_dict = {}
lists_of_metrics = {}
for m in metrics:
for name, (value, weight) in m.items():
if name not in lists_of_metrics:
lists_of_metrics[name] = []
lists_of_metrics[name].append((value, weight))
for name, values_and_weights in sorted(lists_of_metrics.items()):
values = tf.stack([x[0] for x in values_and_weights])
weights = tf.stack([x[1] for x in values_and_weights])
ret_dict[name] = WeightedAvg(values, weights, tf.reduce_sum, name)
return ret_dict
def ConcatPerExampleTensors(per_example):
"""Concatenate per-example tensors from many hosts into one large block.
Args:
per_example: list of dictionaries of per-example tensors.
Returns:
ret_dict - string -> concatenated tensors.
"""
ret_dict = {}
lists_of_per_example = {}
for m in per_example:
for name, value in m.items():
if name not in lists_of_per_example:
lists_of_per_example[name] = []
lists_of_per_example[name].append(value)
for name, values in sorted(lists_of_per_example.items()):
ret_dict[name] = tf.concat(values, 0)
return ret_dict
def CombineMetrics(loss_metric_weight_pairs):
"""Combines metrics from `loss_metric_weight_pairs` according to weights.
Keys must either exist in all metrics, in which it will be processed as a
weighted sum, or exist in only one metrics, in which case it will be copied.
Args:
loss_metric_weight_pairs: a list of (metrics, weight) pairs, where each
weight is a float and each metrics is a dict with str keys and
(metric_value, target_weight) values.
Returns:
A dict with the same set of keys as input metrics and values of
(weighted_sum(metric_value), weighted_sum(target_weight)).
Raises:
ValueError: if there exists a metric that exists in more than one element
of `loss_metric_weight_pairs` but not in all of them.
"""
all_keys = set(
[k for loss_metrics, _ in loss_metric_weight_pairs for k in loss_metrics]) # pylint: disable=g-complex-comprehension
result = {}
for k in all_keys:
count = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
count += 1
if count > 1 and count != len(loss_metric_weight_pairs):
raise ValueError('Found metric %s which exists in more than one'
'but not all loss metrics.' % k)
total_val = 0
total_target_weight = 0
for loss_metrics, weight in loss_metric_weight_pairs:
if k in loss_metrics:
val, target_weight = loss_metrics[k]
if count == 1:
# Single metric, don't multiply by weight.
total_val = val * target_weight
total_target_weight = target_weight
else:
# Total weighted sum of all predictions.
total_val += weight * val * target_weight
total_target_weight += weight * target_weight
result[k] = (total_val / total_target_weight, total_target_weight)
return result
def AddVN(p, x, per_step=False):
"""Add variational noise to x.
Args:
p: Layer params, with a `vn` subparam containing `VariationalNoiseParams`.
x: Input to add variational noise to.
per_step: Whether to add per_step noise.
Returns:
The input with variational noise added according to params.
"""
tensor_name = x.name if not tf.executing_eagerly() else '[eager]'
if per_step:
if not p.vn.per_step_vn:
tf.logging.info(
'p.vn.per_step_vn is not set. Not adding per-step vn to ' +
tensor_name)
return x
else:
if not p.vn.global_vn:
tf.logging.info('p.vn.global_vn is not set. Not adding global vn to ' +
tensor_name)
return x
tf.logging.info(
f"Add {'per-step' if per_step else 'global'} vn to {tensor_name}: {p.vn}")
if p.vn.scale is None:
raise ValueError('VN scale must be set.')
if p.vn.deterministic:
noises = DeterministicVN(p, tf.shape(x), mean=0.0, std=1.0)
noises = tf.cast(noises, x.dtype)
else:
if per_step:
# recurrent.py does not support stateful random ops in cell_fn due to
# rematerialization.
raise ValueError('per_step vn requires deterministic=True.')
noises = tf.random.normal(
tf.shape(x), stddev=1.0, seed=p.vn.seed, dtype=x.dtype)
scale = tf.where(GetGlobalStep() >= p.vn.start_step, p.vn.scale, 0.0)
return x + tf.cast(scale, x.dtype) * noises
def VariationalNoiseParams(scale,
global_vn=False,
per_step_vn=False,
seed=None,
deterministic=None,
start_step=0):
"""Returns a hyperparams for variational noise."""
if deterministic is None:
deterministic = cluster_factory.Current().in_unit_test
p = hyperparams.Params()
p.Define(
'scale', scale,
'Std of the variational noise to apply . This can be a scalar,'
' or a scalar tensor.')
p.Define('global_vn', global_vn,
'Adds global variational noise every training setp iff True.')
p.Define('per_step_vn', per_step_vn,
'Adds per-timesetp variational noise iff True.')
p.Define('seed', seed, 'Random seed used to generate noise.')
p.Define(
'deterministic', deterministic, 'If true, generate noise using'
'stateless random ops that are compatible with TF functional ops.')
p.Define(
'start_step', start_step,
'Step starting from which variational noise is added during training.')
return p
def DefaultVN():
return VariationalNoiseParams(scale=None)
# To disable VN of a layer, we use 1.0 in the first input parameter
# of the following function because otherwise it is the same to DefaultVN()
# which will be updated by parent configuration in CopyBaseParams()
def DisableVN():
return VariationalNoiseParams(1.0, False, False)
# Step seed keyed by graph.
_STEP_SEED_DICT = ThreadLocalDict()
# The step seed will increment by np.prod(_STEP_SEED_INCREMENT.stack)
_STEP_SEED_INCREMENT = ThreadLocalStack()
@contextlib.contextmanager
def StepSeedIncrementContext(step):
"""Adds an element to _STEP_SEED_INCREMENT."""
assert step > 0, ('%s' % step)
_STEP_SEED_INCREMENT.stack.append(step)
try:
yield
finally:
_STEP_SEED_INCREMENT.stack.pop()
def GetStepSeed():
"""Gets step_seed."""
key = id(tf.get_default_graph())
if key not in _STEP_SEED_DICT.dict:
ResetStepSeed()
return _STEP_SEED_DICT.dict[key]
def ResetStepSeed(seed=0):
"""Resets step_seed to specified value."""
key = id(tf.get_default_graph())
_STEP_SEED_DICT.dict[key] = tf.convert_to_tensor(seed, dtype=tf.int64)
def MaybeResetStepSeedFromScope():
"""In graph mode, resets step_seed according to the current named scope.
This is used in graph mode to avoid "tensor is from a different graph"
errors that happen when we share random seend tensors too much.
See b/129159299 for more context.
Eager mode does not have this problem, so in eager mode we do nothing.
"""
if not tf.executing_eagerly():
ResetStepSeed(GenerateSeedFromName(tf.no_op(name='new_step_seed').name))
def MaybeResetStepSeed(seed):
"""If we're in graph mode, reset the step seed."""
if not tf.executing_eagerly():
ResetStepSeed(seed)
def GetIncStepSeed():
"""Returns and increments the step_seed."""
step_seed = GetStepSeed()
# TODO(lepikhin): introduce a routine filling a queue of uint32 random seeds
# independent of underlying PRNG used by tensorflow.
inc = np.prod(_STEP_SEED_INCREMENT.stack)
ResetStepSeed(step_seed + inc)
return step_seed
def GenerateStepSeedPair(p, op_seed=None):
"""Generates a seed pair for deterministic random operations in ...
functional loops.
This function retrieves a unique seed pair on each call, based off the current
global step and step seed. The step seed ensures this function returns a
unique seed pair on each call: calling this function automatically increments
the step seed. The step seed is automatically reset at the beginning of each
global step in the model's FProp and works transparently through recurrent.py.
Args:
p: A hyperparams.Params object, containing keys 'random_seed' and
'is_inference'.
op_seed: An additional operation-level seed to apply.
Returns:
A size 2 tensor of op seeds to use for stateless_random ops.
"""
seed_dtype = tf.int32 if use_tpu() else tf.int64
if p.is_inference and p.random_seed is None:
# Ensure GetIncStepSeed is called even inside the shortcut.
# This ensures if p.random_seed is set for other ops that use this function
# that they will get the same seed pair whether or not p.random_seed is set
# for this specific call.
GetIncStepSeed()
# Unlike tf.random*, stateless random ops are completely determined by the
# passed-in seeds. This means at inference time the same inputs will produce
# the same outputs, even if the model is supposed to have randomness such as
# dropout during inference. We inject additional randomness only during
# inference if the graph is exported with random_seed=None as a workaround.
return tf.random.uniform([2], maxval=seed_dtype.max, dtype=seed_dtype)
global_step = tf.cast(GetGlobalStep(), seed_dtype)
step_seed = tf.cast(GetIncStepSeed(), seed_dtype)
seeds = tf.stack([global_step, step_seed])
if p.random_seed is not None:
seeds += p.random_seed
if op_seed is not None:
op_seed = tf.cast(op_seed, seed_dtype)
seeds += op_seed
return seeds
def DeterministicDropout(x, keep_prob, seeds, noise_shape=None, name=None):
"""Similar to `tf.nn.dropout()`, but fully deterministic.
Args:
x: A float Tensor on which to apply dropout.
keep_prob: A scalar `Tensor` of keep probability.
seeds: A Tensor of shape [2]. 2 seeds for deterministic random number
generator.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated keep/drop flags.
name: An optional name for this operation.
Returns:
A Tensor with the same shape as `x`.
Raises:
InvalidArgumentError: if keep_prob is invalid.
"""
if isinstance(keep_prob, numbers.Real):
if keep_prob <= 0 or keep_prob > 1:
raise tf.errors.InvalidArgumentError(
'keep_prob must be in range (0, 1]. Value: {}'.format(keep_prob))
if keep_prob == 1:
return x
with tf.name_scope(name, 'dropout', [x]) as name:
if use_tpu():
seeds = tf.cast(seeds, tf.int32)
keep_prob = tf.convert_to_tensor(
keep_prob, dtype=tf.float32, name='keep_prob')
# uniform in [keep_prob, 1.0 + keep_prob)
# StatelessRandomUniform op does not support non-float (e.g. bfloat16) dtype
# and non-int32 seed types.
noise_shape = noise_shape or GetShape(x)
random_tensor = keep_prob + tf.random.stateless_uniform(
noise_shape, seed=seeds, dtype=tf.float32)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = tf.floor(random_tensor)
if x.dtype != tf.float32:
binary_tensor = tf.cast(binary_tensor, x.dtype)
keep_prob = tf.cast(keep_prob, dtype=x.dtype)
result = tf.div(x, keep_prob) * binary_tensor
result.set_shape(x.get_shape())
return result
def DeterministicVN(params, noise_shape, mean=0.0, std=1.0, name=None):
"""Produces Fully deterministic Gaussian noise from shape, mean and std.
Args:
params: Nested map of params.
noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for
randomly generated Gaussian noise.
mean: Mean for the Gaussian noise.
std: Standard deviation for noise.
name: An optional name for this operation.
Returns:
A Tensor with the shape noise_shape and type fprop_dtype.
"""
with tf.name_scope(name, 'gaussian_noise') as name:
seeds = GenerateStepSeedPair(params, params.vn.seed)
random_tensor = mean + (
std * tf.random.stateless_normal(noise_shape, seed=seeds))
if FPropDtype(params) != tf.float32:
random_tensor = tf.cast(random_tensor, FPropDtype(params))
return random_tensor
BATCH_NORM_UPDATES = 'batch_norm_updates'
_BATCH_NORM_UPDATES_DICT = '__batch_norm_update_dict'
_get_batch_norm_updates_dict = _CollectionGetter(_BATCH_NORM_UPDATES_DICT,
lambda: {})
def UpdateBatchNormVars(batch_norm_var, batch_norm_stats, decay):
"""Update batch normalization moving averages."""
with tf.name_scope(
'AssignMovingAvg', values=[
batch_norm_var,
batch_norm_stats,
decay,
]) as scope:
with tf.ops.colocate_with(batch_norm_var):
decay = tf.convert_to_tensor(
1.0 - decay, dtype=batch_norm_var.dtype.base_dtype)
update_delta = (batch_norm_var - tf.cast(
batch_norm_stats, batch_norm_var.dtype.base_dtype)) * decay
has_nan_or_inf = tf.reduce_any(
tf.math.logical_or(
tf.math.is_nan(update_delta), tf.math.is_inf(update_delta)))
update_delta = tf.where(has_nan_or_inf, tf.zeros_like(update_delta),
update_delta)
bn_update = tf.assign_sub(batch_norm_var, update_delta, name=scope)
tf.add_to_collection(BATCH_NORM_UPDATES, bn_update)
if not tf.executing_eagerly_outside_functions():
bn_update_dict = _get_batch_norm_updates_dict()
if bn_update.name in bn_update_dict:
raise ValueError(f'BN update {bn_update.name} already exists.')
bn_update_dict[bn_update.name] = (batch_norm_var, batch_norm_stats)
return bn_update
def FindRelevantBatchNormUpdates(loss, batch_norm_updates):
"""Finds and returns a list of relevant batch-normalization updates.
Args:
loss: The loss that is being optimized for. A tensor or a list of tensors.
batch_norm_updates: A list of batch normalization updates.
Returns:
A pair of lists. The first list contains all the batch normalization updates
that are relevant to the loss being optimized, and the second list contains
all in batch_norm_updates but not in the first list.
"""
if tf.executing_eagerly_outside_functions():
return [], []
dependent_ops_and_tensors = set(FindNeeded(loss))
relevant_updates = []
irrelevant_updates = []
bn_update_dict = _get_batch_norm_updates_dict()
for bn_update in batch_norm_updates:
assert bn_update.name in bn_update_dict, (
f'{bn_update.name} is probably not a valid batch normalization update '
'op. Make sure batch normalization is done through calling'
' the py_utils.UpdateBatchNormVars helper routine.')
bn_stat_name = bn_update_dict[bn_update.name][1].name
if bn_stat_name in dependent_ops_and_tensors:
# If a batch normalization stat is computed in the forward pass in
# computing loss, then the corresponding batch normalization update is
# relevant. Otherwise, it is not.
relevant_updates.append(bn_update)
else:
irrelevant_updates.append(bn_update)
return relevant_updates, irrelevant_updates
_SAMPLE_STEP_STACK = ThreadLocalStack()
@contextlib.contextmanager
def SampleStep(step):
"""A context for a sample step during decoding.
Example usage::
with py_utils.SampleStep(step):
sample = self.DecodeOneStep()
Args:
step: the step tensor.
Yields:
a context manager for the step scope.
"""
try:
_SAMPLE_STEP_STACK.stack.append(step)
yield step
finally:
_SAMPLE_STEP_STACK.stack.pop()
def _GetSampleStep():
return _SAMPLE_STEP_STACK.stack[-1] if _SAMPLE_STEP_STACK.stack else None
def AddDebugTensor(tensor, summarize=None, name=None):
"""Adds `tensor` to the debug collection.
Prints the tensor if `--print_debug_tensors` is True.
Args:
tensor: A tensor.
summarize: Only print this many entries of each tensor. If None, then a
maximum of 3 elements are printed per input tensor.
name: An optional name for the tensor.
Returns:
A Tensor that evaluates to the same value as the input tensor.
"""
if _FromGlobal('print_debug_tensors'):
step = _GetSampleStep()
tensors_to_print = ([] if step is None else [step]) + [tensor]
with tf.name_scope(name) as s:
tensor = tf.Print(
tensor,
tensors_to_print,
message='DEBUG tensor %s' % s,
name=name,
summarize=summarize)
return tensor
def ArgMax(inputs):
"""tf.argmax wrapper.
Args:
inputs: A tensor, whose last dimension is being reduced on.
Returns:
A tensor of rank tf.rank(logits)-1. If i == ret[indices],
logits[indices, i] is the maximum among logits[indices, :].
"""
if use_tpu():
return tf.argmax(inputs, axis=-1, output_type=tf.int32)
else:
return tf.argmax(inputs, axis=-1)
def _EnsureMatrixShape(x):
if x.shape.ndims is None:
x.set_shape([None, None])
else:
assert x.shape.ndims == 2
return x
def Matmul(x, y, *args, **kwargs):
"""tf.matmul wrapper expecting x and y are actually matrices."""
x = _EnsureMatrixShape(x)
y = _EnsureMatrixShape(y)
return tf.matmul(x, y, *args, **kwargs)
def clip_by_value(t, clip_value_min, clip_value_max, name=None): # pylint: disable=invalid-name
if t.dtype.is_complex:
return tf.complex(
tf.clip_by_value(
tf.math.real(t), clip_value_min, clip_value_max, '%s_real' % name),
tf.clip_by_value(
tf.math.imag(t), clip_value_min, clip_value_max, '%s_imag' % name))
return tf.clip_by_value(t, clip_value_min, clip_value_max, name)
def _TransformAndSum(tensor_list, transform):
with tf.name_scope('TransformAndSum'):
sum_transform = []
for t in tensor_list:
with tf.device(t.device):
if isinstance(t, tf.IndexedSlices):
sum_transform += [tf.reduce_sum(transform(t.values))]
else:
sum_transform += [tf.reduce_sum(transform(t))]
return tf.add_n(sum_transform)
def SumSquared(tensor_list):
return _TransformAndSum(tensor_list, lambda v: v**2)
def SumAbs(tensor_list):
return _TransformAndSum(tensor_list, tf.abs)
def ReduceRms(x: tf.Tensor) -> tf.Tensor:
"""Computes root mean square of tensor x with numerical stability."""
if not x.shape.is_fully_defined():
raise ValueError('Shape of x must be fully defined.')
if not x.shape.as_list():
return x
denom = functools.reduce((lambda x, y: x * y), x.shape.as_list())
if denom <= 1e8:
return tf.math.sqrt(tf.math.reduce_mean(tf.math.square(x)))
tf.logging.info('reduce_rms %s denom=%d', x, denom)
sum_square_x = tf.math.reduce_sum(tf.math.reduce_sum(tf.math.square(x), -1))
avg_square_x = sum_square_x / tf.constant(denom, dtype=sum_square_x.dtype)
return tf.math.sqrt(avg_square_x)
def PiecewiseConstant(x_in, boundaries, values, vdtype):
"""Returns the piecewise value of x_in."""
x_in = tf.cast(tf.convert_to_tensor(x_in), tf.float32)
assert len(values) == len(boundaries) + 1
assert sorted(boundaries) == list(boundaries)
bs = tf.convert_to_tensor(boundaries, dtype=tf.float32)
vs = tf.convert_to_tensor(values, dtype=vdtype)
# The following is equivalent to 'return vs[index]'.
index = tf.reduce_sum(tf.cast(tf.greater_equal(x_in, bs), tf.int32))
one_hot_vec = tf.one_hot(
tf.expand_dims(index, 0), depth=len(values), dtype=vdtype)
return Matmul(tf.reshape(vs, (1, -1)), tf.transpose(one_hot_vec))[0][0]
def PadSequenceDimension(x, length, pad_val, shape=None, axis=1):
"""Pads x to `length` using `pad_val` along the axis dim.
Assumes `x` is a tensor with rank >= 2, and it only pads `x` to `length`
along the axis dim. Explicitly sets the returned tensor shape to `shape` if
given. Raises runtime errors if x.shape[axis] > length or
x.shape[i] != shape[i] where i != axis.
Args:
x: the tensor to be padded with axis dimension being the time. E.g., x
usually has shape [batch, seq_len, ...], when axis=1.
length: an int to specify the length to pad x to.
pad_val: an int or float used to pad x.
shape: an int array specifying the shape of the padded tensor if specified.
axis: The dimension that x will be padded, default to 1.
Returns:
The padded tensor with shape [batch, seq_len, ...], where
ret[:, :seq_len, ...] == x, when axis=1, and similarly for other axes.
"""
if x.shape.ndims is not None:
rank = x.shape.ndims
assert rank >= 2
slen = GetShape(x, rank)[axis]
pad_len = length - slen
pad = [[0, 0] for _ in range(rank)]
pad[axis][1] = pad_len
else:
rank = tf.rank(x)
with tf.control_dependencies([assert_greater_equal(rank, 2)]):
slen = tf.shape(x)[axis]
pad_len = length - slen
pad = tf.scatter_nd([[axis, 1]], [pad_len], [rank, 2])
x = tf.pad(x, pad, constant_values=pad_val)
if x.shape.ndims is not None and isinstance(length, int):
static_shape = x.shape.as_list()
static_shape[axis] = length
x.set_shape(static_shape)
if shape:
if not isinstance(shape, (list, tuple)):
raise TypeError('Shape must be a list or tuple.')
x = HasRank(x, len(shape))
x = tf.ensure_shape(x, shape)
return x
def PadSequenceTo(xs, padding, length, pad_val):
"""Pads `xs` and `padding` to `length` using `pad_val` along the 2nd dim.
Pads `xs` to `length` using `pad_val`, and `padding` using 1.
Raise error if `x.shape[:2]` and `padding.shape` are not the same.
Args:
xs: A Tensor or a list of Tensors of shape [batch, seqlen] or [batch,
seqlen, ...].
padding: A 0/1 Tensor of shape [batch, seqlen]. 1 is for padded locations.
length: A Python int, the length to pad to.
pad_val: A Python numeric, used for padding x.
Returns:
A tuple of padded xs and padding.
"""
if not isinstance(xs, (list, tuple)):
new_xs = [xs]
else:
new_xs = xs
res = []
for x in new_xs:
batch, slen = GetShape(x, 2)
padding = HasRank(padding, 2)
padding = HasShape(padding, [batch, slen])
new_x = PadSequenceDimension(x, length, pad_val)
res.append(new_x)
padding = PadSequenceDimension(padding, length, tf.cast(1, padding.dtype))
if not isinstance(xs, (list, tuple)):
assert len(res) == 1
return res[0], padding
else:
return tuple(res), padding
def ApplyPadding(padding, x, padded=None, use_select=True, ensure_shape=True):
"""Applies padding to a tensor.
This is preferable to using arithmetic means for masking out padded values
such as::
# Equiv to ApplyPadding(padding, x)
x *= 1.0 - padding
# Equiv to ApplyPadding(padding, new, old)
new = old * padding + new * (1 - padding)
Aside from just being easier to read and reason about, using this function
is friendly to quantized representations because it does not mix arithmetic
on the padding values with the values in the tensor being padded (which can
have a very different range than the 0..1 padding tensor).
In addition, this works around issues in quantized schemes where we are
guaranteed to have an exact 0 but not necessarily any other number (i.e. 1).
Args:
padding: Tensor of padding values where 0 == keep and 1 == pad.
x: Tensor to apply padding to.
padded: Optional. Values to include for padded elements. Defaults to zeros.
Must have a shape broadcastable to 'x' if specified.
use_select: Controls whether padding is applied with a select-mask
(True/default) or arithmetically (False). Some platforms have a
sensitivity to one or the other and this is used to work around such
issues.
ensure_shape: If true, ensures the shape of the result is the same as of x.
Returns:
A tensor with the same shape as x with padded values masked.
"""
padding = with_dependencies([
Assert(
tf.reduce_all(
tf.math.logical_or(
tf.equal(padding, tf.zeros([], padding.dtype)),
tf.equal(padding, tf.ones([], padding.dtype)))), [padding])
], padding)
if use_select:
if padded is None:
padded = tf.zeros([], x.dtype)
if padding.dtype != tf.bool:
padding = padding > tf.zeros([], padding.dtype)
result = tf.where_v2(padding, padded, x)
else:
result = x * tf.cast(1.0 - tf.cast(padding, tf.float32), x.dtype)
if padded is not None:
result += padded * tf.cast(padding, padded.dtype)
if ensure_shape:
result = tf.ensure_shape(result, x.shape)
return result
def LengthsFromPaddings(paddings):
"""Computes lengths of each sequence in a batch, ignoring trailing padding.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x
Args:
paddings: a tensor with shape [batch, length].
Returns:
lengths tensor shaped [batch] containing the unpadded length of each
sequence in the batch.
"""
paddings = HasRank(paddings, 2)
paddings = tf.cast(paddings, tf.int32)
# Find the last unpadded value.
# Cannot just use tf.reduce_sum because there might be leading paddings.
# Everything after the last unpadded value has 1.0 - paddings == 0.0, so in
# the cumsum below they will have the same value.
cumsum = tf.cumsum(1 - paddings, axis=1)
same_as_last_element = tf.equal(cumsum, cumsum[:, -1:])
# Counting the number of elements with the same value gives us num_padded + 1
# and so counting the number that differs gives us num_padded - 1.
length = tf.reduce_sum(
1 - tf.cast(same_as_last_element, tf.int32), axis=1) + 1
# Special case for all 0 paddings.
all_zero_paddings = tf.equal(tf.reduce_sum(1 - paddings, axis=1), 0)
return tf.where(all_zero_paddings, tf.zeros_like(length), length)
def PaddingsFromLengths(lengths, maxlen=None):
"""Computes paddings Tensor from lengths.
Note the following isn't guaranteed due to leading paddings.
PaddingsFromLengths(LengthsFromPaddings(x)) == x.
This method does not generate leading paddings.
Args:
lengths: A int32 Tensor of shape [B].
maxlen: None or a Python int or a scalar Tensor.
Returns:
A 0/1 valued Tensor of shape [B, maxlen or ?] where 1s are padded positions.
"""
lengths = HasRank(lengths, 1)
if maxlen is not None:
lengths = with_dependencies(
[assert_less_equal(tf.cast(tf.reduce_max(lengths), tf.int32), maxlen)],
lengths)
return 1. - tf.sequence_mask(lengths, maxlen=maxlen, dtype=tf.float32)
def TrimTrailingPaddings(inputs, paddings):
"""Trims trailing paddings from inputs.
Since the number of dimensions is not fixed, this will not work on TPU.
Args:
inputs: a tensor with shape [batch, length, ...].
paddings: a tensor with shape [batch, length].
Returns:
Trimmed inputs and paddings. For compatibility reasons, the trimmed tensors
will always have length at least 1.
"""
paddings = HasRank(paddings, 2)
max_length = tf.maximum(tf.reduce_max(LengthsFromPaddings(paddings)), 1)
output_shape = tf.shape(inputs)
output_shape = tf.concat([[output_shape[0], max_length], output_shape[2:]],
axis=0)
outputs = tf.slice(inputs, tf.zeros_like(output_shape), output_shape)
out_paddings = tf.slice(paddings, [0, 0],
tf.stack([output_shape[0], max_length]))
return outputs, out_paddings
def ReversePaddedSequence(inputs, paddings):
"""Reverse inputs based on paddings.
Only reverse the unpadded portion of `inputs`. It assumes inputs are only
padded in the end.
Args:
inputs: a tensor of [seq_length, batch_size, num_input_nodes].
paddings: a tensor of float32/float64 zero or one of shape [seq_length,
batch_size, 1].
Returns:
A reversed tensor of the same shape as `inputs`.
"""
inversed_paddings = 1.0 - tf.squeeze(paddings, 2)
inputs_length = tf.cast(
tf.math.rint(tf.reduce_sum(inversed_paddings, axis=0)), tf.int32)
return tf.reverse_sequence(inputs, inputs_length, seq_axis=0, batch_axis=1)
def ConcatenatePaddedSequences(input0, input1, padding0, padding1, seq_dim=1):
"""Concatenates input sequences with varying lengths as defined by paddings.
This is a helper function for concatenating 2 batches of input sequences,
where each example in the batch can have different lengths, as defined by
the corresponding paddings. To concatenate correctly, it makes use of
tf.reverse_sequence to partially reverse the sequences before
concatenating them together.
NOTE: We assume that the tensors have no leading paddings.
Args:
input0: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
input1: A tensor of size [batch, max_length, ...] or [max_length, batch,
...] depending on the value set for axis.
padding0: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input0.
padding1: A Tensor of size [batch, max_length] or [max_length, batch]
corresponding to the padding for input1.
seq_dim: int, the time axis along which the tensors will be concatenated.
Should be 0 or 1. Assumes that batch_dim is 1 - seq_dim.
Returns:
The concatenation of input0 and input1, and the corresponding padding.
Raises:
tf.errors.InvalidArgumentError when seq_dim is not 0 or 1.
"""
if seq_dim != 0 and seq_dim != 1:
raise tf.errors.InvalidArgumentError(None, None, 'seq_dim must be 0 or 1.')
batch_dim = 1 - seq_dim
# inpu0 and input1 should have the same batch size and same rank.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim],
GetShape(input1)[batch_dim]),
assert_equal(GetRank(input0), GetRank(input1))
], input0)
batch_size = GetShape(padding0)[batch_dim]
# batch dimension of inputs and paddings should match.
input0 = with_dependencies([
assert_equal(GetShape(input0)[batch_dim], batch_size),
assert_equal(GetShape(padding1)[batch_dim], batch_size)
], input0)
input0_seq_dim = tf.cast(
tf.tile([tf.shape(padding0)[seq_dim]], [batch_size]), dtype=tf.int32)
input1_seq_dim = tf.cast(
tf.tile([tf.shape(padding1)[seq_dim]], [batch_size]), dtype=tf.int32)
# LengthsFromPaddings assumes that paddings is of size [batch, max_length].
if seq_dim == 1:
seq_length0 = LengthsFromPaddings(padding0)
seq_length1 = LengthsFromPaddings(padding1)
else:
seq_length0 = LengthsFromPaddings(tf.transpose(padding0))
seq_length1 = LengthsFromPaddings(tf.transpose(padding1))
# We assume that the tensors have no leading paddings.
# TODO(arunnt): Concatenate tensors with leading paddings correctly.
seq_length0 = with_dependencies([
assert_equal(
seq_length0,
tf.cast(tf.reduce_sum(1.0 - padding0, seq_dim), dtype=tf.int32))
], seq_length0)
seq_length1 = with_dependencies([
assert_equal(
seq_length1,
tf.cast(tf.reduce_sum(1.0 - padding1, seq_dim), dtype=tf.int32))
], seq_length1)
# Concatenate input sequences.
reversed_input0 = tf.reverse_sequence(
input0, seq_length0, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_input1 = tf.reverse_sequence(
input1, input1_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat = tf.concat([reversed_input1, reversed_input0], axis=seq_dim)
concat_inputs = tf.reverse_sequence(
reversed_concat,
seq_length0 + input1_seq_dim,
seq_axis=seq_dim,
batch_axis=batch_dim)
# Concatenate paddings. Note that paddings are always a Tensor of 0s and 1s,
# so, unlike the inputs, we don't have to reverse padding1, we can simply
# concatenate reversed padding0 and padding1.
reversed_padding0 = tf.reverse_sequence(
padding0, input0_seq_dim, seq_axis=seq_dim, batch_axis=batch_dim)
reversed_concat_padding = tf.concat([reversed_padding0, padding1],
axis=seq_dim)
concat_paddings = tf.reverse_sequence(
reversed_concat_padding,
input0_seq_dim + seq_length1,
seq_axis=seq_dim,
batch_axis=batch_dim)
return concat_inputs, concat_paddings
def ShiftLeft(tensor, shift_size, pad_val=0, axis=1):
"""Shifts the values in a tensor to the left along the axis dimension.
The first shift_size values are dropped, and the tensor is padded on the
right with pad_val.
Args:
tensor: the input tensor with the axis dim being time.
shift_size: the number of frames >= 0 to shift.
pad_val: the value to pad on the right of the tensor.
axis: The dimension along which the tensor will be shifted, default to 1.
Returns:
A left shifted tensor on dimension axis.
"""
rank = tensor.shape.rank
with tf.control_dependencies(
[assert_greater_equal(rank, 2),
assert_greater_equal(shift_size, 0)]):
time = GetShape(tensor)[axis]
begin = tf.scatter_nd([[axis]], [shift_size], [rank])
return PadSequenceDimension(
tf.slice(tensor, begin, size=[-1] * rank), time, pad_val, axis=axis)
def CreateIdsAndLabels(ids, paddings, sos_id=1, eos_id=2):
"""Creates ids and labels to be used as decoder targets.
Args:
ids: int Tensor of shape [batch, maxlen], without sos or eos.
paddings: float Tensor of shape [batch, maxlen].
sos_id: ID for the sos special token.
eos_id: ID for the eos special token.
Returns:
A NestedMap with:
- ids: int Tensor of shape [batch, maxlen + 1], with sos prepended.
- labels: int Tensor of shape [batch, maxlen + 1], with eos appended.
- paddings: float Tensor of shape [batch, maxlen + 1].
- weights: float Tensor of shape [batch, maxlen + 1].
"""
ids = tf.where(
tf.equal(paddings, 0.0), ids, tf.broadcast_to([[eos_id]], GetShape(ids)))
targets = NestedMap()
targets.ids = tf.pad(ids, [[0, 0], [1, 0]], constant_values=sos_id)
targets.labels = tf.pad(ids, [[0, 0], [0, 1]], constant_values=eos_id)
targets.paddings = tf.pad(paddings, [[0, 0], [1, 0]])
targets.weights = 1.0 - targets.paddings
return targets
def Retry(*args, **kwargs):
return retry.Retry(*args, **kwargs)
# FailedPreconditionError: variables are not initialized.
# AbortedError: processes restarts.
# UnavailableError: Bad hardware status: 0x1
transient_tf_errors = (tf.errors.FailedPreconditionError,
tf.errors.AbortedError, tf.errors.UnavailableError)
def RetryOnTransientTfError(*args, **kwargs):
return Retry(transient_tf_errors, *args, **kwargs)
def PadOrTrimTo(x, shape, pad_val=0, pad_after_contents=True):
"""Pad and slice x to the given shape.
Args:
x: A tensor.
shape: The shape of the returned tensor.
pad_val: An int or float used to pad x.
pad_after_contents: Whether to pad and trim after the original contents of
each dimension.
Returns:
'x' is padded with pad_val and sliced so that the result has the given
shape.
Raises:
ValueError: if shape is a tf.TensorShape and not fully defined.
"""
if isinstance(shape, (list, tuple)):
expected_rank = len(shape)
elif isinstance(shape, tf.TensorShape):
if not shape.is_fully_defined():
raise ValueError('shape %s padding %s must be fully defined.' %
(shape, x))
expected_rank = shape.rank
else:
shape = HasRank(shape, 1)
expected_rank = tf.size(shape)
x = HasRank(x, expected_rank)
pad = shape - tf.minimum(tf.shape(x), shape)
zeros = tf.zeros_like(pad)
if pad_after_contents:
# If dim_i is less than shape[i], pads after contents.
paddings = tf.stack([zeros, pad], axis=1)
# If dim_i is larger than shape[i], we slice [0:shape[i]] for dim_i.
slice_begin = zeros
else:
# If dim_i is less than shape[i], pads before contents.
paddings = tf.stack([pad, zeros], axis=1)
# If dim-i is larger than shape[i], we slice [dim_i - shape[i]:dim_i]
# for dim_i.
slice_begin = tf.shape(x) + pad - shape
x = tf.pad(x, paddings, constant_values=pad_val)
x = tf.slice(x, slice_begin, shape)
return tf.reshape(x, shape)
def RepeatDim(tensor, multiple, axis):
"""Copies elements in tensor's axis "multiple" times, like np.repeat."""
# x = [[1, 2, 3], [4, 5, 6]]
# RepeatDim(x, multiple=2, axis=1) gives:
# [[1, 1, 2, 2, 3, 3]. [4, 4, 5, 5, 6, 6]]
# As a comparison tf.tile(x, multiples=[1, 2]) gives:\
# [[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]
if multiple == 1:
return tensor
t_shape = tf.shape(tensor)
tensor_dims = tf.concat(
[t_shape[:axis], [t_shape[axis] * multiple], t_shape[axis + 1:]], 0)
multiple_dims = tf.concat([
tf.fill([axis + 1], 1), [multiple],
tf.fill([tf.rank(tensor) - axis - 1], 1)
], 0)
return tf.reshape(
tf.tile(tf.expand_dims(tensor, axis + 1), multiple_dims), tensor_dims)
def StackTensorsRecursively(values):
"""Recursively stacks Tensors in a list of `.NestedMap`.
Args:
values: a list of `.NestedMap` or Tensors to stacks.
Returns:
A `.NestedMap` with stacked values or a stacked Tensor.
"""
flatten = [w.Flatten() for w in values]
stacked = []
for i in range(len(flatten[0])):
stacked += [tf.stack([flatten[j][i] for j in range(len(flatten))])]
ret = values[0].Pack(stacked)
return ret
def MixByWeight(inputs, weights, seed=None):
"""Returns a weighted random choice and bprop type from the give inputs.
Args:
inputs: a list of callables, where each callable returns a tf.Tensor or a
nested structure containing tf.Tensor. Function return types must be
consistent across elements. The tf.Operation to compute the result tensor
will only be invoked for one input at a time. For example, if each fn
represents an input record stream, a record will be drawn only from a
selected stream while the other streams will remain unchanged.
weights: a 1D tensor of float > 0 of the same length as inputs.
seed: random seed.
Returns:
A probabilistic sample from the inputs proportional to the weights. The
return type will be the same as return type of individual 'fn' from the
inputs.
A one-hot vector of the source selected.
"""
weights = tf.convert_to_tensor(weights, dtype=tf.float32)
weights = with_dependencies([
assert_equal(tf.shape(weights), [len(inputs)]),
assert_greater_equal(tf.reduce_min(weights), 0.0)
], weights)
lower = tf.cumsum(weights, exclusive=True)
upper = tf.cumsum(weights, exclusive=False)
r = tf.random.uniform(shape=[], maxval=upper[-1], seed=seed)
return_input = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), inputs[i])
for i in range(len(inputs))],
exclusive=True)
selected_index = tf.case(
[(tf.math.logical_and(lower[i] <= r, r < upper[i]), lambda i=i: i)
for i in range(len(inputs))],
exclusive=True)
bprop_index = tf.one_hot(selected_index, len(inputs), dtype=tf.float32)
return return_input, bprop_index
def CheckShapes(shapes):
"""Asserts that shapes is a tuple of NestedMap or tshape.Shape."""
assert isinstance(shapes, tuple), str(shapes)
for s in shapes:
if isinstance(s, NestedMap):
assert all([isinstance(t, tshape.Shape) for t in Flatten(s)
]), '{} contains non-tensor value.'.format(s)
else:
assert isinstance(s, tshape.Shape), '{}: {}'.format(type(s), s)
def FPropDtype(params):
return params.fprop_dtype if params.fprop_dtype is not None else params.dtype
def UpdateFpropDtype(params, fprop_dtype):
"""Recursively update the fprop_dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateFpropDtype(val, fprop_dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateFpropDtype(item, fprop_dtype)
elif key == 'fprop_dtype':
params.fprop_dtype = fprop_dtype
def UpdateDtype(params, dtype):
"""Recursively update the dtype of the Params."""
# Handle the case when the input "params" is not an instance of hyperparams
# For example, when UpdateDtype is called recursively for all the items in
# the "sub" list of SequentialLayer (see 1st elif below)
if not isinstance(params, hyperparams.Params):
return
for key, val in params.IterParams():
if isinstance(val, hyperparams.Params):
UpdateDtype(val, dtype)
elif isinstance(val, (list, tuple)):
for item in val:
UpdateDtype(item, dtype)
elif key == 'dtype':
params.dtype = dtype
def NameScopeDecorator(name_scope):
"""Decorates a python function to introduce a tf.name_scope.
Example::
@py_utils.NameScopeDecorator('foobar')
def MyFoobarMethod(self):
# ... Do TF things
Args:
name_scope: The name scope to introduce.
Returns:
A function decorator.
"""
def Decorator(f):
def Wrapped(*args, **kwargs):
with tf.name_scope(name_scope):
return f(*args, **kwargs)
return Wrapped
return Decorator
def SequencesToDebugStrings(ids, lens, summarize=5):
"""Returns debug strings for the given sequences.
Args:
ids: int32 of [batch, len].
lens: int32 of [batch].
summarize: number of ids to summarize per sequence.
Returns:
A string tensor of [batch].
"""
num_seqs = tf.shape(lens)[0]
def _Body(i, result):
line = tf.strings.format('{}', ids[i, :lens[i]], summarize=summarize)
return i + 1, tf.concat([result, tf.reshape(line, [1])], axis=0)
i0 = tf.zeros(shape=[], dtype=tf.int32)
result0 = tf.constant('', shape=[0], dtype=tf.string)
_, strs = tf.while_loop(
lambda i, result: i < num_seqs,
_Body, (i0, result0),
shape_invariants=(i0.shape, tf.TensorShape([None])))
return strs
# TODO(jamesqin): follow suggestions in
# b/167460492#comment16
def RematerializeFn(fn, *xs):
"""Calls fn and rematerializes fn in the backward pass.
`fn(*xs) -> ys`, where xs and ys can be a single tensor or a tuple of tensors.
Args:
fn: A python function to be rematerialized in the backprop pass.
*xs: A single tensor or a list/tuple of tensors. `xs` are input args to the
fn function.
Returns:
`fn(*xs)`
"""
initial_step_seed = GetStepSeed()
final_step_seed = MaybeGenerateSeedFromScope()
def Backward(fwd_xs, fwd_ys, d_fwd_ys):
"""The backward function that rematerializes forward outputs."""
del fwd_ys
always_true = tf.random.uniform([]) < 2.0
# Alternatively, can do this:
# tf.where(tf.math.is_nan(x),
# tf.constant(float('nan'), dtype=x.dtype) * tf.ones_like(x),
# x)
bak_xs = [tf.where(always_true, x, tf.zeros_like(x)) for x in fwd_xs.xs]
for dst, src in zip(bak_xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(initial_step_seed)
ys = fn(*bak_xs)
MaybeResetStepSeed(final_step_seed)
dxs = tf.gradients(ys, bak_xs, grad_ys=d_fwd_ys)
dxs_final = []
for dx, x in zip(dxs, bak_xs):
if dx is None:
dxs_final.append(tf.zeros_like(x))
else:
dxs_final.append(dx)
assert len(dxs_final) == len(bak_xs)
return NestedMap(
initial_step_seed=tf.zeros_like(initial_step_seed), xs=dxs_final)
ys_shapes = []
# TODO(huangyp, yonghui): Check Forward doesn't use any stateful random ops.
def Forward(fwd_xs):
"""Forward function plus sanity checks."""
for dst, src in zip(fwd_xs.xs, xs):
dst.set_shape(src.shape)
ResetStepSeed(fwd_xs.initial_step_seed)
ys = fn(*fwd_xs.xs)
# Some sanity check.
assert not GetExtraInputs()
assert not GetExtraArgs()
assert not GetExtraVars()
if isinstance(ys, tuple):
for y in ys:
assert isinstance(y, tf.Tensor)
ys_shapes.append(y.shape)
else:
assert isinstance(ys, tf.Tensor)
ys_shapes.append(ys.shape)
return ys
ys = CallDefun(
Forward,
NestedMap(initial_step_seed=initial_step_seed, xs=xs),
bak=Backward)
if isinstance(ys, tuple):
for y, s in zip(ys, ys_shapes):
y.set_shape(s)
else:
ys.set_shape(ys_shapes[0])
# TODO(b/129159299): The ResetStepSeed below is needed to work around this
# bug, which is a problem with global tensors being shared by different
# inference graphs. It should be replaced with the new step seed value
# returned from the Forward function when the bug is fixed.
MaybeResetStepSeed(final_step_seed)
return ys
# A set of names of stateful random number generator ops.
# See tensorflow/core/ops/random_ops.cc
_STATEFUL_RANDOM_OPS = frozenset({
# pyformat: disable
'RandomUniform',
'RandomUniformInt',
'RandomStandardNormal',
'ParameterizedTruncatedNormal',
'TruncatedNormal',
'RandomShuffle',
'Multinomial',
'RandomGamma',
'RandomPoisson',
'RandomPoissonV2',
# pyformat: enable
})
def StatefulRandomOpsInDefun(func, graph=None):
"""Checks whether the Defun depends on stateful random number ops.
Stateful random number generator ops should be avoid in Recurrent() call.
Otherwise, these ops produce inconsistent values between FProp and BProp.
Args:
func: a _DefinedFunction or ConcreteFunction to check.
graph: a Graph. Set None to use the default graph.
Returns:
A list of names of the stateful random ops.
Raises:
InvalidArgumentError: if the input func/graph is invalid.
"""
if graph is None:
graph = tf.get_default_graph()
func.add_to_graph(graph)
graph_def = graph.as_graph_def()
# A dict from function name to FunctionDef.
func_defs = {x.signature.name: x for x in graph_def.library.function}
if isinstance(func, function._DefinedFunction): # pylint: disable=protected-access
if func.definition.signature.name not in func_defs:
raise tf.errors.InvalidArgumentError(
None, None, 'Defun {} is not in the graph .'.format(
func.definition.signature.name))
nodes = py_collections.deque(func.definition.node_def)
else:
nodes = py_collections.deque(func.function_def.node_def)
stateful_ops = []
# Recursively search for stateful random op.
while nodes:
node = nodes.pop()
assert isinstance(node, node_def_pb2.NodeDef), node
if node.op in _STATEFUL_RANDOM_OPS:
stateful_ops.append(node.name)
continue
def _AddDefunNodes(func_name):
"""If the given func_name is a Defun, add its sub-nodes into nodes."""
if func_name in func_defs:
nodes.extend(func_defs[func_name].node_def)
# For functional.{While|For|If} ops, add their Defun attr into search.
if node.op == 'While':
_AddDefunNodes(node.attr['body'].func.name)
_AddDefunNodes(node.attr['cond'].func.name)
elif node.op == 'For':
_AddDefunNodes(node.attr['body'].func.name)
elif node.op == 'If':
_AddDefunNodes(node.attr['then_branch'].func.name)
_AddDefunNodes(node.attr['else_branch'].func.name)
elif node.op == 'StatefulPartitionedCall':
_AddDefunNodes(node.attr['f'].func.name)
elif node.op != 'PartitionedCall':
# For other op, check whether itself is a Defun op.
_AddDefunNodes(node.op)
return stateful_ops
def ToPlaceholders(nmap, dtype=None):
"""Converts every Tensor in nmap to a placeholder."""
def _ToPlacerholder(x):
shape = [None for _ in x.shape[:-1]] + [x.shape[-1]]
return tf.placeholder(dtype=dtype or x.dtype, shape=shape)
return nmap.Transform(_ToPlacerholder)
def Softmax(logits, axis=None, extra_logit=None, name=None):
"""Softmax with extra_logits, might be useful for large xformer LM."""
if extra_logit is None:
return tf.nn.softmax(logits, axis=axis, name=name)
axis = -1 if axis is None else axis
def ReduceLogSumExp(x):
max_logit = tf.math.reduce_max(
tf.stop_gradient(x), axis=axis, keepdims=True)
base_logit = tf.math.maximum(max_logit, extra_logit)
x -= base_logit
exp_x = tf.math.exp(x)
sum_exp_x = tf.math.reduce_sum(exp_x, axis=axis, keepdims=True)
sum_exp_x += tf.math.exp(extra_logit - base_logit)
return tf.math.log(sum_exp_x) + base_logit
def LogSoftmax(x):
return x - ReduceLogSumExp(x)
with tf.name_scope(name):
return tf.math.exp(LogSoftmax(logits))
def SoftmaxCrossEntropyFocalLoss(logits,
label_ids=None,
label_probs=None,
alpha=None,
gamma=None,
stop_gradient_on_focal_loss_coefficient=False):
u"""Focal loss for multinomial (softmax) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the multinomial logistic regression. C is the
number of classes.
label_ids: [...]. Each entry in labels must be an index in [0, C).
label_probs: [..., C]. Each vector along last dimension must be a valid
probability distribution.
alpha: [C]. The weighting factor alpha. Eq (3) in [1].
gamma: []. Tunable focusing parameter. Eq (4) in [1].
stop_gradient_on_focal_loss_coefficient: If true, stops gradient on the
focal loss coefficient (1-p)^gamma to stabilize the gradient.
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
def _ApplyFocalLossCoefficient(loss, log_probs):
if gamma is not None and gamma != 0:
probs = tf.exp(log_probs)
coefficient = tf.pow(1.0 - probs, gamma)
if stop_gradient_on_focal_loss_coefficient:
coefficient = tf.stop_gradient(coefficient)
loss *= coefficient
return loss
if label_probs is not None:
log_probs = tf.nn.log_softmax(logits)
loss = -(label_probs * log_probs)
loss = _ApplyFocalLossCoefficient(loss, log_probs)
if alpha is not None:
loss *= tf.reshape(
alpha, tf.concat([tf.ones(tf.rank(loss) - 1, tf.int32), [-1]],
axis=0))
loss = tf.reduce_sum(loss, axis=-1)
else:
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=label_ids, logits=logits)
loss = _ApplyFocalLossCoefficient(loss, -loss)
if alpha is not None:
loss *= tf.gather(alpha, label_ids)
return loss
def SigmoidCrossEntropyFocalLoss(logits, labels, alpha=None, gamma=None):
u"""Focal loss for binary (sigmoid) logistic loss.
[1] Focal loss https://arxiv.org/abs/1708.02002
Args:
logits: [..., C]. Logits for the sigmoid logistic regression.
labels: [..., C]. 0/1 labels.
alpha: The weighting factor alpha. Eq (3) in [1].
gamma: Tunable focusing parameter. Eq (4) in [1].
Returns:
loss[i..., j] = FL(pₜ) = - αₜ(1-pₜ)ˠlog(pₜ) Eq (5) in [1].
"""
# [1] Eq (4).
#
# The numerically-stable way to compute
# log(p) for positives;
# log(1 - p) for negatives.
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)
if gamma is not None and gamma != 0:
# The modulating factor. Note that
# (1 - p)ˠ = [1 - σ(x)]ˠ = [σ(-x)]ˠ, for positives.
# pˠ = [σ(x)]ˠ, for negatives.
loss *= tf.pow(tf.sigmoid(logits * (1 - labels * 2)), gamma)
if alpha is not None:
# [1] Eq (3)
loss *= (alpha * labels + (1 - alpha) * (1 - labels))
return loss
_RECORD_FORMAT_RE = re.compile('(^[A-Za-z_]+):(.*)')
def RecordFormatFromFilePattern(file_pattern):
"""Return the record format string for a Lingvo file pattern.
Lingvo file patterns take the form of:
tfrecord:/path/to/bar -> tfrecord is the record_format.
This function takes a file pattern and returns a string indicating
which format the filepattern implies.
Args:
file_pattern: String file pattern.
Returns:
Tuple (string, string):
- record_format: String record format, e.g., "tfrecord", etc.
- file_pattern: The file pattern without any prefixes.
"""
result = re.match(_RECORD_FORMAT_RE, file_pattern)
if result is None:
# TODO(vrv): Fix all callers so that file_pattern must contain
# the record format prefix.
return 'sstable', file_pattern
# regexp ensures that a match implies there are two groups:
# the record format and then the file pattern.
return result.groups()
def ReadFileLines(file_path):
"""Read a text file and return the lines.
If the file cannot be found at the given path, attempt to load it from the
Lingvo package (useful for data dependencies in par files).
Args:
file_path: path to file, either absolute or relative to the bazel workspace.
Returns:
A list of lines from the file.
"""
if not tf.io.gfile.exists(file_path):
try:
lines = pkgutil.get_data(
'lingvo', file_path.replace('lingvo/', '', 1))
if lines:
lines = lines.splitlines(True)
except IOError:
# If pkgutil can't find the file, continue and let GFile raise the error.
lines = None
else:
lines = None
if not lines:
with tf.io.gfile.GFile(file_path, 'r') as f:
lines = f.readlines()
return lines
# Partially borrowed from
# https://github.com/tensorflow/tensor2tensor/blob/32929305e1a4ec926eff24123758b794df35492b/tensor2tensor/layers/common_layers.py#L349
def CumSum(x, axis=0, exclusive=False, use_einsum=False):
"""A TPU efficient implementation of tf.cumsum().
This is equivalent to tf.cumsum and is faster on TPU as of 08/2019 unless
the axis dimension is very large. The current Tensorflow implementation is
based on scanning and reducing which is not efficient on TPU.
Args:
x: An input Tensor.
axis: An int for the axis.
exclusive: A bool for performing exclusive cumsum.
use_einsum: If true, use einsum on TPU.
Returns:
A Tensor of the same shape as x.
Raises:
ValueError: if the input axis is invalid.
"""
if x.dtype not in (tf.float32, tf.bfloat16) or not use_tpu():
# Fallback to tf.cumsum when inputs are not floats or not running on TPU.
return tf.cumsum(x, axis=axis, exclusive=exclusive)
rank = GetRank(x)
# Needs to know the rank for the final transpose if axis is not the last
# dimension. Otherwise, falls back to tf.cumsum.
if not isinstance(rank, int) and axis != -1:
return tf.cumsum(x, axis=axis, exclusive=exclusive)
if axis < -1:
if axis + rank < 0:
raise ValueError('Unexpected axis: %d (rank = %d)' % (axis, rank))
axis += rank
if use_einsum:
assert isinstance(rank, int) and rank < 26, rank
# Use einsum to avoid data formatting overhead.
a2z = ''.join([chr(i) for i in range(97, 123)]) # abc...xyz
src = a2z[:rank]
if axis == -1:
tgt = src[:-1] + 'z'
else:
tgt = src[:axis] + 'z' + src[axis + 1:]
length = GetShape(x)[axis]
causal_mask = tf.linalg.band_part(
tf.ones([length, length], dtype=x.dtype), 0, -1)
return tf.einsum(f'{src},{src[axis]}z->{tgt}', x, causal_mask)
length = GetShape(x)[axis]
my_range = tf.range(length)
comparator = tf.less if exclusive else tf.less_equal
mask = tf.cast(
comparator(tf.expand_dims(my_range, 1), tf.expand_dims(my_range, 0)),
x.dtype)
result = tf.tensordot(x, mask, axes=[[axis], [0]])
if axis != -1 and axis != rank - 1:
result = tf.transpose(
result,
list(range(axis)) + [rank - 1] + list(range(axis, rank - 1)))
return result
def ProjectLastDim(inputs, weight, input_dim, output_dim):
"""Linear projection on the last dim of the input tensor.
This is a TPU efficient implementation to avoid reshaping inputs to Rank-2
tensor by using Einsum for the compute.
Args:
inputs: An input Tensor, the last dimension of which is input_dim.
weight: A weight matrix with shape [input_dim, output_dim].
input_dim: An integer or a symbolic dim, the last dimension of the inputs.
output_dim: An integer or a symbolic dim, the last dimension of the outputs.
Returns:
An output Tensor of the same rank as inputs, the last dimension is
output_dim.
"""
input_dim = int(
symbolic.ToStatic(input_dim) if symbolic.IsExpr(input_dim) else input_dim)
output_dim = int(
symbolic.ToStatic(output_dim) if symbolic.IsExpr(output_dim
) else output_dim)
# Assert input_dim and output_dim
inputs = with_dependencies([assert_equal(GetShape(inputs)[-1], input_dim)],
inputs)
weight = with_dependencies([
assert_equal(GetShape(weight)[0], input_dim),
assert_equal(GetShape(weight)[-1], output_dim)
], weight)
if (use_tpu() and inputs.shape is not None and
inputs.shape.rank is not None and inputs.shape.rank < 26):
# Avoids reshape if feasible and uses Einsum.
if inputs.shape.rank == 2:
outputs = tf.matmul(inputs, weight)
else:
# This is equivalent to:
# outputs = tf.einsum('...y,yz->...z', inputs, weight)
# Unfortunately ... in einsum() leads to extra HBM usage.
s = ''.join([chr(x) for x in range(97, 123)]) # abc...xyz
r = inputs.shape.rank
outputs = tf.einsum('{0}y,yz->{0}z'.format(s[:r - 1]), inputs, weight)
else:
outputs = Matmul(tf.reshape(inputs, ToStaticShape([-1, input_dim])), weight)
outputs = tf.reshape(
outputs,
tf.concat([
tf.cast(GetShape(inputs)[:-1], tf.int32),
ToStaticShape([output_dim])
],
axis=0))
return outputs
@contextlib.contextmanager
def RemoveAssertContext(remove=True):
"""Hacks to replace certain unwanted tensorflow ops."""
# TODO(zhifengc/huangyp): Consider implementing assert_equal
# op replacement for lingvo. As assert_equal doesn't support String on GPUs.
# Hack to replace tf.assert_equal
# TODO(b/136040013): Remove this after migration to tf.function.
if remove:
saved_assert_equal = tf.check_ops.assert_equal
def NoOP(*args, **kwargs): # pylint: disable=unused-argument
return tf.no_op()
tf.check_ops.assert_equal = NoOP # Make assert_equal a no op.
try:
yield
finally:
tf.check_ops.assert_equal = saved_assert_equal
else:
yield
def _AssertInputsMatch(op, args, implicit_captures):
"""Assert that op's inputs match with args and implicit_captures.
Args:
op: The operation to check.
args: A nested structure representing the explicit arguments of 'op'.
implicit_captures: A nested structure representing the implicitly captured
inputs of 'op'.
Raises:
ValueError: if the number of inputs mismatch.
"""
expected_inputs = Flatten([args, implicit_captures])
expected_num_inputs = len(expected_inputs)
if len(op.inputs) > expected_num_inputs:
raise ValueError(('Too many inputs. The most likely cause is that fwd '
'captures additional tensors: extra inputs %r vs %r '
'captures=%r') % (list(op.inputs), list(expected_inputs),
list(Flatten(implicit_captures))))
if len(op.inputs) < expected_num_inputs:
raise ValueError(('Mismatched inputs to fwd: Found %d vs expected %d: %r'
'. Implicit captures(%d) = %r') %
(len(op.inputs), expected_num_inputs, list(op.inputs),
len(Flatten(implicit_captures)), implicit_captures))
def TensorSpecs(nmap, keep_shape=True):
"""Transforms tensors in the input nested structure to TensorSpecs."""
if nmap is None:
return None
fn = lambda t: tf.TensorSpec(t.shape if keep_shape else None, t.dtype)
return Transform(fn, nmap)
def _DefineDefun(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- output_dtypes: A nested structure compatible with the outputs of `fwd`
containing the corresponding output dtypes.
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
get_dtype = lambda x: x.dtype
arg_dtypes = Flatten(Transform(get_dtype, fwd_sig))
get_shape = lambda x: x.shape
arg_shapes = Flatten(Transform(get_shape, fwd_sig))
# Used to hold the backward function used by Grad, which will be defined if
# bak is set.
sigs = NestedMap()
# Output of this method.
res = NestedMap()
python_grad_func = None
if bak:
def Grad(op, *args):
"""Gradient function for the forward function.
Args:
op: The forward operation.
*args: Gradients wrt op.outputs.
Returns:
Tuple of derivatives.
"""
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs = op.inputs[:len(arg_dtypes)] # The rest are captures.
return sigs.backward(*Flatten([xs, op.outputs, args]))
python_grad_func = Grad
def _SetShape(dst_list, shape_list):
for dst, shape in zip(dst_list, shape_list):
if isinstance(dst, tf.Tensor):
dst.set_shape(shape)
@tf.Defun(*arg_dtypes, python_grad_func=python_grad_func, noinline=noinline)
def Forward(*args):
"""The forward function."""
_SetShape(args, arg_shapes)
with RemoveAssertContext(remove=noinline):
call = lambda: fwd(Pack(fwd_sig, args)) if args else fwd()
if device is None:
# Defun will handle the device assignment.
rets = call()
else:
with tf.device(device):
rets = call()
res.outputs = rets
return Flatten(rets)
forward = Forward
if not arg_dtypes:
# In this case Forward is an _OverloadedFunction, we need to instantiate it.
forward = Forward.instantiate([])
# Invokes fwd() to get res.outputs.
forward.add_to_graph(tf.get_default_graph())
res.func = forward
res.stateful_ops = forward.stateful_ops
res.captured_inputs = forward.captured_inputs
output_dtypes = Transform(get_dtype, res.outputs)
output_shapes = Transform(get_shape, res.outputs)
def Call(args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = forward()
else:
flat_rets = forward(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
_SetShape(flat_rets, Flatten(output_shapes))
return Pack(output_dtypes, flat_rets)
res.call = Call
if bak:
def Backward(*args):
"""The backward function."""
_SetShape(args, Flatten([arg_shapes, output_shapes, output_shapes]))
xs, ys, dys = Pack([fwd_sig, output_dtypes, output_dtypes], args)
with RemoveAssertContext(remove=noinline):
if device is None:
# Defun will handle the device assignment.
dxs = bak(xs, ys, dys)
else:
with tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
sigs.backward = tf.Defun(
*Flatten([arg_dtypes, output_dtypes, output_dtypes]),
noinline=noinline)(
Backward)
sigs.backward.add_to_graph(tf.get_default_graph())
else:
sigs.backward = Backward
return res
# Global variable to control rendezvous sharing in tf.function.
# If False (default) rendezvous sharing is disabled in tf.function, that is, the
# function body use a separate rendezvous and can't communicate with parent
# graph via send/recv.
# With _GetSharedRendezvous() == True, the function body share the same
# rendezvous with the parent graph and can talk to it using send/recv. This is
# useful for layers like StackedRecurrent.
_SHARED_RENDEZVOUS = ThreadLocalStack()
@contextlib.contextmanager
def _SharedRendezvousScope(shared_rendezvous=True):
_SHARED_RENDEZVOUS.stack.append(shared_rendezvous)
try:
yield
finally:
_SHARED_RENDEZVOUS.stack.pop()
def _GetSharedRendezvous():
"""Get the current rendezvous sharing setting."""
return _SHARED_RENDEZVOUS.stack[-1] if _SHARED_RENDEZVOUS.stack else False
def _ApplySharedRendezvous(func):
"""Apply the rendezvous sharing setting on the given tf.function func."""
# pylint: disable=protected-access
func._shared_rendezvous = _GetSharedRendezvous()
# pylint: enable=protected-access
def _WrapFunction(func=None, input_signature=None):
"""Wraps func as a tf.function."""
if input_signature is None:
input_signature = []
def Decorated(fn):
@tf.function(input_signature=input_signature, autograph=False)
def Fn(*args):
# TODO(b/163904067): mimic Defun' behavior and reset the step seed to
# avoid it being used as an implicit capture. This is not a desired
# behavior, it should take the step seed from parent graph instead.
ResetStepSeed()
# Mimic Defun and disable collection sharing.
graph = tf.get_default_graph()
# Don't share summaries collection with parent graph (b/168745134).
graph.clear_collection(tf.GraphKeys.SUMMARIES)
return fn(*args)
_ApplySharedRendezvous(Fn)
# Add the function to the graph so it'll be traced under the current
# context. This is necessary if the function body captures any non-tensor
# values from the environment, like symbolic maps.
cf = Fn.get_concrete_function()
cf.add_to_graph()
return cf
# For the `foo = _WrapFunction(foo, ...)` use case.
if func is not None:
return Decorated(func)
# For the `@_WrapFunction(...)` use case.
return Decorated
def _DefineFunction(fwd, fwd_sig, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that fwd takes no inputs).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: the device on which to run `fwd` and `bak`.
Returns:
A NestedMap containing:
- call: A callable that will execute `fwd`. It has the same input and output
signatures as `fwd`.
- func: The underlying TF function that `call` calls. If not None, it will
be a _DefinedFunction or ConcreteFunction that takes flat inputs and
returns flat outputs, and can be used by routines that require a TF
function object (e.g. tf.If, tf.While, etc).
Always not None when `bak` is None.
- outputs: The outputs of `fwd`. Used for reflection only (e.g. to get the
output dtypes, shapes, etc).
- stateful_ops: A list of (op_name, op_type) tuples representing the
stateful ops used by `fwd`.
- captured_inputs: Implicit inputs captured by `fwd`.
"""
assert fwd is not None
noinline = not use_xla()
if fwd_sig is None:
fwd_sig = []
if device is None:
# Get the current device to mimic Defun's behavior.
# pylint: disable=protected-access
device_funcs = tf.get_default_graph()._device_functions_outer_to_inner
device = device_funcs[-1] if device_funcs else None
# pylint: enable=protected-access
# Output of this method.
res = NestedMap()
@_WrapFunction(input_signature=Flatten(fwd_sig))
def Forward(*args):
"""The forward function."""
with RemoveAssertContext(remove=noinline), tf.device(device):
if args:
xs = Pack(fwd_sig, args)
rets = fwd(xs)
else:
rets = fwd()
res.outputs = rets
return Flatten(rets)
res.captured_inputs = Forward.captured_inputs
# Get the stateful ops used in cell_fn. Logic borrowed from
# _EagerDefinedFunction.__init__().
graph = Forward.graph
input_ops = set(arg.op for arg in graph.inputs)
operations = [op for op in graph.get_operations() if op not in input_ops]
res.stateful_ops = [(o.name, o.type) for o in operations if o._is_stateful] # pylint: disable=protected-access
def Call(func, args=None):
"""Wrapper of fwd."""
if args is None:
flat_rets = func()
else:
flat_rets = func(*Flatten(args))
if not isinstance(flat_rets, (tuple, list)):
flat_rets = [flat_rets]
return Pack(res.outputs, flat_rets)
if not bak:
res.func = Forward
res.call = lambda args=None: Call(Forward, args)
return res
shared_rendezvous = _GetSharedRendezvous()
ret_specs = TensorSpecs(res.outputs)
def Backward(*args):
xs, ys, dys = Pack([fwd_sig, ret_specs, ret_specs], args)
with RemoveAssertContext(remove=noinline), tf.device(device):
dxs = bak(xs, ys, dys)
return Flatten(dxs)
if bak_as_function:
backward_cf = _WrapFunction(
Backward, input_signature=Flatten([fwd_sig, ret_specs, ret_specs]))
else:
def BackwardWithSharedRendezvous(*args):
with _SharedRendezvousScope(shared_rendezvous):
return Backward(*args)
backward_cf = BackwardWithSharedRendezvous
@tf.custom_gradient
def ForwardWithGrad(*args):
"""Forward function and its custom gradient."""
# Note that `args` includes implicit captures. This is required by
# tf.custom_gradient so that when the Grad() outputs include gradients to
# implicit captures, they match the inputs to ForwardWithGrad().
#
# However, Forward doesn't take implicit captures as input, so we exclude
# them here.
fwd_args = args[:(len(args) - len(Flatten(res.captured_inputs)))]
op = NestedMap(inputs=args, outputs=Forward(*fwd_args))
def Grad(*args, **kwargs):
"""Gradient function for the forward function.
Args:
*args: Gradients wrt op.outputs.
**kwargs: Additional arguments from tf.custom_gradient.
Returns:
Tuple of derivatives.
"""
if kwargs:
tf.logging.warning(
'Ignoring additional arguments used by tf.custom_gradient: %s',
str(kwargs))
_AssertInputsMatch(op, fwd_sig, res.captured_inputs)
# Ensure dys contains no None.
args = ConvertNoneGradientToZeros(list(op.outputs), list(args))
xs, _ = Pack([fwd_sig, res.captured_inputs], op.inputs)
return backward_cf(*Flatten([xs, op.outputs, args]))
return op.outputs, Grad
res.func = None
forward = lambda *xs: ForwardWithGrad(*Flatten([xs, res.captured_inputs]))
res.call = lambda args=None: Call(forward, args)
return res
# Global variable to control whether to use tf.function.
# If not set, the result is determined by tf2 status. See _UseTfFunction for
# details.
# TODO(laigd): remove after b/169869929 is fixed.
_USE_TF_FUNCTION = ThreadLocalStack()
# Constants for propagating framework tensors through Function.
_FRAMEWORK_TENSOR_GLOBAL_STEP = '_global_step'
@contextlib.contextmanager
def TfFunctionScope(use_tf_function=True):
_USE_TF_FUNCTION.stack.append(use_tf_function)
try:
yield
finally:
_USE_TF_FUNCTION.stack.pop()
def _UseTfFunction():
"""Whether to use tf.function instead of tf.Defun."""
if _USE_TF_FUNCTION.stack:
return _USE_TF_FUNCTION.stack[-1]
return tf2_enabled()
class Function(object):
"""Function builds a TensorFlow graph function from a callable.
In the high level this is similar to tf.Defun and tf.function. In fact this
relies on those as underlying implementations, but with specific configuration
so it's easier to use and can work well in some extreme cases in Lingvo.
Example usage:
- No inputs:
>>> @Function()
... def foo():
... return tf.constant(1.0)
>>> y = foo()
- Scalar input:
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32))
... def foo(x):
... return x * 2
>>> y = foo(1.0)
- List input:
>>> @Function(fwd_sig=[tf.TensorSpec(None, tf.float32) for _ in range(2)])
... def foo(xs):
... return xs[0] + xs[1]
>>> y = foo([1.0, 2.0])
- Nested input:
>>> @Function(fwd_sig=NestedMap(x=tf.TensorSpec(None, tf.float32)))
... def foo(nmap):
... return nmap.x * 2
>>> y = foo(NestedMap(x=1.0))
- With custom gradient function (other input types mentioned above are also
supported):
>>> def bar(x, y, dy):
... del y, dy
... return 4.0 * x * dy
>>>
>>> @Function(fwd_sig=tf.TensorSpec(None, tf.float32), bak=bar)
... def foo(x):
... return 2.0 * x * x
- Used in control flow ops:
>>> then_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: x / 2)
>>> else_branch = Function(tf.TensorSpec([], tf.int32))(lambda x: 3 * x + 1)
>>> y = tf.If(cond, inputs, then_branch.func, else_branch.func)
"""
# TODO(laigd): the use_tf_function option is added for backward compatibility
# reasons. Remove it after the migration.
def __init__(self,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Below we assume `fwd` is the input to `__call__` that is used to build the
TensorFlow graph function encapsulated by this object.
Args:
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
self._bak = bak
self._bak_as_function = bak_as_function
self._device = device
self._use_tf_function = use_tf_function
def __call__(self, fwd):
"""Creates a graph function.
Args:
fwd: a callable xs: Nested Structure -> ys: Nested Structure.
Returns:
A DefinedFunction object encapsulating `fwd` as a graph function.
"""
assert callable(fwd)
return DefinedFunction(fwd, self._fwd_sig, self._bak, self._bak_as_function,
self._device, self._use_tf_function)
class DefinedFunction(object):
"""Encapsulates a TensorFlow graph function and its properties."""
def __init__(self,
fwd,
fwd_sig=None,
bak=None,
bak_as_function=False,
device=None,
use_tf_function=None):
"""Constructor.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure. Used to
build the TensorFlow graph function that this object encapsulates.
fwd_sig: A Nested Structure of tf.TensorSpec representing the input
signature of `fwd`, or None (meaning that `fwd` takes no inputs). The
actual inputs should be compatible with this (have same shapes and
dtypes).
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for `fwd`. bak needs to return
dcapture if `fwd` uses any implicitly captured tensors, whose gradients
are dcapture.
bak_as_function: Whether to create a TF graph function for `bak`.
device: The device on which to run `fwd` and `bak`. Defaults to the
current device.
use_tf_function: Whether use tf.function. Defaults to _UseTfFunction().
"""
self._fwd_sig = fwd_sig
wrapped_fwd_sig = fwd_sig
fwd_fn = fwd
bak_fn = bak
graph_random_seed = None
if tf.get_default_graph().seed is not None:
graph_random_seed = tf.get_default_graph().seed
# Wrap the forward function to propagate framework tensors like step_seed
# and global_step.
wrapped_fwd_sig = NestedMap()
self._added_global_step = False
if GetGlobalStep() is not None:
wrapped_fwd_sig[_FRAMEWORK_TENSOR_GLOBAL_STEP] = (
tf.TensorSpec([], tf.int64))
self._added_global_step = True
if fwd_sig is not None:
wrapped_fwd_sig.inputs = fwd_sig
elif not wrapped_fwd_sig:
wrapped_fwd_sig = None
def ForwardWrapped(wrapped_inputs=None):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
global_step = None
if wrapped_inputs:
assert isinstance(wrapped_inputs, NestedMap)
global_step = wrapped_inputs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)
with GlobalStepContext(global_step):
if wrapped_inputs and 'inputs' in wrapped_inputs:
result = fwd(wrapped_inputs.inputs)
else:
result = fwd()
return result
fwd_fn = ForwardWrapped
if bak:
# Wrap the backward function to return zero gradients for framework
# tensors like step_seed and global_step.
def BackwardWrapped(wrapped_xs, ys, dys):
if graph_random_seed is not None:
tf.random.set_seed(graph_random_seed)
with GlobalStepContext(
wrapped_xs.get(_FRAMEWORK_TENSOR_GLOBAL_STEP, None)):
result = bak(wrapped_xs.inputs, ys, dys)
dxs = Transform(tf.zeros_like, wrapped_xs)
if isinstance(result, tuple) and len(result) == 2:
dxs.inputs, dcapture = result
return dxs, dcapture
else:
dxs.inputs = result
return dxs
bak_fn = BackwardWrapped
if use_tf_function is None:
use_tf_function = _UseTfFunction()
fn = _DefineFunction if use_tf_function else _DefineDefun
self._data = fn(
fwd=fwd_fn,
fwd_sig=wrapped_fwd_sig,
bak=bak_fn,
bak_as_function=bak_as_function,
device=device)
def __call__(self, args=None):
"""Invokes the graph function.
Args:
args: the inputs to the graph function, must be compatible with `fwd_sig`.
Returns:
The output tensors with the same structure as the output of `fwd`,
returned by a call to the graph function.
"""
assert IsCompatible(args,
self._fwd_sig), '{} vs {}'.format(args, self._fwd_sig)
return self._data.call(self.AddFrameworkInputs(args))
@property
def func(self):
"""The underlying TensorFlow graph function that this object encapsulates.
The returned graph function is created by tracing `fwd` during construction.
If not None, it will be a _DefinedFunction or ConcreteFunction that takes
flat inputs and returns flat outputs, and can be used by routines that
require a TensorFlow function object (e.g. tf.If, tf.While, etc).
If no backprop function is provided during construction, the result is
always not None.
"""
return self._data.func
def AddFrameworkInputs(self, inputs):
"""Add framework tensors like step_seed and global_step to inputs.
This is only necessary when using `func`, as wrapping is handled
automatically in __call__.
Args:
inputs: inputs to the function.
Returns:
Inputs wrapped with framework tensors suitable for use with `func`.
"""
result = NestedMap()
if self._added_global_step:
global_step = GetGlobalStep()
assert global_step is not None
result[_FRAMEWORK_TENSOR_GLOBAL_STEP] = tf.cast(global_step, tf.int64)
if inputs is not None:
result.inputs = inputs
return result if result else None
@property
def output_dtypes(self):
"""Output dtypes of the graph function.
The result will have the same structure as the outputs of `fwd` but contain
the corresponding output dtypes.
"""
return Transform(lambda x: x.dtype, self._data.outputs)
@property
def stateful_ops(self):
"""Stateful ops used by `fwd`, as a list of (op_name, op_type) tuples."""
return self._data.stateful_ops
@property
def captured_inputs(self):
"""Implicit input tensors captured by `fwd`."""
return self._data.captured_inputs
def CallDefun(fwd, args=None, bak=None, bak_as_function=False, device=None):
"""Wraps fwd in a defun with custom gradient bak and calls it with args.
Args:
fwd: A callable xs: Nested Structure -> ys: Nested Structure.
args: A Nested Structure of tf.Tensor or None.
bak: A callable xs, ys, dys: Nested Structure -> dxs[, dcapture]: Nested
Structure. The custom backprop function for fwd. bak needs to return
dcapture if fwd uses any implicitly captured tensors, whose gradients are
dcapture.
bak_as_function: Whether to create a TF graph function for bak.
device: the device on which to run fwd and bak.
Returns:
A Nested Structure equivalent to what fwd(args) computes.
"""
if args is not None:
args = Transform(tf.convert_to_tensor, args)
sigs = Function(
fwd_sig=TensorSpecs(args),
bak=bak,
bak_as_function=bak_as_function,
device=device)(
fwd=fwd)
if args is None:
return sigs()
else:
return sigs(args)
def If(cond, inputs, then_branch, else_branch):
"""Helper to construct an if/else statement.
Args:
cond: A scalar `Tensor` that can be converted to boolean.
inputs: A flattenable representing the input tensors of the if/else
statement. Can be None to represent no inputs.
then_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'else_branch' returns.
else_branch: A callable 'inputs' -> flattenable. The returned value should
be compatible with what 'then_branch' returns.
Returns:
Output returned by the call to either 'then_branch' or 'else_branch'.
"""
fwd_sig = TensorSpecs(inputs)
then_sigs = Function(fwd_sig=fwd_sig)(fwd=then_branch)
else_sigs = Function(fwd_sig=fwd_sig)(fwd=else_branch)
assert IsCompatible(then_sigs.output_dtypes, else_sigs.output_dtypes), (
'Outputs of then_branch and else_branch are not compatible: {} vs {}'
.format(then_sigs.output_dtypes, else_sigs.output_dtypes))
if then_sigs.captured_inputs != else_sigs.captured_inputs:
raise ValueError('Differing captured inputs in then and else. '
'Ensure the same tensors are captured in the same order.')
ret = tf.If(
cond=cond,
inputs=Flatten(then_sigs.AddFrameworkInputs(inputs)) +
then_sigs.captured_inputs,
then_branch=then_sigs.func,
else_branch=else_sigs.func)
return Pack(then_sigs.output_dtypes, ret)
def _Itype():
"""Loop iterator data type."""
return tf.int32 if use_xla() else tf.int64
def WhileLoop(cond, body, loop_state):
"""Helper to construct a while loop.
Args:
cond: A callable NestedMap -> tf.bool.
body: A callable NestedMap -> NestedMap.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
fwd_sig = TensorSpecs(loop_state)
cond_sigs = Function(fwd_sig=fwd_sig)(fwd=cond)
def BodyWrapped(loop_state):
result = body(loop_state)
# loop_state is augmented with global tensors inside of DefinedFunction.
# WhileLoop needs to return the same structure as the inputs, so we augment
# the return value here to match.
result = cond_sigs.AddFrameworkInputs(result)
return result
body_sigs = Function(fwd_sig=fwd_sig)(fwd=BodyWrapped)
wrapped_inputs = body_sigs.AddFrameworkInputs(loop_state)
new_state = tf.While(
Flatten(wrapped_inputs), cond=cond_sigs.func, body=body_sigs.func)
# The functional `While` used above does not have a registered gradient.
# This was not a problem in Graph mode, however in Eager mode,
# GradientTape will attempt to call the gradient of the While op in the
# forward pass. `stop_gradient` is used to pretend the op is a constant
# in the forward pass. This also avoids calling the gradient of other ops in
# `While` in the forward pass.
# Details in https://www.tensorflow.org/api_docs/python/tf/custom_gradient.
# Guarded by 'IsEagerMode' to limit impact.
if IsEagerMode():
new_state = [tf.stop_gradient(t) for t in new_state]
return Pack(wrapped_inputs, new_state).inputs
def ForLoop(body, start, limit, delta, loop_state):
"""Helper to construct a for loop.
Args:
body: A callable (tf.int, NestedMap) -> NestedMap.
start: Loop variable's initial value.
limit: Loop variable's limit value.
delta: Loop variable's change per iteration.
loop_state: A flattenable (NestedMap, list, tuple, etc.) representing the
loop state.
Returns:
The final loop state in the same structure as loop_state.
"""
state = NestedMap(
iter=tf.cast(start, _Itype()),
limit=tf.cast(limit, _Itype()),
delta=tf.cast(delta, _Itype()),
loop_state=loop_state)
def LoopCond(state):
return tf.less(state.iter, state.limit)
def LoopBody(state):
state.loop_state = body(state.iter, state.loop_state)
state.iter = tf.add(state.iter, state.delta)
return state
return WhileLoop(LoopCond, LoopBody, state).loop_state
def TopK(x_in, k):
"""Equivalent to tf.math.top_k(x_in, k) but more efficient on tpu."""
assert k <= 2, 'This implementation is only efficient for small k.'
# TODO(yonghui): Try out an alternative idea where we first reshape x_in as a
# 2d tensor, then call tf.math.top_k, and then reshape back.
x_in_shape = x_in.shape
x_rank = x_in_shape.rank
assert x_rank and x_in_shape.as_list()[x_rank - 1] > 0
last_dim_size = x_in_shape.as_list()[x_rank - 1]
min_value = tf.math.reduce_min(x_in) - 1.0
out_indices = []
out_values = []
for unused_i in range(k):
index_i = tf.math.argmax(x_in, axis=-1, output_type=tf.int32)
mask_i = tf.one_hot(index_i, last_dim_size)
# TODO(yonghui): Would tf.gather be more efficient and numerically stable
# here?
value_i = tf.reduce_sum(mask_i * x_in, -1, keepdims=True)
x_in = (1.0 - mask_i) * x_in + mask_i * min_value
out_indices.append(tf.expand_dims(index_i, -1))
out_values.append(value_i)
if k == 1:
return out_values[0], out_indices[0]
else:
return tf.concat(out_values, x_rank - 1), tf.concat(out_indices, x_rank - 1)
def ReadVariable(var_op):
"""Returns the value of the given variable operation.
Args:
var_op: the `Operation` object for a VarHandleOp.
Raises:
TypeError: if var_op is not a VarHandleOp.
Returns:
A `Tensor` containing the value of the variable.
"""
if var_op.type != 'VarHandleOp':
raise TypeError('var_op should be a VarHandleOp, got %s' % str(var_op.type))
# Filter out the ReadVariableOps that have control dependencies to avoid
# side-effects when the user runs it.
filter_fn = lambda op: op.type == 'ReadVariableOp' and not op.control_inputs
var_readers = list(filter(filter_fn, var_op.outputs[0].consumers()))
assert var_readers
return var_readers[0].outputs[0]
_TPU_SUMMARY_TENSORS_KEY = ('__lingvo_tpu_summary_tensors')
_TPU_SUMMARY_CONTEXTS = ThreadLocalStack()
def _GetTpuSummaryTensor():
if _TPU_SUMMARY_CONTEXTS.stack:
return _TPU_SUMMARY_CONTEXTS.stack[-1]
return _CollectionGetter(_TPU_SUMMARY_TENSORS_KEY, lambda: [])()
@contextlib.contextmanager
def TpuSummaryTensorContext():
"""Creates a context where AddTpuSummaryTensor() will add tensors."""
_TPU_SUMMARY_CONTEXTS.stack.append([])
try:
yield
finally:
_TPU_SUMMARY_CONTEXTS.stack.pop()
def AddTpuSummaryTensor(name, value, weight=1.0):
"""Adds tensor to global collection of summaries, or a local context if any.
This needs to be used in situations where tf.summary() could be used but
currently tf.summary is not supported. Use py_utils.AddTpuSummaryTensor() in
low level code to add summary tensors to global collection of summaries.
Then recover all summary tensors from global collection by calling
py_utils.GetTpuSummaryTensors() from top level code (for example from
ComputeLoss method of BaseTask).
In addition to 'name' argument, current tensorflow name scope is also
captured and added to the metric name. This way for example summaries from
a repeated layer will appear as separate graphs in the tensorboard.
Weight argument is optional and defaults to 1.0. See BaseTask.ComputeLoss for
the exact definition of weight for eval metrics.
Args:
name: metric name
value: metric value tensor
weight: weight tensor for weighted metrics
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
x = NestedMap()
x.name = name
x.value = value, tf.convert_to_tensor(weight)
x.name_scope = tf.get_default_graph().get_name_scope()
tpu_summary_tensors.append(x)
def GetTpuSummaryTensors():
"""Returns summary tensors from global collection.
Returns:
A dict containing str keys and (metric, weight) pairs as values
"""
tpu_summary_tensors = _GetTpuSummaryTensor()
return {
'%s/%s' % (x.name, SanitizeScopeKey(x.name_scope)): x.value
for x in tpu_summary_tensors
}
def ClearTpuSummaryTensors():
tpu_summary_tensors = _GetTpuSummaryTensor()
del tpu_summary_tensors[:]
def ComputationShape(split_size, topology=None):
"""Decides the computation shape based on the split_size.
Args:
split_size: number of accelerators to use per split.
topology: a serialized string of `tensorflow.tpu.TopologyProto`, or a
`tf.tpu.experimental.Topology` object, that describes the TPU cluster
topology. If not set, it'll use a default setting based on split_size.
Returns:
A 4-element list that describes the computation shape.
"""
if topology:
if isinstance(topology, tf.tpu.experimental.Topology):
topology_info = topology
else:
topology_info = tf_topology.Topology(serialized=topology)
computation_shape = None
if topology and functools.reduce(lambda a, b: a * b,
topology_info.mesh_shape) == split_size:
computation_shape = topology_info.mesh_shape
elif split_size == 1:
computation_shape = [1, 1, 1, 1]
elif topology and topology_info.mesh_shape[
-1] == 1 and split_size in topology_info.mesh_shape:
# For Megacore, if we find exact match on mesh shape, map split_size to it
computation_shape = [1, 1, 1, 1]
computation_shape[topology_info.mesh_shape.tolist().index(
split_size)] = split_size
else:
if topology:
cores_per_chip = topology_info.mesh_shape[-1]
else:
cores_per_chip = 2
assert split_size % cores_per_chip == 0
split_chips = split_size // cores_per_chip
if split_chips == 1:
computation_shape = [1, 1, 1, cores_per_chip]
elif split_chips == 2:
computation_shape = [1, 2, 1, cores_per_chip]
elif split_chips == 4:
computation_shape = [2, 2, 1, cores_per_chip]
elif split_chips == 8:
computation_shape = [4, 2, 1, cores_per_chip]
elif split_chips == 12:
computation_shape = [1, 1, 12, cores_per_chip]
elif split_chips == 16:
computation_shape = [4, 4, 1, cores_per_chip]
elif split_chips == 24:
computation_shape = [1, 2, 12, cores_per_chip]
elif split_chips == 32:
if topology and topology_info.mesh_shape[1] == 32:
# Fwd within-replica all-reduces is performed along column;
# Bwd gradient cross-replica all-reduces is performed along row.
# This currently has better performance than the strided patten.
computation_shape = [1, 32, 1, cores_per_chip]
else:
computation_shape = [4, 8, 1, cores_per_chip]
elif split_chips == 64:
computation_shape = [8, 8, 1, cores_per_chip]
elif split_chips == 128:
computation_shape = [8, 16, 1, cores_per_chip]
elif split_chips == 256:
computation_shape = [16, 16, 1, cores_per_chip]
elif split_chips == 512:
computation_shape = [16, 32, 1, cores_per_chip]
elif split_chips == 1024:
computation_shape = [32, 32, 1, cores_per_chip]
elif split_chips == 2048:
computation_shape = [64, 32, 1, cores_per_chip]
elif split_chips == 4096:
computation_shape = [128, 32, 1, cores_per_chip]
else:
assert False, ('Model parallelism with %d devices is currently not'
' supported.' % split_size)
assert computation_shape is not None
return computation_shape
def GetExtraVars():
"""Returns the captured variables by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.variable_captures
return function.get_extra_vars()
def GetExtraInputs():
"""Returns the captured input tensors by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.external_captures
return function.get_extra_inputs()
def GetExtraArgs():
"""Returns the corresponding function arguments for the captured inputs."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.internal_captures
return function.get_extra_args()
def ShardedFilePatternToGlob(file_pattern):
"""Converts a file pattern path@shards to path-?????-of-shards."""
if ',' in file_pattern:
raise ValueError(
'ShardedFilePatternToGlob does not support multiple file patterns.')
if '@' not in file_pattern:
return file_pattern
path, shards = file_pattern.split('@')
if shards == '*':
return f'{path}-?????-of-*'
return f'{path}-?????-of-{int(shards):05}'
def ComputeNceAndAuc(probs, targets, mask):
"""Compute normalized cross entropy and AUC of the PR curve for a batch.
Args:
probs: a tensor of shape [batch, time].
targets: a tensor of shape [batch, time], where each element is either 0 or
1 indicating wrong or correct.
mask: a tensor of shape [batch, time], a mask for hyp sequence.
Returns:
nce: a tensor of shape [1], the normalized cross entropy value.
auc: a tensor of shape [1], the AUC value.
"""
def LogWithClip(tensor, clip_value_min=1e-8):
"""Clip all elements of a tensor to a minimum before taking log."""
return tf.math.log(tf.clip_by_value(tensor, clip_value_min, 1.0))
bce = -targets * LogWithClip(probs) - (1 - targets) * LogWithClip(1 - probs)
num_cor = tf.reduce_sum(targets * mask)
num_tokens = tf.reduce_sum(mask)
wcr = num_cor / num_tokens
entropy = -wcr * LogWithClip(wcr) - (1 - wcr) * LogWithClip(1 - wcr)
avg_conditional_entropy = tf.reduce_mean(tf.boolean_mask(bce, mask))
nce = (entropy - avg_conditional_entropy) / entropy
auc = tf.metrics.auc(targets, probs, mask, curve='PR')[1]
return nce, auc
def GatherTensorValuesBySeqIndices(tensor, class_indices, keepdims=False):
"""Gather values from a 3d tensor according to sequences of indices.
Args:
tensor: a 3d tensor of [dim0, dim1, num_class], e.g. output from softmax.
class_indices: a 2d tensor of [dim0, dim1], where the second dim is a
sequence of class indices between 0 to num_class - 1, inclusive.
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
A tensor ret of [dim0, dim1], where
ret[b, t] = tensor[b, t, indices[b, t]].
If keepdims is True, then ret has shape [dim0, dim1, 1].
"""
tensor = HasRank(tensor, 3)
class_indices = HasRank(class_indices, 2)
tensor = HasShape(tensor, GetShape(class_indices), 2)
dim0 = GetShape(class_indices)[0]
dim1 = GetShape(class_indices)[1]
dim0_indices = tf.tile(tf.expand_dims(tf.range(dim0), axis=-1), [1, dim1])
dim1_indices = tf.tile(tf.expand_dims(tf.range(dim1), axis=0), [dim0, 1])
gather_indices = tf.stack([
tf.cast(dim0_indices, dtype=class_indices.dtype),
tf.cast(dim1_indices, dtype=class_indices.dtype), class_indices
],
axis=-1)
ret = tf.gather_nd(tensor, gather_indices)
if keepdims:
ret = tf.expand_dims(ret, axis=-1)
return ret
def GetSoftmaxProbsBySeqIndices(logits, indices, keepdims=False):
"""Get softmax probabilities from index sequences given logits sequences.
Args:
logits: a tensor of [batch, time, num_class] or [time, batch, num_class].
indices: a tensor of [batch, time] or [time, batch].
keepdims: bool, expand the last dimension of the returned tensor if True.
Returns:
a tensor of [batch, time] or [time, batch] for the corresponding softmax
probabilities. If keepdims is True, returned tensor has a third dimension
of size 1.
"""
probs = tf.nn.softmax(logits)
return GatherTensorValuesBySeqIndices(probs, indices, keepdims)
def DivideNoNan(x, y):
"""Equivalent to tf.math.divide_no_nan but supports bfloat16."""
safe_y = tf.where(tf.equal(y, 0.), tf.ones_like(y), y)
return tf.where(tf.equal(y, 0.0), tf.zeros_like(x), x / safe_y)
def SequencePaddings(seqlen, maxlen=None):
mask = tf.sequence_mask(seqlen, maxlen, dtype=tf.float32)
return 1 - mask
def AppendDims(x, ndims):
return tf.reshape(x, GetShape(x) + [1] * ndims)
def MaybeSoftCapLogits(x, cap=0.0):
"""Caps logits x to be within a certain range.
Args:
x: A float tensor, the logit values to be capped.
cap: a float, the limit to cap x within. If cap <= 0.0, x is not capped.
Returns:
logits after capping.
"""
if cap <= 0.0:
return x
else:
return cap * tf.math.tanh(x / cap)
def GetTpuEmbeddingGraphCollection():
"""Return the graph collection that stores the TpuEmbeddingCollection."""
tpu_emb_graph_collection = tf.get_collection_ref('__tpu_embedding_collection')
assert len(tpu_emb_graph_collection) <= 1
return tpu_emb_graph_collection
class AuxLossContext:
"""Context that holds a list of aux-losses.
By default it is non-reentrant, but can be specified as reentrant explicitly
when creating an inner context.
"""
_global_stack = []
@classmethod
def Current(cls):
"""Returns current context or None."""
if cls._global_stack:
return cls._global_stack[-1]
else:
return None
def __init__(self, reentrant=False):
self.aux_loss_tensors = []
self._reentrant = reentrant
def AddLoss(self, loss):
self.aux_loss_tensors.append(loss)
@property
def aux_losses(self):
return self.aux_loss_tensors
def __enter__(self):
if not self._reentrant:
assert not self._global_stack, 'no re-entry'
self._global_stack.append(self)
return self
def __exit__(self, *args):
self._global_stack.pop()
def GetTrainableVariables(scope, bprop_variable_filter,
bprop_variable_exclusion, vmap):
"""Returns trainable vars.
Args:
scope: A Python str.
bprop_variable_filter: see BaseTask.Params().bprop_variable_filter.
bprop_variable_exclusion: see BaseTask.Params().bprop_variable_exclusion.
vmap: A NestedMap of var_path(str) -> tf Variable.
Returns:
A filtered NestedMap of var_path(str) -> trainable tf Variable.
"""
pos = re.compile(bprop_variable_filter) if bprop_variable_filter else None
neg = re.compile(
bprop_variable_exclusion) if bprop_variable_exclusion else None
def VariableFilter(v):
"""Returns True if variable v should be optimized by this learner."""
if not v.trainable:
return False
if pos and not pos.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_filter: %s', scope,
v.name)
return False
if neg and neg.search(v.name):
tf.logging.info('%s: disabled by bprop_variable_exclusion: %s', scope,
v.name)
return False
return True
return vmap.Filter(VariableFilter)
|
# dodo.py
import ast
import asyncio
import contextlib
import dataclasses
import datetime
import functools
import io
import itertools
import json
import os
import pathlib
import re
import shutil
import sys
import textwrap
import typing
import aiofiles
import flit
import git
import packaging.requirements
import pathspec
try:
import importlib.resources
except ModuleNotFoundError:
import importlib
import importlib_resources
importlib.resource = importlib_resources
try:
import importlib.metadata
except ModuleNotFoundError:
import importlib
import importlib_metadata
importlib.metadata = importlib_metadata
print(os.getcwd())
import doit
class Reporter(doit.reporter.ConsoleReporter):
def execute_task(self, task):
self.outstream.write("MyReporter --> %s\n" % task.title())
DOIT_CONFIG = dict(verbosity=2, reporter=Reporter)
Path = type(pathlib.Path())
post_pattern = re.compile("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}-(.*)")
def task_docs():
"""configure the documentation"""
docs = project / DOCS
backend = project.docs_backend()
# basically we wanna combine a bunch of shit
if backend == "mkdocs":
return dict(
file_dep=project.all_files(),
actions=[(doit.tools.create_folder, [docs]), project.to(Mkdocs).add],
targets=[project / MKDOCS],
)
return dict(
file_dep=project.all_files(),
actions=[(doit.tools.create_folder, [docs]), project.to(JupyterBook).add],
targets=[project / CONFIG, project / TOC],
)
def task_lint():
"""configure formatters and linters"""
return dict(
file_dep=project.all_files(),
actions=[project.to(Lint).add],
targets=[project / PRECOMMITCONFIG_YML],
)
def task_python():
"""configure the python project"""
targets = [project / PYPROJECT_TOML]
files = project.all_files()
backend = project.python_backend()
task_dep = []
if not any(x for x in files if x.suffix == ".py"):
notebooks = [x for x in files if x.suffix == ".ipynb"]
if notebooks:
task_dep += ["jupytext"]
if backend == "setuptools":
targets += [project / SETUP_CFG]
actions = [project.to(Setuptools).add]
elif backend == "flit":
actions = [project.to(Flit).add]
elif backend == "poetry":
requires = " ".join(project.get_requires())
actions = [project.to(Poetry).add, f"poetry add --lock {requires}"]
return dict(file_dep=files, actions=actions, targets=targets, task_dep=task_dep)
def task_build():
return dict(
file_dep=[project / PYPROJECT_TOML],
actions=["python -m pep517.build ."],
targets=[project.to_whl(), project.to_sdist()],
)
def task_setup_py():
actions = []
if not SETUP_PY.exists():
actions += [
lambda: SETUP_PY.write_text("""__import__("setuptools").setup()\n""")
and None
]
return dict(file_dep=[SETUP_CFG], actions=actions, targets=[SETUP_PY])
def task_requirements():
"""configure the requirements.txt for the project"""
return dict(actions=[project.to(Pip).add], targets=[project / REQUIREMENTS_TXT])
def task_conda():
"""configure a conda environment for the distribution"""
def shuffle_conda():
import doit
file = project / ENVIRONMENT_YAML
env = file.load()
c, p = [], []
for dep in env.get("dependencies", []):
if isinstance(dep, str):
c += [dep]
elif isinstance(dep, dict):
p = dep.pop("pip", [])
if c:
action = doit.tools.CmdAction(
f"""conda install --dry-run -cconda-forge {" ".join(c)}"""
)
if action.err:
for package in packages_from_conda_not_found(action.err.strip()):
p.append(c.pop(c.index(package)))
if p:
if "pip" not in c:
c += ["pip", dict(pip=p)]
file.write(dict(dependencies=c))
return dict(
actions=[project.to(Conda).add, shuffle_conda],
targets=[project / ENVIRONMENT_YAML],
)
def task_gitignore():
"""create a gitignore for the distribution"""
project = Gitignore()
return dict(file_dep=project.all_files(), actions=[], targets=[project / GITIGNORE])
def task_ci():
"""configure a ci workflow for test and release a project"""
return dict(actions=[project.to(Actions).add], targets=[project / BUILDTESTRELEASE])
def task_readthedocs():
"""configure for the distribution for readthedocs"""
return dict(actions=[project.to(Readthedocs).add], targets=[project / READTHEDOCS])
def task_jupyter_book():
"""build the documentation with jupyter book"""
docs = project / "docs"
return dict(
file_dep=[project / TOC, project / CONFIG],
actions=[
"jb build --path-output docs --toc docs/_toc.yml --config docs/_config.yml ."
],
targets=[BUILD / "html"],
task_dep=["docs"],
uptodate=[
doit.tools.config_changed(" ".join(sorted(map(str, project.all_files()))))
],
)
def task_uml():
"""generate a uml diagram of the project with pyreverse."""
return dict(
file_dep=project.all_files(),
actions=[f"pyreverse pyreverse -o png -k {project.get_name()}"],
targets=[project.path / "classes.png", project.path / "packages.png"],
)
def task_mkdocs():
"""build the documentation with mkdocs"""
return dict(file_dep=[MKDOCS], actions=["mkdocs build"], targets=[BUILD / "mkdocs"])
def task_blog():
"""build a blog site with nikola"""
return dict(file_dep=[CONF], actions=["nikola build"], targets=[BUILD / "nikola"])
def task_pdf():
"""build a pdf version of the documentation"""
return dict(actions=[])
def task_jupytext():
actions = []
if not installed("jupytext"):
actions += ["pip install jupytext"]
notebooks = [str(x) for x in project.all_files() if x.suffix == ".ipynb"]
return dict(
actions=actions
+ [f"""jupytext --set-formats ipynb,py:percent {" ".join(notebooks)}"""]
)
class options:
"""options for qpub
options are passed to doit using environment variables in nox."""
__annotations__ = {}
python: str = os.environ.get("QPUB_PYTHON", "infer")
conda: bool = os.environ.get("QPUB_CONDA", False)
tasks: str = os.environ.get("QPUB_TASKS", "").split()
generate_types: bool = os.environ.get("QPUB_GENERATE_TYPES", False)
docs: str = os.environ.get("QPUB_GENERATE_TYPES", "infer")
pdf: bool = os.environ.get("QPUB_DOCS_PDF", False)
watch: bool = os.environ.get("QPUB_DOCS_WATCH", False)
serve: bool = os.environ.get("QPUB_SERVE", False)
binder: bool = os.environ.get("BINDER_URL", False)
confirm: bool = os.environ.get("QPUB_CONFIRM", False)
posargs: bool = os.environ.get("QPUB_POSARGS", "").split()
qpub: str = os.environ.get("QPUB_ID", "qpub")
interactive: bool = os.environ.get("QPUB_INTERACTIVE", False)
monkeytype: bool = os.environ.get("QPUB_INTERACTIVE", False)
mamba: bool = os.environ.get("QPUB_MAMBA", True)
cache: str = Path(os.environ.get("QPUB_CACHE", Path(__file__).parent / "_data"))
dev: bool = os.environ.get("QPUB_DEV", True)
pip_only: bool = os.environ.get("QPUB_PIP", False)
install: bool = os.environ.get("QPUB_INSTALL", True)
install_backend: bool = os.environ.get(
"QPUB_INSTALL_BACKEND",
(
"mamba"
if shutil.which("mamba")
else "conda"
if shutil.which("conda")
else "pip"
),
)
@classmethod
def dump(cls):
return {
f"QPUB_{x.upper()}": " ".join(x)
if isinstance(x, list)
else str(getattr(cls, x))
for x in cls.__annotations__
}
# ███████╗██╗██╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██╗███████╗███╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗
# ██╔════╝██║██║ ██╔════╝ ██╔════╝██╔═══██╗████╗ ██║██║ ██║██╔════╝████╗ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝
# █████╗ ██║██║ █████╗ ██║ ██║ ██║██╔██╗ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗
# ██╔══╝ ██║██║ ██╔══╝ ██║ ██║ ██║██║╚██╗██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║
# ██║ ██║███████╗███████╗ ╚██████╗╚██████╔╝██║ ╚████║ ╚████╔╝ ███████╗██║ ╚████║ ██║ ██║╚██████╔╝██║ ╚████║███████║
# ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
class File(Path):
"""a supercharged file object that make it is easy to dump and load data.
the loaders and dumpers edit files in-place, these constraints may not apply to all systems.
"""
def write(self, object):
self.write_text(self.dump(object))
def update(self, object):
return self.write(merge(self.read(), object))
def load(self):
"""a permissive method to load data from files and edit documents in place."""
for cls in File.__subclasses__():
if hasattr(cls, "_suffixes"):
if self.suffix in cls._suffixes:
return cls.load(self)
else:
raise TypeError(f"Can't load type with suffix: {self.suffix}")
def dump(self, object):
"""a permissive method to dump data from files and edit documents in place."""
for cls in File.__subclasses__():
if hasattr(cls, "_suffixes"):
if self.suffix in cls._suffixes:
return cls.dump(self, object)
else:
raise TypeError(f"Can't dump type with suffix: {self.suffix}")
__add__, read = update, load
class Convention(File):
"""a convention indicates explicit or implicit filename and directory conventions.
the conventions were introduced to separate non-canonical content from canonical configuration files.
if content and configurations are mixed they doit will experience break with cyclic graphs.
"""
DOIT_DB_DAT = Convention(".doit.db.dat")
DOIT_DB_DIR = DOIT_DB_DAT.with_suffix(".dir")
DOIT_DB_BAK = DOIT_DB_DAT.with_suffix(".bak")
PRECOMMITCONFIG_YML = Convention(".pre-commit-config.yaml")
PYPROJECT_TOML = Convention("pyproject.toml")
REQUIREMENTS_TXT = Convention("requirements.txt")
SETUP_CFG = Convention("setup.cfg")
SETUP_PY = Convention("setup.py")
SRC = Convention("src")
GIT = Convention(".git")
GITIGNORE = Convention(".gitignore")
DOCS = Convention("docs")
BUILD = DOCS / "_build" # abides the sphinx gitignore convention.
TOC = DOCS / "_toc.yml"
CONFIG = DOCS / "_config.yml"
CONF = Convention("conf.py")
CONFTEST = Convention("conftest.py")
NOXFILE = Convention("noxfile.py")
DODO = Convention("dodo.py")
POETRY_LOCK = Convention("poetry.lock")
MKDOCS = Convention("mkdocs.yml") # https://www.mkdocs.org/
DIST = Convention("dist")
JUPYTEXT = Convention("jupytext.toml")
MANIFEST = Convention("MANIFEST.in")
ENVIRONMENT_YML = Convention("environment.yml")
ENVIRONMENT_YAML = Convention("environment.yaml")
GITHUB = Convention(".github")
WORKFLOWS = GITHUB / "workflows"
BUILDTESTRELEASE = WORKFLOWS / "build_test_release.yml"
READTHEDOCS = Convention(".readthedocs.yml")
CONVENTIONS = [x for x in locals().values() if isinstance(x, Convention)]
BUILDSYSTEM = "build-system"
# the cli program stops here. there rest work for the tasks
# in the sections below we define tasks to configure Project
@dataclasses.dataclass(order=True)
class Chapter:
dir: pathlib.Path = ""
index: None = None
repo: object = None
parent: object = None
docs: object = None
posts: list = dataclasses.field(default_factory=list)
pages: list = dataclasses.field(default_factory=list)
modules: list = dataclasses.field(default_factory=list)
tests: list = dataclasses.field(default_factory=list)
src: object = None
chapters: list = dataclasses.field(default_factory=list)
other: list = dataclasses.field(default_factory=list)
_chapters: list = dataclasses.field(default_factory=list)
conventions: list = dataclasses.field(default_factory=list, repr=False)
hidden: list = dataclasses.field(default_factory=list, repr=False)
exclude: object = None
_flit_module = None
def get_exclude_patterns(self):
return []
def __post_init__(self):
if not isinstance(self.dir, pathlib.Path):
self.dir = File(self.dir)
if self.repo is None:
if (self.dir / GIT).exists():
self.repo = git.Repo(self.dir / GIT)
if not self.exclude:
import pathspec
self.exclude = pathspec.PathSpec.from_lines(
pathspec.patterns.GitWildMatchPattern,
self.get_exclude_patterns() + [".git"],
)
if (
self.docs
or self.chapters
or self.conventions
or self.hidden
or self.modules
or self.pages
or self.other
):
return
contents = (
self.repo
and list(map(File, git.Git(self.dir).ls_files().splitlines()))
or None
)
for parent in contents or []:
if parent.parent not in contents:
contents += [parent.parent]
for file in self.dir.iterdir():
local = file.relative_to(self.dir)
if contents is not None:
if local not in contents:
continue
if local in {DOCS}:
self.docs = Docs(dir=file, parent=self)
elif local in {SRC}:
self.src = Project(dir=file, parent=self)
elif local in CONVENTIONS:
self.conventions += [file]
elif local.stem.startswith((".",)):
self.hidden += [file]
elif file.is_dir():
if self.exclude.match_file(str(local / ".tmp")):
...
else:
self.chapters += [file]
continue
elif local.stem.startswith(("_",)):
if local.stem.endswith("_"):
self.modules += [file]
else:
self.hidden += [file]
elif self.exclude.match_file(str(local)):
continue
elif file.suffix not in {".ipynb", ".md", ".rst", ".py"}:
self.other += [file]
elif file.stem.lower() in {"readme", "index"}:
self.index = file
elif post_pattern.match(file.stem):
self.posts += [file]
elif is_pythonic(file.stem):
if file.stem.startswith("test_"):
self.tests += [file]
else:
self.modules += [file]
else:
self.pages += [file]
for k in "chapters posts tests modules pages conventions".split():
setattr(self, k, sorted(getattr(self, k), reverse=k in {"posts"}))
self._chapters = list(Chapter(dir=x, parent=self) for x in self.chapters)
def root(self):
return self.parent.root() if self.parent else self
def all_files(self, conventions=False):
return list(self.files(True, True, True, True, conventions, True))
def files(
self,
content=False,
posts=False,
docs=False,
tests=False,
conventions=False,
other=False,
):
if self.index:
yield self.index
if posts:
yield from self.posts
if docs:
yield from self.pages
if self.docs:
yield from self.docs.files(
content=content,
posts=posts,
docs=docs,
tests=tests,
conventions=conventions,
)
if content:
yield from self.modules
if tests:
yield from sorted(
set(
itertools.chain(
self.tests,
self.docs.files(tests=True) if self.docs else [],
*(x.files(tests=True) for x in self._chapters if x),
)
)
)
for chapter in self._chapters:
yield from chapter.files(
content=content,
posts=posts,
docs=docs,
tests=tests,
conventions=conventions,
other=other,
)
if conventions:
yield from self.conventions
if other:
yield from self.other
@property
def path(self):
return File(self.dir)
def __truediv__(self, object):
return self.path / object
@property
def suffixes(self):
return sorted(set(x.suffix for x in self.files(True, True, True, True, True)))
@classmethod
def to(self, type):
return type(
**{k: v for k, v in vars(self).items() if k in type.__annotations__}
)
def cached(callable):
@functools.wraps(callable)
def main(self, *args, **kwargs):
data = self._cache = getattr(self, "_cache", {})
key = self.dir, callable.__name__
if (key in data) and (data[key] is not None):
return data[key]
data[key] = callable(self, *args, **kwargs)
return data[key]
return main
@contextlib.contextmanager
def cd(object):
next = os.getcwd()
os.chdir(object)
yield
os.chdir(next)
class Project(Chapter):
def reset(self):
self._flit_module = None
def add(self, *tasks):
with cd(self.dir):
main(list(tasks))
def get_name(self):
"""get the project name"""
# get the name of subdirectories if there are any.
if self.src:
return self.src.get_name()
if self.chapters:
if len(self.chapters) == 1:
return self.chapters[0].stem
# get the name of modules if there are any.
if self.modules:
names = sorted(
set(str(x.relative_to(x.parent).with_suffix("")) for x in self.modules)
)
if len(names) == 1:
return names[0]
else:
raise BaseException
# look for dated posted
if self.posts:
if len(self.posts) == 1:
return self.posts[0].stem.split("-", 3)[-1].replace(*"-_")
# look for pages.
if self.pages:
if len(self.pages) == 1:
return self.pages[0].stem
if self.tests:
if len(self.tests) == 1:
return self.tests[0].stem
raise BaseException
def get_description(self):
"""get from the docstring of the project. raise an error if it doesn't exist."""
# look in modules/chapters to see if we can flit this project.
if self.is_flit():
import flit
with contextlib.redirect_stderr(io.StringIO()):
try:
return flit.common.get_info_from_module(self._flit_module).pop(
"summary"
)
except:
...
if self.src:
return self.src.get_description()
return ""
def get_version(self):
"""determine a version for the project, if there is no version defer to calver.
it would be good to support semver, calver, and agever (for blogs).
"""
# use the flit convention to get the version.
# there are a bunch of version convention we can look for bumpversion, semver, rever
# if the name is a post name then infer the version from there
version = None
if self.is_flit():
with contextlib.redirect_stderr(io.StringIO()):
try:
version = flit.common.get_info_from_module(self._flit_module).pop(
"version"
)
except:
pass
if version is None:
if self.src:
version = self.src.get_version()
else:
version = datetime.date.today().strftime("%Y.%m.%d")
return normalize_version(version)
@cached
def get_exclude_patterns(self):
"""get the excluded patterns for the current layout"""
return list(sorted(set(dict(self._iter_exclude()).values())))
@cached
def get_exclude_paths(self):
"""get the excluded path by the canonical python.gitignore file."""
return list(sorted(dict(self._iter_exclude())))
def _iter_exclude(self, files=None):
for x in files or itertools.chain(self.dir.iterdir(), (self.dir / BUILD,)):
if x.is_dir():
x /= "tmp"
exclude = self.get_exclude_by(x.relative_to(self.root().dir))
if exclude:
yield x, exclude
def get_exclude_by(self, object):
"""return the path that ignores an object.
exclusion is based off the canonical python.gitignore specification."""
if not hasattr(self, "gitignore_patterns"):
self._init_exclude()
for k, v in self.gitignore_patterns.items():
if any(v.match((str(object),))):
return k
else:
return None
def _init_exclude(self):
"""initialize the path specifications to decide what to omit."""
self.gitignore_patterns = {}
import importlib.resources
for file in (
"Python.gitignore",
"Nikola.gitignore",
"JupyterNotebooks.gitignore",
):
file = where_template(file)
for pattern in (
file.read_text().splitlines()
+ ".local .vscode _build .gitignore".split()
):
if bool(pattern):
match = pathspec.patterns.GitWildMatchPattern(pattern)
if match.include:
self.gitignore_patterns[pattern] = match
@cached
def get_author(self):
if self.repo:
return self.repo.commit().author.name
return "qpub"
@cached
def get_email(self):
if self.repo:
return self.repo.commit().author.email
return ""
@cached
def get_url(self):
if self.repo:
if hasattr(self.repo.remotes, "origin"):
return self.repo.remotes.origin.url
return ""
get_exclude = get_exclude_patterns
@cached
def get_classifiers(self):
"""some classifiers can probably be inferred."""
return []
@cached
def get_license(self):
"""should be a trove classifier"""
# import trove_classifiers
# infer the trove framework
# make a gui for adding the right classifiers.
"I dont know what the right thing is to say here."
return ""
@cached
def get_keywords(self):
return []
def get_python_version(self):
import sys
return f"{sys.version_info.major}.{sys.version_info.minor}"
@cached
def get_test_files(self):
"""list the test like files. we'll access their dependencies separately ."""
return list(self.files(tests=True))
@cached
def get_docs_files(self):
"""list the test like files. we'll access their dependencies separately ."""
backend = self.docs_backend()
requires = []
if backend == "mkdocs":
requires += ["mkdocs"]
if backend == "sphinx":
requires += ["sphinx"]
if backend == "jb":
requires += ["jupyter-book"]
return requires + list(self.files(docs=True))
def get_untracked_files(self):
if self.repo:
self.repo.untracked_files
return []
@cached
def get_description_file(self):
"""get the description file for a project. it looks like readme or index something."""
if self.index and self.index.stem.lower() in {"readme", "index"}:
return self.index
@cached
def get_description_content_type(self):
"""get the description file for a project. it looks like readme or index something."""
file = self.get_description_file()
return {".md": "text/markdown", ".rst": "text/x-rst"}.get(
file and file.suffix.lower() or None, "text/plain"
)
@cached
def get_long_description(self, expand=False):
file = self.get_description_file()
if expand:
return file.read_text()
return f"file: {file}" if file else ""
def get_requires_from_files(self, files):
"""list imports discovered from the files."""
return list(set(import_to_pypi(merged_imports(files))))
def get_requires_from_requirements_txt(self):
"""get any hardcoded dependencies in requirements.txt."""
if (self / REQUIREMENTS_TXT).exists():
known = [
x
for x in REQUIREMENTS_TXT.read_text().splitlines()
if not x.lstrip().startswith("#") and x.strip()
]
return list(packaging.requirements.Requirement(x).name for x in known)
return []
@cached
def get_requires(self):
"""get the requirements for the project.
use heuristics that investigate a few places where requirements may be specified.
the expectation is that pip requirements might be pinned in a requirements file
or anaconda environment file.
"""
known = [self.get_name()]
return sorted(
[
package
for package in self.get_requires_from_files(self.files(content=True))
if package.lower() not in known and package[0].isalpha()
]
)
@cached
def get_test_requires(self):
"""test requires live in test and docs folders."""
requires = ["pytest", "pytest-sugar"]
if ".ipynb" in self.suffixes:
requires += ["nbval", "importnb"]
requires += self.get_requires_from_files(
self / x for x in self.get_test_files()
)
return [x for x in requires if x not in [self.get_name()]]
def get_docs_requires(self):
"""test requires live in test and docs folders."""
# infer the sphinx extensions needed because we miss this often.
if CONF in self.conventions:
"infer the dependencies from conf.py."
requires = []
backend = self.docs_backend()
if backend == "jb":
requires += ["jupyter-book"]
if backend == "mkdocs":
requires += ["mkdocs"]
if backend == "sphinx":
requires += ["sphinx"]
if self.docs:
requires += self.get_requires_from_files(self.docs.files())
return requires
def is_flit(self):
"""does the module abide flit conventions:
1. is the python script or folder with a name
2. can the description and version be inferred
"""
import flit
if self._flit_module is None:
try:
self._flit_module = flit.common.Module(self.get_name(), self.dir)
return True
except ValueError as e:
return False
return True
def is_poetry(self):
"""is the project otherwise a poetry project"""
return bool(not self.is_flit()) and bool(self.chapters)
def is_setuptools(self):
"""is the project otherwise a poetry project"""
return True
def python_backend(self):
if options.python == "infer":
return (
"flit"
if self.is_flit()
else "poetry"
if self.is_poetry()
else "setuptools"
)
return options.python
def docs_backend(self):
if options.docs == "infer":
return "jb"
return options.docs
def metadata(self, infer=False):
url = self.get_url()
if url.endswith(".git"):
url = url[:-4]
exclude = map(str, self.get_exclude())
exclude = [x[:-1] if x.endswith("/") else x for x in exclude]
data = dict(
name=self.get_name(),
version=self.get_version(),
url=url,
author=self.get_author(),
email=self.get_email(),
classifiers=self.get_classifiers(),
license=self.get_license(),
description=self.get_description(),
long_description=str(self.get_description_file()),
keywords=self.get_keywords(),
platforms=[],
python_version=self.get_python_version(),
exclude=exclude,
language="en",
files=sorted(map(str, self.all_files())),
dirs=list(set(str(x.parent) for x in self.all_files() if x)),
)
if infer:
data.update(
requires=self.get_requires(),
test_requires=self.get_test_requires(),
docs_requires=self.get_docs_requires(),
)
return data
def to_whl(self):
return self / DIST / f"{self.get_name()}-{self.get_version()}-py3-none-any.whl"
def to_sdist(self):
return self / DIST / f"{self.get_name()}-{self.get_version()}.tar.gz"
class Environment(Project):
...
class Conda(Environment):
def pip_to_conda(self):
return list(self.get_requires())
def dump(self):
return dict(dependencies=self.pip_to_conda(), channels="conda-forge".split())
def add(self):
(self / ENVIRONMENT_YAML).write(self.dump())
class Pip(Environment):
def add(self):
(self / REQUIREMENTS_TXT).write("\n".join(self.get_requires()))
class Python(Project):
def add(self):
backend = self.python_backend()
(
Flit if backend == "flit" else Poetry if backend == "poetry" else Setuptools
).add(self)
class PyProject(Python):
def dump(self):
return {}
def add(self):
data = self.dump()
(self.dir / PYPROJECT_TOML).update(
merge(
{BUILDSYSTEM: data.pop(BUILDSYSTEM)},
self.to(FlakeHell).dump(),
self.to(Pytest).dump(),
data,
)
)
class Flit(PyProject):
"""flit projects are discovered when a python script
or directory exists with docstring and version."""
def dump(self):
return templated_file("flit.json", self.metadata(True))
class Pytest(PyProject):
def dump(self):
return templated_file("pytest.json", self.metadata())
class FlakeHell(PyProject):
def dump(self):
return {}
class Poetry(PyProject):
def dump(self):
return templated_file("poetry.json", self.metadata())
class Setuptools(PyProject):
def dump_cfg(self):
cfg = "setuptools_cfg.json"
return templated_file(cfg, self.metadata(True))
def dump_toml(self):
toml = "setuptools_toml.json"
return templated_file(toml, {})
def add(self):
(self / SETUP_CFG).update(self.dump_cfg())
(self / PYPROJECT_TOML).update(self.dump_toml())
class Gitignore(Project):
def dump(self):
project = Project()
return project.get_exclude()
def add(self):
(self / GITIGNORE).update
self.dump()
class Lint(Project):
def add(self):
self.to(Precommit).add()
class Precommit(Lint):
def dump(self):
defaults = (File(__file__).parent / "templates" / "precommit.json").load()
precommit = self / PRECOMMITCONFIG_YML
data = precommit.load() or {}
if "repos" not in data:
data["repos"] = []
for suffix in ["null"] + self.suffixes:
if suffix in defaults:
for kind in defaults[suffix]:
for repo in data["repos"]:
if repo["repo"] == kind["repo"]:
repo["rev"] = repo.get("rev", None) or kind.get("rev", None)
ids = set(x["id"] for x in kind["hooks"])
repo["hooks"] = repo["hooks"] + [
x for x in kind["hooks"] if x["id"] not in ids
]
break
else:
data["repos"] += [dict(kind)]
return data
def add(self):
(self / PRECOMMITCONFIG_YML).write(self.dump())
class CI(Project):
def add(self):
self.to(Actions).add()
class Actions(CI):
def dump(self):
return {}
def add(self):
(self / BUILDTESTRELEASE).update(self.dump())
class Docs(Project):
def add(self):
backend = self.docs_backend()
return (
JupyterBook
if backend == "jb"
else Mkdocs
if backend == "mkdocs"
else Sphinx
).add(self)
class Sphinx(Docs):
def add(self):
pass
class Mkdocs(Docs):
def dump(self):
return templated_file("mkdocs.json", self.metadata())
def add(self):
(self / MKDOCS).write(self.dump())
class JupyterBook(Docs):
def dump_config(self, recurse=False):
return templated_file("_config.json", self.metadata())
def dump_toc(self, recurse=False):
index = self.index
if index is None:
for c in (self, *self._chapters):
for object in (c.pages, c.posts, c.tests, c.modules):
if object:
index = object[0]
break
if not index:
raise NoIndex()
data = dict(file=str(index.with_suffix("")), sections=[])
for x in itertools.chain(
self.pages,
(self.docs,) if self.docs else (),
self.posts,
self.tests,
self.modules,
self.chapters,
):
if x == index:
continue
if self.docs and (x == self.docs):
try:
data["sections"].append(JupyterBook.dump_toc(self.docs, recurse))
except NoIndex:
...
elif x in self.chapters:
try:
data["sections"].append(
JupyterBook.dump_toc(
self._chapters[self.chapters.index(x)], recurse
)
)
except NoIndex:
...
else:
data["sections"].append(dict(file=str(x.with_suffix(""))))
return data
def add(self):
(self / DOCS).mkdir(exist_ok=True)
(self / TOC).write(JupyterBook.dump_toc(self, True))
(self / CONFIG).write(JupyterBook.dump_config(self))
class Readthedocs(Docs):
def dump(self):
return templated_file("readthedocs.json", self.metadata())
def add(self):
(self / DOCS / READTHEDOCS).write(self.dump())
class Blog(Docs):
def add(self):
self.to(Nikola).add()
class Nikola(Blog):
"""we'll have to add metadata to make nikola work."""
def add(self):
(self / CONF).write_text("""""")
class Build(PyProject):
...
class CondaBuild(Build):
...
class Jupytext(Project):
...
class Lektor(Docs):
...
class Nbdev(Docs):
...
class Devto(CI):
"""https://github.com/marketplace/actions/devto-act"""
class Tweet(CI):
"""https://github.com/gr2m/twitter-together/"""
def rough_source(nb):
"""extract a rough version of the source in notebook to infer files from"""
if isinstance(nb, str):
nb = json.loads(nb)
return "\n".join(
textwrap.dedent("".join(x["source"]))
for x in nb.get("cells", [])
if x["cell_type"] == "code"
)
def _import_depfinder():
if "depfinder" not in sys.modules:
import requests_cache
import yaml
dir = Path(__file__).parent
requests_cache.install_cache(str(options.cache / "requests_cache"))
dir.mkdir(parents=True, exist_ok=True)
if not hasattr(yaml, "CSafeLoader"):
yaml.CSafeLoader = yaml.SafeLoader
import depfinder
requests_cache.uninstall_cache()
return __import__("depfinder")
async def infer(file):
"""infer imports from different kinds of files."""
depfinder = _import_depfinder()
async with aiofiles.open(file, "r") as f:
if file.suffix not in {".py", ".ipynb", ".md", ".rst"}:
return file, {}
source = await f.read()
if file.suffix == ".ipynb":
source = rough_source(source)
try:
return (file, depfinder.main.get_imported_libs(source).describe())
except SyntaxError:
return file, {}
async def infer_files(files):
return dict(await asyncio.gather(*(infer(file) for file in map(Path, set(files)))))
def gather_imports(files):
""""""
object = infer_files(files)
try:
return dict(asyncio.run(object))
except RuntimeError:
__import__("nest_asyncio").apply()
return dict(asyncio.run(object))
def merged_imports(files):
results = merge(*gather_imports(files).values())
return sorted(
set(list(results.get("required", [])) + list(results.get("questionable", [])))
)
def merge(*args):
if not args:
return {}
if len(args) == 1:
return args[0]
a, b, *args = args
if args:
b = functools.reduce(merge, (b, *args))
if hasattr(a, "items"):
for k, v in a.items():
if k in b:
a[k] = merge(v, b[k])
for k, v in b.items():
if k not in a:
try:
a[k] = v
except ValueError as exception:
if hasattr(a, "add_section"):
a.add_section(k)
a[k].update(v)
else:
raise exception
return a
if isinstance(a, tuple):
return a + tuple(x for x in b if x not in a)
if isinstance(a, list):
return a + list(x for x in b if x not in a)
if isinstance(a, set):
return list(sorted(set(a).union(b)))
return a or b
def import_to_pypi(list):
global IMPORT_TO_PIP
if not IMPORT_TO_PIP:
depfinder = _import_depfinder()
IMPORT_TO_PIP = {
x["import_name"]: x["pypi_name"] for x in depfinder.utils.mapping_list
}
return [IMPORT_TO_PIP.get(x, x) for x in list if x not in ["src"]]
def pypi_to_conda(list):
global PIP_TO_CONDA
if not PIP_TO_CONDA:
depfinder = _import_depfinder()
PIP_TO_CONDA = {
x["import_name"]: x["conda_name"] for x in depfinder.utils.mapping_list
}
return [PIP_TO_CONDA.get(x, x) for x in list]
# file loader loader/dumper functions
def ensure_trailing_eol(callable):
"""a decorator to comply with our linting opinion."""
import functools
@functools.wraps(callable)
def main(object):
str = callable(object)
return str.rstrip() + "\n"
return main
def load_txt(str):
return str.splitlines()
def dump_txt(object):
if isinstance(object, list):
object = "\n".join(object)
return object
def load_config(str):
object = configupdater.ConfigUpdater()
object.read_string(str)
return expand_cfg(object)
@ensure_trailing_eol
def dump_config__er(object):
next = io.StringIO()
object = compact_cfg(object)
if isinstance(object, dict):
import configparser
parser = configparser.ConfigParser(default_section=None)
parser.read_dict(object)
object = parser
object.write(next)
return next.getvalue()
def expand_cfg(object):
"""special conditions for config files so configparser and configuupdates work together."""
for main, section in object.items():
for key, value in section.items():
if isinstance(value, str) and value.startswith("\n"):
value = textwrap.dedent(value).splitlines()[1:]
object[main][key] = value
return object
def compact_cfg(object):
for main, section in object.items():
for key, value in section.items():
if isinstance(value, list):
import textwrap
value = textwrap.indent(
"\n".join([""] + list(map(textwrap.dedent, value))), " " * 4
)
object[main][key] = value
return object
def load_text(str):
return [x for x in str.splitlines()]
@ensure_trailing_eol
def dump_text(object):
return "\n".join(object)
def load_toml(str):
import tomlkit
return tomlkit.parse(str)
@ensure_trailing_eol
def dump_toml(object):
import tomlkit
return tomlkit.dumps(object)
def load_yaml(str):
import ruamel.yaml
object = ruamel.yaml.YAML()
return object.load(str)
@ensure_trailing_eol
def dump_yaml(object):
import ruamel.yaml
if isinstance(object, ruamel.YAML):
next = io.StringIO()
object.dump(next)
return next.getvalue()
return ruamel.yaml.safe_dump(object)
def to_dict(object):
if hasattr(object, "items"):
data = {}
for k, v in object.items():
if k is None:
continue
data[k] = to_dict(v)
else:
return data
return object
class INI(File):
"""dump and load ini files in place."""
_suffixes = ".ini", ".cfg"
def load(self):
try:
return load_config(self.read_text())
except FileNotFoundError:
return load_config("")
def dump(self, object):
return dump_config__er(object)
class TXT(File):
"""dump and load ini files in place."""
_suffixes = (".txt",)
def load(self):
try:
return load_txt(self.read_text())
except FileNotFoundError:
return load_txt("")
def dump(self, object):
return dump_txt(object)
class TOML(File):
"""dump and load toml files in place."""
_suffixes = (".toml",)
def load(self):
try:
return load_toml(self.read_text())
except FileNotFoundError:
return load_toml("")
def dump(self, object):
return dump_toml(object)
class JSON(File):
_suffixes = (".json",)
def load(self):
return json.loads(self.read_text())
def dump(self, boject):
return json.dumps(object)
class YML(File):
"""dump and load yml files in place."""
_suffixes = ".yaml", ".yml"
def load(self):
try:
return load_yaml(self.read_text())
except FileNotFoundError:
return load_yaml("{}")
def dump(self, object):
return dump_yaml(object)
IMPORT_TO_PIP = None
PIP_TO_CONDA = None
def is_pythonic(object):
object = pathlib.Path(object)
try:
ast.parse(object.stem)
except SyntaxError:
return False
return "-" not in object.stem
def normalize_version(object):
import packaging.requirements
with contextlib.redirect_stdout(io.StringIO()):
return str(packaging.version.Version(object))
def where_template(template):
try:
with importlib.resources.path("qpub.templates", template) as template:
template = File(template)
except:
template = File(__file__).parent / "templates" / template
return template
def templated_file(template, data):
import jsone
return jsone.render(where_template(template).load(), data)
def packages_from_conda_not_found(out):
packages = []
if out.startswith("PackagesNotFoundError"):
lines = out.splitlines()[1:]
for line in lines:
strip = line.strip()
if strip.startswith("-"):
packages += [strip.lstrip("-").lstrip()]
elif strip:
break
return packages
def installed(str):
try:
importlib.metadata.distribution(str)
return True
finally:
return False
class NoIndex(BaseException):
...
# # ███████╗██╗███╗ ██╗
# # ██╔════╝██║████╗ ██║
# # █████╗ ██║██╔██╗ ██║
# # ██╔══╝ ██║██║╚██╗██║
# # ██║ ██║██║ ╚████║
# # ╚═╝ ╚═╝╚═╝ ╚═══╝
def main(argv=None, raises=False):
global project
project = Project()
if argv is None:
argv = sys.argv[1:]
if isinstance(argv, str):
argv = argv.split()
main = doit.doit_cmd.DoitMain(doit.cmd_base.ModuleTaskLoader(globals()))
code = main.run(argv)
if raises:
sys.exit(code)
def run_in_doit():
return sys.argv[0].endswith("bin/doit")
if __name__ == "__main__":
main(None, True)
elif run_in_doit():
project = Project()
| # dodo.py
import ast
import asyncio
import contextlib
import dataclasses
import datetime
import functools
import io
import itertools
import json
import os
import pathlib
import re
import shutil
import sys
import textwrap
import typing
import aiofiles
import flit
import git
import packaging.requirements
import pathspec
try:
import importlib.resources
except ModuleNotFoundError:
import importlib
import importlib_resources
importlib.resource = importlib_resources
try:
import importlib.metadata
except ModuleNotFoundError:
import importlib
import importlib_metadata
importlib.metadata = importlib_metadata
print(os.getcwd())
import doit
class Reporter(doit.reporter.ConsoleReporter):
def execute_task(self, task):
self.outstream.write("MyReporter --> %s\n" % task.title())
DOIT_CONFIG = dict(verbosity=2, reporter=Reporter)
Path = type(pathlib.Path())
post_pattern = re.compile("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}-(.*)")
def task_docs():
"""configure the documentation"""
docs = project / DOCS
backend = project.docs_backend()
# basically we wanna combine a bunch of shit
if backend == "mkdocs":
return dict(
file_dep=project.all_files(),
actions=[(doit.tools.create_folder, [docs]), project.to(Mkdocs).add],
targets=[project / MKDOCS],
)
return dict(
file_dep=project.all_files(),
actions=[(doit.tools.create_folder, [docs]), project.to(JupyterBook).add],
targets=[project / CONFIG, project / TOC],
)
def task_lint():
"""configure formatters and linters"""
return dict(
file_dep=project.all_files(),
actions=[project.to(Lint).add],
targets=[project / PRECOMMITCONFIG_YML],
)
def task_python():
"""configure the python project"""
targets = [project / PYPROJECT_TOML]
files = project.all_files()
backend = project.python_backend()
task_dep = []
if not any(x for x in files if x.suffix == ".py"):
notebooks = [x for x in files if x.suffix == ".ipynb"]
if notebooks:
task_dep += ["jupytext"]
if backend == "setuptools":
targets += [project / SETUP_CFG]
actions = [project.to(Setuptools).add]
elif backend == "flit":
actions = [project.to(Flit).add]
elif backend == "poetry":
requires = " ".join(project.get_requires())
actions = [project.to(Poetry).add, f"poetry add --lock {requires}"]
return dict(file_dep=files, actions=actions, targets=targets, task_dep=task_dep)
def task_build():
return dict(
file_dep=[project / PYPROJECT_TOML],
actions=["python -m pep517.build ."],
targets=[project.to_whl(), project.to_sdist()],
)
def task_setup_py():
actions = []
if not SETUP_PY.exists():
actions += [
lambda: SETUP_PY.write_text("""__import__("setuptools").setup()\n""")
and None
]
return dict(file_dep=[SETUP_CFG], actions=actions, targets=[SETUP_PY])
def task_requirements():
"""configure the requirements.txt for the project"""
return dict(actions=[project.to(Pip).add], targets=[project / REQUIREMENTS_TXT])
def task_conda():
"""configure a conda environment for the distribution"""
def shuffle_conda():
import doit
file = project / ENVIRONMENT_YAML
env = file.load()
c, p = [], []
for dep in env.get("dependencies", []):
if isinstance(dep, str):
c += [dep]
elif isinstance(dep, dict):
p = dep.pop("pip", [])
if c:
action = doit.tools.CmdAction(
f"""conda install --dry-run -cconda-forge {" ".join(c)}"""
)
if action.err:
for package in packages_from_conda_not_found(action.err.strip()):
p.append(c.pop(c.index(package)))
if p:
if "pip" not in c:
c += ["pip", dict(pip=p)]
file.write(dict(dependencies=c))
return dict(
actions=[project.to(Conda).add, shuffle_conda],
targets=[project / ENVIRONMENT_YAML],
)
def task_gitignore():
"""create a gitignore for the distribution"""
project = Gitignore()
return dict(file_dep=project.all_files(), actions=[], targets=[project / GITIGNORE])
def task_ci():
"""configure a ci workflow for test and release a project"""
return dict(actions=[project.to(Actions).add], targets=[project / BUILDTESTRELEASE])
def task_readthedocs():
"""configure for the distribution for readthedocs"""
return dict(actions=[project.to(Readthedocs).add], targets=[project / READTHEDOCS])
def task_jupyter_book():
"""build the documentation with jupyter book"""
docs = project / "docs"
return dict(
file_dep=[project / TOC, project / CONFIG],
actions=[
"jb build --path-output docs --toc docs/_toc.yml --config docs/_config.yml ."
],
targets=[BUILD / "html"],
task_dep=["docs"],
uptodate=[
doit.tools.config_changed(" ".join(sorted(map(str, project.all_files()))))
],
)
def task_uml():
"""generate a uml diagram of the project with pyreverse."""
return dict(
file_dep=project.all_files(),
actions=[f"pyreverse pyreverse -o png -k {project.get_name()}"],
targets=[project.path / "classes.png", project.path / "packages.png"],
)
def task_mkdocs():
"""build the documentation with mkdocs"""
return dict(file_dep=[MKDOCS], actions=["mkdocs build"], targets=[BUILD / "mkdocs"])
def task_blog():
"""build a blog site with nikola"""
return dict(file_dep=[CONF], actions=["nikola build"], targets=[BUILD / "nikola"])
def task_pdf():
"""build a pdf version of the documentation"""
return dict(actions=[])
def task_jupytext():
actions = []
if not installed("jupytext"):
actions += ["pip install jupytext"]
notebooks = [str(x) for x in project.all_files() if x.suffix == ".ipynb"]
return dict(
actions=actions
+ [f"""jupytext --set-formats ipynb,py:percent {" ".join(notebooks)}"""]
)
class options:
"""options for qpub
options are passed to doit using environment variables in nox."""
__annotations__ = {}
python: str = os.environ.get("QPUB_PYTHON", "infer")
conda: bool = os.environ.get("QPUB_CONDA", False)
tasks: str = os.environ.get("QPUB_TASKS", "").split()
generate_types: bool = os.environ.get("QPUB_GENERATE_TYPES", False)
docs: str = os.environ.get("QPUB_GENERATE_TYPES", "infer")
pdf: bool = os.environ.get("QPUB_DOCS_PDF", False)
watch: bool = os.environ.get("QPUB_DOCS_WATCH", False)
serve: bool = os.environ.get("QPUB_SERVE", False)
binder: bool = os.environ.get("BINDER_URL", False)
confirm: bool = os.environ.get("QPUB_CONFIRM", False)
posargs: bool = os.environ.get("QPUB_POSARGS", "").split()
qpub: str = os.environ.get("QPUB_ID", "qpub")
interactive: bool = os.environ.get("QPUB_INTERACTIVE", False)
monkeytype: bool = os.environ.get("QPUB_INTERACTIVE", False)
mamba: bool = os.environ.get("QPUB_MAMBA", True)
cache: str = Path(os.environ.get("QPUB_CACHE", Path(__file__).parent / "_data"))
dev: bool = os.environ.get("QPUB_DEV", True)
pip_only: bool = os.environ.get("QPUB_PIP", False)
install: bool = os.environ.get("QPUB_INSTALL", True)
install_backend: bool = os.environ.get(
"QPUB_INSTALL_BACKEND",
(
"mamba"
if shutil.which("mamba")
else "conda"
if shutil.which("conda")
else "pip"
),
)
@classmethod
def dump(cls):
return {
f"QPUB_{x.upper()}": " ".join(x)
if isinstance(x, list)
else str(getattr(cls, x))
for x in cls.__annotations__
}
# ███████╗██╗██╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██╗███████╗███╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗
# ██╔════╝██║██║ ██╔════╝ ██╔════╝██╔═══██╗████╗ ██║██║ ██║██╔════╝████╗ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝
# █████╗ ██║██║ █████╗ ██║ ██║ ██║██╔██╗ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗
# ██╔══╝ ██║██║ ██╔══╝ ██║ ██║ ██║██║╚██╗██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║
# ██║ ██║███████╗███████╗ ╚██████╗╚██████╔╝██║ ╚████║ ╚████╔╝ ███████╗██║ ╚████║ ██║ ██║╚██████╔╝██║ ╚████║███████║
# ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
class File(Path):
"""a supercharged file object that make it is easy to dump and load data.
the loaders and dumpers edit files in-place, these constraints may not apply to all systems.
"""
def write(self, object):
self.write_text(self.dump(object))
def update(self, object):
return self.write(merge(self.read(), object))
def load(self):
"""a permissive method to load data from files and edit documents in place."""
for cls in File.__subclasses__():
if hasattr(cls, "_suffixes"):
if self.suffix in cls._suffixes:
return cls.load(self)
else:
raise TypeError(f"Can't load type with suffix: {self.suffix}")
def dump(self, object):
"""a permissive method to dump data from files and edit documents in place."""
for cls in File.__subclasses__():
if hasattr(cls, "_suffixes"):
if self.suffix in cls._suffixes:
return cls.dump(self, object)
else:
raise TypeError(f"Can't dump type with suffix: {self.suffix}")
__add__, read = update, load
class Convention(File):
"""a convention indicates explicit or implicit filename and directory conventions.
the conventions were introduced to separate non-canonical content from canonical configuration files.
if content and configurations are mixed they doit will experience break with cyclic graphs.
"""
DOIT_DB_DAT = Convention(".doit.db.dat")
DOIT_DB_DIR = DOIT_DB_DAT.with_suffix(".dir")
DOIT_DB_BAK = DOIT_DB_DAT.with_suffix(".bak")
PRECOMMITCONFIG_YML = Convention(".pre-commit-config.yaml")
PYPROJECT_TOML = Convention("pyproject.toml")
REQUIREMENTS_TXT = Convention("requirements.txt")
SETUP_CFG = Convention("setup.cfg")
SETUP_PY = Convention("setup.py")
SRC = Convention("src")
GIT = Convention(".git")
GITIGNORE = Convention(".gitignore")
DOCS = Convention("docs")
BUILD = DOCS / "_build" # abides the sphinx gitignore convention.
TOC = DOCS / "_toc.yml"
CONFIG = DOCS / "_config.yml"
CONF = Convention("conf.py")
CONFTEST = Convention("conftest.py")
NOXFILE = Convention("noxfile.py")
DODO = Convention("dodo.py")
POETRY_LOCK = Convention("poetry.lock")
MKDOCS = Convention("mkdocs.yml") # https://www.mkdocs.org/
DIST = Convention("dist")
JUPYTEXT = Convention("jupytext.toml")
MANIFEST = Convention("MANIFEST.in")
ENVIRONMENT_YML = Convention("environment.yml")
ENVIRONMENT_YAML = Convention("environment.yaml")
GITHUB = Convention(".github")
WORKFLOWS = GITHUB / "workflows"
BUILDTESTRELEASE = WORKFLOWS / "build_test_release.yml"
READTHEDOCS = Convention(".readthedocs.yml")
CONVENTIONS = [x for x in locals().values() if isinstance(x, Convention)]
BUILDSYSTEM = "build-system"
# the cli program stops here. there rest work for the tasks
# in the sections below we define tasks to configure Project
@dataclasses.dataclass(order=True)
class Chapter:
dir: pathlib.Path = ""
index: None = None
repo: object = None
parent: object = None
docs: object = None
posts: list = dataclasses.field(default_factory=list)
pages: list = dataclasses.field(default_factory=list)
modules: list = dataclasses.field(default_factory=list)
tests: list = dataclasses.field(default_factory=list)
src: object = None
chapters: list = dataclasses.field(default_factory=list)
other: list = dataclasses.field(default_factory=list)
_chapters: list = dataclasses.field(default_factory=list)
conventions: list = dataclasses.field(default_factory=list, repr=False)
hidden: list = dataclasses.field(default_factory=list, repr=False)
exclude: object = None
_flit_module = None
def get_exclude_patterns(self):
return []
def __post_init__(self):
if not isinstance(self.dir, pathlib.Path):
self.dir = File(self.dir)
if self.repo is None:
if (self.dir / GIT).exists():
self.repo = git.Repo(self.dir / GIT)
if not self.exclude:
import pathspec
self.exclude = pathspec.PathSpec.from_lines(
pathspec.patterns.GitWildMatchPattern,
self.get_exclude_patterns() + [".git"],
)
if (
self.docs
or self.chapters
or self.conventions
or self.hidden
or self.modules
or self.pages
or self.other
):
return
contents = (
self.repo
and list(map(File, git.Git(self.dir).ls_files().splitlines()))
or None
)
for parent in contents or []:
if parent.parent not in contents:
contents += [parent.parent]
for file in self.dir.iterdir():
local = file.relative_to(self.dir)
if contents is not None:
if local not in contents:
continue
if local in {DOCS}:
self.docs = Docs(dir=file, parent=self)
elif local in {SRC}:
self.src = Project(dir=file, parent=self)
elif local in CONVENTIONS:
self.conventions += [file]
elif local.stem.startswith((".",)):
self.hidden += [file]
elif file.is_dir():
if self.exclude.match_file(str(local / ".tmp")):
...
else:
self.chapters += [file]
continue
elif local.stem.startswith(("_",)):
if local.stem.endswith("_"):
self.modules += [file]
else:
self.hidden += [file]
elif self.exclude.match_file(str(local)):
continue
elif file.suffix not in {".ipynb", ".md", ".rst", ".py"}:
self.other += [file]
elif file.stem.lower() in {"readme", "index"}:
self.index = file
elif post_pattern.match(file.stem):
self.posts += [file]
elif is_pythonic(file.stem):
if file.stem.startswith("test_"):
self.tests += [file]
else:
self.modules += [file]
else:
self.pages += [file]
for k in "chapters posts tests modules pages conventions".split():
setattr(self, k, sorted(getattr(self, k), reverse=k in {"posts"}))
self._chapters = list(Chapter(dir=x, parent=self) for x in self.chapters)
def root(self):
return self.parent.root() if self.parent else self
def all_files(self, conventions=False):
return list(self.files(True, True, True, True, conventions, True))
def files(
self,
content=False,
posts=False,
docs=False,
tests=False,
conventions=False,
other=False,
):
if self.index:
yield self.index
if posts:
yield from self.posts
if docs:
yield from self.pages
if self.docs:
yield from self.docs.files(
content=content,
posts=posts,
docs=docs,
tests=tests,
conventions=conventions,
)
if content:
yield from self.modules
if tests:
yield from sorted(
set(
itertools.chain(
self.tests,
self.docs.files(tests=True) if self.docs else [],
*(x.files(tests=True) for x in self._chapters if x),
)
)
)
for chapter in self._chapters:
yield from chapter.files(
content=content,
posts=posts,
docs=docs,
tests=tests,
conventions=conventions,
other=other,
)
if conventions:
yield from self.conventions
if other:
yield from self.other
@property
def path(self):
return File(self.dir)
def __truediv__(self, object):
return self.path / object
@property
def suffixes(self):
return sorted(set(x.suffix for x in self.files(True, True, True, True, True)))
@classmethod
def to(self, type):
return type(
**{k: v for k, v in vars(self).items() if k in type.__annotations__}
)
def cached(callable):
@functools.wraps(callable)
def main(self, *args, **kwargs):
data = self._cache = getattr(self, "_cache", {})
key = self.dir, callable.__name__
if (key in data) and (data[key] is not None):
return data[key]
data[key] = callable(self, *args, **kwargs)
return data[key]
return main
@contextlib.contextmanager
def cd(object):
next = os.getcwd()
os.chdir(object)
yield
os.chdir(next)
class Project(Chapter):
def reset(self):
self._flit_module = None
def add(self, *tasks):
with cd(self.dir):
main(list(tasks))
def get_name(self):
"""get the project name"""
# get the name of subdirectories if there are any.
if self.src:
return self.src.get_name()
if self.chapters:
if len(self.chapters) == 1:
return self.chapters[0].stem
# get the name of modules if there are any.
if self.modules:
names = sorted(
set(str(x.relative_to(x.parent).with_suffix("")) for x in self.modules)
)
if len(names) == 1:
return names[0]
else:
raise BaseException
# look for dated posted
if self.posts:
if len(self.posts) == 1:
return self.posts[0].stem.split("-", 3)[-1].replace(*"-_")
# look for pages.
if self.pages:
if len(self.pages) == 1:
return self.pages[0].stem
if self.tests:
if len(self.tests) == 1:
return self.tests[0].stem
raise BaseException
def get_description(self):
"""get from the docstring of the project. raise an error if it doesn't exist."""
# look in modules/chapters to see if we can flit this project.
if self.is_flit():
import flit
with contextlib.redirect_stderr(io.StringIO()):
try:
return flit.common.get_info_from_module(self._flit_module).pop(
"summary"
)
except:
...
if self.src:
return self.src.get_description()
return ""
def get_version(self):
"""determine a version for the project, if there is no version defer to calver.
it would be good to support semver, calver, and agever (for blogs).
"""
# use the flit convention to get the version.
# there are a bunch of version convention we can look for bumpversion, semver, rever
# if the name is a post name then infer the version from there
version = None
if self.is_flit():
with contextlib.redirect_stderr(io.StringIO()):
try:
version = flit.common.get_info_from_module(self._flit_module).pop(
"version"
)
except:
pass
if version is None:
if self.src:
version = self.src.get_version()
else:
version = datetime.date.today().strftime("%Y.%m.%d")
return normalize_version(version)
@cached
def get_exclude_patterns(self):
"""get the excluded patterns for the current layout"""
return list(sorted(set(dict(self._iter_exclude()).values())))
@cached
def get_exclude_paths(self):
"""get the excluded path by the canonical python.gitignore file."""
return list(sorted(dict(self._iter_exclude())))
def _iter_exclude(self, files=None):
for x in files or itertools.chain(self.dir.iterdir(), (self.dir / BUILD,)):
if x.is_dir():
x /= "tmp"
exclude = self.get_exclude_by(x.relative_to(self.root().dir))
if exclude:
yield x, exclude
def get_exclude_by(self, object):
"""return the path that ignores an object.
exclusion is based off the canonical python.gitignore specification."""
if not hasattr(self, "gitignore_patterns"):
self._init_exclude()
for k, v in self.gitignore_patterns.items():
if any(v.match((str(object),))):
return k
else:
return None
def _init_exclude(self):
"""initialize the path specifications to decide what to omit."""
self.gitignore_patterns = {}
import importlib.resources
for file in (
"Python.gitignore",
"Nikola.gitignore",
"JupyterNotebooks.gitignore",
):
file = where_template(file)
for pattern in (
file.read_text().splitlines()
+ ".local .vscode _build .gitignore".split()
):
if bool(pattern):
match = pathspec.patterns.GitWildMatchPattern(pattern)
if match.include:
self.gitignore_patterns[pattern] = match
@cached
def get_author(self):
if self.repo:
return self.repo.commit().author.name
return "qpub"
@cached
def get_email(self):
if self.repo:
return self.repo.commit().author.email
return ""
@cached
def get_url(self):
if self.repo:
if hasattr(self.repo.remotes, "origin"):
return self.repo.remotes.origin.url
return ""
get_exclude = get_exclude_patterns
@cached
def get_classifiers(self):
"""some classifiers can probably be inferred."""
return []
@cached
def get_license(self):
"""should be a trove classifier"""
# import trove_classifiers
# infer the trove framework
# make a gui for adding the right classifiers.
"I dont know what the right thing is to say here."
return ""
@cached
def get_keywords(self):
return []
def get_python_version(self):
import sys
return f"{sys.version_info.major}.{sys.version_info.minor}"
@cached
def get_test_files(self):
"""list the test like files. we'll access their dependencies separately ."""
return list(self.files(tests=True))
@cached
def get_docs_files(self):
"""list the test like files. we'll access their dependencies separately ."""
backend = self.docs_backend()
requires = []
if backend == "mkdocs":
requires += ["mkdocs"]
if backend == "sphinx":
requires += ["sphinx"]
if backend == "jb":
requires += ["jupyter-book"]
return requires + list(self.files(docs=True))
def get_untracked_files(self):
if self.repo:
self.repo.untracked_files
return []
@cached
def get_description_file(self):
"""get the description file for a project. it looks like readme or index something."""
if self.index and self.index.stem.lower() in {"readme", "index"}:
return self.index
@cached
def get_description_content_type(self):
"""get the description file for a project. it looks like readme or index something."""
file = self.get_description_file()
return {".md": "text/markdown", ".rst": "text/x-rst"}.get(
file and file.suffix.lower() or None, "text/plain"
)
@cached
def get_long_description(self, expand=False):
file = self.get_description_file()
if expand:
return file.read_text()
return f"file: {file}" if file else ""
def get_requires_from_files(self, files):
"""list imports discovered from the files."""
return list(set(import_to_pypi(merged_imports(files))))
def get_requires_from_requirements_txt(self):
"""get any hardcoded dependencies in requirements.txt."""
if (self / REQUIREMENTS_TXT).exists():
known = [
x
for x in REQUIREMENTS_TXT.read_text().splitlines()
if not x.lstrip().startswith("#") and x.strip()
]
return list(packaging.requirements.Requirement(x).name for x in known)
return []
@cached
def get_requires(self):
"""get the requirements for the project.
use heuristics that investigate a few places where requirements may be specified.
the expectation is that pip requirements might be pinned in a requirements file
or anaconda environment file.
"""
known = [self.get_name()]
return sorted(
[
package
for package in self.get_requires_from_files(self.files(content=True))
if package.lower() not in known and package[0].isalpha()
]
)
@cached
def get_test_requires(self):
"""test requires live in test and docs folders."""
requires = ["pytest", "pytest-sugar"]
if ".ipynb" in self.suffixes:
requires += ["nbval", "importnb"]
requires += self.get_requires_from_files(
self / x for x in self.get_test_files()
)
return [x for x in requires if x not in [self.get_name()]]
def get_docs_requires(self):
"""test requires live in test and docs folders."""
# infer the sphinx extensions needed because we miss this often.
if CONF in self.conventions:
"infer the dependencies from conf.py."
requires = []
backend = self.docs_backend()
if backend == "jb":
requires += ["jupyter-book"]
if backend == "mkdocs":
requires += ["mkdocs"]
if backend == "sphinx":
requires += ["sphinx"]
if self.docs:
requires += self.get_requires_from_files(self.docs.files())
return requires
def is_flit(self):
"""does the module abide flit conventions:
1. is the python script or folder with a name
2. can the description and version be inferred
"""
import flit
if self._flit_module is None:
try:
self._flit_module = flit.common.Module(self.get_name(), self.dir)
return True
except ValueError as e:
return False
return True
def is_poetry(self):
"""is the project otherwise a poetry project"""
return bool(not self.is_flit()) and bool(self.chapters)
def is_setuptools(self):
"""is the project otherwise a poetry project"""
return True
def python_backend(self):
if options.python == "infer":
return (
"flit"
if self.is_flit()
else "poetry"
if self.is_poetry()
else "setuptools"
)
return options.python
def docs_backend(self):
if options.docs == "infer":
return "jb"
return options.docs
def metadata(self, infer=False):
url = self.get_url()
if url.endswith(".git"):
url = url[:-4]
exclude = map(str, self.get_exclude())
exclude = [x[:-1] if x.endswith("/") else x for x in exclude]
data = dict(
name=self.get_name(),
version=self.get_version(),
url=url,
author=self.get_author(),
email=self.get_email(),
classifiers=self.get_classifiers(),
license=self.get_license(),
description=self.get_description(),
long_description=str(self.get_description_file()),
keywords=self.get_keywords(),
platforms=[],
python_version=self.get_python_version(),
exclude=exclude,
language="en",
files=sorted(map(str, self.all_files())),
dirs=list(set(str(x.parent) for x in self.all_files() if x)),
)
if infer:
data.update(
requires=self.get_requires(),
test_requires=self.get_test_requires(),
docs_requires=self.get_docs_requires(),
)
return data
def to_whl(self):
return self / DIST / f"{self.get_name()}-{self.get_version()}-py3-none-any.whl"
def to_sdist(self):
return self / DIST / f"{self.get_name()}-{self.get_version()}.tar.gz"
class Environment(Project):
...
class Conda(Environment):
def pip_to_conda(self):
return list(self.get_requires())
def dump(self):
return dict(dependencies=self.pip_to_conda(), channels="conda-forge".split())
def add(self):
(self / ENVIRONMENT_YAML).write(self.dump())
class Pip(Environment):
def add(self):
(self / REQUIREMENTS_TXT).write("\n".join(self.get_requires()))
class Python(Project):
def add(self):
backend = self.python_backend()
(
Flit if backend == "flit" else Poetry if backend == "poetry" else Setuptools
).add(self)
class PyProject(Python):
def dump(self):
return {}
def add(self):
data = self.dump()
(self.dir / PYPROJECT_TOML).update(
merge(
{BUILDSYSTEM: data.pop(BUILDSYSTEM)},
self.to(FlakeHell).dump(),
self.to(Pytest).dump(),
data,
)
)
class Flit(PyProject):
"""flit projects are discovered when a python script
or directory exists with docstring and version."""
def dump(self):
return templated_file("flit.json", self.metadata(True))
class Pytest(PyProject):
def dump(self):
return templated_file("pytest.json", self.metadata())
class FlakeHell(PyProject):
def dump(self):
return {}
class Poetry(PyProject):
def dump(self):
return templated_file("poetry.json", self.metadata())
class Setuptools(PyProject):
def dump_cfg(self):
cfg = "setuptools_cfg.json"
return templated_file(cfg, self.metadata(True))
def dump_toml(self):
toml = "setuptools_toml.json"
return templated_file(toml, {})
def add(self):
(self / SETUP_CFG).update(self.dump_cfg())
(self / PYPROJECT_TOML).update(self.dump_toml())
class Gitignore(Project):
def dump(self):
project = Project()
return project.get_exclude()
def add(self):
(self / GITIGNORE).update
self.dump()
class Lint(Project):
def add(self):
self.to(Precommit).add()
class Precommit(Lint):
def dump(self):
defaults = (File(__file__).parent / "templates" / "precommit.json").load()
precommit = self / PRECOMMITCONFIG_YML
data = precommit.load() or {}
if "repos" not in data:
data["repos"] = []
for suffix in ["null"] + self.suffixes:
if suffix in defaults:
for kind in defaults[suffix]:
for repo in data["repos"]:
if repo["repo"] == kind["repo"]:
repo["rev"] = repo.get("rev", None) or kind.get("rev", None)
ids = set(x["id"] for x in kind["hooks"])
repo["hooks"] = repo["hooks"] + [
x for x in kind["hooks"] if x["id"] not in ids
]
break
else:
data["repos"] += [dict(kind)]
return data
def add(self):
(self / PRECOMMITCONFIG_YML).write(self.dump())
class CI(Project):
def add(self):
self.to(Actions).add()
class Actions(CI):
def dump(self):
return {}
def add(self):
(self / BUILDTESTRELEASE).update(self.dump())
class Docs(Project):
def add(self):
backend = self.docs_backend()
return (
JupyterBook
if backend == "jb"
else Mkdocs
if backend == "mkdocs"
else Sphinx
).add(self)
class Sphinx(Docs):
def add(self):
pass
class Mkdocs(Docs):
def dump(self):
return templated_file("mkdocs.json", self.metadata())
def add(self):
(self / MKDOCS).write(self.dump())
class JupyterBook(Docs):
def dump_config(self, recurse=False):
return templated_file("_config.json", self.metadata())
def dump_toc(self, recurse=False):
index = self.index
if index is None:
for c in (self, *self._chapters):
for object in (c.pages, c.posts, c.tests, c.modules):
if object:
index = object[0]
break
if not index:
raise NoIndex()
data = dict(file=str(index.with_suffix("")), sections=[])
for x in itertools.chain(
self.pages,
(self.docs,) if self.docs else (),
self.posts,
self.tests,
self.modules,
self.chapters,
):
if x == index:
continue
if self.docs and (x == self.docs):
try:
data["sections"].append(JupyterBook.dump_toc(self.docs, recurse))
except NoIndex:
...
elif x in self.chapters:
try:
data["sections"].append(
JupyterBook.dump_toc(
self._chapters[self.chapters.index(x)], recurse
)
)
except NoIndex:
...
else:
data["sections"].append(dict(file=str(x.with_suffix(""))))
return data
def add(self):
(self / DOCS).mkdir(exist_ok=True)
(self / TOC).write(JupyterBook.dump_toc(self, True))
(self / CONFIG).write(JupyterBook.dump_config(self))
class Readthedocs(Docs):
def dump(self):
return templated_file("readthedocs.json", self.metadata())
def add(self):
(self / DOCS / READTHEDOCS).write(self.dump())
class Blog(Docs):
def add(self):
self.to(Nikola).add()
class Nikola(Blog):
"""we'll have to add metadata to make nikola work."""
def add(self):
(self / CONF).write_text("""""")
class Build(PyProject):
...
class CondaBuild(Build):
...
class Jupytext(Project):
...
class Lektor(Docs):
...
class Nbdev(Docs):
...
class Devto(CI):
"""https://github.com/marketplace/actions/devto-act"""
class Tweet(CI):
"""https://github.com/gr2m/twitter-together/"""
def rough_source(nb):
"""extract a rough version of the source in notebook to infer files from"""
if isinstance(nb, str):
nb = json.loads(nb)
return "\n".join(
textwrap.dedent("".join(x["source"]))
for x in nb.get("cells", [])
if x["cell_type"] == "code"
)
def _import_depfinder():
if "depfinder" not in sys.modules:
import requests_cache
import yaml
dir = Path(__file__).parent
requests_cache.install_cache(str(options.cache / "requests_cache"))
dir.mkdir(parents=True, exist_ok=True)
if not hasattr(yaml, "CSafeLoader"):
yaml.CSafeLoader = yaml.SafeLoader
import depfinder
requests_cache.uninstall_cache()
return __import__("depfinder")
async def infer(file):
"""infer imports from different kinds of files."""
depfinder = _import_depfinder()
async with aiofiles.open(file, "r") as f:
if file.suffix not in {".py", ".ipynb", ".md", ".rst"}:
return file, {}
source = await f.read()
if file.suffix == ".ipynb":
source = rough_source(source)
try:
return (file, depfinder.main.get_imported_libs(source).describe())
except SyntaxError:
return file, {}
async def infer_files(files):
return dict(await asyncio.gather(*(infer(file) for file in map(Path, set(files)))))
def gather_imports(files):
""""""
object = infer_files(files)
try:
return dict(asyncio.run(object))
except RuntimeError:
__import__("nest_asyncio").apply()
return dict(asyncio.run(object))
def merged_imports(files):
results = merge(*gather_imports(files).values())
return sorted(
set(list(results.get("required", [])) + list(results.get("questionable", [])))
)
def merge(*args):
if not args:
return {}
if len(args) == 1:
return args[0]
a, b, *args = args
if args:
b = functools.reduce(merge, (b, *args))
if hasattr(a, "items"):
for k, v in a.items():
if k in b:
a[k] = merge(v, b[k])
for k, v in b.items():
if k not in a:
try:
a[k] = v
except ValueError as exception:
if hasattr(a, "add_section"):
a.add_section(k)
a[k].update(v)
else:
raise exception
return a
if isinstance(a, tuple):
return a + tuple(x for x in b if x not in a)
if isinstance(a, list):
return a + list(x for x in b if x not in a)
if isinstance(a, set):
return list(sorted(set(a).union(b)))
return a or b
def import_to_pypi(list):
global IMPORT_TO_PIP
if not IMPORT_TO_PIP:
depfinder = _import_depfinder()
IMPORT_TO_PIP = {
x["import_name"]: x["pypi_name"] for x in depfinder.utils.mapping_list
}
return [IMPORT_TO_PIP.get(x, x) for x in list if x not in ["src"]]
def pypi_to_conda(list):
global PIP_TO_CONDA
if not PIP_TO_CONDA:
depfinder = _import_depfinder()
PIP_TO_CONDA = {
x["import_name"]: x["conda_name"] for x in depfinder.utils.mapping_list
}
return [PIP_TO_CONDA.get(x, x) for x in list]
# file loader loader/dumper functions
def ensure_trailing_eol(callable):
"""a decorator to comply with our linting opinion."""
import functools
@functools.wraps(callable)
def main(object):
str = callable(object)
return str.rstrip() + "\n"
return main
def load_txt(str):
return str.splitlines()
def dump_txt(object):
if isinstance(object, list):
object = "\n".join(object)
return object
def load_config(str):
object = configupdater.ConfigUpdater()
object.read_string(str)
return expand_cfg(object)
@ensure_trailing_eol
def dump_config__er(object):
next = io.StringIO()
object = compact_cfg(object)
if isinstance(object, dict):
import configparser
parser = configparser.ConfigParser(default_section=None)
parser.read_dict(object)
object = parser
object.write(next)
return next.getvalue()
def expand_cfg(object):
"""special conditions for config files so configparser and configuupdates work together."""
for main, section in object.items():
for key, value in section.items():
if isinstance(value, str) and value.startswith("\n"):
value = textwrap.dedent(value).splitlines()[1:]
object[main][key] = value
return object
def compact_cfg(object):
for main, section in object.items():
for key, value in section.items():
if isinstance(value, list):
import textwrap
value = textwrap.indent(
"\n".join([""] + list(map(textwrap.dedent, value))), " " * 4
)
object[main][key] = value
return object
def load_text(str):
return [x for x in str.splitlines()]
@ensure_trailing_eol
def dump_text(object):
return "\n".join(object)
def load_toml(str):
import tomlkit
return tomlkit.parse(str)
@ensure_trailing_eol
def dump_toml(object):
import tomlkit
return tomlkit.dumps(object)
def load_yaml(str):
import ruamel.yaml
object = ruamel.yaml.YAML()
return object.load(str)
@ensure_trailing_eol
def dump_yaml(object):
import ruamel.yaml
if isinstance(object, ruamel.YAML):
next = io.StringIO()
object.dump(next)
return next.getvalue()
return ruamel.yaml.safe_dump(object)
def to_dict(object):
if hasattr(object, "items"):
data = {}
for k, v in object.items():
if k is None:
continue
data[k] = to_dict(v)
else:
return data
return object
class INI(File):
"""dump and load ini files in place."""
_suffixes = ".ini", ".cfg"
def load(self):
try:
return load_config(self.read_text())
except FileNotFoundError:
return load_config("")
def dump(self, object):
return dump_config__er(object)
class TXT(File):
"""dump and load ini files in place."""
_suffixes = (".txt",)
def load(self):
try:
return load_txt(self.read_text())
except FileNotFoundError:
return load_txt("")
def dump(self, object):
return dump_txt(object)
class TOML(File):
"""dump and load toml files in place."""
_suffixes = (".toml",)
def load(self):
try:
return load_toml(self.read_text())
except FileNotFoundError:
return load_toml("")
def dump(self, object):
return dump_toml(object)
class JSON(File):
_suffixes = (".json",)
def load(self):
return json.loads(self.read_text())
def dump(self, boject):
return json.dumps(object)
class YML(File):
"""dump and load yml files in place."""
_suffixes = ".yaml", ".yml"
def load(self):
try:
return load_yaml(self.read_text())
except FileNotFoundError:
return load_yaml("{}")
def dump(self, object):
return dump_yaml(object)
IMPORT_TO_PIP = None
PIP_TO_CONDA = None
def is_pythonic(object):
object = pathlib.Path(object)
try:
ast.parse(object.stem)
except SyntaxError:
return False
return "-" not in object.stem
def normalize_version(object):
import packaging.requirements
with contextlib.redirect_stdout(io.StringIO()):
return str(packaging.version.Version(object))
def where_template(template):
try:
with importlib.resources.path("qpub.templates", template) as template:
template = File(template)
except:
template = File(__file__).parent / "templates" / template
return template
def templated_file(template, data):
import jsone
return jsone.render(where_template(template).load(), data)
def packages_from_conda_not_found(out):
packages = []
if out.startswith("PackagesNotFoundError"):
lines = out.splitlines()[1:]
for line in lines:
strip = line.strip()
if strip.startswith("-"):
packages += [strip.lstrip("-").lstrip()]
elif strip:
break
return packages
def installed(str):
try:
importlib.metadata.distribution(str)
return True
finally:
return False
class NoIndex(BaseException):
...
# # ███████╗██╗███╗ ██╗
# # ██╔════╝██║████╗ ██║
# # █████╗ ██║██╔██╗ ██║
# # ██╔══╝ ██║██║╚██╗██║
# # ██║ ██║██║ ╚████║
# # ╚═╝ ╚═╝╚═╝ ╚═══╝
def main(argv=None, raises=False):
global project
project = Project()
if argv is None:
argv = sys.argv[1:]
if isinstance(argv, str):
argv = argv.split()
main = doit.doit_cmd.DoitMain(doit.cmd_base.ModuleTaskLoader(globals()))
code = main.run(argv)
if raises:
sys.exit(code)
def run_in_doit():
return sys.argv[0].endswith("bin/doit")
if __name__ == "__main__":
main(None, True)
elif run_in_doit():
project = Project()
|
from enum import Enum
from typing import Any, Dict, List, Optional
from rest_framework import serializers
from rest_framework.exceptions import NotFound, ValidationError
from web3.exceptions import BadFunctionCallOutput
from gnosis.eth import EthereumClientProvider
from gnosis.eth.django.serializers import (EthereumAddressField,
HexadecimalField, Sha3HashField)
from gnosis.safe import Safe
from gnosis.safe.safe_signature import SafeSignature, SafeSignatureType
from gnosis.safe.serializers import SafeMultisigTxSerializerV1
from safe_transaction_service.contracts.tx_decoder import (TxDecoderException,
get_db_tx_decoder)
from safe_transaction_service.tokens.serializers import \
TokenInfoResponseSerializer
from .helpers import DelegateSignatureHelper
from .models import (ConfirmationType, EthereumTx, ModuleTransaction,
MultisigConfirmation, MultisigTransaction, SafeContract,
SafeContractDelegate)
from .services.safe_service import SafeCreationInfo
def get_data_decoded_from_data(data: bytes):
tx_decoder = get_db_tx_decoder()
try:
return tx_decoder.get_data_decoded(data)
except TxDecoderException:
return None
# ================================================ #
# Request Serializers
# ================================================ #
class SafeMultisigConfirmationSerializer(serializers.Serializer):
signature = HexadecimalField(min_length=65) # Signatures must be at least 65 bytes
def validate_signature(self, signature: bytes):
safe_tx_hash = self.context['safe_tx_hash']
try:
multisig_transaction = MultisigTransaction.objects.select_related(
'ethereum_tx'
).get(safe_tx_hash=safe_tx_hash)
except MultisigTransaction.DoesNotExist:
raise NotFound(f'Multisig transaction with safe-tx-hash={safe_tx_hash} was not found')
safe_address = multisig_transaction.safe
if multisig_transaction.executed:
raise ValidationError(f'Transaction with safe-tx-hash={safe_tx_hash} was already executed')
ethereum_client = EthereumClientProvider()
safe = Safe(safe_address, ethereum_client)
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
parsed_signatures = SafeSignature.parse_signature(signature, safe_tx_hash)
signature_owners = []
for safe_signature in parsed_signatures:
owner = safe_signature.owner
if owner not in safe_owners:
raise ValidationError(f'Signer={owner} is not an owner. Current owners={safe_owners}')
if not safe_signature.is_valid(ethereum_client, safe.address):
raise ValidationError(f'Signature={safe_signature.signature.hex()} for owner={owner} is not valid')
if owner in signature_owners:
raise ValidationError(f'Signature for owner={owner} is duplicated')
signature_owners.append(owner)
return signature
def save(self, **kwargs):
safe_tx_hash = self.context['safe_tx_hash']
signature = self.validated_data['signature']
multisig_confirmations = []
parsed_signatures = SafeSignature.parse_signature(signature, safe_tx_hash)
for safe_signature in parsed_signatures:
multisig_confirmation, _ = MultisigConfirmation.objects.get_or_create(
multisig_transaction_hash=safe_tx_hash,
owner=safe_signature.owner,
defaults={
'multisig_transaction_id': safe_tx_hash,
'signature': safe_signature.export_signature(),
'signature_type': safe_signature.signature_type.value,
}
)
multisig_confirmations.append(multisig_confirmation)
if self.validated_data['signature']:
MultisigTransaction.objects.filter(safe_tx_hash=safe_tx_hash).update(trusted=True)
return multisig_confirmations
class SafeMultisigTransactionSerializer(SafeMultisigTxSerializerV1):
contract_transaction_hash = Sha3HashField()
sender = EthereumAddressField()
# TODO Make signature mandatory
signature = HexadecimalField(required=False, min_length=65) # Signatures must be at least 65 bytes
origin = serializers.CharField(max_length=200, allow_null=True, default=None)
def validate(self, data):
super().validate(data)
ethereum_client = EthereumClientProvider()
safe = Safe(data['safe'], ethereum_client)
try:
safe_version = safe.retrieve_version()
except BadFunctionCallOutput as e:
raise ValidationError(f'Could not get Safe version from blockchain, check contract exists on network '
f'{ethereum_client.get_network().name}') from e
except IOError:
raise ValidationError('Problem connecting to the ethereum node, please try again later')
safe_tx = safe.build_multisig_tx(data['to'], data['value'], data['data'], data['operation'],
data['safe_tx_gas'], data['base_gas'], data['gas_price'],
data['gas_token'],
data['refund_receiver'],
safe_nonce=data['nonce'],
safe_version=safe_version)
contract_transaction_hash = safe_tx.safe_tx_hash
# Check safe tx hash matches
if contract_transaction_hash != data['contract_transaction_hash']:
raise ValidationError(f'Contract-transaction-hash={contract_transaction_hash.hex()} '
f'does not match provided contract-tx-hash={data['contract_transaction_hash'].hex()}')
# Check there's not duplicated tx with same `nonce` or same `safeTxHash` for the same Safe.
# We allow duplicated if existing tx is not executed
multisig_transactions = MultisigTransaction.objects.filter(
safe=safe.address,
nonce=data['nonce']
).executed()
if multisig_transactions:
for multisig_transaction in multisig_transactions:
if multisig_transaction.safe_tx_hash == contract_transaction_hash.hex():
raise ValidationError(f'Tx with safe-tx-hash={contract_transaction_hash.hex()} '
f'for safe={safe.address} was already executed in '
f'tx-hash={multisig_transaction.ethereum_tx_id}')
raise ValidationError(f'Tx with nonce={safe_tx.safe_nonce} for safe={safe.address} '
f'already executed in tx-hash={multisig_transactions[0].ethereum_tx_id}')
# Check owners and pending owners
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
except IOError:
raise ValidationError('Problem connecting to the ethereum node, please try again later')
data['safe_owners'] = safe_owners
delegates = SafeContractDelegate.objects.get_delegates_for_safe(safe.address)
allowed_senders = safe_owners + delegates
if not data['sender'] in allowed_senders:
raise ValidationError(f'Sender={data['sender']} is not an owner or delegate. '
f'Current owners={safe_owners}. Delegates={delegates}')
signature_owners = []
# TODO Make signature mandatory
signature = data.get('signature', b'')
parsed_signatures = SafeSignature.parse_signature(signature, contract_transaction_hash)
data['parsed_signatures'] = parsed_signatures
# If there's at least one signature, transaction is trusted (until signatures are mandatory)
data['trusted'] = bool(parsed_signatures)
for safe_signature in parsed_signatures:
owner = safe_signature.owner
if not safe_signature.is_valid(ethereum_client, safe.address):
raise ValidationError(f'Signature={safe_signature.signature.hex()} for owner={owner} is not valid')
if owner in delegates and len(parsed_signatures) > 1:
raise ValidationError('Just one signature is expected if using delegates')
if owner not in allowed_senders:
raise ValidationError(f'Signer={owner} is not an owner or delegate. '
f'Current owners={safe_owners}. Delegates={delegates}')
if owner in signature_owners:
raise ValidationError(f'Signature for owner={owner} is duplicated')
signature_owners.append(owner)
# TODO Make signature mandatory. len(signature_owners) must be >= 1
if signature_owners and data['sender'] not in signature_owners:
raise ValidationError(f'Signature does not match sender={data['sender']}. '
f'Calculated owners={signature_owners}')
return data
def save(self, **kwargs):
safe_tx_hash = self.validated_data['contract_transaction_hash']
origin = self.validated_data['origin']
trusted = self.validated_data['trusted']
multisig_transaction, created = MultisigTransaction.objects.get_or_create(
safe_tx_hash=safe_tx_hash,
defaults={
'safe': self.validated_data['safe'],
'to': self.validated_data['to'],
'value': self.validated_data['value'],
'data': self.validated_data['data'] if self.validated_data['data'] else None,
'operation': self.validated_data['operation'],
'safe_tx_gas': self.validated_data['safe_tx_gas'],
'base_gas': self.validated_data['base_gas'],
'gas_price': self.validated_data['gas_price'],
'gas_token': self.validated_data['gas_token'],
'refund_receiver': self.validated_data['refund_receiver'],
'nonce': self.validated_data['nonce'],
'origin': origin,
'trusted': trusted,
}
)
if not created and trusted and not multisig_transaction.trusted:
multisig_transaction.origin = origin
multisig_transaction.trusted = trusted
multisig_transaction.save(update_fields=['origin', 'trusted'])
for safe_signature in self.validated_data.get('parsed_signatures'):
if safe_signature.owner in self.validated_data['safe_owners']:
multisig_confirmation, _ = MultisigConfirmation.objects.get_or_create(
multisig_transaction_hash=safe_tx_hash,
owner=safe_signature.owner,
defaults={
'multisig_transaction': multisig_transaction,
'signature': safe_signature.export_signature(),
'signature_type': safe_signature.signature_type.value,
}
)
return multisig_transaction
class SafeDelegateDeleteSerializer(serializers.Serializer):
safe = EthereumAddressField()
delegate = EthereumAddressField()
signature = HexadecimalField(min_length=65)
def check_signature(self, signature: bytes, operation_hash: bytes, safe_owners: List[str]) -> Optional[str]:
"""
Checks signature and returns a valid owner if found, None otherwise
:param signature:
:param operation_hash:
:param safe_owners:
:return: Valid delegator address if found, None otherwise
"""
safe_signatures = SafeSignature.parse_signature(signature, operation_hash)
if not safe_signatures:
raise ValidationError('Signature is not valid')
elif len(safe_signatures) > 1:
raise ValidationError('More than one signatures detected, just one is expected')
safe_signature = safe_signatures[0]
delegator = safe_signature.owner
if delegator in safe_owners:
if not safe_signature.is_valid():
raise ValidationError(f'Signature of type={safe_signature.signature_type.name} '
f'for delegator={delegator} is not valid')
return delegator
def validate(self, data):
super().validate(data)
if not SafeContract.objects.filter(address=data['safe']).exists():
raise ValidationError(f"Safe={data["safe"]} does not exist or it's still not indexed")
ethereum_client = EthereumClientProvider()
safe = Safe(data['safe'], ethereum_client)
# Check owners and pending owners
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
signature = data['signature']
delegate = data['delegate'] # Delegate address to be added
# Tries to find a valid delegator using multiple strategies
for operation_hash in (DelegateSignatureHelper.calculate_hash(delegate),
DelegateSignatureHelper.calculate_hash(delegate, eth_sign=True),
DelegateSignatureHelper.calculate_hash(delegate, previous_topt=True),
DelegateSignatureHelper.calculate_hash(delegate, eth_sign=True, previous_topt=True)):
delegator = self.check_signature(signature, operation_hash, safe_owners)
if delegator:
break
if not delegator:
raise ValidationError('Signing owner is not an owner of the Safe')
data['delegator'] = delegator
return data
class SafeDelegateSerializer(SafeDelegateDeleteSerializer):
label = serializers.CharField(max_length=50)
def save(self, **kwargs):
safe_address = self.validated_data['safe']
delegate = self.validated_data['delegate']
delegator = self.validated_data['delegator']
label = self.validated_data['label']
obj, _ = SafeContractDelegate.objects.update_or_create(
safe_contract_id=safe_address,
delegate=delegate,
defaults={
'label': label,
'delegator': delegator,
}
)
return obj
class DataDecoderSerializer(serializers.Serializer):
data = HexadecimalField(allow_null=False, allow_blank=False, min_length=4)
# ================================================ #
# Response Serializers
# ================================================ #
class SafeModuleTransactionResponseSerializer(serializers.ModelSerializer):
execution_date = serializers.DateTimeField()
data = HexadecimalField(allow_null=True, allow_blank=True)
data_decoded = serializers.SerializerMethodField()
transaction_hash = serializers.SerializerMethodField()
block_number = serializers.SerializerMethodField()
class Meta:
model = ModuleTransaction
fields = ('created', 'execution_date', 'block_number', 'transaction_hash', 'safe',
'module', 'to', 'value', 'data', 'operation', 'data_decoded')
def get_block_number(self, obj: ModuleTransaction) -> Optional[int]:
return obj.internal_tx.ethereum_tx.block_id
def get_data_decoded(self, obj: SafeCreationInfo) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.data.tobytes() if obj.data else b'')
def get_transaction_hash(self, obj: ModuleTransaction) -> str:
return obj.internal_tx.ethereum_tx_id
class SafeMultisigConfirmationResponseSerializer(serializers.ModelSerializer):
submission_date = serializers.DateTimeField(source='created')
confirmation_type = serializers.SerializerMethodField()
transaction_hash = serializers.SerializerMethodField()
signature = HexadecimalField()
signature_type = serializers.SerializerMethodField()
class Meta:
model = MultisigConfirmation
fields = ('owner', 'submission_date', 'transaction_hash', 'confirmation_type', 'signature', 'signature_type')
def get_confirmation_type(self, obj: MultisigConfirmation) -> str:
# TODO Remove this field
return ConfirmationType.CONFIRMATION.name
def get_transaction_hash(self, obj: MultisigConfirmation) -> str:
return obj.ethereum_tx_id
def get_signature_type(self, obj: MultisigConfirmation) -> str:
return SafeSignatureType(obj.signature_type).name
class SafeMultisigTransactionResponseSerializer(SafeMultisigTxSerializerV1):
execution_date = serializers.DateTimeField()
submission_date = serializers.DateTimeField(source='created') # First seen by this service
modified = serializers.DateTimeField()
block_number = serializers.SerializerMethodField()
transaction_hash = Sha3HashField(source='ethereum_tx_id')
safe_tx_hash = Sha3HashField()
executor = serializers.SerializerMethodField()
value = serializers.CharField()
is_executed = serializers.BooleanField(source='executed')
is_successful = serializers.SerializerMethodField()
gas_price = serializers.CharField()
eth_gas_price = serializers.SerializerMethodField()
gas_used = serializers.SerializerMethodField()
fee = serializers.SerializerMethodField()
origin = serializers.CharField()
data_decoded = serializers.SerializerMethodField()
confirmations_required = serializers.IntegerField()
confirmations = serializers.SerializerMethodField()
signatures = HexadecimalField()
def get_block_number(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx_id:
return obj.ethereum_tx.block_id
def get_confirmations(self, obj: MultisigTransaction) -> Dict[str, Any]:
"""
Filters confirmations queryset
:param obj: MultisigConfirmation instance
:return: Serialized queryset
"""
return SafeMultisigConfirmationResponseSerializer(obj.confirmations, many=True).data
def get_executor(self, obj: MultisigTransaction) -> Optional[str]:
if obj.ethereum_tx_id:
return obj.ethereum_tx._from
def get_fee(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx:
if obj.ethereum_tx.gas_used and obj.ethereum_tx.gas_price:
return str(obj.ethereum_tx.gas_used * obj.ethereum_tx.gas_price)
def get_eth_gas_price(self, obj: MultisigTransaction) -> Optional[str]:
if obj.ethereum_tx and obj.ethereum_tx.gas_price:
return str(obj.ethereum_tx.gas_price)
def get_gas_used(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx and obj.ethereum_tx.gas_used:
return obj.ethereum_tx.gas_used
def get_is_successful(self, obj: MultisigTransaction) -> Optional[bool]:
if obj.failed is None:
return None
else:
return not obj.failed
def get_data_decoded(self, obj: MultisigTransaction) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.data.tobytes() if obj.data else b'')
class Erc20InfoSerializer(serializers.Serializer):
name = serializers.CharField()
symbol = serializers.CharField()
decimals = serializers.IntegerField()
logo_uri = serializers.CharField()
class SafeBalanceResponseSerializer(serializers.Serializer):
token_address = serializers.CharField()
token = Erc20InfoSerializer()
balance = serializers.CharField()
class SafeBalanceUsdResponseSerializer(SafeBalanceResponseSerializer):
fiat_balance = serializers.CharField()
fiat_conversion = serializers.CharField()
fiat_code = serializers.CharField()
class SafeCollectibleResponseSerializer(serializers.Serializer):
address = serializers.CharField()
token_name = serializers.CharField()
token_symbol = serializers.CharField()
logo_uri = serializers.CharField()
id = serializers.CharField()
uri = serializers.CharField()
name = serializers.CharField()
description = serializers.CharField()
image_uri = serializers.CharField()
metadata = serializers.DictField()
class SafeDelegateResponseSerializer(serializers.Serializer):
delegate = EthereumAddressField()
delegator = EthereumAddressField()
label = serializers.CharField(max_length=50)
class SafeCreationInfoResponseSerializer(serializers.Serializer):
created = serializers.DateTimeField()
creator = EthereumAddressField()
transaction_hash = Sha3HashField()
factory_address = EthereumAddressField()
master_copy = EthereumAddressField(allow_null=True)
setup_data = HexadecimalField(allow_null=True)
data_decoded = serializers.SerializerMethodField()
def get_data_decoded(self, obj: SafeCreationInfo) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.setup_data or b'')
class SafeInfoResponseSerializer(serializers.Serializer):
address = EthereumAddressField()
nonce = serializers.IntegerField()
threshold = serializers.IntegerField()
owners = serializers.ListField(child=EthereumAddressField())
master_copy = EthereumAddressField()
modules = serializers.ListField(child=EthereumAddressField())
fallback_handler = EthereumAddressField()
version = serializers.CharField()
class MasterCopyResponseSerializer(serializers.Serializer):
address = EthereumAddressField()
version = serializers.CharField()
class OwnerResponseSerializer(serializers.Serializer):
safes = serializers.ListField(child=EthereumAddressField())
class TransferType(Enum):
ETHER_TRANSFER = 0
ERC20_TRANSFER = 1
ERC721_TRANSFER = 2
UNKNOWN = 3
class TransferResponseSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
execution_date = serializers.DateTimeField()
block_number = serializers.IntegerField()
transaction_hash = Sha3HashField()
to = EthereumAddressField()
from_ = EthereumAddressField(source='_from', allow_zero_address=True)
value = serializers.CharField(allow_null=True)
token_id = serializers.CharField(allow_null=True)
token_address = EthereumAddressField(allow_null=True, default=None)
def get_fields(self):
result = super().get_fields()
# Rename `from_` to `from`
from_ = result.pop('from_')
result['from'] = from_
return result
def get_type(self, obj: Dict[str, Any]) -> str:
if not obj.get('token_address'):
return TransferType.ETHER_TRANSFER.name
else:
if obj.get('value') is not None:
return TransferType.ERC20_TRANSFER.name
elif obj.get('token_id') is not None:
return TransferType.ERC721_TRANSFER.name
return TransferType.UNKNOWN
def validate(self, data):
super().validate(data)
if data['value'] is None and data['token_id'] is None:
raise ValidationError('Both value and token_id cannot be null')
return data
class TransferWithTokenInfoResponseSerializer(TransferResponseSerializer):
token_info = TokenInfoResponseSerializer(source='token')
def get_type(self, obj: Dict[str, Any]) -> str:
"""
Sometimes ERC20/721 `Transfer` events look the same, if token info is available better use that information
to check
:param obj:
:return: `TransferType` as a string
"""
transfer_type = super().get_type(obj)
if transfer_type in (TransferType.ERC20_TRANSFER.name, TransferType.ERC721_TRANSFER.name):
if token := obj['token']:
decimals = token['decimals'] if isinstance(token, dict) else token.decimals
if decimals is None:
transfer_type = TransferType.ERC721_TRANSFER.name
if obj['token_id'] is None:
obj['token_id'], obj['value'] = obj['value'], obj['token_id']
else:
transfer_type = TransferType.ERC20_TRANSFER.name
if obj['value'] is None:
obj['token_id'], obj['value'] = obj['value'], obj['token_id']
return transfer_type
# All txs serializers
class TxType(Enum):
ETHEREUM_TRANSACTION = 0
MULTISIG_TRANSACTION = 1
MODULE_TRANSACTION = 2
class SafeModuleTransactionWithTransfersResponseSerializer(SafeModuleTransactionResponseSerializer):
class Meta:
model = SafeModuleTransactionResponseSerializer.Meta.model
fields = SafeModuleTransactionResponseSerializer.Meta.fields + ('transfers', 'tx_type')
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.MODULE_TRANSACTION.name
class SafeMultisigTransactionWithTransfersResponseSerializer(SafeMultisigTransactionResponseSerializer):
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.MULTISIG_TRANSACTION.name
class EthereumTxWithTransfersResponseSerializer(serializers.Serializer):
class Meta:
model = EthereumTx
exclude = ('block',)
execution_date = serializers.DateTimeField()
_from = EthereumAddressField(allow_null=False, allow_zero_address=True, source='_from')
to = EthereumAddressField(allow_null=True, allow_zero_address=True)
data = HexadecimalField()
tx_hash = HexadecimalField()
block_number = serializers.SerializerMethodField()
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.ETHEREUM_TRANSACTION.name
def get_fields(self):
result = super().get_fields()
# Rename `_from` to `from`
_from = result.pop('_from')
result['from'] = _from
return result
def get_block_number(self, obj: EthereumTx):
if obj.block_id:
return obj.block_id
class AnalyticsMultisigTxsByOriginResponseSerializer(serializers.Serializer):
origin = serializers.CharField()
transactions = serializers.IntegerField()
class AnalyticsMultisigTxsBySafeResponseSerializer(serializers.Serializer):
safe = EthereumAddressField()
master_copy = EthereumAddressField()
transactions = serializers.IntegerField()
class _AllTransactionsSchemaSerializer(serializers.Serializer):
"""
Just for the purpose of documenting, don't use it
"""
tx_type_1 = SafeModuleTransactionWithTransfersResponseSerializer()
tx_type_2 = SafeMultisigTransactionWithTransfersResponseSerializer()
tx_type_3 = EthereumTxWithTransfersResponseSerializer()
| from enum import Enum
from typing import Any, Dict, List, Optional
from rest_framework import serializers
from rest_framework.exceptions import NotFound, ValidationError
from web3.exceptions import BadFunctionCallOutput
from gnosis.eth import EthereumClientProvider
from gnosis.eth.django.serializers import (EthereumAddressField,
HexadecimalField, Sha3HashField)
from gnosis.safe import Safe
from gnosis.safe.safe_signature import SafeSignature, SafeSignatureType
from gnosis.safe.serializers import SafeMultisigTxSerializerV1
from safe_transaction_service.contracts.tx_decoder import (TxDecoderException,
get_db_tx_decoder)
from safe_transaction_service.tokens.serializers import \
TokenInfoResponseSerializer
from .helpers import DelegateSignatureHelper
from .models import (ConfirmationType, EthereumTx, ModuleTransaction,
MultisigConfirmation, MultisigTransaction, SafeContract,
SafeContractDelegate)
from .services.safe_service import SafeCreationInfo
def get_data_decoded_from_data(data: bytes):
tx_decoder = get_db_tx_decoder()
try:
return tx_decoder.get_data_decoded(data)
except TxDecoderException:
return None
# ================================================ #
# Request Serializers
# ================================================ #
class SafeMultisigConfirmationSerializer(serializers.Serializer):
signature = HexadecimalField(min_length=65) # Signatures must be at least 65 bytes
def validate_signature(self, signature: bytes):
safe_tx_hash = self.context['safe_tx_hash']
try:
multisig_transaction = MultisigTransaction.objects.select_related(
'ethereum_tx'
).get(safe_tx_hash=safe_tx_hash)
except MultisigTransaction.DoesNotExist:
raise NotFound(f'Multisig transaction with safe-tx-hash={safe_tx_hash} was not found')
safe_address = multisig_transaction.safe
if multisig_transaction.executed:
raise ValidationError(f'Transaction with safe-tx-hash={safe_tx_hash} was already executed')
ethereum_client = EthereumClientProvider()
safe = Safe(safe_address, ethereum_client)
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
parsed_signatures = SafeSignature.parse_signature(signature, safe_tx_hash)
signature_owners = []
for safe_signature in parsed_signatures:
owner = safe_signature.owner
if owner not in safe_owners:
raise ValidationError(f'Signer={owner} is not an owner. Current owners={safe_owners}')
if not safe_signature.is_valid(ethereum_client, safe.address):
raise ValidationError(f'Signature={safe_signature.signature.hex()} for owner={owner} is not valid')
if owner in signature_owners:
raise ValidationError(f'Signature for owner={owner} is duplicated')
signature_owners.append(owner)
return signature
def save(self, **kwargs):
safe_tx_hash = self.context['safe_tx_hash']
signature = self.validated_data['signature']
multisig_confirmations = []
parsed_signatures = SafeSignature.parse_signature(signature, safe_tx_hash)
for safe_signature in parsed_signatures:
multisig_confirmation, _ = MultisigConfirmation.objects.get_or_create(
multisig_transaction_hash=safe_tx_hash,
owner=safe_signature.owner,
defaults={
'multisig_transaction_id': safe_tx_hash,
'signature': safe_signature.export_signature(),
'signature_type': safe_signature.signature_type.value,
}
)
multisig_confirmations.append(multisig_confirmation)
if self.validated_data['signature']:
MultisigTransaction.objects.filter(safe_tx_hash=safe_tx_hash).update(trusted=True)
return multisig_confirmations
class SafeMultisigTransactionSerializer(SafeMultisigTxSerializerV1):
contract_transaction_hash = Sha3HashField()
sender = EthereumAddressField()
# TODO Make signature mandatory
signature = HexadecimalField(required=False, min_length=65) # Signatures must be at least 65 bytes
origin = serializers.CharField(max_length=200, allow_null=True, default=None)
def validate(self, data):
super().validate(data)
ethereum_client = EthereumClientProvider()
safe = Safe(data['safe'], ethereum_client)
try:
safe_version = safe.retrieve_version()
except BadFunctionCallOutput as e:
raise ValidationError(f'Could not get Safe version from blockchain, check contract exists on network '
f'{ethereum_client.get_network().name}') from e
except IOError:
raise ValidationError('Problem connecting to the ethereum node, please try again later')
safe_tx = safe.build_multisig_tx(data['to'], data['value'], data['data'], data['operation'],
data['safe_tx_gas'], data['base_gas'], data['gas_price'],
data['gas_token'],
data['refund_receiver'],
safe_nonce=data['nonce'],
safe_version=safe_version)
contract_transaction_hash = safe_tx.safe_tx_hash
# Check safe tx hash matches
if contract_transaction_hash != data['contract_transaction_hash']:
raise ValidationError(f'Contract-transaction-hash={contract_transaction_hash.hex()} '
f'does not match provided contract-tx-hash={data["contract_transaction_hash"].hex()}')
# Check there's not duplicated tx with same `nonce` or same `safeTxHash` for the same Safe.
# We allow duplicated if existing tx is not executed
multisig_transactions = MultisigTransaction.objects.filter(
safe=safe.address,
nonce=data['nonce']
).executed()
if multisig_transactions:
for multisig_transaction in multisig_transactions:
if multisig_transaction.safe_tx_hash == contract_transaction_hash.hex():
raise ValidationError(f'Tx with safe-tx-hash={contract_transaction_hash.hex()} '
f'for safe={safe.address} was already executed in '
f'tx-hash={multisig_transaction.ethereum_tx_id}')
raise ValidationError(f'Tx with nonce={safe_tx.safe_nonce} for safe={safe.address} '
f'already executed in tx-hash={multisig_transactions[0].ethereum_tx_id}')
# Check owners and pending owners
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
except IOError:
raise ValidationError('Problem connecting to the ethereum node, please try again later')
data['safe_owners'] = safe_owners
delegates = SafeContractDelegate.objects.get_delegates_for_safe(safe.address)
allowed_senders = safe_owners + delegates
if not data['sender'] in allowed_senders:
raise ValidationError(f'Sender={data["sender"]} is not an owner or delegate. '
f'Current owners={safe_owners}. Delegates={delegates}')
signature_owners = []
# TODO Make signature mandatory
signature = data.get('signature', b'')
parsed_signatures = SafeSignature.parse_signature(signature, contract_transaction_hash)
data['parsed_signatures'] = parsed_signatures
# If there's at least one signature, transaction is trusted (until signatures are mandatory)
data['trusted'] = bool(parsed_signatures)
for safe_signature in parsed_signatures:
owner = safe_signature.owner
if not safe_signature.is_valid(ethereum_client, safe.address):
raise ValidationError(f'Signature={safe_signature.signature.hex()} for owner={owner} is not valid')
if owner in delegates and len(parsed_signatures) > 1:
raise ValidationError('Just one signature is expected if using delegates')
if owner not in allowed_senders:
raise ValidationError(f'Signer={owner} is not an owner or delegate. '
f'Current owners={safe_owners}. Delegates={delegates}')
if owner in signature_owners:
raise ValidationError(f'Signature for owner={owner} is duplicated')
signature_owners.append(owner)
# TODO Make signature mandatory. len(signature_owners) must be >= 1
if signature_owners and data['sender'] not in signature_owners:
raise ValidationError(f'Signature does not match sender={data["sender"]}. '
f'Calculated owners={signature_owners}')
return data
def save(self, **kwargs):
safe_tx_hash = self.validated_data['contract_transaction_hash']
origin = self.validated_data['origin']
trusted = self.validated_data['trusted']
multisig_transaction, created = MultisigTransaction.objects.get_or_create(
safe_tx_hash=safe_tx_hash,
defaults={
'safe': self.validated_data['safe'],
'to': self.validated_data['to'],
'value': self.validated_data['value'],
'data': self.validated_data['data'] if self.validated_data['data'] else None,
'operation': self.validated_data['operation'],
'safe_tx_gas': self.validated_data['safe_tx_gas'],
'base_gas': self.validated_data['base_gas'],
'gas_price': self.validated_data['gas_price'],
'gas_token': self.validated_data['gas_token'],
'refund_receiver': self.validated_data['refund_receiver'],
'nonce': self.validated_data['nonce'],
'origin': origin,
'trusted': trusted,
}
)
if not created and trusted and not multisig_transaction.trusted:
multisig_transaction.origin = origin
multisig_transaction.trusted = trusted
multisig_transaction.save(update_fields=['origin', 'trusted'])
for safe_signature in self.validated_data.get('parsed_signatures'):
if safe_signature.owner in self.validated_data['safe_owners']:
multisig_confirmation, _ = MultisigConfirmation.objects.get_or_create(
multisig_transaction_hash=safe_tx_hash,
owner=safe_signature.owner,
defaults={
'multisig_transaction': multisig_transaction,
'signature': safe_signature.export_signature(),
'signature_type': safe_signature.signature_type.value,
}
)
return multisig_transaction
class SafeDelegateDeleteSerializer(serializers.Serializer):
safe = EthereumAddressField()
delegate = EthereumAddressField()
signature = HexadecimalField(min_length=65)
def check_signature(self, signature: bytes, operation_hash: bytes, safe_owners: List[str]) -> Optional[str]:
"""
Checks signature and returns a valid owner if found, None otherwise
:param signature:
:param operation_hash:
:param safe_owners:
:return: Valid delegator address if found, None otherwise
"""
safe_signatures = SafeSignature.parse_signature(signature, operation_hash)
if not safe_signatures:
raise ValidationError('Signature is not valid')
elif len(safe_signatures) > 1:
raise ValidationError('More than one signatures detected, just one is expected')
safe_signature = safe_signatures[0]
delegator = safe_signature.owner
if delegator in safe_owners:
if not safe_signature.is_valid():
raise ValidationError(f'Signature of type={safe_signature.signature_type.name} '
f'for delegator={delegator} is not valid')
return delegator
def validate(self, data):
super().validate(data)
if not SafeContract.objects.filter(address=data['safe']).exists():
raise ValidationError(f"Safe={data['safe']} does not exist or it's still not indexed")
ethereum_client = EthereumClientProvider()
safe = Safe(data['safe'], ethereum_client)
# Check owners and pending owners
try:
safe_owners = safe.retrieve_owners(block_identifier='pending')
except BadFunctionCallOutput: # Error using pending block identifier
safe_owners = safe.retrieve_owners(block_identifier='latest')
signature = data['signature']
delegate = data['delegate'] # Delegate address to be added
# Tries to find a valid delegator using multiple strategies
for operation_hash in (DelegateSignatureHelper.calculate_hash(delegate),
DelegateSignatureHelper.calculate_hash(delegate, eth_sign=True),
DelegateSignatureHelper.calculate_hash(delegate, previous_topt=True),
DelegateSignatureHelper.calculate_hash(delegate, eth_sign=True, previous_topt=True)):
delegator = self.check_signature(signature, operation_hash, safe_owners)
if delegator:
break
if not delegator:
raise ValidationError('Signing owner is not an owner of the Safe')
data['delegator'] = delegator
return data
class SafeDelegateSerializer(SafeDelegateDeleteSerializer):
label = serializers.CharField(max_length=50)
def save(self, **kwargs):
safe_address = self.validated_data['safe']
delegate = self.validated_data['delegate']
delegator = self.validated_data['delegator']
label = self.validated_data['label']
obj, _ = SafeContractDelegate.objects.update_or_create(
safe_contract_id=safe_address,
delegate=delegate,
defaults={
'label': label,
'delegator': delegator,
}
)
return obj
class DataDecoderSerializer(serializers.Serializer):
data = HexadecimalField(allow_null=False, allow_blank=False, min_length=4)
# ================================================ #
# Response Serializers
# ================================================ #
class SafeModuleTransactionResponseSerializer(serializers.ModelSerializer):
execution_date = serializers.DateTimeField()
data = HexadecimalField(allow_null=True, allow_blank=True)
data_decoded = serializers.SerializerMethodField()
transaction_hash = serializers.SerializerMethodField()
block_number = serializers.SerializerMethodField()
class Meta:
model = ModuleTransaction
fields = ('created', 'execution_date', 'block_number', 'transaction_hash', 'safe',
'module', 'to', 'value', 'data', 'operation', 'data_decoded')
def get_block_number(self, obj: ModuleTransaction) -> Optional[int]:
return obj.internal_tx.ethereum_tx.block_id
def get_data_decoded(self, obj: SafeCreationInfo) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.data.tobytes() if obj.data else b'')
def get_transaction_hash(self, obj: ModuleTransaction) -> str:
return obj.internal_tx.ethereum_tx_id
class SafeMultisigConfirmationResponseSerializer(serializers.ModelSerializer):
submission_date = serializers.DateTimeField(source='created')
confirmation_type = serializers.SerializerMethodField()
transaction_hash = serializers.SerializerMethodField()
signature = HexadecimalField()
signature_type = serializers.SerializerMethodField()
class Meta:
model = MultisigConfirmation
fields = ('owner', 'submission_date', 'transaction_hash', 'confirmation_type', 'signature', 'signature_type')
def get_confirmation_type(self, obj: MultisigConfirmation) -> str:
# TODO Remove this field
return ConfirmationType.CONFIRMATION.name
def get_transaction_hash(self, obj: MultisigConfirmation) -> str:
return obj.ethereum_tx_id
def get_signature_type(self, obj: MultisigConfirmation) -> str:
return SafeSignatureType(obj.signature_type).name
class SafeMultisigTransactionResponseSerializer(SafeMultisigTxSerializerV1):
execution_date = serializers.DateTimeField()
submission_date = serializers.DateTimeField(source='created') # First seen by this service
modified = serializers.DateTimeField()
block_number = serializers.SerializerMethodField()
transaction_hash = Sha3HashField(source='ethereum_tx_id')
safe_tx_hash = Sha3HashField()
executor = serializers.SerializerMethodField()
value = serializers.CharField()
is_executed = serializers.BooleanField(source='executed')
is_successful = serializers.SerializerMethodField()
gas_price = serializers.CharField()
eth_gas_price = serializers.SerializerMethodField()
gas_used = serializers.SerializerMethodField()
fee = serializers.SerializerMethodField()
origin = serializers.CharField()
data_decoded = serializers.SerializerMethodField()
confirmations_required = serializers.IntegerField()
confirmations = serializers.SerializerMethodField()
signatures = HexadecimalField()
def get_block_number(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx_id:
return obj.ethereum_tx.block_id
def get_confirmations(self, obj: MultisigTransaction) -> Dict[str, Any]:
"""
Filters confirmations queryset
:param obj: MultisigConfirmation instance
:return: Serialized queryset
"""
return SafeMultisigConfirmationResponseSerializer(obj.confirmations, many=True).data
def get_executor(self, obj: MultisigTransaction) -> Optional[str]:
if obj.ethereum_tx_id:
return obj.ethereum_tx._from
def get_fee(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx:
if obj.ethereum_tx.gas_used and obj.ethereum_tx.gas_price:
return str(obj.ethereum_tx.gas_used * obj.ethereum_tx.gas_price)
def get_eth_gas_price(self, obj: MultisigTransaction) -> Optional[str]:
if obj.ethereum_tx and obj.ethereum_tx.gas_price:
return str(obj.ethereum_tx.gas_price)
def get_gas_used(self, obj: MultisigTransaction) -> Optional[int]:
if obj.ethereum_tx and obj.ethereum_tx.gas_used:
return obj.ethereum_tx.gas_used
def get_is_successful(self, obj: MultisigTransaction) -> Optional[bool]:
if obj.failed is None:
return None
else:
return not obj.failed
def get_data_decoded(self, obj: MultisigTransaction) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.data.tobytes() if obj.data else b'')
class Erc20InfoSerializer(serializers.Serializer):
name = serializers.CharField()
symbol = serializers.CharField()
decimals = serializers.IntegerField()
logo_uri = serializers.CharField()
class SafeBalanceResponseSerializer(serializers.Serializer):
token_address = serializers.CharField()
token = Erc20InfoSerializer()
balance = serializers.CharField()
class SafeBalanceUsdResponseSerializer(SafeBalanceResponseSerializer):
fiat_balance = serializers.CharField()
fiat_conversion = serializers.CharField()
fiat_code = serializers.CharField()
class SafeCollectibleResponseSerializer(serializers.Serializer):
address = serializers.CharField()
token_name = serializers.CharField()
token_symbol = serializers.CharField()
logo_uri = serializers.CharField()
id = serializers.CharField()
uri = serializers.CharField()
name = serializers.CharField()
description = serializers.CharField()
image_uri = serializers.CharField()
metadata = serializers.DictField()
class SafeDelegateResponseSerializer(serializers.Serializer):
delegate = EthereumAddressField()
delegator = EthereumAddressField()
label = serializers.CharField(max_length=50)
class SafeCreationInfoResponseSerializer(serializers.Serializer):
created = serializers.DateTimeField()
creator = EthereumAddressField()
transaction_hash = Sha3HashField()
factory_address = EthereumAddressField()
master_copy = EthereumAddressField(allow_null=True)
setup_data = HexadecimalField(allow_null=True)
data_decoded = serializers.SerializerMethodField()
def get_data_decoded(self, obj: SafeCreationInfo) -> Dict[str, Any]:
return get_data_decoded_from_data(obj.setup_data or b'')
class SafeInfoResponseSerializer(serializers.Serializer):
address = EthereumAddressField()
nonce = serializers.IntegerField()
threshold = serializers.IntegerField()
owners = serializers.ListField(child=EthereumAddressField())
master_copy = EthereumAddressField()
modules = serializers.ListField(child=EthereumAddressField())
fallback_handler = EthereumAddressField()
version = serializers.CharField()
class MasterCopyResponseSerializer(serializers.Serializer):
address = EthereumAddressField()
version = serializers.CharField()
class OwnerResponseSerializer(serializers.Serializer):
safes = serializers.ListField(child=EthereumAddressField())
class TransferType(Enum):
ETHER_TRANSFER = 0
ERC20_TRANSFER = 1
ERC721_TRANSFER = 2
UNKNOWN = 3
class TransferResponseSerializer(serializers.Serializer):
type = serializers.SerializerMethodField()
execution_date = serializers.DateTimeField()
block_number = serializers.IntegerField()
transaction_hash = Sha3HashField()
to = EthereumAddressField()
from_ = EthereumAddressField(source='_from', allow_zero_address=True)
value = serializers.CharField(allow_null=True)
token_id = serializers.CharField(allow_null=True)
token_address = EthereumAddressField(allow_null=True, default=None)
def get_fields(self):
result = super().get_fields()
# Rename `from_` to `from`
from_ = result.pop('from_')
result['from'] = from_
return result
def get_type(self, obj: Dict[str, Any]) -> str:
if not obj.get('token_address'):
return TransferType.ETHER_TRANSFER.name
else:
if obj.get('value') is not None:
return TransferType.ERC20_TRANSFER.name
elif obj.get('token_id') is not None:
return TransferType.ERC721_TRANSFER.name
return TransferType.UNKNOWN
def validate(self, data):
super().validate(data)
if data['value'] is None and data['token_id'] is None:
raise ValidationError('Both value and token_id cannot be null')
return data
class TransferWithTokenInfoResponseSerializer(TransferResponseSerializer):
token_info = TokenInfoResponseSerializer(source='token')
def get_type(self, obj: Dict[str, Any]) -> str:
"""
Sometimes ERC20/721 `Transfer` events look the same, if token info is available better use that information
to check
:param obj:
:return: `TransferType` as a string
"""
transfer_type = super().get_type(obj)
if transfer_type in (TransferType.ERC20_TRANSFER.name, TransferType.ERC721_TRANSFER.name):
if token := obj['token']:
decimals = token['decimals'] if isinstance(token, dict) else token.decimals
if decimals is None:
transfer_type = TransferType.ERC721_TRANSFER.name
if obj['token_id'] is None:
obj['token_id'], obj['value'] = obj['value'], obj['token_id']
else:
transfer_type = TransferType.ERC20_TRANSFER.name
if obj['value'] is None:
obj['token_id'], obj['value'] = obj['value'], obj['token_id']
return transfer_type
# All txs serializers
class TxType(Enum):
ETHEREUM_TRANSACTION = 0
MULTISIG_TRANSACTION = 1
MODULE_TRANSACTION = 2
class SafeModuleTransactionWithTransfersResponseSerializer(SafeModuleTransactionResponseSerializer):
class Meta:
model = SafeModuleTransactionResponseSerializer.Meta.model
fields = SafeModuleTransactionResponseSerializer.Meta.fields + ('transfers', 'tx_type')
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.MODULE_TRANSACTION.name
class SafeMultisigTransactionWithTransfersResponseSerializer(SafeMultisigTransactionResponseSerializer):
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.MULTISIG_TRANSACTION.name
class EthereumTxWithTransfersResponseSerializer(serializers.Serializer):
class Meta:
model = EthereumTx
exclude = ('block',)
execution_date = serializers.DateTimeField()
_from = EthereumAddressField(allow_null=False, allow_zero_address=True, source='_from')
to = EthereumAddressField(allow_null=True, allow_zero_address=True)
data = HexadecimalField()
tx_hash = HexadecimalField()
block_number = serializers.SerializerMethodField()
transfers = TransferWithTokenInfoResponseSerializer(many=True)
tx_type = serializers.SerializerMethodField()
def get_tx_type(self, obj):
return TxType.ETHEREUM_TRANSACTION.name
def get_fields(self):
result = super().get_fields()
# Rename `_from` to `from`
_from = result.pop('_from')
result['from'] = _from
return result
def get_block_number(self, obj: EthereumTx):
if obj.block_id:
return obj.block_id
class AnalyticsMultisigTxsByOriginResponseSerializer(serializers.Serializer):
origin = serializers.CharField()
transactions = serializers.IntegerField()
class AnalyticsMultisigTxsBySafeResponseSerializer(serializers.Serializer):
safe = EthereumAddressField()
master_copy = EthereumAddressField()
transactions = serializers.IntegerField()
class _AllTransactionsSchemaSerializer(serializers.Serializer):
"""
Just for the purpose of documenting, don't use it
"""
tx_type_1 = SafeModuleTransactionWithTransfersResponseSerializer()
tx_type_2 = SafeMultisigTransactionWithTransfersResponseSerializer()
tx_type_3 = EthereumTxWithTransfersResponseSerializer()
|
import os
from algorithms.settings import INFERENCE_MODEL
from algorithms.io.aws_connection_definition import download_aws_folder, download_aws_file
from algorithms.io.path_definition import get_project_dir
if __name__ == "__main__":
download_aws_folder(f"data/app/models/YOLO/{INFERENCE_MODEL["YOLO"]}/",
local_folder=f"{get_project_dir()}/data/app/models/YOLO/{INFERENCE_MODEL["YOLO"]}/")
local_folder = f"{get_project_dir()}/data/app/models/Mask_RCNN/{INFERENCE_MODEL["Mask_RCNN"]}"
if not os.path.isdir(local_folder):
os.makedirs(local_folder)
download_aws_file(f"data/app/models/Mask_RCNN/{INFERENCE_MODEL["Mask_RCNN"]}/best_model.h5",
local_file_name=f"{local_folder}/best_model.h5")
| import os
from algorithms.settings import INFERENCE_MODEL
from algorithms.io.aws_connection_definition import download_aws_folder, download_aws_file
from algorithms.io.path_definition import get_project_dir
if __name__ == "__main__":
download_aws_folder(f"data/app/models/YOLO/{INFERENCE_MODEL['YOLO']}/",
local_folder=f"{get_project_dir()}/data/app/models/YOLO/{INFERENCE_MODEL['YOLO']}/")
local_folder = f"{get_project_dir()}/data/app/models/Mask_RCNN/{INFERENCE_MODEL['Mask_RCNN']}"
if not os.path.isdir(local_folder):
os.makedirs(local_folder)
download_aws_file(f"data/app/models/Mask_RCNN/{INFERENCE_MODEL['Mask_RCNN']}/best_model.h5",
local_file_name=f"{local_folder}/best_model.h5")
|
import os
import urllib
from cached_property import cached_property
from ebi_eva_common_pyutils.pg_utils import get_all_results_for_query
from eva_submission.eload_submission import Eload
from eva_submission.eload_utils import get_reference_fasta_and_report, get_project_alias, download_file
class EloadBacklog(Eload):
def fill_in_config(self, force_config=False):
"""Fills in config params from metadata DB and ENA, enabling later parts of pipeline to run."""
if not self.eload_cfg.is_empty() and not force_config:
self.error(f'Already found a config file for {self.eload} while running backlog preparation')
self.error('Please remove the existing config file and try again.')
raise ValueError(f'Already found a config file for {self.eload} while running backlog preparation')
elif not self.eload_cfg.is_empty():
# backup the previous config and remove the existing content
self.eload_cfg.backup()
self.eload_cfg.clear()
self.eload_cfg.set('brokering', 'ena', 'PROJECT', value=self.project_accession)
self.get_analysis_info()
self.get_species_info()
self.update_config_with_hold_date(self.project_accession, self.project_alias)
self.eload_cfg.write()
@cached_property
def project_accession(self):
with self.metadata_connection_handle as conn:
query = f"select project_accession from evapro.project_eva_submission where eload_id={self.eload_num};"
rows = get_all_results_for_query(conn, query)
if len(rows) != 1:
raise ValueError(f'No project accession for {self.eload} found in metadata DB.')
return rows[0][0]
@cached_property
def project_alias(self):
return get_project_alias(self.project_accession)
def get_species_info(self):
"""Adds species info into the config: taxonomy id and scientific name,
and assembly accession, fasta, and report."""
with self.metadata_connection_handle as conn:
query = f"select a.taxonomy_id, b.scientific_name " \
f"from project_taxonomy a " \
f"join taxonomy b on a.taxonomy_id=b.taxonomy_id " \
f"where a.project_accession='{self.project_accession}';"
rows = get_all_results_for_query(conn, query)
if len(rows) < 1:
raise ValueError(f'No taxonomy for {self.project_accession} found in metadata DB.')
elif len(rows) > 1:
raise ValueError(f'Multiple taxonomy for {self.project_accession} found in metadata DB.')
tax_id, sci_name = rows[0]
self.eload_cfg.set('submission', 'taxonomy_id', value=tax_id)
self.eload_cfg.set('submission', 'scientific_name', value=sci_name)
with self.metadata_connection_handle as conn:
query = f"select distinct b.analysis_accession, b.vcf_reference_accession " \
f"from project_analysis a " \
f"join analysis b on a.analysis_accession=b.analysis_accession " \
f"where a.project_accession='{self.project_accession}' and b.hidden_in_eva=0;"
rows = get_all_results_for_query(conn, query)
if len(rows) < 1:
raise ValueError(f'No reference accession for {self.project_accession} found in metadata DB.')
for analysis_accession, asm_accession in rows:
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_accession', value=asm_accession)
fasta_path, report_path = get_reference_fasta_and_report(sci_name, asm_accession)
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_fasta', value=fasta_path)
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_report', value=report_path)
def find_local_file(self, fn):
full_path = os.path.join(self._get_dir('vcf'), fn)
if not os.path.exists(full_path):
self.error(f'File not found: {full_path}')
raise FileNotFoundError(f'File not found: {full_path}')
return full_path
def find_file_on_ena(self, fn, analysis):
basename = os.path.basename(fn)
full_path = os.path.join(self._get_dir('ena'), basename)
if not os.path.exists(full_path):
try:
self.info(f'Retrieve {basename} in {analysis} from ENA ftp')
url = f'ftp://ftp.sra.ebi.ac.uk/vol1/{analysis[:6]}/{analysis}/{basename}'
download_file(url, full_path)
except urllib.error.URLError:
self.error(f'Could not access {url} on ENA: most likely does not exist')
raise FileNotFoundError(f'File not found: {full_path}')
return full_path
def get_analysis_info(self):
"""Adds analysis info into the config: analysis accession(s), and vcf and index files."""
with self.metadata_connection_handle as conn:
query = f"select a.analysis_accession, array_agg(c.filename) " \
f"from project_analysis a " \
f"join analysis_file b on a.analysis_accession=b.analysis_accession " \
f"join file c on b.file_id=c.file_id " \
f"join analysis d on a.analysis_accession=d.analysis_accession " \
f"where a.project_accession='{self.project_accession}' and d.hidden_in_eva=0" \
f"group by a.analysis_accession;"
rows = get_all_results_for_query(conn, query)
if len(rows) == 0:
raise ValueError(f'No analysis for {self.project_accession} found in metadata DB.')
for analysis_accession, filenames in rows:
# Uses the analysis accession as analysis alias
self.eload_cfg.set('brokering', 'ena', 'ANALYSIS', analysis_accession, value=analysis_accession)
vcf_file_list = []
index_file_dict = {}
for fn in filenames:
if not fn.endswith('.vcf.gz') and not fn.endswith('.vcf.gz.tbi'):
self.warning(f'Ignoring {fn} because it is not a VCF or an index')
continue
try:
full_path = self.find_local_file(fn)
except FileNotFoundError:
full_path = self.find_file_on_ena(fn, analysis_accession)
if full_path.endswith('.vcf.gz.tbi'):
# Store with the basename of the VCF file for easy retrieval
index_file_dict[os.path.basename(full_path)[:-4]] = full_path
else:
vcf_file_list.append(full_path)
for vcf_file in vcf_file_list:
basename = os.path.basename(vcf_file)
if basename not in index_file_dict:
raise ValueError(f'Index file is missing from metadata DB for vcf {basename} analysis {analysis_accession}')
self.eload_cfg.set('brokering', 'analyses', analysis_accession, 'vcf_files', vcf_file, 'index',
value=index_file_dict.pop(basename))
# Check if there are any orphaned index
if len(index_file_dict) > 0:
raise ValueError(f'VCF file is missing from metadata DB for index {', '.join(index_file_dict.values())}'
f' for analysis {analysis_accession}')
# Using analysis_accession instead of analysis alias. This should not have any detrimental effect on
# ingestion
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'vcf_files', value=vcf_file_list)
def _analysis_report(self, all_analysis):
reports = []
for analysis_accession in all_analysis:
assembly = all_analysis.get(analysis_accession).get('assembly_accession', '')
fasta = all_analysis.get(analysis_accession).get('assembly_fasta', '')
vcf_files_str = '\n'.join(all_analysis.get(analysis_accession).get('vcf_files', []))
reports.append(f"""{analysis_accession}
- Assembly: {assembly}
- Fasta file: {fasta}
- VCF file:
{vcf_files_str}""")
return '\n'.join(reports)
def report(self):
"""Collect information from the config and write the report."""
report_data = {
'project': self.eload_cfg.query('brokering', 'ena', 'PROJECT', ret_default=''),
'analyses': ', '.join(self.eload_cfg.query('brokering', 'ena', 'ANALYSIS', ret_default=[])),
'analyses_report': self._analysis_report(self.eload_cfg.query('submission', 'analyses', ret_default=[]))
}
report = """Results of backlog study preparation:
Project accession: {project}
Analysis accession(s): {analyses}
Analysis information: {analyses_report}
"""
print(report.format(**report_data))
| import os
import urllib
from cached_property import cached_property
from ebi_eva_common_pyutils.pg_utils import get_all_results_for_query
from eva_submission.eload_submission import Eload
from eva_submission.eload_utils import get_reference_fasta_and_report, get_project_alias, download_file
class EloadBacklog(Eload):
def fill_in_config(self, force_config=False):
"""Fills in config params from metadata DB and ENA, enabling later parts of pipeline to run."""
if not self.eload_cfg.is_empty() and not force_config:
self.error(f'Already found a config file for {self.eload} while running backlog preparation')
self.error('Please remove the existing config file and try again.')
raise ValueError(f'Already found a config file for {self.eload} while running backlog preparation')
elif not self.eload_cfg.is_empty():
# backup the previous config and remove the existing content
self.eload_cfg.backup()
self.eload_cfg.clear()
self.eload_cfg.set('brokering', 'ena', 'PROJECT', value=self.project_accession)
self.get_analysis_info()
self.get_species_info()
self.update_config_with_hold_date(self.project_accession, self.project_alias)
self.eload_cfg.write()
@cached_property
def project_accession(self):
with self.metadata_connection_handle as conn:
query = f"select project_accession from evapro.project_eva_submission where eload_id={self.eload_num};"
rows = get_all_results_for_query(conn, query)
if len(rows) != 1:
raise ValueError(f'No project accession for {self.eload} found in metadata DB.')
return rows[0][0]
@cached_property
def project_alias(self):
return get_project_alias(self.project_accession)
def get_species_info(self):
"""Adds species info into the config: taxonomy id and scientific name,
and assembly accession, fasta, and report."""
with self.metadata_connection_handle as conn:
query = f"select a.taxonomy_id, b.scientific_name " \
f"from project_taxonomy a " \
f"join taxonomy b on a.taxonomy_id=b.taxonomy_id " \
f"where a.project_accession='{self.project_accession}';"
rows = get_all_results_for_query(conn, query)
if len(rows) < 1:
raise ValueError(f'No taxonomy for {self.project_accession} found in metadata DB.')
elif len(rows) > 1:
raise ValueError(f'Multiple taxonomy for {self.project_accession} found in metadata DB.')
tax_id, sci_name = rows[0]
self.eload_cfg.set('submission', 'taxonomy_id', value=tax_id)
self.eload_cfg.set('submission', 'scientific_name', value=sci_name)
with self.metadata_connection_handle as conn:
query = f"select distinct b.analysis_accession, b.vcf_reference_accession " \
f"from project_analysis a " \
f"join analysis b on a.analysis_accession=b.analysis_accession " \
f"where a.project_accession='{self.project_accession}' and b.hidden_in_eva=0;"
rows = get_all_results_for_query(conn, query)
if len(rows) < 1:
raise ValueError(f'No reference accession for {self.project_accession} found in metadata DB.')
for analysis_accession, asm_accession in rows:
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_accession', value=asm_accession)
fasta_path, report_path = get_reference_fasta_and_report(sci_name, asm_accession)
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_fasta', value=fasta_path)
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'assembly_report', value=report_path)
def find_local_file(self, fn):
full_path = os.path.join(self._get_dir('vcf'), fn)
if not os.path.exists(full_path):
self.error(f'File not found: {full_path}')
raise FileNotFoundError(f'File not found: {full_path}')
return full_path
def find_file_on_ena(self, fn, analysis):
basename = os.path.basename(fn)
full_path = os.path.join(self._get_dir('ena'), basename)
if not os.path.exists(full_path):
try:
self.info(f'Retrieve {basename} in {analysis} from ENA ftp')
url = f'ftp://ftp.sra.ebi.ac.uk/vol1/{analysis[:6]}/{analysis}/{basename}'
download_file(url, full_path)
except urllib.error.URLError:
self.error(f'Could not access {url} on ENA: most likely does not exist')
raise FileNotFoundError(f'File not found: {full_path}')
return full_path
def get_analysis_info(self):
"""Adds analysis info into the config: analysis accession(s), and vcf and index files."""
with self.metadata_connection_handle as conn:
query = f"select a.analysis_accession, array_agg(c.filename) " \
f"from project_analysis a " \
f"join analysis_file b on a.analysis_accession=b.analysis_accession " \
f"join file c on b.file_id=c.file_id " \
f"join analysis d on a.analysis_accession=d.analysis_accession " \
f"where a.project_accession='{self.project_accession}' and d.hidden_in_eva=0" \
f"group by a.analysis_accession;"
rows = get_all_results_for_query(conn, query)
if len(rows) == 0:
raise ValueError(f'No analysis for {self.project_accession} found in metadata DB.')
for analysis_accession, filenames in rows:
# Uses the analysis accession as analysis alias
self.eload_cfg.set('brokering', 'ena', 'ANALYSIS', analysis_accession, value=analysis_accession)
vcf_file_list = []
index_file_dict = {}
for fn in filenames:
if not fn.endswith('.vcf.gz') and not fn.endswith('.vcf.gz.tbi'):
self.warning(f'Ignoring {fn} because it is not a VCF or an index')
continue
try:
full_path = self.find_local_file(fn)
except FileNotFoundError:
full_path = self.find_file_on_ena(fn, analysis_accession)
if full_path.endswith('.vcf.gz.tbi'):
# Store with the basename of the VCF file for easy retrieval
index_file_dict[os.path.basename(full_path)[:-4]] = full_path
else:
vcf_file_list.append(full_path)
for vcf_file in vcf_file_list:
basename = os.path.basename(vcf_file)
if basename not in index_file_dict:
raise ValueError(f'Index file is missing from metadata DB for vcf {basename} analysis {analysis_accession}')
self.eload_cfg.set('brokering', 'analyses', analysis_accession, 'vcf_files', vcf_file, 'index',
value=index_file_dict.pop(basename))
# Check if there are any orphaned index
if len(index_file_dict) > 0:
raise ValueError(f'VCF file is missing from metadata DB for index {", ".join(index_file_dict.values())}'
f' for analysis {analysis_accession}')
# Using analysis_accession instead of analysis alias. This should not have any detrimental effect on
# ingestion
self.eload_cfg.set('submission', 'analyses', analysis_accession, 'vcf_files', value=vcf_file_list)
def _analysis_report(self, all_analysis):
reports = []
for analysis_accession in all_analysis:
assembly = all_analysis.get(analysis_accession).get('assembly_accession', '')
fasta = all_analysis.get(analysis_accession).get('assembly_fasta', '')
vcf_files_str = '\n'.join(all_analysis.get(analysis_accession).get('vcf_files', []))
reports.append(f"""{analysis_accession}
- Assembly: {assembly}
- Fasta file: {fasta}
- VCF file:
{vcf_files_str}""")
return '\n'.join(reports)
def report(self):
"""Collect information from the config and write the report."""
report_data = {
'project': self.eload_cfg.query('brokering', 'ena', 'PROJECT', ret_default=''),
'analyses': ', '.join(self.eload_cfg.query('brokering', 'ena', 'ANALYSIS', ret_default=[])),
'analyses_report': self._analysis_report(self.eload_cfg.query('submission', 'analyses', ret_default=[]))
}
report = """Results of backlog study preparation:
Project accession: {project}
Analysis accession(s): {analyses}
Analysis information: {analyses_report}
"""
print(report.format(**report_data))
|
import os
from os.path import join
import shutil
import subprocess
import numpy.random as npr
import numpy as np
import scipy.stats
from dipy.io.image import load_nifti, save_nifti
from dipy.io import read_bvals_bvecs
from dipy.segment.mask import median_otsu
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, recursive_response
from dipy.reconst.csdeconv import auto_response
from dipy.core.gradients import gradient_table
from util.path import absolute_path
from dataset.synth.fibercup import create_fibercup
from dataset.synth.plot import plot_track_vis
from dataset.synth.tract import Bundle, ControlPoint, Tractogram
# general configurations
base_path = '~/mitk/dnn/.dnn/datasets'
dataset_name = 'synth5'
DWI_PARAMS_FILE = 'param.ffp'
# docker paths for Fiberfox
docker_container_name = 'confident_nobel'
base_path_on_docker = '/dnn/.dnn/datasets'
fiberfox_executable = '/dnn/MitkDiffusion/MitkFiberfox.sh'
# singularity exec docker://harangju/ubuntu-mitk:latest ~/mitk2/dnn/MitkDiffusion/MitkFiberfox.sh -o ~/mitk2 -i ~/mitk2/args/tracts.fib -p ~/mitk2/args/dwi_params.ffp
def make_dir(path):
if not os.path.isdir(path):
os.makedirs(path)
return path
def copy_param_dir(src_param_dir, dest_param_dir):
if os.path.isdir(dest_param_dir):
shutil.rmtree(dest_param_dir)
shutil.copytree(src_param_dir, dest_param_dir)
class FibercupRegressionDataset:
def __init__(self, dry_run=False):
self.base_path = os.path.expanduser(base_path)
self.dry_run = dry_run
self.radius = 64
self.depth = 6
self.multiplier = 10
tractogram, self.parcels = create_fibercup(radius=self.radius, depth=self.depth, mult=self.multiplier)
self.tractogram: Tractogram = tractogram
self.tracts_path = make_dir(join(self.base_path, dataset_name, 'tracts'))
self.dwi_path = make_dir(join(self.base_path, dataset_name, 'dwi'))
self.dti_path = make_dir(join(self.base_path, dataset_name, 'dti'))
self.odf_path = make_dir(join(self.base_path, dataset_name, 'odf'))
self.param_path = join(self.base_path, dataset_name, 'params')
copy_param_dir(join(absolute_path('dataset'), 'synth', 'dwi_params'), join(self.base_path, dataset_name, 'params'))
self.flip_evecs()
def process_subject(self, sample_id):
edge = (6, 7)
self.tractogram.bundles.pop(edge, None)
shift = npr.rand()
offset = np.array([shift, 0, 0])
bundle = self.create_bundle(edge, offset)
self.tractogram.add(edge, bundle)
self.save_tract_and_label(sample_id, self.tractogram, label=shift, show_plot=False)
self.simulate_dwi(sample_id)
self.fit_dti(sample_id)
self.fit_odf(sample_id)
def generate_samples(self, num_samples):
for sample_id in range(num_samples):
self.process_subject(sample_id)
def save_tract_and_label(self, sample_id, tractogram, label, show_plot=False):
path = join(self.tracts_path, f'{sample_id}')
if not os.path.isdir(path):
os.makedirs(path)
np.savetxt(join(path, 'label.txt'), np.array([label]), fmt='%f', delimiter='')
fname = 'tracts'
offset = [self.radius, self.radius, self.depth]
tractogram.save(join(path, fname), offset)
if show_plot is True:
url_trk = join(path, fname + '.trk')
plot_track_vis(url_trk)
return join(path, fname + '.fib')
def create_bundle(self, edge, offset):
multiplier = 1
ctl_pt_variance = 5
weight = 200
radius = self.radius
depth = int(0.5 * self.depth + offset[2])
control_points = [
ControlPoint((-int(0.65 * radius + offset[0]), -int(0.3 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.5 * radius + offset[0]), -int(0.4 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.5 * radius + offset[0]), -int(0.5 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.6 * radius + offset[0]), -int(0.7 * radius + offset[1]), depth), ctl_pt_variance)
]
node0 = self.parcels.nodes[edge[0]]
node1 = self.parcels.nodes[edge[1]]
num_streams = weight * multiplier
bundle = Bundle(node0, node1, control_points, num_streams)
return bundle
def simulate_dwi(self, sample_id):
# make target directory on docker locally
path = join(self.dwi_path, f'{sample_id}')
if not os.path.isdir(path):
os.makedirs(path)
# define all paths relative to docker
dwi_base_path = base_path_on_docker
params_url = join(dwi_base_path, dataset_name, 'params', DWI_PARAMS_FILE)
tracts_url = join(dwi_base_path, dataset_name, 'tracts', f'{sample_id}', 'tracts.fib')
target_url = join(dwi_base_path, dataset_name, 'dwi', f'{sample_id}', 'data')
docker_prefix = f'/usr/local/bin/docker exec -i {docker_container_name}'
str_cmd = f'{docker_prefix} {fiberfox_executable} -o {target_url} -i {tracts_url} -p {params_url} --verbose'
subprocess.run(str_cmd, shell=True, check=True)
@staticmethod
def _perform_dti_fit(dti_params, save_tensor=False):
dti_fit_command_str = f"dtifit " \
f"-k {dti_params["data"]} " \
f"-o {dti_params["output"]} " \
f"-m {dti_params["mask"]} " \
f"-r {dti_params["bvecs"]} " \
f"-b {dti_params["bvals"]} "
if save_tensor is True:
dti_fit_command_str += '--save_tensor'
subprocess.run(dti_fit_command_str, shell=True, check=True)
@staticmethod
def get_otsu_mask(image):
b0_mask, mask = median_otsu(image, median_radius=2, numpass=1, vol_idx=np.array([0, 1, 2]))
return mask
@staticmethod
def get_mode_mask(image):
masks = np.full(image.shape, 0)
for k in range(3):
mode_k = scipy.stats.mode(image[..., k].ravel())[0][0]
masks[image[..., k] < 0.99 * mode_k] = 1
mask = np.any(masks, axis=3) * 1.
return mask
def make_mask_from_dwi(self, sample_id, strategy='mode'):
dwi_file_url = join(self.dwi_path, f'{sample_id}', 'data.nii.gz')
image, affine = load_nifti(dwi_file_url)
if strategy == 'mode':
mask = self.get_mode_mask(image)
elif strategy == 'otsu':
mask = self.get_otsu_mask(image)
else:
raise ValueError('Not implemented: unknown dwi mask type')
mask_file_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
affine = np.eye(4)
save_nifti(mask_file_url, mask, affine)
def make_mask(self, sample_id):
mask_file_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
self.parcels.save_mask(mask_file_url=mask_file_url)
def fit_dti(self, sample_id):
output_dti_path = join(self.dti_path, f'{sample_id}')
dti_params = {
'data': join(self.dwi_path, f'{sample_id}', 'data.nii.gz'),
'mask': join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz'),
'bvals': self._flipped_bvals_url(),
'bvecs': self._flipped_bvecs_url(),
'output': join(output_dti_path, 'dti')
}
if not os.path.isdir(output_dti_path):
os.makedirs(output_dti_path)
self.make_mask(sample_id)
self._perform_dti_fit(dti_params, save_tensor=True)
registered_tensor_url = join(self.dti_path, f'{sample_id}', 'dti_tensor.*')
fslconvert_command_str = f'fslchfiletype NIFTI_GZ {registered_tensor_url}'
subprocess.run(fslconvert_command_str, shell=True, check=True)
def _flipped_bvals_url(self):
return join(self.param_path, 'flipped_' + DWI_PARAMS_FILE + '.bvals')
def _flipped_bvecs_url(self):
return join(self.param_path, 'flipped_' + DWI_PARAMS_FILE + '.bvecs')
def flip_evecs(self, flips=(1, -1, 1)):
# flip eigenvectors for compatibility between Mitk Fiberfox and FSL dtifit
bvals_url = join(self.param_path, DWI_PARAMS_FILE + '.bvals')
bvecs_url = join(self.param_path, DWI_PARAMS_FILE + '.bvecs')
bvals, bvecs = read_bvals_bvecs(bvals_url, bvecs_url)
new_bvecs = bvecs @ np.diag(flips)
return self.save_bvals_bvecs(bvals, new_bvecs)
def save_bvals_bvecs(self, bvals, bvecs):
np.savetxt(self._flipped_bvals_url(), np.expand_dims(bvals, axis=0), fmt='%d', delimiter=' ')
np.savetxt(self._flipped_bvecs_url(), bvecs.T, fmt='%2.6f', delimiter=' ')
def fit_odf(self, sample_id):
# bvals_url = self._flipped_bvals_url()
# bvecs_url = self._flipped_bvecs_url()
bvals_url = join(self.param_path, DWI_PARAMS_FILE + '.bvals')
bvecs_url = join(self.param_path, DWI_PARAMS_FILE + '.bvecs')
bvals, bvecs = read_bvals_bvecs(bvals_url, bvecs_url)
gtab = gradient_table(bvals, bvecs)
volumes_url = join(self.dwi_path, f'{sample_id}', 'data.nii.gz')
volumes, volumes_affine = load_nifti(volumes_url)
response, ratio = auto_response(gtab, volumes, roi_center=(29, 48, 2), roi_radius=1, fa_thr=0.24)
# response = recursive_response(gtab, volumes, sh_order=8,
# peak_thr=0.01, init_fa=0.08,
# init_trace=0.0021, iter=8, convergence=0.001,
# parallel=True)
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd_model.fit(volumes)
odf = csd_fit.shm_coeff
# mask_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
# self.make_mask(sample_id)
# mask, affine = load_nifti(mask_url)
# odf_masked = (odf.transpose((3, 0, 1, 2)) * mask).transpose((1, 2, 3, 0))
odf_masked = odf
output_odf_path = join(self.odf_path, f'{sample_id}')
if not os.path.isdir(output_odf_path):
os.makedirs(output_odf_path)
odf_url = join(output_odf_path, 'odf.nii.gz')
save_nifti(odf_url, odf_masked, volumes_affine)
if __name__ == '__main__':
number_of_samples = 2
dataset = FibercupRegressionDataset()
dataset.generate_samples(number_of_samples)
| import os
from os.path import join
import shutil
import subprocess
import numpy.random as npr
import numpy as np
import scipy.stats
from dipy.io.image import load_nifti, save_nifti
from dipy.io import read_bvals_bvecs
from dipy.segment.mask import median_otsu
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, recursive_response
from dipy.reconst.csdeconv import auto_response
from dipy.core.gradients import gradient_table
from util.path import absolute_path
from dataset.synth.fibercup import create_fibercup
from dataset.synth.plot import plot_track_vis
from dataset.synth.tract import Bundle, ControlPoint, Tractogram
# general configurations
base_path = '~/mitk/dnn/.dnn/datasets'
dataset_name = 'synth5'
DWI_PARAMS_FILE = 'param.ffp'
# docker paths for Fiberfox
docker_container_name = 'confident_nobel'
base_path_on_docker = '/dnn/.dnn/datasets'
fiberfox_executable = '/dnn/MitkDiffusion/MitkFiberfox.sh'
# singularity exec docker://harangju/ubuntu-mitk:latest ~/mitk2/dnn/MitkDiffusion/MitkFiberfox.sh -o ~/mitk2 -i ~/mitk2/args/tracts.fib -p ~/mitk2/args/dwi_params.ffp
def make_dir(path):
if not os.path.isdir(path):
os.makedirs(path)
return path
def copy_param_dir(src_param_dir, dest_param_dir):
if os.path.isdir(dest_param_dir):
shutil.rmtree(dest_param_dir)
shutil.copytree(src_param_dir, dest_param_dir)
class FibercupRegressionDataset:
def __init__(self, dry_run=False):
self.base_path = os.path.expanduser(base_path)
self.dry_run = dry_run
self.radius = 64
self.depth = 6
self.multiplier = 10
tractogram, self.parcels = create_fibercup(radius=self.radius, depth=self.depth, mult=self.multiplier)
self.tractogram: Tractogram = tractogram
self.tracts_path = make_dir(join(self.base_path, dataset_name, 'tracts'))
self.dwi_path = make_dir(join(self.base_path, dataset_name, 'dwi'))
self.dti_path = make_dir(join(self.base_path, dataset_name, 'dti'))
self.odf_path = make_dir(join(self.base_path, dataset_name, 'odf'))
self.param_path = join(self.base_path, dataset_name, 'params')
copy_param_dir(join(absolute_path('dataset'), 'synth', 'dwi_params'), join(self.base_path, dataset_name, 'params'))
self.flip_evecs()
def process_subject(self, sample_id):
edge = (6, 7)
self.tractogram.bundles.pop(edge, None)
shift = npr.rand()
offset = np.array([shift, 0, 0])
bundle = self.create_bundle(edge, offset)
self.tractogram.add(edge, bundle)
self.save_tract_and_label(sample_id, self.tractogram, label=shift, show_plot=False)
self.simulate_dwi(sample_id)
self.fit_dti(sample_id)
self.fit_odf(sample_id)
def generate_samples(self, num_samples):
for sample_id in range(num_samples):
self.process_subject(sample_id)
def save_tract_and_label(self, sample_id, tractogram, label, show_plot=False):
path = join(self.tracts_path, f'{sample_id}')
if not os.path.isdir(path):
os.makedirs(path)
np.savetxt(join(path, 'label.txt'), np.array([label]), fmt='%f', delimiter='')
fname = 'tracts'
offset = [self.radius, self.radius, self.depth]
tractogram.save(join(path, fname), offset)
if show_plot is True:
url_trk = join(path, fname + '.trk')
plot_track_vis(url_trk)
return join(path, fname + '.fib')
def create_bundle(self, edge, offset):
multiplier = 1
ctl_pt_variance = 5
weight = 200
radius = self.radius
depth = int(0.5 * self.depth + offset[2])
control_points = [
ControlPoint((-int(0.65 * radius + offset[0]), -int(0.3 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.5 * radius + offset[0]), -int(0.4 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.5 * radius + offset[0]), -int(0.5 * radius + offset[1]), depth), ctl_pt_variance),
ControlPoint((-int(0.6 * radius + offset[0]), -int(0.7 * radius + offset[1]), depth), ctl_pt_variance)
]
node0 = self.parcels.nodes[edge[0]]
node1 = self.parcels.nodes[edge[1]]
num_streams = weight * multiplier
bundle = Bundle(node0, node1, control_points, num_streams)
return bundle
def simulate_dwi(self, sample_id):
# make target directory on docker locally
path = join(self.dwi_path, f'{sample_id}')
if not os.path.isdir(path):
os.makedirs(path)
# define all paths relative to docker
dwi_base_path = base_path_on_docker
params_url = join(dwi_base_path, dataset_name, 'params', DWI_PARAMS_FILE)
tracts_url = join(dwi_base_path, dataset_name, 'tracts', f'{sample_id}', 'tracts.fib')
target_url = join(dwi_base_path, dataset_name, 'dwi', f'{sample_id}', 'data')
docker_prefix = f'/usr/local/bin/docker exec -i {docker_container_name}'
str_cmd = f'{docker_prefix} {fiberfox_executable} -o {target_url} -i {tracts_url} -p {params_url} --verbose'
subprocess.run(str_cmd, shell=True, check=True)
@staticmethod
def _perform_dti_fit(dti_params, save_tensor=False):
dti_fit_command_str = f"dtifit " \
f"-k {dti_params['data']} " \
f"-o {dti_params['output']} " \
f"-m {dti_params['mask']} " \
f"-r {dti_params['bvecs']} " \
f"-b {dti_params['bvals']} "
if save_tensor is True:
dti_fit_command_str += '--save_tensor'
subprocess.run(dti_fit_command_str, shell=True, check=True)
@staticmethod
def get_otsu_mask(image):
b0_mask, mask = median_otsu(image, median_radius=2, numpass=1, vol_idx=np.array([0, 1, 2]))
return mask
@staticmethod
def get_mode_mask(image):
masks = np.full(image.shape, 0)
for k in range(3):
mode_k = scipy.stats.mode(image[..., k].ravel())[0][0]
masks[image[..., k] < 0.99 * mode_k] = 1
mask = np.any(masks, axis=3) * 1.
return mask
def make_mask_from_dwi(self, sample_id, strategy='mode'):
dwi_file_url = join(self.dwi_path, f'{sample_id}', 'data.nii.gz')
image, affine = load_nifti(dwi_file_url)
if strategy == 'mode':
mask = self.get_mode_mask(image)
elif strategy == 'otsu':
mask = self.get_otsu_mask(image)
else:
raise ValueError('Not implemented: unknown dwi mask type')
mask_file_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
affine = np.eye(4)
save_nifti(mask_file_url, mask, affine)
def make_mask(self, sample_id):
mask_file_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
self.parcels.save_mask(mask_file_url=mask_file_url)
def fit_dti(self, sample_id):
output_dti_path = join(self.dti_path, f'{sample_id}')
dti_params = {
'data': join(self.dwi_path, f'{sample_id}', 'data.nii.gz'),
'mask': join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz'),
'bvals': self._flipped_bvals_url(),
'bvecs': self._flipped_bvecs_url(),
'output': join(output_dti_path, 'dti')
}
if not os.path.isdir(output_dti_path):
os.makedirs(output_dti_path)
self.make_mask(sample_id)
self._perform_dti_fit(dti_params, save_tensor=True)
registered_tensor_url = join(self.dti_path, f'{sample_id}', 'dti_tensor.*')
fslconvert_command_str = f'fslchfiletype NIFTI_GZ {registered_tensor_url}'
subprocess.run(fslconvert_command_str, shell=True, check=True)
def _flipped_bvals_url(self):
return join(self.param_path, 'flipped_' + DWI_PARAMS_FILE + '.bvals')
def _flipped_bvecs_url(self):
return join(self.param_path, 'flipped_' + DWI_PARAMS_FILE + '.bvecs')
def flip_evecs(self, flips=(1, -1, 1)):
# flip eigenvectors for compatibility between Mitk Fiberfox and FSL dtifit
bvals_url = join(self.param_path, DWI_PARAMS_FILE + '.bvals')
bvecs_url = join(self.param_path, DWI_PARAMS_FILE + '.bvecs')
bvals, bvecs = read_bvals_bvecs(bvals_url, bvecs_url)
new_bvecs = bvecs @ np.diag(flips)
return self.save_bvals_bvecs(bvals, new_bvecs)
def save_bvals_bvecs(self, bvals, bvecs):
np.savetxt(self._flipped_bvals_url(), np.expand_dims(bvals, axis=0), fmt='%d', delimiter=' ')
np.savetxt(self._flipped_bvecs_url(), bvecs.T, fmt='%2.6f', delimiter=' ')
def fit_odf(self, sample_id):
# bvals_url = self._flipped_bvals_url()
# bvecs_url = self._flipped_bvecs_url()
bvals_url = join(self.param_path, DWI_PARAMS_FILE + '.bvals')
bvecs_url = join(self.param_path, DWI_PARAMS_FILE + '.bvecs')
bvals, bvecs = read_bvals_bvecs(bvals_url, bvecs_url)
gtab = gradient_table(bvals, bvecs)
volumes_url = join(self.dwi_path, f'{sample_id}', 'data.nii.gz')
volumes, volumes_affine = load_nifti(volumes_url)
response, ratio = auto_response(gtab, volumes, roi_center=(29, 48, 2), roi_radius=1, fa_thr=0.24)
# response = recursive_response(gtab, volumes, sh_order=8,
# peak_thr=0.01, init_fa=0.08,
# init_trace=0.0021, iter=8, convergence=0.001,
# parallel=True)
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd_model.fit(volumes)
odf = csd_fit.shm_coeff
# mask_url = join(self.dwi_path, f'{sample_id}', 'data_mask.nii.gz')
# self.make_mask(sample_id)
# mask, affine = load_nifti(mask_url)
# odf_masked = (odf.transpose((3, 0, 1, 2)) * mask).transpose((1, 2, 3, 0))
odf_masked = odf
output_odf_path = join(self.odf_path, f'{sample_id}')
if not os.path.isdir(output_odf_path):
os.makedirs(output_odf_path)
odf_url = join(output_odf_path, 'odf.nii.gz')
save_nifti(odf_url, odf_masked, volumes_affine)
if __name__ == '__main__':
number_of_samples = 2
dataset = FibercupRegressionDataset()
dataset.generate_samples(number_of_samples)
|
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
import sys
from sys import platform
from pathlib import Path
from threading import Event, Thread
from time import sleep, time
from queue import Queue
from openvino.inference_engine import IENetwork, IECore, ExecutableNetwork
from conftest import model_path, plugins_path, model_onnx_path
import ngraph as ng
test_net_xml, test_net_bin = model_path()
test_net_onnx = model_onnx_path()
plugins_xml, plugins_win_xml, plugins_osx_xml = plugins_path()
def test_init_ie_core_no_cfg():
ie = IECore()
assert isinstance(ie, IECore)
def test_init_ie_core_with_cfg():
ie = IECore(plugins_xml)
assert isinstance(ie, IECore)
def test_get_version(device):
ie = IECore()
version = ie.get_versions(device)
assert isinstance(version, dict), "Returned version must be a dictionary"
assert device in version, "{} plugin version wasn't found in versions"
assert hasattr(version[device], "major"), "Returned version has no field 'major'"
assert hasattr(version[device], "minor"), "Returned version has no field 'minor'"
assert hasattr(version[device], "description"), "Returned version has no field 'description'"
assert hasattr(version[device], "build_number"), "Returned version has no field 'build_number'"
def test_load_network(device):
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, device)
assert isinstance(exec_net, ExecutableNetwork)
def test_load_network_from_file(device):
ie = IECore()
exec_net = ie.load_network(test_net_xml, device)
assert isinstance(exec_net, ExecutableNetwork)
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device independent test")
def test_load_network_wrong_device():
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
with pytest.raises(RuntimeError) as e:
ie.load_network(net, "BLA")
assert 'Device with "BLA" name is not registered in the InferenceEngine' in str(e.value)
def test_query_network(device):
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
query_res = ie.query_network(net, device)
func_net = ng.function_from_cnn(net)
ops_net = func_net.get_ordered_ops()
ops_net_names = [op.friendly_name for op in ops_net]
assert [key for key in query_res.keys() if key not in ops_net_names] == [], \
"Not all network layers present in query_network results"
assert next(iter(set(query_res.values()))) == device, "Wrong device for some layers"
@pytest.mark.dynamic_library
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device dependent test")
def test_register_plugin():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to MKLDNNPlugin specific test")
ie.register_plugin("MKLDNNPlugin", "BLA")
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, "BLA")
assert isinstance(exec_net, ExecutableNetwork), "Cannot load the network to the registered plugin with name 'BLA'"
@pytest.mark.dynamic_library
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device dependent test")
def test_register_plugins():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to MKLDNNPlugin specific test")
if platform == "linux" or platform == "linux2":
ie.register_plugins(plugins_xml)
elif platform == "darwin":
ie.register_plugins(plugins_osx_xml)
elif platform == "win32":
ie.register_plugins(plugins_win_xml)
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, "CUSTOM")
assert isinstance(exec_net,
ExecutableNetwork), "Cannot load the network to the registered plugin with name 'CUSTOM' " \
"registred in the XML file"
@pytest.mark.skip(reason="Need to figure out if it's expected behaviour (fails with C++ API as well")
def test_unregister_plugin(device):
ie = IECore()
ie.unregister_plugin(device)
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
with pytest.raises(RuntimeError) as e:
ie.load_network(net, device)
assert f"Device with '{device}' name is not registered in the InferenceEngine" in str(e.value)
def test_available_devices(device):
ie = IECore()
devices = ie.available_devices
assert device in devices, f"Current device '{device}" is not listed in available devices "{", ".join(devices)}'"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get("TEST_DEVICE")}, Plugin specific test")
def test_get_metric_list_of_str():
ie = IECore()
param = ie.get_metric("CPU", "OPTIMIZATION_CAPABILITIES")
assert isinstance(param, list), "Parameter value for 'OPTIMIZATION_CAPABILITIES' " \
f"metric must be a list but {type(param)} is returned"
assert all(isinstance(v, str) for v in param), "Not all of the parameter values for 'OPTIMIZATION_CAPABILITIES' " \
"metric are strings!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get("TEST_DEVICE")}, Plugin specific test")
def test_get_metric_tuple_of_two_ints():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to unsupported device metric")
param = ie.get_metric("CPU", "RANGE_FOR_STREAMS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_STREAMS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), "Not all of the parameter values for 'RANGE_FOR_STREAMS' " \
"metric are integers!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get("TEST_DEVICE")}, Plugin specific test")
def test_get_metric_tuple_of_three_ints():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to unsupported device metric")
param = ie.get_metric("CPU", "RANGE_FOR_ASYNC_INFER_REQUESTS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_ASYNC_INFER_REQUESTS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), "Not all of the parameter values for " \
"'RANGE_FOR_ASYNC_INFER_REQUESTS' metric are integers!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get("TEST_DEVICE")}, Plugin specific test")
def test_get_metric_str():
ie = IECore()
param = ie.get_metric("CPU", "FULL_DEVICE_NAME")
assert isinstance(param, str), "Parameter value for 'FULL_DEVICE_NAME' " \
f"metric must be string but {type(param)} is returned"
def test_read_network_from_xml():
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
assert isinstance(net, IENetwork)
net = ie.read_network(model=test_net_xml)
assert isinstance(net, IENetwork)
def test_read_network_as_path():
ie = IECore()
net = ie.read_network(model=Path(test_net_xml), weights=test_net_bin)
assert isinstance(net, IENetwork)
net = ie.read_network(model=test_net_xml, weights=Path(test_net_bin))
assert isinstance(net, IENetwork)
net = ie.read_network(model=Path(test_net_xml))
assert isinstance(net, IENetwork)
def test_read_network_from_onnx():
ie = IECore()
net = ie.read_network(model=test_net_onnx)
assert isinstance(net, IENetwork)
def test_read_network_from_onnx_as_path():
ie = IECore()
net = ie.read_network(model=Path(test_net_onnx))
assert isinstance(net, IENetwork)
def test_incorrect_xml():
ie = IECore()
with pytest.raises(Exception) as e:
ie.read_network(model="./model.xml", weights=Path(test_net_bin))
assert "Path to the model ./model.xml doesn't exist or it's a directory" in str(e.value)
def test_incorrect_bin():
ie = IECore()
with pytest.raises(Exception) as e:
ie.read_network(model=test_net_xml, weights="./model.bin")
assert "Path to the weights ./model.bin doesn't exist or it's a directory" in str(e.value)
def test_read_net_from_buffer():
ie = IECore()
with open(test_net_bin, 'rb') as f:
bin = f.read()
with open(model_path()[0], 'rb') as f:
xml = f.read()
net = ie.read_network(model=xml, weights=bin, init_from_buffer=True)
assert isinstance(net, IENetwork)
def test_net_from_buffer_valid():
ie = IECore()
with open(test_net_bin, 'rb') as f:
bin = f.read()
with open(model_path()[0], 'rb') as f:
xml = f.read()
net = ie.read_network(model=xml, weights=bin, init_from_buffer=True)
ref_net = ie.read_network(model=test_net_xml, weights=test_net_bin)
assert net.name == ref_net.name
assert net.batch_size == ref_net.batch_size
ii_net = net.input_info
ii_net2 = ref_net.input_info
o_net = net.outputs
o_net2 = ref_net.outputs
assert ii_net.keys() == ii_net2.keys()
assert o_net.keys() == o_net2.keys()
@pytest.mark.skipif(os.environ.get("TEST_DEVICE","CPU") != "GPU", reason=f"Device dependent test")
def test_load_network_release_gil(device):
running = True
message_queue = Queue()
def detect_long_gil_holds():
sleep_time = 0.01
latency_alert_threshold = 0.1
# Send a message to indicate the thread is running and ready to detect GIL locks
message_queue.put("ready to detect")
while running:
start_sleep = time()
sleep(sleep_time)
elapsed = time() - start_sleep
if elapsed > latency_alert_threshold:
# Send a message to the testing thread that a long GIL lock occurred
message_queue.put(latency_alert_threshold)
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
# Wait for the GIL lock detector to be up and running
gil_hold_detection_thread = Thread(daemon=True, target=detect_long_gil_holds)
gil_hold_detection_thread.start()
# Wait to make sure the thread is started and checking for GIL holds
sleep(0.1)
assert message_queue.get(timeout=5) == "ready to detect"
# Run the function that should unlock the GIL
exec_net = ie.load_network(net, device)
# Ensure resources are closed
running = False
gil_hold_detection_thread.join(timeout=5)
# Assert there were never any long gil locks
assert message_queue.qsize() == 0, \
f"More than 0 GIL locks occured! Latency: {message_queue.get()})"
def test_nogil_safe(device):
call_thread_func = Event()
switch_interval = sys.getswitchinterval()
core = IECore()
net = core.read_network(model=test_net_xml, weights=test_net_bin)
def thread_target(thread_func, thread_args):
call_thread_func.wait()
call_thread_func.clear()
thread_func(*thread_args)
def main_thread_target(gil_release_func, args):
call_thread_func.set()
gil_release_func(*args)
def test_run_parallel(gil_release_func, args, thread_func, thread_args):
thread = Thread(target=thread_target, args=[thread_func, thread_args])
sys.setswitchinterval(1000)
thread.start()
main_thread_target(gil_release_func, args)
thread.join()
sys.setswitchinterval(switch_interval)
main_targets = [{
core.read_network: [test_net_xml, test_net_bin],
core.load_network: [net, device],
},
{
core.load_network: [net, device],
}]
thread_targets = [{
core.get_versions: [device,],
core.read_network: [test_net_xml, test_net_bin],
core.load_network: [net, device],
core.query_network: [net, device],
getattr: [core, "available_devices"],
},
{
getattr: [net, "name"],
getattr: [net, "input_info"],
getattr: [net, "outputs"],
getattr: [net, "batch_size"],
}]
for main_target, custom_target in zip(main_targets, thread_targets):
for nogil_func, args in main_target.items():
for thread_func, thread_args in custom_target.items():
test_run_parallel(nogil_func, args, thread_func, thread_args)
| # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
import sys
from sys import platform
from pathlib import Path
from threading import Event, Thread
from time import sleep, time
from queue import Queue
from openvino.inference_engine import IENetwork, IECore, ExecutableNetwork
from conftest import model_path, plugins_path, model_onnx_path
import ngraph as ng
test_net_xml, test_net_bin = model_path()
test_net_onnx = model_onnx_path()
plugins_xml, plugins_win_xml, plugins_osx_xml = plugins_path()
def test_init_ie_core_no_cfg():
ie = IECore()
assert isinstance(ie, IECore)
def test_init_ie_core_with_cfg():
ie = IECore(plugins_xml)
assert isinstance(ie, IECore)
def test_get_version(device):
ie = IECore()
version = ie.get_versions(device)
assert isinstance(version, dict), "Returned version must be a dictionary"
assert device in version, "{} plugin version wasn't found in versions"
assert hasattr(version[device], "major"), "Returned version has no field 'major'"
assert hasattr(version[device], "minor"), "Returned version has no field 'minor'"
assert hasattr(version[device], "description"), "Returned version has no field 'description'"
assert hasattr(version[device], "build_number"), "Returned version has no field 'build_number'"
def test_load_network(device):
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, device)
assert isinstance(exec_net, ExecutableNetwork)
def test_load_network_from_file(device):
ie = IECore()
exec_net = ie.load_network(test_net_xml, device)
assert isinstance(exec_net, ExecutableNetwork)
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device independent test")
def test_load_network_wrong_device():
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
with pytest.raises(RuntimeError) as e:
ie.load_network(net, "BLA")
assert 'Device with "BLA" name is not registered in the InferenceEngine' in str(e.value)
def test_query_network(device):
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
query_res = ie.query_network(net, device)
func_net = ng.function_from_cnn(net)
ops_net = func_net.get_ordered_ops()
ops_net_names = [op.friendly_name for op in ops_net]
assert [key for key in query_res.keys() if key not in ops_net_names] == [], \
"Not all network layers present in query_network results"
assert next(iter(set(query_res.values()))) == device, "Wrong device for some layers"
@pytest.mark.dynamic_library
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device dependent test")
def test_register_plugin():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to MKLDNNPlugin specific test")
ie.register_plugin("MKLDNNPlugin", "BLA")
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, "BLA")
assert isinstance(exec_net, ExecutableNetwork), "Cannot load the network to the registered plugin with name 'BLA'"
@pytest.mark.dynamic_library
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device dependent test")
def test_register_plugins():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to MKLDNNPlugin specific test")
if platform == "linux" or platform == "linux2":
ie.register_plugins(plugins_xml)
elif platform == "darwin":
ie.register_plugins(plugins_osx_xml)
elif platform == "win32":
ie.register_plugins(plugins_win_xml)
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
exec_net = ie.load_network(net, "CUSTOM")
assert isinstance(exec_net,
ExecutableNetwork), "Cannot load the network to the registered plugin with name 'CUSTOM' " \
"registred in the XML file"
@pytest.mark.skip(reason="Need to figure out if it's expected behaviour (fails with C++ API as well")
def test_unregister_plugin(device):
ie = IECore()
ie.unregister_plugin(device)
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
with pytest.raises(RuntimeError) as e:
ie.load_network(net, device)
assert f"Device with '{device}' name is not registered in the InferenceEngine" in str(e.value)
def test_available_devices(device):
ie = IECore()
devices = ie.available_devices
assert device in devices, f"Current device '{device}' is not listed in available devices '{', '.join(devices)}'"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
def test_get_metric_list_of_str():
ie = IECore()
param = ie.get_metric("CPU", "OPTIMIZATION_CAPABILITIES")
assert isinstance(param, list), "Parameter value for 'OPTIMIZATION_CAPABILITIES' " \
f"metric must be a list but {type(param)} is returned"
assert all(isinstance(v, str) for v in param), "Not all of the parameter values for 'OPTIMIZATION_CAPABILITIES' " \
"metric are strings!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
def test_get_metric_tuple_of_two_ints():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to unsupported device metric")
param = ie.get_metric("CPU", "RANGE_FOR_STREAMS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_STREAMS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), "Not all of the parameter values for 'RANGE_FOR_STREAMS' " \
"metric are integers!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
def test_get_metric_tuple_of_three_ints():
ie = IECore()
if ie.get_metric("CPU", "FULL_DEVICE_NAME") == "arm_compute::NEON":
pytest.skip("Can't run on ARM plugin due-to unsupported device metric")
param = ie.get_metric("CPU", "RANGE_FOR_ASYNC_INFER_REQUESTS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_ASYNC_INFER_REQUESTS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), "Not all of the parameter values for " \
"'RANGE_FOR_ASYNC_INFER_REQUESTS' metric are integers!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
def test_get_metric_str():
ie = IECore()
param = ie.get_metric("CPU", "FULL_DEVICE_NAME")
assert isinstance(param, str), "Parameter value for 'FULL_DEVICE_NAME' " \
f"metric must be string but {type(param)} is returned"
def test_read_network_from_xml():
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
assert isinstance(net, IENetwork)
net = ie.read_network(model=test_net_xml)
assert isinstance(net, IENetwork)
def test_read_network_as_path():
ie = IECore()
net = ie.read_network(model=Path(test_net_xml), weights=test_net_bin)
assert isinstance(net, IENetwork)
net = ie.read_network(model=test_net_xml, weights=Path(test_net_bin))
assert isinstance(net, IENetwork)
net = ie.read_network(model=Path(test_net_xml))
assert isinstance(net, IENetwork)
def test_read_network_from_onnx():
ie = IECore()
net = ie.read_network(model=test_net_onnx)
assert isinstance(net, IENetwork)
def test_read_network_from_onnx_as_path():
ie = IECore()
net = ie.read_network(model=Path(test_net_onnx))
assert isinstance(net, IENetwork)
def test_incorrect_xml():
ie = IECore()
with pytest.raises(Exception) as e:
ie.read_network(model="./model.xml", weights=Path(test_net_bin))
assert "Path to the model ./model.xml doesn't exist or it's a directory" in str(e.value)
def test_incorrect_bin():
ie = IECore()
with pytest.raises(Exception) as e:
ie.read_network(model=test_net_xml, weights="./model.bin")
assert "Path to the weights ./model.bin doesn't exist or it's a directory" in str(e.value)
def test_read_net_from_buffer():
ie = IECore()
with open(test_net_bin, 'rb') as f:
bin = f.read()
with open(model_path()[0], 'rb') as f:
xml = f.read()
net = ie.read_network(model=xml, weights=bin, init_from_buffer=True)
assert isinstance(net, IENetwork)
def test_net_from_buffer_valid():
ie = IECore()
with open(test_net_bin, 'rb') as f:
bin = f.read()
with open(model_path()[0], 'rb') as f:
xml = f.read()
net = ie.read_network(model=xml, weights=bin, init_from_buffer=True)
ref_net = ie.read_network(model=test_net_xml, weights=test_net_bin)
assert net.name == ref_net.name
assert net.batch_size == ref_net.batch_size
ii_net = net.input_info
ii_net2 = ref_net.input_info
o_net = net.outputs
o_net2 = ref_net.outputs
assert ii_net.keys() == ii_net2.keys()
assert o_net.keys() == o_net2.keys()
@pytest.mark.skipif(os.environ.get("TEST_DEVICE","CPU") != "GPU", reason=f"Device dependent test")
def test_load_network_release_gil(device):
running = True
message_queue = Queue()
def detect_long_gil_holds():
sleep_time = 0.01
latency_alert_threshold = 0.1
# Send a message to indicate the thread is running and ready to detect GIL locks
message_queue.put("ready to detect")
while running:
start_sleep = time()
sleep(sleep_time)
elapsed = time() - start_sleep
if elapsed > latency_alert_threshold:
# Send a message to the testing thread that a long GIL lock occurred
message_queue.put(latency_alert_threshold)
ie = IECore()
net = ie.read_network(model=test_net_xml, weights=test_net_bin)
# Wait for the GIL lock detector to be up and running
gil_hold_detection_thread = Thread(daemon=True, target=detect_long_gil_holds)
gil_hold_detection_thread.start()
# Wait to make sure the thread is started and checking for GIL holds
sleep(0.1)
assert message_queue.get(timeout=5) == "ready to detect"
# Run the function that should unlock the GIL
exec_net = ie.load_network(net, device)
# Ensure resources are closed
running = False
gil_hold_detection_thread.join(timeout=5)
# Assert there were never any long gil locks
assert message_queue.qsize() == 0, \
f"More than 0 GIL locks occured! Latency: {message_queue.get()})"
def test_nogil_safe(device):
call_thread_func = Event()
switch_interval = sys.getswitchinterval()
core = IECore()
net = core.read_network(model=test_net_xml, weights=test_net_bin)
def thread_target(thread_func, thread_args):
call_thread_func.wait()
call_thread_func.clear()
thread_func(*thread_args)
def main_thread_target(gil_release_func, args):
call_thread_func.set()
gil_release_func(*args)
def test_run_parallel(gil_release_func, args, thread_func, thread_args):
thread = Thread(target=thread_target, args=[thread_func, thread_args])
sys.setswitchinterval(1000)
thread.start()
main_thread_target(gil_release_func, args)
thread.join()
sys.setswitchinterval(switch_interval)
main_targets = [{
core.read_network: [test_net_xml, test_net_bin],
core.load_network: [net, device],
},
{
core.load_network: [net, device],
}]
thread_targets = [{
core.get_versions: [device,],
core.read_network: [test_net_xml, test_net_bin],
core.load_network: [net, device],
core.query_network: [net, device],
getattr: [core, "available_devices"],
},
{
getattr: [net, "name"],
getattr: [net, "input_info"],
getattr: [net, "outputs"],
getattr: [net, "batch_size"],
}]
for main_target, custom_target in zip(main_targets, thread_targets):
for nogil_func, args in main_target.items():
for thread_func, thread_args in custom_target.items():
test_run_parallel(nogil_func, args, thread_func, thread_args)
|
import json
import requests
import os
import csv
class MakeDataSet:
def __init__(self,data):
self.data = data
self.fileType = ""
self.logError = {
"errorVoc" : [],
"errorId" : [],
"errReport" : []
}
#
# errorVoc format => {
# "yearType" : ___
# "vocType" : ___
# }
# errorId format => {
# "id" : ___
# "yearType" : ___
# "vocType" : ___
# }
# proccess data to folder
def makeEachVocFolder(self,bfFolder,yearType,num):
folderName = f"{bfFolder}/{yearType}_{num}" if num != 0 else f"{bfFolder}/{yearType}"
print()
print(f"[!] begin to create folder {folderName}")
if os.path.exists(folderName):
print(f"[x] {folderName} already taken")
return self.makeEachVocFolder(bfFolder,yearType,num+1)
os.mkdir(folderName)
print(f"[✓] successfully created folder {folderName}")
return folderName
def makeItJson(self,pathFile,dtToCreate):
with open(pathFile,"w") as fileJson:
dumped = json.dumps(dtToCreate,indent=4)
fileJson.write(dumped)
fileJson.close()
return True
def makeItCsv(self,pathFile,dtToCreate):
with open(pathFile,"w",encoding="UTF-8",newline='') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames=dtToCreate["head"])
writer.writeheader()
writer.writerows(dtToCreate["data"])
return True
def makeEachDataSet(self,data,folderName):
print("[!] begin to create each json file")
tobeMergedAll = {
"id" : [],
"name": [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"head" : [],
"data" : []
}
for item in data:
if item["data"]:
folderYearPath = self.makeEachVocFolder(folderName,item["typeYear"],0)
tobeMergedEachVoc = {
"id" : [],
"name": [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"head" : item["head"],
"data" : []
}
for subitem in item["data"]:
if subitem["error"] == False:
if self.fileType == "json":
jsonFile = {
"id" : subitem["id"],
"name" : subitem["name"],
"gender" : subitem["gender"],
"school" : subitem["school"],
"kec" : subitem["kec"],
"kel" : subitem["kel"]
}
tobeMergedEachVoc["id"] = tobeMergedEachVoc["id"] + subitem["id"]
tobeMergedEachVoc["name"] = tobeMergedEachVoc["name"] + subitem["name"]
tobeMergedEachVoc["gender"] = tobeMergedEachVoc["gender"] + subitem["gender"]
tobeMergedEachVoc["school"] = tobeMergedEachVoc["school"] + subitem["school"]
tobeMergedEachVoc["kec"] = tobeMergedEachVoc["kec"] + subitem["kec"]
tobeMergedEachVoc["kel"] = tobeMergedEachVoc["kel"] + subitem["kel"]
fileName = f"{subitem["vocType"]}-{item["typeYear"]}.json"
subitemJson = self.makeItJson(f"{folderYearPath}/{fileName}",jsonFile)
if subitemJson:
print(f" ➥ [✓] {fileName} successfully created")
else:
tobeMergedEachVoc["data"] = tobeMergedEachVoc["data"] + subitem["csvData"]
fileName = f"{subitem["vocType"]}-{item["typeYear"]}.csv"
subitemCsv = self.makeItCsv(f"{folderYearPath}/{fileName}",{
"head" : item["head"],
"data" : subitem["csvData"]
})
if subitemCsv:
print(f" ➥ [✓] {fileName} successfully created")
mergedJson = self.makeItJson(f"{folderYearPath}/merged-{item["typeYear"]}.json",tobeMergedEachVoc) if self.fileType == "json" else self.makeItCsv(f"{folderYearPath}/merged-{item["typeYear"]}.csv",tobeMergedEachVoc)
if mergedJson:
print(f" ➥ [✓] succesfully merged data and create merged-{item["typeYear"]}")
if self.fileType == "json":
tobeMergedAll["id"] = tobeMergedAll["id"] + tobeMergedEachVoc["id"]
tobeMergedAll["name"] = tobeMergedAll["name"] + tobeMergedEachVoc["name"]
tobeMergedAll["gender"] = tobeMergedAll["gender"] + tobeMergedEachVoc["gender"]
tobeMergedAll["school"] = tobeMergedAll["school"] + tobeMergedEachVoc["school"]
tobeMergedAll["kec"] = tobeMergedAll["kec"] + tobeMergedEachVoc["kec"]
tobeMergedAll["kel"] = tobeMergedAll["kel"] + tobeMergedEachVoc["kel"]
else:
tobeMergedAll["head"] = tobeMergedEachVoc["head"]
tobeMergedAll["data"] = tobeMergedAll["data"] + tobeMergedEachVoc["data"]
mergedAll = self.makeItJson(f"{folderName}/all-merged.json",tobeMergedAll) if self.fileType == "json" else self.makeItCsv(f"{folderName}/all-merged.csv",tobeMergedAll)
if mergedAll:
print(f"[✓] Successfully Merged All Data To One {self.fileType} File")
return True
def makeFolderMain(self,name,num):
folderName = f"{name}_{num}"
print(f"[!] begin creating folder {folderName}")
if os.path.exists(folderName):
print(f"[x] {folderName} already taken")
return self.makeFolderMain(name,num+1)
os.mkdir(folderName)
print(f"[✓] successfully created folder {folderName}")
return folderName
# make Data from requested API
def eachDataHandler(self,studentList,yearType,vocType):
yearType = "current" if yearType == "testing" else yearType #for testing only
apiLink = "https://api.siap-ppdb.com/cari?no_daftar=" if yearType == "current" else f"https://arsip.siap-ppdb.com/{yearType}/api/cari?no_daftar="
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Host": "arsip.siap-ppdb.com",
"Referer": "https://arsip.siap-ppdb.com/2020/jakarta/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"Sec-GPC": "1",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" # add your own userAgent
}
dataBucket = {
"vocType" :vocType,
"error" : False,
"id" : [],
"name" : [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"vocType" : vocType,
"error" : False,
"csvData" : []
}
for studentId in studentList:
try:
req = requests.get(f"{apiLink}{studentId}",timeout=3) if yearType == "current" else requests.get(f"{apiLink}{studentId}",timeout=3,headers=headers)
jsoned = req.json()
splittedkecKel = jsoned[0][3][5][3].split(",")
kelData = splittedkecKel[1][1:]
kecData = splittedkecKel[2][1:]
nameData = jsoned[0][3][2][-1]
genderData = jsoned[0][3][3][-2]
schoolData = jsoned[0][3][6][3]
if jsoned[-1][3][3][-1] != "Tidak Lapor Diri":
if self.fileType == "json":
dataBucket["id"].append(studentId)
dataBucket["name"].append(nameData)
dataBucket["gender"].append(genderData)
dataBucket["school"].append(schoolData)
dataBucket["kel"].append(kelData)
dataBucket["kec"].append(kecData)
else:
dataBucket["csvData"].append(
{
"id" : studentId,
"name" : nameData,
"gender" : genderData,
"school" : schoolData,
"kec" : kecData,
"kel" : kelData
}
)
print(f" ➥ [✓] {studentId}\t\tOK")
else:
self.logError["errReport"].append({
"id" : studentId,
"yearType" : yearType,
"vocType" : vocType
})
print(f" ➥ [x] {studentId}\t\tFalse")
except Exception as e:
self.logError["errorId"].append({
"id" : studentId,
"yearType" : yearType,
"vocType" : vocType
})
print(f" ➥ [x] {studentId}\t\tFailed")
return dataBucket
def makeReqToApi(self,arg):
afterParsed = self.data["data"] if arg == "all" else [item for item in self.data["data"] if item["yearType"] == arg]
if afterParsed:
requestBucket = []
for item in afterParsed:
afterAlleachBucket = {
"typeYear" : item["yearType"],
"head" : ["id","name","gender","school","kec","kel"],
"data" : []
}
print()
print(f"[!] proccessing {item["yearType"]}")
for subitem in item["sourceDataLink"]:
try:
print(f"\n ➤ [!] Fetching {subitem["vocType"]}")
req = requests.get(subitem["api"],timeout=3)
jsoned = req.json()
eachDataBucket = self.eachDataHandler([item[3] for item in jsoned["data"]],item["yearType"],subitem["vocType"])
afterAlleachBucket["data"].append(eachDataBucket)
except Exception as e:
afterAlleachBucket["data"].append({
"vocType" : subitem["vocType"],
"error" : True
})
self.logError["errorVoc"].append({
"yearType" : item["yearType"],
"vocType" : subitem["vocType"]
})
print(f" ➥ [x] Failed to fetch {subitem["vocType"]}\n")
requestBucket.append(afterAlleachBucket)
return requestBucket
else:
return False
def make(self,arg):
try:
while True:
q = int(input("[?] choose data type ! \n ➥ 1. json\n ➥ 2. csv\n (1/2) : "))
if q == 1:
self.fileType = "json"
break
elif q == 2:
self.fileType = "csv"
break
else:
print("[x] invalid option")
tobeReturned = self.makeReqToApi(arg)
print()
self.logger()
print()
if tobeReturned != False:
counterFailed = 0
for item in tobeReturned:
for subitem in item["data"]:
if subitem["error"] == True:
counterFailed += 1
if counterFailed == sum([len(item["data"]) for item in tobeReturned]):
print("➥[x] can't create dataset. All of connections went failed")
return False
while True:
makeFolderMain = str(input("[?] begin to make dataset (y/n) : "))
if makeFolderMain.lower() == "y":
fdName = self.makeFolderMain("outputDataSet",0)
self.makeEachDataSet(tobeReturned,fdName)
break
elif makeFolderMain == "n":
return False
else:
print("[x] invalid option")
return False
except KeyboardInterrupt:
print("\n[x] Adios")
# getter
def logger(self):
if self.logError["errorVoc"] or self.logError["errorId"] or self.logError["errReport"]:
print("\n\n\n")
print("[x] Error Data log")
if self.logError["errorVoc"]:
for item in self.logError["errorVoc"]:
print(f" ➥ [~] Can't Fetch {item["vocType"]} in {item["yearType"]} Data")
elif self.logError["errorId"]:
for itemid in self.logError["errorId"]:
print(f" ➥ [~] Cant Fetch {itemid["vocType"]}'s {itemid["id"]} in {itemid["yearType"]} Data")
elif self.logError["errReport"]:
for itemid in self.logError["errReport"]:
print(f" ➥ [~] {itemid["id"]}'s self-report status : False")
print("\n\n\n")
else:
print("[✓] No Log To Be Displayed,All Data Successfully Fetched") | import json
import requests
import os
import csv
class MakeDataSet:
def __init__(self,data):
self.data = data
self.fileType = ""
self.logError = {
"errorVoc" : [],
"errorId" : [],
"errReport" : []
}
#
# errorVoc format => {
# "yearType" : ___
# "vocType" : ___
# }
# errorId format => {
# "id" : ___
# "yearType" : ___
# "vocType" : ___
# }
# proccess data to folder
def makeEachVocFolder(self,bfFolder,yearType,num):
folderName = f"{bfFolder}/{yearType}_{num}" if num != 0 else f"{bfFolder}/{yearType}"
print()
print(f"[!] begin to create folder {folderName}")
if os.path.exists(folderName):
print(f"[x] {folderName} already taken")
return self.makeEachVocFolder(bfFolder,yearType,num+1)
os.mkdir(folderName)
print(f"[✓] successfully created folder {folderName}")
return folderName
def makeItJson(self,pathFile,dtToCreate):
with open(pathFile,"w") as fileJson:
dumped = json.dumps(dtToCreate,indent=4)
fileJson.write(dumped)
fileJson.close()
return True
def makeItCsv(self,pathFile,dtToCreate):
with open(pathFile,"w",encoding="UTF-8",newline='') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames=dtToCreate["head"])
writer.writeheader()
writer.writerows(dtToCreate["data"])
return True
def makeEachDataSet(self,data,folderName):
print("[!] begin to create each json file")
tobeMergedAll = {
"id" : [],
"name": [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"head" : [],
"data" : []
}
for item in data:
if item["data"]:
folderYearPath = self.makeEachVocFolder(folderName,item["typeYear"],0)
tobeMergedEachVoc = {
"id" : [],
"name": [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"head" : item["head"],
"data" : []
}
for subitem in item["data"]:
if subitem["error"] == False:
if self.fileType == "json":
jsonFile = {
"id" : subitem["id"],
"name" : subitem["name"],
"gender" : subitem["gender"],
"school" : subitem["school"],
"kec" : subitem["kec"],
"kel" : subitem["kel"]
}
tobeMergedEachVoc["id"] = tobeMergedEachVoc["id"] + subitem["id"]
tobeMergedEachVoc["name"] = tobeMergedEachVoc["name"] + subitem["name"]
tobeMergedEachVoc["gender"] = tobeMergedEachVoc["gender"] + subitem["gender"]
tobeMergedEachVoc["school"] = tobeMergedEachVoc["school"] + subitem["school"]
tobeMergedEachVoc["kec"] = tobeMergedEachVoc["kec"] + subitem["kec"]
tobeMergedEachVoc["kel"] = tobeMergedEachVoc["kel"] + subitem["kel"]
fileName = f"{subitem['vocType']}-{item['typeYear']}.json"
subitemJson = self.makeItJson(f"{folderYearPath}/{fileName}",jsonFile)
if subitemJson:
print(f" ➥ [✓] {fileName} successfully created")
else:
tobeMergedEachVoc["data"] = tobeMergedEachVoc["data"] + subitem["csvData"]
fileName = f"{subitem['vocType']}-{item['typeYear']}.csv"
subitemCsv = self.makeItCsv(f"{folderYearPath}/{fileName}",{
"head" : item["head"],
"data" : subitem["csvData"]
})
if subitemCsv:
print(f" ➥ [✓] {fileName} successfully created")
mergedJson = self.makeItJson(f"{folderYearPath}/merged-{item['typeYear']}.json",tobeMergedEachVoc) if self.fileType == "json" else self.makeItCsv(f"{folderYearPath}/merged-{item['typeYear']}.csv",tobeMergedEachVoc)
if mergedJson:
print(f" ➥ [✓] succesfully merged data and create merged-{item['typeYear']}")
if self.fileType == "json":
tobeMergedAll["id"] = tobeMergedAll["id"] + tobeMergedEachVoc["id"]
tobeMergedAll["name"] = tobeMergedAll["name"] + tobeMergedEachVoc["name"]
tobeMergedAll["gender"] = tobeMergedAll["gender"] + tobeMergedEachVoc["gender"]
tobeMergedAll["school"] = tobeMergedAll["school"] + tobeMergedEachVoc["school"]
tobeMergedAll["kec"] = tobeMergedAll["kec"] + tobeMergedEachVoc["kec"]
tobeMergedAll["kel"] = tobeMergedAll["kel"] + tobeMergedEachVoc["kel"]
else:
tobeMergedAll["head"] = tobeMergedEachVoc["head"]
tobeMergedAll["data"] = tobeMergedAll["data"] + tobeMergedEachVoc["data"]
mergedAll = self.makeItJson(f"{folderName}/all-merged.json",tobeMergedAll) if self.fileType == "json" else self.makeItCsv(f"{folderName}/all-merged.csv",tobeMergedAll)
if mergedAll:
print(f"[✓] Successfully Merged All Data To One {self.fileType} File")
return True
def makeFolderMain(self,name,num):
folderName = f"{name}_{num}"
print(f"[!] begin creating folder {folderName}")
if os.path.exists(folderName):
print(f"[x] {folderName} already taken")
return self.makeFolderMain(name,num+1)
os.mkdir(folderName)
print(f"[✓] successfully created folder {folderName}")
return folderName
# make Data from requested API
def eachDataHandler(self,studentList,yearType,vocType):
yearType = "current" if yearType == "testing" else yearType #for testing only
apiLink = "https://api.siap-ppdb.com/cari?no_daftar=" if yearType == "current" else f"https://arsip.siap-ppdb.com/{yearType}/api/cari?no_daftar="
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Host": "arsip.siap-ppdb.com",
"Referer": "https://arsip.siap-ppdb.com/2020/jakarta/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"Sec-GPC": "1",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36" # add your own userAgent
}
dataBucket = {
"vocType" :vocType,
"error" : False,
"id" : [],
"name" : [],
"gender" : [],
"school" : [],
"kec" : [],
"kel" : []
} if self.fileType == "json" else {
"vocType" : vocType,
"error" : False,
"csvData" : []
}
for studentId in studentList:
try:
req = requests.get(f"{apiLink}{studentId}",timeout=3) if yearType == "current" else requests.get(f"{apiLink}{studentId}",timeout=3,headers=headers)
jsoned = req.json()
splittedkecKel = jsoned[0][3][5][3].split(",")
kelData = splittedkecKel[1][1:]
kecData = splittedkecKel[2][1:]
nameData = jsoned[0][3][2][-1]
genderData = jsoned[0][3][3][-2]
schoolData = jsoned[0][3][6][3]
if jsoned[-1][3][3][-1] != "Tidak Lapor Diri":
if self.fileType == "json":
dataBucket["id"].append(studentId)
dataBucket["name"].append(nameData)
dataBucket["gender"].append(genderData)
dataBucket["school"].append(schoolData)
dataBucket["kel"].append(kelData)
dataBucket["kec"].append(kecData)
else:
dataBucket["csvData"].append(
{
"id" : studentId,
"name" : nameData,
"gender" : genderData,
"school" : schoolData,
"kec" : kecData,
"kel" : kelData
}
)
print(f" ➥ [✓] {studentId}\t\tOK")
else:
self.logError["errReport"].append({
"id" : studentId,
"yearType" : yearType,
"vocType" : vocType
})
print(f" ➥ [x] {studentId}\t\tFalse")
except Exception as e:
self.logError["errorId"].append({
"id" : studentId,
"yearType" : yearType,
"vocType" : vocType
})
print(f" ➥ [x] {studentId}\t\tFailed")
return dataBucket
def makeReqToApi(self,arg):
afterParsed = self.data["data"] if arg == "all" else [item for item in self.data["data"] if item["yearType"] == arg]
if afterParsed:
requestBucket = []
for item in afterParsed:
afterAlleachBucket = {
"typeYear" : item["yearType"],
"head" : ["id","name","gender","school","kec","kel"],
"data" : []
}
print()
print(f"[!] proccessing {item['yearType']}")
for subitem in item["sourceDataLink"]:
try:
print(f"\n ➤ [!] Fetching {subitem['vocType']}")
req = requests.get(subitem["api"],timeout=3)
jsoned = req.json()
eachDataBucket = self.eachDataHandler([item[3] for item in jsoned["data"]],item["yearType"],subitem["vocType"])
afterAlleachBucket["data"].append(eachDataBucket)
except Exception as e:
afterAlleachBucket["data"].append({
"vocType" : subitem["vocType"],
"error" : True
})
self.logError["errorVoc"].append({
"yearType" : item["yearType"],
"vocType" : subitem["vocType"]
})
print(f" ➥ [x] Failed to fetch {subitem['vocType']}\n")
requestBucket.append(afterAlleachBucket)
return requestBucket
else:
return False
def make(self,arg):
try:
while True:
q = int(input("[?] choose data type ! \n ➥ 1. json\n ➥ 2. csv\n (1/2) : "))
if q == 1:
self.fileType = "json"
break
elif q == 2:
self.fileType = "csv"
break
else:
print("[x] invalid option")
tobeReturned = self.makeReqToApi(arg)
print()
self.logger()
print()
if tobeReturned != False:
counterFailed = 0
for item in tobeReturned:
for subitem in item["data"]:
if subitem["error"] == True:
counterFailed += 1
if counterFailed == sum([len(item["data"]) for item in tobeReturned]):
print("➥[x] can't create dataset. All of connections went failed")
return False
while True:
makeFolderMain = str(input("[?] begin to make dataset (y/n) : "))
if makeFolderMain.lower() == "y":
fdName = self.makeFolderMain("outputDataSet",0)
self.makeEachDataSet(tobeReturned,fdName)
break
elif makeFolderMain == "n":
return False
else:
print("[x] invalid option")
return False
except KeyboardInterrupt:
print("\n[x] Adios")
# getter
def logger(self):
if self.logError["errorVoc"] or self.logError["errorId"] or self.logError["errReport"]:
print("\n\n\n")
print("[x] Error Data log")
if self.logError["errorVoc"]:
for item in self.logError["errorVoc"]:
print(f" ➥ [~] Can't Fetch {item['vocType']} in {item['yearType']} Data")
elif self.logError["errorId"]:
for itemid in self.logError["errorId"]:
print(f" ➥ [~] Cant Fetch {itemid['vocType']}'s {itemid['id']} in {itemid['yearType']} Data")
elif self.logError["errReport"]:
for itemid in self.logError["errReport"]:
print(f" ➥ [~] {itemid['id']}'s self-report status : False")
print("\n\n\n")
else:
print("[✓] No Log To Be Displayed,All Data Successfully Fetched") |
import contextlib
import glob
import os
import platform
import shutil
import subprocess
import sys
import tempfile
# dependencies that are always installed
REQUIRED_DEPS = [
"git",
"jupyter",
"numpy",
"matplotlib",
"h5py",
"cython",
"nose",
"sympy",
"setuptools",
]
# dependencies that aren't installed by default
OPTIONAL_DEPS = [
"embree",
"pyx",
"scipy",
"astropy",
"cartopy",
"pooch",
]
# dependencies that are only installable when yt is built from source
YT_SOURCE_ONLY_DEPS = [
"embree",
]
DEPENDENCY_IMPORT_TESTS = {
"embree": "from yt.utilities.lib.embree_mesh import mesh_traversal",
}
def call_unix_command(command):
print(f'Running "{command}" in {os.getcwd()}')
output = ""
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as er:
raise RuntimeError(
"Command '%s' failed with return code '%s' and error:\n\n%s"
% (command, er.returncode, er.output.decode("utf-8"))
)
finally:
if len(output.splitlines()) > 25:
print("truncated output:")
print("\n".join((output.decode().splitlines())[-25:]))
else:
print(output)
@contextlib.contextmanager
def working_directory(path):
"""A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
shutil.rmtree(path)
def run_install_script(install_script_path, inst_py3, binary_yt=False):
msg = "Testing installation with inst_py3={} and binary_yt={}"
print(msg.format(inst_py3, binary_yt))
shutil.copy(install_script_path, os.curdir)
with open("install_script.sh", "r") as source:
with open("install_script_edited.sh", "w") as target:
data = source.read()
for dep in OPTIONAL_DEPS:
if binary_yt and dep in YT_SOURCE_ONLY_DEPS:
continue
if dep == "rockstar":
# compiling rockstar is broken on newer MacOS releases
if platform.mac_ver()[0].startswith(("10.12", "10.13")):
continue
dname = f"INST_{dep.upper()}"
data = data.replace(dname + "=0", dname + "=1")
if inst_py3:
data = data.replace("INST_PY3=0", "INST_PY3=1")
if not binary_yt:
data = data.replace("INST_YT_SOURCE=0", "INST_YT_SOURCE=1")
target.write(data)
shutil.copyfile("install_script_edited.sh", "install_script.sh")
call_unix_command("bash install_script.sh --yes")
def verify_yt_installation(binary_yt):
yt_dir = glob.glob("yt-*")
ndirs = len(yt_dir)
if ndirs != 1:
raise RuntimeError("A yt installation was not properly cleaned up, exiting")
yt_dir = yt_dir[0]
python_path = os.sep.join([yt_dir, "bin", "python"])
for dep in OPTIONAL_DEPS + REQUIRED_DEPS:
if binary_yt and dep in YT_SOURCE_ONLY_DEPS:
continue
if dep == "git":
git_path = os.sep.join([yt_dir, "bin", "git"])
call_unix_command(f"{git_path} --version")
if dep in DEPENDENCY_IMPORT_TESTS:
cmd = "{} -c '{}'"
if dep == "rockstar":
# compiling rockstar is broken on newer MacOS releases
if platform.mac_ver()[0].startswith(("10.12", "10.13")):
continue
cmd = (
f"LD_LIBRARY_PATH={os.sep.join([os.curdir, yt_dir, "lib"])} " + cmd
)
if sys.platform == "darwin":
cmd = "DY" + cmd
call_unix_command(cmd.format(python_path, DEPENDENCY_IMPORT_TESTS[dep]))
else:
call_unix_command(f"{python_path} -c 'import {dep}'")
return yt_dir
if __name__ == "__main__":
install_script_path = os.path.abspath(
os.path.sep.join([os.getcwd(), os.pardir, "doc", "install_script.sh"])
)
for inst_py3 in [False, True]:
tmpdir = tempfile.mkdtemp()
with working_directory(tmpdir):
run_install_script(install_script_path, inst_py3, binary_yt=True)
conda_binary_path = verify_yt_installation(binary_yt=True)
shutil.rmtree(conda_binary_path)
run_install_script(install_script_path, inst_py3, binary_yt=False)
conda_source_path = verify_yt_installation(binary_yt=False)
shutil.rmtree(conda_source_path)
| import contextlib
import glob
import os
import platform
import shutil
import subprocess
import sys
import tempfile
# dependencies that are always installed
REQUIRED_DEPS = [
"git",
"jupyter",
"numpy",
"matplotlib",
"h5py",
"cython",
"nose",
"sympy",
"setuptools",
]
# dependencies that aren't installed by default
OPTIONAL_DEPS = [
"embree",
"pyx",
"scipy",
"astropy",
"cartopy",
"pooch",
]
# dependencies that are only installable when yt is built from source
YT_SOURCE_ONLY_DEPS = [
"embree",
]
DEPENDENCY_IMPORT_TESTS = {
"embree": "from yt.utilities.lib.embree_mesh import mesh_traversal",
}
def call_unix_command(command):
print(f'Running "{command}" in {os.getcwd()}')
output = ""
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as er:
raise RuntimeError(
"Command '%s' failed with return code '%s' and error:\n\n%s"
% (command, er.returncode, er.output.decode("utf-8"))
)
finally:
if len(output.splitlines()) > 25:
print("truncated output:")
print("\n".join((output.decode().splitlines())[-25:]))
else:
print(output)
@contextlib.contextmanager
def working_directory(path):
"""A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
shutil.rmtree(path)
def run_install_script(install_script_path, inst_py3, binary_yt=False):
msg = "Testing installation with inst_py3={} and binary_yt={}"
print(msg.format(inst_py3, binary_yt))
shutil.copy(install_script_path, os.curdir)
with open("install_script.sh", "r") as source:
with open("install_script_edited.sh", "w") as target:
data = source.read()
for dep in OPTIONAL_DEPS:
if binary_yt and dep in YT_SOURCE_ONLY_DEPS:
continue
if dep == "rockstar":
# compiling rockstar is broken on newer MacOS releases
if platform.mac_ver()[0].startswith(("10.12", "10.13")):
continue
dname = f"INST_{dep.upper()}"
data = data.replace(dname + "=0", dname + "=1")
if inst_py3:
data = data.replace("INST_PY3=0", "INST_PY3=1")
if not binary_yt:
data = data.replace("INST_YT_SOURCE=0", "INST_YT_SOURCE=1")
target.write(data)
shutil.copyfile("install_script_edited.sh", "install_script.sh")
call_unix_command("bash install_script.sh --yes")
def verify_yt_installation(binary_yt):
yt_dir = glob.glob("yt-*")
ndirs = len(yt_dir)
if ndirs != 1:
raise RuntimeError("A yt installation was not properly cleaned up, exiting")
yt_dir = yt_dir[0]
python_path = os.sep.join([yt_dir, "bin", "python"])
for dep in OPTIONAL_DEPS + REQUIRED_DEPS:
if binary_yt and dep in YT_SOURCE_ONLY_DEPS:
continue
if dep == "git":
git_path = os.sep.join([yt_dir, "bin", "git"])
call_unix_command(f"{git_path} --version")
if dep in DEPENDENCY_IMPORT_TESTS:
cmd = "{} -c '{}'"
if dep == "rockstar":
# compiling rockstar is broken on newer MacOS releases
if platform.mac_ver()[0].startswith(("10.12", "10.13")):
continue
cmd = (
f"LD_LIBRARY_PATH={os.sep.join([os.curdir, yt_dir, 'lib'])} " + cmd
)
if sys.platform == "darwin":
cmd = "DY" + cmd
call_unix_command(cmd.format(python_path, DEPENDENCY_IMPORT_TESTS[dep]))
else:
call_unix_command(f"{python_path} -c 'import {dep}'")
return yt_dir
if __name__ == "__main__":
install_script_path = os.path.abspath(
os.path.sep.join([os.getcwd(), os.pardir, "doc", "install_script.sh"])
)
for inst_py3 in [False, True]:
tmpdir = tempfile.mkdtemp()
with working_directory(tmpdir):
run_install_script(install_script_path, inst_py3, binary_yt=True)
conda_binary_path = verify_yt_installation(binary_yt=True)
shutil.rmtree(conda_binary_path)
run_install_script(install_script_path, inst_py3, binary_yt=False)
conda_source_path = verify_yt_installation(binary_yt=False)
shutil.rmtree(conda_source_path)
|
from __future__ import annotations
from typing import Any, List, Union, Collection, TYPE_CHECKING, Optional
import O365.message as message
import O365.utils.utils as utils
from subtypes import Str, Html
from pathmagic import Dir, PathLike, File
from ..attribute import Attribute, NonFilterableAttribute, EnumerativeAttribute, BooleanAttribute
from ..query import Query, BulkAction, BulkActionContext
from ..fluent import FluentEntity
if TYPE_CHECKING:
from ..people import Contact
class Message(message.Message):
"""A class representing a Microsoft Outlook message. Provides methods and properties for interacting with it."""
style = {
"font-size": 11,
"font-family": "Calibri, sans-serif, serif, "EmojiFont"",
"margin": 0
}
def __repr__(self) -> str:
return f"{type(self).__name__}(subject={repr(self.subject)}, from={repr(self.sender.address)}, is_read={self.is_read}, importance={repr(self.importance.value)}, attachments={len(self.attachments)}, received={self.received})"
def __str__(self) -> str:
return self.text
def __hash__(self) -> int:
return id(self)
def _repr_html_(self) -> str:
return f"<strong><mark>{self.subject}</mark></strong><br><br>{self.body}"
@property
def text(self) -> str:
"""A property controlling access to the string form of the message body, with all html tags and constructs handled and stripped out."""
return Html(self.body).text.strip()
@property
def html(self) -> Html:
"""A property controlling access to the subtypes.Html object corresponding to this message's html body."""
return Html(self.body)
@property
def fluent(self) -> FluentMessage:
"""Convert this Message to an equivalent FluentMessage."""
return FluentMessage(parent=self)
def reply(self, *args: Any, **kwargs: Any) -> FluentMessage:
"""Create a new FluentMessage serving as a reply to this message."""
new: Message = super().reply(*args, **kwargs)
return new.fluent
def forward(self) -> FluentMessage:
"""Create a new FluentMessage serving as a forward of this message."""
new: Message = super().forward()
return new.fluent
def copy(self, *args: Any, **kwargs: Any) -> FluentMessage:
"""Create a new FluentMessage serving as a copy of this message."""
new: Message = super().copy(*args, **kwargs)
return new.fluent
def render(self) -> None:
"""Render the message body html in a separate window. Will block until the window has been closed by a user."""
from iotools import HtmlGui
HtmlGui(name=self.subject, text=self.body).start()
def save_attachments_to(self, path: PathLike) -> list[File]:
"""Save all attachments of this message to the given folder path."""
if not self.has_attachments:
return []
else:
self.attachments.download_attachments()
for attachment in self.attachments:
attachment.save(path)
return [Dir(path).files[attachment.name] for attachment in self.attachments]
class Attributes:
class From(Attribute):
name = "from"
class Sender(Attribute):
name = "sender"
class Subject(Attribute):
name = "subject"
class ReceivedOn(Attribute):
name = "received_date_time"
class LastModified(Attribute):
name = "last_modified_date_time"
class Categories(Attribute):
name = "categories"
class IsRead(BooleanAttribute):
name = "is_read"
class HasAttachments(BooleanAttribute):
name = "has_attachments"
class IsDraft(BooleanAttribute):
name = "is_draft"
class HasDeliveryReceipt(BooleanAttribute):
name = "is_delivery_receipt_requested"
class HasReadReceipt(BooleanAttribute):
name = "is_read_receipt_requested"
class Importance(EnumerativeAttribute):
name, enumeration = "importance", utils.ImportanceLevel
class Body(NonFilterableAttribute):
name = "body"
class Cc(NonFilterableAttribute):
name = "cc_recipients"
class Bcc(NonFilterableAttribute):
name = "bcc_recipients"
class To(NonFilterableAttribute):
name = "to_recipients"
class BulkMessageAction(BulkAction):
"""A class representing a bulk action performed on the resultset of a message query."""
def copy(self, folder: Any) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.copy, args=(folder,))
def move(self, folder: Any) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.move, args=(folder,))
def delete(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.delete)
def mark_as_read(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.mark_as_read)
def save_draft(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.save_draft)
class MessageQuery(Query):
"""A class for querying the messages within a given collection."""
@property
def bulk(self) -> BulkMessageAction:
"""Perform a bulk action on the resultset of this query."""
return BulkMessageAction(self)
def execute(self) -> list[Message]:
"""Execute this query and return any messages that match."""
return list(self._container.get_messages(limit=self._limit, query=self._query))
class FluentMessage(FluentEntity):
"""A class representing a message that doesn't yet exist. All public methods allow chaining. At the end of the method chain call FluentMessage.send() to send the message."""
def __init__(self, parent: Message = None) -> None:
self.entity, self.office, self._signing = parent, parent.con.office, False
self.entity.sender.address = self.office.resource
self._temp_body: Optional[str] = None
def from_(self, address: str) -> FluentMessage:
"""Set the email address this message will appear to originate from."""
self.entity.sender.address = address
return self
def to(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.to.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def cc(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.cc.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def bcc(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.bcc.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def request_read_receipt(self, request_read_receipt: bool) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.is_read_receipt_requested = request_read_receipt
return self
def request_delivery_receipt(self, request_delivery_receipt: bool) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.is_delivery_receipt_requested = request_delivery_receipt
return self
def send(self) -> bool:
"""Send this message as it currently is."""
if self._temp_body is not None:
start, end = f"""<p style="font-size: {self.entity.style["font-size"]}pt; font-family: {self.entity.style["font-family"]}; margin: {self.entity.style["margin"]}px;">""", "</p>"
body = f"{start}{self._temp_body}{end}"
self.entity.body = f"{body}<br>{self.office.outlook.signature}" if self._signing else body
return self.entity.send()
| from __future__ import annotations
from typing import Any, List, Union, Collection, TYPE_CHECKING, Optional
import O365.message as message
import O365.utils.utils as utils
from subtypes import Str, Html
from pathmagic import Dir, PathLike, File
from ..attribute import Attribute, NonFilterableAttribute, EnumerativeAttribute, BooleanAttribute
from ..query import Query, BulkAction, BulkActionContext
from ..fluent import FluentEntity
if TYPE_CHECKING:
from ..people import Contact
class Message(message.Message):
"""A class representing a Microsoft Outlook message. Provides methods and properties for interacting with it."""
style = {
"font-size": 11,
"font-family": "Calibri, sans-serif, serif, "EmojiFont"",
"margin": 0
}
def __repr__(self) -> str:
return f"{type(self).__name__}(subject={repr(self.subject)}, from={repr(self.sender.address)}, is_read={self.is_read}, importance={repr(self.importance.value)}, attachments={len(self.attachments)}, received={self.received})"
def __str__(self) -> str:
return self.text
def __hash__(self) -> int:
return id(self)
def _repr_html_(self) -> str:
return f"<strong><mark>{self.subject}</mark></strong><br><br>{self.body}"
@property
def text(self) -> str:
"""A property controlling access to the string form of the message body, with all html tags and constructs handled and stripped out."""
return Html(self.body).text.strip()
@property
def html(self) -> Html:
"""A property controlling access to the subtypes.Html object corresponding to this message's html body."""
return Html(self.body)
@property
def fluent(self) -> FluentMessage:
"""Convert this Message to an equivalent FluentMessage."""
return FluentMessage(parent=self)
def reply(self, *args: Any, **kwargs: Any) -> FluentMessage:
"""Create a new FluentMessage serving as a reply to this message."""
new: Message = super().reply(*args, **kwargs)
return new.fluent
def forward(self) -> FluentMessage:
"""Create a new FluentMessage serving as a forward of this message."""
new: Message = super().forward()
return new.fluent
def copy(self, *args: Any, **kwargs: Any) -> FluentMessage:
"""Create a new FluentMessage serving as a copy of this message."""
new: Message = super().copy(*args, **kwargs)
return new.fluent
def render(self) -> None:
"""Render the message body html in a separate window. Will block until the window has been closed by a user."""
from iotools import HtmlGui
HtmlGui(name=self.subject, text=self.body).start()
def save_attachments_to(self, path: PathLike) -> list[File]:
"""Save all attachments of this message to the given folder path."""
if not self.has_attachments:
return []
else:
self.attachments.download_attachments()
for attachment in self.attachments:
attachment.save(path)
return [Dir(path).files[attachment.name] for attachment in self.attachments]
class Attributes:
class From(Attribute):
name = "from"
class Sender(Attribute):
name = "sender"
class Subject(Attribute):
name = "subject"
class ReceivedOn(Attribute):
name = "received_date_time"
class LastModified(Attribute):
name = "last_modified_date_time"
class Categories(Attribute):
name = "categories"
class IsRead(BooleanAttribute):
name = "is_read"
class HasAttachments(BooleanAttribute):
name = "has_attachments"
class IsDraft(BooleanAttribute):
name = "is_draft"
class HasDeliveryReceipt(BooleanAttribute):
name = "is_delivery_receipt_requested"
class HasReadReceipt(BooleanAttribute):
name = "is_read_receipt_requested"
class Importance(EnumerativeAttribute):
name, enumeration = "importance", utils.ImportanceLevel
class Body(NonFilterableAttribute):
name = "body"
class Cc(NonFilterableAttribute):
name = "cc_recipients"
class Bcc(NonFilterableAttribute):
name = "bcc_recipients"
class To(NonFilterableAttribute):
name = "to_recipients"
class BulkMessageAction(BulkAction):
"""A class representing a bulk action performed on the resultset of a message query."""
def copy(self, folder: Any) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.copy, args=(folder,))
def move(self, folder: Any) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.move, args=(folder,))
def delete(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.delete)
def mark_as_read(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.mark_as_read)
def save_draft(self) -> BulkActionContext:
return BulkActionContext(query=self._query, action=Message.save_draft)
class MessageQuery(Query):
"""A class for querying the messages within a given collection."""
@property
def bulk(self) -> BulkMessageAction:
"""Perform a bulk action on the resultset of this query."""
return BulkMessageAction(self)
def execute(self) -> list[Message]:
"""Execute this query and return any messages that match."""
return list(self._container.get_messages(limit=self._limit, query=self._query))
class FluentMessage(FluentEntity):
"""A class representing a message that doesn't yet exist. All public methods allow chaining. At the end of the method chain call FluentMessage.send() to send the message."""
def __init__(self, parent: Message = None) -> None:
self.entity, self.office, self._signing = parent, parent.con.office, False
self.entity.sender.address = self.office.resource
self._temp_body: Optional[str] = None
def from_(self, address: str) -> FluentMessage:
"""Set the email address this message will appear to originate from."""
self.entity.sender.address = address
return self
def to(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.to.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def cc(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.cc.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def bcc(self, contacts: Union[Union[str, Contact], Collection[Union[str, Contact]]]) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.bcc.add(self._parse_contacts_to_emails(contacts=contacts))
return self
def request_read_receipt(self, request_read_receipt: bool) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.is_read_receipt_requested = request_read_receipt
return self
def request_delivery_receipt(self, request_delivery_receipt: bool) -> FluentMessage:
"""Set the email address(es) (a single one or a collection of them) this message will be sent to. Email addresses can be provided either as strings or as contact objects."""
self.entity.is_delivery_receipt_requested = request_delivery_receipt
return self
def send(self) -> bool:
"""Send this message as it currently is."""
if self._temp_body is not None:
start, end = f"""<p style="font-size: {self.entity.style["font-size"]}pt; font-family: {self.entity.style["font-family"]}; margin: {self.entity.style["margin"]}px;">""", "</p>"
body = f"{start}{self._temp_body}{end}"
self.entity.body = f"{body}<br>{self.office.outlook.signature}" if self._signing else body
return self.entity.send()
|
import torch
from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor
from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor
from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv1_ssd_lite_predictor
from vision.ssd.mobilenet_v2_ssd_lite_xiaomi import create_mobilenetv2_ssd_lite_xiaomi, create_mobilenetv2_ssd_lite_predictor_xiaomi
from vision.ssd.fairnas_a_ssd_lite import create_fairnas_a_ssd_lite, create_fairnas_a_ssd_lite_predictor
from vision.ssd.fairnas_b_ssd_lite import create_fairnas_b_ssd_lite, create_fairnas_b_ssd_lite_predictor
from vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite, create_squeezenet_ssd_lite_predictor
from vision.datasets.voc_dataset import VOCDataset
from vision.datasets.open_images import OpenImagesDataset
from vision.datasets.coco_dataset import CocoDatasetTest
from vision.utils import box_utils, measurements
from vision.utils.misc import str2bool, Timer
import argparse
import pathlib
import numpy as np
import logging
import sys
from vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite, create_mobilenetv2_ssd_lite_predictor
parser = argparse.ArgumentParser(description="SSD Evaluation on VOC Dataset.")
parser.add_argument('--net', default="vgg16-ssd",
help="The network architecture, it should be of mb1-ssd, mb1-ssd-lite, mb2-ssd-lite or vgg16-ssd.")
parser.add_argument("--trained_model", type=str)
parser.add_argument("--dataset_type", default="voc", type=str,
help='Specify dataset type. Currently support voc and open_images.')
parser.add_argument("--dataset", type=str, help="The root directory of the VOC dataset or Open Images dataset.")
parser.add_argument('--annfile', type=str, help='json annotation file, just for coco dataset')
parser.add_argument("--label_file", type=str, help="The label file path.")
parser.add_argument("--use_cuda", type=str2bool, default=True)
parser.add_argument("--use_2007_metric", type=str2bool, default=True)
parser.add_argument("--nms_method", type=str, default="hard")
parser.add_argument("--iou_threshold", type=float, default=0.5, help="The threshold of Intersection over Union.")
parser.add_argument("--eval_dir", default="eval_results", type=str, help="The directory to store evaluation results.")
parser.add_argument('--mb2_width_mult', default=1.0, type=float,
help='Width Multiplifier for MobilenetV2')
args = parser.parse_args()
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() and args.use_cuda else "cpu")
def group_annotation_by_class(dataset):
true_case_stat = {}
all_gt_boxes = {}
all_difficult_cases = {}
for i in range(len(dataset)):
image_id, annotation = dataset.get_annotation(i)
gt_boxes, classes, is_difficult = annotation
gt_boxes = torch.from_numpy(gt_boxes)
for i, difficult in enumerate(is_difficult):
class_index = int(classes[i])
gt_box = gt_boxes[i]
if not difficult:
true_case_stat[class_index] = true_case_stat.get(class_index, 0) + 1
if class_index not in all_gt_boxes:
all_gt_boxes[class_index] = {}
if image_id not in all_gt_boxes[class_index]:
all_gt_boxes[class_index][image_id] = []
all_gt_boxes[class_index][image_id].append(gt_box)
if class_index not in all_difficult_cases:
all_difficult_cases[class_index]={}
if image_id not in all_difficult_cases[class_index]:
all_difficult_cases[class_index][image_id] = []
all_difficult_cases[class_index][image_id].append(difficult)
for class_index in all_gt_boxes:
for image_id in all_gt_boxes[class_index]:
all_gt_boxes[class_index][image_id] = torch.stack(all_gt_boxes[class_index][image_id])
for class_index in all_difficult_cases:
for image_id in all_difficult_cases[class_index]:
all_gt_boxes[class_index][image_id] = torch.tensor(all_gt_boxes[class_index][image_id])
return true_case_stat, all_gt_boxes, all_difficult_cases
def compute_average_precision_per_class(num_true_cases, gt_boxes, difficult_cases,
prediction_file, iou_threshold, use_2007_metric):
with open(prediction_file) as f:
image_ids = []
boxes = []
scores = []
for line in f:
t = line.rstrip().split(" ")
image_ids.append(t[0])
scores.append(float(t[1]))
box = torch.tensor([float(v) for v in t[2:]]).unsqueeze(0)
box -= 1.0 # convert to python format where indexes start from 0
boxes.append(box)
scores = np.array(scores)
sorted_indexes = np.argsort(-scores)
boxes = [boxes[i] for i in sorted_indexes]
image_ids = [image_ids[i] for i in sorted_indexes]
true_positive = np.zeros(len(image_ids))
false_positive = np.zeros(len(image_ids))
matched = set()
for i, image_id in enumerate(image_ids):
box = boxes[i]
if image_id not in gt_boxes:
false_positive[i] = 1
continue
gt_box = gt_boxes[image_id]
ious = box_utils.iou_of(box, gt_box)
max_iou = torch.max(ious).item()
max_arg = torch.argmax(ious).item()
if max_iou > iou_threshold:
if difficult_cases[image_id][max_arg] == 0:
if (image_id, max_arg) not in matched:
true_positive[i] = 1
matched.add((image_id, max_arg))
else:
false_positive[i] = 1
else:
false_positive[i] = 1
true_positive = true_positive.cumsum()
false_positive = false_positive.cumsum()
precision = true_positive / (true_positive + false_positive)
recall = true_positive / num_true_cases
if use_2007_metric:
return measurements.compute_voc2007_average_precision(precision, recall)
else:
return measurements.compute_average_precision(precision, recall)
if __name__ == '__main__':
eval_path = pathlib.Path(args.eval_dir)
eval_path.mkdir(exist_ok=True)
timer = Timer()
class_names = [name.strip() for name in open(args.label_file).readlines()]
if args.dataset_type == "voc":
dataset = VOCDataset(args.dataset, is_test=True)
elif args.dataset_type == 'open_images':
dataset = OpenImagesDataset(args.dataset, dataset_type="test")
elif args.dataset_type == 'coco':
dataset = CocoDatasetTest(args.dataset, args.annfile)
true_case_stat, all_gb_boxes, all_difficult_cases = group_annotation_by_class(dataset)
if args.net == 'vgg16-ssd':
net = create_vgg_ssd(len(class_names), is_test=True)
elif args.net == 'mb1-ssd':
net = create_mobilenetv1_ssd(len(class_names), is_test=True)
elif args.net == 'mb1-ssd-lite':
net = create_mobilenetv1_ssd_lite(len(class_names), is_test=True)
elif args.net == 'sq-ssd-lite':
net = create_squeezenet_ssd_lite(len(class_names), is_test=True)
elif args.net == 'mb2-ssd-lite':
net = create_mobilenetv2_ssd_lite(len(class_names), width_mult=args.mb2_width_mult, is_test=True)
elif args.net == 'mb2-ssd-lite-xiaomi':
net = create_mobilenetv2_ssd_lite_xiaomi(len(class_names), width_mult=args.mb2_width_mult, is_test=True)
elif args.net == 'fairnas-a-ssd-lite':
net = create_fairnas_a_ssd_lite(len(class_names), is_test=True)
elif args.net == 'fairnas-b-ssd-lite':
net = create_fairnas_b_ssd_lite(len(class_names), is_test=True)
else:
logging.fatal("The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.")
parser.print_help(sys.stderr)
sys.exit(1)
timer.start("Load Model")
net.load(args.trained_model)
net = net.to(DEVICE)
print(f'It took {timer.end('Load Model')} seconds to load the model.')
if args.net == 'vgg16-ssd':
predictor = create_vgg_ssd_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb1-ssd':
predictor = create_mobilenetv1_ssd_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb1-ssd-lite':
predictor = create_mobilenetv1_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'sq-ssd-lite':
predictor = create_squeezenet_ssd_lite_predictor(net,nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb2-ssd-lite':
predictor = create_mobilenetv2_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb2-ssd-lite-xiaomi':
predictor = create_mobilenetv2_ssd_lite_predictor_xiaomi(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'fairnas-a-ssd-lite':
predictor = create_fairnas_a_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'fairnas-b-ssd-lite':
predictor = create_fairnas_b_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
else:
logging.fatal("The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.")
parser.print_help(sys.stderr)
sys.exit(1)
results = []
for i in range(len(dataset)):
print("process image", i)
timer.start("Load Image")
image = dataset.get_image(i)
print("Load Image: {:4f} seconds.".format(timer.end("Load Image")))
timer.start("Predict")
boxes, labels, probs = predictor.predict(image)
print("Prediction: {:4f} seconds.".format(timer.end("Predict")))
indexes = torch.ones(labels.size(0), 1, dtype=torch.float32) * i
results.append(torch.cat([
indexes.reshape(-1, 1),
labels.reshape(-1, 1).float(),
probs.reshape(-1, 1),
boxes + 1.0 # matlab's indexes start from 1
], dim=1))
results = torch.cat(results)
for class_index, class_name in enumerate(class_names):
if class_index == 0:
continue # ignore background
prediction_path = eval_path / f"det_test_{class_name}.txt"
with open(prediction_path, "w") as f:
sub = results[results[:, 1] == class_index, :]
for i in range(sub.size(0)):
prob_box = sub[i, 2:].numpy()
image_id = dataset.ids[int(sub[i, 0])]
print(
str(image_id) + " " + " ".join([str(v) for v in prob_box]),
file=f
)
aps = []
print("\n\nAverage Precision Per-class:")
for class_index, class_name in enumerate(class_names):
# coco class has _ name
if class_index == 0:
continue
prediction_path = eval_path / f"det_test_{class_name}.txt"
ap = compute_average_precision_per_class(
true_case_stat[class_index],
all_gb_boxes[class_index],
all_difficult_cases[class_index],
prediction_path,
args.iou_threshold,
args.use_2007_metric
)
aps.append(ap)
print(f"{class_name}: {ap}")
print(f"\nAverage Precision Across All Classes:{sum(aps)/len(aps)}")
| import torch
from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor
from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor
from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv1_ssd_lite_predictor
from vision.ssd.mobilenet_v2_ssd_lite_xiaomi import create_mobilenetv2_ssd_lite_xiaomi, create_mobilenetv2_ssd_lite_predictor_xiaomi
from vision.ssd.fairnas_a_ssd_lite import create_fairnas_a_ssd_lite, create_fairnas_a_ssd_lite_predictor
from vision.ssd.fairnas_b_ssd_lite import create_fairnas_b_ssd_lite, create_fairnas_b_ssd_lite_predictor
from vision.ssd.squeezenet_ssd_lite import create_squeezenet_ssd_lite, create_squeezenet_ssd_lite_predictor
from vision.datasets.voc_dataset import VOCDataset
from vision.datasets.open_images import OpenImagesDataset
from vision.datasets.coco_dataset import CocoDatasetTest
from vision.utils import box_utils, measurements
from vision.utils.misc import str2bool, Timer
import argparse
import pathlib
import numpy as np
import logging
import sys
from vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite, create_mobilenetv2_ssd_lite_predictor
parser = argparse.ArgumentParser(description="SSD Evaluation on VOC Dataset.")
parser.add_argument('--net', default="vgg16-ssd",
help="The network architecture, it should be of mb1-ssd, mb1-ssd-lite, mb2-ssd-lite or vgg16-ssd.")
parser.add_argument("--trained_model", type=str)
parser.add_argument("--dataset_type", default="voc", type=str,
help='Specify dataset type. Currently support voc and open_images.')
parser.add_argument("--dataset", type=str, help="The root directory of the VOC dataset or Open Images dataset.")
parser.add_argument('--annfile', type=str, help='json annotation file, just for coco dataset')
parser.add_argument("--label_file", type=str, help="The label file path.")
parser.add_argument("--use_cuda", type=str2bool, default=True)
parser.add_argument("--use_2007_metric", type=str2bool, default=True)
parser.add_argument("--nms_method", type=str, default="hard")
parser.add_argument("--iou_threshold", type=float, default=0.5, help="The threshold of Intersection over Union.")
parser.add_argument("--eval_dir", default="eval_results", type=str, help="The directory to store evaluation results.")
parser.add_argument('--mb2_width_mult', default=1.0, type=float,
help='Width Multiplifier for MobilenetV2')
args = parser.parse_args()
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() and args.use_cuda else "cpu")
def group_annotation_by_class(dataset):
true_case_stat = {}
all_gt_boxes = {}
all_difficult_cases = {}
for i in range(len(dataset)):
image_id, annotation = dataset.get_annotation(i)
gt_boxes, classes, is_difficult = annotation
gt_boxes = torch.from_numpy(gt_boxes)
for i, difficult in enumerate(is_difficult):
class_index = int(classes[i])
gt_box = gt_boxes[i]
if not difficult:
true_case_stat[class_index] = true_case_stat.get(class_index, 0) + 1
if class_index not in all_gt_boxes:
all_gt_boxes[class_index] = {}
if image_id not in all_gt_boxes[class_index]:
all_gt_boxes[class_index][image_id] = []
all_gt_boxes[class_index][image_id].append(gt_box)
if class_index not in all_difficult_cases:
all_difficult_cases[class_index]={}
if image_id not in all_difficult_cases[class_index]:
all_difficult_cases[class_index][image_id] = []
all_difficult_cases[class_index][image_id].append(difficult)
for class_index in all_gt_boxes:
for image_id in all_gt_boxes[class_index]:
all_gt_boxes[class_index][image_id] = torch.stack(all_gt_boxes[class_index][image_id])
for class_index in all_difficult_cases:
for image_id in all_difficult_cases[class_index]:
all_gt_boxes[class_index][image_id] = torch.tensor(all_gt_boxes[class_index][image_id])
return true_case_stat, all_gt_boxes, all_difficult_cases
def compute_average_precision_per_class(num_true_cases, gt_boxes, difficult_cases,
prediction_file, iou_threshold, use_2007_metric):
with open(prediction_file) as f:
image_ids = []
boxes = []
scores = []
for line in f:
t = line.rstrip().split(" ")
image_ids.append(t[0])
scores.append(float(t[1]))
box = torch.tensor([float(v) for v in t[2:]]).unsqueeze(0)
box -= 1.0 # convert to python format where indexes start from 0
boxes.append(box)
scores = np.array(scores)
sorted_indexes = np.argsort(-scores)
boxes = [boxes[i] for i in sorted_indexes]
image_ids = [image_ids[i] for i in sorted_indexes]
true_positive = np.zeros(len(image_ids))
false_positive = np.zeros(len(image_ids))
matched = set()
for i, image_id in enumerate(image_ids):
box = boxes[i]
if image_id not in gt_boxes:
false_positive[i] = 1
continue
gt_box = gt_boxes[image_id]
ious = box_utils.iou_of(box, gt_box)
max_iou = torch.max(ious).item()
max_arg = torch.argmax(ious).item()
if max_iou > iou_threshold:
if difficult_cases[image_id][max_arg] == 0:
if (image_id, max_arg) not in matched:
true_positive[i] = 1
matched.add((image_id, max_arg))
else:
false_positive[i] = 1
else:
false_positive[i] = 1
true_positive = true_positive.cumsum()
false_positive = false_positive.cumsum()
precision = true_positive / (true_positive + false_positive)
recall = true_positive / num_true_cases
if use_2007_metric:
return measurements.compute_voc2007_average_precision(precision, recall)
else:
return measurements.compute_average_precision(precision, recall)
if __name__ == '__main__':
eval_path = pathlib.Path(args.eval_dir)
eval_path.mkdir(exist_ok=True)
timer = Timer()
class_names = [name.strip() for name in open(args.label_file).readlines()]
if args.dataset_type == "voc":
dataset = VOCDataset(args.dataset, is_test=True)
elif args.dataset_type == 'open_images':
dataset = OpenImagesDataset(args.dataset, dataset_type="test")
elif args.dataset_type == 'coco':
dataset = CocoDatasetTest(args.dataset, args.annfile)
true_case_stat, all_gb_boxes, all_difficult_cases = group_annotation_by_class(dataset)
if args.net == 'vgg16-ssd':
net = create_vgg_ssd(len(class_names), is_test=True)
elif args.net == 'mb1-ssd':
net = create_mobilenetv1_ssd(len(class_names), is_test=True)
elif args.net == 'mb1-ssd-lite':
net = create_mobilenetv1_ssd_lite(len(class_names), is_test=True)
elif args.net == 'sq-ssd-lite':
net = create_squeezenet_ssd_lite(len(class_names), is_test=True)
elif args.net == 'mb2-ssd-lite':
net = create_mobilenetv2_ssd_lite(len(class_names), width_mult=args.mb2_width_mult, is_test=True)
elif args.net == 'mb2-ssd-lite-xiaomi':
net = create_mobilenetv2_ssd_lite_xiaomi(len(class_names), width_mult=args.mb2_width_mult, is_test=True)
elif args.net == 'fairnas-a-ssd-lite':
net = create_fairnas_a_ssd_lite(len(class_names), is_test=True)
elif args.net == 'fairnas-b-ssd-lite':
net = create_fairnas_b_ssd_lite(len(class_names), is_test=True)
else:
logging.fatal("The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.")
parser.print_help(sys.stderr)
sys.exit(1)
timer.start("Load Model")
net.load(args.trained_model)
net = net.to(DEVICE)
print(f'It took {timer.end("Load Model")} seconds to load the model.')
if args.net == 'vgg16-ssd':
predictor = create_vgg_ssd_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb1-ssd':
predictor = create_mobilenetv1_ssd_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb1-ssd-lite':
predictor = create_mobilenetv1_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'sq-ssd-lite':
predictor = create_squeezenet_ssd_lite_predictor(net,nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb2-ssd-lite':
predictor = create_mobilenetv2_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'mb2-ssd-lite-xiaomi':
predictor = create_mobilenetv2_ssd_lite_predictor_xiaomi(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'fairnas-a-ssd-lite':
predictor = create_fairnas_a_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
elif args.net == 'fairnas-b-ssd-lite':
predictor = create_fairnas_b_ssd_lite_predictor(net, nms_method=args.nms_method, device=DEVICE)
else:
logging.fatal("The net type is wrong. It should be one of vgg16-ssd, mb1-ssd and mb1-ssd-lite.")
parser.print_help(sys.stderr)
sys.exit(1)
results = []
for i in range(len(dataset)):
print("process image", i)
timer.start("Load Image")
image = dataset.get_image(i)
print("Load Image: {:4f} seconds.".format(timer.end("Load Image")))
timer.start("Predict")
boxes, labels, probs = predictor.predict(image)
print("Prediction: {:4f} seconds.".format(timer.end("Predict")))
indexes = torch.ones(labels.size(0), 1, dtype=torch.float32) * i
results.append(torch.cat([
indexes.reshape(-1, 1),
labels.reshape(-1, 1).float(),
probs.reshape(-1, 1),
boxes + 1.0 # matlab's indexes start from 1
], dim=1))
results = torch.cat(results)
for class_index, class_name in enumerate(class_names):
if class_index == 0:
continue # ignore background
prediction_path = eval_path / f"det_test_{class_name}.txt"
with open(prediction_path, "w") as f:
sub = results[results[:, 1] == class_index, :]
for i in range(sub.size(0)):
prob_box = sub[i, 2:].numpy()
image_id = dataset.ids[int(sub[i, 0])]
print(
str(image_id) + " " + " ".join([str(v) for v in prob_box]),
file=f
)
aps = []
print("\n\nAverage Precision Per-class:")
for class_index, class_name in enumerate(class_names):
# coco class has _ name
if class_index == 0:
continue
prediction_path = eval_path / f"det_test_{class_name}.txt"
ap = compute_average_precision_per_class(
true_case_stat[class_index],
all_gb_boxes[class_index],
all_difficult_cases[class_index],
prediction_path,
args.iou_threshold,
args.use_2007_metric
)
aps.append(ap)
print(f"{class_name}: {ap}")
print(f"\nAverage Precision Across All Classes:{sum(aps)/len(aps)}")
|
from collections import namedtuple
from datetime import datetime, timedelta
from functools import partial
from pathlib import Path
from typing import Generator, Union, Iterable
from dateutil.tz import tzlocal
from .casters import cast_date, cast_default, cast_recurrence, cast_int
class Calendar:
_key_map = {
'UID': ('uid', None),
'SEQUENCE': ('sequence', cast_int),
'STATUS': ('status', None), # CONFIRMED, TENTATIVE, CANCELLED
'CREATED': ('dt_created', cast_date),
'LAST-MODIFIED': ('dt_modified', cast_date),
'DTSTART': ('dt_start', cast_date),
'DTEND': ('dt_end', cast_date),
'DESCRIPTION': ('description', None),
'SUMMARY': ('summary', None),
'LOCATION': ('location', None),
'RRULE': ('recurrence', cast_recurrence),
}
_event_attrs = [
'uid',
'sequence',
'status',
'dt_created',
'dt_modified',
'dt_start',
'dt_end',
'description',
'summary',
'location',
'recurrence',
]
Event = namedtuple('Event', _event_attrs)
@classmethod
def event_stringify(cls, event: Event) -> str:
"""Create a string representation for an event object.
:param event:
"""
location = event.location
if location:
location = f' [{location}]'
status = event.status
if status:
status = f' [{status}]'
out = f"{event.dt_start} - {event.dt_end} | {event.summary}{location or ""}{status or ""}"
return out
@classmethod
def iter_events_from_file(
cls,
filepath: Union[Path, str],
upcoming_days: int = None
) -> Generator[Event, None, None]:
"""Yields event objects from a given file.
:param filepath:
:param upcoming_days:
"""
if upcoming_days is None:
func = cls.iter_events
else:
func = partial(cls.iter_events_upcoming, days_forward=upcoming_days)
with open(f'{filepath}') as f:
yield from func(f)
@classmethod
def iter_events(cls, source: Iterable) -> Generator[Event, None, None]:
"""Yields event objects from a given source.
.. note:: This won't yield recurrent events automatically, as `.iter_events_upcoming()` does.
:param source:
"""
def init_event_data():
return {}.fromkeys(cls._event_attrs)
event_data = init_event_data()
in_event = False
last_key = ''
shared_params = {
'tz': None,
}
cls_event = cls.Event
key_map = cls._key_map
for line in source:
line = line.rstrip()
if line == 'BEGIN:VEVENT':
last_key = ''
in_event = True
event_data = init_event_data()
continue
if line == 'END:VEVENT':
yield cls_event(**event_data)
last_key = ''
in_event = False
continue
if not in_event:
if line.startswith('X-WR-TIMEZONE:'):
shared_params['tz'] = line.partition(':')[2]
continue
if line.startswith(' '):
key = last_key
value = line[1:]
params = '' # No params support for continuation.
else:
key, _, value = line.partition(':')
key, _, params = key.partition(';')
last_key = key
mapped = key_map.get(key)
if mapped is None:
continue
mapped_key, func_cast = mapped
func_cast = func_cast or cast_default
value = func_cast(value=value, params=params, shared=shared_params)
value_seen = event_data[mapped_key]
if value_seen is None:
value_seen = value
else:
# Continuation (folding) support.
value_seen = f"{value_seen}{value}"
event_data[mapped_key] = value_seen
@classmethod
def iter_events_recurrent(cls, *, event: Event, date_max: datetime) -> Generator[Event, None, None]:
"""Builds and yields recurrent events for a given event till the date.
:param event:
:param date_max:
"""
start = event.dt_start
end = event.dt_end
recurred = []
for recurrent_start in event.recurrence:
recurrent_start = recurrent_start.replace(
hour=start.hour,
minute=start.minute,
second=start.second,
tzinfo=start.tzinfo,
)
recurrent_end = recurrent_start.replace(
hour=end.hour,
minute=end.minute,
second=end.second,
)
recurred.append((recurrent_start, recurrent_end))
if recurrent_start >= date_max:
break
for recurrent_start, recurrent_end in recurred:
yield event._replace(dt_start=recurrent_start, dt_end=recurrent_end)
@classmethod
def iter_events_upcoming(cls, source: Iterable, *, days_forward=30) -> Generator[Event, None, None]:
"""Yields upcoming event objects from a given source for nex N days.
.. note:: This will yield recurrent events automatically, in contrast to `.iter_events()`.
:param source:
:param days_forward:
"""
now = datetime.now(tzlocal())
date_max = now + timedelta(days=days_forward)
for event in cls.iter_events(source):
if event.recurrence:
yield from cls.iter_events_recurrent(event=event, date_max=date_max)
elif now <= event.dt_start <= date_max:
yield event
| from collections import namedtuple
from datetime import datetime, timedelta
from functools import partial
from pathlib import Path
from typing import Generator, Union, Iterable
from dateutil.tz import tzlocal
from .casters import cast_date, cast_default, cast_recurrence, cast_int
class Calendar:
_key_map = {
'UID': ('uid', None),
'SEQUENCE': ('sequence', cast_int),
'STATUS': ('status', None), # CONFIRMED, TENTATIVE, CANCELLED
'CREATED': ('dt_created', cast_date),
'LAST-MODIFIED': ('dt_modified', cast_date),
'DTSTART': ('dt_start', cast_date),
'DTEND': ('dt_end', cast_date),
'DESCRIPTION': ('description', None),
'SUMMARY': ('summary', None),
'LOCATION': ('location', None),
'RRULE': ('recurrence', cast_recurrence),
}
_event_attrs = [
'uid',
'sequence',
'status',
'dt_created',
'dt_modified',
'dt_start',
'dt_end',
'description',
'summary',
'location',
'recurrence',
]
Event = namedtuple('Event', _event_attrs)
@classmethod
def event_stringify(cls, event: Event) -> str:
"""Create a string representation for an event object.
:param event:
"""
location = event.location
if location:
location = f' [{location}]'
status = event.status
if status:
status = f' [{status}]'
out = f"{event.dt_start} - {event.dt_end} | {event.summary}{location or ''}{status or ''}"
return out
@classmethod
def iter_events_from_file(
cls,
filepath: Union[Path, str],
upcoming_days: int = None
) -> Generator[Event, None, None]:
"""Yields event objects from a given file.
:param filepath:
:param upcoming_days:
"""
if upcoming_days is None:
func = cls.iter_events
else:
func = partial(cls.iter_events_upcoming, days_forward=upcoming_days)
with open(f'{filepath}') as f:
yield from func(f)
@classmethod
def iter_events(cls, source: Iterable) -> Generator[Event, None, None]:
"""Yields event objects from a given source.
.. note:: This won't yield recurrent events automatically, as `.iter_events_upcoming()` does.
:param source:
"""
def init_event_data():
return {}.fromkeys(cls._event_attrs)
event_data = init_event_data()
in_event = False
last_key = ''
shared_params = {
'tz': None,
}
cls_event = cls.Event
key_map = cls._key_map
for line in source:
line = line.rstrip()
if line == 'BEGIN:VEVENT':
last_key = ''
in_event = True
event_data = init_event_data()
continue
if line == 'END:VEVENT':
yield cls_event(**event_data)
last_key = ''
in_event = False
continue
if not in_event:
if line.startswith('X-WR-TIMEZONE:'):
shared_params['tz'] = line.partition(':')[2]
continue
if line.startswith(' '):
key = last_key
value = line[1:]
params = '' # No params support for continuation.
else:
key, _, value = line.partition(':')
key, _, params = key.partition(';')
last_key = key
mapped = key_map.get(key)
if mapped is None:
continue
mapped_key, func_cast = mapped
func_cast = func_cast or cast_default
value = func_cast(value=value, params=params, shared=shared_params)
value_seen = event_data[mapped_key]
if value_seen is None:
value_seen = value
else:
# Continuation (folding) support.
value_seen = f"{value_seen}{value}"
event_data[mapped_key] = value_seen
@classmethod
def iter_events_recurrent(cls, *, event: Event, date_max: datetime) -> Generator[Event, None, None]:
"""Builds and yields recurrent events for a given event till the date.
:param event:
:param date_max:
"""
start = event.dt_start
end = event.dt_end
recurred = []
for recurrent_start in event.recurrence:
recurrent_start = recurrent_start.replace(
hour=start.hour,
minute=start.minute,
second=start.second,
tzinfo=start.tzinfo,
)
recurrent_end = recurrent_start.replace(
hour=end.hour,
minute=end.minute,
second=end.second,
)
recurred.append((recurrent_start, recurrent_end))
if recurrent_start >= date_max:
break
for recurrent_start, recurrent_end in recurred:
yield event._replace(dt_start=recurrent_start, dt_end=recurrent_end)
@classmethod
def iter_events_upcoming(cls, source: Iterable, *, days_forward=30) -> Generator[Event, None, None]:
"""Yields upcoming event objects from a given source for nex N days.
.. note:: This will yield recurrent events automatically, in contrast to `.iter_events()`.
:param source:
:param days_forward:
"""
now = datetime.now(tzlocal())
date_max = now + timedelta(days=days_forward)
for event in cls.iter_events(source):
if event.recurrence:
yield from cls.iter_events_recurrent(event=event, date_max=date_max)
elif now <= event.dt_start <= date_max:
yield event
|
"""Utilities defining "Galaxy Flavored Markdown".
This is an extension of markdown designed to allow rendering Galaxy object
references.
The core "Galaxy Flavored Markdown" format should just reference objects
by encoded IDs - but preprocessing should allow for instance workflow objects
to be referenced relative to the workflow (inputs, outputs, steps, etc..) and
potential history flavor would allow objects to be referenced by HID. This
second idea is unimplemented, it is just an example of the general concept of
context specific processing.
"""
import abc
import base64
import codecs
import logging
import os
import re
import shutil
import tempfile
from typing import (
Any,
Dict,
List,
Match,
Optional,
)
import markdown
try:
import weasyprint
except Exception:
weasyprint = None
from galaxy.config import GalaxyAppConfiguration
from galaxy.exceptions import (
MalformedContents,
ServerNotConfiguredForRequest,
)
from galaxy.managers.hdcas import HDCASerializer
from galaxy.managers.jobs import (
JobManager,
summarize_job_metrics,
summarize_job_parameters,
)
from galaxy.model.item_attrs import get_item_annotation_str
from galaxy.model.orm.now import now
from galaxy.schema import PdfDocumentType
from galaxy.schema.tasks import GeneratePdfDownload
from galaxy.util.resources import resource_string
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web.short_term_storage import (
ShortTermStorageMonitor,
storage_context,
)
from .markdown_parse import (
GALAXY_MARKDOWN_FUNCTION_CALL_LINE,
validate_galaxy_markdown,
)
log = logging.getLogger(__name__)
ARG_VAL_CAPTURED_REGEX = r"""(?:([\w_\-\|]+)|\"([^\"]+)\"|\'([^\']+)\')"""
OUTPUT_LABEL_PATTERN = re.compile(r"output=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
INPUT_LABEL_PATTERN = re.compile(r"input=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
STEP_LABEL_PATTERN = re.compile(r"step=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
PATH_LABEL_PATTERN = re.compile(r"path=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
# STEP_OUTPUT_LABEL_PATTERN = re.compile(r'step_output=([\w_\-]+)/([\w_\-]+)')
UNENCODED_ID_PATTERN = re.compile(
r"(history_id|workflow_id|history_dataset_id|history_dataset_collection_id|job_id|invocation_id)=([\d]+)"
)
ENCODED_ID_PATTERN = re.compile(
r"(history_id|workflow_id|history_dataset_id|history_dataset_collection_id|job_id|invocation_id)=([a-z0-9]+)"
)
INVOCATION_SECTION_MARKDOWN_CONTAINER_LINE_PATTERN = re.compile(r"```\s*galaxy\s*")
GALAXY_FENCED_BLOCK = re.compile(r"^```\s*galaxy\s*(.*?)^```", re.MULTILINE ^ re.DOTALL)
VALID_CONTAINER_START_PATTERN = re.compile(r"^```\s+[\w]+.*$")
def ready_galaxy_markdown_for_import(trans, external_galaxy_markdown):
"""Convert from encoded IDs to decoded numeric IDs for storing in the DB."""
_validate(external_galaxy_markdown, internal=False)
def _remap(container, line):
id_match = re.search(ENCODED_ID_PATTERN, line)
object_id = None
if id_match:
object_id = id_match.group(2)
decoded_id = trans.security.decode_id(object_id)
line = line.replace(id_match.group(), "%s=%d" % (id_match.group(1), decoded_id))
return (line, False)
internal_markdown = _remap_galaxy_markdown_calls(_remap, external_galaxy_markdown)
return internal_markdown
class GalaxyInternalMarkdownDirectiveHandler(metaclass=abc.ABCMeta):
def walk(self, trans, internal_galaxy_markdown):
hda_manager = trans.app.hda_manager
history_manager = trans.app.history_manager
workflow_manager = trans.app.workflow_manager
job_manager = JobManager(trans.app)
collection_manager = trans.app.dataset_collection_manager
def _check_object(object_id, line):
if object_id is None:
raise MalformedContents(f"Missing object identifier [{line}].")
def _remap(container, line):
id_match = re.search(UNENCODED_ID_PATTERN, line)
object_id = None
encoded_id = None
if id_match:
object_id = int(id_match.group(2))
encoded_id = trans.security.encode_id(object_id)
line = line.replace(id_match.group(), f"{id_match.group(1)}={encoded_id}")
if container == "history_link":
_check_object(object_id, line)
history = history_manager.get_accessible(object_id, trans.user)
rval = self.handle_history_link(line, history)
elif container == "history_dataset_display":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_link":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_index":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_embedded":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_embedded(line, hda)
elif container == "history_dataset_as_image":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_as_image(line, hda)
elif container == "history_dataset_peek":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_peek(line, hda)
elif container == "history_dataset_info":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_info(line, hda)
elif container == "history_dataset_type":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_type(line, hda)
elif container == "history_dataset_name":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_name(line, hda)
elif container == "workflow_display":
stored_workflow = workflow_manager.get_stored_accessible_workflow(trans, encoded_id)
rval = self.handle_workflow_display(line, stored_workflow)
elif container == "history_dataset_collection_display":
hdca = collection_manager.get_dataset_collection_instance(trans, "history", encoded_id)
rval = self.handle_dataset_collection_display(line, hdca)
elif container == "tool_stdout":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_tool_stdout(line, job)
elif container == "tool_stderr":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_tool_stderr(line, job)
elif container == "job_parameters":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_job_parameters(line, job)
elif container == "job_metrics":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_job_metrics(line, job)
elif container == "generate_galaxy_version":
version = trans.app.config.version_major
rval = self.handle_generate_galaxy_version(line, version)
elif container == "generate_time":
rval = self.handle_generate_time(line, now())
elif container == "invocation_time":
invocation = workflow_manager.get_invocation(trans, object_id)
rval = self.handle_invocation_time(line, invocation)
elif container == "visualization":
rval = None
else:
raise MalformedContents(f"Unknown Galaxy Markdown directive encountered [{container}].")
if rval is not None:
return rval
else:
return (line, False)
def _remap_container(container, line):
try:
return _remap(container, line)
except Exception as e:
return self.handle_error(container, line, str(e))
export_markdown = _remap_galaxy_markdown_calls(_remap_container, internal_galaxy_markdown)
return export_markdown
@abc.abstractmethod
def handle_history_link(self, line, history):
pass
@abc.abstractmethod
def handle_dataset_display(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_as_image(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_peek(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_embedded(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_info(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_name(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_type(self, line, hda):
pass
@abc.abstractmethod
def handle_workflow_display(self, line, stored_workflow):
pass
@abc.abstractmethod
def handle_dataset_collection_display(self, line, hdca):
pass
@abc.abstractmethod
def handle_tool_stdout(self, line, job):
pass
@abc.abstractmethod
def handle_tool_stderr(self, line, job):
pass
@abc.abstractmethod
def handle_job_metrics(self, line, job):
pass
@abc.abstractmethod
def handle_job_parameters(self, line, job):
pass
@abc.abstractmethod
def handle_generate_galaxy_version(self, line, galaxy_version):
pass
@abc.abstractmethod
def handle_generate_time(self, line, date):
pass
@abc.abstractmethod
def handle_invocation_time(self, line, date):
pass
@abc.abstractmethod
def handle_error(self, container, line, error):
pass
class ReadyForExportMarkdownDirectiveHandler(GalaxyInternalMarkdownDirectiveHandler):
def __init__(self, trans, extra_rendering_data=None):
extra_rendering_data = extra_rendering_data or {}
self.trans = trans
self.extra_rendering_data = extra_rendering_data
def ensure_rendering_data_for(self, object_type, obj):
encoded_id = self.trans.security.encode_id(obj.id)
if object_type not in self.extra_rendering_data:
self.extra_rendering_data[object_type] = {}
object_type_data = self.extra_rendering_data[object_type]
if encoded_id not in object_type_data:
object_type_data[encoded_id] = {}
return object_type_data[encoded_id]
def extend_history_dataset_rendering_data(self, obj, key, val, default_val):
self.ensure_rendering_data_for("history_datasets", obj)[key] = val or default_val
def handle_dataset_display(self, line, hda):
self.handle_dataset_name(line, hda)
self.handle_dataset_type(line, hda)
def handle_dataset_embedded(self, line, hda):
self.handle_dataset_name(line, hda)
def handle_dataset_peek(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "peek", hda.peek, "*No Dataset Peek Available*")
def handle_dataset_info(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "info", hda.info, "*No Dataset Info Available*")
def handle_workflow_display(self, line, stored_workflow):
self.ensure_rendering_data_for("workflows", stored_workflow)["name"] = stored_workflow.name
def handle_dataset_collection_display(self, line, hdca):
hdca_serializer = HDCASerializer(self.trans.app)
hdca_view = hdca_serializer.serialize_to_view(hdca, user=self.trans.user, trans=self.trans, view="summary")
self.ensure_rendering_data_for("history_dataset_collections", hdca).update(hdca_view)
def handle_tool_stdout(self, line, job):
self.ensure_rendering_data_for("jobs", job)["tool_stdout"] = job.tool_stdout or "*No Standard Output Available*"
def handle_tool_stderr(self, line, job):
self.ensure_rendering_data_for("jobs", job)["tool_stderr"] = job.tool_stderr or "*No Standard Error Available*"
def handle_history_link(self, line, history):
self.ensure_rendering_data_for("histories", history)["name"] = history.name
# Following three cases - the client side widgets have everything they need
# from the encoded ID. Don't implement a default on the base class though because
# it is good to force both Client and PDF/HTML export to deal with each new directive
# explicitly.
def handle_dataset_as_image(self, line, hda):
pass
def handle_job_metrics(self, line, job):
pass
def handle_job_parameters(self, line, job):
pass
def handle_generate_galaxy_version(self, line, generate_version):
pass
def handle_generate_time(self, line, generate_time):
pass
def handle_invocation_time(self, line, invocation):
self.ensure_rendering_data_for("invocations", invocation)["create_time"] = invocation.create_time.isoformat()
def handle_dataset_type(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "ext", hda.ext, "*Unknown dataset type*")
def handle_dataset_name(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "name", hda.name, "*Unknown dataset name*")
def handle_error(self, container, line, error):
if "errors" not in self.extra_rendering_data:
self.extra_rendering_data["errors"] = []
self.extra_rendering_data["errors"].append(
{
"error": error,
"line": line,
"container": container,
}
)
return (line, False)
def ready_galaxy_markdown_for_export(trans, internal_galaxy_markdown):
"""Fill in details needed to render Galaxy flavored markdown.
Take it from a minimal internal version to an externally render-able version
with more details populated and actual IDs replaced with encoded IDs to render
external links. Return expanded markdown and extra data useful for rendering
custom container tags.
"""
extra_rendering_data = {
"generate_time": now().isoformat(),
"generate_version": trans.app.config.version_major,
}
# Walk Galaxy directives inside the Galaxy Markdown and collect dict-ified data
# needed to render this efficiently.
directive_handler = ReadyForExportMarkdownDirectiveHandler(trans, extra_rendering_data)
export_markdown = directive_handler.walk(trans, internal_galaxy_markdown)
return export_markdown, extra_rendering_data
class ToBasicMarkdownDirectiveHandler(GalaxyInternalMarkdownDirectiveHandler):
def __init__(self, trans, markdown_formatting_helpers):
self.trans = trans
self.markdown_formatting_helpers = markdown_formatting_helpers
def handle_dataset_display(self, line, hda):
name = hda.name or ""
markdown = "---\n"
markdown += f"**Dataset:** {name}\n\n"
markdown += self._display_dataset_content(hda)
markdown += "\n---\n"
return (markdown, True)
def handle_dataset_embedded(self, line, hda):
datatype = hda.datatype
markdown = ""
# subtly different than below since no Contents: prefix and new lines and such.
if datatype is None:
markdown += "*cannot display - cannot format unknown datatype*\n\n"
else:
markdown += datatype.display_as_markdown(hda, self.markdown_formatting_helpers)
return (markdown, True)
def _display_dataset_content(self, hda, header="Contents"):
datatype = hda.datatype
markdown = ""
if datatype is None:
markdown += f"**{header}:** *cannot display - cannot format unknown datatype*\n\n"
else:
markdown += f"**{header}:**\n"
markdown += datatype.display_as_markdown(hda, self.markdown_formatting_helpers)
return markdown
def handle_dataset_as_image(self, line, hda):
dataset = hda.dataset
name = hda.name or ""
path_match = re.search(PATH_LABEL_PATTERN, line)
if path_match:
filepath = path_match.group(2)
file = os.path.join(hda.extra_files_path, filepath)
else:
file = dataset.file_name
with open(file, "rb") as f:
base64_image_data = base64.b64encode(f.read()).decode("utf-8")
rval = (f"", True)
return rval
def handle_history_link(self, line, history):
if history:
content = self.markdown_formatting_helpers.literal_via_fence(history.name)
else:
content = "*No History available*"
return (content, True)
def handle_dataset_peek(self, line, hda):
if hda.peek:
content = self.markdown_formatting_helpers.literal_via_fence(hda.peek)
else:
content = "*No Dataset Peek Available*"
return (content, True)
def handle_dataset_info(self, line, hda):
if hda.info:
content = self.markdown_formatting_helpers.literal_via_fence(hda.info)
else:
content = "*No Dataset Info Available*"
return (content, True)
def handle_workflow_display(self, line, stored_workflow):
# workflows/display.mako as markdown... meh...
markdown = "---\n"
markdown += f"**Workflow:** {stored_workflow.name}\n\n"
markdown += "**Steps:**\n\n"
markdown += "|Step|Annotation|\n"
markdown += "|----|----------|\n"
# Pass two should add tool information, labels, etc.. but
# it requires module_injector and such.
for order_index, step in enumerate(stored_workflow.latest_workflow.steps):
annotation = get_item_annotation_str(self.trans.sa_session, self.trans.user, step) or ""
markdown += "|{}|{}|\n".format(step.label or "Step %d" % (order_index + 1), annotation)
markdown += "\n---\n"
return (markdown, True)
def handle_dataset_collection_display(self, line, hdca):
name = hdca.name or ""
# put it in a list to hack around no nonlocal on Python 2.
markdown_wrapper = [f"**Dataset Collection:** {name}\n\n"]
def walk_elements(collection, element_prefix=""):
if ":" in collection.collection_type:
for element in collection.elements:
walk_elements(element.child_collection, f"{element_prefix + element.element_identifier}:")
else:
for element in collection.elements:
markdown_wrapper[0] += f"**Element:** {element_prefix}{element.element_identifier}\n\n"
markdown_wrapper[0] += self._display_dataset_content(element.hda, header="Element Contents")
walk_elements(hdca.collection)
markdown = f"---\n{markdown_wrapper[0]}\n---\n"
return (markdown, True)
def handle_tool_stdout(self, line, job):
stdout = job.tool_stdout or "*No Standard Output Available*"
return (f"**Standard Output:** {stdout}", True)
def handle_tool_stderr(self, line, job):
stderr = job.tool_stderr or "*No Standard Error Available*"
return (f"**Standard Error:** {stderr}", True)
def handle_job_metrics(self, line, job):
job_metrics = summarize_job_metrics(self.trans, job)
metrics_by_plugin: Dict[str, Dict[str, Any]] = {}
for job_metric in job_metrics:
plugin = job_metric["plugin"]
if plugin not in metrics_by_plugin:
metrics_by_plugin[plugin] = {}
metrics_by_plugin[plugin][job_metric["title"]] = job_metric["value"]
markdown = ""
for metric_plugin, metrics_for_plugin in metrics_by_plugin.items():
markdown += f"**{metric_plugin}**\n\n"
markdown += "| | |\n|---|--|\n"
for title, value in metrics_for_plugin.items():
markdown += f"| {title} | {value} |\n"
return (markdown, True)
def handle_job_parameters(self, line, job):
markdown = """
| Input Parameter | Value |
|-----------------|-------|
"""
parameters = summarize_job_parameters(self.trans, job)["parameters"]
for parameter in parameters:
markdown += "| "
depth = parameter["depth"]
if depth > 1:
markdown += f"{">" * (parameter["depth"] - 1)} "
markdown += parameter["text"]
markdown += " | "
value = parameter["value"]
if isinstance(value, list):
markdown += ", ".join(f"{p["hid"]}: {p["name"]}" for p in value)
else:
markdown += value
markdown += " |\n"
return (markdown, True)
def handle_generate_galaxy_version(self, line, generate_version):
if generate_version:
content = self.markdown_formatting_helpers.literal_via_fence(generate_version)
else:
content = "*No Galaxy Version Available*"
return (content, True)
def handle_generate_time(self, line, generate_time):
content = self.markdown_formatting_helpers.literal_via_fence(generate_time.isoformat())
return (content, True)
def handle_invocation_time(self, line, invocation):
content = self.markdown_formatting_helpers.literal_via_fence(invocation.create_time.isoformat())
return (content, True)
def handle_dataset_name(self, line, hda):
if hda.name:
content = self.markdown_formatting_helpers.literal_via_fence(hda.name)
else:
content = "*No Dataset Name Available*"
return (content, True)
def handle_dataset_type(self, line, hda):
if hda.ext:
content = self.markdown_formatting_helpers.literal_via_fence(hda.ext)
else:
content = "*No Dataset Type Available*"
return (content, True)
def handle_error(self, container, line, error):
return (line, False)
class MarkdownFormatHelpers:
"""Inject common markdown formatting helpers for per-datatype rendering."""
@staticmethod
def literal_via_fence(content):
return "\n%s\n" % "\n".join(f" {line}" for line in content.splitlines())
@staticmethod
def indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
@staticmethod
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre>"
def to_basic_markdown(trans, internal_galaxy_markdown: str) -> str:
"""Replace Galaxy Markdown extensions with plain Markdown for PDF/HTML export."""
markdown_formatting_helpers = MarkdownFormatHelpers()
directive_handler = ToBasicMarkdownDirectiveHandler(trans, markdown_formatting_helpers)
plain_markdown = directive_handler.walk(trans, internal_galaxy_markdown)
return plain_markdown
def to_html(basic_markdown: str) -> str:
# Allow data: urls so we can embed images.
html = sanitize_html(markdown.markdown(basic_markdown, extensions=["tables"]), allow_data_urls=True)
return html
def to_pdf_raw(basic_markdown: str, css_paths: Optional[List[str]] = None) -> bytes:
"""Convert RAW markdown with specified CSS paths into bytes of a PDF."""
css_paths = css_paths or []
as_html = to_html(basic_markdown)
directory = tempfile.mkdtemp("gxmarkdown")
index = os.path.join(directory, "index.html")
try:
output_file = codecs.open(index, "w", encoding="utf-8", errors="xmlcharrefreplace")
output_file.write(as_html)
output_file.close()
html = weasyprint.HTML(filename=index)
stylesheets = [weasyprint.CSS(string=resource_string(__package__, "markdown_export_base.css"))]
for css_path in css_paths:
with open(css_path) as f:
css_content = f.read()
css = weasyprint.CSS(string=css_content)
stylesheets.append(css)
return html.write_pdf(stylesheets=stylesheets)
finally:
shutil.rmtree(directory)
def weasyprint_available() -> bool:
return weasyprint is not None
def _check_can_convert_to_pdf_or_raise():
"""Checks if the HTML to PDF converter is available."""
if not weasyprint_available():
raise ServerNotConfiguredForRequest("PDF conversion service not available.")
def internal_galaxy_markdown_to_pdf(trans, internal_galaxy_markdown: str, document_type: PdfDocumentType) -> bytes:
_check_can_convert_to_pdf_or_raise()
basic_markdown = to_basic_markdown(trans, internal_galaxy_markdown)
config = trans.app.config
return to_branded_pdf(basic_markdown, document_type, config)
def generate_branded_pdf(
request: GeneratePdfDownload, config: GalaxyAppConfiguration, short_term_storage_monitor: ShortTermStorageMonitor
):
with storage_context(request.short_term_storage_request_id, short_term_storage_monitor) as target:
raw_contents = to_branded_pdf(
request.basic_markdown,
request.document_type,
config,
)
with open(target.path, "wb") as f:
f.write(raw_contents)
def to_branded_pdf(basic_markdown: str, document_type: PdfDocumentType, config: GalaxyAppConfiguration) -> bytes:
document_type_prologue = getattr(config, f"markdown_export_prologue_{document_type}s", "") or ""
document_type_epilogue = getattr(config, f"markdown_export_epilogue_{document_type}s", "") or ""
general_prologue = config.markdown_export_prologue or ""
general_epilogue = config.markdown_export_epilogue or ""
effective_prologue = document_type_prologue or general_prologue
effective_epilogue = document_type_epilogue or general_epilogue
branded_markdown = effective_prologue + basic_markdown + effective_epilogue
css_paths = []
general_css_path = config.markdown_export_css
document_type_css_path = getattr(config, f"markdown_export_css_{document_type}s", None)
if general_css_path and os.path.exists(general_css_path):
css_paths.append(general_css_path)
if document_type_css_path and os.path.exists(document_type_css_path):
css_paths.append(document_type_css_path)
return to_pdf_raw(branded_markdown, css_paths=css_paths)
def resolve_invocation_markdown(trans, invocation, workflow_markdown):
"""Resolve invocation objects to convert markdown to 'internal' representation.
Replace references to abstract workflow parts with actual galaxy object IDs corresponding
to the actual executed workflow. For instance:
convert output=name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
convert input=name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
convert step=name -to- job_id=<id>
Also expand/convert workflow invocation specific container sections into actual Galaxy
markdown - these containers include: invocation_inputs, invocation_outputs, invocation_workflow.
Hopefully this list will be expanded to include invocation_qc.
"""
# TODO: convert step outputs?
# convert step_output=index/name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
def _section_remap(container, line):
section_markdown = ""
if container == "invocation_outputs":
for output_assoc in invocation.output_associations:
if not output_assoc.workflow_output.label:
continue
if output_assoc.history_content_type == "dataset":
section_markdown += """#### Output Dataset: {}
```galaxy
history_dataset_display(output="{}")
```
""".format(
output_assoc.workflow_output.label, output_assoc.workflow_output.label
)
else:
section_markdown += """#### Output Dataset Collection: {}
```galaxy
history_dataset_collection_display(output="{}")
```
""".format(
output_assoc.workflow_output.label, output_assoc.workflow_output.label
)
elif container == "invocation_inputs":
for input_assoc in invocation.input_associations:
if not input_assoc.workflow_step.label:
continue
if input_assoc.history_content_type == "dataset":
section_markdown += """#### Input Dataset: {}
```galaxy
history_dataset_display(input="{}")
```
""".format(
input_assoc.workflow_step.label, input_assoc.workflow_step.label
)
else:
section_markdown += """#### Input Dataset Collection: {}
```galaxy
history_dataset_collection_display(input={})
```
""".format(
input_assoc.workflow_step.label, input_assoc.workflow_step.label
)
else:
return line, False
return section_markdown, True
def _remap(container, line):
if container == "workflow_display":
# TODO: this really should be workflow id not stored workflow id but the API
# it consumes wants the stored id.
return (f"workflow_display(workflow_id={invocation.workflow.stored_workflow.id})\n", False)
if container == "history_link":
return (f"history_link(history_id={invocation.history.id})\n", False)
if container == "invocation_time":
return (f"invocation_time(invocation_id={invocation.id})\n", False)
ref_object_type = None
output_match = re.search(OUTPUT_LABEL_PATTERN, line)
input_match = re.search(INPUT_LABEL_PATTERN, line)
step_match = re.search(STEP_LABEL_PATTERN, line)
def find_non_empty_group(match):
for group in match.groups():
if group:
return group
target_match: Optional[Match]
ref_object: Optional[Any]
if output_match:
target_match = output_match
name = find_non_empty_group(target_match)
ref_object = invocation.get_output_object(name)
elif input_match:
target_match = input_match
name = find_non_empty_group(target_match)
ref_object = invocation.get_input_object(name)
elif step_match:
target_match = step_match
name = find_non_empty_group(target_match)
ref_object_type = "job"
ref_object = invocation.step_invocation_for_label(name).job
else:
target_match = None
ref_object = None
if ref_object:
assert target_match # tell type system, this is set when ref_object is set
if ref_object_type is None:
if ref_object.history_content_type == "dataset":
ref_object_type = "history_dataset"
else:
ref_object_type = "history_dataset_collection"
line = line.replace(target_match.group(), f"{ref_object_type}_id={ref_object.id}")
return (line, False)
workflow_markdown = _remap_galaxy_markdown_calls(
_section_remap,
workflow_markdown,
)
galaxy_markdown = _remap_galaxy_markdown_calls(_remap, workflow_markdown)
return galaxy_markdown
def _remap_galaxy_markdown_containers(func, markdown):
new_markdown = markdown
searching_from = 0
while True:
from_markdown = new_markdown[searching_from:]
match = re.search(GALAXY_FENCED_BLOCK, from_markdown)
if match is not None:
replace = match.group(1)
(replacement, whole_block) = func(replace)
if whole_block:
start_pos = match.start()
end_pos = match.end()
else:
start_pos = match.start(1)
end_pos = match.end(1)
start_pos = start_pos + searching_from
end_pos = end_pos + searching_from
new_markdown = new_markdown[:start_pos] + replacement + new_markdown[end_pos:]
searching_from = start_pos + len(replacement)
else:
break
return new_markdown
def _remap_galaxy_markdown_calls(func, markdown):
def _remap_container(container):
matching_line = None
for line in container.splitlines():
if GALAXY_MARKDOWN_FUNCTION_CALL_LINE.match(line):
assert matching_line is None
matching_line = line
if matching_line:
match = GALAXY_MARKDOWN_FUNCTION_CALL_LINE.match(line)
assert match # already matched
return func(match.group(1), f"{matching_line}\n")
else:
return (container, True)
return _remap_galaxy_markdown_containers(_remap_container, markdown)
def _validate(*args, **kwds):
"""Light wrapper around validate_galaxy_markdown to throw galaxy exceptions instead of ValueError."""
try:
return validate_galaxy_markdown(*args, **kwds)
except ValueError as e:
raise MalformedContents(str(e))
__all__ = (
"internal_galaxy_markdown_to_pdf",
"ready_galaxy_markdown_for_export",
"ready_galaxy_markdown_for_import",
"resolve_invocation_markdown",
"to_basic_markdown",
)
| """Utilities defining "Galaxy Flavored Markdown".
This is an extension of markdown designed to allow rendering Galaxy object
references.
The core "Galaxy Flavored Markdown" format should just reference objects
by encoded IDs - but preprocessing should allow for instance workflow objects
to be referenced relative to the workflow (inputs, outputs, steps, etc..) and
potential history flavor would allow objects to be referenced by HID. This
second idea is unimplemented, it is just an example of the general concept of
context specific processing.
"""
import abc
import base64
import codecs
import logging
import os
import re
import shutil
import tempfile
from typing import (
Any,
Dict,
List,
Match,
Optional,
)
import markdown
try:
import weasyprint
except Exception:
weasyprint = None
from galaxy.config import GalaxyAppConfiguration
from galaxy.exceptions import (
MalformedContents,
ServerNotConfiguredForRequest,
)
from galaxy.managers.hdcas import HDCASerializer
from galaxy.managers.jobs import (
JobManager,
summarize_job_metrics,
summarize_job_parameters,
)
from galaxy.model.item_attrs import get_item_annotation_str
from galaxy.model.orm.now import now
from galaxy.schema import PdfDocumentType
from galaxy.schema.tasks import GeneratePdfDownload
from galaxy.util.resources import resource_string
from galaxy.util.sanitize_html import sanitize_html
from galaxy.web.short_term_storage import (
ShortTermStorageMonitor,
storage_context,
)
from .markdown_parse import (
GALAXY_MARKDOWN_FUNCTION_CALL_LINE,
validate_galaxy_markdown,
)
log = logging.getLogger(__name__)
ARG_VAL_CAPTURED_REGEX = r"""(?:([\w_\-\|]+)|\"([^\"]+)\"|\'([^\']+)\')"""
OUTPUT_LABEL_PATTERN = re.compile(r"output=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
INPUT_LABEL_PATTERN = re.compile(r"input=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
STEP_LABEL_PATTERN = re.compile(r"step=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
PATH_LABEL_PATTERN = re.compile(r"path=\s*%s\s*" % ARG_VAL_CAPTURED_REGEX)
# STEP_OUTPUT_LABEL_PATTERN = re.compile(r'step_output=([\w_\-]+)/([\w_\-]+)')
UNENCODED_ID_PATTERN = re.compile(
r"(history_id|workflow_id|history_dataset_id|history_dataset_collection_id|job_id|invocation_id)=([\d]+)"
)
ENCODED_ID_PATTERN = re.compile(
r"(history_id|workflow_id|history_dataset_id|history_dataset_collection_id|job_id|invocation_id)=([a-z0-9]+)"
)
INVOCATION_SECTION_MARKDOWN_CONTAINER_LINE_PATTERN = re.compile(r"```\s*galaxy\s*")
GALAXY_FENCED_BLOCK = re.compile(r"^```\s*galaxy\s*(.*?)^```", re.MULTILINE ^ re.DOTALL)
VALID_CONTAINER_START_PATTERN = re.compile(r"^```\s+[\w]+.*$")
def ready_galaxy_markdown_for_import(trans, external_galaxy_markdown):
"""Convert from encoded IDs to decoded numeric IDs for storing in the DB."""
_validate(external_galaxy_markdown, internal=False)
def _remap(container, line):
id_match = re.search(ENCODED_ID_PATTERN, line)
object_id = None
if id_match:
object_id = id_match.group(2)
decoded_id = trans.security.decode_id(object_id)
line = line.replace(id_match.group(), "%s=%d" % (id_match.group(1), decoded_id))
return (line, False)
internal_markdown = _remap_galaxy_markdown_calls(_remap, external_galaxy_markdown)
return internal_markdown
class GalaxyInternalMarkdownDirectiveHandler(metaclass=abc.ABCMeta):
def walk(self, trans, internal_galaxy_markdown):
hda_manager = trans.app.hda_manager
history_manager = trans.app.history_manager
workflow_manager = trans.app.workflow_manager
job_manager = JobManager(trans.app)
collection_manager = trans.app.dataset_collection_manager
def _check_object(object_id, line):
if object_id is None:
raise MalformedContents(f"Missing object identifier [{line}].")
def _remap(container, line):
id_match = re.search(UNENCODED_ID_PATTERN, line)
object_id = None
encoded_id = None
if id_match:
object_id = int(id_match.group(2))
encoded_id = trans.security.encode_id(object_id)
line = line.replace(id_match.group(), f"{id_match.group(1)}={encoded_id}")
if container == "history_link":
_check_object(object_id, line)
history = history_manager.get_accessible(object_id, trans.user)
rval = self.handle_history_link(line, history)
elif container == "history_dataset_display":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_link":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_index":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_display(line, hda)
elif container == "history_dataset_embedded":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_embedded(line, hda)
elif container == "history_dataset_as_image":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_as_image(line, hda)
elif container == "history_dataset_peek":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_peek(line, hda)
elif container == "history_dataset_info":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_info(line, hda)
elif container == "history_dataset_type":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_type(line, hda)
elif container == "history_dataset_name":
_check_object(object_id, line)
hda = hda_manager.get_accessible(object_id, trans.user)
rval = self.handle_dataset_name(line, hda)
elif container == "workflow_display":
stored_workflow = workflow_manager.get_stored_accessible_workflow(trans, encoded_id)
rval = self.handle_workflow_display(line, stored_workflow)
elif container == "history_dataset_collection_display":
hdca = collection_manager.get_dataset_collection_instance(trans, "history", encoded_id)
rval = self.handle_dataset_collection_display(line, hdca)
elif container == "tool_stdout":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_tool_stdout(line, job)
elif container == "tool_stderr":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_tool_stderr(line, job)
elif container == "job_parameters":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_job_parameters(line, job)
elif container == "job_metrics":
job = job_manager.get_accessible_job(trans, object_id)
rval = self.handle_job_metrics(line, job)
elif container == "generate_galaxy_version":
version = trans.app.config.version_major
rval = self.handle_generate_galaxy_version(line, version)
elif container == "generate_time":
rval = self.handle_generate_time(line, now())
elif container == "invocation_time":
invocation = workflow_manager.get_invocation(trans, object_id)
rval = self.handle_invocation_time(line, invocation)
elif container == "visualization":
rval = None
else:
raise MalformedContents(f"Unknown Galaxy Markdown directive encountered [{container}].")
if rval is not None:
return rval
else:
return (line, False)
def _remap_container(container, line):
try:
return _remap(container, line)
except Exception as e:
return self.handle_error(container, line, str(e))
export_markdown = _remap_galaxy_markdown_calls(_remap_container, internal_galaxy_markdown)
return export_markdown
@abc.abstractmethod
def handle_history_link(self, line, history):
pass
@abc.abstractmethod
def handle_dataset_display(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_as_image(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_peek(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_embedded(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_info(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_name(self, line, hda):
pass
@abc.abstractmethod
def handle_dataset_type(self, line, hda):
pass
@abc.abstractmethod
def handle_workflow_display(self, line, stored_workflow):
pass
@abc.abstractmethod
def handle_dataset_collection_display(self, line, hdca):
pass
@abc.abstractmethod
def handle_tool_stdout(self, line, job):
pass
@abc.abstractmethod
def handle_tool_stderr(self, line, job):
pass
@abc.abstractmethod
def handle_job_metrics(self, line, job):
pass
@abc.abstractmethod
def handle_job_parameters(self, line, job):
pass
@abc.abstractmethod
def handle_generate_galaxy_version(self, line, galaxy_version):
pass
@abc.abstractmethod
def handle_generate_time(self, line, date):
pass
@abc.abstractmethod
def handle_invocation_time(self, line, date):
pass
@abc.abstractmethod
def handle_error(self, container, line, error):
pass
class ReadyForExportMarkdownDirectiveHandler(GalaxyInternalMarkdownDirectiveHandler):
def __init__(self, trans, extra_rendering_data=None):
extra_rendering_data = extra_rendering_data or {}
self.trans = trans
self.extra_rendering_data = extra_rendering_data
def ensure_rendering_data_for(self, object_type, obj):
encoded_id = self.trans.security.encode_id(obj.id)
if object_type not in self.extra_rendering_data:
self.extra_rendering_data[object_type] = {}
object_type_data = self.extra_rendering_data[object_type]
if encoded_id not in object_type_data:
object_type_data[encoded_id] = {}
return object_type_data[encoded_id]
def extend_history_dataset_rendering_data(self, obj, key, val, default_val):
self.ensure_rendering_data_for("history_datasets", obj)[key] = val or default_val
def handle_dataset_display(self, line, hda):
self.handle_dataset_name(line, hda)
self.handle_dataset_type(line, hda)
def handle_dataset_embedded(self, line, hda):
self.handle_dataset_name(line, hda)
def handle_dataset_peek(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "peek", hda.peek, "*No Dataset Peek Available*")
def handle_dataset_info(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "info", hda.info, "*No Dataset Info Available*")
def handle_workflow_display(self, line, stored_workflow):
self.ensure_rendering_data_for("workflows", stored_workflow)["name"] = stored_workflow.name
def handle_dataset_collection_display(self, line, hdca):
hdca_serializer = HDCASerializer(self.trans.app)
hdca_view = hdca_serializer.serialize_to_view(hdca, user=self.trans.user, trans=self.trans, view="summary")
self.ensure_rendering_data_for("history_dataset_collections", hdca).update(hdca_view)
def handle_tool_stdout(self, line, job):
self.ensure_rendering_data_for("jobs", job)["tool_stdout"] = job.tool_stdout or "*No Standard Output Available*"
def handle_tool_stderr(self, line, job):
self.ensure_rendering_data_for("jobs", job)["tool_stderr"] = job.tool_stderr or "*No Standard Error Available*"
def handle_history_link(self, line, history):
self.ensure_rendering_data_for("histories", history)["name"] = history.name
# Following three cases - the client side widgets have everything they need
# from the encoded ID. Don't implement a default on the base class though because
# it is good to force both Client and PDF/HTML export to deal with each new directive
# explicitly.
def handle_dataset_as_image(self, line, hda):
pass
def handle_job_metrics(self, line, job):
pass
def handle_job_parameters(self, line, job):
pass
def handle_generate_galaxy_version(self, line, generate_version):
pass
def handle_generate_time(self, line, generate_time):
pass
def handle_invocation_time(self, line, invocation):
self.ensure_rendering_data_for("invocations", invocation)["create_time"] = invocation.create_time.isoformat()
def handle_dataset_type(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "ext", hda.ext, "*Unknown dataset type*")
def handle_dataset_name(self, line, hda):
self.extend_history_dataset_rendering_data(hda, "name", hda.name, "*Unknown dataset name*")
def handle_error(self, container, line, error):
if "errors" not in self.extra_rendering_data:
self.extra_rendering_data["errors"] = []
self.extra_rendering_data["errors"].append(
{
"error": error,
"line": line,
"container": container,
}
)
return (line, False)
def ready_galaxy_markdown_for_export(trans, internal_galaxy_markdown):
"""Fill in details needed to render Galaxy flavored markdown.
Take it from a minimal internal version to an externally render-able version
with more details populated and actual IDs replaced with encoded IDs to render
external links. Return expanded markdown and extra data useful for rendering
custom container tags.
"""
extra_rendering_data = {
"generate_time": now().isoformat(),
"generate_version": trans.app.config.version_major,
}
# Walk Galaxy directives inside the Galaxy Markdown and collect dict-ified data
# needed to render this efficiently.
directive_handler = ReadyForExportMarkdownDirectiveHandler(trans, extra_rendering_data)
export_markdown = directive_handler.walk(trans, internal_galaxy_markdown)
return export_markdown, extra_rendering_data
class ToBasicMarkdownDirectiveHandler(GalaxyInternalMarkdownDirectiveHandler):
def __init__(self, trans, markdown_formatting_helpers):
self.trans = trans
self.markdown_formatting_helpers = markdown_formatting_helpers
def handle_dataset_display(self, line, hda):
name = hda.name or ""
markdown = "---\n"
markdown += f"**Dataset:** {name}\n\n"
markdown += self._display_dataset_content(hda)
markdown += "\n---\n"
return (markdown, True)
def handle_dataset_embedded(self, line, hda):
datatype = hda.datatype
markdown = ""
# subtly different than below since no Contents: prefix and new lines and such.
if datatype is None:
markdown += "*cannot display - cannot format unknown datatype*\n\n"
else:
markdown += datatype.display_as_markdown(hda, self.markdown_formatting_helpers)
return (markdown, True)
def _display_dataset_content(self, hda, header="Contents"):
datatype = hda.datatype
markdown = ""
if datatype is None:
markdown += f"**{header}:** *cannot display - cannot format unknown datatype*\n\n"
else:
markdown += f"**{header}:**\n"
markdown += datatype.display_as_markdown(hda, self.markdown_formatting_helpers)
return markdown
def handle_dataset_as_image(self, line, hda):
dataset = hda.dataset
name = hda.name or ""
path_match = re.search(PATH_LABEL_PATTERN, line)
if path_match:
filepath = path_match.group(2)
file = os.path.join(hda.extra_files_path, filepath)
else:
file = dataset.file_name
with open(file, "rb") as f:
base64_image_data = base64.b64encode(f.read()).decode("utf-8")
rval = (f"", True)
return rval
def handle_history_link(self, line, history):
if history:
content = self.markdown_formatting_helpers.literal_via_fence(history.name)
else:
content = "*No History available*"
return (content, True)
def handle_dataset_peek(self, line, hda):
if hda.peek:
content = self.markdown_formatting_helpers.literal_via_fence(hda.peek)
else:
content = "*No Dataset Peek Available*"
return (content, True)
def handle_dataset_info(self, line, hda):
if hda.info:
content = self.markdown_formatting_helpers.literal_via_fence(hda.info)
else:
content = "*No Dataset Info Available*"
return (content, True)
def handle_workflow_display(self, line, stored_workflow):
# workflows/display.mako as markdown... meh...
markdown = "---\n"
markdown += f"**Workflow:** {stored_workflow.name}\n\n"
markdown += "**Steps:**\n\n"
markdown += "|Step|Annotation|\n"
markdown += "|----|----------|\n"
# Pass two should add tool information, labels, etc.. but
# it requires module_injector and such.
for order_index, step in enumerate(stored_workflow.latest_workflow.steps):
annotation = get_item_annotation_str(self.trans.sa_session, self.trans.user, step) or ""
markdown += "|{}|{}|\n".format(step.label or "Step %d" % (order_index + 1), annotation)
markdown += "\n---\n"
return (markdown, True)
def handle_dataset_collection_display(self, line, hdca):
name = hdca.name or ""
# put it in a list to hack around no nonlocal on Python 2.
markdown_wrapper = [f"**Dataset Collection:** {name}\n\n"]
def walk_elements(collection, element_prefix=""):
if ":" in collection.collection_type:
for element in collection.elements:
walk_elements(element.child_collection, f"{element_prefix + element.element_identifier}:")
else:
for element in collection.elements:
markdown_wrapper[0] += f"**Element:** {element_prefix}{element.element_identifier}\n\n"
markdown_wrapper[0] += self._display_dataset_content(element.hda, header="Element Contents")
walk_elements(hdca.collection)
markdown = f"---\n{markdown_wrapper[0]}\n---\n"
return (markdown, True)
def handle_tool_stdout(self, line, job):
stdout = job.tool_stdout or "*No Standard Output Available*"
return (f"**Standard Output:** {stdout}", True)
def handle_tool_stderr(self, line, job):
stderr = job.tool_stderr or "*No Standard Error Available*"
return (f"**Standard Error:** {stderr}", True)
def handle_job_metrics(self, line, job):
job_metrics = summarize_job_metrics(self.trans, job)
metrics_by_plugin: Dict[str, Dict[str, Any]] = {}
for job_metric in job_metrics:
plugin = job_metric["plugin"]
if plugin not in metrics_by_plugin:
metrics_by_plugin[plugin] = {}
metrics_by_plugin[plugin][job_metric["title"]] = job_metric["value"]
markdown = ""
for metric_plugin, metrics_for_plugin in metrics_by_plugin.items():
markdown += f"**{metric_plugin}**\n\n"
markdown += "| | |\n|---|--|\n"
for title, value in metrics_for_plugin.items():
markdown += f"| {title} | {value} |\n"
return (markdown, True)
def handle_job_parameters(self, line, job):
markdown = """
| Input Parameter | Value |
|-----------------|-------|
"""
parameters = summarize_job_parameters(self.trans, job)["parameters"]
for parameter in parameters:
markdown += "| "
depth = parameter["depth"]
if depth > 1:
markdown += f"{'>' * (parameter['depth'] - 1)} "
markdown += parameter["text"]
markdown += " | "
value = parameter["value"]
if isinstance(value, list):
markdown += ", ".join(f"{p['hid']}: {p['name']}" for p in value)
else:
markdown += value
markdown += " |\n"
return (markdown, True)
def handle_generate_galaxy_version(self, line, generate_version):
if generate_version:
content = self.markdown_formatting_helpers.literal_via_fence(generate_version)
else:
content = "*No Galaxy Version Available*"
return (content, True)
def handle_generate_time(self, line, generate_time):
content = self.markdown_formatting_helpers.literal_via_fence(generate_time.isoformat())
return (content, True)
def handle_invocation_time(self, line, invocation):
content = self.markdown_formatting_helpers.literal_via_fence(invocation.create_time.isoformat())
return (content, True)
def handle_dataset_name(self, line, hda):
if hda.name:
content = self.markdown_formatting_helpers.literal_via_fence(hda.name)
else:
content = "*No Dataset Name Available*"
return (content, True)
def handle_dataset_type(self, line, hda):
if hda.ext:
content = self.markdown_formatting_helpers.literal_via_fence(hda.ext)
else:
content = "*No Dataset Type Available*"
return (content, True)
def handle_error(self, container, line, error):
return (line, False)
class MarkdownFormatHelpers:
"""Inject common markdown formatting helpers for per-datatype rendering."""
@staticmethod
def literal_via_fence(content):
return "\n%s\n" % "\n".join(f" {line}" for line in content.splitlines())
@staticmethod
def indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
@staticmethod
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre>"
def to_basic_markdown(trans, internal_galaxy_markdown: str) -> str:
"""Replace Galaxy Markdown extensions with plain Markdown for PDF/HTML export."""
markdown_formatting_helpers = MarkdownFormatHelpers()
directive_handler = ToBasicMarkdownDirectiveHandler(trans, markdown_formatting_helpers)
plain_markdown = directive_handler.walk(trans, internal_galaxy_markdown)
return plain_markdown
def to_html(basic_markdown: str) -> str:
# Allow data: urls so we can embed images.
html = sanitize_html(markdown.markdown(basic_markdown, extensions=["tables"]), allow_data_urls=True)
return html
def to_pdf_raw(basic_markdown: str, css_paths: Optional[List[str]] = None) -> bytes:
"""Convert RAW markdown with specified CSS paths into bytes of a PDF."""
css_paths = css_paths or []
as_html = to_html(basic_markdown)
directory = tempfile.mkdtemp("gxmarkdown")
index = os.path.join(directory, "index.html")
try:
output_file = codecs.open(index, "w", encoding="utf-8", errors="xmlcharrefreplace")
output_file.write(as_html)
output_file.close()
html = weasyprint.HTML(filename=index)
stylesheets = [weasyprint.CSS(string=resource_string(__package__, "markdown_export_base.css"))]
for css_path in css_paths:
with open(css_path) as f:
css_content = f.read()
css = weasyprint.CSS(string=css_content)
stylesheets.append(css)
return html.write_pdf(stylesheets=stylesheets)
finally:
shutil.rmtree(directory)
def weasyprint_available() -> bool:
return weasyprint is not None
def _check_can_convert_to_pdf_or_raise():
"""Checks if the HTML to PDF converter is available."""
if not weasyprint_available():
raise ServerNotConfiguredForRequest("PDF conversion service not available.")
def internal_galaxy_markdown_to_pdf(trans, internal_galaxy_markdown: str, document_type: PdfDocumentType) -> bytes:
_check_can_convert_to_pdf_or_raise()
basic_markdown = to_basic_markdown(trans, internal_galaxy_markdown)
config = trans.app.config
return to_branded_pdf(basic_markdown, document_type, config)
def generate_branded_pdf(
request: GeneratePdfDownload, config: GalaxyAppConfiguration, short_term_storage_monitor: ShortTermStorageMonitor
):
with storage_context(request.short_term_storage_request_id, short_term_storage_monitor) as target:
raw_contents = to_branded_pdf(
request.basic_markdown,
request.document_type,
config,
)
with open(target.path, "wb") as f:
f.write(raw_contents)
def to_branded_pdf(basic_markdown: str, document_type: PdfDocumentType, config: GalaxyAppConfiguration) -> bytes:
document_type_prologue = getattr(config, f"markdown_export_prologue_{document_type}s", "") or ""
document_type_epilogue = getattr(config, f"markdown_export_epilogue_{document_type}s", "") or ""
general_prologue = config.markdown_export_prologue or ""
general_epilogue = config.markdown_export_epilogue or ""
effective_prologue = document_type_prologue or general_prologue
effective_epilogue = document_type_epilogue or general_epilogue
branded_markdown = effective_prologue + basic_markdown + effective_epilogue
css_paths = []
general_css_path = config.markdown_export_css
document_type_css_path = getattr(config, f"markdown_export_css_{document_type}s", None)
if general_css_path and os.path.exists(general_css_path):
css_paths.append(general_css_path)
if document_type_css_path and os.path.exists(document_type_css_path):
css_paths.append(document_type_css_path)
return to_pdf_raw(branded_markdown, css_paths=css_paths)
def resolve_invocation_markdown(trans, invocation, workflow_markdown):
"""Resolve invocation objects to convert markdown to 'internal' representation.
Replace references to abstract workflow parts with actual galaxy object IDs corresponding
to the actual executed workflow. For instance:
convert output=name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
convert input=name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
convert step=name -to- job_id=<id>
Also expand/convert workflow invocation specific container sections into actual Galaxy
markdown - these containers include: invocation_inputs, invocation_outputs, invocation_workflow.
Hopefully this list will be expanded to include invocation_qc.
"""
# TODO: convert step outputs?
# convert step_output=index/name -to- history_dataset_id=<id> | history_dataset_collection_id=<id>
def _section_remap(container, line):
section_markdown = ""
if container == "invocation_outputs":
for output_assoc in invocation.output_associations:
if not output_assoc.workflow_output.label:
continue
if output_assoc.history_content_type == "dataset":
section_markdown += """#### Output Dataset: {}
```galaxy
history_dataset_display(output="{}")
```
""".format(
output_assoc.workflow_output.label, output_assoc.workflow_output.label
)
else:
section_markdown += """#### Output Dataset Collection: {}
```galaxy
history_dataset_collection_display(output="{}")
```
""".format(
output_assoc.workflow_output.label, output_assoc.workflow_output.label
)
elif container == "invocation_inputs":
for input_assoc in invocation.input_associations:
if not input_assoc.workflow_step.label:
continue
if input_assoc.history_content_type == "dataset":
section_markdown += """#### Input Dataset: {}
```galaxy
history_dataset_display(input="{}")
```
""".format(
input_assoc.workflow_step.label, input_assoc.workflow_step.label
)
else:
section_markdown += """#### Input Dataset Collection: {}
```galaxy
history_dataset_collection_display(input={})
```
""".format(
input_assoc.workflow_step.label, input_assoc.workflow_step.label
)
else:
return line, False
return section_markdown, True
def _remap(container, line):
if container == "workflow_display":
# TODO: this really should be workflow id not stored workflow id but the API
# it consumes wants the stored id.
return (f"workflow_display(workflow_id={invocation.workflow.stored_workflow.id})\n", False)
if container == "history_link":
return (f"history_link(history_id={invocation.history.id})\n", False)
if container == "invocation_time":
return (f"invocation_time(invocation_id={invocation.id})\n", False)
ref_object_type = None
output_match = re.search(OUTPUT_LABEL_PATTERN, line)
input_match = re.search(INPUT_LABEL_PATTERN, line)
step_match = re.search(STEP_LABEL_PATTERN, line)
def find_non_empty_group(match):
for group in match.groups():
if group:
return group
target_match: Optional[Match]
ref_object: Optional[Any]
if output_match:
target_match = output_match
name = find_non_empty_group(target_match)
ref_object = invocation.get_output_object(name)
elif input_match:
target_match = input_match
name = find_non_empty_group(target_match)
ref_object = invocation.get_input_object(name)
elif step_match:
target_match = step_match
name = find_non_empty_group(target_match)
ref_object_type = "job"
ref_object = invocation.step_invocation_for_label(name).job
else:
target_match = None
ref_object = None
if ref_object:
assert target_match # tell type system, this is set when ref_object is set
if ref_object_type is None:
if ref_object.history_content_type == "dataset":
ref_object_type = "history_dataset"
else:
ref_object_type = "history_dataset_collection"
line = line.replace(target_match.group(), f"{ref_object_type}_id={ref_object.id}")
return (line, False)
workflow_markdown = _remap_galaxy_markdown_calls(
_section_remap,
workflow_markdown,
)
galaxy_markdown = _remap_galaxy_markdown_calls(_remap, workflow_markdown)
return galaxy_markdown
def _remap_galaxy_markdown_containers(func, markdown):
new_markdown = markdown
searching_from = 0
while True:
from_markdown = new_markdown[searching_from:]
match = re.search(GALAXY_FENCED_BLOCK, from_markdown)
if match is not None:
replace = match.group(1)
(replacement, whole_block) = func(replace)
if whole_block:
start_pos = match.start()
end_pos = match.end()
else:
start_pos = match.start(1)
end_pos = match.end(1)
start_pos = start_pos + searching_from
end_pos = end_pos + searching_from
new_markdown = new_markdown[:start_pos] + replacement + new_markdown[end_pos:]
searching_from = start_pos + len(replacement)
else:
break
return new_markdown
def _remap_galaxy_markdown_calls(func, markdown):
def _remap_container(container):
matching_line = None
for line in container.splitlines():
if GALAXY_MARKDOWN_FUNCTION_CALL_LINE.match(line):
assert matching_line is None
matching_line = line
if matching_line:
match = GALAXY_MARKDOWN_FUNCTION_CALL_LINE.match(line)
assert match # already matched
return func(match.group(1), f"{matching_line}\n")
else:
return (container, True)
return _remap_galaxy_markdown_containers(_remap_container, markdown)
def _validate(*args, **kwds):
"""Light wrapper around validate_galaxy_markdown to throw galaxy exceptions instead of ValueError."""
try:
return validate_galaxy_markdown(*args, **kwds)
except ValueError as e:
raise MalformedContents(str(e))
__all__ = (
"internal_galaxy_markdown_to_pdf",
"ready_galaxy_markdown_for_export",
"ready_galaxy_markdown_for_import",
"resolve_invocation_markdown",
"to_basic_markdown",
)
|
from typing import List
from dispatch.config import INCIDENT_PLUGIN_CONTACT_SLUG
from dispatch.decorators import background_task
from dispatch.incident import flows as incident_flows
from dispatch.participant import service as participant_service
from dispatch.participant_role import service as participant_role_service
from dispatch.plugins.base import plugins
from dispatch.plugins.dispatch_slack import service as dispatch_slack_service
from dispatch.task import service as task_service
from dispatch.task.models import TaskStatus, Task
from .config import (
SLACK_COMMAND_ASSIGN_ROLE_SLUG,
SLACK_COMMAND_ENGAGE_ONCALL_SLUG,
SLACK_COMMAND_EXECUTIVE_REPORT_SLUG,
SLACK_COMMAND_LIST_MY_TASKS_SLUG,
SLACK_COMMAND_LIST_PARTICIPANTS_SLUG,
SLACK_COMMAND_LIST_RESOURCES_SLUG,
SLACK_COMMAND_LIST_TASKS_SLUG,
SLACK_COMMAND_REPORT_INCIDENT_SLUG,
SLACK_COMMAND_TACTICAL_REPORT_SLUG,
SLACK_COMMAND_UPDATE_INCIDENT_SLUG,
SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG,
SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG,
)
from .modals import (
create_update_notifications_group_modal,
create_report_incident_modal,
create_update_participant_modal,
)
from .dialogs import (
create_assign_role_dialog,
create_engage_oncall_dialog,
create_executive_report_dialog,
create_tactical_report_dialog,
create_update_incident_dialog,
)
slack_client = dispatch_slack_service.create_slack_client()
def command_functions(command: str):
"""Interprets the command and routes it the appropriate function."""
command_mappings = {
SLACK_COMMAND_ASSIGN_ROLE_SLUG: [create_assign_role_dialog],
SLACK_COMMAND_ENGAGE_ONCALL_SLUG: [create_engage_oncall_dialog],
SLACK_COMMAND_EXECUTIVE_REPORT_SLUG: [create_executive_report_dialog],
SLACK_COMMAND_LIST_MY_TASKS_SLUG: [list_my_tasks],
SLACK_COMMAND_LIST_PARTICIPANTS_SLUG: [list_participants],
SLACK_COMMAND_LIST_RESOURCES_SLUG: [incident_flows.incident_list_resources_flow],
SLACK_COMMAND_LIST_TASKS_SLUG: [list_tasks],
SLACK_COMMAND_REPORT_INCIDENT_SLUG: [create_report_incident_modal],
SLACK_COMMAND_TACTICAL_REPORT_SLUG: [create_tactical_report_dialog],
SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [create_update_incident_dialog],
SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG: [create_update_notifications_group_modal],
SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG: [create_update_participant_modal],
}
return command_mappings.get(command, [])
def filter_tasks_by_assignee_and_creator(tasks: List[Task], by_assignee: str, by_creator: str):
"""Filters a list of tasks looking for a given creator or assignee."""
filtered_tasks = []
for t in tasks:
if by_creator:
creator_email = t.creator.individual.email
if creator_email == by_creator:
filtered_tasks.append(t)
# lets avoid duplication if creator is also assignee
continue
if by_assignee:
assignee_emails = [a.individual.email for a in t.assignees]
if by_assignee in assignee_emails:
filtered_tasks.append(t)
return filtered_tasks
@background_task
def list_my_tasks(incident_id: int, command: dict = None, db_session=None):
"""Returns the list of incident tasks to the user as an ephemeral message."""
user_email = dispatch_slack_service.get_user_email(slack_client, command["user_id"])
list_tasks(
incident_id=incident_id,
command=command,
db_session=db_session,
by_creator=user_email,
by_assignee=user_email,
)
@background_task
def list_tasks(
incident_id: int,
command: dict = None,
db_session=None,
by_creator: str = None,
by_assignee: str = None,
):
"""Returns the list of incident tasks to the user as an ephemeral message."""
blocks = []
for status in TaskStatus:
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*{status.value} Incident Tasks*"},
}
)
tasks = task_service.get_all_by_incident_id_and_status(
db_session=db_session, incident_id=incident_id, status=status.value
)
if by_creator or by_assignee:
tasks = filter_tasks_by_assignee_and_creator(tasks, by_assignee, by_creator)
for task in tasks:
assignees = [a.individual.email for a in task.assignees]
blocks.append(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"*Description:* <{task.weblink}|{task.description}>\n"
f"*Assignees:* {", ".join(assignees)}"
),
},
}
)
blocks.append({"type": "divider"})
dispatch_slack_service.send_ephemeral_message(
slack_client,
command["channel_id"],
command["user_id"],
"Incident List Tasks",
blocks=blocks,
)
@background_task
def list_participants(incident_id: int, command: dict = None, db_session=None):
"""Returns the list of incident participants to the user as an ephemeral message."""
blocks = []
blocks.append(
{"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Participants*"}}
)
participants = participant_service.get_all_by_incident_id(
db_session=db_session, incident_id=incident_id
).all()
contact_plugin = plugins.get(INCIDENT_PLUGIN_CONTACT_SLUG)
for participant in participants:
if participant.is_active:
participant_email = participant.individual.email
participant_info = contact_plugin.get(participant_email)
participant_name = participant_info["fullname"]
participant_team = participant_info["team"]
participant_department = participant_info["department"]
participant_location = participant_info["location"]
participant_weblink = participant_info["weblink"]
participant_avatar_url = dispatch_slack_service.get_user_avatar_url(
slack_client, participant_email
)
participant_reason_added = participant.added_reason or "Unknown"
if participant.added_by:
participant_added_by = participant.added_by.individual.name
else:
participant_added_by = "Unknown"
participant_active_roles = participant_role_service.get_all_active_roles(
db_session=db_session, participant_id=participant.id
)
participant_roles = []
for role in participant_active_roles:
participant_roles.append(role.role)
block = {
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"*Name:* <{participant_weblink}|{participant_name}>\n"
f"*Team*: {participant_team}, {participant_department}\n"
f"*Location*: {participant_location}\n"
f"*Incident Role(s)*: {(", ").join(participant_roles)}\n"
f"*Reason Added*: {participant_reason_added}\n"
f"*Added By*: {participant_added_by}\n"
),
},
}
if len(participants) < 20:
block.update(
{
"accessory": {
"type": "image",
"alt_text": participant_name,
"image_url": participant_avatar_url,
},
}
)
blocks.append(block)
blocks.append({"type": "divider"})
dispatch_slack_service.send_ephemeral_message(
slack_client,
command["channel_id"],
command["user_id"],
"Incident List Participants",
blocks=blocks,
)
| from typing import List
from dispatch.config import INCIDENT_PLUGIN_CONTACT_SLUG
from dispatch.decorators import background_task
from dispatch.incident import flows as incident_flows
from dispatch.participant import service as participant_service
from dispatch.participant_role import service as participant_role_service
from dispatch.plugins.base import plugins
from dispatch.plugins.dispatch_slack import service as dispatch_slack_service
from dispatch.task import service as task_service
from dispatch.task.models import TaskStatus, Task
from .config import (
SLACK_COMMAND_ASSIGN_ROLE_SLUG,
SLACK_COMMAND_ENGAGE_ONCALL_SLUG,
SLACK_COMMAND_EXECUTIVE_REPORT_SLUG,
SLACK_COMMAND_LIST_MY_TASKS_SLUG,
SLACK_COMMAND_LIST_PARTICIPANTS_SLUG,
SLACK_COMMAND_LIST_RESOURCES_SLUG,
SLACK_COMMAND_LIST_TASKS_SLUG,
SLACK_COMMAND_REPORT_INCIDENT_SLUG,
SLACK_COMMAND_TACTICAL_REPORT_SLUG,
SLACK_COMMAND_UPDATE_INCIDENT_SLUG,
SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG,
SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG,
)
from .modals import (
create_update_notifications_group_modal,
create_report_incident_modal,
create_update_participant_modal,
)
from .dialogs import (
create_assign_role_dialog,
create_engage_oncall_dialog,
create_executive_report_dialog,
create_tactical_report_dialog,
create_update_incident_dialog,
)
slack_client = dispatch_slack_service.create_slack_client()
def command_functions(command: str):
"""Interprets the command and routes it the appropriate function."""
command_mappings = {
SLACK_COMMAND_ASSIGN_ROLE_SLUG: [create_assign_role_dialog],
SLACK_COMMAND_ENGAGE_ONCALL_SLUG: [create_engage_oncall_dialog],
SLACK_COMMAND_EXECUTIVE_REPORT_SLUG: [create_executive_report_dialog],
SLACK_COMMAND_LIST_MY_TASKS_SLUG: [list_my_tasks],
SLACK_COMMAND_LIST_PARTICIPANTS_SLUG: [list_participants],
SLACK_COMMAND_LIST_RESOURCES_SLUG: [incident_flows.incident_list_resources_flow],
SLACK_COMMAND_LIST_TASKS_SLUG: [list_tasks],
SLACK_COMMAND_REPORT_INCIDENT_SLUG: [create_report_incident_modal],
SLACK_COMMAND_TACTICAL_REPORT_SLUG: [create_tactical_report_dialog],
SLACK_COMMAND_UPDATE_INCIDENT_SLUG: [create_update_incident_dialog],
SLACK_COMMAND_UPDATE_NOTIFICATIONS_GROUP_SLUG: [create_update_notifications_group_modal],
SLACK_COMMAND_UPDATE_PARTICIPANT_SLUG: [create_update_participant_modal],
}
return command_mappings.get(command, [])
def filter_tasks_by_assignee_and_creator(tasks: List[Task], by_assignee: str, by_creator: str):
"""Filters a list of tasks looking for a given creator or assignee."""
filtered_tasks = []
for t in tasks:
if by_creator:
creator_email = t.creator.individual.email
if creator_email == by_creator:
filtered_tasks.append(t)
# lets avoid duplication if creator is also assignee
continue
if by_assignee:
assignee_emails = [a.individual.email for a in t.assignees]
if by_assignee in assignee_emails:
filtered_tasks.append(t)
return filtered_tasks
@background_task
def list_my_tasks(incident_id: int, command: dict = None, db_session=None):
"""Returns the list of incident tasks to the user as an ephemeral message."""
user_email = dispatch_slack_service.get_user_email(slack_client, command["user_id"])
list_tasks(
incident_id=incident_id,
command=command,
db_session=db_session,
by_creator=user_email,
by_assignee=user_email,
)
@background_task
def list_tasks(
incident_id: int,
command: dict = None,
db_session=None,
by_creator: str = None,
by_assignee: str = None,
):
"""Returns the list of incident tasks to the user as an ephemeral message."""
blocks = []
for status in TaskStatus:
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*{status.value} Incident Tasks*"},
}
)
tasks = task_service.get_all_by_incident_id_and_status(
db_session=db_session, incident_id=incident_id, status=status.value
)
if by_creator or by_assignee:
tasks = filter_tasks_by_assignee_and_creator(tasks, by_assignee, by_creator)
for task in tasks:
assignees = [a.individual.email for a in task.assignees]
blocks.append(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"*Description:* <{task.weblink}|{task.description}>\n"
f"*Assignees:* {', '.join(assignees)}"
),
},
}
)
blocks.append({"type": "divider"})
dispatch_slack_service.send_ephemeral_message(
slack_client,
command["channel_id"],
command["user_id"],
"Incident List Tasks",
blocks=blocks,
)
@background_task
def list_participants(incident_id: int, command: dict = None, db_session=None):
"""Returns the list of incident participants to the user as an ephemeral message."""
blocks = []
blocks.append(
{"type": "section", "text": {"type": "mrkdwn", "text": "*Incident Participants*"}}
)
participants = participant_service.get_all_by_incident_id(
db_session=db_session, incident_id=incident_id
).all()
contact_plugin = plugins.get(INCIDENT_PLUGIN_CONTACT_SLUG)
for participant in participants:
if participant.is_active:
participant_email = participant.individual.email
participant_info = contact_plugin.get(participant_email)
participant_name = participant_info["fullname"]
participant_team = participant_info["team"]
participant_department = participant_info["department"]
participant_location = participant_info["location"]
participant_weblink = participant_info["weblink"]
participant_avatar_url = dispatch_slack_service.get_user_avatar_url(
slack_client, participant_email
)
participant_reason_added = participant.added_reason or "Unknown"
if participant.added_by:
participant_added_by = participant.added_by.individual.name
else:
participant_added_by = "Unknown"
participant_active_roles = participant_role_service.get_all_active_roles(
db_session=db_session, participant_id=participant.id
)
participant_roles = []
for role in participant_active_roles:
participant_roles.append(role.role)
block = {
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"*Name:* <{participant_weblink}|{participant_name}>\n"
f"*Team*: {participant_team}, {participant_department}\n"
f"*Location*: {participant_location}\n"
f"*Incident Role(s)*: {(', ').join(participant_roles)}\n"
f"*Reason Added*: {participant_reason_added}\n"
f"*Added By*: {participant_added_by}\n"
),
},
}
if len(participants) < 20:
block.update(
{
"accessory": {
"type": "image",
"alt_text": participant_name,
"image_url": participant_avatar_url,
},
}
)
blocks.append(block)
blocks.append({"type": "divider"})
dispatch_slack_service.send_ephemeral_message(
slack_client,
command["channel_id"],
command["user_id"],
"Incident List Participants",
blocks=blocks,
)
|
from math import dist
import requests, json, time
import tkinter as tk
root=tk.Tk()
root.geometry("425x300")
root.title('Tamil Nadu COVID-19 Tracker App')
root['bg']='yellow'
day = str(time.localtime().tm_mday) + '.' + str(time.localtime().tm_mon) + '.' + str(time.localtime().tm_year)
district = tk.StringVar()
display_result = tk.Label(root,text='Enter TN District', font=('calibre',20, 'bold'), bg='yellow')
display_result.pack()
district_entry = tk.Entry(root,textvariable = district, font=('calibre',10,'normal'), width=50,borderwidth=5)
district_entry.pack()
time_label = tk.Label(root, text = f"Date:{day}", font=('calibre',20, 'bold'), bg='yellow')
time_label.pack()
api_source = tk.Label(root,text = 'https://api.covid19india.org/state_district_wise.json', font=('calibre',10, 'bold'), bg='yellow')
api_source.pack()
def submit():
try:
#display_result.grid(row = 2,column =0)
api = 'https://api.covid19india.org/state_district_wise.json'
data = requests.get(api).json()
district1=district.get().strip().capitalize()
x=data.get('Tamil Nadu').get('districtData').get(district1)
print(district1, x)
display_result.config(text=f"Entered Place: {district1}"+"\n"+f"Confirmed Cases: {x.get("confirmed")}"+'\n'+f"Active Cases: {x.get("active")}"+'\n'+f"Deaths: {x.get("deceased")}"+'\n'+f"Recovered: {x.get("recovered")}")
display_result.pack()
except:
display_result.config(text="Try Again, Enter TN district")
display_result.pack()
def key_handler(event):
if event.keysym in ("Return", "equal"):
global x
x = submit()
root.bind("<Key>", key_handler)
root.mainloop()
| from math import dist
import requests, json, time
import tkinter as tk
root=tk.Tk()
root.geometry("425x300")
root.title('Tamil Nadu COVID-19 Tracker App')
root['bg']='yellow'
day = str(time.localtime().tm_mday) + '.' + str(time.localtime().tm_mon) + '.' + str(time.localtime().tm_year)
district = tk.StringVar()
display_result = tk.Label(root,text='Enter TN District', font=('calibre',20, 'bold'), bg='yellow')
display_result.pack()
district_entry = tk.Entry(root,textvariable = district, font=('calibre',10,'normal'), width=50,borderwidth=5)
district_entry.pack()
time_label = tk.Label(root, text = f"Date:{day}", font=('calibre',20, 'bold'), bg='yellow')
time_label.pack()
api_source = tk.Label(root,text = 'https://api.covid19india.org/state_district_wise.json', font=('calibre',10, 'bold'), bg='yellow')
api_source.pack()
def submit():
try:
#display_result.grid(row = 2,column =0)
api = 'https://api.covid19india.org/state_district_wise.json'
data = requests.get(api).json()
district1=district.get().strip().capitalize()
x=data.get('Tamil Nadu').get('districtData').get(district1)
print(district1, x)
display_result.config(text=f"Entered Place: {district1}"+'\n'+f"Confirmed Cases: {x.get('confirmed')}"+'\n'+f"Active Cases: {x.get('active')}"+'\n'+f"Deaths: {x.get('deceased')}"+'\n'+f"Recovered: {x.get('recovered')}")
display_result.pack()
except:
display_result.config(text="Try Again, Enter TN district")
display_result.pack()
def key_handler(event):
if event.keysym in ("Return", "equal"):
global x
x = submit()
root.bind("<Key>", key_handler)
root.mainloop()
|
"""'Callbacks' are what enable the "reactive" functionality
of a Python Dash web application (literally, the react.js).
Every time a user interacts with a UI component on the web
app page in their browser, a callback with matching Input
(via the component's 'id' attribute) from this module is
activated, thus allowing customized programmed reactions
to any individual and/or series of any [possible combi-
nation of] user actions.
> dash-webapp-template
> C a l l b a c k s
> 𝕄𝕠𝕕𝕦𝕝𝕖
> ண⎤꜒𓇃𓇃𓇃ཥ⅌ཤ𓇃𓇃𓇃𓋏ཀཫ𓋏𓇃𓇃𓇃╗╔𓇃𓇃𓆽⦄༽⸶⸷༼⦃𓆽𓇃𓇃𓇃𓇊𓊢ༀ࿐࿓𓇊࿑
## John Collins GitHub Public Repos — dash-webapp-template
To learn more about callbacks, see:
https://dash.plot.ly/getting-started-part-2
> ୡ ୡୡ ୡ
> ◖𓇃ⴶ〰⸅‖⸄〰ж𓇃𓇃𓇃𓇃⸠⎫𓏉⎧⸡𓇃𓇃𓇃𓏟𓏞𓇃𓇃╗╔𓇃𓇃𓇃𓐩𓋥⸶⸷𓋥𓐩◗
> ୡ ୡ ୡୡ
> ◖𓇃𓇃𓇃𓏣🜾𓏣𓇃𓇃𓉽𓇃𓎸𓈌𓎹𓇃⎨⎬𓇃˥⎡𓇃𓇃࿅𓇃𓊢ꃊ𓊢𓇃𓇃𓇃◗
Attributes:
----------
logger (logging.Logger):
Current session log file
version (str):
Current git-committed source codebase version
____________________________
ୡ
𓇃𓏣🜾𓏣𓇃࿑
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from flask import Flask
from werkzeug.routing import Rule
from .config import *
from .utils import *
from seqapp import app
import config
from config import *
import bioinfo as bioinformatics
from bioinfo import pipeline, visualization
from bioinfo.pipeline import (
parse_contents,
)
version = VERSION
logger = logging.getLogger(__name__)
########################################
# S T A N D A R D F U N C T I O N S #
########################################
""" See the app.utils module & also the /app/config init file
for some of the more general, non-reactive functions which may
nonetheless be imported and used in the callbacks below.
"""
########################################
# F L A S K F U N C T I O N S #
########################################
""" The dash.Dash() app object is itself at its core a flask app
object, too; thus, all of the [vast] Flask source code
functionalities are compatible as-is with Dash apps.
"""
app.server.url_map.add(Rule('/', endpoint='downloadZAll'))
app.server.url_map.add(Rule('/', endpoint='urlToDownload'))
@app.server.endpoint("/downloadZAll")
def download_all_selected():
"""Send path from directory to allow user to
download zipped files as an attachment.
Returns:
File download directly to user's PC.
"""
value = flask.request.args.get("value")
fbn = f"{os.path.basename(value)}"
app.logger.info(f"🗽| REQUEST TO DOWNLOAD: for [zipped] server file @ {value}")
return flask.send_from_directory(
directory=f"{os.path.dirname(value)}",
filename=fbn,
attachment_filename=fbn,
as_attachment=True,
mimetype="zip",
)
@app.server.endpoint("/urlToDownload")
def download_file():
"""Send path from directory to allow user
to download file as an attachment.
Returns:
"""
value = flask.request.args.get("value")
fbn = f"{os.path.basename(value)}"
app.logger.info(f"🗽| REQUEST TO DOWNLOAD: for server file @ {value}")
mime = "text/plain" if "png" not in value else "image/png"
return flask.send_from_directory(
directory=f"{os.path.dirname(value)}",
filename=fbn,
attachment_filename=fbn,
as_attachment=True,
mimetype=mime,
)
########################################
# C A L L B A C K F U N C T I O N S #
########################################
""" Every callback function is preceded by a special `@app.callback`
Python decorator function, which necessarily has an Output() and
at least one Input() parameter (both objects from dash.dependencies).
Optionally, a callback function decorator can also contain a
State() parameter (also imported from dash.dependencies).
Typically, the return of a callback function is an html.Div()
object containing a list of updated components to be returned to
the UI via the 'id' attribute indicated on the Output() object
of callback decorator.
For a helpful overview on Python decorators, see:
https://realpython.com/primer-on-python-decorators/
"""
@app.callback(
Output(f"user-login-confirmation", "children"),
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"input-user-name", "value"),
Input(f"clear-pipeline", "n_clicks"),
Input(f"session", "data"),
Input(f"log-out-submit", "n_clicks")
],
[State(f"sign-on-submit", "n_clicks_timestamp")],
)
def confirm_new_session(
n_clicks,
user_sign_on,
clear_n_clicks,
session_data,
logout,
login_timestamp,
):
"""Responsive components generation for user sign-on at top of app UI page.
Parameters
----------
n_clicks : int
Total cumulative count of clicks 'submit' (sign-in) button
user_sign_on : str
Selected user name from sign on dropdown
clear_n_clicks : int
Total cumulative count of clicks clear pipeline button
session_data : Dash.dcc.Store(type='session')
Dash HTTP client-side memory caching, "Session" type (auto-cleared when
browser tab closes [but *not* on Refresh's]).
logout : int
Total cumulative count of clicks logout button
login_timestamp : int
Timestamp at most recent sign on button click as integer
(e.g., 1572843293129)
"""
if user_sign_on == "None" and logout < 1:
raise PreventUpdate
if not user_sign_on:
return [
html.H6(
"Please sign in to create a new session.",
style={"fontSize": "1.2rem", "fontWeight": "300"},
)
]
try:
enter_user = session_data["current_user"]
user_proper = session_data["user_proper"]
putat_user = user_sign_on[0] + user_sign_on.split("_")[0].lower()[1:]
try:
prev_user = session_data[f"SIGN_ON-№{n_clicks-1}"]
except KeyError as e:
prev_user = "NONE"
app.logger.debug(f"Recorded user name: {enter_user} (Prev. user={prev_user})")
if login_timestamp:
submit_t_elapsed = tns() / 1e9 - login_timestamp / 1e3
app.logger.debug(f"USER LOGIN : `submit_t_elapsed` = {submit_t_elapsed}")
else:
submit_t_elapsed = 0 # <1 ≡ No recent sign in!
if (
user_sign_on == enter_user
or session_data["user_logged_in"] == "True"
) and submit_t_elapsed < 1:
log_t_init = session_data["login_t_init"]
session_log_file = session_data["session_log_file"]
RUN_ID = session_data["RUN_ID"]
app.logger.info(
f"* C R E A T E D N E W 'Current SESSION OUTPUT DIR' *\n{session_data["PATH_TO_SESSION_OUTPUT"]}"
)
return html.Details(
[
html.Div(
[
html.Span(
f"Active User Account — {enter_user.replace("_", " ").title()}",
style={
"fontSize": "1.2rem",
"fontFamily": "'Open Sans', sans-serif",
"fontWeight": "300",
"color": "#304479",
},
),
html.Span(
className="fader-line-short", style={"marginBottom": "20px"}
),
html.P("You're all set!"),
html.H6(f"Sign-on Timestamp: {log_t_init.split("=")[1]}", style={"fontSize": "0.65rem"}),
html.P(
f"Session ID:\t{RUN_ID}",
style={
"animation": "anim-text-flow-keys 60s infinite linear",
"mixBlendMode": "difference",
"fontSize": "0.7rem",
},
),
],
className="updates-list",
),
html.Summary(
html.Code(
f"✔ LOGGED IN",
style={"color": "rgb(24, 230, 112)"},
className="updates-header",
)
),
],
id="logged-in-status",
)
elif n_clicks > 1 and prev_user != "None yet.." and enter_user != prev_user:
return [
html.Br(),
html.H4(
f"{putat_user}, would you like to sign on [& log out {prev_user}]?",
style={"display": "block"},
),
html.P(f"🧙🧠🗲⚛ 👌📓⬸📖🖊", style={"fontSize": "3rem"}),
]
except Exception as e:
user_proper = "⚠:[USER_UNKNOWN!]"
app.logger.warning(f"Note: Exception raised during user sign on: {e}")
return [
html.Br(),
html.H6("Sign In ( ⮩️🚪✨ ) to create a new, blank output directory for your analysis."),
]
@app.callback(
Output(f"input-user-name", "value"),
[
Input(f"log-out-submit", "n_clicks"),
Input(f"log-back-in-submit", "n_clicks"),
],
[
State(f"log-out-submit", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks_timestamp"),
State(f"log-back-in-submit", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks"),
State(f"local", "data"),
],
)
def log_out_or_comeback(
logout,
quick_logback,
log_out_timestamp,
sign_on_timestamp,
logback_on_timestamp,
signon,
user_profile,
):
"""Enable USER "Log Out" functionality.
Parameters
----------
logout : int
Total cumulative count of clicks log out button
quick_logback : int
Total cumulative count of clicks "Return" button
log_out_timestamp : int
Timestamp of last user click log out button
sign_on_timestamp : int
Timestamp of last user click sign-in button
logback_on_timestamp : int
Timestamp of last user click "Return" button
signon : int
Total cumulative count of clicks user sign-in button
user_profile : Dash.dcc.Store(type='local')
Browser-cached local app memory, containing stored saved
user "profile" info / stats.
"""
if not user_profile:
raise PreventUpdate
if logout < 1 and quick_logback < 1:
raise PreventUpdate
if quick_logback > 0:
if signon > 0 and logout > 0:
if logback_on_timestamp > max(log_out_timestamp, sign_on_timestamp):
return user_profile["userAccount"]
elif signon < 1:
return user_profile["userAccount"]
elif logout > 0 and signon > 0:
if log_out_timestamp > sign_on_timestamp:
return "None"
@app.callback(
[
Output(f"session", "data"),
Output(f"local", "data"),
],
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"log-out-submit", "n_clicks"),
Input(f"clear-pipeline", "n_clicks"),
],
[
State(f"input-user-name", "value"),
State(f"session", "data"),
State(f"local", "data"),
State(f"initiate-pipeline", "n_clicks"),
State(f"initiate-pipeline", "n_clicks_timestamp"),
State(f"clear-pipeline", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks_timestamp"),
State(f"refresh-uploads", "n_clicks_timestamp"),
State(f"log-out-submit", "n_clicks_timestamp"),
],
)
def record_user_name(
login_n_clicks,
logout_n_clicks,
clear_pl_n_clicks,
user_selection,
data,
local_cache,
init_pl_n_clicks,
initiate_pipeline_timestamp,
clear_pipeline_timestamp,
user_login_timestamp,
refresh_uploads_timestamp,
log_out_timestamp,
):
"""Upon user sign on (or sign off), correspondingly update the cached
information describing the current user (e.g., name, proper name, sign
in history, etc.) and create and store a new RUN ID for the current
session, as applicable.
Args:
login_n_clicks (int):
Total cumulative count of clicks user sign-in button
logout_n_clicks (int):
Total cumulative count of clicks log out button
clear_pl_n_clicks (int):
Total cumulative count of clicks clear results button
user_selection (str):
Selected value from user names dropdown in app log-in section
data (Dash.dcc.Store):
[Session] HTTP client-side memory cache
local_cache (Dash.dcc.Store):
[Local] HTTP client-side memory cache
init_pl_n_clicks (int):
Total cumulative count of clicks initiate step 2 pipeline button
initiate_pipeline_timestamp (int):
Timestamp of last user click initiate step 2 pipeline button
clear_pipeline_timestamp (int):
Timestamp of last user click clear results button
user_login_timestamp (int):
Timestamp of last user click sign-in button
refresh_uploads_timestamp (int):
Timestamp of last user click refresh uploads button
log_out_timestamp (int):
Timestamp of last user click log out button
"""
app.logger.debug(f"sign on timestamp: {user_login_timestamp}")
reset_session_data = {
"SIGN_ON-№0": "None yet..",
"RUN_ID": "NA",
"current_user": "None",
"user_logged_in": "False",
"user_proper": "NA",
}
if login_n_clicks < 1 or user_selection == "None" or not user_selection:
if not user_selection:
return (
reset_session_data,
local_cache,
)
else:
data = {"SIGN_ON-№0": "None yet.."}
data["RUN_ID"] = "NA"
data["current_user"] = user_selection
data["login n_clicks"] = login_n_clicks
data["user_logged_in"] = "False"
data["user_proper"] = user_selection.replace("_", " ").title().split()[0]
return data, local_cache
login_t_elapse = tns() / 1e9 - user_login_timestamp / 1e3
UUID = f"{"".join([*map(lambda x: x[:2], user_selection.split("_"))])}"
logins = f"SIGN_ON-№{login_n_clicks}"
data = data or {"SIGN_ON-№0": "None yet.."}
data["UUID"] = UUID
user_proper = user_selection[0] + user_selection.split("_")[0].lower()[1:]
data["user_proper"] = user_proper
data["current_user"] = user_selection
data["login n_clicks"] = login_n_clicks
if (login_n_clicks > logout_n_clicks and user_selection != "None") and login_t_elapse < 2:
data["user_logged_in"] = "True"
if logout_n_clicks > 0:
if (tns() / 1e9 - log_out_timestamp / 1e3) < 2:
return reset_session_data, local_cache
if not user_selection:
data["user_logged_in"] = "None"
return data, local_cache
# Proceed with apparent sign-in submission if this point reached:
login_t_init = f"{tns()} = {now()}"
data["login_t_init"] = login_t_init
data[logins] = user_selection
if "SIGN_ON-№1" in data.keys():
data["prev_user"] = data[f"SIGN_ON-№{max(login_n_clicks-1,1)}"]
RUN_ID = f"APP_RUNID_{now()}"
SESSION_OUTPUT_DIR = f"{RUN_OUTPUT_DIR}/{today()}/{RUN_ID}/"
data["RUN_ID"] = RUN_ID
data["PATH_TO_SESSION_OUTPUT"] = SESSION_OUTPUT_DIR
session_log_file = f"{SESSION_OUTPUT_DIR}{RUN_ID}_CurrentSession.log"
os.makedirs(SESSION_OUTPUT_DIR, exist_ok=True)
app.logger.debug(f"Number of logger handlers: {logger.handlers}")
fh = add_logfile(logfile=session_log_file, logger=logger)
app.logger.addHandler(fh)
app.logger.debug(f"Number of logger handlers: {logger.handlers}")
app.logger.info(f"USER SIGN ON @ {login_t_init}")
app.logger.info(f"*** CURRENT APP APP SOFTWARE VERSION = {VERSION} ***")
data["session_log_file"] = session_log_file
data["SESSION_DATA"] = pd.DataFrame(
[[RUN_ID, SESSION_OUTPUT_DIR, user_selection, session_log_file]],
columns=["RUN_ID", "PATH_TO_SESSION_OUTPUT", "USER_ID", "LOG_FILE"],
).to_json(date_format="iso", orient="split")
app.logger.info(f"USER: '{user_selection}' | RUN ID: {RUN_ID}")
# Store basic user profile in browser local cache for app:
reset_local_cache = {
"userName": user_proper,
"userAccount": user_selection,
"userProfileCreated": now(),
"countUserLogIns": 0,
"userRuns": {RUN_ID: data},
}
try:
if local_cache["userAccount"] != user_selection:
local_cache = reset_local_cache
local_cache["countUserLogIns"] += 1
local_cache["userRuns"][RUN_ID] = data
except Exception as e:
app.logger.info(
f"Creating {user_proper}'s first local memory cache! (I.e., by which to remember them by! 😉)"
)
local_cache = reset_local_cache
local_cache["countUserLogIns"] += 1
return data, local_cache
@app.callback(
Output(f"user-status", "children"),
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"refresh-user-history", "n_clicks"),
Input(f"session", "data"),
],
[State(f"input-user-name", "value"), State(f"local", "data")],
)
def show_user_in_menubar(
sign_on_n_clicks, save_results_n_clicks, session_data, selected_username, local_data_cache
):
"""
Parameters
----------
sign_on_n_clicks
int
save_results_n_clicks
int
session_data
Dash.dcc.Store(type='session')
selected_username
str
local_data_cache
Dash.dcc.Store(type='local')
"""
log_in = [
html.Span(
html.A(["⁂ Sign In"], href=f"#log-in-below"),
style={"fontSize": "80%", "color": "goldenrod"},
id=f"log-in",
)
]
if session_data and sign_on_n_clicks > 0:
if "session_log_file" in session_data:
if session_data["current_user"] != "None":
user = session_data["user_proper"]
USER = session_data["current_user"]
default = []
history = {}
try:
history = local_data_cache[f"{USER}_APP_Saved_History"]
app.logger.debug(str(local_data_cache), str(history))
except Exception as e:
history = {}
default = [html.Li(f"You have no saved APP Results History, yet!\n")]
return [
html.Details(
[
html.Summary(
[
html.Span(
f"👤Signed in as: {user}",
style={
"fontFamily": "Muli",
"fontSize": "85%",
"cursor": "pointer",
},
className="user-menu-summary",
)
]
),
html.Div(
[
html.Ul(
[
html.Li(f"Current RUN_ID: {session_data["RUN_ID"]}"),
html.Li(
f"User Is Logged In: {session_data["user_logged_in"]}",
className="user-menu-action-items",
style={"color": "rgb(37, 109, 210)"},
),
html.Li(
f"Signed On @ {session_data["login_t_init"]}",
className="user-menu-action-items",
style={"color": "rgb(17, 199, 210)"},
),
html.Li(
[
html.A(
"Your Saved Analysis History",
href="#save-user-results",
),
html.Ul(
[
html.Li(dcc.Link(f"{k}", href=f"/{k}"))
for k in history.keys()
]
+ default,
style={
"listStyle": "decimal-leading-zero",
"margin": "0!important",
"padding": "0!important",
},
),
],
className="user-menu-action-items",
style={"color": "rgb(37, 149, 180)"},
),
html.Li(
[
html.A(
"Report an Issue/Bug",
href="mailto:jcollins.bioinformatics@gmail.com",
)
],
className="user-menu-action-items",
style={"color": "rgb(7, 69, 180)"},
),
]
)
],
className="user-menu",
style={"color": "rgb(199, 199, 199)"},
),
]
)
]
return log_in
@app.callback(Output(f"workflow-selection", "children"), [Input(f"workflow-id", "value")])
def update_workflow_choice(workflow):
"""Update display at top of app based on USER's Worlflow selection
(e.g., "Gene Editing: [...]", etc.)
Args:
workflow: str
Returns:
Array of H2 HTML Header element containing workflow text.
"""
app.logger.debug(f"CALLBACK:::`update_workflow_choice` triggered with value: {workflow}")
return [html.H2(f"{workflow}", style={"textAlign": "center"})]
@app.callback(Output("dd2-dropdown", "options"), [Input("dd1-dropdown", "value")])
def update_dropdown(dd1):
"""Update Dropdown for sample corresponding to USER-selected ID.
Args:
dd1 (Array of "label":"value" pairs dictionary containing the): Dropdown's options.
Returns:
Updated array matching form of input.
"""
app.logger.debug(f"CALLBACK:::`update_dropdown` triggered with value: {dd1}")
if dd1 and dd1 != "None":
ent_id, ent_name, = dd1.split("-")
try:
wells = entity_schemas.loc[ent_name].columns #.unique()
except KeyError as e:
app.logger.info(f"WellID dropdown error in Plasmid Tool:\n{e}")
return [{"label": "——N/A——", "value": "Error"}]
# ⤑⟗αβ⟗⇒ *Trigger Ligation*
return [{"label": " ✔ Confirm Well & EXP ID", "value": "None"}] + [
{"label": w, "value": w}
for w in wells
]
else:
return [{"label": "——N/A——", "value": "None"}]
@app.callback(
Output("submission-status", "children"),
[Input("submit-selected-dds", "n_clicks"), Input("clear-dd-selections", "n_clicks")],
[State("dd1-dropdown", "value"), State("dd2-dropdown", "value")],
)
def trigger_dropdowns(submit_n_clicks, clear_n_clicks, dd1, dd2):
"""Initiate first analysis
Args:
submit_n_clicks: int
clear_n_clicks: int
dd1: str
dd2: str
Returns:
Dash html component(s)
"""
if clear_n_clicks == submit_n_clicks + 1:
return html.Code(
"⚠ | ℹ Overclicking clear *may* require compensatory submits! (I.e., Try clicking submit button >1 times, if submissions are not going through.)",
style={
"color": "red",
"display": "flex",
"flexFlow": "column wrap",
"fontSize": "1.0rem",
"margin": "0px 30% 20px 30%",
},
)
if all(ui not in ("None", None) for ui in [dd1, dd2]):
app.logger.info(
f"-:!:- FUNCTION('trigger_dropdowns') has been activated, and now has value 'submit_n_clicks' = {submit_n_clicks}"
)
return [html.Code(f"SUBMISSION for: {dd1}, @Well{dd2}")]
elif clear_n_clicks > submit_n_clicks + 1:
app.logger.info(
f"-:!:- FUNCTION('trigger_dropdowns') has been cleared, and now has value 'clear_n_clicks' = {clear_n_clicks}"
)
return html.Code(
f"Submissions cleared: {clear_n_clicks}, [submissions_count={submit_n_clicks}].",
style={"fontStyle": "normal", "color": "gray", "margin": "0px 30% 20px 30%"},
)
else:
return html.Code("No submissions received, it seems...")
@app.callback(
Output("dd-selections", "children"),
[
Input("dd1-dropdown", "value"),
Input("dd2-dropdown", "value"),
Input("submit-dds", "n_clicks"),
Input("clear-dd-selections", "n_clicks"),
Input("workflow-id", "value"),
],
[State("session", "data"), State("submit-selected-dds", "n_clicks_timestamp")],
)
def display_generated_dd_output(
dd1,
dd2,
submission,
clear_submission,
workflow,
session_data,
submission_timestamp,
):
"""Generic template for a paired dynamics set of dropdowns;
such that the user selection in the first dropdown dynamically
modifies live the possible options in the second dropdown.
Args:
dd1: str
dd2: str
submission: int
clear_submission: int
workflow: str
session_data: Dash.dcc.Store(type='session')
submission_timestamp: int
"""
if (dd1 == "None" and dd2 == "None") or dd1 is None:
return [
html.Div(
[
html.Span(
f"Make a new selection.",
style={"textAlign": "center", "fontFamily": "Muli", "fontSize": "1.5rem"},
),
html.Span(
html.Img(
src="../assets/animations/dna-minimal-green.gif",
height="150",
style={
"transform": "translateY(-55px) translateX(5px)",
"filter": "hue-rotate(100deg) contrast(1.1) saturate(5)",
"position": "absolute",
"opacity": "0.5",
"borderRadius": "250px",
},
)
),
],
style={
"marginLeft": "25%",
"position": "relative",
"textAlign": "center",
"width": "50%",
"zIndex": "-1",
},
),
html.Div(
[
html.Span("↪⦿"),
html.Img(
src="../assets/images/scope-unic.png",
width="80",
style={"marginTop": "15px", "marginBottom": "-25px", "cursor": "pointer"},
),
html.Span("⥅♅"),
],
style={
"textAlign": "center",
"fontSize": "1.75rem",
"animation": "animateGlow 45s infinite linear!important",
"cursor": "pointer",
},
),
]
elif any(ui == "Error" for ui in [dd1, dd2]):
return
elif dd1 != "None" and dd2 is None:
return [
html.H5(
f"ℹ | Informational message to display.",
style={"textAlign": "center", "marginLeft": "25%", "width": "50%"},
)
]
elif all(ui != "None" for ui in [dd1, dd2]):
return html.Div(
[
html.Code(
f"♻ Cleared submission state: [total_clears={clear_submission}]",
style={"fontStyle": "italic", "fontSize": "0.9rem", "marginBottom": "5px"},
),
html.Br(),
html.Div(
[
html.H6(
[
html.P(f"⮊ Click ⬫Submit⬫ 𝑓𝗈𝓇⤑{dd2} ~ {dd1}"),
html.Span("to initiate "),
html.Span(
f"in silico ",
style={"fontStyle": "italic", "fontFamily": "'Times', serif"},
),
html.Span("analysis of selections."),
],
style={
"textAlign": "center",
"cursor": "pointer",
"color": "#ffffff6e",
"backgroundImage": "url(https://media.giphy.com/media/4HIOPSXOitJ2o/giphy.gif)",
"mozBackgroundClip": "text",
"webkitBackgroundClip": "text",
"fontWeight": "700",
"backgroundSize": "60%",
},
)
],
style={
"position": "absolute",
"margin": """0.5% -5% -5% -5%""",
"textAlign": "center",
"display": "inline-block",
"mixBlendMode": "lighten",
"width": "200px",
},
),
html.Br(),
html.Br(),
html.Div(
[
html.Span("✂"),
html.Span(""),
html.Span("⭾"),
html.Span("α/β"),
html.Div(
[
html.Video(
src=f"data:video/mp4;base64,{base64.b64encode(open(f"../assets/animations/T-Cell_TEM_4-3.mp4", "rb").read()).decode()}",
id="t-cell",
autoPlay=True,
loop=True,
controls=False,
preload="true",
muted=True,
)
],
style={"filter": "opacity(0.25)"},
),
],
style={
"textAlign": "center",
"fontSize": "2rem",
"width": "20%",
"marginLeft": "40.5%",
"mixBlendMode": "exclusion",
},
className="animate twirl",
),
],
style={"textAlign": "center"},
)
@app.callback(Output("dd1-dropdown", "value"), [Input("clear-dd-selections", "n_clicks")])
def clear_dd1_selection(n_clicks):
"""Clear Dropdown selections for Dropdown #1 (dd1)
( Dropdown to clear #1 of 2 )
Args:
n_clicks: int
Returns:
str: Resets selections to default, blank states.
"""
if n_clicks > 0:
app.logger.info(
f"-:!:- FUNCTION('clear_dd1_selection') has been activated, and now has value 'n_clicks' = {n_clicks}"
)
return "None"
@app.callback(
Output("dd2-dropdown", "value"),
[Input("dd1-dropdown", "value"), Input("clear-dd-selections", "n_clicks")],
)
def clear_dd2_selection(val, n_clicks):
"""Clear Dropdown selections for Dropdown #2 (dd2)
( Dropdown to clear #2 of 2 )
Args:
val (str): cascading response via `clear_dd2_selection()` callback
n_clicks: int
Returns:
str: Resets selections to default, blank states.
"""
if n_clicks > 0:
app.logger.info(
f"-:!:- FUNCTION('clear_dd2_selection') has been activated, and now has value 'n_clicks' = {n_clicks} & 'val' = {val}"
)
if val == "None":
return "None"
else:
return None
@app.callback(
Output("memory", "data"),
[
Input("append-uploads", "n_clicks"),
Input("clear-uploads", "n_clicks"),
Input("refresh-uploads", "n_clicks"),
Input("upload-data", "contents"),
],
[
State("session", "data"),
State("memory", "data"),
State("append-uploads", "n_clicks_timestamp"),
State("refresh-uploads", "n_clicks_timestamp"),
State("clear-uploads", "n_clicks_timestamp"),
State("upload-data", "filename"),
State("upload-data", "last_modified"),
],
)
def enable_combined_file_uploads(
append_nclicks,
clear_nclicks,
refresh_nclicks,
list_of_contents,
session_data,
clientside_memory_cache,
append_nclicks_timestamp,
refresh_nclicks_timestamp,
clear_nclicks_timestamp,
list_of_names,
list_of_dates,
):
"""Management of app components and file upload States allowing for USER-
toggled continuation of upload (i.e., as opposed to overwriting any previously
received ABI files uploaded).
Args:
append_nclicks: int
clear_nclicks: int
refresh_nclicks: int
list_of_contents: list of bytes
session_data: Dash.dcc.Store(type='memory')
clientside_memory_cache: Dash.dcc.Store(type='memory')
append_nclicks_timestamp: int
refresh_nclicks_timestamp: int
clear_nclicks_timestamp: int
list_of_names: list of str
list_of_dates: list of int
"""
memory_reset = {}
if not session_data:
raise PreventUpdate
if clear_nclicks > 0:
t_elapse = tns() / 1e9 - clear_nclicks_timestamp / 1e3
app.logger.info(f"CLEAR UPLOAD UI ACTION DETECTED, W/ `t_elapse` = {t_elapse}")
if t_elapse < 2:
return memory_reset
if append_nclicks > 0:
LOG_FILE = session_data["session_log_file"]
RUN_ID = session_data["RUN_ID"]
SESSION_OUTPUT_DIR = session_data["PATH_TO_SESSION_OUTPUT"]
app.logger.info(f"Append to Uploads in progress...")
app.logger.info(f" ...Adding the following files: \n{list_of_names}")
memory_reset = {f"{RUN_ID}-list_of_names": []}
uploads_cache = clientside_memory_cache or memory_reset
parsed_upload_children = [
html.Details(
[
parse_contents(c, n, d, SESSION_OUTPUT_DIR, session_log_file=LOG_FILE)
for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)
]
)
]
uploads_cache[f"{RUN_ID}-len_most_recent"] = len(parsed_upload_children)
uploads_cache[f"{RUN_ID}-list_of_names"].extend(list_of_names)
uploads_cache[f"{RUN_ID}-list_of_names"] = list(
set(uploads_cache[f"{RUN_ID}-list_of_names"])
)
uploads_cache[f"{RUN_ID}-len_of_contents"] = len(uploads_cache[f"{RUN_ID}-list_of_names"])
return uploads_cache
else:
return memory_reset
for n in range(1000):
@app.callback(
Output(f"cmds-dt-{n}", "style"),
[Input(f"show-cmds-{n}", "n_clicks")],
[State(f"cmds-dt-{n}", "style")],
)
def show_pipeline_commands(show_pl_cmds_n_clicks, style):
"""Enable dynamic reveal/hide functionality for showing
the technical-heavy exact command line commands called
during the pipeline execution of processes.
Args:
show_pl_cmds_n_clicks: int
style: <type>
Returns:
<type>
Raises:
PreventUpdate: Description
PreventUpdate
"""
if show_pl_cmds_n_clicks > 0:
if (show_pl_cmds_n_clicks % 2) == 1:
app.logger.info(f"show_pl_cmds clicked: {show_pl_cmds_n_clicks % 2}")
return {"display": "block"}
else:
return {"display": "none"}
else:
raise PreventUpdate
@app.callback(
Output("output-data-upload", "children"),
[
Input("upload-data", "contents"),
Input("upload-data", "filename"),
Input("upload-data", "last_modified"),
Input("initiate-pipeline", "n_clicks"),
Input("clear-pipeline", "n_clicks"),
Input("append-uploads", "n_clicks"),
Input("refresh-uploads", "n_clicks"),
Input("clear-uploads", "n_clicks"),
Input("memory", "data"),
Input("sign-on-submit", "n_clicks"),
Input("session", "data"),
],
[
State("workflow-id", "value"),
State("initiate-pipeline", "n_clicks_timestamp"),
State("clear-pipeline", "n_clicks_timestamp"),
State("sign-on-submit", "n_clicks_timestamp"),
State("refresh-uploads", "n_clicks_timestamp"),
State("clear-uploads", "n_clicks_timestamp"),
],
)
def update_output(
list_of_contents,
list_of_names,
list_of_dates,
initiate_pipeline_n_clicks,
clear_pipeline_n_clicks,
append_uploads_n_clicks,
refresh_uploads_n_clicks,
clear_uploads_n_clicks,
memory,
user_login_n_clicks,
session_data,
workflow,
initiate_pipeline_timestamp,
clear_pipeline_timestamp,
user_login_timestamp,
refresh_uploads_timestamp,
clear_uploads_timestamp,
):
"""Primary APP Pipeline function, as triggered by 'Initiate
[APP] Pipeline' UI button (located in the "Step 2 (2/2)"
section).
Parameters
----------
list_of_contents
<list of str>
Array containing user-uploaded ABI raw contents as
binary strings (thus requiring decoding)
list_of_names
<list of str>
Array containing user-uploaded ABI filenames
(does not include the full path for security reasons)
list_of_dates
<list of int>
Array containing user-uploaded ABI last modified timestamps
(integers as seconds since 1970)
initiate_pipeline_n_clicks
<int>
Total count of UI button clicks
clear_pipeline_n_clicks
<int>
Total count of UI button clicks
append_uploads_n_clicks
<int>
Total count of UI button clicks
refresh_uploads_n_clicks
<int>
Total count of UI button clicks
clear_uploads_n_clicks
<int>
Total count of UI button clicks
memory
Dash.dcc.Store(type='session')
user_login_n_clicks
<int>
Total count of UI button clicks
session_data
Dash.dcc.Store(type='session')
workflow
<type>
initiate_pipeline_timestamp
<type>
clear_pipeline_timestamp
<type>
user_login_timestamp
<type>
refresh_uploads_timestamp
<type>
clear_uploads_timestamp
<type>
"""
def show_list_of_names(USER, list_of_names):
"""Display the filenames for all successfully received
USER-uploaded ABI files.
Args:
USER: <str>
Active user
list_of_names: <list>
List of user-uploaded ABI filenames
Returns:
<html.Div([...])>
Reactive response to display after processing upload
"""
if not all([fn.endswith(tuple([".csv",".xlsx"])) for fn in list_of_names]):
return html.Div(
[
html.Br(),
html.Code(
f"⚠ UPLOAD ERROR: Not all of the {len(list_of_names)} files are CSV or Excel files !",
style={"color": "red"},
),
html.Br(),
html.Code(
f"⛔ | Please reset this upload & then perform a fresh upload of either .csv or .xlsx files."
),
]
)
return html.Div(
[
html.Br(),
html.Code(
f"✔ UPLOAD SUCCESSFUL (N={len(list_of_names)})", style={"color": "green"}
),
html.Br(),
html.Br(),
html.Details(
[
html.Summary(
html.H3(
f"File(s) received (click to expand)",
style={"textAlign": "left", "fontSize": "120%"},
)
),
html.Div(
[
html.Li(f"{"{:02d}".format(i+1)})\t{abi}")
for (i, abi) in enumerate(sorted(list_of_names))
],
id="files-received",
style={
"textAlign": "left",
"fontSize": "60%",
"columnCount": "3",
"paddingBottom": "2%",
"fontFamily": "'Roboto Mono', monospace",
},
),
html.Hr(
style={
"borderTop": "1px solid",
"animation": "pact-gradient-text-flow 3s infinite linear",
"borderRadius": "5px",
"opacity": "0.67",
"width": "50%",
"marginLeft": "25%",
}
),
]
),
html.Br(),
html.Span(className="fader-line-short", style={"marginBottom": "20px"}),
],
style={"width": "80%", "marginLeft": "10%"},
)
not_signed_in_msg = html.Div(
[html.H6("Please log in to release the pipeline as ready for activation.")]
)
try:
if session_data: # ["user_logged_in"] == "True":
RUN_ID = session_data["RUN_ID"]
SESSION_OUTPUT_DIR = session_data["PATH_TO_SESSION_OUTPUT"]
LOG_FILE = session_data["session_log_file"]
USER = session_data["user_proper"]
UUID = session_data["UUID"]
if len(app.logger.handlers) < 1:
app.logger.info(
f"Number logger handlers = {len(app.logger.handlers)}->{logger.handlers}"
)
app.logger.info("Adding log FileHandler...")
fh = logging.FileHandler(LOG_FILE)
fh.setLevel(logging.INFO)
app.logger.addHandler(fh)
app.logger.info(
f"Number logger handlers = {len(app.logger.handlers)}->{logger.handlers}"
)
else:
return not_signed_in_msg
except KeyError as e:
app.logger.error(f"No user appears to be logged in (KeyError: {e})")
return not_signed_in_msg
### UPON USER FILE UPLOAD(S):
if list_of_contents is not None:
if initiate_pipeline_n_clicks >= 1:
init_t_elapse = tns() / 1e9 - initiate_pipeline_timestamp / 1e3
app.logger.info(f"init_t_elapse = {init_t_elapse}; ")
if init_t_elapse < 30:
if (
clear_pipeline_n_clicks > 0
and refresh_uploads_n_clicks <= clear_pipeline_n_clicks
):
if all(
clear_pipeline_timestamp > ts
for ts in [initiate_pipeline_timestamp, user_login_timestamp]
):
return [
html.H3(
f"Thanks, {USER}; the previous pipeline results have been cleared."
),
html.H4(f"Current analysis output folder: {RUN_ID}"),
html.H5(
html.Div(
[
html.Span(f"Launch a new analysis."),
html.Br(),
]
)
),
]
elif clear_pipeline_n_clicks > 0:
if clear_pipeline_timestamp > initiate_pipeline_timestamp:
if refresh_uploads_n_clicks > 0:
if refresh_uploads_timestamp > clear_pipeline_timestamp:
return show_list_of_names(USER, list_of_names)
return html.Div(
html.H5(
f"(Pipeline results [{RUN_ID}] CLEARED)", style={"color": "red"}
)
)
app.logger.info(
f"📟📶⌁⌁⌁📠Using the following as pipeline data input. \n{len(list_of_names)} USER UPLOADED FILE(S) : \n"
+ "\n 📊⇢🧬 ".join(
[
"{:>03d})\t{:>50s}".format(i + 1, abi)
for i, abi in enumerate(sorted(list_of_names))
]
)
)
app.logger.info(
f"INITIALIZING NEW PIPELINE LAUNCH:\n\n\t\t{SESSION_OUTPUT_DIR}"
)
start_time = tns()
children = []
parsed_upload_children = [
html.Details(
[
parse_contents(c, n, d, SESSION_OUTPUT_DIR, session_log_file=LOG_FILE)
for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)
]
)
]
# Generate (single!) TCR alpha/beta chain pair combinations
# base pipeline reference files (e.g., agg'd fq, designated master
# reference 'genome', DataFrames, log, etc.)
try:
pipeline_output = ljoin(
[
r
for r in pipeline.run_pipeline(
RUN_ID,
SESSION_OUTPUT_DIR,
workflow=workflow,
session_log_file=LOG_FILE,
)
]
)
args = [(*(x), i + 1) for i, x in enumerate(pipeline_output)]
except Exception as e:
logs = []
report = None
with open(LOG_FILE, "r+") as log_file:
for line in log_file.readlines():
logs.append(line)
stderr = [
dcc.Textarea(
placeholder="(Main Sequence -- logger placeholder)",
value="\n".join(logs),
style={
"height": "400px",
"width": "50%",
"fontSize": "0.7rem",
"lineHeight": "0.9rem",
"fontFamily": "'Roboto Mono', monospace",
},
className="logger-text",
name="organization",
readOnly=True,
)
]
fatal_crash = "⚠ ALERT: ERROR IN MAIN PIPELINE SEQUENCE"
app.logger.error(f"{fatal_crash}: \n\n{e}")
log_exc(app.logger)
return html.Div(
[
html.H2(fatal_crash, style={"color": "red"}),
html.P(f"App runtime was: {gtt(start_time)}"),
html.Code(f"Primary error message for crash:\n{e}"),
html.H4("See [end of] AUDIT LOG (below) for failure reason."),
html.H5(f"WEB SERVER SYSTEM LOG:", style={"color": "red"}),
html.Div(stderr),
]
)
### # # # # # # # # # #### # # # # # # # # # ###
children.append(
html.Div(
[
html.Hr(),
html.Br(),
html.H4("All files analyzed in most recent upload:"),
]
)
)
""" ~ ◮ ~
S U M M A R Y
a n a l y s i s
~ ~ ~
~ ◮ ~
"""
if report:
summary_report = [
html.Div(
[
html.Br(),
html.H2(
"Pipeline Output Summary",
style={
"fontSize": "80%",
"letterSpacing": "1.33rem",
"fontFamily": "Cinzel",
"animation": "anim-text-flow-keys 120s infinite linear",
},
),
html.Hr(),
],
style={"width": "90%", "marginLeft": "5%"},
)
]
else:
summary_report = [html.Div([html.H4(f"No final output found.")])]
html_out = f"{SESSION_OUTPUT_DIR}{RUN_ID}_HTMLprops.tsv"
pd.DataFrame(
[str(c.to_plotly_json()) for c in children], columns=["DashHTMLDivComponents"]
).to_csv(html_out, encoding="utf-8", sep="\t")
app.logger.info("Processed & analzyed input files were:")
app.logger.debug(parsed_upload_children)
app.logger.info(",".join([str(type(x)) for x in parsed_upload_children]))
total_exec_time = gtt(start_time)
app.logger.info(
f"———COMPLETE——-\n\n \t ☆☆☆ Total EXECUTION TIME Required ☆☆☆\n\n \t\t = {total_exec_time} s \n\n"
)
show_exec_time = [
html.Div(
[
html.Hr(),
html.H3(
f"* ゚(>͂ ͡͡︒ ͜ ʖ ͡︒)>-。゚☆* :・゚.☆ * ・ "
),
html.H4(f"Total Execution Time Required = {total_exec_time} s"),
html.Hr(),
html.Br(),
]
)
]
if len(children) > 50:
full_report = [
html.Div(
[
html.H2(
f"NOTICE: Due to an unusually large number of results in this analysis (N={len(children)}), full report display has been automatically disabled."
)
]
)
]
else:
full_report = children
children = (
show_exec_time
+ TOC
+ summary_report
+ full_report
+ parsed_upload_children
+ [html.Div(html.Hr())]
)
app.logger.debug(",".join([str(type(x)) for x in children]))
app.logger.debug(f"Number of html.Div elements in final layout: {len(children)}")
return children
elif initiate_pipeline_n_clicks > 15:
return html.Div(
[
html.H4(
"⚠ | ALERT ! : Un𝒇ortunately, you have over-activated the pipeline submissions check system. Please re𝒇resh the page, re-log in, and re-upload the set o𝒇 ABI 𝒇iles you would like analyzed. 🛠⎆ "
),
html.H6("↺ Please Re𝒇resh the page. ↺"),
]
)
if clear_uploads_n_clicks > 0:
t_elapsed = tns() / 1e9 - clear_uploads_timestamp / 1e3
if t_elapsed < 2:
for tcr_dir in os.listdir(SESSION_OUTPUT_DIR):
grouped_clone_fqs = f"{SESSION_OUTPUT_DIR}{tcr_dir}"
if os.path.isdir(grouped_clone_fqs):
shutil.rmtree(grouped_clone_fqs)
return html.Div(
[
html.Code(f"UPLOADS CLEARED", style={"color": "red"}),
html.H5(
f'To continue, submit at least one new upload & click "✥ Append".'
),
]
)
if append_uploads_n_clicks > 0 or clear_uploads_n_clicks > 0:
if len(list_of_names) > 0 and len(memory.items()) > 0:
all_uploads = (
memory[f"{RUN_ID}-list_of_names"]
if len(memory[f"{RUN_ID}-list_of_names"]) > 0
else list_of_names
)
return show_list_of_names(USER, all_uploads)
elif len(memory.items()) == 0:
return html.Div(html.Code("NONE"))
else:
app.logger.info(
f"{USER} uploaded the following {len(list_of_names)} file(s):"
+ "\n\t ◇ 📄 "
+ "\n\t ◇ 📄 ".join(sorted(list_of_names))
+ ".\n"
)
return show_list_of_names(USER, list_of_names)
else:
return html.Div(
[html.Br(), html.H5(f"Logged in as: {USER}", style={"color": "rgb(32,92,188)"})]
)
@app.callback(
Output(f"output-file-list", "children"),
[Input(f"refresh-downloads-links", "n_clicks")],
[State(f"download-dropdown", "value"), State(f"session", "data")],
)
def update_link(refresh_n_clicks, value, session_data):
""""Download Output Files" dropdown components suite.
Allows user to choose from a list of file 'genres' (i.e.,
subsets of similar bioinformatics datafile types) - and
reacts by displaying all corresponding generated results
files for the current session analysis up-to-now, which
dual, and principally serve their purpose, as direct-to-
desktop functional download links.
Also capable of showing a full printout of the current cum-
ulative state of the session logfile in via an HTML
textarea Dash component.
Finally, users are also presented (via HTML button comp)
the option and ability to create a click-to-download link
for a dynamically generated zipped archive of all curr-
ently selected (& thus [reactively] displayed) results
files.
Args:
-----
refresh_n_clicks : int
value : str
session_data (dcc.Store( : Dash HTTP client-side memory caching,
type='session') . "Session" type (auto-cleared when browser
) . tab closes [but *not* on Refresh's]).
Returns:
--------
html.Div([html.Li's]) : An array of download-enabling Dash HTML
hyperlink components.
"""
if value:
if session_data:
selection = output_filetype_genres[value]
try:
session_output = session_data["PATH_TO_SESSION_OUTPUT"]
except KeyError as e:
app.logger.info(
f"User attempting to access files when not yet logged in!\nError:\n{e}"
)
return [html.Li(f"(Please log in first!)")]
if value == "LOGS":
files = sorted(get_output_files(selection, session_output))
logs = []
for f in files:
with open(f, "r+") as log_file:
for line in log_file.readlines():
logs.append(line)
if len(app.logger.handlers) < 1:
app.logger.addHandler(add_logfile(f))
app.logger.info("Re-added logfile (post-log printout)")
return [html.Li(file_download_link(filename)) for filename in files] + [
dcc.Textarea(
placeholder="(No logged activity yet.)",
value="\n".join(logs),
style={
"height": "550px",
"width": "60%",
"fontSize": "0.7rem",
"lineHeight": "0.9rem",
"fontFamily": "'Roboto Mono', monospace",
},
className="logger-text",
name="organization",
readOnly=True,
)
]
elif value == "REF":
return [
html.Li(
file_download_link(filename),
style={"fontFamily": "'Roboto Mono', monospace", "letterSpacing": "-1pt"},
)
for filename in sorted(get_output_files(selection))
]
files = get_output_files(selection, session_output)
if len(files) == 0:
return [html.Li(f"No output files available for selection: {value}.")]
else:
return [
html.Li(
file_download_link(filename),
style={"fontFamily": "'Roboto Mono', monospace", "letterSpacing": "-1pt"},
)
for filename in sorted(files)
]
else:
return [html.Li(f"(Please log in first!)")]
else:
return [html.Li(f"[Select an output filetype(s) category.]")]
@app.callback(
Output(f"download-all", "children"),
[Input(f"request-all-zipped", "n_clicks")],
[State(f"download-dropdown", "value"), State(f"session", "data")],
)
def zip_all_downloadables(getZipped_n_clicks, value, session_data):
"""Create a downloadable zip of USER selected set of output files.
Args:
getZipped_n_clicks: int
value: str
session_data: Dash.dcc.Store(type='session')
Returns:
html.Div([]): Dash HTML div component↦ itself an array of Dash HTML components
"""
if getZipped_n_clicks > 0 and any(session_data):
selection = output_filetype_genres[value]
session_output = session_data["PATH_TO_SESSION_OUTPUT"]
RUN_ID = session_data["RUN_ID"]
source = session_output if value != "REF" else PLASMIDS_ARCHIVE
files = get_output_files(selection, final_output_dir=source)
zipped = re.sub("['\ \(\)]", "", f"{session_output}{RUN_ID}_{clock()[-4:]}.zip")
for i, filename in enumerate(files):
fbn = f"{os.path.basename(filename)}"
app.logger.info(f"{i}: Adding file {filename} to new zipped archive: {fbn}...")
with zipfile.ZipFile(zipped, "a") as zipf:
zipf.write(filename, fbn)
return html.Div(
[
html.H4(f"Zip⇝⇶🗃⇨Download All:"),
html.H4([html.Li(file_download_link(zipped), className="zip-dl-link")]),
]
) | """'Callbacks' are what enable the "reactive" functionality
of a Python Dash web application (literally, the react.js).
Every time a user interacts with a UI component on the web
app page in their browser, a callback with matching Input
(via the component's 'id' attribute) from this module is
activated, thus allowing customized programmed reactions
to any individual and/or series of any [possible combi-
nation of] user actions.
> dash-webapp-template
> C a l l b a c k s
> 𝕄𝕠𝕕𝕦𝕝𝕖
> ண⎤꜒𓇃𓇃𓇃ཥ⅌ཤ𓇃𓇃𓇃𓋏ཀཫ𓋏𓇃𓇃𓇃╗╔𓇃𓇃𓆽⦄༽⸶⸷༼⦃𓆽𓇃𓇃𓇃𓇊𓊢ༀ࿐࿓𓇊࿑
## John Collins GitHub Public Repos — dash-webapp-template
To learn more about callbacks, see:
https://dash.plot.ly/getting-started-part-2
> ୡ ୡୡ ୡ
> ◖𓇃ⴶ〰⸅‖⸄〰ж𓇃𓇃𓇃𓇃⸠⎫𓏉⎧⸡𓇃𓇃𓇃𓏟𓏞𓇃𓇃╗╔𓇃𓇃𓇃𓐩𓋥⸶⸷𓋥𓐩◗
> ୡ ୡ ୡୡ
> ◖𓇃𓇃𓇃𓏣🜾𓏣𓇃𓇃𓉽𓇃𓎸𓈌𓎹𓇃⎨⎬𓇃˥⎡𓇃𓇃࿅𓇃𓊢ꃊ𓊢𓇃𓇃𓇃◗
Attributes:
----------
logger (logging.Logger):
Current session log file
version (str):
Current git-committed source codebase version
____________________________
ୡ
𓇃𓏣🜾𓏣𓇃࿑
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from flask import Flask
from werkzeug.routing import Rule
from .config import *
from .utils import *
from seqapp import app
import config
from config import *
import bioinfo as bioinformatics
from bioinfo import pipeline, visualization
from bioinfo.pipeline import (
parse_contents,
)
version = VERSION
logger = logging.getLogger(__name__)
########################################
# S T A N D A R D F U N C T I O N S #
########################################
""" See the app.utils module & also the /app/config init file
for some of the more general, non-reactive functions which may
nonetheless be imported and used in the callbacks below.
"""
########################################
# F L A S K F U N C T I O N S #
########################################
""" The dash.Dash() app object is itself at its core a flask app
object, too; thus, all of the [vast] Flask source code
functionalities are compatible as-is with Dash apps.
"""
app.server.url_map.add(Rule('/', endpoint='downloadZAll'))
app.server.url_map.add(Rule('/', endpoint='urlToDownload'))
@app.server.endpoint("/downloadZAll")
def download_all_selected():
"""Send path from directory to allow user to
download zipped files as an attachment.
Returns:
File download directly to user's PC.
"""
value = flask.request.args.get("value")
fbn = f"{os.path.basename(value)}"
app.logger.info(f"🗽| REQUEST TO DOWNLOAD: for [zipped] server file @ {value}")
return flask.send_from_directory(
directory=f"{os.path.dirname(value)}",
filename=fbn,
attachment_filename=fbn,
as_attachment=True,
mimetype="zip",
)
@app.server.endpoint("/urlToDownload")
def download_file():
"""Send path from directory to allow user
to download file as an attachment.
Returns:
"""
value = flask.request.args.get("value")
fbn = f"{os.path.basename(value)}"
app.logger.info(f"🗽| REQUEST TO DOWNLOAD: for server file @ {value}")
mime = "text/plain" if "png" not in value else "image/png"
return flask.send_from_directory(
directory=f"{os.path.dirname(value)}",
filename=fbn,
attachment_filename=fbn,
as_attachment=True,
mimetype=mime,
)
########################################
# C A L L B A C K F U N C T I O N S #
########################################
""" Every callback function is preceded by a special `@app.callback`
Python decorator function, which necessarily has an Output() and
at least one Input() parameter (both objects from dash.dependencies).
Optionally, a callback function decorator can also contain a
State() parameter (also imported from dash.dependencies).
Typically, the return of a callback function is an html.Div()
object containing a list of updated components to be returned to
the UI via the 'id' attribute indicated on the Output() object
of callback decorator.
For a helpful overview on Python decorators, see:
https://realpython.com/primer-on-python-decorators/
"""
@app.callback(
Output(f"user-login-confirmation", "children"),
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"input-user-name", "value"),
Input(f"clear-pipeline", "n_clicks"),
Input(f"session", "data"),
Input(f"log-out-submit", "n_clicks")
],
[State(f"sign-on-submit", "n_clicks_timestamp")],
)
def confirm_new_session(
n_clicks,
user_sign_on,
clear_n_clicks,
session_data,
logout,
login_timestamp,
):
"""Responsive components generation for user sign-on at top of app UI page.
Parameters
----------
n_clicks : int
Total cumulative count of clicks 'submit' (sign-in) button
user_sign_on : str
Selected user name from sign on dropdown
clear_n_clicks : int
Total cumulative count of clicks clear pipeline button
session_data : Dash.dcc.Store(type='session')
Dash HTTP client-side memory caching, "Session" type (auto-cleared when
browser tab closes [but *not* on Refresh's]).
logout : int
Total cumulative count of clicks logout button
login_timestamp : int
Timestamp at most recent sign on button click as integer
(e.g., 1572843293129)
"""
if user_sign_on == "None" and logout < 1:
raise PreventUpdate
if not user_sign_on:
return [
html.H6(
"Please sign in to create a new session.",
style={"fontSize": "1.2rem", "fontWeight": "300"},
)
]
try:
enter_user = session_data["current_user"]
user_proper = session_data["user_proper"]
putat_user = user_sign_on[0] + user_sign_on.split("_")[0].lower()[1:]
try:
prev_user = session_data[f"SIGN_ON-№{n_clicks-1}"]
except KeyError as e:
prev_user = "NONE"
app.logger.debug(f"Recorded user name: {enter_user} (Prev. user={prev_user})")
if login_timestamp:
submit_t_elapsed = tns() / 1e9 - login_timestamp / 1e3
app.logger.debug(f"USER LOGIN : `submit_t_elapsed` = {submit_t_elapsed}")
else:
submit_t_elapsed = 0 # <1 ≡ No recent sign in!
if (
user_sign_on == enter_user
or session_data["user_logged_in"] == "True"
) and submit_t_elapsed < 1:
log_t_init = session_data["login_t_init"]
session_log_file = session_data["session_log_file"]
RUN_ID = session_data["RUN_ID"]
app.logger.info(
f"* C R E A T E D N E W 'Current SESSION OUTPUT DIR' *\n{session_data['PATH_TO_SESSION_OUTPUT']}"
)
return html.Details(
[
html.Div(
[
html.Span(
f"Active User Account — {enter_user.replace('_', ' ').title()}",
style={
"fontSize": "1.2rem",
"fontFamily": "'Open Sans', sans-serif",
"fontWeight": "300",
"color": "#304479",
},
),
html.Span(
className="fader-line-short", style={"marginBottom": "20px"}
),
html.P("You're all set!"),
html.H6(f"Sign-on Timestamp: {log_t_init.split('=')[1]}", style={"fontSize": "0.65rem"}),
html.P(
f"Session ID:\t{RUN_ID}",
style={
"animation": "anim-text-flow-keys 60s infinite linear",
"mixBlendMode": "difference",
"fontSize": "0.7rem",
},
),
],
className="updates-list",
),
html.Summary(
html.Code(
f"✔ LOGGED IN",
style={"color": "rgb(24, 230, 112)"},
className="updates-header",
)
),
],
id="logged-in-status",
)
elif n_clicks > 1 and prev_user != "None yet.." and enter_user != prev_user:
return [
html.Br(),
html.H4(
f"{putat_user}, would you like to sign on [& log out {prev_user}]?",
style={"display": "block"},
),
html.P(f"🧙🧠🗲⚛ 👌📓⬸📖🖊", style={"fontSize": "3rem"}),
]
except Exception as e:
user_proper = "⚠:[USER_UNKNOWN!]"
app.logger.warning(f"Note: Exception raised during user sign on: {e}")
return [
html.Br(),
html.H6("Sign In ( ⮩️🚪✨ ) to create a new, blank output directory for your analysis."),
]
@app.callback(
Output(f"input-user-name", "value"),
[
Input(f"log-out-submit", "n_clicks"),
Input(f"log-back-in-submit", "n_clicks"),
],
[
State(f"log-out-submit", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks_timestamp"),
State(f"log-back-in-submit", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks"),
State(f"local", "data"),
],
)
def log_out_or_comeback(
logout,
quick_logback,
log_out_timestamp,
sign_on_timestamp,
logback_on_timestamp,
signon,
user_profile,
):
"""Enable USER "Log Out" functionality.
Parameters
----------
logout : int
Total cumulative count of clicks log out button
quick_logback : int
Total cumulative count of clicks "Return" button
log_out_timestamp : int
Timestamp of last user click log out button
sign_on_timestamp : int
Timestamp of last user click sign-in button
logback_on_timestamp : int
Timestamp of last user click "Return" button
signon : int
Total cumulative count of clicks user sign-in button
user_profile : Dash.dcc.Store(type='local')
Browser-cached local app memory, containing stored saved
user "profile" info / stats.
"""
if not user_profile:
raise PreventUpdate
if logout < 1 and quick_logback < 1:
raise PreventUpdate
if quick_logback > 0:
if signon > 0 and logout > 0:
if logback_on_timestamp > max(log_out_timestamp, sign_on_timestamp):
return user_profile["userAccount"]
elif signon < 1:
return user_profile["userAccount"]
elif logout > 0 and signon > 0:
if log_out_timestamp > sign_on_timestamp:
return "None"
@app.callback(
[
Output(f"session", "data"),
Output(f"local", "data"),
],
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"log-out-submit", "n_clicks"),
Input(f"clear-pipeline", "n_clicks"),
],
[
State(f"input-user-name", "value"),
State(f"session", "data"),
State(f"local", "data"),
State(f"initiate-pipeline", "n_clicks"),
State(f"initiate-pipeline", "n_clicks_timestamp"),
State(f"clear-pipeline", "n_clicks_timestamp"),
State(f"sign-on-submit", "n_clicks_timestamp"),
State(f"refresh-uploads", "n_clicks_timestamp"),
State(f"log-out-submit", "n_clicks_timestamp"),
],
)
def record_user_name(
login_n_clicks,
logout_n_clicks,
clear_pl_n_clicks,
user_selection,
data,
local_cache,
init_pl_n_clicks,
initiate_pipeline_timestamp,
clear_pipeline_timestamp,
user_login_timestamp,
refresh_uploads_timestamp,
log_out_timestamp,
):
"""Upon user sign on (or sign off), correspondingly update the cached
information describing the current user (e.g., name, proper name, sign
in history, etc.) and create and store a new RUN ID for the current
session, as applicable.
Args:
login_n_clicks (int):
Total cumulative count of clicks user sign-in button
logout_n_clicks (int):
Total cumulative count of clicks log out button
clear_pl_n_clicks (int):
Total cumulative count of clicks clear results button
user_selection (str):
Selected value from user names dropdown in app log-in section
data (Dash.dcc.Store):
[Session] HTTP client-side memory cache
local_cache (Dash.dcc.Store):
[Local] HTTP client-side memory cache
init_pl_n_clicks (int):
Total cumulative count of clicks initiate step 2 pipeline button
initiate_pipeline_timestamp (int):
Timestamp of last user click initiate step 2 pipeline button
clear_pipeline_timestamp (int):
Timestamp of last user click clear results button
user_login_timestamp (int):
Timestamp of last user click sign-in button
refresh_uploads_timestamp (int):
Timestamp of last user click refresh uploads button
log_out_timestamp (int):
Timestamp of last user click log out button
"""
app.logger.debug(f"sign on timestamp: {user_login_timestamp}")
reset_session_data = {
"SIGN_ON-№0": "None yet..",
"RUN_ID": "NA",
"current_user": "None",
"user_logged_in": "False",
"user_proper": "NA",
}
if login_n_clicks < 1 or user_selection == "None" or not user_selection:
if not user_selection:
return (
reset_session_data,
local_cache,
)
else:
data = {"SIGN_ON-№0": "None yet.."}
data["RUN_ID"] = "NA"
data["current_user"] = user_selection
data["login n_clicks"] = login_n_clicks
data["user_logged_in"] = "False"
data["user_proper"] = user_selection.replace("_", " ").title().split()[0]
return data, local_cache
login_t_elapse = tns() / 1e9 - user_login_timestamp / 1e3
UUID = f"{''.join([*map(lambda x: x[:2], user_selection.split('_'))])}"
logins = f"SIGN_ON-№{login_n_clicks}"
data = data or {"SIGN_ON-№0": "None yet.."}
data["UUID"] = UUID
user_proper = user_selection[0] + user_selection.split("_")[0].lower()[1:]
data["user_proper"] = user_proper
data["current_user"] = user_selection
data["login n_clicks"] = login_n_clicks
if (login_n_clicks > logout_n_clicks and user_selection != "None") and login_t_elapse < 2:
data["user_logged_in"] = "True"
if logout_n_clicks > 0:
if (tns() / 1e9 - log_out_timestamp / 1e3) < 2:
return reset_session_data, local_cache
if not user_selection:
data["user_logged_in"] = "None"
return data, local_cache
# Proceed with apparent sign-in submission if this point reached:
login_t_init = f"{tns()} = {now()}"
data["login_t_init"] = login_t_init
data[logins] = user_selection
if "SIGN_ON-№1" in data.keys():
data["prev_user"] = data[f"SIGN_ON-№{max(login_n_clicks-1,1)}"]
RUN_ID = f"APP_RUNID_{now()}"
SESSION_OUTPUT_DIR = f"{RUN_OUTPUT_DIR}/{today()}/{RUN_ID}/"
data["RUN_ID"] = RUN_ID
data["PATH_TO_SESSION_OUTPUT"] = SESSION_OUTPUT_DIR
session_log_file = f"{SESSION_OUTPUT_DIR}{RUN_ID}_CurrentSession.log"
os.makedirs(SESSION_OUTPUT_DIR, exist_ok=True)
app.logger.debug(f"Number of logger handlers: {logger.handlers}")
fh = add_logfile(logfile=session_log_file, logger=logger)
app.logger.addHandler(fh)
app.logger.debug(f"Number of logger handlers: {logger.handlers}")
app.logger.info(f"USER SIGN ON @ {login_t_init}")
app.logger.info(f"*** CURRENT APP APP SOFTWARE VERSION = {VERSION} ***")
data["session_log_file"] = session_log_file
data["SESSION_DATA"] = pd.DataFrame(
[[RUN_ID, SESSION_OUTPUT_DIR, user_selection, session_log_file]],
columns=["RUN_ID", "PATH_TO_SESSION_OUTPUT", "USER_ID", "LOG_FILE"],
).to_json(date_format="iso", orient="split")
app.logger.info(f"USER: '{user_selection}' | RUN ID: {RUN_ID}")
# Store basic user profile in browser local cache for app:
reset_local_cache = {
"userName": user_proper,
"userAccount": user_selection,
"userProfileCreated": now(),
"countUserLogIns": 0,
"userRuns": {RUN_ID: data},
}
try:
if local_cache["userAccount"] != user_selection:
local_cache = reset_local_cache
local_cache["countUserLogIns"] += 1
local_cache["userRuns"][RUN_ID] = data
except Exception as e:
app.logger.info(
f"Creating {user_proper}'s first local memory cache! (I.e., by which to remember them by! 😉)"
)
local_cache = reset_local_cache
local_cache["countUserLogIns"] += 1
return data, local_cache
@app.callback(
Output(f"user-status", "children"),
[
Input(f"sign-on-submit", "n_clicks"),
Input(f"refresh-user-history", "n_clicks"),
Input(f"session", "data"),
],
[State(f"input-user-name", "value"), State(f"local", "data")],
)
def show_user_in_menubar(
sign_on_n_clicks, save_results_n_clicks, session_data, selected_username, local_data_cache
):
"""
Parameters
----------
sign_on_n_clicks
int
save_results_n_clicks
int
session_data
Dash.dcc.Store(type='session')
selected_username
str
local_data_cache
Dash.dcc.Store(type='local')
"""
log_in = [
html.Span(
html.A(["⁂ Sign In"], href=f"#log-in-below"),
style={"fontSize": "80%", "color": "goldenrod"},
id=f"log-in",
)
]
if session_data and sign_on_n_clicks > 0:
if "session_log_file" in session_data:
if session_data["current_user"] != "None":
user = session_data["user_proper"]
USER = session_data["current_user"]
default = []
history = {}
try:
history = local_data_cache[f"{USER}_APP_Saved_History"]
app.logger.debug(str(local_data_cache), str(history))
except Exception as e:
history = {}
default = [html.Li(f"You have no saved APP Results History, yet!\n")]
return [
html.Details(
[
html.Summary(
[
html.Span(
f"👤Signed in as: {user}",
style={
"fontFamily": "Muli",
"fontSize": "85%",
"cursor": "pointer",
},
className="user-menu-summary",
)
]
),
html.Div(
[
html.Ul(
[
html.Li(f"Current RUN_ID: {session_data['RUN_ID']}"),
html.Li(
f"User Is Logged In: {session_data['user_logged_in']}",
className="user-menu-action-items",
style={"color": "rgb(37, 109, 210)"},
),
html.Li(
f"Signed On @ {session_data['login_t_init']}",
className="user-menu-action-items",
style={"color": "rgb(17, 199, 210)"},
),
html.Li(
[
html.A(
"Your Saved Analysis History",
href="#save-user-results",
),
html.Ul(
[
html.Li(dcc.Link(f"{k}", href=f"/{k}"))
for k in history.keys()
]
+ default,
style={
"listStyle": "decimal-leading-zero",
"margin": "0!important",
"padding": "0!important",
},
),
],
className="user-menu-action-items",
style={"color": "rgb(37, 149, 180)"},
),
html.Li(
[
html.A(
"Report an Issue/Bug",
href="mailto:jcollins.bioinformatics@gmail.com",
)
],
className="user-menu-action-items",
style={"color": "rgb(7, 69, 180)"},
),
]
)
],
className="user-menu",
style={"color": "rgb(199, 199, 199)"},
),
]
)
]
return log_in
@app.callback(Output(f"workflow-selection", "children"), [Input(f"workflow-id", "value")])
def update_workflow_choice(workflow):
"""Update display at top of app based on USER's Worlflow selection
(e.g., "Gene Editing: [...]", etc.)
Args:
workflow: str
Returns:
Array of H2 HTML Header element containing workflow text.
"""
app.logger.debug(f"CALLBACK:::`update_workflow_choice` triggered with value: {workflow}")
return [html.H2(f"{workflow}", style={"textAlign": "center"})]
@app.callback(Output("dd2-dropdown", "options"), [Input("dd1-dropdown", "value")])
def update_dropdown(dd1):
"""Update Dropdown for sample corresponding to USER-selected ID.
Args:
dd1 (Array of "label":"value" pairs dictionary containing the): Dropdown's options.
Returns:
Updated array matching form of input.
"""
app.logger.debug(f"CALLBACK:::`update_dropdown` triggered with value: {dd1}")
if dd1 and dd1 != "None":
ent_id, ent_name, = dd1.split("-")
try:
wells = entity_schemas.loc[ent_name].columns #.unique()
except KeyError as e:
app.logger.info(f"WellID dropdown error in Plasmid Tool:\n{e}")
return [{"label": "——N/A——", "value": "Error"}]
# ⤑⟗αβ⟗⇒ *Trigger Ligation*
return [{"label": " ✔ Confirm Well & EXP ID", "value": "None"}] + [
{"label": w, "value": w}
for w in wells
]
else:
return [{"label": "——N/A——", "value": "None"}]
@app.callback(
Output("submission-status", "children"),
[Input("submit-selected-dds", "n_clicks"), Input("clear-dd-selections", "n_clicks")],
[State("dd1-dropdown", "value"), State("dd2-dropdown", "value")],
)
def trigger_dropdowns(submit_n_clicks, clear_n_clicks, dd1, dd2):
"""Initiate first analysis
Args:
submit_n_clicks: int
clear_n_clicks: int
dd1: str
dd2: str
Returns:
Dash html component(s)
"""
if clear_n_clicks == submit_n_clicks + 1:
return html.Code(
"⚠ | ℹ Overclicking clear *may* require compensatory submits! (I.e., Try clicking submit button >1 times, if submissions are not going through.)",
style={
"color": "red",
"display": "flex",
"flexFlow": "column wrap",
"fontSize": "1.0rem",
"margin": "0px 30% 20px 30%",
},
)
if all(ui not in ("None", None) for ui in [dd1, dd2]):
app.logger.info(
f"-:!:- FUNCTION('trigger_dropdowns') has been activated, and now has value 'submit_n_clicks' = {submit_n_clicks}"
)
return [html.Code(f"SUBMISSION for: {dd1}, @Well{dd2}")]
elif clear_n_clicks > submit_n_clicks + 1:
app.logger.info(
f"-:!:- FUNCTION('trigger_dropdowns') has been cleared, and now has value 'clear_n_clicks' = {clear_n_clicks}"
)
return html.Code(
f"Submissions cleared: {clear_n_clicks}, [submissions_count={submit_n_clicks}].",
style={"fontStyle": "normal", "color": "gray", "margin": "0px 30% 20px 30%"},
)
else:
return html.Code("No submissions received, it seems...")
@app.callback(
Output("dd-selections", "children"),
[
Input("dd1-dropdown", "value"),
Input("dd2-dropdown", "value"),
Input("submit-dds", "n_clicks"),
Input("clear-dd-selections", "n_clicks"),
Input("workflow-id", "value"),
],
[State("session", "data"), State("submit-selected-dds", "n_clicks_timestamp")],
)
def display_generated_dd_output(
dd1,
dd2,
submission,
clear_submission,
workflow,
session_data,
submission_timestamp,
):
"""Generic template for a paired dynamics set of dropdowns;
such that the user selection in the first dropdown dynamically
modifies live the possible options in the second dropdown.
Args:
dd1: str
dd2: str
submission: int
clear_submission: int
workflow: str
session_data: Dash.dcc.Store(type='session')
submission_timestamp: int
"""
if (dd1 == "None" and dd2 == "None") or dd1 is None:
return [
html.Div(
[
html.Span(
f"Make a new selection.",
style={"textAlign": "center", "fontFamily": "Muli", "fontSize": "1.5rem"},
),
html.Span(
html.Img(
src="../assets/animations/dna-minimal-green.gif",
height="150",
style={
"transform": "translateY(-55px) translateX(5px)",
"filter": "hue-rotate(100deg) contrast(1.1) saturate(5)",
"position": "absolute",
"opacity": "0.5",
"borderRadius": "250px",
},
)
),
],
style={
"marginLeft": "25%",
"position": "relative",
"textAlign": "center",
"width": "50%",
"zIndex": "-1",
},
),
html.Div(
[
html.Span("↪⦿"),
html.Img(
src="../assets/images/scope-unic.png",
width="80",
style={"marginTop": "15px", "marginBottom": "-25px", "cursor": "pointer"},
),
html.Span("⥅♅"),
],
style={
"textAlign": "center",
"fontSize": "1.75rem",
"animation": "animateGlow 45s infinite linear!important",
"cursor": "pointer",
},
),
]
elif any(ui == "Error" for ui in [dd1, dd2]):
return
elif dd1 != "None" and dd2 is None:
return [
html.H5(
f"ℹ | Informational message to display.",
style={"textAlign": "center", "marginLeft": "25%", "width": "50%"},
)
]
elif all(ui != "None" for ui in [dd1, dd2]):
return html.Div(
[
html.Code(
f"♻ Cleared submission state: [total_clears={clear_submission}]",
style={"fontStyle": "italic", "fontSize": "0.9rem", "marginBottom": "5px"},
),
html.Br(),
html.Div(
[
html.H6(
[
html.P(f"⮊ Click ⬫Submit⬫ 𝑓𝗈𝓇⤑{dd2} ~ {dd1}"),
html.Span("to initiate "),
html.Span(
f"in silico ",
style={"fontStyle": "italic", "fontFamily": "'Times', serif"},
),
html.Span("analysis of selections."),
],
style={
"textAlign": "center",
"cursor": "pointer",
"color": "#ffffff6e",
"backgroundImage": "url(https://media.giphy.com/media/4HIOPSXOitJ2o/giphy.gif)",
"mozBackgroundClip": "text",
"webkitBackgroundClip": "text",
"fontWeight": "700",
"backgroundSize": "60%",
},
)
],
style={
"position": "absolute",
"margin": """0.5% -5% -5% -5%""",
"textAlign": "center",
"display": "inline-block",
"mixBlendMode": "lighten",
"width": "200px",
},
),
html.Br(),
html.Br(),
html.Div(
[
html.Span("✂"),
html.Span(""),
html.Span("⭾"),
html.Span("α/β"),
html.Div(
[
html.Video(
src=f"data:video/mp4;base64,{base64.b64encode(open(f'../assets/animations/T-Cell_TEM_4-3.mp4', 'rb').read()).decode()}",
id="t-cell",
autoPlay=True,
loop=True,
controls=False,
preload="true",
muted=True,
)
],
style={"filter": "opacity(0.25)"},
),
],
style={
"textAlign": "center",
"fontSize": "2rem",
"width": "20%",
"marginLeft": "40.5%",
"mixBlendMode": "exclusion",
},
className="animate twirl",
),
],
style={"textAlign": "center"},
)
@app.callback(Output("dd1-dropdown", "value"), [Input("clear-dd-selections", "n_clicks")])
def clear_dd1_selection(n_clicks):
"""Clear Dropdown selections for Dropdown #1 (dd1)
( Dropdown to clear #1 of 2 )
Args:
n_clicks: int
Returns:
str: Resets selections to default, blank states.
"""
if n_clicks > 0:
app.logger.info(
f"-:!:- FUNCTION('clear_dd1_selection') has been activated, and now has value 'n_clicks' = {n_clicks}"
)
return "None"
@app.callback(
Output("dd2-dropdown", "value"),
[Input("dd1-dropdown", "value"), Input("clear-dd-selections", "n_clicks")],
)
def clear_dd2_selection(val, n_clicks):
"""Clear Dropdown selections for Dropdown #2 (dd2)
( Dropdown to clear #2 of 2 )
Args:
val (str): cascading response via `clear_dd2_selection()` callback
n_clicks: int
Returns:
str: Resets selections to default, blank states.
"""
if n_clicks > 0:
app.logger.info(
f"-:!:- FUNCTION('clear_dd2_selection') has been activated, and now has value 'n_clicks' = {n_clicks} & 'val' = {val}"
)
if val == "None":
return "None"
else:
return None
@app.callback(
Output("memory", "data"),
[
Input("append-uploads", "n_clicks"),
Input("clear-uploads", "n_clicks"),
Input("refresh-uploads", "n_clicks"),
Input("upload-data", "contents"),
],
[
State("session", "data"),
State("memory", "data"),
State("append-uploads", "n_clicks_timestamp"),
State("refresh-uploads", "n_clicks_timestamp"),
State("clear-uploads", "n_clicks_timestamp"),
State("upload-data", "filename"),
State("upload-data", "last_modified"),
],
)
def enable_combined_file_uploads(
append_nclicks,
clear_nclicks,
refresh_nclicks,
list_of_contents,
session_data,
clientside_memory_cache,
append_nclicks_timestamp,
refresh_nclicks_timestamp,
clear_nclicks_timestamp,
list_of_names,
list_of_dates,
):
"""Management of app components and file upload States allowing for USER-
toggled continuation of upload (i.e., as opposed to overwriting any previously
received ABI files uploaded).
Args:
append_nclicks: int
clear_nclicks: int
refresh_nclicks: int
list_of_contents: list of bytes
session_data: Dash.dcc.Store(type='memory')
clientside_memory_cache: Dash.dcc.Store(type='memory')
append_nclicks_timestamp: int
refresh_nclicks_timestamp: int
clear_nclicks_timestamp: int
list_of_names: list of str
list_of_dates: list of int
"""
memory_reset = {}
if not session_data:
raise PreventUpdate
if clear_nclicks > 0:
t_elapse = tns() / 1e9 - clear_nclicks_timestamp / 1e3
app.logger.info(f"CLEAR UPLOAD UI ACTION DETECTED, W/ `t_elapse` = {t_elapse}")
if t_elapse < 2:
return memory_reset
if append_nclicks > 0:
LOG_FILE = session_data["session_log_file"]
RUN_ID = session_data["RUN_ID"]
SESSION_OUTPUT_DIR = session_data["PATH_TO_SESSION_OUTPUT"]
app.logger.info(f"Append to Uploads in progress...")
app.logger.info(f" ...Adding the following files: \n{list_of_names}")
memory_reset = {f"{RUN_ID}-list_of_names": []}
uploads_cache = clientside_memory_cache or memory_reset
parsed_upload_children = [
html.Details(
[
parse_contents(c, n, d, SESSION_OUTPUT_DIR, session_log_file=LOG_FILE)
for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)
]
)
]
uploads_cache[f"{RUN_ID}-len_most_recent"] = len(parsed_upload_children)
uploads_cache[f"{RUN_ID}-list_of_names"].extend(list_of_names)
uploads_cache[f"{RUN_ID}-list_of_names"] = list(
set(uploads_cache[f"{RUN_ID}-list_of_names"])
)
uploads_cache[f"{RUN_ID}-len_of_contents"] = len(uploads_cache[f"{RUN_ID}-list_of_names"])
return uploads_cache
else:
return memory_reset
for n in range(1000):
@app.callback(
Output(f"cmds-dt-{n}", "style"),
[Input(f"show-cmds-{n}", "n_clicks")],
[State(f"cmds-dt-{n}", "style")],
)
def show_pipeline_commands(show_pl_cmds_n_clicks, style):
"""Enable dynamic reveal/hide functionality for showing
the technical-heavy exact command line commands called
during the pipeline execution of processes.
Args:
show_pl_cmds_n_clicks: int
style: <type>
Returns:
<type>
Raises:
PreventUpdate: Description
PreventUpdate
"""
if show_pl_cmds_n_clicks > 0:
if (show_pl_cmds_n_clicks % 2) == 1:
app.logger.info(f"show_pl_cmds clicked: {show_pl_cmds_n_clicks % 2}")
return {"display": "block"}
else:
return {"display": "none"}
else:
raise PreventUpdate
@app.callback(
Output("output-data-upload", "children"),
[
Input("upload-data", "contents"),
Input("upload-data", "filename"),
Input("upload-data", "last_modified"),
Input("initiate-pipeline", "n_clicks"),
Input("clear-pipeline", "n_clicks"),
Input("append-uploads", "n_clicks"),
Input("refresh-uploads", "n_clicks"),
Input("clear-uploads", "n_clicks"),
Input("memory", "data"),
Input("sign-on-submit", "n_clicks"),
Input("session", "data"),
],
[
State("workflow-id", "value"),
State("initiate-pipeline", "n_clicks_timestamp"),
State("clear-pipeline", "n_clicks_timestamp"),
State("sign-on-submit", "n_clicks_timestamp"),
State("refresh-uploads", "n_clicks_timestamp"),
State("clear-uploads", "n_clicks_timestamp"),
],
)
def update_output(
list_of_contents,
list_of_names,
list_of_dates,
initiate_pipeline_n_clicks,
clear_pipeline_n_clicks,
append_uploads_n_clicks,
refresh_uploads_n_clicks,
clear_uploads_n_clicks,
memory,
user_login_n_clicks,
session_data,
workflow,
initiate_pipeline_timestamp,
clear_pipeline_timestamp,
user_login_timestamp,
refresh_uploads_timestamp,
clear_uploads_timestamp,
):
"""Primary APP Pipeline function, as triggered by 'Initiate
[APP] Pipeline' UI button (located in the "Step 2 (2/2)"
section).
Parameters
----------
list_of_contents
<list of str>
Array containing user-uploaded ABI raw contents as
binary strings (thus requiring decoding)
list_of_names
<list of str>
Array containing user-uploaded ABI filenames
(does not include the full path for security reasons)
list_of_dates
<list of int>
Array containing user-uploaded ABI last modified timestamps
(integers as seconds since 1970)
initiate_pipeline_n_clicks
<int>
Total count of UI button clicks
clear_pipeline_n_clicks
<int>
Total count of UI button clicks
append_uploads_n_clicks
<int>
Total count of UI button clicks
refresh_uploads_n_clicks
<int>
Total count of UI button clicks
clear_uploads_n_clicks
<int>
Total count of UI button clicks
memory
Dash.dcc.Store(type='session')
user_login_n_clicks
<int>
Total count of UI button clicks
session_data
Dash.dcc.Store(type='session')
workflow
<type>
initiate_pipeline_timestamp
<type>
clear_pipeline_timestamp
<type>
user_login_timestamp
<type>
refresh_uploads_timestamp
<type>
clear_uploads_timestamp
<type>
"""
def show_list_of_names(USER, list_of_names):
"""Display the filenames for all successfully received
USER-uploaded ABI files.
Args:
USER: <str>
Active user
list_of_names: <list>
List of user-uploaded ABI filenames
Returns:
<html.Div([...])>
Reactive response to display after processing upload
"""
if not all([fn.endswith(tuple([".csv",".xlsx"])) for fn in list_of_names]):
return html.Div(
[
html.Br(),
html.Code(
f"⚠ UPLOAD ERROR: Not all of the {len(list_of_names)} files are CSV or Excel files !",
style={"color": "red"},
),
html.Br(),
html.Code(
f"⛔ | Please reset this upload & then perform a fresh upload of either .csv or .xlsx files."
),
]
)
return html.Div(
[
html.Br(),
html.Code(
f"✔ UPLOAD SUCCESSFUL (N={len(list_of_names)})", style={"color": "green"}
),
html.Br(),
html.Br(),
html.Details(
[
html.Summary(
html.H3(
f"File(s) received (click to expand)",
style={"textAlign": "left", "fontSize": "120%"},
)
),
html.Div(
[
html.Li(f"{'{:02d}'.format(i+1)})\t{abi}")
for (i, abi) in enumerate(sorted(list_of_names))
],
id="files-received",
style={
"textAlign": "left",
"fontSize": "60%",
"columnCount": "3",
"paddingBottom": "2%",
"fontFamily": "'Roboto Mono', monospace",
},
),
html.Hr(
style={
"borderTop": "1px solid",
"animation": "pact-gradient-text-flow 3s infinite linear",
"borderRadius": "5px",
"opacity": "0.67",
"width": "50%",
"marginLeft": "25%",
}
),
]
),
html.Br(),
html.Span(className="fader-line-short", style={"marginBottom": "20px"}),
],
style={"width": "80%", "marginLeft": "10%"},
)
not_signed_in_msg = html.Div(
[html.H6("Please log in to release the pipeline as ready for activation.")]
)
try:
if session_data: # ["user_logged_in"] == "True":
RUN_ID = session_data["RUN_ID"]
SESSION_OUTPUT_DIR = session_data["PATH_TO_SESSION_OUTPUT"]
LOG_FILE = session_data["session_log_file"]
USER = session_data["user_proper"]
UUID = session_data["UUID"]
if len(app.logger.handlers) < 1:
app.logger.info(
f"Number logger handlers = {len(app.logger.handlers)}->{logger.handlers}"
)
app.logger.info("Adding log FileHandler...")
fh = logging.FileHandler(LOG_FILE)
fh.setLevel(logging.INFO)
app.logger.addHandler(fh)
app.logger.info(
f"Number logger handlers = {len(app.logger.handlers)}->{logger.handlers}"
)
else:
return not_signed_in_msg
except KeyError as e:
app.logger.error(f"No user appears to be logged in (KeyError: {e})")
return not_signed_in_msg
### UPON USER FILE UPLOAD(S):
if list_of_contents is not None:
if initiate_pipeline_n_clicks >= 1:
init_t_elapse = tns() / 1e9 - initiate_pipeline_timestamp / 1e3
app.logger.info(f"init_t_elapse = {init_t_elapse}; ")
if init_t_elapse < 30:
if (
clear_pipeline_n_clicks > 0
and refresh_uploads_n_clicks <= clear_pipeline_n_clicks
):
if all(
clear_pipeline_timestamp > ts
for ts in [initiate_pipeline_timestamp, user_login_timestamp]
):
return [
html.H3(
f"Thanks, {USER}; the previous pipeline results have been cleared."
),
html.H4(f"Current analysis output folder: {RUN_ID}"),
html.H5(
html.Div(
[
html.Span(f"Launch a new analysis."),
html.Br(),
]
)
),
]
elif clear_pipeline_n_clicks > 0:
if clear_pipeline_timestamp > initiate_pipeline_timestamp:
if refresh_uploads_n_clicks > 0:
if refresh_uploads_timestamp > clear_pipeline_timestamp:
return show_list_of_names(USER, list_of_names)
return html.Div(
html.H5(
f"(Pipeline results [{RUN_ID}] CLEARED)", style={"color": "red"}
)
)
app.logger.info(
f"📟📶⌁⌁⌁📠Using the following as pipeline data input. \n{len(list_of_names)} USER UPLOADED FILE(S) : \n"
+ "\n 📊⇢🧬 ".join(
[
"{:>03d})\t{:>50s}".format(i + 1, abi)
for i, abi in enumerate(sorted(list_of_names))
]
)
)
app.logger.info(
f"INITIALIZING NEW PIPELINE LAUNCH:\n\n\t\t{SESSION_OUTPUT_DIR}"
)
start_time = tns()
children = []
parsed_upload_children = [
html.Details(
[
parse_contents(c, n, d, SESSION_OUTPUT_DIR, session_log_file=LOG_FILE)
for c, n, d in zip(list_of_contents, list_of_names, list_of_dates)
]
)
]
# Generate (single!) TCR alpha/beta chain pair combinations
# base pipeline reference files (e.g., agg'd fq, designated master
# reference 'genome', DataFrames, log, etc.)
try:
pipeline_output = ljoin(
[
r
for r in pipeline.run_pipeline(
RUN_ID,
SESSION_OUTPUT_DIR,
workflow=workflow,
session_log_file=LOG_FILE,
)
]
)
args = [(*(x), i + 1) for i, x in enumerate(pipeline_output)]
except Exception as e:
logs = []
report = None
with open(LOG_FILE, "r+") as log_file:
for line in log_file.readlines():
logs.append(line)
stderr = [
dcc.Textarea(
placeholder="(Main Sequence -- logger placeholder)",
value="\n".join(logs),
style={
"height": "400px",
"width": "50%",
"fontSize": "0.7rem",
"lineHeight": "0.9rem",
"fontFamily": "'Roboto Mono', monospace",
},
className="logger-text",
name="organization",
readOnly=True,
)
]
fatal_crash = "⚠ ALERT: ERROR IN MAIN PIPELINE SEQUENCE"
app.logger.error(f"{fatal_crash}: \n\n{e}")
log_exc(app.logger)
return html.Div(
[
html.H2(fatal_crash, style={"color": "red"}),
html.P(f"App runtime was: {gtt(start_time)}"),
html.Code(f"Primary error message for crash:\n{e}"),
html.H4("See [end of] AUDIT LOG (below) for failure reason."),
html.H5(f"WEB SERVER SYSTEM LOG:", style={"color": "red"}),
html.Div(stderr),
]
)
### # # # # # # # # # #### # # # # # # # # # ###
children.append(
html.Div(
[
html.Hr(),
html.Br(),
html.H4("All files analyzed in most recent upload:"),
]
)
)
""" ~ ◮ ~
S U M M A R Y
a n a l y s i s
~ ~ ~
~ ◮ ~
"""
if report:
summary_report = [
html.Div(
[
html.Br(),
html.H2(
"Pipeline Output Summary",
style={
"fontSize": "80%",
"letterSpacing": "1.33rem",
"fontFamily": "Cinzel",
"animation": "anim-text-flow-keys 120s infinite linear",
},
),
html.Hr(),
],
style={"width": "90%", "marginLeft": "5%"},
)
]
else:
summary_report = [html.Div([html.H4(f"No final output found.")])]
html_out = f"{SESSION_OUTPUT_DIR}{RUN_ID}_HTMLprops.tsv"
pd.DataFrame(
[str(c.to_plotly_json()) for c in children], columns=["DashHTMLDivComponents"]
).to_csv(html_out, encoding="utf-8", sep="\t")
app.logger.info("Processed & analzyed input files were:")
app.logger.debug(parsed_upload_children)
app.logger.info(",".join([str(type(x)) for x in parsed_upload_children]))
total_exec_time = gtt(start_time)
app.logger.info(
f"———COMPLETE——-\n\n \t ☆☆☆ Total EXECUTION TIME Required ☆☆☆\n\n \t\t = {total_exec_time} s \n\n"
)
show_exec_time = [
html.Div(
[
html.Hr(),
html.H3(
f"* ゚(>͂ ͡͡︒ ͜ ʖ ͡︒)>-。゚☆* :・゚.☆ * ・ "
),
html.H4(f"Total Execution Time Required = {total_exec_time} s"),
html.Hr(),
html.Br(),
]
)
]
if len(children) > 50:
full_report = [
html.Div(
[
html.H2(
f"NOTICE: Due to an unusually large number of results in this analysis (N={len(children)}), full report display has been automatically disabled."
)
]
)
]
else:
full_report = children
children = (
show_exec_time
+ TOC
+ summary_report
+ full_report
+ parsed_upload_children
+ [html.Div(html.Hr())]
)
app.logger.debug(",".join([str(type(x)) for x in children]))
app.logger.debug(f"Number of html.Div elements in final layout: {len(children)}")
return children
elif initiate_pipeline_n_clicks > 15:
return html.Div(
[
html.H4(
"⚠ | ALERT ! : Un𝒇ortunately, you have over-activated the pipeline submissions check system. Please re𝒇resh the page, re-log in, and re-upload the set o𝒇 ABI 𝒇iles you would like analyzed. 🛠⎆ "
),
html.H6("↺ Please Re𝒇resh the page. ↺"),
]
)
if clear_uploads_n_clicks > 0:
t_elapsed = tns() / 1e9 - clear_uploads_timestamp / 1e3
if t_elapsed < 2:
for tcr_dir in os.listdir(SESSION_OUTPUT_DIR):
grouped_clone_fqs = f"{SESSION_OUTPUT_DIR}{tcr_dir}"
if os.path.isdir(grouped_clone_fqs):
shutil.rmtree(grouped_clone_fqs)
return html.Div(
[
html.Code(f"UPLOADS CLEARED", style={"color": "red"}),
html.H5(
f'To continue, submit at least one new upload & click "✥ Append".'
),
]
)
if append_uploads_n_clicks > 0 or clear_uploads_n_clicks > 0:
if len(list_of_names) > 0 and len(memory.items()) > 0:
all_uploads = (
memory[f"{RUN_ID}-list_of_names"]
if len(memory[f"{RUN_ID}-list_of_names"]) > 0
else list_of_names
)
return show_list_of_names(USER, all_uploads)
elif len(memory.items()) == 0:
return html.Div(html.Code("NONE"))
else:
app.logger.info(
f"{USER} uploaded the following {len(list_of_names)} file(s):"
+ "\n\t ◇ 📄 "
+ "\n\t ◇ 📄 ".join(sorted(list_of_names))
+ ".\n"
)
return show_list_of_names(USER, list_of_names)
else:
return html.Div(
[html.Br(), html.H5(f"Logged in as: {USER}", style={"color": "rgb(32,92,188)"})]
)
@app.callback(
Output(f"output-file-list", "children"),
[Input(f"refresh-downloads-links", "n_clicks")],
[State(f"download-dropdown", "value"), State(f"session", "data")],
)
def update_link(refresh_n_clicks, value, session_data):
""""Download Output Files" dropdown components suite.
Allows user to choose from a list of file 'genres' (i.e.,
subsets of similar bioinformatics datafile types) - and
reacts by displaying all corresponding generated results
files for the current session analysis up-to-now, which
dual, and principally serve their purpose, as direct-to-
desktop functional download links.
Also capable of showing a full printout of the current cum-
ulative state of the session logfile in via an HTML
textarea Dash component.
Finally, users are also presented (via HTML button comp)
the option and ability to create a click-to-download link
for a dynamically generated zipped archive of all curr-
ently selected (& thus [reactively] displayed) results
files.
Args:
-----
refresh_n_clicks : int
value : str
session_data (dcc.Store( : Dash HTTP client-side memory caching,
type='session') . "Session" type (auto-cleared when browser
) . tab closes [but *not* on Refresh's]).
Returns:
--------
html.Div([html.Li's]) : An array of download-enabling Dash HTML
hyperlink components.
"""
if value:
if session_data:
selection = output_filetype_genres[value]
try:
session_output = session_data["PATH_TO_SESSION_OUTPUT"]
except KeyError as e:
app.logger.info(
f"User attempting to access files when not yet logged in!\nError:\n{e}"
)
return [html.Li(f"(Please log in first!)")]
if value == "LOGS":
files = sorted(get_output_files(selection, session_output))
logs = []
for f in files:
with open(f, "r+") as log_file:
for line in log_file.readlines():
logs.append(line)
if len(app.logger.handlers) < 1:
app.logger.addHandler(add_logfile(f))
app.logger.info("Re-added logfile (post-log printout)")
return [html.Li(file_download_link(filename)) for filename in files] + [
dcc.Textarea(
placeholder="(No logged activity yet.)",
value="\n".join(logs),
style={
"height": "550px",
"width": "60%",
"fontSize": "0.7rem",
"lineHeight": "0.9rem",
"fontFamily": "'Roboto Mono', monospace",
},
className="logger-text",
name="organization",
readOnly=True,
)
]
elif value == "REF":
return [
html.Li(
file_download_link(filename),
style={"fontFamily": "'Roboto Mono', monospace", "letterSpacing": "-1pt"},
)
for filename in sorted(get_output_files(selection))
]
files = get_output_files(selection, session_output)
if len(files) == 0:
return [html.Li(f"No output files available for selection: {value}.")]
else:
return [
html.Li(
file_download_link(filename),
style={"fontFamily": "'Roboto Mono', monospace", "letterSpacing": "-1pt"},
)
for filename in sorted(files)
]
else:
return [html.Li(f"(Please log in first!)")]
else:
return [html.Li(f"[Select an output filetype(s) category.]")]
@app.callback(
Output(f"download-all", "children"),
[Input(f"request-all-zipped", "n_clicks")],
[State(f"download-dropdown", "value"), State(f"session", "data")],
)
def zip_all_downloadables(getZipped_n_clicks, value, session_data):
"""Create a downloadable zip of USER selected set of output files.
Args:
getZipped_n_clicks: int
value: str
session_data: Dash.dcc.Store(type='session')
Returns:
html.Div([]): Dash HTML div component↦ itself an array of Dash HTML components
"""
if getZipped_n_clicks > 0 and any(session_data):
selection = output_filetype_genres[value]
session_output = session_data["PATH_TO_SESSION_OUTPUT"]
RUN_ID = session_data["RUN_ID"]
source = session_output if value != "REF" else PLASMIDS_ARCHIVE
files = get_output_files(selection, final_output_dir=source)
zipped = re.sub("['\ \(\)]", "", f"{session_output}{RUN_ID}_{clock()[-4:]}.zip")
for i, filename in enumerate(files):
fbn = f"{os.path.basename(filename)}"
app.logger.info(f"{i}: Adding file {filename} to new zipped archive: {fbn}...")
with zipfile.ZipFile(zipped, "a") as zipf:
zipf.write(filename, fbn)
return html.Div(
[
html.H4(f"Zip⇝⇶🗃⇨Download All:"),
html.H4([html.Li(file_download_link(zipped), className="zip-dl-link")]),
]
) |
import logging
from reconcile import queries
from reconcile.slack_base import slackapi_from_slack_workspace
from reconcile.utils.unleash import get_feature_toggles
from reconcile.utils.slack_api import SlackApi
from reconcile.utils.secret_reader import SecretReader
from reconcile.utils.state import State
QONTRACT_INTEGRATION = 'unleash-watcher'
def fetch_current_state(unleash_instance):
api_url = f"{unleash_instance["url"]}/api"
secret_reader = SecretReader(settings=queries.get_app_interface_settings())
admin_access_token = \
secret_reader.read(unleash_instance['token'])
return get_feature_toggles(api_url, admin_access_token)
def fetch_previous_state(state, instance_name):
return state.get_all(instance_name)
def format_message(url, key, event,
previous_state=None, current_state=None):
info = \
': {} -> {}'.format(previous_state,
current_state) \
if previous_state and current_state else ''
return '{} {} {}{}'.format(url, key, event, info)
def calculate_diff(current_state, previous_state):
diffs = []
for toggle, current_value in current_state.items():
# new toggles
if toggle not in previous_state:
diff = {
'event': 'created',
'toggle': toggle,
'to': current_value
}
diffs.append(diff)
# updated toggles
else:
previous_value = previous_state[toggle]
if current_value != previous_value:
diff = {
'event': 'updated',
'toggle': toggle,
'from': previous_value,
'to': current_value
}
diffs.append(diff)
# deleted toggles
for toggle in previous_state:
if toggle not in current_state:
diff = {
'event': 'deleted',
'toggle': toggle
}
diffs.append(diff)
return diffs
def init_slack_map(unleash_instance) -> dict[str, SlackApi]:
settings = queries.get_app_interface_settings()
return {slack_info['channel']:
slackapi_from_slack_workspace(slack_info, settings,
QONTRACT_INTEGRATION,
init_usergroups=False)
for slack_info in unleash_instance['notifications']['slack']}
def act(dry_run, state, unleash_instance, diffs):
if not dry_run and diffs:
slack_notifications = \
unleash_instance.get('notifications') \
and unleash_instance['notifications'].get('slack')
if not slack_notifications:
return
slack_map = init_slack_map(unleash_instance)
for diff in reversed(diffs):
event = diff['event']
toggle = diff['toggle']
msg = f"Feature toggle {toggle} {event}"
if event == 'updated':
msg += f": {diff["from"]} -> {diff["to"]}"
logging.info(msg)
if not dry_run:
for slack in slack_map.values():
slack.chat_post_message(msg)
key = f"{unleash_instance["name"]}/{toggle}"
if event == 'created':
state.add(key, diff['to'])
elif event == 'deleted':
state.rm(key)
elif event == 'updated':
state.add(key, diff['to'], force=True)
def run(dry_run):
unleash_instances = queries.get_unleash_instances()
accounts = queries.get_state_aws_accounts()
settings = queries.get_app_interface_settings()
state = State(
integration=QONTRACT_INTEGRATION,
accounts=accounts,
settings=settings
)
for unleash_instance in unleash_instances:
instance_name = unleash_instance['name']
current_state = fetch_current_state(unleash_instance)
if not current_state:
logging.warning(
'not acting on empty Unleash instances. ' +
'please create a feature toggle to get started.'
)
continue
previous_state = fetch_previous_state(state, instance_name)
diffs = calculate_diff(current_state, previous_state)
if diffs:
act(dry_run, state, unleash_instance, diffs)
| import logging
from reconcile import queries
from reconcile.slack_base import slackapi_from_slack_workspace
from reconcile.utils.unleash import get_feature_toggles
from reconcile.utils.slack_api import SlackApi
from reconcile.utils.secret_reader import SecretReader
from reconcile.utils.state import State
QONTRACT_INTEGRATION = 'unleash-watcher'
def fetch_current_state(unleash_instance):
api_url = f"{unleash_instance['url']}/api"
secret_reader = SecretReader(settings=queries.get_app_interface_settings())
admin_access_token = \
secret_reader.read(unleash_instance['token'])
return get_feature_toggles(api_url, admin_access_token)
def fetch_previous_state(state, instance_name):
return state.get_all(instance_name)
def format_message(url, key, event,
previous_state=None, current_state=None):
info = \
': {} -> {}'.format(previous_state,
current_state) \
if previous_state and current_state else ''
return '{} {} {}{}'.format(url, key, event, info)
def calculate_diff(current_state, previous_state):
diffs = []
for toggle, current_value in current_state.items():
# new toggles
if toggle not in previous_state:
diff = {
'event': 'created',
'toggle': toggle,
'to': current_value
}
diffs.append(diff)
# updated toggles
else:
previous_value = previous_state[toggle]
if current_value != previous_value:
diff = {
'event': 'updated',
'toggle': toggle,
'from': previous_value,
'to': current_value
}
diffs.append(diff)
# deleted toggles
for toggle in previous_state:
if toggle not in current_state:
diff = {
'event': 'deleted',
'toggle': toggle
}
diffs.append(diff)
return diffs
def init_slack_map(unleash_instance) -> dict[str, SlackApi]:
settings = queries.get_app_interface_settings()
return {slack_info['channel']:
slackapi_from_slack_workspace(slack_info, settings,
QONTRACT_INTEGRATION,
init_usergroups=False)
for slack_info in unleash_instance['notifications']['slack']}
def act(dry_run, state, unleash_instance, diffs):
if not dry_run and diffs:
slack_notifications = \
unleash_instance.get('notifications') \
and unleash_instance['notifications'].get('slack')
if not slack_notifications:
return
slack_map = init_slack_map(unleash_instance)
for diff in reversed(diffs):
event = diff['event']
toggle = diff['toggle']
msg = f"Feature toggle {toggle} {event}"
if event == 'updated':
msg += f": {diff['from']} -> {diff['to']}"
logging.info(msg)
if not dry_run:
for slack in slack_map.values():
slack.chat_post_message(msg)
key = f"{unleash_instance['name']}/{toggle}"
if event == 'created':
state.add(key, diff['to'])
elif event == 'deleted':
state.rm(key)
elif event == 'updated':
state.add(key, diff['to'], force=True)
def run(dry_run):
unleash_instances = queries.get_unleash_instances()
accounts = queries.get_state_aws_accounts()
settings = queries.get_app_interface_settings()
state = State(
integration=QONTRACT_INTEGRATION,
accounts=accounts,
settings=settings
)
for unleash_instance in unleash_instances:
instance_name = unleash_instance['name']
current_state = fetch_current_state(unleash_instance)
if not current_state:
logging.warning(
'not acting on empty Unleash instances. ' +
'please create a feature toggle to get started.'
)
continue
previous_state = fetch_previous_state(state, instance_name)
diffs = calculate_diff(current_state, previous_state)
if diffs:
act(dry_run, state, unleash_instance, diffs)
|
import asyncio
import functools
import inspect
import json
import math
import os
import random
import re
import sys
import threading
import time
import uuid
import warnings
from argparse import ArgumentParser, Namespace
from collections.abc import MutableMapping
from datetime import datetime
from itertools import islice
from types import SimpleNamespace
from typing import (
Callable,
Tuple,
Optional,
Iterator,
Any,
Union,
List,
Dict,
Set,
Sequence,
Iterable,
TypeVar,
TYPE_CHECKING,
)
from jina import __windows__
__all__ = [
'batch_iterator',
'parse_arg',
'random_port',
'random_identity',
'random_uuid',
'expand_env_var',
'colored',
'ArgNamespace',
'is_valid_local_config_source',
'cached_property',
'typename',
'get_public_ip',
'get_internal_ip',
'convert_tuple_to_list',
'run_async',
'deprecated_alias',
'countdown',
'CatchAllCleanupContextManager',
'download_mermaid_url',
'get_readable_size',
'get_or_reuse_loop',
'T',
]
if TYPE_CHECKING:
from docarray import DocumentArray
T = TypeVar('T')
def deprecated_alias(**aliases):
"""
Usage, kwargs with key as the deprecated arg name and value be a tuple, (new_name, deprecate_level).
With level 0 means warning, level 1 means exception.
For example:
.. highlight:: python
.. code-block:: python
@deprecated_alias(input_fn=('inputs', 0), buffer=('input_fn', 0), callback=('on_done', 1), output_fn=('on_done', 1))
:param aliases: maps aliases to new arguments
:return: wrapper
"""
from jina.excepts import NotSupportedError
def _rename_kwargs(func_name: str, kwargs, aliases):
"""
Raise warnings or exceptions for deprecated arguments.
:param func_name: Name of the function.
:param kwargs: key word arguments from the function which is decorated.
:param aliases: kwargs with key as the deprecated arg name and value be a tuple, (new_name, deprecate_level).
"""
for alias, new_arg in aliases.items():
if not isinstance(new_arg, tuple):
raise ValueError(
f'{new_arg} must be a tuple, with first element as the new name, '
f'second element as the deprecated level: 0 as warning, 1 as exception'
)
if alias in kwargs:
new_name, dep_level = new_arg
if new_name in kwargs:
raise NotSupportedError(
f'{func_name} received both {alias} and {new_name}'
)
if dep_level == 0:
warnings.warn(
f'`{alias}` is renamed to `{new_name}` in `{func_name}()`, the usage of `{alias}` is '
f'deprecated and will be removed in the next version.',
DeprecationWarning,
)
kwargs[new_name] = kwargs.pop(alias)
elif dep_level == 1:
raise NotSupportedError(f'{alias} has been renamed to `{new_name}`')
def deco(f):
"""
Set Decorator function.
:param f: function the decorator is used for
:return: wrapper
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
"""
Set wrapper function.
:param args: wrapper arguments
:param kwargs: wrapper key word arguments
:return: result of renamed function.
"""
_rename_kwargs(f.__name__, kwargs, aliases)
return f(*args, **kwargs)
return wrapper
return deco
def deprecated_method(new_function_name):
def deco(func):
def wrapper(*args, **kwargs):
warnings.warn(
f'`{func.__name__}` is renamed to `{new_function_name}`, the usage of `{func.__name__}` is '
f'deprecated and will be removed.',
DeprecationWarning,
)
return func(*args, **kwargs)
return wrapper
return deco
def get_readable_size(num_bytes: Union[int, float]) -> str:
"""
Transform the bytes into readable value with different units (e.g. 1 KB, 20 MB, 30.1 GB).
:param num_bytes: Number of bytes.
:return: Human readable string representation.
"""
num_bytes = int(num_bytes)
if num_bytes < 1024:
return f'{num_bytes} Bytes'
elif num_bytes < 1024 ** 2:
return f'{num_bytes / 1024:.1f} KB'
elif num_bytes < 1024 ** 3:
return f'{num_bytes / (1024 ** 2):.1f} MB'
else:
return f'{num_bytes / (1024 ** 3):.1f} GB'
def batch_iterator(
data: Iterable[Any],
batch_size: int,
axis: int = 0,
) -> Iterator[Any]:
"""
Get an iterator of batches of data.
For example:
.. highlight:: python
.. code-block:: python
for req in batch_iterator(data, batch_size, split_over_axis):
# Do something with batch
:param data: Data source.
:param batch_size: Size of one batch.
:param axis: Determine which axis to iterate for np.ndarray data.
:yield: data
:return: An Iterator of batch data.
"""
import numpy as np
if not batch_size or batch_size <= 0:
yield data
return
if isinstance(data, np.ndarray):
_l = data.shape[axis]
_d = data.ndim
sl = [slice(None)] * _d
if batch_size >= _l:
yield data
return
for start in range(0, _l, batch_size):
end = min(_l, start + batch_size)
sl[axis] = slice(start, end)
yield data[tuple(sl)]
elif isinstance(data, Sequence):
if batch_size >= len(data):
yield data
return
for _ in range(0, len(data), batch_size):
yield data[_ : _ + batch_size]
elif isinstance(data, Iterable):
# as iterator, there is no way to know the length of it
iterator = iter(data)
while True:
chunk = tuple(islice(iterator, batch_size))
if not chunk:
return
yield chunk
else:
raise TypeError(f'unsupported type: {type(data)}')
def parse_arg(v: str) -> Optional[Union[bool, int, str, list, float]]:
"""
Parse the arguments from string to `Union[bool, int, str, list, float]`.
:param v: The string of arguments
:return: The parsed arguments list.
"""
m = re.match(r'^[\'"](.*)[\'"]$', v)
if m:
return m.group(1)
if v.startswith('[') and v.endswith(']'):
# function args must be immutable tuples not list
tmp = v.replace('[', '').replace(']', '').strip().split(',')
if len(tmp) > 0:
return [parse_arg(vv.strip()) for vv in tmp]
else:
return []
try:
v = int(v) # parse int parameter
except ValueError:
try:
v = float(v) # parse float parameter
except ValueError:
if len(v) == 0:
# ignore it when the parameter is empty
v = None
elif v.lower() == 'true': # parse boolean parameter
v = True
elif v.lower() == 'false':
v = False
return v
def countdown(t: int, reason: str = 'I am blocking this thread') -> None:
"""
Display the countdown in console.
For example:
.. highlight:: python
.. code-block:: python
countdown(10, reason=colored('re-fetch access token', 'cyan', attrs=['bold', 'reverse']))
:param t: Countdown time.
:param reason: A string message of reason for this Countdown.
"""
try:
sys.stdout.write('\n')
sys.stdout.flush()
while t > 0:
t -= 1
msg = f'⏳ {colored('%3d' % t, 'yellow')}s left: {reason}'
sys.stdout.write(f'\r{msg}')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\n')
sys.stdout.flush()
except KeyboardInterrupt:
sys.stdout.write('no more patience? good bye!')
_random_names = (
(
'first',
'great',
'local',
'small',
'right',
'large',
'young',
'early',
'major',
'clear',
'black',
'whole',
'third',
'white',
'short',
'human',
'royal',
'wrong',
'legal',
'final',
'close',
'total',
'prime',
'happy',
'sorry',
'basic',
'aware',
'ready',
'green',
'heavy',
'extra',
'civil',
'chief',
'usual',
'front',
'fresh',
'joint',
'alone',
'rural',
'light',
'equal',
'quiet',
'quick',
'daily',
'urban',
'upper',
'moral',
'vital',
'empty',
'brief',
),
(
'world',
'house',
'place',
'group',
'party',
'money',
'point',
'state',
'night',
'water',
'thing',
'order',
'power',
'court',
'level',
'child',
'south',
'staff',
'woman',
'north',
'sense',
'death',
'range',
'table',
'trade',
'study',
'other',
'price',
'class',
'union',
'value',
'paper',
'right',
'voice',
'stage',
'light',
'march',
'board',
'month',
'music',
'field',
'award',
'issue',
'basis',
'front',
'heart',
'force',
'model',
'space',
'peter',
),
)
def random_name() -> str:
"""
Generate a random name from list.
:return: A Random name.
"""
return '_'.join(random.choice(_random_names[j]) for j in range(2))
assigned_ports = set()
unassigned_ports = []
DEFAULT_MIN_PORT = 49153
MAX_PORT = 65535
def reset_ports():
def _get_unassigned_ports():
# if we are running out of ports, lower default minimum port
if MAX_PORT - DEFAULT_MIN_PORT - len(assigned_ports) < 100:
min_port = int(os.environ.get('JINA_RANDOM_PORT_MIN', '16384'))
else:
min_port = int(
os.environ.get('JINA_RANDOM_PORT_MIN', str(DEFAULT_MIN_PORT))
)
max_port = int(os.environ.get('JINA_RANDOM_PORT_MAX', str(MAX_PORT)))
return set(range(min_port, max_port + 1)) - set(assigned_ports)
unassigned_ports.clear()
assigned_ports.clear()
unassigned_ports.extend(_get_unassigned_ports())
random.shuffle(unassigned_ports)
def random_port() -> Optional[int]:
"""
Get a random available port number.
:return: A random port.
"""
def _random_port():
import socket
def _check_bind(port):
with socket.socket() as s:
try:
s.bind(('', port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return port
except OSError:
return None
_port = None
if len(unassigned_ports) == 0:
reset_ports()
for idx, _port in enumerate(unassigned_ports):
if _check_bind(_port) is not None:
break
else:
raise OSError(
f'can not find an available port in {len(unassigned_ports)} unassigned ports, assigned already {len(assigned_ports)} ports'
)
int_port = int(_port)
unassigned_ports.pop(idx)
assigned_ports.add(int_port)
return int_port
try:
return _random_port()
except OSError:
assigned_ports.clear()
unassigned_ports.clear()
return _random_port()
def random_identity(use_uuid1: bool = False) -> str:
"""
Generate random UUID.
..note::
A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work
to sort numbers closer-together than those distributed randomly (UUID4) (see here).
A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not
explicitly stored.
:param use_uuid1: use UUID1 instead of UUID4. This is the default Document ID generator.
:return: A random UUID.
"""
return random_uuid(use_uuid1).hex
def random_uuid(use_uuid1: bool = False) -> uuid.UUID:
"""
Get a random UUID.
:param use_uuid1: Use UUID1 if True, else use UUID4.
:return: A random UUID.
"""
return uuid.uuid1() if use_uuid1 else uuid.uuid4()
def expand_env_var(v: str) -> Optional[Union[bool, int, str, list, float]]:
"""
Expand the environment variables.
:param v: String of environment variables.
:return: Parsed environment variables.
"""
if isinstance(v, str):
return parse_arg(os.path.expandvars(v))
else:
return v
def expand_dict(
d: Dict, expand_fn=expand_env_var, resolve_cycle_ref=True
) -> Dict[str, Any]:
"""
Expand variables from YAML file.
:param d: Target Dict.
:param expand_fn: Parsed environment variables.
:param resolve_cycle_ref: Defines if cyclic references should be resolved.
:return: Expanded variables.
"""
expand_map = SimpleNamespace()
pat = re.compile(r'{.+}|\$[a-zA-Z0-9_]*\b')
def _scan(sub_d: Union[Dict, List], p):
if isinstance(sub_d, dict):
for k, v in sub_d.items():
if isinstance(v, dict):
p.__dict__[k] = SimpleNamespace()
_scan(v, p.__dict__[k])
elif isinstance(v, list):
p.__dict__[k] = list()
_scan(v, p.__dict__[k])
else:
p.__dict__[k] = v
elif isinstance(sub_d, list):
for idx, v in enumerate(sub_d):
if isinstance(v, dict):
p.append(SimpleNamespace())
_scan(v, p[idx])
elif isinstance(v, list):
p.append(list())
_scan(v, p[idx])
else:
p.append(v)
def _replace(sub_d: Union[Dict, List], p):
if isinstance(sub_d, Dict):
for k, v in sub_d.items():
if isinstance(v, (dict, list)):
_replace(v, p.__dict__[k])
else:
if isinstance(v, str) and pat.findall(v):
sub_d[k] = _sub(v, p)
elif isinstance(sub_d, List):
for idx, v in enumerate(sub_d):
if isinstance(v, (dict, list)):
_replace(v, p[idx])
else:
if isinstance(v, str) and pat.findall(v):
sub_d[idx] = _sub(v, p)
def _sub(v, p):
if resolve_cycle_ref:
try:
v = v.format(root=expand_map, this=p)
except KeyError:
pass
return expand_fn(v)
_scan(d, expand_map)
_replace(d, expand_map)
return d
_ATTRIBUTES = {
'bold': 1,
'dark': 2,
'underline': 4,
'blink': 5,
'reverse': 7,
'concealed': 8,
}
_HIGHLIGHTS = {
'on_grey': 40,
'on_red': 41,
'on_green': 42,
'on_yellow': 43,
'on_blue': 44,
'on_magenta': 45,
'on_cyan': 46,
'on_white': 47,
}
_COLORS = {
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
}
_RESET = '\033[0m'
if __windows__:
os.system('color')
def colored(
text: str,
color: Optional[str] = None,
on_color: Optional[str] = None,
attrs: Optional[Union[str, list]] = None,
) -> str:
"""
Give the text with color.
:param text: The target text.
:param color: The color of text. Chosen from the following.
{
'grey': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37
}
:param on_color: The on_color of text. Chosen from the following.
{
'on_grey': 40,
'on_red': 41,
'on_green': 42,
'on_yellow': 43,
'on_blue': 44,
'on_magenta': 45,
'on_cyan': 46,
'on_white': 47
}
:param attrs: Attributes of color. Chosen from the following.
{
'bold': 1,
'dark': 2,
'underline': 4,
'blink': 5,
'reverse': 7,
'concealed': 8
}
:return: Colored text.
"""
if 'JINA_LOG_NO_COLOR' not in os.environ:
fmt_str = '\033[%dm%s'
if color:
text = fmt_str % (_COLORS[color], text)
if on_color:
text = fmt_str % (_HIGHLIGHTS[on_color], text)
if attrs:
if isinstance(attrs, str):
attrs = [attrs]
if isinstance(attrs, list):
for attr in attrs:
text = fmt_str % (_ATTRIBUTES[attr], text)
text += _RESET
return text
class ColorContext:
def __init__(self, color: str, bold: Optional[bool] = False):
self._color = color
self._bold = bold
def __enter__(self):
if self._bold:
fmt_str = '\033[1;%dm'
else:
fmt_str = '\033[0;%dm'
c = fmt_str % (_COLORS[self._color])
print(c, flush=True, end='')
return self
def __exit__(self, typ, value, traceback):
print(_RESET, flush=True, end='')
def warn_unknown_args(unknown_args: List[str]):
"""Creates warnings for all given arguments.
:param unknown_args: arguments that are possibly unknown to Jina
"""
from cli.lookup import _build_lookup_table
all_args = _build_lookup_table()[0]
has_migration_tip = False
real_unknown_args = []
warn_strs = []
for arg in unknown_args:
if arg.replace('--', '') not in all_args:
from jina.parsers.deprecated import get_deprecated_replacement
new_arg = get_deprecated_replacement(arg)
if new_arg:
if not has_migration_tip:
warn_strs.append('Migration tips:')
has_migration_tip = True
warn_strs.append(f'\t`{arg}` has been renamed to `{new_arg}`')
real_unknown_args.append(arg)
if real_unknown_args:
warn_strs = [f'ignored unknown argument: {real_unknown_args}.'] + warn_strs
warnings.warn(''.join(warn_strs))
class ArgNamespace:
"""Helper function for argparse.Namespace object."""
@staticmethod
def kwargs2list(kwargs: Dict) -> List[str]:
"""
Convert dict to an argparse-friendly list.
:param kwargs: dictionary of key-values to be converted
:return: argument list
"""
args = []
from jina.serve.executors import BaseExecutor
for k, v in kwargs.items():
k = k.replace('_', '-')
if v is not None:
if isinstance(v, bool):
if v:
args.append(f'--{k}')
elif isinstance(v, list): # for nargs
args.extend([f'--{k}', *(str(vv) for vv in v)])
elif isinstance(v, dict):
args.extend([f'--{k}', json.dumps(v)])
elif isinstance(v, type) and issubclass(v, BaseExecutor):
args.extend([f'--{k}', v.__name__])
else:
args.extend([f'--{k}', str(v)])
return args
@staticmethod
def kwargs2namespace(
kwargs: Dict[str, Union[str, int, bool]],
parser: ArgumentParser,
warn_unknown: bool = False,
fallback_parsers: Optional[List[ArgumentParser]] = None,
positional_args: Optional[Tuple[str, ...]] = None,
) -> Namespace:
"""
Convert dict to a namespace.
:param kwargs: dictionary of key-values to be converted
:param parser: the parser for building kwargs into a namespace
:param warn_unknown: True, if unknown arguments should be logged
:param fallback_parsers: a list of parsers to help resolving the args
:param positional_args: some parser requires positional arguments to be presented
:return: argument list
"""
args = ArgNamespace.kwargs2list(kwargs)
if positional_args:
args += positional_args
p_args, unknown_args = parser.parse_known_args(args)
unknown_args = list(filter(lambda x: x.startswith('--'), unknown_args))
if warn_unknown and unknown_args:
_leftovers = set(unknown_args)
if fallback_parsers:
for p in fallback_parsers:
_, _unk_args = p.parse_known_args(args)
_leftovers = _leftovers.intersection(_unk_args)
if not _leftovers:
# all args have been resolved
break
warn_unknown_args(_leftovers)
return p_args
@staticmethod
def get_non_defaults_args(
args: Namespace, parser: ArgumentParser, taboo: Optional[Set[str]] = None
) -> Dict:
"""
Get non-default args in a dict.
:param args: the namespace to parse
:param parser: the parser for referring the default values
:param taboo: exclude keys in the final result
:return: non defaults
"""
if taboo is None:
taboo = set()
non_defaults = {}
_defaults = vars(parser.parse_args([]))
for k, v in vars(args).items():
if k in _defaults and k not in taboo and _defaults[k] != v:
non_defaults[k] = v
return non_defaults
@staticmethod
def flatten_to_dict(
args: Union[Dict[str, 'Namespace'], 'Namespace']
) -> Dict[str, Any]:
"""Convert argparse.Namespace to dict to be uploaded via REST.
:param args: namespace or dict or namespace to dict.
:return: pod args
"""
if isinstance(args, Namespace):
return vars(args)
elif isinstance(args, dict):
pod_args = {}
for k, v in args.items():
if isinstance(v, Namespace):
pod_args[k] = vars(v)
elif isinstance(v, list):
pod_args[k] = [vars(_) for _ in v]
else:
pod_args[k] = v
return pod_args
def is_valid_local_config_source(path: str) -> bool:
# TODO: this function must be refactored before 1.0 (Han 12.22)
"""
Check if the path is valid.
:param path: Local file path.
:return: True if the path is valid else False.
"""
try:
from jina.jaml import parse_config_source
parse_config_source(path)
return True
except FileNotFoundError:
return False
def get_full_version() -> Optional[Tuple[Dict, Dict]]:
"""
Get the version of libraries used in Jina and environment variables.
:return: Version information and environment variables
"""
import os, grpc, google.protobuf, yaml, platform
from jina import (
__version__,
__proto_version__,
__docarray_version__,
__jina_env__,
__uptime__,
__unset_msg__,
)
from google.protobuf.internal import api_implementation
from grpc import _grpcio_metadata
from jina.logging.predefined import default_logger
from uuid import getnode
try:
info = {
'jina': __version__,
'docarray': __docarray_version__,
'jina-proto': __proto_version__,
'jina-vcs-tag': os.environ.get('JINA_VCS_VERSION', __unset_msg__),
'protobuf': google.protobuf.__version__,
'proto-backend': api_implementation._default_implementation_type,
'grpcio': getattr(grpc, '__version__', _grpcio_metadata.__version__),
'pyyaml': yaml.__version__,
'python': platform.python_version(),
'platform': platform.system(),
'platform-release': platform.release(),
'platform-version': platform.version(),
'architecture': platform.machine(),
'processor': platform.processor(),
'uid': getnode(),
'session-id': str(random_uuid(use_uuid1=True)),
'uptime': __uptime__,
'ci-vendor': get_ci_vendor() or __unset_msg__,
}
env_info = {k: os.getenv(k, __unset_msg__) for k in __jina_env__}
full_version = info, env_info
except Exception as e:
default_logger.error(str(e))
full_version = None
return full_version
def format_full_version_info(info: Dict, env_info: Dict) -> str:
"""
Format the version information.
:param info: Version information of Jina libraries.
:param env_info: The Jina environment variables.
:return: Formatted version information.
"""
version_info = '\n'.join(f'- {k:30s}{v}' for k, v in info.items())
env_info = '\n'.join(f'* {k:30s}{v}' for k, v in env_info.items())
return version_info + '\n' + env_info
def _update_policy():
if __windows__:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
elif 'JINA_DISABLE_UVLOOP' in os.environ:
return
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ModuleNotFoundError:
warnings.warn(
'Install `uvloop` via `pip install "jina[uvloop]"` for better performance.'
)
def get_or_reuse_loop():
"""
Get a new eventloop or reuse the current opened eventloop.
:return: A new eventloop or reuse the current opened eventloop.
"""
try:
loop = asyncio.get_running_loop()
if loop.is_closed():
raise RuntimeError
except RuntimeError:
_update_policy()
# no running event loop
# create a new loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def typename(obj):
"""
Get the typename of object.
:param obj: Target object.
:return: Typename of the obj.
"""
if not isinstance(obj, type):
obj = obj.__class__
try:
return f'{obj.__module__}.{obj.__name__}'
except AttributeError:
return str(obj)
class CatchAllCleanupContextManager:
"""
This context manager guarantees, that the :method:``__exit__`` of the
sub context is called, even when there is an Exception in the
:method:``__enter__``.
:param sub_context: The context, that should be taken care of.
"""
def __init__(self, sub_context):
self.sub_context = sub_context
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
self.sub_context.__exit__(exc_type, exc_val, exc_tb)
class cached_property:
"""The decorator to cache property of a class."""
def __init__(self, func):
"""
Create the :class:`cached_property`.
:param func: Cached function.
"""
self.func = func
def __get__(self, obj, cls):
cached_value = obj.__dict__.get(f'CACHED_{self.func.__name__}', None)
if cached_value is not None:
return cached_value
value = obj.__dict__[f'CACHED_{self.func.__name__}'] = self.func(obj)
return value
def __delete__(self, obj):
cached_value = obj.__dict__.get(f'CACHED_{self.func.__name__}', None)
if cached_value is not None:
if hasattr(cached_value, 'close'):
cached_value.close()
del obj.__dict__[f'CACHED_{self.func.__name__}']
class _cache_invalidate:
"""Class for cache invalidation, remove strategy.
:param func: func to wrap as a decorator.
:param attribute: String as the function name to invalidate cached
data. E.g. in :class:`cached_property` we cache data inside the class obj
with the `key`: `CACHED_{func.__name__}`, the func name in `cached_property`
is the name to invalidate.
"""
def __init__(self, func, attribute: str):
self.func = func
self.attribute = attribute
def __call__(self, *args, **kwargs):
obj = args[0]
cached_key = f'CACHED_{self.attribute}'
if cached_key in obj.__dict__:
del obj.__dict__[cached_key] # invalidate
self.func(*args, **kwargs)
def __get__(self, obj, cls):
from functools import partial
return partial(self.__call__, obj)
def cache_invalidate(attribute: str):
"""The cache invalidator decorator to wrap the method call.
Check the implementation in :class:`_cache_invalidate`.
:param attribute: The func name as was stored in the obj to invalidate.
:return: wrapped method.
"""
def _wrap(func):
return _cache_invalidate(func, attribute)
return _wrap
def get_now_timestamp():
"""
Get the datetime.
:return: The datetime in int format.
"""
now = datetime.now()
return int(datetime.timestamp(now))
def get_readable_time(*args, **kwargs):
"""
Get the datetime in human readable format (e.g. 115 days and 17 hours and 46 minutes and 40 seconds).
For example:
.. highlight:: python
.. code-block:: python
get_readable_time(seconds=1000)
:param args: arguments for datetime.timedelta
:param kwargs: key word arguments for datetime.timedelta
:return: Datetime in human readable format.
"""
import datetime
secs = float(datetime.timedelta(*args, **kwargs).total_seconds())
units = [('day', 86400), ('hour', 3600), ('minute', 60), ('second', 1)]
parts = []
for unit, mul in units:
if secs / mul >= 1 or mul == 1:
if mul > 1:
n = int(math.floor(secs / mul))
secs -= n * mul
else:
n = int(secs)
parts.append(f'{n} {unit}' + ('' if n == 1 else 's'))
return ' and '.join(parts)
def get_internal_ip():
"""
Return the private IP address of the gateway for connecting from other machine in the same network.
:return: Private IP address.
"""
import socket
ip = '127.0.0.1'
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except Exception:
pass
return ip
def get_public_ip(timeout: float = 0.3):
"""
Return the public IP address of the gateway for connecting from other machine in the public network.
:param timeout: the seconds to wait until return None.
:return: Public IP address.
.. warn::
Set `timeout` to a large number will block the Flow.
"""
import urllib.request
results = []
def _get_ip(url):
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=timeout) as fp:
_ip = fp.read().decode().strip()
results.append(_ip)
except:
pass # intentionally ignored, public ip is not showed
ip_server_list = [
'https://api.ipify.org',
'https://ident.me',
'https://checkip.amazonaws.com/',
]
threads = []
for idx, ip in enumerate(ip_server_list):
t = threading.Thread(target=_get_ip, args=(ip,))
threads.append(t)
t.start()
for t in threads:
t.join(timeout)
for r in results:
if r:
return r
def convert_tuple_to_list(d: Dict):
"""
Convert all the tuple type values from a dict to list.
:param d: Dict type of data.
"""
for k, v in d.items():
if isinstance(v, tuple):
d[k] = list(v)
elif isinstance(v, dict):
convert_tuple_to_list(v)
def is_jupyter() -> bool: # pragma: no cover
"""
Check if we're running in a Jupyter notebook, using magic command `get_ipython` that only available in Jupyter.
:return: True if run in a Jupyter notebook else False.
"""
try:
get_ipython # noqa: F821
except NameError:
return False
shell = get_ipython().__class__.__name__ # noqa: F821
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'Shell':
return True # Google colab
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
def iscoroutinefunction(func: Callable):
return inspect.iscoroutinefunction(func)
async def run_in_threadpool(func: Callable, executor=None, *args, **kwargs):
return await get_or_reuse_loop().run_in_executor(
executor, functools.partial(func, *args, **kwargs)
)
def run_async(func, *args, **kwargs):
"""Generalized asyncio.run for jupyter notebook.
When running inside jupyter, an eventloop is already exist, can't be stopped, can't be killed.
Directly calling asyncio.run will fail, as This function cannot be called when another asyncio event loop
is running in the same thread.
.. see_also:
https://stackoverflow.com/questions/55409641/asyncio-run-cannot-be-called-from-a-running-event-loop
call `run_async(my_function, any_event_loop=True, *args, **kwargs)` to enable run with any eventloop
:param func: function to run
:param args: parameters
:param kwargs: key-value parameters
:return: asyncio.run(func)
"""
any_event_loop = kwargs.pop('any_event_loop', False)
class _RunThread(threading.Thread):
"""Create a running thread when in Jupyter notebook."""
def run(self):
"""Run given `func` asynchronously."""
self.result = asyncio.run(func(*args, **kwargs))
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop and loop.is_running():
# eventloop already exist
# running inside Jupyter
if any_event_loop or is_jupyter():
thread = _RunThread()
thread.start()
thread.join()
try:
return thread.result
except AttributeError:
from jina.excepts import BadClient
raise BadClient(
'something wrong when running the eventloop, result can not be retrieved'
)
else:
raise RuntimeError(
'you have an eventloop running but not using Jupyter/ipython, '
'this may mean you are using Jina with other integration? if so, then you '
'may want to use Client/Flow(asyncio=True). If not, then '
'please report this issue here: https://github.com/jina-ai/jina'
)
else:
return get_or_reuse_loop().run_until_complete(func(*args, **kwargs))
def slugify(value):
"""
Normalize string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.
:param value: Original string.
:return: Processed string.
"""
s = str(value).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
def is_yaml_filepath(val) -> bool:
"""
Check if the file is YAML file.
:param val: Path of target file.
:return: True if the file is YAML else False.
"""
if __windows__:
r = r'.*.ya?ml$' # TODO: might not be exhaustive
else:
r = r'^[/\w\-\_\.]+.ya?ml$'
return re.match(r, val.strip()) is not None
def download_mermaid_url(mermaid_url, output) -> None:
"""
Download the jpg image from mermaid_url.
:param mermaid_url: The URL of the image.
:param output: A filename specifying the name of the image to be created, the suffix svg/jpg determines the file type of the output image.
"""
from urllib.request import Request, urlopen
try:
req = Request(mermaid_url, headers={'User-Agent': 'Mozilla/5.0'})
with open(output, 'wb') as fp:
fp.write(urlopen(req).read())
except:
from jina.logging.predefined import default_logger
default_logger.error(
'can not download image, please check your graph and the network connections'
)
def find_request_binding(target):
"""Find `@request` decorated methods in a class.
:param target: the target class to check
:return: a dictionary with key as request type and value as method name
"""
import ast, inspect
from jina import __default_endpoint__
res = {}
def visit_function_def(node):
for e in node.decorator_list:
req_name = ''
if isinstance(e, ast.Call) and e.func.id == 'requests':
req_name = e.keywords[0].value.s
elif isinstance(e, ast.Name) and e.id == 'requests':
req_name = __default_endpoint__
if req_name:
if req_name in res:
raise ValueError(
f'you already bind `{res[req_name]}` with `{req_name}` request'
)
else:
res[req_name] = node.name
V = ast.NodeVisitor()
V.visit_FunctionDef = visit_function_def
V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
return res
def dunder_get(_dict: Any, key: str) -> Any:
"""Returns value for a specified dunderkey
A "dunderkey" is just a fieldname that may or may not contain
double underscores (dunderscores!) for referencing nested keys in
a dict. eg::
>>> data = {'a': {'b': 1}}
>>> dunder_get(data, 'a__b')
1
key 'b' can be referrenced as 'a__b'
:param _dict : (dict, list, struct or object) which we want to index into
:param key : (str) that represents a first level or nested key in the dict
:return: (mixed) value corresponding to the key
"""
try:
part1, part2 = key.split('__', 1)
except ValueError:
part1, part2 = key, ''
try:
part1 = int(part1) # parse int parameter
except ValueError:
pass
from google.protobuf.struct_pb2 import ListValue
from google.protobuf.struct_pb2 import Struct
if isinstance(part1, int):
result = _dict[part1]
elif isinstance(_dict, (dict, Struct, MutableMapping)):
if part1 in _dict:
result = _dict[part1]
else:
result = None
elif isinstance(_dict, (Iterable, ListValue)):
result = _dict[part1]
else:
result = getattr(_dict, part1)
return dunder_get(result, part2) if part2 else result
if TYPE_CHECKING:
from fastapi import FastAPI
def extend_rest_interface(app: 'FastAPI') -> 'FastAPI':
"""Extend Jina built-in FastAPI instance with customized APIs, routing, etc.
:param app: the built-in FastAPI instance given by Jina
:return: the extended FastAPI instance
.. highlight:: python
.. code-block:: python
def extend_rest_interface(app: 'FastAPI'):
@app.get('/extension1')
async def root():
return {"message": "Hello World"}
return app
"""
return app
def get_ci_vendor() -> Optional[str]:
from jina import __resources_path__
with open(os.path.join(__resources_path__, 'ci-vendors.json')) as fp:
all_cis = json.load(fp)
for c in all_cis:
if isinstance(c['env'], str) and c['env'] in os.environ:
return c['constant']
elif isinstance(c['env'], dict):
for k, v in c['env'].items():
if os.environ.get(k, None) == v:
return c['constant']
elif isinstance(c['env'], list):
for k in c['env']:
if k in os.environ:
return c['constant']
def deprecate_by(new_fn):
def _f(*args, **kwargs):
import inspect
old_fn_name = inspect.stack()[1][4][0].strip().split("=")[0].strip()
warnings.warn(
f'`{old_fn_name}` is renamed to `{new_fn.__name__}` with the same usage, please use the latter instead. '
f'The old function will be removed soon.',
DeprecationWarning,
)
return new_fn(*args, **kwargs)
return _f
def get_request_header() -> Dict:
"""Return the header of request.
:return: request header
"""
metas, envs = get_full_version()
header = {
**{f'jinameta-{k}': str(v) for k, v in metas.items()},
**envs,
}
return header
| import asyncio
import functools
import inspect
import json
import math
import os
import random
import re
import sys
import threading
import time
import uuid
import warnings
from argparse import ArgumentParser, Namespace
from collections.abc import MutableMapping
from datetime import datetime
from itertools import islice
from types import SimpleNamespace
from typing import (
Callable,
Tuple,
Optional,
Iterator,
Any,
Union,
List,
Dict,
Set,
Sequence,
Iterable,
TypeVar,
TYPE_CHECKING,
)
from jina import __windows__
__all__ = [
'batch_iterator',
'parse_arg',
'random_port',
'random_identity',
'random_uuid',
'expand_env_var',
'colored',
'ArgNamespace',
'is_valid_local_config_source',
'cached_property',
'typename',
'get_public_ip',
'get_internal_ip',
'convert_tuple_to_list',
'run_async',
'deprecated_alias',
'countdown',
'CatchAllCleanupContextManager',
'download_mermaid_url',
'get_readable_size',
'get_or_reuse_loop',
'T',
]
if TYPE_CHECKING:
from docarray import DocumentArray
T = TypeVar('T')
def deprecated_alias(**aliases):
"""
Usage, kwargs with key as the deprecated arg name and value be a tuple, (new_name, deprecate_level).
With level 0 means warning, level 1 means exception.
For example:
.. highlight:: python
.. code-block:: python
@deprecated_alias(input_fn=('inputs', 0), buffer=('input_fn', 0), callback=('on_done', 1), output_fn=('on_done', 1))
:param aliases: maps aliases to new arguments
:return: wrapper
"""
from jina.excepts import NotSupportedError
def _rename_kwargs(func_name: str, kwargs, aliases):
"""
Raise warnings or exceptions for deprecated arguments.
:param func_name: Name of the function.
:param kwargs: key word arguments from the function which is decorated.
:param aliases: kwargs with key as the deprecated arg name and value be a tuple, (new_name, deprecate_level).
"""
for alias, new_arg in aliases.items():
if not isinstance(new_arg, tuple):
raise ValueError(
f'{new_arg} must be a tuple, with first element as the new name, '
f'second element as the deprecated level: 0 as warning, 1 as exception'
)
if alias in kwargs:
new_name, dep_level = new_arg
if new_name in kwargs:
raise NotSupportedError(
f'{func_name} received both {alias} and {new_name}'
)
if dep_level == 0:
warnings.warn(
f'`{alias}` is renamed to `{new_name}` in `{func_name}()`, the usage of `{alias}` is '
f'deprecated and will be removed in the next version.',
DeprecationWarning,
)
kwargs[new_name] = kwargs.pop(alias)
elif dep_level == 1:
raise NotSupportedError(f'{alias} has been renamed to `{new_name}`')
def deco(f):
"""
Set Decorator function.
:param f: function the decorator is used for
:return: wrapper
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
"""
Set wrapper function.
:param args: wrapper arguments
:param kwargs: wrapper key word arguments
:return: result of renamed function.
"""
_rename_kwargs(f.__name__, kwargs, aliases)
return f(*args, **kwargs)
return wrapper
return deco
def deprecated_method(new_function_name):
def deco(func):
def wrapper(*args, **kwargs):
warnings.warn(
f'`{func.__name__}` is renamed to `{new_function_name}`, the usage of `{func.__name__}` is '
f'deprecated and will be removed.',
DeprecationWarning,
)
return func(*args, **kwargs)
return wrapper
return deco
def get_readable_size(num_bytes: Union[int, float]) -> str:
"""
Transform the bytes into readable value with different units (e.g. 1 KB, 20 MB, 30.1 GB).
:param num_bytes: Number of bytes.
:return: Human readable string representation.
"""
num_bytes = int(num_bytes)
if num_bytes < 1024:
return f'{num_bytes} Bytes'
elif num_bytes < 1024 ** 2:
return f'{num_bytes / 1024:.1f} KB'
elif num_bytes < 1024 ** 3:
return f'{num_bytes / (1024 ** 2):.1f} MB'
else:
return f'{num_bytes / (1024 ** 3):.1f} GB'
def batch_iterator(
data: Iterable[Any],
batch_size: int,
axis: int = 0,
) -> Iterator[Any]:
"""
Get an iterator of batches of data.
For example:
.. highlight:: python
.. code-block:: python
for req in batch_iterator(data, batch_size, split_over_axis):
# Do something with batch
:param data: Data source.
:param batch_size: Size of one batch.
:param axis: Determine which axis to iterate for np.ndarray data.
:yield: data
:return: An Iterator of batch data.
"""
import numpy as np
if not batch_size or batch_size <= 0:
yield data
return
if isinstance(data, np.ndarray):
_l = data.shape[axis]
_d = data.ndim
sl = [slice(None)] * _d
if batch_size >= _l:
yield data
return
for start in range(0, _l, batch_size):
end = min(_l, start + batch_size)
sl[axis] = slice(start, end)
yield data[tuple(sl)]
elif isinstance(data, Sequence):
if batch_size >= len(data):
yield data
return
for _ in range(0, len(data), batch_size):
yield data[_ : _ + batch_size]
elif isinstance(data, Iterable):
# as iterator, there is no way to know the length of it
iterator = iter(data)
while True:
chunk = tuple(islice(iterator, batch_size))
if not chunk:
return
yield chunk
else:
raise TypeError(f'unsupported type: {type(data)}')
def parse_arg(v: str) -> Optional[Union[bool, int, str, list, float]]:
"""
Parse the arguments from string to `Union[bool, int, str, list, float]`.
:param v: The string of arguments
:return: The parsed arguments list.
"""
m = re.match(r'^[\'"](.*)[\'"]$', v)
if m:
return m.group(1)
if v.startswith('[') and v.endswith(']'):
# function args must be immutable tuples not list
tmp = v.replace('[', '').replace(']', '').strip().split(',')
if len(tmp) > 0:
return [parse_arg(vv.strip()) for vv in tmp]
else:
return []
try:
v = int(v) # parse int parameter
except ValueError:
try:
v = float(v) # parse float parameter
except ValueError:
if len(v) == 0:
# ignore it when the parameter is empty
v = None
elif v.lower() == 'true': # parse boolean parameter
v = True
elif v.lower() == 'false':
v = False
return v
def countdown(t: int, reason: str = 'I am blocking this thread') -> None:
"""
Display the countdown in console.
For example:
.. highlight:: python
.. code-block:: python
countdown(10, reason=colored('re-fetch access token', 'cyan', attrs=['bold', 'reverse']))
:param t: Countdown time.
:param reason: A string message of reason for this Countdown.
"""
try:
sys.stdout.write('\n')
sys.stdout.flush()
while t > 0:
t -= 1
msg = f'⏳ {colored("%3d" % t, "yellow")}s left: {reason}'
sys.stdout.write(f'\r{msg}')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\n')
sys.stdout.flush()
except KeyboardInterrupt:
sys.stdout.write('no more patience? good bye!')
_random_names = (
(
'first',
'great',
'local',
'small',
'right',
'large',
'young',
'early',
'major',
'clear',
'black',
'whole',
'third',
'white',
'short',
'human',
'royal',
'wrong',
'legal',
'final',
'close',
'total',
'prime',
'happy',
'sorry',
'basic',
'aware',
'ready',
'green',
'heavy',
'extra',
'civil',
'chief',
'usual',
'front',
'fresh',
'joint',
'alone',
'rural',
'light',
'equal',
'quiet',
'quick',
'daily',
'urban',
'upper',
'moral',
'vital',
'empty',
'brief',
),
(
'world',
'house',
'place',
'group',
'party',
'money',
'point',
'state',
'night',
'water',
'thing',
'order',
'power',
'court',
'level',
'child',
'south',
'staff',
'woman',
'north',
'sense',
'death',
'range',
'table',
'trade',
'study',
'other',
'price',
'class',
'union',
'value',
'paper',
'right',
'voice',
'stage',
'light',
'march',
'board',
'month',
'music',
'field',
'award',
'issue',
'basis',
'front',
'heart',
'force',
'model',
'space',
'peter',
),
)
def random_name() -> str:
"""
Generate a random name from list.
:return: A Random name.
"""
return '_'.join(random.choice(_random_names[j]) for j in range(2))
assigned_ports = set()
unassigned_ports = []
DEFAULT_MIN_PORT = 49153
MAX_PORT = 65535
def reset_ports():
def _get_unassigned_ports():
# if we are running out of ports, lower default minimum port
if MAX_PORT - DEFAULT_MIN_PORT - len(assigned_ports) < 100:
min_port = int(os.environ.get('JINA_RANDOM_PORT_MIN', '16384'))
else:
min_port = int(
os.environ.get('JINA_RANDOM_PORT_MIN', str(DEFAULT_MIN_PORT))
)
max_port = int(os.environ.get('JINA_RANDOM_PORT_MAX', str(MAX_PORT)))
return set(range(min_port, max_port + 1)) - set(assigned_ports)
unassigned_ports.clear()
assigned_ports.clear()
unassigned_ports.extend(_get_unassigned_ports())
random.shuffle(unassigned_ports)
def random_port() -> Optional[int]:
"""
Get a random available port number.
:return: A random port.
"""
def _random_port():
import socket
def _check_bind(port):
with socket.socket() as s:
try:
s.bind(('', port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return port
except OSError:
return None
_port = None
if len(unassigned_ports) == 0:
reset_ports()
for idx, _port in enumerate(unassigned_ports):
if _check_bind(_port) is not None:
break
else:
raise OSError(
f'can not find an available port in {len(unassigned_ports)} unassigned ports, assigned already {len(assigned_ports)} ports'
)
int_port = int(_port)
unassigned_ports.pop(idx)
assigned_ports.add(int_port)
return int_port
try:
return _random_port()
except OSError:
assigned_ports.clear()
unassigned_ports.clear()
return _random_port()
def random_identity(use_uuid1: bool = False) -> str:
"""
Generate random UUID.
..note::
A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work
to sort numbers closer-together than those distributed randomly (UUID4) (see here).
A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not
explicitly stored.
:param use_uuid1: use UUID1 instead of UUID4. This is the default Document ID generator.
:return: A random UUID.
"""
return random_uuid(use_uuid1).hex
def random_uuid(use_uuid1: bool = False) -> uuid.UUID:
"""
Get a random UUID.
:param use_uuid1: Use UUID1 if True, else use UUID4.
:return: A random UUID.
"""
return uuid.uuid1() if use_uuid1 else uuid.uuid4()
def expand_env_var(v: str) -> Optional[Union[bool, int, str, list, float]]:
"""
Expand the environment variables.
:param v: String of environment variables.
:return: Parsed environment variables.
"""
if isinstance(v, str):
return parse_arg(os.path.expandvars(v))
else:
return v
def expand_dict(
d: Dict, expand_fn=expand_env_var, resolve_cycle_ref=True
) -> Dict[str, Any]:
"""
Expand variables from YAML file.
:param d: Target Dict.
:param expand_fn: Parsed environment variables.
:param resolve_cycle_ref: Defines if cyclic references should be resolved.
:return: Expanded variables.
"""
expand_map = SimpleNamespace()
pat = re.compile(r'{.+}|\$[a-zA-Z0-9_]*\b')
def _scan(sub_d: Union[Dict, List], p):
if isinstance(sub_d, dict):
for k, v in sub_d.items():
if isinstance(v, dict):
p.__dict__[k] = SimpleNamespace()
_scan(v, p.__dict__[k])
elif isinstance(v, list):
p.__dict__[k] = list()
_scan(v, p.__dict__[k])
else:
p.__dict__[k] = v
elif isinstance(sub_d, list):
for idx, v in enumerate(sub_d):
if isinstance(v, dict):
p.append(SimpleNamespace())
_scan(v, p[idx])
elif isinstance(v, list):
p.append(list())
_scan(v, p[idx])
else:
p.append(v)
def _replace(sub_d: Union[Dict, List], p):
if isinstance(sub_d, Dict):
for k, v in sub_d.items():
if isinstance(v, (dict, list)):
_replace(v, p.__dict__[k])
else:
if isinstance(v, str) and pat.findall(v):
sub_d[k] = _sub(v, p)
elif isinstance(sub_d, List):
for idx, v in enumerate(sub_d):
if isinstance(v, (dict, list)):
_replace(v, p[idx])
else:
if isinstance(v, str) and pat.findall(v):
sub_d[idx] = _sub(v, p)
def _sub(v, p):
if resolve_cycle_ref:
try:
v = v.format(root=expand_map, this=p)
except KeyError:
pass
return expand_fn(v)
_scan(d, expand_map)
_replace(d, expand_map)
return d
_ATTRIBUTES = {
'bold': 1,
'dark': 2,
'underline': 4,
'blink': 5,
'reverse': 7,
'concealed': 8,
}
_HIGHLIGHTS = {
'on_grey': 40,
'on_red': 41,
'on_green': 42,
'on_yellow': 43,
'on_blue': 44,
'on_magenta': 45,
'on_cyan': 46,
'on_white': 47,
}
_COLORS = {
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
}
_RESET = '\033[0m'
if __windows__:
os.system('color')
def colored(
text: str,
color: Optional[str] = None,
on_color: Optional[str] = None,
attrs: Optional[Union[str, list]] = None,
) -> str:
"""
Give the text with color.
:param text: The target text.
:param color: The color of text. Chosen from the following.
{
'grey': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37
}
:param on_color: The on_color of text. Chosen from the following.
{
'on_grey': 40,
'on_red': 41,
'on_green': 42,
'on_yellow': 43,
'on_blue': 44,
'on_magenta': 45,
'on_cyan': 46,
'on_white': 47
}
:param attrs: Attributes of color. Chosen from the following.
{
'bold': 1,
'dark': 2,
'underline': 4,
'blink': 5,
'reverse': 7,
'concealed': 8
}
:return: Colored text.
"""
if 'JINA_LOG_NO_COLOR' not in os.environ:
fmt_str = '\033[%dm%s'
if color:
text = fmt_str % (_COLORS[color], text)
if on_color:
text = fmt_str % (_HIGHLIGHTS[on_color], text)
if attrs:
if isinstance(attrs, str):
attrs = [attrs]
if isinstance(attrs, list):
for attr in attrs:
text = fmt_str % (_ATTRIBUTES[attr], text)
text += _RESET
return text
class ColorContext:
def __init__(self, color: str, bold: Optional[bool] = False):
self._color = color
self._bold = bold
def __enter__(self):
if self._bold:
fmt_str = '\033[1;%dm'
else:
fmt_str = '\033[0;%dm'
c = fmt_str % (_COLORS[self._color])
print(c, flush=True, end='')
return self
def __exit__(self, typ, value, traceback):
print(_RESET, flush=True, end='')
def warn_unknown_args(unknown_args: List[str]):
"""Creates warnings for all given arguments.
:param unknown_args: arguments that are possibly unknown to Jina
"""
from cli.lookup import _build_lookup_table
all_args = _build_lookup_table()[0]
has_migration_tip = False
real_unknown_args = []
warn_strs = []
for arg in unknown_args:
if arg.replace('--', '') not in all_args:
from jina.parsers.deprecated import get_deprecated_replacement
new_arg = get_deprecated_replacement(arg)
if new_arg:
if not has_migration_tip:
warn_strs.append('Migration tips:')
has_migration_tip = True
warn_strs.append(f'\t`{arg}` has been renamed to `{new_arg}`')
real_unknown_args.append(arg)
if real_unknown_args:
warn_strs = [f'ignored unknown argument: {real_unknown_args}.'] + warn_strs
warnings.warn(''.join(warn_strs))
class ArgNamespace:
"""Helper function for argparse.Namespace object."""
@staticmethod
def kwargs2list(kwargs: Dict) -> List[str]:
"""
Convert dict to an argparse-friendly list.
:param kwargs: dictionary of key-values to be converted
:return: argument list
"""
args = []
from jina.serve.executors import BaseExecutor
for k, v in kwargs.items():
k = k.replace('_', '-')
if v is not None:
if isinstance(v, bool):
if v:
args.append(f'--{k}')
elif isinstance(v, list): # for nargs
args.extend([f'--{k}', *(str(vv) for vv in v)])
elif isinstance(v, dict):
args.extend([f'--{k}', json.dumps(v)])
elif isinstance(v, type) and issubclass(v, BaseExecutor):
args.extend([f'--{k}', v.__name__])
else:
args.extend([f'--{k}', str(v)])
return args
@staticmethod
def kwargs2namespace(
kwargs: Dict[str, Union[str, int, bool]],
parser: ArgumentParser,
warn_unknown: bool = False,
fallback_parsers: Optional[List[ArgumentParser]] = None,
positional_args: Optional[Tuple[str, ...]] = None,
) -> Namespace:
"""
Convert dict to a namespace.
:param kwargs: dictionary of key-values to be converted
:param parser: the parser for building kwargs into a namespace
:param warn_unknown: True, if unknown arguments should be logged
:param fallback_parsers: a list of parsers to help resolving the args
:param positional_args: some parser requires positional arguments to be presented
:return: argument list
"""
args = ArgNamespace.kwargs2list(kwargs)
if positional_args:
args += positional_args
p_args, unknown_args = parser.parse_known_args(args)
unknown_args = list(filter(lambda x: x.startswith('--'), unknown_args))
if warn_unknown and unknown_args:
_leftovers = set(unknown_args)
if fallback_parsers:
for p in fallback_parsers:
_, _unk_args = p.parse_known_args(args)
_leftovers = _leftovers.intersection(_unk_args)
if not _leftovers:
# all args have been resolved
break
warn_unknown_args(_leftovers)
return p_args
@staticmethod
def get_non_defaults_args(
args: Namespace, parser: ArgumentParser, taboo: Optional[Set[str]] = None
) -> Dict:
"""
Get non-default args in a dict.
:param args: the namespace to parse
:param parser: the parser for referring the default values
:param taboo: exclude keys in the final result
:return: non defaults
"""
if taboo is None:
taboo = set()
non_defaults = {}
_defaults = vars(parser.parse_args([]))
for k, v in vars(args).items():
if k in _defaults and k not in taboo and _defaults[k] != v:
non_defaults[k] = v
return non_defaults
@staticmethod
def flatten_to_dict(
args: Union[Dict[str, 'Namespace'], 'Namespace']
) -> Dict[str, Any]:
"""Convert argparse.Namespace to dict to be uploaded via REST.
:param args: namespace or dict or namespace to dict.
:return: pod args
"""
if isinstance(args, Namespace):
return vars(args)
elif isinstance(args, dict):
pod_args = {}
for k, v in args.items():
if isinstance(v, Namespace):
pod_args[k] = vars(v)
elif isinstance(v, list):
pod_args[k] = [vars(_) for _ in v]
else:
pod_args[k] = v
return pod_args
def is_valid_local_config_source(path: str) -> bool:
# TODO: this function must be refactored before 1.0 (Han 12.22)
"""
Check if the path is valid.
:param path: Local file path.
:return: True if the path is valid else False.
"""
try:
from jina.jaml import parse_config_source
parse_config_source(path)
return True
except FileNotFoundError:
return False
def get_full_version() -> Optional[Tuple[Dict, Dict]]:
"""
Get the version of libraries used in Jina and environment variables.
:return: Version information and environment variables
"""
import os, grpc, google.protobuf, yaml, platform
from jina import (
__version__,
__proto_version__,
__docarray_version__,
__jina_env__,
__uptime__,
__unset_msg__,
)
from google.protobuf.internal import api_implementation
from grpc import _grpcio_metadata
from jina.logging.predefined import default_logger
from uuid import getnode
try:
info = {
'jina': __version__,
'docarray': __docarray_version__,
'jina-proto': __proto_version__,
'jina-vcs-tag': os.environ.get('JINA_VCS_VERSION', __unset_msg__),
'protobuf': google.protobuf.__version__,
'proto-backend': api_implementation._default_implementation_type,
'grpcio': getattr(grpc, '__version__', _grpcio_metadata.__version__),
'pyyaml': yaml.__version__,
'python': platform.python_version(),
'platform': platform.system(),
'platform-release': platform.release(),
'platform-version': platform.version(),
'architecture': platform.machine(),
'processor': platform.processor(),
'uid': getnode(),
'session-id': str(random_uuid(use_uuid1=True)),
'uptime': __uptime__,
'ci-vendor': get_ci_vendor() or __unset_msg__,
}
env_info = {k: os.getenv(k, __unset_msg__) for k in __jina_env__}
full_version = info, env_info
except Exception as e:
default_logger.error(str(e))
full_version = None
return full_version
def format_full_version_info(info: Dict, env_info: Dict) -> str:
"""
Format the version information.
:param info: Version information of Jina libraries.
:param env_info: The Jina environment variables.
:return: Formatted version information.
"""
version_info = '\n'.join(f'- {k:30s}{v}' for k, v in info.items())
env_info = '\n'.join(f'* {k:30s}{v}' for k, v in env_info.items())
return version_info + '\n' + env_info
def _update_policy():
if __windows__:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
elif 'JINA_DISABLE_UVLOOP' in os.environ:
return
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ModuleNotFoundError:
warnings.warn(
'Install `uvloop` via `pip install "jina[uvloop]"` for better performance.'
)
def get_or_reuse_loop():
"""
Get a new eventloop or reuse the current opened eventloop.
:return: A new eventloop or reuse the current opened eventloop.
"""
try:
loop = asyncio.get_running_loop()
if loop.is_closed():
raise RuntimeError
except RuntimeError:
_update_policy()
# no running event loop
# create a new loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def typename(obj):
"""
Get the typename of object.
:param obj: Target object.
:return: Typename of the obj.
"""
if not isinstance(obj, type):
obj = obj.__class__
try:
return f'{obj.__module__}.{obj.__name__}'
except AttributeError:
return str(obj)
class CatchAllCleanupContextManager:
"""
This context manager guarantees, that the :method:``__exit__`` of the
sub context is called, even when there is an Exception in the
:method:``__enter__``.
:param sub_context: The context, that should be taken care of.
"""
def __init__(self, sub_context):
self.sub_context = sub_context
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
self.sub_context.__exit__(exc_type, exc_val, exc_tb)
class cached_property:
"""The decorator to cache property of a class."""
def __init__(self, func):
"""
Create the :class:`cached_property`.
:param func: Cached function.
"""
self.func = func
def __get__(self, obj, cls):
cached_value = obj.__dict__.get(f'CACHED_{self.func.__name__}', None)
if cached_value is not None:
return cached_value
value = obj.__dict__[f'CACHED_{self.func.__name__}'] = self.func(obj)
return value
def __delete__(self, obj):
cached_value = obj.__dict__.get(f'CACHED_{self.func.__name__}', None)
if cached_value is not None:
if hasattr(cached_value, 'close'):
cached_value.close()
del obj.__dict__[f'CACHED_{self.func.__name__}']
class _cache_invalidate:
"""Class for cache invalidation, remove strategy.
:param func: func to wrap as a decorator.
:param attribute: String as the function name to invalidate cached
data. E.g. in :class:`cached_property` we cache data inside the class obj
with the `key`: `CACHED_{func.__name__}`, the func name in `cached_property`
is the name to invalidate.
"""
def __init__(self, func, attribute: str):
self.func = func
self.attribute = attribute
def __call__(self, *args, **kwargs):
obj = args[0]
cached_key = f'CACHED_{self.attribute}'
if cached_key in obj.__dict__:
del obj.__dict__[cached_key] # invalidate
self.func(*args, **kwargs)
def __get__(self, obj, cls):
from functools import partial
return partial(self.__call__, obj)
def cache_invalidate(attribute: str):
"""The cache invalidator decorator to wrap the method call.
Check the implementation in :class:`_cache_invalidate`.
:param attribute: The func name as was stored in the obj to invalidate.
:return: wrapped method.
"""
def _wrap(func):
return _cache_invalidate(func, attribute)
return _wrap
def get_now_timestamp():
"""
Get the datetime.
:return: The datetime in int format.
"""
now = datetime.now()
return int(datetime.timestamp(now))
def get_readable_time(*args, **kwargs):
"""
Get the datetime in human readable format (e.g. 115 days and 17 hours and 46 minutes and 40 seconds).
For example:
.. highlight:: python
.. code-block:: python
get_readable_time(seconds=1000)
:param args: arguments for datetime.timedelta
:param kwargs: key word arguments for datetime.timedelta
:return: Datetime in human readable format.
"""
import datetime
secs = float(datetime.timedelta(*args, **kwargs).total_seconds())
units = [('day', 86400), ('hour', 3600), ('minute', 60), ('second', 1)]
parts = []
for unit, mul in units:
if secs / mul >= 1 or mul == 1:
if mul > 1:
n = int(math.floor(secs / mul))
secs -= n * mul
else:
n = int(secs)
parts.append(f'{n} {unit}' + ('' if n == 1 else 's'))
return ' and '.join(parts)
def get_internal_ip():
"""
Return the private IP address of the gateway for connecting from other machine in the same network.
:return: Private IP address.
"""
import socket
ip = '127.0.0.1'
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except Exception:
pass
return ip
def get_public_ip(timeout: float = 0.3):
"""
Return the public IP address of the gateway for connecting from other machine in the public network.
:param timeout: the seconds to wait until return None.
:return: Public IP address.
.. warn::
Set `timeout` to a large number will block the Flow.
"""
import urllib.request
results = []
def _get_ip(url):
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=timeout) as fp:
_ip = fp.read().decode().strip()
results.append(_ip)
except:
pass # intentionally ignored, public ip is not showed
ip_server_list = [
'https://api.ipify.org',
'https://ident.me',
'https://checkip.amazonaws.com/',
]
threads = []
for idx, ip in enumerate(ip_server_list):
t = threading.Thread(target=_get_ip, args=(ip,))
threads.append(t)
t.start()
for t in threads:
t.join(timeout)
for r in results:
if r:
return r
def convert_tuple_to_list(d: Dict):
"""
Convert all the tuple type values from a dict to list.
:param d: Dict type of data.
"""
for k, v in d.items():
if isinstance(v, tuple):
d[k] = list(v)
elif isinstance(v, dict):
convert_tuple_to_list(v)
def is_jupyter() -> bool: # pragma: no cover
"""
Check if we're running in a Jupyter notebook, using magic command `get_ipython` that only available in Jupyter.
:return: True if run in a Jupyter notebook else False.
"""
try:
get_ipython # noqa: F821
except NameError:
return False
shell = get_ipython().__class__.__name__ # noqa: F821
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'Shell':
return True # Google colab
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
def iscoroutinefunction(func: Callable):
return inspect.iscoroutinefunction(func)
async def run_in_threadpool(func: Callable, executor=None, *args, **kwargs):
return await get_or_reuse_loop().run_in_executor(
executor, functools.partial(func, *args, **kwargs)
)
def run_async(func, *args, **kwargs):
"""Generalized asyncio.run for jupyter notebook.
When running inside jupyter, an eventloop is already exist, can't be stopped, can't be killed.
Directly calling asyncio.run will fail, as This function cannot be called when another asyncio event loop
is running in the same thread.
.. see_also:
https://stackoverflow.com/questions/55409641/asyncio-run-cannot-be-called-from-a-running-event-loop
call `run_async(my_function, any_event_loop=True, *args, **kwargs)` to enable run with any eventloop
:param func: function to run
:param args: parameters
:param kwargs: key-value parameters
:return: asyncio.run(func)
"""
any_event_loop = kwargs.pop('any_event_loop', False)
class _RunThread(threading.Thread):
"""Create a running thread when in Jupyter notebook."""
def run(self):
"""Run given `func` asynchronously."""
self.result = asyncio.run(func(*args, **kwargs))
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop and loop.is_running():
# eventloop already exist
# running inside Jupyter
if any_event_loop or is_jupyter():
thread = _RunThread()
thread.start()
thread.join()
try:
return thread.result
except AttributeError:
from jina.excepts import BadClient
raise BadClient(
'something wrong when running the eventloop, result can not be retrieved'
)
else:
raise RuntimeError(
'you have an eventloop running but not using Jupyter/ipython, '
'this may mean you are using Jina with other integration? if so, then you '
'may want to use Client/Flow(asyncio=True). If not, then '
'please report this issue here: https://github.com/jina-ai/jina'
)
else:
return get_or_reuse_loop().run_until_complete(func(*args, **kwargs))
def slugify(value):
"""
Normalize string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.
:param value: Original string.
:return: Processed string.
"""
s = str(value).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
def is_yaml_filepath(val) -> bool:
"""
Check if the file is YAML file.
:param val: Path of target file.
:return: True if the file is YAML else False.
"""
if __windows__:
r = r'.*.ya?ml$' # TODO: might not be exhaustive
else:
r = r'^[/\w\-\_\.]+.ya?ml$'
return re.match(r, val.strip()) is not None
def download_mermaid_url(mermaid_url, output) -> None:
"""
Download the jpg image from mermaid_url.
:param mermaid_url: The URL of the image.
:param output: A filename specifying the name of the image to be created, the suffix svg/jpg determines the file type of the output image.
"""
from urllib.request import Request, urlopen
try:
req = Request(mermaid_url, headers={'User-Agent': 'Mozilla/5.0'})
with open(output, 'wb') as fp:
fp.write(urlopen(req).read())
except:
from jina.logging.predefined import default_logger
default_logger.error(
'can not download image, please check your graph and the network connections'
)
def find_request_binding(target):
"""Find `@request` decorated methods in a class.
:param target: the target class to check
:return: a dictionary with key as request type and value as method name
"""
import ast, inspect
from jina import __default_endpoint__
res = {}
def visit_function_def(node):
for e in node.decorator_list:
req_name = ''
if isinstance(e, ast.Call) and e.func.id == 'requests':
req_name = e.keywords[0].value.s
elif isinstance(e, ast.Name) and e.id == 'requests':
req_name = __default_endpoint__
if req_name:
if req_name in res:
raise ValueError(
f'you already bind `{res[req_name]}` with `{req_name}` request'
)
else:
res[req_name] = node.name
V = ast.NodeVisitor()
V.visit_FunctionDef = visit_function_def
V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
return res
def dunder_get(_dict: Any, key: str) -> Any:
"""Returns value for a specified dunderkey
A "dunderkey" is just a fieldname that may or may not contain
double underscores (dunderscores!) for referencing nested keys in
a dict. eg::
>>> data = {'a': {'b': 1}}
>>> dunder_get(data, 'a__b')
1
key 'b' can be referrenced as 'a__b'
:param _dict : (dict, list, struct or object) which we want to index into
:param key : (str) that represents a first level or nested key in the dict
:return: (mixed) value corresponding to the key
"""
try:
part1, part2 = key.split('__', 1)
except ValueError:
part1, part2 = key, ''
try:
part1 = int(part1) # parse int parameter
except ValueError:
pass
from google.protobuf.struct_pb2 import ListValue
from google.protobuf.struct_pb2 import Struct
if isinstance(part1, int):
result = _dict[part1]
elif isinstance(_dict, (dict, Struct, MutableMapping)):
if part1 in _dict:
result = _dict[part1]
else:
result = None
elif isinstance(_dict, (Iterable, ListValue)):
result = _dict[part1]
else:
result = getattr(_dict, part1)
return dunder_get(result, part2) if part2 else result
if TYPE_CHECKING:
from fastapi import FastAPI
def extend_rest_interface(app: 'FastAPI') -> 'FastAPI':
"""Extend Jina built-in FastAPI instance with customized APIs, routing, etc.
:param app: the built-in FastAPI instance given by Jina
:return: the extended FastAPI instance
.. highlight:: python
.. code-block:: python
def extend_rest_interface(app: 'FastAPI'):
@app.get('/extension1')
async def root():
return {"message": "Hello World"}
return app
"""
return app
def get_ci_vendor() -> Optional[str]:
from jina import __resources_path__
with open(os.path.join(__resources_path__, 'ci-vendors.json')) as fp:
all_cis = json.load(fp)
for c in all_cis:
if isinstance(c['env'], str) and c['env'] in os.environ:
return c['constant']
elif isinstance(c['env'], dict):
for k, v in c['env'].items():
if os.environ.get(k, None) == v:
return c['constant']
elif isinstance(c['env'], list):
for k in c['env']:
if k in os.environ:
return c['constant']
def deprecate_by(new_fn):
def _f(*args, **kwargs):
import inspect
old_fn_name = inspect.stack()[1][4][0].strip().split("=")[0].strip()
warnings.warn(
f'`{old_fn_name}` is renamed to `{new_fn.__name__}` with the same usage, please use the latter instead. '
f'The old function will be removed soon.',
DeprecationWarning,
)
return new_fn(*args, **kwargs)
return _f
def get_request_header() -> Dict:
"""Return the header of request.
:return: request header
"""
metas, envs = get_full_version()
header = {
**{f'jinameta-{k}': str(v) for k, v in metas.items()},
**envs,
}
return header
|
import logging
from selenium import webdriver
import json
from abprocess.authenticator import Authenticator
from abprocess.booking_course import BookingCourse
from datetime import datetime
from abprocess.logger import LogFileHandler
from abprocess.process import Process
import os
logger = logging.getLogger()
LogFileHandler(logger=logger).set_log_configuration()
logger.info('From main : Starting Process')
logger.info('Reading parameters...')
with open('parameters.json', 'r') as json_file:
parameters = json.load(json_file)
logger.info(
f"Starting process for date : {parameters["date"]}, hour : {parameters["hour"]}, player : {parameters["player_name"]} ")
start = datetime.now()
logger.info('Launching Chrome application')
# Starting a new browser session
path = os.getcwd()
browser = webdriver.Chrome(path+'/abprocess/chromedriver')
authenticator = Authenticator(browser=browser)
booking_course = BookingCourse(tennis_course_date=parameters['date'], tennis_course_hour=parameters['hour'],
tennis_course_name='A',
player_name=parameters['player_name'])
process = Process(authenticator=authenticator, booking_course=booking_course)
process.process()
end = datetime.now()
time = end - start
logger.info(f"process finished in {time.seconds} seconds")
| import logging
from selenium import webdriver
import json
from abprocess.authenticator import Authenticator
from abprocess.booking_course import BookingCourse
from datetime import datetime
from abprocess.logger import LogFileHandler
from abprocess.process import Process
import os
logger = logging.getLogger()
LogFileHandler(logger=logger).set_log_configuration()
logger.info('From main : Starting Process')
logger.info('Reading parameters...')
with open('parameters.json', 'r') as json_file:
parameters = json.load(json_file)
logger.info(
f"Starting process for date : {parameters['date']}, hour : {parameters['hour']}, player : {parameters['player_name']} ")
start = datetime.now()
logger.info('Launching Chrome application')
# Starting a new browser session
path = os.getcwd()
browser = webdriver.Chrome(path+'/abprocess/chromedriver')
authenticator = Authenticator(browser=browser)
booking_course = BookingCourse(tennis_course_date=parameters['date'], tennis_course_hour=parameters['hour'],
tennis_course_name='A',
player_name=parameters['player_name'])
process = Process(authenticator=authenticator, booking_course=booking_course)
process.process()
end = datetime.now()
time = end - start
logger.info(f"process finished in {time.seconds} seconds")
|
from os import system
from pip._internal.utils.misc import get_installed_distributions
from runas import runas
def check_dependencies():
"""Install all the dependencies listed within requirements.txt"""
with open('requirements.txt', 'r') as dependencies:
dependencies = set(dependencies.read().split())
# set of requirements.txt
dependencies = {i for i in dependencies}
installed_pkgs = get_installed_distributions()
# set of all installed pip packages
installed_pkgs = {str(i).split()[0].lower() for i in installed_pkgs}
# set of dependencies that must be installed
dependencies = dependencies.difference(installed_pkgs)
if dependencies:
print(f'Found {len(dependencies)} packages to install')
for dep in dependencies:
system(f'pip install {dep}')
print(f'{dep.ljust(30, ' ')} OK!')
return 'OK'
else:
print(f'All the dependencies satisfied')
return 'OK'
if __name__ == '__main__':
check_dependencies()
from gateway import main
runas(main)
| from os import system
from pip._internal.utils.misc import get_installed_distributions
from runas import runas
def check_dependencies():
"""Install all the dependencies listed within requirements.txt"""
with open('requirements.txt', 'r') as dependencies:
dependencies = set(dependencies.read().split())
# set of requirements.txt
dependencies = {i for i in dependencies}
installed_pkgs = get_installed_distributions()
# set of all installed pip packages
installed_pkgs = {str(i).split()[0].lower() for i in installed_pkgs}
# set of dependencies that must be installed
dependencies = dependencies.difference(installed_pkgs)
if dependencies:
print(f'Found {len(dependencies)} packages to install')
for dep in dependencies:
system(f'pip install {dep}')
print(f'{dep.ljust(30, " ")} OK!')
return 'OK'
else:
print(f'All the dependencies satisfied')
return 'OK'
if __name__ == '__main__':
check_dependencies()
from gateway import main
runas(main)
|
from httprunner.loader import load_folder_files, load_test_file
from httprunner.make import format_pytest_with_black, make_testcase, make_testsuite
from loguru import logger
from sentry_sdk import capture_message
from httprunner.compat import ensure_cli_args, ensure_testcase_v3_api
import os
import pytest
from httprunner import exceptions
pytest_files_run_set = set()
pytest_files_made_cache_mapping = {}
def __make(tests_path):
""" make testcase(s) with testcase/testsuite/folder absolute path
generated pytest file path will be cached in pytest_files_made_cache_mapping
Args:
tests_path: should be in absolute path
"""
logger.info(f"make path: {tests_path}")
test_files = []
if os.path.isdir(tests_path):
files_list = load_folder_files(tests_path)
test_files.extend(files_list)
elif os.path.isfile(tests_path):
test_files.append(tests_path)
else:
raise Exception
for test_file in test_files:
if test_file.lower().endswith("_test.py"):
pytest_files_run_set.add(test_file)
continue
try:
test_content = load_test_file(test_file)
except (exceptions.FileNotFound, exceptions.FileFormatError) as ex:
logger.warning(f"Invalid test file: {test_file}\n{type(ex).__name__}: {ex}")
continue
if not isinstance(test_content, dict):
logger.warning(
f"Invalid test file: {test_file}\n"
f"reason: test content not in dict format."
)
continue
# api in v2 format, convert to v3 testcase
if "request" in test_content and "name" in test_content:
test_content = ensure_testcase_v3_api(test_content)
if "config" not in test_content:
logger.warning(
f"Invalid testcase/testsuite file: {test_file}\n"
f"reason: missing config part."
)
continue
elif not isinstance(test_content["config"], dict):
logger.warning(
f"Invalid testcase/testsuite file: {test_file}\n"
f"reason: config should be dict type, got {test_content["config"]}"
)
continue
# ensure path absolute
test_content.setdefault("config", {})["path"] = test_file
# testcase
if "teststeps" in test_content:
try:
testcase_pytest_path = make_testcase(test_content)
pytest_files_run_set.add(testcase_pytest_path)
except exceptions.TestCaseFormatError as ex:
logger.warning(
f"Invalid testcase file: {test_file}\n{type(ex).__name__}: {ex}"
)
continue
# testsuite
elif "testcases" in test_content:
try:
make_testsuite(test_content)
except exceptions.TestSuiteFormatError as ex:
logger.warning(
f"Invalid testsuite file: {test_file}\n{type(ex).__name__}: {ex}"
)
continue
# invalid format
else:
logger.warning(
f"Invalid test file: {test_file}\n"
f"reason: file content is neither testcase nor testsuite"
)
def main_make(tests_paths: list) -> list:
if not tests_paths:
return []
for tests_path in tests_paths:
try:
__make(tests_path)
except Exception as e:
print(e)
# format pytest files
pytest_files_format_list = pytest_files_made_cache_mapping.keys()
format_pytest_with_black(*pytest_files_format_list)
return list(pytest_files_run_set)
def wrapper_test():
capture_message("start to run")
args = ["D:\\github_repo\\easy-api-tester\\tests\\test.yaml", '--html=D:\\github_repo\\easy-api-tester\\tests\\test_1_1.html']
extra_args = ensure_cli_args(args)
tests_path_list = []
extra_args_new = []
for item in extra_args:
if not os.path.exists(item):
# item is not file/folder path
extra_args_new.append(item)
else:
# item is file/folder path
tests_path_list.append(item)
testcase_path_list = main_make(tests_path_list)
if "--tb=short" not in extra_args_new:
extra_args_new.append("--tb=short")
extra_args_new.extend(testcase_path_list)
return pytest.main(extra_args_new)
def wrapper(yamls:list,htmlPath):
capture_message("start to run")
pytest_files_made_cache_mapping.clear()
yamls.append(htmlPath)
extra_args = ensure_cli_args(yamls)
tests_path_list = []
extra_args_new = []
for item in extra_args:
if not os.path.exists(item):
# item is not file/folder path
extra_args_new.append(item)
else:
# item is file/folder path
tests_path_list.append(item)
testcase_path_list = main_make(tests_path_list)
if "--tb=short" not in extra_args_new:
extra_args_new.append("--tb=short")
extra_args_new.extend(testcase_path_list)
return pytest.main(extra_args_new)
# if __name__ == "__main__":
# i = wrapper_test()
# print("结果是{}".format(i)) | from httprunner.loader import load_folder_files, load_test_file
from httprunner.make import format_pytest_with_black, make_testcase, make_testsuite
from loguru import logger
from sentry_sdk import capture_message
from httprunner.compat import ensure_cli_args, ensure_testcase_v3_api
import os
import pytest
from httprunner import exceptions
pytest_files_run_set = set()
pytest_files_made_cache_mapping = {}
def __make(tests_path):
""" make testcase(s) with testcase/testsuite/folder absolute path
generated pytest file path will be cached in pytest_files_made_cache_mapping
Args:
tests_path: should be in absolute path
"""
logger.info(f"make path: {tests_path}")
test_files = []
if os.path.isdir(tests_path):
files_list = load_folder_files(tests_path)
test_files.extend(files_list)
elif os.path.isfile(tests_path):
test_files.append(tests_path)
else:
raise Exception
for test_file in test_files:
if test_file.lower().endswith("_test.py"):
pytest_files_run_set.add(test_file)
continue
try:
test_content = load_test_file(test_file)
except (exceptions.FileNotFound, exceptions.FileFormatError) as ex:
logger.warning(f"Invalid test file: {test_file}\n{type(ex).__name__}: {ex}")
continue
if not isinstance(test_content, dict):
logger.warning(
f"Invalid test file: {test_file}\n"
f"reason: test content not in dict format."
)
continue
# api in v2 format, convert to v3 testcase
if "request" in test_content and "name" in test_content:
test_content = ensure_testcase_v3_api(test_content)
if "config" not in test_content:
logger.warning(
f"Invalid testcase/testsuite file: {test_file}\n"
f"reason: missing config part."
)
continue
elif not isinstance(test_content["config"], dict):
logger.warning(
f"Invalid testcase/testsuite file: {test_file}\n"
f"reason: config should be dict type, got {test_content['config']}"
)
continue
# ensure path absolute
test_content.setdefault("config", {})["path"] = test_file
# testcase
if "teststeps" in test_content:
try:
testcase_pytest_path = make_testcase(test_content)
pytest_files_run_set.add(testcase_pytest_path)
except exceptions.TestCaseFormatError as ex:
logger.warning(
f"Invalid testcase file: {test_file}\n{type(ex).__name__}: {ex}"
)
continue
# testsuite
elif "testcases" in test_content:
try:
make_testsuite(test_content)
except exceptions.TestSuiteFormatError as ex:
logger.warning(
f"Invalid testsuite file: {test_file}\n{type(ex).__name__}: {ex}"
)
continue
# invalid format
else:
logger.warning(
f"Invalid test file: {test_file}\n"
f"reason: file content is neither testcase nor testsuite"
)
def main_make(tests_paths: list) -> list:
if not tests_paths:
return []
for tests_path in tests_paths:
try:
__make(tests_path)
except Exception as e:
print(e)
# format pytest files
pytest_files_format_list = pytest_files_made_cache_mapping.keys()
format_pytest_with_black(*pytest_files_format_list)
return list(pytest_files_run_set)
def wrapper_test():
capture_message("start to run")
args = ["D:\\github_repo\\easy-api-tester\\tests\\test.yaml", '--html=D:\\github_repo\\easy-api-tester\\tests\\test_1_1.html']
extra_args = ensure_cli_args(args)
tests_path_list = []
extra_args_new = []
for item in extra_args:
if not os.path.exists(item):
# item is not file/folder path
extra_args_new.append(item)
else:
# item is file/folder path
tests_path_list.append(item)
testcase_path_list = main_make(tests_path_list)
if "--tb=short" not in extra_args_new:
extra_args_new.append("--tb=short")
extra_args_new.extend(testcase_path_list)
return pytest.main(extra_args_new)
def wrapper(yamls:list,htmlPath):
capture_message("start to run")
pytest_files_made_cache_mapping.clear()
yamls.append(htmlPath)
extra_args = ensure_cli_args(yamls)
tests_path_list = []
extra_args_new = []
for item in extra_args:
if not os.path.exists(item):
# item is not file/folder path
extra_args_new.append(item)
else:
# item is file/folder path
tests_path_list.append(item)
testcase_path_list = main_make(tests_path_list)
if "--tb=short" not in extra_args_new:
extra_args_new.append("--tb=short")
extra_args_new.extend(testcase_path_list)
return pytest.main(extra_args_new)
# if __name__ == "__main__":
# i = wrapper_test()
# print("结果是{}".format(i)) |
import numpy as np
import cv2
from numpy.core.fromnumeric import trace
import mediapipe_utils as mpu
from pathlib import Path
from FPS import FPS, now
import depthai as dai
import marshal
import sys
from string import Template
from math import sin, cos
SCRIPT_DIR = Path(__file__).resolve().parent
POSE_DETECTION_MODEL = str(SCRIPT_DIR / "models/pose_detection_sh4.blob")
LANDMARK_MODEL_FULL = str(SCRIPT_DIR / "models/pose_landmark_full_sh4.blob")
LANDMARK_MODEL_HEAVY = str(SCRIPT_DIR / "models/pose_landmark_heavy_sh4.blob")
LANDMARK_MODEL_LITE = str(SCRIPT_DIR / "models/pose_landmark_lite_sh4.blob")
DETECTION_POSTPROCESSING_MODEL = str(SCRIPT_DIR / "custom_models/DetectionBestCandidate_sh1.blob")
DIVIDE_BY_255_MODEL = str(SCRIPT_DIR / "custom_models/DivideBy255_sh1.blob")
TEMPLATE_MANAGER_SCRIPT = str(SCRIPT_DIR / "template_manager_script.py")
def to_planar(arr: np.ndarray, shape: tuple) -> np.ndarray:
return cv2.resize(arr, shape).transpose(2,0,1).flatten()
class BlazeposeDepthai:
"""
Blazepose body pose detector
Arguments:
- input_src: frame source,
- "rgb" or None: OAK* internal color camera,
- "rgb_laconic": same as "rgb" but without sending the frames to the host,
Note that as we are in Edge mode, input sources coming from the host like a image or a video is not supported
- pd_model: Blazepose detection model blob file (if None, takes the default value POSE_DETECTION_MODEL),
- pd_score: confidence score to determine whether a detection is reliable (a float between 0 and 1).
- pp_model: detection postprocessing model blob file (if None, takes the default value DETECTION_POSTPROCESSING_MODEL),,
- lm_model: Blazepose landmark model blob file
- None or "full": the default blob file LANDMARK_MODEL_FULL,
- "lite": the default blob file LANDMARK_MODEL_LITE,
- "831": the full model from previous version of mediapipe (0.8.3.1) LANDMARK_MODEL_FULL_0831,
- a path of a blob file.
- lm_score_thresh : confidence score to determine whether landmarks prediction is reliable (a float between 0 and 1).
- xyz: boolean, when True get the (x, y, z) coords of the reference point (center of the hips) (if the device supports depth measures).
- crop : boolean which indicates if square cropping is done or not
- smoothing: boolean which indicates if smoothing filtering is applied
- filter_window_size and filter_velocity_scale:
The filter keeps track (on a window of specified size) of
value changes over time, which as result gives velocity of how value
changes over time. With higher velocity it weights new values higher.
- higher filter_window_size adds to lag and to stability
- lower filter_velocity_scale adds to lag and to stability
- internal_fps : when using the internal color camera as input source, set its FPS to this value (calling setFps()).
- internal_frame_height : when using the internal color camera, set the frame height (calling setIspScale()).
The width is calculated accordingly to height and depends on value of 'crop'
- stats : boolean, when True, display some statistics when exiting.
- trace: boolean, when True print some debug messages
- force_detection: boolean, force person detection on every frame (never use landmarks from previous frame to determine ROI)
"""
def __init__(self, input_src="rgb",
pd_model=None,
pd_score_thresh=0.5,
pp_model=None,
lm_model=None,
lm_score_thresh=0.7,
xyz = False,
crop=False,
smoothing= True,
filter_window_size=5,
filter_velocity_scale=10,
stats=False,
internal_fps=None,
internal_frame_height=1080,
trace=False,
force_detection=False):
self.pd_model = pd_model if pd_model else POSE_DETECTION_MODEL
self.pp_model = pp_model if pd_model else DETECTION_POSTPROCESSING_MODEL
self.divide_by_255_model = DIVIDE_BY_255_MODEL
print(f"Pose detection blob file : {self.pd_model}")
self.rect_transf_scale = 1.25
if lm_model is None or lm_model == "full":
self.lm_model = LANDMARK_MODEL_FULL
elif lm_model == "lite":
self.lm_model = LANDMARK_MODEL_LITE
elif lm_model == "heavy":
self.lm_model = LANDMARK_MODEL_HEAVY
else:
self.lm_model = lm_model
print(f"Landmarks using blob file : {self.lm_model}")
self.pd_score_thresh = pd_score_thresh
self.lm_score_thresh = lm_score_thresh
self.smoothing = smoothing
self.crop = crop
self.internal_fps = internal_fps
self.stats = stats
self.presence_threshold = 0.5
self.visibility_threshold = 0.5
self.trace = trace
self.force_detection = force_detection
self.device = dai.Device()
self.xyz = False
if input_src == None or input_src == "rgb" or input_src == "rgb_laconic":
self.input_type = "rgb" # OAK* internal color camera
self.laconic = input_src == "rgb_laconic" # Camera frames are not sent to the host
if xyz:
# Check if the device supports stereo
cameras = self.device.getConnectedCameras()
if dai.CameraBoardSocket.LEFT in cameras and dai.CameraBoardSocket.RIGHT in cameras:
self.xyz = True
else:
print("Warning: depth unavailable on this device, 'xyz' argument is ignored")
if internal_fps is None:
if "full" in str(self.lm_model):
self.internal_fps = 18 if self.xyz else 20
elif "heavy" in str(lm_model):
self.internal_fps = 7 if self.xyz else 8
else: # "lite"
self.internal_fps = 22 if self.xyz else 26
else:
self.internal_fps = internal_fps
print(f"Internal camera FPS set to: {self.internal_fps}")
self.video_fps = self.internal_fps # Used when saving the output in a video file. Should be close to the real fps
if self.crop:
self.frame_size, self.scale_nd = mpu.find_isp_scale_params(internal_frame_height)
self.img_h = self.img_w = self.frame_size
self.pad_w = self.pad_h = 0
self.crop_w = (int(round(1920 * self.scale_nd[0] / self.scale_nd[1])) - self.img_w) // 2
else:
width, self.scale_nd = mpu.find_isp_scale_params(internal_frame_height * 1920 / 1080, is_height=False)
self.img_h = int(round(1080 * self.scale_nd[0] / self.scale_nd[1]))
self.img_w = int(round(1920 * self.scale_nd[0] / self.scale_nd[1]))
self.pad_h = (self.img_w - self.img_h) // 2
self.pad_w = 0
self.frame_size = self.img_w
self.crop_w = 0
print(f"Internal camera image size: {self.img_w} x {self.img_h} - pad_h: {self.pad_h}")
else:
print("Invalid input source:", input_src)
sys.exit()
self.nb_kps = 33
if self.smoothing:
self.filter_landmarks = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.05,
beta=80,
derivate_cutoff=1
)
# landmarks_aux corresponds to the 2 landmarks used to compute the ROI in next frame
self.filter_landmarks_aux = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.01,
beta=10,
derivate_cutoff=1
)
self.filter_landmarks_world = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.1,
beta=40,
derivate_cutoff=1,
disable_value_scaling=True
)
if self.xyz:
self.filter_xyz = mpu.LowPassFilter(alpha=0.25)
# Define and start pipeline
usb_speed = self.device.getUsbSpeed()
self.device.startPipeline(self.create_pipeline())
print(f"Pipeline started - USB speed: {str(usb_speed).split(".")[-1]}")
# Define data queues
if not self.laconic:
self.q_video = self.device.getOutputQueue(name="cam_out", maxSize=1, blocking=False)
self.q_manager_out = self.device.getOutputQueue(name="manager_out", maxSize=1, blocking=False)
# For debugging
# self.q_pre_pd_manip_out = self.device.getOutputQueue(name="pre_pd_manip_out", maxSize=1, blocking=False)
# self.q_pre_lm_manip_out = self.device.getOutputQueue(name="pre_lm_manip_out", maxSize=1, blocking=False)
self.fps = FPS()
self.nb_pd_inferences = 0
self.nb_lm_inferences = 0
self.nb_lm_inferences_after_landmarks_ROI = 0
self.nb_frames_no_body = 0
def create_pipeline(self):
print("Creating pipeline...")
# Start defining a pipeline
pipeline = dai.Pipeline()
pipeline.setOpenVINOVersion(dai.OpenVINO.Version.VERSION_2021_4)
self.pd_input_length = 224
self.lm_input_length = 256
# ColorCamera
print("Creating Color Camera...")
cam = pipeline.create(dai.node.ColorCamera)
cam.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)
cam.setInterleaved(False)
cam.setIspScale(self.scale_nd[0], self.scale_nd[1])
cam.setFps(self.internal_fps)
cam.setBoardSocket(dai.CameraBoardSocket.RGB)
if self.crop:
cam.setVideoSize(self.frame_size, self.frame_size)
cam.setPreviewSize(self.frame_size, self.frame_size)
else:
cam.setVideoSize(self.img_w, self.img_h)
cam.setPreviewSize(self.img_w, self.img_h)
if not self.laconic:
cam_out = pipeline.create(dai.node.XLinkOut)
cam_out.setStreamName("cam_out")
cam_out.input.setQueueSize(1)
cam_out.input.setBlocking(False)
cam.video.link(cam_out.input)
# Define manager script node
manager_script = pipeline.create(dai.node.Script)
manager_script.setScript(self.build_manager_script())
if self.xyz:
print("Creating MonoCameras, Stereo and SpatialLocationCalculator nodes...")
# For now, RGB needs fixed focus to properly align with depth.
# This value was used during calibration
cam.initialControl.setManualFocus(130)
mono_resolution = dai.MonoCameraProperties.SensorResolution.THE_400_P
left = pipeline.createMonoCamera()
left.setBoardSocket(dai.CameraBoardSocket.LEFT)
left.setResolution(mono_resolution)
left.setFps(self.internal_fps)
right = pipeline.createMonoCamera()
right.setBoardSocket(dai.CameraBoardSocket.RIGHT)
right.setResolution(mono_resolution)
right.setFps(self.internal_fps)
stereo = pipeline.createStereoDepth()
stereo.setConfidenceThreshold(230)
# LR-check is required for depth alignment
stereo.setLeftRightCheck(True)
stereo.setDepthAlign(dai.CameraBoardSocket.RGB)
stereo.setSubpixel(False) # subpixel True -> latency
# MEDIAN_OFF necessary in depthai 2.7.2.
# Otherwise : [critical] Fatal error. Please report to developers. Log: 'StereoSipp' '533'
# stereo.setMedianFilter(dai.StereoDepthProperties.MedianFilter.MEDIAN_OFF)
spatial_location_calculator = pipeline.createSpatialLocationCalculator()
spatial_location_calculator.setWaitForConfigInput(True)
spatial_location_calculator.inputDepth.setBlocking(False)
spatial_location_calculator.inputDepth.setQueueSize(1)
left.out.link(stereo.left)
right.out.link(stereo.right)
stereo.depth.link(spatial_location_calculator.inputDepth)
manager_script.outputs['spatial_location_config'].link(spatial_location_calculator.inputConfig)
spatial_location_calculator.out.link(manager_script.inputs['spatial_data'])
# Define pose detection pre processing (resize preview to (self.pd_input_length, self.pd_input_length))
print("Creating Pose Detection pre processing image manip...")
pre_pd_manip = pipeline.create(dai.node.ImageManip)
pre_pd_manip.setMaxOutputFrameSize(self.pd_input_length*self.pd_input_length*3)
pre_pd_manip.setWaitForConfigInput(True)
pre_pd_manip.inputImage.setQueueSize(1)
pre_pd_manip.inputImage.setBlocking(False)
cam.preview.link(pre_pd_manip.inputImage)
manager_script.outputs['pre_pd_manip_cfg'].link(pre_pd_manip.inputConfig)
# For debugging
# pre_pd_manip_out = pipeline.createXLinkOut()
# pre_pd_manip_out.setStreamName("pre_pd_manip_out")
# pre_pd_manip.out.link(pre_pd_manip_out.input)
# Define pose detection model
print("Creating Pose Detection Neural Network...")
pd_nn = pipeline.create(dai.node.NeuralNetwork)
pd_nn.setBlobPath(self.pd_model)
# Increase threads for detection
# pd_nn.setNumInferenceThreads(2)
pre_pd_manip.out.link(pd_nn.input)
# Define pose detection post processing "model"
print("Creating Pose Detection post processing Neural Network...")
post_pd_nn = pipeline.create(dai.node.NeuralNetwork)
post_pd_nn.setBlobPath(self.pp_model)
pd_nn.out.link(post_pd_nn.input)
post_pd_nn.out.link(manager_script.inputs['from_post_pd_nn'])
# Define link to send result to host
manager_out = pipeline.create(dai.node.XLinkOut)
manager_out.setStreamName("manager_out")
manager_script.outputs['host'].link(manager_out.input)
# Define landmark pre processing image manip
print("Creating Landmark pre processing image manip...")
pre_lm_manip = pipeline.create(dai.node.ImageManip)
pre_lm_manip.setMaxOutputFrameSize(self.lm_input_length*self.lm_input_length*3)
pre_lm_manip.setWaitForConfigInput(True)
pre_lm_manip.inputImage.setQueueSize(1)
pre_lm_manip.inputImage.setBlocking(False)
cam.preview.link(pre_lm_manip.inputImage)
# For debugging
# pre_lm_manip_out = pipeline.createXLinkOut()
# pre_lm_manip_out.setStreamName("pre_lm_manip_out")
# pre_lm_manip.out.link(pre_lm_manip_out.input)
manager_script.outputs['pre_lm_manip_cfg'].link(pre_lm_manip.inputConfig)
# Define normalization model between ImageManip and landmark model
# This is a temporary step. Could be removed when support of setFrameType(RGBF16F16F16p) in ImageManip node
print("Creating DiveideBy255 Neural Network...")
divide_nn = pipeline.create(dai.node.NeuralNetwork)
divide_nn.setBlobPath(self.divide_by_255_model)
pre_lm_manip.out.link(divide_nn.input)
# Define landmark model
print("Creating Landmark Neural Network...")
lm_nn = pipeline.create(dai.node.NeuralNetwork)
lm_nn.setBlobPath(self.lm_model)
# lm_nn.setNumInferenceThreads(1)
divide_nn.out.link(lm_nn.input)
lm_nn.out.link(manager_script.inputs['from_lm_nn'])
print("Pipeline created.")
return pipeline
def build_manager_script(self):
'''
The code of the scripting node 'manager_script' depends on :
- the NN model (full, lite, 831),
- the score threshold,
- the video frame shape
So we build this code from the content of the file template_manager_script.py which is a python template
'''
# Read the template
with open(TEMPLATE_MANAGER_SCRIPT, 'r') as file:
template = Template(file.read())
# Perform the substitution
code = template.substitute(
_TRACE = "node.warn" if self.trace else "#",
_pd_score_thresh = self.pd_score_thresh,
_lm_score_thresh = self.lm_score_thresh,
_force_detection = self.force_detection,
_pad_h = self.pad_h,
_img_h = self.img_h,
_frame_size = self.frame_size,
_crop_w = self.crop_w,
_rect_transf_scale = self.rect_transf_scale,
_IF_XYZ = "" if self.xyz else '"""',
_buffer_size = 2910 if self.xyz else 2863,
_visibility_threshold = self.visibility_threshold
)
# Remove comments and empty lines
import re
code = re.sub(r'"{3}.*?"{3}', '', code, flags=re.DOTALL)
code = re.sub(r'#.*', '', code)
code = re.sub('\n\s*\n', '\n', code)
# For debugging
if self.trace:
with open("tmp_code.py", "w") as file:
file.write(code)
return code
def is_present(self, body, lm_id):
return body.presence[lm_id] > self.presence_threshold
def lm_postprocess(self, body, lms, lms_world):
# lms : landmarks sent by Manager script node to host (list of 39*5 elements for full body or 31*5 for upper body)
lm_raw = np.array(lms).reshape(-1,5)
# Each keypoint have 5 information:
# - X,Y coordinates are local to the body of
# interest and range from [0.0, 255.0].
# - Z coordinate is measured in "image pixels" like
# the X and Y coordinates and represents the
# distance relative to the plane of the subject's
# hips, which is the origin of the Z axis. Negative
# values are between the hips and the camera;
# positive values are behind the hips. Z coordinate
# scale is similar with X, Y scales but has different
# nature as obtained not via human annotation, by
# fitting synthetic data (GHUM model) to the 2D
# annotation.
# - Visibility, after user-applied sigmoid denotes the
# probability that a keypoint is located within the
# frame and not occluded by another bigger body
# part or another object.
# - Presence, after user-applied sigmoid denotes the
# probability that a keypoint is located within the
# frame.
# Normalize x,y,z. Scaling in z = scaling in x = 1/self.lm_input_length
lm_raw[:,:3] /= self.lm_input_length
# Apply sigmoid on visibility and presence (if used later)
body.visibility = 1 / (1 + np.exp(-lm_raw[:,3]))
body.presence = 1 / (1 + np.exp(-lm_raw[:,4]))
# body.norm_landmarks contains the normalized ([0:1]) 3D coordinates of landmarks in the square rotated body bounding box
body.norm_landmarks = lm_raw[:,:3]
# Now calculate body.landmarks = the landmarks in the image coordinate system (in pixel) (body.landmarks)
src = np.array([(0, 0), (1, 0), (1, 1)], dtype=np.float32)
dst = np.array([ (x, y) for x,y in body.rect_points[1:]], dtype=np.float32) # body.rect_points[0] is left bottom point and points going clockwise!
mat = cv2.getAffineTransform(src, dst)
lm_xy = np.expand_dims(body.norm_landmarks[:self.nb_kps,:2], axis=0)
lm_xy = np.squeeze(cv2.transform(lm_xy, mat))
# A segment of length 1 in the coordinates system of body bounding box takes body.rect_w_a pixels in the
# original image. Then we arbitrarily divide by 4 for a more realistic appearance.
lm_z = body.norm_landmarks[:self.nb_kps,2:3] * body.rect_w_a / 4
lm_xyz = np.hstack((lm_xy, lm_z))
# World landmarks are predicted in meters rather than in pixels of the image
# and have origin in the middle of the hips rather than in the corner of the
# pose image (cropped with given rectangle). Thus only rotation (but not scale
# and translation) is applied to the landmarks to transform them back to
# original coordinates.
body.landmarks_world = np.array(lms_world).reshape(-1,3)
sin_rot = sin(body.rotation)
cos_rot = cos(body.rotation)
rot_m = np.array([[cos_rot, sin_rot], [-sin_rot, cos_rot]])
body.landmarks_world[:,:2] = np.dot(body.landmarks_world[:,:2], rot_m)
if self.smoothing:
timestamp = now()
object_scale = body.rect_w_a
lm_xyz[:self.nb_kps] = self.filter_landmarks.apply(lm_xyz[:self.nb_kps], timestamp, object_scale)
lm_xyz[self.nb_kps:] = self.filter_landmarks_aux.apply(lm_xyz[self.nb_kps:], timestamp, object_scale)
body.landmarks_world = self.filter_landmarks_world.apply(body.landmarks_world, timestamp)
body.landmarks = lm_xyz.astype(np.int)
# If we added padding to make the image square, we need to remove this padding from landmark coordinates and from rect_points
if self.pad_h > 0:
body.landmarks[:,1] -= self.pad_h
for i in range(len(body.rect_points)):
body.rect_points[i][1] -= self.pad_h
# if self.pad_w > 0:
# body.landmarks[:,0] -= self.pad_w
# for i in range(len(body.rect_points)):
# body.rect_points[i][0] -= self.pad_w
def next_frame(self):
self.fps.update()
if self.laconic:
video_frame = np.zeros((self.frame_size, self.frame_size, 3), dtype=np.uint8)
else:
in_video = self.q_video.get()
video_frame = in_video.getCvFrame()
# For debugging
# pre_pd_manip = self.q_pre_pd_manip_out.tryGet()
# if pre_pd_manip:
# pre_pd_manip = pre_pd_manip.getCvFrame()
# cv2.imshow("pre_pd_manip", pre_pd_manip)
# pre_lm_manip = self.q_pre_lm_manip_out.tryGet()
# if pre_lm_manip:
# pre_lm_manip = pre_lm_manip.getCvFrame()
# cv2.imshow("pre_lm_manip", pre_lm_manip)
# Get result from device
res = marshal.loads(self.q_manager_out.get().getData())
if res["type"] != 0 and res["lm_score"] > self.lm_score_thresh:
body = mpu.Body()
body.rect_x_center_a = res["rect_center_x"] * self.frame_size
body.rect_y_center_a = res["rect_center_y"] * self.frame_size
body.rect_w_a = body.rect_h_a = res["rect_size"] * self.frame_size
body.rotation = res["rotation"]
body.rect_points = mpu.rotated_rect_to_points(body.rect_x_center_a, body.rect_y_center_a, body.rect_w_a, body.rect_h_a, body.rotation)
body.lm_score = res["lm_score"]
self.lm_postprocess(body, res['lms'], res['lms_world'])
if self.xyz:
if res['xyz_ref'] == 0:
body.xyz_ref = None
else:
if res['xyz_ref'] == 1:
body.xyz_ref = "mid_hips"
else: # res['xyz_ref'] == 2:
body.xyz_ref = "mid_shoulders"
body.xyz = np.array(res["xyz"])
if self.smoothing:
body.xyz = self.filter_xyz.apply(body.xyz)
body.xyz_zone = np.array(res["xyz_zone"])
body.xyz_ref_coords_pixel = np.mean(body.xyz_zone.reshape((2,2)), axis=0)
else:
body = None
if self.smoothing:
self.filter_landmarks.reset()
self.filter_landmarks_aux.reset()
self.filter_landmarks_world.reset()
if self.xyz: self.filter_xyz.reset()
# Statistics
if self.stats:
if res["type"] == 0:
self.nb_pd_inferences += 1
self.nb_frames_no_body += 1
else:
self.nb_lm_inferences += 1
if res["type"] == 1:
self.nb_pd_inferences += 1
else: # res["type"] == 2
self.nb_lm_inferences_after_landmarks_ROI += 1
if res["lm_score"] < self.lm_score_thresh: self.nb_frames_no_body += 1
return video_frame, body
def exit(self):
self.device.close()
# Print some stats
if self.stats:
print(f"FPS : {self.fps.get_global():.1f} f/s (# frames = {self.fps.nbf})")
print(f"# frames without body : {self.nb_frames_no_body}")
print(f"# pose detection inferences : {self.nb_pd_inferences}")
print(f"# landmark inferences : {self.nb_lm_inferences} - # after pose detection: {self.nb_lm_inferences - self.nb_lm_inferences_after_landmarks_ROI} - # after landmarks ROI prediction: {self.nb_lm_inferences_after_landmarks_ROI}")
| import numpy as np
import cv2
from numpy.core.fromnumeric import trace
import mediapipe_utils as mpu
from pathlib import Path
from FPS import FPS, now
import depthai as dai
import marshal
import sys
from string import Template
from math import sin, cos
SCRIPT_DIR = Path(__file__).resolve().parent
POSE_DETECTION_MODEL = str(SCRIPT_DIR / "models/pose_detection_sh4.blob")
LANDMARK_MODEL_FULL = str(SCRIPT_DIR / "models/pose_landmark_full_sh4.blob")
LANDMARK_MODEL_HEAVY = str(SCRIPT_DIR / "models/pose_landmark_heavy_sh4.blob")
LANDMARK_MODEL_LITE = str(SCRIPT_DIR / "models/pose_landmark_lite_sh4.blob")
DETECTION_POSTPROCESSING_MODEL = str(SCRIPT_DIR / "custom_models/DetectionBestCandidate_sh1.blob")
DIVIDE_BY_255_MODEL = str(SCRIPT_DIR / "custom_models/DivideBy255_sh1.blob")
TEMPLATE_MANAGER_SCRIPT = str(SCRIPT_DIR / "template_manager_script.py")
def to_planar(arr: np.ndarray, shape: tuple) -> np.ndarray:
return cv2.resize(arr, shape).transpose(2,0,1).flatten()
class BlazeposeDepthai:
"""
Blazepose body pose detector
Arguments:
- input_src: frame source,
- "rgb" or None: OAK* internal color camera,
- "rgb_laconic": same as "rgb" but without sending the frames to the host,
Note that as we are in Edge mode, input sources coming from the host like a image or a video is not supported
- pd_model: Blazepose detection model blob file (if None, takes the default value POSE_DETECTION_MODEL),
- pd_score: confidence score to determine whether a detection is reliable (a float between 0 and 1).
- pp_model: detection postprocessing model blob file (if None, takes the default value DETECTION_POSTPROCESSING_MODEL),,
- lm_model: Blazepose landmark model blob file
- None or "full": the default blob file LANDMARK_MODEL_FULL,
- "lite": the default blob file LANDMARK_MODEL_LITE,
- "831": the full model from previous version of mediapipe (0.8.3.1) LANDMARK_MODEL_FULL_0831,
- a path of a blob file.
- lm_score_thresh : confidence score to determine whether landmarks prediction is reliable (a float between 0 and 1).
- xyz: boolean, when True get the (x, y, z) coords of the reference point (center of the hips) (if the device supports depth measures).
- crop : boolean which indicates if square cropping is done or not
- smoothing: boolean which indicates if smoothing filtering is applied
- filter_window_size and filter_velocity_scale:
The filter keeps track (on a window of specified size) of
value changes over time, which as result gives velocity of how value
changes over time. With higher velocity it weights new values higher.
- higher filter_window_size adds to lag and to stability
- lower filter_velocity_scale adds to lag and to stability
- internal_fps : when using the internal color camera as input source, set its FPS to this value (calling setFps()).
- internal_frame_height : when using the internal color camera, set the frame height (calling setIspScale()).
The width is calculated accordingly to height and depends on value of 'crop'
- stats : boolean, when True, display some statistics when exiting.
- trace: boolean, when True print some debug messages
- force_detection: boolean, force person detection on every frame (never use landmarks from previous frame to determine ROI)
"""
def __init__(self, input_src="rgb",
pd_model=None,
pd_score_thresh=0.5,
pp_model=None,
lm_model=None,
lm_score_thresh=0.7,
xyz = False,
crop=False,
smoothing= True,
filter_window_size=5,
filter_velocity_scale=10,
stats=False,
internal_fps=None,
internal_frame_height=1080,
trace=False,
force_detection=False):
self.pd_model = pd_model if pd_model else POSE_DETECTION_MODEL
self.pp_model = pp_model if pd_model else DETECTION_POSTPROCESSING_MODEL
self.divide_by_255_model = DIVIDE_BY_255_MODEL
print(f"Pose detection blob file : {self.pd_model}")
self.rect_transf_scale = 1.25
if lm_model is None or lm_model == "full":
self.lm_model = LANDMARK_MODEL_FULL
elif lm_model == "lite":
self.lm_model = LANDMARK_MODEL_LITE
elif lm_model == "heavy":
self.lm_model = LANDMARK_MODEL_HEAVY
else:
self.lm_model = lm_model
print(f"Landmarks using blob file : {self.lm_model}")
self.pd_score_thresh = pd_score_thresh
self.lm_score_thresh = lm_score_thresh
self.smoothing = smoothing
self.crop = crop
self.internal_fps = internal_fps
self.stats = stats
self.presence_threshold = 0.5
self.visibility_threshold = 0.5
self.trace = trace
self.force_detection = force_detection
self.device = dai.Device()
self.xyz = False
if input_src == None or input_src == "rgb" or input_src == "rgb_laconic":
self.input_type = "rgb" # OAK* internal color camera
self.laconic = input_src == "rgb_laconic" # Camera frames are not sent to the host
if xyz:
# Check if the device supports stereo
cameras = self.device.getConnectedCameras()
if dai.CameraBoardSocket.LEFT in cameras and dai.CameraBoardSocket.RIGHT in cameras:
self.xyz = True
else:
print("Warning: depth unavailable on this device, 'xyz' argument is ignored")
if internal_fps is None:
if "full" in str(self.lm_model):
self.internal_fps = 18 if self.xyz else 20
elif "heavy" in str(lm_model):
self.internal_fps = 7 if self.xyz else 8
else: # "lite"
self.internal_fps = 22 if self.xyz else 26
else:
self.internal_fps = internal_fps
print(f"Internal camera FPS set to: {self.internal_fps}")
self.video_fps = self.internal_fps # Used when saving the output in a video file. Should be close to the real fps
if self.crop:
self.frame_size, self.scale_nd = mpu.find_isp_scale_params(internal_frame_height)
self.img_h = self.img_w = self.frame_size
self.pad_w = self.pad_h = 0
self.crop_w = (int(round(1920 * self.scale_nd[0] / self.scale_nd[1])) - self.img_w) // 2
else:
width, self.scale_nd = mpu.find_isp_scale_params(internal_frame_height * 1920 / 1080, is_height=False)
self.img_h = int(round(1080 * self.scale_nd[0] / self.scale_nd[1]))
self.img_w = int(round(1920 * self.scale_nd[0] / self.scale_nd[1]))
self.pad_h = (self.img_w - self.img_h) // 2
self.pad_w = 0
self.frame_size = self.img_w
self.crop_w = 0
print(f"Internal camera image size: {self.img_w} x {self.img_h} - pad_h: {self.pad_h}")
else:
print("Invalid input source:", input_src)
sys.exit()
self.nb_kps = 33
if self.smoothing:
self.filter_landmarks = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.05,
beta=80,
derivate_cutoff=1
)
# landmarks_aux corresponds to the 2 landmarks used to compute the ROI in next frame
self.filter_landmarks_aux = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.01,
beta=10,
derivate_cutoff=1
)
self.filter_landmarks_world = mpu.LandmarksSmoothingFilter(
frequency=self.video_fps,
min_cutoff=0.1,
beta=40,
derivate_cutoff=1,
disable_value_scaling=True
)
if self.xyz:
self.filter_xyz = mpu.LowPassFilter(alpha=0.25)
# Define and start pipeline
usb_speed = self.device.getUsbSpeed()
self.device.startPipeline(self.create_pipeline())
print(f"Pipeline started - USB speed: {str(usb_speed).split('.')[-1]}")
# Define data queues
if not self.laconic:
self.q_video = self.device.getOutputQueue(name="cam_out", maxSize=1, blocking=False)
self.q_manager_out = self.device.getOutputQueue(name="manager_out", maxSize=1, blocking=False)
# For debugging
# self.q_pre_pd_manip_out = self.device.getOutputQueue(name="pre_pd_manip_out", maxSize=1, blocking=False)
# self.q_pre_lm_manip_out = self.device.getOutputQueue(name="pre_lm_manip_out", maxSize=1, blocking=False)
self.fps = FPS()
self.nb_pd_inferences = 0
self.nb_lm_inferences = 0
self.nb_lm_inferences_after_landmarks_ROI = 0
self.nb_frames_no_body = 0
def create_pipeline(self):
print("Creating pipeline...")
# Start defining a pipeline
pipeline = dai.Pipeline()
pipeline.setOpenVINOVersion(dai.OpenVINO.Version.VERSION_2021_4)
self.pd_input_length = 224
self.lm_input_length = 256
# ColorCamera
print("Creating Color Camera...")
cam = pipeline.create(dai.node.ColorCamera)
cam.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)
cam.setInterleaved(False)
cam.setIspScale(self.scale_nd[0], self.scale_nd[1])
cam.setFps(self.internal_fps)
cam.setBoardSocket(dai.CameraBoardSocket.RGB)
if self.crop:
cam.setVideoSize(self.frame_size, self.frame_size)
cam.setPreviewSize(self.frame_size, self.frame_size)
else:
cam.setVideoSize(self.img_w, self.img_h)
cam.setPreviewSize(self.img_w, self.img_h)
if not self.laconic:
cam_out = pipeline.create(dai.node.XLinkOut)
cam_out.setStreamName("cam_out")
cam_out.input.setQueueSize(1)
cam_out.input.setBlocking(False)
cam.video.link(cam_out.input)
# Define manager script node
manager_script = pipeline.create(dai.node.Script)
manager_script.setScript(self.build_manager_script())
if self.xyz:
print("Creating MonoCameras, Stereo and SpatialLocationCalculator nodes...")
# For now, RGB needs fixed focus to properly align with depth.
# This value was used during calibration
cam.initialControl.setManualFocus(130)
mono_resolution = dai.MonoCameraProperties.SensorResolution.THE_400_P
left = pipeline.createMonoCamera()
left.setBoardSocket(dai.CameraBoardSocket.LEFT)
left.setResolution(mono_resolution)
left.setFps(self.internal_fps)
right = pipeline.createMonoCamera()
right.setBoardSocket(dai.CameraBoardSocket.RIGHT)
right.setResolution(mono_resolution)
right.setFps(self.internal_fps)
stereo = pipeline.createStereoDepth()
stereo.setConfidenceThreshold(230)
# LR-check is required for depth alignment
stereo.setLeftRightCheck(True)
stereo.setDepthAlign(dai.CameraBoardSocket.RGB)
stereo.setSubpixel(False) # subpixel True -> latency
# MEDIAN_OFF necessary in depthai 2.7.2.
# Otherwise : [critical] Fatal error. Please report to developers. Log: 'StereoSipp' '533'
# stereo.setMedianFilter(dai.StereoDepthProperties.MedianFilter.MEDIAN_OFF)
spatial_location_calculator = pipeline.createSpatialLocationCalculator()
spatial_location_calculator.setWaitForConfigInput(True)
spatial_location_calculator.inputDepth.setBlocking(False)
spatial_location_calculator.inputDepth.setQueueSize(1)
left.out.link(stereo.left)
right.out.link(stereo.right)
stereo.depth.link(spatial_location_calculator.inputDepth)
manager_script.outputs['spatial_location_config'].link(spatial_location_calculator.inputConfig)
spatial_location_calculator.out.link(manager_script.inputs['spatial_data'])
# Define pose detection pre processing (resize preview to (self.pd_input_length, self.pd_input_length))
print("Creating Pose Detection pre processing image manip...")
pre_pd_manip = pipeline.create(dai.node.ImageManip)
pre_pd_manip.setMaxOutputFrameSize(self.pd_input_length*self.pd_input_length*3)
pre_pd_manip.setWaitForConfigInput(True)
pre_pd_manip.inputImage.setQueueSize(1)
pre_pd_manip.inputImage.setBlocking(False)
cam.preview.link(pre_pd_manip.inputImage)
manager_script.outputs['pre_pd_manip_cfg'].link(pre_pd_manip.inputConfig)
# For debugging
# pre_pd_manip_out = pipeline.createXLinkOut()
# pre_pd_manip_out.setStreamName("pre_pd_manip_out")
# pre_pd_manip.out.link(pre_pd_manip_out.input)
# Define pose detection model
print("Creating Pose Detection Neural Network...")
pd_nn = pipeline.create(dai.node.NeuralNetwork)
pd_nn.setBlobPath(self.pd_model)
# Increase threads for detection
# pd_nn.setNumInferenceThreads(2)
pre_pd_manip.out.link(pd_nn.input)
# Define pose detection post processing "model"
print("Creating Pose Detection post processing Neural Network...")
post_pd_nn = pipeline.create(dai.node.NeuralNetwork)
post_pd_nn.setBlobPath(self.pp_model)
pd_nn.out.link(post_pd_nn.input)
post_pd_nn.out.link(manager_script.inputs['from_post_pd_nn'])
# Define link to send result to host
manager_out = pipeline.create(dai.node.XLinkOut)
manager_out.setStreamName("manager_out")
manager_script.outputs['host'].link(manager_out.input)
# Define landmark pre processing image manip
print("Creating Landmark pre processing image manip...")
pre_lm_manip = pipeline.create(dai.node.ImageManip)
pre_lm_manip.setMaxOutputFrameSize(self.lm_input_length*self.lm_input_length*3)
pre_lm_manip.setWaitForConfigInput(True)
pre_lm_manip.inputImage.setQueueSize(1)
pre_lm_manip.inputImage.setBlocking(False)
cam.preview.link(pre_lm_manip.inputImage)
# For debugging
# pre_lm_manip_out = pipeline.createXLinkOut()
# pre_lm_manip_out.setStreamName("pre_lm_manip_out")
# pre_lm_manip.out.link(pre_lm_manip_out.input)
manager_script.outputs['pre_lm_manip_cfg'].link(pre_lm_manip.inputConfig)
# Define normalization model between ImageManip and landmark model
# This is a temporary step. Could be removed when support of setFrameType(RGBF16F16F16p) in ImageManip node
print("Creating DiveideBy255 Neural Network...")
divide_nn = pipeline.create(dai.node.NeuralNetwork)
divide_nn.setBlobPath(self.divide_by_255_model)
pre_lm_manip.out.link(divide_nn.input)
# Define landmark model
print("Creating Landmark Neural Network...")
lm_nn = pipeline.create(dai.node.NeuralNetwork)
lm_nn.setBlobPath(self.lm_model)
# lm_nn.setNumInferenceThreads(1)
divide_nn.out.link(lm_nn.input)
lm_nn.out.link(manager_script.inputs['from_lm_nn'])
print("Pipeline created.")
return pipeline
def build_manager_script(self):
'''
The code of the scripting node 'manager_script' depends on :
- the NN model (full, lite, 831),
- the score threshold,
- the video frame shape
So we build this code from the content of the file template_manager_script.py which is a python template
'''
# Read the template
with open(TEMPLATE_MANAGER_SCRIPT, 'r') as file:
template = Template(file.read())
# Perform the substitution
code = template.substitute(
_TRACE = "node.warn" if self.trace else "#",
_pd_score_thresh = self.pd_score_thresh,
_lm_score_thresh = self.lm_score_thresh,
_force_detection = self.force_detection,
_pad_h = self.pad_h,
_img_h = self.img_h,
_frame_size = self.frame_size,
_crop_w = self.crop_w,
_rect_transf_scale = self.rect_transf_scale,
_IF_XYZ = "" if self.xyz else '"""',
_buffer_size = 2910 if self.xyz else 2863,
_visibility_threshold = self.visibility_threshold
)
# Remove comments and empty lines
import re
code = re.sub(r'"{3}.*?"{3}', '', code, flags=re.DOTALL)
code = re.sub(r'#.*', '', code)
code = re.sub('\n\s*\n', '\n', code)
# For debugging
if self.trace:
with open("tmp_code.py", "w") as file:
file.write(code)
return code
def is_present(self, body, lm_id):
return body.presence[lm_id] > self.presence_threshold
def lm_postprocess(self, body, lms, lms_world):
# lms : landmarks sent by Manager script node to host (list of 39*5 elements for full body or 31*5 for upper body)
lm_raw = np.array(lms).reshape(-1,5)
# Each keypoint have 5 information:
# - X,Y coordinates are local to the body of
# interest and range from [0.0, 255.0].
# - Z coordinate is measured in "image pixels" like
# the X and Y coordinates and represents the
# distance relative to the plane of the subject's
# hips, which is the origin of the Z axis. Negative
# values are between the hips and the camera;
# positive values are behind the hips. Z coordinate
# scale is similar with X, Y scales but has different
# nature as obtained not via human annotation, by
# fitting synthetic data (GHUM model) to the 2D
# annotation.
# - Visibility, after user-applied sigmoid denotes the
# probability that a keypoint is located within the
# frame and not occluded by another bigger body
# part or another object.
# - Presence, after user-applied sigmoid denotes the
# probability that a keypoint is located within the
# frame.
# Normalize x,y,z. Scaling in z = scaling in x = 1/self.lm_input_length
lm_raw[:,:3] /= self.lm_input_length
# Apply sigmoid on visibility and presence (if used later)
body.visibility = 1 / (1 + np.exp(-lm_raw[:,3]))
body.presence = 1 / (1 + np.exp(-lm_raw[:,4]))
# body.norm_landmarks contains the normalized ([0:1]) 3D coordinates of landmarks in the square rotated body bounding box
body.norm_landmarks = lm_raw[:,:3]
# Now calculate body.landmarks = the landmarks in the image coordinate system (in pixel) (body.landmarks)
src = np.array([(0, 0), (1, 0), (1, 1)], dtype=np.float32)
dst = np.array([ (x, y) for x,y in body.rect_points[1:]], dtype=np.float32) # body.rect_points[0] is left bottom point and points going clockwise!
mat = cv2.getAffineTransform(src, dst)
lm_xy = np.expand_dims(body.norm_landmarks[:self.nb_kps,:2], axis=0)
lm_xy = np.squeeze(cv2.transform(lm_xy, mat))
# A segment of length 1 in the coordinates system of body bounding box takes body.rect_w_a pixels in the
# original image. Then we arbitrarily divide by 4 for a more realistic appearance.
lm_z = body.norm_landmarks[:self.nb_kps,2:3] * body.rect_w_a / 4
lm_xyz = np.hstack((lm_xy, lm_z))
# World landmarks are predicted in meters rather than in pixels of the image
# and have origin in the middle of the hips rather than in the corner of the
# pose image (cropped with given rectangle). Thus only rotation (but not scale
# and translation) is applied to the landmarks to transform them back to
# original coordinates.
body.landmarks_world = np.array(lms_world).reshape(-1,3)
sin_rot = sin(body.rotation)
cos_rot = cos(body.rotation)
rot_m = np.array([[cos_rot, sin_rot], [-sin_rot, cos_rot]])
body.landmarks_world[:,:2] = np.dot(body.landmarks_world[:,:2], rot_m)
if self.smoothing:
timestamp = now()
object_scale = body.rect_w_a
lm_xyz[:self.nb_kps] = self.filter_landmarks.apply(lm_xyz[:self.nb_kps], timestamp, object_scale)
lm_xyz[self.nb_kps:] = self.filter_landmarks_aux.apply(lm_xyz[self.nb_kps:], timestamp, object_scale)
body.landmarks_world = self.filter_landmarks_world.apply(body.landmarks_world, timestamp)
body.landmarks = lm_xyz.astype(np.int)
# If we added padding to make the image square, we need to remove this padding from landmark coordinates and from rect_points
if self.pad_h > 0:
body.landmarks[:,1] -= self.pad_h
for i in range(len(body.rect_points)):
body.rect_points[i][1] -= self.pad_h
# if self.pad_w > 0:
# body.landmarks[:,0] -= self.pad_w
# for i in range(len(body.rect_points)):
# body.rect_points[i][0] -= self.pad_w
def next_frame(self):
self.fps.update()
if self.laconic:
video_frame = np.zeros((self.frame_size, self.frame_size, 3), dtype=np.uint8)
else:
in_video = self.q_video.get()
video_frame = in_video.getCvFrame()
# For debugging
# pre_pd_manip = self.q_pre_pd_manip_out.tryGet()
# if pre_pd_manip:
# pre_pd_manip = pre_pd_manip.getCvFrame()
# cv2.imshow("pre_pd_manip", pre_pd_manip)
# pre_lm_manip = self.q_pre_lm_manip_out.tryGet()
# if pre_lm_manip:
# pre_lm_manip = pre_lm_manip.getCvFrame()
# cv2.imshow("pre_lm_manip", pre_lm_manip)
# Get result from device
res = marshal.loads(self.q_manager_out.get().getData())
if res["type"] != 0 and res["lm_score"] > self.lm_score_thresh:
body = mpu.Body()
body.rect_x_center_a = res["rect_center_x"] * self.frame_size
body.rect_y_center_a = res["rect_center_y"] * self.frame_size
body.rect_w_a = body.rect_h_a = res["rect_size"] * self.frame_size
body.rotation = res["rotation"]
body.rect_points = mpu.rotated_rect_to_points(body.rect_x_center_a, body.rect_y_center_a, body.rect_w_a, body.rect_h_a, body.rotation)
body.lm_score = res["lm_score"]
self.lm_postprocess(body, res['lms'], res['lms_world'])
if self.xyz:
if res['xyz_ref'] == 0:
body.xyz_ref = None
else:
if res['xyz_ref'] == 1:
body.xyz_ref = "mid_hips"
else: # res['xyz_ref'] == 2:
body.xyz_ref = "mid_shoulders"
body.xyz = np.array(res["xyz"])
if self.smoothing:
body.xyz = self.filter_xyz.apply(body.xyz)
body.xyz_zone = np.array(res["xyz_zone"])
body.xyz_ref_coords_pixel = np.mean(body.xyz_zone.reshape((2,2)), axis=0)
else:
body = None
if self.smoothing:
self.filter_landmarks.reset()
self.filter_landmarks_aux.reset()
self.filter_landmarks_world.reset()
if self.xyz: self.filter_xyz.reset()
# Statistics
if self.stats:
if res["type"] == 0:
self.nb_pd_inferences += 1
self.nb_frames_no_body += 1
else:
self.nb_lm_inferences += 1
if res["type"] == 1:
self.nb_pd_inferences += 1
else: # res["type"] == 2
self.nb_lm_inferences_after_landmarks_ROI += 1
if res["lm_score"] < self.lm_score_thresh: self.nb_frames_no_body += 1
return video_frame, body
def exit(self):
self.device.close()
# Print some stats
if self.stats:
print(f"FPS : {self.fps.get_global():.1f} f/s (# frames = {self.fps.nbf})")
print(f"# frames without body : {self.nb_frames_no_body}")
print(f"# pose detection inferences : {self.nb_pd_inferences}")
print(f"# landmark inferences : {self.nb_lm_inferences} - # after pose detection: {self.nb_lm_inferences - self.nb_lm_inferences_after_landmarks_ROI} - # after landmarks ROI prediction: {self.nb_lm_inferences_after_landmarks_ROI}")
|
import os.path
import re
import sys
version = sys.argv[2]
lib_suffix = "" if len(sys.argv) < 4 else sys.argv[3]
with open(sys.argv[1], "r") as f_in:
with open("static_link.sh", "w") as f_out:
if os.path.isfile(f"libtensorflow_framework.{version}.dylib-2.params"):
p_cd = re.compile(r"^\((cd .*) && \\$")
p_linker = re.compile(fr"^\s*.+cc_wrapper.sh.+(@bazel-out\S+libtensorflow{lib_suffix}\.\d\.\d\.\d\.dylib-2\.params).*")
f_out.write("#!/bin/bash\n# note: ar/binutils version 2.27 required to support output files > 4GB\n")
env = []
for line in f_in:
if line.startswith("(cd"):
# new command, reset
env = [line]
else:
m1 = p_linker.match(line)
if m1:
m2 = p_cd.match(env[0])
f_out.write(m2.group(1) + "\n")
line = f'"/usr/bin/libtool" -static -o {m1.group(1)[1:-9].replace('.dylib', '.a')} {m1.group(1).replace('.dylib', '.a')}\n'
f_out.write(line)
else:
env.append(line)
else:
# old behaviour (still on some platforms): inline all parameters instead of using -2.params file
p_cd = re.compile(r"^\((cd .*) && \\$")
p_linker1 = re.compile(fr"^.*cc_wrapper.sh.+-shared.+-o (bazel-out\S+libtensorflow{lib_suffix}\.\d\.\d\.\d\.dylib)")
p_linker2 = re.compile("^.*cc_wrapper.sh.+-shared.+-o (bazel-out\\S+libtensorflow_framework\\.\\d\\.\\d\\.\\d\\.dylib)")
f_out.write("#!/bin/bash\n# note: ar/binutils version 2.27 required to support output files > 4GB\n")
env = []
parts = None
for line in f_in:
if line.startswith("(cd"):
# new command, reset
env = [line]
else:
m1 = p_linker1.match(line)
m2 = p_linker2.match(line)
if m1:
tokens = line.split()
if parts is None:
parts = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
else:
m = p_cd.match(env[0])
f_out.write(m.group(1) + "\n")
tmp = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
old = set(parts)
parts += [t for t in tmp if t not in old]
line = f"libtool -static -o {m1.group(1).replace(".dylib", ".a")} {" ".join(parts)}\n"
f_out.write(line)
break
elif m2 and len(env) > 6:
tokens = line.split()
if parts is None:
parts = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
else:
m = p_cd.match(env[0])
f_out.write(m.group(1) + "\n")
tmp = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
old = set(parts)
parts += [t for t in tmp if t not in old]
line = f"libtool -static -o {m2.group(1).replace("_framework", lib_suffix).replace(".dylib", ".a")} {" ".join(parts)}\n"
f_out.write(line)
break
else:
env.append(line)
| import os.path
import re
import sys
version = sys.argv[2]
lib_suffix = "" if len(sys.argv) < 4 else sys.argv[3]
with open(sys.argv[1], "r") as f_in:
with open("static_link.sh", "w") as f_out:
if os.path.isfile(f"libtensorflow_framework.{version}.dylib-2.params"):
p_cd = re.compile(r"^\((cd .*) && \\$")
p_linker = re.compile(fr"^\s*.+cc_wrapper.sh.+(@bazel-out\S+libtensorflow{lib_suffix}\.\d\.\d\.\d\.dylib-2\.params).*")
f_out.write("#!/bin/bash\n# note: ar/binutils version 2.27 required to support output files > 4GB\n")
env = []
for line in f_in:
if line.startswith("(cd"):
# new command, reset
env = [line]
else:
m1 = p_linker.match(line)
if m1:
m2 = p_cd.match(env[0])
f_out.write(m2.group(1) + "\n")
line = f'"/usr/bin/libtool" -static -o {m1.group(1)[1:-9].replace(".dylib", ".a")} {m1.group(1).replace(".dylib", ".a")}\n'
f_out.write(line)
else:
env.append(line)
else:
# old behaviour (still on some platforms): inline all parameters instead of using -2.params file
p_cd = re.compile(r"^\((cd .*) && \\$")
p_linker1 = re.compile(fr"^.*cc_wrapper.sh.+-shared.+-o (bazel-out\S+libtensorflow{lib_suffix}\.\d\.\d\.\d\.dylib)")
p_linker2 = re.compile("^.*cc_wrapper.sh.+-shared.+-o (bazel-out\\S+libtensorflow_framework\\.\\d\\.\\d\\.\\d\\.dylib)")
f_out.write("#!/bin/bash\n# note: ar/binutils version 2.27 required to support output files > 4GB\n")
env = []
parts = None
for line in f_in:
if line.startswith("(cd"):
# new command, reset
env = [line]
else:
m1 = p_linker1.match(line)
m2 = p_linker2.match(line)
if m1:
tokens = line.split()
if parts is None:
parts = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
else:
m = p_cd.match(env[0])
f_out.write(m.group(1) + "\n")
tmp = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
old = set(parts)
parts += [t for t in tmp if t not in old]
line = f"libtool -static -o {m1.group(1).replace('.dylib', '.a')} {' '.join(parts)}\n"
f_out.write(line)
break
elif m2 and len(env) > 6:
tokens = line.split()
if parts is None:
parts = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
else:
m = p_cd.match(env[0])
f_out.write(m.group(1) + "\n")
tmp = [t[16:] for t in tokens if t.startswith("-Wl,-force_load,")]
old = set(parts)
parts += [t for t in tmp if t not in old]
line = f"libtool -static -o {m2.group(1).replace('_framework', lib_suffix).replace('.dylib', '.a')} {' '.join(parts)}\n"
f_out.write(line)
break
else:
env.append(line)
|
from pymongo import MongoClient
from src.types.messages import MESSAGES_TYPES, Message
from .base import BaseStorage
class MongoDBStorage(BaseStorage):
"""
Message storage with MongoDB as backend.
"""
def __init__(self, host: str, port: int, db: str, collection: str):
self._client = MongoClient(host, port)
self._db = self._client[db]
self._collection = self._client[collection]
def messages(self, user_id: int, type: str | None) -> list[Message]:
"""
Get all messages for a user.
Args:
user_id: The user id.
type: The type of message to get. If None, all messages will be returned.
Returns:
A list of messages.
"""
messages = [
self._convert(message)
for message in self._collection.get(str(user_id))
]
if type:
messages = [
message for message in messages if message.type() == type
]
return messages
def save(self, user_id: int, message: Message):
"""
Save a new message.
Args:
user_id: The user id.
message: The message to save.
"""
if not self._collection.get(str(user_id)):
self._collection.insert_one({"_id": str(user_id), "messages": []})
self._collection.update_one(
{"_id": str(user_id)}, {"$push": {"messages": message.dict()}}
)
def delete(self, user_id: int, message: Message):
"""
Delete a message.
Args:
user_id: The user id.
message: The message to delete.
"""
if not self._collection.get(str(user_id)):
self._collection.insert_one({"_id": str(user_id), "messages": []})
self._collection.update_one(
{"_id": str(user_id)}, {"$push": {"messages": message.dict()}}
)
def _convert(self, d: dict) -> Message:
"""
Convert a dict to a message.
Args:
d: The dict to convert.
Returns:
A message.
"""
for message_type in MESSAGES_TYPES:
if d["type"] == message_type.type():
return message_type(**d)
raise ValueError(f"Unknown message type: {d["type"]}")
__all__ = ["MongoDBStorage"]
| from pymongo import MongoClient
from src.types.messages import MESSAGES_TYPES, Message
from .base import BaseStorage
class MongoDBStorage(BaseStorage):
"""
Message storage with MongoDB as backend.
"""
def __init__(self, host: str, port: int, db: str, collection: str):
self._client = MongoClient(host, port)
self._db = self._client[db]
self._collection = self._client[collection]
def messages(self, user_id: int, type: str | None) -> list[Message]:
"""
Get all messages for a user.
Args:
user_id: The user id.
type: The type of message to get. If None, all messages will be returned.
Returns:
A list of messages.
"""
messages = [
self._convert(message)
for message in self._collection.get(str(user_id))
]
if type:
messages = [
message for message in messages if message.type() == type
]
return messages
def save(self, user_id: int, message: Message):
"""
Save a new message.
Args:
user_id: The user id.
message: The message to save.
"""
if not self._collection.get(str(user_id)):
self._collection.insert_one({"_id": str(user_id), "messages": []})
self._collection.update_one(
{"_id": str(user_id)}, {"$push": {"messages": message.dict()}}
)
def delete(self, user_id: int, message: Message):
"""
Delete a message.
Args:
user_id: The user id.
message: The message to delete.
"""
if not self._collection.get(str(user_id)):
self._collection.insert_one({"_id": str(user_id), "messages": []})
self._collection.update_one(
{"_id": str(user_id)}, {"$push": {"messages": message.dict()}}
)
def _convert(self, d: dict) -> Message:
"""
Convert a dict to a message.
Args:
d: The dict to convert.
Returns:
A message.
"""
for message_type in MESSAGES_TYPES:
if d["type"] == message_type.type():
return message_type(**d)
raise ValueError(f"Unknown message type: {d['type']}")
__all__ = ["MongoDBStorage"]
|
import random
import time
import numpy as np
from carla.agents.core import ActorCritic
from carla.agents.utils.dummy_vec_env import DummyVecEnv
from carla.agents.utils.pytorch_utils import dict_obs_to_tensor, merge_dict_obs_list, merge_list_of_dicts
from carla.agents.utils.subproc_vec_env import SubprocVecEnv
from carla.agents.utils.weight_init import *
def logging(log_writer, logger, log_interval, epoch, steps_per_epoch, start_time):
# log info to tensorboard
log_writer.add_scalar(f'stats/EpRet', np.mean(logger.epoch_dict['EpRet']), epoch)
log_writer.add_scalar(f'stats/EpLen', np.mean(logger.epoch_dict['EpLen']), epoch)
log_writer.add_scalar(f'stats/LossPi', np.mean(logger.epoch_dict['LossPi']), epoch)
log_writer.add_scalar(f'stats/LossV', np.mean(logger.epoch_dict['LossV']), epoch)
log_writer.add_scalar(f'stats/Entropy', np.mean(logger.epoch_dict['Entropy']), epoch)
# Log info about epoch
logger.log_tabular('Epoch', epoch)
logger.log_tabular('EpRet', with_min_and_max=True)
logger.log_tabular('EpLen', average_only=True)
logger.log_tabular('TotalEnvInteracts', (epoch + 1) * steps_per_epoch)
# log context statistics
for key in logger.epoch_dict.keys():
if "EpRet_" in key and len(logger.epoch_dict[key]) > 0:
context = key.split("_")[-1]
if epoch % log_interval == 0:
log_writer.add_scalar(f'context_{context}/EpRet', np.mean(logger.epoch_dict[f"EpRet_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/EpLen', np.mean(logger.epoch_dict[f"EpLen_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/NObs', np.mean(logger.epoch_dict[f"NObs_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/NGoodies', np.mean(logger.epoch_dict[f"NGoodies_{context}"]),
epoch)
log_writer.add_scalar(f'context_{context}/GoalReached',
np.mean(logger.epoch_dict[f"GoalReached_{context}"]), epoch)
logger.log_tabular('Time', time.time() - start_time)
log_stats = logger.log_current_row
print(f'Epoch: {epoch} | Avg. Ep. Return: {log_stats['AverageEpRet']:.4f} '
f'| Avg. Ep. Length: {log_stats['EpLen']:.4f} | Time Passed: {log_stats['Time']:.4f}')
logger.dump_tabular(print_to_terminal=False)
def collect_epoch_data(ac, env, initial_obs, buf, local_steps_per_epoch, obs_space, device,
logger, n_proc, ep_ret, ep_len, max_ep_len, vae_buffer=None):
# make sure agent is in eval mode, and for case of pretrained VAE, weights of encoder are frozen and in eval model.
ac.eval()
ac.freeze_context_net()
ac.set_eval_context_net()
o = initial_obs
for t in range(local_steps_per_epoch):
o = merge_dict_obs_list(o, obs_space)
a, v, logp = ac.step(dict_obs_to_tensor(o, device=device))
next_o, r, d, info = env.step(a)
ep_ret += r
ep_len += 1
info = merge_list_of_dicts(info)
# save and log
buf.store(o, a, r, v, logp)
logger.store(VVals=v)
if vae_buffer is not None:
vae_buffer.store(o)
# Update obs (critical!)
o = next_o
for proc_idx in range(n_proc):
timeout = ep_len[proc_idx] == max_ep_len
terminal = d[proc_idx] or timeout
epoch_ended = t == local_steps_per_epoch - 1
if terminal or epoch_ended:
# if trajectory didn't reach terminal state, bootstrap value target
if timeout or epoch_ended:
if n_proc > 1:
# in case of more then one processes it should be wrapped as a list
step_o = [o[proc_idx]]
else:
step_o = o
_, v, _ = ac.step(dict_obs_to_tensor(merge_dict_obs_list(step_o, obs_space), device=device))
v = v[0] # index 0 to get v as a single number
else:
v = 0
buf.finish_path(proc_idx, v)
if terminal:
# only save EpRet / EpLen if trajectory finished
logger.store(EpRet=ep_ret[proc_idx], EpLen=ep_len[proc_idx])
# log context specific statistics
context_id = info['context'][proc_idx]
obstacles = info['obstacles'][proc_idx]
goodies = info['goodies'][proc_idx]
goal = info['goal_reached'][proc_idx]
logger.store(**{f'EpRet_{context_id}': ep_ret[proc_idx],
f'EpLen_{context_id}': ep_len[proc_idx],
f'NObs_{context_id}': obstacles,
f'NGoodies_{context_id}': goodies,
f'GoalReached_{context_id}': goal,
})
# no env reset necessary, handled implicitly by subroc_vec_env
ep_ret[proc_idx] = 0
ep_len[proc_idx] = 0
# return the initial observation for the next epoch
return o
def setup_agent(obs_space, action_space, ac_kwargs, device):
# Create actor-critic module
ac = ActorCritic(obs_space, action_space, **ac_kwargs)
# handling freezing and eval mode for VAE in context_net
ac.freeze_context_net()
ac.set_eval_context_net()
ac = ac.to(device)
return ac
def setup_environments(env_fn, env_kwargs, eval_env_kwargs, n_proc):
# test env for logging
test_env = env_fn(rank=0, **env_kwargs)()
# Instantiate environment
env_fns = [env_fn(rank=i, **env_kwargs) for i in range(n_proc)]
eval_env = env_fn(rank=0, **eval_env_kwargs)()
if n_proc == 1:
env = DummyVecEnv(env_fns)
else:
env = SubprocVecEnv(env_fns)
return env, eval_env, test_env
def set_seeds(seed):
# Random seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True |
import random
import time
import numpy as np
from carla.agents.core import ActorCritic
from carla.agents.utils.dummy_vec_env import DummyVecEnv
from carla.agents.utils.pytorch_utils import dict_obs_to_tensor, merge_dict_obs_list, merge_list_of_dicts
from carla.agents.utils.subproc_vec_env import SubprocVecEnv
from carla.agents.utils.weight_init import *
def logging(log_writer, logger, log_interval, epoch, steps_per_epoch, start_time):
# log info to tensorboard
log_writer.add_scalar(f'stats/EpRet', np.mean(logger.epoch_dict['EpRet']), epoch)
log_writer.add_scalar(f'stats/EpLen', np.mean(logger.epoch_dict['EpLen']), epoch)
log_writer.add_scalar(f'stats/LossPi', np.mean(logger.epoch_dict['LossPi']), epoch)
log_writer.add_scalar(f'stats/LossV', np.mean(logger.epoch_dict['LossV']), epoch)
log_writer.add_scalar(f'stats/Entropy', np.mean(logger.epoch_dict['Entropy']), epoch)
# Log info about epoch
logger.log_tabular('Epoch', epoch)
logger.log_tabular('EpRet', with_min_and_max=True)
logger.log_tabular('EpLen', average_only=True)
logger.log_tabular('TotalEnvInteracts', (epoch + 1) * steps_per_epoch)
# log context statistics
for key in logger.epoch_dict.keys():
if "EpRet_" in key and len(logger.epoch_dict[key]) > 0:
context = key.split("_")[-1]
if epoch % log_interval == 0:
log_writer.add_scalar(f'context_{context}/EpRet', np.mean(logger.epoch_dict[f"EpRet_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/EpLen', np.mean(logger.epoch_dict[f"EpLen_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/NObs', np.mean(logger.epoch_dict[f"NObs_{context}"]), epoch)
log_writer.add_scalar(f'context_{context}/NGoodies', np.mean(logger.epoch_dict[f"NGoodies_{context}"]),
epoch)
log_writer.add_scalar(f'context_{context}/GoalReached',
np.mean(logger.epoch_dict[f"GoalReached_{context}"]), epoch)
logger.log_tabular('Time', time.time() - start_time)
log_stats = logger.log_current_row
print(f'Epoch: {epoch} | Avg. Ep. Return: {log_stats["AverageEpRet"]:.4f} '
f'| Avg. Ep. Length: {log_stats["EpLen"]:.4f} | Time Passed: {log_stats["Time"]:.4f}')
logger.dump_tabular(print_to_terminal=False)
def collect_epoch_data(ac, env, initial_obs, buf, local_steps_per_epoch, obs_space, device,
logger, n_proc, ep_ret, ep_len, max_ep_len, vae_buffer=None):
# make sure agent is in eval mode, and for case of pretrained VAE, weights of encoder are frozen and in eval model.
ac.eval()
ac.freeze_context_net()
ac.set_eval_context_net()
o = initial_obs
for t in range(local_steps_per_epoch):
o = merge_dict_obs_list(o, obs_space)
a, v, logp = ac.step(dict_obs_to_tensor(o, device=device))
next_o, r, d, info = env.step(a)
ep_ret += r
ep_len += 1
info = merge_list_of_dicts(info)
# save and log
buf.store(o, a, r, v, logp)
logger.store(VVals=v)
if vae_buffer is not None:
vae_buffer.store(o)
# Update obs (critical!)
o = next_o
for proc_idx in range(n_proc):
timeout = ep_len[proc_idx] == max_ep_len
terminal = d[proc_idx] or timeout
epoch_ended = t == local_steps_per_epoch - 1
if terminal or epoch_ended:
# if trajectory didn't reach terminal state, bootstrap value target
if timeout or epoch_ended:
if n_proc > 1:
# in case of more then one processes it should be wrapped as a list
step_o = [o[proc_idx]]
else:
step_o = o
_, v, _ = ac.step(dict_obs_to_tensor(merge_dict_obs_list(step_o, obs_space), device=device))
v = v[0] # index 0 to get v as a single number
else:
v = 0
buf.finish_path(proc_idx, v)
if terminal:
# only save EpRet / EpLen if trajectory finished
logger.store(EpRet=ep_ret[proc_idx], EpLen=ep_len[proc_idx])
# log context specific statistics
context_id = info['context'][proc_idx]
obstacles = info['obstacles'][proc_idx]
goodies = info['goodies'][proc_idx]
goal = info['goal_reached'][proc_idx]
logger.store(**{f'EpRet_{context_id}': ep_ret[proc_idx],
f'EpLen_{context_id}': ep_len[proc_idx],
f'NObs_{context_id}': obstacles,
f'NGoodies_{context_id}': goodies,
f'GoalReached_{context_id}': goal,
})
# no env reset necessary, handled implicitly by subroc_vec_env
ep_ret[proc_idx] = 0
ep_len[proc_idx] = 0
# return the initial observation for the next epoch
return o
def setup_agent(obs_space, action_space, ac_kwargs, device):
# Create actor-critic module
ac = ActorCritic(obs_space, action_space, **ac_kwargs)
# handling freezing and eval mode for VAE in context_net
ac.freeze_context_net()
ac.set_eval_context_net()
ac = ac.to(device)
return ac
def setup_environments(env_fn, env_kwargs, eval_env_kwargs, n_proc):
# test env for logging
test_env = env_fn(rank=0, **env_kwargs)()
# Instantiate environment
env_fns = [env_fn(rank=i, **env_kwargs) for i in range(n_proc)]
eval_env = env_fn(rank=0, **eval_env_kwargs)()
if n_proc == 1:
env = DummyVecEnv(env_fns)
else:
env = SubprocVecEnv(env_fns)
return env, eval_env, test_env
def set_seeds(seed):
# Random seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True |
import sys
import googleapiclient.discovery
from ultideploy import constants, credentials, resources
def bootstrap(args):
google_credentials = credentials.default_google_credentials()
organization = resources.get_organization(
f"organizations/{args.organization_id}", google_credentials
)
projects_service = googleapiclient.discovery.build(
'cloudresourcemanager',
'v1',
credentials=google_credentials
)
print(f"Looking for existing '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project...")
request = projects_service.projects().list(
filter=f"id:{constants.TERRAFORM_ADMIN_PROJECT_ID}"
)
response = request.execute()
projects = response.get("projects", [])
if len(projects) == 0:
print(f"The '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project does not exist.\n")
project = resources.create_terraform_admin_project(
projects_service, args.organization_id
)
elif len(projects) == 1:
print(f"The '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project already exists.\n")
project = projects[0]
else:
print(
f"Received {len(projects)} projects matching the query when 0 or "
f"1 were expected."
)
sys.exit(1)
print(f"Project Number: {project["projectNumber"]}\n")
billing_account = resources.get_billing_account(google_credentials)
resources.set_project_billing_account(
project.get('projectId'), billing_account.get('name'), google_credentials
)
resources.enable_admin_services(project['projectNumber'], google_credentials)
service_account = resources.get_or_create_service_account(
constants.TERRAFORM_ADMIN_PROJECT_ID,
constants.TERRAFORM_SERVICE_ACCOUNT_ID,
constants.TERRAFORM_SERVICE_ACCOUNT_NAME,
google_credentials
)
resources.bootstrap_credentials(service_account.get('name'), google_credentials)
resources.bootstrap_organization_privileges(
organization.get('name'),
service_account.get('email'),
google_credentials
)
resources.bootstrap_admin_project_privileges(
project.get('projectId'),
service_account.get('email'),
google_credentials
)
resources.bootstrap_dns_project_privileges(
constants.DNS_PROJECT_ID,
service_account.get('email'),
google_credentials
)
resources.bootstrap_storage_bucket(
project.get('projectId'), constants.TERRAFORM_BUCKET_NAME, google_credentials
)
| import sys
import googleapiclient.discovery
from ultideploy import constants, credentials, resources
def bootstrap(args):
google_credentials = credentials.default_google_credentials()
organization = resources.get_organization(
f"organizations/{args.organization_id}", google_credentials
)
projects_service = googleapiclient.discovery.build(
'cloudresourcemanager',
'v1',
credentials=google_credentials
)
print(f"Looking for existing '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project...")
request = projects_service.projects().list(
filter=f"id:{constants.TERRAFORM_ADMIN_PROJECT_ID}"
)
response = request.execute()
projects = response.get("projects", [])
if len(projects) == 0:
print(f"The '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project does not exist.\n")
project = resources.create_terraform_admin_project(
projects_service, args.organization_id
)
elif len(projects) == 1:
print(f"The '{constants.TERRAFORM_ADMIN_PROJECT_ID}' project already exists.\n")
project = projects[0]
else:
print(
f"Received {len(projects)} projects matching the query when 0 or "
f"1 were expected."
)
sys.exit(1)
print(f"Project Number: {project['projectNumber']}\n")
billing_account = resources.get_billing_account(google_credentials)
resources.set_project_billing_account(
project.get('projectId'), billing_account.get('name'), google_credentials
)
resources.enable_admin_services(project['projectNumber'], google_credentials)
service_account = resources.get_or_create_service_account(
constants.TERRAFORM_ADMIN_PROJECT_ID,
constants.TERRAFORM_SERVICE_ACCOUNT_ID,
constants.TERRAFORM_SERVICE_ACCOUNT_NAME,
google_credentials
)
resources.bootstrap_credentials(service_account.get('name'), google_credentials)
resources.bootstrap_organization_privileges(
organization.get('name'),
service_account.get('email'),
google_credentials
)
resources.bootstrap_admin_project_privileges(
project.get('projectId'),
service_account.get('email'),
google_credentials
)
resources.bootstrap_dns_project_privileges(
constants.DNS_PROJECT_ID,
service_account.get('email'),
google_credentials
)
resources.bootstrap_storage_bucket(
project.get('projectId'), constants.TERRAFORM_BUCKET_NAME, google_credentials
)
|
"""
Module for applying conditional formatting to DataFrames and Series.
"""
from collections import defaultdict
from contextlib import contextmanager
import copy
from functools import partial
from itertools import product
from typing import (
Any,
Callable,
DefaultDict,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
)
from uuid import uuid1
import numpy as np
from pandas._config import get_option
from pandas._libs import lib
from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, Label
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
from pandas.core.dtypes.common import is_float
import pandas as pd
from pandas.api.types import is_dict_like, is_list_like
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame
from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice
jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
try:
import matplotlib.pyplot as plt
from matplotlib import colors
has_mpl = True
except ImportError:
has_mpl = False
no_mpl_message = "{0} requires matplotlib."
@contextmanager
def _mpl(func: Callable):
if has_mpl:
yield plt, colors
else:
raise ImportError(no_mpl_message.format(func.__name__))
class Styler:
"""
Helps style a DataFrame or Series according to the data with HTML and CSS.
Parameters
----------
data : Series or DataFrame
Data to be styled - either a Series or DataFrame.
precision : int
Precision to round floats to, defaults to pd.options.display.precision.
table_styles : list-like, default None
List of {selector: (attr, value)} dicts; see Notes.
uuid : str, default None
A unique identifier to avoid CSS collisions; generated automatically.
caption : str, default None
Caption to attach to the table.
table_attributes : str, default None
Items that show up in the opening ``<table>`` tag
in addition to automatic (by default) id.
cell_ids : bool, default True
If True, each cell will have an ``id`` attribute in their HTML tag.
The ``id`` takes the form ``T_<uuid>_row<num_row>_col<num_col>``
where ``<uuid>`` is the unique identifier, ``<num_row>`` is the row
number and ``<num_col>`` is the column number.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied.
.. versionadded:: 1.0.0
Attributes
----------
env : Jinja2 jinja2.Environment
template : Jinja2 Template
loader : Jinja2 Loader
See Also
--------
DataFrame.style : Return a Styler object containing methods for building
a styled HTML representation for the DataFrame.
Notes
-----
Most styling will be done by passing style functions into
``Styler.apply`` or ``Styler.applymap``. Style functions should
return values with strings containing CSS ``'attr: value'`` that will
be applied to the indicated cells.
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
to automatically render itself. Otherwise call Styler.render to get
the generated HTML.
CSS classes are attached to the generated HTML
* Index and Column names include ``index_name`` and ``level<k>``
where `k` is its level in a MultiIndex
* Index label cells include
* ``row_heading``
* ``row<n>`` where `n` is the numeric position of the row
* ``level<k>`` where `k` is the level in a MultiIndex
* Column label cells include
* ``col_heading``
* ``col<n>`` where `n` is the numeric position of the column
* ``level<k>`` where `k` is the level in a MultiIndex
* Blank cells include ``blank``
* Data cells include ``data``
"""
loader = jinja2.PackageLoader("pandas", "io/formats/templates")
env = jinja2.Environment(loader=loader, trim_blocks=True)
template = env.get_template("html.tpl")
def __init__(
self,
data: FrameOrSeriesUnion,
precision: Optional[int] = None,
table_styles: Optional[List[Dict[str, List[Tuple[str, str]]]]] = None,
uuid: Optional[str] = None,
caption: Optional[str] = None,
table_attributes: Optional[str] = None,
cell_ids: bool = True,
na_rep: Optional[str] = None,
):
self.ctx: DefaultDict[Tuple[int, int], List[str]] = defaultdict(list)
self._todo: List[Tuple[Callable, Tuple, Dict]] = []
if not isinstance(data, (pd.Series, pd.DataFrame)):
raise TypeError("``data`` must be a Series or DataFrame")
if data.ndim == 1:
data = data.to_frame()
if not data.index.is_unique or not data.columns.is_unique:
raise ValueError("style is not supported for non-unique indices.")
self.data = data
self.index = data.index
self.columns = data.columns
self.uuid = uuid
self.table_styles = table_styles
self.caption = caption
if precision is None:
precision = get_option("display.precision")
self.precision = precision
self.table_attributes = table_attributes
self.hidden_index = False
self.hidden_columns: Sequence[int] = []
self.cell_ids = cell_ids
self.na_rep = na_rep
# display_funcs maps (row, col) -> formatting function
def default_display_func(x):
if self.na_rep is not None and pd.isna(x):
return self.na_rep
elif is_float(x):
display_format = f"{x:.{self.precision}f}"
return display_format
else:
return x
self._display_funcs: DefaultDict[
Tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: default_display_func)
def _repr_html_(self) -> str:
"""
Hooks into Jupyter notebook rich display system.
"""
return self.render()
@doc(NDFrame.to_excel, klass="Styler")
def to_excel(
self,
excel_writer,
sheet_name: str = "Sheet1",
na_rep: str = "",
float_format: Optional[str] = None,
columns: Optional[Sequence[Label]] = None,
header: Union[Sequence[Label], bool] = True,
index: bool = True,
index_label: Optional[Union[Label, Sequence[Label]]] = None,
startrow: int = 0,
startcol: int = 0,
engine: Optional[str] = None,
merge_cells: bool = True,
encoding: Optional[str] = None,
inf_rep: str = "inf",
verbose: bool = True,
freeze_panes: Optional[Tuple[int, int]] = None,
) -> None:
from pandas.io.formats.excel import ExcelFormatter
formatter = ExcelFormatter(
self,
na_rep=na_rep,
cols=columns,
header=header,
float_format=float_format,
index=index,
index_label=index_label,
merge_cells=merge_cells,
inf_rep=inf_rep,
)
formatter.write(
excel_writer,
sheet_name=sheet_name,
startrow=startrow,
startcol=startcol,
freeze_panes=freeze_panes,
engine=engine,
)
def _translate(self):
"""
Convert the DataFrame in `self.data` and the attrs from `_build_styles`
into a dictionary of {head, body, uuid, cellstyle}.
"""
table_styles = self.table_styles or []
caption = self.caption
ctx = self.ctx
precision = self.precision
hidden_index = self.hidden_index
hidden_columns = self.hidden_columns
uuid = self.uuid or str(uuid1()).replace("-", "_")
ROW_HEADING_CLASS = "row_heading"
COL_HEADING_CLASS = "col_heading"
INDEX_NAME_CLASS = "index_name"
DATA_CLASS = "data"
BLANK_CLASS = "blank"
BLANK_VALUE = ""
def format_attr(pair):
return f"{pair["key"]}={pair["value"]}"
# for sparsifying a MultiIndex
idx_lengths = _get_level_lengths(self.index)
col_lengths = _get_level_lengths(self.columns, hidden_columns)
cell_context = dict()
n_rlvls = self.data.index.nlevels
n_clvls = self.data.columns.nlevels
rlabels = self.data.index.tolist()
clabels = self.data.columns.tolist()
if n_rlvls == 1:
rlabels = [[x] for x in rlabels]
if n_clvls == 1:
clabels = [[x] for x in clabels]
clabels = list(zip(*clabels))
cellstyle_map = defaultdict(list)
head = []
for r in range(n_clvls):
# Blank for Index columns...
row_es = [
{
"type": "th",
"value": BLANK_VALUE,
"display_value": BLANK_VALUE,
"is_visible": not hidden_index,
"class": " ".join([BLANK_CLASS]),
}
] * (n_rlvls - 1)
# ... except maybe the last for columns.names
name = self.data.columns.names[r]
cs = [
BLANK_CLASS if name is None else INDEX_NAME_CLASS,
f"level{r}",
]
name = BLANK_VALUE if name is None else name
row_es.append(
{
"type": "th",
"value": name,
"display_value": name,
"class": " ".join(cs),
"is_visible": not hidden_index,
}
)
if clabels:
for c, value in enumerate(clabels[r]):
cs = [
COL_HEADING_CLASS,
f"level{r}",
f"col{c}",
]
cs.extend(
cell_context.get("col_headings", {}).get(r, {}).get(c, [])
)
es = {
"type": "th",
"value": value,
"display_value": value,
"class": " ".join(cs),
"is_visible": _is_visible(c, r, col_lengths),
}
colspan = col_lengths.get((r, c), 0)
if colspan > 1:
es["attributes"] = [
format_attr({"key": "colspan", "value": colspan})
]
row_es.append(es)
head.append(row_es)
if (
self.data.index.names
and com.any_not_none(*self.data.index.names)
and not hidden_index
):
index_header_row = []
for c, name in enumerate(self.data.index.names):
cs = [INDEX_NAME_CLASS, f"level{c}"]
name = "" if name is None else name
index_header_row.append(
{"type": "th", "value": name, "class": " ".join(cs)}
)
index_header_row.extend(
[{"type": "th", "value": BLANK_VALUE, "class": " ".join([BLANK_CLASS])}]
* (len(clabels[0]) - len(hidden_columns))
)
head.append(index_header_row)
body = []
for r, idx in enumerate(self.data.index):
row_es = []
for c, value in enumerate(rlabels[r]):
rid = [
ROW_HEADING_CLASS,
f"level{c}",
f"row{r}",
]
es = {
"type": "th",
"is_visible": (_is_visible(r, c, idx_lengths) and not hidden_index),
"value": value,
"display_value": value,
"id": "_".join(rid[1:]),
"class": " ".join(rid),
}
rowspan = idx_lengths.get((c, r), 0)
if rowspan > 1:
es["attributes"] = [
format_attr({"key": "rowspan", "value": rowspan})
]
row_es.append(es)
for c, col in enumerate(self.data.columns):
cs = [DATA_CLASS, f"row{r}", f"col{c}"]
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
formatter = self._display_funcs[(r, c)]
value = self.data.iloc[r, c]
row_dict = {
"type": "td",
"value": value,
"class": " ".join(cs),
"display_value": formatter(value),
"is_visible": (c not in hidden_columns),
}
# only add an id if the cell has a style
if self.cell_ids or not (len(ctx[r, c]) == 1 and ctx[r, c][0] == ""):
row_dict["id"] = "_".join(cs[1:])
row_es.append(row_dict)
props = []
for x in ctx[r, c]:
# have to handle empty styles like ['']
if x.count(":"):
props.append(tuple(x.split(":")))
else:
props.append(("", ""))
cellstyle_map[tuple(props)].append(f"row{r}_col{c}")
body.append(row_es)
cellstyle = [
{"props": list(props), "selectors": selectors}
for props, selectors in cellstyle_map.items()
]
table_attr = self.table_attributes
use_mathjax = get_option("display.html.use_mathjax")
if not use_mathjax:
table_attr = table_attr or ""
if 'class="' in table_attr:
table_attr = table_attr.replace('class="', 'class="tex2jax_ignore ')
else:
table_attr += ' class="tex2jax_ignore"'
return dict(
head=head,
cellstyle=cellstyle,
body=body,
uuid=uuid,
precision=precision,
table_styles=table_styles,
caption=caption,
table_attributes=table_attr,
)
def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> "Styler":
"""
Format the text display value of cells.
Parameters
----------
formatter : str, callable, dict or None
If ``formatter`` is None, the default formatter is used.
subset : IndexSlice
An argument to ``DataFrame.loc`` that restricts which elements
``formatter`` is applied to.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied.
.. versionadded:: 1.0.0
Returns
-------
self : Styler
Notes
-----
``formatter`` is either an ``a`` or a dict ``{column name: a}`` where
``a`` is one of
- str: this will be wrapped in: ``a.format(x)``
- callable: called with the value of an individual cell
The default display value for numeric values is the "general" (``g``)
format with ``pd.options.display.precision`` precision.
Examples
--------
>>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
>>> df.style.format("{:.2%}")
>>> df['c'] = ['a', 'b', 'c', 'd']
>>> df.style.format({'c': str.upper})
"""
if formatter is None:
assert self._display_funcs.default_factory is not None
formatter = self._display_funcs.default_factory()
if subset is None:
row_locs = range(len(self.data))
col_locs = range(len(self.data.columns))
else:
subset = _non_reducing_slice(subset)
if len(subset) == 1:
subset = subset, self.data.columns
sub_df = self.data.loc[subset]
row_locs = self.data.index.get_indexer_for(sub_df.index)
col_locs = self.data.columns.get_indexer_for(sub_df.columns)
if is_dict_like(formatter):
for col, col_formatter in formatter.items():
# formatter must be callable, so '{}' are converted to lambdas
col_formatter = _maybe_wrap_formatter(col_formatter, na_rep)
col_num = self.data.columns.get_indexer_for([col])[0]
for row_num in row_locs:
self._display_funcs[(row_num, col_num)] = col_formatter
else:
# single scalar to format all cells with
formatter = _maybe_wrap_formatter(formatter, na_rep)
locs = product(*(row_locs, col_locs))
for i, j in locs:
self._display_funcs[(i, j)] = formatter
return self
def render(self, **kwargs) -> str:
"""
Render the built up styles to HTML.
Parameters
----------
**kwargs
Any additional keyword arguments are passed
through to ``self.template.render``.
This is useful when you need to provide
additional variables for a custom template.
Returns
-------
rendered : str
The rendered HTML.
Notes
-----
``Styler`` objects have defined the ``_repr_html_`` method
which automatically calls ``self.render()`` when it's the
last item in a Notebook cell. When calling ``Styler.render()``
directly, wrap the result in ``IPython.display.HTML`` to view
the rendered HTML in the notebook.
Pandas uses the following keys in render. Arguments passed
in ``**kwargs`` take precedence, so think carefully if you want
to override them:
* head
* cellstyle
* body
* uuid
* precision
* table_styles
* caption
* table_attributes
"""
self._compute()
# TODO: namespace all the pandas keys
d = self._translate()
# filter out empty styles, every cell will have a class
# but the list of props may just be [['', '']].
# so we have the nested anys below
trimmed = [x for x in d["cellstyle"] if any(any(y) for y in x["props"])]
d["cellstyle"] = trimmed
d.update(kwargs)
return self.template.render(**d)
def _update_ctx(self, attrs: DataFrame) -> None:
"""
Update the state of the Styler.
Collects a mapping of {index_label: ['<property>: <value>']}.
Parameters
----------
attrs : DataFrame
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter.
"""
for row_label, v in attrs.iterrows():
for col_label, col in v.items():
i = self.index.get_indexer([row_label])[0]
j = self.columns.get_indexer([col_label])[0]
for pair in col.rstrip(";").split(";"):
self.ctx[(i, j)].append(pair)
def _copy(self, deepcopy: bool = False) -> "Styler":
styler = Styler(
self.data,
precision=self.precision,
caption=self.caption,
uuid=self.uuid,
table_styles=self.table_styles,
na_rep=self.na_rep,
)
if deepcopy:
styler.ctx = copy.deepcopy(self.ctx)
styler._todo = copy.deepcopy(self._todo)
else:
styler.ctx = self.ctx
styler._todo = self._todo
return styler
def __copy__(self) -> "Styler":
"""
Deep copy by default.
"""
return self._copy(deepcopy=False)
def __deepcopy__(self, memo) -> "Styler":
return self._copy(deepcopy=True)
def clear(self) -> None:
"""
Reset the styler, removing any previously applied styles.
Returns None.
"""
self.ctx.clear()
self._todo = []
def _compute(self):
"""
Execute the style functions built up in `self._todo`.
Relies on the conventions that all style functions go through
.apply or .applymap. The append styles to apply as tuples of
(application method, *args, **kwargs)
"""
r = self
for func, args, kwargs in self._todo:
r = func(self)(*args, **kwargs)
return r
def _apply(
self,
func: Callable[..., "Styler"],
axis: Optional[Axis] = 0,
subset=None,
**kwargs,
) -> "Styler":
subset = slice(None) if subset is None else subset
subset = _non_reducing_slice(subset)
data = self.data.loc[subset]
if axis is not None:
result = data.apply(func, axis=axis, result_type="expand", **kwargs)
result.columns = data.columns
else:
result = func(data, **kwargs)
if not isinstance(result, pd.DataFrame):
raise TypeError(
f"Function {repr(func)} must return a DataFrame when "
f"passed to `Styler.apply` with axis=None"
)
if not (
result.index.equals(data.index) and result.columns.equals(data.columns)
):
raise ValueError(
f"Result of {repr(func)} must have identical "
f"index and columns as the input"
)
result_shape = result.shape
expected_shape = self.data.loc[subset].shape
if result_shape != expected_shape:
raise ValueError(
f"Function {repr(func)} returned the wrong shape.\n"
f"Result has shape: {result.shape}\n"
f"Expected shape: {expected_shape}"
)
self._update_ctx(result)
return self
def apply(
self,
func: Callable[..., "Styler"],
axis: Optional[Axis] = 0,
subset=None,
**kwargs,
) -> "Styler":
"""
Apply a function column-wise, row-wise, or table-wise.
Updates the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a Series or DataFrame (depending
on ``axis``), and return an object with the same shape.
Must return a DataFrame with identical index and
column labels when ``axis=None``.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``func``.
Returns
-------
self : Styler
Notes
-----
The output shape of ``func`` should match the input, i.e. if
``x`` is the input row, column, or table (depending on ``axis``),
then ``func(x).shape == x.shape`` should be true.
This is similar to ``DataFrame.apply``, except that ``axis=None``
applies the function to the entire DataFrame at once,
rather than column-wise or row-wise.
Examples
--------
>>> def highlight_max(x):
... return ['background-color: yellow' if v == x.max() else ''
for v in x]
...
>>> df = pd.DataFrame(np.random.randn(5, 2))
>>> df.style.apply(highlight_max)
"""
self._todo.append(
(lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs)
)
return self
def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
func = partial(func, **kwargs) # applymap doesn't take kwargs?
if subset is None:
subset = pd.IndexSlice[:]
subset = _non_reducing_slice(subset)
result = self.data.loc[subset].applymap(func)
self._update_ctx(result)
return self
def applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
"""
Apply a function elementwise.
Updates the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a scalar and return a scalar.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``func``.
Returns
-------
self : Styler
See Also
--------
Styler.where
"""
self._todo.append(
(lambda instance: getattr(instance, "_applymap"), (func, subset), kwargs)
)
return self
def where(
self,
cond: Callable,
value: str,
other: Optional[str] = None,
subset=None,
**kwargs,
) -> "Styler":
"""
Apply a function elementwise.
Updates the HTML representation with a style which is
selected in accordance with the return value of a function.
Parameters
----------
cond : callable
``cond`` should take a scalar and return a boolean.
value : str
Applied when ``cond`` returns true.
other : str
Applied when ``cond`` returns false.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``cond``.
Returns
-------
self : Styler
See Also
--------
Styler.applymap
"""
if other is None:
other = ""
return self.applymap(
lambda val: value if cond(val) else other, subset=subset, **kwargs
)
def set_precision(self, precision: int) -> "Styler":
"""
Set the precision used to render.
Parameters
----------
precision : int
Returns
-------
self : Styler
"""
self.precision = precision
return self
def set_table_attributes(self, attributes: str) -> "Styler":
"""
Set the table attributes.
These are the items that show up in the opening ``<table>`` tag
in addition to to automatic (by default) id.
Parameters
----------
attributes : str
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_attributes('class="pure-table"')
# ... <table class="pure-table"> ...
"""
self.table_attributes = attributes
return self
def export(self) -> List[Tuple[Callable, Tuple, Dict]]:
"""
Export the styles to applied to the current Styler.
Can be applied to a second style with ``Styler.use``.
Returns
-------
styles : list
See Also
--------
Styler.use
"""
return self._todo
def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler":
"""
Set the styles on the current Styler.
Possibly uses styles from ``Styler.export``.
Parameters
----------
styles : list
List of style functions.
Returns
-------
self : Styler
See Also
--------
Styler.export
"""
self._todo.extend(styles)
return self
def set_uuid(self, uuid: str) -> "Styler":
"""
Set the uuid for a Styler.
Parameters
----------
uuid : str
Returns
-------
self : Styler
"""
self.uuid = uuid
return self
def set_caption(self, caption: str) -> "Styler":
"""
Set the caption on a Styler.
Parameters
----------
caption : str
Returns
-------
self : Styler
"""
self.caption = caption
return self
def set_table_styles(self, table_styles) -> "Styler":
"""
Set the table styles on a Styler.
These are placed in a ``<style>`` tag before the generated HTML table.
Parameters
----------
table_styles : list
Each individual table_style should be a dictionary with
``selector`` and ``props`` keys. ``selector`` should be a CSS
selector that the style will be applied to (automatically
prefixed by the table's UUID) and ``props`` should be a list of
tuples with ``(attribute, value)``.
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_styles(
... [{'selector': 'tr:hover',
... 'props': [('background-color', 'yellow')]}]
... )
"""
self.table_styles = table_styles
return self
def set_na_rep(self, na_rep: str) -> "Styler":
"""
Set the missing data representation on a Styler.
.. versionadded:: 1.0.0
Parameters
----------
na_rep : str
Returns
-------
self : Styler
"""
self.na_rep = na_rep
return self
def hide_index(self) -> "Styler":
"""
Hide any indices from rendering.
.. versionadded:: 0.23.0
Returns
-------
self : Styler
"""
self.hidden_index = True
return self
def hide_columns(self, subset) -> "Styler":
"""
Hide columns from rendering.
.. versionadded:: 0.23.0
Parameters
----------
subset : IndexSlice
An argument to ``DataFrame.loc`` that identifies which columns
are hidden.
Returns
-------
self : Styler
"""
subset = _non_reducing_slice(subset)
hidden_df = self.data.loc[subset]
self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
return self
# -----------------------------------------------------------------------
# A collection of "builtin" styles
# -----------------------------------------------------------------------
@staticmethod
def _highlight_null(v, null_color: str) -> str:
return f"background-color: {null_color}" if pd.isna(v) else ""
def highlight_null(
self,
null_color: str = "red",
subset: Optional[Union[Label, Sequence[Label]]] = None,
) -> "Styler":
"""
Shade the background ``null_color`` for missing values.
Parameters
----------
null_color : str, default 'red'
subset : label or list of labels, default None
A valid slice for ``data`` to limit the style application to.
.. versionadded:: 1.1.0
Returns
-------
self : Styler
"""
self.applymap(self._highlight_null, null_color=null_color, subset=subset)
return self
def background_gradient(
self,
cmap="PuBu",
low: float = 0,
high: float = 0,
axis: Optional[Axis] = 0,
subset=None,
text_color_threshold: float = 0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> "Styler":
"""
Color the background in a gradient style.
The background color is determined according
to the data in each column (optionally row). Requires matplotlib.
Parameters
----------
cmap : str or colormap
Matplotlib colormap.
low : float
Compress the range by the low.
high : float
Compress the range by the high.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
subset : IndexSlice
A valid slice for ``data`` to limit the style application to.
text_color_threshold : float or int
Luminance threshold for determining text color. Facilitates text
visibility across varying background colors. From 0 to 1.
0 = all text is dark colored, 1 = all text is light colored.
.. versionadded:: 0.24.0
vmin : float, optional
Minimum data value that corresponds to colormap minimum value.
When None (default): the minimum value of the data will be used.
.. versionadded:: 1.0.0
vmax : float, optional
Maximum data value that corresponds to colormap maximum value.
When None (default): the maximum value of the data will be used.
.. versionadded:: 1.0.0
Returns
-------
self : Styler
Raises
------
ValueError
If ``text_color_threshold`` is not a value from 0 to 1.
Notes
-----
Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the
text legible by not using the entire range of the color map. The range
of the data is extended by ``low * (x.max() - x.min())`` and ``high *
(x.max() - x.min())`` before normalizing.
"""
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(
self._background_gradient,
cmap=cmap,
subset=subset,
axis=axis,
low=low,
high=high,
text_color_threshold=text_color_threshold,
vmin=vmin,
vmax=vmax,
)
return self
@staticmethod
def _background_gradient(
s,
cmap="PuBu",
low: float = 0,
high: float = 0,
text_color_threshold: float = 0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
"""
Color background in a range according to the data.
"""
if (
not isinstance(text_color_threshold, (float, int))
or not 0 <= text_color_threshold <= 1
):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)
with _mpl(Styler.background_gradient) as (plt, colors):
smin = np.nanmin(s.to_numpy()) if vmin is None else vmin
smax = np.nanmax(s.to_numpy()) if vmax is None else vmax
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
# matplotlib colors.Normalize modifies inplace?
# https://github.com/matplotlib/matplotlib/issues/5427
rgbas = plt.cm.get_cmap(cmap)(norm(s.to_numpy(dtype=float)))
def relative_luminance(rgba) -> float:
"""
Calculate relative luminance of a color.
The calculation adheres to the W3C standards
(https://www.w3.org/WAI/GL/wiki/Relative_luminance)
Parameters
----------
color : rgb or rgba tuple
Returns
-------
float
The relative luminance as a value from 0 to 1
"""
r, g, b = (
x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
for x in rgba[:3]
)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def css(rgba) -> str:
dark = relative_luminance(rgba) < text_color_threshold
text_color = "#f1f1f1" if dark else "#000000"
return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};"
if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
else:
return pd.DataFrame(
[[css(rgba) for rgba in row] for row in rgbas],
index=s.index,
columns=s.columns,
)
def set_properties(self, subset=None, **kwargs) -> "Styler":
"""
Method to set one or more non-data dependent properties or each cell.
Parameters
----------
subset : IndexSlice
A valid slice for ``data`` to limit the style application to.
**kwargs : dict
A dictionary of property, value pairs to be set for each cell.
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_properties(color="white", align="right")
>>> df.style.set_properties(**{'background-color': 'yellow'})
"""
values = ";".join(f"{p}: {v}" for p, v in kwargs.items())
f = lambda x: values
return self.applymap(f, subset=subset)
@staticmethod
def _bar(
s,
align: str,
colors: List[str],
width: float = 100,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
"""
Draw bar chart in dataframe cells.
"""
# Get input value range.
smin = np.nanmin(s.to_numpy()) if vmin is None else vmin
smax = np.nanmax(s.to_numpy()) if vmax is None else vmax
if align == "mid":
smin = min(0, smin)
smax = max(0, smax)
elif align == "zero":
# For "zero" mode, we want the range to be symmetrical around zero.
smax = max(abs(smin), abs(smax))
smin = -smax
# Transform to percent-range of linear-gradient
normed = width * (s.to_numpy(dtype=float) - smin) / (smax - smin + 1e-12)
zero = -width * smin / (smax - smin + 1e-12)
def css_bar(start: float, end: float, color: str) -> str:
"""
Generate CSS code to draw a bar from start to end.
"""
css = "width: 10em; height: 80%;"
if end > start:
css += "background: linear-gradient(90deg,"
if start > 0:
css += f" transparent {start:.1f}%, {color} {start:.1f}%, "
e = min(end, width)
css += f"{color} {e:.1f}%, transparent {e:.1f}%)"
return css
def css(x):
if pd.isna(x):
return ""
# avoid deprecated indexing `colors[x > zero]`
color = colors[1] if x > zero else colors[0]
if align == "left":
return css_bar(0, x, color)
else:
return css_bar(min(x, zero), max(x, zero), color)
if s.ndim == 1:
return [css(x) for x in normed]
else:
return pd.DataFrame(
[[css(x) for x in row] for row in normed],
index=s.index,
columns=s.columns,
)
def bar(
self,
subset=None,
axis: Optional[Axis] = 0,
color="#d65f5f",
width: float = 100,
align: str = "left",
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> "Styler":
"""
Draw bar chart in the cell backgrounds.
Parameters
----------
subset : IndexSlice, optional
A valid slice for `data` to limit the style application to.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
color : str or 2-tuple/list
If a str is passed, the color is the same for both
negative and positive numbers. If 2-tuple/list is used, the
first element is the color_negative and the second is the
color_positive (eg: ['#d65f5f', '#5fba7d']).
width : float, default 100
A number between 0 or 100. The largest value will cover `width`
percent of the cell's width.
align : {'left', 'zero',' mid'}, default 'left'
How to align the bars with the cells.
- 'left' : the min value starts at the left of the cell.
- 'zero' : a value of zero is located at the center of the cell.
- 'mid' : the center of the cell is at (max-min)/2, or
if values are all negative (positive) the zero is aligned
at the right (left) of the cell.
vmin : float, optional
Minimum bar value, defining the left hand limit
of the bar drawing range, lower values are clipped to `vmin`.
When None (default): the minimum value of the data will be used.
.. versionadded:: 0.24.0
vmax : float, optional
Maximum bar value, defining the right hand limit
of the bar drawing range, higher values are clipped to `vmax`.
When None (default): the maximum value of the data will be used.
.. versionadded:: 0.24.0
Returns
-------
self : Styler
"""
if align not in ("left", "zero", "mid"):
raise ValueError("`align` must be one of {'left', 'zero',' mid'}")
if not (is_list_like(color)):
color = [color, color]
elif len(color) == 1:
color = [color[0], color[0]]
elif len(color) > 2:
raise ValueError(
"`color` must be string or a list-like "
"of length 2: [`color_neg`, `color_pos`] "
"(eg: color=['#d65f5f', '#5fba7d'])"
)
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(
self._bar,
subset=subset,
axis=axis,
align=align,
colors=color,
width=width,
vmin=vmin,
vmax=vmax,
)
return self
def highlight_max(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
) -> "Styler":
"""
Highlight the maximum by shading the background.
Parameters
----------
subset : IndexSlice, default None
A valid slice for ``data`` to limit the style application to.
color : str, default 'yellow'
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
Returns
-------
self : Styler
"""
return self._highlight_handler(subset=subset, color=color, axis=axis, max_=True)
def highlight_min(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
) -> "Styler":
"""
Highlight the minimum by shading the background.
Parameters
----------
subset : IndexSlice, default None
A valid slice for ``data`` to limit the style application to.
color : str, default 'yellow'
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
Returns
-------
self : Styler
"""
return self._highlight_handler(
subset=subset, color=color, axis=axis, max_=False
)
def _highlight_handler(
self,
subset=None,
color: str = "yellow",
axis: Optional[Axis] = None,
max_: bool = True,
) -> "Styler":
subset = _non_reducing_slice(_maybe_numeric_slice(self.data, subset))
self.apply(
self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_
)
return self
@staticmethod
def _highlight_extrema(
data: FrameOrSeries, color: str = "yellow", max_: bool = True
):
"""
Highlight the min or max in a Series or DataFrame.
"""
attr = f"background-color: {color}"
if max_:
extrema = data == np.nanmax(data.to_numpy())
else:
extrema = data == np.nanmin(data.to_numpy())
if data.ndim == 1: # Series from .apply
return [attr if v else "" for v in extrema]
else: # DataFrame from .tee
return pd.DataFrame(
np.where(extrema, attr, ""), index=data.index, columns=data.columns
)
@classmethod
def from_custom_template(cls, searchpath, name):
"""
Factory function for creating a subclass of ``Styler``.
Uses a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates.
name : str
Name of your custom template to use for rendering.
Returns
-------
MyStyler : subclass of Styler
Has the correct ``env`` and ``template`` class attributes set.
"""
loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(searchpath), cls.loader])
class MyStyler(cls):
env = jinja2.Environment(loader=loader)
template = env.get_template(name)
return MyStyler
def pipe(self, func: Callable, *args, **kwargs):
"""
Apply ``func(self, *args, **kwargs)``, and return the result.
.. versionadded:: 0.24.0
Parameters
----------
func : function
Function to apply to the Styler. Alternatively, a
``(callable, keyword)`` tuple where ``keyword`` is a string
indicating the keyword of ``callable`` that expects the Styler.
*args : optional
Arguments passed to `func`.
**kwargs : optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object :
The value returned by ``func``.
See Also
--------
DataFrame.pipe : Analogous method for DataFrame.
Styler.apply : Apply a function row-wise, column-wise, or table-wise to
modify the dataframe's styling.
Notes
-----
Like :meth:`DataFrame.pipe`, this method can simplify the
application of several user-defined functions to a styler. Instead
of writing:
.. code-block:: python
f(g(df.style.set_precision(3), arg1=a), arg2=b, arg3=c)
users can write:
.. code-block:: python
(df.style.set_precision(3)
.pipe(g, arg1=a)
.pipe(f, arg2=b, arg3=c))
In particular, this allows users to define functions that take a
styler object, along with other parameters, and return the styler after
making styling changes (such as calling :meth:`Styler.apply` or
:meth:`Styler.set_properties`). Using ``.pipe``, these user-defined
style "transformations" can be interleaved with calls to the built-in
Styler interface.
Examples
--------
>>> def format_conversion(styler):
... return (styler.set_properties(**{'text-align': 'right'})
... .format({'conversion': '{:.1%}'}))
The user-defined ``format_conversion`` function above can be called
within a sequence of other style modifications:
>>> df = pd.DataFrame({'trial': list(range(5)),
... 'conversion': [0.75, 0.85, np.nan, 0.7, 0.72]})
>>> (df.style
... .highlight_min(subset=['conversion'], color='yellow')
... .pipe(format_conversion)
... .set_caption("Results with minimum conversion highlighted."))
"""
return com.pipe(self, func, *args, **kwargs)
def _is_visible(idx_row, idx_col, lengths) -> bool:
"""
Index -> {(idx_row, idx_col): bool}).
"""
return (idx_col, idx_row) in lengths
def _get_level_lengths(index, hidden_elements=None):
"""
Given an index, find the level length for each element.
Optional argument is a list of index positions which
should not be visible.
Result is a dictionary of (level, initial_position): span
"""
levels = index.format(sparsify=lib.no_default, adjoin=False, names=False)
if hidden_elements is None:
hidden_elements = []
lengths = {}
if index.nlevels == 1:
for i, value in enumerate(levels):
if i not in hidden_elements:
lengths[(0, i)] = 1
return lengths
for i, lvl in enumerate(levels):
for j, row in enumerate(lvl):
if not get_option("display.multi_sparse"):
lengths[(i, j)] = 1
elif (row is not lib.no_default) and (j not in hidden_elements):
last_label = j
lengths[(i, last_label)] = 1
elif row is not lib.no_default:
# even if its hidden, keep track of it in case
# length >1 and later elements are visible
last_label = j
lengths[(i, last_label)] = 0
elif j not in hidden_elements:
lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1
}
return non_zero_lengths
def _maybe_wrap_formatter(
formatter: Union[Callable, str], na_rep: Optional[str]
) -> Callable:
if isinstance(formatter, str):
formatter_func = lambda x: formatter.format(x)
elif callable(formatter):
formatter_func = formatter
else:
msg = f"Expected a template string or callable, got {formatter} instead"
raise TypeError(msg)
if na_rep is None:
return formatter_func
elif isinstance(na_rep, str):
return lambda x: na_rep if pd.isna(x) else formatter_func(x)
else:
msg = f"Expected a string, got {na_rep} instead"
raise TypeError(msg)
| """
Module for applying conditional formatting to DataFrames and Series.
"""
from collections import defaultdict
from contextlib import contextmanager
import copy
from functools import partial
from itertools import product
from typing import (
Any,
Callable,
DefaultDict,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
)
from uuid import uuid1
import numpy as np
from pandas._config import get_option
from pandas._libs import lib
from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, Label
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
from pandas.core.dtypes.common import is_float
import pandas as pd
from pandas.api.types import is_dict_like, is_list_like
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame
from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice
jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
try:
import matplotlib.pyplot as plt
from matplotlib import colors
has_mpl = True
except ImportError:
has_mpl = False
no_mpl_message = "{0} requires matplotlib."
@contextmanager
def _mpl(func: Callable):
if has_mpl:
yield plt, colors
else:
raise ImportError(no_mpl_message.format(func.__name__))
class Styler:
"""
Helps style a DataFrame or Series according to the data with HTML and CSS.
Parameters
----------
data : Series or DataFrame
Data to be styled - either a Series or DataFrame.
precision : int
Precision to round floats to, defaults to pd.options.display.precision.
table_styles : list-like, default None
List of {selector: (attr, value)} dicts; see Notes.
uuid : str, default None
A unique identifier to avoid CSS collisions; generated automatically.
caption : str, default None
Caption to attach to the table.
table_attributes : str, default None
Items that show up in the opening ``<table>`` tag
in addition to automatic (by default) id.
cell_ids : bool, default True
If True, each cell will have an ``id`` attribute in their HTML tag.
The ``id`` takes the form ``T_<uuid>_row<num_row>_col<num_col>``
where ``<uuid>`` is the unique identifier, ``<num_row>`` is the row
number and ``<num_col>`` is the column number.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied.
.. versionadded:: 1.0.0
Attributes
----------
env : Jinja2 jinja2.Environment
template : Jinja2 Template
loader : Jinja2 Loader
See Also
--------
DataFrame.style : Return a Styler object containing methods for building
a styled HTML representation for the DataFrame.
Notes
-----
Most styling will be done by passing style functions into
``Styler.apply`` or ``Styler.applymap``. Style functions should
return values with strings containing CSS ``'attr: value'`` that will
be applied to the indicated cells.
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
to automatically render itself. Otherwise call Styler.render to get
the generated HTML.
CSS classes are attached to the generated HTML
* Index and Column names include ``index_name`` and ``level<k>``
where `k` is its level in a MultiIndex
* Index label cells include
* ``row_heading``
* ``row<n>`` where `n` is the numeric position of the row
* ``level<k>`` where `k` is the level in a MultiIndex
* Column label cells include
* ``col_heading``
* ``col<n>`` where `n` is the numeric position of the column
* ``level<k>`` where `k` is the level in a MultiIndex
* Blank cells include ``blank``
* Data cells include ``data``
"""
loader = jinja2.PackageLoader("pandas", "io/formats/templates")
env = jinja2.Environment(loader=loader, trim_blocks=True)
template = env.get_template("html.tpl")
def __init__(
self,
data: FrameOrSeriesUnion,
precision: Optional[int] = None,
table_styles: Optional[List[Dict[str, List[Tuple[str, str]]]]] = None,
uuid: Optional[str] = None,
caption: Optional[str] = None,
table_attributes: Optional[str] = None,
cell_ids: bool = True,
na_rep: Optional[str] = None,
):
self.ctx: DefaultDict[Tuple[int, int], List[str]] = defaultdict(list)
self._todo: List[Tuple[Callable, Tuple, Dict]] = []
if not isinstance(data, (pd.Series, pd.DataFrame)):
raise TypeError("``data`` must be a Series or DataFrame")
if data.ndim == 1:
data = data.to_frame()
if not data.index.is_unique or not data.columns.is_unique:
raise ValueError("style is not supported for non-unique indices.")
self.data = data
self.index = data.index
self.columns = data.columns
self.uuid = uuid
self.table_styles = table_styles
self.caption = caption
if precision is None:
precision = get_option("display.precision")
self.precision = precision
self.table_attributes = table_attributes
self.hidden_index = False
self.hidden_columns: Sequence[int] = []
self.cell_ids = cell_ids
self.na_rep = na_rep
# display_funcs maps (row, col) -> formatting function
def default_display_func(x):
if self.na_rep is not None and pd.isna(x):
return self.na_rep
elif is_float(x):
display_format = f"{x:.{self.precision}f}"
return display_format
else:
return x
self._display_funcs: DefaultDict[
Tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: default_display_func)
def _repr_html_(self) -> str:
"""
Hooks into Jupyter notebook rich display system.
"""
return self.render()
@doc(NDFrame.to_excel, klass="Styler")
def to_excel(
self,
excel_writer,
sheet_name: str = "Sheet1",
na_rep: str = "",
float_format: Optional[str] = None,
columns: Optional[Sequence[Label]] = None,
header: Union[Sequence[Label], bool] = True,
index: bool = True,
index_label: Optional[Union[Label, Sequence[Label]]] = None,
startrow: int = 0,
startcol: int = 0,
engine: Optional[str] = None,
merge_cells: bool = True,
encoding: Optional[str] = None,
inf_rep: str = "inf",
verbose: bool = True,
freeze_panes: Optional[Tuple[int, int]] = None,
) -> None:
from pandas.io.formats.excel import ExcelFormatter
formatter = ExcelFormatter(
self,
na_rep=na_rep,
cols=columns,
header=header,
float_format=float_format,
index=index,
index_label=index_label,
merge_cells=merge_cells,
inf_rep=inf_rep,
)
formatter.write(
excel_writer,
sheet_name=sheet_name,
startrow=startrow,
startcol=startcol,
freeze_panes=freeze_panes,
engine=engine,
)
def _translate(self):
"""
Convert the DataFrame in `self.data` and the attrs from `_build_styles`
into a dictionary of {head, body, uuid, cellstyle}.
"""
table_styles = self.table_styles or []
caption = self.caption
ctx = self.ctx
precision = self.precision
hidden_index = self.hidden_index
hidden_columns = self.hidden_columns
uuid = self.uuid or str(uuid1()).replace("-", "_")
ROW_HEADING_CLASS = "row_heading"
COL_HEADING_CLASS = "col_heading"
INDEX_NAME_CLASS = "index_name"
DATA_CLASS = "data"
BLANK_CLASS = "blank"
BLANK_VALUE = ""
def format_attr(pair):
return f"{pair['key']}={pair['value']}"
# for sparsifying a MultiIndex
idx_lengths = _get_level_lengths(self.index)
col_lengths = _get_level_lengths(self.columns, hidden_columns)
cell_context = dict()
n_rlvls = self.data.index.nlevels
n_clvls = self.data.columns.nlevels
rlabels = self.data.index.tolist()
clabels = self.data.columns.tolist()
if n_rlvls == 1:
rlabels = [[x] for x in rlabels]
if n_clvls == 1:
clabels = [[x] for x in clabels]
clabels = list(zip(*clabels))
cellstyle_map = defaultdict(list)
head = []
for r in range(n_clvls):
# Blank for Index columns...
row_es = [
{
"type": "th",
"value": BLANK_VALUE,
"display_value": BLANK_VALUE,
"is_visible": not hidden_index,
"class": " ".join([BLANK_CLASS]),
}
] * (n_rlvls - 1)
# ... except maybe the last for columns.names
name = self.data.columns.names[r]
cs = [
BLANK_CLASS if name is None else INDEX_NAME_CLASS,
f"level{r}",
]
name = BLANK_VALUE if name is None else name
row_es.append(
{
"type": "th",
"value": name,
"display_value": name,
"class": " ".join(cs),
"is_visible": not hidden_index,
}
)
if clabels:
for c, value in enumerate(clabels[r]):
cs = [
COL_HEADING_CLASS,
f"level{r}",
f"col{c}",
]
cs.extend(
cell_context.get("col_headings", {}).get(r, {}).get(c, [])
)
es = {
"type": "th",
"value": value,
"display_value": value,
"class": " ".join(cs),
"is_visible": _is_visible(c, r, col_lengths),
}
colspan = col_lengths.get((r, c), 0)
if colspan > 1:
es["attributes"] = [
format_attr({"key": "colspan", "value": colspan})
]
row_es.append(es)
head.append(row_es)
if (
self.data.index.names
and com.any_not_none(*self.data.index.names)
and not hidden_index
):
index_header_row = []
for c, name in enumerate(self.data.index.names):
cs = [INDEX_NAME_CLASS, f"level{c}"]
name = "" if name is None else name
index_header_row.append(
{"type": "th", "value": name, "class": " ".join(cs)}
)
index_header_row.extend(
[{"type": "th", "value": BLANK_VALUE, "class": " ".join([BLANK_CLASS])}]
* (len(clabels[0]) - len(hidden_columns))
)
head.append(index_header_row)
body = []
for r, idx in enumerate(self.data.index):
row_es = []
for c, value in enumerate(rlabels[r]):
rid = [
ROW_HEADING_CLASS,
f"level{c}",
f"row{r}",
]
es = {
"type": "th",
"is_visible": (_is_visible(r, c, idx_lengths) and not hidden_index),
"value": value,
"display_value": value,
"id": "_".join(rid[1:]),
"class": " ".join(rid),
}
rowspan = idx_lengths.get((c, r), 0)
if rowspan > 1:
es["attributes"] = [
format_attr({"key": "rowspan", "value": rowspan})
]
row_es.append(es)
for c, col in enumerate(self.data.columns):
cs = [DATA_CLASS, f"row{r}", f"col{c}"]
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
formatter = self._display_funcs[(r, c)]
value = self.data.iloc[r, c]
row_dict = {
"type": "td",
"value": value,
"class": " ".join(cs),
"display_value": formatter(value),
"is_visible": (c not in hidden_columns),
}
# only add an id if the cell has a style
if self.cell_ids or not (len(ctx[r, c]) == 1 and ctx[r, c][0] == ""):
row_dict["id"] = "_".join(cs[1:])
row_es.append(row_dict)
props = []
for x in ctx[r, c]:
# have to handle empty styles like ['']
if x.count(":"):
props.append(tuple(x.split(":")))
else:
props.append(("", ""))
cellstyle_map[tuple(props)].append(f"row{r}_col{c}")
body.append(row_es)
cellstyle = [
{"props": list(props), "selectors": selectors}
for props, selectors in cellstyle_map.items()
]
table_attr = self.table_attributes
use_mathjax = get_option("display.html.use_mathjax")
if not use_mathjax:
table_attr = table_attr or ""
if 'class="' in table_attr:
table_attr = table_attr.replace('class="', 'class="tex2jax_ignore ')
else:
table_attr += ' class="tex2jax_ignore"'
return dict(
head=head,
cellstyle=cellstyle,
body=body,
uuid=uuid,
precision=precision,
table_styles=table_styles,
caption=caption,
table_attributes=table_attr,
)
def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> "Styler":
"""
Format the text display value of cells.
Parameters
----------
formatter : str, callable, dict or None
If ``formatter`` is None, the default formatter is used.
subset : IndexSlice
An argument to ``DataFrame.loc`` that restricts which elements
``formatter`` is applied to.
na_rep : str, optional
Representation for missing values.
If ``na_rep`` is None, no special formatting is applied.
.. versionadded:: 1.0.0
Returns
-------
self : Styler
Notes
-----
``formatter`` is either an ``a`` or a dict ``{column name: a}`` where
``a`` is one of
- str: this will be wrapped in: ``a.format(x)``
- callable: called with the value of an individual cell
The default display value for numeric values is the "general" (``g``)
format with ``pd.options.display.precision`` precision.
Examples
--------
>>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])
>>> df.style.format("{:.2%}")
>>> df['c'] = ['a', 'b', 'c', 'd']
>>> df.style.format({'c': str.upper})
"""
if formatter is None:
assert self._display_funcs.default_factory is not None
formatter = self._display_funcs.default_factory()
if subset is None:
row_locs = range(len(self.data))
col_locs = range(len(self.data.columns))
else:
subset = _non_reducing_slice(subset)
if len(subset) == 1:
subset = subset, self.data.columns
sub_df = self.data.loc[subset]
row_locs = self.data.index.get_indexer_for(sub_df.index)
col_locs = self.data.columns.get_indexer_for(sub_df.columns)
if is_dict_like(formatter):
for col, col_formatter in formatter.items():
# formatter must be callable, so '{}' are converted to lambdas
col_formatter = _maybe_wrap_formatter(col_formatter, na_rep)
col_num = self.data.columns.get_indexer_for([col])[0]
for row_num in row_locs:
self._display_funcs[(row_num, col_num)] = col_formatter
else:
# single scalar to format all cells with
formatter = _maybe_wrap_formatter(formatter, na_rep)
locs = product(*(row_locs, col_locs))
for i, j in locs:
self._display_funcs[(i, j)] = formatter
return self
def render(self, **kwargs) -> str:
"""
Render the built up styles to HTML.
Parameters
----------
**kwargs
Any additional keyword arguments are passed
through to ``self.template.render``.
This is useful when you need to provide
additional variables for a custom template.
Returns
-------
rendered : str
The rendered HTML.
Notes
-----
``Styler`` objects have defined the ``_repr_html_`` method
which automatically calls ``self.render()`` when it's the
last item in a Notebook cell. When calling ``Styler.render()``
directly, wrap the result in ``IPython.display.HTML`` to view
the rendered HTML in the notebook.
Pandas uses the following keys in render. Arguments passed
in ``**kwargs`` take precedence, so think carefully if you want
to override them:
* head
* cellstyle
* body
* uuid
* precision
* table_styles
* caption
* table_attributes
"""
self._compute()
# TODO: namespace all the pandas keys
d = self._translate()
# filter out empty styles, every cell will have a class
# but the list of props may just be [['', '']].
# so we have the nested anys below
trimmed = [x for x in d["cellstyle"] if any(any(y) for y in x["props"])]
d["cellstyle"] = trimmed
d.update(kwargs)
return self.template.render(**d)
def _update_ctx(self, attrs: DataFrame) -> None:
"""
Update the state of the Styler.
Collects a mapping of {index_label: ['<property>: <value>']}.
Parameters
----------
attrs : DataFrame
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter.
"""
for row_label, v in attrs.iterrows():
for col_label, col in v.items():
i = self.index.get_indexer([row_label])[0]
j = self.columns.get_indexer([col_label])[0]
for pair in col.rstrip(";").split(";"):
self.ctx[(i, j)].append(pair)
def _copy(self, deepcopy: bool = False) -> "Styler":
styler = Styler(
self.data,
precision=self.precision,
caption=self.caption,
uuid=self.uuid,
table_styles=self.table_styles,
na_rep=self.na_rep,
)
if deepcopy:
styler.ctx = copy.deepcopy(self.ctx)
styler._todo = copy.deepcopy(self._todo)
else:
styler.ctx = self.ctx
styler._todo = self._todo
return styler
def __copy__(self) -> "Styler":
"""
Deep copy by default.
"""
return self._copy(deepcopy=False)
def __deepcopy__(self, memo) -> "Styler":
return self._copy(deepcopy=True)
def clear(self) -> None:
"""
Reset the styler, removing any previously applied styles.
Returns None.
"""
self.ctx.clear()
self._todo = []
def _compute(self):
"""
Execute the style functions built up in `self._todo`.
Relies on the conventions that all style functions go through
.apply or .applymap. The append styles to apply as tuples of
(application method, *args, **kwargs)
"""
r = self
for func, args, kwargs in self._todo:
r = func(self)(*args, **kwargs)
return r
def _apply(
self,
func: Callable[..., "Styler"],
axis: Optional[Axis] = 0,
subset=None,
**kwargs,
) -> "Styler":
subset = slice(None) if subset is None else subset
subset = _non_reducing_slice(subset)
data = self.data.loc[subset]
if axis is not None:
result = data.apply(func, axis=axis, result_type="expand", **kwargs)
result.columns = data.columns
else:
result = func(data, **kwargs)
if not isinstance(result, pd.DataFrame):
raise TypeError(
f"Function {repr(func)} must return a DataFrame when "
f"passed to `Styler.apply` with axis=None"
)
if not (
result.index.equals(data.index) and result.columns.equals(data.columns)
):
raise ValueError(
f"Result of {repr(func)} must have identical "
f"index and columns as the input"
)
result_shape = result.shape
expected_shape = self.data.loc[subset].shape
if result_shape != expected_shape:
raise ValueError(
f"Function {repr(func)} returned the wrong shape.\n"
f"Result has shape: {result.shape}\n"
f"Expected shape: {expected_shape}"
)
self._update_ctx(result)
return self
def apply(
self,
func: Callable[..., "Styler"],
axis: Optional[Axis] = 0,
subset=None,
**kwargs,
) -> "Styler":
"""
Apply a function column-wise, row-wise, or table-wise.
Updates the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a Series or DataFrame (depending
on ``axis``), and return an object with the same shape.
Must return a DataFrame with identical index and
column labels when ``axis=None``.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``func``.
Returns
-------
self : Styler
Notes
-----
The output shape of ``func`` should match the input, i.e. if
``x`` is the input row, column, or table (depending on ``axis``),
then ``func(x).shape == x.shape`` should be true.
This is similar to ``DataFrame.apply``, except that ``axis=None``
applies the function to the entire DataFrame at once,
rather than column-wise or row-wise.
Examples
--------
>>> def highlight_max(x):
... return ['background-color: yellow' if v == x.max() else ''
for v in x]
...
>>> df = pd.DataFrame(np.random.randn(5, 2))
>>> df.style.apply(highlight_max)
"""
self._todo.append(
(lambda instance: getattr(instance, "_apply"), (func, axis, subset), kwargs)
)
return self
def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
func = partial(func, **kwargs) # applymap doesn't take kwargs?
if subset is None:
subset = pd.IndexSlice[:]
subset = _non_reducing_slice(subset)
result = self.data.loc[subset].applymap(func)
self._update_ctx(result)
return self
def applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
"""
Apply a function elementwise.
Updates the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a scalar and return a scalar.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``func``.
Returns
-------
self : Styler
See Also
--------
Styler.where
"""
self._todo.append(
(lambda instance: getattr(instance, "_applymap"), (func, subset), kwargs)
)
return self
def where(
self,
cond: Callable,
value: str,
other: Optional[str] = None,
subset=None,
**kwargs,
) -> "Styler":
"""
Apply a function elementwise.
Updates the HTML representation with a style which is
selected in accordance with the return value of a function.
Parameters
----------
cond : callable
``cond`` should take a scalar and return a boolean.
value : str
Applied when ``cond`` returns true.
other : str
Applied when ``cond`` returns false.
subset : IndexSlice
A valid indexer to limit ``data`` to *before* applying the
function. Consider using a pandas.IndexSlice.
**kwargs : dict
Pass along to ``cond``.
Returns
-------
self : Styler
See Also
--------
Styler.applymap
"""
if other is None:
other = ""
return self.applymap(
lambda val: value if cond(val) else other, subset=subset, **kwargs
)
def set_precision(self, precision: int) -> "Styler":
"""
Set the precision used to render.
Parameters
----------
precision : int
Returns
-------
self : Styler
"""
self.precision = precision
return self
def set_table_attributes(self, attributes: str) -> "Styler":
"""
Set the table attributes.
These are the items that show up in the opening ``<table>`` tag
in addition to to automatic (by default) id.
Parameters
----------
attributes : str
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_attributes('class="pure-table"')
# ... <table class="pure-table"> ...
"""
self.table_attributes = attributes
return self
def export(self) -> List[Tuple[Callable, Tuple, Dict]]:
"""
Export the styles to applied to the current Styler.
Can be applied to a second style with ``Styler.use``.
Returns
-------
styles : list
See Also
--------
Styler.use
"""
return self._todo
def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler":
"""
Set the styles on the current Styler.
Possibly uses styles from ``Styler.export``.
Parameters
----------
styles : list
List of style functions.
Returns
-------
self : Styler
See Also
--------
Styler.export
"""
self._todo.extend(styles)
return self
def set_uuid(self, uuid: str) -> "Styler":
"""
Set the uuid for a Styler.
Parameters
----------
uuid : str
Returns
-------
self : Styler
"""
self.uuid = uuid
return self
def set_caption(self, caption: str) -> "Styler":
"""
Set the caption on a Styler.
Parameters
----------
caption : str
Returns
-------
self : Styler
"""
self.caption = caption
return self
def set_table_styles(self, table_styles) -> "Styler":
"""
Set the table styles on a Styler.
These are placed in a ``<style>`` tag before the generated HTML table.
Parameters
----------
table_styles : list
Each individual table_style should be a dictionary with
``selector`` and ``props`` keys. ``selector`` should be a CSS
selector that the style will be applied to (automatically
prefixed by the table's UUID) and ``props`` should be a list of
tuples with ``(attribute, value)``.
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_styles(
... [{'selector': 'tr:hover',
... 'props': [('background-color', 'yellow')]}]
... )
"""
self.table_styles = table_styles
return self
def set_na_rep(self, na_rep: str) -> "Styler":
"""
Set the missing data representation on a Styler.
.. versionadded:: 1.0.0
Parameters
----------
na_rep : str
Returns
-------
self : Styler
"""
self.na_rep = na_rep
return self
def hide_index(self) -> "Styler":
"""
Hide any indices from rendering.
.. versionadded:: 0.23.0
Returns
-------
self : Styler
"""
self.hidden_index = True
return self
def hide_columns(self, subset) -> "Styler":
"""
Hide columns from rendering.
.. versionadded:: 0.23.0
Parameters
----------
subset : IndexSlice
An argument to ``DataFrame.loc`` that identifies which columns
are hidden.
Returns
-------
self : Styler
"""
subset = _non_reducing_slice(subset)
hidden_df = self.data.loc[subset]
self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
return self
# -----------------------------------------------------------------------
# A collection of "builtin" styles
# -----------------------------------------------------------------------
@staticmethod
def _highlight_null(v, null_color: str) -> str:
return f"background-color: {null_color}" if pd.isna(v) else ""
def highlight_null(
self,
null_color: str = "red",
subset: Optional[Union[Label, Sequence[Label]]] = None,
) -> "Styler":
"""
Shade the background ``null_color`` for missing values.
Parameters
----------
null_color : str, default 'red'
subset : label or list of labels, default None
A valid slice for ``data`` to limit the style application to.
.. versionadded:: 1.1.0
Returns
-------
self : Styler
"""
self.applymap(self._highlight_null, null_color=null_color, subset=subset)
return self
def background_gradient(
self,
cmap="PuBu",
low: float = 0,
high: float = 0,
axis: Optional[Axis] = 0,
subset=None,
text_color_threshold: float = 0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> "Styler":
"""
Color the background in a gradient style.
The background color is determined according
to the data in each column (optionally row). Requires matplotlib.
Parameters
----------
cmap : str or colormap
Matplotlib colormap.
low : float
Compress the range by the low.
high : float
Compress the range by the high.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
subset : IndexSlice
A valid slice for ``data`` to limit the style application to.
text_color_threshold : float or int
Luminance threshold for determining text color. Facilitates text
visibility across varying background colors. From 0 to 1.
0 = all text is dark colored, 1 = all text is light colored.
.. versionadded:: 0.24.0
vmin : float, optional
Minimum data value that corresponds to colormap minimum value.
When None (default): the minimum value of the data will be used.
.. versionadded:: 1.0.0
vmax : float, optional
Maximum data value that corresponds to colormap maximum value.
When None (default): the maximum value of the data will be used.
.. versionadded:: 1.0.0
Returns
-------
self : Styler
Raises
------
ValueError
If ``text_color_threshold`` is not a value from 0 to 1.
Notes
-----
Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the
text legible by not using the entire range of the color map. The range
of the data is extended by ``low * (x.max() - x.min())`` and ``high *
(x.max() - x.min())`` before normalizing.
"""
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(
self._background_gradient,
cmap=cmap,
subset=subset,
axis=axis,
low=low,
high=high,
text_color_threshold=text_color_threshold,
vmin=vmin,
vmax=vmax,
)
return self
@staticmethod
def _background_gradient(
s,
cmap="PuBu",
low: float = 0,
high: float = 0,
text_color_threshold: float = 0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
"""
Color background in a range according to the data.
"""
if (
not isinstance(text_color_threshold, (float, int))
or not 0 <= text_color_threshold <= 1
):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)
with _mpl(Styler.background_gradient) as (plt, colors):
smin = np.nanmin(s.to_numpy()) if vmin is None else vmin
smax = np.nanmax(s.to_numpy()) if vmax is None else vmax
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
# matplotlib colors.Normalize modifies inplace?
# https://github.com/matplotlib/matplotlib/issues/5427
rgbas = plt.cm.get_cmap(cmap)(norm(s.to_numpy(dtype=float)))
def relative_luminance(rgba) -> float:
"""
Calculate relative luminance of a color.
The calculation adheres to the W3C standards
(https://www.w3.org/WAI/GL/wiki/Relative_luminance)
Parameters
----------
color : rgb or rgba tuple
Returns
-------
float
The relative luminance as a value from 0 to 1
"""
r, g, b = (
x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
for x in rgba[:3]
)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def css(rgba) -> str:
dark = relative_luminance(rgba) < text_color_threshold
text_color = "#f1f1f1" if dark else "#000000"
return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};"
if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
else:
return pd.DataFrame(
[[css(rgba) for rgba in row] for row in rgbas],
index=s.index,
columns=s.columns,
)
def set_properties(self, subset=None, **kwargs) -> "Styler":
"""
Method to set one or more non-data dependent properties or each cell.
Parameters
----------
subset : IndexSlice
A valid slice for ``data`` to limit the style application to.
**kwargs : dict
A dictionary of property, value pairs to be set for each cell.
Returns
-------
self : Styler
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_properties(color="white", align="right")
>>> df.style.set_properties(**{'background-color': 'yellow'})
"""
values = ";".join(f"{p}: {v}" for p, v in kwargs.items())
f = lambda x: values
return self.applymap(f, subset=subset)
@staticmethod
def _bar(
s,
align: str,
colors: List[str],
width: float = 100,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
"""
Draw bar chart in dataframe cells.
"""
# Get input value range.
smin = np.nanmin(s.to_numpy()) if vmin is None else vmin
smax = np.nanmax(s.to_numpy()) if vmax is None else vmax
if align == "mid":
smin = min(0, smin)
smax = max(0, smax)
elif align == "zero":
# For "zero" mode, we want the range to be symmetrical around zero.
smax = max(abs(smin), abs(smax))
smin = -smax
# Transform to percent-range of linear-gradient
normed = width * (s.to_numpy(dtype=float) - smin) / (smax - smin + 1e-12)
zero = -width * smin / (smax - smin + 1e-12)
def css_bar(start: float, end: float, color: str) -> str:
"""
Generate CSS code to draw a bar from start to end.
"""
css = "width: 10em; height: 80%;"
if end > start:
css += "background: linear-gradient(90deg,"
if start > 0:
css += f" transparent {start:.1f}%, {color} {start:.1f}%, "
e = min(end, width)
css += f"{color} {e:.1f}%, transparent {e:.1f}%)"
return css
def css(x):
if pd.isna(x):
return ""
# avoid deprecated indexing `colors[x > zero]`
color = colors[1] if x > zero else colors[0]
if align == "left":
return css_bar(0, x, color)
else:
return css_bar(min(x, zero), max(x, zero), color)
if s.ndim == 1:
return [css(x) for x in normed]
else:
return pd.DataFrame(
[[css(x) for x in row] for row in normed],
index=s.index,
columns=s.columns,
)
def bar(
self,
subset=None,
axis: Optional[Axis] = 0,
color="#d65f5f",
width: float = 100,
align: str = "left",
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> "Styler":
"""
Draw bar chart in the cell backgrounds.
Parameters
----------
subset : IndexSlice, optional
A valid slice for `data` to limit the style application to.
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
color : str or 2-tuple/list
If a str is passed, the color is the same for both
negative and positive numbers. If 2-tuple/list is used, the
first element is the color_negative and the second is the
color_positive (eg: ['#d65f5f', '#5fba7d']).
width : float, default 100
A number between 0 or 100. The largest value will cover `width`
percent of the cell's width.
align : {'left', 'zero',' mid'}, default 'left'
How to align the bars with the cells.
- 'left' : the min value starts at the left of the cell.
- 'zero' : a value of zero is located at the center of the cell.
- 'mid' : the center of the cell is at (max-min)/2, or
if values are all negative (positive) the zero is aligned
at the right (left) of the cell.
vmin : float, optional
Minimum bar value, defining the left hand limit
of the bar drawing range, lower values are clipped to `vmin`.
When None (default): the minimum value of the data will be used.
.. versionadded:: 0.24.0
vmax : float, optional
Maximum bar value, defining the right hand limit
of the bar drawing range, higher values are clipped to `vmax`.
When None (default): the maximum value of the data will be used.
.. versionadded:: 0.24.0
Returns
-------
self : Styler
"""
if align not in ("left", "zero", "mid"):
raise ValueError("`align` must be one of {'left', 'zero',' mid'}")
if not (is_list_like(color)):
color = [color, color]
elif len(color) == 1:
color = [color[0], color[0]]
elif len(color) > 2:
raise ValueError(
"`color` must be string or a list-like "
"of length 2: [`color_neg`, `color_pos`] "
"(eg: color=['#d65f5f', '#5fba7d'])"
)
subset = _maybe_numeric_slice(self.data, subset)
subset = _non_reducing_slice(subset)
self.apply(
self._bar,
subset=subset,
axis=axis,
align=align,
colors=color,
width=width,
vmin=vmin,
vmax=vmax,
)
return self
def highlight_max(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
) -> "Styler":
"""
Highlight the maximum by shading the background.
Parameters
----------
subset : IndexSlice, default None
A valid slice for ``data`` to limit the style application to.
color : str, default 'yellow'
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
Returns
-------
self : Styler
"""
return self._highlight_handler(subset=subset, color=color, axis=axis, max_=True)
def highlight_min(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
) -> "Styler":
"""
Highlight the minimum by shading the background.
Parameters
----------
subset : IndexSlice, default None
A valid slice for ``data`` to limit the style application to.
color : str, default 'yellow'
axis : {0 or 'index', 1 or 'columns', None}, default 0
Apply to each column (``axis=0`` or ``'index'``), to each row
(``axis=1`` or ``'columns'``), or to the entire DataFrame at once
with ``axis=None``.
Returns
-------
self : Styler
"""
return self._highlight_handler(
subset=subset, color=color, axis=axis, max_=False
)
def _highlight_handler(
self,
subset=None,
color: str = "yellow",
axis: Optional[Axis] = None,
max_: bool = True,
) -> "Styler":
subset = _non_reducing_slice(_maybe_numeric_slice(self.data, subset))
self.apply(
self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_
)
return self
@staticmethod
def _highlight_extrema(
data: FrameOrSeries, color: str = "yellow", max_: bool = True
):
"""
Highlight the min or max in a Series or DataFrame.
"""
attr = f"background-color: {color}"
if max_:
extrema = data == np.nanmax(data.to_numpy())
else:
extrema = data == np.nanmin(data.to_numpy())
if data.ndim == 1: # Series from .apply
return [attr if v else "" for v in extrema]
else: # DataFrame from .tee
return pd.DataFrame(
np.where(extrema, attr, ""), index=data.index, columns=data.columns
)
@classmethod
def from_custom_template(cls, searchpath, name):
"""
Factory function for creating a subclass of ``Styler``.
Uses a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates.
name : str
Name of your custom template to use for rendering.
Returns
-------
MyStyler : subclass of Styler
Has the correct ``env`` and ``template`` class attributes set.
"""
loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(searchpath), cls.loader])
class MyStyler(cls):
env = jinja2.Environment(loader=loader)
template = env.get_template(name)
return MyStyler
def pipe(self, func: Callable, *args, **kwargs):
"""
Apply ``func(self, *args, **kwargs)``, and return the result.
.. versionadded:: 0.24.0
Parameters
----------
func : function
Function to apply to the Styler. Alternatively, a
``(callable, keyword)`` tuple where ``keyword`` is a string
indicating the keyword of ``callable`` that expects the Styler.
*args : optional
Arguments passed to `func`.
**kwargs : optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object :
The value returned by ``func``.
See Also
--------
DataFrame.pipe : Analogous method for DataFrame.
Styler.apply : Apply a function row-wise, column-wise, or table-wise to
modify the dataframe's styling.
Notes
-----
Like :meth:`DataFrame.pipe`, this method can simplify the
application of several user-defined functions to a styler. Instead
of writing:
.. code-block:: python
f(g(df.style.set_precision(3), arg1=a), arg2=b, arg3=c)
users can write:
.. code-block:: python
(df.style.set_precision(3)
.pipe(g, arg1=a)
.pipe(f, arg2=b, arg3=c))
In particular, this allows users to define functions that take a
styler object, along with other parameters, and return the styler after
making styling changes (such as calling :meth:`Styler.apply` or
:meth:`Styler.set_properties`). Using ``.pipe``, these user-defined
style "transformations" can be interleaved with calls to the built-in
Styler interface.
Examples
--------
>>> def format_conversion(styler):
... return (styler.set_properties(**{'text-align': 'right'})
... .format({'conversion': '{:.1%}'}))
The user-defined ``format_conversion`` function above can be called
within a sequence of other style modifications:
>>> df = pd.DataFrame({'trial': list(range(5)),
... 'conversion': [0.75, 0.85, np.nan, 0.7, 0.72]})
>>> (df.style
... .highlight_min(subset=['conversion'], color='yellow')
... .pipe(format_conversion)
... .set_caption("Results with minimum conversion highlighted."))
"""
return com.pipe(self, func, *args, **kwargs)
def _is_visible(idx_row, idx_col, lengths) -> bool:
"""
Index -> {(idx_row, idx_col): bool}).
"""
return (idx_col, idx_row) in lengths
def _get_level_lengths(index, hidden_elements=None):
"""
Given an index, find the level length for each element.
Optional argument is a list of index positions which
should not be visible.
Result is a dictionary of (level, initial_position): span
"""
levels = index.format(sparsify=lib.no_default, adjoin=False, names=False)
if hidden_elements is None:
hidden_elements = []
lengths = {}
if index.nlevels == 1:
for i, value in enumerate(levels):
if i not in hidden_elements:
lengths[(0, i)] = 1
return lengths
for i, lvl in enumerate(levels):
for j, row in enumerate(lvl):
if not get_option("display.multi_sparse"):
lengths[(i, j)] = 1
elif (row is not lib.no_default) and (j not in hidden_elements):
last_label = j
lengths[(i, last_label)] = 1
elif row is not lib.no_default:
# even if its hidden, keep track of it in case
# length >1 and later elements are visible
last_label = j
lengths[(i, last_label)] = 0
elif j not in hidden_elements:
lengths[(i, last_label)] += 1
non_zero_lengths = {
element: length for element, length in lengths.items() if length >= 1
}
return non_zero_lengths
def _maybe_wrap_formatter(
formatter: Union[Callable, str], na_rep: Optional[str]
) -> Callable:
if isinstance(formatter, str):
formatter_func = lambda x: formatter.format(x)
elif callable(formatter):
formatter_func = formatter
else:
msg = f"Expected a template string or callable, got {formatter} instead"
raise TypeError(msg)
if na_rep is None:
return formatter_func
elif isinstance(na_rep, str):
return lambda x: na_rep if pd.isna(x) else formatter_func(x)
else:
msg = f"Expected a string, got {na_rep} instead"
raise TypeError(msg)
|
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import math
import warnings
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer,
build_norm_layer)
from mmcv.runner.base_module import BaseModule, ModuleList, Sequential
from mmcv.utils import (ConfigDict, build_from_cfg, deprecated_api_warning,
to_2tuple)
from .drop import build_dropout
from .registry import (ATTENTION, FEEDFORWARD_NETWORK, POSITIONAL_ENCODING,
TRANSFORMER_LAYER, TRANSFORMER_LAYER_SEQUENCE)
# Avoid BC-breaking of importing MultiScaleDeformableAttention from this file
try:
from mmcv.ops.multi_scale_deform_attn import \
MultiScaleDeformableAttention # noqa F401
warnings.warn(
ImportWarning(
'``MultiScaleDeformableAttention`` has been moved to '
'``mmcv.ops.multi_scale_deform_attn``, please change original path ' # noqa E501
'``from mmcv.cnn.bricks.transformer import MultiScaleDeformableAttention`` ' # noqa E501
'to ``from mmcv.ops.multi_scale_deform_attn import MultiScaleDeformableAttention`` ' # noqa E501
))
except ImportError:
warnings.warn('Fail to import ``MultiScaleDeformableAttention`` from '
'``mmcv.ops.multi_scale_deform_attn``, '
'You should install ``mmcv-full`` if you need this module. ')
def build_positional_encoding(cfg, default_args=None):
"""Builder for Position Encoding."""
return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
def build_attention(cfg, default_args=None):
"""Builder for attention."""
return build_from_cfg(cfg, ATTENTION, default_args)
def build_feedforward_network(cfg, default_args=None):
"""Builder for feed-forward network (FFN)."""
return build_from_cfg(cfg, FEEDFORWARD_NETWORK, default_args)
def build_transformer_layer(cfg, default_args=None):
"""Builder for transformer layer."""
return build_from_cfg(cfg, TRANSFORMER_LAYER, default_args)
def build_transformer_layer_sequence(cfg, default_args=None):
"""Builder for transformer encoder and transformer decoder."""
return build_from_cfg(cfg, TRANSFORMER_LAYER_SEQUENCE, default_args)
class AdaptivePadding(nn.Module):
"""Applies padding adaptively to the input.
This module can make input get fully covered by filter
you specified. It support two modes "same" and "corner". The
"same" mode is same with "SAME" padding mode in TensorFlow, pad
zero around input. The "corner" mode would pad zero
to bottom right.
Args:
kernel_size (int | tuple): Size of the kernel. Default: 1.
stride (int | tuple): Stride of the filter. Default: 1.
dilation (int | tuple): Spacing between kernel elements.
Default: 1.
padding (str): Support "same" and "corner", "corner" mode
would pad zero to bottom right, and "same" mode would
pad zero around input. Default: "corner".
Example:
>>> kernel_size = 16
>>> stride = 16
>>> dilation = 1
>>> input = torch.rand(1, 1, 15, 17)
>>> adap_pad = AdaptivePadding(
>>> kernel_size=kernel_size,
>>> stride=stride,
>>> dilation=dilation,
>>> padding="corner")
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
>>> input = torch.rand(1, 1, 16, 17)
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
"""
def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):
super().__init__()
assert padding in ('same', 'corner')
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
self.padding = padding
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
def get_pad_shape(self, input_shape):
"""Calculate the padding size of input.
Args:
input_shape (:obj:`torch.Size`): arrange as (H, W).
Returns:
Tuple[int]: The padding size along the
original H and W directions
"""
input_h, input_w = input_shape
kernel_h, kernel_w = self.kernel_size
stride_h, stride_w = self.stride
output_h = math.ceil(input_h / stride_h)
output_w = math.ceil(input_w / stride_w)
pad_h = max((output_h - 1) * stride_h +
(kernel_h - 1) * self.dilation[0] + 1 - input_h, 0)
pad_w = max((output_w - 1) * stride_w +
(kernel_w - 1) * self.dilation[1] + 1 - input_w, 0)
return pad_h, pad_w
def forward(self, x):
"""Add padding to `x`
Args:
x (Tensor): Input tensor has shape (B, C, H, W).
Returns:
Tensor: The tensor with adaptive padding
"""
pad_h, pad_w = self.get_pad_shape(x.size()[-2:])
if pad_h > 0 or pad_w > 0:
if self.padding == 'corner':
x = F.pad(x, [0, pad_w, 0, pad_h])
elif self.padding == 'same':
x = F.pad(x, [
pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
pad_h - pad_h // 2
])
return x
class PatchEmbed(BaseModule):
"""Image to Patch Embedding.
We use a conv layer to implement PatchEmbed.
Args:
in_channels (int): The num of input channels. Default: 3
embed_dims (int): The dimensions of embedding. Default: 768
conv_type (str): The type of convolution
to generate patch embedding. Default: "Conv2d".
kernel_size (int): The kernel_size of embedding conv. Default: 16.
stride (int): The slide stride of embedding conv.
Default: 16.
padding (int | tuple | string): The padding length of
embedding conv. When it is a string, it means the mode
of adaptive padding, support "same" and "corner" now.
Default: "corner".
dilation (int): The dilation rate of embedding conv. Default: 1.
bias (bool): Bias of embed conv. Default: True.
norm_cfg (dict, optional): Config dict for normalization layer.
Default: None.
input_size (int | tuple | None): The size of input, which will be
used to calculate the out size. Only works when `dynamic_size`
is False. Default: None.
init_cfg (`mmcv.ConfigDict`, optional): The Config for initialization.
Default: None.
"""
def __init__(self,
in_channels=3,
embed_dims=768,
conv_type='Conv2d',
kernel_size=16,
stride=16,
padding='corner',
dilation=1,
bias=True,
norm_cfg=None,
input_size=None,
init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.embed_dims = embed_dims
if stride is None:
stride = kernel_size
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
if isinstance(padding, str):
self.adaptive_padding = AdaptivePadding(
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
padding=padding)
# disable the padding of conv
padding = 0
else:
self.adaptive_padding = None
padding = to_2tuple(padding)
self.projection = build_conv_layer(
dict(type=conv_type),
in_channels=in_channels,
out_channels=embed_dims,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias)
if norm_cfg is not None:
self.norm = build_norm_layer(norm_cfg, embed_dims)[1]
else:
self.norm = None
if input_size:
input_size = to_2tuple(input_size)
# `init_out_size` would be used outside to
# calculate the num_patches
# e.g. when `use_abs_pos_embed` outside
self.init_input_size = input_size
if self.adaptive_padding:
pad_h, pad_w = self.adaptive_padding.get_pad_shape(input_size)
input_h, input_w = input_size
input_h = input_h + pad_h
input_w = input_w + pad_w
input_size = (input_h, input_w)
# https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
h_out = (input_size[0] + 2 * padding[0] - dilation[0] *
(kernel_size[0] - 1) - 1) // stride[0] + 1
w_out = (input_size[1] + 2 * padding[1] - dilation[1] *
(kernel_size[1] - 1) - 1) // stride[1] + 1
self.init_out_size = (h_out, w_out)
else:
self.init_input_size = None
self.init_out_size = None
def forward(self, x):
"""
Args:
x (Tensor): Has shape (B, C, H, W). In most case, C is 3.
Returns:
tuple: Contains merged results and its spatial shape.
- x (Tensor): Has shape (B, out_h * out_w, embed_dims)
- out_size (tuple[int]): Spatial shape of x, arrange as
(out_h, out_w).
"""
if self.adaptive_padding:
x = self.adaptive_padding(x)
x = self.projection(x)
out_size = (x.shape[2], x.shape[3])
x = x.flatten(2).transpose(1, 2)
if self.norm is not None:
x = self.norm(x)
return x, out_size
class PatchMerging(BaseModule):
"""Merge patch feature map.
This layer groups feature map by kernel_size, and applies norm and linear
layers to the grouped feature map ((used in Swin Transformer)).
Our implementation uses `nn.Unfold` to
merge patches, which is about 25% faster than the original
implementation. However, we need to modify pretrained
models for compatibility.
Args:
in_channels (int): The num of input channels.
to gets fully covered by filter and stride you specified.
out_channels (int): The num of output channels.
kernel_size (int | tuple, optional): the kernel size in the unfold
layer. Defaults to 2.
stride (int | tuple, optional): the stride of the sliding blocks in the
unfold layer. Default: None. (Would be set as `kernel_size`)
padding (int | tuple | string ): The padding length of
embedding conv. When it is a string, it means the mode
of adaptive padding, support "same" and "corner" now.
Default: "corner".
dilation (int | tuple, optional): dilation parameter in the unfold
layer. Default: 1.
bias (bool, optional): Whether to add bias in linear layer or not.
Defaults: False.
norm_cfg (dict, optional): Config dict for normalization layer.
Default: dict(type='LN').
init_cfg (dict, optional): The extra config for initialization.
Default: None.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size=2,
stride=None,
padding='corner',
dilation=1,
bias=False,
norm_cfg=dict(type='LN'),
init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.in_channels = in_channels
self.out_channels = out_channels
if stride:
stride = stride
else:
stride = kernel_size
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
if isinstance(padding, str):
self.adaptive_padding = AdaptivePadding(
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
padding=padding)
# disable the padding of unfold
padding = 0
else:
self.adaptive_padding = None
padding = to_2tuple(padding)
self.sampler = nn.Unfold(
kernel_size=kernel_size,
dilation=dilation,
padding=padding,
stride=stride)
sample_dim = kernel_size[0] * kernel_size[1] * in_channels
if norm_cfg is not None:
self.norm = build_norm_layer(norm_cfg, sample_dim)[1]
else:
self.norm = None
self.reduction = nn.Linear(sample_dim, out_channels, bias=bias)
def forward(self, x, input_size):
"""
Args:
x (Tensor): Has shape (B, H*W, C_in).
input_size (tuple[int]): The spatial shape of x, arrange as (H, W).
Default: None.
Returns:
tuple: Contains merged results and its spatial shape.
- x (Tensor): Has shape (B, Merged_H * Merged_W, C_out)
- out_size (tuple[int]): Spatial shape of x, arrange as
(Merged_H, Merged_W).
"""
B, L, C = x.shape
assert isinstance(input_size, Sequence), f'Expect ' \
f'input_size is ' \
f'`Sequence` ' \
f'but get {input_size}'
H, W = input_size
assert L == H * W, 'input feature has wrong size'
x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W
if self.adaptive_padding:
x = self.adaptive_padding(x)
H, W = x.shape[-2:]
# Use nn.Unfold to merge patch. About 25% faster than original method,
# but need to modify pretrained model for compatibility
# if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2)
x = self.sampler(x)
out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] *
(self.sampler.kernel_size[0] - 1) -
1) // self.sampler.stride[0] + 1
out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] *
(self.sampler.kernel_size[1] - 1) -
1) // self.sampler.stride[1] + 1
output_size = (out_h, out_w)
x = x.transpose(1, 2) # B, H/2*W/2, 4*C
x = self.norm(x) if self.norm else x
x = self.reduction(x)
return x, output_size
@ATTENTION.register_module()
class MultiheadAttention(BaseModule):
"""A wrapper for ``torch.nn.MultiheadAttention``.
This module implements MultiheadAttention with identity connection,
and positional encoding is also passed as input.
Args:
embed_dims (int): The embedding dimension.
num_heads (int): Parallel attention heads.
attn_drop (float): A Dropout layer on attn_output_weights.
Default: 0.0.
proj_drop (float): A Dropout layer after `nn.MultiheadAttention`.
Default: 0.0.
dropout_layer (obj:`ConfigDict`): The dropout_layer used
when adding the shortcut.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
batch_first (bool): When it is True, Key, Query and Value are shape of
(batch, n, embed_dim), otherwise (n, batch, embed_dim).
Default to False.
"""
def __init__(self,
embed_dims,
num_heads,
attn_drop=0.,
proj_drop=0.,
dropout_layer=dict(type='Dropout', drop_prob=0.),
init_cfg=None,
batch_first=False,
**kwargs):
super().__init__(init_cfg)
if 'dropout' in kwargs:
warnings.warn(
'The arguments `dropout` in MultiheadAttention '
'has been deprecated, now you can separately '
'set `attn_drop`(float), proj_drop(float), '
'and `dropout_layer`(dict) ', DeprecationWarning)
attn_drop = kwargs['dropout']
dropout_layer['drop_prob'] = kwargs.pop('dropout')
self.embed_dims = embed_dims
self.num_heads = num_heads
self.batch_first = batch_first
self.attn = nn.MultiheadAttention(embed_dims, num_heads, attn_drop,
**kwargs)
self.proj_drop = nn.Dropout(proj_drop)
self.dropout_layer = build_dropout(
dropout_layer) if dropout_layer else nn.Identity()
@deprecated_api_warning({'residual': 'identity'},
cls_name='MultiheadAttention')
def forward(self,
query,
key=None,
value=None,
identity=None,
query_pos=None,
key_pos=None,
attn_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `MultiheadAttention`.
**kwargs allow passing a more general data flow when combining
with other operations in `transformerlayer`.
Args:
query (Tensor): The input query with shape [num_queries, bs,
embed_dims] if self.batch_first is False, else
[bs, num_queries embed_dims].
key (Tensor): The key tensor with shape [num_keys, bs,
embed_dims] if self.batch_first is False, else
[bs, num_keys, embed_dims] .
If None, the ``query`` will be used. Defaults to None.
value (Tensor): The value tensor with same shape as `key`.
Same in `nn.MultiheadAttention.forward`. Defaults to None.
If None, the `key` will be used.
identity (Tensor): This tensor, with the same shape as x,
will be used for the identity link.
If None, `x` will be used. Defaults to None.
query_pos (Tensor): The positional encoding for query, with
the same shape as `x`. If not None, it will
be added to `x` before forward function. Defaults to None.
key_pos (Tensor): The positional encoding for `key`, with the
same shape as `key`. Defaults to None. If not None, it will
be added to `key` before forward function. If None, and
`query_pos` has the same shape as `key`, then `query_pos`
will be used for `key_pos`. Defaults to None.
attn_mask (Tensor): ByteTensor mask with shape [num_queries,
num_keys]. Same in `nn.MultiheadAttention.forward`.
Defaults to None.
key_padding_mask (Tensor): ByteTensor with shape [bs, num_keys].
Defaults to None.
Returns:
Tensor: forwarded results with shape
[num_queries, bs, embed_dims]
if self.batch_first is False, else
[bs, num_queries embed_dims].
"""
if key is None:
key = query
if value is None:
value = key
if identity is None:
identity = query
if key_pos is None:
if query_pos is not None:
# use query_pos if key_pos is not available
if query_pos.shape == key.shape:
key_pos = query_pos
else:
warnings.warn(f'position encoding of key is'
f'missing in {self.__class__.__name__}.')
if query_pos is not None:
query = query + query_pos
if key_pos is not None:
key = key + key_pos
# Because the dataflow('key', 'query', 'value') of
# ``torch.nn.MultiheadAttention`` is (num_query, batch,
# embed_dims), We should adjust the shape of dataflow from
# batch_first (batch, num_query, embed_dims) to num_query_first
# (num_query ,batch, embed_dims), and recover ``attn_output``
# from num_query_first to batch_first.
if self.batch_first:
query = query.transpose(0, 1)
key = key.transpose(0, 1)
value = value.transpose(0, 1)
out = self.attn(
query=query,
key=key,
value=value,
attn_mask=attn_mask,
key_padding_mask=key_padding_mask)[0]
if self.batch_first:
out = out.transpose(0, 1)
return identity + self.dropout_layer(self.proj_drop(out))
@FEEDFORWARD_NETWORK.register_module()
class FFN(BaseModule):
"""Implements feed-forward networks (FFNs) with identity connection.
Args:
embed_dims (int): The feature dimension. Same as
`MultiheadAttention`. Defaults: 256.
feedforward_channels (int): The hidden dimension of FFNs.
Defaults: 1024.
num_fcs (int, optional): The number of fully-connected layers in
FFNs. Default: 2.
act_cfg (dict, optional): The activation config for FFNs.
Default: dict(type='ReLU')
ffn_drop (float, optional): Probability of an element to be
zeroed in FFN. Default 0.0.
add_identity (bool, optional): Whether to add the
identity connection. Default: `True`.
dropout_layer (obj:`ConfigDict`): The dropout_layer used
when adding the shortcut.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
"""
@deprecated_api_warning(
{
'dropout': 'ffn_drop',
'add_residual': 'add_identity'
},
cls_name='FFN')
def __init__(self,
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
act_cfg=dict(type='ReLU', inplace=True),
ffn_drop=0.,
dropout_layer=None,
add_identity=True,
init_cfg=None,
**kwargs):
super().__init__(init_cfg)
assert num_fcs >= 2, 'num_fcs should be no less ' \
f'than 2. got {num_fcs}.'
self.embed_dims = embed_dims
self.feedforward_channels = feedforward_channels
self.num_fcs = num_fcs
self.act_cfg = act_cfg
self.activate = build_activation_layer(act_cfg)
layers = []
in_channels = embed_dims
for _ in range(num_fcs - 1):
layers.append(
Sequential(
Linear(in_channels, feedforward_channels), self.activate,
nn.Dropout(ffn_drop)))
in_channels = feedforward_channels
layers.append(Linear(feedforward_channels, embed_dims))
layers.append(nn.Dropout(ffn_drop))
self.layers = Sequential(*layers)
self.dropout_layer = build_dropout(
dropout_layer) if dropout_layer else torch.nn.Identity()
self.add_identity = add_identity
@deprecated_api_warning({'residual': 'identity'}, cls_name='FFN')
def forward(self, x, identity=None):
"""Forward function for `FFN`.
The function would add x to the output tensor if residue is None.
"""
out = self.layers(x)
if not self.add_identity:
return self.dropout_layer(out)
if identity is None:
identity = x
return identity + self.dropout_layer(out)
@TRANSFORMER_LAYER.register_module()
class BaseTransformerLayer(BaseModule):
"""Base `TransformerLayer` for vision transformer.
It can be built from `mmcv.ConfigDict` and support more flexible
customization, for example, using any number of `FFN or LN ` and
use different kinds of `attention` by specifying a list of `ConfigDict`
named `attn_cfgs`. It is worth mentioning that it supports `prenorm`
when you specifying `norm` as the first element of `operation_order`.
More details about the `prenorm`: `On Layer Normalization in the
Transformer Architecture <https://arxiv.org/abs/2002.04745>`_ .
Args:
attn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):
Configs for `self_attention` or `cross_attention` modules,
The order of the configs in the list should be consistent with
corresponding attentions in operation_order.
If it is a dict, all of the attention modules in operation_order
will be built with this config. Default: None.
ffn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):
Configs for FFN, The order of the configs in the list should be
consistent with corresponding ffn in operation_order.
If it is a dict, all of the attention modules in operation_order
will be built with this config.
operation_order (tuple[str]): The execution order of operation
in transformer. Such as ('self_attn', 'norm', 'ffn', 'norm').
Support `prenorm` when you specifying first element as `norm`.
Default:None.
norm_cfg (dict): Config dict for normalization layer.
Default: dict(type='LN').
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
batch_first (bool): Key, Query and Value are shape
of (batch, n, embed_dim)
or (n, batch, embed_dim). Default to False.
"""
def __init__(self,
attn_cfgs=None,
ffn_cfgs=dict(
type='FFN',
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
ffn_drop=0.,
act_cfg=dict(type='ReLU', inplace=True),
),
operation_order=None,
norm_cfg=dict(type='LN'),
init_cfg=None,
batch_first=False,
**kwargs):
deprecated_args = dict(
feedforward_channels='feedforward_channels',
ffn_dropout='ffn_drop',
ffn_num_fcs='num_fcs')
for ori_name, new_name in deprecated_args.items():
if ori_name in kwargs:
warnings.warn(
f'The arguments `{ori_name}` in BaseTransformerLayer '
f'has been deprecated, now you should set `{new_name}` '
f'and other FFN related arguments '
f'to a dict named `ffn_cfgs`. ', DeprecationWarning)
ffn_cfgs[new_name] = kwargs[ori_name]
super().__init__(init_cfg)
self.batch_first = batch_first
assert set(operation_order) & {
'self_attn', 'norm', 'ffn', 'cross_attn'} == \
set(operation_order), f'The operation_order of' \
f' {self.__class__.__name__} should ' \
f'contains all four operation type ' \
f"{["self_attn", "norm", "ffn", "cross_attn"]}"
num_attn = operation_order.count('self_attn') + operation_order.count(
'cross_attn')
if isinstance(attn_cfgs, dict):
attn_cfgs = [copy.deepcopy(attn_cfgs) for _ in range(num_attn)]
else:
assert num_attn == len(attn_cfgs), f'The length ' \
f'of attn_cfg {num_attn} is ' \
f'not consistent with the number of attention' \
f'in operation_order {operation_order}.'
self.num_attn = num_attn
self.operation_order = operation_order
self.norm_cfg = norm_cfg
self.pre_norm = operation_order[0] == 'norm'
self.attentions = ModuleList()
index = 0
for operation_name in operation_order:
if operation_name in ['self_attn', 'cross_attn']:
if 'batch_first' in attn_cfgs[index]:
assert self.batch_first == attn_cfgs[index]['batch_first']
else:
attn_cfgs[index]['batch_first'] = self.batch_first
attention = build_attention(attn_cfgs[index])
# Some custom attentions used as `self_attn`
# or `cross_attn` can have different behavior.
attention.operation_name = operation_name
self.attentions.append(attention)
index += 1
self.embed_dims = self.attentions[0].embed_dims
self.ffns = ModuleList()
num_ffns = operation_order.count('ffn')
if isinstance(ffn_cfgs, dict):
ffn_cfgs = ConfigDict(ffn_cfgs)
if isinstance(ffn_cfgs, dict):
ffn_cfgs = [copy.deepcopy(ffn_cfgs) for _ in range(num_ffns)]
assert len(ffn_cfgs) == num_ffns
for ffn_index in range(num_ffns):
if 'embed_dims' not in ffn_cfgs[ffn_index]:
ffn_cfgs[ffn_index]['embed_dims'] = self.embed_dims
else:
assert ffn_cfgs[ffn_index]['embed_dims'] == self.embed_dims
self.ffns.append(
build_feedforward_network(ffn_cfgs[ffn_index],
dict(type='FFN')))
self.norms = ModuleList()
num_norms = operation_order.count('norm')
for _ in range(num_norms):
self.norms.append(build_norm_layer(norm_cfg, self.embed_dims)[1])
def forward(self,
query,
key=None,
value=None,
query_pos=None,
key_pos=None,
attn_masks=None,
query_key_padding_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `TransformerDecoderLayer`.
**kwargs contains some specific arguments of attentions.
Args:
query (Tensor): The input query with shape
[num_queries, bs, embed_dims] if
self.batch_first is False, else
[bs, num_queries embed_dims].
key (Tensor): The key tensor with shape [num_keys, bs,
embed_dims] if self.batch_first is False, else
[bs, num_keys, embed_dims] .
value (Tensor): The value tensor with same shape as `key`.
query_pos (Tensor): The positional encoding for `query`.
Default: None.
key_pos (Tensor): The positional encoding for `key`.
Default: None.
attn_masks (List[Tensor] | None): 2D Tensor used in
calculation of corresponding attention. The length of
it should equal to the number of `attention` in
`operation_order`. Default: None.
query_key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_queries]. Only used in `self_attn` layer.
Defaults to None.
key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_keys]. Default: None.
Returns:
Tensor: forwarded results with shape [num_queries, bs, embed_dims].
"""
norm_index = 0
attn_index = 0
ffn_index = 0
identity = query
if attn_masks is None:
attn_masks = [None for _ in range(self.num_attn)]
elif isinstance(attn_masks, torch.Tensor):
attn_masks = [
copy.deepcopy(attn_masks) for _ in range(self.num_attn)
]
warnings.warn(f'Use same attn_mask in all attentions in '
f'{self.__class__.__name__} ')
else:
assert len(attn_masks) == self.num_attn, f'The length of ' \
f'attn_masks {len(attn_masks)} must be equal ' \
f'to the number of attention in ' \
f'operation_order {self.num_attn}'
for layer in self.operation_order:
if layer == 'self_attn':
temp_key = temp_value = query
query = self.attentions[attn_index](
query,
temp_key,
temp_value,
identity if self.pre_norm else None,
query_pos=query_pos,
key_pos=query_pos,
attn_mask=attn_masks[attn_index],
key_padding_mask=query_key_padding_mask,
**kwargs)
attn_index += 1
identity = query
elif layer == 'norm':
query = self.norms[norm_index](query)
norm_index += 1
elif layer == 'cross_attn':
query = self.attentions[attn_index](
query,
key,
value,
identity if self.pre_norm else None,
query_pos=query_pos,
key_pos=key_pos,
attn_mask=attn_masks[attn_index],
key_padding_mask=key_padding_mask,
**kwargs)
attn_index += 1
identity = query
elif layer == 'ffn':
query = self.ffns[ffn_index](
query, identity if self.pre_norm else None)
ffn_index += 1
return query
@TRANSFORMER_LAYER_SEQUENCE.register_module()
class TransformerLayerSequence(BaseModule):
"""Base class for TransformerEncoder and TransformerDecoder in vision
transformer.
As base-class of Encoder and Decoder in vision transformer.
Support customization such as specifying different kind
of `transformer_layer` in `transformer_coder`.
Args:
transformerlayer (list[obj:`mmcv.ConfigDict`] |
obj:`mmcv.ConfigDict`): Config of transformerlayer
in TransformerCoder. If it is obj:`mmcv.ConfigDict`,
it would be repeated `num_layer` times to a
list[`mmcv.ConfigDict`]. Default: None.
num_layers (int): The number of `TransformerLayer`. Default: None.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
"""
def __init__(self, transformerlayers=None, num_layers=None, init_cfg=None):
super().__init__(init_cfg)
if isinstance(transformerlayers, dict):
transformerlayers = [
copy.deepcopy(transformerlayers) for _ in range(num_layers)
]
else:
assert isinstance(transformerlayers, list) and \
len(transformerlayers) == num_layers
self.num_layers = num_layers
self.layers = ModuleList()
for i in range(num_layers):
self.layers.append(build_transformer_layer(transformerlayers[i]))
self.embed_dims = self.layers[0].embed_dims
self.pre_norm = self.layers[0].pre_norm
def forward(self,
query,
key,
value,
query_pos=None,
key_pos=None,
attn_masks=None,
query_key_padding_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `TransformerCoder`.
Args:
query (Tensor): Input query with shape
`(num_queries, bs, embed_dims)`.
key (Tensor): The key tensor with shape
`(num_keys, bs, embed_dims)`.
value (Tensor): The value tensor with shape
`(num_keys, bs, embed_dims)`.
query_pos (Tensor): The positional encoding for `query`.
Default: None.
key_pos (Tensor): The positional encoding for `key`.
Default: None.
attn_masks (List[Tensor], optional): Each element is 2D Tensor
which is used in calculation of corresponding attention in
operation_order. Default: None.
query_key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_queries]. Only used in self-attention
Default: None.
key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_keys]. Default: None.
Returns:
Tensor: results with shape [num_queries, bs, embed_dims].
"""
for layer in self.layers:
query = layer(
query,
key,
value,
query_pos=query_pos,
key_pos=key_pos,
attn_masks=attn_masks,
query_key_padding_mask=query_key_padding_mask,
key_padding_mask=key_padding_mask,
**kwargs)
return query
| # Copyright (c) OpenMMLab. All rights reserved.
import copy
import math
import warnings
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer,
build_norm_layer)
from mmcv.runner.base_module import BaseModule, ModuleList, Sequential
from mmcv.utils import (ConfigDict, build_from_cfg, deprecated_api_warning,
to_2tuple)
from .drop import build_dropout
from .registry import (ATTENTION, FEEDFORWARD_NETWORK, POSITIONAL_ENCODING,
TRANSFORMER_LAYER, TRANSFORMER_LAYER_SEQUENCE)
# Avoid BC-breaking of importing MultiScaleDeformableAttention from this file
try:
from mmcv.ops.multi_scale_deform_attn import \
MultiScaleDeformableAttention # noqa F401
warnings.warn(
ImportWarning(
'``MultiScaleDeformableAttention`` has been moved to '
'``mmcv.ops.multi_scale_deform_attn``, please change original path ' # noqa E501
'``from mmcv.cnn.bricks.transformer import MultiScaleDeformableAttention`` ' # noqa E501
'to ``from mmcv.ops.multi_scale_deform_attn import MultiScaleDeformableAttention`` ' # noqa E501
))
except ImportError:
warnings.warn('Fail to import ``MultiScaleDeformableAttention`` from '
'``mmcv.ops.multi_scale_deform_attn``, '
'You should install ``mmcv-full`` if you need this module. ')
def build_positional_encoding(cfg, default_args=None):
"""Builder for Position Encoding."""
return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
def build_attention(cfg, default_args=None):
"""Builder for attention."""
return build_from_cfg(cfg, ATTENTION, default_args)
def build_feedforward_network(cfg, default_args=None):
"""Builder for feed-forward network (FFN)."""
return build_from_cfg(cfg, FEEDFORWARD_NETWORK, default_args)
def build_transformer_layer(cfg, default_args=None):
"""Builder for transformer layer."""
return build_from_cfg(cfg, TRANSFORMER_LAYER, default_args)
def build_transformer_layer_sequence(cfg, default_args=None):
"""Builder for transformer encoder and transformer decoder."""
return build_from_cfg(cfg, TRANSFORMER_LAYER_SEQUENCE, default_args)
class AdaptivePadding(nn.Module):
"""Applies padding adaptively to the input.
This module can make input get fully covered by filter
you specified. It support two modes "same" and "corner". The
"same" mode is same with "SAME" padding mode in TensorFlow, pad
zero around input. The "corner" mode would pad zero
to bottom right.
Args:
kernel_size (int | tuple): Size of the kernel. Default: 1.
stride (int | tuple): Stride of the filter. Default: 1.
dilation (int | tuple): Spacing between kernel elements.
Default: 1.
padding (str): Support "same" and "corner", "corner" mode
would pad zero to bottom right, and "same" mode would
pad zero around input. Default: "corner".
Example:
>>> kernel_size = 16
>>> stride = 16
>>> dilation = 1
>>> input = torch.rand(1, 1, 15, 17)
>>> adap_pad = AdaptivePadding(
>>> kernel_size=kernel_size,
>>> stride=stride,
>>> dilation=dilation,
>>> padding="corner")
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
>>> input = torch.rand(1, 1, 16, 17)
>>> out = adap_pad(input)
>>> assert (out.shape[2], out.shape[3]) == (16, 32)
"""
def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):
super().__init__()
assert padding in ('same', 'corner')
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
self.padding = padding
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
def get_pad_shape(self, input_shape):
"""Calculate the padding size of input.
Args:
input_shape (:obj:`torch.Size`): arrange as (H, W).
Returns:
Tuple[int]: The padding size along the
original H and W directions
"""
input_h, input_w = input_shape
kernel_h, kernel_w = self.kernel_size
stride_h, stride_w = self.stride
output_h = math.ceil(input_h / stride_h)
output_w = math.ceil(input_w / stride_w)
pad_h = max((output_h - 1) * stride_h +
(kernel_h - 1) * self.dilation[0] + 1 - input_h, 0)
pad_w = max((output_w - 1) * stride_w +
(kernel_w - 1) * self.dilation[1] + 1 - input_w, 0)
return pad_h, pad_w
def forward(self, x):
"""Add padding to `x`
Args:
x (Tensor): Input tensor has shape (B, C, H, W).
Returns:
Tensor: The tensor with adaptive padding
"""
pad_h, pad_w = self.get_pad_shape(x.size()[-2:])
if pad_h > 0 or pad_w > 0:
if self.padding == 'corner':
x = F.pad(x, [0, pad_w, 0, pad_h])
elif self.padding == 'same':
x = F.pad(x, [
pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
pad_h - pad_h // 2
])
return x
class PatchEmbed(BaseModule):
"""Image to Patch Embedding.
We use a conv layer to implement PatchEmbed.
Args:
in_channels (int): The num of input channels. Default: 3
embed_dims (int): The dimensions of embedding. Default: 768
conv_type (str): The type of convolution
to generate patch embedding. Default: "Conv2d".
kernel_size (int): The kernel_size of embedding conv. Default: 16.
stride (int): The slide stride of embedding conv.
Default: 16.
padding (int | tuple | string): The padding length of
embedding conv. When it is a string, it means the mode
of adaptive padding, support "same" and "corner" now.
Default: "corner".
dilation (int): The dilation rate of embedding conv. Default: 1.
bias (bool): Bias of embed conv. Default: True.
norm_cfg (dict, optional): Config dict for normalization layer.
Default: None.
input_size (int | tuple | None): The size of input, which will be
used to calculate the out size. Only works when `dynamic_size`
is False. Default: None.
init_cfg (`mmcv.ConfigDict`, optional): The Config for initialization.
Default: None.
"""
def __init__(self,
in_channels=3,
embed_dims=768,
conv_type='Conv2d',
kernel_size=16,
stride=16,
padding='corner',
dilation=1,
bias=True,
norm_cfg=None,
input_size=None,
init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.embed_dims = embed_dims
if stride is None:
stride = kernel_size
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
if isinstance(padding, str):
self.adaptive_padding = AdaptivePadding(
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
padding=padding)
# disable the padding of conv
padding = 0
else:
self.adaptive_padding = None
padding = to_2tuple(padding)
self.projection = build_conv_layer(
dict(type=conv_type),
in_channels=in_channels,
out_channels=embed_dims,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias)
if norm_cfg is not None:
self.norm = build_norm_layer(norm_cfg, embed_dims)[1]
else:
self.norm = None
if input_size:
input_size = to_2tuple(input_size)
# `init_out_size` would be used outside to
# calculate the num_patches
# e.g. when `use_abs_pos_embed` outside
self.init_input_size = input_size
if self.adaptive_padding:
pad_h, pad_w = self.adaptive_padding.get_pad_shape(input_size)
input_h, input_w = input_size
input_h = input_h + pad_h
input_w = input_w + pad_w
input_size = (input_h, input_w)
# https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
h_out = (input_size[0] + 2 * padding[0] - dilation[0] *
(kernel_size[0] - 1) - 1) // stride[0] + 1
w_out = (input_size[1] + 2 * padding[1] - dilation[1] *
(kernel_size[1] - 1) - 1) // stride[1] + 1
self.init_out_size = (h_out, w_out)
else:
self.init_input_size = None
self.init_out_size = None
def forward(self, x):
"""
Args:
x (Tensor): Has shape (B, C, H, W). In most case, C is 3.
Returns:
tuple: Contains merged results and its spatial shape.
- x (Tensor): Has shape (B, out_h * out_w, embed_dims)
- out_size (tuple[int]): Spatial shape of x, arrange as
(out_h, out_w).
"""
if self.adaptive_padding:
x = self.adaptive_padding(x)
x = self.projection(x)
out_size = (x.shape[2], x.shape[3])
x = x.flatten(2).transpose(1, 2)
if self.norm is not None:
x = self.norm(x)
return x, out_size
class PatchMerging(BaseModule):
"""Merge patch feature map.
This layer groups feature map by kernel_size, and applies norm and linear
layers to the grouped feature map ((used in Swin Transformer)).
Our implementation uses `nn.Unfold` to
merge patches, which is about 25% faster than the original
implementation. However, we need to modify pretrained
models for compatibility.
Args:
in_channels (int): The num of input channels.
to gets fully covered by filter and stride you specified.
out_channels (int): The num of output channels.
kernel_size (int | tuple, optional): the kernel size in the unfold
layer. Defaults to 2.
stride (int | tuple, optional): the stride of the sliding blocks in the
unfold layer. Default: None. (Would be set as `kernel_size`)
padding (int | tuple | string ): The padding length of
embedding conv. When it is a string, it means the mode
of adaptive padding, support "same" and "corner" now.
Default: "corner".
dilation (int | tuple, optional): dilation parameter in the unfold
layer. Default: 1.
bias (bool, optional): Whether to add bias in linear layer or not.
Defaults: False.
norm_cfg (dict, optional): Config dict for normalization layer.
Default: dict(type='LN').
init_cfg (dict, optional): The extra config for initialization.
Default: None.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size=2,
stride=None,
padding='corner',
dilation=1,
bias=False,
norm_cfg=dict(type='LN'),
init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.in_channels = in_channels
self.out_channels = out_channels
if stride:
stride = stride
else:
stride = kernel_size
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dilation)
if isinstance(padding, str):
self.adaptive_padding = AdaptivePadding(
kernel_size=kernel_size,
stride=stride,
dilation=dilation,
padding=padding)
# disable the padding of unfold
padding = 0
else:
self.adaptive_padding = None
padding = to_2tuple(padding)
self.sampler = nn.Unfold(
kernel_size=kernel_size,
dilation=dilation,
padding=padding,
stride=stride)
sample_dim = kernel_size[0] * kernel_size[1] * in_channels
if norm_cfg is not None:
self.norm = build_norm_layer(norm_cfg, sample_dim)[1]
else:
self.norm = None
self.reduction = nn.Linear(sample_dim, out_channels, bias=bias)
def forward(self, x, input_size):
"""
Args:
x (Tensor): Has shape (B, H*W, C_in).
input_size (tuple[int]): The spatial shape of x, arrange as (H, W).
Default: None.
Returns:
tuple: Contains merged results and its spatial shape.
- x (Tensor): Has shape (B, Merged_H * Merged_W, C_out)
- out_size (tuple[int]): Spatial shape of x, arrange as
(Merged_H, Merged_W).
"""
B, L, C = x.shape
assert isinstance(input_size, Sequence), f'Expect ' \
f'input_size is ' \
f'`Sequence` ' \
f'but get {input_size}'
H, W = input_size
assert L == H * W, 'input feature has wrong size'
x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W
if self.adaptive_padding:
x = self.adaptive_padding(x)
H, W = x.shape[-2:]
# Use nn.Unfold to merge patch. About 25% faster than original method,
# but need to modify pretrained model for compatibility
# if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2)
x = self.sampler(x)
out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] *
(self.sampler.kernel_size[0] - 1) -
1) // self.sampler.stride[0] + 1
out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] *
(self.sampler.kernel_size[1] - 1) -
1) // self.sampler.stride[1] + 1
output_size = (out_h, out_w)
x = x.transpose(1, 2) # B, H/2*W/2, 4*C
x = self.norm(x) if self.norm else x
x = self.reduction(x)
return x, output_size
@ATTENTION.register_module()
class MultiheadAttention(BaseModule):
"""A wrapper for ``torch.nn.MultiheadAttention``.
This module implements MultiheadAttention with identity connection,
and positional encoding is also passed as input.
Args:
embed_dims (int): The embedding dimension.
num_heads (int): Parallel attention heads.
attn_drop (float): A Dropout layer on attn_output_weights.
Default: 0.0.
proj_drop (float): A Dropout layer after `nn.MultiheadAttention`.
Default: 0.0.
dropout_layer (obj:`ConfigDict`): The dropout_layer used
when adding the shortcut.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
batch_first (bool): When it is True, Key, Query and Value are shape of
(batch, n, embed_dim), otherwise (n, batch, embed_dim).
Default to False.
"""
def __init__(self,
embed_dims,
num_heads,
attn_drop=0.,
proj_drop=0.,
dropout_layer=dict(type='Dropout', drop_prob=0.),
init_cfg=None,
batch_first=False,
**kwargs):
super().__init__(init_cfg)
if 'dropout' in kwargs:
warnings.warn(
'The arguments `dropout` in MultiheadAttention '
'has been deprecated, now you can separately '
'set `attn_drop`(float), proj_drop(float), '
'and `dropout_layer`(dict) ', DeprecationWarning)
attn_drop = kwargs['dropout']
dropout_layer['drop_prob'] = kwargs.pop('dropout')
self.embed_dims = embed_dims
self.num_heads = num_heads
self.batch_first = batch_first
self.attn = nn.MultiheadAttention(embed_dims, num_heads, attn_drop,
**kwargs)
self.proj_drop = nn.Dropout(proj_drop)
self.dropout_layer = build_dropout(
dropout_layer) if dropout_layer else nn.Identity()
@deprecated_api_warning({'residual': 'identity'},
cls_name='MultiheadAttention')
def forward(self,
query,
key=None,
value=None,
identity=None,
query_pos=None,
key_pos=None,
attn_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `MultiheadAttention`.
**kwargs allow passing a more general data flow when combining
with other operations in `transformerlayer`.
Args:
query (Tensor): The input query with shape [num_queries, bs,
embed_dims] if self.batch_first is False, else
[bs, num_queries embed_dims].
key (Tensor): The key tensor with shape [num_keys, bs,
embed_dims] if self.batch_first is False, else
[bs, num_keys, embed_dims] .
If None, the ``query`` will be used. Defaults to None.
value (Tensor): The value tensor with same shape as `key`.
Same in `nn.MultiheadAttention.forward`. Defaults to None.
If None, the `key` will be used.
identity (Tensor): This tensor, with the same shape as x,
will be used for the identity link.
If None, `x` will be used. Defaults to None.
query_pos (Tensor): The positional encoding for query, with
the same shape as `x`. If not None, it will
be added to `x` before forward function. Defaults to None.
key_pos (Tensor): The positional encoding for `key`, with the
same shape as `key`. Defaults to None. If not None, it will
be added to `key` before forward function. If None, and
`query_pos` has the same shape as `key`, then `query_pos`
will be used for `key_pos`. Defaults to None.
attn_mask (Tensor): ByteTensor mask with shape [num_queries,
num_keys]. Same in `nn.MultiheadAttention.forward`.
Defaults to None.
key_padding_mask (Tensor): ByteTensor with shape [bs, num_keys].
Defaults to None.
Returns:
Tensor: forwarded results with shape
[num_queries, bs, embed_dims]
if self.batch_first is False, else
[bs, num_queries embed_dims].
"""
if key is None:
key = query
if value is None:
value = key
if identity is None:
identity = query
if key_pos is None:
if query_pos is not None:
# use query_pos if key_pos is not available
if query_pos.shape == key.shape:
key_pos = query_pos
else:
warnings.warn(f'position encoding of key is'
f'missing in {self.__class__.__name__}.')
if query_pos is not None:
query = query + query_pos
if key_pos is not None:
key = key + key_pos
# Because the dataflow('key', 'query', 'value') of
# ``torch.nn.MultiheadAttention`` is (num_query, batch,
# embed_dims), We should adjust the shape of dataflow from
# batch_first (batch, num_query, embed_dims) to num_query_first
# (num_query ,batch, embed_dims), and recover ``attn_output``
# from num_query_first to batch_first.
if self.batch_first:
query = query.transpose(0, 1)
key = key.transpose(0, 1)
value = value.transpose(0, 1)
out = self.attn(
query=query,
key=key,
value=value,
attn_mask=attn_mask,
key_padding_mask=key_padding_mask)[0]
if self.batch_first:
out = out.transpose(0, 1)
return identity + self.dropout_layer(self.proj_drop(out))
@FEEDFORWARD_NETWORK.register_module()
class FFN(BaseModule):
"""Implements feed-forward networks (FFNs) with identity connection.
Args:
embed_dims (int): The feature dimension. Same as
`MultiheadAttention`. Defaults: 256.
feedforward_channels (int): The hidden dimension of FFNs.
Defaults: 1024.
num_fcs (int, optional): The number of fully-connected layers in
FFNs. Default: 2.
act_cfg (dict, optional): The activation config for FFNs.
Default: dict(type='ReLU')
ffn_drop (float, optional): Probability of an element to be
zeroed in FFN. Default 0.0.
add_identity (bool, optional): Whether to add the
identity connection. Default: `True`.
dropout_layer (obj:`ConfigDict`): The dropout_layer used
when adding the shortcut.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
"""
@deprecated_api_warning(
{
'dropout': 'ffn_drop',
'add_residual': 'add_identity'
},
cls_name='FFN')
def __init__(self,
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
act_cfg=dict(type='ReLU', inplace=True),
ffn_drop=0.,
dropout_layer=None,
add_identity=True,
init_cfg=None,
**kwargs):
super().__init__(init_cfg)
assert num_fcs >= 2, 'num_fcs should be no less ' \
f'than 2. got {num_fcs}.'
self.embed_dims = embed_dims
self.feedforward_channels = feedforward_channels
self.num_fcs = num_fcs
self.act_cfg = act_cfg
self.activate = build_activation_layer(act_cfg)
layers = []
in_channels = embed_dims
for _ in range(num_fcs - 1):
layers.append(
Sequential(
Linear(in_channels, feedforward_channels), self.activate,
nn.Dropout(ffn_drop)))
in_channels = feedforward_channels
layers.append(Linear(feedforward_channels, embed_dims))
layers.append(nn.Dropout(ffn_drop))
self.layers = Sequential(*layers)
self.dropout_layer = build_dropout(
dropout_layer) if dropout_layer else torch.nn.Identity()
self.add_identity = add_identity
@deprecated_api_warning({'residual': 'identity'}, cls_name='FFN')
def forward(self, x, identity=None):
"""Forward function for `FFN`.
The function would add x to the output tensor if residue is None.
"""
out = self.layers(x)
if not self.add_identity:
return self.dropout_layer(out)
if identity is None:
identity = x
return identity + self.dropout_layer(out)
@TRANSFORMER_LAYER.register_module()
class BaseTransformerLayer(BaseModule):
"""Base `TransformerLayer` for vision transformer.
It can be built from `mmcv.ConfigDict` and support more flexible
customization, for example, using any number of `FFN or LN ` and
use different kinds of `attention` by specifying a list of `ConfigDict`
named `attn_cfgs`. It is worth mentioning that it supports `prenorm`
when you specifying `norm` as the first element of `operation_order`.
More details about the `prenorm`: `On Layer Normalization in the
Transformer Architecture <https://arxiv.org/abs/2002.04745>`_ .
Args:
attn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):
Configs for `self_attention` or `cross_attention` modules,
The order of the configs in the list should be consistent with
corresponding attentions in operation_order.
If it is a dict, all of the attention modules in operation_order
will be built with this config. Default: None.
ffn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):
Configs for FFN, The order of the configs in the list should be
consistent with corresponding ffn in operation_order.
If it is a dict, all of the attention modules in operation_order
will be built with this config.
operation_order (tuple[str]): The execution order of operation
in transformer. Such as ('self_attn', 'norm', 'ffn', 'norm').
Support `prenorm` when you specifying first element as `norm`.
Default:None.
norm_cfg (dict): Config dict for normalization layer.
Default: dict(type='LN').
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
batch_first (bool): Key, Query and Value are shape
of (batch, n, embed_dim)
or (n, batch, embed_dim). Default to False.
"""
def __init__(self,
attn_cfgs=None,
ffn_cfgs=dict(
type='FFN',
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
ffn_drop=0.,
act_cfg=dict(type='ReLU', inplace=True),
),
operation_order=None,
norm_cfg=dict(type='LN'),
init_cfg=None,
batch_first=False,
**kwargs):
deprecated_args = dict(
feedforward_channels='feedforward_channels',
ffn_dropout='ffn_drop',
ffn_num_fcs='num_fcs')
for ori_name, new_name in deprecated_args.items():
if ori_name in kwargs:
warnings.warn(
f'The arguments `{ori_name}` in BaseTransformerLayer '
f'has been deprecated, now you should set `{new_name}` '
f'and other FFN related arguments '
f'to a dict named `ffn_cfgs`. ', DeprecationWarning)
ffn_cfgs[new_name] = kwargs[ori_name]
super().__init__(init_cfg)
self.batch_first = batch_first
assert set(operation_order) & {
'self_attn', 'norm', 'ffn', 'cross_attn'} == \
set(operation_order), f'The operation_order of' \
f' {self.__class__.__name__} should ' \
f'contains all four operation type ' \
f"{['self_attn', 'norm', 'ffn', 'cross_attn']}"
num_attn = operation_order.count('self_attn') + operation_order.count(
'cross_attn')
if isinstance(attn_cfgs, dict):
attn_cfgs = [copy.deepcopy(attn_cfgs) for _ in range(num_attn)]
else:
assert num_attn == len(attn_cfgs), f'The length ' \
f'of attn_cfg {num_attn} is ' \
f'not consistent with the number of attention' \
f'in operation_order {operation_order}.'
self.num_attn = num_attn
self.operation_order = operation_order
self.norm_cfg = norm_cfg
self.pre_norm = operation_order[0] == 'norm'
self.attentions = ModuleList()
index = 0
for operation_name in operation_order:
if operation_name in ['self_attn', 'cross_attn']:
if 'batch_first' in attn_cfgs[index]:
assert self.batch_first == attn_cfgs[index]['batch_first']
else:
attn_cfgs[index]['batch_first'] = self.batch_first
attention = build_attention(attn_cfgs[index])
# Some custom attentions used as `self_attn`
# or `cross_attn` can have different behavior.
attention.operation_name = operation_name
self.attentions.append(attention)
index += 1
self.embed_dims = self.attentions[0].embed_dims
self.ffns = ModuleList()
num_ffns = operation_order.count('ffn')
if isinstance(ffn_cfgs, dict):
ffn_cfgs = ConfigDict(ffn_cfgs)
if isinstance(ffn_cfgs, dict):
ffn_cfgs = [copy.deepcopy(ffn_cfgs) for _ in range(num_ffns)]
assert len(ffn_cfgs) == num_ffns
for ffn_index in range(num_ffns):
if 'embed_dims' not in ffn_cfgs[ffn_index]:
ffn_cfgs[ffn_index]['embed_dims'] = self.embed_dims
else:
assert ffn_cfgs[ffn_index]['embed_dims'] == self.embed_dims
self.ffns.append(
build_feedforward_network(ffn_cfgs[ffn_index],
dict(type='FFN')))
self.norms = ModuleList()
num_norms = operation_order.count('norm')
for _ in range(num_norms):
self.norms.append(build_norm_layer(norm_cfg, self.embed_dims)[1])
def forward(self,
query,
key=None,
value=None,
query_pos=None,
key_pos=None,
attn_masks=None,
query_key_padding_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `TransformerDecoderLayer`.
**kwargs contains some specific arguments of attentions.
Args:
query (Tensor): The input query with shape
[num_queries, bs, embed_dims] if
self.batch_first is False, else
[bs, num_queries embed_dims].
key (Tensor): The key tensor with shape [num_keys, bs,
embed_dims] if self.batch_first is False, else
[bs, num_keys, embed_dims] .
value (Tensor): The value tensor with same shape as `key`.
query_pos (Tensor): The positional encoding for `query`.
Default: None.
key_pos (Tensor): The positional encoding for `key`.
Default: None.
attn_masks (List[Tensor] | None): 2D Tensor used in
calculation of corresponding attention. The length of
it should equal to the number of `attention` in
`operation_order`. Default: None.
query_key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_queries]. Only used in `self_attn` layer.
Defaults to None.
key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_keys]. Default: None.
Returns:
Tensor: forwarded results with shape [num_queries, bs, embed_dims].
"""
norm_index = 0
attn_index = 0
ffn_index = 0
identity = query
if attn_masks is None:
attn_masks = [None for _ in range(self.num_attn)]
elif isinstance(attn_masks, torch.Tensor):
attn_masks = [
copy.deepcopy(attn_masks) for _ in range(self.num_attn)
]
warnings.warn(f'Use same attn_mask in all attentions in '
f'{self.__class__.__name__} ')
else:
assert len(attn_masks) == self.num_attn, f'The length of ' \
f'attn_masks {len(attn_masks)} must be equal ' \
f'to the number of attention in ' \
f'operation_order {self.num_attn}'
for layer in self.operation_order:
if layer == 'self_attn':
temp_key = temp_value = query
query = self.attentions[attn_index](
query,
temp_key,
temp_value,
identity if self.pre_norm else None,
query_pos=query_pos,
key_pos=query_pos,
attn_mask=attn_masks[attn_index],
key_padding_mask=query_key_padding_mask,
**kwargs)
attn_index += 1
identity = query
elif layer == 'norm':
query = self.norms[norm_index](query)
norm_index += 1
elif layer == 'cross_attn':
query = self.attentions[attn_index](
query,
key,
value,
identity if self.pre_norm else None,
query_pos=query_pos,
key_pos=key_pos,
attn_mask=attn_masks[attn_index],
key_padding_mask=key_padding_mask,
**kwargs)
attn_index += 1
identity = query
elif layer == 'ffn':
query = self.ffns[ffn_index](
query, identity if self.pre_norm else None)
ffn_index += 1
return query
@TRANSFORMER_LAYER_SEQUENCE.register_module()
class TransformerLayerSequence(BaseModule):
"""Base class for TransformerEncoder and TransformerDecoder in vision
transformer.
As base-class of Encoder and Decoder in vision transformer.
Support customization such as specifying different kind
of `transformer_layer` in `transformer_coder`.
Args:
transformerlayer (list[obj:`mmcv.ConfigDict`] |
obj:`mmcv.ConfigDict`): Config of transformerlayer
in TransformerCoder. If it is obj:`mmcv.ConfigDict`,
it would be repeated `num_layer` times to a
list[`mmcv.ConfigDict`]. Default: None.
num_layers (int): The number of `TransformerLayer`. Default: None.
init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
Default: None.
"""
def __init__(self, transformerlayers=None, num_layers=None, init_cfg=None):
super().__init__(init_cfg)
if isinstance(transformerlayers, dict):
transformerlayers = [
copy.deepcopy(transformerlayers) for _ in range(num_layers)
]
else:
assert isinstance(transformerlayers, list) and \
len(transformerlayers) == num_layers
self.num_layers = num_layers
self.layers = ModuleList()
for i in range(num_layers):
self.layers.append(build_transformer_layer(transformerlayers[i]))
self.embed_dims = self.layers[0].embed_dims
self.pre_norm = self.layers[0].pre_norm
def forward(self,
query,
key,
value,
query_pos=None,
key_pos=None,
attn_masks=None,
query_key_padding_mask=None,
key_padding_mask=None,
**kwargs):
"""Forward function for `TransformerCoder`.
Args:
query (Tensor): Input query with shape
`(num_queries, bs, embed_dims)`.
key (Tensor): The key tensor with shape
`(num_keys, bs, embed_dims)`.
value (Tensor): The value tensor with shape
`(num_keys, bs, embed_dims)`.
query_pos (Tensor): The positional encoding for `query`.
Default: None.
key_pos (Tensor): The positional encoding for `key`.
Default: None.
attn_masks (List[Tensor], optional): Each element is 2D Tensor
which is used in calculation of corresponding attention in
operation_order. Default: None.
query_key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_queries]. Only used in self-attention
Default: None.
key_padding_mask (Tensor): ByteTensor for `query`, with
shape [bs, num_keys]. Default: None.
Returns:
Tensor: results with shape [num_queries, bs, embed_dims].
"""
for layer in self.layers:
query = layer(
query,
key,
value,
query_pos=query_pos,
key_pos=key_pos,
attn_masks=attn_masks,
query_key_padding_mask=query_key_padding_mask,
key_padding_mask=key_padding_mask,
**kwargs)
return query
|
import os
import time
print('Por favor, digite abaixo os valores da equação.')
a = str(input('\nValor de A: '))
b = str(input('Valor de B: '))
c = str(input('Valor de C: '))
print('\nAguarde um instante...')
time.sleep(1)
os.system('cls || clear')
print('='*50 + '\n' + f'{'Resolução':^50}' + '\n' + '='*50)
def print_equacao(a, b, c):
if int(b) < 0:
bn = b[1]
vb = f' - {bn}x'
else:
vb = f' + {b}x'
if int(c) < 0:
cn = c[1]
vc = f' - {cn}x'
else:
vc = f' + {c}x'
if b == 0:
vb = ''
if c == 0:
vc = ''
print(f'Equação = {a}x²{vb}{vc} = 0')
print_equacao(a, b, c)
a = int(a)
b = int(b)
c = int(c)
delta = (b*b) - 4 * a * c
print(f'\n∆ = {delta}')
if delta < 0:
print('\n\nDelta é menor que zero. Esta equação não tem x1/x2.')
else:
x1 = (-b + (delta ** 0.5)) / (2*a)
x2 = (-b - (delta ** 0.5)) / (2*a)
if x1 > 0:
x1 = int(x1)
else:
if (-b + (delta ** 0.5)) % (2*a) == 0:
x1 = int(x1)
else:
x1 = f'{x1:.1f}'
if x2 > 0:
x2 = int(x2)
else:
if (-b - (delta ** 0.5)) % (2*a) == 0:
x2 = int(x2)
else:
x2 = f'{x2:.1f}'
print(f'\nX1 => {x1}')
print(f'X2 => {x2}') | import os
import time
print('Por favor, digite abaixo os valores da equação.')
a = str(input('\nValor de A: '))
b = str(input('Valor de B: '))
c = str(input('Valor de C: '))
print('\nAguarde um instante...')
time.sleep(1)
os.system('cls || clear')
print('='*50 + '\n' + f'{"Resolução":^50}' + '\n' + '='*50)
def print_equacao(a, b, c):
if int(b) < 0:
bn = b[1]
vb = f' - {bn}x'
else:
vb = f' + {b}x'
if int(c) < 0:
cn = c[1]
vc = f' - {cn}x'
else:
vc = f' + {c}x'
if b == 0:
vb = ''
if c == 0:
vc = ''
print(f'Equação = {a}x²{vb}{vc} = 0')
print_equacao(a, b, c)
a = int(a)
b = int(b)
c = int(c)
delta = (b*b) - 4 * a * c
print(f'\n∆ = {delta}')
if delta < 0:
print('\n\nDelta é menor que zero. Esta equação não tem x1/x2.')
else:
x1 = (-b + (delta ** 0.5)) / (2*a)
x2 = (-b - (delta ** 0.5)) / (2*a)
if x1 > 0:
x1 = int(x1)
else:
if (-b + (delta ** 0.5)) % (2*a) == 0:
x1 = int(x1)
else:
x1 = f'{x1:.1f}'
if x2 > 0:
x2 = int(x2)
else:
if (-b - (delta ** 0.5)) % (2*a) == 0:
x2 = int(x2)
else:
x2 = f'{x2:.1f}'
print(f'\nX1 => {x1}')
print(f'X2 => {x2}') |
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For a detailed description of the phases, see
# https://github.com/tesseract-ocr/tesseract/wiki/TrainingTesseract
#
import argparse
import atexit
import concurrent.futures
import logging
import os
import pathlib
import platform
import shutil
import subprocess
import sys
from datetime import date
from operator import itemgetter
from tempfile import TemporaryDirectory, mkdtemp
from tqdm import tqdm
from language_specific import VERTICAL_FONTS
log = logging.getLogger(__name__)
class TrainingArgs(argparse.Namespace):
def __init__(self):
super(TrainingArgs, self).__init__()
self.uname = platform.uname().system.lower()
self.lang_code = "eng"
self.timestamp = str(date.today())
self._font_config_cache = TemporaryDirectory(prefix="font_tmp")
self.font_config_cache = self._font_config_cache.name
self.fonts_dir = (
"/Library/Fonts/" if "darwin" in self.uname else "/usr/share/fonts/"
)
self.max_pages = 0
self.save_box_tiff = False
self.overwrite = False
self.linedata = False
self.run_shape_clustering = False
self.extract_font_properties = True
self.distort_image = False
def err_exit(msg):
log.critical(msg)
sys.exit(1)
# Helper function to run a command and append its output to a log. Aborts early
# if the program file is not found.
# Usage: run_command CMD ARG1 ARG2...
def run_command(cmd, *args, env=None):
for d in ("", "api/", "training/"):
testcmd = shutil.which(f"{d}{cmd}")
if shutil.which(testcmd):
cmd = testcmd
break
if not shutil.which(cmd):
err_exit(f"{cmd} not found")
log.debug(f"Running {cmd}")
args = list(args)
for idx, arg in enumerate(args):
log.debug(arg)
# Workaround for https://bugs.python.org/issue33617
# TypeError: argument of type 'WindowsPath' is not iterable
if isinstance(arg, pathlib.WindowsPath):
args[idx] = str(arg)
proc = subprocess.run(
[cmd, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env
)
proclog = logging.getLogger(cmd)
if proc.returncode == 0:
proclog.debug(proc.stdout.decode("utf-8", errors="replace"))
else:
try:
proclog.error(proc.stdout.decode("utf-8", errors="replace"))
except Exception as e:
proclog.error(e)
err_exit(f"Program {cmd} failed with return code {proc.returncode}. Abort.")
# Check if all the given files exist, or exit otherwise.
# Used to check required input files and produced output files in each phase.
# Usage: check_file_readable FILE1 FILE2...
def check_file_readable(*filenames):
if isinstance(filenames, (str, pathlib.Path)):
filenames = [filenames]
for filename in filenames:
try:
with pathlib.Path(filename).open():
pass
except FileNotFoundError:
err_exit(f"Required/expected file '{filename}' does not exist")
except PermissionError:
err_exit(f"{filename} is not readable")
except IOError as e:
err_exit(f"{filename} IO Error: {str(e)}")
return True
parser = argparse.ArgumentParser(
epilog="""
The font names specified in --fontlist need to be recognizable by Pango using
fontconfig. An easy way to list the canonical names of all fonts available on
your system is to run text2image with --list_available_fonts and the
appropriate --fonts_dir path.
"""
)
parser.add_argument(
"--fontlist",
dest="fonts",
nargs="+",
type=str,
help="A list of fontnames to train on.",
)
parser.add_argument("--fonts_dir", help="Path to font files.")
parser.add_argument("--tmp_dir", help="Path to temporary training directory.")
parser.add_argument(
"--lang", metavar="LANG_CODE", dest="lang_code", help="ISO 639 code."
)
parser.add_argument(
"--langdata_dir",
metavar="DATADIR",
help="Path to tesseract/training/langdata directory.",
)
parser.add_argument("--maxpages", type=int, dest="max_pages")
parser.add_argument(
"--output_dir", metavar="OUTPUTDIR", help="Location of output traineddata file."
)
parser.add_argument(
"--overwrite", action="store_true", help="Safe to overwrite files in output_dir."
)
parser.add_argument(
"--save_box_tiff",
action="store_true",
help="Save box/tiff pairs along with lstmf files.",
)
parser.add_argument(
"--linedata_only",
dest="linedata",
action="store_true",
help="Only generate training data for lstmtraining.",
)
inputdata_group = parser.add_argument_group(
"inputdata",
"OPTIONAL flags for input data. If unspecified we will look for them in the langdata_dir directory.",
)
inputdata_group.add_argument(
"--training_text", metavar="TEXTFILE", help="Text to render and use for training."
)
inputdata_group.add_argument(
"--wordlist",
dest="wordlist_file",
metavar="WORDFILE",
help="Word list for the language ordered by decreasing frequency.",
)
parser.add_argument("--extract_font_properties", action="store_true")
parser.add_argument(
"--noextract_font_properties", dest="extract_font_properties", action="store_false"
)
parser.add_argument(
"--distort_image", dest="distort_image", action="store_true"
)
tessdata_group = parser.add_argument_group(
"tessdata",
"OPTIONAL flag to specify location of existing traineddata files, required during feature extraction. If unspecified will use TESSDATA_PREFIX defined in the current environment.",
)
tessdata_group.add_argument(
"--tessdata_dir",
metavar="TESSDATADIR",
help="Path to tesseract/tessdata directory.",
)
parser.add_argument(
"--exposures",
metavar="EXPOSURES",
action="append",
nargs="+",
help="A list of exposure levels to use (e.g. -1,0,1).",
)
# Does simple command-line parsing and initialization.
def parse_flags(argv=None):
ctx = TrainingArgs()
log.debug(ctx)
parser.parse_args(args=argv, namespace=ctx)
log.debug(ctx)
if not ctx.lang_code:
err_exit("Need to specify a language --lang")
if not ctx.langdata_dir:
err_exit("Need to specify path to language files --langdata_dir")
if not ctx.tessdata_dir:
tessdata_prefix = os.environ.get("TESSDATA_PREFIX", "")
if not tessdata_prefix:
err_exit(
"Need to specify a --tessdata_dir or have a "
"TESSDATA_PREFIX variable defined in your environment"
)
else:
ctx.tessdata_dir = tessdata_prefix
if not ctx.output_dir:
ctx.output_dir = mkdtemp(prefix=f"trained-{ctx.lang_code}-{ctx.timestamp}")
log.info(f"Output directory set to: {ctx.output_dir}")
# Location where intermediate files will be created.
if not ctx.tmp_dir:
ctx.training_dir = mkdtemp(prefix=f"{ctx.lang_code}-{ctx.timestamp}")
else:
ctx.training_dir = mkdtemp(prefix=f"{ctx.lang_code}-{ctx.timestamp}", dir=ctx.tmp_dir)
# Location of log file for the whole run.
ctx.log_file = pathlib.Path(ctx.training_dir) / "tesstrain.log"
log.info(f"Log file location: {ctx.log_file}")
def show_tmpdir_location(training_dir):
# On successful exit we will delete this first; on failure we want to let the user
# know where the log is
if pathlib.Path(training_dir).exists():
print(f"Temporary files retained at: {training_dir}")
atexit.register(show_tmpdir_location, ctx.training_dir)
# Take training text and wordlist from the langdata directory if not
# specified in the command-line.
if not ctx.training_text:
ctx.training_text = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.training_text"
)
if not ctx.wordlist_file:
ctx.wordlist_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.wordlist"
)
ctx.word_bigrams_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.word.bigrams"
)
ctx.numbers_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.numbers"
)
ctx.punc_file = pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.punc"
ctx.bigram_freqs_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.bigram_freqs"
)
ctx.unigram_freqs_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.unigram_freqs"
)
ctx.train_ngrams_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.train_ngrams"
)
ctx.generate_dawgs = 1
log.debug(ctx)
return ctx
def cleanup(ctx):
shutil.copy(ctx.log_file, ctx.output_dir)
shutil.rmtree(ctx.training_dir)
return
# Function initializes font config with a unique font cache dir.
def initialize_fontconfig(ctx):
sample_path = pathlib.Path(ctx.font_config_cache) / "sample_text.txt"
pathlib.Path(sample_path).write_text("Text\n")
log.info(f"Testing font: {ctx.fonts[0]}")
run_command(
"text2image",
f"--fonts_dir={ctx.fonts_dir}",
f"--font={ctx.fonts[0]}",
f"--outputbase={sample_path}",
f"--text={sample_path}",
f"--fontconfig_tmpdir={ctx.font_config_cache}",
)
def make_fontname(font):
return font.replace(" ", "_").replace(",", "")
def make_outbase(ctx, fontname, exposure):
return pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.{fontname}.exp{exposure}"
# Helper function for phaseI_generate_image. Generates the image for a single
# language/font combination in a way that can be run in parallel.
def generate_font_image(ctx, font, exposure, char_spacing):
log.info(f"Rendering using {font}")
fontname = make_fontname(font)
outbase = make_outbase(ctx, fontname, exposure)
common_args = [
f"--fontconfig_tmpdir={ctx.font_config_cache}",
f"--fonts_dir={ctx.fonts_dir}",
f"--strip_unrenderable_words",
f"--leading={ctx.leading}",
f"--char_spacing={char_spacing}",
f"--exposure={exposure}",
f"--outputbase={outbase}",
f"--max_pages={ctx.max_pages}",
]
if ctx.distort_image:
common_args.append("--distort_image")
# add --writing_mode=vertical-upright to common_args if the font is
# specified to be rendered vertically.
if font in VERTICAL_FONTS:
common_args.append("--writing_mode=vertical-upright")
run_command(
"text2image",
*common_args,
f"--font={font}",
f"--text={ctx.training_text}",
*ctx.text2image_extra_args,
)
check_file_readable(str(outbase) + ".box", str(outbase) + ".tif")
if ctx.extract_font_properties and pathlib.Path(ctx.train_ngrams_file).exists():
log.info(f"Extracting font properties of {font}")
run_command(
"text2image",
*common_args,
f"--font={font}",
f"--ligatures=false",
f"--text={ctx.train_ngrams_file}",
f"--only_extract_font_properties",
f"--ptsize=32",
)
check_file_readable(str(outbase) + ".fontinfo")
return f"{font}-{exposure}"
# Phase I : Generate (I)mages from training text for each font.
def phase_I_generate_image(ctx, par_factor):
if not par_factor or par_factor <= 0:
par_factor = 1
log.info("=== Phase I: Generating training images ===")
check_file_readable(ctx.training_text)
char_spacing = 0.0
for exposure in ctx.exposures:
if ctx.extract_font_properties and pathlib.Path(ctx.bigram_freqs_file).exists():
# Parse .bigram_freqs file and compose a .train_ngrams file with text
# for tesseract to recognize during training. Take only the ngrams whose
# combined weight accounts for 95% of all the bigrams in the language.
lines = pathlib.Path(ctx.bigram_freqs_file).read_text(encoding="utf-8").split("\n")
records = (line.split(" ") for line in lines)
p = 0.99
ngram_frac = p * sum(int(rec[1]) for rec in records if len(rec) >= 2)
with pathlib.Path(ctx.train_ngrams_file).open("w", encoding="utf-8") as f:
cumsum = 0
for bigram, count in sorted(records, key=itemgetter(1), reverse=True):
if cumsum > ngram_frac:
break
f.write(bigram + " ")
cumsum += count
check_file_readable(ctx.train_ngrams_file)
with tqdm(
total=len(ctx.fonts)
) as pbar, concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
futures = [
executor.submit(generate_font_image, ctx, font, exposure, char_spacing)
for font in ctx.fonts
]
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as exc:
err_exit("Failed while generating images " + str(exc))
else:
pbar.update(1)
# Check that each process was successful.
for font in ctx.fonts:
fontname = make_fontname(font)
outbase = make_outbase(ctx, fontname, exposure)
check_file_readable(str(outbase) + ".box", str(outbase) + ".tif")
return
# Phase UP : Generate (U)nicharset and (P)roperties file.
def phase_UP_generate_unicharset(ctx):
log.info("=== Phase UP: Generating unicharset and unichar properties files ===")
box_files = pathlib.Path(ctx.training_dir).glob("*.box")
ctx.unicharset_file = pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.unicharset"
run_command(
"unicharset_extractor",
"--output_unicharset",
f"{ctx.unicharset_file}",
"--norm_mode",
f"{ctx.norm_mode}",
*box_files,
)
check_file_readable(ctx.unicharset_file)
ctx.xheights_file = pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.xheights"
run_command(
"set_unicharset_properties",
"-U",
f"{ctx.unicharset_file}",
"-O",
f"{ctx.unicharset_file}",
"-X",
f"{ctx.xheights_file}",
f"--script_dir={ctx.langdata_dir}",
)
check_file_readable(ctx.xheights_file)
# # Phase D : Generate (D)awg files from unicharset file and wordlist files
# phase_D_generate_dawg() {
# tlog "\n=== Phase D: Generating Dawg files ==="
# # Skip if requested
# if [[ ${GENERATE_DAWGS} -eq 0 ]]; then
# tlog "Skipping ${phase_name}"
# return
# fi
# # Output files
# WORD_DAWG=${TRAINING_DIR}/${LANG_CODE}.word-dawg
# FREQ_DAWG=${TRAINING_DIR}/${LANG_CODE}.freq-dawg
# PUNC_DAWG=${TRAINING_DIR}/${LANG_CODE}.punc-dawg
# NUMBER_DAWG=${TRAINING_DIR}/${LANG_CODE}.number-dawg
# BIGRAM_DAWG=${TRAINING_DIR}/${LANG_CODE}.bigram-dawg
# # Word DAWG
# local freq_wordlist_file=${TRAINING_DIR}/${LANG_CODE}.wordlist.clean.freq
# if [[ -s ${WORDLIST_FILE} ]]; then
# tlog "Generating word Dawg"
# check_file_readable ${unicharset_file}
# run_command wordlist2dawg -r 1 ${WORDLIST_FILE} ${WORD_DAWG} \
# ${UNICHARSET_FILE}
# check_file_readable ${WORD_DAWG}
# FREQ_DAWG_SIZE=100
# head -n ${FREQ_DAWG_SIZE} ${WORDLIST_FILE} > ${freq_wordlist_file}
# fi
# # Freq-word DAWG
# if [[ -s ${freq_wordlist_file} ]]; then
# check_file_readable ${UNICHARSET_FILE}
# tlog "Generating frequent-word Dawg"
# run_command wordlist2dawg -r 1 ${freq_wordlist_file} \
# ${FREQ_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${FREQ_DAWG}
# fi
# # Punctuation DAWG
# # -r arguments to wordlist2dawg denote RTL reverse policy
# # (see Trie::RTLReversePolicy enum in third_party/tesseract/dict/trie.h).
# # We specify 0/RRP_DO_NO_REVERSE when generating number DAWG,
# # 1/RRP_REVERSE_IF_HAS_RTL for freq and word DAWGS,
# # 2/RRP_FORCE_REVERSE for the punctuation DAWG.
# local punc_reverse_policy=0;
# if [[ "${LANG_IS_RTL}" == "1" ]]; then
# punc_reverse_policy=2
# fi
# if [[ ! -s ${PUNC_FILE} ]]; then
# PUNC_FILE="{ctx.langdata_dir}/common.punc"
# fi
# check_file_readable ${PUNC_FILE}
# run_command wordlist2dawg -r ${punc_reverse_policy} \
# ${PUNC_FILE} ${PUNC_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${PUNC_DAWG}
# # Numbers DAWG
# if [[ -s ${NUMBERS_FILE} ]]; then
# run_command wordlist2dawg -r 0 \
# ${NUMBERS_FILE} ${NUMBER_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${NUMBER_DAWG}
# fi
# # Bigram dawg
# if [[ -s ${WORD_BIGRAMS_FILE} ]]; then
# run_command wordlist2dawg -r 1 \
# ${WORD_BIGRAMS_FILE} ${BIGRAM_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${BIGRAM_DAWG}
# fi
# }
# Phase E : (E)xtract .tr feature files from .tif/.box files
def phase_E_extract_features(ctx, box_config, ext):
log.info(f"=== Phase E: Generating {ext} files ===")
img_files = list(pathlib.Path(ctx.training_dir).glob("*.exp*.tif"))
log.debug(img_files)
# Use any available language-specific configs.
config = ""
testconfig = pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.config"
if testconfig.exists():
config = testconfig
log.info(f"Using {ctx.lang_code}.config")
tessdata_environ = os.environ.copy()
tessdata_environ["TESSDATA_PREFIX"] = str(ctx.tessdata_dir)
log.info(f"Using TESSDATA_PREFIX={tessdata_environ["TESSDATA_PREFIX"]}")
with tqdm(total=len(img_files)) as pbar, concurrent.futures.ThreadPoolExecutor(
max_workers=2
) as executor:
futures = []
for img_file in img_files:
future = executor.submit(
run_command,
"tesseract",
img_file,
pathlib.Path(img_file).with_suffix(""),
*box_config,
config,
env=tessdata_environ,
)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as exc:
err_exit("Failed while extracting features: " + str(exc))
else:
pbar.update(1)
# Check that all the output files were produced.
for img_file in img_files:
check_file_readable(pathlib.Path(img_file.with_suffix("." + ext)))
return
# # Phase C : (C)luster feature prototypes in .tr into normproto file (cnTraining)
# # phaseC_cluster_prototypes ${TRAINING_DIR}/${LANG_CODE}.normproto
# phase_C_cluster_prototypes() {
# tlog "\n=== Phase C: Clustering feature prototypes (cnTraining) ==="
# local out_normproto=$1
# run_command cntraining -D "${TRAINING_DIR}/" \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/normproto
# mv ${TRAINING_DIR}/normproto ${out_normproto}
# }
# # Phase S : (S)hape clustering
# phase_S_cluster_shapes() {
# if ((! RUN_SHAPE_CLUSTERING)); then
# tlog "\n=== Shape Clustering disabled ==="
# return
# fi
# check_file_readable {ctx.langdata_dir}/font_properties
# local font_props="-F {ctx.langdata_dir}/font_properties"
# if [[ -r ${TRAINING_DIR}/${LANG_CODE}.xheights ]] &&\
# [[ -s ${TRAINING_DIR}/${LANG_CODE}.xheights ]]; then
# font_props=${font_props}" -X ${TRAINING_DIR}/${LANG_CODE}.xheights"
# fi
# run_command shapeclustering \
# -D "${TRAINING_DIR}/" \
# -U ${TRAINING_DIR}/${LANG_CODE}.unicharset \
# -O ${TRAINING_DIR}/${LANG_CODE}.mfunicharset \
# ${font_props} \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/shapetable \
# ${TRAINING_DIR}/${LANG_CODE}.mfunicharset
# }
# # Phase M : Clustering microfeatures (mfTraining)
# phase_M_cluster_microfeatures() {
# tlog "\n=== Phase M : Clustering microfeatures (mfTraining) ==="
# check_file_readable {ctx.langdata_dir}/font_properties
# font_props="-F {ctx.langdata_dir}/font_properties"
# if [[ -r ${TRAINING_DIR}/${LANG_CODE}.xheights ]] && \
# [[ -s ${TRAINING_DIR}/${LANG_CODE}.xheights ]]; then
# font_props=${font_props}" -X ${TRAINING_DIR}/${LANG_CODE}.xheights"
# fi
# run_command mftraining \
# -D "${TRAINING_DIR}/" \
# -U ${TRAINING_DIR}/${LANG_CODE}.unicharset \
# -O ${TRAINING_DIR}/${LANG_CODE}.mfunicharset \
# ${font_props} \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/inttemp ${TRAINING_DIR}/shapetable \
# ${TRAINING_DIR}/pffmtable ${TRAINING_DIR}/${LANG_CODE}.mfunicharset
# mv ${TRAINING_DIR}/inttemp ${TRAINING_DIR}/${LANG_CODE}.inttemp
# mv ${TRAINING_DIR}/shapetable ${TRAINING_DIR}/${LANG_CODE}.shapetable
# mv ${TRAINING_DIR}/pffmtable ${TRAINING_DIR}/${LANG_CODE}.pffmtable
# mv ${TRAINING_DIR}/${LANG_CODE}.mfunicharset ${TRAINING_DIR}/${LANG_CODE}.unicharset
# }
# phase_B_generate_ambiguities() {
# tlog "\n=== Phase B : ambiguities training ==="
# # Check for manually created ambiguities data.
# if [[ -r {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs ]]; then
# tlog "Found file {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs"
# cp {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs \
# ${TRAINING_DIR}/${LANG_CODE}.unicharambigs
# # Make it writable, as it may be read-only in the client.
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.unicharambigs
# return
# else
# tlog "No unicharambigs file found!"
# fi
# # TODO: Add support for generating ambiguities automatically.
# }
def make_lstmdata(ctx):
log.info("=== Constructing LSTM training data ===")
lang_prefix = f"{ctx.langdata_dir}/{ctx.lang_code}/{ctx.lang_code}"
path_output = pathlib.Path(ctx.output_dir)
if not path_output.is_dir():
log.info(f"Creating new directory {ctx.output_dir}")
path_output.mkdir(exist_ok=True, parents=True)
args = []
if ctx.lang_is_rtl:
args.append("--lang_is_rtl")
if ctx.norm_mode >= 2:
args.append("--pass_through_recoder")
# Build the starter traineddata from the inputs.
run_command(
"combine_lang_model",
"--input_unicharset",
f"{ctx.training_dir}/{ctx.lang_code}.unicharset",
"--script_dir",
f"{ctx.langdata_dir}",
"--words",
f"{lang_prefix}.wordlist",
"--numbers",
f"{lang_prefix}.numbers",
"--puncs",
f"{lang_prefix}.punc",
"--output_dir",
f"{ctx.output_dir}",
"--lang",
f"{ctx.lang_code}",
*args,
)
def get_file_list():
training_path = pathlib.Path(ctx.training_dir)
if ctx.save_box_tiff:
log.info("=== Saving box/tiff pairs for training data ===")
yield from training_path.glob(f"{ctx.lang_code}*.box")
yield from training_path.glob(f"{ctx.lang_code}*.tif")
log.info("=== Moving lstmf files for training data ===")
yield from training_path.glob(f"{ctx.lang_code}.*.lstmf")
for f in get_file_list():
log.debug(f"Moving {f} to {path_output / f.name}")
shutil.move(str(f), path_output / f.name)
lstm_list = f"{ctx.output_dir}/{ctx.lang_code}.training_files.txt"
dir_listing = (str(p) for p in path_output.glob(f"{ctx.lang_code}.*.lstmf"))
pathlib.Path(lstm_list).write_text("\n".join(dir_listing))
# make__traineddata() {
# tlog "\n=== Making final traineddata file ==="
# local lang_prefix={ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}
# # Combine available files for this language from the langdata dir.
# if [[ -r ${lang_prefix}.config ]]; then
# tlog "Copying ${lang_prefix}.config to ${TRAINING_DIR}"
# cp ${lang_prefix}.config ${TRAINING_DIR}
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.config
# fi
# if [[ -r ${lang_prefix}.params-model ]]; then
# tlog "Copying ${lang_prefix}.params-model to ${TRAINING_DIR}"
# cp ${lang_prefix}.params-model ${TRAINING_DIR}
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.params-model
# fi
# # Compose the traineddata file.
# run_command combine_tessdata ${TRAINING_DIR}/${LANG_CODE}.
# # Copy it to the output dir, overwriting only if allowed by the cmdline flag.
# if [[ ! -d ${OUTPUT_DIR} ]]; then
# tlog "Creating new directory ${OUTPUT_DIR}"
# mkdir -p ${OUTPUT_DIR}
# fi
# local destfile=${OUTPUT_DIR}/${LANG_CODE}.traineddata;
# if [[ -f ${destfile} ]] && ((! OVERWRITE)); then
# err_exit "File ${destfile} exists and no --overwrite specified";
# fi
# tlog "Moving ${TRAINING_DIR}/${LANG_CODE}.traineddata to ${OUTPUT_DIR}"
# cp -f ${TRAINING_DIR}/${LANG_CODE}.traineddata ${destfile}
# }
| # (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For a detailed description of the phases, see
# https://github.com/tesseract-ocr/tesseract/wiki/TrainingTesseract
#
import argparse
import atexit
import concurrent.futures
import logging
import os
import pathlib
import platform
import shutil
import subprocess
import sys
from datetime import date
from operator import itemgetter
from tempfile import TemporaryDirectory, mkdtemp
from tqdm import tqdm
from language_specific import VERTICAL_FONTS
log = logging.getLogger(__name__)
class TrainingArgs(argparse.Namespace):
def __init__(self):
super(TrainingArgs, self).__init__()
self.uname = platform.uname().system.lower()
self.lang_code = "eng"
self.timestamp = str(date.today())
self._font_config_cache = TemporaryDirectory(prefix="font_tmp")
self.font_config_cache = self._font_config_cache.name
self.fonts_dir = (
"/Library/Fonts/" if "darwin" in self.uname else "/usr/share/fonts/"
)
self.max_pages = 0
self.save_box_tiff = False
self.overwrite = False
self.linedata = False
self.run_shape_clustering = False
self.extract_font_properties = True
self.distort_image = False
def err_exit(msg):
log.critical(msg)
sys.exit(1)
# Helper function to run a command and append its output to a log. Aborts early
# if the program file is not found.
# Usage: run_command CMD ARG1 ARG2...
def run_command(cmd, *args, env=None):
for d in ("", "api/", "training/"):
testcmd = shutil.which(f"{d}{cmd}")
if shutil.which(testcmd):
cmd = testcmd
break
if not shutil.which(cmd):
err_exit(f"{cmd} not found")
log.debug(f"Running {cmd}")
args = list(args)
for idx, arg in enumerate(args):
log.debug(arg)
# Workaround for https://bugs.python.org/issue33617
# TypeError: argument of type 'WindowsPath' is not iterable
if isinstance(arg, pathlib.WindowsPath):
args[idx] = str(arg)
proc = subprocess.run(
[cmd, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env
)
proclog = logging.getLogger(cmd)
if proc.returncode == 0:
proclog.debug(proc.stdout.decode("utf-8", errors="replace"))
else:
try:
proclog.error(proc.stdout.decode("utf-8", errors="replace"))
except Exception as e:
proclog.error(e)
err_exit(f"Program {cmd} failed with return code {proc.returncode}. Abort.")
# Check if all the given files exist, or exit otherwise.
# Used to check required input files and produced output files in each phase.
# Usage: check_file_readable FILE1 FILE2...
def check_file_readable(*filenames):
if isinstance(filenames, (str, pathlib.Path)):
filenames = [filenames]
for filename in filenames:
try:
with pathlib.Path(filename).open():
pass
except FileNotFoundError:
err_exit(f"Required/expected file '{filename}' does not exist")
except PermissionError:
err_exit(f"{filename} is not readable")
except IOError as e:
err_exit(f"{filename} IO Error: {str(e)}")
return True
parser = argparse.ArgumentParser(
epilog="""
The font names specified in --fontlist need to be recognizable by Pango using
fontconfig. An easy way to list the canonical names of all fonts available on
your system is to run text2image with --list_available_fonts and the
appropriate --fonts_dir path.
"""
)
parser.add_argument(
"--fontlist",
dest="fonts",
nargs="+",
type=str,
help="A list of fontnames to train on.",
)
parser.add_argument("--fonts_dir", help="Path to font files.")
parser.add_argument("--tmp_dir", help="Path to temporary training directory.")
parser.add_argument(
"--lang", metavar="LANG_CODE", dest="lang_code", help="ISO 639 code."
)
parser.add_argument(
"--langdata_dir",
metavar="DATADIR",
help="Path to tesseract/training/langdata directory.",
)
parser.add_argument("--maxpages", type=int, dest="max_pages")
parser.add_argument(
"--output_dir", metavar="OUTPUTDIR", help="Location of output traineddata file."
)
parser.add_argument(
"--overwrite", action="store_true", help="Safe to overwrite files in output_dir."
)
parser.add_argument(
"--save_box_tiff",
action="store_true",
help="Save box/tiff pairs along with lstmf files.",
)
parser.add_argument(
"--linedata_only",
dest="linedata",
action="store_true",
help="Only generate training data for lstmtraining.",
)
inputdata_group = parser.add_argument_group(
"inputdata",
"OPTIONAL flags for input data. If unspecified we will look for them in the langdata_dir directory.",
)
inputdata_group.add_argument(
"--training_text", metavar="TEXTFILE", help="Text to render and use for training."
)
inputdata_group.add_argument(
"--wordlist",
dest="wordlist_file",
metavar="WORDFILE",
help="Word list for the language ordered by decreasing frequency.",
)
parser.add_argument("--extract_font_properties", action="store_true")
parser.add_argument(
"--noextract_font_properties", dest="extract_font_properties", action="store_false"
)
parser.add_argument(
"--distort_image", dest="distort_image", action="store_true"
)
tessdata_group = parser.add_argument_group(
"tessdata",
"OPTIONAL flag to specify location of existing traineddata files, required during feature extraction. If unspecified will use TESSDATA_PREFIX defined in the current environment.",
)
tessdata_group.add_argument(
"--tessdata_dir",
metavar="TESSDATADIR",
help="Path to tesseract/tessdata directory.",
)
parser.add_argument(
"--exposures",
metavar="EXPOSURES",
action="append",
nargs="+",
help="A list of exposure levels to use (e.g. -1,0,1).",
)
# Does simple command-line parsing and initialization.
def parse_flags(argv=None):
ctx = TrainingArgs()
log.debug(ctx)
parser.parse_args(args=argv, namespace=ctx)
log.debug(ctx)
if not ctx.lang_code:
err_exit("Need to specify a language --lang")
if not ctx.langdata_dir:
err_exit("Need to specify path to language files --langdata_dir")
if not ctx.tessdata_dir:
tessdata_prefix = os.environ.get("TESSDATA_PREFIX", "")
if not tessdata_prefix:
err_exit(
"Need to specify a --tessdata_dir or have a "
"TESSDATA_PREFIX variable defined in your environment"
)
else:
ctx.tessdata_dir = tessdata_prefix
if not ctx.output_dir:
ctx.output_dir = mkdtemp(prefix=f"trained-{ctx.lang_code}-{ctx.timestamp}")
log.info(f"Output directory set to: {ctx.output_dir}")
# Location where intermediate files will be created.
if not ctx.tmp_dir:
ctx.training_dir = mkdtemp(prefix=f"{ctx.lang_code}-{ctx.timestamp}")
else:
ctx.training_dir = mkdtemp(prefix=f"{ctx.lang_code}-{ctx.timestamp}", dir=ctx.tmp_dir)
# Location of log file for the whole run.
ctx.log_file = pathlib.Path(ctx.training_dir) / "tesstrain.log"
log.info(f"Log file location: {ctx.log_file}")
def show_tmpdir_location(training_dir):
# On successful exit we will delete this first; on failure we want to let the user
# know where the log is
if pathlib.Path(training_dir).exists():
print(f"Temporary files retained at: {training_dir}")
atexit.register(show_tmpdir_location, ctx.training_dir)
# Take training text and wordlist from the langdata directory if not
# specified in the command-line.
if not ctx.training_text:
ctx.training_text = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.training_text"
)
if not ctx.wordlist_file:
ctx.wordlist_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.wordlist"
)
ctx.word_bigrams_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.word.bigrams"
)
ctx.numbers_file = (
pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.numbers"
)
ctx.punc_file = pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.punc"
ctx.bigram_freqs_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.bigram_freqs"
)
ctx.unigram_freqs_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.unigram_freqs"
)
ctx.train_ngrams_file = pathlib.Path(ctx.training_text).with_suffix(
".training_text.train_ngrams"
)
ctx.generate_dawgs = 1
log.debug(ctx)
return ctx
def cleanup(ctx):
shutil.copy(ctx.log_file, ctx.output_dir)
shutil.rmtree(ctx.training_dir)
return
# Function initializes font config with a unique font cache dir.
def initialize_fontconfig(ctx):
sample_path = pathlib.Path(ctx.font_config_cache) / "sample_text.txt"
pathlib.Path(sample_path).write_text("Text\n")
log.info(f"Testing font: {ctx.fonts[0]}")
run_command(
"text2image",
f"--fonts_dir={ctx.fonts_dir}",
f"--font={ctx.fonts[0]}",
f"--outputbase={sample_path}",
f"--text={sample_path}",
f"--fontconfig_tmpdir={ctx.font_config_cache}",
)
def make_fontname(font):
return font.replace(" ", "_").replace(",", "")
def make_outbase(ctx, fontname, exposure):
return pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.{fontname}.exp{exposure}"
# Helper function for phaseI_generate_image. Generates the image for a single
# language/font combination in a way that can be run in parallel.
def generate_font_image(ctx, font, exposure, char_spacing):
log.info(f"Rendering using {font}")
fontname = make_fontname(font)
outbase = make_outbase(ctx, fontname, exposure)
common_args = [
f"--fontconfig_tmpdir={ctx.font_config_cache}",
f"--fonts_dir={ctx.fonts_dir}",
f"--strip_unrenderable_words",
f"--leading={ctx.leading}",
f"--char_spacing={char_spacing}",
f"--exposure={exposure}",
f"--outputbase={outbase}",
f"--max_pages={ctx.max_pages}",
]
if ctx.distort_image:
common_args.append("--distort_image")
# add --writing_mode=vertical-upright to common_args if the font is
# specified to be rendered vertically.
if font in VERTICAL_FONTS:
common_args.append("--writing_mode=vertical-upright")
run_command(
"text2image",
*common_args,
f"--font={font}",
f"--text={ctx.training_text}",
*ctx.text2image_extra_args,
)
check_file_readable(str(outbase) + ".box", str(outbase) + ".tif")
if ctx.extract_font_properties and pathlib.Path(ctx.train_ngrams_file).exists():
log.info(f"Extracting font properties of {font}")
run_command(
"text2image",
*common_args,
f"--font={font}",
f"--ligatures=false",
f"--text={ctx.train_ngrams_file}",
f"--only_extract_font_properties",
f"--ptsize=32",
)
check_file_readable(str(outbase) + ".fontinfo")
return f"{font}-{exposure}"
# Phase I : Generate (I)mages from training text for each font.
def phase_I_generate_image(ctx, par_factor):
if not par_factor or par_factor <= 0:
par_factor = 1
log.info("=== Phase I: Generating training images ===")
check_file_readable(ctx.training_text)
char_spacing = 0.0
for exposure in ctx.exposures:
if ctx.extract_font_properties and pathlib.Path(ctx.bigram_freqs_file).exists():
# Parse .bigram_freqs file and compose a .train_ngrams file with text
# for tesseract to recognize during training. Take only the ngrams whose
# combined weight accounts for 95% of all the bigrams in the language.
lines = pathlib.Path(ctx.bigram_freqs_file).read_text(encoding="utf-8").split("\n")
records = (line.split(" ") for line in lines)
p = 0.99
ngram_frac = p * sum(int(rec[1]) for rec in records if len(rec) >= 2)
with pathlib.Path(ctx.train_ngrams_file).open("w", encoding="utf-8") as f:
cumsum = 0
for bigram, count in sorted(records, key=itemgetter(1), reverse=True):
if cumsum > ngram_frac:
break
f.write(bigram + " ")
cumsum += count
check_file_readable(ctx.train_ngrams_file)
with tqdm(
total=len(ctx.fonts)
) as pbar, concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
futures = [
executor.submit(generate_font_image, ctx, font, exposure, char_spacing)
for font in ctx.fonts
]
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as exc:
err_exit("Failed while generating images " + str(exc))
else:
pbar.update(1)
# Check that each process was successful.
for font in ctx.fonts:
fontname = make_fontname(font)
outbase = make_outbase(ctx, fontname, exposure)
check_file_readable(str(outbase) + ".box", str(outbase) + ".tif")
return
# Phase UP : Generate (U)nicharset and (P)roperties file.
def phase_UP_generate_unicharset(ctx):
log.info("=== Phase UP: Generating unicharset and unichar properties files ===")
box_files = pathlib.Path(ctx.training_dir).glob("*.box")
ctx.unicharset_file = pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.unicharset"
run_command(
"unicharset_extractor",
"--output_unicharset",
f"{ctx.unicharset_file}",
"--norm_mode",
f"{ctx.norm_mode}",
*box_files,
)
check_file_readable(ctx.unicharset_file)
ctx.xheights_file = pathlib.Path(ctx.training_dir) / f"{ctx.lang_code}.xheights"
run_command(
"set_unicharset_properties",
"-U",
f"{ctx.unicharset_file}",
"-O",
f"{ctx.unicharset_file}",
"-X",
f"{ctx.xheights_file}",
f"--script_dir={ctx.langdata_dir}",
)
check_file_readable(ctx.xheights_file)
# # Phase D : Generate (D)awg files from unicharset file and wordlist files
# phase_D_generate_dawg() {
# tlog "\n=== Phase D: Generating Dawg files ==="
# # Skip if requested
# if [[ ${GENERATE_DAWGS} -eq 0 ]]; then
# tlog "Skipping ${phase_name}"
# return
# fi
# # Output files
# WORD_DAWG=${TRAINING_DIR}/${LANG_CODE}.word-dawg
# FREQ_DAWG=${TRAINING_DIR}/${LANG_CODE}.freq-dawg
# PUNC_DAWG=${TRAINING_DIR}/${LANG_CODE}.punc-dawg
# NUMBER_DAWG=${TRAINING_DIR}/${LANG_CODE}.number-dawg
# BIGRAM_DAWG=${TRAINING_DIR}/${LANG_CODE}.bigram-dawg
# # Word DAWG
# local freq_wordlist_file=${TRAINING_DIR}/${LANG_CODE}.wordlist.clean.freq
# if [[ -s ${WORDLIST_FILE} ]]; then
# tlog "Generating word Dawg"
# check_file_readable ${unicharset_file}
# run_command wordlist2dawg -r 1 ${WORDLIST_FILE} ${WORD_DAWG} \
# ${UNICHARSET_FILE}
# check_file_readable ${WORD_DAWG}
# FREQ_DAWG_SIZE=100
# head -n ${FREQ_DAWG_SIZE} ${WORDLIST_FILE} > ${freq_wordlist_file}
# fi
# # Freq-word DAWG
# if [[ -s ${freq_wordlist_file} ]]; then
# check_file_readable ${UNICHARSET_FILE}
# tlog "Generating frequent-word Dawg"
# run_command wordlist2dawg -r 1 ${freq_wordlist_file} \
# ${FREQ_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${FREQ_DAWG}
# fi
# # Punctuation DAWG
# # -r arguments to wordlist2dawg denote RTL reverse policy
# # (see Trie::RTLReversePolicy enum in third_party/tesseract/dict/trie.h).
# # We specify 0/RRP_DO_NO_REVERSE when generating number DAWG,
# # 1/RRP_REVERSE_IF_HAS_RTL for freq and word DAWGS,
# # 2/RRP_FORCE_REVERSE for the punctuation DAWG.
# local punc_reverse_policy=0;
# if [[ "${LANG_IS_RTL}" == "1" ]]; then
# punc_reverse_policy=2
# fi
# if [[ ! -s ${PUNC_FILE} ]]; then
# PUNC_FILE="{ctx.langdata_dir}/common.punc"
# fi
# check_file_readable ${PUNC_FILE}
# run_command wordlist2dawg -r ${punc_reverse_policy} \
# ${PUNC_FILE} ${PUNC_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${PUNC_DAWG}
# # Numbers DAWG
# if [[ -s ${NUMBERS_FILE} ]]; then
# run_command wordlist2dawg -r 0 \
# ${NUMBERS_FILE} ${NUMBER_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${NUMBER_DAWG}
# fi
# # Bigram dawg
# if [[ -s ${WORD_BIGRAMS_FILE} ]]; then
# run_command wordlist2dawg -r 1 \
# ${WORD_BIGRAMS_FILE} ${BIGRAM_DAWG} ${UNICHARSET_FILE}
# check_file_readable ${BIGRAM_DAWG}
# fi
# }
# Phase E : (E)xtract .tr feature files from .tif/.box files
def phase_E_extract_features(ctx, box_config, ext):
log.info(f"=== Phase E: Generating {ext} files ===")
img_files = list(pathlib.Path(ctx.training_dir).glob("*.exp*.tif"))
log.debug(img_files)
# Use any available language-specific configs.
config = ""
testconfig = pathlib.Path(ctx.langdata_dir) / ctx.lang_code / f"{ctx.lang_code}.config"
if testconfig.exists():
config = testconfig
log.info(f"Using {ctx.lang_code}.config")
tessdata_environ = os.environ.copy()
tessdata_environ["TESSDATA_PREFIX"] = str(ctx.tessdata_dir)
log.info(f"Using TESSDATA_PREFIX={tessdata_environ['TESSDATA_PREFIX']}")
with tqdm(total=len(img_files)) as pbar, concurrent.futures.ThreadPoolExecutor(
max_workers=2
) as executor:
futures = []
for img_file in img_files:
future = executor.submit(
run_command,
"tesseract",
img_file,
pathlib.Path(img_file).with_suffix(""),
*box_config,
config,
env=tessdata_environ,
)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as exc:
err_exit("Failed while extracting features: " + str(exc))
else:
pbar.update(1)
# Check that all the output files were produced.
for img_file in img_files:
check_file_readable(pathlib.Path(img_file.with_suffix("." + ext)))
return
# # Phase C : (C)luster feature prototypes in .tr into normproto file (cnTraining)
# # phaseC_cluster_prototypes ${TRAINING_DIR}/${LANG_CODE}.normproto
# phase_C_cluster_prototypes() {
# tlog "\n=== Phase C: Clustering feature prototypes (cnTraining) ==="
# local out_normproto=$1
# run_command cntraining -D "${TRAINING_DIR}/" \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/normproto
# mv ${TRAINING_DIR}/normproto ${out_normproto}
# }
# # Phase S : (S)hape clustering
# phase_S_cluster_shapes() {
# if ((! RUN_SHAPE_CLUSTERING)); then
# tlog "\n=== Shape Clustering disabled ==="
# return
# fi
# check_file_readable {ctx.langdata_dir}/font_properties
# local font_props="-F {ctx.langdata_dir}/font_properties"
# if [[ -r ${TRAINING_DIR}/${LANG_CODE}.xheights ]] &&\
# [[ -s ${TRAINING_DIR}/${LANG_CODE}.xheights ]]; then
# font_props=${font_props}" -X ${TRAINING_DIR}/${LANG_CODE}.xheights"
# fi
# run_command shapeclustering \
# -D "${TRAINING_DIR}/" \
# -U ${TRAINING_DIR}/${LANG_CODE}.unicharset \
# -O ${TRAINING_DIR}/${LANG_CODE}.mfunicharset \
# ${font_props} \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/shapetable \
# ${TRAINING_DIR}/${LANG_CODE}.mfunicharset
# }
# # Phase M : Clustering microfeatures (mfTraining)
# phase_M_cluster_microfeatures() {
# tlog "\n=== Phase M : Clustering microfeatures (mfTraining) ==="
# check_file_readable {ctx.langdata_dir}/font_properties
# font_props="-F {ctx.langdata_dir}/font_properties"
# if [[ -r ${TRAINING_DIR}/${LANG_CODE}.xheights ]] && \
# [[ -s ${TRAINING_DIR}/${LANG_CODE}.xheights ]]; then
# font_props=${font_props}" -X ${TRAINING_DIR}/${LANG_CODE}.xheights"
# fi
# run_command mftraining \
# -D "${TRAINING_DIR}/" \
# -U ${TRAINING_DIR}/${LANG_CODE}.unicharset \
# -O ${TRAINING_DIR}/${LANG_CODE}.mfunicharset \
# ${font_props} \
# $(ls ${TRAINING_DIR}/*.tr)
# check_file_readable ${TRAINING_DIR}/inttemp ${TRAINING_DIR}/shapetable \
# ${TRAINING_DIR}/pffmtable ${TRAINING_DIR}/${LANG_CODE}.mfunicharset
# mv ${TRAINING_DIR}/inttemp ${TRAINING_DIR}/${LANG_CODE}.inttemp
# mv ${TRAINING_DIR}/shapetable ${TRAINING_DIR}/${LANG_CODE}.shapetable
# mv ${TRAINING_DIR}/pffmtable ${TRAINING_DIR}/${LANG_CODE}.pffmtable
# mv ${TRAINING_DIR}/${LANG_CODE}.mfunicharset ${TRAINING_DIR}/${LANG_CODE}.unicharset
# }
# phase_B_generate_ambiguities() {
# tlog "\n=== Phase B : ambiguities training ==="
# # Check for manually created ambiguities data.
# if [[ -r {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs ]]; then
# tlog "Found file {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs"
# cp {ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}.unicharambigs \
# ${TRAINING_DIR}/${LANG_CODE}.unicharambigs
# # Make it writable, as it may be read-only in the client.
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.unicharambigs
# return
# else
# tlog "No unicharambigs file found!"
# fi
# # TODO: Add support for generating ambiguities automatically.
# }
def make_lstmdata(ctx):
log.info("=== Constructing LSTM training data ===")
lang_prefix = f"{ctx.langdata_dir}/{ctx.lang_code}/{ctx.lang_code}"
path_output = pathlib.Path(ctx.output_dir)
if not path_output.is_dir():
log.info(f"Creating new directory {ctx.output_dir}")
path_output.mkdir(exist_ok=True, parents=True)
args = []
if ctx.lang_is_rtl:
args.append("--lang_is_rtl")
if ctx.norm_mode >= 2:
args.append("--pass_through_recoder")
# Build the starter traineddata from the inputs.
run_command(
"combine_lang_model",
"--input_unicharset",
f"{ctx.training_dir}/{ctx.lang_code}.unicharset",
"--script_dir",
f"{ctx.langdata_dir}",
"--words",
f"{lang_prefix}.wordlist",
"--numbers",
f"{lang_prefix}.numbers",
"--puncs",
f"{lang_prefix}.punc",
"--output_dir",
f"{ctx.output_dir}",
"--lang",
f"{ctx.lang_code}",
*args,
)
def get_file_list():
training_path = pathlib.Path(ctx.training_dir)
if ctx.save_box_tiff:
log.info("=== Saving box/tiff pairs for training data ===")
yield from training_path.glob(f"{ctx.lang_code}*.box")
yield from training_path.glob(f"{ctx.lang_code}*.tif")
log.info("=== Moving lstmf files for training data ===")
yield from training_path.glob(f"{ctx.lang_code}.*.lstmf")
for f in get_file_list():
log.debug(f"Moving {f} to {path_output / f.name}")
shutil.move(str(f), path_output / f.name)
lstm_list = f"{ctx.output_dir}/{ctx.lang_code}.training_files.txt"
dir_listing = (str(p) for p in path_output.glob(f"{ctx.lang_code}.*.lstmf"))
pathlib.Path(lstm_list).write_text("\n".join(dir_listing))
# make__traineddata() {
# tlog "\n=== Making final traineddata file ==="
# local lang_prefix={ctx.langdata_dir}/${LANG_CODE}/${LANG_CODE}
# # Combine available files for this language from the langdata dir.
# if [[ -r ${lang_prefix}.config ]]; then
# tlog "Copying ${lang_prefix}.config to ${TRAINING_DIR}"
# cp ${lang_prefix}.config ${TRAINING_DIR}
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.config
# fi
# if [[ -r ${lang_prefix}.params-model ]]; then
# tlog "Copying ${lang_prefix}.params-model to ${TRAINING_DIR}"
# cp ${lang_prefix}.params-model ${TRAINING_DIR}
# chmod u+w ${TRAINING_DIR}/${LANG_CODE}.params-model
# fi
# # Compose the traineddata file.
# run_command combine_tessdata ${TRAINING_DIR}/${LANG_CODE}.
# # Copy it to the output dir, overwriting only if allowed by the cmdline flag.
# if [[ ! -d ${OUTPUT_DIR} ]]; then
# tlog "Creating new directory ${OUTPUT_DIR}"
# mkdir -p ${OUTPUT_DIR}
# fi
# local destfile=${OUTPUT_DIR}/${LANG_CODE}.traineddata;
# if [[ -f ${destfile} ]] && ((! OVERWRITE)); then
# err_exit "File ${destfile} exists and no --overwrite specified";
# fi
# tlog "Moving ${TRAINING_DIR}/${LANG_CODE}.traineddata to ${OUTPUT_DIR}"
# cp -f ${TRAINING_DIR}/${LANG_CODE}.traineddata ${destfile}
# }
|
import abc
import asyncio
import logging
import typing as t
from collections import namedtuple
from functools import partial
import discord
from discord import Guild, HTTPException, Member, Message, Reaction, User
from discord.ext.commands import Context
from bot import constants
from bot.api import ResponseCodeError
from bot.bot import Bot
log = logging.getLogger(__name__)
# These objects are declared as namedtuples because tuples are hashable,
# something that we make use of when diffing site roles against guild roles.
_Role = namedtuple('Role', ('id', 'name', 'colour', 'permissions', 'position'))
_User = namedtuple('User', ('id', 'name', 'discriminator', 'roles', 'in_guild'))
_Diff = namedtuple('Diff', ('created', 'updated', 'deleted'))
class Syncer(abc.ABC):
"""Base class for synchronising the database with objects in the Discord cache."""
_CORE_DEV_MENTION = f"<@&{constants.Roles.core_developers}> "
_REACTION_EMOJIS = (constants.Emojis.check_mark, constants.Emojis.cross_mark)
def __init__(self, bot: Bot) -> None:
self.bot = bot
@property
@abc.abstractmethod
def name(self) -> str:
"""The name of the syncer; used in output messages and logging."""
raise NotImplementedError # pragma: no cover
async def _send_prompt(self, message: t.Optional[Message] = None) -> t.Optional[Message]:
"""
Send a prompt to confirm or abort a sync using reactions and return the sent message.
If a message is given, it is edited to display the prompt and reactions. Otherwise, a new
message is sent to the dev-core channel and mentions the core developers role. If the
channel cannot be retrieved, return None.
"""
log.trace(f"Sending {self.name} sync confirmation prompt.")
msg_content = (
f'Possible cache issue while syncing {self.name}s. '
f'More than {constants.Sync.max_diff} {self.name}s were changed. '
f'React to confirm or abort the sync.'
)
# Send to core developers if it's an automatic sync.
if not message:
log.trace("Message not provided for confirmation; creating a new one in dev-core.")
channel = self.bot.get_channel(constants.Channels.dev_core)
if not channel:
log.debug("Failed to get the dev-core channel from cache; attempting to fetch it.")
try:
channel = await self.bot.fetch_channel(constants.Channels.dev_core)
except HTTPException:
log.exception(
f"Failed to fetch channel for sending sync confirmation prompt; "
f"aborting {self.name} sync."
)
return None
allowed_roles = [discord.Object(constants.Roles.core_developers)]
message = await channel.send(
f"{self._CORE_DEV_MENTION}{msg_content}",
allowed_mentions=discord.AllowedMentions(everyone=False, roles=allowed_roles)
)
else:
await message.edit(content=msg_content)
# Add the initial reactions.
log.trace(f"Adding reactions to {self.name} syncer confirmation prompt.")
for emoji in self._REACTION_EMOJIS:
await message.add_reaction(emoji)
return message
def _reaction_check(
self,
author: Member,
message: Message,
reaction: Reaction,
user: t.Union[Member, User]
) -> bool:
"""
Return True if the `reaction` is a valid confirmation or abort reaction on `message`.
If the `author` of the prompt is a bot, then a reaction by any core developer will be
considered valid. Otherwise, the author of the reaction (`user`) will have to be the
`author` of the prompt.
"""
# For automatic syncs, check for the core dev role instead of an exact author
has_role = any(constants.Roles.core_developers == role.id for role in user.roles)
return (
reaction.message.id == message.id
and not user.bot
and (has_role if author.bot else user == author)
and str(reaction.emoji) in self._REACTION_EMOJIS
)
async def _wait_for_confirmation(self, author: Member, message: Message) -> bool:
"""
Wait for a confirmation reaction by `author` on `message` and return True if confirmed.
Uses the `_reaction_check` function to determine if a reaction is valid.
If there is no reaction within `bot.constants.Sync.confirm_timeout` seconds, return False.
To acknowledge the reaction (or lack thereof), `message` will be edited.
"""
# Preserve the core-dev role mention in the message edits so users aren't confused about
# where notifications came from.
mention = self._CORE_DEV_MENTION if author.bot else ""
reaction = None
try:
log.trace(f"Waiting for a reaction to the {self.name} syncer confirmation prompt.")
reaction, _ = await self.bot.wait_for(
'reaction_add',
check=partial(self._reaction_check, author, message),
timeout=constants.Sync.confirm_timeout
)
except asyncio.TimeoutError:
# reaction will remain none thus sync will be aborted in the finally block below.
log.debug(f"The {self.name} syncer confirmation prompt timed out.")
if str(reaction) == constants.Emojis.check_mark:
log.trace(f"The {self.name} syncer was confirmed.")
await message.edit(content=f':ok_hand: {mention}{self.name} sync will proceed.')
return True
else:
log.info(f"The {self.name} syncer was aborted or timed out!")
await message.edit(
content=f':warning: {mention}{self.name} sync aborted or timed out!'
)
return False
@abc.abstractmethod
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference between the cache of `guild` and the database."""
raise NotImplementedError # pragma: no cover
@abc.abstractmethod
async def _sync(self, diff: _Diff) -> None:
"""Perform the API calls for synchronisation."""
raise NotImplementedError # pragma: no cover
async def _get_confirmation_result(
self,
diff_size: int,
author: Member,
message: t.Optional[Message] = None
) -> t.Tuple[bool, t.Optional[Message]]:
"""
Prompt for confirmation and return a tuple of the result and the prompt message.
`diff_size` is the size of the diff of the sync. If it is greater than
`bot.constants.Sync.max_diff`, the prompt will be sent. The `author` is the invoked of the
sync and the `message` is an extant message to edit to display the prompt.
If confirmed or no confirmation was needed, the result is True. The returned message will
either be the given `message` or a new one which was created when sending the prompt.
"""
log.trace(f"Determining if confirmation prompt should be sent for {self.name} syncer.")
if diff_size > constants.Sync.max_diff:
message = await self._send_prompt(message)
if not message:
return False, None # Couldn't get channel.
confirmed = await self._wait_for_confirmation(author, message)
if not confirmed:
return False, message # Sync aborted.
return True, message
async def sync(self, guild: Guild, ctx: t.Optional[Context] = None) -> None:
"""
Synchronise the database with the cache of `guild`.
If the differences between the cache and the database are greater than
`bot.constants.Sync.max_diff`, then a confirmation prompt will be sent to the dev-core
channel. The confirmation can be optionally redirect to `ctx` instead.
"""
log.info(f"Starting {self.name} syncer.")
message = None
author = self.bot.user
if ctx:
message = await ctx.send(f"📊 Synchronising {self.name}s.")
author = ctx.author
diff = await self._get_diff(guild)
diff_dict = diff._asdict() # Ugly method for transforming the NamedTuple into a dict
totals = {k: len(v) for k, v in diff_dict.items() if v is not None}
diff_size = sum(totals.values())
confirmed, message = await self._get_confirmation_result(diff_size, author, message)
if not confirmed:
return
# Preserve the core-dev role mention in the message edits so users aren't confused about
# where notifications came from.
mention = self._CORE_DEV_MENTION if author.bot else ""
try:
await self._sync(diff)
except ResponseCodeError as e:
log.exception(f"{self.name} syncer failed!")
# Don't show response text because it's probably some really long HTML.
results = f"status {e.status}\n```{e.response_json or "See log output for details"}```"
content = f":x: {mention}Synchronisation of {self.name}s failed: {results}"
else:
results = ", ".join(f"{name} `{total}`" for name, total in totals.items())
log.info(f"{self.name} syncer finished: {results}.")
content = f":ok_hand: {mention}Synchronisation of {self.name}s complete: {results}"
if message:
await message.edit(content=content)
class RoleSyncer(Syncer):
"""Synchronise the database with roles in the cache."""
name = "role"
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of roles between the cache of `guild` and the database."""
log.trace("Getting the diff for roles.")
roles = await self.bot.api_client.get('bot/roles')
# Pack DB roles and guild roles into one common, hashable format.
# They're hashable so that they're easily comparable with sets later.
db_roles = {_Role(**role_dict) for role_dict in roles}
guild_roles = {
_Role(
id=role.id,
name=role.name,
colour=role.colour.value,
permissions=role.permissions.value,
position=role.position,
)
for role in guild.roles
}
guild_role_ids = {role.id for role in guild_roles}
api_role_ids = {role.id for role in db_roles}
new_role_ids = guild_role_ids - api_role_ids
deleted_role_ids = api_role_ids - guild_role_ids
# New roles are those which are on the cached guild but not on the
# DB guild, going by the role ID. We need to send them in for creation.
roles_to_create = {role for role in guild_roles if role.id in new_role_ids}
roles_to_update = guild_roles - db_roles - roles_to_create
roles_to_delete = {role for role in db_roles if role.id in deleted_role_ids}
return _Diff(roles_to_create, roles_to_update, roles_to_delete)
async def _sync(self, diff: _Diff) -> None:
"""Synchronise the database with the role cache of `guild`."""
log.trace("Syncing created roles...")
for role in diff.created:
await self.bot.api_client.post('bot/roles', json=role._asdict())
log.trace("Syncing updated roles...")
for role in diff.updated:
await self.bot.api_client.put(f'bot/roles/{role.id}', json=role._asdict())
log.trace("Syncing deleted roles...")
for role in diff.deleted:
await self.bot.api_client.delete(f'bot/roles/{role.id}')
class UserSyncer(Syncer):
"""Synchronise the database with users in the cache."""
name = "user"
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of users between the cache of `guild` and the database."""
log.trace("Getting the diff for users.")
users = await self.bot.api_client.get('bot/users')
# Pack DB roles and guild roles into one common, hashable format.
# They're hashable so that they're easily comparable with sets later.
db_users = {
user_dict['id']: _User(
roles=tuple(sorted(user_dict.pop('roles'))),
**user_dict
)
for user_dict in users
}
guild_users = {
member.id: _User(
id=member.id,
name=member.name,
discriminator=int(member.discriminator),
roles=tuple(sorted(role.id for role in member.roles)),
in_guild=True
)
for member in guild.members
}
users_to_create = set()
users_to_update = set()
for db_user in db_users.values():
guild_user = guild_users.get(db_user.id)
if guild_user is not None:
if db_user != guild_user:
users_to_update.add(guild_user)
elif db_user.in_guild:
# The user is known in the DB but not the guild, and the
# DB currently specifies that the user is a member of the guild.
# This means that the user has left since the last sync.
# Update the `in_guild` attribute of the user on the site
# to signify that the user left.
new_api_user = db_user._replace(in_guild=False)
users_to_update.add(new_api_user)
new_user_ids = set(guild_users.keys()) - set(db_users.keys())
for user_id in new_user_ids:
# The user is known on the guild but not on the API. This means
# that the user has joined since the last sync. Create it.
new_user = guild_users[user_id]
users_to_create.add(new_user)
return _Diff(users_to_create, users_to_update, None)
async def _sync(self, diff: _Diff) -> None:
"""Synchronise the database with the user cache of `guild`."""
log.trace("Syncing created users...")
for user in diff.created:
await self.bot.api_client.post('bot/users', json=user._asdict())
log.trace("Syncing updated users...")
for user in diff.updated:
await self.bot.api_client.put(f'bot/users/{user.id}', json=user._asdict())
| import abc
import asyncio
import logging
import typing as t
from collections import namedtuple
from functools import partial
import discord
from discord import Guild, HTTPException, Member, Message, Reaction, User
from discord.ext.commands import Context
from bot import constants
from bot.api import ResponseCodeError
from bot.bot import Bot
log = logging.getLogger(__name__)
# These objects are declared as namedtuples because tuples are hashable,
# something that we make use of when diffing site roles against guild roles.
_Role = namedtuple('Role', ('id', 'name', 'colour', 'permissions', 'position'))
_User = namedtuple('User', ('id', 'name', 'discriminator', 'roles', 'in_guild'))
_Diff = namedtuple('Diff', ('created', 'updated', 'deleted'))
class Syncer(abc.ABC):
"""Base class for synchronising the database with objects in the Discord cache."""
_CORE_DEV_MENTION = f"<@&{constants.Roles.core_developers}> "
_REACTION_EMOJIS = (constants.Emojis.check_mark, constants.Emojis.cross_mark)
def __init__(self, bot: Bot) -> None:
self.bot = bot
@property
@abc.abstractmethod
def name(self) -> str:
"""The name of the syncer; used in output messages and logging."""
raise NotImplementedError # pragma: no cover
async def _send_prompt(self, message: t.Optional[Message] = None) -> t.Optional[Message]:
"""
Send a prompt to confirm or abort a sync using reactions and return the sent message.
If a message is given, it is edited to display the prompt and reactions. Otherwise, a new
message is sent to the dev-core channel and mentions the core developers role. If the
channel cannot be retrieved, return None.
"""
log.trace(f"Sending {self.name} sync confirmation prompt.")
msg_content = (
f'Possible cache issue while syncing {self.name}s. '
f'More than {constants.Sync.max_diff} {self.name}s were changed. '
f'React to confirm or abort the sync.'
)
# Send to core developers if it's an automatic sync.
if not message:
log.trace("Message not provided for confirmation; creating a new one in dev-core.")
channel = self.bot.get_channel(constants.Channels.dev_core)
if not channel:
log.debug("Failed to get the dev-core channel from cache; attempting to fetch it.")
try:
channel = await self.bot.fetch_channel(constants.Channels.dev_core)
except HTTPException:
log.exception(
f"Failed to fetch channel for sending sync confirmation prompt; "
f"aborting {self.name} sync."
)
return None
allowed_roles = [discord.Object(constants.Roles.core_developers)]
message = await channel.send(
f"{self._CORE_DEV_MENTION}{msg_content}",
allowed_mentions=discord.AllowedMentions(everyone=False, roles=allowed_roles)
)
else:
await message.edit(content=msg_content)
# Add the initial reactions.
log.trace(f"Adding reactions to {self.name} syncer confirmation prompt.")
for emoji in self._REACTION_EMOJIS:
await message.add_reaction(emoji)
return message
def _reaction_check(
self,
author: Member,
message: Message,
reaction: Reaction,
user: t.Union[Member, User]
) -> bool:
"""
Return True if the `reaction` is a valid confirmation or abort reaction on `message`.
If the `author` of the prompt is a bot, then a reaction by any core developer will be
considered valid. Otherwise, the author of the reaction (`user`) will have to be the
`author` of the prompt.
"""
# For automatic syncs, check for the core dev role instead of an exact author
has_role = any(constants.Roles.core_developers == role.id for role in user.roles)
return (
reaction.message.id == message.id
and not user.bot
and (has_role if author.bot else user == author)
and str(reaction.emoji) in self._REACTION_EMOJIS
)
async def _wait_for_confirmation(self, author: Member, message: Message) -> bool:
"""
Wait for a confirmation reaction by `author` on `message` and return True if confirmed.
Uses the `_reaction_check` function to determine if a reaction is valid.
If there is no reaction within `bot.constants.Sync.confirm_timeout` seconds, return False.
To acknowledge the reaction (or lack thereof), `message` will be edited.
"""
# Preserve the core-dev role mention in the message edits so users aren't confused about
# where notifications came from.
mention = self._CORE_DEV_MENTION if author.bot else ""
reaction = None
try:
log.trace(f"Waiting for a reaction to the {self.name} syncer confirmation prompt.")
reaction, _ = await self.bot.wait_for(
'reaction_add',
check=partial(self._reaction_check, author, message),
timeout=constants.Sync.confirm_timeout
)
except asyncio.TimeoutError:
# reaction will remain none thus sync will be aborted in the finally block below.
log.debug(f"The {self.name} syncer confirmation prompt timed out.")
if str(reaction) == constants.Emojis.check_mark:
log.trace(f"The {self.name} syncer was confirmed.")
await message.edit(content=f':ok_hand: {mention}{self.name} sync will proceed.')
return True
else:
log.info(f"The {self.name} syncer was aborted or timed out!")
await message.edit(
content=f':warning: {mention}{self.name} sync aborted or timed out!'
)
return False
@abc.abstractmethod
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference between the cache of `guild` and the database."""
raise NotImplementedError # pragma: no cover
@abc.abstractmethod
async def _sync(self, diff: _Diff) -> None:
"""Perform the API calls for synchronisation."""
raise NotImplementedError # pragma: no cover
async def _get_confirmation_result(
self,
diff_size: int,
author: Member,
message: t.Optional[Message] = None
) -> t.Tuple[bool, t.Optional[Message]]:
"""
Prompt for confirmation and return a tuple of the result and the prompt message.
`diff_size` is the size of the diff of the sync. If it is greater than
`bot.constants.Sync.max_diff`, the prompt will be sent. The `author` is the invoked of the
sync and the `message` is an extant message to edit to display the prompt.
If confirmed or no confirmation was needed, the result is True. The returned message will
either be the given `message` or a new one which was created when sending the prompt.
"""
log.trace(f"Determining if confirmation prompt should be sent for {self.name} syncer.")
if diff_size > constants.Sync.max_diff:
message = await self._send_prompt(message)
if not message:
return False, None # Couldn't get channel.
confirmed = await self._wait_for_confirmation(author, message)
if not confirmed:
return False, message # Sync aborted.
return True, message
async def sync(self, guild: Guild, ctx: t.Optional[Context] = None) -> None:
"""
Synchronise the database with the cache of `guild`.
If the differences between the cache and the database are greater than
`bot.constants.Sync.max_diff`, then a confirmation prompt will be sent to the dev-core
channel. The confirmation can be optionally redirect to `ctx` instead.
"""
log.info(f"Starting {self.name} syncer.")
message = None
author = self.bot.user
if ctx:
message = await ctx.send(f"📊 Synchronising {self.name}s.")
author = ctx.author
diff = await self._get_diff(guild)
diff_dict = diff._asdict() # Ugly method for transforming the NamedTuple into a dict
totals = {k: len(v) for k, v in diff_dict.items() if v is not None}
diff_size = sum(totals.values())
confirmed, message = await self._get_confirmation_result(diff_size, author, message)
if not confirmed:
return
# Preserve the core-dev role mention in the message edits so users aren't confused about
# where notifications came from.
mention = self._CORE_DEV_MENTION if author.bot else ""
try:
await self._sync(diff)
except ResponseCodeError as e:
log.exception(f"{self.name} syncer failed!")
# Don't show response text because it's probably some really long HTML.
results = f"status {e.status}\n```{e.response_json or 'See log output for details'}```"
content = f":x: {mention}Synchronisation of {self.name}s failed: {results}"
else:
results = ", ".join(f"{name} `{total}`" for name, total in totals.items())
log.info(f"{self.name} syncer finished: {results}.")
content = f":ok_hand: {mention}Synchronisation of {self.name}s complete: {results}"
if message:
await message.edit(content=content)
class RoleSyncer(Syncer):
"""Synchronise the database with roles in the cache."""
name = "role"
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of roles between the cache of `guild` and the database."""
log.trace("Getting the diff for roles.")
roles = await self.bot.api_client.get('bot/roles')
# Pack DB roles and guild roles into one common, hashable format.
# They're hashable so that they're easily comparable with sets later.
db_roles = {_Role(**role_dict) for role_dict in roles}
guild_roles = {
_Role(
id=role.id,
name=role.name,
colour=role.colour.value,
permissions=role.permissions.value,
position=role.position,
)
for role in guild.roles
}
guild_role_ids = {role.id for role in guild_roles}
api_role_ids = {role.id for role in db_roles}
new_role_ids = guild_role_ids - api_role_ids
deleted_role_ids = api_role_ids - guild_role_ids
# New roles are those which are on the cached guild but not on the
# DB guild, going by the role ID. We need to send them in for creation.
roles_to_create = {role for role in guild_roles if role.id in new_role_ids}
roles_to_update = guild_roles - db_roles - roles_to_create
roles_to_delete = {role for role in db_roles if role.id in deleted_role_ids}
return _Diff(roles_to_create, roles_to_update, roles_to_delete)
async def _sync(self, diff: _Diff) -> None:
"""Synchronise the database with the role cache of `guild`."""
log.trace("Syncing created roles...")
for role in diff.created:
await self.bot.api_client.post('bot/roles', json=role._asdict())
log.trace("Syncing updated roles...")
for role in diff.updated:
await self.bot.api_client.put(f'bot/roles/{role.id}', json=role._asdict())
log.trace("Syncing deleted roles...")
for role in diff.deleted:
await self.bot.api_client.delete(f'bot/roles/{role.id}')
class UserSyncer(Syncer):
"""Synchronise the database with users in the cache."""
name = "user"
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of users between the cache of `guild` and the database."""
log.trace("Getting the diff for users.")
users = await self.bot.api_client.get('bot/users')
# Pack DB roles and guild roles into one common, hashable format.
# They're hashable so that they're easily comparable with sets later.
db_users = {
user_dict['id']: _User(
roles=tuple(sorted(user_dict.pop('roles'))),
**user_dict
)
for user_dict in users
}
guild_users = {
member.id: _User(
id=member.id,
name=member.name,
discriminator=int(member.discriminator),
roles=tuple(sorted(role.id for role in member.roles)),
in_guild=True
)
for member in guild.members
}
users_to_create = set()
users_to_update = set()
for db_user in db_users.values():
guild_user = guild_users.get(db_user.id)
if guild_user is not None:
if db_user != guild_user:
users_to_update.add(guild_user)
elif db_user.in_guild:
# The user is known in the DB but not the guild, and the
# DB currently specifies that the user is a member of the guild.
# This means that the user has left since the last sync.
# Update the `in_guild` attribute of the user on the site
# to signify that the user left.
new_api_user = db_user._replace(in_guild=False)
users_to_update.add(new_api_user)
new_user_ids = set(guild_users.keys()) - set(db_users.keys())
for user_id in new_user_ids:
# The user is known on the guild but not on the API. This means
# that the user has joined since the last sync. Create it.
new_user = guild_users[user_id]
users_to_create.add(new_user)
return _Diff(users_to_create, users_to_update, None)
async def _sync(self, diff: _Diff) -> None:
"""Synchronise the database with the user cache of `guild`."""
log.trace("Syncing created users...")
for user in diff.created:
await self.bot.api_client.post('bot/users', json=user._asdict())
log.trace("Syncing updated users...")
for user in diff.updated:
await self.bot.api_client.put(f'bot/users/{user.id}', json=user._asdict())
|
nome = str(input('Digite o seu nome: '))
i = int(input('Digite a sua idade: '))
p = float(input('Digite o seu peso: '))
a = float(input('Digite a sua altura: '))
imc = p/a**2
print(f"{"":=^20}")
print(f"{"Ficha IMC":^20}")
print(f"{"":=^20}")
print('Nome: {}'.format(nome))
print('Idade: {}'.format(i))
print('Peso: {}kg'.format(p))
print('Altura: {}m'.format(a))
print('IMC: {:.1f}'.format(imc))
if(imc < 18.5):
print('Status: Você está abaixo do peso!')
elif(imc >= 18.5) and (imc <= 24.9):
print('Status: Peso Normal!')
elif(imc >= 25) and (imc <= 29.9):
print('Status: Sobrepeso!')
elif(imc >= 30) and (imc <= 34.9):
print('Status: OBESIDADE GRAU 1!!!')
elif(imc >= 35) and (imc <= 39.9):
print('Status: OBESIDADE GRAU 2!!!')
elif(imc >= 40):
print('Status: OBESIDADE MÓRBIDA!!!'
' VOCÊ ESTÁ MORRENDO!!!')
print(f"{"":=^20}") | nome = str(input('Digite o seu nome: '))
i = int(input('Digite a sua idade: '))
p = float(input('Digite o seu peso: '))
a = float(input('Digite a sua altura: '))
imc = p/a**2
print(f"{'':=^20}")
print(f"{'Ficha IMC':^20}")
print(f"{'':=^20}")
print('Nome: {}'.format(nome))
print('Idade: {}'.format(i))
print('Peso: {}kg'.format(p))
print('Altura: {}m'.format(a))
print('IMC: {:.1f}'.format(imc))
if(imc < 18.5):
print('Status: Você está abaixo do peso!')
elif(imc >= 18.5) and (imc <= 24.9):
print('Status: Peso Normal!')
elif(imc >= 25) and (imc <= 29.9):
print('Status: Sobrepeso!')
elif(imc >= 30) and (imc <= 34.9):
print('Status: OBESIDADE GRAU 1!!!')
elif(imc >= 35) and (imc <= 39.9):
print('Status: OBESIDADE GRAU 2!!!')
elif(imc >= 40):
print('Status: OBESIDADE MÓRBIDA!!!'
' VOCÊ ESTÁ MORRENDO!!!')
print(f"{'':=^20}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.