Ejemplo n.º 1
0
/**
 * Unconditionally logs an error message.
 *
 * @param msg The message format specification (ala printf).
 * @return ESR_SUCCESS if success, anything else if an error occurs.
 */
ESR_ReturnCode PLogError(const char* msg, ...)
{
  va_list args;
  ESR_ReturnCode rc;
#if defined (ANDROID)
#if defined (HAVE_ANDROID_OS)
  char log_text [2048];
#endif
#endif

  va_start(args, msg);
#if defined (ANDROID)
#if defined (HAVE_ANDROID_OS)
  pvsprintf ( log_text, msg, args);
/* We need to disable some error messages because they are frequently not
 * errors but due to sloppy use of some functions. This prevents us from
 * getting flooded with bad error messages. SteveR
 */
  if ( ( strncmp ( log_text, FILTER_MSG_1, FILTER_MSG_1_SIZE ) != 0 ) &&
    ( strncmp ( log_text, FILTER_MSG_2, FILTER_MSG_2_SIZE ) != 0 ) )
  {
    LOGE ( log_text );
  }
  rc = 0;
#else
  rc = logIt(msg, args, ESR_TRUE);
#endif
#else
  rc = logIt(msg, args, ESR_TRUE);
#endif
  va_end(args);
  
  return rc;
}
Ejemplo n.º 2
0
int startReconstruction(){

	int return_value = 0;
	char str[200];

	FILE *dataFile = fopen(sinoPath,"r");
	logIt(DEBUG, "startReconstruction() started.");
	//Read P2
	fgets(str, 200, dataFile);
	if(!(str[0] == 'P' && str[1] == '2')){
		logIt(ERR, "Not a pgm.");
		return 1;
	}


	fgets(str, 200, dataFile); //Hopefully a commentary
	fscanf(dataFile,"%d",&imgwidth);
	fscanf(dataFile,"%d",&numangles);
	logIt(TRACE, "width: %d, angles: %d", imgwidth, numangles);
	fgets(str, 200, dataFile);

	fgets(str, 200, dataFile);//colordepth, we dont care about


	imgheight = 512;		//This is the height of the reconstructed image.

	return_value = reconstruct(dataFile);

	logIt(DEBUG, "startReconstruction() finished.");
	return return_value;
}
void logListStats(struct intList **pList)
/* Write out some stats to log file. */
{
struct intList *el;
long long total = 0;
int minVal = 0, medVal0 = 0, medVal1 = 0, maxVal = 0;
int count = slCount(*pList);
int i, middle = count/2;
float medVal;


if (count != 0)
    {
    slSort(pList, intListCmp);
    minVal = (*pList)->val;
    for (i=0, el = *pList; el != NULL; el = el->next, ++i)
	{
	int val = el->val;
	total += val;
	maxVal = val;
	if (i == middle)
	    medVal0 = val;
	else if (i == middle+1)
	    medVal1 = val;
	}
    if (((count % 2) == 0) && (count > 1))
        medVal = (medVal0+medVal1)/2.0;
    else
        medVal = medVal0;
    logIt("ave: %0.1f  min: %d  max: %d  median: %0.1f  total: %lld", 
          total/(double)count, minVal, maxVal, medVal, total);
    }
logIt("\n");
}
Ejemplo n.º 4
0
/*
	This kernel creates a basic sync function to be used as a filter for the sinogram
 */
void createFilter() {
	int idx;
	logIt(DEBUG, "createFilter() started.");


	for(idx = -imgwidth; idx < imgwidth; idx++){
		//logIt(TRACE, "idx+imgwidth = %d", (idx+imgwidth));
		h[idx+imgwidth] = (0.5f*(idx==0?1.0f:(sin(PI*idx)/(PI*idx)))) - (0.25f*pow((idx==0?1.0f:(sin(PI*idx/2.0f)/(PI*idx/2.0f))), 2));

	}
	logIt(DEBUG, "createFilter() finished.");
}
Ejemplo n.º 5
0
Message FilePort::read()
{
    Message msg = protocol->unpack(inputFile->readLine());
    emit messageReceived(msg);
    logIt(msg);
    return msg;
}
Ejemplo n.º 6
0
eventsLog::eventsLog(){
    ofile = fopen("log.txt","a");
    // have to set this FILE stream line buffered or non-buffered
//    setvbuf(ofile,NULL,_IOLBF,BUFSIZ);
    setvbuf(ofile,NULL,_IOLBF,0);
    const char* delim = "------------------------------------------------"
                        "----------------------------";
    fprintf(ofile,"%s\n",delim);
    logIt("Server started!\n");
}
Ejemplo n.º 7
0
Message PUMCommunication::read()
{
    Message resultMsg;

    if(!commDevice->isOpen())
        return resultMsg;

    while(commDevice->bytesAvailable() > 0)
    {
        QByteArray readBytes;

        while(commDevice->bytesAvailable() > 0)
        {
            readBytes.append(commDevice->read(1));

            if(readBytes.endsWith(END_SYMBOL))
                break;

            if(commDevice->bytesAvailable() == 0 && !readBytes.endsWith(END_SYMBOL))
                this->waitForData();
        }

        try
        {
            if(readBytes.size() > 1)
            {
                resultMsg = protocol->unpack(readBytes);
                emit messageReceived(resultMsg);
                logIt(resultMsg, true);
            }
        }
        catch(...)
        {
            logIt("Error during transmission: " + readBytes);
            qDebug((QString("Error during transmission: "+readBytes).toLocal8Bit()));
        }

    }

    return resultMsg;
}
Ejemplo n.º 8
0
Archivo: Run.c Proyecto: Axelius/CTSim
int main(int argc, char *argv[]){
    LARGE_INTEGER frequency;
    LARGE_INTEGER t1, t2;
    double elapsedTime;
	int ret = 0;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&t1);
	if(argc != 2){
		printhelp();
		return EXIT_FAILURE;
	}
	startLogger("log.txt");
	readSettingsFromConfigFile(argv[1]);
	setUpSpectrum();


	logIt(DEBUG, "pathToSlice=%s", cfg.pathToSlice);
	logIt(DEBUG, "pathToOutputReconstruction=%s", cfg.pathToOutputReconstruction);


	setUpAttenuation();
	logIt(INFO, "Everything set up successfully. Starting simulation...");

	ret = simulation(cfg.pathToSlice, cfg.pathToOutputSinogram);
	reconstruction(cfg.pathToOutputSinogram, cfg.pathToOutputReconstruction);
	QueryPerformanceCounter(&t2);
	elapsedTime = (double)(t2.QuadPart - t1.QuadPart) / frequency.QuadPart;
	logIt(INFO, "Total computation time: %f seconds.", elapsedTime);
	logIt(INFO, "Reconstructed image saved as %s. Exiting...", cfg.pathToOutputReconstruction);
	logIt(DEBUG, "main(int argc, char *argv[]) finished.");
	stopLogger();
	return ret;
}
Ejemplo n.º 9
0
double getAttenuation(int material, double kV, int positionX, int positionY) {
	unsigned int **imageRaw;
	logIt(TRACE, "getAttenuation(int material, double kV, int positionX, int positionY) started.");

	switch(material){
	case IRON:
		logIt(TRACE, "Material ID%d: iron", material);
		imageRaw = ironRaw;
		break;
	case BONE:
		logIt(TRACE, "Material ID%d: bone", material);
		imageRaw = boneRaw;
		break;
	case WATER:
		logIt(TRACE, "Material ID%d: water", material);
		imageRaw = waterRaw;
		break;
	case AIR:
		logIt(TRACE, "Material ID%d: air", material);
		imageRaw = airRaw;
		break;
	case MUSCLE:
		logIt(TRACE, "Material ID%d: muscle", material);
		imageRaw = muscleRaw;
		break;
	case TISSUE:
		logIt(TRACE, "Material ID%d: tissue", material);
		imageRaw = tissueRaw;
		break;
	default:
		logIt(ERR, "Material ID%d not found!", material);
		logIt(TRACE, "getAttenuation(int material, double energy) finished.");
		return 0.0f;
	}


	logIt(TRACE, "getAttenuation(int material, double energy) finished.");
	return ((getInterpolatedAttenuationValue(material, kV) * ((double)imageRaw[positionX][positionY])))/255.0;
}
Ejemplo n.º 10
0
	//-------------------------------------------------------------------------
	void Log::log(LogTarget target, LogLevel level, const char* msg, ...)
	{
        // check whenver we have already initialised the log engine
        if (!_bInitialized) return;
			
		// get messages 
		va_list args; 
		va_start(args,msg);
		char szBuf[2056];
		memset(szBuf, 0, sizeof(char)*2056);
		vsprintf(szBuf,msg,args);
		va_end(args);
		
		// log the message
		logIt(target, level, szBuf);
		
		// echo logging
		if (_echoMap[target]){
			logIt(_echoMap[target], level, szBuf);
		}
		
	}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
	int i;
/*
HANDLE hStdout; 

hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 

unsigned long int dwWritten;
WriteFile(hStdout, "help\n", 5, &dwWritten, NULL); 
*/
	logIt("started");

	fprintf(stderr, "Program Arguments\n");
	for (i=0;i<argc;i++)
	{
		fprintf(stderr, "%s\n", argv[i]);
		logIt(argv[i]);
	}
	fprintf(stderr, "\n");

	char buffer[1024];
	while (true)
	{
	logIt("waiting for input");
		gets(buffer);
	logIt(buffer);

		fprintf(stderr, "GOT %s\n", buffer);

		for (i=0;buffer[i];i++)
			buffer[i]=toupper(buffer[i]);

		printf("%s\n", buffer);
	}

	return 1;
}
Ejemplo n.º 12
0
int reconstruction(char *pathToSino, char *pathToOutput) {
	int ret = 0;
	logIt(DEBUG, "reconstruction(char *pathToSino, char *pathToOutput) started.");
	outputPath = pathToOutput;
	sinoPath = pathToSino;
    LARGE_INTEGER frequency;
    LARGE_INTEGER t1, t2;
    double elapsedTime;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&t1);

	logIt(DEBUG, "Debug: outputpath: %s", outputPath);
	logIt(INFO, "Starting Reconstruction for %d projections.", cfg.numberOfProjectionAngles);


	ret = startReconstruction();

	QueryPerformanceCounter(&t2);
	elapsedTime = (double)(t2.QuadPart - t1.QuadPart) / frequency.QuadPart;
	logIt(INFO,  "Reconstruction finished. Runtime: %f seconds.", elapsedTime);
	logIt(DEBUG, "reconstruction(char *pathToSino, char *pathToOutput) finished.");
	return ret;
}
Ejemplo n.º 13
0
qint64 PUMCommunication::write(Message toWrite)
{
    logIt(toWrite, false);

    read();
    qint64 bytesWritten = commDevice->write(protocol->pack(toWrite));

    if(bytesWritten != -1)
        emit messageSent(toWrite);

    else
        qDebug ((QString("No bytes written. Message: ")+ protocol->pack(toWrite)).toLocal8Bit());

    return bytesWritten;
}
Ejemplo n.º 14
0
/*
	This kernel filters the original sinogram data line by line by convolving
	each line of the sinogram with the 'h' filter.
 */
void filterSinogram(float *img, float *img_res) {
	int j, k, i;
	logIt(DEBUG, "filterSinogram(float *img, float *img_res) started.");

	for (j = 0; j < numangles; j++){
		for (k = 0; k < imgwidth; k++){
			int gLoc = k + j*imgwidth;
			float sum = 0;
			float value = 0;

			for(i = -imgwidth; i < imgwidth; i++){
				if((k + i) < 0 || (k + i) > imgwidth-1){
					value = 0;
				}
				else{
					value = img[gLoc + i];
				}
				sum += value * h[imgwidth + i];
			}
			img_res[gLoc] = sum;
		}
	}
	logIt(DEBUG, "filterSinogram(float *img, float *img_res) finished.");
}
Ejemplo n.º 15
0
/**
 * Conditionally PLogs a message.  The message is logged only if module is enabled.
 *
 * @param msg The message format specification (ala printf).
 * @return ESR_SUCCESS if success, anything else if an error occurs.
 */
ESR_ReturnCode PLogMessage(const char* msg, ...)
{
  va_list args;
  ESR_ReturnCode rc;
#if USE_STACKTRACE
  size_t depth;
#endif
  
#if defined (ANDROID)
#if defined (HAVE_ANDROID_OS)
  return ( ESR_SUCCESS );/* Get rid of this for phone device */
#endif
#endif

  if (Glogger == NULL)
    return ESR_INVALID_STATE;
#ifdef USE_STACKTRACE
  return ESR_SUCCESS;
  rc = PStackTraceGetDepth(&depth);
  
  if (rc == ESR_NOT_SUPPORTED)
  {
    /* Debugging symbols are missing */
    return ESR_SUCCESS;
  }
  else if (rc != ESR_SUCCESS)
  {
    pfprintf(PSTDERR, L("PStackTraceGetDepth"), ESR_rc2str(rc));
    goto CLEANUP;
  }
  
  /* Remove PLogMessage() from depth */
  --depth;
  if (GlogLevel < depth)
    return ESR_SUCCESS;
#endif
    
  va_start(args, msg);
  rc = logIt(msg, args, ESR_FALSE);
  va_end(args);
  return rc;
#if USE_STACKTRACE
CLEANUP:
  return rc;
#endif
}
Ejemplo n.º 16
0
//Reads all attenuation coefficient tables. Path to them is hardcoded
void setUpAttenuation(){
	int i;
	logIt(DEBUG, "setUpAttenuation() started.");
	readAttenuationFile("Data/MassAttenuationCoefficients/iron.txt", &iron, &ironLength);
	readAttenuationFile("Data/MassAttenuationCoefficients/boneCortical.txt", &bone, &boneLength);
	readAttenuationFile("Data/MassAttenuationCoefficients/water.txt", &water, &waterLength);
	readAttenuationFile("Data/MassAttenuationCoefficients/air.txt", &air, &airLength);
	readAttenuationFile("Data/MassAttenuationCoefficients/muscleSceletal.txt", &muscle, &muscleLength);
	readAttenuationFile("Data/MassAttenuationCoefficients/tissueSoft.txt", &tissue, &tissueLength);

	//Log attenuations if loglevel == trace
	i = 0;
	if(LOGLEVEL == TRACE){
		for(i = 0; i<ironLength; i++){
			logIt(TRACE, "iron[%d]: iron.energy: %f, iron.mu: %f\n", i, iron[i].energy, iron[i].mu);
		}
		for(i = 0; i<boneLength; i++){
			logIt(TRACE, "bone[%d]: bone.energy: %f, bone.mu: %f\n", i, bone[i].energy, bone[i].mu);
		}

		for(i = 0; i<waterLength; i++){
			logIt(TRACE, "water[%d]: water.energy: %f, water.mu: %f\n", i, water[i].energy, water[i].mu);
		}

		for(i = 0; i<airLength; i++){
			logIt(TRACE, "air[%d]: air.energy: %f, air.mu: %f\n", i, air[i].energy, air[i].mu);
		}

		for(i = 0; i<muscleLength; i++){
			logIt(TRACE, "muscle[%d]: muscle.energy: %f, muscle.mu: %f\n", i, muscle[i].energy, muscle[i].mu);
		}

		for(i = 0; i<tissueLength; i++){
			logIt(TRACE, "tissue[%d]: tissue.energy: %f, tissue.mu: %f\n", i, tissue[i].energy, tissue[i].mu);
		}
	}




	logIt(DEBUG, "setUpAttenuation() finished.");
}
Ejemplo n.º 17
0
//Reads table of attenuation coefficients and saves them to attenuation array
void readAttenuationFile(char* pathToAttFile, attenuation** att, size_t* attLength){
	char line[200];
	int i = 0;
	int numAlloc;
	FILE* read;
	logIt(DEBUG, "readAttenuationFile(char* pathToAttFile, attenuation** att, size_t* attLength) started.");

	read = fopen(pathToAttFile, "r");

	while(fgets(line, 200, read) != NULL){
		logIt(TRACE, "Line%d: %s", i, line);
		i++;
	}
	logIt(TRACE, "%d lines found.", i);
	numAlloc = i-6;
	*attLength = i-6;
	*att = malloc(numAlloc * sizeof(attenuation));
	if(att == 0){
		logIt(ERR, "out of memory");
	}
	logIt(TRACE,  "Allocated memory for %d attenuation elements.", numAlloc);
	fclose(read);
	read = fopen(pathToAttFile, "r");
	logIt(TRACE, "File reopened");
	i = 0;
	//read the header of the file and discard it
	fgets(line, 200, read);
	fgets(line, 200, read);
	fgets(line, 200, read);
	fgets(line, 200, read);

	while(i< numAlloc && fgets(line, 200, read) != NULL){
		fscanf(read, "%E  %E", &(((*att)[i]).energy), &(((*att)[i]).mu));
		logIt(TRACE, "att[%d]: energy: %f, mu: %f\n",i, (((*att)[i]).energy), (((*att)[i]).mu));
		i++;
	}
	//attenuation from the file should now be in the attenuation struct
	fclose(read);
	logIt(DEBUG, "readAttenuationFile(char* pathToAttFile, attenuation** att, size_t* attLength) finished.");
}
void netStats(char *summaryFile, int inCount, char *inFiles[])
/* netStats - Gather statistics on net. */
{
int i;
int netCount = 0;
FILE *gapFile = optionalFile("gap");
FILE *fillFile = optionalFile("fill");
FILE *topFile = optionalFile("top");
FILE *nonSynFile = optionalFile("nonSyn");
FILE *invFile = optionalFile("inv");
FILE *synFile = optionalFile("syn");
FILE *dupeFile = optionalFile("dupe");

intLm = lmInit(0);
logFile = mustOpen(summaryFile, "w");
logIt("net files: %d\n", inCount);
for (i=0; i<inCount; ++i)
    {
    struct lineFile *lf = lineFileOpen(inFiles[i], TRUE);
    struct chainNet *net;
    while ((net = chainNetRead(lf)) != NULL)
	{
	printf("%s\n", net->name);
	++netCount;
	traverseNet(net, NULL, depthGather);
	traverseNet(net, gapFile, gapGather);
	traverseNet(net, fillFile, fillGather);
	traverseNet(net, topFile, topGather);
	traverseNet(net, nonSynFile, nonSynGather);
	traverseNet(net, synFile, synGather);
	traverseNet(net, invFile, invGather);
	traverseNet(net, dupeFile, dupeGather);
	chainNetFree(&net);
	}
    lineFileClose(&lf);
    }

logIt("net chromosomes: %d\n", netCount);
logIt("max depth: %d\n", depthMax);
logIt("gap count: %d\n",  gapCount);
logIt("gap average size T: %4.1f\n", gapSizeT/(double)gapCount);
logIt("gap average size Q: %4.1f\n", gapSizeQ/(double)gapCount);
logFillStats("fill", &fillStats);
logFillStats("top", &topStats);
logFillStats("nonSyn", &nonSynStats);
logFillStats("syn", &synStats);
logFillStats("inv", &invStats);
logFillStats("dupe", &dupeStats);
}
Ejemplo n.º 19
0
void daemonSignalsHandler(int sig){
    switch(sig) {
        case SIGHUP:
            /* We restart the daemon */
            logIt("[OK] Restarting...");
            restartDaemon();
            break;
        case SIGTERM:
            /* We stop the daemon */
            closeDaemon();
            exit(EXIT_SUCCESS);
            break;
        case SIGINT:
            /* Ctrl c : we do nothing */
            break;
        case SIGCHLD:
            /* Child terminates */
            break;
    }
}
Ejemplo n.º 20
0
int main(int argc, char **argv) {
    
    if (argc != 3) {
        printf("Usage: plconvert <in file> <out file>\nIf the in file is an XML property list, convert to binary property list in out file. If the in file is a binary property list, convert to XML property list in out file.\n");
    } else {
        CFMutableDataRef plistData = createDataFromFile(argv[1]);
        if (!plistData) {
            printf("Unable to create data from file name: %s", argv[1]);
        } else {
            CFPropertyListFormat fmt;
            CFErrorRef err;
            CFPropertyListRef plist = CFPropertyListCreateWithData(kCFAllocatorSystemDefault, (CFDataRef)plistData, 0, &fmt, &err);
            if (!plist) {
                logIt(CFSTR("Unable to create property list from data: %@"), err);
            } else {
                logIt(CFSTR("Property list contents:\n%@"), plist);
                if (fmt == kCFPropertyListBinaryFormat_v1_0) {
                    logIt(CFSTR("Converting to XML property list at: %s"), argv[2]);
                    fmt = kCFPropertyListXMLFormat_v1_0;
                } else if (fmt == kCFPropertyListXMLFormat_v1_0) {
                    logIt(CFSTR("Converting to binary property list at: %s"), argv[2]);
                    fmt = kCFPropertyListBinaryFormat_v1_0;
                } else {
                    logIt(CFSTR("Unknown property list format! Not converting output format."));
                }
                
                CFDataRef outputData = CFPropertyListCreateData(kCFAllocatorSystemDefault, plist, fmt, 0, &err);
                if (!outputData) {
                    logIt(CFSTR("Unable to write property list to data: %@"), err);
                } else {
                    bool success = writeDataToFile(outputData, argv[2]);
                    if (!success) {
                        logIt(CFSTR("Unable to write data to file"));
                    }
                    CFRelease(outputData);
                }
                CFRelease(plist);
            }
            CFRelease(plistData);
        }
    }
}
void logFillStats(char *name, struct fillStats *stats)
/* Write out info on stats */
{
logIt("%s count: %d\n", name, stats->count);
logIt("%s aligned: %lld\n", name, stats->totalAli);
logIt("%s percent of total: %3.1f%%\n", name, 
	100.0*stats->totalAli/fillStats.totalAli);
logIt("%s span-T: ", name);
logListStats(&stats->spanT);
logIt("%s span-Q: ", name);
logListStats(&stats->spanQ);
logIt("%s aligning: ", name);
logListStats(&stats->ali);
if (stats->qDup != NULL)
    {
    logIt("%s ave-qDup: ", name);
    logListStats(&stats->qDup);
    }
if (stats->qFar != NULL)
    {
    logIt("%s ave-qFar: ", name);
    logListStats(&stats->qFar);
    }
}
Ejemplo n.º 22
0
ESR_ReturnCode SR_EventLog_Event(SR_EventLog* self, const LCHAR* event)
{
  SR_EventLogImpl *impl = (SR_EventLogImpl *)self;
  ESR_ReturnCode rc;
  long userTime, kernelTime;
  long cpuTime;
  LCHAR buf[P_PATH_MAX];  /* allow space for EVNT=<blah> */
  size_t writtenSize;

  if (impl == NULL || event == NULL)
    return ESR_INVALID_ARGUMENT;
  if (impl->logLevel == 0)
    return ESR_SUCCESS;

  /* event cannot contain '=' */
  if (LSTRCHR(event, L('=')) != NULL)
  {
    PLogError(L("SLEE: SR_EventLog_Event: warning: "
                "SR_EventLog_Event failed.  Event '%s' contains illegal '=' "
                "character\n"), event);
    return ESR_INVALID_ARGUMENT;
  }

  CHKLOG(rc, PGetCPUTimes(&userTime, &kernelTime));

  if (!LSTRCMP(event, "SWIrcst"))
  {
    impl->serviceStartUserCPU = userTime;
    impl->serviceStartKernelCPU = kernelTime;
  }

  LSTRCPY(buf, event);
  if (quote_delimiter(buf, LSTRLEN(buf) + 1) != 0)
  {
    PLogError(L("ESR_BUFFER_OVERFLOW: '%s' exceeds 8 characters when '|' characters are quoted"), buf);
    return ESR_BUFFER_OVERFLOW;
  }

  /* if this event is an end-of-recognition event then check to see if we
     want to capture this waveform. */

  if (!LSTRCMP(event, "SWIrcnd"))
  {
    /* what to do ??? ALTsleeLogCheckWaveCapture(data); */
  }

  cpuTime = userTime - impl->serviceStartUserCPU;
  SR_EventLogTokenInt(self, L("UCPU"), cpuTime);
  cpuTime = kernelTime - impl->serviceStartKernelCPU;
  SR_EventLogTokenInt(self, L("SCPU"), cpuTime);


  sprintf(buf, "EVNT=%s", event);
  /* This call will set writtenSize to be some value >= 0 */
  logIt(impl, buf, impl->tokenBuf, &writtenSize);
  impl->tokenBuf[0] = 0;

  return ESR_SUCCESS;
CLEANUP:
  return rc;
}
Ejemplo n.º 23
0
void daemonize(){
    /* Our process ID and Session ID */
    pid_t pid, sid;
    /* lock file */
    char pidstr[10];
    /* Signals */
    sigset_t sig_proc;
    struct sigaction action;

    /* Fork off the parent process */
    pid = fork();
    if (pid < 0) {
        printf("[ERROR] Fork failed.\n");
        exit(EXIT_FAILURE);
    }
    /* If we got a good PID, then we can exit the parent process. */
    if (pid > 0) {
        printf("[OK] Launching...\n");
        exit(EXIT_SUCCESS);
    }

    /* Change the file mode mask */
    umask(027);

    /* Create a new SID for the child process */
    sid = setsid();
    if (sid < 0) {
        /* Log the failure */
        printf("[ERROR] setsid() failed.\n");
        exit(EXIT_FAILURE);
    }

    /* Change the current working directory */
    if ((chdir(RUNNINGDIR)) < 0){
        printf("[ERROR] Cannot chdir to the running directory.\n");
        exit(EXIT_FAILURE);
    }

    /* Create pid file & lock it */
    lockfile=open("pid.lock",O_RDWR|O_CREAT,0640);
    if (lockfile < 0){
        printf("[ERROR] Cannot open logfile. Exiting...\n");
        logIt("[ERROR] Cannot open logfile. Exiting...");
        exit(EXIT_FAILURE);
    }
    if (lockf(lockfile,F_TLOCK,0 ) < 0){
        printf("[ERROR] The daemon seems to be launched already. Exiting...\n");
        logIt("[ERROR] The daemon seems to be launched already. Exiting...");
        exit(EXIT_FAILURE);
    }
    sprintf(pidstr, "%d\n", getpid());
    write(lockfile, pidstr, strlen(pidstr));

    /* Handle the signals */
    sigemptyset(&sig_proc);
    action.sa_mask=sig_proc;
    action.sa_flags=0;
    action.sa_handler = daemonSignalsHandler;
    sigaction(SIGINT, &action,0);
    sigaction(SIGTERM, &action,0);
    sigaction(SIGHUP, &action,0);
    sigaction(SIGCHLD, &action,0);

    /* Close out the standard file descriptors */
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    /* Daemon-specific initialization goes here */
    logIt("[OK] Initialized.");
}
Ejemplo n.º 24
0
void closeDaemon(){
    logIt("[OK] Exiting...");
    close(lockfile);
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 25
0
/*
	This is the primary host code.
 */
int reconstruct(FILE *dataFile){
	int j, i;
	float min, max;
	FILE *fileOut;
	float *orig_sinogram;
	float *filt_sinogram;
	float *output;
	float deltaTheta;
	size_t size_sinogram = imgwidth*numangles*sizeof(float);
	size_t size_result = imgwidth*imgheight*sizeof(float);
	logIt(DEBUG, "reconstruct(FILE *dataFile) started.");

	output = (float *)malloc(size_result);




	// Reserve host memory for sinogram versions
	orig_sinogram = (float *)malloc(size_sinogram);
	filt_sinogram = (float *)malloc(size_sinogram);


	if (dataFile == NULL){
		logIt(ERR, "Data file: data was not found.");
		return 0;
	}

	//Read in sinogram from text file. This is probably a slow point!
	for(i=0; i < numangles*imgwidth; i++){
		fscanf(dataFile,"%f",&orig_sinogram[i]);
	}




	fclose(dataFile);

	//Create filter and save to device memory. The filter is never viewed on the host.
	createFilter();

	// Filtere the lines of the sinogram using the generated filter.
	filterSinogram(orig_sinogram, filt_sinogram);

	deltaTheta = PI/cfg.numberOfProjectionAngles;  //delta theta in radians
	// Back Project and reconstruct full image pixel by pixel.

	backProject(deltaTheta, output, filt_sinogram);
	logIt(DEBUG, "Backprojection finished.");
	fileOut = fopen(outputPath, "wb");
	fprintf(fileOut, "P2\n%d %d\n255\n", imgwidth, imgheight);



	min = output[0];
	max = output[0];
	for(j = 0; j<imgheight*imgwidth; j++){
		if(output[j]<min){
			min = output[j];
		}

		if(output[j]>max){
			max = output[j];
		}
	}

	//Export image data.
	for(j=0;j<imgwidth;j++){
		for(i = 0; i< imgheight; i++){
			//printf("%e ",output_host[j*IMG_WIDTH + i]);
			fprintf(fileOut,"%d ",(int)((output[j*imgwidth + i]-min)/(max-min)*255.0));
			//fwrite((const void *) &(output_host[j*IMG_WIDTH + i]), 1,3,fileOut);


		}

	}



	//Free all remaining host memory.
	free(orig_sinogram);
	free(filt_sinogram);
	free(output);
	fclose(fileOut);

	logIt(DEBUG, "reconstruct(FILE *dataFile) finished.");
	return 0;
}
Ejemplo n.º 26
0
int findBestMove(Communicator comm, char origB[BS], char color, int depth) {

	int wallClockTime;
	int processorTime;
	int boardCount;

	int possibleMoves[BS];
	int scores[BS];
	int totalWorkRequests = 0;
	int i;
	int resultScores[BS];
	int resultCount[BS];
	char logBuffer[200];
    struct timeval startTime, endTime;

	gettimeofday(&startTime, NULL);

	
	WorkRequest* wReq;// = new WorkRequest();
	
	validMoves(origB, color, possibleMoves, scores);

	// seed the system - push all current valid moves onto the queue one at a time
	cout << "Ready to process possible moves.\n";
	wReq = new WorkRequest();
	processorTime = 0;
	boardCount = 0;
	wallClockTime = 0;
	for (int whichPossibleMove=0; possibleMoves[whichPossibleMove]; whichPossibleMove++) {
		strncpy(wReq->b,origB,BS);
		wReq->color = color;
		wReq->depth = depth;
		wReq->history[1] = 0;

		resultScores[possibleMoves[whichPossibleMove]] = 0;
		resultCount[possibleMoves[whichPossibleMove]] = 0;
		
		wReq->history[0] = possibleMoves[whichPossibleMove];

		processRequest(comm, wReq, totalWorkRequests, resultScores, resultCount);
		cout << comm.rank << "\tDone processing " << possibleMoves[whichPossibleMove] << endl;
	}
	delete wReq;

	gettimeofday(&endTime, NULL);
	
	int elapsed = elapsedTime(&endTime, &startTime);
	logIt(elapsed);
	
	cout << "*********************************************" << endl;
	cout << "***    all done processing possible moves  **" << endl;
	cout << "*********************************************" << endl;
	cout << "requests sent: " << totalWorkRequests << endl;


	double bestValue = -9.0e100;
	int bestPosition = 0;
	for (i=0; possibleMoves[i]; i++) {
		int move = possibleMoves[i];
		double finalScore = (double)resultScores[move] / (double)resultCount[move];
		cout << "Position " << move << " final score: " << finalScore << " (" << resultScores[move] << "/" << resultCount[move] << ")" << endl;
		if (bestValue < finalScore) {
			bestValue = finalScore;
			bestPosition = move;
		}
	}
  	cout << "best position appears to be " << bestPosition << endl;

	return bestPosition;
}
Ejemplo n.º 27
0
/*
	This is the main kernel for the reconstruction. Each thresad operates on a
	single pixel of the fully reconstructed image.  For each angel in the sinogram,
	the thread calculates which pixel out of that line of the sinogram would be
	projected onto the pixel that the thread is computing.  This pixel value
	is added to the pixel value and then the thread moves on to the next angel
	and therefore the next line of the sinogram.
 */
void backProject(float deltaTheta, float *resultImage, float *sinogram){

	int i, j, k;
	float cosTheta;
	float sinTheta;
	float ninety = PI/2.0f;
	float one_eighty = PI;
	int index;
	logIt(DEBUG, "backProject(float deltaTheta, float *resultImage, float *sinogram) started.");
	//iterate over each row of the sinogram each thread gets one pixel from the line.
	for (j = 0; j < imgheight; j++){
		for (k = 0; k < imgwidth; k++){
			float finalPixel = 0.0f;
			float theta = 0.0f;
			for(i = 0; i < numangles; i++){
				cosTheta = cos(theta);
				sinTheta = sin(theta);


				//Check for boundary conditions, infinite slope lines
				if (theta == 0.0f){
					index = k;
				}
				else if(theta == ninety){
					index = 511 - j;
				}
				else if(theta == one_eighty){
					index = 511 - k;
				}
				// Do normal computation for non-corner cases
				else{
					//Calculate slopes of both lines.
					float m1 = -cosTheta/sinTheta;
					float m2 = sinTheta/cosTheta;
					// Calculate x coordinate of lines intersection
					float x = ((255.0f - j) - m1*(k - 256.0f))/(m2-m1);
					// calculate the distance from origin to desired point on rotated line.
					float d = abs(x)*sqrt(1+pow(m2,2));
					//Calculate index into sinogram row for this angel
					if (theta < ninety){
						if (x < 0.0f)
							index = 256 + floor(d);
						else
							index = 256 - floor(d);
					}
					else{// theta > 90.0
						if (x < 0.0f)
							index = 256 - floor(d);
						else
							index = 256 + floor(d);
					}
				}

				// boundary check and update running sum
				if(index >= 0 && index < 512){
					finalPixel += sinogram[index+i*512];
				}
				theta += deltaTheta;
			}
			// do one coherent write for the block back to global memory of the fully reconstructed pixel
			resultImage[k + j*imgwidth] = finalPixel;
		}
	}
	logIt(DEBUG, "backProject(float deltaTheta, float *resultImage, float *sinogram) finished.");
}
Ejemplo n.º 28
0
double getInterpolatedAttenuationValue(int material, double energy) {
	attenuation* mat;
	size_t matLength;
	int i = 0;
	logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) started.");

	switch(material){
	case IRON:
		logIt(TRACE, "Material ID%d: iron", material);
		mat = iron;
		matLength = ironLength;
		break;
	case BONE:
		logIt(TRACE, "Material ID%d: bone", material);
		mat = bone;
		matLength = boneLength;
		break;
	case WATER:
		logIt(TRACE, "Material ID%d: water", material);
		mat = water;
		matLength = waterLength;
		break;
	case AIR:
		logIt(TRACE, "Material ID%d: air", material);
		mat = air;
		matLength = airLength;
		break;
	case MUSCLE:
		logIt(TRACE, "Material ID%d: muscle", material);
		mat = muscle;
		matLength = muscleLength;
		break;
	case TISSUE:
		logIt(TRACE, "Material ID%d: tissue", material);
		mat = tissue;
		matLength = tissueLength;
		break;
	default:
		logIt(ERR, "Material ID%d not found!", material);
		logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) finished.");
		return 0.0f;
	}



	if(energy < mat[0].energy){
		//extrapolate in the lower end
		logIt(TRACE, "extrapolating in the lower end");
		logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) finished.");
		return (((mat[1].mu - mat[0].mu)/(mat[1].energy - mat[0].energy))*(energy - mat[0].energy) + mat[0].mu);
	}
	for(i = 0; i<matLength; i++){
		if(energy-mat[i].energy < 0.000001){
			logIt(TRACE, "perfect match");
			logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) finished.");
			return mat[i].mu;
		}
		if(energy>mat[i].energy && energy<mat[i+1].energy){
			//interpolate here
			logIt(TRACE, "interpolate between element[%d]: (energy: %f, mu: %f) and element[%d]: (energy: %f, mu: %f)", i, mat[i].energy, mat[i].mu, i+1, mat[i+1].energy, mat[i+1].mu);
			logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) finished.");
			return (((mat[i+1].mu - mat[i].mu)/(mat[i+1].energy - mat[i].energy))*(energy - mat[i].energy) + mat[i].mu);
		}
	}
	//extrapolate in the upper end
	logIt(TRACE, "extrapolating in the upper end");
	logIt(TRACE, "getInterpolatedAttenuation(int material, double energy) finished.");
	return (((mat[matLength-1].mu - mat[matLength-2].mu)/(mat[matLength-1].energy - mat[matLength-2].energy))*(energy - mat[matLength-1].energy) + mat[matLength-1].mu);
}
Ejemplo n.º 29
0
int main(int argc, char** argv) {
	char b[BS];
	int r, c;


	Communicator comm(argc, argv);
	int validHMoves[BS];
	int validCMoves[BS];
	int scoreHMoves[BS];
	validCMoves[0] = 0;
	char buf[100];
	ofstream outputFile;
	if (comm.rank == 0) {
		
		sprintf(buf,"\n\nP = %d", comm.nprocs);
		logIt(buf);
		int hMove = 0;
		int depth = atoi(argv[1]);
		
		srand((int) time(NULL));
		setupBoard(b);
		do {
			validMoves(b,H,validHMoves,scoreHMoves);
			displayBoard(b);
			if (validHMoves[0]) {
				hMove = moveHuman(b,validHMoves);	// to get a manually entered move
				if (hMove == 0) {
					break;
				}
				cout << "After your move the board is:\n";
				displayBoard(b,C);
			} else {
				cout << "You Don't have any valid moves.\n";
			}
			cout << "Computer is plotting your demise.\n";

			int best = findBestMove(comm, b, C, depth);

			if (best != 0) {
				squareScore(b,best,C,true);
				aiToBs(best, r, c);
				cout << "Computer moves to [" << r << "," << c << "]\n";
			} else {
				cout << "Computer does not have a valid move\n";
			}
		} while ((validCMoves[0] || validHMoves[0]) && (hMove != 0));

		WorkRequest* wReq = new WorkRequest();
		wReq->b[0] = 'T';
		for(int i = 1; i < comm.nprocs; i++)
			comm.send(i, (char *) wReq, 1, TAG_DO_THIS_WORK);
		cout << "\n\nGame over\n\n";
		
	} else { // not comm.rank 0
		worker(comm);
	}
	
	comm.finalize();
	
	return (EXIT_SUCCESS);
}