<?php

////Daniel Sobral
/// Obtains indirect evidence from analysis of regulatory region and morpholinos

/////////////////////////SIMPLIFY HIERARCHY
function simplify_hierarchy($hierarch,$root,$leaf_lsts,$region_lst){

	$ret_list = (array) null;	
	$expand_list = (array) null;
	foreach($region_lst as $region){ 
		if(isset($leaf_lsts[$region])){	$expand_list = array_merge($expand_list,$leaf_lsts[$region]); }
	}
	$parent_list = array($root);

	while(count($expand_list)>0){
		$child_list = (array)null;
		foreach ($parent_list as $cur_anat){	
			$cur_leafs = (array)null;	
			if(isset($leaf_lsts[$cur_anat])) { $cur_leafs = $leaf_lsts[$cur_anat]; }
			if(count(array_intersect($cur_leafs,$expand_list))>=count($cur_leafs)){
				$ret_list[]=$cur_anat;
			} else { 
				if(isset($hierarch[$cur_anat])){
					$child_list = array_merge($child_list, $hierarch[$cur_anat]);	
				}
			}
		}
		if(count($child_list)==0){ 	break; }
		$parent_list = $child_list;
	}		
	return $ret_list;
}	
/////////////////////////SIMPLIFY HIERARCHY
include("../constant.php");
$c=pg_connect("host=$hostAniseed dbname=$dbnameAniseed user=$userSuperAniseed password=$passwordSuperAniseed") or die("<h3>NO CONNECTION</h3>");

print '<html>';
print '<title>Calculate Indirect Evidence for Regulation Events Using Regulatory Region Data</title>';

print '<body>';

ini_set("memory_limit","128M");

//$stmt = pg_query($c,"BEGIN");
//Erase previous data!
//$khoueiry = "DELETE * FROM \"REG_EVIDENCE\";";
//$stmt = pg_query($c,$khoueiry);

//calculate hierarchy and stuff for anatomy simplification
$hierarchy=(array) null;
$parent_lsts=(array) null;
$leaf_lsts=(array) null;
$roots=(array) null;

$khoueiry = "SELECT A.\"DEV_STAGE_ID\", A.\"ANAT_ID\" AS \"CHILD\", B.\"ANAT_ID\" AS \"PARENT\", B.\"NAME\" FROM 
		\"ANAT_ENTITY\" A, \"ANAT_ENTITY\" B WHERE A.\"CHILD_OF\"=B.\"ANAT_ID\" ";
$stmt = pg_query($c,$khoueiry);
$anat_lst=(array) null;
$inv_hierarchy=(array) null;
while($row=pg_fetch_array($stmt)){
	$inv_hierarchy[$row["DEV_STAGE_ID"]][$row["CHILD"]]=$row["PARENT"];	
	$hierarchy[$row["DEV_STAGE_ID"]][$row["PARENT"]][]=$row["CHILD"];
	$anat_lst[$row["DEV_STAGE_ID"]][$row["CHILD"]]=1;	
	$anat_lst[$row["DEV_STAGE_ID"]][$row["PARENT"]]=1;			
	if($row["NAME"]=='Whole embryo'){ $roots[$row["DEV_STAGE_ID"]] = $row["PARENT"]; }
}

foreach($anat_lst as $stage => $st_anat_lst){
	foreach ($st_anat_lst as $anat => $bogus){		

		$cur_par = $anat;		
		$par_lst=(array) null;
		while(true){
			$par_lst[count($par_lst)] = $cur_par;
			if(!isset($inv_hierarchy[$stage][$cur_par])){
				break;
			} 
			$cur_par = $inv_hierarchy[$stage][$cur_par];
		}
		$parent_lsts[$stage][$anat] = $par_lst;
	
		$to_process=array($anat);
		while(count($to_process)>0){
			$cur = array_pop($to_process);
			if(!isset($hierarchy[$stage][$cur])){
				$leaf_lsts[$stage][$anat][] = $cur;
			} else {
				foreach($hierarchy[$stage][$cur] as $child){
					array_push($to_process, $child);
				}
			}					
		}		
	}
}
//END calculate hierarchy and stuff for anatomy simplification

$wt_expr = (array)null;
//Get "WT" expression for all constructions available
$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"TARGET_ID\", \"REGION_ID\", 
	\"DEV_STAGE_ID\", \"WILD_TYPE\", \"CHECKED\" FROM 
	\"TARGET\", \"IN_SITU\" WHERE \"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND
	\"TARGET_ID\" IN (SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\");";
$stmt = pg_query($c,$khoueiry);
while($row=pg_fetch_array($stmt)){ 
	if(($row["CHECKED"]==="y") && ($row["WILD_TYPE"]==="y")){	
		$arr = (array)null;
		if(isset($wt_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]])){
			$arr = $wt_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]];
		}
		if(isset($leaf_lsts[$row["DEV_STAGE_ID"]][$row["REGION_ID"]])){
			$arr = array_merge($arr,$leaf_lsts[$row["DEV_STAGE_ID"]][$row["REGION_ID"]]);
			$arr = array_unique($arr);
		}
		$wt_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]] = $arr;
		
	}
}

$mut_expr = (array)null;
//Mutant for Regions... compare this with regions with capacity for WT... this is indirect evidence!...
$khoueiry="SELECT \"TARGET\".\"IN_SITU_ID\", \"TARGET_ID\", \"REGION_ID\", 
	\"DEV_STAGE_ID\", \"CHECKED\" FROM \"TARGET\", \"IN_SITU\" WHERE 
	\"TARGET\".\"IN_SITU_ID\" = \"IN_SITU\".\"IN_SITU_ID\" AND 
	\"TARGET\".\"IN_SITU_ID\" IN (SELECT \"IN_SITU_ID\" FROM \"MUTANT\") AND
	\"TARGET\".\"IN_SITU_ID\" NOT IN (SELECT \"IN_SITU_ID\" FROM \"EMBRYO_MANIP\") AND
	\"TARGET_ID\" IN (SELECT \"CONSTRUCTION_ID\" FROM \"CONSTRUCTION\");";
$stmt = pg_query($c,$khoueiry);
while($row=pg_fetch_array($stmt)){ 
	if(($row["CHECKED"]=="y")){
		$arr = (array)null;
		if(isset($mut_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]])){
			$arr = $mut_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]];
		}
		if(isset($leaf_lsts[$row["DEV_STAGE_ID"]][$row["REGION_ID"]])){
			$arr = array_merge($arr,$leaf_lsts[$row["DEV_STAGE_ID"]][$row["REGION_ID"]]);
			$arr = array_unique($arr);
		}
		$mut_expr[$row["DEV_STAGE_ID"]][$row["TARGET_ID"]][$row["IN_SITU_ID"]] = $arr;		
	}
}

foreach ($mut_expr as $stage => $target_list){	
	foreach($target_list as $target => $mut_ish_list){	
		if(isset($wt_expr[$stage]) && isset($wt_expr[$stage][$target])){
			//Find out what this target corresponds to...				
			$wt_gene = null;
			$khoueiry = "SELECT \"GENE_ID\" FROM \"GENE_REGULATION\", \"CONSTRUCTION\" WHERE
				\"GENE_REGULATION\".\"PROMOTER_ID\"=\"CONSTRUCTION\".\"PROMOTER_ID\" AND
				\"CONSTRUCTION_ID\"=$target;";
			$stmt = pg_query($c,$khoueiry);
			if($row=pg_fetch_array($stmt)){ 
				$khoueiry = "SELECT \"GENE_CLUSTER_ID\" FROM \"GENE_CONCEPT\" WHERE \"GENE_MODEL_ID\"=".$row["GENE_ID"];				
				$wt_gene = $row["GENE_ID"];
				$stmt = pg_query($c,$khoueiry);
				if($row=pg_fetch_array($stmt)){ 	
					$wt_gene = $row["GENE_CLUSTER_ID"];
				}
			}			
			
			//not worth continuing if gene regulated does not exist			
			if( $wt_gene == null) continue;
			
			foreach ($mut_ish_list as $mutish => $mut_regions){
								
				$mut_gene = null;
				$up_down = null;
				//find out what is the gene that is affecting target and how it is being affected
				$khoueiry = "SELECT \"GENE_CLUSTER_ID\", \"UP_DOWN\" FROM \"GENE_CONCEPT\", \"GENE\", \"MUTANT\" WHERE 
					\"GENE_CONCEPT\".\"GENE_MODEL_ID\"=\"GENE\".\"GENE_ID\" AND \"GENE\".\"NAME\"=\"MUTANT\".\"NAME\" AND
					\"IN_SITU_ID\"=$mutish";
				$stmt = pg_query($c,$khoueiry);
				
				//If it has more than one and they are opposing... then ignore...
				while($row=pg_fetch_array($stmt)){ 
					if($up_down !== null){
						if($up_down !== $row["UP_DOWN"]){
							$mut_gene = null;
							$up_down = null;
							break;
						}
					}
					$mut_gene = $row["GENE_CLUSTER_ID"];
					$up_down = $row["UP_DOWN"];
				}
				if(!is_null($mut_gene)){					
								
					foreach ($wt_expr[$stage][$target] as $wtish => $wt_regions){
					
						$up_regions = (array)null;
						$down_regions = (array)null;
			
						if($up_down=='downregulated'){
							$up_regions = array_diff($wt_regions, $mut_regions);
							$down_regions = array_diff($mut_regions, $wt_regions);
						} else {
							$down_regions = array_diff($wt_regions, $mut_regions);
							$up_regions = array_diff($mut_regions, $wt_regions);
						}
			
						$up_regions  = simplify_hierarchy($hierarchy[$stage],$roots[$stage],
															$leaf_lsts[$stage],$up_regions);
						$down_regions  = simplify_hierarchy($hierarchy[$stage],$roots[$stage],
															$leaf_lsts[$stage],$down_regions);			
			
						foreach($up_regions as $up_region){
							print "$mut_gene upregulates $wt_gene in $up_region : $mutish - $wtish</br>";
				
							$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$mut_gene', '$wt_gene', 'upregulates', $up_region, 'n', $mutish, $wtish, $stage) ";	
							$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
						}
						foreach($down_regions as $down_region){
							print "$mut_gene downregulates $wt_gene in $down_region : $mutish - $wtish</br>";
				
							$khoueiry = "INSERT INTO \"REG_EVIDENCE\" (\"GENE_X\", \"GENE_Y\", \"TYPE\", \"REG_ANAT\", \"DIRECT\", \"EVIDENCE\", \"CONTROL\", \"DEV_STAGE_ID\") VALUES ('$mut_gene', '$wt_gene', 'downregulates', $down_region, 'n', $mutish, $wtish, $stage) ";	
							$stmt = pg_query($c,$khoueiry) or die("ERROR: ".pg_last_error($c));
						}
												
						
					}					
					
				}				
			}						
		}		
	}
	

}


//Start direct evidence


print '<br/>The End</body></html>';
?>
