首页 > 编程语言 >Python 矩阵运算

Python 矩阵运算

时间:2024-02-04 14:33:06浏览次数:31  
标签:24 12 运算 Python float 矩阵 result str preForecastData

# 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()

标签:24,12,运算,Python,float,矩阵,result,str,preForecastData
From: https://www.cnblogs.com/gzl0612/p/18006130

相关文章

  • 【Python】conda常用命令
    ✨conda下载AnacondaFreeDownload|AnacondaMinicondaMiniconda—minicondadocumentation个人推荐安装Miniconda即可反正我从来没有使用过Anaconda的GUI✨conda基本命令新建环境condacreate-n${envName}python=3.8-n新建环境名称python=3.8可选指定Py......
  • 很好用的python游戏环境(续):强化学习算法走迷宫游戏环境(导航问题 navigation):分享一个pyt
    前文分享了一个python下的maze游戏环境,本文再给出一个不错的实现项目,这个项目的实现更加的简单,并且可视化界面做的很好看,是用tkinter框架做的可视化:相关:迷宫游戏python实现Github地址:https://github.com/wonanut/Maze-Game/tree/Maze-game-v1.0.7......
  • 很好用的python游戏环境:强化学习算法走迷宫游戏环境(导航问题 navigation):分享一个pyth
    项目的GitHub地址(作者:莫凡):https://github.com/MorvanZhou/mmaze运行的示例代码:importmmazestart=(0,0)end=(10,10)m=mmaze.generate(width=11,height=11,symmetry="horizontal")solutions=m.solve(start=start,end=end)m.plot(solution=solutions[0],star......
  • python语言下的迷宫游戏的实现猜想
    由于本人是研究AI的,尤其是AI的强化学习方向,有时候就会对一些小游戏环境的实现有几分兴趣,因为刚看了有关reinforcementlearning解决maze游戏的论文,于是就突发奇想的对这个maze迷宫的实现有些想了解了。迷宫其实就是在一个表格上画线,然后构成的从某点到另一个点的一个通路的环境:具体......
  • pyqt报错、python报错:src/pyaudio/device_api.c:9:10: fatal error: portaudio.h: 没
    报错信息:-DNDEBUG-fwrapv-O2-Wall-fPIC-O2-isystem/home/devil/anaconda3/envs/91/include-fPIC-O2-isystem/home/devil/anaconda3/envs/91/include-fPIC-I/usr/local/include-I/usr/include-I/home/devil/anaconda3/envs/91/include/python3.10-csrc/pyaudio/d......
  • 如何绕过Python readline的Tab-补全
    在Python中,readline模块提供了一个交互式的命令行输入接口,其中的Tab补全是指用户在输入时按下Tab键,系统会自动尝试完成当前输入的命令或路径。Tab补全的主要功能是帮助用户更快速、更准确地输入命令或路径,尤其是当有很多可能的选项时。下面我将用详细的步骤来说明Tab补全......
  • python操作yaml
     补充:yaml语法详见:yaml语法 yaml应用场景1、保存自动化测试数据2、保存自动化测试中的关联数据  安装yaml模块pipinstallpyyaml==5.4.1 读取yaml数据读取数据:load()或者full_load(),返回一个对象用例数据:case.yaml-caseId:1apiName:registerdescribe:注册url:......
  • 系统环境变量,python包导入的路径搜索机制,PYTHONPATH,sys.path
    系统环境变量的定义通过在环境变量里面加入所有软件的安装路径,当我们想运行某一软件时双击其快捷方式,此时,计算机除了在其当前目录下寻找该软件的.exe文件外(windows系统),还会在环境变量中搜索软件的路径,找到,运行。综上,Windows中的环境变量,当要求系统运行一个程序而没有告诉它程序......
  • Python 基于pymongo操作Mongodb学习总结
    实践环境Python3.6.4pymongo4.1.1pymongo-3.12.3-cp36-cp36m-win_amd64.whl下载地址:https://pypi.org/simple/pymongo/代码实践#!/usr/bin/envpython#-*-coding:utf-8-*-importdatetimeimportrandomimportpymongofrompymongoimportMongoClientfrombson.objecti......
  • Python elasticsearch-py类库基础用法
    实践环境https://pypi.org/project/elasticsearch/pipinstallelasticsearch==7.6.0离线安装包及依赖包下载地址:https://files.pythonhosted.org/packages/f5/71/45d36a8df68f3ebb098d6861b2c017f3d094538c0fb98fa61d4dc43e69b9/urllib3-1.26.2-py2.py3-none-any.whl#sha256=d8ff9......