
    5iI                        d dl mZmZmZm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mZmZmZmZmZ ddlmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ d
Z dZ!d Z"d Z#i dfdZ$ddZ%d Z&d Z'd Z(d Z)g dfdZ*ddZ+d Z,y)    )print_functionunicode_literalsdivisionabsolute_importN   )get_field_from_jborget_job_from_jborget_index_from_jbor
is_job_refjob_output_to_str
JOB_STATES)GREENBLUEBOLDENDCfill)is_localjob_id   )
basestring)file_load_utilsw
c                     | dz  } | dt        t        j                  j                  d            z   z  } t	        j
                  |        y)z
    :param msg: string message to print before exiting

    Print the error message, as well as a blurb on where to find the
    job workspaces
    r   z&Local job workspaces can be found in: DX_TEST_JOB_HOMEDIRSN)strosenvirongetsysexit)msgs    }/home/marpiech/ifpan-abm-pgxpred/analysis/marpiech-gwas-test/venv/lib/python3.12/site-packages/dxpy/utils/local_exec_utils.pyexit_with_errorr#   !   s;     4KC3c"**..I_:`6aaaCHHSM    c                 L   g }| D ]k  }t        | |         r t        | |         j                  d      s/ yt        | |   t              st        | |   t
              sX|j                  | |          m t        |      dkD  r#|j                         }t        |t              rt        t        |            D ]k  }t        ||         r t        ||         j                  d      s/ yt        ||   t              st        ||   t
              sX|j                  ||          m np|D ]k  }t        ||         r t        ||         j                  d      s/ yt        ||   t              st        ||   t
              sX|j                  ||          m t        |      dkD  r#y)z
    :param io_hash: input/output hash
    :type io_hash: dict
    :returns: boolean indicating whether any job-based object references are found in *io_hash*
    localjobTr   F)
r   r	   
startswith
isinstancelistdictappendlenpoprange)io_hashqfieldthingis        r"   has_local_job_refsr4   ,   si    	A %gen% 0;;JG-GEND1QHHWU^$% a&1*eT"3u:& 'eAh'(q2==jI#a$/:eAh3MHHU1X&'  +eEl+(u6AA*M#ed3z%,PT7UHHU5\*+ a&1*" r$   Tc                 "  	 t        |       }t        |       t        |       		fd}t        |      rO|j	                  |      |rt        d|z   dz         | S ||   vrt        d|z   dz   z   dz          |||         S t        j                  |      }	 |j                          |j                         }|d
   vrt        d|z   dz   z   dz          ||d
         S # t
        $ r"}t        d|z   d	z   t        |      z         d}~ww xY w)a  
    :param jbor: a dict that is a valid job-based object reference
    :type jbor: dict
    :param job_outputs: a dict of finished local jobs to their output hashes
    :type job_outputs: :class:`collections.OrderedDict`
    :returns: the referenced value if present
    :raises: :exc:`Exception` if the job-based object reference cannot be resolved

    TODO: Support metadata references
    c                 "    |    S |       S N )output_hashref_job_fieldref_job_indexs    r"   resolve_from_hashz*resolve_job_ref.<locals>.resolve_from_hash\   s$     }--}-m<<r$   NJob z! not found in local finished jobsz"Cannot resolve a JBOR with job ID z because field "z" was not found in its outputCould not wait for z to finish: output)r	   r   r
   r   r   	ExceptiondxpyDXJobwait_on_doner   describe)
jborjob_outputsshould_resolve
ref_job_idr<   dxjobejob_descr:   r;   s
           @@r"   resolve_job_refrL   N   s]    #4(J'-M'-M=
 j!??:&. 36Y YZZJ 77@:MPbberr  vU  U  V  V Z!899

:&	Z  >># 22@:MPbberr  vU  U  V  V (!344  	Z1J>ORUVWRXXYY	Zs   C# #	D,D		Dc                    g }| D ]_  }t        | |         rt        | |   ||      | |<   %t        | |   t              st        | |   t              sL|j                  | |          a t        |      dkD  r|j                         }t        |t              rwt        t        |            D ]_  }t        ||         rt        ||   ||      ||<   %t        ||   t              st        ||   t              sL|j                  ||          a nd|D ]_  }t        ||         rt        ||   ||      ||<   %t        ||   t              st        ||   t              sL|j                  ||          a t        |      dkD  ryy)a  
    :param io_hash: an input or output hash in which to resolve any job-based object references possible
    :type io_hash: dict
    :param job_outputs: a mapping of finished local jobs to their output hashes
    :type job_outputs: dict
    :param should_resolve: whether it is an error if a job-based object reference in *io_hash* cannot be resolved yet
    :type should_resolve: boolean

    Modifies *io_hash* in-place.
    r   N)	r   rL   r(   r)   r*   r+   r,   r-   r.   )r/   rF   rG   r0   r1   r2   r3   s          r"   resolve_job_referencesrN   u   sX    	A %gen%,WU^[.YGEN-GEND1QHHWU^$	% a&1*eT"3u:& 'eAh'.uQxnUE!Ha$/:eAh3MHHU1X&	'  +eEl+#25<n#]E%Led3z%,PT7UHHU5\*	+ a&1*r$   c                    d }t        | t              rDd| v r@t        | d   t              r| d   }n't        | d   t              r| d   j                  d      }|y t	        j
                  |      }|j                  d      dk7  r|S y )Nz$dnanexus_linkidstateclosed)r(   r*   r   r   rA   rD   )r2   obj_idobj_descs      r"   get_nonclosed_data_obj_linkrU      s    F%#3u#<e,-z:+,F./6+,006F~}}V$H||G( )r$   c                    g }| D ]_  }t        | |         }||j                  |       %t        | |   t              st        | |   t              sL|j                  | |          a t        |      dkD  r|j                         }t        |t              rwt        t        |            D ]_  }t        ||         }||j                  |       %t        ||   t              st        ||   t              sL|j                  ||          a nd|D ]_  }t        ||         }||j                  |       %t        ||   t              st        ||   t              sL|j                  ||          a t        |      dkD  ryy)zS
    Add DNAnexus links to non-closed data objects in input_hash to depends_on
    Nr   )rU   r+   r(   r)   r*   r,   r-   r.   )
input_hash
depends_onr0   r1   possible_depr2   r3   s          r"   get_implicit_depends_onrZ      s]    	A (2:e3DE#l+
5)40Jz%?PRV4WHHZ&'( a&1*eT"3u:& ':58D+%%l3a$/:eAh3MHHU1X&'  +:5<H+%%l3ed3z%,PT7UHHU5\*+ a&1*r$   c                    t        |       dkD  rt        t        d             | D ]  }	 t        d|z   dz          |j                  d      r"|j	                  |      }t        d|z   dz         |j                  d      r&t        j                  |      }|j                          n5t        j                  |      }|j                         }|j                           y y # t
        $ r"}t        d	|z   d
z   t        |      z         d }~ww xY w)Nr   zKProcessing dependsOn and any DNAnexus links to closing objects in the inputz  Waiting for z...r&   r=   z* could not be found in local finished jobsjobr>   : )r,   printr   r'   r   r@   rA   rB   rC   get_handlerrD   _wait_on_closer   )rX   all_job_outputsan_idrI   handlerdescrJ   s          r"   wait_for_depends_onre      s   
:d`ab 	OEO&.67##J/&**519'9e(eff%%e, JJu-E&&("..u5G"++-D**,	O   O 5 = Ds1v MNNOs   B0C	D&DDc                  n    dD ]0  } | t         j                  vst        j                  d| z   dz          2 y )N)
DX_FS_ROOTDX_TEST_CODE_PATHr   zEError: Cannot run an entry point locally if the environment variable z has not been set)r   r   r   r    )vars    r"   ensure_env_varsrj      s<    ( z bjj HH\_bbexxy	zr$   c                 &   t                t        j                  j                  t        j                  d   d      }t        |d      5 }t        j                  |t        j                        }dt        t        |            z   }ddd       t        |t              5 }d<   t        j                  ||d       |j                  t               ddd       t        j                  j                  t        j                  d         }t        j                   |       t        j                  j                  t        j                  d   d	      }	t        |	d      5 }t        j                  |      }
ddd       || ||d
}|||d<   
j#                  |       t        |	t              5 }t        j                  |
|d       |j                  t               ddd       |S # 1 sw Y   ]xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   |S xY w)a  
    :param function: function to run
    :param input_hash: input to new job
    :param depends_on: list of data object IDs and/or job IDs (local or remote) to wait for before the job can be run
    :type depends_on: list of strings
    :param name: job name (optional)
    :returns: new local job ID

    This function should only be called by a locally running job, so
    all relevant DX_TEST_* environment variables should be set.

    This function will set up the home directory for the job, add an
    entry in job_outputs.json, and append the job information to the
    job_queue.json file.  (Both files found in
    $DX_TEST_JOB_HOMEDIRS.)
    r   job_outputs.jsonrobject_pairs_hookz	localjob-N   indentjob_queue.json)rP   functionrW   rX   name)rj   r   pathjoinr   openjsonloadcollectionsOrderedDictr   r,   
write_modedumpwriteeolmkdirr+   )rt   rW   rX   ru   all_job_outputs_pathfdra   job_idjob_homedirjob_queue_path	job_queue	job_entrys               r"   queue_entry_pointr      s   " 77<<

3I(JL^_	"C	( 9B))B+:Q:QRs3#7889 
"J	/ 2"&		/2a0

 '',,rzz*@A6JKHH[WW\\"**-C"DFVWN	nc	" "bIIbM	"%))+I  	&Y	nj	) R		)R*
 M59 9 " " Ms0   =G 3G-G:(.H G*-G7:HHc           
         t        d       t        j                  j                  t        j                  d   |       }t        j                  j                         }t        j                  j                  t        j                  d   |       |d<   t        j                  j                  t        j                  d   d      }t        |d      5 }	t        j                  |	t        j                        }
ddd       t        |t              r|d| z   d	z   |z   d
z   z  }n| d	z   |z   }t               t               z   |z   t               z   }t        |       	 t!        |
       |g }t-        ||       	 t/        |
       t        t        j                  j                  |d      d      5 }	t        j0                  ||	d       |	j3                  d       ddd       t        t5        |t               dz   t               z   t7        d            j9                                |d   dk(  rt        j                  j                  |d      }t        |d      5 }	t        j                  j                  |d      }t;        j<                  ||      }t?        |jA                               D ]&  \  }}|	j3                  djC                  ||             ( 	 ddd       t        t               dz   t               z          tD        jD                  jG                         }|d   dk(  rdjC                  tI        jJ                  |      tI        jJ                  t        j                  j                  |d   d            tI        jJ                  t        j                  d         |      }g dt        j                  jM                  d       rd!gng z   |gz   }n1|d   d"k(  r)d#jC                  tO        |      |d$   %      }||d&<   d'd(|g}|}tQ        jR                  |)      }|jU                          tD        jD                  jG                         }|jV                  d*k7  rEt%        |dz   t'        d      z   d+z   t+        |jV                        z   d,z   t+        ||z
        z          t        j                  j                  |d   d-      }t        j                  jY                  |      r<	 t        |d      5 }	t        j                  |	t        j                        }ddd       ni }t        |d1z   t]               z   d2z   t               z   d,z   t+        ||z
        z          t        t5        t               d3z   t               z   t7        d3            j9                                t        t        j                  j                  t        j                  d   d      d      5 }	t        j                  |	t        j                        }
ddd       |
| <   |
D ]  }|
|   	t!        |
|   |
d45        t        t        j                  j                  t        j                  d   d      t^              5 }	t        j0                  |
|	d       |	j3                  t`               ddd       y# 1 sw Y   xY w# t"        $ r=}t%        |dz   t'        d      z   dz   t)        t+        |            z          Y d}~d}~ww xY w# t"        $ r=}t%        |dz   t'        d      z   dz   t)        t+        |            z          Y d}~d}~ww xY w# 1 sw Y   dxY w# 1 sw Y   vxY w# 1 sw Y   ExY w# t"        $ rJ}t%        d.|z   d/z   t)        t+        |jZ                        d0z   t+        |      z         z          Y d}~d}~ww xY w# 1 sw Y   xY w# 1 sw Y   yxY w)6a  
    :param job_id: job ID of the local job to run
    :type job_id: string
    :param function: function to run
    :type function: string
    :param input_hash: input for the job (may include job-based object references)
    :type input_hash: dict
    :param run_spec: run specification from the dxapp.json of the app
    :type run_spec: dict

    Runs the specified entry point and retrieves the job's output,
    updating job_outputs.json (in $DX_TEST_JOB_HOMEDIRS) appropriately.
    z======r   HOMErl   rm   rn   Nz (:) failedz when resolving input:
z when processing depends_on:
zjob_input.jsonr   rp   rq   r   zInput: )title	title_leninterpreterbashenvironment)r   z{}={}
zLogs:a0  
          cd {homedir};
          . {env_path};
          . {code_path};
          if [[ $(type -t {function}) == "function" ]];
          then {function};
          else echo "$0: Global scope execution complete. Not invoking entry point function {function} because it was not found" 1>&2;
          firh   )homedirenv_path	code_pathrt   )r   -cz-eDX_TEST_X_FLAGz-xz	python2.7z#!/usr/bin/env python
import os
os.chdir({homedir})

{code}

import dxpy, json
if dxpy.utils.exec_utils.RUN_COUNT == 0:
    dxpy.run()
code)r   r   DX_TEST_FUNCTIONpythonr   )envr   z, exited with error code z after zjob_output.jsonz Error: Could not load output of z:
r]   z -> zfinished runningzOutput: F)rG   )1r^   r   rv   rw   r   copyrx   ry   rz   r{   r|   r(   r   r   r   r   rN   r@   r#   r   r   r   rZ   re   r~   r   r   r,   lstripr   gen_bash_varsr)   itemsformatdatetimenowshlexquoter   repr
subprocessPopencommunicate
returncodeexists	__class__r   r}   r   )r   rt   rW   run_specrX   ru   r   job_envr   r   ra   job_namerJ   r   job_input_filevar_defs_hashkeyval
start_timescriptinvocation_argsr   
fn_processend_timejob_output_path
job_outputother_job_ids                              r"   run_one_entry_pointr     s    
(O'',,rzz*@A6JKjjooGggll2::.D#EvNGFO77<<

3I(JL^_	"C	( SB))B+:Q:QRS $
#v#h.44|h&v%.H	(Okz?; 
J
3qJ8
 
bggll;(893	? 2		*b+
 

Jtv	/ADF/J&))n66<fh@ &(77<<];(C  	5BWW\\+7GHN+99.VabM !4!4!67 5S))#s345	5 
$&7
TV
#$""&&(J&( u{{;7 %BGGLL-,X Y!&RZZ8K-L!M (  * 	 /BJJNNK[<\4&bdeiohpp	-	 K	/	 F4$   " 	 '/"##T62
C!!/s;J  $$&H!3H)==@[[^ablbwbw^xx  |E  E  HK  LT  Wa  La  Hb  b  	c ggll76?4EFO	ww~~o&	|os+ Vr!YYr[=T=TU
V
 
	(V
eg
%(:
:TV
Ci
ORUV^akVkRl
lm	
Jtv
/BTV/K&)*o77=vxA 
bggll2::&<=?QRTW	X S\^))B+:Q:QRS(OF ( e<(0|<o^cd	e 
bggll2::&<=?QRT^	_ ce		/2a0
 _S S  k3H)==@ZZ]abefgbh]iijjk  q3H)==@``cghklmhncooppq 	5 	5fV V 	|>IEQTXY\]^]h]hYilpYpsvwxsyYyTzz{{	|S S s   &ZZ  0[) &*\2A:\?] #&]	] &^/.^<Z 	[&)2[!![&)	\/22\**\/2\<?]	]] 	^,"?^''^,/^9<_c           
         t         j                  j                  t         j                  d   d      }t         j                  j                  t         j                  d   d      }	 t	        |d      5 }t        j                  |      }ddd       t              dk(  ryt	        |d      5 }t        j                  |      }ddd       d}t        |      D ]I  \  }}d}	t        |d         r	 t        |d          t        |d         r|	s8|j                  |      } n ||j                  d      }t	        |t              5 }t        j                  ||       |j                  t               ddd       t!        |d
   |d   |d   | |j#                  dg       |j#                  d             N# 1 sw Y   .xY w# 1 sw Y   xY w#  d	}	Y xY w# 1 sw Y   gxY w)a
  
    :param run_spec: run specification from the dxapp.json of the app
    :type run_spec: dict

    Runs all job entry points found in
    $DX_TEST_JOB_HOMEDIRS/job_queue.json in a first-in, first-out
    manner until it is an empty array (or an error occurs).
    r   rs   rl   Trm   Nr   rW   FrP   rt   rX   ru   )r   rt   rW   r   rX   ru   )r   rv   rw   r   rx   ry   rz   r,   	enumerater4   rN   r-   r}   r~   r   r   r   r   )
r   r   r   r   r   ra   entry_point_to_runr3   entry_pointrunnables
             r"   run_entry_pointsr     s    WW\\"**-C"DFVWN77<<

3I(JL^_
.#& 	&"		"I	&y>Q&, 	,"iimO	, "'	2 	NA{H$[%>?*;|+DoV %[%>? %.]]1%5"	 % "+q!1.*- 	 IIi$HHSM		 	#5d#;%7
%C'9,'G%-'9'='=lB'O!3!7!7!?	AE 	& 	&
	, 	,$H	 	s0   0F2)F?+G,G2F<?G	GG)Tr7   )-
__future__r   r   r   r   r   r   ry   r   r   r{   r   rA   rD   r   r	   r
   r   r   r   printingr   r   r   r   r   resolverr   compatr    r   r}   r   r#   r4   rL   rN   rU   rZ   re   rj   r   r   r   r8   r$   r"   <module>r      s   " S R ' ' '  B B 5 5 $  

	 D ') %5N +D+<O(z 8: /bHT3Ar$   