RCircos / rcircos_action.php

<?php
date_default_timezone_set('America/New_York');
// move uploaded files to the temp directory
$outDir="temp/";
$linkFile = $_POST['linkLines'];
$Track1File = $_POST['track1'];
$Track2File = $_POST['track2'];
$Track3File = $_POST['track3'];
$Track4File = $_POST['track4'];
$Track5File = $_POST['track5'];
$geneFile = $_POST['geneLabel'];
// Get the filetypes so that r can read them correctly. files that aren't txt or csv should've been caught in fileupload so every file
// should satisfy one of these conditions
if(substr($linkFile, -3) =="txt") {
	$linkType = "table";
} elseif(substr($linkFile, -3) == "csv") {
	$linkType = "csv";
} 
if(substr($Track1File, -3) =="txt") {
	$track1FileType = "table";
} elseif(substr($Track1File, -3) == "csv") {
		$track1FileType = "csv";
} 
if(substr($Track2File, -3) =="txt") {
	$track2FileType = "table";
} elseif(substr($Track2File, -3) == "csv") {
		$track2FileType = "csv";
} 
if(substr($Track3File, -3) =="txt") {
	$track3FileType = "table";
} elseif(substr($Track3File, -3) == "csv") {
		$track3FileType = "csv";
} 
if(substr($Track4File, -3) =="txt") {
	$track4FileType = "table";
} elseif(substr($Track4File, -3) == "csv") {
		$track4FileType = "csv";
}
if(substr($Track5File, -3) =="txt") {
	$track5FileType = "table";
} elseif(substr($Track5File, -3) == "csv") {
		$track5FileType = "csv";
} elseif($Track5File !='') {
	echo "ERROR: data files must be .csv or .txt";
	exit();
}
if(substr($geneFile, -3) =="txt") {
	$geneFileType = "table";
} elseif(substr($geneFile, -3) == "csv") {
		$geneFileType = "csv";
} elseif($geneFile !='') {
	echo "ERROR: data files must be .csv or .txt";
	exit();
}
// by counting how many files are being used we can adjust the size of the circos plot so that it is not needlessly big for only a few tracks
$files = array($Track1File, $Track2File, $Track3File, $Track4File, $Track5File, $geneFile, $linkFile);
$filespresent = 0;
foreach($files as $file) {
	if($file != '') {
		$filespresent++;
	}
}
//echo "<pre>" . print_r($_FILES, true) . "</pre>";
//echo "<pre>" . print_r($_POST, true) . "</pre>";
$username = $_POST['username'];
$chrList = $_POST['chrList'];
$missingChrs = array();
$i = 0;
$c = 0;
// easy way to convert the included list which is more inuitive for user input into the exclude list that rcricos needs
$humanChrList = array( chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8, chr9, chr10, chr11, chr12, chr13, chr14, chr15, chr16, chr17, chr18, chr19, chr20, chr21, chr22, 'chrX', 'chrY'	);
foreach ($humanChrList as $value) {
	if($value != $chrList[$i]) {
		$missingChrs[$c] = "$value";
	} else {
		$missingChrs[$c] = NULL;
		$i++;
	}
	$c++;
}
$fileType = $_POST['fileType'];
$width = $_POST['width'];
$trackHeight = $_POST['trackHeight'];
$trackHeight = round($trackHeight * 0.1, 5);
$textSize = $width*.2/3.0;
// the plot looks super wierd when the size gets really small
if($width < 3) {
	echo "WARNING: Sizes less than 3 inches are not recommended";
}
$speciesName = $_POST['speciesName'];
$geneLabel = $_POST['geneLabel'];
$trackType1 = $_POST['trackType1'];
$trackType2 = $_POST['trackType2'];
$trackType3 = $_POST['trackType3'];
$trackType4 = $_POST['trackType4'];
$trackType5 = $_POST['trackType5'];
$fileName = $_POST['plotName'];
$date = getdate();
// depending on what number the day of the month is give it 'st' , 'nd' , 'rd' or 'th'
if($fileName == '') {
	$fileName = date("M") . "_" . $date["mday"];
	if($date["mday"] == 01 | $date["mday"] == 21 | $date["mday"] == 31 ) {
		$fileName =$fileName . "st_" . $date["hours"] ."_".$date["minutes"]. "_" . $date["seconds"]; 
	} else if($date["mday"] == 02 | $date["mday"] == 22 ) {
		$fileName =$fileName . "nd_" . $date["hours"] ."_".$date["minutes"]. "_" . $date["seconds"];
	} else if($date["mday"] == 02 | $date["mday"] == 22 ) {
		$fileName =$fileName . "rd_" . $date["hours"] ."_".$date["minutes"]. "_" . $date["seconds"];
	} else {
		$fileName =$fileName . "th_" . $date["hours"] ."_".$date["minutes"]. "_" . $date["seconds"];
	}
}
// make sure you aren't overwriting a prexisting file and if you are change the name so it doesn't
while(is_file("temp/$username/hist/$fileName.png") | is_file("temp/$username/hist/$fileName.pdf") | is_file("temp/$username/hist/$fileName.jpeg")) {
	$fileName .= "1";
}
$R_script =<<<THERSCRIPT
library(RCircos)
Species <- '$speciesName';
if(Species == 'Human') {
	data(UCSC.HG19.Human.CytoBandIdeogram);
	cyto.info <- UCSC.HG19.Human.CytoBandIdeogram;
} else if(Species == "Mouse") {
	data(UCSC.Mouse.GRCm38.CytoBandIdeogram);
	cyto.info <- UCSC.Mouse.GRCm38.CytoBandIdeogram;
} else {
	data(UCSC.Baylor.3.4.Rat.cytoBandIdeogram);
	cyto.info <- UCSC.Baylor.3.4.Rat.cytoBandIdeogram;
}
excChrs <- c();
excChrs <- append(excChrs, "$missingChrs[0]");excChrs <- append(excChrs, "$missingChrs[1]");excChrs <- append(excChrs, "$missingChrs[2]");
excChrs <- append(excChrs, "$missingChrs[3]");excChrs <- append(excChrs, "$missingChrs[4]");excChrs <- append(excChrs, "$missingChrs[5]");
excChrs <- append(excChrs, "$missingChrs[6]");excChrs <- append(excChrs, "$missingChrs[7]");excChrs <- append(excChrs, "$missingChrs[8]");
excChrs <- append(excChrs, "$missingChrs[9]");excChrs <- append(excChrs, "$missingChrs[10]");excChrs <- append(excChrs, "$missingChrs[11]");
excChrs <- append(excChrs, "$missingChrs[12]");excChrs <- append(excChrs, "$missingChrs[13]");excChrs <- append(excChrs, "$missingChrs[14]");
excChrs <- append(excChrs, "$missingChrs[15]");excChrs <- append(excChrs, "$missingChrs[16]");excChrs <- append(excChrs, "$missingChrs[17]");
excChrs <- append(excChrs, "$missingChrs[18]");excChrs <- append(excChrs, "$missingChrs[19]");excChrs <- append(excChrs, "$missingChrs[20]");
excChrs <- append(excChrs, "$missingChrs[21]");excChrs <- append(excChrs, "$missingChrs[22]");excChrs <- append(excChrs, "$missingChrs[23]");
excChrs <- excChrs[excChrs != ""]
RCircos.Set.Core.Components(cyto.info, chr.exclude=excChrs, $filespresent + 4, 0);
rcircos.params <- RCircos.Get.Plot.Parameters();
rcircos.params\$text.size <- $textSize;
rcircos.params\$track.height <- $trackHeight;
RCircos.Reset.Plot.Parameters(rcircos.params);
TrackTypes <- c("$trackType1", "$trackType2", "$trackType3", "$trackType4", "$trackType5");
TrackFiles <- c("$Track1File", "$Track2File", "$Track3File", "$Track4File", "$Track5File");
FileTypes <- c("$track1FileType", "$track2FileType", "$track3FileType", "$track4FileType", "$track5FileType");
out.file <- "temp/$username/hist/$fileName.$fileType";
if('$fileType' == 'pdf') {
	pdf(file = out.file, width=$width, height=$width);
} else {
	$fileType(filename = out.file, width=$width, height=$width, units="in", res=300, 	type="cairo");
}
RCircos.Set.Plot.Area();
RCircos.Chromosome.Ideogram.Plot();
linkNumber <- 0;
c <- 0;
probe <- F;
	if('$geneFile' =='') {
		c <- c-3
		probe <- T;
		linkNumber <- c;
}
for( i in 1:5) {
	TrackType <- TrackTypes[i];
	TrackFile <- TrackFiles[i];
	FileType <- FileTypes[i];
	if(TrackType == "Heatmap" & TrackFile !='') {
	c <- c+1;
		if(FileType == "table") {
			TrackData <- read.table(TrackFile, sep="\t", quote="", head=T);
		} else {
			TrackData <- read.csv(TrackFile, sep=",", quote="", head=T);
		}
		RCircos.Heatmap.Plot(TrackData, 6, c+3, "in");
		linkNumber <- c;
	} else if(TrackType == "Histogram" & TrackFile!='') {
	c <- c+1;
	
		if(FileType == "table") {
			TrackData <- read.table(TrackFile, sep="\t", quote="", head=T);
		} else {
			TrackData <- read.csv(TrackFile, sep=",", quote="", head=T);
		}
		RCircos.Histogram.Plot(TrackData, 4, c+3, "in");
		linkNumber <- c;
	} else if(TrackType == "Line" & TrackFile !='') {
	c <- c+1;
		if(FileType == "table") {
			TrackData <- read.table(TrackFile, sep="\t", quote="", head=T);
		} else {
			TrackData <- read.csv(TrackFile, sep=",", quote="", head=T);
		}
		RCircos.Line.Plot(TrackData, 5, c+3, "in");
		linkNumber <- c;
	} else if(TrackType == "Scatter" & TrackFile !='') {
	c <- c+1;
		if(FileType == "table") {
			TrackData <- read.table(TrackFile, sep="\t", quote="", head=T);
		} else {
			TrackData <- read.csv(TrackFile, sep=",", quote="", head=T);
		}
		RCircos.Scatter.Plot(TrackData, 5, c+3, "in", 1);
		linkNumber <- c;
	} else if(TrackType == "Tile" & TrackFile !='') {
	c <- c+1;
		if(FileType == "table") {
			TrackData <- read.table(TrackFile, sep="\t", quote="", head=T);
		} else {
			TrackData <- read.csv(TrackFile, sep=",", quote="", head=T);
		}
		RCircos.Tile.Plot(TrackData, c+3, "in");
		linkNumber <- c;
	} 
}
if('$geneFile' == '' & linkNumber == 0 & '$linkFile' != '' & probe == F) {
	if("$linkType" == "table") {
		link.data <- read.table("$linkFile", sep="\t", quote="", head=T);
	} else {
		link.data <- read.csv("$linkFile", sep=",", quote="", head=T);
	}
	RCircos.Link.Plot(link.data, 1, TRUE);
} else if('$linkFile' != '') {
	if("$linkType" == "table") {
		link.data <- read.table("$linkFile", sep="\t", quote="", head=T);
	} else {
		link.data <- read.csv("$linkFile", sep=",", quote="", head=T);
	}
		RCircos.Link.Plot(link.data, 4 + linkNumber, TRUE);	
}
if('$geneFile' !='') {
	if("$geneFileType" == "table") {
		gene.data <- read.table("$geneFile", sep="\t", quote="", head=T);
	} else {
		gene.data <- read.csv("$geneFile", sep=",", quote="", head=T);
	}
	RCircos.Gene.Connector.Plot(gene.data, 1, "in");
	RCircos.Gene.Name.Plot(gene.data, 4, 2,"in");
}

dev.off();
THERSCRIPT;
$circosPlot ="temp/" . $username . "/hist/" . $fileName."." .$fileType;
//echo "<pre>" . print_r($relationsArray, true) . "</pre>";
// any sessions that haven't been used for 2 or more weeks are deleted here
foreach (glob("temp/" . '*') as $allfile1) {
	if ( (time() - filemtime($allfile1)) > 60*60*24*7) unlink($allfile1);
}
$isDone = false;
$c = 0;
// since the filemanager's rows are generated by having a file in the upload folder these files allow it to display 
// all the plots if there are more plots than files uploaded
while($isDone == false) {
	if(is_file('temp/' . $username . '/zzzzzzz' . $c . ".txt")) {
		$c++;
	} else {
		fopen('temp/' . $username . '/zzzzzzz' . $c . ".txt", 'w');
		$isDone = true;
	}
}
$cmd_file = "temp/" . $fileName. '_R.cmd';
$RFileHandle = fopen($cmd_file, "w") or die("Could not open tempfile");
fwrite($RFileHandle, $R_script);
fclose($RFileHandle);
$cmd = "/usr/bin/R --vanilla < " .  $cmd_file . ' 2>&1';
$changeDir = shell_exec("cd ".$outDir);
$output = shell_exec($cmd); 
// creates a log for the r output to make bug tracking easier
$log = fopen('temp/' . $username .'/logs/'. $fileName . "_log.txt", 'a');
fwrite($log, $output);
fclose($log);
// if an error occured let the user know
$errorCheck = explode("Error!", $output);
if(count($errorCheck) > 1) {
	echo "<script>window.alert('Some of your data was unable to be plotted. Check what data is missing in your plot and make sure that the files with that data are formatted correctly and do not go outside chromosome bounds');</script>";
}
// since pdf's are not images they have to be handled differently from png's or jpeg's
if($fileType == "pdf") {
	echo "<script>
if($('#history1').children().length > 0) {
var html = $('#historySelect').html();
	html = html + \"<option value='$circosPlot'>$fileName.$fileType</option>\";
	$('#historySelect').html(html);
} else {
	html = \"History:(month:day:hour:minute:second)<select name='historySelect' id='historySelect' onchange='Javascript: histUpdate();'><option value='none'>No option selected</option><option value='$circosPlot'>$fileName.$fileType</option>\"
	$('#history1').html(html);
}
if($('#history2').children().length > 0) {
var html = $('#historySelect').html();
	html = html + \"<option value='$circosPlot'>$fileName.$fileType</option>\";
	$('#historySelect').html(html);
} else {
	html = \"History:(month:day:hour:minute:second)<select name='historySelect' id='historySelect' onchange='Javascript: histUpdate();'><option value='none'>No option selected</option><option value='$circosPlot'>$fileName.$fileType</option>\"
	$('#history2').html(html);
}

$('#historySelect').val('$circosPlot');
$('#modal2').dialog( 'close');
	</script><a href='". $circosPlot ."'>Download Plot</a>";
} else {
	echo "	<script>
if($('#history').children().length > 0) {
var html = $('#historySelect').html();
	html = html + \"<option value='$circosPlot'>$fileName.$fileType</option>\";
	$('#historySelect').html(html);
} else {
	html = \"History:(month:day:hour:minute:second)<select name='historySelect' id='historySelect' onchange='Javascript: histUpdate();'><option value='none'>No option selected</option><option value='$circosPlot'>$fileName.$fileType</option>\"
	$('#history').html(html);
}

$('#historySelect').val('$circosPlot');
$('#modal2').dialog( 'close');
	</script><img align='center' src='". $circosPlot ."' height='800' width='800' >";
}
// this creates the file which relates the plot to the files that were used to create it. Extensions are removed because they interfere with html classes
$relations = fopen('temp/' . $username ."/relations.txt", 'a');
$file1 = substr($Track1File, 6 + strlen($username), -4);
$file2 = substr($Track2File, 6 + strlen($username), -4);
$file3 = substr($Track3File, 6 + strlen($username), -4);
$file4 = substr($Track4File, 6 + strlen($username), -4);
$file5 = substr($Track5File, 6 + strlen($username), -4);
$file6 = substr($geneFile, 6 + strlen($username), -4);
$file7 = substr($linkFile, 6 + strlen($username), -4);
$relationstext = "var relArray = new Array('".$fileName."'";
$c = 1;
// don't include an empty file name I think the $c is for something I ended up removing but I'm afraid to delete things since I won't have time to test
// changes right now
if($file1 != '') {
	$relationstext .= " ,'$file1'";
	$c++;
}
if($file2 !='') {
	$relationstext .= ",'$file2'";
	$c++;
}
if($file3 != '') {
	$relationstext .= ",'$file3'";
	$c++;
}
if($file4 != '') {
	$relationstext .= ",'$file4'";
	$c++;
}
if($file5 != '') {
	$relationstext .= ",'$file5'";
	$c++;
}
if($file6 != '') {
	$relationstext .= ",'$file6'";
	$c++;
}
if($file7 != '') {
	$relationstext .= ",'$file7'";
} $relationstext .= ");~";
fwrite($relations, $relationstext);
fclose($relations);
$emailInput = $_POST['email'];
// returns the url of the page so that this works whether it's on localhost, alps, or watson
function curPageURL() {
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	$pageURL = substr($pageURL, 0, -18);
	return $pageURL;
}
// if there are multiple emails provided we simply create an array of them
$emailArray = explode(",", $emailInput);
foreach($emailArray as $email) {
	// eliminate whitespace
	$email = preg_replace('/\s+/', '', $email);
	if(empty($email) == false) {
		$emailText = 'Your circos plot is ready to download! Right click the link below and select "save file as" to download it. ' . curPageURL() . $circosPlot;
		mail($email, 'Your Circos Plot is Complete', $emailText);
	}
}
?>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.