def set_color_range(self, color1, color2): hsl_cs = colour.color_scale(color1.get_hsl(), color2.get_hsl(), 100) rgb_cs = [colour.hsl2rgb(a) for a in hsl_cs] self.scaled_cs = [] for a in rgb_cs: self.scaled_cs.append( (round(a[0] * 255), round(a[1] * 255), round(a[2] * 255)))
def dominant_color(image): hsl_cat = np.zeros((6, 5, 5)) image = (prepare_image(image).astype('uint8')) red = 0 blue = 0 for i in range(image.shape[0]): pix_hsl = rgb2hsl(image[i]) if image[i][0] > image[i][2]: red += 1 else: blue += 1 #print(image[i],pix_hsl) for i in range(1, 6): if pix_hsl[0] >= hue[i][0] and pix_hsl[0] < hue[i][1]: pix_h = i if pix_hsl[0] >= 330 or pix_hsl[0] < 30: pix_h = 0 for i in range(5): if pix_hsl[1] >= satuation[i][0] and pix_hsl[1] < satuation[i][1]: pix_s = i if pix_hsl[2] >= lightness[i][0] and pix_hsl[2] < lightness[i][1]: pix_l = i hsl_cat[pix_h, pix_s, pix_l] += 1 #print([pix_h,pix_s,pix_l]) color_cat_flat = hsl_cat.reshape(150) frequency = {} for i in range(150): frequency[i] = color_cat_flat[i] color_count = np.arange(150) for i in range(150): color_count[i] = frequency[i] color_order = np.argsort(color_count)[::-1] color_rank_rgb = [] for i in color_order: i1, i2, i3 = oneD_to_3D_index(i) color_hsl = np.asarray([ hue_value[i1] / 360., satuation_value[i2] / 100., lightness_value[i3] / 100. ]) color_rgb = np.asarray(hsl2rgb(color_hsl)) color_rank_rgb.append(color_rgb) return color_order, color_rank_rgb, color_count
def render(hsl0, hsl1, trans01, trans10): """take params and return array of rendered frames to loop""" # TODO: decide if want to actually use hsl hsl0 = hsl0.unsqueeze(0) hsl1 = hsl1.unsqueeze(0) _, w_hsl0_01 = laggy_logistic_fn(trans01[0], trans01[1], trans01[2]) w_hsl0_01 = w_hsl0_01.unsqueeze(-1) hsl_01 = (w_hsl0_01 * hsl0) + ((1. - w_hsl0_01) * hsl1) _, w_hsl0_10 = laggy_logistic_fn(trans10[0], trans10[1], trans10[2]) w_hsl0_10 = w_hsl0_10.unsqueeze(-1) hsl_10 = (w_hsl0_10 * hsl1) + ((1. - w_hsl0_10) * hsl0) frames = torch.cat([hsl_01, hsl_10]).data.numpy() rgb_frames = np.stack([hsl2rgb(frame) for frame in frames]) return rgb_frames
def create_data(self) -> str: """Returns a JavaScript string defining a JavaScript object containing the data. Returns: :obj:`str`: JavaScript code defining an object containing the data """ s = self.scale mini, maxi = self.get_min_max() diff = maxi - mini output = "const data = {\n" # Create the data for the scatters # TODO: If it's not interactive, labels shouldn't be exported. for name, data in self.scatters_data.items(): mapping = self.scatters[name]["mapping"] colormaps = self.scatters[name]["colormap"] cmaps = [None] * len(colormaps) for i, colormap in enumerate(colormaps): if isinstance(colormap, str): cmaps[i] = plt.cm.get_cmap(colormap) else: cmaps[i] = colormap output += name + ": {\n" x_norm = [round(s * (x - mini) / diff, 3) for x in data[mapping["x"]]] output += "x: [" + ",".join(map(str, x_norm)) + "],\n" y_norm = [round(s * (y - mini) / diff, 3) for y in data[mapping["y"]]] output += "y: [" + ",".join(map(str, y_norm)) + "],\n" z_norm = [round(s * (z - mini) / diff, 3) for z in data[mapping["z"]]] output += "z: [" + ",".join(map(str, z_norm)) + "],\n" if mapping["labels"] in data: fmt_labels = ["'{0}'".format(s) for s in data[mapping["labels"]]] output += "labels: [" + ",".join(fmt_labels) + "],\n" if mapping["s"] in data: output += "s: [" for series in range(len(data[mapping["s"]])): output += ( "[" + ",".join(map(str, np.round(data[mapping["s"]][series], 3))) + "],\n" ) output += "],\n" output += "colors: [\n" for series in range(len(data[mapping["c"]])): output += "{\n" if mapping["cs"] in data: colors = np.array( [cmaps[series](x) for x in data[mapping["c"]][series]] ) for i, c in enumerate(colors): hsl = np.array(colour.rgb2hsl(c[:3])) hsl[1] = hsl[1] - hsl[1] * data[mapping["cs"]][series][i] colors[i] = np.append(np.array(colour.hsl2rgb(hsl)), 1.0) colors = np.round(colors * 255.0) output += ( "r: [" + ",".join(map(str, map(int, colors[:, 0]))) + "],\n" ) output += ( "g: [" + ",".join(map(str, map(int, colors[:, 1]))) + "],\n" ) output += ( "b: [" + ",".join(map(str, map(int, colors[:, 2]))) + "],\n" ) elif mapping["c"] in data: colors = np.array( [cmaps[series](x) for x in data[mapping["c"]][series]] ) colors = np.round(colors * 255.0) output += ( "r: [" + ",".join(map(str, map(int, colors[:, 0]))) + "],\n" ) output += ( "g: [" + ",".join(map(str, map(int, colors[:, 1]))) + "],\n" ) output += ( "b: [" + ",".join(map(str, map(int, colors[:, 2]))) + "],\n" ) output += "},\n" output += "]" output += "},\n" for name, data in self.trees_data.items(): mapping = self.trees[name]["mapping"] point_helper = self.trees[name]["point_helper"] output += name + ": {\n" if point_helper is not None and point_helper in self.scatters_data: scatter = self.scatters_data[point_helper] scatter_mapping = self.scatters[point_helper]["mapping"] x_t = [] y_t = [] z_t = [] for i in range(len(data[mapping["from"]])): x_t.append(scatter[scatter_mapping["x"]][data[mapping["from"]][i]]) x_t.append(scatter[scatter_mapping["x"]][data[mapping["to"]][i]]) y_t.append(scatter[scatter_mapping["y"]][data[mapping["from"]][i]]) y_t.append(scatter[scatter_mapping["y"]][data[mapping["to"]][i]]) z_t.append(scatter[scatter_mapping["z"]][data[mapping["from"]][i]]) z_t.append(scatter[scatter_mapping["z"]][data[mapping["to"]][i]]) x_norm = [round(s * (x - mini) / diff, 3) for x in x_t] output += f"x: [" + ",".join(map(str, x_norm)) + "],\n" y_norm = [round(s * (y - mini) / diff, 3) for y in y_t] output += "y: [" + ",".join(map(str, y_norm)) + "],\n" z_norm = [round(s * (z - mini) / diff, 3) for z in z_t] output += "z: [" + ",".join(map(str, z_norm)) + "],\n" else: x_norm = [round(s * (x - mini) / diff, 3) for x in data[mapping["x"]]] output += "x: [" + ",".join(map(str, x_norm)) + "],\n" y_norm = [round(s * (y - mini) / diff, 3) for y in data[mapping["y"]]] output += "y: [" + ",".join(map(str, y_norm)) + "],\n" z_norm = [round(s * (z - mini) / diff, 3) for z in data[mapping["z"]]] output += "z: [" + ",".join(map(str, z_norm)) + "],\n" if mapping["c"] in data: colormap = self.trees[name]["colormap"] cmap = None if isinstance(colormap, str): cmap = plt.cm.get_cmap(colormap) else: cmap = colormap colors = np.array([cmap(x) for x in data[mapping["c"]]]) colors = np.round(colors * 255.0) output += "r: [" + ",".join(map(str, colors[:, 0])) + "],\n" output += "g: [" + ",".join(map(str, colors[:, 1])) + "],\n" output += "b: [" + ",".join(map(str, colors[:, 2])) + "],\n" output += "},\n" output += "};\n" return output
def create_python_data(self) -> dict: """Returns a Python dict containing the data Returns: :obj:`dict`: The data defined in this Faerun instance """ s = self.scale minimum, maximum = self.get_min_max() diff = maximum - minimum output = {} # Create the data for the scatters for name, data in self.scatters_data.items(): mapping = self.scatters[name]["mapping"] colormaps = self.scatters[name]["colormap"] cmaps = [None] * len(colormaps) for i, colormap in enumerate(colormaps): if isinstance(colormap, str): cmaps[i] = plt.cm.get_cmap(colormap) else: cmaps[i] = colormap output[name] = {} output[name]["meta"] = self.scatters[name] output[name]["type"] = "scatter" output[name]["x"] = np.array( [s * (x - minimum) / diff for x in data[mapping["x"]]], dtype=np.float32 ) output[name]["y"] = np.array( [s * (y - minimum) / diff for y in data[mapping["y"]]], dtype=np.float32 ) output[name]["z"] = np.array( [s * (z - minimum) / diff for z in data[mapping["z"]]], dtype=np.float32 ) if mapping["labels"] in data: # Make sure that the labels are always strings output[name]["labels"] = list(map(str, data[mapping["labels"]])) if mapping["s"] in data: output[name]["s"] = np.array(data[mapping["s"]], dtype=np.float32) output[name]["colors"] = [{}] * len(data[mapping["c"]]) for s in range(len(data[mapping["c"]])): if mapping["cs"] in data: colors = np.array([cmaps[s](x) for x in data[mapping["c"]][s]]) for i, c in enumerate(colors): hsl = np.array(colour.rgb2hsl(c[:3])) hsl[1] = hsl[1] - hsl[1] * data[mapping["cs"]][s][i] colors[i] = np.append(np.array(colour.hsl2rgb(hsl)), 1.0) colors = np.round(colors * 255.0) output[name]["colors"][s]["r"] = np.array( colors[:, 0], dtype=np.float32 ) output[name]["colors"][s]["g"] = np.array( colors[:, 1], dtype=np.float32 ) output[name]["colors"][s]["b"] = np.array( colors[:, 2], dtype=np.float32 ) else: colors = np.array([cmaps[s](x) for x in data[mapping["c"]][s]]) colors = np.round(colors * 255.0) output[name]["colors"][s]["r"] = np.array( colors[:, 0], dtype=np.float32 ) output[name]["colors"][s]["g"] = np.array( colors[:, 1], dtype=np.float32 ) output[name]["colors"][s]["b"] = np.array( colors[:, 2], dtype=np.float32 ) for name, data in self.trees_data.items(): mapping = self.trees[name]["mapping"] point_helper = self.trees[name]["point_helper"] output[name] = {} output[name]["meta"] = self.trees[name] output[name]["type"] = "tree" if point_helper is not None and point_helper in self.scatters_data: scatter = self.scatters_data[point_helper] scatter_mapping = self.scatters[point_helper]["mapping"] x_t = [] y_t = [] z_t = [] for i in range(len(data[mapping["from"]])): x_t.append(scatter[scatter_mapping["x"]][data[mapping["from"]][i]]) x_t.append(scatter[scatter_mapping["x"]][data[mapping["to"]][i]]) y_t.append(scatter[scatter_mapping["y"]][data[mapping["from"]][i]]) y_t.append(scatter[scatter_mapping["y"]][data[mapping["to"]][i]]) z_t.append(scatter[scatter_mapping["z"]][data[mapping["from"]][i]]) z_t.append(scatter[scatter_mapping["z"]][data[mapping["to"]][i]]) output[name]["x"] = np.array( [s * (x - minimum) / diff for x in x_t], dtype=np.float32 ) output[name]["y"] = np.array( [s * (y - minimum) / diff for y in y_t], dtype=np.float32 ) output[name]["z"] = np.array( [s * (z - minimum) / diff for z in z_t], dtype=np.float32 ) else: output[name]["x"] = np.array( [s * (x - minimum) / diff for x in data[mapping["x"]]], dtype=np.float32, ) output[name]["y"] = np.array( [s * (y - minimum) / diff for y in data[mapping["y"]]], dtype=np.float32, ) output[name]["z"] = np.array( [s * (z - minimum) / diff for z in data[mapping["z"]]], dtype=np.float32, ) if mapping["c"] in data: colormap = self.trees[name]["colormap"] cmap = None if isinstance(colormap, str): cmap = plt.cm.get_cmap(colormap) else: cmap = colormap colors = np.array([cmap(x) for x in data[mapping["c"]]]) colors = np.round(colors * 255.0) output[name]["r"] = np.array(colors[:, 0], dtype=np.float32) output[name]["g"] = np.array(colors[:, 1], dtype=np.float32) output[name]["b"] = np.array(colors[:, 2], dtype=np.float32) return output
#r2 = r2_score(y_train, preds) from colour import hsl2rgb time_save = time[:divide].append(time[divide:]) data_save = np.append(y_train, y_valid) model_save = np.append(preds_train, preds_test) #dict={'time':time_save,'data':data_save,'model':model_save} #df_save=pd.DataFrame(data=dict) #df_save.to_csv("color_feature_hsl/model_fit_"+i+".csv") fig, ax = plt.subplots(figsize=(8, 5)) ax.plot(pd.to_datetime(time[:divide]), y_train * 100, color=hsl2rgb([0.6, 0.5, 70 / 100.]), lw=3, label='data') ax.plot(pd.to_datetime(time[:divide]), preds_train * 100, color=hsl2rgb([0.6, 0.5, 10 / 100.]), lw=2, ls=":", label='model') ax.plot(pd.to_datetime(time[divide:size]), y_valid * 100, color=hsl2rgb([0.6, 0.5, 70 / 100.]), lw=3) #,ls=":")#,label='test data') ax.plot(pd.to_datetime(time[divide:size]), preds_test * 100, color=hsl2rgb([0.6, 0.5, 10 / 100.]),
def get_plotly_SxL_pop(data, hue=4): col = ['s0l2', 's0l1', 's1l1', 's1l2', 's0l3'] #fig = go.Figure() fig = go.Figure() for col_test in col: s = int(col_test[1]) l = int(col_test[-1]) df_forecasting = rolling_rf_data_pre(data, col=col_test) f = forescast_feature_pre(data, df_forecasting, col=col_test) t, model, pred = forecast_rf(df_forecasting, f) time = list(t) time.append(pd.to_datetime("2020-06-30")) forecast = list(100 * model) forecast.append(pred[0] * 100) color = np.asarray( hsl2rgb([ hue_value[hue] / 360., satuation_value[s] / 100, lightness_value[l] / 100 ])) color = (color * 255).astype('int') color = rgb2hex(color) fig.add_trace( go.Scatter(x=t, y=100 * df_forecasting[col_test], mode='lines', name='data: saturation = ' + str(satuation_value[s]) + '%, lightness = ' + str(lightness_value[l]) + '%', line=dict(color=color, width=3))) fig.add_trace( go.Scatter(x=time, y=forecast, mode='lines', name='forecast', line=dict(color=color, dash='dot', width=3))) title = "Most Popular Saturation X Lightness Categories (Hue Independent)" fig.update_layout( title=title, width=1050, height=650, xaxis_title="time", yaxis_title="% popularity", font=dict(family="Courier New, monospace", size=17, color="#7f7f7f"), xaxis=dict( range=[pd.to_datetime("2016-06-30"), pd.to_datetime("2020-06-30")], rangeselector=dict(buttons=list([ dict(count=6, label="last 6 months", step="month", stepmode="backward"), dict(count=1, label="last year", step="year", stepmode="backward"), dict(step="all") ])), rangeslider=dict(visible=True), type="date"), legend=dict( x=1.1, y=0.99, traceorder='normal', font=dict(size=12, ), ), ) return fig
def get_plotly_H_6(data): col = ['h0', 'h1', 'h2', 'h3', 'h4', 'h5'] fig = go.Figure() i = 0 for col_test in col: df_forecasting = rolling_rf_data_pre(data, col=col_test) f = forescast_feature_pre(data, df_forecasting, col=col_test) t, model, pred = forecast_rf(df_forecasting, f) time = list(t) time.append(pd.to_datetime("2020-06-30")) forecast = list(100 * model) forecast.append(pred[0] * 100) color = np.asarray(hsl2rgb([hue_value[i] / 360., 0.5, 0.7])) color = (color * 255).astype('int') color = rgb2hex(color) fig.add_trace( go.Scatter(x=t, y=100 * df_forecasting[col_test], name='data: ' + hue_name[i], mode='lines', line=dict(color=color, width=4))) fig.add_trace( go.Scatter(x=time, y=forecast, mode='lines', name='forecast', line=dict(color=color, dash='dot', width=4))) i += 1 print(color) h = int(col_test[1]) title = "Popularity of Each Primary Hue" fig.update_layout( title=title, width=850, height=550, xaxis_title="time", yaxis_title="% popularity", font=dict(family="Courier New, monospace", size=17, color="#7f7f7f"), xaxis_showgrid=True, yaxis_showgrid=True, xaxis=dict( range=[pd.to_datetime("2016-06-30"), pd.to_datetime("2020-06-30")], rangeselector=dict(buttons=list([ dict(count=6, label="last 6 months", step="month", stepmode="backward"), dict(count=1, label="last year", step="year", stepmode="backward"), dict(step="all") ])), rangeslider=dict(visible=True), type="date"), legend=dict( x=1.1, y=0.99, traceorder='normal', font=dict(size=12, ), ), #paper_bgcolor='rgba(0,0,0,0)') plot_bgcolor='rgba(0,0,0,0)', ) fig.update_yaxes(showgrid=True, gridcolor="#DCDCDC") fig.update_xaxes(showgrid=True, gridcolor="#DCDCDC") return fig
def get_plotly_SxL(col_test, data): s = int(col_test[1]) l = int(col_test[-1]) df_forecasting = rolling_rf_data_pre(data, col=col_test) f = forescast_feature_pre(data, df_forecasting, col=col_test) t, model, pred = forecast_rf(df_forecasting, f) #fig = go.Figure() fig = make_subplots( rows=1, cols=2, subplot_titles=( " ", "Colors in the Same <br> Saturation X Lightness Palette"), specs=[[{ 'type': 'xy' }, { 'type': 'polar' }]], column_widths=[0.75, 0.25]) time = list(t) time.append(pd.to_datetime("2020-06-30")) forecast = list(100 * model) forecast.append(pred[0] * 100) fig.add_trace(go.Scatter(x=time, y=forecast, mode='lines', name='model & forecast', line=dict(color="#80bf40", dash='dot', width=3)), row=1, col=1) fig.add_trace(go.Scatter(x=t, y=100 * df_forecasting[col_test], mode='lines', name='data', line=dict(color="#409fbf", width=3)), row=1, col=1) title = 'Saturation = ' + str(satuation[s]) + ', Lightness = ' + str( satuation[l]) fig.update_layout( title=title, title_x=0., width=1050, height=650, xaxis_title="time", yaxis_title="% popularity", font=dict(family="Courier New, monospace", size=17, color="#7f7f7f"), xaxis=dict( range=[pd.to_datetime("2016-06-30"), pd.to_datetime("2020-06-30")], rangeselector=dict(buttons=list([ dict(count=6, label="last 6 months", step="month", stepmode="backward"), dict(count=1, label="last year", step="year", stepmode="backward"), dict(step="all") ])), rangeslider=dict(visible=True), type="date"), legend=dict( x=0, y=0.99, traceorder='normal', font=dict(size=12, ), ), ) hexcode = [] for h in hue_value: color = np.asarray((hsl2rgb([(h + 10) / 360, satuation_value[s] / 100, lightness_value[l] / 100]))) color = color * 255 color = color.astype('int') #print(color) hexcode.append(rgb2hex(color)) fig.add_trace(go.Barpolar(r=[2] * 6, theta=hue_value, width=[60] * 6, marker_color=hexcode, showlegend=False, hoverinfo='none'), row=1, col=2) fig.update_layout( template=None, polar=dict( radialaxis=dict(showticklabels=False, ticks='', showgrid=False, showline=False), angularaxis=dict(showticklabels=False, ticks='', showgrid=False, showline=False, rotation=90), ), ) return fig
def axis_colours(self): for ax_name, ax in self.axes.items(): yield (colour.hsl2rgb((ax.get_color(), 1.0, 0.35)), ax_name)
def trace_colours(self): for ax in self.axes.values(): size = float(len(ax)) for i, trace in enumerate(ax.traces): yield (colour.hsl2rgb((ax.get_color(i), 1.0, 0.35)), trace)
def axis_colours(self): for ax_name, ax in self.axes.items(): yield (colour.hsl2rgb((ax.get_color(), 1.0, 0.35)), ax_name)
def trace_colours(self): for ax in self.axes.values(): size = float(len(ax)) for i, trace in enumerate(ax.traces): yield (colour.hsl2rgb((ax.get_color(i), 1.0, 0.35)), trace)