2016-01-01 3 views
0
class beam(object): 
    '''This class is models the deflection of a simply supported beam under 
    multiple point loads, following Euler-Bernoulli theory and the principle  
    of superposition 
    ''' 

Так что я пытаюсь построить график 3 моих функций для пучка на одном графике с помощью модуля Matplotlib и я получаю ошибки значение при попытке сделать это , Основная часть кода:Python: ошибка Значение при попытке построить график с помощью Matplotlib

def __init__(self, E, I, L): 
    '''The class costructor 
    ''' 
    self.E = E # Young's modulus of the beam in N/m^2 
    self.I = I # Second moment of area of the beam in m^4 
    self.L = L # Length of the beam in m 
    self.Loads = [(0.0, 0.0)] # the list of loads applied to the beam 

def setLoads(self, Loads): 
    '''This function allows multiple point loads to be applied to the beam 
    using a list of tuples of the form (load, position) 
    ''' 
    self.Loads = Loads 

def beamDeflection(self, Load, x): 
    """Calculate the deflection at point x due to application of single 
    load 
    """ 
    Force, distanceA = Load #P1 = Force , a = distanceA 
    E = self.E 
    I = self.I 
    L = self.L 
    distanceB = L - distanceA 
    i = (Force*distanceB)/(6*L*E*I) 
    j = ((L/distanceB)*(x-distanceA)**3 - x**3 + (L**2 - distanceB**2)*x) 
    k = (Force*distanceB*x)/(6*L*E*I)   
    l = (L**2 - x**2 - distanceB**2) 
    if x > distanceA: 
     return i*j 
    else: 
     return k*l 


def getTotalDeflection(self, x): 
    """Calculate total deflection of beam due to multiple loads 
    """ 
    #return sum(self.beamDeflection(loadall, x) for loadall in self.Loads) 
    return sum(self.beamDeflection(load, x) for load in self.Loads) 


def getSlope(self, x): 
    """Calculate gradient at a point x on beam due to deflection 
    """ 
    V = lambda x: self.getTotalDeflection(x) 
    return scipy.misc.derivative(V, x, dx = 10**-6) 


def getMoment(self, x): 
    """Calculate bending moment at a point x on beam 
    """ 
    E = self.E 
    I = self.I 
    W1 = lambda x: self.getSlope(x) 
    W2 = scipy.misc.derivative(W1, x, dx = 10**-6) 
    return (-1*E*I)*W2 

Это часть кода я получаю сообщение об ошибке для:

def plotBeamData(self, xs): 
    """Plot deflection, slope and bending moment against position x for a 
    list of floats or numpy.array xs describing positions along beam 
    """ 
    deflection = self.getTotalDeflection 
    slope = self.getSlope 
    moment = self.getMoment  
    matplotlib.pyplot.plot(xs, deflection, 'b', label = "deflection (mm)") 
    matplotlib.pyplot.plot(xs, slope, 'g', label = "slope (mm/m)") 
    matplotlib.pyplot.plot(xs, moment, 'r', label = "moment (kNm)") 
    matplotlib.pyplot.xlabel("Distance along beam (m)") 
    matplotlib.pyplot.ylabel("Value in units") 
    matplotlib.pyplot.show() 

Пример ввода будет:

>>> b = beam(8.0E9, 1.333E-4, 5.0) 
>>> b.setLoads([(900, 3.1), (700, 3.8), (1000, 4.2)]) 
>>> xs = numpy.linspace(0,5,500) 
>>> b.plotBeamData(xs) 

я ошибка я получаю:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:/Users/Dag/Downloads/beamModel.py", line 97, in plotBeamData 
matplotlib.pyplot.plot(xs, deflection, 'b', label = "deflection (mm)") 
    File "C:\Users\Dag\Anaconda2\lib\site-packages\matplotlib\pyplot.py", line 3099, in plot 
ret = ax.plot(*args, **kwargs) 
    File "C:\Users\Dag\Anaconda2\lib\site-packages\matplotlib\axes\_axes.py", line 1373, in plot 
for line in self._get_lines(*args, **kwargs): 
    File "C:\Users\Dag\Anaconda2\lib\site-packages\matplotlib\axes\_base.py", line 304, in _grab_next_args 
for seg in self._plot_args(remaining, kwargs): 
    File "C:\Users\Dag\Anaconda2\lib\site-packages\matplotlib\axes\_base.py", line 282, in _plot_args 
    x, y = self._xy_from_xy(x, y) 
    File "C:\Users\Dag\Anaconda2\lib\site-packages\matplotlib\axes\_base.py", line 223, in _xy_from_xy 
raise ValueError("x and y must have same first dimension") 
ValueError: x and y must have same first dimension 

Благодарен за любые помогите, действительно застрял. Благодарю.

ответ

1

Вы забыли на самом деле назвать свои методы для расчета результатов. Ниже приведена модифицированная версия функции построения графика:

def plotBeamData(self, xs): 
    """Plot deflection, slope and bending moment against position x for a 
    list of floats or numpy.array xs describing positions along beam 
    """ 
    deflection = self.getTotalDeflection(xs) 
    slope = self.getSlope(xs) 
    moment = self.getMoment(xs) 
    matplotlib.pyplot.plot(xs, deflection, 'b', label = "deflection (mm)") 
    matplotlib.pyplot.plot(xs, slope, 'g', label = "slope (mm/m)") 
    matplotlib.pyplot.plot(xs, moment, 'r', label = "moment (kNm)") 
    matplotlib.pyplot.xlabel("Distance along beam (m)") 
    matplotlib.pyplot.ylabel("Value in units") 
    matplotlib.pyplot.show() 
+0

Благодарим за быстрый ответ. Однако, это дает мне следующую ошибку. 'if x> distanceA: ValueError: Значение истинности массива с более чем одним элементом неоднозначно. Используйте a.any() или a.all() ' – Student1001

+0

Возможно, это проблема, которая должна быть решена в отдельном вопросе @ Student1001. – Gabriel

+0

BTW, посмотрите здесь: http://stackoverflow.com/q/10062954/1391441 – Gabriel

Смежные вопросы