"""Created on Tue Dec 1 15:32:28 2020@author: ASUS"""importpandasaspdimporttimeimportnumpyasnpimportpandasaspdfromscipy.interpolateimportlagrangefrommatplotlibimportpyplotaspltimportdatetimeimportmathimportnumpyasnpfromnumpyimportarray, sign, zerosfromscipy.interpolateimportinterp1dimportscipy.signalassignalfromscipyimportfftpackplt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=Falsedefcut_date(t):
returnt[:10]
defget_data(flag=1,car_num='粤S85377',date=['2021-06-27','2021-06-28']):
ifflag==1:
data=pd.read_csv('车辆列表.csv')
data=data[['车牌号','创建时间','更新时间','装载体积']]
data=data[data.duplicated()==False]
GMT_FORMAT='%a %b %d %H:%M:%S CST %Y'data['创建时间']=data['创建时间'].apply(lambdax :datetime.datetime.strptime(x, GMT_FORMAT))
data['更新时间']=data['更新时间'].apply(lambdax :datetime.datetime.strptime(x, GMT_FORMAT))
data['time']=data['创建时间'].apply(str)
data['volume']=data['装载体积']
print(data.columns)
data=data[data['车牌号']==car_num]
data['date']=data['time'].apply(cut_date)
data=data[(data['date']==date[0])|(data['date']==date[1])]
ifdata.shape[0]==0:
print('自研设备【{0}】当天【{1}】没数据'.format(car_num, date[0]))
returndatanew_index=pd.date_range(start=data['time'].min()[:10],end=data['time'].max(),freq='s')
data['time']=pd.to_datetime(data['time'])
data=data.set_index('time',drop=True)
data=data.sort_index()
data=data.reindex(new_index)
data['time']=data.indexdata['day']=data['time'].apply(lambdax: time.strftime('%Y-%m-%d',time.strptime(str(x),'%Y-%m-%d %H:%M:%S')))
data['minute']=data['time'].apply(lambdax: time.strftime('%Y-%m-%d %H:%M',time.strptime(str(x),'%Y-%m-%d %H:%M:%S')))
data=data[['volume']].groupby(data['minute']).mean()
data=data.interpolate('linear')
data=data.sort_index()
data=data.reset_index()
else:
data=pd.read_csv('all_data2.csv')
data=data[data.duplicated(subset=['time','carnum'])==False]
print(data.columns)
data=data[data['carnum']==car_num]
data['date']=data['time'].apply(cut_date)
data=data[(data['date']==date[0])|(data['date']==date[1])]
ifdata.shape[0]==0:
print('G7设备【{0}】当天【{1}】没数据'.format(car_num, date[0]))
returndatanew_index=pd.date_range(start=data['time'].min()[:10],end=data['time'].max(),freq='s')
data['time']=pd.to_datetime(data['time'])
data.index=data['time']
data=data.reindex(new_index)
data['time']=data.indexdata['day']=data['time'].apply(lambdax: time.strftime('%Y-%m-%d',time.strptime(str(x),'%Y-%m-%d %H:%M:%S')))
data['minute']=data['time'].apply(lambdax: time.strftime('%Y-%m-%d %H:%M',time.strptime(str(x),'%Y-%m-%d %H:%M:%S')))
data=data[['volume']].groupby(data['minute']).mean()
data=data.interpolate('linear')
data=data.sort_index()
data=data.reset_index()
print(data.shape)
returndatadefevent_num(i,event_flag):
data_tmp=data.copy()
ifevent_flag==1:
data_tmp.loc[(data_tmp['diffxx']>-0.2)&(data_tmp['diffxx']<i),'diffxx']=0elifevent_flag==2:
data_tmp.loc[(data_tmp['diffxx']>-i)&(data_tmp['diffxx']<0.2),'diffxx']=0data_tmp['tag']=data_tmp['diffxx'].apply(lambdax: 10ifx==0else20ifx>0else0ifx<0elseNone)
data_tmp['tag_pr']=data_tmp['tag'].shift()
data_tmp['tag2']='最终状态'data_tmp.loc[(data_tmp['tag_pr']==0)&(data_tmp['tag']==0),'tag2']='卸货中'data_tmp.loc[(data_tmp['tag_pr']==0)&(data_tmp['tag']==10),'tag2']='结束卸货'data_tmp.loc[(data_tmp['tag_pr']==0)&(data_tmp['tag']==20),'tag2']='错误状态1'data_tmp.loc[(data_tmp['tag_pr']==10)&(data_tmp['tag']==0),'tag2']='开始卸货'data_tmp.loc[(data_tmp['tag_pr']==10)&(data_tmp['tag']==10),'tag2']='运输中'data_tmp.loc[(data_tmp['tag_pr']==10)&(data_tmp['tag']==20),'tag2']='开始装货'data_tmp.loc[(data_tmp['tag_pr']==20)&(data_tmp['tag']==0),'tag2']='错误状态2'data_tmp.loc[(data_tmp['tag_pr']==20)&(data_tmp['tag']==10),'tag2']='结束装货'data_tmp.loc[(data_tmp['tag_pr']==20)&(data_tmp['tag']==20),'tag2']='装货中'tmp=data_tmp.reset_index(drop=True)
ifevent_flag==1:
iftmp.shape[0]>0:
iftmp.iloc[0]['tag2']=='结束装货':
tmp=tmp.iloc[1:]
iftmp.shape[0]>0:
iftmp.iloc[-1]['tag2']=='开始装货':
tmp=tmp.iloc[:-1]
num=tmp[tmp['tag2']=='开始装货'].shape[0]
elifevent_flag==2:
iftmp.shape[0]>0:
iftmp.iloc[0]['tag2']=='结束卸货':
tmp=tmp.iloc[1:]
iftmp.shape[0]>0:
iftmp.iloc[-1]['tag2']=='开始卸货':
tmp=tmp.iloc[:-1]
num=tmp[tmp['tag2']=='开始卸货'].shape[0]
returnnumdefenvelope_extraction(signal):
s=signal.astype(float )
q_u=np.zeros(s.shape)
q_l=np.zeros(s.shape)
u_x= [0,] u_y= [s[0],] l_x= [0,] l_y= [s[0],] forkinrange(1,len(s)-1):
if (sign(s[k]-s[k-1])==1) and (sign(s[k]-s[k+1])==1):
u_x.append(k)
u_y.append(s[k])
if (sign(s[k]-s[k-1])==-1) and ((sign(s[k]-s[k+1]))==-1):
l_x.append(k)
l_y.append(s[k])
u_x.append(len(s)-1) u_y.append(s[-1]) l_x.append(len(s)-1) l_y.append(s[-1]) upper_envelope_y=np.zeros(len(signal))
lower_envelope_y=np.zeros(len(signal))
upper_envelope_y[0] =u_y[0]upper_envelope_y[-1] =u_y[-1]
lower_envelope_y[0] =l_y[0]lower_envelope_y[-1] =l_y[-1]
last_idx,next_idx=0, 0k, b=general_equation(u_x[0], u_y[0], u_x[1], u_y[1]) foreinrange(1, len(upper_envelope_y)-1):
ifenotinu_x:
v=k*e+bupper_envelope_y[e] =velse:
idx=u_x.index(e)
upper_envelope_y[e] =u_y[idx]
last_idx=u_x.index(e)
next_idx=u_x.index(e) +1k, b=general_equation(u_x[last_idx], u_y[last_idx], u_x[next_idx], u_y[next_idx])
last_idx,next_idx=0, 0k, b=general_equation(l_x[0], l_y[0], l_x[1], l_y[1]) foreinrange(1, len(lower_envelope_y)-1):
ifenotinl_x:
v=k*e+blower_envelope_y[e] =velse:
idx=l_x.index(e)
lower_envelope_y[e] =l_y[idx]
last_idx=l_x.index(e)
next_idx=l_x.index(e) +1k, b=general_equation(l_x[last_idx], l_y[last_idx], l_x[next_idx], l_y[next_idx])
returnupper_envelope_y, lower_envelope_ydefgeneral_equation(first_x,first_y,second_x,second_y):
A=second_y-first_yB=first_x-second_xC=second_x*first_y-first_x*second_yk=-1*A/Bb=-1*C/Breturnk, bdefget_time_err(time_1,time_2):
time_1_struct=datetime.datetime.strptime(time_1, "%Y-%m-%d %H:%M")
time_2_struct=datetime.datetime.strptime(time_2, "%Y-%m-%d %H:%M")
total_seconds= (time_2_struct-time_1_struct).total_seconds()
min_sub=total_seconds/60returnmin_subdefget_event():
data['tag']=data['diffxx'].apply(lambdax: 10ifx==0else20ifx>0else0ifx<0elseNone)
data['tag_pr']=data['tag'].shift()
data['tag2']='最终状态'data.loc[(data['tag_pr']==0)&(data['tag']==0),'tag2']='卸货中'data.loc[(data['tag_pr']==0)&(data['tag']==10),'tag2']='结束卸货'data.loc[(data['tag_pr']==0)&(data['tag']==20),'tag2']='错误状态1'data.loc[(data['tag_pr']==10)&(data['tag']==0),'tag2']='开始卸货'data.loc[(data['tag_pr']==10)&(data['tag']==10),'tag2']='运输中'data.loc[(data['tag_pr']==10)&(data['tag']==20),'tag2']='开始装货'data.loc[(data['tag_pr']==20)&(data['tag']==0),'tag2']='错误状态2'data.loc[(data['tag_pr']==20)&(data['tag']==10),'tag2']='结束装货'data.loc[(data['tag_pr']==20)&(data['tag']==20),'tag2']='装货中'tmp=data[['volume','tag']]
tmp.plot()
plt.title('车牌:{0} 时间:{1}'.format(c,v))
plt.savefig('./pictures/车牌:{0} 时间:{1}_事件结果.jpg'.format(c,v))
plt.show()
data_rexsult=data[(data['tag2']=='开始卸货')|(data['tag2']=='开始装货')|(data['tag2']=='结束卸货')|(data['tag2']=='结束装货')]
print('事件初次识别:',data_rexsult)
data_rexsult.to_csv('事件初次识别.csv')
data_transform=data[(data['tag2']=='开始装货')|(data['tag2']=='结束装货')]
data_transform=data_transform.reset_index(drop=True)
data_transform['tag4']=Falseforindex, rowindata_transform[:-1].iterrows():
ifdata_transform.iloc[index]['tag2']==data_transform.iloc[index+1]['tag2']:
data_transform.iloc[index:index+1]['tag4']=Truedata_transform=data_transform[data_transform['tag4']==False]
data_transform=data_transform[['minute', 'volume','tag', 'tag_pr', 'tag2']]
data_transform['minute2']=data_transform['minute'].shift(-1)
last_fill_date=datetime.datetime.strftime(datetime.datetime.strptime(data_transform['minute2'][0], "%Y-%m-%d %H:%M")+datetime.timedelta(days=+2), "%Y-%m-%d %H:%M")
data_transform['minute2']=data_transform['minute2'].fillna(last_fill_date)
data_transform['minute_shift']=data_transform.apply(lambdax:get_time_err(x['minute'],x['minute2']),axis=1)
data_transform=data_transform[['minute', 'volume', 'tag2', 'minute2', 'minute_shift']]
data_transform['drop']=Falseprint('data_transform1:',data_transform)
forindex, rowindata_transform.iterrows():
ifrow['tag2']=='结束装货'androw['minute_shift']<30:
data_transform.iloc[index:index+2]['drop']=Truedata_transform=data_transform[data_transform['drop']==False]
data_transform=data_transform.reset_index(drop=True)
print('data_transform2:',data_transform)
data_transform=data_transform.reset_index(drop=True)
data_transform['minute2']=data_transform['minute'].shift(-1)
last_fill_date=datetime.datetime.strftime(datetime.datetime.strptime(data_transform['minute2'][0], "%Y-%m-%d %H:%M")+datetime.timedelta(days=+2), "%Y-%m-%d %H:%M")
data_transform['minute2']=data_transform['minute2'].fillna(last_fill_date)
data_transform['minute_shift']=data_transform.apply(lambdax:get_time_err(x['minute'],x['minute2']),axis=1)
data_transform=data_transform[['minute', 'volume', 'tag2', 'minute2', 'minute_shift']]
data_transform['drop']=Falseprint('data_transform3:',data_transform)
forindex, rowindata_transform.iterrows():
ifrow['tag2']=='开始装货'androw['minute_shift']<10:
data_transform.iloc[index:index+2]['drop']=Truedata_transform=data_transform[data_transform['drop']==False]
data_transform=data_transform.reset_index(drop=True)
print('data_transform4:',data_transform)
tmp=data_transform.reset_index(drop=True)
iftmp.shape[0]>0:
iftmp.iloc[0]['tag2']=='结束装货':
tmp=tmp.iloc[1:]
iftmp.shape[0]>0:
iftmp.iloc[-1]['tag2']=='开始装货':
tmp=tmp.iloc[:-1]
tmp=pd.concat([tmp,tmp.shift(-1)],axis=1,keys=['开始', '结束'])[:-1]
tmp=tmp[tmp[('开始', 'tag2')]=='开始装货']
tmp=tmp.loc[:, [('开始', 'minute'), ('结束', 'minute'),('开始', 'volume'), ('结束', 'volume')]]
tmp.columns=['start_time','end_time','start_volume','end_volume']
tmp['event_type']='装车'tmp_zhuangche=tmp[['event_type','start_time','end_time','start_volume','end_volume']]
data_transform=data[(data['tag2']=='开始卸货')|(data['tag2']=='结束卸货')]
data_transform=data_transform.reset_index(drop=True)
data_transform['tag4']=Falseforindex, rowindata_transform[:-1].iterrows():
ifdata_transform.iloc[index]['tag2']==data_transform.iloc[index+1]['tag2']:
data_transform.iloc[index:index+1]['tag4']=Truedata_transform=data_transform[data_transform['tag4']==False]
data_transform=data_transform.reset_index(drop=True)
data_transform=data_transform[['minute', 'volume','tag', 'tag_pr', 'tag2']]
data_transform['minute2']=data_transform['minute'].shift(-1)
last_fill_date=datetime.datetime.strftime(datetime.datetime.strptime(data_transform['minute2'][0], "%Y-%m-%d %H:%M")+datetime.timedelta(days=+2), "%Y-%m-%d %H:%M")
data_transform['minute2']=data_transform['minute2'].fillna(last_fill_date)
data_transform['minute_shift']=data_transform.apply(lambdax:get_time_err(x['minute'],x['minute2']),axis=1)
data_transform=data_transform[['minute', 'volume', 'tag2', 'minute2', 'minute_shift']]
data_transform['drop']=Falseprint('data_transform1:',data_transform)
forindex, rowindata_transform.iterrows():
ifrow['tag2']=='结束卸货'androw['minute_shift']<30:
print(index,row['tag2'],row['minute_shift'])
data_transform.iloc[index:index+2]['drop']=Truedata_transform=data_transform[data_transform['drop']==False]
data_transform=data_transform.reset_index(drop=True)
print('data_transform2:',data_transform)
data_transform=data_transform.reset_index(drop=True)
data_transform['minute2']=data_transform['minute'].shift(-1)
last_fill_date=datetime.datetime.strftime(datetime.datetime.strptime(data_transform['minute2'][0], "%Y-%m-%d %H:%M")+datetime.timedelta(days=+2), "%Y-%m-%d %H:%M")
data_transform['minute2']=data_transform['minute2'].fillna(last_fill_date)
data_transform['minute_shift']=data_transform.apply(lambdax:get_time_err(x['minute'],x['minute2']),axis=1)
data_transform=data_transform[['minute', 'volume', 'tag2', 'minute2', 'minute_shift']]
data_transform=data_transform.reset_index(drop=True)
data_transform['drop']=Falseprint('data_transform3:',data_transform)
forindex, rowindata_transform.iterrows():
ifrow['tag2']=='开始卸货'androw['minute_shift']<10:
print(index,row['tag2'],row['minute_shift'])
data_transform.iloc[index:index+2]['drop']=Truedata_transform=data_transform[data_transform['drop']==False]
data_transform=data_transform.reset_index(drop=True)
print('data_transform4:',data_transform)
tmp=data_transform.reset_index(drop=True)
iftmp.shape[0]>0:
iftmp.iloc[0]['tag2']=='结束卸货':
tmp=tmp.iloc[1:]
iftmp.shape[0]>0:
iftmp.iloc[-1]['tag2']=='开始卸货':
tmp=tmp.iloc[:-1]
tmp=pd.concat([tmp,tmp.shift(-1)],axis=1,keys=['开始', '结束'])[:-1]
tmp=tmp[tmp[('开始', 'tag2')]=='开始卸货']
tmp=tmp.loc[:, [('开始', 'minute'), ('结束', 'minute'),('开始', 'volume'), ('结束', 'volume')]]
tmp.columns=['start_time','end_time','start_volume','end_volume']
tmp['event_type']='卸车'tmp_xieche=tmp[['event_type','start_time','end_time','start_volume','end_volume']]
event_result=pd.concat([tmp_zhuangche,tmp_xieche])
event_result.to_csv('合并拆分后的识别结果.csv')
data_rexsult=data[(data['tag2']=='错误状态1')|(data['tag2']=='错误状态2')]
if(data_rexsult.shape[0]!=0):
print('存在错误状态!!!')
zhuangche_num=data[data['tag2']=='开始装货'].shape[0]
xiehche_num=data[data['tag2']=='开始卸货'].shape[0]
returnevent_result,zhuangche_num,xiehche_numif__name__=="__main__":
testdict={}
date_list=[str(i)[:10] foriinpd.date_range(start='2021-06-24',end='2021-06-25',freq='D')]
forcin ['浙E60272']:
fori,vinenumerate(date_list[:-1]):
print(c,v)
data=get_data(flag=2,car_num=c,date=date_list[i:i+2])
print('数据尺寸:',data.shape)
ifdata.shape[0]==0: continuedata['3']=data['volume'].rolling(3, center=False).median()
data['5']=data['volume'].rolling(5, center=False).median()
data['7']=data['volume'].rolling(7, center=False).median()
data['10']=data['volume'].rolling(10, center=False).mean()
data['xx']=(data['3']+data['5']+data['7']+data['10'])/4data[['volume','xx']].plot()
plt.title('车牌:{0} 时间:{1}'.format(c,v))
plt.savefig('./pictures/车牌:{0} 时间:{1}_平滑.jpg'.format(c,v))
plt.show()
data['diffxx']=(data['xx']-data['xx'].shift())
data['diffxx']=data['diffxx'].rolling(7, center=True).median()
data['diffxx3']=data['diffxx'].rolling(3, center=True).median()
data['diffxx5']=data['diffxx'].rolling(5, center=True).median()
data['diffxx7']=data['diffxx'].rolling(7, center=True).median()
data['diffxx10']=data['diffxx'].rolling(10, center=True).median()
data['diffxx']=(data['diffxx3']+data['diffxx5']+data['diffxx7']+data['diffxx10'])/4data['diffxx'].plot()
plt.title('车牌:{0} 时间:{1}'.format(c,v))
plt.savefig('./pictures/车牌:{0} 时间:{1}_diff.jpg'.format(c,v))
plt.show()
l=[]
n=20threshold_zhuangche=0.2dt= [i/50foriinrange(0,50)]
h=pd.DataFrame(dt, columns= [u'阈值']) h[u'事件数'] =h[u'阈值'].apply(event_num,args=(1,)) h[u'事件数'].plot()
h[u'斜率'] =h[u'事件数'].diff()/0.25h[u'斜率指标'] =h[u'斜率'].abs().rolling(n).mean() ts=h[u'阈值'][h[u'斜率指标'].idxmin() -n]
ifts>threshold_zhuangche:
threshold_zhuangche=tsprint(threshold_zhuangche)
threshold_xieche=0.2dt= [i/50foriinrange(0,50)]
h=pd.DataFrame(dt, columns= [u'阈值']) h[u'事件数'] =h[u'阈值'].apply(event_num,args=(2,)) h[u'事件数'].plot()
h[u'斜率'] =h[u'事件数'].diff()/0.25h[u'斜率指标'] =h[u'斜率'].abs().rolling(n).mean() ts=h[u'阈值'][h[u'斜率指标'].idxmin() -n]
ifts>threshold_xieche:
threshold_xieche=tsprint(threshold_xieche)
plt.title('车牌:{0} 时间:{1}'.format(c,v))
plt.savefig('./pictures/车牌:{0} 时间:{1}_最优值下降趋势.jpg'.format(c,v))
plt.show()
threshold_xieche=0.2threshold_zhuangche=0.2data['diffxx2']=data['diffxx']
data.loc[(data['diffxx']>-threshold_xieche)&(data['diffxx']<threshold_zhuangche),'diffxx']=0data['分钟维度车载体积变化率']=data['diffxx2']
data['滤波后体积变化率']=data['diffxx']
data[['分钟维度车载体积变化率','滤波后体积变化率']].plot()
data['diffxx'][(data['diffxx']<=-threshold_xieche)]=-1data['diffxx'][(data['diffxx']>=threshold_zhuangche)]=1data['diffxx'].plot()
plt.show()
result_event,m,n=get_event()
testdict[(c,v)]=result_event[((result_event['event_type']=='装车')&(result_event['start_volume']>result_event['end_volume']))|((result_event['event_type']=='卸车')&(result_event['start_volume']<result_event['end_volume']))]
tmp=data[['volume','tag','minute']]
tmp['tag3']=10forindex,rowinresult_event.iterrows():
ifrow['event_type']=='装车':
tmp['tag3'][(tmp['minute']>=row['start_time'])&(tmp['minute']<=row['end_time'])]=20elifrow['event_type']=='卸车':
tmp['tag3'][(tmp['minute']>=row['start_time'])&(tmp['minute']<=row['end_time'])]=0tmp[['volume','tag3']].plot()
plt.title('车牌:{0} 时间:{1}'.format(c,v))
plt.savefig('./pictures/车牌:{0} 时间:{1}_事件结果.jpg'.format(c,v))
plt.show()