B
    C[CaQ                 @   s"  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZ d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dlZd dlZd dlZ d dl!m"Z" d dl!m!Z! d d	l!m#Z# d d
l!m$Z$ dd Z%dd Z&dd Z'dd Z(dd Z)dd Z*dddZ+dS )    N)interpolate)Time)PdfPages)pyplot)convolveBox1DKernel)calc_targOlapf)calc_shk)old_calc_shk)old_hk_windowsc          	   C   s2   t | | t| | d}t|}W d Q R X |S )Nrb)create_flat_dict_fileopenpickleload)flatPath
flatPicklefflatDict r   0/home/travis/obs/LCO/nreshk/NRES_SHK_Pipeline.pyNRES_SHK_MkFlat-   s    
r   c          	   C   s  t  }|dt  i |dt  i |dt  i |dt  i xt| D ]\}}}x||D ]t}|drbtjjtj	
||}|d j}t|d }	|d }
|d	 }|tj	
||f}||
 }||	|i qbW qRW t| | d
}t|| W d Q R X d S )Ncpttlvlscelpz.fitsr   zMJD-OBSSITEIDNAXIS2wb)dictupdateoswalkendswithastropyiofitsr   pathjoinheaderfloatr   dump)ZflatDirfileNamer   r'   subdirsfilesnameZflHDu1r)   mjdsitenOrdtuplZsiteDictr   r   r   r   r   ;   s$    


r   c             C   s  d }t j| }|d d |d  }|d d |d  }| }tjj|}tjj|}|d jd }|d j}	t	|dkrt
|d tjjjjjkry|d jd d }
W q   |d jd d }
Y qX n*t	|dkr|d jd }
n|d jd }
t|
||	| d}|  |  |S )Nr   z-noflat   z-waveZWavelenStarZ
WavelengthT)r!   r'   splitextr$   r%   r&   r   datar)   lentypehdutableBinTableHDUhrawDataclose)obsFileNamer6   spltnoFlatwaver,   ZspecHDuZwvHDuspecr)   waveGridr   r   r   old_multifile_NRES_to_data]   s*    
&rE   c       
      C   s   g }g }g }d}d}d }t j| }|d d |d  }t j|rHd}|rTt| S tjj| }	|	d j	}|	d j	}|	d j
}t|||| |}|	  |S )N Fr   z-noflatr4   T   )r!   r'   r5   existsrE   r$   r%   r&   r   r6   r)   r<   r=   r>   )
r?   rD   rC   r)   r,   Z	oldFormatr6   ZsplitFrA   ZoHDur   r   r   load_obs_for_pipeline   s&    


rI   c          	   C   sj  | j }| j}ttj|}ddg}d}t|}| j}g }	xt|D ]}
|		ddg qBW d}|d |d  | d }|d |tj|tj
d	  }tj||ftj
d	}tj||ftj
d	}xftt|D ]V}t||d d f ||d d f< ||d d f ||t|d
 f  ||d d f< qW |d|d d f }tj||ftj
d	}g }xtt|D ]}
d||
d|	|
 d f< d||
|	|
 d d f< ttt||
d d f ||
d d f  tdtdtd||
d d f< qXW tjt|tj
d	}xPtt|D ]@}
tj|||
 d d f ||
d d f ddd}||| }qW |jdd}t|dkr`d}|||fS )Ng     w@g     @z@gMbP?iX  i  Fr4   r   )dtype      linearextrapolate)kind
fill_value)ming      ?T)rD   r2   nparanger<   lowGOrdr7   nxrangeappendfloat64zerosgradientintr   r   r   interp1dclipmax)rawflatlamhighOrdgOrdZlamRandLamZnGordrU   boundsibadnLamlamGridZdLambxscaleyZgFlatZsgFlatstuffflatOlap
interpfuncr   r   r   mk_flatolap   sB    "4P.ro   c             C   s   d S )Nr   )obsr   r   r   find_and_make_flat  s    rq   c	       5         s  d}	d}
t | }i }x|D ]}g }g }g }g }g }t |sTtd| d  q|dk	r||krr|dkrd}qt|d  qntj|| rt|d  qtd	 td
|  td	 |}	tj| |}tj|d dd}dd |D }tdt	t
|  x|D ]}t|  dkr&q
|dk	rFt j|krFq
 j|krVq
td |	 _| j } j} fdd| D }t |t j}|| d }tjjtj||}|d j}|  |dk	r jdkrq
|dkr jdkrd _t |}|d }|d } t | |}!tj|d d |d | |!d|
d}"t| |!|"}#t |d d |d | |!|
}$|$d }%y`|d ! j}|d | }&tdt	 j  x,t"t
|&D ]}'|&dk	r|&d |"|'< qW W n   Y nX t#| |! |#}(|(d })|(d }*d}+d},t $| |!}-|-t j%krJd}+|& j |,d7 },n&|d dkrp|& j d}+|,d7 },t ' | ||!|)|"d|+|#|
}.|.( }/|.j)}0t|.* d  t	|-  t j+dkrt,-| |%|.d! |+rtt	 j|,  q
|.jdkr|&|. n
|&|. q
W t.||	|%}t.||	|%}|| }t /|.(  g g g}1x.|D ]&}2|1d &|2j |1d &|2j0 qRW g }3|dkrt|.( |	 d" d#}4t12|4}3W dQ R X |dkrt|.( |	 d$ d%}4t13||4 W dQ R X t|.( |	 d& d%}4t13||4 W dQ R X |dkrt|.( |	 d$ d%}4t13|3|4 W dQ R X t|.( |	 d& d%}4t13||4 W dQ R X ||3 }t|.( |	 d" d%}4t13||4 W dQ R X t| t,4|| |5|	|i qW |S )'a  Main NRES SHK Function with various options to create time-series for input stars.

    dataPath- location of data folder

    outputPath- location of output folder

    flatDict- dictionary of flat files created with create_flat_dict_file

    lab- reference spectra to align against

    skip- List of MJD's to skip due to bad data or testing

    forceRun- stars to run even if they have an output folder already

    manualAdj- list of MJD's coupled with 4 offsets(analyzedData.offset) to manually adjust bad shifting

    only- If it exists, the pipeline will ignore observations with MJD's not in this list
    new68- 9/19/2020 Temporary variable to test 67/68 order differences
    rF   g{Gz?zbad folder ''Nr   z is not in force runz already has outputzN++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++zRunning pipeline on HD z//**//*-e91.fitsT)	recursivec             S   s   g | ]}d |kr|qS )outputr   ).0rr   r   r   
<listcomp>j  s    z%NRES_SHK_Pipeline.<locals>.<listcomp>zNumber of observations: zO-------------------------------------------------------------------------------c                s$   i | ]\}}|d   j kr||qS )r   )r2   )ru   keyvalue)obsRawr   r   
<dictcomp>  s    z%NRES_SHK_Pipeline.<locals>.<dictcomp>r4   C   D   
   rL   )rj   smoothzmanual offset for mjd Fz Bad: z bad spec detector.rK   z bad flat. z with bad ratio: g333333?z.pklr   z_O67.pklr   z_N68.pkl)6r<   get_immediate_subdirectoriesis_folder_starprintr!   r'   rH   r(   globstrr7   rI   rR   floorr0   starr1   r2   items
closestKeyr*   r$   r%   r&   r   r6   r>   ro   r   pipefind_window_offsetscreate_integration_windowscalc_del_lamindexrV   r	   bad_spec_detection_v2maxNoiseRatiorW   analyzedDatastarDir	decimalYrlabelpdfModeplotpdf_from_intermediate_datasum_daily_datamkdir_pshkr   r   r+   plot_timeseriesr    )5dataPath
outputPathr   labskipZforceRunZ	manualAdjonlyZnew68starNameresstarsZstarDatasZobsFilesZanalyzed_67Zanalyzed_68ZanalyzedZbadDrf   ZstarPathZobsUnr?   ZfDr2   ZflatSubZfKZflatFilePathZfHDur`   ZflatRetrm   ri   	targOlapfoffsetsZintegrationWinsZlaboutlabSpecZoffsoshkRetr   windowsZbadSpecZ	badReasonZ
noiseRatiooData	outputDirr   tdoldr   r   )rz   r   NRES_SHK_Pipeline0  s    








"






r   )NN),sysr!   shutilr   loggingr   pprintastropy.io.fitsr$   timeZscipy.constants	constantsscnumpyrR   scipyr   astropy.timer   matplotlib.backends.backend_pdfr   
matplotlibr   pltastropy.convolutionr   r   helpersr<   pipeliner   plottingr   r	   r   r
   r   r   r   rE   rI   ro   rq   r   r   r   r   r   <module>   s:   ",+d