首页 > 解决方案 > 用于创建故障评估图图表的 Python 代码

问题描述

我想在结构分析中做一个蒙特卡洛概率模型。为此,我需要绘制此模型:

时尚

我制定了以下代码,但仍然需要做很多工作:

import pandas as pd
from matplotlib import pyplot
import numpy as np
from scipy.optimize import curve_fit
from numpy import arange
%matplotlib inline

# define the true objective function
def objective(x, a, b, c, d, e, f):
    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + f

y = np.array([1,0.99,0.97,0.93,0.9,0.81,0.7,0.57,0.5,0.32,0.25])
x = np.array([0,0.2,0.4,0.6,0.67,.8,0.9,1.0,1.05,1.2,1.32])

popt, _ = curve_fit(objective, x, y)
a, b, c, d, e, f = popt
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 0.1)
# calculate the output for the range
y_line = objective(x_line, a, b, c, d, e, f)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')
pyplot.show()

尝试

  1. 你能帮我正确地编写代码来创建curve_fit吗?
  2. 如何确定随机数是否会在曲线内?

标签: pythonmatplotlibscipycurve-fitting

解决方案


  1. 要使曲线附加到左侧的 Y 轴,一种方法是将 X 轴最小值设置为与您拥有的最小 X 轴值相同(在本例中为零)。 matplotlib.pyplot.xlim

    要关闭绘图的右侧,您可以根据数据集的最小值/最大值绘制一条垂直线。 matplotlib.pyplot.vlines

  2. 虽然对您的问题的看法可能过于简单,但一种方法是简单地将有问题的值与数据集的范围进行比较。 min(y) <= a[1] <= max(y)

下面的代码显示了每个示例,但没有花时间使其尽可能像 Pythonic 一样(字面意思是为了说明而写的)。

代码:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pandas as pd
from matplotlib import pyplot
import numpy as np
from scipy.optimize import curve_fit
from numpy import arange
# %matplotlib inline

# define the true objective function
def objective(x, a, b, c, d, e, f):
    return (a * x) + (b * x**2) + (c * x**3) + (d * x**4) + (e * x**5) + f

y = np.array([1,0.99,0.97,0.93,0.9,0.81,0.7,0.57,0.5,0.32,0.25])
x = np.array([0,0.2,0.4,0.6,0.67,.8,0.9,1.0,1.05,1.2,1.32])

popt, _ = curve_fit(objective, x, y)
a, b, c, d, e, f = popt
pyplot.scatter(x, y)
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x), max(x), 0.1)
# calculate the output for the range
y_line = objective(x_line, a, b, c, d, e, f)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, '--', color='red')


# Set X axis limits 
pyplot.xlim(min(x),)

# Set Y axis limits 
pyplot.ylim(0,)

# Close the curve on the right
pyplot.vlines(max(x), min(y), 0, linestyles='--', color='red')

# Value within range?
a = (0.15, 0.63)

a1 = min(x) <= a[0] <= max(x)
a2 = min(y) <= a[1] <= max(y)
if a1 and a2:
    print('True')

# Plot test point
pyplot.plot(a[0], a[1], marker='o', markersize=5, color="blue")

pyplot.show()

输出:
示例 FAD 输出

外壳输出: True


推荐阅读