domain_structure_analysis.py 3.89 KB
Newer Older
李明杰's avatar
李明杰 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
# -*- coding: utf-8 -*-
# author:Li Mingjie time:2019/2/28
# Brief:Domain Structure Analysis

import pandas as pd
import matplotlib.pyplot as plt
import bottom_function.data_read as dr
import json
from flask import Flask
from flask import request
from flask_cors import CORS


def data_statistics_plot(datatype, starttime, endtime, graphtype):
    csv_data = pd.DataFrame()
    csv_data = dr.read_domain_data(datatype=datatype, starttime=starttime, endtime=endtime)

    csv_data = csv_data.drop(columns=['datetime'])
    csv_data['col_sum'] = csv_data.apply(lambda x: x.sum(), axis=1)
    csv_data.loc['row_sum'] = csv_data.apply(lambda x: x.sum())
    # csv_data = csv_data[~csv_data.isin([0])]
    m_data = pd.Series()
    m_data = csv_data.loc['row_sum'][:-1]
    # m_data.dropna(inplace=True)
    m_data.sort_values(ascending=False, inplace=True)
    m_data = m_data[m_data.values != 0]
    fig = plt.figure(figsize=(10, 6))

    if graphtype == 'pie':
        e = []
        for j in m_data.index:
            if j == 'chat' or j == 'airconditioner':
                e.append(0.1)
            else:
                e.append(0)
        if len(m_data.index) > 6:
            labels = list(m_data.index[:6])
            labels.append('others')
            fracs = list(m_data.values[:6])
            other = sum(list(m_data.values[6:]))
            fracs.append(other)
        else:
            labels = list(m_data.index)
            fracs = list(m_data.values)

        v_sum = sum(fracs)
        v_data = fracs
        for i in range(0, len(fracs)):
            v_data[i] = fracs[i] / v_sum * 100
        fracs = v_data
        explode = e[:(len(fracs))]
        if sum(e[len(fracs):]) > 0:
            explode[-1] = 0.1
        plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.2f%%', shadow=True, startangle=90)
    elif graphtype == 'bar':
        name_list = list(m_data.index)
        num_list = list(m_data.values)
        m_data.plot(kind=graphtype, use_index=True)
        m_data.plot(kind='line', use_index=True)
        plt.xticks(rotation=45)
        plt.ylabel('Number', fontsize=12, labelpad=5)
        for x, y in zip(range(len(num_list)), num_list):
            plt.text(x, y, '%d' % y, ha='left', va='center', fontsize=9)
    else:
        m_data.plot(kind=graphtype, use_index=True)
    plt.title(str(starttime) + ' to ' + str(endtime) + ' semantic domain analysis of ' + graphtype + ' graph',
              fontsize=12)
    plt.tight_layout(5)
    path = '/roobo/soft/phpmyadmin/plot_domain.jpg'
    plt.savefig(path)
    return path


app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route('/SPDAS/domain_structure_analysis1', methods=['POST'])
def domain():
    param = ({"data_type": [{"value": "control"}, {"value": "application"}, {"value": "all"}],
              "time": "2018-12-01 00:00:00/2018-12-02 00:00:00",
              "graph_type": [{"value": "bar"}, {"value": "pie"}]})
    return json.JSONEncoder().encode(param)


@app.route('/SPDAS/domain_structure_analysis2', methods=['POST'])
def domain_form():
    # 需要从request对象读取表单内容:
    data = request.get_data()
    json_re = json.loads(data)
    print(json_re)
    datatype = json_re['data_type']
    m_time = json_re['time']
    graphtype = json_re['graph_type']
    str_time = str(m_time)
    m_time = str_time.split('/')
    starttime = m_time[0]
    endtime = m_time[1]
    image_path = data_statistics_plot(datatype=datatype, starttime=starttime, endtime=endtime, graphtype=graphtype)
    path = ({"domain_image": image_path})
    return json.JSONEncoder().encode(path)


if __name__ == '__main__':
    app.run(debug=True, host='10.7.19.129', port=5000)

# str_time = str('2018.12.01 00:00:00/2018.12.02 00:00:00')
# m_time = str_time.split('/')
# starttime = m_time[0]
# endtime = m_time[1]
# print(starttime)
# data_statistics_plot(datatype='all', starttime='2018-12-01 00:00:00', endtime='2018-12-02 00:00:00', graphtype='pie')