Как я могу отрезать кусок от сюжета и установить нулевую точку? - PullRequest
1 голос
/ 09 июля 2020

В своей работе у меня есть задача прочитать файл CSV и провести с ним вычисления. Файл CSV состоит из 9 различных столбцов и около 150 строк с разными значениями, полученными с датчиков. Сначала было определено горизонтальное ускорение, из которого расстояние было получено путем двойного интегрирования. Это нижний график двух графиков на картинке. Верхний график представляет так называемые силовые данные. Оранжевый график показывает график для 9-го столбца CSV-файла, а синий график показывает график для 7-го столбца CSV-файла.

Plots

As you can see I have drawn two vertical lines in the lower plot in the picture. These lines represent the x-value, which in the upper plot is the global minimum of the orange function and the intersection with the blue function. Now I want to do the following, but I need some help: While I want the intersection point between the first vertical line and the graph to be (0,0), i.e. the function has to be moved down. How do I achieve this? Furthermore, the piece of the function before this first intersection point (shown in purple) should be omitted, so that the function really only starts at this point. How can I do this? In the following picture I try to demonstrate how I would like to do that: введите описание изображения здесь

Если вам нужен мой код, вы можете увидеть его здесь:

import numpy as np
import matplotlib.pyplot as plt
import math as m
import loaddataa as ld
import scipy.integrate as inte
from scipy.signal import find_peaks
import pandas as pd
import os

# Loading of the values

print(os.path.realpath(__file__))
a,b = os.path.split(os.path.realpath(__file__))

print(os.chdir(a))
print(os.chdir('..'))
print(os.chdir('..'))
path=os.getcwd()
path=path+"\\Data\\1 Fabienne\\Test1\\left foot\\50cm"
print(path)
dataListStride = ld.loadData(path)
indexStrideData = 0 
strideData = dataListStride[indexStrideData]

#%%Calculation of the horizontal acceleration

def horizontal(yAngle, yAcceleration, xAcceleration):
     a = ((m.cos(m.radians(yAngle)))*yAcceleration)-((m.sin(m.radians(yAngle)))*xAcceleration)
     return a
 
resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))

resultsHorizontal.insert(0, 0)

#plt.plot(x_values, resultsHorizontal)

#%%
#x-axis "convert" into time: 100 Hertz makes 0.01 seconds
scale_factor = 0.01 
x_values = np.arange(len(resultsHorizontal)) * scale_factor

#Calculation of the global high and low points
heel_one=pd.Series(strideData.iloc[:,7])
plt.scatter(heel_one.idxmax()*scale_factor,heel_one.max(), color='red')
plt.scatter(heel_one.idxmin()*scale_factor,heel_one.min(), color='blue')

heel_two=pd.Series(strideData.iloc[:,9])
plt.scatter(heel_two.idxmax()*scale_factor,heel_two.max(), color='orange')
plt.scatter(heel_two.idxmin()*scale_factor,heel_two.min(), color='green')#!

#Plot of force data
plt.plot(x_values[:-1],strideData.iloc[:,7]) #force heel 
plt.plot(x_values[:-1],strideData.iloc[:,9]) #force toe

# while - loop to calculate the point of intersection with the blue function 
i = heel_one.idxmax()
while strideData.iloc[i,7] > strideData.iloc[i,9]:
    i = i-1

# Length calculation between global minimum orange function and intersection with blue function
laenge=(i-heel_two.idxmin())*scale_factor
print(laenge)

#%% Integration of horizontal acceleration
velocity = inte.cumtrapz(resultsHorizontal,x_values)
plt.plot(x_values[:-1], velocity)

#%% Integration of the velocity
s = inte.cumtrapz(velocity, x_values[:-1])
plt.plot(x_values[:-2],s)

Надеюсь, понятно, что я хочу делать. Спасибо, что помогли мне!

1 Ответ

1 голос
/ 09 июля 2020

Я не копался полностью в вашем коде, но следующие приемы могут быть полезны.

Допустим, у вас есть значения x и y:

x = np.linspace(0,3,100)
y = x**2

Теперь вам нужны только значения, соответствующие, скажем, .5 < x < 1.5. Сначала создайте логическую маску для массивов следующим образом:

mask = np.logical_and(.5 < x, x < 1.5)

(если это кажется волшебным, запустите x < 1.5 в вашем интерпретаторе и посмотрите на результаты). Затем используйте эту маску, чтобы выбрать желаемые значения x и y:

x_masked = x[mask]
y_masked = y[mask]

Затем вы можете преобразовать все эти значения так, чтобы первая пара x,y находилась в начале координат:

x_translated = x_masked - x_masked[0]
y_translated = y_masked - y_masked[0]

Это то, что вы искали?

...