Visual Python Pendulum: Solving the Forces

In summary, the user is trying to use a GUI program to collect data from a set of buttons. The buttons do not show up on the GUI.
  • #1
Kaimyn
44
1
Hello and thanks in advance for your help.

For about a week now, I've been trying to write what should be a simple python program. The idea is first to write a program for a simple harmonic pendulum, then adapt it to a spring pendulum. However, in order to do this, I have to write the simple harmonic pendulum so that it is moved by forces in certain directions.

I have all (or most?) of the mathematics and physics behind it sorted, but I have no idea how to program it in a way that would include the forces acting upon the pendulum to make it work.

The forces (simple harmonic pendulum):

Gravity: g
Perpendicular: -mgsin(theta)
Bottom of the weight: mgcos(theta)
Total (directionless) speed of weight: [tex]v=\sqrt{2gr(cos(\theta_{1})-cos(\theta_{0}))[/tex] (Theta1 is the current angle the object is making, Theta0 is the starting angle)
And a few others

Would it require a rule that doesn't allow it to go more than the length of the string away from the origin, or is it possible to model it with forces too? (It doesn't really matter though, as the spring pendulum doesn't have this restriction)

With the pendulum as a spring, the only thing I can think of to add would be Hooke's law.

Thanks again, and any help would be appreciated.
 
Technology news on Phys.org
  • #2
Hello, I need to write a program that will plot any set of .nc data with dimensions stored in t-z-y-x order but I'm having some problems that's driving me crazy.

first problem: how do I find the names of the variables for each dimension for example how would I find the name 'lat' for the latitude (I know in the .nc file but I'm not allowed to hard code it)

second problem: The graphs that I plot have white bits on the outside because the x and y-axis are bigger than the data set, is there a way to eliminate this part?

my program is below notice that I have to hardcode the words 'lon' and 'lat when I need to get them from the file instead somehow!)


# Assignment2 module1
# FILENAME: A2P1

def plotMap(locStr, varStr, tI, zI):
'''reads a file location (string), variable (string), a time index and then a z index'''
print "importing..."
import numpy as np
import matplotlib
import netCDF4
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
import string

print "reading data..."
nc = Dataset(locStr)
var = nc.variables[varStr]

print "Converting the coordinates..."
lonvar = nc.variables['lon']
lonvals = lonvar[:]
latvar = nc.variables['lat']
latvals = latvar[:]

print "Creating plot attributes..."
data=var[zI]
pc=plt.pcolor(lonvals, latvals, data)
plt.colorbar(pc, orientation='horizontal')
plt.xlabel('longitude (' + lonvar.units +')')
plt.ylabel('latitude (' + latvar.units + ')')
plt.title('plot of ' + varStr + ' at level z=' + str(zI) + ' (' + var.units + ')')
ax=plt.gca()
ax.set_xlim(0,360)
ax.set_ylim(-90,90)

print "Plotting graph..."
plt.show()
plt.savefig(varStr + '.png')
return

import A2P1
A2P1.plotMap('/home/edev/classes/class7/FOAM_20110209.0.nc', 'TMP', 1, 12)
#A2P1.plotMap('/home/edev/classes/class6/GlobModel_temp.nc', 'Pressure', 1, 1)


here are links to two .nc file this program should work for but doesn't quite yet

http://ubuntuone.com/7lLwrQfbicWiOk613f3gkE
http://ubuntuone.com/5LcyOXP7YutIcc3UE6sD2X

I have used a lot of time looking for the command that will fix everything, your help will be very appretiated. If can't help and have a good idea of where to look that would be usedful too,

thank you

Jason
 
  • #3
Why is my code not working? It uses Python 3's tkinter module.
There are no exception errors, it's just that the buttons don't show up on the GUI. It showed up when I created the Frame without using classes.

from tkinter import*;

root = Tk();
root.title("Lazy Buttons");
root.geometry("200x85");

class Application(Frame):
def __init__(self,master):
Frame.__init__(self,master);
self.grid;
self.bttn_clicks = 0;
self.create_widget();
def create_widget(self):
self.bttn = Button(self);
self.bttn["text"] = "Total Clicks: 0";
self.bttn["command"] = self.update_count;
self.bttn.grid();
def update_count(self):
self.bttn_clicks += 1;
self.bttn["text"] = "Total clicks: " + str(self.bttn_clicks);


app = Application(root);
root.mainloop();
 
  • #4
Hello, I am writing my first software program (language:python) with the goal of conducting an interesting exercise related to matrices. I've ran into a slightly complex problem. First let me define something that will make my problem easier to communicate. Let an "H group" be a group of cells in matrix A. The group has an order to it, may start anywhere in matrix A and each cell is connected to an adjacent unused cell. No cell can be used twice and call the number of cells in any given H group its length, L. Example:

Matrix A: 2x2:

[1][2][3]
[4][5][6]
[7][8][9]

An H group that starts at cell [1], has length 4 and goes clockwise along the perimeter would be : [1], [2], [3], [6]. This H group has 1 turn. Other examples of H groups: [2],[5],[9],[6],[8] and [7],[8],[9],[6],[5],[4],[1],[2],[3] and [3],[5],[6],[2] and [1],[2],[6],[8] but NOT [1],[2],[8].

My goal is to find and equation to represent the number of H groups with length L>=3 in a pxq matrix. These H groups may have turns (unlike the two equations below)

Now, I've obtained an equation to find the number of H groups that are directed only Up, Down, Left and Right. Keep in mid this means these H groups have no "turns" in their pattern and the pattern connecting the cells is either purely up, down, left or right. This equation is: sum of up + down + left + right = 2p(q-L+1)+2q(p-L+1). Note, this form of the equation does not hold for H groups with L = 1. Please disregard this.

I've also obtained a similar equation for the diagonal sum of H groups. Again, no turns allowed. The sum of unidirectional diagonal H groups in any direction (upright, upleft, downright or downleft) is =(p-L+1)*(q-L+1). The sum of all 4 directions is 4*(p-L+1)*(q-L+1). Again ignore the case of L = 1.

Now I obtained these two equations by picking small pxq matrices, counting the unidirectional H groups and finding a pattern that lead me to the equation. However, the complexity is greatly increased when turns are involved. I could try a brute force approach and start with a 2x2 matrix and find all the H groups by hand. This has so far proven unhelpful...

The following part may or may not be useful depending on how clearly you interrupt me. I encourage you to ignore it if you do not fully understand...Though I was able to fairly easily predict H groups of length L=4 in a 2x3 matrix by looking at the H groups of length L=3, I have found no reasonable pattern. The approach I've been taking involves looking at unique patterns (aka basic shapes) and rotating these basic shapes.

For your resource:

basic shapes of L = 3 in 2x2: 3*4rotations
basic shapes of L = 4 in 2x2: 3*4rotations
basic shapes of L = 3 in 2x3: 4*2rotations
basic shapes of L = 4 in 2x2: 16*2rotations

**I know I've been unclear, but I encourage you to try this problem yourself and post any questions or solutions you may have. Feel free to email me at <<Deleted by Moderator>> Sorry for being so long winded. Like I said, this is an exercise for fun so the reasoning is more important than the solution.
 
Last edited by a moderator:
  • #5
Hey all.

twice now I've coded sift from scratch, but mine never gives as good results, and the one part i used a library for (convolution for DoG) didn't give same results given same params as example image tests online.

I need this one small part for a much, much, larger project, and I want a neasy fix for this. What libraries don't use openCV but can also perform feauture point detection and matching. Any help appreciated. I am new to python, so I would prefer not to mess with compiling the libraries with cmake or any other 3rd party software.
I use notepad ++ and the default interpreter for python 3.6 on windows 10.

Any help appreciated, i have spent days googling, and even tried many diffrent languages. I'm not asking for lack of effort, every google suggestion seems to have a "gotcha" that requires backdated versions of libs or compiling binaries or only works on linux.
 
  • #6
In the following example, there are three time series and I want to predict another time series y which is a function of the three. How can I use four inputs to predict the time series where the fourth input is the output at previous time step?
Python:
    import tensorflow as tf
    import numpy as np
    import pandas as pd
   
    #clean computation graph
    tf.reset_default_graph()
   
    tf.set_random_seed(777)  # reproducibility
    np.random.seed(0)
   
    import matplotlib.pyplot as plt
   
   
   
   
    def MinMaxScaler(data):
   
        numerator = data - np.min(data, 0)
        denominator = np.max(data, 0) - np.min(data, 0)
        # noise term prevents the zero division
        return numerator / (denominator + 1e-7)
   
   
   
    class generate_data(object):
       
        def __init__(self, data_len,  in_series, y_pred, seq_lengths, method='sum' ):
            self.data_len = data_len
            self.data = None
            self.in_series = in_series #number of input series
            self.y_pred = y_pred  #number of final outputs from model
            self.seq_lengths = seq_lengths
            self.method = method
           
        def _f(self, x):
            y = 0
            result = []
            for _ in x:
                result.append(y)
                y += np.random.normal(scale=1)
            return np.array(result)
   
        def _runningMean(self, x, N):
            return np.convolve(x, np.ones((N,))/N)[(N-1):]
   
       
        def sine(self):
            DATA = np.zeros((self.data_len, self.in_series))
            xx = [None]
            data_0 = np.sin(np.arange(self.data_len*self.in_series))
            xx = data_0.reshape(self.data_len, self.in_series)
            DATA[:,0: self.in_series] = xx           
            y = self._get_y(DATA)
            return xx,y, DATA
           
       
        def _get_y(self, xx):
            if self.method=='sum':
                yy = np.array([np.sum(xx[i,:]) for i in range(np.shape(xx)[0])])
            elif self.method == 'mean':
                  yy = np.array([np.mean(xx[i,:]) for i in range(np.shape(xx)[0])])
           
            elif self.method == 'self_mul':
                yy = np.array([np.prod(xx[i,:]) for i in range(np.shape(xx)[0])])
            elif self.method == 'mean_mirror':
                yy = np.array([np.mean(xx[i,:]) for i in range(np.shape(xx)[0])])
            return yy
       
       
        def normalize(self, xx1,yy1):
            
            yy = [None]*len(yy1)
            YMinMax = {}
           
            xx = MinMaxScaler(xx1)
            for i in range(self.y_pred):
                YMinMax['ymin_' + str(i)] = np.min(yy1[0])
                YMinMax['ymax_' + str(i)] = np.max(yy1[0])
                yy[i] = MinMaxScaler(yy1[0])
            setattr(self, 'YMinMax', YMinMax)
            return xx,yy
       
       
        def create_dataset(self, xx, yy):
            '''creates a dataset consisting of windows for x and y data'''
            dataX = self._build_input_windows(xx, self.seq_lengths)
           
            if self.y_pred > 1:
                pass
            elif self.y_pred > 1 and self.seq_lengths != any(self.seq_lengths):
                pass
            else:
                dataY = self._build_y_windows(yy[0] , self.seq_lengths)       
            return dataX, dataY
       
       
        def _build_input_windows(self, time_series, seq_length):
            dataX = []
            for i in range(0, len(time_series) - seq_length):
                _x = time_series[i:i + seq_length, :]
                dataX.append(_x)
            return np.array(dataX)  
   
   
        def _build_y_windows(self, iny, seq_length):       
            dataY = []
            for i in range(0, len(iny) - seq_length):
                _y = iny[i + seq_length, ]  # Next close price          
                dataY.append(_y)
            return  np.array(dataY)
       
       
        def TrainTestSplit(self, dataX, dataY, train_frac):
           
            train_size = int(len(dataY) * train_frac)           
            trainX, testX = np.array(dataX[0:train_size]), np.array(dataX[train_size:len(dataX)])
           
            trainY, testY = np.array(dataY[0:train_size]), np.array(dataY[train_size:len(dataY)])
            trainY = trainY.reshape(len(trainY), 1)
            testY = testY.reshape(len(testY), 1) 
            return trainX, trainY, testX, testY, train_size
           
   
    #training/hyper parameters
    tot_epochs = 500
    batch_size = 32
    learning_rate = 0.01
    seq_lengths = 5  #sequence lengths/window size for  RNN
    rnn_inputs = 3 # no of inputs for  RNN
    y_pred = 1
    data_length = 105  #this can be overwritten or useless
    gen_data = generate_data(data_length,  rnn_inputs, y_pred, seq_lengths, 'sum')
    xx,yy,data_1 = gen_data.sine()
   
    train_frac = 0.8
    xx1,yy1 = gen_data.normalize(xx,[yy])
    dataX, dataY = gen_data.create_dataset(xx1,yy1)
    trainX, trainY, testX, testY, train_size = gen_data.TrainTestSplit( dataX, dataY, train_frac)
   
    keep_prob = tf.placeholder(tf.float32)
    x_placeholders = tf.placeholder(tf.float32, [None, 5, 3])
    Y =  tf.placeholder(tf.float32, [None, 1])
   
    with tf.variable_scope('scope0'):  #defining  RNN
        cell = tf.contrib.rnn.BasicLSTMCell(num_units= 7, state_is_tuple=True, activation=tf.tanh)
        outputs1, _states = tf.nn.dynamic_rnn(cell, x_placeholders, dtype=tf.float32)
        Y_pred1 = tf.contrib.layers.fully_connected(outputs1[:, -1], 1, activation_fn=None)
    Y_pred = Y_pred1
   
    ## cost/loss
    loss = tf.reduce_sum(tf.square(Y_pred - Y))  # sum of the squares
    ## optimizer
    optimizer = tf.train.AdamOptimizer(learning_rate)
    train = optimizer.minimize(loss)
    #
    ## RMSE
    targets = tf.placeholder(tf.float32, [None, 1])
    predictions = tf.placeholder(tf.float32, [None, 1])
    rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))
   
   
    with tf.Session() as sess:
        saver = tf.train.Saver(max_to_keep=41)
        writer = tf.summary.FileWriter('./laos_2out/cnntest', sess.graph)
       
        init = tf.global_variables_initializer()
        sess.run(init)
   
        # Training step
        for epoch in range(tot_epochs):
           
          total_batches = int(train_size / batch_size)  ##total batches/ no. of steps in an epoch
            
          #for batch in range(total_batches):
          _, step_loss = sess.run([train, loss], feed_dict= {x_placeholders:trainX, Y:trainY, keep_prob:0.5} )
   
    #    # evaluating on test data
        test_predict = sess.run(Y_pred, feed_dict= {x_placeholders:testX, Y:trainY, keep_prob:0.5} )
   
        #evaluating on training data
        train_predict = sess.run(Y_pred, feed_dict={x_placeholders:trainX, Y:trainY, keep_prob:0.5})
       
        rmse_val = sess.run(rmse, feed_dict={targets: testY, predictions: test_predict})
        print("RMSE: {}".format(rmse_val))
       
        # Plot predictions
        fig, (ax1,ax2) = plt.subplots(1,2, sharey=True)
        fig.set_figwidth(14)
        fig.set_figheight(5)
        ax2.plot(testY, 'b', label='observed')
        ax2.plot(test_predict, 'k', label='predicted')
        ax2.legend(loc="best")
        ax2.set_xlabel("Time Period")
        ax2.set_title('Testing')
        ax1.plot(trainY, 'b', label='observed')
        ax1.plot(train_predict, 'k',label= 'predicted')
        ax1.legend(loc="best")
        ax1.set_xlabel("Time Period")
        ax1.set_ylabel("discharge (cms)")
        ax1.set_title('Training')
        plt.show()

I have googled other similar answers which make use of tf.nn.raw_rnn but in those cases only the predicted output at previous time steps is used but I want the predicted output at previous timesteps plus other three inputs to be used for prediction.
 
  • #7
Summary: I'm starting a project in my lab where I need to make a program using the Lennard-Jones potential equation in Python. There also needs to be an output graph with the program showing the function. I'm having problems finding workable codes (I keep running into errors) that I could use for reference/analysis. I use jupyter Notebook running Python. Does anyone know a good site or have any advice on starting? (i'm fairly new to Python and somewhat new to programming in general)

1571466720638.png


As of now I've been trying to figure out how much the following link (a Jupyter Notebook I came across) can help me...

https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/lennard_jones_potential.ipynb
Please include as much detail and support material as possible.
 
  • #8
Hello! My question is actually mostly python related, but I guess it applies to fitting in general. To be specific, here I am talking about the lmfit or scipy fitting packages. When I do a fit and I pass the errors on y to the fitting function, I am getting a value for the parameters of the fit. Yet if I scale the error say, err = 10 * err, I am getting the same errors on the parameters, even if by the propagation of error the errors should be bigger, too. I have noticed that there is a parameter called scale_covar which is by default True. However if I set it to False, and try the error increase that I mentioned above, I do indeed get the expected effect i.e. the errors on parameters increase, too. Can someone explain to me what does this scale of the covariance mean? What errors should I quote (in a publication for example)? When should I set that parameter to False and when should I let it to True? Thank you!
 

FAQ: Visual Python Pendulum: Solving the Forces

1. What is Visual Python Pendulum and how does it work?

Visual Python Pendulum is a simulation program that uses the physics principles of forces and motion to model the behavior of a pendulum. It creates a virtual pendulum in a 3D space and calculates the forces acting on it to predict its motion.

2. What are the forces involved in a pendulum and how do they affect its motion?

The two main forces acting on a pendulum are gravity and tension. Gravity pulls the pendulum towards the center of the Earth while tension pulls it back towards its resting position. These forces work together to create the swinging motion of the pendulum.

3. How does Visual Python Pendulum solve for the forces in a pendulum?

Visual Python Pendulum uses the equations of motion and the principles of conservation of energy and momentum to calculate the forces acting on the pendulum. It takes into account the mass, length, and angle of the pendulum to accurately predict its motion.

4. Can Visual Python Pendulum be used to study the behavior of real-life pendulums?

Yes, Visual Python Pendulum can be used as a tool to study the behavior of real-life pendulums. By adjusting the parameters and initial conditions, the simulation can mimic the behavior of various types of pendulums, allowing for a better understanding of their motion.

5. Are there any limitations to the accuracy of Visual Python Pendulum?

While Visual Python Pendulum provides a good approximation of the behavior of a pendulum, there may be some limitations to its accuracy. Factors such as air resistance and friction are not taken into account in the simulation, which may affect the motion of a physical pendulum. Additionally, the accuracy of the simulation may also depend on the computer's processing power and the precision of the input values.

Similar threads

Back
Top