I am trying to read large oscilloscope .trc files and plot them. Plotting one file works but as soon as I put the script into a loop, trying to plot all files (1 file a loop) I am getting a MemoryError.
Code:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import readTrc #external file, same location as script
foldername = 'trc_folder'
folder = os.listdir(foldername)
path = os.path.dirname(os.path.realpath(__file__))
for filenumber, i in enumerate(folder):
trc = path + '/' + foldername + '/' + i
print('reading trc file ' + str(filenumber))
datX, datY, m = readTrc.readTrc(trc)
srx, sry = pd.Series(datX * 1000), pd.Series(datY * 1000)
df_oszi = pd.concat([srx, sry], axis = 1)
df_oszi.set_index(0, inplace = True)
#ERROR APPEARS with xticks argument
#removing xticks does not help, because then errorpath changes to
#/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py
df_oszi.plot(grid = 1,
color = 'blue',
linewidth = 0.5,
figsize = (9,5),
legend = False,
xticks = np.arange(df_oszi.index[0], df_oszi.index[-1], 1))
print('plotting file ' + str(filenumber))
plt.savefig('Plot_' + str(filenumber) + '.png', dpi = 300)
The problem seems to be with the external module readTrc. It took me quite a while to figure this out because python was throwing errors around Matplotlib and Pandas rather than readTrc, which seems to be an unofficial script for reading .trc files. I found it on the net as I was looking for a way to read .trc files in python. If you know a better way for reading oscilloscope files, please let me know.
I zipped everything you need to execute the script to this folder: folder
(It is quite large 582MB, because every .trc file is about of 200MB size) Inside you will find the script, a folder with .trc files and the external python file (module) readTrc which is required for reading .trc files. Executing the script should plot the first file but throw a MemoryError when plotting/constructing the second, at least on my Ubuntu machine. What confuses me is that I only get this MemoryError on Ubuntu (18.04), not on Windows 10.
I would appreciate help so that I can continue with my project. Please let me know, if you need additional information.
Edit:
Single Download for readTrc.py
Single Download for Script.py
print(type(datX)) returns:
<class 'numpy.ndarray'>
printing datX returns an object with 50 million values:
[-0.005 -0.005 -0.005 ... 0.005 0.005 0.005]
these are round by the print() function and are:
-0.004999999906663635
-0.004999999806663634
-0.004999999706663633
-0.004999999606663631
-0.00499999950666363
Edit 2:
To run the code with the new version of readTrc make these changes:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import readTrc
foldername = 'trc_folder'
folder = os.listdir(foldername)
path = os.path.dirname(os.path.realpath(__file__))
for filenumber, i in enumerate(folder):
trc = path + '/' + foldername + '/' + i
print('reading trc file ' + str(filenumber))
datX, datY, d = readTrc.Trc().open(trc)
srx, sry = pd.Series(datX * 1000), pd.Series(datY * 1000)
df_oszi = pd.concat([srx, sry], axis = 1)
df_oszi.set_index(0, inplace = True)
df_oszi.plot(grid = 1,
color = 'blue',
linewidth = 0.5,
figsize = (9,5),
legend = False,
xticks = np.arange(df_oszi.index[0], df_oszi.index[-1], 1))
print('plotting file ' + str(filenumber))
plt.savefig('Plot_' + str(filenumber) + '.png', dpi = 300)
MemoryError:
Traceback (most recent call last):
File "/home/artur/Desktop/zip_original/Script.py", line 27, in <module>
xticks = np.arange(df_oszi.index[0], df_oszi.index[-1], 1))
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 2941, in __call__
sort_columns=sort_columns, **kwds)
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 1977, in plot_frame
**kwds)
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 1804, in _plot
plot_obj.generate()
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 260, in generate
self._make_plot()
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 985, in _make_plot
**kwds)
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 1001, in _plot
lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
File "/usr/local/lib/python3.6/dist-packages/pandas/plotting/_core.py", line 615, in _plot
return ax.plot(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/matplotlib/__init__.py", line 1805, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py", line 1604, in plot
self.add_line(line)
File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 1891, in add_line
self._update_line_limits(line)
File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 1913, in _update_line_limits
path = line.get_path()
File "/usr/local/lib/python3.6/dist-packages/matplotlib/lines.py", line 945, in get_path
self.recache()
File "/usr/local/lib/python3.6/dist-packages/matplotlib/lines.py", line 649, in recache
self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
MemoryError
Edit 3:
Sampling the dataset seems to reduce the data value. These are examples of the same dataset with sampling = 1, sampling = 10, sampling = 100
srx, sry = pd.Series(datX[::sampling] * 1000), pd.Series(datY[::sampling] * 1000)
The reason for this is the extremely short impulse period of Ultra High Frequency waves (UHF). Each impulse can be consisting of only a few data values. If you set down the amount of values taken into account, this results in large data loss. Although this solution makes the code work, it also reduces the data value significantly.
Oh, wow, I couldn't see the wood for the trees, as they say.
You're attempting to plot way too many data points (i.e. 100000002, i think that's about 4km length of paper printed at 600dpi), which can be resolved either by sampling:
sampling=100
srx, sry = pd.Series(datX[::sampling] * 1000), pd.Series(datY[::sampling] * 1000)
or by selectively studying specific ranges:
srx, sry = pd.Series(datX[0:50000] * 1000), pd.Series(datY[0:50000] * 1000)
or a combination of both.
It took quite some time but I managed to get the MemoryError under control. Not only had I to put gc.collect() at the end of each loop but also plt.close(). Only then the Errors would stop. Sorry for the confusion. I learned a lot from this.
Related
I am a beginner with coding.I am try to call the function fitData on another script (main code).
I called the function fitData with this sintax, at the end of the script:
# If the experiments stops before a default response is inserted
stairs.addResponse(0)
stairs.saveAsExcel(outputfile)
df.to_excel(outputfile + '_trials_summary.xlsx')
win.close()
raise
#analyzeStaircases(stairs, stairInfo['AverageReversals'])
fitData(stairs, 75)
################################
# The experiment starts here #
###############################
if __name__ == "__main__":
startExperiment()
fitData code
from psychopy import data
import pylab
from numpy import average,std
def fitData(stairs,percent):
allIntensities, allResponses = [],[]
for s in stairs.staircases:
allIntensities.append( s.intensities )
allResponses.append( s.data )
for s in stairs.staircases:
print ("Mean for condition"),s.condition['label'],"=",average(s.reversalIntensities),"std=",std(s.reversalIntensities)
#plot each condition
pylab.subplot(221)
#for stairNumber, thisStair in enumerate(allIntensities):
pylab.plot(allIntensities[0], 'o-', label=stairs.staircases[0].condition['label'] )
pylab.xlabel('Trials')
pylab.ylabel('Speed [cm/s]')
pylab.legend()
# Get combined data
combinedInten, combinedResp, combinedN = data.functionFromStaircase(allIntensities, allResponses, 10)
# Fit curve - in this case using a Weibull function
fit = data.FitWeibull('weibullTAFC',combinedInten, combinedResp, guess=None)
#fit = data.FitCumNormal(combinedInten,combinedResp)
intensitiesDomainInterp = pylab.arange(min(allIntensities[0]), max(allIntensities[0]), 0.01)
smoothResponses = fit.eval(intensitiesDomainInterp)
thresh = fit.inverse(percent)
#Plot fitted curve
pylab.subplot(222)
pylab.axis(xmin=min(allIntensities[0]),xmax=max(allIntensities[0]))
pylab.xlabel('Speed [cm/s]')
pylab.ylabel('Probability')
pylab.plot(intensitiesDomainInterp, smoothResponses, '-')
pylab.plot([thresh, thresh],[0,percent],'--')
pylab.plot([0, thresh],[percent,percent],'--')
pylab.title('Threshold at ' + str(percent) + '= %0.3f' % (thresh) )
# Plot points
pylab.plot(combinedInten, combinedResp, 'o')
pylab.ylim([0,1])
# SECOND CONDITION, the plots are in a second row, under
pylab.subplot(223)
#for stairNumber, thisStair in enumerate(allIntensities):
pylab.plot(allIntensities[1], 'o-', label=stairs.staircases[1].condition['label'] )
pylab.xlabel('Trials')
pylab.ylabel('Speed [cm/s]')
pylab.legend()
# Get combined data
combinedInten, combinedResp, combinedN = data.functionFromStaircase(allIntensities[1], allResponses[1], 10)
#fit curve - in this case using a Weibull function
#fit = data.FitFunction('weibullTAFC',combinedInten, combinedResp, guess=None)
fit = data.FitCumNormal(combinedInten,combinedResp)
intensitiesDomainInterp = pylab.arange(min(allIntensities[1]), max(allIntensities[1]), 0.01)
smoothResponses = fit.eval(intensitiesDomainInterp)
thresh = fit.inverse(percent)
#print "Threshold at " + str(percent) +"% with Cumulative Normal= ",thresh
#Plot fitted curve
pylab.subplot(224)
pylab.axis(xmin=min(allIntensities[1]),xmax=max(allIntensities[1]))
pylab.xlabel('Speed [cm/s]')
pylab.ylabel('Probability')
pylab.plot(intensitiesDomainInterp, smoothResponses, '-')
pylab.plot([thresh, thresh],[0,percent],'--')
pylab.plot([0, thresh],[percent,percent],'--')
pylab.title('Threshold at ' + str(percent) + '= %0.3f' % (thresh) )
# Plot points
pylab.plot(combinedInten, combinedResp, 'o')
pylab.ylim([0,1])
pylab.show()
When I call the function fitData on the main code I get this output errore:
Traceback (most recent call last):
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\trackingExperiment2Staircase - py3 - FITDATA.py", line 627, in <module>
startExperiment()
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\trackingExperiment2Staircase - py3 - FITDATA.py", line 621, in startExperiment
fitData(stairs, 75)
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\common\fitData.py", line 39, in fitData
fit = data.FitWeibull('weibullTAFC',combinedInten, combinedResp, guess=None, display=1, expectedMin=0.5, optimize_kws=None)
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\venv\lib\site-packages\psychopy\data\fit.py", line 36, in __init__
self._doFit()
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\venv\lib\site-packages\psychopy\data\fit.py", line 55, in _doFit
self.params, self.covar = optimize.curve_fit(
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\venv\lib\site-packages\scipy\optimize\_minpack_py.py", line 743, in curve_fit
xdata = np.asarray_chkfinite(xdata, float)
File "C:\Users\OneDrive\Desktop\py2convers\psychoflicker-master\src\venv\lib\site-packages\numpy\lib\function_base.py", line 601, in asarray_chkfinite
a = asarray(a, dtype=dtype, order=order)
ValueError: could not convert string to float: 'weibullTAFC'
Could you give me some suggestion on how can I fix this error?
Also I am not sure that the arguments of the function fitData on the main script are correct.
I am trying to show area under a curve using manim
this is my code
from manimlib import *
import numpy as np
class GraphExample(Scene):
def construct(self):
ax = Axes((-3, 10), (-1, 8))
ax.add_coordinate_labels()
curve = ax.get_graph(lambda x: 2 * np.sin(x))
self.add(ax,curve)
area = ax.get_area_under_graph(graph=curve, x_range= (0,2))
self.add(curve, area)
self.wait(1)
this is giving an error message
File "c:\manim-master\manimlib\__main__.py", line 17, in main scene.run()
File "c:\manim-master\manimlib\scene\scene.py", line 75, in run self.construct()
File "test.py", line 21, in construct self.add(area)
File "c:\manim-master\manimlib\scene\scene.py", line 209, in add self.remove(*new_mobjects)
File "c:\manim-master\manimlib\scene\scene.py", line 226, in remove self.mobjects = restructure_list_to_exclude_certain_family_members(
File "c:\manim-master\manimlib\utils\family_ops.py", line 25, in restructure_list_to_exclude_certain_family_members
to_remove = extract_mobject_family_members(to_remove)
File "c:\manim-master\manimlib\utils\family_ops.py", line 5, in extract_mobject_family_members result = list(it.chain(*[
File "c:\manim-master\manimlib\utils\family_ops.py", line 6, in <listcomp>mob.get_family()
AttributeError: 'NoneType' object has no attribute 'get_family'
I don't know what I need to change, someone please help me out here
I changed the code to use Manim's get_area method.
get_area(graph, x_range=None, color=['#58C4DD', '#83C167'], opacity=0.3, bounded_graph=None, **kwargs)
Returns a Polygon representing the area under the graph passed.
from manim import *
import numpy as np
class GraphExample(Scene):
def construct(self):
ax = Axes((-3, 10), (-1, 8))
ax.add_coordinates()
curve = ax.get_graph(lambda x: 2 * np.sin(x))
self.add(ax, curve)
area = ax.get_area(graph=curve, x_range=(0,2))
self.add(area)
self.wait(1)
Output:
I have tried to draw a histogram using matplotlib and the pandas but while drawing the smooth curve it gave me an error I can you please help to resolve this and maybe give me some method to draw the smooth curve on histogram using matplotlib I am trying not to use any another library (seaborn) here is the code
mu,sigma = 100,15
plt.style.use('dark_background')
x = mu + sigma * np.random.randn(10000)
n,bins,patches = plt.hist(x,bins=50,density=1,facecolor='g',alpha = 0.5)
zee=bins[:-1]
plt.plot(np.round(zee),patches,'ro')
plt.xlabel('Smarts')
plt.ylabel('Probablity')
plt.title('Histogram of the Iq')
plt.axis([40,160,0,0.03])
plt.grid(1)
plt.show()
the error shown is
python3 -u "/home/somesh/Downloads/vscode_code/python ml course /firstml.py"
Traceback (most recent call last):
File "/home/somesh/Downloads/vscode_code/python ml course /firstml.py", line 149, in <module>
plt.plot(np.round(zee),patches,'ro')
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2840, in plot
return gca().plot(
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 1745, in plot
self.add_line(line)
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 1964, in add_line
self._update_line_limits(line)
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 1986, in _update_line_limits
path = line.get_path()
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/lines.py", line 1011, in get_path
self.recache()
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/lines.py", line 658, in recache
y = _to_unmasked_float_array(yconv).ravel()
File "/home/somesh/.local/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 1289, in _to_unmasked_float_array
return np.asarray(x, float)
File "/home/somesh/.local/lib/python3.8/site-packages/numpy/core/_asarray.py", line 85, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number, not 'Rectangle'
and is this possible to draw the smooth curve using only the matplotlib library
edit 1: thanks for the answer I was finally able to spot the error
In your code, zee is a matplotlibobject Rectangle object. However, the plot function need a float as input.
Since what you are plotting is a normal distribution. Also, you like the curve to be smooth. So why not generate a normal distribution and plot it into same figure. Here is a modified version of your code.
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
mu,sigma = 100,15
plt.style.use('dark_background')
x = mu + sigma * np.random.randn(10000)
n,bins,patches = plt.hist(x,bins=50,density=1,facecolor='g',alpha = 0.5)
# zee=bins[:-1]
# plt.plot(np.round(zee),patches,'ro')
x_overlay = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x_overlay, stats.norm.pdf(x_overlay, mu, sigma),"ro")
plt.xlabel('Smarts')
plt.ylabel('Probablity')
plt.title('Histogram of the Iq')
plt.axis([40,160,0,0.03])
plt.grid(1)
plt.show()
Output of the plot:
n has the same size with zee, which is length(bins)-1:
mu,sigma = 100,15
plt.style.use('dark_background')
x = mu + sigma * np.random.randn(10000)
n,bins,patches = plt.hist(x,bins=50,density=1,facecolor='g',alpha = 0.5)
zee=bins[:-1]
## this
plt.plot(np.round(zee),n,'ro')
Output:
I am generating some (noisy) data-points (y) with some known parameters (m,c) that represent the equation of a straight line. Using sampling-based Bayesian methods, I now want to know the true values of parameters (m,c) from the data. Therefore, I am using DE Metropolis (PyMC3) to estimate the true parameters.
I am getting theano error theano.gof.fg.MissingInputError: Input 0 of the graph (indices start from 0), used to compute sigmoid(c_interval__), was not provided and not given a value.
Theano version: 1.0.4
PyMC3 version: 3.9.1
import matplotlib.pyplot as plt
import numpy as np
import arviz as az
import pymc3
import theano.tensor as tt
from theano.compile.ops import as_op
plt.style.use("ggplot")
# define a theano Op for our likelihood function
class LogLike(tt.Op):
itypes = [tt.dvector] # expects a vector of parameter values when called
otypes = [tt.dscalar] # outputs a single scalar value (the log likelihood)
def __init__(self, loglike, data, x, sigma):
# add inputs as class attributes
self.likelihood = loglike
self.data = data
self.x = x
self.sigma = sigma
def perform(self, node, inputs, outputs):
# the method that is used when calling the Op
theta, = inputs # this will contain my variables
# call the log-likelihood function
logl = self.likelihood(theta, self.x, self.data, self.sigma)
outputs[0][0] = np.array(logl) # output the log-likelihood
def my_model(theta, x):
y = theta[0]*x + theta[1]
return y
def my_loglike(theta, x, data, sigma):
model = my_model(theta, x)
ll = -(0.5/sigma**2)*np.sum((data - model)**2)
return ll
# set up our data
N = 10 # number of data points
sigma = 1. # standard deviation of noise
x = np.linspace(0., 9., N)
mtrue = 0.4 # true gradient
ctrue = 3. # true y-intercept
truemodel = my_model([mtrue, ctrue], x)
# make data
np.random.seed(716742) # set random seed, so the data is reproducible each time
data = sigma*np.random.randn(N) + truemodel
print(data)
ndraws = 3000 # number of draws from the distribution
# create our Op
logl = LogLike(my_loglike, data, x, sigma)
# use PyMC3 to sampler from log-likelihood
with pymc3.Model():
# uniform priors on m and c
m = pymc3.Uniform('m', lower=-10., upper=10.)
c = pymc3.Uniform('c', lower=-10., upper=10.)
# convert m and c to a tensor vector
theta = tt.as_tensor_variable([m, c])
# use a DensityDist (use a lamdba function to "call" the Op)
pymc3.DensityDist('likelihood', lambda v: logl(v), observed={'v': theta})
step = pymc3.DEMetropolis()
trace = pymc3.sample(ndraws, step)
# plot the traces
axes = az.plot_trace(trace)
fig = axes.ravel()[0].figure
fig.savefig('./trace_plots.png')
Find the full trace here:
Population sampling (4 chains)
DEMetropolis: [c, m]
Attempting to parallelize chains to all cores. You can turn this off with `pm.sample(cores=1)`.
Population parallelization failed. Falling back to sequential stepping of chains.---------------------| 0.00% [0/4 00:00<00:00]
Sampling 4 chains for 0 tune and 4_000 draw iterations (0 + 16_000 draws total) took 5 seconds.███████| 100.00% [4000/4000 00:04<00:00]
Traceback (most recent call last):
File "test.py", line 75, in <module>
trace = pymc3.sample(ndraws, step)
File "/home/csl_user/.local/lib/python3.7/site-packages/pymc3/sampling.py", line 599, in sample
idata = arviz.from_pymc3(trace, **ikwargs)
File "/home/csl_user/.local/lib/python3.7/site-packages/arviz/data/io_pymc3.py", line 531, in from_pymc3
save_warmup=save_warmup,
File "/home/csl_user/.local/lib/python3.7/site-packages/arviz/data/io_pymc3.py", line 159, in __init__
self.observations, self.multi_observations = self.find_observations()
File "/home/csl_user/.local/lib/python3.7/site-packages/arviz/data/io_pymc3.py", line 172, in find_observations
multi_observations[key] = val.eval() if hasattr(val, "eval") else val
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/gof/graph.py", line 522, in eval
self._fn_cache[inputs] = theano.function(inputs, self)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/compile/function.py", line 317, in function
output_keys=output_keys)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/compile/pfunc.py", line 486, in pfunc
output_keys=output_keys)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/compile/function_module.py", line 1839, in orig_function
name=name)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/compile/function_module.py", line 1487, in __init__
accept_inplace)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/compile/function_module.py", line 181, in std_fgraph
update_mapping=update_mapping)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/gof/fg.py", line 175, in __init__
self.__import_r__(output, reason="init")
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/gof/fg.py", line 346, in __import_r__
self.__import__(variable.owner, reason=reason)
File "/home/csl_user/.local/lib/python3.7/site-packages/theano/gof/fg.py", line 391, in __import__
raise MissingInputError(error_msg, variable=r)
theano.gof.fg.MissingInputError: Input 0 of the graph (indices start from 0), used to compute sigmoid(c_interval__), was not provided and not given a value. Use the Theano flag exception_verbosity='high', for more information on this error.
I've run into the same problem when following the example how to sample from a black box likelihood found here:
https://docs.pymc.io/notebooks/blackbox_external_likelihood.html
This seems to be a version problem. I'm on Manjaro Linux and also ran theano 1.0.4 and pymc3 3.9 using python 3.8. I could solve the issue and make the code work by downgrading to python 3.7 and pymc3 3.8. This seems to be in issue with python 3.8, as simply downgrading pymc3 did not solve the issue for me. I am far from an expert in pymc3 so I don't have a solution how to fix this issue using the newest versions, but for now downgrading makes my simulations run.
Hope this helps.
Edit: The devs seem to be aware of this, there is a an open issue on their github page
https://github.com/pymc-devs/pymc3/issues/4002
trying to recreate that by using valuetrackers
Here is my code and the err is also inside that pastebin
Thank you for all the help since I cannot yet create an animation I thought about using this to make by
linking the dots and lines both to some lists of valuetrackers and then finally storing the updation of these value trackers in an animation list and finally playing them was my goal
class Network3(Scene):
def construct(self):
screen_grid = ScreenGrid()
self.add(screen_grid)
#function to just random the x and y coordinates
def randomize_xy():
for i in range(0,no_of_dots):
x_coord[i]=random.randint(-7,+7)
y_coord[i]=random.randint(-4,+4)
print(x_coord)
print(y_coord)
no_of_dots=20
#make some dots
dots=[]
for i in range(0,no_of_dots):
dots.append(Dot())
#make initial list of coordinates
x_coord=[]
y_coord=[]
for i in range(0,no_of_dots):
x_coord.append(random.randint(-7,7))
y_coord.append(random.randint(-4,4))
# #make sure all the lengths are ok
# print(f"length of dots lenght={len(dots)} of x_coord={len(x_coord)}") error of int base 10 is coming from here
print("length of dots=",end="")
print(str(len(dots))) #print(len(dots)) still causes an error !!!
#add all dots at one point
self.add(*dots)
#make anim list to move everything to their position from origin
animlist=[]
for i in range(0,no_of_dots):
animlist.extend([dots[i].move_to,[x_coord[i],y_coord[i],0]])
#play
self.play(*animlist)
#make a list of value trackers
x_trackers=[]
y_trackers=[]
for i in range(0,no_of_dots):
x_tracker=ValueTracker(x_coord[i])
y_tracker=ValueTracker(y_coord[i])
x_trackers.append(x_tracker)
y_trackers.append(y_tracker)
#making lines
lines=[]
for i in range(0,no_of_dots-1):
t1=[x_coord[i],y_coord[i],0]
t2=[x_coord[i+1],y_coord[i+1],0]
line=Line(t1,t2)
lines.append(line)
def update_func1(obj,i):
temp1=np.array([x_trackers[i],y_trackers[i],0])
temp2=np.array([x_trackers[i+1],y_trackers[i+1],0])
line=Line(start=temp1,end=temp2)
obj.become(line)
#making a link between each line and value tracker
for i in range(0,no_of_dots-1):
lines[i].add_updater(lambda m:update_func1(m,i))
#adding again
self.add(*lines)
#making a link between each dot and value tracker
for i in range(0,no_of_dots):
dots[i].add_updater(lambda m:m.move_to([x_trackers[i],y_trackers[i],0]))
#now somehow have to change all the value tracker at once
animlist2=[]
for i in range(0,no_of_dots):
animlist2.extend([x_trackers[i].set_value,random.randint(-7,+7)])
animlist2.extend([y_trackers[i].set_value,random.randint(-4,+4)])
#now play
self.play(*animlist2)
#end
self.wait(3)
Current error I am getting is:
Traceback (most recent call last):
File "C:\manim\manimlib\extract_scene.py", line 155, in main
scene = SceneClass(**scene_kwargs)
File "C:\manim\manimlib\scene\scene.py", line 53, in __init__
self.construct()
File "network_graphic.py", line 584, in construct
lines[i].add_updater(lambda m:update_func1(m,i))
File "C:\manim\manimlib\mobject\mobject.py", line 192, in add_updater
self.update(0)
File "C:\manim\manimlib\mobject\mobject.py", line 159, in update
updater(self)
File "network_graphic.py", line 584, in <lambda>
lines[i].add_updater(lambda m:update_func1(m,i))
File "network_graphic.py", line 578, in update_func1
line=Line(start=temp1,end=temp2)
File "C:\manim\manimlib\mobject\geometry.py", line 431, in __init__
self.set_start_and_end_attrs(start, end)
File "C:\manim\manimlib\mobject\geometry.py", line 471, in set_start_and_end_attrs
vect = normalize(rough_end - rough_start)
TypeError: unsupported operand type(s) for -: 'ValueTracker' and 'ValueTracker'
I think your best option is to use the functions with "dt", then watch my video if you have any doubts. This is a basic example Grant made in one of his very old videos, but I think you can use it for your idea.
class RandomMove(Scene):
CONFIG = {
"amplitude": 0.4,
"jiggles_per_second": 1,
}
def construct(self):
points = VGroup(*[
Dot(radius=0.2) for _ in range(9)
])
points.arrange_in_grid(buff=1)
for submob in points:
submob.jiggling_direction = rotate_vector(
RIGHT, np.random.random() * TAU *1.5,
)
submob.jiggling_phase = np.random.random() * TAU *1.5
def update_mob(mob, dt):
for submob in mob:
submob.jiggling_phase += dt * self.jiggles_per_second * TAU
submob.shift(
self.amplitude *
submob.jiggling_direction *
np.sin(submob.jiggling_phase) * dt
)
points.add_updater(update_mob)
self.add(points)
self.wait(10)
Result here