0

I am brand new to coding, please be gentle! I have a main script that runs a simulation of particles colliding with each other and walls in micro-gravity conditions. This part of the script outputs individual data files containing: timestep, vtotal. There are 15 particles so I get out 15 txt files.

N_max = sim.getNumTimeSteps()
particleData = [ [] for x in range(len(sim.getParticleList()))]
for n in range (N_max):
    sim.runTimeStep()
    if (n%1000==0):
        particles = sim.getParticleList()
        for i in range(len(sim.getParticleList())):
            print i
            x, y, z = particles[i].getVelocity()
            particleData[i].append( (n, x, y, z ))
print len(sim.getParticleList())
            
for i in range(len(sim.getParticleList())):
    with open("{0:d}.dat".format(i), "w") as f:
        for j in particleData[i]:
            f.write("%f,%f \n" % (j[0], (math.sqrt(float(j[1])**2+float(j[2])**2+float(j[3])**2)) ))
sim.exit()

The end result I need to work toward is a graph of the mean of those 15 particles over time. For example, in this simulation it was running for 22000 timesteps, at increments of 1000. Correct me if I am wrong, but the mean should be (vtotal1+vtotal2+vtotal3+...vtotal15)/per increment. When that is plotted over time, a single line represents the mean velocity of the 15 particles from the simulation? Here is a version of what I was doing that was adapted from another averaging attempt.

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import csv
import math
import numpy as np

x = []
y = []
y_mean = np.array([1 for _ in range(22000/1000)])
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 7))
for i in range(15):
    x = []
    y = []
    with open("{}.dat".format(i),'r') as csvfile:
        plots = csv.reader(csvfile, delimiter=',')
        for row in plots:
            x.append(float(row[0]))
            y.append(float(row[1]))
            y_mean[int(float(row[0]) / 1000)] += y[-1]
        axes.plot(x,y, color='skyblue', label="Total v {}".format(i+1))
        axes.plot(x,y_mean, color='olive', label="Average v {}".format(i+1))
        plt.title('Particles Over Time')
        plt.xlabel('Timestep Number')
        plt.grid(alpha=.5,linestyle='--')
        plt.ylabel('Velocity')
        plt.xlim(0, 2000)
        plt.show()
        plt.autoscale(enable=True, axis=y, tight=True)
plt.legend()
plt.savefig("round2avgs.png")
y_mean = np.asarray(y) / 15

I just don't know what's going wrong. Any assistance is appreciated.

2
  • 1
    Can you include your expected/actual output? Commented Jun 25, 2020 at 1:33
  • Here is what the plot looks like: (i.imgur.com/VknfAyu.png) Here is what the velocity one had looked like before: (i.imgur.com/4AZetMc.png) And what an attempt at averaging looked like before: (i.imgur.com/Ap4cqIq.png) Commented Jun 25, 2020 at 5:14

1 Answer 1

1

Normally, you should split your data processing and visualization into two different steps.

Say you have a 5 CSVs, all having the same data:

0,1
1000,2
2000,3
3000,4
4000,5

Let's name this 1.dat, 2.dat ... 3.dat.

  1. Import the libraries and load the data
import csv

import matplotlib.pyplot as plt
import numpy as np

x = []
ys = []
for i in range(5):
    with open(f'{i+1}.dat') as data_file:
        data = csv.reader(data_file, delimiter=',')
        y = []
        for row in data:
            if i == 0:
                x.append(float(row[0]))
            y.append(float(row[1]))
        ys.append(y)
  1. Calculate the means per timestep using numpy
means_per_timestep = np.array(ys).mean(axis=0)
  1. Plot it
plt.plot(x, means_per_timestep)

Is this what you were expecting?

Plot

Sign up to request clarification or add additional context in comments.

2 Comments

Yes! That looks more like it. Thank you!
I'd appreciate if you hit the green tick next to my answer if you found it helpful :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.