How to quantize a 2Hz sine wave with 3-bit and plot the error as a graph
I am relatively new to Python and cannot figure out how to quantize a sine wave down to 3-bit with ±3 levels. The number of quantization steps should be adjustable by the parameter level and should be the same in the positive and negative range (level = 3 means 3 steps in the negative range and 3 steps in the negative range and 3 steps in the positive range). The amplitude has to be 1.
This is my code so far:
freq = 2
time = np.arange(0, 1, 0.001) #sample rate of 1000
y = np.sin(2 * np.pi * freq * time)
plt.plot(time, y)
plt.title('sine wave')
plt.grid()
plt.show()
do you know?
how many words do you know
See also questions close to this topic
-
How to deal with the colorbar axis space in matplotlib subplots
I am plotting seven different parameters over four seasons, as shown in below image. but on last column (Post-Monsoon) sub_plots axis compromised with colorbar axis, that is really awkward!!
import matplotlib.pyplot as plt import cartopy import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import warnings warnings.filterwarnings('ignore') k = [1,5,9,13,17,21,25] k1= [25,26,27,28] k2= [4,8,12,16,20,24,28] k3= [1,2,3,4] k4=[25] S=['Winter','Pre-monsoon','Monsoon','Post-Monsoon'] fig=plt.figure(figsize=(13,11), dpi=300) for i in range(1,29): ax = fig.add_subplot(7,4,i, projection=ccrs.PlateCarree()) ax.set_extent([39.9,100.5,-0.5,25.5],ccrs.PlateCarree()) ax.add_feature(cartopy.feature.COASTLINE) ax.add_feature(cartopy.feature.BORDERS, linestyle='-') ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k') ax.set_xticks([40,50,60,70,80,90,100], crs=ccrs.PlateCarree()) ax.set_yticks([0,5,10,15,20,25], crs=ccrs.PlateCarree()) ax.tick_params(axis='x', length=7, width=1, bottom=True, top=True) ax.tick_params(axis='y', length=7, width=1, right=True, left=True) ax.yaxis.set_major_formatter(plt.NullFormatter()) ax.xaxis.set_major_formatter(plt.NullFormatter()) A=D[i-1].plot.pcolormesh(ax=ax, cmap='seismic', transform=ccrs.PlateCarree(), add_colorbar=False,add_labels=False) # D contains list of parameters to be plotted if i in k: gl = ax.gridlines(draw_labels=True, linestyle='--') gl.xlabels_top=False gl.xlabels_bottom=False gl.ylabels_right=False gl.xformatter=LONGITUDE_FORMATTER gl.yformatter=LATITUDE_FORMATTER gl.xlabel_style={'size':10,} gl.ylabel_style={'size':10,} ax.tick_params(axis='y', length=7, width=1, left=False) if i in k1: gl = ax.gridlines(draw_labels=True, linestyle='--') gl.xlabels_top=False gl.xlabels_bottom=True gl.ylabels_right=False gl.ylabels_left=False gl.xformatter=LONGITUDE_FORMATTER gl.yformatter=LATITUDE_FORMATTER gl.xlabel_style={'size':10,} gl.ylabel_style={'size':10,} ax.tick_params(axis='x', length=7, width=1, bottom=False, top=True) ax.tick_params(axis='y', length=7, width=1, right=True, left=True) if i in k4: ax.tick_params(axis='y', length=7, width=1, right=True, left=False) if i in k2: ax.tick_params(axis='y', length=7, width=1, right=False) fig.colorbar(A,ax=ax, shrink=0.5) # Here is the Colorbar option if i in k3: ax.tick_params(axis='x', length=7, width=1,top=False) ax.title.set_text(S[i-1]) fig.tight_layout(h_pad=0) plt.show()
How to adjust colorbar without distortion of the last axis, Any remark from the community🙏 Thanks
-
Place ipywidget Dropdown on screen in matplotlib.pyplot axes ax1
When I run this code, the Dropdown is nowhere to be found. How do I make it appear in ax1? (I think I would like to avoid Tkinter.)
#!/usr/bin/env python3 #Place ipywidget Dropdown on screen in matplotlib.pyplot axes ax1 import matplotlib.pyplot as plt from ipywidgets.widgets import Dropdown, Layout fig = plt.figure() axcolor = 'lightgoldenrodyellow' # I want a fig with 1 axes--left rectangle with Dropdown (later I will have 4 other axes) # instance the axes [left, bottom, width, height]. ax1 = fig.add_axes([.1, .4, .4, .4]) #([.92, .97, .08, .03]) # Dropdown is from ipywidgets def STypeGrp_event_handler(change): print(change.new) STypeGrp.value = "" STypeGrp = Dropdown( options=list(['E1', 'E2', 'F1']), value='E1', description='Type-Grp:', layout=Layout(width='100px', margin = '20px 20px 20px 20px') ) STypeGrp.observe(STypeGrp_event_handler) #widgets.interact(STypeGrp_event_handler, value=STypeGrp) plots = [STypeGrp] # ?? How do I put STypeGrp dropdown into the ax1 frame?? figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show()
-
Training plot is not appearing properly for keras model
I have data where I need to train it with X and Y. Traning part is done but when I want to plot the prediction and actual data, it is appearing with so many lines instead of showing just non-linear regression line.
model= Sequential() model.add(Dense(7,input_dim=1, activation="tanh")) model.add(Dense(1)) model.compile(loss="mse", optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), metrics= ["mae"]) history=model.fit(X,Y,epochs=1000) predict=model.predict(X) plt.scatter(X, Y,edgecolors='g') plt.plot(X, predict,'r') plt.legend([ 'Predictated Y' ,'Actual Y']) plt.show()
Please see the attached imageplotting image
-
r - Plotting monthly time series data in R - cannot plot more than 10 series
I'm having a lot of trouble plotting my time series data in R Studio. My data is laid out as follows:
tsf
Time Series: Start = 1995 End = 2021 Frequency = 1 Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec 1995 10817 8916 9697 10314 9775 7125 9007 6000 4155 3692 2236 996 1996 12773 12562 13479 14280 13839 9168 10959 6582 5162 4815 3768 1946 1997 14691 12982 13545 14131 14162 10415 11420 7870 6340 6869 6777 6637 1998 17192 15480 14703 16903 15921 13381 13779 9127 6676 6511 5419 3447 1999 13578 19470 23411 18190 18979 17296 16588 12561 10405 8537 7304 4003 2000 20100 29419 30125 27147 27832 23874 19728 15847 11477 9301 6933 3486 2001 16528 22258 22146 19027 19436 15688 14558 10609 6799 6563 4816 2480 2002 14724 19424 21391 17215 18775 13017 14385 10044 7649 6598 4497 2766 2003 17051 20182 18564 18484 15365 12180 13313 8859 6830 6371 3781 2012 2004 16875 20084 21150 19057 16153 13619 14144 9599 7390 5830 3763 2033 2005 20002 24153 23160 20864 18331 14950 14149 11086 7475 6290 3779 2134 2006 24605 26384 24858 20634 18951 15048 14905 10749 7259 5479 3074 1509 2007 29281 26495 25974 21427 20232 15465 15738 10006 6674 5301 2857 1304 2008 32961 24290 20190 17587 12172 7369 16175 6822 4364 2699 1174 667 2009 10996 8793 7345 5558 4840 4833 4355 2422 2272 1596 948 474 2010 10469 11707 12379 9599 8893 8314 7018 5310 4683 3742 2146 647 2011 13624 13470 12390 11171 9359 9240 6953 3653 2861 2216 1398 597 2012 14507 10993 10581 9388 7986 5481 6164 3736 2783 2442 1421 774 2013 10735 9671 10596 8113 7095 3293 9306 4504 3257 2832 1307 639 2014 15975 11906 11485 11757 7767 3390 14037 6201 4376 3082 1465 920 2015 20105 15384 17054 13166 9027 3924 21290 8572 5924 3943 1874 847 2016 27106 21173 20096 14847 10125 4143 22462 9781 5842 3831 1846 679 2017 26668 16905 17180 13427 9581 3585 21316 8105 4828 3255 1594 601 2018 25813 16501 16088 11557 9362 3716 20743 7681 4397 2874 1647 778 2019 22279 14178 14404 13794 9126 3858 18741 7202 4104 3214 1676 729 2020 20665 13263 10239 1338 1490 2189 15329 7360 5747 4189 1468 1032 2021 16948 11672 10672 8214 7337 4980 20232 8563 6354 3882 2167 832
When I attempt rudimentary code to plot the data I get the following
plot(tsf) 'Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, : cannot plot more than 10 series as "multiple"'
My data is monthly and therefore 12 months exceed this apparent limit of 10 graphs.I've been able to make some plot by excluding two months but this is not practical for me. I've looked at lots of answers on this, many of which recommending
ggplot() {ggplot2}
The link below had data most closely resembling my data but I still wasn't able to apply it.
issues plotting multivariate time series in R
Any help greatly appreciated.
-
How to plot a Sequential Bayes Factor as participants are added
I am currently analyzing eye-tracking data using the Sequential Bayes Factor method, and I would like to plot how the resulting Bayes Factor (BF; calculated from average looking times) changes as participants are added.
I would like the x-axis to represent the number of participants included in the calculation, and the y-axis to represent the resulting Bayes Factor.
For example, when participants 1-10 are included, BF = [y-value], and that is one plot point on the graph. When participants 1-11 are included, BF = [y-value], and that is the second plot point on the graph.
Is there a way to do this in R?
For example, I have this data set:
ID avg_PTL <chr> <dbl> 1 D07 -0.0609 2 D08 0.0427 3 D12 0.112 4 D15 -0.106 5 D16 0.199 6 D19 0.0677 7 D20 0.0459 8 d21 -0.158 9 D23 0.0650 10 D25 0.0579 11 D27 0.0463 12 D29 0.00822 13 D30 0.00613 14 D36 -0.0484 15 D37 0.0312 16 D39 0.000547 17 D44 0.0336 18 D46 0.0514 19 D48 0.236 20 D51 -0.000487 21 D60 0.0410 22 D61 0.0622 23 D62 0.0337 24 D64 -0.125 25 D65 0.215 26 D66 0.200
And I calculate the BF with:
bf.mono.correct = ttestBF(x = avg_PTL_mono_correct$avg_PTL)
Any tips are much appreciated!
-
Julia plot hline! doesn't work with multiple threads
I have a simple simulation and I want to plot errors on 3 distinct figures. To speed things up I wanted to introduce a little bit of parallel computing.
Threads.@threads for i in 1:3 plt = plot(t, err[:, i], linecolor=:blue, label=[""], linewidth=3) hline!(plt, [0], linestyle=:dash, linecolor=:black, label=[""]) xlabel!(L"t") ylabel!(L"e_%$i") savefig(plt, "fig/Staubli_Slotine_Li$i.pdf") end
Everything stops working when I try running julia with
-t3
flagERROR: LoadError: TaskFailedException Stacktrace: [1] wait @ ./task.jl:334 [inlined] [2] threading_run(func::Function) @ Base.Threads ./threadingconstructs.jl:38 [3] top-level scope @ ./threadingconstructs.jl:97 nested task error: KeyError: key :annotations not found Stacktrace: [1] pop!(h::Dict{Symbol, Any}, key::Symbol) @ Base ./dict.jl:587 [2] pop_kw!(dd::RecipesPipeline.DefaultsDict, k::Symbol) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/utils.jl:57 [3] _update_subplot_args(plt::Plots.Plot{Plots.PGFPlotsXBackend}, sp::Plots.Subplot{Plots.PGFPlotsXBackend}, plotattributes_in::Dict{Symbol, Any}, subplot_index::Int64, remove_pair::Bool) @ Plots ~/.julia/packages/Plots/nzdhU/src/args.jl:2058 [4] _subplot_setup(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:277 [5] plot_setup!(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:138 [6] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/RecipesPipeline.jl:87 [7] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:208 [8] plot!(::Plots.Plot; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:198 [9] plot!(; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:188 [10] #xlabel!#484 @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [11] xlabel! @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [12] macro expansion @ ~/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:29 [inlined] [13] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})(onethread::Bool) @ Main ./threadingconstructs.jl:85 [14] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})() @ Main ./threadingconstructs.jl:52 in expression starting at /home/jcebulsk/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:26
If I comment out
hline!
the script runs without any issue.It looks like I can't have both
hline
and parallel operation. -
How to prevent WebGL from clipping outside bounds when drawing a wavy circle?
I have a shader that draws a bunch of instanced circles, and it works great! It works by basically drawing a bunch of rectangles at every given location, and then in the fragment shader it effectively discards pixels that are outside the radius, and this draws a circle.
I'm trying to update the shader now to make it draw "wavy" circles. That is, having a sin curve trace the entire outer edge of the circle. But the issue I'm running into now is that this curve will clip outside the bounds of the rectangle, and as a result, edges will be cut off. I drew a (crude) picture of what I think is happening:
As you can see, making a circle by hollowing out a quad works fine in the easy case. But when you add waves to the circle, portions of it clip outside of the unit space, causing those portions to not be rendered, so the rendered circle gets cut off at those parts. Here is what it looks like in my application (notice it gets cut off on the top, bottom, right, and left edges):
Here is where I believe the clip is occurring:
Here are my current vertex and fragment shaders for drawing these wavy circles. Is there any way I can modify them to prevent this clipping from occurring? Or maybe there is some WebGL setting I could use to fix this?
Vertex Shader:
in vec2 a_unit; // unit quad in vec4 u_transform; // x, y, r, alpha uniform mat3 u_projection; // camera out float v_tint; out vec2 v_pos; void main() { float r = u_transform.z; float x = u_transform.x - r; float y = u_transform.y - r; float w = r * 2.0; float h = r * 2.0; mat3 world = mat3( w, 0, 0, 0, h, 0, x, y, 1 ); gl_Position = vec4(u_projection * world * vec3(a_unit, 1), 1); v_tint = u_transform.w; v_pos = a_unit; }
Fragment Shader:
in vec2 v_pos; in float v_tint; uniform vec4 u_color; uniform mat3 u_projection; uniform float u_time; out vec4 outputColor; void main() { vec2 cxy = 2.0 * v_pos - 1.0; // convert to clip space float r = cxy.x * cxy.x + cxy.y * cxy.y; float theta = 3.1415926 - atan(cxy.y, cxy.x) * 10.0; // current angle r += 0.3 * sin(theta); // add waves float delta = fwidth(r); // anti-aliasing float alpha = 1.0 - smoothstep(1.0 - delta, 1.0 + delta, r); outputColor = u_color * alpha * vec4(1, 1, 1, v_tint); }
-
Sine fitting using scipy is not returning good fit
trying to fit some sine wave to data i collected. But Amplitude and Frequency are way off. Any suggestions?
x=[0,1,3,4,5,6,7,11,12,13,14,15,16,18,20,21,22,24,26,28,29,30,31,32,35,37,38,40,41,42,43,44,45,48,49,50,51,52,53,54,55,57,58,60,61,62,63,65,66,67,68,69,70,71,73,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,112,114,115,116,117,120,122,123,124,125,128,129,130,131,132,136,137,138,139,140,143,145,147,148,150,151,153,154,155,156,160,163,164,165,167,168,169,171,172,173,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,199,201,202,203,204,205,207,209,210,215,217,218,223,224,225,226,228,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,254,255,256,257,258,259,260,261,262,263,264,265,266,267,269,270,271,272,273,274,275,276,279,280,281,282,286,287,288,292,294,295,296,298,301,302,303,310,311,312,313,315,316,317,318,319,320,321,323,324,325,326,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,348,349,350,351,352,354,356,357,358,359,362,363,365,366,367,371,372,373,374,375,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,404,405,406,407,408,411,412,413,417,418,419,420,421,422,428,429,431,435,436,437,443,444,445,446,450,451,452,453,454,455,456,459,460,461,462,464,465,466,467,468,469,470,471,472,473,474,475,476,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,495,496,497,498,499,500,501,505,506,507,512,513,514,515,516,517,519,521,522,523,524,525,526,528,529,530,531,532,533,535,537,538,539,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,559,560,561,562,563,564,566,567,568,569,570,571,572,573,574,575,577,578,579,584,585,586,588,591,592,593,594,596,598,600,601,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,642,643,644,646,647,648,650,652,653,654,655,656,660,661,662,663,665,666,667,668,669,670,671,672,673,676,677,678,679,680,681,682,684,685,687,688,690,691,692,693,694,695,696,697,698,701,702,703,704,707,708,709,710,712,713,714,715,717,718,719,721,722,723 ] y=[53.66666667,53.5,51,53.66666667,54.33333333,55.5,57,59,56.5,57.33333333,56,56,57,58,58.66666667,59.5,57,59,58,61.5,60,61,62.5,67,60.66666667,62.5,64.33333333,64,64,65,65,65.66666667,68,70.5,67,67.5,71.5,65,70.5,73.33333333,72,67,76,73.5,72.83333333,75,73,74,73,71,70.5,73.16666667,70,75,69,71,68.33333333,68.5,66.75,62,63.5,63,62.5,61,53.5,61.25,55,57.5,62,54.75,56.5,52.33333333,52.33333333,49,47.66666667,47.5,45,44,42.5,41,37,37.2,34.5,33.4,33.2,34,26,28.6,25,25.5,27,22.66666667,21.66666667,21.5,22.5,22,19.8,19.66666667,20,20,17,26,22.6,19,28,26.33333333,24.25,27,28.5,30,24,33,31,41,38,22,31.66666667,30,39,26,33.5,40,40.5,38,44,47,48,43,42.5,44,43,51.5,48,49.66666667,51.5,47,56,50,50,58,51,58,58.5,57.33333333,57.5,64,57,59,56.5,65.5,60,63.66666667,62,62,65.33333333,66.5,65,66,65,68,65.5,65.83333333,60,65.5,70,68,64,65.42857143,62,68,63.25,62,63.33333333,60.4,59,52.5,52.6,55.16666667,50,51,45.33333333,48.33333333,39.4,38.25,34.33333333,43.25,31.33333333,29.5,29.5,29,27,26,27,25.5,24.5,23,22,22.5,19.5,20,20,18,18.5,17,16,16,15,14,14.5,13,12.5,11.5,11,11,11,10.5,10.5,9,9,10,10,10.5,9,10,10,11,11,11,10,10.66666667,12,12,12.5,13,13,14,14,14.5,16,16,18,16.5,20.5,21.5,21,25,28,22,29,29,28.66666667,36,42,36.75,43.5,48,44.75,50.66666667,53.75,51,57.33333333,58.5,58.66666667,60,60.25,61.75,60,58.5,63,61,60.33333333,62,63,63,60,61.5,62.33333333,62.66666667,61,63.5,61,61.66666667,62,59,60,57.5,56,57,58.5,52.5,50.5,47.5,49.66666667,49.66666667,54.66666667,45.66666667,41,44,33.16666667,49,45,29.5,39.5,29,20.5,23.5,23,19,18.66666667,17,16.75,15.5,15,16,17,13.5,12.2,12,14,13,11,11.5,11.5,11,11.5,11,11.5,11.5,12,13,13,13,13,13.5,14,14,14,15,17,15,16,16,17,18,17,18,18.5,19.5,20.5,20,21.5,20,22,22,23,23,25,26,28,29,36.25,31,37.75,41.33333333,43.6,37.5,46.5,38,47.33333333,46.75,47,50.5,48.5,58,50.5,48.75,54.33333333,56,49,55.5,60,56.5,56,60,56.5,52.75,54,56,57,56,52.66666667,52,52.66666667,53,47.66666667,44,48,50.5,45,46.66666667,48,44.66666667,42.33333333,46.5,43,36.75,41,28,35,36.5,36,37.33333333,24,30.5,29,29.33333333,32.5,20,25.5,27.5,18,33,25.75,26,19.5,16,15.5,18,13,21,12,12.25,11,5,9,10,7.5,5,7.5,4,4.5,5.666666667,3.5,6.5,5,7,7.333333333,7,9,7.5,9,9.5,11,9,10,12,11.5,12.5,13,14,13.5,13,14,15,15,16,16.5,17.5,19.66666667,19.33333333,20.5,23.66666667,25.5,28.75,31,32.66666667,33.66666667,29,32.33333333,37.6,31,39.5,49,44.14285714,41,42.16666667,45,47.66666667,50.2,52.66666667,52,50,54,53.33333333,54.66666667,54.5,54,56,54,53.5,53,53,52,51.5,51.5,52,48,53,48,50,49.5,48.5,46,45,47,49,48,44,42,42,43,43,42.5,41.5,39.5,46,36,37.5,39,39,38,43,40,38,32.5,34,35.33333333,35,35,30.5,30,31.33333333,33,26,30,27,24,30,28,25,29,25.33333333] from scipy.optimize import curve_fit from numpy import sin def fitting(x, a, b, c): return a * sin(b*x + c) constants = curve_fit(fitting, x, y) a_fit= constants[0][0] b_fit= constants[0][1] c_fit = constants[0][2] fit_y=[] for i in x: fit_y.append(fitting(i, a_fit, b_fit, c_fit)) plt.plot(x,fit_y, '--', color='red') plt.scatter(x,y)
-
Merging two different sized intersecting circles and finding the coordinates of a radius-weighted center
I'm working on a fun little simulation environment for circles. I cannot find an accurate way to combine two circles and find their center coordinate.
I set up an html canvas, then generate random coords on the plane along with a random sized radius. After every generation, I check for an intersection between every circle and every other circle. When circles intersect I want them to merge - making a circle with the combined surface area. Finding the coordinates of the new center is my issue.
I don't want to simply find the midpoint of the centers because that doesn't factor in the size of the circles. A humongous circle could be swayed by a tiny one, which doesn't make for a realistic simulation.
I've thought up what I think is a bad solution: multiplying the change in distance created by the midpoint formula by the ratio of the two circles radii, getting the angle of the resulting triangle, using trig to get the x and y difference, then adding that to the center of the larger circle and calling it a day.
Really have no clue if that is the right way to do it, so I wanted to ask people smarter than me.
Oh also here's a link to the repo on github: Circle Simulator
This is my first stackOverflow question so bear with me if I did something completely stupid. Thanks everyone!
var dataForm = document.getElementById('dataForm'); var type = document.getElementById('type'); var dataMinRad = document.getElementById('dataMinRad'); var dataMaxRad = document.getElementById('dataMaxRad'); var phaseInterval = document.getElementById('phaseInterval'); //form on submit const onDataSubmit = (e) => { if (e) e.preventDefault(); //updates min and max radius minRadius = parseInt(dataMinRad.value); maxRadius = parseInt(dataMaxRad.value); //clears canvas c.clearRect(0, 0, canvas.width, canvas.height); //clears circles circles = []; //clears any previous interval clearInterval(phase); let generator = eval(type.value), data; //every one second this code is repeated phase = setInterval(() => { //gets the circle data from whatever generator is selected data = generator(); //adds the new circle and draws it on the canvas if the data is good if (data) { circles.push(new Circle(data.x, data.y, data.rad)); circles[circles.length - 1].draw(); } }, parseInt(phaseInterval.value)); } dataForm.addEventListener('submit', onDataSubmit); </script> <script> //initializes global elements var stage = document.getElementById('stage'); var canvas = document.getElementById('myCanvas'); var c = canvas.getContext('2d'); //sets width and height of canvas to that of the stage canvas.setAttribute('width', stage.clientWidth); canvas.setAttribute('height', stage.clientHeight); class Circle { constructor (x, y, rad) { this.x = x; this.y = y; this.rad = rad; } draw() { c.fillStyle = 'black'; c.beginPath(); c.arc(this.x, this.y, this.rad, 0, 2 * Math.PI, true); c.stroke(); } } //variables var circles = []; var maxRadius = 100; var minRadius = 1; var phase; const random = () => { //random coords and radius let x, y, rad; do { [x, y, rad] = [Math.round(Math.random() * canvas.width), Math.round(Math.random() * canvas.height), Math.ceil(Math.random() * (maxRadius - minRadius)) + minRadius]; } while ((() => { for (let i in circles) { if (Math.sqrt(Math.pow(x - circles[i].x, 2) + Math.pow(y - circles[i].y, 2)) < rad + circles[i].rad) { return true; } } return false; })()) //end while return { x: x, y: y, rad: rad}; } const order = () => { //gets some random coords and sets the radius to max let [x, y, rad] = [Math.round(Math.random() * canvas.width), Math.round(Math.random() * canvas.height), maxRadius]; //decreases the radius while the resulting circle still intercects any other circle while (rad >= minRadius && (() => { for (let i in circles) { if (Math.sqrt(Math.pow(x - circles[i].x, 2) + Math.pow(y - circles[i].y, 2)) < rad + circles[i].rad) { return true; } } return false; })()) { rad--; } //only sends the radii that are greater than the minimum radius if (rad >= minRadius) return { x: x, y: y, rad: rad}; } //the position changes must be weighted somehow const agar = () => { //some looping control variables let i = 0, j = 1, noChange = true; //loops through the circles array in every circle until the noChange variable is false while (i < circles.length && noChange) { while (j < circles.length && noChange) { //checks if each circle is inside each other circle if (Math.sqrt(Math.pow(circles[i].x - circles[j].x, 2) + Math.pow(circles[i].y - circles[j].y, 2)) < circles[i].rad + circles[j].rad) { //copies the two circles let tempCircles = [circles[i], circles[j]]; //splices the item closest to the end of the array first so that the position of the other doesn't shift after the splice if (i > j) { circles.splice(i, 1); circles.splice(j, 1); } else { circles.splice(j, 1); circles.splice(i, 1); } //radius of the two circles' surface area combined let rad = Math.sqrt(tempCircles[0].rad * tempCircles[0].rad + tempCircles[1].rad * tempCircles[1].rad); /* // method 1: the midpoint of the centers // let x = (tempCircles[0].x + tempCircles[1].x) / 2; let y = (tempCircles[0].y + tempCircles[1].y) / 2; */ // method 2: the radius ratio weighted // let bigCircle, smallCircle; if (tempCircles[0].rad > tempCircles[1].rad) { bigCircle = tempCircles[0]; smallCircle = tempCircles[1]; } else { bigCircle = tempCircles[1]; smallCircle = tempCircles[0]; } //get the distance between the two circles let dist = Math.sqrt(Math.pow(bigCircle.x - smallCircle.x, 2) + Math.pow(bigCircle.y - smallCircle.y, 2)); //gets the ratio of the two circles radius size let radRatio = smallCircle.rad / bigCircle.rad; //the adjusted hypot for the ratio dist = dist * radRatio; //the angle let theta = Math.atan2(smallCircle.y - bigCircle.y, smallCircle.x - bigCircle.x); // all hail atan2! //the new center coords let x = bigCircle.x + dist * Math.cos(theta); let y = bigCircle.y + dist * Math.sin(theta); circles.push(new Circle(x, y, rad)); //change happened so the variable should be false noChange = false; /* -find the middle of the point -weigh it in the direction of teh biggest circle radius as the magnitude and [angle of the triangle created when the centers are connected] as the direction for both radii. find the point on each circle closest to the center of the other circle find those two points midpoint find the distance from that point to each of the centers those two distances are the magnitude of two new vectors with the same angels as before add those two vectors is there really not a freaking easier way? */ /* try this: -get the distance between the centers. -multiply that by the ratio -get the angle -use that angle and that hypot to find the x and y -add the x and y to the bigger circles centerr */ } j++; } i++; j = i + 1; } //if there was no change if (noChange) { //random coords and radius size let x = Math.round(Math.random() * canvas.width), y = Math.round(Math.random() * canvas.height), rad = Math.ceil(Math.random() * (maxRadius - minRadius)) + minRadius; //adds the random circle to the array circles.push(new Circle(x, y, rad)); } //clears canvas c.clearRect(0, 0, canvas.width, canvas.height); //redraws ALL circles for (let i in circles) { circles[i].draw(); } } onDataSubmit();
* { margin: 0; box-sizing: border-box; } #wrapper { width: 100%; max-width: 1280px; margin: auto; margin-right: 0; display: flex; flex-flow: row nowrap; } #dataContainer { height: 100%; width: 20%; padding: 5px; } #dataContainer>* { padding: 15px; } #dataForm { max-width: 200px; display: grid; } #dataForm>* { margin-top: 5px; width: 100%; } .center { margin: auto; } #stage { margin: 5px; width: 80%; height: 97vh; }
<div id='wrapper'> <!-- form containter --> <div id='dataContainer'> <h3>Data</h3> <form id='dataForm' method='post'> <label for='type'>Type:</label> <select id='type' name='type'> <option value='random' selected>Random</option> <option value='order'>Order</option> <option value='agar'>Agario</option> </select> <label for='min'>Min-Radius:</label> <input id='dataMinRad' name='min' type='number' value='1' min='0'> <label for='max'>Max-Radius:</label> <input id='dataMaxRad' name='max' type='number' value='100'> <label for='interval'>Phase Interval:</label> <input id='phaseInterval' name='interval' type='number' value='1' min='1'> <button type='submit' id='dataSubmit' class='center'>Load</submit> </form> </div> <!-- canvas container--> <div id='stage'> <canvas id='myCanvas'></canvas> </div> </div>
-
key generation from feature vectors in high dimentions
I welcome any suggestions to solve the following hard problem:
I have a dataset of float feature vectors of size 512 where each feature vector is extracted from a face image. I want to generate a key given a feature vector (this key can be a number/binary code/etc) that is consistent to each person without comparisons between feature vectors. The only input I have is the given feature vector. for example if I see a photo of me I want to generate a number X. another photo of me will generate the same number X without comparison between the two feature vectors from the two photos.
Assumption1: feature vectors of images from the same person are very close to each other (dot product is high) and feature vectors of images from different persons are far (dot product is low). Assumption2: assume I only have 1K or 10K keys, it is ok if there's some collision in the keys. The key doesn't have to be super unique, but it has to be consistent. Assupmtion3: a given feature vector can be from a face image of a person that is not in the dataset I have.
I tried a few things solution1: the easy solution would be to assign each person a random key and given a new feature vector compare to all and assign the same key. But, I want to generate the key without comparisons (for multiple reasons - this constrain is important). solution2: I tried to normalize the feature vectors so that they sit on the 512-sphere, then tried to divide the sphere with N=10k seeds. Given a feature vector I assign to it the number of the nearest seed. The problem is that clustering algorithms break in very high dimentions (all seeds are far from a new feature vector - the nearst becomes almost random, therefore not consistent to all new feature vectors of same person). solution3: I tried to discretize the feature vectors to generate a binary code (for example using sign on the feature vector) it doesn't produce a consistent enough code for feature vectors of same person.
I appreciate anything you can give.
-
How pytorch implement forward for a quantized linear layer?
I have a quantized model in pytorch and now I want to extract the parameter of the quantized linear layer and implement the forward manually. I search the source code but only find this function.
def forward(self, x: torch.Tensor) -> torch.Tensor: return torch.ops.quantized.linear( x, self._packed_params._packed_params, self.scale, self.zero_point)
But no where I can find how torch.ops.quantized.linear is defined.
Can someone give me a hind how the forward of quantized linear are defined?
-
How to use RATE_VERY_FAST in accelerometer (Android Studio, Java)
In documentation for developing on android there is information about RATE_VERY_FAST Method it allows reading data from accelerometer with 440-1760 Sample rate. How to use it? Is there an example of code?
https://developer.android.com/reference/android/hardware/SensorDirectChannel#RATE_VERY_FAST
-
Is there a limit of sample rate of accelerometer on android?
Is it possible to reading data from accelerometer with very high sample rate? I need about an 1-2 KHZ. My sensor is can read data with sample rate 25 KHZ, but on android it reading data with 200-400 HZ sample rate. What to do?