a
    ”"©bíP  ã                   @   s   d Z ddlZddlZddlmZ e d¡ejdd„ ƒƒZe d¡ej	dd	d
e
dd�ej	ddd
e
dd�e d¡e d¡dd„ ƒƒƒƒƒZe d¡ej	ddddd�ej	ddddd�e d¡ejdd„ ƒƒƒƒƒZe d¡e d¡ejdd „ ƒƒƒZe d!¡ej	dd"d#d$d�ej	dd%d&d'd�ej	dd(d
d)d�ej	d*d+g d,¢d-e
d.d/�ej	d0d1ded2d�e d3¡e d4¡ejd5d6„ ƒƒƒƒƒƒƒƒƒZe d7¡ej	dd(d
d)d�ej	d*d+g d,¢d-e
d.d/�e d3¡e d8¡ejd9d:„ ƒƒƒƒƒƒZe d;¡ej	dd	d<dd�ej	ddd=dd�ej	d>d?d@dAd�ej	dBdCddDd�ej	dEdFdGdHd�ej	dIdJedKd�ej	dLdMdNdOd�ej	dPd=dQd�ej	dRdSdTd�ej	dd(dUdVd�ej	d*d+g d,¢d-e
d.d/�ej	dWdXdYd�ej	dZd[d\d�ej	d]ded^d�ej	d_d`edad�e d3¡e d8¡ejdbdc„ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒZe dd¡ej	dBdeddfd�ej	dgdhdid�ej	djdkdld�e dm¡e dn¡e do¡ejdpdq„ ƒƒƒƒƒƒƒƒZe dr¡ej	dsde
dtd�ej	djdkdld�ej	dudvdwd�ej	dxdydzd�e d{¡e do¡ejd|d}„ ƒƒƒƒƒƒƒƒZe d~¡ej	djdkdld�ej	dudvdwd�ej	dd€d�d�ej	d]dd‚d�e d{¡e do¡ejdƒd}„ ƒƒƒƒƒƒƒƒZe d„¡e d{¡e do¡ejd…d†„ ƒƒƒƒZe d‡¡ej	dd	dˆdd�ej	ddd=dd�ej	d>d?d@dAd�ej	dEd‰dJdKd�e dŠ¡ejd‹dŒ„ ƒƒƒƒƒƒƒZe d�¡ej	dŽd�d�d‘d�e d’¡e d“¡ejd”d•„ ƒƒƒƒƒZe d–¡e d’¡e d“¡ejd—d•„ ƒƒƒƒZe d˜¡e d™¡e dŠ¡ejdšd›„ ƒƒƒƒZe dœ¡ej	d>d�džedŸd�ej	dd d¡ed¢d�ej	dd£d¤d¥d�e d¡e do¡ejd¦d§„ ƒƒƒƒƒƒƒZd¨d©„ Zdªek�rüeƒ  dS )«z@
Export wirecell.sigproc functionality to a main Click program.
é    N)ÚunitsÚsigprocc                 C   s   dS )z.
    Wire Cell Signal Processing Features
    N© )Úctxr   r   ú=/home/yuhw/wc/wire-cell-python-pr-11/wirecell/sigproc/main.pyÚcli   s    r   Úfr2npzz-gz--gainç        zSet gain in mV/fC.)ÚdefaultÚtypeÚhelpz-sz	--shapingzSet shaping time in us.z	json-fileznpz-filec           	      C   s€   ddl m  m  m} ddlm  m  m} ddl}| |¡}| tj	tj
 9 } |tj9 }| || |¡}|j|fi |¤Ž dS )a¥  
    Convert field response file to numpy (.json or .json.bz2 to .npz)

    If gain and shaping are non zero then convolve each field response
    function with the corresponding electronics response function.

    Result holds a number of arrays and scalar values.

    Arrays:

        - resp[012] :: one 2D array for each plane.  A wire region is
          10 pixels wide.  Each row of pixels represents the average
          field response between the two original drift paths bounding
          the row.  The 2D array also makes explicit the
          flipped-symmetry that the original field response file
          leaves implicit.  The columns mark time.  Note, to make a
          per-wire sub-array of all impact rows #3 (counting from 0)
          you can use Numpy indexing like: dat['resp2'][3::10,:]

        - bincenters[012] :: the pitch location in mm of the row
          centers

        - pitches :: the nominal wire pitch for each plane as used in
          the Garfield simulation.

        - locations :: the locations along the drift direction of each
          of the planes.

        - eresp :: electronics response function, if gain/shaping given

        - espec :: the FFT of this, if gain/shaping given

    Scalar values:

        - origin :: in mm of where the drifts start in the same axis
          as the locations

        - tstart :: time when drift starts

        - period :: the sampling period in ns of the field response
          (ie, width of resp columns)

        - speed :: in mm/ns of the nominal electron drift speed used
          in the Garfield calculation.

        - gain : the passed in gain

        - shaping :: the passed in shaping time

    r   N)Ú!wirecell.sigproc.response.persistr   ÚresponseÚpersistÚ wirecell.sigproc.response.arraysÚarraysÚnumpyÚloadr   ÚmVÚfCÚusZ	fr2arraysÚsavez)	ÚgainÚshapingÚ	json_fileZnpz_fileÚperÚarrsr   ÚfrÚdatr   r   r   r      s    :

Úfrzeroz-nz--numberz6Number of strip to keep, default keeps just zero strip)r
   r   z-oz--outputz/dev/stdoutz1Output WCT file (.json or .json.bz2, def: stdout)Úinfilec              	   C   sÀ   ddl m  m  m} ddlm  m  m} | |¡}|jD ]n}|jD ]b}t	|j
|j ƒ}	t|	ƒ|krŠtd|	› d|j
› d|j› �ƒ qJt|jƒ}
t|
ƒD ]}d|j|< qœqJq@| ||¡ dS )zK
    Given a WCT FR file, make a new one with off-center wires zeroed.
    r   Nzkeep wire: z
, pitch = z / )r   r   r   r   r   r   r   ÚplanesÚpathsÚintÚpitchposÚpitchÚabsÚprintÚlenÚcurrentÚrangeÚdump)r   ZnumberÚoutputr    r   r   r   ÚprÚpathZwireZncÚindr   r   r   r   V   s    



zresponse-infoc              
   C   s¨   ddl m  m  m} | |¡}td|jtj |j	tj
 |jtj
 |jtjtj
  |jd |jd |jd f ƒ |jD ](}td|j|jtj |jtj f ƒ qzdS )zJ
    Show some info about a field response file (.json or .json.bz2).
    r   NzWorigin:%.2f cm, period:%.2f us, tstart:%.2f us, speed:%.2f mm/us, axis:(%.2f,%.2f,%.2f)é   é   z(	plane:%d, location:%.4fmm, pitch:%.4fmm)r   r   r   r   r   r'   Úoriginr   ÚcmÚperiodr   ZtstartÚspeedZmmZaxisr!   ZplaneidÚlocationr%   )r   r   r   r   r-   r   r   r   Úresponse_infor   s    
Hÿ
ÿr7   zconvert-garfieldz--originz10.0*cmz*Set drift origin (give units, eg '10*cm').z--speedz1.114*mm/usz7Set nominal drift speed (give untis, eg '1.114*mm/us').z--normalizationzHSet normalization: 0:none, <0:electrons, >0:multiplicative scale.  def=0z-zz--zero-wire-locs)r	   r	   r	   é   z'Set location of zero wires.  def: 0 0 0)r
   Únargsr   r   z-dz--delayzASet additional delay of bins in the output field response.  def=0zgarfield-filesetzwirecell-field-response-filec                 C   sz   ddl m  m} ddlm}	 ddlm  m  m}
 t|t	j
ƒ}t|t	j
ƒ}| ||||¡}|	|||ƒ}|
 ||¡ dS )zž
    Convert an archive of a Garfield fileset (zip, tar, tgz) into a
    Wire Cell field response file (.json with optional .gz or .bz2
    compression).
    r   N)Úrf1dtoschema)Úwirecell.sigproc.garfieldr   ÚgarfieldÚwirecell.sigproc.responser:   r   r   r   Úevalr   Ú__dict__r   r+   )r   r2   r5   ÚnormalizationÚzero_wire_locsZdelayÚgarfield_filesetZwirecell_field_response_fileÚgarr:   r   Zrflistr   r   r   r   Úconvert_garfield�   s    rD   zplot-garfield-exhaustiveÚpdffilec                 C   sB   ddl m  m} | |||¡}ddlm  m} | ||¡ dS )z2
    Plot all the Garfield current responses.
    r   N)r;   r   r<   r   Úwirecell.sigproc.plotsÚplotsZgarfield_exhaustive)r   r@   rA   rB   rE   rC   r   rG   r   r   r   Úplot_garfield_exhaustive£   s    rH   zplot-garfield-track-responseg      ,Àg       @z-tz--tickg      à?z1Set tick time in us (0.1 is good for no shaping).z-pz--tick-paddingz1Number of ticks of zero ADC to pre-pad the plots.z-ez--electronsiô3  z.Set normalization in units of electron charge.z--elec-typeZcoldz/Set electronics type [cold | warm] (def: cold).z-az
--adc-gaing333333ó?zSet ADC gain (unitless).z--adc-voltagezSet ADC voltage range in Volt.z--adc-resolutioné   zSet ADC resolution in bits.éÿÿÿÿzISet normalization: 0:none, <0:electrons, >0:multiplicative scale.  def=-1z--yming      DÀz	Set Y minz--ymaxg      N@z	Set Y maxz	--regionsz0Set how many wire regions to use, default to allz--dump-dataÚ zMDump the plotted data in format given by extension (.json, .txt or .npz/.npy)c           !         s0  ddl m  m} ddlm  m} ddlm  m} |tjtj	 9 }|tj
9 }|tj
9 }|tj9 }|d9 }|tj9 }d|	> }	||	 | }| ||
|¡}ˆ rºtdˆ  ƒ ‡ fdd„|D ƒ}| ||¡}d}d	|v rÖd
}d|v râd}td| ƒ ttdd„ |D ƒƒƒd }d}|j|||||||||||d�\}}td| ƒ | |¡ |�r,td| ƒ | d¡�rxddl}| ||¡ | d¡�r˜ddl}| ||¡ | d¡�rút|dƒ�:}|D ]$}d tt|ƒ¡}| |d ¡ �q´W d  ƒ n1 �sð0    Y  | d¡�r,ddl} t|dƒ | j| ¡ dd�¡ dS )zÌ
    Plot Garfield response assuming a perpendicular track.

    Note, defaults are chosen to reproduce the "ADC Waveform with 2D
    MicroBooNE Wire Plane Model" plot for the MicroBooNE noise paper.
    r   Ng      ð?r0   zLimiting to %d regionsc                    s"   g | ]}t |jƒtˆ ƒv r|‘qS r   )r&   Úregionr*   ©Ú.0Úr©Úregionsr   r   Ú
<listcomp>õ   ó    z0plot_garfield_track_response.<locals>.<listcomp>rK   Zub_Z
MicroBooNEZdune_ZDUNEzUsing detector hints: "%s"c                 S   s   g | ]}t |jƒ‘qS r   )r&   rL   rM   r   r   r   rR      rS   )ÚtickÚ	elec_typeÚadc_per_voltageÚdetectorÚyminÚymaxÚmsgÚtick_paddingzplotting to %szdumping data to %sz.npzz.npyz.txtZwtú	Ú
z.jsoné   ©Zindent) r;   r   r<   r=   r   rF   rG   r   r   r   r   ÚeplusZvoltr   r'   Úliner(   ÚsetZplot_digitized_lineÚsavefigÚendswithr   r   ZsaveÚopenÚjoinÚmapÚstrÚwriteÚjsonÚdumpsÚtolist)!r   r   r   rT   r[   Z	electronsrU   Zadc_gainZadc_voltageZadc_resolutionr@   rA   rX   rY   rQ   Z	dump_datarB   rE   rC   ÚresrG   rV   r   ZuvwrW   ZnwiresrZ   ÚfigÚdatar   Úfpra   rj   r   rP   r   Úplot_garfield_track_responseµ   sd    .




ú

2rq   zplot-response-compare-waveformsz--planeZPlanez--irangeÚ0z(Impact range as comma separated integersz--trangez0,70z-Set time range in us as comma pair. def: 0,70Úresponsefile1Úresponsefile2Úoutfilec              	      sº   ddl m  m  m‰ ddlm  m  m‰ tttˆ 	d¡ƒƒ‰tttˆ 	d¡ƒƒ‰ddg‰ ddg‰ddl
m‰ ddl‰‡ ‡‡‡‡‡‡‡‡f	dd„}||dƒ ||d	ƒ ˆ |¡ dS )
z6
    Plot common response waveforms from two sets
    r   Nú,ZredZblueZsolidc           
         sð   ˆ  | ¡}|jˆ }tˆ | › d| › dˆ› dt|jƒ› d�ƒ ˆD ]¨}|j| }ˆ |j¡|j }|jtj	 }|tj
 }td|› d|jd›dt|jƒ› d|d›d	|d›d
�ƒ ˆ ¡ jˆŽ  ˆ |ˆ¡}	ˆj|	tj	 |jˆ | ˆ| d� qBd S )Nú z: plane=z paths:r\   z: Úfz samples, dt=z.3fz	 us, tot=z
 electrons)ZcolorZ	linestyle)r   r!   r'   r(   r"   Úsumr)   r4   r   r   r`   r$   ZgcaZset_xlimZtime_linspaceZplot)
ZrfileÚnr   r-   r/   r.   Ztot_qZdt_usZtot_esÚtimes©	ZcolorsÚiranger   r   ÚplanerG   ZpltZstylesÚtranger   r   Ú
plot_paths;  s    

*

6z3plot_response_compare_waveforms.<locals>.plot_pathsr0   )r   r   r   r   Úwirecell.sigproc.response.plotsrG   Úlistrg   r#   ÚsplitZmatplotlib.pyplotZpyplotr   rc   )r   r~   r}   r   rs   rt   ru   r€   r   r|   r   Úplot_response_compare_waveforms!  s    

r„   zplot-responsez--regionz2Set a region to demark as 'electrode 0'. def: nonez--titlez	Response:zAn initial distinguishing titlez--reflect/--no-reflectTzApply symmetry reflectionÚresponsefilec           
      C   sf   ddl m  m  m} ddlm  m  m} ttt| 	d¡ƒƒ}| 
|¡}	| |	|||||¡ dS )z#
    Plot per plane responses.
    r   Nrv   )r   r   r   r   r�   rG   r‚   rg   r#   rƒ   r   Zplot_planes)
r   r…   ru   rL   r   ÚtitleZreflectr   rG   r   r   r   r   Úplot_responseR  s
    
r‡   zplot-response-conductorsz--log10/--no-log10Fz$Use 'signed log10' else linear scalez/Comma separated list of regions, default is allc           
      C   s~   ddl m  m  m} ddlm  m  m} ttt| 	d¡ƒƒ}|r\ttt| 	d¡ƒƒ}| 
|¡}	| |	|||||¡ dS )z5
    Plot per-conductor (wire/strip) respnonses.
    r   Nrv   )r   r   r   r   r�   rG   r‚   rg   r#   rƒ   r   Zplot_conductors)
r   r   r†   Zlog10rQ   r…   ru   r   rG   r   r   r   r   r‡   j  s    
zplot-spectrac                 C   sJ   ddl m  m  m} ddlm  m  m} | |¡}| ||¡ dS )z*
    Plot per plane response spectra.
    r   N)r   r   r   r   r�   rG   r   Z
plot_specs)r   r…   ru   r   rG   r   r   r   r   Úplot_spectra…  s    
rˆ   zplot-electronics-responseg      ,@z
--electypeÚplotfilec                 C   sT   |t jt j 9 }|t j9 }|t j9 }ddlm  m} | ||||¡}| |¡ dS )z1
    Plot the electronics response function.
    r   N)	r   r   r   r   rF   r   rG   Zone_electronicsrc   )r   r   r   rT   Zelectyper‰   rG   rn   r   r   r   Úplot_electronics_response”  s    

rŠ   zconvert-noise-spectraz-fz--formatÚmicroboonev1zFormat of input fileÚ	inputfileÚ
outputfilec           
      C   s�   d}|dkrddl m} |}n2|dkr8ddlm} |}n|dkrPddlm} |}|slt d	| ¡ t d
¡ ||ƒ}ddl	m
}	 |	 ||¡ dS )zS
    Convert an file of noise spectra in some external format into WCT format.
    Nr‹   r   )Úload_noise_spectra_v1zicarusv1-incoherent)Úload_noise_spectrazicarusv1-coherent)Úload_coherent_noise_spectraúUnknown format: "%s"r0   ©r   )Z!wirecell.sigproc.noise.microboonerŽ   Zwirecell.sigproc.noise.icarusr�   r�   ÚclickÚechoÚsysÚexitÚwirecell.sigproc.noiser   r+   )
r   ÚformatrŒ   r�   ÚloaderrŽ   r�   r�   Úspectrar   r   r   r   Úconvert_noise_spectra«  s     

r›   zconvert-electronics-responsec                 C   sP   ddl m} |}|s,t dt ¡ t d¡ ||ƒ}ddl m} | ||¡ dS )zc
    Convert a table of electronics response function in some external format into WCT format.
    r   )Úload_text_electronics_responser‘   r0   r’   N)	r=   rœ   r“   r”   r˜   r•   r–   r   r+   )r   rŒ   r�   rœ   r™   Zelecrespr   r   r   r   r›   É  s    
zplot-noise-spectraÚspectrafilec                 C   s*   ddl m}m} | |¡}| ||¡ dS )zq
    Plot contents of a WCT noise spectra file such as produced by
    the convert-noise-spectra subcommand.
    r   )r   rG   N)r—   r   rG   r   Z	plot_many)r   r�   r‰   r   rG   rš   r   r   r   Úplot_noise_spectraÜ  s    	
rž   zchannel-responsesz--tscalez0.5*usz$Scale of time axis in the histogram.z--scalez1e-9*0.5/1.13312zScale applied to the samples.z--nameZpResponseVsChz3Data name (eg, the TH2D name if using 'hist' schemac                 C   s�  ddl }ddl}ddl}ddlm}	 t|tjƒ}t|tjƒ}|j 	t
|ƒ¡}
|
sTJ ‚|
 t
|ƒ¡}|s‚t d||f ¡ t d¡ |	|dd�\}}||9 }|d }||dd…  \}}|| }|j\}}tƒ }t|ƒD ]4}d	d
„ ||dd…f  ¡ D ƒ}||g}| |¡ qÖt|||d�}|j|dd�}| d¡�rRddl}| |d¡ |¡ dS | d¡�r|ddl}| |d¡ |¡ dS t|dƒ |¡ dS )aò  Produce the per-channel calibrated response JSON file from a TH2D
    of the given name in the input ROOT file provided by the analysis.

    - tscale :: a number to multiply to the time axis of the histogram
      in order to bring the result into the WCT system of units.  It
      may be expressed as a string of an algebraic expression which
      includes symbols, eg "0.5*us".

    - scale :: a number multiplied to all samples in the histogram in
      order to make the sample value a unitless relative measure.  It
      may be expressed as a string of an algebraic expression which
      includes symbols, eg "0.5*us". For uBoone's initial
      20171006_responseWaveforms.root the appropriate scale is
      1e-9*0.5/1.13312 = 4.41267e-10
    r   N)Ú
hist2arrayz$Failed to get histogram "%s" from %sr0   T)Zreturn_edgesr1   c                 S   s   g | ]}t d | ƒ‘qS )z%.6g)Úfloat)rN   Úxr   r   r   rR     rS   z%channel_responses.<locals>.<listcomp>)rT   Út0Úchannelsr^   r_   z	.json.bz2Úwz.json.gzÚwb)rj   ÚROOTr   Z
root_numpyrŸ   r>   r   r?   ZTFileZOpenrh   ZGetr“   r”   r•   r–   Úshaper‚   r*   rl   ÚappendÚdictrk   rd   Úbz2ÚBZ2Fileri   Úgzipre   )r   ZtscaleZscaleÚnamer    ru   rj   r¦   r   rŸ   ZtfÚhZarrZedgesZtedgesr¢   Út1rT   ZnchansZnticksr£   Úchrm   Zoner   Zjtextrª   r¬   r   r   r   Úchannel_responsesë  sF    

r±   c                   C   s   t tƒ d� d S )N)Úobj)r   r©   r   r   r   r   Úmain3  s    r³   Ú__main__)Ú__doc__r•   r“   Úwirecellr   ÚgroupZpass_contextr   ZcommandÚoptionr    Zargumentr   r   r7   r#   rD   rH   rh   rq   r„   r‡   rˆ   rŠ   r›   rž   r±   r³   Ú__name__r   r   r   r   Ú<module>   s²  ÿÿ=
ÿþ
ÿ
ÿ
ÿÿÿ
ÿÿ

ÿ
ÿ
ÿ
ÿ
ÿ
ÿ
ÿÿÿ
ÿÿÿÿ
ÿ
ÿ.J
ÿÿÿ&
ÿÿÿÿÿÿÿÿ
ÿ
ÿ
ÿ
ÿ
ÿÿÿ
ÿ>
