示例#1
0
def inv_energy__gen():
    print('inv_energy__gen')
    # Getting the form values
    filter_date = None
    filter_location_list = None
    filter_type = 'DAY'
    filter_type_nev = None
    try:
        filter_date = request.form['filter_date']
        filter_location_list = request.form.getlist('filter_location_list[]')
        filter_type = request.form['filter_type']
        filter_type_nev = request.form['filter_type_nev']
    except Exception as err:
        print(str(err))

    req_param = {
        'filter_date': filter_date,
        'filter_location_list': filter_location_list
    }

    # Changing to the time format
    try:
        start_time = datetime.strptime(filter_date, '%d/%m/%Y')
        end_time = start_time + timedelta(days=int(1))
    except Exception as err:
        print(str(err))
        start_time = None
        end_time = None

    if start_time is None and start_time != "":
        start_time = DateUtil.get_current_day()
    if end_time is None and end_time != "":
        end_time = start_time + timedelta(days=int(1))

    # Change the table and time condition based on the query
    curr_day = DateUtil.get_current_day()
    if filter_type_nev == "NEXT":
        curr_day = session['last_end_time'] + timedelta(days=int(1))
        start_time = curr_day
        end_time = curr_day + timedelta(days=int(1))
    elif filter_type_nev == "PREV":
        curr_day = session['last_start_date'] - timedelta(days=int(1))
        start_time = curr_day
        end_time = curr_day + timedelta(days=int(1))

    time_axis_format = '%d-%b(%H:%M)'
    _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
    if filter_type == "WEEK":
        start_time, end_time = DateUtil.week_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b(%H:%M)'
    elif filter_type == "MONTH":
        start_time, end_time = DateUtil.month_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b-%Y'
    elif filter_type == "YEAR":
        start_time, end_time = DateUtil.year_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b(%H:%M)'

    session['last_start_date'] = start_time
    session['last_end_time'] = end_time
    _condition = {
        "sender_timestamp": {
            "$gte": start_time,
            "$lte": end_time
        },
        'sensor_type': "INVERTER",
        "irr_value": {
            "$exists": 'true'
        }
    }
    if filter_location_list and "ALL" not in filter_location_list:
        _condition.__setitem__('resource_path', {'$in': filter_location_list})

    _projection = {
        "sender_timestamp": 1,
        'resource_path': 1,
        'sensor_id': 1,
        'AGGREGATE_VALUE': 1,
        'performance_ratio': 1,
        'expected_value': 1
    }

    print("search criteria ", _condition)
    print("Projection ", _projection)
    result = iot_dao.getrecord_from_table(
        _table, _condition, _projection,
        _sortby='resource_path').reset_index()
    try:
        result['AGGREGATE_VALUE'] = result['AGGREGATE_VALUE'].replace(
            [np.NaN, ''], 0).astype(np.float64).fillna(0.0)
        result['AGGREGATE_VALUE'] = round(result['AGGREGATE_VALUE'], 2)
        result['performance_ratio'] = result['performance_ratio'].replace(
            [np.NaN, ''], 0).astype(np.float64).fillna(0.0)
        result['performance_ratio'] = round(result['performance_ratio'], 2)
    except Exception as err:
        print(str(err))

    agg = {"AGGREGATE_VALUE": 'sum', "performance_ratio": 'mean'}
    location_detail = uti_service.get_location_details()
    data_lst = []

    graph_set = []
    common_x = []
    max_y = 10
    if not result.empty:
        #result_4_grp = result[result['AGGREGATE_VALUE'] > 0]
        result_4_grp = result.groupby(['sender_timestamp',
                                       'sensor_id']).agg(agg).reset_index()
        result_4_grp = result_4_grp.sort_values(['sender_timestamp'],
                                                ascending=[True])

        sensor_id_list = []
        summary = []
        for sensor_id in result_4_grp['sensor_id'].unique():
            sensor_id_list.append(sensor_id)
            x = []
            y = []
            result_4_grp_tmp = result_4_grp[result_4_grp['sensor_id'] ==
                                            sensor_id]
            print("sensor_id    ", sensor_id)
            summary_info = {}
            max = 0
            sum = 0
            min = 1000
            for index, row in result_4_grp_tmp.iterrows():
                print(index)
                x.append(row['sender_timestamp'].strftime('%d-%m-%Y %H:%M'))
                y.append(round(row['AGGREGATE_VALUE'], 2))
                sum = sum + round(row['AGGREGATE_VALUE'], 2)
                if max < round(row['AGGREGATE_VALUE'], 2):
                    max = round(row['AGGREGATE_VALUE'], 2)
                if row['AGGREGATE_VALUE'] != 0 and min > round(
                        row['AGGREGATE_VALUE'], 2):
                    min = row['AGGREGATE_VALUE']
                if max_y < row['AGGREGATE_VALUE']:
                    max_y = round(row['AGGREGATE_VALUE'])

            summary_info.__setitem__('sensor_id', sensor_id)
            summary_info.__setitem__('max_energy', round(max, 2))
            if min == 1000:
                min = 0
            summary_info.__setitem__('min_energy', round(min, 2))
            summary_info.__setitem__('energy_gen', round(sum, 2))
            summary.append(summary_info)

            if len(common_x) < len(x):
                common_x = x
            gp = {'X': x, 'Y': y, 'label': sensor_id, 'type': 'line'}
            print(gp)
            graph_set.append(gp)

        asert_info_tmp = iot_dao.getJSON_LISTrecord_from_table(
            TABLE.IOT_ASSET_MSTR, {"sensor_id": {
                '$in': sensor_id_list
            }}, {
                "asset_name": 1,
                "resource_path": 1,
                "asset_capacity": 1,
                "asset_location": 1,
                "asset_desc": 1,
                "sensor_id": 1,
                "sensor_type": 1,
                "model": 1,
                "module_efficiency": 1,
                "serial_no": 1,
                "total_panel_area": 1,
                "vendor_detail": 1
            }, None)
        asert_info = []
        for row in asert_info_tmp:
            rw = {}
            rw.__setitem__('Device Id', row['sensor_id'])
            rw.__setitem__('Location', row['resource_path'])
            rw.__setitem__('model', row['model'])
            rw.__setitem__('Device Name', row['asset_name'])
            rw.__setitem__('Device Desc', row['asset_desc'])
            rw.__setitem__('Total PV Area (SQM)', row['total_panel_area'])
            rw.__setitem__('Capacity (kWp)', row['asset_capacity'])

            asert_info.append(rw)

        for index, row in result.iterrows():
            rw = {}
            rw.__setitem__('SENDER_TIMESTAMP',
                           row['sender_timestamp'].strftime('%d-%m-%Y %H:%M'))
            rw.__setitem__('Location', row['resource_path'])
            rw.__setitem__(
                'Location Code',
                location_detail[row['resource_path']]['location_code'])
            rw.__setitem__('sensor_id', row['sensor_id'])
            rw.__setitem__('Energy (kWh)', row['AGGREGATE_VALUE'])
            rw.__setitem__('Performance Ratio (%)', row['performance_ratio'])

            data_lst.append(rw)

    loc_list = []
    for index, val in location_detail.items():
        val['selected'] = 'F'
        if filter_location_list:
            if (val['resource_path'] in filter_location_list):
                val['selected'] = 'Y'

        loc_list.append(val)

    print(max_y)
    return render_template('sub_pages/common_template.html',
                           pagename="inv_energy_gen_summary",
                           title="Inverter Energy Generation",
                           menu="menu_pr",
                           data=data_lst,
                           location_detail=loc_list,
                           req_param=req_param,
                           filter_type=filter_type,
                           graph_set=graph_set,
                           X_axies=common_x,
                           max_y=max_y,
                           info=asert_info,
                           summary=summary)
示例#2
0
def inverter_pr():
    print('inverter_pr')
    # Getting the form values
    filter_date = None
    filter_location_list = None
    filter_type = 'DAY'
    filter_type_nev = None
    try:
        filter_date = request.form['filter_date']
        filter_location_list = request.form.getlist('filter_location_list[]')
        filter_type = request.form['filter_type']
        filter_type_nev = request.form['filter_type_nev']
    except Exception as err:
        print(str(err))

    req_param = {
        'filter_date': filter_date,
        'filter_location_list': filter_location_list
    }

    # Changing to the time format
    try:
        start_time = datetime.strptime(filter_date, '%d/%m/%Y')
        end_time = start_time + timedelta(days=int(1))
    except Exception as err:
        print(str(err))
        start_time = None
        end_time = None

    if start_time is None and start_time != "":
        start_time = DateUtil.get_current_day()
    if end_time is None and end_time != "":
        end_time = start_time + timedelta(days=int(1))

    # Change the table and time condition based on the query
    curr_day = DateUtil.get_current_day()
    if filter_type_nev == "NEXT":
        curr_day = session['last_end_time'] + timedelta(days=int(1))
        start_time = curr_day
        end_time = curr_day + timedelta(days=int(1))
    elif filter_type_nev == "PREV":
        curr_day = session['last_start_date'] - timedelta(days=int(1))
        start_time = curr_day
        end_time = curr_day + timedelta(days=int(1))

    time_axis_format = '%d-%b(%H:%M)'
    _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
    if filter_type == "WEEK":
        start_time, end_time = DateUtil.week_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b(%H:%M)'
    elif filter_type == "MONTH":
        start_time, end_time = DateUtil.month_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b-%Y'
    elif filter_type == "YEAR":
        start_time, end_time = DateUtil.year_range(curr_day)
        _table = TABLE.IOT_AGG_1_HOUR_SUMMARY_TABLE
        time_axis_format = '%d-%b(%H:%M)'

    session['last_start_date'] = start_time
    session['last_end_time'] = end_time
    _condition = {
        "sender_timestamp": {
            "$gte": start_time,
            "$lte": end_time
        },
        'sensor_type': "INVERTER",
        "irr_value": {
            "$exists": 'true'
        }
    }
    if filter_location_list and "ALL" not in filter_location_list:
        _condition.__setitem__('resource_path', {'$in': filter_location_list})

    _projection = {
        "sender_timestamp": 1,
        'resource_path': 1,
        'sensor_id': 1,
        'AGGREGATE_VALUE': 1,
        'performance_ratio': 1,
        'expected_value': 1
    }

    print("search criteria ", _condition)
    print("Projection ", _projection)
    result = iot_dao.getrecord_from_table(
        _table, _condition, _projection,
        _sortby='resource_path').reset_index()
    try:
        result['AGGREGATE_VALUE'] = result['AGGREGATE_VALUE'].replace(
            [np.NaN, ''], 0).astype(np.float64).fillna(0.0)
        result['AGGREGATE_VALUE'] = round(result['AGGREGATE_VALUE'], 2)
        result['performance_ratio'] = result['performance_ratio'].replace(
            [np.NaN, ''], 0).astype(np.float64).fillna(0.0)
        result['performance_ratio'] = round(result['performance_ratio'], 2)
    except Exception as err:
        print(str(err))

    agg = {"AGGREGATE_VALUE": 'sum', "performance_ratio": 'mean'}
    location_detail = uti_service.get_location_details()
    data_lst = []
    x = []
    y1 = []
    y2 = []
    if not result.empty:
        result_4_grp = result[result['AGGREGATE_VALUE'] > 0]
        result_4_grp = result_4_grp.groupby(['sensor_id'
                                             ]).agg(agg).reset_index()
        result_4_grp = result_4_grp.sort_values(['AGGREGATE_VALUE'],
                                                ascending=[True])
        for index, row in result_4_grp.iterrows():
            x.append(row['sensor_id'])
            if row['performance_ratio'] > 100:
                row['performance_ratio'] = 100
            y1.append(round(row['performance_ratio']))
            y2.append(round(row['AGGREGATE_VALUE'], 2))

        for index, row in result.iterrows():
            rw = {}
            rw.__setitem__('SENDER_TIMESTAMP',
                           row['sender_timestamp'].strftime('%d-%m-%Y %H:%M'))
            rw.__setitem__('Location', row['resource_path'])
            rw.__setitem__(
                'Location Code',
                location_detail[row['resource_path']]['location_code'])
            rw.__setitem__('sensor_id', row['sensor_id'])
            rw.__setitem__('Energy (kWh)', row['AGGREGATE_VALUE'])
            rw.__setitem__('Performance Ratio (%)', row['performance_ratio'])

            data_lst.append(rw)

    loc_list = []
    for index, val in location_detail.items():
        val['selected'] = 'F'
        if filter_location_list:
            if (val['resource_path'] in filter_location_list):
                val['selected'] = 'Y'

        loc_list.append(val)

    plot_data, layout = polt_dashboard.rander_simplegraph(
        x_axies=x,
        y_axies_01=y1,
        y_label_01="PR (%)",
        y_axies_02=y2,
        y_label_02="Energy (kWh)",
        title="Time Vs performance_ratio",
        type_01="Scatter",
        type_02="Bar")
    print(plot_data)
    print(layout)
    graphs = dict(data=plot_data, layout=layout)
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('sub_pages/common_template.html',
                           pagename="inv_performance_ratio_summary",
                           title="Inverter Performance Ratio",
                           menu="menu_pr",
                           data=data_lst,
                           location_detail=loc_list,
                           req_param=req_param,
                           filter_type=filter_type,
                           graphJSON=graphJSON,
                           X=x,
                           Y1=y1,
                           Y2=y2,
                           y1_lable="Energy (kWh)",
                           y2_lable="Performance Ratio (%)")