Python 矩阵运算

# coding=utf8
from requests.sessions import session
import pub
import numpy as np
import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler

def get_default_conn():
    conn = (host="127.0.0.1",
    port="3306",
    database="SYSTEM",
    user="sa",
    password="sa!123",
    charset="GBK")
    return conn


# 文件日志数据入库
def log_insert(sql_list):
    try:
        # 入库脚本
        insert_sql =" INSERT INTO P_ROADICINGWARNING_LOG (OBSERVTIME, HH,CREATETIME, FILEPATH, EDIT_FLAG, TYP ) VALUES (?,?,?,?,?,?);"

        if len(sql_list) > 0:
            #print(sql_list[0])
            conn = get_default_conn()
            cur = conn.cursor()
            cur.executemany(insert_sql, sql_list)
            cur.close()
            conn.close()
            sql_list.clear()
    except Exception as exception:
        print("文件日志入库出错,错误信息为:{0}".format(insert_sql))

 
def fileWrite(files,elename, ddate, hh, left, bottom, right, top, rows, cols, data):
    try:
        rgrid = round((right - left) / cols, 4)
        cgrid = round((top - bottom) / rows, 4)
        head = "diamond 4 " + str(ddate.year) + "年" + str(ddate.month).zfill(2) + "月" + str(ddate.day).zfill(2) + "日" + str(ddate.hour).zfill(2) + "时_" + str(hh).zfill(3) + "数据\n" + str(ddate.year) + " " + str(ddate.month).zfill(2) + " " + str(ddate.day).zfill(2) + " " + str(ddate.hour).zfill(2) + " " + str(hh) + " 0 " + str(rgrid) + " " + str(cgrid) + " " + str(left) + " " + str(right) + " " + str(bottom) + " " + str(top) + " " + str(cols) + " " + str(rows) + " 0 0 0 0 0"
 
        ddate = "{0}{1}{2}{3}".format(str(ddate.year),str(ddate.month).zfill(2),str(ddate.day).zfill(2),str(ddate.hour).zfill(2))

        filename = "{0}_{1}.{2}".format(elename, ddate, str(hh).zfill(3))

        # 判断文件路径是否存在,不存在则创建
        isExists = os.path.exists('{0}'.format(files))
        if not isExists:
            os.makedirs('{0}'.format(files))
        filesave = '{0}/'.format(files) + filename
        np.savetxt(filesave, np.flipud(data), fmt="%0.1f", delimiter=' ', header=head, footer='', comments='')
        return filesave
 
    except Exception as ex:
        print("Error: 研判结果保存失败!{0}".format(ex))


def getForecastGridData(element, start, step):
    try:
         
        datestart = datetime.datetime.strptime(start, '%Y-%m-%d %H:00:00')

        result = pub.getGridData(element, datestart.strftime('%Y-%m-%d %H:00:00'), str(step))
        if result != None:
            left = result[0]
            bottom = result[1]
            right = result[2]
            top = result[3]
            rows = result[4]
            cols = result[5]
            # 矩阵点对点取最大值
            alert_data = result[6]

            return alert_data
        else:
            return ""
    except Exception as ex:
        return "网格数据获取出错,错误信息为:{0}".format(ex)

def getPreLvl(preForecastData_12, preForecastData_24):
    b_preForecastData_12 = np.where(((preForecastData_12 == float(6)) | (preForecastData_12 == float(13))| (preForecastData_12 == float(14))| (preForecastData_12 == float(33))), 1, 0)
    y_preForecastData_12 = np.where(((preForecastData_12 == float(15)) | (preForecastData_12 == float(26))), 2, 0)
    o_preForecastData_12 = np.where(((preForecastData_12 == float(16)) | (preForecastData_12 == float(27))), 3, 0)
    r_preForecastData_12 = np.where(((preForecastData_12 == float(17)) | (preForecastData_12 == float(28))), 4, 0)
    b_preForecastData_24 = np.where(((preForecastData_24 == float(6)) | (preForecastData_24 == float(13))| (preForecastData_24 == float(14))| (preForecastData_24 == float(33))), 1, 0)
    y_preForecastData_24 = np.where(((preForecastData_12 == float(15)) | (preForecastData_24 == float(26))), 2, 0)
    o_preForecastData_24 = np.where(((preForecastData_24 == float(16)) | (preForecastData_24 == float(27))), 3, 0)
    r_preForecastData_24 = np.where(((preForecastData_24 == float(17)) | (preForecastData_24 == float(28))), 4, 0)
    preForecastData_12 = b_preForecastData_12 + y_preForecastData_12 + o_preForecastData_12 + r_preForecastData_12
    preForecastData_24 = b_preForecastData_24 + y_preForecastData_24 + o_preForecastData_24 + r_preForecastData_24
    alert_data =np.maximum(preForecastData_12, preForecastData_24)

    return alert_data

def getTmpLvl(time_hh, ddate):
   
 
    hh = time_hh

    # 初始化网格数据,用于接收计算结果
    result_lvl = np.mat(np.zeros((int(210), int(338))))

    # 循环计算持续天数
    while time_hh <= 240:
        result = pub.getGridData("TMIN", ddate, str(time_hh))[6]

        # 生成数据文件
        # fileWrite("E:\\rhtd\\micaps4", "DLJB_TMP", datetime.datetime.strptime("2024-02-02 08:00:00", '%Y-%m-%d %H:00:00'), time_hh, 91.975, 32.425, 108.87, 42.925, 210, 338, result)

        if(result.min() < -15):
            # 计算持续天数
            result_lvl += np.where((result < float(0)), 1, 0)
            time_hh += 24
        else:
            break
   
    b_tmin_result = np.where(((result_lvl > float(0)) & (result_lvl <= float(2))), 1, 0)

    y_tmin_result = np.where(((result_lvl > float(2)) & (result_lvl <= float(5))), 2, 0)

 
    o_tmin_result = np.where(((result_lvl > float(5)) & (result_lvl <= float(9))), 3, 0)

 
    r_tmin_result = np.where((result_lvl > float(9)) , 4, 0)
   
    # 合成综合等级文件
    tmin_result = b_tmin_result + y_tmin_result + o_tmin_result + r_tmin_result

    fileWrite("E:\\rhtd\\micaps4", "DLJB_TMP_YJ", datetime.datetime.strptime("2024-02-03 08:00:00", '%Y-%m-%d %H:00:00'), hh, 91.975, 32.425, 108.87, 42.925, 210, 338, tmin_result)

    # 返回结果
    return tmin_result



def task():

    ddate = datetime.datetime.now()
    print(ddate)

    if (ddate.hour >= 8 and ddate.hour < 16):
        f_date = datetime.datetime.strftime(ddate, '%Y-%m-%d 08:00:00')
    else:
        f_date = datetime.datetime.strftime(ddate, '%Y-%m-%d 20:00:00')
   

    f_date ='2024-02-03 08:00:00'

    # 文件存放路径
    filepath = r"E:/01_product/roadIcingWarning"

    # 日志入库记录
    log_list = []
   
    left = 91.975
 
    bottom = 32.425

    right = 108.875

    top = 42.925

    # 网格行数
    rows = 210

    # 网格列数
    cols = 338

    # 开始时效
    time_hh = 24
    while(time_hh <= 240):
        preForecastData_12 = getForecastGridData("wp_12h_{0}".format(str(time_hh-12).zfill(3)), f_date, 1)
        preForecastData_24 = getForecastGridData("wp_12h_{0}".format(str(time_hh).zfill(3)), f_date, 1)

        # 计算等级
        pre_lvl = getPreLvl(preForecastData_12, preForecastData_24)

        tmpForecastData = getTmpLvl(time_hh, f_date)
        alert_data = pre_lvl * tmpForecastData
        b_alert_result = np.where(((alert_data > float(0)) & (alert_data <= float(3))), 4, 0)
        y_alert_result = np.where(((alert_data > float(3)) & (alert_data <= float(6))), 3, 0)
        o_alert_result = np.where(((alert_data > float(6)) & (alert_data <= float(9))), 2, 0)
 
        r_alert_result = np.where((alert_data > float(9)) , 1, 0)

        alert_result = b_alert_result + y_alert_result + o_alert_result + r_alert_result
        filename = fileWrite(filepath, "DLJB", datetime.datetime.strptime(f_date, '%Y-%m-%d %H:00:00'), time_hh, left, bottom, right, top, rows, cols, alert_result)

        # 打印生成的文件路径
        print("预警文件【{0}】已生成!".format(filename))

        uints = (datetime.datetime.strptime(f_date, '%Y-%m-%d %H:00:00'),time_hh, datetime.datetime.now(), filename, 0, "DLJB")

        log_list.append(uints)

        # 时效循环
        time_hh +=24

    # 文件记录入库
    log_insert(log_list)



# 自动任务调度函数
def task_Auto():
    print('===============定时执行任务===============\r\n')
    scheduler = BlockingScheduler(timezone='Asia/Shanghai')
    scheduler.add_job(task, 'cron', hour=8, minute=0, args=[],misfire_grace_time=3600)
    scheduler.add_job(task, 'cron', hour=16, minute=40, args=[],misfire_grace_time=3600)

    try:
        scheduler.start()
    except Exception as e:
        pass


if __name__ == "__main__":
    task_Auto()
posted @ 2024-02-04 14:30  沈墨白  阅读(3)  评论(0编辑  收藏  举报