Related
just beginning with Dash 2.0 from plotly. Mainly to take advantage of longcallbacks. I try to get callback's id without success (i.e. the id I see in the worker when executing long call). Also struggling to get its state, ready(), successful() etc.
What I've got so far:
#app.long_callback(
output=Output("paragraph_id", "children"),
inputs=Input("button_id", "n_clicks"),
running=[
(Output("button_id", "disabled"), True, False),
(Output("cancel_button_id", "disabled"), False, True),
(
Output("paragraph_id", "style"),
{"visibility": "hidden"},
{"visibility": "visible"},
),
(
Output("progress_bar", "style"),
{"visibility": "visible"},
{"visibility": "hidden"},
),
],
cancel=[Input("cancel_button_id", "n_clicks")],
progress=[Output("progress_bar", "value"), Output("progress_bar", "max")],
prevent_initial_call=True
)
def update_progress(set_progress, n_clicks):
currentProgress = check_progress.delay()
i = 0
total = 15
while currentProgress.ready() == False:
time.sleep(1)
print("currentProgress.STATE")
print(currentProgress.state)
set_progress((str(i + 1), str(total)))
i += 1
return [f"Clicked {n_clicks} times" + " " + currentProgress.id]
#celery_app.task(bind=True)
def check_progress(self):
time.sleep(15)
return
I can manage to get these when executing celery task - check_progress(). How do I get id of update_progress() long callback?
I want to animate a bar chart in manim and it works just fine. However, the bar_names are long and have to be displayed rather small. Is there a way to rotate them so they can be displayed bigger?
CONFIG = {
"max_value" : 100,
"bar_names" : ["Fleisch von Wiederkäuern","Anderes Fleisch, Fisch","Milchprodukte","Früchte", "Snacks, etc.","Gemüse","Pflanzliche Öle","Getreideprodukte", "Pflanzliche Proteine"],
"bar_label_scale_val" : 0.2,
"bar_stroke_width" : 0,
"width" : 10,
"height" : 6,
"label_y_axis" : False,
}
def construct(self):
composition = [96.350861, 18.5706488, 14.7071608, 8.25588773, 7.33856028, 4.24083463, 1.65574964, 1.36437485, 1]
chart = BarChart(values=composition, **self.CONFIG)
self.play(Write(chart), run_time=2)```
Maybe something like this?
(I just made new labels so delete the old ones, or delete their size)
(also I modified some of the names because my Latex crashed with some characters)
CONFIG = {
"height": 4,
"width": 10,
"n_ticks": 4,
"tick_width": 0.2,
"label_y_axis": False,
"y_axis_label_height": 0.25,
"max_value": 100,
"bar_colors": [BLUE, YELLOW],
"bar_fill_opacity": 0.8,
"bar_stroke_width": 0,
"bar_names": ["Fleisch von Wiederkuern","Anderes Fleisch, Fisch","Milchprodukte","Frchte", "Snacks, etc.","Gemse","Pflanzliche le","Getreideprodukte", "Pflanzliche Proteine"],
"bar_label_scale_val": 0
}
def construct(self):
bar_names=["Fleisch von Wiederkuern","Anderes Fleisch, Fisch","Milchprodukte","Frchte", "Snacks, etc.","Gemse","Pflanzliche le","Getreideprodukte", "Pflanzliche Proteine"]
Lsize=0.55
Lseparation=1.1
Lpositionx=-5.4
Lpositiony=2
bar_labels = VGroup()
for i in range(len(bar_names)):
label = TexMobject(bar_names[i])
label.scale(Lsize)
label.move_to(DOWN*Lpositiony+(i*Lseparation+Lpositionx)*RIGHT)
label.rotate(np.pi*(1.5/6))
bar_labels.add(label)
composition = [96.350861, 18.5706488, 14.7071608, 8.25588773, 7.33856028, 4.24083463, 1.65574964, 1.36437485, 1]
chart = BarChart(values=composition, **self.CONFIG)
chart.shift(UP)
self.play(Write(chart),Write(bar_labels), run_time=2)
# Manim Community Version 0.7.0 in Google Colab
%%manim -qm -v WARNING BarChartExample2
import numpy as np
mobject.probability.np = np
class BarChartExample2(Scene):
CONFIG = {
"height": 4,
"width": 10,
"n_ticks": 4,
"tick_width": 0.2,
"label_y_axis": False,
"y_axis_label_height": 0.25,
"max_value": 100,
"bar_colors": [BLUE, YELLOW],
"bar_fill_opacity": 0.8,
"bar_stroke_width": 0,
"bar_names": ["Fleisch von Wiederkuern","Anderes Fleisch, Fisch","Milchprodukte",
"Frchte", "Snacks, etc.","Gemse","Pflanzliche le","Getreideprodukte", "Pflanzliche Proteine"],
"bar_label_scale_val": 0
}
def construct(self):
bar_names=["Fleisch von Wiederkuern","Anderes Fleisch, Fisch","Milchprodukte",
"Frchte", "Snacks, etc.","Gemse","Pflanzliche le","Getreideprodukte", "Pflanzliche Proteine"]
Lsize=0.55
Lseparation=1.1
Lpositionx=-5.4
Lpositiony=2
bar_labels = VGroup()
for i in range(len(bar_names)):
#label = TexMobject(bar_names[i])
label = MathTex(bar_names[i])
label.scale(Lsize)
label.move_to(DOWN*Lpositiony+(i*Lseparation+Lpositionx)*RIGHT)
label.rotate(np.pi*(1.5/6))
bar_labels.add(label)
composition = [96.350861, 18.5706488, 14.7071608, 8.25588773, 7.33856028, 4.24083463, 1.65574964, 1.36437485, 1]
chart = BarChart(values=composition,**self.CONFIG)
chart.shift(UP)
self.play(Write(chart),Write(bar_labels), run_time=2)
I'm using GNU Octave, version 4.4.1. I'm trying to make an interactive plot of a simple oscillator by including two sliders which would allow the initial velocity and oscillator mass to be changed.
The plot itself shows fine, as well as the script with one slider (for velocity). Here's a part of that script with the callback function:
function titranje_ia1 (hslider, event)
v0 = get ( hslider, "value" );
m = 1;
k = 1;
t = 0:0.1:30;
x = v0*sin(sqrt(k/m)*t);
axes ('position', [0.1, 0.2, 0.8, 0.75]);
h = plot ( t, x );
axis ([0 30 -11 11]);
set (h, "linewidth", 2);
set (gca, "xlabel", "t (s)", "ylabel", "x (m)", "fontsize", 12);
set (gca, 'XTick', 0:pi:10*pi)
set (gca, 'XTickLabel', {'0','\pi','2\pi','3\pi','4\pi','5\pi','6\pi','7\pi','8\pi','9\pi','10\pi'})
grid on;
l = legend (sprintf('v0 = %f', v0));
set (l, "fontsize", 12)
endfunction
However, when I include a second slider
function titranje_ia2 (hslider1, hslider2, event)
v0 = get ( hslider1, "value" );
m = get ( hslider2, "value" );
k = 1;
t = 0:0.1:30;
x = v0.*sin(sqrt(k./m).*t);
axes ('position', [0.1, 0.2, 0.8, 0.75]);
h = plot ( t, x );
axis ([0 30 -11 11]);
set (h, "linewidth", 2);
set (gca, "xlabel", "t (s)", "ylabel", "x (m)", "fontsize", 12);
set (gca, 'XTick', 0:pi:10*pi)
set (gca, 'XTickLabel', {'0','\pi','2\pi','3\pi','4\pi','5\pi','6\pi','7\pi','8\pi','9\pi','10\pi'})
grid on;
l = legend (sprintf('v0 = %f', v0));
set (l, "fontsize", 12)
endfunction
I receive an error:
error: titranje_ia2: product: nonconformant arguments (op1 is 0x0, op2 is 1x301)
execution error in graphics callback function
Since I know that 'k' is a scalar and 't' a vector (but I'm not sure what v0 and m would be; I suppose scalars), I included an elementwise operations in function 'x' definition. 't' size is 1x301, so I assume that 'sqrt(k./m)' is 0x0 (as seen by Octave). Shouldn't it be 1x1?
Indeed, when I try
size(m)
I receive ans = 0 0 (for size(v0) I get ans = 1 1). Could it be that there is a problem with slider definition? I include at the end both slider definitions:
%Definiramo ui element: 'klizac' za v0
hslider1 = uicontrol (
"style", "slider",
"units", "normalized",
"position", [0.1, 0.0, 0.8, 0.1],
"min", 1,
"max", 10,
"value", 4,
"callback", #titranje_ia2
);
%Definiramo ui element: 'klizac' za m
hslider2 = uicontrol (
"style", "slider",
"units", "normalized",
"position", [0.1, 0.05, 0.8, 0.1],
"min", 1,
"max", 10,
"value", 1,
"callback", #titranje_ia2
);
Thank You in advance!
Best regards,
Igor
You seem to be misunderstanding a bit how callbacks work. Whenever you interact with a uicontrol object, the associated callback is always called automatically with [at least] two arguments: the first is always the 'handle' of the corresponding uicontrol object that triggerred he callback, and the second is the type of 'event' that was triggered. Therefore your callback function needs to always have a signature of callbackname( hndl, evt ) at the very least, so that it can handle those two arguments passed to it by default.
You can specify extra arguments to passed to the callback if you want, but these will necessarily be interpreted as 3rd, 4th, and so on, inside the callback function (see example below).
If you have a case like yours where you don't really care where the event originated from, and you want to affect (or in this case 'read from') two existing uicontrols in a single callback, regardless which one triggerred the event, the simplest thing to do is to make both slider handles to be extra arguments to the callback, and simply ignore the first argument (i.e. the 'active handle') inside your callback. (in fact, you're already ignoring the 'event' argument too!).
Here's an example:
%% In file makesliders.m
function makesliders()
% Label and slider for initial velocity
IV_label = uicontrol( 'style', 'text' , 'units', 'normalized', 'position', [0.10, 0.025, 0.30, 0.075], 'string', 'Initial Velocity' );
IV_slider = uicontrol( 'style', 'slider', 'units', 'normalized', 'position', [0.45, 0.025, 0.50, 0.075], 'min', 1, 'max', 10 );
% Label and slider for oscillator mass
OM_label = uicontrol( 'style', 'text' , 'units', 'normalized', 'position', [0.10, 0.125, 0.30, 0.075], 'string', 'Oscillator Mass ' );
OM_slider = uicontrol( 'style', 'slider', 'units', 'normalized', 'position', [0.45, 0.125, 0.50, 0.075], 'min', 1, 'max', 10 );
% Set callbacks and initial values to IV and OM sliders, and plot initial graph
v0_init = 4; m_init = 1;
set( IV_slider, 'value', v0_init, 'callback', { #slider_callback, IV_slider, OM_slider } );
set( OM_slider, 'value', m_init , 'callback', { #slider_callback, IV_slider, OM_slider } );
plot_oscillation( v0_init, m_init );
endfunction
function slider_callback (active_handle, event, IV_slider, OM_slider )
v0 = get( IV_slider, 'value' );
m = get( OM_slider, 'value' );
plot_oscillation( v0, m );
endfunction
function plot_oscillation( v0, m )
k = 1;
t = 0 : 0.1 : 30;
x = v0 * sin( sqrt( k / m ) * t );
h = plot( t, x ); set( h , 'linewidth', 2);
set( gca, 'position', [0.1, 0.325, 0.85, 0.650], 'xlim', [0, 30], 'ylim', [-11, 11], 'xlabel', 't (s)', 'ylabel', 'x (m)', 'fontsize', 12, 'xtick', [0 : pi : 10 * pi], 'xticklabel', strcat( arrayfun( #num2str, 0:10, 'uniformoutput', false ), '\pi' ), 'xgrid', 'on', 'ygrid', 'on' );
l = legend( sprintf( 'v0 = %.2f, m = %.2f', v0, m ) ); set( l, 'fontsize', 12 );
endfunction
I am building a dashboard using Plotly Dash. I am using bootstrap.min.css , I would like to increase the width of my container so that I can accommodate two graphs , in a single row.
My second graphs(Line graph) , has more width hence unable to align them in a single row.
I have attached the snapshot below,
DASH UI CODE :
# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
"top": 0,
"left": 0,
"bottom": 0,
"width": "16rem",
"padding": "2rem 1rem",
"background-color": "#f8f9fa",
"position": "fixed",
"color":"#000",
}
# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
}
sidebar = html.Div(
[
html.H2("Plate", className="display-4"),
html.Hr(),
html.P(
"A simple dashboard", className="lead"
),
dbc.Nav(
[
dbc.NavLink("Dashboard", href="/dashboard", id="page-1-link"),
dbc.NavLink("Analytics", href="/page-2", id="page-2-link"),
dbc.NavLink("Page 3", href="/page-3", id="page-3-link"),
html.Hr(),
dbc.NavLink("Logout", href="/logout", id="page-4-link"),
],
vertical=True,
pills=True,
),
],
style=SIDEBAR_STYLE,
)
content = html.Div(id='page-content' , className ='container' ,style=CONTENT_STYLE)
app.layout = html.Div([dcc.Location(id="url"), sidebar, content])
app.config.suppress_callback_exceptions = True
# this callback uses the current pathname to set the active state of the
# corresponding nav link to true, allowing users to tell see page they are on
#app.callback(
[Output(f"page-{i}-link", "active") for i in range(1, 4)],
[Input("url", "pathname")],
)
def toggle_active_links(pathname):
if pathname == "/" or pathname == "/dashboard":
# Treat page 1 as the homepage / index
return True, False, False
return [pathname == f"/page-{i}" for i in range(1, 4)]
#app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
if pathname in ["/", "/page-1", "/dashboard"]:
dashBoard = html.Div([
html.Div([dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=dt(minDate[0],minDate[1],minDate[2]),
max_date_allowed=dt(maxDate[0],maxDate[1],maxDate[2]),
initial_visible_month=dt(maxDate[0],maxDate[1],maxDate[2]),
start_date=dt(minDate[0],minDate[1],minDate[2]).date(),
end_date=dt(maxDate[0],maxDate[1],maxDate[2]).date()
),
html.Button(id="date-button" , children ="Analyze" , n_clicks = 0, className = 'btn btn-outline-success')
], className = 'row'),
html.Div([
html.Br(),
html.Div([
html.H4(['Category Overview'] , className = 'display-4'),
html.Br(),
html.Br(),
], className = 'row'),
html.Div([
html.Div([dcc.Graph(id='categoryPerformance',figure = dict(data=ge.returnCategoryOverviewBarGraph(df)[0],
layout=ge.returnCategoryOverviewBarGraph(df)[1]))
], className = 'col'),
html.Div([dcc.Graph(id='categoryPerformanceTrend')
], className = 'col')
], className = 'row'),
html.Hr(),
html.Div([
html.Div([
dcc.Dropdown(id = 'category-dd', options = category_items, value = 'Food')
], className = 'col-6 col-md-4'),
html.Div([
dcc.Slider(id = 'headCount' , min = 5, max=20 , step = 5 , value = 5, marks = {i: 'Count {}'.format(i) for i in range(5,21,5)})
], className = 'col-12 col-sm-6 col-md-8')
], className = 'row'),
html.Div([
html.Br(),
html.Br(),
html.Div([
dcc.Graph(id ='idvlCategoryPerformanceBest')
], className ='col'),
html.Div([
dcc.Graph(id ='idvlCategoryPerformanceLeast')
], className = 'col')
], className = 'row')
])
] , className='container')
return dashBoard
I have zero knowledge in frontend / css , any help is much appreciated. Thanks !
does anybody know how to plot the Dirac function in top left corner and the sinus function given in the picture. I managed to plot the second and third easily. Would you do this with a piecewise function or is there an easy way for Plot #1 and #4 ? Thank you very much!
Arbitrary Excitations
If this is homework then I suppose that for the sinus example you are being asked to investigate the effects of scale and shift.
Consider these plots, one after another. Observe how they differ. First I scale the magnitude (y-direction) by 10. Then I scale in the x-direction. And finally I shift in the x-direction.
plots:-setoptions(size=[300,0.6],tickmarks=[decimalticks,default]):
plot( 10*sin( x ), x=0 .. Pi, view=[0..Pi, 0..18] );
plot( 10*sin( x*Pi ), x=0 .. 1, view=[0..1, 0..18] );
plot( 10*sin( x*Pi/0.3 ), x=0 .. 0.3, view=[0..1, 0..18] );
plot( 10*sin( (x-0.1)*Pi/0.3 ), x=0.1 .. 0.4, view=[0..1, 0..18] );
plots:-setoptions();
It can be made to look similar to the 4th plot in the image to which you linked quite easily. You can try it with and without the various options.
P:= plot( 10*sin( (x-0.1)*Pi/0.3 ), x=0.1 .. 0.4
, axes=none
, color=black
, size=[300,0.7]
, thickness=2
):
plots:-display( P
, view=[0.0 .. 0.6, 0..18]
, tickmarks=[[0.1,0.4],[10=10*N]]
, axes=normal, labels=[`t[s]`,`F(t)`]
, size=[300,0.6]
);
And with more effort it can be made a closer match, visually.
plots:-display( P
, plottools:-arrow([0,0],[0.6,0], 0.05, 0.9, 0.05)
, plottools:-arrow([0,0],[0,16], 0.001, 0.02, 0.08)
, plots:-textplot([0.6, -3.5, `t[s]`, font=["courier",16]])
, plots:-textplot([0.0, 18, `F(t)`, font=["courier",16]])
, seq(plots:-textplot([X, -1.5, X]), X=[0,0.1,0.4])
, plots:-textplot([-0.05, 10, "10 N"])
);
For your other plot you could simply plot a sequence of lines.
T:=table([1=60,2=100,3=0,4=20]):
P2:=seq(plottools:-line([i,0],[i,T[i]],thickness=2,color=black),
i=1..4):
And you could adjust the look and feel of the final plot as above. I'll leave that to you.
plots:-display(P2
, size=[300,0.7]
, view=[0..6, 0..120]
, labels=["",""]
);