Beispiel #1
0
bool  FITSViewer::initFITS()
{

    free(imgBuffer);
    imgBuffer = NULL;
    image->clearMem();
    
  /* Load image into buffer */
    if ( (imgBuffer = loadData (currentURL.path().ascii(), imgBuffer)) == NULL)  { close(); return false; }
    /* Display image in the central widget */
    if (image->loadFits(currentURL.path().ascii()) == -1) { close(); return false; }

    /* Clear history */
    history->clear();
    
    /* Set new file caption */
    setCaption(currentURL.fileName());
    
    /* Get initial statistics */
    calculateStats();
    
    image->viewport()->resize(image->viewport()->width() + 5, image->viewport()->height());
    image->viewportResizeEvent(NULL);
    
    return true;

}
double ProbabilityOfMatch::modelProbability(const ConstOsmMapPtr& map,
  const shared_ptr<const Way>& w1, const shared_ptr<const Way>& w2, double portionScore)
{
  std::map<QString, double> sample = calculateStats(map, w1, w2, portionScore);

  return _model.evaluate(sample);
}
void GeneticPopulation::evolve() {

	std::sort(population.begin(), population.end());

	calculateStats();
	Genomes newPopulation;

	assert((bestTopN * bestCopies) % 2 == 0);
	assert(population.size() % 2 == 0);

	pickBest(bestTopN, bestCopies, newPopulation);

	while (newPopulation.size() < population.size()) {
		Genome parent1 = pickRoulette();
		Genome parent2 = pickRoulette();

		Weights child1, child2;

		crossover(parent1.weights, parent2.weights, child1, child2);

		mutate(child1);
		mutate(child2);

		newPopulation.push_back(Genome(child1, 0));
		newPopulation.push_back(Genome(child2, 0));
	}

	population = newPopulation;
}
Beispiel #4
0
void FITSViewer::imageReduction()
{
  FITSProcessCommand *cbc;
  FITSHistogramCommand *hbc;
  QStringList darkFiles, flatFiles, darkflatFiles;
  int darkCombineMode = 0 , flatCombineMode = 0, darkflatCombineMode =0;
  QListViewItem *file;
  
  image->saveTemplateImage();
  ImageReductionDlg irDialog(this);
     
  if (irDialog.exec() == QDialog::Accepted)
  {
    if (irDialog.darkListView->childCount() == 0 && 
        irDialog.flatListView->childCount() == 0)
	{
	 image->destroyTemplateImage();
	 return;
	}
     
    darkCombineMode    = irDialog.darkAverageB->isChecked() ? 0 : 1;
    flatCombineMode    = irDialog.flatAverageB->isChecked() ? 0 : 1;
    darkflatCombineMode= irDialog.darkflatAverageB->isChecked() ? 0 : 1;
     
    file = irDialog.darkListView->firstChild();
    while (file)
    {
      darkFiles << file->text(0);
      file = file->nextSibling();
    }
    
    file = irDialog.flatListView->firstChild();
    while (file)
    {
      flatFiles << file->text(0);
      file = file->nextSibling();
    }
    
    file = irDialog.darkflatListView->firstChild();
    while (file)
    {
      darkflatFiles << file->text(0);
      file = file->nextSibling();
    }
      
      cbc = new FITSProcessCommand(this);
      FITSProcess reduc(this, darkFiles, flatFiles, darkflatFiles, darkCombineMode, flatCombineMode, darkflatCombineMode);
      reduc.reduce();
      history->addCommand(cbc, false);
      calculateStats();
      hbc = new FITSHistogramCommand(this, NULL, FITSImage::FITSLinear, (int) stats.min, (int) stats.max);
      history->addCommand(hbc);
      fitsChange();
  }
  
  image->destroyTemplateImage();

}
Beispiel #5
0
    void ICharacter::setImbue (const Imbue &imbue)
    {
        boost::mutex::scoped_lock lock(m_buff_mutex);

        m_Imbue = imbue;

        lock.unlock();

        calculateStats();
    }
Beispiel #6
0
void NetInfo::calculateStats(unsigned int timeToDiscard, unsigned int analyzerSleepTime) {
    adquireLock(this);
    this->maxPackets = timeToDiscard*SECtoMICROSEC/interval;
    
    if (not beacons.empty()) {
        if ((lastDelay != 0 or timeOK < timeToDiscard) and bestIndex >= 0) {
            numPackets = beacons.size();
            if (not calculateStats(false) and lastDelay < 0.8) timeOK = 0;
            else if (timeOK < timeToDiscard) timeOK += analyzerSleepTime;
        }
        removeOldBeacons(timeToDiscard);
        selectBest();
        calculateStats(true);
        statsTimestamp = time(NULL);
        ok = timeOK >= timeToDiscard;
    }
    
    releaseLock(this);
}
Beispiel #7
0
void FITSViewer::updateImgBuffer()
{
  int width = image->width;
  int height = image->height;
  
  for (int i=0; i < height; i++)
    for (int j=0; j < width; j++)
       imgBuffer[i * width + j] = (int) *(image->displayImage->scanLine(height - i - 1) + j);
       //image->reducedImgBuffer[i * width + j];

   calculateStats();
}
Beispiel #8
0
    void ICharacter::addBuff (const Buff &buff)
    {
        assert(buff.skill->refID());

        if (buff.skill->hasBuffs())
        {
            boost::mutex::scoped_lock lock(m_buff_mutex);

            m_buff_list.insert(std::make_pair(buff.skill->refID(),buff));

            lock.unlock();

            calculateStats();
        }
    }
Beispiel #9
0
void DLProcess::parsePBILine(QString line){
  //Quick checks for line formatting
  if( line.startsWith("FETCH:") ){ emit UpdateMessage(tr("Download Starting...")); return; }
  else if( line == "FETCHDONE"){ emit UpdateMessage(tr("Download Finished")); return; }
  else if(!line.startsWith("SIZE:")){ emit UpdateMessage(line); return; }
  //Now parse the PBI download line
  //qDebug() << "parse Download Line:" << line;
  //Line format: SIZE:  <KB> DOWNLOADED:  <KB> SPEED:  <KB/s> KB/s
  line = line.simplified();
  line.replace("SIZE: ","");
  line.replace("DOWNLOADED: ", "");
  line.replace("SPEED: ","");
  line.replace("KB/s","");
  //Now run the calculations and emit the signal
  calculateStats(line.section(" ",1,1), line.section(" ",0,0), line.section(" ",2,2), "");
}
Beispiel #10
0
void FITSViewer::fitsStatistics()
{
  statForm stat(this);
  
  calculateStats();
  
  stat.widthOUT->setText(QString("%1").arg(stats.width));
  stat.heightOUT->setText(QString("%1").arg(stats.height));
  stat.bitpixOUT->setText(QString("%1").arg(stats.bitpix));
  stat.maxOUT->setText(QString("%1").arg(stats.max));
  stat.minOUT->setText(QString("%1").arg(stats.min));
  stat.atMaxOUT->setText(QString("%1").arg(stats.maxAt));
  stat.atMinOUT->setText(QString("%1").arg(stats.minAt));
  stat.meanOUT->setText(QString("%1").arg(stats.average));
  stat.stddevOUT->setText(QString("%1").arg(stats.stddev));
  
  stat.exec();

}
Beispiel #11
0
    std::pair<uint32_t,uint32_t> ICharacter::removeImbue (const uint32_t skillID, bool signal)
    {
        boost::mutex::scoped_lock lock(m_buff_mutex);

        std::pair<uint32_t,uint32_t> ret = std::make_pair(0,0);

        if (m_Imbue.skill && m_Imbue.skill->refID() == skillID)
        {
            ret = std::make_pair(m_Imbue.taskID,m_Imbue.castID);

            m_Imbue = Imbue();

            lock.unlock();

            if (signal)
                calculateStats();
        }

        return ret;
    }
Beispiel #12
0
    std::pair<uint32_t,uint32_t> ICharacter::removeBuff (const uint32_t SkillID, bool signal)
    {
        boost::mutex::scoped_lock lock(m_buff_mutex);

        std::pair<uint32_t,uint32_t> ret = std::make_pair(0,0);
        std::map<uint32_t,Buff>::iterator i = m_buff_list.find(SkillID);

        if (i != m_buff_list.end())
        {
            ret = std::make_pair(i->second.taskID,i->second.CastID);

            m_buff_list.erase(i);

            lock.unlock();

            if (signal)
                calculateStats();
        }

        return ret;
    }
Beispiel #13
0
// Runs a full round of experiments
void performExperiments(struct parameters* params,
                        unsigned int nGenerations,
                        unsigned int nRepeats,
                        const std::string& nodeFunctions) {
  setCustomFitnessFunction(params, fitness, "PocMan Level 1");

  struct chromosome* bestChromosome = nullptr;
  double bestFitness = DBL_MAX;
  std::vector<double> fitnesses;
  std::vector<double> durations;
  fitnesses.reserve(nRepeats);
  durations.reserve(nRepeats);

  for (unsigned int i = 0; i < nRepeats; i++) {
    // Run CGP, record the results
    auto start = std::chrono::steady_clock::now();
    struct chromosome* chromo = runCGP(params, nullptr, nGenerations);
    auto end = std::chrono::steady_clock::now();

    double fitness = getChromosomeFitness(chromo);
    fitnesses.push_back(fitness);

    std::chrono::duration<double> diff = end - start;
    double duration = diff.count();
    durations.push_back(duration);

    // Should we keep this chromosome?
    if (fitness < bestFitness) {
      if (bestChromosome != nullptr)
        freeChromosome(bestChromosome);
      bestChromosome = chromo;
      bestFitness = fitness;
    } else {
      freeChromosome(chromo);
    }
  }

  // Stats!
  double meanFitness, stdevFitness, minFitness, maxFitness;
  std::tie(meanFitness, stdevFitness, minFitness, maxFitness) = calculateStats(fitnesses);

  double meanDuration, stdevDuration, minDuration, maxDuration;
  std::tie(meanDuration, stdevDuration, minDuration, maxDuration) = calculateStats(durations);

  // Logging!
  log("### PARAMETERS\n");
  log(parametersToString(params));
  log("generations: " + std::to_string(nGenerations) + "\n");
  log("\n--------------------\n\n");
  log("### FITNESS VALUES\n");
  for (unsigned int i = 0; i < nRepeats; i++)
    log("(" + std::to_string(i + 1) + "):\t" + std::to_string(fitnesses[i]) + "\n");
  log("\n--------------------\n\n");
  log("### STATISTICS (FITNESS)\n");
  log("mean : " + std::to_string(meanFitness) + "\n");
  log("std  : " + std::to_string(stdevFitness) + "\n");
  log("rng  : " + std::to_string(minFitness) +":" + std::to_string(maxFitness) + "\n");
  log("\n--------------------\n\n");
  log("### DURATION VALUES\n");
  for (unsigned int i = 0; i < nRepeats; i++)
    log("(" + std::to_string(i + 1) + "):\t" + std::to_string(durations[i]) + "\n");
  log("\n--------------------\n\n");
  log("### STATISTICS (DURATIONS)\n");
  log("mean : " + std::to_string(meanDuration) + "\n");
  log("std  : " + std::to_string(stdevDuration) + "\n");
  log("rng  : " + std::to_string(minDuration) + ":" + std::to_string(maxDuration) + "\n");
  log("\n--------------------\n\n");
  log("### BEST CHROMOSOME\n");
  log(chromosomeToString(bestChromosome, 0));
  log("\n--------------------\n\n");
  log("### GAMEPLAY TRACE\n");
  log(controller.generateGameTrace(bestChromosome));
}
Beispiel #14
0
void ImageWriter::writeImage(QString theInputFileString, QString theOutputFileString)
{
	//printf("Started with input :  %s output: %s \n",theInputFileString,theOutputFileString);
	GDALAllRegister();
	GDALDataset  *gdalDataset = (GDALDataset *) GDALOpen( theInputFileString, GA_ReadOnly );
	if ( gdalDataset == NULL )
	{
		//valid = FALSE;
		return ;
	}
	int myXDimInt = gdalDataset->GetRasterXSize();
	int myYDimInt = gdalDataset->GetRasterYSize();
	printf("Raster is %i x %i cells\n", myXDimInt, myYDimInt);
	GDALRasterBand  *myGdalBand = gdalDataset->GetRasterBand( 1 );
	// RasterIO() takes care of scaling down image
	uint *myGdalScanData = (uint*) CPLMalloc(sizeof(uint)*myXDimInt * sizeof(uint)*myYDimInt);
	CPLErr myResultCPLerr = myGdalBand->RasterIO(GF_Read, 0, 0, myXDimInt, myYDimInt, myGdalScanData, myXDimInt, myYDimInt, GDT_UInt32, 0, 0 );
	QImage myQImage=QImage(myXDimInt,myYDimInt,32);
	myQImage.setAlphaBuffer(true);
	uint stdDevsToPlotDouble=0;
	bool invertHistogramFlag=false;
	int transparencyLevelInt=255;
	//calculate the adjusted matrix stats - which come into affect if the user has chosen

	RasterBandStats * myAdjustedRasterBandStats = new RasterBandStats();
	calculateStats(myAdjustedRasterBandStats, gdalDataset);

	myAdjustedRasterBandStats->noDataDouble=0;//hard coding for now
	//to histogram stretch to a given number of std deviations
	//see if we are using histogram stretch using stddev and plot only within the selected number of deviations if we are
	//cout << "stdDevsToPlotDouble: " << cboStdDev->currentText() << " converted to " << stdDevsToPlotDouble << endl;
	if (stdDevsToPlotDouble > 0)
	{
		//work out how far on either side of the mean we should include data
		float myTotalDeviationDouble = stdDevsToPlotDouble * myAdjustedRasterBandStats->stdDevDouble;
		//printf("myTotalDeviationDouble: %i\n" , myTotalDeviationDouble );
		//adjust min and max accordingly
		//only change min if it is less than mean  -  (n  x  deviations)
		if (myAdjustedRasterBandStats->minValDouble < (myAdjustedRasterBandStats->meanDouble-myTotalDeviationDouble))
		{
			myAdjustedRasterBandStats->minValDouble=(myAdjustedRasterBandStats->meanDouble-myTotalDeviationDouble);
			//cout << "Adjusting minValDouble to: " << myAdjustedRasterBandStats->minValDouble << endl;
		}
		//only change max if it is greater than mean  +  (n  x  deviations)
		if (myAdjustedRasterBandStats->maxValDouble > (myAdjustedRasterBandStats->meanDouble + myTotalDeviationDouble))
		{
			myAdjustedRasterBandStats->maxValDouble=(myAdjustedRasterBandStats->meanDouble+myTotalDeviationDouble);
			//cout << "Adjusting maxValDouble to: " << myAdjustedRasterBandStats->maxValDouble << endl;
		}
		//update the range
		myAdjustedRasterBandStats->rangeDouble = myAdjustedRasterBandStats->maxValDouble-myAdjustedRasterBandStats->minValDouble;
	}

	printf("Main ::\n");
	std::cout << "Band Name   : " << myAdjustedRasterBandStats->bandName << std::endl;
	printf("Band No   : %i\n",myAdjustedRasterBandStats->bandNo);
	printf("Band min  : %f\n",myAdjustedRasterBandStats->minValDouble);
	printf("Band max  : %f\n",myAdjustedRasterBandStats->maxValDouble);
	printf("Band range: %f\n",myAdjustedRasterBandStats->rangeDouble);
	printf("Band mean : %f\n",myAdjustedRasterBandStats->meanDouble);
	printf("Band sum : %f\n",myAdjustedRasterBandStats->sumDouble);

	//double sumSqrDevDouble; //used to calculate stddev
	//double stdDevDouble;
	//double sumDouble;
	//int elementCountInt;
	//double noDataDouble;

	//set up the three class breaks for pseudocolour mapping
	double myBreakSizeDouble = myAdjustedRasterBandStats->rangeDouble / 3;
	double myClassBreakMin1 = myAdjustedRasterBandStats->minValDouble;
	double myClassBreakMax1 = myAdjustedRasterBandStats->minValDouble + myBreakSizeDouble;
	double myClassBreakMin2 = myClassBreakMax1;
	double myClassBreakMax2 = myClassBreakMin2 + myBreakSizeDouble;
	double myClassBreakMin3 = myClassBreakMax2;
	double myClassBreakMax3 = myAdjustedRasterBandStats->maxValDouble;

	printf ("ClassBreak size : %f \n",myBreakSizeDouble);
	printf ("ClassBreak 1 : %f - %f\n",myClassBreakMin1,myClassBreakMax1);
	printf ("ClassBreak 2 : %f - %f\n",myClassBreakMin2,myClassBreakMax2);
	printf ("ClassBreak 3 : %f - %f\n",myClassBreakMin3,myClassBreakMax3);

	int myRedInt=0;
	int myGreenInt=0;
	int myBlueInt=0;
	for (int myColumnInt = 0; myColumnInt < myYDimInt; myColumnInt++)
	{
		for (int myRowInt =0; myRowInt < myXDimInt; myRowInt++)
		{
			int myInt=myGdalScanData[myColumnInt*myXDimInt + myRowInt];
			//dont draw this point if it is no data !
			//double check that myInt >= min and <= max
			//this is relevant if we are plotting within stddevs
			if ((myInt < myAdjustedRasterBandStats->minValDouble ) && (myInt != myAdjustedRasterBandStats->noDataDouble))
			{
				myInt = static_cast<int>(myAdjustedRasterBandStats->minValDouble);
			}
			if ((myInt > myAdjustedRasterBandStats->maxValDouble)   && (myInt != myAdjustedRasterBandStats->noDataDouble))
			{
				myInt = static_cast<int>(myAdjustedRasterBandStats->maxValDouble);
			}
			if (myInt==myAdjustedRasterBandStats->noDataDouble)
			{
				//hardcoding to white for now
				myRedInt = 255;
				myBlueInt = 255;
				myGreenInt =255;
			}
			else if(!invertHistogramFlag)
			{
				//check if we are in the first class break
				if ((myInt >= myClassBreakMin1) &&  (myInt < myClassBreakMax1) )
				{
					myRedInt = 0;
					myBlueInt = 255;
					myGreenInt = static_cast<int>(((255/myAdjustedRasterBandStats->rangeDouble) * (myInt-myClassBreakMin1))*3);
				}
				//check if we are in the second class break
				else if ((myInt >= myClassBreakMin2) &&  (myInt < myClassBreakMax2) )
				{
					myRedInt = static_cast<int>(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin2)/1))*3);
					myBlueInt = static_cast<int>(255-(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin2)/1))*3));
					myGreenInt = 255;
				}
				//otherwise we must be in the third classbreak
				else
				{
					myRedInt = 255;
					myBlueInt = 0;
					myGreenInt = static_cast<int>(255-(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin3)/1)*3)));
				}
			}
			else  //invert histogram toggle is on
			{
				//check if we are in the first class break
				if ((myInt >= myClassBreakMin1) &&  (myInt < myClassBreakMax1) )
				{
					myRedInt = 255;
					myBlueInt = 0;
					myGreenInt = static_cast<int>(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin1)/1)*3));
				}
				//check if we are in the second class break
				else if ((myInt >= myClassBreakMin2) &&  (myInt < myClassBreakMax2) )
				{
					myRedInt = static_cast<int>(255-(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin2)/1))*3));
					myBlueInt = static_cast<int>(((255/myAdjustedRasterBandStats->rangeDouble) * ((myInt-myClassBreakMin2)/1))*3);
					myGreenInt = 255;
				}
				//otherwise we must be in the third classbreak
				else
				{
					myRedInt = 0;
					myBlueInt = 255;
					myGreenInt = static_cast<int>(255-(((255/myAdjustedRasterBandStats->rangeDouble) * (myInt-myClassBreakMin3))*3));
				}
			}
			myQImage.setPixel( myRowInt, myColumnInt, qRgba( myRedInt, myGreenInt, myBlueInt, transparencyLevelInt ));
		}
	}
	//draw with the experimental transaparency support
	CPLFree(myGdalScanData);
	GDALClose(gdalDataset);
	printf("Saving image...\n");
	myQImage.save(theOutputFileString,"PNG");
	return ;
}
/**
 *	This gets the number of calculated chunks.
 *
 *  @return				The number of calculated chunks.
 */
size_t ChunkWatcher::numberCalcedChunks() const
{
	if (!numbersValid_)
		calculateStats();
	return numCalced_;
}
/**
 *	This gets the number of dirty chunks.
 *
 *  @return				The number of dirty chunks.
 */
size_t ChunkWatcher::numberDirtyChunks() const
{
	if (!numbersValid_)
		calculateStats();
	return numDirty_;
}
Beispiel #17
0
void DLProcess::parsePKGLine(QString line){
     // KPM!!
     // TODO 12-12-2013
     // No JSON in Qt4, once we move to Qt5, replace this hack
     // with the new JSON parser
     // Moved 2/18/14 to this class from pc-pkgmanager by Ken Moore
     //qDebug() << " -- pkg line:" << line;
     // Look for a download status update
     if ( line.indexOf("\"INFO_FETCH") != -1 && line.indexOf("\"url\"") != -1 ) {
       QString file, dl, tot;
          line.remove(0, line.indexOf("\"url") + 8);
          line.truncate(line.lastIndexOf("}"));

          // Get the file basename
          file = line;
	  //qDebug() << "DL File:" << file;
          file.truncate(line.indexOf("\""));
	  file = file.section("/",-1).section(".txz",0,0); //replace the QFileInfo method below (Ken)
          //QFileInfo tFile;
          //tFile.setFile(file);
          //file = tFile.baseName();

          // Get the download / total
          dl = line.section(":", 2, 2).section(",", 0, 0);
          tot = line.section(":", 3, 3).section("}", 0, 0);
          dl = dl.simplified();
          tot = tot.simplified();
	     
	  //These are in bytes, need to convert to kilobytes before sending it on...
	  dl = QString::number( dl.toLongLong()/1024 );
	  tot = QString::number( tot.toLongLong()/1024 );
	     
        //Now calculate the stats and emit the signal
	calculateStats(dl, tot, "", file);
     }
     else if ( line.indexOf("PKGCONFLICTS: ") == 0 ) {
	QString tmp = line; 
     	tmp.replace("PKGCONFLICTS: ", "");
        ConflictList = tmp;
     }
     else if ( line.indexOf("PKGREPLY: ") == 0 ) {
	QString ans;
	QString tmp = line; 
     	tmp.replace("PKGREPLY: ", "");
        QMessageBox msgBox(parentW);
 	msgBox.setText(tr("The following packages are causing conflicts with the selected changes and can be automatically removed. Continue?") + "\n" + ConflictList);
        msgBox.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
   	msgBox.setDetailedText(getConflictDetailText());
        msgBox.setDefaultButton(QMessageBox::No);
        if ( msgBox.exec() == QMessageBox::Yes) {
	  // We will try to fix conflicts
	  ans="yes";
        } else {
	  // We will fail :(
          QMessageBox::warning(parentW, tr("Package Conflicts"),
          tr("You may need to manually fix the conflicts before trying again."),
          QMessageBox::Ok,
          QMessageBox::Ok);
	  ans="no";
        }

        QFile pkgTrig( tmp );
        if ( pkgTrig.open( QIODevice::WriteOnly ) ) {
           QTextStream streamTrig( &pkgTrig );
           streamTrig << ans;
	   pkgTrig.close();
	   ConflictList.clear(); //already sent an answer - clear the internal list
	}
     }else{
     	  //Just emit the message
          //line.remove(0, line.indexOf("\"msg") + 8);
          //line.truncate(line.lastIndexOf("\""));
	  emit UpdateMessage(line);
	  return;
     }
}
Beispiel #18
0
bool FITSImage::loadFITS ( const QString &inFilename, QProgressDialog *progress )
{
    int status=0, nulval=0, anynull=0;
    long fpixel[2], nelements, naxes[2];
    char error_status[512];

    qDeleteAll(starCenters);
    starCenters.clear();

    if (mode == FITS_NORMAL && progress)
    {
        progress->setLabelText(i18n("Please hold while loading FITS file..."));
        progress->setWindowTitle(i18n("Loading FITS"));
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(30);

    if (fptr)
    {

        fits_close_file(fptr, &status);

        if (tempFile)
            QFile::remove(filename);
    }

    filename = inFilename;

    if (filename.contains("/tmp/"))
        tempFile = true;
    else
        tempFile = false;

    filename.remove("file://");


    if (fits_open_image(&fptr, filename.toAscii(), READONLY, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);
        if (progress)
            KMessageBox::error(0, i18n("Could not open file %1 (fits_get_img_param). Error %2", filename, QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }


    if (mode == FITS_NORMAL && progress)
        if (progress->wasCanceled())
            return false;

    if (mode == FITS_NORMAL && progress)
        progress->setValue(40);


    if (fits_get_img_param(fptr, 2, &(stats.bitpix), &(stats.ndim), naxes, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);

        if (progress)
            KMessageBox::error(0, i18n("FITS file open error (fits_get_img_param): %1", QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }

    if (stats.ndim < 2)
    {
        if (progress)
            KMessageBox::error(0, i18n("1D FITS images are not supported in KStars."), i18n("FITS Open"));
        return false;
    }


    if (fits_get_img_type(fptr, &data_type, &status))
    {
        fits_report_error(stderr, status);
        fits_get_errstatus(status, error_status);

        if (progress)
            KMessageBox::error(0, i18n("FITS file open error (fits_get_img_type): %1", QString::fromUtf8(error_status)), i18n("FITS Open"));
        return false;
    }

    if (mode == FITS_NORMAL && progress)
        if (progress->wasCanceled())
            return false;

    if (mode == FITS_NORMAL && progress)
        progress->setValue(60);

    stats.dim[0] = naxes[0];
    stats.dim[1] = naxes[1];

    delete (image_buffer);
    image_buffer = NULL;

    image_buffer = new float[stats.dim[0] * stats.dim[1]];

    if (image_buffer == NULL)
    {
        qDebug() << "Not enough memory for image_buffer";
        return false;
    }
    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
        delete (image_buffer);
        return false;
        }
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(70);

    nelements = stats.dim[0] * stats.dim[1];
    fpixel[0] = 1;
    fpixel[1] = 1;

    qApp->processEvents();

    if (fits_read_2d_flt(fptr, 0, nulval, naxes[0], naxes[0], naxes[1], image_buffer, &anynull, &status))
    {
        fprintf(stderr, "fits_read_pix error\n");
        fits_report_error(stderr, status);
        return false;
    }

    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
            delete (image_buffer);
            return false;
        }
    }

    calculateStats();

    if (mode == FITS_NORMAL && progress)
        progress->setValue(80);

    //currentWidth  = stats.dim[0];
   // currentHeight = stats.dim[1];

    qApp->processEvents();

    if (mode == FITS_NORMAL)
    {
        checkWCS();

        if (progress)
            progress->setValue(90);
    }

    if (mode == FITS_NORMAL && progress)
    {
        if (progress->wasCanceled())
        {
            delete (image_buffer);
            return false;
        }
    }

    if (mode == FITS_NORMAL && progress)
        progress->setValue(100);

    starsSearched = false;

    return true;

}