Exemplo n.º 1
0
    def createStackBarPlot(self,predictDate,payment) : 

        loadedModel = joblib.load(self.modelName)

        inputDataGetter = InputDataGetter

        inputData = inputDataGetter.getInputData()

        predictor = Predictor(inputData)

        predictData = predictor.executePrediction(loadedModel)

        predictData = predictData.loc[predictDate]

        # 전기요금 계산 필드 추가
        elecFeeCalculator = ElecFeeCalculator(predictData)

        # period 0 : 시간 당 전기요금 계산
        # contractElec : 시간 당 전기요금이기 때문에 입력 필요 x->0으로 입력
        finalData = elecFeeCalculator.calElecFee(0,payment,0)

        finalData = calculateGasFee(finalData)

        # print(finalData)
        graph = [

            go.Bar(x=finalData.index,y=finalData['cElec'],name='CCHP 발전 전력 사용량'),
            go.Bar(x=finalData.index,y=finalData['kElec'],name='한전 전력 사용량'),

            go.Layout(
                colorway=['#5E0DAC','#2dce89'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': 'CCHP 스케쥴링', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="예측 전력 사용량 (kwh)",
                    tickformat = ".0f"
                ),
                barmode='stack'
            ),
            go.Scatter(x=finalData.index, y=finalData['elecFee'], name='한국 전력 사용 요금',mode='lines+markers',marker=dict(
                    color='#2dce89',
                    size=7)
            ),
            go.Scatter(x=finalData.index, y=finalData['gasFee'], name='CCHP 발전 사용 요금',mode='lines+markers',marker=dict(
                    color='#5E0DAC',
                    size=7)),
            go.Layout(
                colorway=['#2dce89', '#5E0DAC'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': '전력 사용 요금 비교', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="전력 사용 요금 (원)",
                    tickformat = ".0f"
                ) 
            )
        ]
        
        graphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder)
        # print("graphJSON : " + graphJSON)
        return graphJSON
Exemplo n.º 2
0
    def createSchLinePlot(self,predictDate) :
        
        loadedModel = joblib.load(self.modelName)

        inputDataGetter = InputDataGetter

        inputData = inputDataGetter.getInputData().loc[predictDate]

        predictor = Predictor(inputData)

        predictData = predictor.executePrediction(loadedModel)

        # predictData = predictData.loc[predictDate]

        newData = inputData
        newData['consumption'] = predictData['consumption']

        # print(predictData)
        # print(inputData)


        feature = ['consumption','temperature','humidity','windSpeed']

        newData = newData[feature].astype(float)

        graph = [
            go.Scatter(x=newData.index,y=newData['consumption'],name='예측 전력 사용량',mode='lines+markers',marker=dict(
                    color='#2dce89',
                    size=4
            )),

            go.Layout(
                colorway=['#2dce89'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': '예측 전력 사용량', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="예측 전력 사용량 (kwh)",
                    tickformat = ".0f"
                ) 
            ),

            go.Scatter(x=newData.index,y=newData['temperature'],name='기온', mode='lines+markers',marker=dict(
                    color='#5E0DAC',
                    size=4
            )),

            go.Layout(
                colorway=['#5E0DAC'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': '기온', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="기온 (℃)",
                    tickformat = ".0f"
                ) 
            ),

            go.Scatter(x=newData.index,y=newData['humidity'],name='습도',mode='lines+markers',marker=dict(
                    color='#2dce89',
                    size=4
            )),

            go.Layout(
                colorway=['#2dce89'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': '습도', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="습도 %",
                    tickformat = ".0f"
                ) 
            ),

            go.Scatter(x=newData.index,y=newData['windSpeed'],name='풍속',mode='lines+markers',marker=dict(
                    color='#5E0DAC',
                    size=4
            )),

            go.Layout(
                colorway=['#5E0DAC'],
                template='plotly_dark',
                paper_bgcolor='rgba(0, 0, 0, 0)',
                plot_bgcolor='rgba(0, 0, 0, 0)',
                #   margin={'autoexpand' : True},
                #   height=100,
                hovermode='x',
                #   autosize=True,
                title={'text': '풍속', 'font': {'color': 'white'}, 'x': 0.5},
                xaxis=dict(
                    rangeselector=dict(
                        buttons=list([
                            dict(count=1,
                                label="1m",
                                step="month",
                                stepmode="backward"),
                            dict(count=1,
                                label="1y",
                                step="year",
                                stepmode="backward"),
                            dict(step="all")
                        ]),
                        bgcolor='rgba(0,0,0,0)',
                        activecolor = 'rgba(0,0,0,1)'
                    ),
                    rangeslider=dict(
                    visible=True
                    ),
                    type="date"
                ),
                yaxis=dict(
                    title="풍속 (M/s)",
                    tickformat = ".0f"
                ) 
            )
        ]
        
        graphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder)
        # print("graphJSON : " + graphJSON)
        return graphJSON
Exemplo n.º 3
0
    def addData():

        today = datetime.datetime.now() - datetime.timedelta(hours=1)

        # weekday
        weekday = today.weekday()

        # isHoliday : weekday가 주말이면 1
        isHoliday = 0

        if weekday == 5 or weekday == 6:
            isHoliday = 1

        # 초단기 실황 : api 제공시간 - 정각 + 40분
        base_date = str(today.year) + str(today.month).zfill(2) + str(
            today.day).zfill(2)
        # base_time = str(today.hour).zfill(2) + '00'
        base_time = str(today.hour).zfill(2) + '00'

        # date
        date = datetime.datetime.strptime(base_date + base_time, '%Y%m%d%H%M')

        # get weather data
        serviceKey = "52s6pZxbOiLmg7H76y%2BN1Rs2tXn4ru798V6iWXFOFWzwKDzqkzuVuxdhol%2FuBCEYc9IOUIKfeJBn2XcEzKXZbg%3D%3D"
        url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService/getUltraSrtNcst'

        queryParams = '?ServiceKey=' + serviceKey + '&pageNo=1&numOfRows=50000&dataType=JSON&base_date=' + base_date + '&base_time=' + base_time + '&nx=62&ny=126'

        response = requests.get(url + queryParams)

        html = response.text

        data = json.loads(html)

        tempData = data['response']['body']['items']['item']

        for i in range(0, len(tempData)):

            item = tempData[i]

            category = item['category']

            # temperature
            if category == 'T1H':
                temperature = item['obsrValue']

            # humidity
            elif category == 'REH':
                humidity = item['obsrValue']

            # windSpeed
            elif category == 'WSD':
                windSpeed = item['obsrValue']

        # set isHoliday
        serviceKey = "52s6pZxbOiLmg7H76y%2BN1Rs2tXn4ru798V6iWXFOFWzwKDzqkzuVuxdhol%2FuBCEYc9IOUIKfeJBn2XcEzKXZbg%3D%3D"
        url = 'http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo'

        holidayList = []

        queryParams = '?ServiceKey=' + serviceKey + '&pageNo=1&numOfRows=100&solYear=' + str(
            today.year) + '&solMonth=' + str(today.month).zfill(2)

        response = requests.get(url + queryParams)
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')
        holiday = soup.find_all('locdate')

        for i in range(0, len(holiday)):

            holidayStr = holiday[i].text
            year = holidayStr[0:4]
            month = holidayStr[4:6]
            day = holidayStr[6:8]

            holidayList.append(year + '-' + month + '-' + day)

        for i in range(0, len(holidayList)):
            dateStr = str(today.year) + '-' + str(
                today.month).zfill(0) + '-' + str(today.day).zfill(0)

            if dateStr == holidayList[i]:
                isHoliday = 1

        # change type
        temperature = float(temperature)
        humidity = float(humidity)
        windSpeed = float(windSpeed)

        # prediction

        modelName = 'sejong_power_consumption_model2.pkl'
        loadedModel = joblib.load(modelName)

        month = date.month
        hour = date.hour

        dataDict = {"temperature": [temperature], "humidity": [humidity], "windSpeed": [windSpeed], \
                    "weekday" : [weekday], "isHoliday" : [isHoliday], "date" : [date], "month" : [month], \
                    "hour" : [hour]}

        dataDf = pd.DataFrame(dataDict).set_index('date')

        predictor = Predictor(dataDf)

        predictData = predictor.executePrediction(loadedModel)

        dataDf['consumption'] = predictData['consumption']

        consumption = dataDf.loc[date]['consumption']

        dataVO = DataVO(date, consumption, temperature, humidity, windSpeed,
                        weekday, isHoliday)

        connector = DBConnector()

        dataGetter = DataGetter(connector)

        # data type: dataFrame
        dataGetter.insertData(dataVO)