Python在工業中的應用

Python語言作為一種高級編程語言,常常被用在各種科學計算和數據分析的領域中。其獨特的特性、易讀性、可擴展性以及開源性為Python在工業中的應用提供了極大的可能性。本篇文章將從Python語言在自動化控制、機械人、物聯網、圖像識別、大數據分析五個方面進行探討。

一、自動化控制

自動化控制作為一個龐大的業界,在各個行業中都扮演着重要的角色。Python語言自身的優秀特性和充足的庫支持為自動化控制提供了有力的技術支撐。Python語言擁有了自己的控制系統庫,比如:PyControl庫。下面我們用PyControl庫來完成一個簡單的例子,使用Python實現二級負反饋調節器:


from pycontrol import *
import numpy as np

def cascade_pid_demo():

    #===================================
    # Physical System Description
    #===================================
    Kq = 0.33
    Ks = 19.8
    Ke = 0.8
    Jl = 0.0001
    Bl = 0.0001
    Jr = 0.0116
    Br = 0.0120
    Bm = 0.0127
    Kb = 0.567
    Kt = 0.042
    Rm = 2.92
    Lm = 0.00294

    Tau_s = 0.001
    Tau_m = 0.03
    
    #===================================
    # Controller Description
    #===================================
    Kp_c = 1
    Ki_c = 1
    Kd_c = 1
    gamma_c = 1
    
    Kp_sat = 1000
    Ki_sat = 1000
    Kd_sat = 1000
    
    #===================================
    # Synthetic System Description
    #===================================
    Ap = np.array([[0, 1], [-Ks/Jl, -Bl/Jl]])
    Cp = np.array([[0, 1]])
    Bp = np.array([[0], [1/Jl]])
    Dp = np.array([[0]])
    sys_P = StateSpace(Ap, Bp, Cp, Dp)

    Am = np.array([[0, 1], [-Kt/(Jr*Tau_m), -Br/Jr]])
    Cm = np.array([[0, 1]])
    Bm = np.array([[-Kb/(Jr*Tau_m)], [0]])
    Dm = np.array([[0]])
    sys_M = StateSpace(Am, Bm, Cm, Dm)

    Aq = np.array([[0, 1],[-Ke*Kq/(Jl), -(Bl + Ke*Ke*Kq)/(Jl)]])
    Cq = np.array([[0, 1]])
    Bq = np.array([[0], [Kq/(Jl)]])
    Dq = np.array([[0]])
    sys_Q = StateSpace(Aq, Bq, Cq, Dq)

    tau = Tau_s
    sys1 = Cascade(sys_P, sys_M, sys_Q, tau)

    #===================================
    # Control System Description
    #===================================
    Kp = Kp_c
    Ki = Ki_c
    Kd = Kd_c
    gamma = gamma_c
    
    Kp_s = Kp_sat
    Ki_s = Ki_sat
    Kd_s = Kd_sat

    sys_CL = ClosingLoop(sys1, Kp, Ki, Kd, Kp_s, Ki_s, Kd_s, gamma)
    sys_CL_name = "Cascade PID Controlled System"

    # Plot the step response of the control system
    sys_CL.PlotStepResponse(0.0,20.0,stepSize=0.01,Name=sys_CL_name)

if __name__ == '__main__':
    cascade_pid_demo()

二、機械人

Python不僅可以實現智能化控制,還可以實現科學計算和數據分析方面的機械人項目。Python語言的科學計算的數值模塊,如NumPy和matplotlib等,使計算和繪圖變得輕鬆而快捷。下面我們使用Python實現一個人工神經網絡的機械人項目。


import numpy as np
import matplotlib.pyplot as plt
import random

class NeuralNetwork():
    def __init__(self):
        random.seed(1)
        self.synaptic_weights = 2 * random.random((3, 1)) - 1

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        return x * (1 - x)

    def train(self, training_inputs, training_outputs, training_iterations):
        for iteration in range(training_iterations):
            output = self.think(training_inputs)
            error = training_outputs - output
            adjustment = np.dot(training_inputs.T, error * self.sigmoid_derivative(output))
            self.synaptic_weights += adjustment

    def think(self, inputs):
        return self.sigmoid(np.dot(inputs, self.synaptic_weights))

if __name__ == "__main__":
    
    neural_network = NeuralNetwork()
    print("Random starting synaptic weights: ")
    print(neural_network.synaptic_weights)

    training_inputs = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
    training_outputs = np.array([[0, 1, 1, 0]]).T

    neural_network.train(training_inputs, training_outputs, 15000)
    print("Synaptic weights after training: ")
    print(neural_network.synaptic_weights)

    new_inputs = np.array([1, 0, 0])
    output = neural_network.think(new_inputs)

    print("Output of robotic brain:---> ")
    print(output)

三、物聯網

Python語言在物聯網行業中常用於物聯網平台的構建、數據的處理。作為一種簡單易學、語法輕鬆、代碼可讀性好的編程語言,Python語言在物聯網領域中得到了越來越多的應用。下面我們以火災預警識別系統為例,展示Python語言在物聯網行業中的應用:


import time    
import threading

class Smoke_Sensor(threading.Thread):
 
    def __init__(self, thread_name, sensor_delay, concentrations):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.sensor_delay = sensor_delay
        self.concentrations = concentrations
        self.smoke_threshold = 100
        print("Smoke_Sensor Starting:" + self.thread_name)

    def run(self):
        print("Starting " + self.thread_name + " thread....")
        while True:
            for index in range(0, len(self.concentrations)):
                if self.concentrations[index] > self.smoke_threshold:
                    print("\nSmoke_Alert! The concentration of toxic gases -", index + 1, " exceeds the threshold limit!!!\n\n\n")
            time.sleep(self.sensor_delay)
            
class Temperature_Sensor(threading.Thread):
 
    def __init__(self, thread_name, sensor_delay, temperature_values):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.sensor_delay = sensor_delay
        self.temperature_values = temperature_values
        self.temperature_threshold = 70
        print("Temperature_Sensor Starting:" + self.thread_name)

    def run(self):
        print("Starting " + self.thread_name + " thread....")
        while True:
            for index in range(0, len(self.temperature_values)):
                if self.temperature_values[index] > self.temperature_threshold:
                    print("\nTemperature_Alert! The temperature -", index + 1, " exceeds the threshold limit!!!\n\n\n")
            time.sleep(self.sensor_delay)

if __name__ == '__main__':
    
    # The predefined simulated data feed for sensors
    smoke_concentrations = [10, 12, 22, 65]
    temperature_values = [65, 72, 77, 85]
    
    # Creating Smoke Sensor Object
    smoke_sensor = Smoke_Sensor("Smoke_Sensor_Thread", 30, smoke_concentrations)
    smoke_sensor.start()
    
    # Creating Temperature Sensor Object
    temperature_sensor = Temperature_Sensor("Temperature_Sensor_Thread", 60, temperature_values)
    temperature_sensor.start()

四、圖像識別

圖像識別,作為一種先進的技術,為各個領域提供了很多優秀的應用。Python語言最重要的庫之一就是OpenCV,它是具有超高性能的圖像識別和處理庫。利用Python語言和OpenCV庫的強大功能,可以輕鬆實現各種圖像識別項目。下面我們用Python和OpenCV庫來實現基礎的圖像識別程序:


import cv2

def show_webcam(mirror=False):
    cam = cv2.VideoCapture(0)
    while True:
        ret_val, img = cam.read()
        if mirror:
            img = cv2.flip(img, 1)
        cv2.imshow('my webcam', img)
        if cv2.waitKey(1) == 27:
            break  # esc to quit
    cv2.destroyAllWindows()

def main():
    show_webcam(mirror=True)

if __name__ == '__main__':
    main()

五、大數據分析

Python語言作為一種數據分析的語言,其常用的數據分析庫NumPy、Matplotlib等在大數據領域中都表現出了卓越的能力。應用Python進行數據分析,特別是對海量數據進行分析和預測,具有簡單、快速、高效的特點。下面我們用Python語言中的pandas庫實現數據分析:


import pandas as pd
import numpy as np

data = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
print(data.tail())

df = pd.DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D'])
print(df.head(3))

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
print(df.sort_index(axis=1, ascending=False))

原創文章,作者:JBOKW,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/375306.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
JBOKW的頭像JBOKW
上一篇 2025-04-29 12:49
下一篇 2025-04-29 12:49

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論