Explorar el Código

(Add/modify) Data in/out ...

Kanggu Park hace 4 años
padre
commit
af6d4c9257
Se han modificado 2 ficheros con 70 adiciones y 115 borrados
  1. 58 87
      RealTimeSimulator_HeatStorageSystem.py
  2. 12 28
      RealTimeSimulator_LoadForecasting.py

+ 58 - 87
RealTimeSimulator_HeatStorageSystem.py

@@ -260,13 +260,12 @@ if __name__ == "__main__" :
 			targetDBUserID = rowDB_info[6]
 			targetDBUserPW = rowDB_info[7]
 			targetDBName = rowDB_info[8]
-			
-			startday = datetime.date(int(rowDB_info[9].year), int(rowDB_info[9].month), int(rowDB_info[9].day))
-			
+						
 			now=datetime.datetime.now().now()
 			lastday = datetime.date(now.year, now.month, now.day)
 			isRecent = True
 
+			startday = datetime.date(2020,4,9)
 			if startday < datetime.date(2020,4,8):
 				print('[ERROR] 데이터 최소 시작 시점은 2020.04.08 입니다')
 				startday = datetime.date(2020,4,9)
@@ -1380,69 +1379,32 @@ if __name__ == "__main__" :
 			conn = pymssql.connect(host = targetDBIP, user = targetDBUserID, password = targetDBUserPW, database = targetDBName, autocommit=True)
 			# Create Cursor from Connection
 			cursor = conn.cursor()
-			# Execute SQL
-			InitDate = datetime.datetime(now.year, now.month, now.day, now.hour, int(int(now.minute/15)*15),0)
 			
-			## Storage mode
-			cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 16 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")			
-			# 데이타 한꺼번에 Fetch
-			rows = cursor.fetchall()			
-			rawData_StorageMode = []
-			for i in rows:
-				rawData_StorageMode.append(i)
+			InitDate = datetime.datetime(now.year, now.month, now.day, now.hour, int(int(now.minute/15)*15), 0)
+			FinalDate = datetime.datetime(now.year, now.month, now.day, 21, 0, 0)
+			TmpTime = InitDate
+			TimeLen = 0
+			while TmpTime < FinalDate:
+				TmpTime += datetime.timedelta(minutes=15)
+				TimeLen += 1
 				
-			time.sleep(1)	
-			## REF1 status
-			cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 2 and FacilityCode = 4479 and PropertyId = 15 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")			
-			# 데이타 한꺼번에 Fetch
-			rows = cursor.fetchall()			
-			rawData_RefStatus1 = []
-			for i in rows:
-				rawData_RefStatus1.append(i)
-							
-			# rawData_RefStatus1=rawData_RefStatus1[:len(rawData_RefStatus1)-1]
-			#rawData_RefStatus1=rawData_RefStatus1[:-2]
-						
-			time.sleep(1)
-			## REF2 status
-			cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 2 and FacilityCode = 4480 and PropertyId = 15 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")
-			# 데이타 한꺼번에 Fetch
-			rows = cursor.fetchall()
-			rawData_RefStatus2 = []
-			for i in rows:
-				rawData_RefStatus2.append(i)
-			# rawData_RefStatus2=rawData_RefStatus2[:len(rawData_RefStatus2)-1]
-			# rawData_RefStatus2=rawData_RefStatus2[:-2]
-							
-			CustomizedStatus=[]
-			for i in range(len(rawData_StorageMode)):
-				CustomizedStatus.append(rawData_StorageMode[i][6])
-			
-			CustomizedRefStatus1=[]
-			for i in range(len(rawData_RefStatus1)):
-				CustomizedRefStatus1.append(rawData_RefStatus1[i][6])
-			
-			CustomizedRefStatus2 = []
-			for i in range(len(rawData_RefStatus2)):
-				CustomizedRefStatus2.append(rawData_RefStatus2[i][6])
+			while True:				
+				## Storage mode
+				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 16 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")			
+				# 데이타 한꺼번에 Fetch
+				rows = cursor.fetchall()			
+				rawData_StorageMode = []
+				for i in rows:
+					rawData_StorageMode.append(i)
 				
-			# 한번 더 데이터 불러오기 (가끔 제대로 로드 안되는 경우 있음)
-			time.sleep(0.5)
-			if len(CustomizedStatus) != len(CustomizedRefStatus1):
 				## REF1 status
-				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 2 and FacilityCode = 4479 and PropertyId = 15 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")			
+				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 2 and FacilityCode = 4479 and PropertyId = 15 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")	
 				# 데이타 한꺼번에 Fetch
-				rows = cursor.fetchall()			
+				rows = cursor.fetchall()
 				rawData_RefStatus1 = []
 				for i in rows:
 					rawData_RefStatus1.append(i)
-				
-				CustomizedRefStatus1=[]
-				for i in range(len(rawData_RefStatus1)):
-					CustomizedRefStatus1.append(rawData_RefStatus1[i][6])
-				
-			time.sleep(0.5)
-			if len(CustomizedStatus) != len(CustomizedRefStatus2):
+
 				## REF2 status
 				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 2 and FacilityCode = 4480 and PropertyId = 15 and SimulationCase = 1 and TargetDateTime >= '" + InitDate.strftime('%Y-%m-%d %H:%M:00') + "' and TargetDateTime < '" + (InitDate + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:00:00') + "'  order by TargetDateTime asc")
 				# 데이타 한꺼번에 Fetch
@@ -1450,11 +1412,22 @@ if __name__ == "__main__" :
 				rawData_RefStatus2 = []
 				for i in rows:
 					rawData_RefStatus2.append(i)
+								
+				CustomizedStatus=[]
+				for i in range(len(rawData_StorageMode)):
+					CustomizedStatus.append(rawData_StorageMode[i][6])
+				
+				CustomizedRefStatus1=[]
+				for i in range(len(rawData_RefStatus1)):
+					CustomizedRefStatus1.append(rawData_RefStatus1[i][6])
 				
 				CustomizedRefStatus2 = []
 				for i in range(len(rawData_RefStatus2)):
 					CustomizedRefStatus2.append(rawData_RefStatus2[i][6])
-			
+				
+				if TimeLen == len(CustomizedStatus) and TimeLen == len(CustomizedRefStatus1) and TimeLen == len(CustomizedRefStatus2):
+					break
+				time.sleep(1)			
 			
 			SimulCalAmount=[CalAmount_wo_nan[-1]]
 			for i in range(len(CustomizedStatus)):
@@ -1506,34 +1479,7 @@ if __name__ == "__main__" :
 					CustomizedRefStatus2[i] = 0
 							
 			
-			#### 시뮬레이션 결과 데이터 DB 삽입 	
-			## Thermal energy amount
-			for i in range(len(CustomizedStatus)):
-				TmpDate = InitDate + datetime.timedelta(minutes=i*15)
-				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 2 and SimulationCase = 1 and TargetDateTime = '" + TmpDate.strftime('%Y-%m-%d %H:%M:00') + "' ")
-				
-				# 데이타 하나씩 Fetch하여 출력
-				row = cursor.fetchone()
-				if row:
-					try:
-						cursor.execute("UPDATE " + targetDBName + ".dbo.BemsIceThermalStorageSimulation set CreatedDateTime = '"+ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +"', SimulationValue = " + str(SimulCalAmount[i]) + " where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 2 and SimulationCase = 1 and TargetDateTime = '"+ TmpDate.strftime('%Y-%m-%d %H:%M:00')+"'")
-						
-						if i == len(CustomizedStatus)-1:
-							print("* Thermal energy amount was updated!! (Simul)")
-					except:
-						print("[ERROR] There is an update error!! (Simulated thermal energy amount)")
-					
-				else:
-					try:
-						cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsIceThermalStorageSimulation (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,SimulationValue,SimulationCase) VALUES(1,3,4478,2,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','" + TmpDate.strftime('%Y-%m-%d %H:%M:00') + "', "+ str(SimulCalAmount[i]) + ", 1)" )
-						
-						if i == len(CustomizedStatus)-1:
-							print("* Thermal energy amount was inserted!! (Simul)")
-					except:
-						print("[ERROR] There is an insert error!! (Simulated thermal energy amount)")
-					
-				
-			
+			#### 시뮬레이션 결과 데이터 DB 삽입 				
 			## REF1 power consume			
 			for i in range(len(CustomizedStatus)):
 				TmpDate = InitDate + datetime.timedelta(minutes=i*15)
@@ -1592,6 +1538,31 @@ if __name__ == "__main__" :
 							print("* The REF2 power comsumption was inserted!! (Simul)")					
 					except:
 						print("[ERROR] There is an insert error!! (Simulated refrigerator2 power)")
+						
+			## Thermal energy amount
+			for i in range(len(CustomizedStatus)):
+				TmpDate = InitDate + datetime.timedelta(minutes=i*15)
+				cursor.execute("SELECT * FROM " + targetDBName + ".dbo.BemsIceThermalStorageSimulation where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 2 and SimulationCase = 1 and TargetDateTime = '" + TmpDate.strftime('%Y-%m-%d %H:%M:00') + "' ")
+				
+				# 데이타 하나씩 Fetch하여 출력
+				row = cursor.fetchone()
+				if row:
+					try:
+						cursor.execute("UPDATE " + targetDBName + ".dbo.BemsIceThermalStorageSimulation set CreatedDateTime = '"+ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +"', SimulationValue = " + str(SimulCalAmount[i]) + " where SiteId = 1 and FacilityTypeId = 3 and FacilityCode = 4478 and PropertyId = 2 and SimulationCase = 1 and TargetDateTime = '"+ TmpDate.strftime('%Y-%m-%d %H:%M:00')+"'")
+						
+						if i == len(CustomizedStatus)-1:
+							print("* Thermal energy amount was updated!! (Simul)")
+					except:
+						print("[ERROR] There is an update error!! (Simulated thermal energy amount)")
+					
+				else:
+					try:
+						cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsIceThermalStorageSimulation (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,SimulationValue,SimulationCase) VALUES(1,3,4478,2,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','" + TmpDate.strftime('%Y-%m-%d %H:%M:00') + "', "+ str(SimulCalAmount[i]) + ", 1)" )
+						
+						if i == len(CustomizedStatus)-1:
+							print("* Thermal energy amount was inserted!! (Simul)")
+					except:
+						print("[ERROR] There is an insert error!! (Simulated thermal energy amount)")					
 			
 			conn.close()
 			print('************ (Finish) Simulator! ************')

+ 12 - 28
RealTimeSimulator_LoadForecasting.py

@@ -617,45 +617,29 @@ if __name__ == "__main__" :
 					
 					#########################################################################
 					# Restore the previous data and save data	
-					# Hour-ahead
+					# Hour-ahead (지우고 다시 쓰기)
 					currentTime = datetime.datetime(now.year, now.month, now.day, now.hour, 0, 0)
 					tmpTime = [datetime.datetime(now.year, now.month, now.day, 0, 0, 0)]
 					while tmpTime[-1] < currentTime:
 						tmpTime.append(tmpTime[-1] + datetime.timedelta(hours=1))
 						
-					cursor.execute("SELECT * FROM BemsMonitoringPointForecastingHourAhead where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime >= '" + datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') + "' order by CreatedDateTime asc")
-					# 데이타 하나씩 Fetch하여 출력
-					row = cursor.fetchall()
-					RawData = row
-					idx_tmp = 0
+					cursor.execute("DELETE " + targetDBName + ".dbo.BemsMonitoringPointForecastingHourAhead where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime >= '" + datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') + "' and TargetDateTime < '" + (datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00') + "'")
+					
 					for i in range(len(tmpTime)):
-						if len(RawData) == 0:
-							cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingHourAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_oneStep[i])+")")	
-						else:
-							if tmpTime[i] != RawData[idx_tmp][5]:			
-								cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingHourAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_oneStep[i])+")")								
-							else:	### CreatedDateTime이 web에서 데이터 불러오는데 영향 받움							
-								cursor.execute("UPDATE " + targetDBName + ".dbo.BemsMonitoringPointForecastingHourAhead set CreatedDateTime = '"+ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +"'" + " where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime = '"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "'")
-								idx_tmp += 1
-							
+						cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingHourAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_oneStep[i])+")")	
+					
+						
+					# Day-ahead (지우고 다시 쓰기)	
 					FinalTime = datetime.datetime(now.year, now.month, now.day, 23, 0, 0)
 					tmpTime = [datetime.datetime(now.year, now.month, now.day, 0, 0, 0)]
 					while tmpTime[-1] < FinalTime:
 						tmpTime.append(tmpTime[-1] + datetime.timedelta(hours=1))
 						
-					# Day-ahead
-					cursor.execute("SELECT * FROM BemsMonitoringPointForecastingDayAhead where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime >= '" + datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') + "' and TargetDateTime < '" + (datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00') + "' order by CreatedDateTime asc")
-					# 데이타 하나씩 Fetch하여 출력
-					row = cursor.fetchall()
-					RawData = row
-					idx_tmp = 0
-					if len(RawData) == 0:
-						for i in range(len(tmpTime)):
-							cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingDayAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_dayAhead[i])+")")
-					elif len(RawData) != 24:
-						cursor.execute("DELETE " + targetDBName + ".dbo.BemsMonitoringPointForecastingDayAhead where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime >= '" + datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') + "' and TargetDateTime < '" + (datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00') + "'")
-						for i in range(len(tmpTime)):
-							cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingDayAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_dayAhead[i])+")")						
+					cursor.execute("DELETE " + targetDBName + ".dbo.BemsMonitoringPointForecastingDayAhead where SiteId = 1 and FacilityTypeId = 99 and FacilityCode = 4863 and PropertyId = 1 and TargetDateTime >= '" + datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') + "' and TargetDateTime < '" + (datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00') + "'")
+					
+					for i in range(len(tmpTime)):
+						cursor.execute("INSERT INTO " + targetDBName + ".dbo.BemsMonitoringPointForecastingDayAhead (SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,TargetDateTime,ForecastedValue) VALUES(1,99,4863,1,'" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','"+ datetime.datetime(tmpTime[i].year,tmpTime[i].month,tmpTime[i].day,tmpTime[i].hour,0,0).strftime('%Y-%m-%d %H:00:00') + "',"+str(y_pred_dayAhead[i])+")")
+									
 					#########################################################################
 
 					conn.close()