
    L9f%                         d dl Zd dlZd dlmZ d dlmZ d dl	Z
d dl Zd dlmZmZ d dlZd dlmZ d dlmZ dZ G d de          ZdS )	    N)HydraHeadApp)StepsStep)chain)Sequencyz{:,.2f}c                       e Zd ZddZd ZdS )WalshApp c                 H    | j                             |           || _        d S )N)__dict__updatetitle)selfr   kwargss      F/Users/putuwistika/Documents/TRILAK/hydralit-example/apps/walsh_app.py__init__zWalshApp.__init__   s#    V$$$


    c           
      H   	 t          j        d           t          j        d           t          j        dd           t	          j        dddgd	          }|                     |d
d           t          j        d           t          j        d           t           j	        
                    ddddd          }t           j	        
                    ddddd          }t           j	                            dd          }t                      }t          j                            ddd          }t!                                          t%          t'          dt)          |                              |          }|                    |                                ||          }|                    |                                ||          }	t!                                          |                                |          }
t!                                          |                                |	          }|                    d          }|                    |dd d!"           |
                    |d#d d$d%&           |                                 t          j        |                                d'           t          j        d(           t          j        d)           t!          j        |dd*          }|                    t	          j        d+d,d          -          }|                    |                                ||          }|                    |                                ||          }t!                                          |                    d.          |          }t!                                          |                    d.          |          }|                    dd/0          }|                    |d1d23           |                    |d1d43           |                                 t          j        |                                d'           t          j        d5           t          j        d6           t?          j         d,d78          \  }\  }}}|!                    d9:           t                      }|"                    |                                          \  }}}|#                    d;           |$                    d<           |%                    d=           |&                    ||           |                                j'        d>         }|(                    |                                d t          j)        z  |z            \  }}|#                    d?           |$                    d@           |%                    d=           |&                    ||           |(                    |*                                d t          j)        z  |z            \  }}|#                    dA           |$                    d@           |%                    d=           |&                    |dd          |dd                     t          j        |d'           d S # tV          $ r\}t          j,        dBdC           t          j-        dD           t          j-        dE.                    |                     Y d }~d S d }~ww xY w)FNzSequency Denoisinga  Source for this quick tutorial on using Sequency methods for denoising step change data can be found in the [Hotstepper documentation](https://hotstepper.readthedocs.io/notebooks/sequency_quickstart.html). An example of how easy it is to convert an existing application and use within a Hydralit multi-page application, see the secret saurce [here] (https://github.com/TangleSpace/hydralit).z<br><br>T)unsafe_allow_htmlzZhttps://raw.githubusercontent.com/TangleSpace/hotstepper-data/master/data/vessel_queue.csventerleave)parse_datesdayfirstzdata.csvzDownload Example Dataa<  
                Another typical use case of Fourier transforms is to remove high frequency noise from a single by decomposing it into constituent frequency components and setting frequencies below a threshold value to zero.                 With Sequency analysis, we have a similar functionality, except since we have step data and we are wanting to retain the nature of the step data (as steps) instead of just smoothing away the details,                 we can use the denoise method of the Sequency module to remove the higher sequency number components. An explicit example is shown below, here for now, we pass in the direct steps data for denoising,                 apply a strength parameter to determine how many of the high sequency components are set to zero and then we construct a new Steps object.
                a  
denoise_step_changes_strong = seq.denoise(rand_steps.step_changes(),denoise_strength=0.7,denoise_mode='range')
denoise_step_changes = seq.denoise(rand_steps.step_changes(),denoise_strength=0.2)

rand_steps_denoise_strong = Steps().add_direct(data_start=rand_steps.step_keys(),data_weight = denoise_step_changes_strong)
rand_steps_denoise = Steps().add_direct(data_start=rand_steps.step_keys(),data_weight = denoise_step_changes)

ax = rand_steps.plot(label='Original Data')
rand_steps_denoise.plot(ax=ax,color='g',linewidth=2,label='Light Denoise');
rand_steps_denoise_strong.plot(ax=ax,color='r',linewidth=2,linestyle='-',label='Strong Denoise')
ax.legend();
                zStrong Denoise Strengthgffffff?g{Gz?g      ?)value	min_value	max_valuestepzLight Denoise Strengthg?zDenoise Mode)ranger   i   d      )
data_startdata_weight)denoise_strengthdenoise_modezOriginal Data)labelg   zLight Denoise)axcolor	linewidthr&   r-zStrong Denoise)r)   r*   r+   	linestyler&   )clear_figureuO  
                As another quick example, we can apply the same technique to one of the HotStepper sample datasets, for this tutorial, we’ll only look at the first two months of data in order to better highlight what the sequency denoising can do to help better show the trend or typical step behaviour of the data.
                aQ  
df_vq_samp = pd.read_csv(r'https://raw.githubusercontent.com/TangleSpace/hotstepper-data/master/data/vessel_queue.csv',parse_dates=['enter','leave'],dayfirst=True)

vq_samp = Steps.read_dataframe(df_vq_samp,start='enter',end='leave')
vq_clip = vq_samp.clip(ubound=pd.Timestamp(2020,3,1))

dn = seq.denoise(vq_clip.step_changes(),denoise_mode='range')
vq_clip_dn = Steps().add_direct(data_start=vq_clip.step_keys(convert_keys=True),data_weight=dn)

ax = vq_clip.plot(label='Original Data',figsize=(14,6))
vq_clip_dn.plot(ax=ax,linewidth=3,label='Sequency Denoise')
ax.legend()
                )startendi     )ubound)convert_keys)      )r&   figsizeg      ?zStrong Sequency Denoise)r)   r+   r&   zLight Sequency Denoisea  
                As the last item, we can take a look at the sequency spectrum for the vessel queue data. This dataset has a large number of changes and therefore the sequency range goes quite high, however it does show a number of peaks that are significantly larger than the others, indicating a number of distinct and repeating step change patterns within the data over this period.
                a  
fig, (ax,ax2,ax3) = plt.subplots(nrows=3,figsize=(12,8))
fig.tight_layout(h_pad=4)

# Sequency object to use for analysis
vq_clip_seq = Sequency()
n,sp,l = vq_clip_seq.sequency_spectrum(vq_clip.step_changes())


ax.set_title('Step Change Sequency Spectrum')
ax.set_xlabel('Sequency Number')
ax.set_ylabel('Amplitude')
ax.stem(n,sp)

# number of data points, needed to create the sampling frequency
no_points = vq_clip.step_changes().shape[0]

fr,fsp = vq_clip_seq.frequency_spectrum(vq_clip.step_changes(),2*np.pi*no_points)

ax2.set_title('Step Change Frequency Spectrum')
ax2.set_xlabel('Frequency')
ax2.set_ylabel('Amplitude')
ax2.stem(fr,fsp)

# FFT the steps values instead of the delta changes to see the difference in the spectrum.
frv,fspv = vq_clip_seq.frequency_spectrum(vq_clip.step_values(),2*np.pi*no_points)

ax3.set_title('Steps Value Frequency Spectrum')
ax3.set_xlabel('Frequency')
ax3.set_ylabel('Amplitude')
ax3.stem(frv[1:],fspv[1:]);
                )r      )nrowsr7      )h_padzStep Change Sequency SpectrumzSequency Number	Amplituder   zStep Change Frequency Spectrum	FrequencyzSteps Value Frequency Spectrumz./resources/failure.png)widthzhAn error has occurred, someone will be punished for your inconvenience, we humbly request you try again.zError details: {})/str   	subheadermarkdownpdread_csvdownload_buttonwritecodesidebarsliderradior   nprandomrandintr   
add_directlistr   lendenoisestep_changes	step_keysplotlegendpyplot
get_figureread_dataframeclip	Timestamppltsubplotstight_layoutsequency_spectrum	set_title
set_xlabel
set_ylabelstemshapefrequency_spectrumpistep_values	Exceptionimageerrorformat) r   
df_vq_sampdenoise_power_strong_selectdenoise_power_light_selectdenoise_mode_selectseqsteps_changes
rand_stepsdenoise_step_changes_strongdenoise_step_changesrand_steps_denoise_strongrand_steps_denoiser)   vq_sampvq_clip	dn_strongdn_lightvq_clip_dn_strongvq_clip_dn_lightfigax2ax3vq_clip_seqnspl	no_pointsfrfspfrvfspves                                    r   runzWalshApp.run   s3   n	4H)***L  c  d  d  dK
T::::  &C  QX  Y`  Pa  ko  p  p  pJ  J7NOOOH   G   +-**;*;<U\_jny|  CG*;  +H  +H')+):):;SZ]hlwz  AE):  *F  *F&"$*"2"2>BS"T"T **CI--c"S99M++tE!CDVDV<W<W7X7Xgt+uuJ*-++j6M6M6O6Oa|  K^+  +_  +_'#&;;z/F/F/H/HZt  CV;  $W  $W (-(:(:jFZFZF\F\  lG(:  )H  )H%!&!3!3z?S?S?U?Udx!3!y!y77B##rao#VVV%**bsQQT[k*lllIIKKKIbmmoo48888 H   G    *:GPPPGll",tAa*@*@lAAG G$8$8$:$:Lg  vI  J  JI{{7#7#7#9#9Ke  tG{  H  HH % 2 2g>O>O]a>O>b>box 2 y y$ww11W=N=N\`=N=a=anv1wwOFCCB""b3=V"WWW!!R#<T!UUUIIKKKIbmmoo48888H   G! ! !H !$1V D D DC"S1%%% #**K 2273G3G3I3IJJFAb LL8999MM+,,,MM+&&&GGAbMMM  ,,..4Q7I 33G4H4H4J4J1RU7S\K\]]FBsMM:;;;NN;'''NN;'''HHR #55g6I6I6K6KAbeGT]L]^^HCMM:;;;NN;'''NN;'''HHSWT!""X&&&Ict,,,,,,  	4 	4 	4H.S::::H  A  A  AH(//22333333333	4s   Z7Z; ;
\!A\\!N)r
   )__name__
__module____qualname__r   r    r   r   r	   r	      s<           
p4 p4 p4 p4 p4r   r	   )pandasrB   	streamlitr?   hydralitr   matplotlib.pyplotrU   rZ   numpyrJ   
hotstepperr   r   hs	itertoolsr   r   SIG_FIGURE_FMTr	   r   r   r   <module>r      s            ! ! ! ! ! !               ! ! ! ! ! ! ! !                 x4 x4 x4 x4 x4| x4 x4 x4 x4 x4r   