id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,534,430
ivcolordockwidget.cc
schirmermischa_THELI/src/iview/dockwidgets/ivcolordockwidget.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ivcolordockwidget.h" #include "ui_ivcolordockwidget.h" #include "../iview.h" #include <cmath> #include <QString> #include <QPushButton> IvColorDockWidget::IvColorDockWidget(IView *parent) : QDockWidget(parent), ui(new Ui::IvColorDockWidget) { ui->setupUi(this); iview = parent; ui->redSlider->setMinimum(0); ui->redSlider->setMaximum(sliderSteps); ui->redSlider->setValue(sliderSteps/2); // ui->redSlider->setMinimumWidth(150); // ui->redSlider->setMaximumWidth(250); // ui->redFactorLineEdit->setMinimumWidth(120); // ui->redFactorLineEdit->setMaximumWidth(120); // ui->redResetPushButton->setText("Reset"); ui->blueSlider->setMinimum(0); ui->blueSlider->setMaximum(sliderSteps); ui->blueSlider->setValue(sliderSteps/2); // ui->blueSlider->setMinimumWidth(150); // ui->blueSlider->setMaximumWidth(250); // ui->blueFactorLineEdit->setMinimumWidth(120); // ui->blueFactorLineEdit->setMaximumWidth(120); // ui->blueResetPushButton->setText("Reset"); connect(ui->blueFactorLineEdit, &QLineEdit::textChanged, this, &IvColorDockWidget::validate); connect(ui->redFactorLineEdit, &QLineEdit::textChanged, this, &IvColorDockWidget::validate); connect(ui->redFactorLineEdit, &QLineEdit::textEdited, this, &IvColorDockWidget::redFactorEdited); connect(ui->blueFactorLineEdit, &QLineEdit::textEdited, this, &IvColorDockWidget::blueFactorEdited); connect(ui->redSlider, &QSlider::sliderMoved, this, &IvColorDockWidget::redSliderMoved); connect(ui->blueSlider, &QSlider::sliderMoved, this, &IvColorDockWidget::blueSliderMoved); connect(this, &IvColorDockWidget::colorFactorChanged, iview, &IView::colorFactorChanged_receiver); connect(ui->G2referencesPushButton, &QPushButton::toggled, iview, &IView::showG2References); } IvColorDockWidget::~IvColorDockWidget() { delete ui; } void IvColorDockWidget::validate() { // Floating point validator QRegExp rf( "^[0-9]+[.]{0,1}[0-9]+" ); QValidator *validator = new QRegExpValidator( rf, this ); ui->blueFactorLineEdit->setValidator( validator ); ui->redFactorLineEdit->setValidator( validator ); } void IvColorDockWidget::sliderToText(int sliderValue, QString channel) { float sh = sliderSteps / 2.0; if (channel == "red") { colorFactorApplied[0] = colorFactorZeropoint[0] * pow(2., float(sliderValue-sh) / sh); ui->redFactorLineEdit->setText(QString::number(colorFactorApplied[0], 'f', 3)); } if (channel == "blue") { colorFactorApplied[2] = colorFactorZeropoint[2] * pow(2., float(sliderValue-sh) / sh); ui->blueFactorLineEdit->setText(QString::number(colorFactorApplied[2], 'f', 3)); } } void IvColorDockWidget::textToSlider(QString value, QString channel) { float sh = sliderSteps / 2.0; if (channel == "red") { int sliderValue = sh * ( log(value.toFloat() / colorFactorZeropoint[0]) / log(2.) + 1.); ui->redSlider->setValue(sliderValue); } if (channel == "blue") { int sliderValue = sh * ( log(value.toFloat() / colorFactorZeropoint[2]) / log(2.) + 1.); ui->blueSlider->setValue(sliderValue); } } void IvColorDockWidget::redSliderMoved(const int &sliderValue) { sliderToText(sliderValue, "red"); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::blueSliderMoved(const int &sliderValue) { sliderToText(sliderValue, "blue"); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::redFactorEdited(const QString &value) { textToSlider(value, "red"); colorFactorApplied[0] = value.toFloat(); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::blueFactorEdited(const QString &value) { textToSlider(value, "blue"); colorFactorApplied[2] = value.toFloat(); emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::on_redResetPushButton_clicked() { ui->redSlider->setValue(sliderSteps/2.); ui->redFactorLineEdit->setText(QString::number(colorFactorZeropoint[0], 'f', 3)); colorFactorApplied[0] = colorFactorZeropoint[0]; emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); } void IvColorDockWidget::on_blueResetPushButton_clicked() { ui->blueSlider->setValue(sliderSteps/2.); ui->blueFactorLineEdit->setText(QString::number(colorFactorZeropoint[2], 'f', 3)); colorFactorApplied[2] = colorFactorZeropoint[2]; emit colorFactorChanged(ui->redFactorLineEdit->text(), ui->blueFactorLineEdit->text()); }
5,412
C++
.cc
123
40.601626
104
0.739271
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,431
processingStatus.cc
schirmermischa_THELI/src/processingStatus/processingStatus.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "processingStatus.h" #include "../functions.h" #include <QObject> #include <QDir> #include <QString> #include <QFile> #include <QDebug> #include <QTextStream> ProcessingStatus::ProcessingStatus(QString dirname, QObject *parent) : QObject(parent) { dirName = dirname; dir.setPath(dirname); if (!dir.exists()) { emit messageAvailable("ProcessingStatus::ProcessingStatus(): Directory " + dirName + " does not exist", "error"); emit critical(); statusString = ""; return; } } void ProcessingStatus::writeToDrive() { QFile file(dirName + "/.processingStatus"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("ProcessingStatus::write(): Could not write "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return; } // Write status stream << getStatusString() << "\n"; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void ProcessingStatus::deleteFromDrive() { QFile file(dirName + "/.processingStatus"); file.remove(); } void ProcessingStatus::readFromDrive() { QFile file(dirName + "/.processingStatus"); if (!file.exists()) { inferStatusFromFilenames(); statusToBoolean(statusString); return; } if(!file.open(QIODevice::ReadOnly)) { emit messageAvailable("ProcessingStatus::read(): Could not open "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return; } QTextStream stream(&file); statusString = stream.readLine(); statusToBoolean(statusString); file.close(); } // same as above, just returning the string QString ProcessingStatus::whatIsStatusOnDrive() { QFile file(dirName + "/.processingStatus"); if (!file.exists()) { inferStatusFromFilenames(); statusToBoolean(statusString); return ""; } if(!file.open(QIODevice::ReadOnly)) { emit messageAvailable("ProcessingStatus::read(): Could not open "+dirName + "/.processingStatus "+file.errorString(), "error"); emit critical(); return ""; } QTextStream stream(&file); QString tmp = stream.readLine(); file.close(); return tmp; } QString ProcessingStatus::getStatusString() { statusString = ""; if (HDUreformat) statusString.append("P"); if (Processscience) statusString.append("A"); if (Chopnod) statusString.append("M"); if (Background) statusString.append("B"); if (Collapse) statusString.append("C"); if (Starflat) statusString.append("D"); if (Skysub) statusString.append("S"); return statusString; } void ProcessingStatus::statusToBoolean(QString status) { reset(); if (status.contains("P")) HDUreformat = true; if (status.contains("A")) Processscience = true; if (status.contains("M")) Chopnod = true; if (status.contains("B")) Background = true; if (status.contains("C")) Collapse = true; if (status.contains("D")) Starflat = true; if (status.contains("S")) Skysub = true; // WARNING: This signal is not connected anywhere! emit processingStatusChanged(); } void ProcessingStatus::reset() { HDUreformat = false; Processscience = false; Chopnod = false; Background = false; Collapse = false; Starflat = false; Skysub = false; } // If the .processingStatus file is absent when initialising the Data class, then infer the status from the FITS file names void ProcessingStatus::inferStatusFromFilenames() { statusString = ""; QStringList statusList; QStringList fileList = dir.entryList(QStringList() << "*.fits"); for (auto &it : fileList) { QString status = extractStatusFromFilename(it); if (!statusList.contains(status)) statusList.append(status); } if (statusList.length() == 1) statusString = statusList.at(0); else { QString joined = ""; for (auto &it : statusList) { joined.append(it+" "); } joined = joined.simplified(); QString message = "Could not infer unambiguous processing status from the FITS file names in " + dirName + ".<br>The following statuses were identified: "+ joined + "<br>Cleanup the directory manually to establish a consistent status. Restart required."; // qDebug() << message; // THIS NEEDS FIXING. Even if the message is triggered upon launching a new project, it does not appear to be a problem. emit messageAvailable(QString(__func__)+message, "error"); // For some reason this signal is never received by the controller, even though 'Data' re-emits it. emit critical(); statusString = ""; } } // This does not work if raw data have e.g. the form fsr_1075_03_c2.fits (FourStar). // It would return 'c'. Or in case of Gemini, e.g. S20191231S0495.fits, it would return 'SS' // Hence this function must not be called if no processing has taken place yet. // UPDATE: This function IS called when initializing the Data class. But inside that initialization, we check for RAW data, // and if any are found, the status string and internal data are reset. QString ProcessingStatus::extractStatusFromFilename(QString &filename) { QString id = getLastWord(filename, '_'); QString status = id.remove(".fits"); status.remove(QRegExp("[0123456789]")); return status; } bool ProcessingStatus::doesStatusFileExist() { QFile file(dirName + "/.processingStatus"); if( !file.exists()) return false; else return true; }
6,311
C++
.cc
169
32.745562
167
0.693944
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,432
query.cc
schirmermischa_THELI/src/query/query.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "query.h" #include "../functions.h" #include "../tools/tools.h" #include "../myimage/myimage.h" #include "../processingInternal/data.h" #include "../tools/cfitsioerrorcodes.h" #include "wcs.h" #include "wcshdr.h" #include <QMetaObject> #include <QVector> #include <QStringList> // #include <QSettings> #include <QProcess> #include <QStandardPaths> Query::Query(int *verbose) { // Initialization initEnvironment(thelidir, userdir); // QSettings settings("THELI", "PREFERENCES"); // QString server = settings.value("prefServerComboBox").toString(); // downloadServer = translateServer(server); pythonExecutable = findExecutableName("python"); curlExecutable = findExecutableName("curl"); // reserve 1MB for the downloaded catalog byteArray.reserve(1e6); verbosity = verbose; } Query::~Query() { } void Query::doBrightStarQueryFromWeb() { initAstromQuery(); getMedianEpoch(); buildQuerySyntaxAstrom(); runCommand(queryCommand); processBrightStarCatalog(); } void Query::doAstromQueryFromWeb() { initAstromQuery(); getMedianEpoch(); buildQuerySyntaxAstrom(); runCommand(queryCommand); processAstromCatalog(); } // Used for image quality, a pure stellar catalog void Query::doGaiaQuery() { initGaiaQuery(); getMedianEpoch(); buildQuerySyntaxGaia(); runCommand(queryCommand); processGaiaCatalog(); } void Query::doPhotomQueryFromWeb() { initPhotomQuery(); // getMedianEpoch(); buildQuerySyntaxPhotom(); runCommand(queryCommand); processPhotomCatalog(); } void Query::doColorCalibQueryFromWeb() { initColorCalibQuery(); buildQuerySyntaxColorCalib(); runCommand(queryCommand); processColorCalibCatalog(); } void Query::getCatalogSearchLocationAstrom() { if (!successProcessing) return; QVector<double> crval1 = scienceData->getKeyFromAllImages("CRVAL1"); QVector<double> crval2 = scienceData->getKeyFromAllImages("CRVAL2"); if (crval1.isEmpty() || crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchLocationAstrom(): CRVAL vectors are empty", "error"); emit critical(); successProcessing = false; return; } // Use median to calculate field center (avoiding issues with RA=0|360 deg boundary) // Do not average central two elements if number of data points is even alpha = straightMedian_T(crval1, 0, false); delta = straightMedian_T(crval2, 0, false); // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(alpha, 'f', 6); delta_string = QString::number(delta, 'f', 6); } void Query::getCatalogSearchRadiusAstrom() { if (!successProcessing) return; QVector<double> corners_crval1 = scienceData->getKeyFromAllImages("CORNERS_CRVAL1"); QVector<double> corners_crval2 = scienceData->getKeyFromAllImages("CORNERS_CRVAL2"); if (corners_crval1.isEmpty() || corners_crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchRadiusAstrom(): Corner vectors are empty", "error"); emit critical(); successProcessing = false; return; } // Search radius in DEC in arcmin double crval2_min = minVec_T(corners_crval2); double crval2_max = maxVec_T(corners_crval2); double crval2_radius = 60.*(crval2_max - crval2_min)*0.5; // Search radius in RA in arcmin, take into account possible pass over 0|360 deg boundary double crval1_min = minVec_T(corners_crval1); double crval1_max = maxVec_T(corners_crval1); if (crval1_max - crval1_min > 180.) { for (auto &ra : corners_crval1) { if (ra > 180.) ra -= 360.; } // Calculate min / max once more crval1_min = minVec_T(corners_crval1); crval1_max = maxVec_T(corners_crval1); } double crval1_radius = 60. * (crval1_max - crval1_min) * 0.5 * cos(delta*rad); // in [arcmin] if (!radius_manual.isEmpty()) { if (refcatName.contains("PANSTARRS")) radius_string = QString::number(radius_manual.toFloat()/60., 'f', 6); else radius_string = radius_manual; } else { // Include a 10% safety margin in the search radius radius = 1.1*sqrt(crval1_radius*crval1_radius + crval2_radius*crval2_radius); // safeguarding against a potential threading issue with wcslib: if (radius > 5.*scienceData->instData->radius*60) { radius = 2.*scienceData->instData->radius*60; // TODO: this is probably not necessary anymore because of the wcslock in MyImage::initWCS() and the corresponding critical sections emit messageAvailable("Truncating the search radius to "+QString::number(radius, 'f', 1) + " arcmin", "warning"); emit messageAvailable("Do you have different targets collected in the same directory?", "warning"); qDebug() << "RA corner vertices" << corners_crval1; qDebug() << "DEC corner vertices" << corners_crval2; } if (refcatName.contains("PANSTARRS")) radius /= 60.; // MAST query is in degrees radius_string = QString::number(radius, 'f', 6); } } void Query::getCatalogSearchLocationPhotom() { if (!successProcessing) return; // Calculate RA/DEC of image center photomImage = new MyImage(photomDir, photomImageName, "", 1, QVector<bool>(), verbosity); photomImage->loadHeader(); naxis1 = photomImage->naxis1; naxis2 = photomImage->naxis2; radius = 1.1 * sqrt(naxis1*naxis1+naxis2*naxis2) / 2. * photomImage->plateScale / 60.; // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(photomImage->alpha_ctr, 'f', 6); delta_string = QString::number(photomImage->delta_ctr, 'f', 6); if (refcatName.contains("PANSTARRS")) radius /= 60.; radius_string = QString::number(radius, 'f', 6); } void Query::getCatalogSearchLocationColorCalib() { if (!successProcessing) return; // Calculate RA/DEC of image center photomImage->loadHeader(); naxis1 = photomImage->naxis1; naxis2 = photomImage->naxis2; radius = 1.1 * sqrt(naxis1*naxis1+naxis2*naxis2) / 2. * photomImage->plateScale / 60.; // Convert to string (because we pass this to 'vizquery' alpha_string = QString::number(photomImage->alpha_ctr, 'f', 6); delta_string = QString::number(photomImage->delta_ctr, 'f', 6); if (refcatName.contains("PANSTARRS")) radius /= 60.; radius_string = QString::number(radius, 'f', 6); } void Query::getMedianEpoch() { if (!successProcessing) return; // Get median observation epoch (for GAIA) QVector<double> epochs = scienceData->getKeyFromAllImages("DATE-OBS"); if (epochs.isEmpty() && refcatName.contains("GAIA")) { emit messageAvailable("Query::getMedianEpoch():<br>The DATE-OBS keyword was not found in the FITS headers, but is required for the GAIA reference catalog.<br>You must choose a different reference catalog.", "error"); emit critical(); successProcessing = false; return; } epoch = straightMedian_T(epochs); } void Query::initAstromQuery() { if (!successProcessing) return; // Reformat if necessary if (alpha_manual.contains(":")) alpha_manual = hmsToDecimal(alpha_manual); if (delta_manual.contains(":")) delta_manual = dmsToDecimal(delta_manual); // Get location. Manual or automatic mode if (magLimit_string.isEmpty()) magLimit_string = "25"; if (alpha_manual.isEmpty() || delta_manual.isEmpty()) { getCatalogSearchLocationAstrom(); } else { alpha_string = alpha_manual; delta_string = delta_manual; } // Get search radius getCatalogSearchRadiusAstrom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); // Vizier does not deal correctly with integer coords if (!alpha_string.contains(".")) alpha_string.append(".0"); if (!delta_string.contains(".")) delta_string.append(".0"); } void Query::initGaiaQuery() { if (!successProcessing) return; getCatalogSearchLocationAstrom(); // search radius is provided explicitly only by the coaddition. Otherwise, we have to determine it if (radius_string.isEmpty()) getCatalogSearchRadiusAstrom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); // Vizier does not deal correctly with integer coords if (!alpha_string.contains(".")) alpha_string.append(".0"); if (!delta_string.contains(".")) delta_string.append(".0"); } void Query::initPhotomQuery() { if (!successProcessing) return; getCatalogSearchLocationPhotom(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); } void Query::initColorCalibQuery() { if (!successProcessing) return; getCatalogSearchLocationColorCalib(); // Make declination explicitly positive (sometimes the cdsclient wants that, or wanted that) if (!delta_string.contains('-') && !delta_string.contains('+') ) delta_string.prepend('+'); } void Query::buildQuerySyntaxAstrom() { if (!successProcessing) return; if (!refcatName.contains("PANSTARRS")) { // Vizier queries queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=170000 "); // TODO: More than ~170000 crashes writeAstromScamp(), for unknown reasons // queryCommand.append("-site="+downloadServer+" "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); if (refcatName.contains("ASCC")) queryCommand.append("-out=_RAJ -out=_DEJ -source=I/280B -out=Vmag Vmag=0.."+magLimit_string); else if (refcatName.contains("TYC")) queryCommand.append("-out=_RAJ -out=_DEJ -source=TYC/tyc_main -out=Vmag Vmag=0.."+magLimit_string); else if (refcatName.contains("2MASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=2MASS-PSC -out='Jmag,Hmag,Kmag' Hmag=0.."+magLimit_string); else if (refcatName.contains("UCAC")) queryCommand.append("-out=RAgaia -out=DEgaia -source=I/340 -out='Gmag,RMag' -out=pmRA -out=pmDE Rmag=0.."+magLimit_string); else if (refcatName.contains("GAIA")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=I/355/gaiadr3 -out=Gmag -out=pmRA -out=pmDE Gmag=0.."+magLimit_string); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/154/sdss16 -out=gmag,rmag,imag rmag=0.."+magLimit_string); else if (refcatName.contains("VHS")) queryCommand.append("-out=RAJ2000 -out=DEJ2000 -source=II/359/vhs_dr4 -out=Jap4,Hap4,Ksap4 Jap4=0.."+magLimit_string); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/379/smssdr4 -out=gPSF,rPSF,iPSF rPSF=0.."+magLimit_string); } else { // Querying MAST Panstarrs-DR2 delta_string.remove("+"); // MAST queries don't like explicit "+" signs for the declination queryCommand = curlExecutable + " 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/stack.csv?"; queryCommand.append("ra="+alpha_string+"&"); queryCommand.append("dec="+delta_string+"&"); queryCommand.append("radius="+radius_string+"&"); queryCommand.append("pagesize=170000&"); queryCommand.append("iPSFMag.lte"+magLimit_string+"&"); queryCommand.append("columns=%5BobjID%2CraMean%2CdecMean%2CgPSFMag%2CrPSFMag%2CiPSFMag%2CzPSFMag%2CyPSFMag'"); } } void Query::buildQuerySyntaxGaia() { if (!successProcessing) return; // Vizier query for GAIA point sources. Point sources are identified by means of proper motion, in extractRaDecGaia(); queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=I/355/gaiadr3 -out=Gmag -out=pmRA -out=pmDE -out=e_pmRA -out=e_pmDE"); } void Query::buildQuerySyntaxPhotom() { if (!successProcessing) return; // Vizier queries if (!refcatName.contains("PANSTARRS")) { queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); // queryCommand.append("-site="+downloadServer+" "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); QString filter1 = filterStringToVizierName(refcatFilter1); QString filter2 = filterStringToVizierName(refcatFilter2); if (refcatName.contains("2MASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=2MASS-PSC "); else if (refcatName.contains("VHS")) queryCommand.append("-out=RAJ2000 -out=DEJ2000 -source=II/367/vhs_dr5 "); else if (refcatName.contains("APASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/336 "); else if (refcatName.contains("GAIA")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=I/355/gaiadr3"); else if (refcatName.contains("UKIDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=II/319 "); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/154/sdss16 "); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/379/smssdr4 "); else if (refcatName.contains("ATLAS-REFCAT2")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=J/ApJ/867/105 "); queryCommand.append("-out=" + filter1 + " -out=" + filter2 + " -out=e_" + filter1 + " -out=e_" + filter2); // mags and their errors } else { // Querying MAST Panstarrs-DR2 delta_string.remove("+"); // MAST queries don't like explicit "+" signs for the declination queryCommand = curlExecutable + " 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/stack.csv?"; queryCommand.append("ra="+alpha_string+"&"); queryCommand.append("dec="+delta_string+"&"); queryCommand.append("radius="+radius_string+"&"); queryCommand.append("pagesize=1000000&"); queryCommand.append("columns=%5BobjID%2CraMean%2CdecMean%2CgPSFMag%2CrPSFMag%2CiPSFMag%2CzPSFMag%2CyPSFMag'"); } } void Query::buildQuerySyntaxColorCalib() { if (!successProcessing) return; // Vizier queries if (!refcatName.contains("PANSTARRS")) { queryCommand = pythonExecutable + " " + thelidir+"/python/vizquery.py "; queryCommand.append("-mime=tsv -out.max=1000000 "); queryCommand.append("-c.rm="+radius_string+" "); queryCommand.append("-c='"+alpha_string+delta_string+"' "); } else { delta_string.remove("+"); // MAST queries don't like explicit "+" signs for the declination queryCommand = curlExecutable + " 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/stack.csv?"; queryCommand.append("ra="+alpha_string+"&"); queryCommand.append("dec="+delta_string+"&"); queryCommand.append("radius="+radius_string+"&"); queryCommand.append("pagesize=1000000&"); queryCommand.append("columns=%5BobjID%2CraMean%2CdecMean%2CgPSFMag%2CrPSFMag%2CiPSFMag%2CzPSFMag%2CyPSFMag'"); return; } // Using max 5 filters to identify G2 type stars QString filter1; QString filter2; QString filter3; QString filter4; QString filter5; if (refcatName.contains("SDSS")) { filter1 = filterStringToVizierName("u"); filter2 = filterStringToVizierName("g"); filter3 = filterStringToVizierName("r"); filter4 = filterStringToVizierName("i"); filter5 = filterStringToVizierName("z"); } if (refcatName.contains("SKYMAPPER")) { // ignoring v-band filter filter1 = filterStringToVizierName("u"); filter2 = filterStringToVizierName("g"); filter3 = filterStringToVizierName("r"); filter4 = filterStringToVizierName("i"); filter5 = filterStringToVizierName("z"); } if (refcatName.contains("APASS")) { filter1 = filterStringToVizierName("B"); filter2 = filterStringToVizierName("V"); filter3 = filterStringToVizierName("g"); filter4 = filterStringToVizierName("r"); filter5 = filterStringToVizierName("i"); } if (refcatName.contains("ATLAS-REFCAT2")) { filter1 = filterStringToVizierName("g"); filter2 = filterStringToVizierName("r"); filter3 = filterStringToVizierName("i"); filter4 = filterStringToVizierName("z"); filter5 = ""; } if (refcatName.contains("APASS")) queryCommand.append("-out=_RAJ -out=_DEJ -source=II/336 "); else if (refcatName.contains("SDSS")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=V/154/sdss16 "); else if (refcatName.contains("SKYMAPPER")) queryCommand.append("-out=RAICRS -out=DEICRS -source=II/379/smssdr4 "); else if (refcatName.contains("ATLAS-REFCAT2")) queryCommand.append("-out=RA_ICRS -out=DE_ICRS -source=J/ApJ/867/105 "); queryCommand.append("-out=" + filter1 + " -out=" + filter2 + " -out=" + filter3 + " -out=" + filter4 + " -out=" + filter5); } QString Query::filterStringToVizierName(QString filter) { if (!successProcessing) return ""; if (refcatName.contains("APASS") && filter == "B") return "Bmag"; if (refcatName.contains("APASS") && filter == "V") return "Vmag"; if (refcatName.contains("APASS") && filter == "g") return "g\\'mag"; if (refcatName.contains("APASS") && filter == "r") return "r\\'mag"; if (refcatName.contains("APASS") && filter == "i") return "i\\'mag"; if (refcatName.contains("GAIA") && filter == "G") return "Gmag"; if (refcatName.contains("GAIA") && filter == "BP") return "BPmag"; if (refcatName.contains("GAIA") && filter == "RP") return "RPmag"; if (refcatName.contains("SDSS") && filter == "u") return "umag"; if (refcatName.contains("SDSS") && filter == "g") return "gmag"; if (refcatName.contains("SDSS") && filter == "r") return "rmag"; if (refcatName.contains("SDSS") && filter == "i") return "imag"; if (refcatName.contains("SDSS") && filter == "z") return "zmag"; if (refcatName.contains("SKYMAPPER") && filter == "u") return "uPSF"; if (refcatName.contains("SKYMAPPER") && filter == "v") return "vPSF"; if (refcatName.contains("SKYMAPPER") && filter == "g") return "gPSF"; if (refcatName.contains("SKYMAPPER") && filter == "r") return "rPSF"; if (refcatName.contains("SKYMAPPER") && filter == "i") return "iPSF"; if (refcatName.contains("SKYMAPPER") && filter == "z") return "zPSF"; if (refcatName.contains("PANSTARRS") && filter == "g") return "gPSFMag"; if (refcatName.contains("PANSTARRS") && filter == "r") return "rPSFMag"; if (refcatName.contains("PANSTARRS") && filter == "i") return "iPSFMag"; if (refcatName.contains("PANSTARRS") && filter == "z") return "zPSFMag"; if (refcatName.contains("PANSTARRS") && filter == "y") return "yPSFMag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "g") return "gmag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "r") return "rmag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "i") return "imag"; if (refcatName.contains("ATLAS-REFCAT2") && filter == "z") return "zmag"; if (refcatName.contains("2MASS") && filter == "J") return "Jmag"; if (refcatName.contains("2MASS") && filter == "H") return "Hmag"; if (refcatName.contains("2MASS") && filter == "Ks") return "Kmag"; if (refcatName.contains("VHS") && filter == "Y") return "Yap4"; // using 2.8 " aperture magnitudes if (refcatName.contains("VHS") && filter == "J") return "Jap4"; if (refcatName.contains("VHS") && filter == "H") return "Hap4"; if (refcatName.contains("VHS") && filter == "Ks") return "Ksap4"; if (refcatName.contains("UKIDSS") && filter == "") return "Ymag"; if (refcatName.contains("UKIDSS") && filter == "") return "Jmag1"; if (refcatName.contains("UKIDSS") && filter == "") return "Hmag"; if (refcatName.contains("UKIDSS") && filter == "") return "Kmag"; return ""; } QString Query::resolveTargetSidereal(QString target) { if (!successProcessing) return "Unresolved"; queryCommand = pythonExecutable + " " + thelidir+"/python/resolvetargets.py "+target; runCommand(queryCommand); QTextStream stream(&byteArray, QIODevice::ReadOnly); QString line; while (stream.readLineInto(&line)) { line = line.simplified(); if (line.contains("Traceback")) return "Unresolved"; else { // DEPRECATED. GUI will not launch if python3 cannot be found. The following is kept for reference only. // In case python2 is used instead of python3, we have to remove parentheses and commas from the output line = line.remove("("); line = line.remove(")"); line = line.replace(",", " "); line = line.simplified(); QStringList coordList = line.split(' '); targetAlpha = coordList[0]; targetDelta = coordList[1]; // Convert to HHMMSS and DDMMSS if (!targetAlpha.contains(":")) targetAlpha = decimalToHms(targetAlpha.toDouble()); if (!targetDelta.contains(":")) targetDelta = decimalToDms(targetDelta.toDouble()); return "Resolved"; } } return "Unresolved"; } QString Query::resolveTargetNonsidereal(QString target, QString dateobs, float geoLon, float geoLat) { if (!successProcessing) return "Unresolved"; QString geolonString = QString::number(geoLon, 'f', 4)+"d"; QString geolatString = QString::number(geoLat, 'f', 4)+"d"; queryCommand = pythonExecutable + " " + thelidir+"/python/mpc_query.py "+target + " " + dateobs + " " + geolonString + " " + geolatString; runCommand(queryCommand); QTextStream stream(&byteArray, QIODevice::ReadOnly); QString line; while (stream.readLineInto(&line)) { line = line.simplified(); if (line.contains("Traceback")) return "Unresolved"; else { // DEPRECATED. GUI will not launch if python3 cannot be found. The following is kept for reference only. // In case python2 is used instead of python3, we have to remove parentheses and commas from the output line = line.remove("("); line = line.remove(")"); line = line.replace(",", " "); line = line.simplified(); QStringList coordList = line.split(' '); targetAlpha = coordList[0]; targetDelta = coordList[1]; // Convert to HHMMSS and DDMMSS if (!targetAlpha.contains(":")) targetAlpha = decimalToHms(targetAlpha.toDouble()); if (!targetDelta.contains(":")) targetDelta = decimalToDms(targetDelta.toDouble()); return "Resolved"; } } return "Unresolved"; } /* // Extract 'value' in a line <tag>value</tag> QString Query::parseXML(QString &line, const QString &tag) { line.remove("<"+tag+">"); line.remove("</"+tag+">"); return line.simplified(); } // Extract 'value' in a line <tag>value</tag> void Query::parseXML2(QString &line, const QString &tag, QString &val1, QString &val2) { line.remove("<"+tag+">"); line.remove("</"+tag+">"); QStringList list = line.simplified().split(" "); val1 = list[0]; val2 = list[1]; } */ void Query::clearAstrom() { raMotions.clear(); deMotions.clear(); numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); } void Query::clearGaia() { raMotions.clear(); deMotions.clear(); raMotions_err.clear(); deMotions_err.clear(); numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); } void Query::clearPhotom() { numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); mag2_out.clear(); mag1err_out.clear(); mag2err_out.clear(); } void Query::clearColorCalib() { numSources = 0; ra_out.clear(); de_out.clear(); mag1_out.clear(); mag2_out.clear(); mag3_out.clear(); mag4_out.clear(); mag5_out.clear(); } void Query::processAstromCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearAstrom(); // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_mystd.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processAstromCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog, prepare scamp and anet QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("objID") // MAST Queries || line.contains("Total") // MAST Queries || line.contains("Fail") // MAST Queries || line.contains("-999.0") // MAST Queries || line.contains("--")) continue; QString result = extractRaDecMagAstrom(line); // also prepares scamp and anet if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); measureBulkMotion(); // display mean bulk motion in that field pushNumberOfSources(); // display number of refcat sources writeAstromScamp(); writeAstromANET(); // Can be lengthy if 100000 sources or more are retrieved. dumpRefcatID(); // writes refcat/.refcatID, used to check whether the catalog needs to be recreated } void Query::processGaiaCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearGaia(); // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_pointsources.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processGaiaCatalog(): "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("objID") // MAST Queries || line.contains("Total") // MAST Queries || line.contains("Fail") // MAST Queries || line.contains("-999.0") // MAST Queries || line.contains("--")) continue; QString result = extractRaDecGaia(line); // includes point source filtering if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); // pushNumberOfSources(); // display number of refcat sources dumpRefcatID(); // writes refcat/.refcatID, used to check whether the catalog needs to be recreated } // used externally when modeling the background. // difference: does not dump catalogs to drive void Query::processBrightStarCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearAstrom(); // Process the stream QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("objID") // MAST Queries || line.contains("Total") // MAST Queries || line.contains("Fail") // MAST Queries || line.contains("-999.0") // MAST Queries || line.contains("--")) continue; QString result = extractRaDecMagAstrom(line); if (!result.isEmpty()) ++numSources; ++i; } } void Query::processPhotomCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearPhotom(); // The iView catalog (ASCII) QString outpath = photomDir+"/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/refcatPhotom.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processPhotomCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("objID") // MAST Queries || line.contains("Total") // MAST Queries || line.contains("Fail") // MAST Queries || line.contains("-999.0") // MAST Queries || line.contains("--")) continue; QString result = extractRaDecMagPhotom(line); if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::processColorCalibCatalog() { if (!successProcessing) return; QTextStream stream(&byteArray, QIODevice::ReadOnly); clearColorCalib(); // The iView catalog (ASCII) QString outpath = photomDir+"/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/PHOTCAT_calibration/PHOTCAT_sources_"+refcatName+".iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::processPhotomCatalog(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog QString line; long i=0; while (stream.readLineInto(&line)) { if (line.contains("database is not currently reachable")) { successfulDataBaseAccess = false; emit messageAvailable("Query:: The CDS database is currently not reachable", "error"); emit critical(); break; } if (line.contains("#") || line.isEmpty() || line.contains("deg") || line.contains("RA") || line.contains("Content-Type") || line.contains("Content-Disposition") || line.contains("DocumentRef") || line.contains("objID") // MAST Queries || line.contains("Total") // MAST Queries || line.contains("Fail") // MAST Queries || line.contains("-999.0") // MAST Queries || line.contains("--")) continue; QString result = extractRaDecMagColorCalib(line); if (!result.isEmpty()) { stream_iview << result << "\n"; ++numSources; } ++i; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::pushNumberOfSources() { QString messageString = ""; if (numSources > 0) { if (!fromImage) { messageString = QString::number(numSources) + " " + refcatName + " reference sources retrieved at this location:" // + "<br>RA = " + QString::number(alpha, 'f', 5) // + "<br>DEC = " + QString::number(delta, 'f', 5) + "<br>RA = " + alpha_string + "<br>DEC = " + delta_string + "<br>radius = " + radius_string + "'"; emit messageAvailable(messageString, "ignore"); } else { messageString = QString::number(numSources) + " " + refcatName + " reference sources detected in the image."; emit messageAvailable(messageString, "ignore"); } } else { if (!successfulDataBaseAccess) { emit messageAvailable("Query:: The CDS database is currently not reachable", "stop"); emit critical(); successfulDataBaseAccess = true; } if (!suppressCatalogWarning) { messageString = "WARNING: No reference sources retrieved! <br>" "-- try a different catalog <br>" "-- check your internet connection <br>" "-- do not run THELI from a console with active conda/astroconda environment <br>" "-- adjust mag limit and radius"; emit messageAvailable(messageString, "stop"); emit critical(); } } } void Query::identifySolarTypeStars() { if (!successProcessing) return; if (refcatName.contains("SDSS")) { c1min = sunUG; c1max = sunUG; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunUGtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("SKYMAPPER")) { c1min = sunUG; c1max = sunUG; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunUGtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("APASS")) { c1min = sunBV; c1max = sunBV; c2min = sunGR; c2max = sunGR; c3min = sunRI; c3max = sunRI; c1tol = sunBVtol; c2tol = sunGRtol; c3tol = sunRItol; } if (refcatName.contains("PANSTARRS")) { c1min = sunGR; c1max = sunGR; c2min = sunRI; c2max = sunRI; c3min = sunIZ; c3max = sunIZ; c1tol = sunGRtol; c2tol = sunRItol; c3tol = sunIZtol; } if (refcatName.contains("ATLAS-REFCAT2")) { c1min = sunGR; c1max = sunGR; c2min = sunRI; c2max = sunRI; c3min = sunIZ; c3max = sunIZ; c1tol = sunGRtol; c2tol = sunRItol; c3tol = sunIZtol; } QVector<float> tolerances = {1.0, 1.5, 2.0}; // We use the first three colors, only // SDSS: u-g, g-r, r-i // SKYMAPPER: u-g, g-r, r-i // APASS: B-V, g-r, r-i // PANSTARRS: g-r, r-i, i-z // ATLAS-REFCAT2: g-r, r-i, i-z for (auto &tol : tolerances) { G2type.fill(false, mag1_out.length()); int nmatch = 0; float c1min0 = c1min - tol*c1tol; float c1max0 = c1max + tol*c1tol; float c2min0 = c2min - tol*c2tol; float c2max0 = c2max + tol*c2tol; float c3min0 = c3min - tol*c3tol; float c3max0 = c3max + tol*c3tol; for (long k=0; k<mag1_out.length(); ++k) { float col1 = 0.; float col2 = 0.; float col3 = 0.; if (refcatName.contains("PANSTARRS") || refcatName.contains("SDSS") || refcatName.contains("SKYMAPPER") || refcatName.contains("ATLAS-REFCAT2")) { col1 = mag1_out[k] - mag2_out[k]; col2 = mag2_out[k] - mag3_out[k]; col3 = mag3_out[k] - mag4_out[k]; } else if (refcatName.contains("APASS")) { col1 = mag1_out[k] - mag2_out[k]; // "B-V" col2 = mag3_out[k] - mag4_out[k]; // "g-r" col3 = mag4_out[k] - mag5_out[k]; // "r-i" } if (col1 >= c1min0 && col1 <= c1max0 && col2 >= c2min0 && col2 <= c2max0 && col3 >= c3min0 && col3 <= c3max0) { G2type[k] = true; ++nmatch; } } if (nmatch > 0) { numG2sources = nmatch; break; } } } void Query::measureBulkMotion() { if (!successProcessing) return; if (!refcatName.contains("GAIA") && !refcatName.contains("UCAC5")) return; raBulkMotion = straightMedian_T(raMotions); deBulkMotion = straightMedian_T(deMotions); if (raMotions.length() > 1) { raErrBulkMotion = rmsMask_T(raMotions) / sqrt(raMotions.length()); deErrBulkMotion = rmsMask_T(deMotions) / sqrt(deMotions.length()); } else { raErrBulkMotion = 0.; deErrBulkMotion = 0.; } QString pmRA_GUI = QString::number(raBulkMotion, 'f', 3) + " +/- " + QString::number(raErrBulkMotion, 'f', 3); QString pmDE_GUI = QString::number(deBulkMotion, 'f', 3) + " +/- " + QString::number(deErrBulkMotion, 'f', 3); emit bulkMotionObtained(pmRA_GUI, pmDE_GUI); } QString Query::extractRaDecMagAstrom(QString &line) { if (!successProcessing) return ""; // 'line' contains RA, DEC, and an arbitrary number of magnitudes (which we average) // Fields are separated by tabs (vizquery) or commas (MAST queries) QString result = ""; // line = line.simplified(); QString splitchar = ""; int offset = 0; // needed because MAST queries insert the objID and I don't know how to turn that off. if (!refcatName.contains("PANSTARRS")) splitchar = '\t'; else { splitchar = ','; offset = 1; } QStringList list = line.split(splitchar); int length = list.length(); if (refcatName.contains("GAIA") && length < 5) return result; if (!refcatName.contains("GAIA") && length < 3) return result; QString ra = list[0+offset].simplified(); QString dec = list[1+offset].simplified(); if (ra.isEmpty()) return ""; QVector<float> magnitudes; magLimit = magLimit_string.toFloat(); // without proper motions if (!refcatName.contains("GAIA") && !refcatName.contains("UCAC")) { for (int i=2+offset; i<length; ++i) { QString mag = list[i].simplified(); if (!mag.isEmpty()) magnitudes << mag.toFloat(); } float meanMag = meanMask(magnitudes); result = ra+" "+dec+" "+QString::number(meanMag, 'f', 3); ra_out.append(ra.toDouble()); de_out.append(dec.toDouble()); mag1_out.append(meanMag); } // with proper motions else { for (int i=2; i<length-2; ++i) { QString mag = list[i].simplified(); if (!mag.isEmpty()) magnitudes << mag.toFloat(); } float meanMag = meanMask(magnitudes); double ra_obj = ra.toDouble(); double dec_obj = dec.toDouble(); QString pmRA_string = list[length-2].simplified(); QString pmDE_string = list[length-1].simplified(); float pmRA = pmRA_string.toFloat(); float pmDE = pmDE_string.toFloat(); raMotions << pmRA; deMotions << pmDE; float pm = sqrt(pmRA*pmRA+pmDE*pmDE); if (!maxProperMotion_string.isEmpty()) maxProperMotion = maxProperMotion_string.toFloat(); // Correct coordinates for proper motion. double pmRA_rescaled = pmRA / 1000. / 3600. / cos(dec_obj*rad); double pmDE_rescaled = pmDE / 1000. / 3600.; ra_obj = ra_obj + pmRA_rescaled * (epoch - epochReference); dec_obj = dec_obj + pmDE_rescaled * (epoch - epochReference); ra = QString::number(ra_obj, 'f', 9); dec = QString::number(dec_obj, 'f', 9); // keep the reference source if it is brighter than the limiting magnitude, and its proper motion is less than the max allowed proper motion if (pm < maxProperMotion) { result = ra+" "+dec+" "+QString::number(meanMag, 'f', 3); ra_out.append(ra_obj); de_out.append(dec_obj); mag1_out.append(meanMag); } } return result; } QString Query::extractRaDecGaia(QString &line) { if (!successProcessing) return ""; // 'line' contains RA, DEC, pmRA, pmDE, e_pmRA, e_pmDE // Fields are separated by semi-colons QString result = ""; QStringList list = line.split('\t'); int length = list.length(); // Need RA, DEC, pmRA, pmDE, e_pmRA, e_pmDE if (length < 6) return ""; QString ra = list[0].simplified(); QString dec = list[1].simplified(); QString pmRA_string = list[2].simplified(); QString pmDE_string = list[3].simplified(); QString e_pmRA_string = list[4].simplified(); QString e_pmDE_string = list[5].simplified(); if (ra.isEmpty()) return ""; double ra_obj = ra.toDouble(); double dec_obj = dec.toDouble(); float pmRA = pmRA_string.toFloat(); float pmDE = pmDE_string.toFloat(); float e_pmRA = e_pmRA_string.toFloat(); float e_pmDE = e_pmDE_string.toFloat(); raMotions << pmRA; deMotions << pmDE; raMotions_err << e_pmRA; deMotions_err << e_pmDE; float pm = sqrt(pmRA*pmRA+pmDE*pmDE); float e_pm = 1./pm * sqrt(pow(pmRA*e_pmRA,2) + pow(pmDE*e_pmDE,2)); // propagation of uncertainty float sn; if (e_pm <= 0.) sn = 0.; else sn = pm / e_pm; // Minimum SN for the proper motion detection: 95% confidence, and therefore it must be a point source (stars move, distant galaxies don't) if (sn < 2.) return ""; // Correct coordinates for proper motion. double pmRA_rescaled = pmRA / 1000. / 3600. / cos(dec_obj*rad); double pmDE_rescaled = pmDE / 1000. / 3600.; ra_obj = ra_obj + pmRA_rescaled * (epoch - epochReference); dec_obj = dec_obj + pmDE_rescaled * (epoch - epochReference); ra = QString::number(ra_obj, 'f', 9); dec = QString::number(dec_obj, 'f', 9); result = ra+" "+dec; ra_out.append(ra_obj); de_out.append(dec_obj); return result; } QString Query::extractRaDecMagPhotom(QString &line) { if (!successProcessing) return ""; // 'line' contains RA, DEC, and 2 magnitudes, and their errors // Fields are separated by semi-colons QString result = ""; // line = line.simplified(); QStringList list = line.split('\t'); int length = list.length(); if (length != 6) return result; QString ra = list[0].simplified(); QString dec = list[1].simplified(); QString mag1 = list[2].simplified(); QString mag2 = list[3].simplified(); QString mag1err = list[4].simplified(); QString mag2err = list[5].simplified(); if (ra.isEmpty() || dec.isEmpty() || mag1.isEmpty() || mag2.isEmpty() || mag1err.isEmpty() || mag2err.isEmpty()) return result; result = ra+" "+dec+" "+mag1+" "+mag2; // we do not propagate the errors into the output, just keep them in the variables ra_out.append(ra.toDouble()); de_out.append(dec.toDouble()); mag1_out.append(mag1.toFloat()); mag2_out.append(mag2.toFloat()); mag1err_out.append(mag1err.toFloat()); mag2err_out.append(mag2err.toFloat()); return result; } QString Query::extractRaDecMagColorCalib(QString &line) { if (!successProcessing) return ""; // 'line' contains RA, DEC, and 4-5 magnitudes // Fields are separated by semi-colons QString result = ""; QStringList list = line.split('\t'); int length = list.length(); if (length < 5) return result; QString ra = list[0].simplified(); QString dec = list[1].simplified(); QString mag1 = list[2].simplified(); QString mag2 = list[3].simplified(); QString mag3 = list[4].simplified(); QString mag4 = list[5].simplified(); QString mag5; if (refcatName.contains("ATLAS-REFCAT2")) mag5 = mag1; // contains only 4 mags else { if (list.length() == 7) mag5 = list[6].simplified(); else { emit messageAvailable("Query::extractRaDecMagColorCalib(): Unexpected format for " + refcatName + ": " +line, "warning"); mag5 = mag1; } } if (ra.isEmpty() || dec.isEmpty() || mag1.isEmpty() || mag2.isEmpty() || mag3.isEmpty() || mag4.isEmpty() || mag5.isEmpty()) return result; result = ra+" "+dec+" "+mag1+" "+mag2+" "+mag3+" "+mag4+" "+mag5; // we do not propagate the errors into the output, just keep them in the variables ra_out.append(ra.toDouble()); de_out.append(dec.toDouble()); mag1_out.append(mag1.toFloat()); mag2_out.append(mag2.toFloat()); mag3_out.append(mag3.toFloat()); mag4_out.append(mag4.toFloat()); mag5_out.append(mag5.toFloat()); return result; } // Retrieves the multi-line output of a query to one of the reference catalog servers void Query::runCommand(QString command) { if (!successProcessing) return; if (*verbosity > 1) { if (command.contains("vizquery")) emit messageAvailable("vizquery command: <br>"+queryCommand, "ignore"); if (command.contains("resolvetargets")) emit messageAvailable("resolve targets command: <br>"+queryCommand, "ignore"); } byteArray.clear(); QProcess process; process.start("/bin/sh -c \""+command+"\""); process.waitForFinished(-1); byteArray = process.readAllStandardOutput(); // check output for issues with anaconda / python3 QTextStream stream(&byteArray, QIODevice::ReadOnly); QString line; int count = 0; while (stream.readLineInto(&line) && count < 10) { // the counter is to avoid processing very large, correct output. line = line.simplified(); if (line.contains("-c requires an argument") && queryCommand.contains("python") && (queryCommand.contains("astroconda",Qt::CaseInsensitive) || queryCommand.contains("anaconda",Qt::CaseInsensitive))) { emit messageAvailable(QString(__func__)+" ERROR: Incompatible anaconda / astroconda python executable used:", "error"); emit messageAvailable(pythonExecutable, "error"); emit messageAvailable("Deactivate your conda environment, and use your system's python installation instead.", "error"); emit critical(); return; } ++count; } } /* // needed if the data isn't in memory yet (e.g. immediately after starting the main GUI) void Query::provideHeaderInfo() { for (int chip=0; chip<scienceData->instData->numChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); } } } */ void Query::writeAstromScamp() { if (!successProcessing) return; // Don't write an empty catalog (so that tasks checking for failure (non-existence of the catalog) can succeed) if (ra_out.length() == 0) return; char xworld[100] = "X_WORLD"; char yworld[100] = "Y_WORLD"; char mag[100] = "MAG"; char magerr[100] = "MAGERR"; char erra[100] = "ERRA_WORLD"; char errb[100] = "ERRB_WORLD"; char errt[100] = "ERRTHETA_WORLD"; // scamp does not complain if this key is absent char flags[100] = "FLAGS"; char obsdate[100] = "OBSDATE"; // char field[100] = "FIELD_POS"; char *ttype[9] = {xworld, yworld, mag, magerr, erra, errb, errt, flags, obsdate}; // char *ttype[8] = {"X_WORLD", "Y_WORLD", "MAG", "MAGERR", "ERRA_WORLD", "ERRB_WORLD", "ERRTHETA_WORLD", "FIELD_POS"}; // invalid in C++ char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char tf4[10] = "1E"; char tf5[10] = "1E"; char tf6[10] = "1E"; char tf7[10] = "1E"; char tf8[10] = "1I"; char tf9[10] = "1E"; // char tf10[10] = "1I"; char *tform[9] = {tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9}; // Init numSources if called from outside Query if (numSources == 0) numSources = ra_out.length(); double ra_arr[numSources]; double de_arr[numSources]; float mag_arr[numSources]; float magErr_arr[numSources]; float aErr_arr[numSources]; float bErr_arr[numSources]; float thetaErr_arr[numSources]; int flags_arr[numSources]; float obsdate_arr[numSources]; // short fieldpos[numSources]; float dateobs = 2000.0; // dummy, for most catalogs if (refcatName.contains("GAIA")) dateobs = epochReference; for (long i=0; i<numSources; ++i) { ra_arr[i] = ra_out[i]; de_arr[i] = de_out[i]; mag_arr[i] = mag1_out[i]; magErr_arr[i] = 0.1; aErr_arr[i] = 0.00003; bErr_arr[i] = 0.00003; thetaErr_arr[i] = 0.1; flags_arr[i] = 0; obsdate_arr[i] = dateobs; // fieldpos[i] = 1; } int status = 0; fitsfile *fptr; long firstrow = 1; long firstelem = 1; int tfields = 9; long nrows = numSources; QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QString filename = outpath + "/theli_mystd.scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "LDAC_OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, ra_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, de_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_write_col(fptr, TFLOAT, 4, firstrow, firstelem, nrows, magErr_arr, &status); fits_write_col(fptr, TFLOAT, 5, firstrow, firstelem, nrows, aErr_arr, &status); fits_write_col(fptr, TFLOAT, 6, firstrow, firstelem, nrows, bErr_arr, &status); fits_write_col(fptr, TFLOAT, 7, firstrow, firstelem, nrows, thetaErr_arr, &status); fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, flags_arr, &status); fits_write_col(fptr, TFLOAT, 9, firstrow, firstelem, nrows, obsdate_arr, &status); // fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, fieldpos, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); QFile file(filename); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::writeAstromANET() { if (!successProcessing) return; // STEP 1: write a FITS table char xworld[100] = "RA"; char yworld[100] = "DEC"; char mag[100] = "MAG"; char *ttype[3] = {xworld, yworld, mag}; char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char *tform[3] = {tf1, tf2, tf3}; // Init numSources if called from outside Query if (numSources == 0) numSources = ra_out.length(); double ra_arr[numSources]; double de_arr[numSources]; float mag_arr[numSources]; for (long i=0; i<numSources; ++i) { ra_arr[i] = ra_out[i]; de_arr[i] = de_out[i]; mag_arr[i] = mag1_out[i]; } int status = 0; fitsfile *fptr; long firstrow = 1; long firstelem = 1; int tfields = 3; long nrows = numSources; if (numSources > 150000) { QString messageString = "NOTE: More than 150000 sources were retrieved.\n" "The astrometry.net index is not being built as it is very time consuming.\n" "If you want to use astrometry.net, reduce the catalog size by imposing\n" "a (tighter) magnitude limit."; emit messageAvailable(messageString, "warning"); return; } QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QString filename1 = outpath+"/theli_mystd_anet.cat"; filename1 = "!"+filename1; fits_create_file(&fptr, filename1.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, ra_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, de_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // STEP 2: build the anet index // The diameter of one chip in arcmin float diameter = sqrt(naxis1*naxis1+naxis2*naxis2)*pixscale/60.; // The anet scale number float x = 2./log(2.)*log(diameter/6.); int scaleNumber; if (x-int(x) < 0.5) scaleNumber = int(x); else scaleNumber = int(x) + 1; if (scaleNumber<0) scaleNumber = 0; if (scaleNumber>19) scaleNumber = 19; filename1 = outpath+"/theli_mystd_anet.cat"; // without the exclamation mark QString filename2 = outpath + "/theli_mystd.index"; QString buildIndexCommand = findExecutableName("build-astrometry-index"); if (buildIndexCommand.isEmpty()) { emit messageAvailable("Query::writeAstromANET(): Could not find build-astrometry-index command in your PATH", "warning"); return; } buildIndexCommand.append(" -i "+filename1); buildIndexCommand.append(" -o "+filename2); buildIndexCommand.append(" -E -M -S MAG -j 0.1 -I 1"); buildIndexCommand.append(" -t "+outpath); buildIndexCommand.append(" -P "+QString::number(scaleNumber)); runCommand(buildIndexCommand); QFile file(filename2); file.setPermissions(QFile::ReadUser | QFile::WriteUser); QFile file1(filename1); file1.remove(); } void Query::writeAstromIview() { if (!successProcessing) return; // The iView catalog (ASCII) QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile outcat_iview(outpath+"/theli_mystd.iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::writeRefCatxxx(): ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit critical(); return; } // Write iView catalog long dim = ra_out.length(); stream_iview.setRealNumberPrecision(9); for (long i=0; i<dim; ++i) { stream_iview << QString::number(ra_out[i], 'f', 9) << " " << QString::number(de_out[i], 'f', 9) << " " << QString::number(mag1_out[i], 'f', 3) << "\n"; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Query::dumpRefcatID() { if (!successProcessing) return; QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile file(outpath+"/.refcatID"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::dumpRefcatID(): ERROR writing "+outpath+file.fileName()+" : "+file.errorString(), "error"); emit critical(); return; } if (!refcatName.contains("GAIA")) { stream << refcatName+"_"+alpha_manual+"_"+delta_manual+"_"+magLimit_string+"_"+radius_manual << "\n"; } else { stream << refcatName+"_"+alpha_manual+"_"+delta_manual+"_"+magLimit_string+"_"+radius_manual+"_"+maxProperMotion_string << "\n"; } file.close(); } void Query::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Query::"+funcName+":<br>" + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } }
59,174
C++
.cc
1,362
36.408957
224
0.62857
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,433
abszeropoint.cc
schirmermischa_THELI/src/abszp/abszeropoint.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "abszeropoint.h" #include "ui_abszeropoint.h" #include "../functions.h" #include "../instrumentdata.h" #include "../qcustomplot.h" #include "../query/query.h" #include "../myimage/myimage.h" #include "../threading/memoryworker.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "fitsio2.h" #include <QDir> #include <QFileDialog> #include <QTextStream> #include <QMessageBox> #include <QDebug> #include <QThread> #include <QTest> AbsZeroPoint::AbsZeroPoint(QString image, QWidget *parent) : QMainWindow(parent), startImage(image), ui(new Ui::AbsZeroPoint) { ui->setupUi(this); initEnvironment(thelidir, userdir); initGUI(); if (!startImage.isEmpty()) { ui->zpImageLineEdit->setText(startImage); } performingStartup = false; connect(this, &AbsZeroPoint::messageAvailable, this, &AbsZeroPoint::displayMessage); connect(this, &AbsZeroPoint::readyForPlotting, this, &AbsZeroPoint::buildAbsPhot); // connect(this, &AbsZeroPoint::progressUpdate, this, &AbsZeroPoint::progressUpdateReceived); // connect(this, &AbsZeroPoint::resetProgressBar, this, &AbsZeroPoint::resetProgressBarReceived); } void AbsZeroPoint::closeEvent(QCloseEvent *event) { emit abszpClosed(); event->accept(); } AbsZeroPoint::~AbsZeroPoint() { delete absPhot; absPhot = nullptr; delete ui; } void AbsZeroPoint::displayMessage(QString message, QString type) { if (type == "error") ui->zpPlainTextEdit->appendHtml("<font color=\"#ee0000\">"+message+"</font>"); else if (type == "info") ui->zpPlainTextEdit->appendHtml("<font color=\"#0033cc\">"+message+"</font>"); else ui->zpPlainTextEdit->appendHtml(message); } void AbsZeroPoint::initGUI() { clearText(); // Fill in defaults on_zpRefcatComboBox_currentTextChanged("ATLAS-REFCAT2"); on_zpFilterComboBox_currentTextChanged("g"); defaults_if_empty(); // Crashes the GUI upon launch // ui->topDockWidget->titleBarWidget()->setFixedHeight(1); // Connections // For the GUI connect(ui->zpSaturationLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); connect(ui->zpPhoterrorLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); connect(ui->zpApertureLineEdit, &QLineEdit::textChanged, this, &AbsZeroPoint::validate); // For a mouse-click in the plot connect(ui->zpPlot, &QCustomPlot::plottableClick, this, &AbsZeroPoint::showData); // Deactivate UKIDSS for the time being // very inhomogeneous sky coverage in various epochs const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( ui->zpRefcatComboBox->model() ); model->item(7,0)->setEnabled(false); // Provide a roughly log range of apertures ui->zpApertureLineEdit->setText("10,15,20,25,30,40,50,75,100"); // Initialize the plot ui->zpPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->zpPlot->plotLayout()->clear(); // clear default axis rect so we can start from scratch setWindowIcon(QIcon(":/icons/abszp.png")); loadPreferences(); } // UNUSED slot void AbsZeroPoint::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void AbsZeroPoint::clearText() { QFont notoFont("Noto Sans", 10, QFont::Normal); ui->zpHeaderLabel->setText("System output"); ui->zpPlainTextEdit->clear(); ui->zpPlainTextEdit->setFont(notoFont); } void AbsZeroPoint::validate() { // Validators QRegExp rfloat( "[0-9]*[.]{0,1}[0-9]+" ); QValidator* validator_float = new QRegExpValidator(rfloat, this); QRegExp rintcomma( "[0-9, ]+" ); QValidator* validator_intcomma = new QRegExpValidator(rintcomma, this); QRegExp rint( "^[-]{0,1}[0-9]+" ); QValidator* validator_int = new QRegExpValidator(rint, this); ui->zpSaturationLineEdit->setValidator(validator_float); ui->zpPhoterrorLineEdit->setValidator(validator_float); ui->zpApertureLineEdit->setValidator(validator_intcomma); ui->zpDTLineEdit->setValidator(validator_float); ui->zpDMINLineEdit->setValidator(validator_int); } void AbsZeroPoint::defaults_if_empty() { if (ui->zpPhoterrorLineEdit->text().isEmpty()) ui->zpPhoterrorLineEdit->setText("0.05"); if (ui->zpSaturationLineEdit->text().isEmpty()) ui->zpSaturationLineEdit->setText("100"); if (ui->zpApertureLineEdit->text().isEmpty()) ui->zpApertureLineEdit->setText("20"); } void AbsZeroPoint::loadPreferences() { QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox").toInt(); verbosity = settings.value("prefVerbosityComboBox").toInt(); } void AbsZeroPoint::on_startPushButton_clicked() { if (ui->zpImageLineEdit->text().isEmpty()) { QMessageBox::information(this, tr("Missing image."), tr("You have not specified an image to be calibrated."), QMessageBox::Ok); return; } on_zpClearPushButton_clicked(); absPhot->clear(); plot(); QTest::qWait(50); // Launch the thread ui->startPushButton->setText("Running ..."); ui->startPushButton->setDisabled(true); ui->zpColorComboBox->setDisabled(true); ui->zpFilterComboBox->setDisabled(true); ui->zpRefcatComboBox->setDisabled(true); workerThread = new QThread(); abszpWorker = new AbszpWorker(this); //workerInit = true; //workerThreadInit = true; abszpWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, abszpWorker, &AbszpWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::finished, this, &AbsZeroPoint::finishedCalculations); connect(abszpWorker, &AbszpWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::finished, abszpWorker, &QObject::deleteLater, Qt::DirectConnection); connect(abszpWorker, &AbszpWorker::messageAvailable, this, &AbsZeroPoint::displayMessage); workerThread->start(); } void AbsZeroPoint::criticalReceived() { emit finished(); } void AbsZeroPoint::updateSaturationValue(float value) { // use 90% of the highest measured value as a limit ui->zpSaturationLineEdit->setText(QString::number(0.9*value, 'f', 2)); } // Running in separate thread! // Here is where the actual work happens void AbsZeroPoint::taskInternalAbszeropoint() { myImage = new MyImage(ui->zpImageLineEdit->text(), QVector<bool>(), &verbosity); connect(myImage, &MyImage::messageAvailable, this, &AbsZeroPoint::displayMessage); connect(myImage, &MyImage::critical, this, &AbsZeroPoint::criticalReceived); myImage->globalMaskAvailable = false; myImage->maxCPU = maxCPU; myImage->loadHeader(); bool successQuery = true; bool successDetection = true; // executing catalog query and source detection in parallel #pragma omp parallel sections { #pragma omp section { emit messageAvailable("Querying " + ui->zpRefcatComboBox->currentText() + " ...", "ignore"); queryRefCat(); if (numRefSources == 0) { emit messageAvailable("AbsZP: Aborting, could not find any reference sources.", "error"); emit finished(); successQuery = false; } } #pragma omp section { emit messageAvailable("Detecting objects in image ...", "ignore"); QString DT = ui->zpDTLineEdit->text(); QString DMIN = ui->zpDMINLineEdit->text(); if (DT.isEmpty()) { DT = "10"; ui->zpDTLineEdit->setText("10"); } if (DMIN.isEmpty()) { DMIN = "10"; ui->zpDMINLineEdit->setText("10"); } // Collect apertures and pass them on QString ap = ui->zpApertureLineEdit->text(); ap = ap.replace(","," ").simplified(); QStringList apList = ap.split(" "); QVector<float> apertures; for (auto &val : apList) { apertures << val.toFloat(); } myImage->apertures = apertures; // Detect objects myImage->readImage(ui->zpImageLineEdit->text()); if (!myImage->successProcessing) successDetection = false; myImage->readWeight(); myImage->successProcessing = true; myImage->apertures = apertures; myImage->backgroundModel(100, "interpolate"); myImage->segmentImage(DT, DMIN, true, false); long ngood = 0; for (auto &it : myImage->objectList) if (it->FLAGS == 0) ++ngood; emit messageAvailable(QString::number(myImage->objectList.length()) + " sources detected, "+QString::number(ngood) + " selected", "info"); } } if (!successDetection || !successQuery) return; emit messageAvailable("Matching objects with reference sources ...", "ignore"); refDat.clear(); objDat.clear(); // DEC comes first in the catalogs, because the matching alg sorts the vectors for DEC for (auto &object : myImage->objectList) { QVector<double> objdata; if (object->FLAGS == 0) { objdata << object->DELTA_J2000 << object->ALPHA_J2000 << object->MAG_AUTO << object->MAGERR_AUTO << object->MAG_APER << object->MAGERR_APER; objDat.append(objdata); // qDebug() << qSetRealNumberPrecision(12) << object->ALPHA_J2000 << object->DELTA_J2000; } } // Estimate the matching tolerance myImage->estimateMatchingTolerance(); // qDebug() << "matching tolerance: " << myImage->matchingTolerance; // qDebug() << " " ; // spacer between object and reference catalog output // Iterate the matching once to get a sensible upper limit for the refcat download // (and thus a cleaner process in extreme cases where the refcat is MUCH deeper than the image) refCatUpperMagLimit = 40.; int multiple1 = 0; int multiple2 = 0; int loop = 0; while (loop <= 1) { // Collect suitable reference sources refDat.clear(); for (int i=0; i<raRefCat.length(); ++i) { QVector<double> refdata; // only propagate reference sources inside the image area and brighter than the upper mag limit if (myImage->containsRaDec(raRefCat[i], deRefCat[i]) && mag1RefCat[i] < refCatUpperMagLimit) { refdata << deRefCat[i] << raRefCat[i] << mag1RefCat[i] << mag2RefCat[i] << mag1errRefCat[i] << mag2errRefCat[i]; refDat.append(refdata); } // qDebug() << qSetRealNumberPrecision(12) << raRefCat[i] << deRefCat[i]; } // Now do the matching multiple1 = 0; multiple2 = 0; matched.clear(); // Otherwise, multiple runs will append to previous data if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { // simple way to accomodate accumulated proper motions for 2MASS (adding 1" matching radius) match2D_refcoords(objDat, refDat, matched, myImage->matchingTolerance + 1./3600., multiple1, multiple2, maxCPU); } else { match2D_refcoords(objDat, refDat, matched, myImage->matchingTolerance, multiple1, multiple2, maxCPU); } // Update upper refcat mag limit and repeat once refCatUpperMagLimit = getFirstZPestimate(); // qDebug() << "upper limit:" << refCatUpperMagLimit << refDat.length(); ++loop; } // debugging: output catalogs QFile outcat_detected(myImage->path+"/detected.cat"); QFile outcat_downloaded(myImage->path+"/downloaded.cat"); QTextStream stream_detected(&outcat_detected); QTextStream stream_downloaded(&outcat_downloaded); outcat_detected.open(QIODevice::WriteOnly); outcat_downloaded.open(QIODevice::WriteOnly); long i = 0; for (auto &it : raRefCat) { stream_downloaded << QString::number(it, 'f', 9) << " " << QString::number(deRefCat[i], 'f', 9) << " " << QString::number(mag1RefCat[i], 'f', 3) << "\n"; ++i; } outcat_downloaded.close(); outcat_downloaded.setPermissions(QFile::ReadUser | QFile::WriteUser); for (auto &it : objDat) { stream_detected << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_detected.close(); outcat_detected.setPermissions(QFile::ReadUser | QFile::WriteUser); if (matched.length() == 0) { emit messageAvailable("No matches found!", "error"); emit finished(); return; } else { emit messageAvailable(QString::number(matched.length()) + " clean matches found.", "ignore"); // for (auto &it : matched) qDebug() << qSetRealNumberPrecision(10) << it[0] << it[1]; } if (multiple1 > 1) emit messageAvailable("Multiply matched objects (ignored): " + QString::number(multiple1), "ignore"); if (multiple2 > 1) emit messageAvailable("Multiply matched reference sources (ignored): " + QString::number(multiple2), "ignore"); // The plotting makes changes to the GUI, and therefore has been done from within the main thread! emit readyForPlotting(); // update the catalog display if iview is open writeAbsPhotRefcat(); if (iViewOpen) on_showAbsphotPushButton_clicked(); getFirstZPestimate(); } double AbsZeroPoint::getFirstZPestimate() { // if the reference catalog is much deeper than the image, we should apply a magnitude cut before matching. // Hence, do a rough ZP estimate (without color term) and then rematch QVector<double> magdiff; QVector<double> magDetected; magdiff.resize(matched.length()); magDetected.resize(matched.length()); long i = 0; for (auto &it : matched) { magdiff[i] = it[2] - it[6]; magDetected[i] = it[6]; ++i; } double medianZP = straightMedian_T(magdiff); // double rms = madMask_T(magdiff); // return the faintest detected magnitude estimate, and add 0.3 mag as a margin return maxVec_T(magDetected) + medianZP + 0.3; } void AbsZeroPoint::queryRefCat() { Query *query = new Query(&verbosity); query->photomDir = myImage->path; query->photomImageName = myImage->name; query->refcatName = ui->zpRefcatComboBox->currentText(); QString filter1 = ui->zpFilterComboBox->currentText(); QString filter2 = ui->zpColorComboBox->currentText().remove('-').remove(filter1); QString filter3 = ""; // For Gaia we enforce to always use BP-RP as colour if (query->refcatName.contains("GAIA")) { filter1 = "G"; filter2 = "BP"; filter3 = "RP"; query->refcatFilter1 = filter1; query->refcatFilter2 = filter2; query->refcatFilter3 = filter3; } else { query->refcatFilter1 = filter1; query->refcatFilter2 = filter2; } query->doPhotomQueryFromWeb(); raRefCat.swap(query->ra_out); deRefCat.swap(query->de_out); mag1RefCat.swap(query->mag1_out); mag2RefCat.swap(query->mag2_out); mag1errRefCat.swap(query->mag1err_out); mag2errRefCat.swap(query->mag2err_out); if (query->refcatName.contains("GAIA")) { mag3RefCat.swap(query->mag3_out); mag3errRefCat.swap(query->mag3err_out); } numRefSources = query->numSources; // Conversion to AB mag if not yet done // Convert APASS VEGA mags to AB mags // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html if (query->refcatName.contains("APASS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "B") corr1 = -0.09; else if (filter1 == "V") corr1 = 0.02; if (filter2 == "B") corr2 = -0.09; else if (filter2 == "V") corr2 = 0.02; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert Gaia mags to AB mags // https://gea.esac.esa.int/archive/documentation/GEDR3/Data_processing/chap_cu5pho/cu5pho_sec_photProc/cu5pho_ssec_photCal.html if (query->refcatName.contains("GAIA")) { float corr1 = 0.; float corr2 = 0.; float corr3 = 0.; if (filter1 == "G") corr1 = 0.1136; else if (filter1 == "BP") corr1 = 0.0155; else if (filter1 == "RP") corr1 = 0.3561; if (filter2 == "G") corr2 = 0.1136; else if (filter2 == "BP") corr2 = 0.0155; else if (filter2 == "RP") corr2 = 0.3561; if (filter3 == "G") corr3 = 0.1136; else if (filter3 == "BP") corr3 = 0.0155; else if (filter3 == "RP") corr3 = 0.3561; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; for (auto &mag : mag3RefCat) mag += corr3; } // Convert 2MASS VEGA mags to AB mags // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html if (query->refcatName.contains("2MASS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "J") corr1 = 0.91; else if (filter1 == "H") corr1 = 1.39; else if (filter1 == "Ks") corr1 = 1.85; if (filter2 == "J") corr2 = 0.91; else if (filter2 == "H") corr2 = 1.39; else if (filter2 == "Ks") corr2 = 1.85; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert VHS VEGA mags to AB mags // Pons et al. 2019, MNRAS, 484, 5142: https://academic.oup.com/mnras/article/484/4/5142/5303744 // http://www.astronomy.ohio-state.edu/~martini/usefuldata.html (for Y-band) if (query->refcatName.contains("VHS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "Y") corr1 = 0.634; else if (filter1 == "J") corr1 = 0.937; else if (filter1 == "H") corr1 = 1.384; else if (filter1 == "Ks") corr1 = 1.839; if (filter2 == "Y") corr2 = 0.634; else if (filter2 == "J") corr2 = 0.937; else if (filter2 == "H") corr2 = 1.384; else if (filter2 == "Ks") corr2 = 1.839; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } // Convert UKIDSS VEGA mags to AB mags // Hewett et al. 2006, MNRAS, 367, 454 if (query->refcatName.contains("UKIDSS")) { float corr1 = 0.; float corr2 = 0.; if (filter1 == "J") corr1 = 0.938; else if (filter1 == "H") corr1 = 1.379; else if (filter1 == "Ks") corr1 = 1.900; if (filter2 == "J") corr2 = 0.938; else if (filter2 == "H") corr2 = 1.379; else if (filter2 == "Ks") corr2 = 1.900; for (auto &mag : mag1RefCat) mag += corr1; for (auto &mag : mag2RefCat) mag += corr2; } delete query; query = nullptr; // Count how many inside image long ngood = 0; for (int i=0; i<raRefCat.length(); ++i) { if (myImage->containsRaDec(raRefCat[i], deRefCat[i])) ++ngood; } emit messageAvailable(QString::number(numRefSources) + " reference sources found, "+QString::number(ngood)+" inside image", "info"); emit messageAvailable("Please wait for object detection to finish ...", "ignore"); } void AbsZeroPoint::writeAbsPhotRefcat() { // The iView catalog (ASCII) QString outpath = myImage->path; QDir outdir(outpath); if (!outdir.exists()) { emit messageAvailable(QString(__func__) + " : " + myImage->path +" directory does not exist to write AbsPhot reference catalogs", "error"); emit criticalReceived(); return; } QFile outcat_iview_matched(outpath+"/ABSPHOT_sources_matched.iview"); QTextStream stream_iview_matched(&outcat_iview_matched); if( !outcat_iview_matched.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + " : ERROR writing "+outpath+outcat_iview_matched.fileName()+" : "+outcat_iview_matched.errorString(), "error"); emit criticalReceived(); return; } QFile outcat_iview_down(outpath+"/ABSPHOT_sources_downloaded.iview"); QTextStream stream_iview_down(&outcat_iview_down); if( !outcat_iview_down.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + " : ERROR writing "+outpath+outcat_iview_down.fileName()+" : "+outcat_iview_down.errorString(), "error"); emit criticalReceived(); return; } // Write downloaded iView catalog for (auto &it : refDat) { stream_iview_down << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_iview_down.close(); outcat_iview_down.setPermissions(QFile::ReadUser | QFile::WriteUser); // Write matched iView catalog for (auto &it : matched) { stream_iview_matched << QString::number(it[1], 'f', 9) << " " << QString::number(it[0], 'f', 9) << " " << QString::number(it[2], 'f', 3) << "\n"; } outcat_iview_matched.close(); outcat_iview_matched.setPermissions(QFile::ReadUser | QFile::WriteUser); } // Not yet developed for Gaia void AbsZeroPoint::buildAbsPhot() { QString apertures = ui->zpApertureLineEdit->text(); apertures = apertures.replace(",", " "); apertures = apertures.simplified(); QStringList aperList = apertures.split(" "); int numAper = aperList.length(); absPhot->numAper += numAper; for (int i=0; i<numAper; ++i) { QString ap = aperList.at(i); absPhot->qv_apertures.append(ap.toDouble()); } // We need to know which color term was used so that we can // calculate the color correctly absPhot->color = ui->zpColorComboBox->currentText(); absPhot->filter = ui->zpFilterComboBox->currentText(); QString colorfilter = ui->zpColorComboBox->currentText(); absPhot->colorfilter = colorfilter.remove("-").remove(ui->zpFilterComboBox->currentText()); // Each matched entry contains // RA DEC Mag1REF Mag2REF Mag1ERR_REF Mag2ERR_REF MAG_AUTO MAGERR_AUTO MAG_APER(vector) MAGERR_APER(vector) // Object magnitudes are calculated for a fiducial ZP = 0, and need to be exposure time normalized // CHECK: this would go wrong if someone calibrates an image that is not normalized to one second! // float normalization = 2.5*log10(myImage->exptime); float normalization = 0.; // additive, in mag-space for (auto &match : matched) { absPhot->qv_RA.append(match[1]); absPhot->qv_DEC.append(match[0]); absPhot->qv_mag1ref.append(match[2]); absPhot->qv_mag2ref.append(match[3]); absPhot->qv_mag1errref.append(match[4]); absPhot->qv_mag2errref.append(match[5]); absPhot->qv_magauto.append(match[6] + normalization); absPhot->qv_magerrauto.append(match[7]); QVector<double> dummy1; QVector<double> dummy2; for (int i=0; i<numAper; ++i) { dummy1.append(match[8+i] + normalization); dummy2.append(match[8+numAper+i]); } absPhot->qv_magaper.append(dummy1); absPhot->qv_magerraper.append(dummy2); absPhot->qv_ManualMask.append(false); absPhot->numObj += 1; } // Calculations absPhot->initialized = true; // Individual color indices absPhot->getColor(); // Calculate the ZP dependence on the color term // absPhot->regressionLinfit(absPhot->slope, absPhot->cutoff); if (!doColortermFit()) return; // Calculate the ZPs per aperture absPhot->getZP(); plot(); emit finished(); } void AbsZeroPoint::finishedCalculations() { ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); ui->zpColorComboBox->setEnabled(true); ui->zpFilterComboBox->setEnabled(true); ui->zpRefcatComboBox->setEnabled(true); } void AbsZeroPoint::on_abortPushButton_clicked() { if (!ui->startPushButton->isEnabled()) { if (workerThread) workerThread->quit(); if (workerThread) workerThread->wait(); finishedCalculations(); } } void AbsZeroPoint::on_zpLoadPushButton_clicked() { QString currentFileName = QFileDialog::getOpenFileName(this, tr("Select astrometrically calibrated image"), QDir::homePath(), tr("Images (*.fits *.fit *.fts *.FIT *.FITS *.FTS);; All (*.*)")); ui->zpImageLineEdit->setText(currentFileName); paintPathLineEdit(ui->zpImageLineEdit, currentFileName, "file"); } void AbsZeroPoint::on_zpImageLineEdit_textChanged(const QString &arg1) { paintPathLineEdit(ui->zpImageLineEdit, arg1, "file"); fileInfo.setFile(arg1); // Clear the plot on_zpClearPushButton_clicked(); } void AbsZeroPoint::on_zpRefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1.contains("ATLAS-REFCAT2")) { fill_combobox(ui->zpFilterComboBox, "g r i z"); fill_combobox(ui->zpColorComboBox, "g-r g-i r-i i-z"); } if (arg1.contains("GAIA")) { fill_combobox(ui->zpFilterComboBox, "G"); fill_combobox(ui->zpColorComboBox, "BP-RP"); } if (arg1.contains("PANSTARRS")) { fill_combobox(ui->zpFilterComboBox, "g r i z y"); fill_combobox(ui->zpColorComboBox, "g-r g-i r-i i-z z-y"); } else if (arg1.contains("SDSS")) { fill_combobox(ui->zpFilterComboBox, "u g r i z"); fill_combobox(ui->zpColorComboBox, "u-g g-r g-i r-i i-z"); } else if (arg1.contains("SKYMAPPER")) { fill_combobox(ui->zpFilterComboBox, "u v g r i z"); fill_combobox(ui->zpColorComboBox, "u-g u-v g-r v-r g-i v-i r-i i-z"); } else if (arg1.contains("APASS")) { fill_combobox(ui->zpFilterComboBox, "B V g r i"); fill_combobox(ui->zpColorComboBox, "B-V g-r g-i r-i"); } else if (arg1.contains("2MASS")) { fill_combobox(ui->zpFilterComboBox, "J H Ks"); fill_combobox(ui->zpColorComboBox, "J-H J-Ks H-Ks"); } else if (arg1.contains("VHS")) { fill_combobox(ui->zpFilterComboBox, "Y J H Ks"); fill_combobox(ui->zpColorComboBox, "Y-J J-H J-Ks H-Ks"); } // currently not implemented because of very patchy photometric coverage else if (arg1.contains("UKIDSS")) { fill_combobox(ui->zpFilterComboBox, "Y J H K"); fill_combobox(ui->zpFilterComboBox, "Y-J J-H J-K H-K"); } on_zpFilterComboBox_currentTextChanged(ui->zpFilterComboBox->currentText()); } void AbsZeroPoint::on_zpClearPushButton_clicked() { if (absPhot->numObj > 0) { clearText(); absPhot->clear(); ui->zpPlot->clearGraphs(); ui->zpPlot->clearItems(); ui->zpPlot->plotLayout()->clear(); plot(); } } void AbsZeroPoint::on_zpExportPushButton_clicked() { if (absPhot->numObj == 0) return; QString path = fileInfo.absolutePath(); QString base = fileInfo.completeBaseName(); /* PDSF output is extremely slow, freezes the GUI for 1 minute; * deactivated for the time being QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save Image"), base+".png", tr("Graphics file (*.png *.pdf)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (! (graphicsInfo.suffix() == "png" || graphicsInfo.suffix() == "pdf")) { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only graphics formats .png and .pdf are allowed."), QMessageBox::Ok); return; } if (graphicsInfo.suffix() == "pdf") ui->zpPlot->savePdf(saveFileName); else if (graphicsInfo.suffix() == "png") ui->zpPlot->savePng(saveFileName); */ QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save .png Image"), path+"/"+base+"_ZPcurve.png", tr("Graphics file (*.png)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (graphicsInfo.suffix() != "png") { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only .png format is currently allowed."), QMessageBox::Ok); return; } else { ui->zpPlot->savePng(saveFileName,0,0,1.25); } } void AbsZeroPoint::on_zpFilterComboBox_currentTextChanged(const QString &arg1) { // Leave the colour combobox unchanged for Gaia. We always use BP-RP. if (ui->zpRefcatComboBox->currentText().contains("GAIA")) return; // Mask color terms that do not contain the primary filter: const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( ui->zpColorComboBox->model() ); int length = ui->zpColorComboBox->count(); bool updated = false; for (int i=0; i<length; ++i) { QString text = model->item(i,0)->text(); if (!(model->item(i,0)->text()).contains(arg1)) { model->item(i,0)->setEnabled(false); } else { model->item(i,0)->setEnabled(true); if (!updated) { ui->zpColorComboBox->setCurrentIndex(i); updated = true; } } } on_zpClearPushButton_clicked(); } /* void AbsZeroPoint::endScript() { // Process the result table QString image = ui->zpImageLineEdit->text(); QFileInfo fileInfo(image); QString catalogName = fileInfo.path()+"/"+fileInfo.completeBaseName()+".absphot.cat"; // The file contains Ra Dec Mag1REF Mag2REF MagAUTO MagerrAUTO MagAPER(vector) QString apertures = ui->zpApertureLineEdit->text(); apertures = apertures.replace(",", " "); apertures = apertures.simplified(); QStringList aperList = apertures.split(" "); int numAper = aperList.length(); absPhot->numAper += numAper; for (int i=0; i<numAper; ++i) { QString ap = aperList.at(i); absPhot->qv_apertures.append(ap.toDouble()); } // We need to know which color term was used so that we can // calculate the color correctly absPhot->color = ui->zpColorComboBox->currentText(); absPhot->filter = ui->zpFilterComboBox->currentText(); QString colorfilter = ui->zpColorComboBox->currentText(); absPhot->colorfilter = colorfilter.remove("-").remove(ui->zpFilterComboBox->currentText()); QFile catalog(catalogName); QString line; QStringList lineList; // Read all the magnitudes into the absPhot class if ( catalog.open(QIODevice::ReadOnly)) { QTextStream stream( &catalog ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); // skip header lines if (line.contains("#")) continue; lineList = line.split(" "); absPhot->qv_RA.append(lineList.at(0).toDouble()); absPhot->qv_DEC.append(lineList.at(1).toDouble()); absPhot->qv_mag1ref.append(lineList.at(2).toDouble()); absPhot->qv_mag1errref.append(lineList.at(3).toDouble()); absPhot->qv_mag2ref.append(lineList.at(4).toDouble()); absPhot->qv_mag2errref.append(lineList.at(5).toDouble()); absPhot->qv_magauto.append(lineList.at(6).toDouble()); absPhot->qv_magerrauto.append(lineList.at(7).toDouble()); QVector<double> dummy = QVector<double>(); for (int i=0; i<numAper; ++i) { dummy.append(lineList.at(8+i).toDouble()); } absPhot->qv_magaper.append(dummy); absPhot->qv_ManualMask.append(false); absPhot->numObj += 1; } catalog.close(); } // Calculations absPhot->initialized = true; // Individual color indices absPhot->getColor(); // Calculate the ZP dependence on the color term // absPhot->regressionLinfit(absPhot->slope, absPhot->cutoff); if (!doColortermFit()) return; // Calculate the ZPs per aperture absPhot->getZP(); plot(); ui->startPushButton->setEnabled(true); ui->startPushButton->setText("Start"); ui->zpColorComboBox->setEnabled(true); ui->zpFilterComboBox->setEnabled(true); ui->zpRefcatComboBox->setEnabled(true); } */ // void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex) { if (plottable->parentLayerable()->objectName() == "aperRect") { absPhot->ZPSelected = QString::number(absPhot->qv_ZP[dataIndex], 'f', 3); absPhot->ZPerrSelected = QString::number(absPhot->qv_ZPerr[dataIndex], 'f', 3); absPhot->Aperture = QString::number(absPhot->qv_apertures[dataIndex], 'f', 3); absPhot->Color1Selected = QString::number(absPhot->fitParams[1], 'f', 4); absPhot->Color2Selected = QString::number(absPhot->fitParams[2], 'f', 4); absPhot->Color3Selected = QString::number(absPhot->fitParams[3], 'f', 4); absPhot->ColorErr1Selected = QString::number(absPhot->fitParamsErr[1], 'f', 4); absPhot->ColorErr2Selected = QString::number(absPhot->fitParamsErr[2], 'f', 4); absPhot->ColorErr3Selected = QString::number(absPhot->fitParamsErr[3], 'f', 4); updateCoaddHeader(); } /* * * NOT WORKING! for some reason dataIndex does not select the object clicked, but some random other object. * It appears that data points plotted start with index 0 at left and have highest index at right. */ else if (plottable->parentLayerable()->objectName() == "colorRect") { // Select only clicks on data points // if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable)) { // set or unset the flag for this data point // if (absPhot->qv_ManualFlag[dataIndex]) absPhot->qv_ManualFlag[dataIndex] = false; // else absPhot->qv_ManualFlag[dataIndex] = true; // qDebug() << qSetRealNumberPrecision(12) << dataIndex << "AA" << absPhot->qv_colorIndividual[dataIndex] << absPhot->qv_ZPIndividual[dataIndex] << absPhot->qv_RA[dataIndex] << absPhot->qv_DEC[dataIndex]; // absPhot->regression(absPhot->slope, absPhot->cutoff); // absPhot->getZP(); // plot(); // } } } void AbsZeroPoint::plot() { if (absPhot->numAper == 0) { ui->zpPlot->replot(); ui->zpPlot->update(); return; } ui->zpPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->zpPlot->plotLayout()->clear(); // clear default axis rect so we can start from scratch // The axes box for the ZP Growth curve QCPAxisRect *AxisRectAper = new QCPAxisRect(ui->zpPlot); AxisRectAper->setObjectName("aperRect"); AxisRectAper->setupFullAxesBox(true); AxisRectAper->axis(QCPAxis::atBottom)->setLabel("Aperture diameter [pixel]"); AxisRectAper->axis(QCPAxis::atLeft)->setLabel("ZP "+ui->zpFilterComboBox->currentText()+" [ mag ]"); AxisRectAper->axis(QCPAxis::atBottom)->setRange(0,100); AxisRectAper->axis(QCPAxis::atLeft)->setRange(24,28); // The axes box for the ZP color dependence QCPAxisRect *AxisRectColor = new QCPAxisRect(ui->zpPlot); AxisRectColor->setObjectName("colorRect"); AxisRectColor->setupFullAxesBox(true); AxisRectColor->axis(QCPAxis::atBottom)->setLabel(ui->zpColorComboBox->currentText()+" [ mag ]"); AxisRectColor->axis(QCPAxis::atLeft)->setLabel("Ref - Inst [ mag ]"); AxisRectColor->axis(QCPAxis::atBottom)->setRange(-1,3); AxisRectColor->axis(QCPAxis::atLeft)->setRange(24,28); // Space for the title bar QString imagename = fileInfo.fileName(); QCPTextElement *title = new QCPTextElement(ui->zpPlot, imagename, QFont("sans", 12)); ui->zpPlot->plotLayout()->addElement(0, 0, title); ui->zpPlot->plotLayout()->addElement(1, 0, AxisRectAper); ui->zpPlot->plotLayout()->addElement(2, 0, AxisRectColor); /* // The Auto mag Rectangle in the growth curve. Must plot first, so other clickable data points end up on top QCPItemRect *magAuto = new QCPItemRect(ui->zpPlot); magAuto->topLeft->setType(QCPItemPosition::PositionType::ptPlotCoords); magAuto->bottomRight->setType(QCPItemPosition::PositionType::ptPlotCoords); magAuto->topLeft->setCoords(QPointF(minVec_T(absPhot->qv_apertures), absPhot->ZPauto + absPhot->ZPautoerr)); magAuto->bottomRight->setCoords(QPointF(maxVec_T(absPhot->qv_apertures), absPhot->ZPauto - absPhot->ZPautoerr)); magAuto->setClipToAxisRect(true); magAuto->setPen(QPen(Qt::red)); magAuto->setSelectable(false); QBrush boxBrush(QColor(255, 0, 0, 100)); magAuto->setBrush(boxBrush); double maxAp = maxVec_T(absPhot->qv_apertures); double minAp = minVec_T(absPhot->qv_apertures); // Add label for magAuto QCPItemText *magAutoText = new QCPItemText(ui->zpPlot); magAutoText->position->setType(QCPItemPosition::ptPlotCoords); magAutoText->setPositionAlignment(Qt::AlignLeft|Qt::AlignCenter); magAutoText->position->setCoords(0.5*(minAp+maxAp), absPhot->ZPauto); magAutoText->setSelectable(false); magAutoText->setText("MAG_AUTO"); magAutoText->setTextAlignment(Qt::AlignLeft); magAutoText->setFont(QFont(font().family(), 9)); magAutoText->setPadding(QMargins(4, 0, 4, 0)); magAutoText->setPen(QPen(Qt::black)); */ // The graph for the ZP growth curve QCPGraph *aperZPGraph = ui->zpPlot->addGraph(AxisRectAper->axis(QCPAxis::atBottom), AxisRectAper->axis(QCPAxis::atLeft)); aperZPGraph->setSelectable(QCP::stSingleData); aperZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(Qt::blue), QBrush(Qt::blue), 6)); aperZPGraph->setLineStyle(QCPGraph::lsLine); aperZPGraph->setData(absPhot->qv_apertures,absPhot->qv_ZP); QCPSelectionDecorator *decorator = new QCPSelectionDecorator(); QCPScatterStyle scatterstyle(QCPScatterStyle::ScatterShape::ssSquare, QColor("#009988"), QColor("#009988"), 12); decorator->setPen(QPen(QColor("#000000"))); decorator->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); aperZPGraph->setSelectionDecorator(decorator); double xmin = minVec_T(absPhot->qv_apertures); double xmax = maxVec_T(absPhot->qv_apertures); double ymin = minVec_T(absPhot->qv_ZP) - absPhot->qv_ZPerr[0]; double ymax = maxVec_T(absPhot->qv_ZP) + absPhot->qv_ZPerr[absPhot->qv_ZPerr.size()-1]; double dx = (xmax - xmin) * 0.05; double dy = (ymax - ymin) * 0.05; aperZPGraph->keyAxis()->setRange(xmin-dx, xmax+dx); aperZPGraph->valueAxis()->setRange(ymin-dy, ymax+dy); // Error bars QCPErrorBars *errorBarsZP = new QCPErrorBars(aperZPGraph->keyAxis(), aperZPGraph->valueAxis()); errorBarsZP->setDataPlottable(aperZPGraph); errorBarsZP->setSelectable(QCP::SelectionType::stNone); errorBarsZP->setData(absPhot->qv_ZPerr); // The graph for the color dependence QCPGraph *colorZPGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraph->setSelectable(QCP::stSingleData); // colorZPGraph->setSelectable(QCP::SelectionType::stNone); colorZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#096169")), QBrush(QColor("#096169")), 6)); colorZPGraph->setLineStyle(QCPGraph::lsNone); colorZPGraph->rescaleKeyAxis(); colorZPGraph->rescaleValueAxis(); colorZPGraph->setData(absPhot->qv_colorIndividual,absPhot->qv_ZPIndividual); // vertical error bars QCPErrorBars *errorValueBarsColor = new QCPErrorBars(colorZPGraph->keyAxis(), colorZPGraph->valueAxis()); errorValueBarsColor->setDataPlottable(colorZPGraph); errorValueBarsColor->setSelectable(QCP::SelectionType::stNone); errorValueBarsColor->setData(absPhot->qv_ZPerrIndividual); errorValueBarsColor->setPen(QPen(QColor("#1eb7ce"))); errorValueBarsColor->setErrorType(QCPErrorBars::etValueError); // horizontal error bars QCPErrorBars *errorKeyBarsColor = new QCPErrorBars(colorZPGraph->keyAxis(), colorZPGraph->valueAxis()); errorKeyBarsColor->setDataPlottable(colorZPGraph); errorKeyBarsColor->setSelectable(QCP::SelectionType::stNone); errorKeyBarsColor->setData(absPhot->qv_colorErrIndividual); errorKeyBarsColor->setPen(QPen(QColor("#1eb7ce"))); errorKeyBarsColor->setErrorType(QCPErrorBars::etKeyError); xmin = minVec_T(absPhot->qv_colorIndividual); xmax = maxVec_T(absPhot->qv_colorIndividual); ymin = minVec_T(absPhot->qv_ZPIndividual); ymax = maxVec_T(absPhot->qv_ZPIndividual); // we always want to see the origin: if (xmin > 0.) xmin = -0.1; dx = (xmax - xmin) * 0.08; dy = (ymax - ymin) * 0.08; colorZPGraph->keyAxis()->setRange(xmin-dx, xmax+dx); colorZPGraph->valueAxis()->setRange(ymin-dy, ymax+dy); // The graph for the color dependence outliers if (absPhot->num_outliers > 0) { QCPGraph *colorOutlierZPGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorOutlierZPGraph->setSelectable(QCP::SelectionType::stNone); colorOutlierZPGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCrossCircle, 12)); colorOutlierZPGraph->setPen(QPen(QColor(Qt::red))); colorOutlierZPGraph->setLineStyle(QCPGraph::lsNone); colorOutlierZPGraph->rescaleKeyAxis(); colorOutlierZPGraph->rescaleValueAxis(); colorOutlierZPGraph->setData(absPhot->qv_colorIndividualOutlier,absPhot->qv_ZPIndividualOutlier); } // Show LINEAR line fit to the color dependence /* QVector<QCPGraphData> dataFit(2); dataFit[0].key = xmin - 0.5; dataFit[1].key = xmax + 0.5; dataFit[0].value = absPhot->cutoff + absPhot->slope * dataFit[0].key; dataFit[1].value = absPhot->cutoff + absPhot->slope * dataFit[1].key; QCPGraph *fitGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); fitGraph->data()->set(dataFit); fitGraph->setSelectable(QCP::stNone); fitGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6)); fitGraph->setPen(QPen(QColor(Qt::black), 2)); */ // Show GSL fit to the color dependence QVector<QCPGraphData> dataFit; float step = (xmax - xmin + 2.*dx) / 100; // plot at 100 intervals for (int i=0; i<=100; ++i) { double xval = xmin - dx + i*step; double yval = 0.; for (int k=0; k<4; ++k) { // polynomial degree is hardcoded to three (higher order coeffs might be zero if a lower order was requested) yval += absPhot->fitParams[k]*pow(xval, double(k)); } QCPGraphData dataPoint(xval, yval); dataFit.append(dataPoint); } QCPGraph *fitGraph = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); fitGraph->data()->set(dataFit); fitGraph->setSelectable(QCP::stNone); // fitGraph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black), QBrush(Qt::white), 6)); fitGraph->setPen(QPen(QColor(Qt::red), 2)); // The graph for the color dependence (replot because of cluttering by the error bars) QCPGraph *colorZPGraph2 = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraph2->setSelectable(QCP::SelectionType::stMultipleDataRanges); colorZPGraph2->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#096169")), QBrush(QColor("#096169")), 6)); colorZPGraph2->setLineStyle(QCPGraph::lsNone); colorZPGraph2->rescaleKeyAxis(); colorZPGraph2->rescaleValueAxis(); colorZPGraph2->setData(absPhot->qv_colorIndividual,absPhot->qv_ZPIndividual); /* // The graph for manual outliers (if any) if (absPhot->num_ManualOutliers > 0) { QCPGraph *colorZPGraphManualOutlier = ui->zpPlot->addGraph(AxisRectColor->axis(QCPAxis::atBottom), AxisRectColor->axis(QCPAxis::atLeft)); colorZPGraphManualOutlier->setSelectable(QCP::SelectionType::stMultipleDataRanges); colorZPGraphManualOutlier->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(QColor("#ff0000")), QBrush(QColor("#ff0000")), 9)); colorZPGraphManualOutlier->setLineStyle(QCPGraph::lsNone); colorZPGraphManualOutlier->rescaleKeyAxis(); colorZPGraphManualOutlier->rescaleValueAxis(); colorZPGraphManualOutlier->setData(absPhot->qv_colorManualOutlier,absPhot->qv_ZPManualOutlier); // void AbsZeroPoint::showData(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) } */ // Place data points in the topmost layer // QCPLayer *zpLayer = aperZPGraph->layer(); // ui->zpPlot->moveLayer(zpLayer,ui->zpPlot->layer("main")); // QCPLayer *colorLayer = colorZPGraph->layer(); // colorLayer->setMode(QCPLayer::lmBuffered); ui->zpPlot->replot(); ui->zpPlot->update(); } void AbsZeroPoint::on_actionClose_triggered() { emit abszpClosed(); this->close(); } bool AbsZeroPoint::doColortermFit() { /* int fitOrder = ui->zpFitOrderSpinBox->value(); if (!absPhot->regression(fitOrder)) { QMessageBox::information( this, "Ill-constrainend fit", "There are not enough photometric reference stars to perform a fit of order "+QString::number(fitOrder), QMessageBox::Ok); return false; } */ absPhot->regressionLinfit(); return true; } void AbsZeroPoint::on_zpFitOrderSpinBox_valueChanged(int arg1) { if (performingStartup) return; // This slot is triggered by the GUI setp when data are still unavailable if (!doColortermFit()) return; ui->zpPlot->clearGraphs(); ui->zpPlot->clearItems(); ui->zpPlot->plotLayout()->clear(); plot(); updateCoaddHeader(); } void AbsZeroPoint::updateCoaddHeader() { absPhot->Color1Selected = QString::number(absPhot->fitParams[1], 'f', 4); absPhot->Color2Selected = QString::number(absPhot->fitParams[2], 'f', 4); absPhot->Color3Selected = QString::number(absPhot->fitParams[3], 'f', 4); absPhot->ColorErr1Selected = QString::number(absPhot->fitParamsErr[1], 'f', 4); absPhot->ColorErr2Selected = QString::number(absPhot->fitParamsErr[2], 'f', 4); absPhot->ColorErr3Selected = QString::number(absPhot->fitParamsErr[3], 'f', 4); float fluxConv = 0.0; if (!absPhot->ZPSelected.isEmpty()) { fluxConv = 1.e6 * pow(10, -0.4 * (absPhot->ZPSelected.toFloat() - 8.90)); // Converting ZP to microJy } // The coadded FITS file fitsfile *fptr; int status = 0; QString name = ui->zpImageLineEdit->text(); fits_open_file(&fptr, name.toUtf8().data(), READWRITE, &status); fits_update_key_flt(fptr, "ZPD", absPhot->ZPSelected.toFloat(), 6, "Photometric ZP in ZPD_FILT", &status); fits_update_key_flt(fptr, "ZPD_ERR", absPhot->ZPerrSelected.toFloat(), 6, "Error of ZPD", &status); fits_update_key_str(fptr, "ZPD_FILT", ui->zpFilterComboBox->currentText().toUtf8().data(), "Filter for ZPD", &status); fits_update_key_flt(fptr, "ZPD_APER", absPhot->Aperture.toFloat(), 6, "Aperture diameter [pixel]", &status); fits_update_key_flt(fptr, "ZPD_C1", absPhot->Color1Selected.toFloat(), 6, "Linear color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_C2", absPhot->Color2Selected.toFloat(), 6, "Quadratic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_C3", absPhot->Color3Selected.toFloat(), 6, "Cubic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER1", absPhot->ColorErr1Selected.toFloat(), 6, "Error linear color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER2", absPhot->ColorErr2Selected.toFloat(), 6, "Error quadratic color term in ZPD_SURV", &status); fits_update_key_flt(fptr, "ZPD_CER3", absPhot->ColorErr3Selected.toFloat(), 6, "Error cubic color term in ZPD_SURV", &status); fits_update_key_str(fptr, "ZPD_INDX", ui->zpColorComboBox->currentText().toUtf8().data(), "Color index in ZPD_SURV", &status); if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (converted from 2MASS VEGA mags)", &status); } else if (ui->zpRefcatComboBox->currentText().contains("UKIDSS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (converted from 2MASS UKIDSS mags)", &status); } else if (ui->zpRefcatComboBox->currentText().contains("APASS")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (B and V VEGA mags converted to AB)", &status); } else if (ui->zpRefcatComboBox->currentText().contains("GAIA")) { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Mag. system (Gaia mags converted to AB)", &status); } else { fits_update_key_str(fptr, "ZPD_SYST", "ABmag", "Magnitude system", &status); } fits_update_key_str(fptr, "ZPD_SURV", ui->zpRefcatComboBox->currentText().toUtf8().data(), "Survey and filter system", &status); fits_update_key_flt(fptr, "FLUXCONV", fluxConv, 6, "Factor to convert image to microJansky", &status); fits_close_file(fptr, &status); ui->zpHeaderLabel->setText("FITS header entries were updated:"); ui->zpPlainTextEdit->clear(); if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); QString code = errorCodes->errorKeyMap.value(status); ui->zpPlainTextEdit->appendHtml("<font color=\"#ee0000\">Cfitsio error while updating header: " + code + "</font>"); } QFont notoFontMono("Noto Sans Mono CJK JP", 8, QFont::Normal); ui->zpPlainTextEdit->setFont(notoFontMono); ui->zpPlainTextEdit->appendHtml("<tt>ZPD&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= "+absPhot->ZPSelected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_ERR&nbsp;= "+absPhot->ZPerrSelected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_FILT= '"+ui->zpFilterComboBox->currentText()+"'</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_APER= "+absPhot->Aperture+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_C1&nbsp;&nbsp;= "+absPhot->Color1Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_C2&nbsp;&nbsp;= "+absPhot->Color2Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_C3&nbsp;&nbsp;= "+absPhot->Color3Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_CER1= "+absPhot->ColorErr1Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_CER2= "+absPhot->ColorErr2Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_CER3= "+absPhot->ColorErr3Selected+"</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>ZPD_INDX= '"+ui->zpColorComboBox->currentText()+"'</tt>"); // CHECK: everytime we add new reference catalogs if (ui->zpRefcatComboBox->currentText().contains("2MASS")) { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag' (converted from 2MASS VEGA mags)</tt>"); } else if (ui->zpRefcatComboBox->currentText().contains("UKIDSS")) { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag' (converted from UKIDSS VEGA mags)</tt>"); } else if (ui->zpRefcatComboBox->currentText().contains("APASS")) { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag' (B and V VEGA mags converted to AB mag)</tt>"); } else if (ui->zpRefcatComboBox->currentText().contains("GAIA")) { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag' (Gaia mags converted to AB mag)</tt>"); } else if (ui->zpRefcatComboBox->currentText().contains("VHS")) { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag' (converted from VEGA mags)</tt>"); } else { ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SYST= 'ABmag'</tt>"); } ui->zpPlainTextEdit->appendHtml("<tt>ZPD_SURV= '"+ui->zpRefcatComboBox->currentText()+"'</tt>"); ui->zpPlainTextEdit->appendHtml("<tt>FLUXCONV= "+QString::number(fluxConv, 'f', 4)+" (conversion factor to microJy)</tt>"); } void AbsZeroPoint::on_closePushButton_clicked() { emit abszpClosed(); this->close(); } void AbsZeroPoint::on_showAbsphotPushButton_clicked() { // TODO: show sources that are kept after the fit in yet another color if (!iViewOpen) { iView = new IView("FITSmonochrome", ui->zpImageLineEdit->text(), this); connect(iView, &IView::closed, this, &AbsZeroPoint::iViewClosed); connect(this, &AbsZeroPoint::updateAbsPhotPlot, iView, &IView::showAbsPhotReferences); iView->show(); iView->AbsPhotReferencePathName = myImage->path; iView->showAbsPhotReferences(true); iViewOpen = true; } else { iView->show(); iView->AbsPhotReferencePathName = myImage->path; emit updateAbsPhotPlot(true); } } void AbsZeroPoint::iViewClosed() { iViewOpen = false; }
54,001
C++
.cc
1,132
41.263251
215
0.662778
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,434
absphot.cc
schirmermischa_THELI/src/abszp/absphot.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "absphot.h" #include "../functions.h" #include "../instrumentdata.h" #include <gsl/gsl_multifit.h> #include <QDebug> #include <QMessageBox> AbsPhot::AbsPhot() { } void AbsPhot::clear() { qv_ZP.clear(); qv_mag1ref.clear(); qv_mag2ref.clear(); qv_mag1errref.clear(); qv_mag2errref.clear(); qv_colorIndividual.clear(); qv_colorErrIndividual.clear(); qv_ZPIndividual.clear(); qv_ZPerrIndividual.clear(); qv_colorIndividualOutlier.clear(); qv_ZPIndividualOutlier.clear(); qv_colorManualOutlier.clear(); qv_ZPManualOutlier.clear(); qv_magauto.clear(); qv_magerrauto.clear(); qv_magaper.clear(); qv_magerraper.clear(); qv_apertures.clear(); qv_fitMask.clear(); qv_fitMask_old.clear(); qv_ManualMask.clear(); qv_ManualMask_old.clear(); filter = ""; colorfilter = ""; color = ""; initialized = false; numAper = 0; numObj = 0; ZPauto = 0.; ZPautoerr = 0.; ZPSelected = ""; ZPerrSelected = ""; Color1Selected = ""; Color2Selected = ""; Color3Selected = ""; } void AbsPhot::getColor() { QString filter1 = color.split("-").at(0); QString filter2 = color.split("-").at(1); qv_colorIndividual.clear(); qv_colorErrIndividual.clear(); qv_ZPIndividual.clear(); for (int i=0; i<numObj; ++i) { if (filter1 == filter) qv_colorIndividual.append(qv_mag1ref[i] - qv_mag2ref[i]); else if (filter2 == filter) qv_colorIndividual.append(qv_mag2ref[i] - qv_mag1ref[i]); else { qDebug() << "AbsPhot::getColor(): Error, this should not happen."; break; } qv_colorErrIndividual.append(sqrt(qv_mag1errref[i]*qv_mag1errref[i] + qv_mag2errref[i]*qv_mag2errref[i])); qv_ZPerrIndividual.append(sqrt(qv_mag1errref[i]*qv_mag1errref[i] + qv_magerrauto[i]*qv_magerrauto[i])); qv_ZPIndividual.append(qv_mag1ref[i] - qv_magauto[i]); } } void AbsPhot::getZP() { qv_ZP.clear(); qv_ZPerr.clear(); // Calculate the ZP for each MAG_APER QVector<double> dummyZPaper; for (int i=0; i<numAper; ++i) { for (int j=0; j<numObj; ++j) { // include color term correction dummyZPaper.append(qv_mag1ref[j] - qv_magaper[j][i] - slope*qv_colorIndividual[j]); } double tmp_mederr = medianerrMask(dummyZPaper, qv_fitMask); // Add (roughly) error contribution from individual sources if (numObj > 0) { double tmperr = rmsMask_T(qv_ZPerrIndividual, qv_fitMask) / sqrt(numObj); tmp_mederr = sqrt(tmp_mederr*tmp_mederr + tmperr*tmperr); } qv_ZP.append(medianMask_T(dummyZPaper, qv_fitMask)); qv_ZPerr.append(tmp_mederr); dummyZPaper.clear(); } // Calculate the ZP for MAG_AUTO QVector<double> dummyZPauto; for (int j=0; j<numObj; ++j) { dummyZPauto.append(qv_mag1ref[j] - qv_magauto[j] - slope*qv_colorIndividual[j]); } ZPauto = medianMask_T(dummyZPauto, qv_fitMask); ZPautoerr = medianerrMask(dummyZPauto, qv_fitMask); // Add (roughly) error contribution from individual sources if (numObj > 0) { double tmperr = rmsMask_T(qv_ZPerrIndividual, qv_fitMask) / sqrt(numObj); ZPautoerr = sqrt(ZPautoerr*ZPautoerr + tmperr*tmperr); } } long AbsPhot::setupFitMask() { // Initially, allow all objects to enter the fit; // Also initializes qv_fitMask for the first time; qv_fitMask.fill(false, numObj); qv_fitMask_old.fill(false, numObj); // Exclude objects which have been manually rejected long count = 0; for (long i=0; i<numObj; ++i) { if (qv_ManualMask[i]) { qv_fitMask[i] = true; qv_fitMask_old[i] = true; } else ++count; } return count; // the number of good data points that will enter the fit } // Iterative regression void AbsPhot::regressionLinfit() { int iter_count = 0; int iter_max = 10; // Initialize object masks for fitting setupFitMask(); // Iterative straight line fit while (iter_count <= iter_max) { double sum_col_ZP = 0.; double sum_col_col = 0.; double meanColor = meanMask_T(qv_colorIndividual, qv_fitMask); double meanZP = meanMask_T(qv_ZPIndividual, qv_fitMask); // Calculate the regression coefficients for (long i=0; i<numObj; ++i) { if (!qv_fitMask[i]) { sum_col_ZP += (qv_colorIndividual[i] - meanColor) * (qv_ZPIndividual[i] - meanZP); sum_col_col += (qv_colorIndividual[i] - meanColor) * (qv_colorIndividual[i] - meanColor); } } slope = sum_col_ZP / sum_col_col; cutoff = meanZP - slope * meanColor; // Check for 2.5 sigma outliers double kappa = 2.5; // Residuals QVector<double> residuals = QVector<double>(); for (long i=0; i<numObj; ++i) { double fitval = slope * qv_colorIndividual[i] + cutoff; double diff = qv_ZPIndividual[i] - fitval; residuals.append(diff); } // Outlier? Set flag if yes double rmsval = rmsMask_T(residuals, qv_fitMask); for (long i=0; i<numObj; ++i) { if (fabs(residuals[i]) > kappa*rmsval) qv_fitMask[i] = true; else qv_fitMask[i] = false; } // Compare with previous flag set int check = 1; for (long i=0; i<numObj; ++i) { if (qv_fitMask[i] != qv_fitMask_old[i]) check *= 0; } if (check == 1) break; // converged else { // Update "previous" flag set for (long i=0; i<numObj; ++i) { qv_fitMask_old[i] = qv_fitMask[i]; } } // However, exclude objects which have been manually rejected for (int i=0; i<numObj; ++i) { if (qv_ManualMask[i]) { qv_fitMask[i] = true; qv_fitMask_old[i] = true; } } iter_count++; } // count outliers num_outliers = 0; for (long i=0; i<numObj; ++i) { if (qv_fitMask[i]) { num_outliers++; qv_colorIndividualOutlier.append(qv_colorIndividual[i]); qv_ZPIndividualOutlier.append(qv_ZPIndividual[i]); } } qv_colorManualOutlier.clear(); qv_ZPManualOutlier.clear(); num_ManualOutliers = 0; for (long i=0; i<numObj; ++i) { if (qv_ManualMask[i]) { num_ManualOutliers++; qv_colorManualOutlier.append(qv_colorIndividual[i]); qv_ZPManualOutlier.append(qv_ZPIndividual[i]); } } // Store the result, after resetting all parameters (un-used params for a lower order fit are explicitly set to 0) fitParams[0] = cutoff; fitParams[1] = slope; fitParamsErr[0] = 0.; fitParamsErr[1] = 0.; } bool AbsPhot::regression(int fitOrder) { // Initialize object masks for fitting long n = setupFitMask(); // Reset the solution for (auto &it : fitParams) it = 0.; for (auto &it : fitParamsErr) it = 0.; int p = fitOrder + 1; if (n <= p) return false; gsl_matrix *X, *cov; gsl_vector *y, *w, *c, *yerr, *w_orig, *r; X = gsl_matrix_alloc(n, p); // input y = gsl_vector_alloc(n); // input yerr = gsl_vector_alloc(n); // input w = gsl_vector_alloc(n); // input w_orig = gsl_vector_alloc(n); // input r = gsl_vector_alloc(n); // input c = gsl_vector_alloc(p); // output cov = gsl_matrix_alloc(p, p); // output long i = 0; for (auto &mask : qv_fitMask) { // add data points and (total) errors if not masked by the user if (!mask) { float xi = qv_colorIndividual[i]; float yi = qv_ZPIndividual[i]; float xierr = qv_colorErrIndividual[i]; float yierr = qv_ZPerrIndividual[i]; float ei = sqrt(xierr*xierr + yierr*yierr); for (int k=0; k<=fitOrder; ++k) { gsl_matrix_set(X, i, k, pow(xi, double(k))); } gsl_vector_set(y, i, yi); gsl_vector_set(yerr, i, yierr); gsl_vector_set(w, i, 1./(ei*ei)); gsl_vector_set(w_orig, i, 1./(ei*ei)); ++i; } } double chisq; gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc (n, p); // iterative fit int iter = 0; int iterMax = 3; while (iter < iterMax) { gsl_multifit_wlinear(X, w, y, c, cov, &chisq, work); gsl_multifit_linear_residuals(X, y, c, r); // Reset the weights to the original weights for (size_t i=0; i<r->size; ++i) { gsl_vector_set(w, i, gsl_vector_get(w_orig, i)); } // 3 sigma outlier rejection (setting the weights to zero for the next fit) for (size_t i=0; i<r->size; ++i) { if (gsl_vector_get(r, i) > 3.*gsl_vector_get(yerr, i)) { gsl_vector_set(w, i, 0.); } } ++iter; } gsl_multifit_linear_free(work); // Store the result, after resetting all parameters (un-used params for a lower order fit are explicitly set to 0) for (int k=0; k<p; ++k) { fitParams[k] = gsl_vector_get(c,(k)); fitParamsErr[k] = sqrt(gsl_matrix_get(cov,(k),(k))); } gsl_matrix_free(X); gsl_vector_free(y); gsl_vector_free(w); gsl_vector_free(c); gsl_matrix_free(cov); return true; }
10,213
C++
.cc
285
28.838596
118
0.599535
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,435
errordialog.cc
schirmermischa_THELI/src/processingExternal/errordialog.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "errordialog.h" #include "ui_errordialog.h" #include "../functions.h" #include "../preferences.h" #include <QSysInfo> #include <QDebug> #include <QSettings> #include <QMessageBox> ErrorDialog::ErrorDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ErrorDialog) { ui->setupUi(this); // connect(ui->errorShowPushButton, &QPushButton::clicked, this, &ErrorDialog::openLogfile); readSettings(); } ErrorDialog::~ErrorDialog() { delete ui; } void ErrorDialog::update(){ ui->errorCodeLabel->setText(code); ui->errorFoundLabel->setText("An error was found in this logfile (line "+line+"):"); ui->errorExplanationTextEdit->setText(explanation); ui->errorSuggestionsTextEdit->setText(suggestion); ui->errorLogfileLineEdit->setText(logname); } void ErrorDialog::getErrorLine(QString code) { QStringList list = code.split(" "); if (list.length() >=3 ) { line = list.at(2); line.remove("):"); } else { line = "<Unknown>"; } } int ErrorDialog::readSettings() { QSettings settings("THELI", "PREFERENCES"); editorPreference = settings.value("prefEditorComboBox").toString(); return settings.status(); } void ErrorDialog::on_errorShowPushButton_clicked() { showLogfile(logname, line); } void ErrorDialog::translate() { // Typically, the errormessage string looks like this: // "Error (line 3743): performing run processing" // Split it by the first colon, then simplify the string thereafter // Remove everything up to and including the colon: int colonindex = code.indexOf(":"); code = code.remove(0,colonindex+1); code = code.simplified(); if (code == "Illegal instruction") { explanation = "This is an error that mostly occurs in 'scamp' during astrometry."; suggestion = "The cause for this is not known. " "Try using a denser / less dense reference catalog, adjust the object detection thresholds, and/or the scamp parameters."; } // Uncomment the following for testing purposes /* else if (code == "GUIVERSION !") { explanation = "Dummy"; suggestion = "Dummy"; } */ else if (code == "inaccuracies likely to occur") { explanation = "This warning occurs during astrometry or coaddition. It always implies a bad astrometric solution, " "which may or may not be immediately visible in your coadded image."; suggestion = "You should rerun the astrometry, trying to achieve a better solution. " "Review the checkplots in the \"plots/\" directory carefully. Were the images correctly " "identified on the sky? (fgroups_1.png)"; } else if (code == "WARNING: Not enough matched detections in ") { explanation = "This error occurs during astrometry with scamp. " "It means that for or more detectors no matches were found with the reference catalog, " "which should be immediately visible in plots/fgroups_1.png .\n" "The three most common reasons are\n" "(1) The reference catalog and the source catalog do not share sufficiently many sources\n" "(2) The true astrometric solution is outside the search space defined by the scamp parameters\n" "(3) The scamp parameters insufficiently constrain the solution space (too many false positives).\n"; suggestion = "(1) Review the checkplots. Are most images off or just a single one (which?)\n" "(2) If in a low density field, decrease the source detection thresholds for the object catalogs " " and increase the magnitude for the reference catalog to get more sources." "(3) If still unsuccessful, load the reference catalog ($HOME/.theli/scripts/theli_mystd.[skycat | reg] " " over one of your images, and see if you can match it by eye. How large are the offsets / rotations? " " Adjust POSITION_MAXERR and POSANGLE_MAXERR accordingly.\n" "(4) Reference catalog and matching parameters look fine, but still no success? " " Load the source detections (SCIENCE/cat/[ds9cat | skycat]/ over your image. " " Can you match them with the reference catalog?\n" "(5) Try the astrometry.net implementation in THELI.\n" "(1-4) should solve most problems. Think out of the box, e.g if you observe in K-band in a molecular " " cloud you'll have plenty of detetcions, but optical reference catalogs won't show anything. " " Use 2MASS instead. Or, all reference sources are badly saturated in your images and rejected " " from your source catalogs. Use deeper reference catalogs, or adjust the detection flags. " "(5) There are other cases though which are harder to crack, e.g. wide-angle fish-eye exposures, " " MCAO, etc, and there is no off-the-shelf answer what to do."; } else if (code == " 0 astrometric references loaded from theli_mystd.scamp") { explanation = "scamp does not find reference sources in the downloaded online catalog."; suggestion = "Did you download the reference catalog for the correct sky position? " "It could also be that you have one or more stray images from a different pointing in your data set, " "and that results in the reference catalog being downloaded in an area somewhere 'in between' the two " "pointings, resulting in no actual overlap with either position."; } else if (code == "WARNING: Significant inaccuracy likely to occur in projection") { explanation = "This warning occurs during coaddition. It always implies a bad astrometric solution, " "which may or may not be immediately visible in your coadded image."; suggestion = "You must rerun the astrometry and try to achieve a better solution. " "Review the checkplots in the \"plots/\" directory carefully. Were the images correctly " "identified on the sky? (fgroups_1.png)"; } else if (code == "WARNING: Null or negative global weighting factor") { explanation = "This occurs during coaddition and means that the (manually provided) " "reference coordinates do not (by a large amount) overlap with the actual pointing of your data."; suggestion = "Check the manually provided reference coordinates."; } else if (code == "fatal: division by zero attempted") { explanation = "Happens during astrometry, in case one or more images have no or very few sources. " "It could also be that there is an error with one of the download servers for the reference catalog."; suggestion = "Lower your detection thresholds. Check your images for bad ones (clouds, focus, etc). " "Try a different reference catalog or download server (under Edit->Preferences) if the problem occurs at this step."; } else if (code == "no match with reference catalog !") { explanation = "scamp does not find matching sources in the reference catalog."; suggestion = "Did you download the reference catalog for the correct sky position? " "It could also be that you have one or more stray images from a different pointing in your data set, " "and that results in the reference catalog being downloaded in an area somewhere 'in between' the two " "pointings, resulting in no actual overlap with either position.\n" "Other things to check:\n" "(1) The reference catalog and the source catalog do not share sufficiently many sources,\n" "(2) The true astrometric solution is outside the search space defined by the scamp parameters,\n" "(3) The scamp parameters insufficiently constrain the solution space (too many false positives)."; suggestion = "(1) Review the checkplots. Are most images off or just a single one (which?)\n" "(2) If in a low density field, decrease the source detection thresholds for the object catalogs " " and increase the magnitude for the reference catalog to get more sources.\n" "(3) If still unsuccessful, load the reference catalog ($HOME/.theli/scripts/theli_mystd.[skycat | reg] " " over one of your images, and see if you can match it by eye. How large are the offsets / rotations? " " Adjust POSITION_MAXERR and POSANGLE_MAXERR accordingly.\n" "(4) Reference catalog and matching parameters look fine, but still no success? " " Load the source detections (SCIENCE/cat/[ds9cat | skycat]/ over your image. " " Can you match them with the reference catalog?" "(5) Try the astrometry.net implementation in THELI.\n" "(1-4) should solve most problems. Think out of the box, e.g if you observe in K-band in a molecular " " cloud you'll have plenty of detetcions, but optical reference catalogs won't show anything. " " Use 2MASS instead. Or, all reference sources are badly saturated in your images and rejected " " from your source catalogs. Use deeper reference catalogs, or adjust the detection flags.\n" "(5) There are other cases though which are harder to crack, e.g. wide-angle fish-eye exposures, " " MCAO, etc, and there is no off-the-shelf answer what to do."; } else if (code == "Not enough memory") { explanation = "This happens either during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two. " "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "buffer overflow detected") { explanation = "This happens either during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two. " "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "did not solve") { explanation = "This error occurs when astrometry.net cannot find a solution."; suggestion = "Try running the astrometry with scamp, where you have much more control."; } else if (code == "(core dumped)") { explanation = "This is a very uncommon error implying some memory corruption."; suggestion = "If it happens during coaddition, check plate scale " "and manually provided reference coordinates."; } else if (code == "has flux scale = 0: I will take 1 instead") { explanation = "This happens during coaddition and implies a wrong / incomplete astrometric solution."; suggestion = "Check the logfile to see which image is causing the problem. Perhaps the image is bad " "and could not be solved completely during astrometry."; } else if (code == "Could not allocate memory") { explanation = "This happens most likely during astrometry or coaddition."; suggestion = "If in astrometry, try reducing the number of CPUs by a factor of two.\n" "Check the memory usage using 'top' on the command line. If doing a coaddition, are you " "creating a huge mosaic? Perhaps you have entered the wrong plate scale?"; } else if (code == "ERROR: No photometric reference sources retrieved!") { explanation = "This occurs when determining an absolute photometric zeropoint."; suggestion = "Is the WCS in your image good? Is the network connection working? " "If you used a catalog that does not have full sky coverage (e.g. SDSS, PANSTARRS), then " "this message indicates that your field is probably not covered by that catalog."; } else if (code == "ERROR: Could not find file with blank sky positions") { explanation = "The positions where the sky estimates are taken was not found."; suggestion = "If you requested a polynomial fit, then you must define blank sky positions. " "This message will also be shown if you requested a constant sky subtraction, " "with the empty sky regions set to 'Specific sky area(s)' instead of a whole chip. " "If you want to use specific areas, use the THELI internal FITS viewer to create a file with empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: File with blank sky positions") { explanation = "The file with empty sky positions does not contain any entries."; suggestion = "Use the THELI internal FITS viewer to create a file with empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: Less than 3 sky positions were located in the images.") { explanation = "The sky polynomial fit is underconstrained. More sky positions are required."; suggestion = "Use the THELI internal FITS viewer to create a file with sufficiently many empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "ERROR: Insufficient number of sky positions for a model of degree") { explanation = "The sky polynomial fit is underconstrained. More sky positions are required."; suggestion = "Use the THELI internal FITS viewer to create a file with sufficiently many empty sky positions. " "Load an astrometrically calibrated image, and define areas using middle-click drags on the image. " "The file will be automatically created and updated on the fly in the SCIENCE directory."; } else if (code == "Did not create any quads") { explanation = "astrometry.net did not create any quads, which are used for pattern matching between source and reference catalog"; suggestion = "This can happen if the source density is very low. Try using a different reference catalog."; } else if (code == "solve-field: invalid option --") { explanation = "The syntax of astrometry.net has changed."; suggestion = "THELI is not using the correct syntax for astrometry.net. Please send the logfile to schirmer@mpia.de ."; } } void ErrorDialog::on_errorLogfileLineEdit_textChanged(const QString &arg1) { paintPathLineEdit(ui->errorLogfileLineEdit, arg1, "file"); }
16,508
C++
.cc
245
56.946939
143
0.660266
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,436
monitor.cc
schirmermischa_THELI/src/dockwidgets/monitor.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "monitor.h" #include "ui_monitor.h" #include "functions.h" #include <QString> #include <QDebug> Monitor::Monitor(QWidget *parent) : QDockWidget(parent), ui(new Ui::Monitor) { ui->setupUi(this); } Monitor::~Monitor() { delete ui; } void Monitor::displayMessage(QString text, QString type) { mutex.lock(); message(ui->monitorPlainTextEdit, text, type); mutex.unlock(); } void Monitor::appendOK() { ui->monitorPlainTextEdit->moveCursor(QTextCursor::End); ui->monitorPlainTextEdit->insertPlainText(" OK"); ui->monitorPlainTextEdit->moveCursor(QTextCursor::End); }
1,292
C++
.cc
41
29.292683
75
0.771152
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,437
defaults.cc
schirmermischa_THELI/src/dockwidgets/defaults.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include "mainwindow.h" #include "ui_mainwindow.h" void ConfDockWidget::populateDefaultMap() { // These are the defaults that will be used if an empty parameter field // would be passed onto the scripts // Only LineEdits defaultMap.insert("APDmaxphoterrorLineEdit", "0.05"); defaultMap.insert("APIWCSLineEdit", "10"); defaultMap.insert("APIapertureLineEdit", "10"); defaultMap.insert("APIcolortermLineEdit", "0.0"); defaultMap.insert("APIconvergenceLineEdit", "0.01"); defaultMap.insert("APIextinctionLineEdit", "-0.1"); defaultMap.insert("APIfilterkeywordLineEdit", ""); defaultMap.insert("APIkappaLineEdit", "2.0"); defaultMap.insert("APIminmagLineEdit", "0"); defaultMap.insert("APIthresholdLineEdit", "0.15"); defaultMap.insert("APIzpmaxLineEdit", ""); defaultMap.insert("APIzpminLineEdit", ""); defaultMap.insert("ARCdecLineEdit", ""); defaultMap.insert("ARCmaxpmLineEdit", ""); defaultMap.insert("ARCminmagLineEdit", "25"); defaultMap.insert("ARCraLineEdit", ""); defaultMap.insert("ARCradiusLineEdit", ""); defaultMap.insert("ARCmaxpmLineEdit", ""); defaultMap.insert("ARCpmRALineEdit",""); defaultMap.insert("ARCpmDECLineEdit",""); defaultMap.insert("ASTanetpixscaleLineEdit", "1.05"); defaultMap.insert("ASTastrefweightLineEdit", "1.0"); defaultMap.insert("ASTastrinstrukeyLineEdit", "FILTER"); defaultMap.insert("ASTcrossidLineEdit", "1.0"); defaultMap.insert("ASTdistortLineEdit", "3"); defaultMap.insert("ASTdistortgroupsLineEdit", ""); defaultMap.insert("ASTdistortkeysLineEdit", ""); defaultMap.insert("ASTfgroupLineEdit", "1.0"); defaultMap.insert("ASTphotinstrukeyLineEdit", "FILTER"); defaultMap.insert("ASTpixscaleLineEdit", "1.05"); defaultMap.insert("ASTposangleLineEdit", "2"); defaultMap.insert("ASTpositionLineEdit", "2.0"); defaultMap.insert("ASTresolutionLineEdit", "800"); defaultMap.insert("ASTsnthreshLineEdit", "5,20"); defaultMap.insert("BAC1nhighLineEdit", "0"); defaultMap.insert("BAC1nlowLineEdit", "0"); defaultMap.insert("BAC2nhighLineEdit", "0"); defaultMap.insert("BAC2nlowLineEdit", "0"); defaultMap.insert("BACDMINLineEdit", ""); defaultMap.insert("BACDTLineEdit", ""); defaultMap.insert("BACbacksmoothscaleLineEdit", ""); defaultMap.insert("BACdistLineEdit", ""); defaultMap.insert("BACfringesmoothscaleLineEdit", ""); defaultMap.insert("BACgapsizeLineEdit", ""); defaultMap.insert("BACmagLineEdit", ""); defaultMap.insert("BACmefLineEdit", ""); defaultMap.insert("BACwindowLineEdit", "0"); defaultMap.insert("BACminWindowLineEdit", ""); defaultMap.insert("CGWbackclustolLineEdit", ""); defaultMap.insert("CGWbackcoltolLineEdit", ""); defaultMap.insert("CGWbackmaxLineEdit", ""); defaultMap.insert("CGWbackminLineEdit", ""); defaultMap.insert("CGWbackrowtolLineEdit", ""); defaultMap.insert("CGWbacksmoothLineEdit", ""); defaultMap.insert("CGWdarkmaxLineEdit", ""); defaultMap.insert("CGWdarkminLineEdit", ""); defaultMap.insert("CGWflatclustolLineEdit", ""); defaultMap.insert("CGWflatcoltolLineEdit", ""); defaultMap.insert("CGWflatmaxLineEdit", "1.5"); defaultMap.insert("CGWflatminLineEdit", "0.5"); defaultMap.insert("CGWflatrowtolLineEdit", ""); defaultMap.insert("CGWflatsmoothLineEdit", ""); defaultMap.insert("CIWbloomRangeLineEdit", ""); defaultMap.insert("CIWbloomMinaduLineEdit", ""); defaultMap.insert("CIWbloomMinareaLineEdit", ""); defaultMap.insert("CIWaggressivenessLineEdit", ""); defaultMap.insert("CIWmaxaduLineEdit", ""); defaultMap.insert("CIWminaduLineEdit", ""); defaultMap.insert("COAchipsLineEdit", ""); defaultMap.insert("COAdecLineEdit", ""); defaultMap.insert("COAedgesmoothingLineEdit", ""); defaultMap.insert("COAmaxseeingLineEdit", ""); defaultMap.insert("COAminrzpLineEdit", ""); defaultMap.insert("COAoutborderLineEdit", ""); defaultMap.insert("COAoutsizeLineEdit", "4"); defaultMap.insert("COAoutthreshLineEdit", "3"); defaultMap.insert("COApmdecLineEdit", ""); defaultMap.insert("COApmraLineEdit", ""); defaultMap.insert("COAraLineEdit", ""); defaultMap.insert("COAsizexLineEdit", ""); defaultMap.insert("COAsizeyLineEdit", ""); defaultMap.insert("COAskypaLineEdit", ""); defaultMap.insert("COAuniqueidLineEdit", ""); defaultMap.insert("COCDMINLineEdit", "5"); defaultMap.insert("COCDTLineEdit", "1.5"); defaultMap.insert("COCmefLineEdit", ""); defaultMap.insert("COCrejectLineEdit", "1.5"); defaultMap.insert("COCxmaxLineEdit", ""); defaultMap.insert("COCxminLineEdit", ""); defaultMap.insert("COCymaxLineEdit", ""); defaultMap.insert("COCyminLineEdit", ""); defaultMap.insert("CSCDMINLineEdit", "5"); defaultMap.insert("CSCDTLineEdit", "5"); defaultMap.insert("CSCFWHMLineEdit", "1.5"); defaultMap.insert("CSCbackgroundLineEdit", ""); defaultMap.insert("CSCmaxflagLineEdit", "8"); defaultMap.insert("CSCmincontLineEdit", "0.0005"); defaultMap.insert("CSCminobjectsLineEdit", ""); defaultMap.insert("CSCsaturationLineEdit", "1.e8"); defaultMap.insert("CSCrejectExposureLineEdit", ""); defaultMap.insert("SPSlengthLineEdit", "10"); defaultMap.insert("SPSnumbergroupsLineEdit", "3"); defaultMap.insert("biasMaxLineEdit", ""); defaultMap.insert("biasMinLineEdit", ""); defaultMap.insert("biasNhighLineEdit", ""); defaultMap.insert("biasNlowLineEdit", ""); defaultMap.insert("darkMaxLineEdit", ""); defaultMap.insert("darkMinLineEdit", ""); defaultMap.insert("darkNhighLineEdit", ""); defaultMap.insert("darkNlowLineEdit", ""); defaultMap.insert("flatMaxLineEdit", ""); defaultMap.insert("flatMinLineEdit", ""); defaultMap.insert("flatNhighLineEdit", ""); defaultMap.insert("flatNlowLineEdit", ""); defaultMap.insert("flatoffMaxLineEdit", ""); defaultMap.insert("flatoffMinLineEdit", ""); defaultMap.insert("flatoffNhighLineEdit", ""); defaultMap.insert("flatoffNlowLineEdit", ""); defaultMap.insert("normalxtalkAmplitudeLineEdit", "0.0"); defaultMap.insert("overscanNhighLineEdit", ""); defaultMap.insert("overscanNlowLineEdit", ""); defaultMap.insert("rowxtalkAmplitudeLineEdit", "0.0"); defaultMap.insert("saturationLineEdit", ""); defaultMap.insert("separateTargetLineEdit", ""); defaultMap.insert("skyDMINLineEdit", "10"); defaultMap.insert("skyDTLineEdit", "1.5"); defaultMap.insert("skyKernelLineEdit", "256"); defaultMap.insert("skyMefLineEdit", ""); defaultMap.insert("skyOverrideLineEdit", ""); defaultMap.insert("skyVertex1LineEdit", ""); defaultMap.insert("skyVertex2LineEdit", ""); defaultMap.insert("skyVertex3LineEdit", ""); defaultMap.insert("skyVertex4LineEdit", ""); } void ConfDockWidget::loadDefaults() { // qDebug() << "loading" << sender(); if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0) { /* ui->setupMainLineEdit->clear(); ui->setupBiasLineEdit->clear(); ui->setupDarkLineEdit->clear(); ui->setupFlatLineEdit->clear(); ui->setupFlatoffLineEdit->clear(); ui->setupScienceLineEdit->clear(); ui->setupSkyLineEdit->clear(); ui->setupStandardLineEdit->clear(); */ // TODO: why do we need this again? for (auto &it: mainGUI->status.listCheckBox) { it->setChecked(false); } mainGUI->ui->plainTextEdit->clear(); } // TODO: use default map! if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 0)) { ui->xtalk_nor_2x2ToolButton->setChecked(true); ui->xtalk_row_2x2ToolButton->setChecked(true); ui->normalxtalkCheckBox->setChecked(false); ui->rowxtalkCheckBox->setChecked(false); ui->normalxtalkAmplitudeLineEdit->setText(""); ui->rowxtalkAmplitudeLineEdit->setText(""); ui->overscanCheckBox->setChecked(true); ui->theliRenamingCheckBox->setChecked(true); ui->nonlinearityCheckBox->setChecked(false); ui->nonlinearityCheckBox->setChecked(false); ui->splitMIRcubeCheckBox->setChecked(false); ui->biasNlowLineEdit->setText(""); ui->biasNhighLineEdit->setText(""); ui->darkNlowLineEdit->setText(""); ui->darkNhighLineEdit->setText(""); ui->excludeDetectorsLineEdit->clear(); ui->flatoffNlowLineEdit->setText(""); ui->flatoffNhighLineEdit->setText(""); ui->flatNlowLineEdit->setText(""); ui->flatNhighLineEdit->setText(""); ui->biasMinLineEdit->clear(); ui->biasMaxLineEdit->clear(); ui->darkMinLineEdit->clear(); ui->darkMaxLineEdit->clear(); ui->flatoffMinLineEdit->clear(); ui->flatoffMaxLineEdit->clear(); ui->flatMinLineEdit->clear(); ui->flatMaxLineEdit->clear(); ui->saturationLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 1)) { // qDebug() << "background"; ui->SPSnumbergroupsLineEdit->clear(); ui->SPSlengthLineEdit->clear(); ui->chopnodComboBox->setCurrentIndex(0); ui->chopnodInvertCheckBox->setChecked(false); ui->BAC1nhighLineEdit->setText("0"); ui->BAC1nlowLineEdit->setText("0"); ui->BAC2nhighLineEdit->setText("0"); ui->BAC2nlowLineEdit->setText("0"); ui->BAC2passCheckBox->setChecked(true); ui->BACDMINLineEdit->setText("5"); ui->BACDTLineEdit->setText("1.5"); ui->BACapplyComboBox->setCurrentIndex(0); ui->BACbacksmoothscaleLineEdit->clear(); ui->BACconvolutionCheckBox->setChecked(false); ui->BACdistLineEdit->clear(); ui->BACgapsizeLineEdit->clear(); ui->BACmagLineEdit->clear(); ui->BACmefLineEdit->clear(); ui->BACmethodComboBox->setCurrentIndex(0); ui->BACrescaleCheckBox->setChecked(true); ui->BACwindowLineEdit->setText("0"); ui->BACminWindowLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 2)) { ui->COCDMINLineEdit->setText("5"); ui->COCDTLineEdit->setText("1.5"); ui->COCdirectionComboBox->setCurrentIndex(0); ui->COCmefLineEdit->clear(); ui->COCrejectLineEdit->setText("1.5"); ui->COCxmaxLineEdit->clear(); ui->COCxminLineEdit->clear(); ui->COCymaxLineEdit->clear(); ui->COCyminLineEdit->clear(); ui->BIPSpinBox->setValue(1); ui->BIPrejectCheckBox->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 3)) { ui->CGWbackclustolLineEdit->clear(); ui->CGWbackcoltolLineEdit->clear(); ui->CGWbackrowtolLineEdit->clear(); ui->CGWbacksmoothLineEdit->clear(); ui->CGWbackmaxLineEdit->clear(); ui->CGWbackminLineEdit->clear(); ui->CGWdarkmaxLineEdit->clear(); ui->CGWdarkminLineEdit->clear(); ui->CGWflatclustolLineEdit->clear(); ui->CGWflatcoltolLineEdit->clear(); ui->CGWflatmaxLineEdit->setText("1.5"); ui->CGWflatminLineEdit->setText("0.5"); ui->CGWflatrowtolLineEdit->clear(); ui->CGWflatsmoothLineEdit->clear(); ui->CGWsameweightCheckBox->setChecked(false); ui->CIWbloomRangeLineEdit->clear(); ui->CIWbloomMinaduLineEdit->clear(); ui->CIWaggressivenessLineEdit->clear(); ui->CIWmaskbloomingCheckBox->setChecked(false); ui->CIWmaxaduLineEdit->clear(); ui->CIWminaduLineEdit->clear(); ui->separateTargetLineEdit->setText(""); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 4)) { load_default_stdcat(); if (instrument_type == "NIR") { ui->APIrefcatComboBox->setCurrentText("MKO_JHK"); } else { ui->APIrefcatComboBox->setCurrentText("SMITH_u'g'r'i'z'"); } ui->APIWCSCheckBox->setChecked(true); ui->APIWCSLineEdit->setText("10"); ui->APIzpmaxLineEdit->clear(); ui->APIzpminLineEdit->clear(); ui->APIapertureLineEdit->setText("10"); ui->APIcalibrationmodeComboBox->setCurrentIndex(0); ui->APIcolorComboBox->setCurrentIndex(0); ui->APIcolortermLineEdit->setText("0.0"); ui->APIconvergenceLineEdit->setText("0.01"); ui->APIextinctionLineEdit->setText("-0.1"); ui->APIfilterComboBox->setCurrentIndex(0); ui->APIfilterkeywordLineEdit->clear(); ui->APIkappaLineEdit->setText("2.0"); ui->APIminmagLineEdit->clear(); ui->APIthresholdLineEdit->setText("0.15"); ui->APInight1ComboBox->setCurrentIndex(0); ui->APInight1PushButton->setChecked(false); ui->APInight2ComboBox->setCurrentIndex(0); ui->APInight2PushButton->setChecked(false); ui->APInight3ComboBox->setCurrentIndex(0); ui->APInight3PushButton->setChecked(false); ui->APInight4ComboBox->setCurrentIndex(0); ui->APInight4PushButton->setChecked(false); ui->APInight5ComboBox->setCurrentIndex(0); ui->APInight5PushButton->setChecked(false); ui->APInight6ComboBox->setCurrentIndex(0); ui->APInight6PushButton->setChecked(false); ui->APInight7ComboBox->setCurrentIndex(0); ui->APInight7PushButton->setChecked(false); ui->APInight8ComboBox->setCurrentIndex(0); ui->APInight8PushButton->setChecked(false); ui->APInight9ComboBox->setCurrentIndex(0); ui->APInight9PushButton->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 5)) { load_default_stdcat(); ui->ARCcatalogComboBox->setCurrentIndex(0); ui->ARCdecLineEdit->clear(); ui->ARCminmagLineEdit->clear(); ui->ARCmaxpmLineEdit->clear(); ui->ARCDTLineEdit->setText("5"); ui->ARCDMINLineEdit->setText("5"); ui->ARCraLineEdit->clear(); ui->ARCradiusLineEdit->clear(); ui->ARCselectimageLineEdit->clear(); ui->ARCtargetresolverLineEdit->clear(); ui->ARCmaxpmLineEdit->clear(); ui->ARCpmRALineEdit->clear(); ui->ARCpmDECLineEdit->clear(); ui->CSCDMINLineEdit->setText("5"); ui->CSCDTLineEdit->setText("5"); ui->CSCFWHMLineEdit->setText("1.5"); ui->CSCbackgroundLineEdit->clear(); ui->CSCmaxflagLineEdit->setText("8"); ui->CSCmincontLineEdit->setText("0.0005"); ui->CSCrejectExposureLineEdit->clear(); ui->CSCsamplingCheckBox->setChecked(false); ui->CSCconvolutionCheckBox->setChecked(true); ui->CSCsaturationLineEdit->clear(); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 6)) { if (instrument_type == "NIR") { ui->APDrefcatComboBox->setCurrentText("SDSS"); } else { ui->APDrefcatComboBox->setCurrentText("2MASS"); } ui->APDfilterComboBox->setCurrentIndex(0); ui->APDfilterComboBox->setCurrentIndex(0); ui->APDmaxphoterrorLineEdit->setText("0.05"); ui->ASTastrefweightLineEdit->setText("1.0"); ui->ASTastrinstrukeyLineEdit->setText("FILTER"); ui->ASTcrossidLineEdit->setText("1.0"); ui->ASTdistortLineEdit->setText("3"); ui->ASTdistortgroupsLineEdit->clear(); ui->ASTdistortkeysLineEdit->clear(); ui->ASTmatchMethodComboBox->setCurrentIndex(0); ui->ASTmatchflippedCheckBox->setChecked(false); ui->ASTmethodComboBox->setCurrentIndex(0); if (instrument_nchips == 1) { ui->ASTmosaictypeComboBox->setCurrentIndex(0); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } else { ui->ASTmosaictypeComboBox->setCurrentIndex(4); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } ui->ASTphotinstrukeyLineEdit->setText("FILTER"); ui->ASTpixscaleLineEdit->setText("1.05"); ui->ASTposangleLineEdit->setText("2"); ui->ASTpositionLineEdit->setText("2.0"); ui->ASTresolutionLineEdit->setText("800"); ui->ASTsnthreshLineEdit->setText("5,20"); ui->ASTstabilityComboBox->setCurrentIndex(1); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 7)) { ui->skyAreaComboBox->setCurrentIndex(0); ui->skyConstsubRadioButton->setChecked(false); ui->skyDMINLineEdit->setText("10"); ui->skyDTLineEdit->setText("1.5"); ui->skyKernelLineEdit->setText("256"); ui->skyMefLineEdit->clear(); ui->skyModelRadioButton->setChecked(true); ui->skyPolynomialRadioButton->setChecked(false); ui->skyPolynomialSpinBox->setValue(1); ui->skySavemodelCheckBox->setChecked(false); } if (sender() == mainGUI->ui->setupProjectResetToolButton || sender() == 0 || (sender() == ui->parametersDefaultPushButton && ui->confStackedWidget->currentIndex() == 8)) { ui->COAcelestialtypeComboBox->setCurrentIndex(0); ui->COAchipsLineEdit->clear(); ui->COAcombinetypeComboBox->setCurrentIndex(0); ui->COAdecLineEdit->clear(); ui->COAedgesmoothingLineEdit->clear(); ui->COAfluxcalibCheckBox->setChecked(false); ui->COAkernelComboBox->setCurrentIndex(3); ui->COAoutsizeLineEdit->setText("4"); ui->COAoutthreshLineEdit->setText("3"); ui->COAoutborderLineEdit->clear(); ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE")); ui->COApmComboBox->setCurrentIndex(0); ui->COApmdecLineEdit->clear(); ui->COApmraLineEdit->clear(); ui->COAprojectionComboBox->setCurrentIndex(0); ui->COAraLineEdit->clear(); ui->COArescaleweightsCheckBox->setChecked(false); ui->COArzpCheckBox->setChecked(false); ui->COAsizexLineEdit->clear(); ui->COAsizeyLineEdit->clear(); ui->COAskypaLineEdit->clear(); ui->COAuniqueidLineEdit->clear(); } }
19,898
C++
.cc
421
40.007126
109
0.670744
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,438
memoryviewer.cc
schirmermischa_THELI/src/dockwidgets/memoryviewer.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "memoryviewer.h" #include "ui_memoryviewer.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../myimage/myimage.h" #include "functions.h" #include "../processingInternal/controller.h" #include "../processingInternal/data.h" #include "../datamodel/datamodel.h" #include "../threading/memoryworker.h" #include <omp.h> #include <QList> #include <QTest> #include <QThread> #include <QTableView> #include <QString> #include <QStringList> MemoryViewer::MemoryViewer(Controller *ctrl, MainWindow *parent) : QDockWidget(parent), ui(new Ui::MemoryViewer) { ui->setupUi(this); mainGUI = parent; controller = ctrl; // connect(ui->memoryTableView, &QTableView::clicked, this, &MemoryViewer::writeCheckBoxClicked); connect(ui->procstatusHDUreformatCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusProcessscienceCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusChopnodCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusBackgroundCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusCollapseCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusStarflatCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(ui->procstatusSkysubCheckbox, &QCheckBox::clicked, this, &MemoryViewer::updateProcessingStatusOnDriveAndInData); connect(this, &MemoryViewer::refreshMemoryViewer, mainGUI, &MainWindow::refreshMemoryViewerReceiver); QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QString::fromLatin1(file.readAll()); qApp->setStyleSheet(styleSheet); QIcon download(":/icons/download.png"); QIcon upload(":/icons/upload.png"); ui->downloadToolButton->setIcon(download); ui->uploadToolButton->setIcon(upload); // Not sure what this button actually would do (that cannot be done with the checkboxes) ui->uploadToolButton->hide(); } MemoryViewer::~MemoryViewer() { /* for (auto &dataModel : dataModelList) { if (dataModel != nullptr) delete dataModel; } if (workerInit) delete worker; */ if (workerThreadInit) { if (workerThread) workerThread->quit(); if (workerThread) workerThread->wait(); // delete workerThread; } delete ui; } void MemoryViewer::populate() { ui->datadirComboBox->clear(); ui->restoreComboBox->clear(); dataModelList.clear(); // Add data from the defined data directories addData(controller->DT_SCIENCE, "SCI"); addData(controller->DT_SKY, "SKY"); addData(controller->DT_BIAS, "BIAS"); addData(controller->DT_DARK, "DARK"); addData(controller->DT_FLATOFF, "FLATOFF"); addData(controller->DT_FLAT, "FLAT"); addData(controller->DT_STANDARD, "STD"); addDataWeights(controller->DT_SCIENCE); addDataWeights(controller->DT_SKY); addDataWeights(controller->DT_STANDARD); addGlobalWeights(); on_datadirComboBox_currentIndexChanged(0); } void MemoryViewer::clearMemoryViewReceived() { // ui->datadirComboBox->clear(); // emit beginResetModel(); ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(emptyModel); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); for (auto &model : dataModelList) { model->deleteLater(); } dataModelList.clear(); ui->datadirComboBox->clear(); ui->restoreComboBox->clear(); } void MemoryViewer::populateMemoryViewReceived() { populate(); if (dataModelList.isEmpty()) return; // emit endResetModel(); ui->datadirComboBox->setCurrentIndex(0); ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(dataModelList[0]); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); /* for (auto &model : dataModelList) { delete model; model = nullptr; } */ } void MemoryViewer::addData(const QList<Data*> &DT_x, const QString &type) { if (DT_x.isEmpty()) return; QStringList list; for (auto &data : DT_x) { if (data == nullptr || !data->dataInitialized || !data->dir.exists() || data->subDirName.isEmpty()) continue; list << type+":"+" "+data->subDirName; DataModel *dataModel = new DataModel(data); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); connect(dataModel, &DataModel::refreshMemoryViewer, mainGUI, &MainWindow::refreshMemoryViewerReceiver); connect(dataModel, &DataModel::activationWarning, controller, &Controller::activationWarningReceived); connect(dataModel, &DataModel::activationChanged, this, &MemoryViewer::activationChangedReceiver); } if (list.isEmpty()) return; ui->datadirComboBox->addItems(list); ui->datadirComboBox->update(); } void MemoryViewer::addDataWeights(const QList<Data*> &DT_x) { if (DT_x.isEmpty()) return; QStringList list; QString weight = "WEIGHT:"; for (auto &data : DT_x) { if (!data->dataInitialized) continue; QDir weightDir(data->mainDirName+"/WEIGHTS"); if (!weightDir.exists()) continue; list << weight+" "+data->subDirName; DataModel *dataModel = new DataModel(data, "weight"); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); } if (list.isEmpty()) return; ui->datadirComboBox->addItems(list); ui->datadirComboBox->update(); } void MemoryViewer::addGlobalWeights() { if (controller->GLOBALWEIGHTS == nullptr || !controller->GLOBALWEIGHTS->dataInitialized || !controller->GLOBALWEIGHTS->dir.exists()) return; DataModel *dataModel = new DataModel(controller->GLOBALWEIGHTS); dataModel->setParent(this); dataModelList.append(dataModel); connect(this, &MemoryViewer::beginResetModel, dataModel, &DataModel::beginResetModelReceived, Qt::DirectConnection); connect(this, &MemoryViewer::endResetModel, dataModel, &DataModel::endResetModelReceived, Qt::DirectConnection); ui->datadirComboBox->addItem("GLOBALWEIGHTS"); ui->datadirComboBox->update(); } void MemoryViewer::on_datadirComboBox_currentIndexChanged(int index) { if (dataModelList.isEmpty() || index == -1) return; if (ui->datadirComboBox->count() == 0) return; if (mainGUI->doingInitialLaunch || mainGUI->readingSettings) return; ui->memoryTableView->clearSpans(); ui->memoryTableView->setModel(dataModelList[index]); ui->memoryTableView->resizeColumnsToContents(); ui->memoryTableView->resizeRowsToContents(); ui->memoryTableView->sortByColumn(0, Qt::AscendingOrder); ui->memoryTableView->horizontalHeader()->setStretchLastSection(true); ui->memoryTableView->show(); if (iViewOpen) { if (dataModelList[index]->modelType == "weight") iView->weightMode = true; else iView->weightMode = false; iView->myImageList = dataModelList[index]->imageList; iView->numImages = dataModelList[index]->imageList.length(); if (ui->datadirComboBox->currentText() == "GLOBALWEIGHTS") { iView->dirName = controller->mainDirName + "/GLOBALWEIGHTS"; } else { iView->dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); } } showhideStatusCheckBoxes(dataModelList[index]->modelType); updateStatusCheckBoxes(dataModelList[index]->myData); // Populate the restore mode accordingly ui->restoreComboBox->clear(); if (dataModelList[index]->modelType == "calib") { ui->restoreComboBox->insertItem(0, "RAWDATA"); } if (dataModelList[index]->modelType == "science") { QString status1 = ""; QString status2 = ""; QString status3 = ""; // Must test for empty when having done full data reset, and then selecting the "science" tab in the memory viewer if (!dataModelList[index]->imageList.isEmpty()) { status1 = dataModelList[index]->imageList[0]->statusBackupL1; status2 = dataModelList[index]->imageList[0]->statusBackupL2; status3 = dataModelList[index]->imageList[0]->statusBackupL3; } ui->restoreComboBox->addItem("RAWDATA"); if (!status1.isEmpty()) ui->restoreComboBox->addItem(status1+"_IMAGES"); if (!status2.isEmpty()) ui->restoreComboBox->addItem(status2+"_IMAGES"); if (!status3.isEmpty()) ui->restoreComboBox->addItem(status3+"_IMAGES"); addBackupDirs(dataModelList[index]->myData->dirName); } if (dataModelList[index]->modelType == "weight" || dataModelList[index]->modelType == "globalweight") { ui->restoreComboBox->setDisabled(true); ui->restorePushButton->setDisabled(true); } else { ui->restoreComboBox->setEnabled(true); ui->restorePushButton->setEnabled(true); } ui->restoreComboBox->update(); updateStatusTipRestoreButton(); } // triggered when a processing task has created a new backup dir. Only for the currently visible science data void MemoryViewer::addBackupDirReceived(QString scienceDir) { if (ui->datadirComboBox->currentText() == "SCI: "+scienceDir) { repopulateRestoreComboBox(); } } void MemoryViewer::addBackupDirs(const QString &dirName) { QDir dir(dirName); QDir dirCopy(dirName); dirCopy.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); if (dirCopy.count() == 0) return; QStringList dirList = dir.entryList(QDir::Dirs); for (auto &it : dirList) { // add the dir to the combobox if it is a true backup dir, and not yet contained in the combobox if (it.contains("_IMAGES") && ui->restoreComboBox->findText(it) == -1) { ui->restoreComboBox->addItem(it); } } ui->restoreComboBox->update(); // Qt 5.9 /* QDir dir(dirName); QStringList dirList = dir.entryList(QDir::Dirs); for (auto &it : dirList) { // add the dir to the combobox if it is a true backup dir, and not yet contained in the combobox if (it.contains("_IMAGES") && ui->restoreComboBox->findText(it) == -1 && !dir.isEmpty()) { ui->restoreComboBox->addItem(it); } } ui->restoreComboBox->update(); */ } void MemoryViewer::writeCheckBoxClicked(const QModelIndex &index) { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; DataModel *model = dataModelList[cbindex]; if (model->imageList.isEmpty()) return; // Not sure this is ever happening worker->myImage = model->imageList[index.row()]; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::MemoryViewerDumpImagesToDrive); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } /* void MemoryViewer::activeStateCheckBoxClicked(QModelIndex index) { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; DataModel *model = dataModelList[ui->datadirComboBox->currentIndex()]; worker->myImage = model->imageList[index.row()]; worker->path = controller->mainDirName + "/" + ui->datadirComboBox->currentText(); worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::processActiveStatusChanged); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } */ /* void MemoryViewer::on_L0ToDrivePushButton_clicked() { ui->L0ToDrivePushButton->setText("Writing data ..."); ui->L0ToDrivePushButton->setDisabled(true); QTest::qWait(50); int index = ui->datadirComboBox->currentIndex(); #pragma omp parallel for num_threads(controller->maxExternalThreads) for (int i=0; i<dataModelList[index]->imageList.length(); ++i) { // TODO: check if status string is properly set MyImage *it = dataModelList[index]->imageList[i]; if (!it->imageOnDrive) { it->writeImage(it->path + "/" + it->baseName + controller->statusNew + ".fits"); it->imageOnDrive = true; it->emitModelUpdateNeeded(); } } ui->L0ToDrivePushButton->setText("Write L0 data to Drive"); ui->L0ToDrivePushButton->setEnabled(true); } */ void MemoryViewer::on_downloadToolButton_clicked() { workerThread = new QThread(this); worker = new MemoryWorker(this); workerInit = true; workerThreadInit = true; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MemoryWorker::MemoryViewerDumpImagesToDrive); QObject::connect(worker, &MemoryWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); } void MemoryViewer::on_memoryTableView_clicked(const QModelIndex &index) { int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; // don't show the image if the "active/deactivate" column is clicked if (index.column() == 1) return; // don't show the image if the "dump to drive" column is clicked if (index.column() == 2) return; DataModel *model = dataModelList[cbindex]; if (model->imageList.isEmpty()) return; // Not sure this is ever happening // CHECK: uncommented on 2019-10-02; should have no impact since unused // MyImage *myImage = model->imageList[index.row()]; if (!iViewOpen) { QString dirName = ""; if (ui->datadirComboBox->currentText() == "GLOBALWEIGHTS") { dirName = controller->mainDirName + "/GLOBALWEIGHTS"; } else { dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); } iView = new IView("MEMview", model->imageList, dirName, this); iViewOpen = true; if (model->modelType == "weight") iView->weightMode = true; else iView->weightMode = false; connect(iView, &IView::currentlyDisplayedIndex, this, &MemoryViewer::currentlyDisplayedIndex_received); connect(iView, &IView::destroyed, this, &MemoryViewer::iViewClosed_received); connect(iView, &IView::closed, this, &MemoryViewer::iViewClosed_received); } bool sourcecatShown = iView->sourcecatSourcesShown; bool refcatShown = iView->refcatSourcesShown; iView->clearItems(); iView->loadFromRAM(model->imageList[index.row()], index.column()); // iView->loadFromRAMlist(index); iView->currentId = index.row(); iView->setCatalogOverlaysExternally(sourcecatShown, refcatShown); iView->redrawSkyCirclesAndCats(); iView->show(); // iView->raise(); } void MemoryViewer::iViewClosed_received() { iViewOpen = false; } void MemoryViewer::activationChangedReceiver() { emit activationChanged(); } void MemoryViewer::currentlyDisplayedIndex_received(int currentId) { // Deselect current selection QModelIndex currentIndex = ui->memoryTableView->selectionModel()->currentIndex(); ui->memoryTableView->selectionModel()->setCurrentIndex(currentIndex, QItemSelectionModel::Deselect); int cbindex = ui->datadirComboBox->currentIndex(); if (cbindex == -1) return; // Make new selection QModelIndex index = dataModelList[cbindex]->index(currentId,0); ui->memoryTableView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select); } void MemoryViewer::on_restorePushButton_clicked() { Data *data = getDataClassThisModel(); if (data == nullptr) return; QString backupDir = ui->restoreComboBox->currentText(); if (backupDir.isEmpty()) return; data->restoreBackupLevel(backupDir); // ui->restoreComboBox->removeItem(ui->restoreComboBox->currentIndex()); repopulateRestoreComboBox(); // header line only changes if we manually resize the viewer, or: // quickly load the monitor, then the memory viewer again: emit refreshMemoryViewer(); } void MemoryViewer::hideStatusCheckBoxes() { ui->procstatusHDUreformatCheckbox->setVisible(false); ui->procstatusProcessscienceCheckbox->setVisible(false); ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(false); ui->procstatusCollapseCheckbox->setVisible(false); ui->procstatusStarflatCheckbox->setVisible(false); ui->procstatusSkysubCheckbox->setVisible(false); } void MemoryViewer::showhideStatusCheckBoxes(QString type) { hideStatusCheckBoxes(); return; // Never needed this /* Data *data = getDataClassThisModel(); if (data == nullptr) return; if (type == "science") { ui->procstatusHDUreformatCheckbox->setVisible(true); ui->procstatusProcessscienceCheckbox->setVisible(true); ui->procstatusCollapseCheckbox->setVisible(true); ui->procstatusSkysubCheckbox->setVisible(true); if (data->instData->type == "OPT") { ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "NIR") { ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "NIRMIR") { ui->procstatusChopnodCheckbox->setVisible(true); ui->procstatusBackgroundCheckbox->setVisible(true); } else if (data->instData->type == "MIR") { ui->procstatusChopnodCheckbox->setVisible(true); ui->procstatusBackgroundCheckbox->setVisible(false); } ui->procstatusStarflatCheckbox->setVisible(false); } else { ui->procstatusHDUreformatCheckbox->setVisible(true); ui->procstatusProcessscienceCheckbox->setVisible(false); ui->procstatusChopnodCheckbox->setVisible(false); ui->procstatusBackgroundCheckbox->setVisible(false); ui->procstatusCollapseCheckbox->setVisible(false); ui->procstatusStarflatCheckbox->setVisible(false); ui->procstatusSkysubCheckbox->setVisible(false); } */ } void MemoryViewer::updateStatusCheckBoxes(Data *data) { ui->procstatusHDUreformatCheckbox->setChecked(data->processingStatus->HDUreformat); ui->procstatusProcessscienceCheckbox->setChecked(data->processingStatus->Processscience); ui->procstatusChopnodCheckbox->setChecked(data->processingStatus->Chopnod); ui->procstatusBackgroundCheckbox->setChecked(data->processingStatus->Background); ui->procstatusCollapseCheckbox->setChecked(data->processingStatus->Collapse); ui->procstatusStarflatCheckbox->setChecked(data->processingStatus->Starflat); ui->procstatusSkysubCheckbox->setChecked(data->processingStatus->Skysub); } // reflect a status update in the currently shown checkboxes (if they represent the Data class that sent the signal) void MemoryViewer::updateStatusCheckBoxesReceived(QString statusString) { // The statusString arg is used by another slot in mainwindow.cc int index = ui->datadirComboBox->currentIndex(); if (dataModelList.isEmpty() || index == -1 || mainGUI->doingInitialLaunch) return; Data *data = qobject_cast<Data*>(sender()); if (dataModelList[index]->myData == data) statusDataToCheckBox(data); } // Reflect the processingStatus of Data class in the checkboxes void MemoryViewer::statusDataToCheckBox(Data *data) { ui->procstatusHDUreformatCheckbox->setChecked(data->processingStatus->HDUreformat); ui->procstatusProcessscienceCheckbox->setChecked(data->processingStatus->Processscience); ui->procstatusChopnodCheckbox->setChecked(data->processingStatus->Chopnod); ui->procstatusBackgroundCheckbox->setChecked(data->processingStatus->Background); ui->procstatusCollapseCheckbox->setChecked(data->processingStatus->Collapse); ui->procstatusStarflatCheckbox->setChecked(data->processingStatus->Starflat); ui->procstatusSkysubCheckbox->setChecked(data->processingStatus->Skysub); } // Reflect the processingStatus of the checkboxes in the Data class void MemoryViewer::statusCheckBoxToData() { Data *data = getDataClassThisModel(); if (data == nullptr) return; data->processingStatus->HDUreformat = ui->procstatusHDUreformatCheckbox->isChecked(); data->processingStatus->Processscience = ui->procstatusProcessscienceCheckbox->isChecked(); data->processingStatus->Chopnod = ui->procstatusChopnodCheckbox->isChecked(); data->processingStatus->Background = ui->procstatusBackgroundCheckbox->isChecked(); data->processingStatus->Collapse = ui->procstatusCollapseCheckbox->isChecked(); data->processingStatus->Starflat = ui->procstatusStarflatCheckbox->isChecked(); data->processingStatus->Skysub = ui->procstatusSkysubCheckbox->isChecked(); } void MemoryViewer::projectResetReceived() { ui->restoreComboBox->clear(); ui->procstatusHDUreformatCheckbox->setChecked(false); ui->procstatusProcessscienceCheckbox->setChecked(false); ui->procstatusChopnodCheckbox->setChecked(false); ui->procstatusBackgroundCheckbox->setChecked(false); ui->procstatusCollapseCheckbox->setChecked(false); ui->procstatusStarflatCheckbox->setChecked(false); ui->procstatusSkysubCheckbox->setChecked(false); } Data* MemoryViewer::getDataClassThisModel() { int index = ui->datadirComboBox->currentIndex(); if (dataModelList.isEmpty() || index == -1 || mainGUI->doingInitialLaunch) return nullptr; return dataModelList[index]->myData; } void MemoryViewer::repopulateRestoreComboBox() { QString dirName = controller->mainDirName + "/" + ui->datadirComboBox->currentText().split(":").at(1).simplified(); QDir dir(dirName); if (!dir.exists()) return; // should never happen QStringList filters; filters << "RAWDATA" << "*_IMAGES"; QStringList backupdirList = dir.entryList(filters, QDir::Dirs); ui->restoreComboBox->clear(); // Add the directory only if it is not empty! ui->restoreComboBox->addItems(backupdirList); ui->restoreComboBox->update(); } void MemoryViewer::updateProcessingStatusOnDriveAndInData() { Data *data = getDataClassThisModel(); if (data == nullptr) return; statusCheckBoxToData(); data->processingStatus->getStatusString(); data->processingStatus->writeToDrive(); } void MemoryViewer::updateStatusTipRestoreButton() { if (ui->restoreComboBox->count() == 0 || ui->datadirComboBox->count() == 0) { ui->restorePushButton->setStatusTip("Restores certain processing stages"); return; } QString backupDir = ui->restoreComboBox->currentText(); QString dirName = ui->datadirComboBox->currentText().split(":").at(1).simplified(); QString statusTip = "Restores "+backupDir+" in " + dirName + ". Images currently present in "+dirName + " will be deleted!"; ui->restorePushButton->setStatusTip(statusTip); } void MemoryViewer::on_restoreComboBox_currentTextChanged(const QString &arg1) { updateStatusTipRestoreButton(); }
25,399
C++
.cc
567
39.4903
132
0.717549
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,439
confdockwidget.cc
schirmermischa_THELI/src/dockwidgets/confdockwidget.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "functions.h" #include "../iview/iview.h" #include <QPushButton> #include <QToolButton> #include <QRadioButton> #include <QComboBox> ConfDockWidget::ConfDockWidget(MainWindow *parent) : QDockWidget(parent), ui(new Ui::ConfDockWidget) { mainGUI = parent; ui->setupUi(this); doingInitialLaunch = true; initConfDockWidget(); setupAstrometry(); populateDefaultMap(); establish_connections(); populateAPIlists(); updateConfPageLabel(); ui->skyAreaComboBox->setStyleSheet("combobox-popup: 0;"); // enforcing max number of 18 entries (set in designer) doingInitialLaunch = false; } ConfDockWidget::~ConfDockWidget() { delete ui; } void ConfDockWidget::initConfDockWidget() { QIcon magnifyer(":/icons/magnifyer.png"); ui->ARCtargetresolverToolButton->setIcon(magnifyer); ui->xtalk_col_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_col_1x2.png")); ui->xtalk_col_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_col_2x1.png")); ui->xtalk_col_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_col_2x2.png")); ui->xtalk_nor_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_nor_1x2.png")); ui->xtalk_nor_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_nor_2x1.png")); ui->xtalk_nor_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_nor_2x2.png")); ui->xtalk_row_1x2ToolButton->setIcon(QIcon(":/icons/xtalk_row_1x2.png")); ui->xtalk_row_2x1ToolButton->setIcon(QIcon(":/icons/xtalk_row_2x1.png")); ui->xtalk_row_2x2ToolButton->setIcon(QIcon(":/icons/xtalk_row_2x2.png")); ui->skyReadmePushButton->hide(); ui->COAhistogramMJDOBSPushButton->hide(); // update the collapse direction icon QString colldir = ui->COCdirectionComboBox->currentText(); ui->COCdirectionLabel->setPixmap(QPixmap(":/icons/collapse_"+colldir)); // These comboboxes do not get initialized or filled properly unless one clicks on it: on_APDrefcatComboBox_currentTextChanged(ui->APDrefcatComboBox->currentText()); on_ASTmethodComboBox_currentIndexChanged(ui->ASTmethodComboBox->currentIndex()); // why commented / uncommented above? // on_APIrefcatComboBox_currentTextChanged(ui->APIrefcatComboBox->currentText()); updateARCdisplay(); toggle_skyparams(); toggle_skyparamThresholds(""); applyStyleSheets(); setupXtalkButtonGroups(); updateAPIsolutions(); } void ConfDockWidget::establish_connections() { // Connect crosstalk ToolButtons with icon updater connect(ui->xtalk_col_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_col_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_col_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_row_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_1x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_2x1ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); connect(ui->xtalk_nor_2x2ToolButton, &QToolButton::toggled, this, &ConfDockWidget::toggle_icons_xtalkToolButtons); // Connect skysub Radio Buttons with a function that dis/enables frames connect(ui->skyModelRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyPolynomialRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyConstsubRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::toggle_skyparams); connect(ui->skyAreaComboBox, &QComboBox::currentTextChanged, this, &ConfDockWidget::toggle_skyparamThresholds); connect(ui->BACwindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::switch_static_dynamic); connect(ui->confStackedWidget, &QStackedWidget::currentChanged, this, &ConfDockWidget::updateConfPageLabel); connect(ui->parametersDefaultPushButton, &QPushButton::clicked, this, &ConfDockWidget::loadDefaults); // TODO: check if needed // connect(ui->skyModelRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->skyPolynomialRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->skyConstsubRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // Update command list in real time when the following parameters are changed // (may or may not add further scripts) // TODO: check if needed // connect(ui->BACdistLineEdit, &QLineEdit::textChanged, this, &MainWindow::on_startPushButton_clicked); // connect(ui->BACmagLineEdit, &QLineEdit::textChanged, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ARCwebRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ARCimageRadioButton, &QRadioButton::clicked, this, &MainWindow::on_startPushButton_clicked); // connect(ui->ASTmethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::startPushButton_clicked_dummy); // connect(ui->APIWCSCheckBox, &QCheckBox::clicked, this, &MainWindow::on_startPushButton_clicked); // TODO: must activate connect(ui->ARCgetcatalogPushButton, &QPushButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->restoreHeaderPushButton, &QPushButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->ARCtargetresolverToolButton, &QToolButton::clicked, mainGUI, &MainWindow::on_startPushButton_clicked); connect(ui->ARCwebRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::updateARCdisplay); connect(ui->ARCimageRadioButton, &QRadioButton::clicked, this, &ConfDockWidget::updateARCdisplay); connect(ui->COAchipsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::update_COA_uniqueID); connect(ui->COAminMJDOBSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::update_COA_uniqueID); connect(ui->COAmaxMJDOBSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::update_COA_uniqueID); // TODO: must activate // Connect StandardStar solution PushButtons with iView for (auto &it : APIstdPushButtonList) { connect(it, &QPushButton::clicked, this, &ConfDockWidget::showAPIsolution); } connect(ui->excludeDetectorsLineEdit, &QLineEdit::textChanged, mainGUI, &MainWindow::updateExcludedDetectors); connect(mainGUI->ui->setupInstrumentComboBox, &QComboBox::currentTextChanged, this, &ConfDockWidget::setupInstrumentComboBox_clicked); connect_validators(); } void ConfDockWidget::applyStyleSheets() { QList<QLabel*> conftitleLabelList; conftitleLabelList.append(ui->conftitleHDUreformatLabel); conftitleLabelList.append(ui->conftitleExcludeDetectorsLabel); conftitleLabelList.append(ui->conftitleProcessbiasLabel); conftitleLabelList.append(ui->conftitleChopnodLabel); conftitleLabelList.append(ui->conftitleBackground1Label); conftitleLabelList.append(ui->conftitleBackground2Label); conftitleLabelList.append(ui->conftitleCollapseLabel); conftitleLabelList.append(ui->conftitleBinnedpreviewLabel); conftitleLabelList.append(ui->conftitleGlobalweightLabel); conftitleLabelList.append(ui->conftitleIndividualweightLabel); conftitleLabelList.append(ui->conftitleSeparateLabel); conftitleLabelList.append(ui->conftitleAbsphotindirect1Label); conftitleLabelList.append(ui->conftitleAbsphotindirect2Label); conftitleLabelList.append(ui->conftitleCreatesourcecatLabel); conftitleLabelList.append(ui->conftitleGetCatalogLabel); conftitleLabelList.append(ui->conftitleAstromphotom1Label); conftitleLabelList.append(ui->conftitleAstromphotom2Label); conftitleLabelList.append(ui->conftitleStarflatLabel); conftitleLabelList.append(ui->conftitleSkysubLabel); conftitleLabelList.append(ui->conftitleCoadd1Label); conftitleLabelList.append(ui->conftitleCoadd2Label); for (auto &it : conftitleLabelList) { it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);"); it->setMargin(8); } QList<QLabel*> confsubtitleLabelList; confsubtitleLabelList.append(ui->confsubtitleHDUreformat1Label); confsubtitleLabelList.append(ui->confsubtitleHDUreformat2Label); confsubtitleLabelList.append(ui->confsubtitleCalibrators1Label); confsubtitleLabelList.append(ui->confsubtitleCalibrators2Label); confsubtitleLabelList.append(ui->confsubtitleBackground1Label); confsubtitleLabelList.append(ui->confsubtitleBackground2Label); confsubtitleLabelList.append(ui->confsubtitleBackground3Label); confsubtitleLabelList.append(ui->confsubtitleBackground4Label); confsubtitleLabelList.append(ui->confsubtitleBackground5Label); confsubtitleLabelList.append(ui->confsubtitleBackground6Label); confsubtitleLabelList.append(ui->confsubtitleCollapse1Label); confsubtitleLabelList.append(ui->confsubtitleCollapse2Label); confsubtitleLabelList.append(ui->confsubtitleCollapse3Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight1Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight2Label); confsubtitleLabelList.append(ui->confsubtitleGlobalweight3Label); confsubtitleLabelList.append(ui->confsubtitleIndividualweight1Label); confsubtitleLabelList.append(ui->confsubtitleIndividualweight2Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect1Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect2Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect3Label); confsubtitleLabelList.append(ui->confsubtitleAbsphotindirect4Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat1Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat2Label); confsubtitleLabelList.append(ui->confsubtitleCreatesourcecat3Label); confsubtitleLabelList.append(ui->confsubtitleGetCatalog1Label); confsubtitleLabelList.append(ui->confsubtitleGetCatalog2Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom1Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom2Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom3Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom4Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom5Label); confsubtitleLabelList.append(ui->confsubtitleAstromphotom6Label); confsubtitleLabelList.append(ui->confsubtitleSkysub1Label); confsubtitleLabelList.append(ui->confsubtitleSkysub2Label); confsubtitleLabelList.append(ui->confsubtitleSkysub3Label); confsubtitleLabelList.append(ui->confsubtitleCoadd1Label); confsubtitleLabelList.append(ui->confsubtitleCoadd2Label); confsubtitleLabelList.append(ui->confsubtitleCoadd3Label); confsubtitleLabelList.append(ui->confsubtitleCoadd4Label); confsubtitleLabelList.append(ui->confsubtitleCoadd5Label); confsubtitleLabelList.append(ui->confsubtitleCoadd6Label); for (auto &it : confsubtitleLabelList) { it->setStyleSheet("background-color: rgb(190,190,210);"); it->setMargin(4); } QList<QFrame*> confFrameList; confFrameList.append(ui->confHDUreformat1Frame); confFrameList.append(ui->confHDUreformat2Frame); confFrameList.append(ui->confExcludeDetectorsFrame); confFrameList.append(ui->confCalibrators1Frame); confFrameList.append(ui->confCalibrators2Frame); confFrameList.append(ui->confChopnodFrame); confFrameList.append(ui->confBackground1Frame); confFrameList.append(ui->confBackground2Frame); confFrameList.append(ui->confBackground3Frame); confFrameList.append(ui->confBackground4Frame); confFrameList.append(ui->confBackground5Frame); confFrameList.append(ui->confBackground6Frame); confFrameList.append(ui->confCollapse1Frame); confFrameList.append(ui->confCollapse2Frame); confFrameList.append(ui->confCollapse3Frame); confFrameList.append(ui->confBinnedpreviewFrame); confFrameList.append(ui->confGlobalweight1Frame); confFrameList.append(ui->confGlobalweight2Frame); confFrameList.append(ui->confGlobalweight3Frame); confFrameList.append(ui->confIndividualweight1Frame); confFrameList.append(ui->confIndividualweight2Frame); confFrameList.append(ui->confSeparateFrame); confFrameList.append(ui->confAbsphotindirect1Frame); confFrameList.append(ui->confAbsphotindirect2Frame); confFrameList.append(ui->confAbsphotindirect3Frame); confFrameList.append(ui->confAbsphotindirect4Frame); confFrameList.append(ui->confAstromphotom1Frame); confFrameList.append(ui->confAstromphotom2Frame); confFrameList.append(ui->confAstromphotom3Frame); confFrameList.append(ui->confAstromphotom4Frame); confFrameList.append(ui->confAstromphotom5Frame); confFrameList.append(ui->confAstromphotom6Frame); confFrameList.append(ui->confCreatesourcecat1Frame); confFrameList.append(ui->confCreatesourcecat2Frame); confFrameList.append(ui->confCreatesourcecat3Frame); confFrameList.append(ui->confGetCatalog1Frame); confFrameList.append(ui->confGetCatalog2Frame); confFrameList.append(ui->confStarflatFrame); confFrameList.append(ui->confSkysub1Frame); confFrameList.append(ui->confSkysub2Frame); confFrameList.append(ui->confSkysub3Frame); confFrameList.append(ui->confCoadd1Frame); confFrameList.append(ui->confCoadd2Frame); confFrameList.append(ui->confCoadd3Frame); confFrameList.append(ui->confCoadd4Frame); confFrameList.append(ui->confCoadd5Frame); /* for (auto &it : confFrameList) { // specify large style sheet? } */ /* // Checkboxes with differently colored background QList<QCheckBox*> confCheckboxList; confCheckboxList.append(ui->CIWmaskbloomingCheckBox); for (auto &it : confCheckboxList) { // it->setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(160,160,160);"); it->setStyleSheet("background-color: rgb(190,190,210);"); } */ } void ConfDockWidget::targetResolvedReceived(const QString &alpha, const QString &delta) { ui->ARCraLineEdit->setText(alpha); ui->ARCdecLineEdit->setText(delta); } void ConfDockWidget::toggle_icons_xtalkToolButtons() { QToolButton *toolbutton = qobject_cast<QToolButton*>(sender()); QString sender_name = toolbutton->objectName().remove("ToolButton"); // Override checked/unchecked ToolButton background color // The "checked" color will actually be a bit darker than requested here (shade overriden) QPalette palette_checked, palette_unchecked; palette_checked.setColor(QPalette::Button,QColor("#00ffff")); palette_unchecked.setColor(QPalette::Button,QColor("#ffffff")); if (toolbutton->isChecked()) { if (sender()) { QToolButton *toolbutton = qobject_cast<QToolButton*>(sender()); if (toolbutton->isChecked()) toolbutton->setPalette(palette_checked); else toolbutton->setPalette(palette_unchecked); } toolbutton->setPalette(palette_checked); // also activate the checkbox if a xtalk mode is selected if (sender_name.contains("nor")) ui->normalxtalkCheckBox->setChecked(true); else ui->rowxtalkCheckBox->setChecked(true); } else { toolbutton->setPalette(palette_unchecked); } } // This is a slot that receives a signal with a QString argument, but does not use it void ConfDockWidget::toggle_skyparamThresholds(QString text) { if (ui->skyAreaComboBox->currentIndex() == 0 && ui->confSkysub3Frame->isEnabled()) ui->confSkysub2Frame->setDisabled(true); else ui->confSkysub2Frame->setEnabled(true); } void ConfDockWidget::load_default_stdcat() { if (instrument_type == "OPT") { ui->APIrefcatComboBox->setCurrentIndex(4); ui->APDfilterComboBox->setCurrentIndex(0); } else if (instrument_type == "NIR") { ui->APIrefcatComboBox->setCurrentIndex(6); ui->APDfilterComboBox->setCurrentIndex(1); } else if (instrument_type == "NIRMIR") { ui->APIrefcatComboBox->setCurrentIndex(10); ui->APDfilterComboBox->setCurrentIndex(1); } else { // There isn't really a solution for MIR... ui->APIrefcatComboBox->setCurrentIndex(10); ui->APDfilterComboBox->setCurrentIndex(1); } } void ConfDockWidget::populateAPIlists() { APIstdPushButtonList.append(ui->APInight1PushButton); APIstdPushButtonList.append(ui->APInight2PushButton); APIstdPushButtonList.append(ui->APInight3PushButton); APIstdPushButtonList.append(ui->APInight4PushButton); APIstdPushButtonList.append(ui->APInight5PushButton); APIstdPushButtonList.append(ui->APInight6PushButton); APIstdPushButtonList.append(ui->APInight7PushButton); APIstdPushButtonList.append(ui->APInight8PushButton); APIstdPushButtonList.append(ui->APInight9PushButton); APIstdComboBoxList.append(ui->APInight1ComboBox); APIstdComboBoxList.append(ui->APInight2ComboBox); APIstdComboBoxList.append(ui->APInight3ComboBox); APIstdComboBoxList.append(ui->APInight4ComboBox); APIstdComboBoxList.append(ui->APInight5ComboBox); APIstdComboBoxList.append(ui->APInight6ComboBox); APIstdComboBoxList.append(ui->APInight7ComboBox); APIstdComboBoxList.append(ui->APInight8ComboBox); APIstdComboBoxList.append(ui->APInight9ComboBox); } void ConfDockWidget::toggle_skyparams() { const QStandardItemModel* skyAreaModel = dynamic_cast< QStandardItemModel * >( ui->skyAreaComboBox->model() ); if (ui->skyModelRadioButton->isChecked()) { ui->confSkysub2Frame->setEnabled(true); ui->confSkysub3Frame->setDisabled(true); ui->skyAreaPushButton->setDisabled(true); } else if (ui->skyPolynomialRadioButton->isChecked()) { ui->confSkysub2Frame->setDisabled(true); ui->confSkysub3Frame->setEnabled(true); for (int i=1; i<ui->skyAreaComboBox->count(); ++i) { skyAreaModel->item(i,0)->setEnabled(false); } // Must use specific areas ui->skyAreaComboBox->setCurrentIndex(0); ui->skyAreaPushButton->setEnabled(true); } else { if (ui->skyAreaComboBox->currentIndex() == 0) ui->confSkysub2Frame->setDisabled(true); else ui->confSkysub2Frame->setEnabled(true); ui->confSkysub3Frame->setEnabled(true); for (int i=1; i<ui->skyAreaComboBox->count(); ++i) { skyAreaModel->item(i,0)->setEnabled(true); } ui->skyAreaPushButton->setEnabled(true); } } void ConfDockWidget::on_COAcelestialtypeComboBox_activated(const QString &arg1) { if (arg1 == "EQUATORIAL") { ui->COAtype1Label->setText("R.A."); ui->COAtype2Label->setText("DEC"); } else if (arg1 == "GALACTIC") { ui->COAtype1Label->setText("GLON"); ui->COAtype2Label->setText("GLAT"); } else if (arg1 == "ECLIPTIC") { ui->COAtype1Label->setText("ELON"); ui->COAtype2Label->setText("ELAT"); } else if (arg1 == "SUPERGALACTIC") { ui->COAtype1Label->setText("SLON"); ui->COAtype2Label->setText("SLAT"); } else { ui->COAtype1Label->setText("R.A."); ui->COAtype2Label->setText("DEC"); } } void ConfDockWidget::switch_static_dynamic() { if (ui->BACwindowLineEdit->text().toInt() == 0) ui->BACcurrentmodeLabel->setText("The mode is: STATIC"); else ui->BACcurrentmodeLabel->setText("The mode is: DYNAMIC"); } void ConfDockWidget::on_COCdirectionComboBox_currentTextChanged(const QString &arg1) { ui->COCdirectionLabel->setPixmap(QPixmap(":/icons/collapse_"+arg1)); } void ConfDockWidget::on_APDrefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1 == "SDSS") fill_combobox(ui->APDfilterComboBox, "u g r i z"); else if (arg1 == "2MASS") fill_combobox(ui->APDfilterComboBox, "J H Ks"); } void ConfDockWidget::on_APIrefcatComboBox_currentTextChanged(const QString &arg1) { if (arg1 == "LANDOLT_UBVRI") { fill_combobox(ui->APIfilterComboBox, "U B V R I"); fill_combobox(ui->APIcolorComboBox, "U-B B-V V-R R-I"); } else if (arg1 == "STETSON_UBVRI") { fill_combobox(ui->APIfilterComboBox, "U B V R I"); fill_combobox(ui->APIcolorComboBox, "U-B B-V V-R R-I"); } else if (arg1 == "STRIPE82_ugriz") { fill_combobox(ui->APIfilterComboBox, "u g r i z"); fill_combobox(ui->APIcolorComboBox, "u-g g-r r-i i-z g-i"); } else if (arg1 == "STRIPE82_u'g'r'i'z'") { fill_combobox(ui->APIfilterComboBox, "u' g' r' i' z'"); fill_combobox(ui->APIcolorComboBox, "u'-g' g'-r' r'-i' i'-z' g'-i'"); } else if (arg1 == "SMITH_u'g'r'i'z'") { fill_combobox(ui->APIfilterComboBox, "u' g' r' i' z'"); fill_combobox(ui->APIcolorComboBox, "u'-g' g'-r' r'-i' i'-z' g'-i'"); } else if (arg1 == "WASHINGTON") { fill_combobox(ui->APIfilterComboBox, "C M T1 T2"); fill_combobox(ui->APIcolorComboBox, "C-M M-T1 T1-T2"); } else if (arg1 == "MKO_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "HUNT_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "2MASSfaint_JHK") { fill_combobox(ui->APIfilterComboBox, "J H K"); fill_combobox(ui->APIcolorComboBox, "J-H H-K J-K"); } else if (arg1 == "PERSSON_JHKKs") { fill_combobox(ui->APIfilterComboBox, "J H K Ks"); fill_combobox(ui->APIcolorComboBox, "J-H H-K H-Ks J-K J-Ks"); } else if (arg1 == "JAC_YJHKLM") { fill_combobox(ui->APIfilterComboBox, "Y J H K L M"); fill_combobox(ui->APIcolorComboBox, "Y-J J-H H-K J-K K-L L-M"); } else if (arg1 == "MKO_LM") { fill_combobox(ui->APIfilterComboBox, "L M"); fill_combobox(ui->APIcolorComboBox, "L-M"); } } void ConfDockWidget::on_confStackedWidget_currentChanged(int arg1) { if (this->isFloating()) { ui->confStackedWidget->setGeometry(100,100,300,300); } } void ConfDockWidget::updateARCdisplay() { if (ui->ARCwebRadioButton->isChecked()) ui->ARCstackedWidget->setCurrentIndex(0); else ui->ARCstackedWidget->setCurrentIndex(1); } void ConfDockWidget::on_ASTmatchMethodComboBox_currentIndexChanged(int index) { // TODO: check if needed (probably not, because we don't invoke scripts anymore) // on_startPushButton_clicked(); if (index >= 1) { ui->ASTposangleLineEdit->setDisabled(true); ui->ASTpositionLineEdit->setDisabled(true); ui->ASTmatchflippedCheckBox->setDisabled(true); ui->ASTposangleLabel->setDisabled(true); ui->ASTpositionLabel->setDisabled(true); } else { ui->ASTposangleLineEdit->setEnabled(true); ui->ASTpositionLineEdit->setEnabled(true); ui->ASTmatchflippedCheckBox->setEnabled(true); ui->ASTposangleLabel->setEnabled(true); ui->ASTpositionLabel->setEnabled(true); } } void ConfDockWidget::on_ASTmethodComboBox_currentIndexChanged(int index) { if (index == 0) { // ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->confAstromphotom6Frame->setEnabled(true); ui->ASTxcorrDTLineEdit->hide(); ui->ASTxcorrDMINLineEdit->hide(); ui->ASTxcorrDTLabel->hide(); ui->ASTxcorrDMINLabel->hide(); } else if (index == 1) { // ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->confAstromphotom6Frame->setDisabled(true); ui->ASTxcorrDTLineEdit->show(); ui->ASTxcorrDMINLineEdit->show(); ui->ASTxcorrDTLabel->show(); ui->ASTxcorrDMINLabel->show(); } else { // ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->confAstromphotom6Frame->setDisabled(true); ui->ASTxcorrDTLineEdit->hide(); ui->ASTxcorrDMINLineEdit->hide(); ui->ASTxcorrDTLabel->hide(); ui->ASTxcorrDMINLabel->hide(); } } void ConfDockWidget::on_COAskypaPushButton_clicked() { QString maindir = mainGUI->ui->setupMainLineEdit->text(); // Grab the first entry of the science dir QString science; if (!mainGUI->ui->setupScienceLineEdit->text().isEmpty()) { science = datadir2StringList(mainGUI->ui->setupScienceLineEdit).at(0); } else { return; } QString sciencedir = maindir+"/"+science; QDir dir(sciencedir); if (!dir.exists()) return; int testChip = -1; for (int chip=0; chip<mainGUI->instData.numChips; ++chip) { if (!mainGUI->instData.badChips.contains(chip)) { testChip = chip; break; } } if (testChip == -1) { qDebug() << __func__ << "error: no data left after filtering"; } QString currentStatus = mainGUI->status.getStatusFromHistory(); QStringList filter1("*_"+QString::number(testChip+1)+currentStatus+".fits"); QStringList filter2("*_"+QString::number(testChip+1)+currentStatus+".sub.fits"); dir.setNameFilters(filter1); dir.setSorting(QDir::Name); QStringList list = dir.entryList(); QString sub = ""; if (list.isEmpty()) { // Probably normal images were parked or removed, try skysub images dir.setNameFilters(filter2); dir.setSorting(QDir::Name); list = dir.entryList(); qDebug() << "Q7"; if (list.isEmpty()) return; sub = ".sub"; } if (list.length() == 0) { QMessageBox::warning( this, "Data not found!", "No "+currentStatus+"-images were found in "+science+"\n"); return; } // Images must have astrometric headers QString headerdir = sciencedir+"/headers/"; bool check = hasMatchingPartnerFiles(sciencedir, currentStatus+sub+".fits", headerdir, ".head", "This task requires that all science images have astrometric headers."); if (!check) return; // Grab the first header file QString baseName = list.at(0); baseName.replace(currentStatus+sub+".fits",""); QString headerName = headerdir+baseName+".head"; QFile header(headerName); QString cd11 = ""; QString cd12 = ""; QString cd21 = ""; QString cd22 = ""; QString line; QString key; QString value; if ( header.open(QIODevice::ReadOnly)) { QTextStream stream( &header ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); if (!line.isEmpty()) { key = line.section(' ',0,0); value = line.section(' ',2,2); if (key == "CD1_1") cd11 = value; if (key == "CD1_2") cd12 = value; if (key == "CD2_1") cd21 = value; if (key == "CD2_2") cd22 = value; } } header.close(); } if (!cd11.isEmpty() && !cd12.isEmpty() && !cd21.isEmpty() && !cd22.isEmpty()) { double skyPA = getPosAnglefromCD(cd11.toDouble(), cd12.toDouble(), cd21.toDouble(), cd22.toDouble()); // in [deg] skyPA *= -1.; // it appears I need that, at least for: /* * these data require a -1 prefactor GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD1_1 = 2.069880636041E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD1_2 = -5.020554295263E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD2_1 = 4.995016509429E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_1.head:CD2_2 = 2.197139027629E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD1_1 = 2.133359158630E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD1_2 = -5.029786624776E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD2_1 = 5.142047608929E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_2.head:CD2_2 = 2.185105945141E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD1_1 = 2.113575793537E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD1_2 = -5.089493103124E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD2_1 = 5.144032585776E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_3.head:CD2_2 = 2.028047913328E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD1_1 = 2.060624347989E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD1_2 = -5.091430845254E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD2_1 = 4.999641460896E-06 / Linear projection matrix GSAOI.Ks.2013-05-22T06:50:58.5_4.head:CD2_2 = 2.040364194243E-06 / Linear projection matrix */ // Truncate the result to one digit QString skyPAstring = QString::number(skyPA, 'f', 1); ui->COAskypaLineEdit->setText(skyPAstring); } else QMessageBox::warning( this, "Corrupted astrometric header", "The CD matrix in "+headerName+" is incomplete, meaning the astrometry was not successful."); } /* void ConfDockWidget::on_viewerToolButton_clicked() { QString main = ui->setupMainLineEdit->text(); QString science = ui->setupScienceLineEdit->text().split(" ").at(0); QString dirname = main+"/"+science; if (!QDir(dirname).exists()) dirname = QDir::homePath(); IView *iView = new IView(dirname, "*.fits", this); iView->show(); } */ void ConfDockWidget::on_skyAreaComboBox_currentTextChanged(const QString &arg1) { if (arg1 != "Specific sky area(s)") ui->skyAreaPushButton->setDisabled(true); else ui->skyAreaPushButton->setEnabled(true); } void ConfDockWidget::on_skyAreaPushButton_clicked() { QMessageBox msgBox; msgBox.setText("Use the middle mouse button (click and drag) to select one or more empty sky areas. " "You can use the forward / backward buttons to select other images. Close the viewer when finished.\n\n" "Alternatively, you can click on any image in the memory viewer, or open any astrometrically calibrated image in iView, e.g. a previous coaddition of the same data. " "Select the dropper tool at the upper left and then use the middle mouse button as explained above."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); QString maindir = mainGUI->ui->setupMainLineEdit->text(); // Grab the first entry of the science dir QString science; if (!mainGUI->ui->setupScienceLineEdit->text().isEmpty()) { science = datadir2StringList(mainGUI->ui->setupScienceLineEdit).at(0); } else { QMessageBox msgBox; msgBox.setText("The science directory is empty."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return; } QString sciencedir = maindir+"/"+science; if (!QDir(sciencedir).exists()) { QMessageBox msgBox; msgBox.setText("The science directory"+sciencedir+"does not exist."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return; } launchViewer("SkyMode"); } // void ConfDockWidget::launchViewer(const QString &dirname, const QString &filter, const QString &mode) void ConfDockWidget::launchViewer(const QString &mode) { // Load the plot viewer // IView *iView = new IView(dirname, filter, false); // IView *iView = new IView("FITSmonochrome", dirname, filter, this); // IView *iView = new IView(dirname, filter); // iView->show(); // iView->setMiddleMouseMode(mode); QString mainDirName = mainGUI->controller->mainDirName; QString scienceDirName = mainGUI->controller->DT_SCIENCE[0]->subDirName; QString dirName = mainDirName + "/"+scienceDirName; IView *iView = new IView("FITSmonochrome", mainGUI->controller->DT_SCIENCE[0]->myImageList[mainGUI->instData.validChip], dirName, this); iView->scene->clear(); MyImage *it = mainGUI->controller->DT_SCIENCE[0]->myImageList[mainGUI->instData.validChip][0]; iView->loadFromRAM(it, 3); iView->currentId = 0; // IView needs to know the directory name so that it can overlay catalogs iView->show(); iView->setMiddleMouseMode(mode); // iView->raise(); } void ConfDockWidget::on_ARCcatalogComboBox_currentTextChanged(const QString &arg1) { if (arg1.contains("GAIA") || arg1.contains("UCAC5")) ui->gaiaFrame->show(); else ui->gaiaFrame->hide(); } void ConfDockWidget::on_ARCselectimagePushButton_clicked() { QString currentFileName = QFileDialog::getOpenFileName(this, tr("Select astrometrically calibrated image"), QDir::homePath(), tr("Images (*.fits *.fit *.fts *.FIT *.FITS *.FTS);; All (*.*)")); if ( currentFileName.isEmpty() ) return; ui->ARCselectimageLineEdit->setText(currentFileName); } void ConfDockWidget::updateGaiaBulkMotion(const QString &pmRA, const QString &pmDE) { ui->ARCpmRALineEdit->setText(pmRA); ui->ARCpmDECLineEdit->setText(pmDE); } void ConfDockWidget::on_confForwardPushButton_clicked() { int count = ui->confStackedWidget->count(); int current = ui->confStackedWidget->currentIndex(); ui->confBackwardPushButton->setDisabled(false); if (current >= count-2) { ui->confForwardPushButton->setDisabled(true); ui->confBackwardPushButton->setFocus(); } if (current < count-1) ui->confStackedWidget->setCurrentIndex(current+1); updateConfPageLabel(); } void ConfDockWidget::on_confBackwardPushButton_clicked() { int current = ui->confStackedWidget->currentIndex(); ui->confForwardPushButton->setDisabled(false); if (current <= 1) { ui->confBackwardPushButton->setDisabled(true); ui->confForwardPushButton->setFocus(); } if (current > 0) ui->confStackedWidget->setCurrentIndex(current-1); updateConfPageLabel(); } void ConfDockWidget::updateConfPageLabel() { int current = ui->confStackedWidget->currentIndex(); ui->confPageLabel->setText("Page "+QString::number(current+1)+"/9"); ui->parametersDefaultPushButton->setText("Defaults for page "+QString::number(current+1)); } void ConfDockWidget::setupAstrometry() { const QStandardItemModel* astrometryMatchModel = dynamic_cast< QStandardItemModel * >( ui->ASTmatchMethodComboBox->model() ); // Enable / disable matching methods QString anetSolver = findExecutableName("solve-field"); QString anetIndex = findExecutableName("build-astrometry-index"); bool anet = true; if (anetSolver.isEmpty() || anetIndex.isEmpty()) anet = false; astrometryMatchModel->item( 0,0 )->setEnabled( true ); astrometryMatchModel->item( 1,0 )->setEnabled( anet ); astrometryMatchModel->item( 2,0 )->setEnabled( true ); if (!doingInitialLaunch) { ui->ASTmatchMethodComboBox->setCurrentIndex(0); } } void ConfDockWidget::setupXtalkButtonGroups() { norxtalkButtonGroup->addButton(ui->xtalk_nor_2x2ToolButton); norxtalkButtonGroup->addButton(ui->xtalk_nor_1x2ToolButton); norxtalkButtonGroup->addButton(ui->xtalk_nor_2x1ToolButton); norxtalkButtonGroup->setId(ui->xtalk_nor_2x2ToolButton, 0); norxtalkButtonGroup->setId(ui->xtalk_nor_1x2ToolButton, 1); norxtalkButtonGroup->setId(ui->xtalk_nor_2x1ToolButton, 2); ui->xtalk_nor_2x2ToolButton->setChecked(true); rowxtalkButtonGroup->addButton(ui->xtalk_row_2x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_row_1x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_row_2x1ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_2x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_1x2ToolButton); rowxtalkButtonGroup->addButton(ui->xtalk_col_2x1ToolButton); rowxtalkButtonGroup->setId(ui->xtalk_row_2x2ToolButton, 0); rowxtalkButtonGroup->setId(ui->xtalk_row_1x2ToolButton, 1); rowxtalkButtonGroup->setId(ui->xtalk_row_2x1ToolButton, 2); rowxtalkButtonGroup->setId(ui->xtalk_col_2x2ToolButton, 3); rowxtalkButtonGroup->setId(ui->xtalk_col_1x2ToolButton, 4); rowxtalkButtonGroup->setId(ui->xtalk_col_2x1ToolButton, 5); ui->xtalk_row_2x2ToolButton->setChecked(true); } void ConfDockWidget::setupInstrumentComboBox_clicked() { // The structure holding the content of the instrument file // TODO: check if actually needed // initInstrumentData(instrument_dir+instrument_name+".ini"); //if (!readingSettings) { // ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE")); //} // Update some comboboxes ui->skyAreaComboBox->clear(); ui->skyAreaComboBox->addItem("Specific sky area(s)"); if (instrument_nchips == 1) { ui->skyAreaComboBox->addItem("From entire chip"); } else { ui->skyAreaComboBox->addItem("From each chip"); for (int i=1; i<=instrument_nchips; ++i) { QString entry = "From chip "+QString::number(i); ui->skyAreaComboBox->addItem(entry); } } int currentASTmethod = ui->ASTmethodComboBox->currentIndex(); // (de)activate some GUI elements depending on wavelength regime; // the following two lines are needed to (de)activate some elements in a ComboBox const QStandardItemModel* astrom_model = dynamic_cast< QStandardItemModel * >( ui->ASTmethodComboBox->model() ); const QStandardItemModel* mosaictype_model = dynamic_cast< QStandardItemModel * >( ui->ASTmosaictypeComboBox->model() ); const QStandardItemModel* focalplane_model = dynamic_cast< QStandardItemModel * >( ui->ASTfocalplaneComboBox->model() ); const QStandardItemModel* std_model = dynamic_cast< QStandardItemModel * >( ui->APIrefcatComboBox->model() ); if (instrument_nchips == 1) { mosaictype_model->item( 1,0 )->setEnabled( false ); mosaictype_model->item( 2,0 )->setEnabled( false ); mosaictype_model->item( 3,0 )->setEnabled( false ); mosaictype_model->item( 4,0 )->setEnabled( false ); focalplane_model->item( 1,0 )->setEnabled( false ); focalplane_model->item( 2,0 )->setEnabled( false ); if (!doingInitialLaunch) { ui->ASTmosaictypeComboBox->setCurrentIndex(0); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } // Show the option of masking a rectangular region for collapse correction ui->confsubtitleCollapse3Label->show(); ui->confCollapse3Frame->show(); } else { mosaictype_model->item( 1,0 )->setEnabled( true ); mosaictype_model->item( 2,0 )->setEnabled( true ); mosaictype_model->item( 3,0 )->setEnabled( true ); mosaictype_model->item( 4,0 )->setEnabled( true ); focalplane_model->item( 1,0 )->setEnabled( true ); focalplane_model->item( 2,0 )->setEnabled( true ); if (ui->ASTstabilityComboBox->currentText() == "INSTRUMENT") { ui->ASTmosaictypeComboBox->setCurrentIndex(3); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } else if (ui->ASTstabilityComboBox->currentText() == "EXPOSURE") { ui->ASTmosaictypeComboBox->setCurrentIndex(4); ui->ASTfocalplaneComboBox->setCurrentIndex(0); } // Hide the option of masking a rectangular region for collapse correction ui->confsubtitleCollapse3Label->hide(); ui->confCollapse3Frame->hide(); } if (instrument_type == "MIR") { ui->splitMIRcubeCheckBox->show(); ui->confChopnodSpacer->changeSize(1,30); ui->confChopnodFrame->show(); ui->conftitleChopnodLabel->show(); ui->confsubtitleBackground1Label->setDisabled(true); ui->confsubtitleBackground2Label->setDisabled(true); ui->confsubtitleBackground3Label->setDisabled(true); ui->confsubtitleBackground4Label->setDisabled(true); ui->confsubtitleBackground5Label->setDisabled(true); ui->confsubtitleBackground6Label->setDisabled(true); ui->confBackground1Frame->setDisabled(true); ui->confBackground2Frame->setDisabled(true); ui->confBackground3Frame->setDisabled(true); ui->confBackground4Frame->setDisabled(true); ui->confBackground5Frame->setDisabled(true); ui->confBackground6Frame->setDisabled(true); ui->ASTmethodComboBox->setCurrentIndex(2); ui->confAstromphotom1Frame->setDisabled(true); ui->confAstromphotom2Frame->setDisabled(true); ui->confAstromphotom3Frame->setDisabled(true); ui->confAstromphotom4Frame->setDisabled(true); ui->confAstromphotom5Frame->setDisabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( false ); } else if (instrument_type == "NIR") { ui->splitMIRcubeCheckBox->hide(); ui->confChopnodFrame->hide(); ui->conftitleChopnodLabel->hide(); ui->confChopnodSpacer->changeSize(1,0); ui->confsubtitleBackground1Label->setEnabled(true); ui->confsubtitleBackground1Label->show(); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->setEnabled(true); ui->confBackground1Frame->show(); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); // ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( false ); std_model->item( 1,0 )->setEnabled( false ); std_model->item( 2,0 )->setEnabled( false ); std_model->item( 3,0 )->setEnabled( false ); std_model->item( 4,0 )->setEnabled( false ); std_model->item( 5,0 )->setEnabled( false ); std_model->item( 6,0 )->setEnabled( true ); std_model->item( 7,0 )->setEnabled( true ); std_model->item( 8,0 )->setEnabled( true ); std_model->item( 9,0 )->setEnabled( true ); std_model->item( 10,0 )->setEnabled( true ); std_model->item( 11,0 )->setEnabled( true ); } else if (instrument_type == "NIRMIR") { ui->splitMIRcubeCheckBox->show(); ui->confChopnodFrame->show(); ui->conftitleChopnodLabel->show(); ui->confChopnodSpacer->changeSize(1,30); ui->confsubtitleBackground1Label->setEnabled(true); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->setEnabled(true); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setDisabled(true); // ui->confIndividualweight2Frame->setDisabled(true); astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( false ); std_model->item( 1,0 )->setEnabled( false ); std_model->item( 2,0 )->setEnabled( false ); std_model->item( 3,0 )->setEnabled( false ); std_model->item( 4,0 )->setEnabled( false ); std_model->item( 5,0 )->setEnabled( false ); std_model->item( 6,0 )->setEnabled( true ); std_model->item( 7,0 )->setEnabled( true ); std_model->item( 8,0 )->setEnabled( true ); std_model->item( 9,0 )->setEnabled( true ); std_model->item( 10,0 )->setEnabled( true ); std_model->item( 11,0 )->setEnabled( true ); } else if (instrument_type == "OPT" || instrument_type == "") { ui->splitMIRcubeCheckBox->hide(); ui->confChopnodSpacer->changeSize(1,0); ui->confChopnodFrame->hide(); ui->conftitleChopnodLabel->hide(); ui->confsubtitleBackground1Label->hide(); ui->confsubtitleBackground2Label->setEnabled(true); ui->confsubtitleBackground3Label->setEnabled(true); ui->confsubtitleBackground4Label->setEnabled(true); ui->confsubtitleBackground5Label->setEnabled(true); ui->confsubtitleBackground6Label->setEnabled(true); ui->confBackground1Frame->hide(); ui->confBackground2Frame->setEnabled(true); ui->confBackground3Frame->setEnabled(true); ui->confBackground4Frame->setEnabled(true); ui->confBackground5Frame->setEnabled(true); ui->confBackground6Frame->setEnabled(true); if (currentASTmethod < 2) ui->ASTmethodComboBox->setCurrentIndex(currentASTmethod); else ui->ASTmethodComboBox->setCurrentIndex(0); ui->confAstromphotom1Frame->setEnabled(true); ui->confAstromphotom2Frame->setEnabled(true); ui->confAstromphotom3Frame->setEnabled(true); ui->confAstromphotom4Frame->setEnabled(true); ui->confAstromphotom5Frame->setEnabled(true); ui->CIWmaskbloomingCheckBox->setEnabled(true); ui->confIndividualweight2Frame->setEnabled(true); // The following line triggers repaintDataDirs. Why? astrom_model->item( 0,0 )->setEnabled( true ); std_model->item( 0,0 )->setEnabled( true ); std_model->item( 1,0 )->setEnabled( true ); std_model->item( 2,0 )->setEnabled( true ); std_model->item( 3,0 )->setEnabled( true ); std_model->item( 4,0 )->setEnabled( true ); std_model->item( 5,0 )->setEnabled( true ); std_model->item( 6,0 )->setEnabled( false ); std_model->item( 7,0 )->setEnabled( false ); std_model->item( 8,0 )->setEnabled( false ); std_model->item( 9,0 )->setEnabled( false ); std_model->item( 10,0 )->setEnabled( false ); std_model->item( 11,0 )->setEnabled( false ); } load_default_stdcat(); // Update settings // TODO: make sure this does not happen in parallel to the same task in MainWindow // MUST UNCOMMENT // writeGUISettings(); } void ConfDockWidget::updateAPIsolutions() { QString standard = getNthWord(mainGUI->ui->setupStandardLineEdit->text(),1); QDir standardDir = QDir(mainGUI->ui->setupMainLineEdit->text()+"/"+standard+"/calib/"); QStringList filter("night*.dat"); QStringList solutionList = standardDir.entryList(filter); if (solutionList.isEmpty()) ui->APInodataLabel->show(); else ui->APInodataLabel->hide(); int numNights = solutionList.length(); int i=0; for (auto &it : APIstdPushButtonList) { if (i<numNights) { QString buttonText = solutionList.at(i); buttonText = buttonText.remove(".dat"); it->setText("Show "+buttonText); it->show(); } else { it->hide(); } ++i; } i=0; for (auto &it : APIstdComboBoxList) { if (i<numNights) it->show(); else it->hide(); ++i; } } // Not yet implemented void ConfDockWidget::showAPIsolution() { // QString standard = getNthWord(mainGUI->ui->setupStandardLineEdit->text(),1); // QPushButton* pushbutton = qobject_cast<QPushButton*>(sender()); // QString solutionPlotPath = mainGUI->ui->setupMainLineEdit->text()+"/"+standard+"/calib/"; // launchViewer(solutionPlotPath, pushbutton->text()+"_result.png", ""); // probably have to define a new IView mode for this } void ConfDockWidget::on_ASTreadmepushButton_clicked() { scampreadme = new ScampReadme(this); scampreadme->show(); } bool ConfDockWidget::checkRightScampMode(const QString &coordsMode) { if (coordsMode != "execute") return true; if (instrument_nchips == 1) return true; if (ui->ASTmosaictypeComboBox->currentText() == "UNCHANGED" || (ui->ASTmosaictypeComboBox->currentText() == "FIX_FOCALPLANE" && ui->ASTfocalplaneComboBox->currentText() != "IGNORE_PRIOR")) { QMessageBox msgBox; msgBox.setText("Likely inconsistent Scamp setup:\n'MOSAIC_TYPE = UNCHANGED' or\n" "'MOSAIC_TYPE = FIX_FOCALPLANE' and 'FPA mode = IGNORE_PRIOR'"); msgBox.setInformativeText("Relative chip orientations as encoded by the reference pixels and CD matrix " "may vary over short or long time scales. The best way is to re-measure the " "relative orientations from the data themselves. Five well-dithered exposures " "are usually sufficient, in particular if calibrated against GAIA. To do this, use\n\n" "'MOSAIC_TYPE = FIX_FOCALPLANE' and 'FPA mode = IGNORE_PRIOR'. \n\n" "If that doesn't work, try \n\n" "'MOSAIC_TYPE = LOOSE' and 'FPA mode = IGNORE_PRIOR'.\n\n" "If that does not work, try using the pre-determined focal plane array (FPA):\n\n " "'MOSAIC_TYPE = SAME_CRVAL' and 'FPA mode = USE_PRIOR'.\n\n"); QAbstractButton* pButtonContinue = msgBox.addButton(tr("Continue as is"), QMessageBox::YesRole); QAbstractButton* pButtonDetails = msgBox.addButton(tr("Details [...]"), QMessageBox::YesRole); QAbstractButton* pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton()==pButtonContinue) return true; else if (msgBox.clickedButton()==pButtonDetails) { scampreadme = new ScampReadme(this); scampreadme->show(); return false; } else if (msgBox.clickedButton()==pButtonCancel) { return false; } } else return true; return true; } void ConfDockWidget::on_nonlinearityCheckBox_clicked() { if (!ui->nonlinearityCheckBox->isChecked()) return; QString coeffsFileName = instrument_dir+"/"+instrument_name+".nldat"; QFile coeffsFile(coeffsFileName); if (!coeffsFile.exists() || !coeffsFile.open(QIODevice::ReadOnly)) { QMessageBox msgBox; msgBox.setText("Nonlinearity correction for "+instrument_name+" is not implemented.\n" +"Contact the author if you have the polynomial correction coefficients available."); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); ui->nonlinearityCheckBox->setChecked(false); } } void ConfDockWidget::on_ASTviewCheckPlotsPushButton_clicked() { Data *scienceData = nullptr; if (mainGUI->controller->DT_SCIENCE.length() == 1) { scienceData = mainGUI->controller->DT_SCIENCE.at(0); } else if (mainGUI->controller->DT_SCIENCE.length() == 0) { QMessageBox::information(this, tr("Missing data"), tr("No SCIENCE data were specified in the data tree.\n"), QMessageBox::Ok); return; } // See if any checkplots exist bool checkPlotsExist = false; for (auto &data : mainGUI->controller->DT_SCIENCE) { QDir plotsDir = data->dirName+"/plots/"; if (plotsDir.exists()) checkPlotsExist = true; } if (checkPlotsExist) { if (mainGUI->controller->DT_SCIENCE.length() > 1) { QMessageBox msgBox; msgBox.setInformativeText(tr("The current SCIENCE data tree contains several entries for which astrometry check plots exist.\n") + tr("Display the plots for:\n\n")); for (auto &data : mainGUI->controller->DT_SCIENCE) { QDir plotsDir = data->dirName+"/plots/"; if (plotsDir.exists()) msgBox.addButton(data->subDirName, QMessageBox::YesRole); } QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole); msgBox.exec(); QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a KDE fix if (msgBox.clickedButton()== pCancel) return; for (auto &data : mainGUI->controller->DT_SCIENCE) { if (data->subDirName == choice) { scienceData = data; break; } } } IView *checkplotViewer = new IView("SCAMP_VIEWONLY", scienceData->dirName+"/plots/", this); checkplotViewer->show(); } else { QMessageBox msgBox; msgBox.setInformativeText(tr("Could not find astrometric check plots in any of the science directories.\n") + tr("You must run the astrometry first.\n")); msgBox.addButton(tr("OK"), QMessageBox::YesRole); msgBox.exec(); } } void ConfDockWidget::update_COA_uniqueID() { QString uniqueID = ""; QString chipID = ui->COAchipsLineEdit->text().simplified(); QString minMJD = ui->COAminMJDOBSLineEdit->text().simplified(); QString maxMJD = ui->COAmaxMJDOBSLineEdit->text().simplified(); chipID.replace(",","-"); chipID.replace(" ","-"); chipID.replace("--","-"); bool added = false; if (!chipID.isEmpty()) { chipID = "chip-"+chipID; uniqueID.append(chipID); added = true; } if (!minMJD.isEmpty()) { minMJD = "min"+minMJD; if (added) uniqueID.append("_"+minMJD); else uniqueID.append(minMJD); added = true; } if (!maxMJD.isEmpty()) { maxMJD = "max"+maxMJD; if (added) uniqueID.append("_"+maxMJD); else uniqueID.append(maxMJD); } ui->COAuniqueidLineEdit->setText(uniqueID); }
57,499
C++
.cc
1,175
42.026383
185
0.691237
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,440
validate_confdock.cc
schirmermischa_THELI/src/dockwidgets/validate_confdock.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "confdockwidget.h" #include "ui_confdockwidget.h" #include <QValidator> #include <QRegExpValidator> void ConfDockWidget::validate() { QRegExp ri( "^[0-9]+" ); QRegExp ricomma( "^[0-9,]+" ); QRegExp ricommablank( "^[0-9,\\s]+" ); QRegExp rint( "^[-]{0,1}[0-9]+" ); QRegExp rx( "^\\S+$" ); QRegExp RA( "[0-9.:]+" ); QRegExp DEC( "^[-]{0,1}[0-9.:]+" ); QRegExp rx3( "^[A-Z0-9a-z-+._,:]+$" ); QRegExp rx4( "^[A-Z0-9a-z-+_]+$" ); QRegExp rx5( "^[A-Z0-9a-z-+._, ]+$" ); QRegExp rf( "^[-]{0,1}[0-9]*[.]{0,1}[0-9]+" ); QRegExp rf2( "^[0-9]*[.]{0,1}[0-9]+" ); QValidator* validator_int_pos = new QRegExpValidator( ri, this ); QValidator* validator_int_pos_comma = new QRegExpValidator( ricomma, this ); QValidator* validator_int_pos_comma_blank = new QRegExpValidator( ricommablank, this ); QValidator* validator_int = new QRegExpValidator( rint, this ); QValidator* validator_string = new QRegExpValidator( rx, this ); QValidator* validator_ra = new QRegExpValidator( RA, this ); QValidator* validator_dec = new QRegExpValidator( DEC, this ); QValidator* validator_string3 = new QRegExpValidator( rx3, this ); QValidator* validator_headerkeyword = new QRegExpValidator( rx4, this ); QValidator* validator_stringdir = new QRegExpValidator( rx5, this ); QValidator* validator_float = new QRegExpValidator(rf, this ); QValidator* validator_float_pos = new QRegExpValidator(rf2, this ); ui->APDmaxphoterrorLineEdit->setValidator( validator_float_pos ); ui->APIWCSLineEdit->setValidator( validator_float_pos ); ui->APIapertureLineEdit->setValidator( validator_int_pos ); ui->APIcolortermLineEdit->setValidator( validator_float ); ui->APIconvergenceLineEdit->setValidator( validator_float_pos ); ui->APIextinctionLineEdit->setValidator( validator_float ); ui->APIfilterkeywordLineEdit->setValidator( validator_string ); ui->APIkappaLineEdit->setValidator( validator_float_pos ); ui->APIminmagLineEdit->setValidator( validator_float_pos ); ui->APIthresholdLineEdit->setValidator( validator_float_pos ); ui->APIzpmaxLineEdit->setValidator( validator_float_pos ); ui->APIzpminLineEdit->setValidator( validator_float_pos ); ui->ARCdecLineEdit->setValidator( validator_dec ); ui->ARCmaxpmLineEdit->setValidator( validator_float_pos ); ui->ARCminmagLineEdit->setValidator( validator_float_pos ); ui->ARCraLineEdit->setValidator( validator_ra ); ui->ARCradiusLineEdit->setValidator( validator_float_pos ); ui->ARCselectimageLineEdit->setValidator( validator_string ); ui->ARCtargetresolverLineEdit->setValidator( validator_stringdir ); ui->ASTastrefweightLineEdit->setValidator( validator_float_pos ); ui->ASTastrinstrukeyLineEdit->setValidator( validator_headerkeyword ); ui->ASTcrossidLineEdit->setValidator( validator_float_pos ); ui->ASTdistortLineEdit->setValidator( validator_int_pos ); ui->ASTdistortgroupsLineEdit->setValidator( validator_int_pos_comma ); ui->ASTdistortkeysLineEdit->setValidator( validator_string3 ); ui->ASTphotinstrukeyLineEdit->setValidator( validator_headerkeyword ); ui->ASTpixscaleLineEdit->setValidator( validator_float_pos ); ui->ASTposangleLineEdit->setValidator( validator_float_pos ); ui->ASTpositionLineEdit->setValidator( validator_float_pos ); ui->ASTresolutionLineEdit->setValidator( validator_int_pos ); ui->ASTsnthreshLineEdit->setValidator( validator_int_pos_comma ); ui->ASTxcorrDMINLineEdit->setValidator( validator_int_pos ); ui->ASTxcorrDTLineEdit->setValidator( validator_float_pos ); ui->BAC1nhighLineEdit->setValidator( validator_int_pos ); ui->BAC1nlowLineEdit->setValidator( validator_int_pos); ui->BAC2nhighLineEdit->setValidator( validator_int_pos ); ui->BAC2nlowLineEdit->setValidator( validator_int_pos ); ui->BACDMINLineEdit->setValidator( validator_int_pos ); ui->BACDTLineEdit->setValidator( validator_float_pos); ui->BACbacksmoothscaleLineEdit->setValidator( validator_int_pos ); ui->BACdistLineEdit->setValidator( validator_float_pos ); ui->BACgapsizeLineEdit->setValidator( validator_float_pos); ui->BACmagLineEdit->setValidator( validator_float_pos ); ui->BACmefLineEdit->setValidator( validator_float_pos ); ui->BACwindowLineEdit->setValidator( validator_int_pos ); ui->BACminWindowLineEdit->setValidator( validator_int_pos ); ui->CGWbackclustolLineEdit->setValidator( validator_float_pos); ui->CGWbackcoltolLineEdit->setValidator( validator_float_pos ); ui->CGWbackrowtolLineEdit->setValidator( validator_float_pos); ui->CGWbacksmoothLineEdit->setValidator( validator_float_pos ); ui->CGWbackmaxLineEdit->setValidator( validator_float_pos ); ui->CGWbackminLineEdit->setValidator( validator_float_pos ); ui->CGWdarkmaxLineEdit->setValidator( validator_int ); ui->CGWdarkminLineEdit->setValidator( validator_int ); ui->CGWflatclustolLineEdit->setValidator( validator_float_pos ); ui->CGWflatcoltolLineEdit->setValidator( validator_float_pos ); ui->CGWflatmaxLineEdit->setValidator( validator_float_pos ); ui->CGWflatminLineEdit->setValidator( validator_float_pos ); ui->CGWflatrowtolLineEdit->setValidator( validator_float_pos ); ui->CGWflatsmoothLineEdit->setValidator( validator_float_pos ); ui->CIWsaturationLineEdit->setValidator( validator_float_pos ); ui->CIWbloomRangeLineEdit->setValidator( validator_int_pos ); ui->CIWbloomMinaduLineEdit->setValidator( validator_int_pos ); ui->CIWaggressivenessLineEdit->setValidator( validator_float_pos ); ui->CIWmaxaduLineEdit->setValidator( validator_int ); ui->CIWminaduLineEdit->setValidator( validator_int ); ui->COAchipsLineEdit->setValidator( validator_int_pos_comma_blank ); ui->COAdecLineEdit->setValidator( validator_dec ); ui->COAedgesmoothingLineEdit->setValidator( validator_int_pos ); ui->COAoutborderLineEdit->setValidator( validator_int_pos ); ui->COAoutsizeLineEdit->setValidator( validator_int_pos ); ui->COAoutthreshLineEdit->setValidator( validator_float_pos ); ui->COApixscaleLineEdit->setValidator( validator_float_pos ); ui->COApmdecLineEdit->setValidator( validator_float ); ui->COApmraLineEdit->setValidator( validator_float ); ui->COAraLineEdit->setValidator( validator_ra ); ui->COAminMJDOBSLineEdit->setValidator( validator_float_pos ); ui->COAmaxMJDOBSLineEdit->setValidator( validator_float_pos ); ui->COAsizexLineEdit->setValidator( validator_int_pos ); ui->COAsizeyLineEdit->setValidator( validator_int_pos ); ui->COAskypaLineEdit->setValidator( validator_float ); ui->COAuniqueidLineEdit->setValidator( validator_string ); ui->COCDMINLineEdit->setValidator( validator_int_pos ); ui->COCDTLineEdit->setValidator( validator_float_pos ); ui->COCmefLineEdit->setValidator( validator_float_pos ); ui->COCrejectLineEdit->setValidator( validator_float_pos ); ui->COCxmaxLineEdit->setValidator( validator_int_pos ); ui->COCxminLineEdit->setValidator( validator_int_pos ); ui->COCymaxLineEdit->setValidator( validator_int_pos ); ui->COCyminLineEdit->setValidator( validator_int_pos ); ui->CSCDMINLineEdit->setValidator( validator_int_pos ); ui->CSCDTLineEdit->setValidator( validator_float_pos ); ui->CSCFWHMLineEdit->setValidator( validator_float_pos ); ui->CSCbackgroundLineEdit->setValidator( validator_float ); ui->CSCmaxflagLineEdit->setValidator( validator_int_pos ); ui->CSCmaxellLineEdit->setValidator( validator_float_pos ); ui->CSCmincontLineEdit->setValidator( validator_float_pos ); ui->CSCrejectExposureLineEdit->setValidator( validator_int_pos ); ui->CSCsaturationLineEdit->setValidator( validator_int_pos ); ui->SPSlengthLineEdit->setValidator( validator_int_pos ); ui->SPSexcludeLineEdit->setValidator( validator_int_pos ); ui->SPSnumbergroupsLineEdit->setValidator( validator_int_pos ); ui->biasMaxLineEdit->setValidator( validator_int_pos ); ui->biasMinLineEdit->setValidator( validator_int_pos ); ui->biasNhighLineEdit->setValidator( validator_int_pos ); ui->biasNlowLineEdit->setValidator( validator_int_pos ); ui->darkMaxLineEdit->setValidator( validator_int_pos ); ui->darkMinLineEdit->setValidator( validator_int_pos ); ui->darkNhighLineEdit->setValidator( validator_int_pos ); ui->darkNlowLineEdit->setValidator( validator_int_pos ); ui->excludeDetectorsLineEdit->setValidator( validator_int_pos_comma_blank ); ui->flatoffMaxLineEdit->setValidator( validator_int_pos ); ui->flatoffMinLineEdit->setValidator( validator_int_pos ); ui->flatoffNhighLineEdit->setValidator( validator_int_pos ); ui->flatoffNlowLineEdit->setValidator( validator_int_pos ); ui->flatMaxLineEdit->setValidator( validator_int_pos ); ui->flatMinLineEdit->setValidator( validator_int_pos ); ui->flatNhighLineEdit->setValidator( validator_int_pos ); ui->flatNlowLineEdit->setValidator( validator_int_pos ); ui->normalxtalkAmplitudeLineEdit->setValidator( validator_float ); ui->rowxtalkAmplitudeLineEdit->setValidator( validator_float ); ui->saturationLineEdit->setValidator( validator_int_pos ); ui->separateTargetLineEdit->setValidator( validator_float_pos ); ui->skyDMINLineEdit->setValidator( validator_int_pos ); ui->skyDTLineEdit->setValidator( validator_float_pos ); ui->skyKernelLineEdit->setValidator( validator_int_pos ); ui->skyMefLineEdit->setValidator( validator_float_pos ); } void ConfDockWidget::connect_validators() { connect(ui->APDmaxphoterrorLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIWCSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIapertureLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIcolortermLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIconvergenceLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIextinctionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIfilterkeywordLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIkappaLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIminmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIthresholdLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIzpmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->APIzpminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCminmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCradiusLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCselectimageLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ARCtargetresolverLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTastrefweightLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTastrinstrukeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTcrossidLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortgroupsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTdistortkeysLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTphotinstrukeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTpixscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTposangleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTpositionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTresolutionLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->ASTsnthreshLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC1nhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC1nlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC2nhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BAC2nlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACbacksmoothscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACdistLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACgapsizeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACmagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACmefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACwindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->BACminWindowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackclustolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackcoltolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackrowtolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbacksmoothLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWbackminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWdarkmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWdarkminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatclustolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatcoltolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatrowtolLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CGWflatsmoothLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWbloomRangeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWsaturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWbloomMinaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWaggressivenessLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWmaxaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CIWminaduLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAchipsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAedgesmoothingLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutborderLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutsizeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAoutthreshLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApixscaleLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApmdecLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COApmraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAraLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAminMJDOBSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAmaxMJDOBSLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAsizexLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAsizeyLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAskypaLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COAuniqueidLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCmefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCrejectLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCxmaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCxminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCymaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->COCyminLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCFWHMLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCbackgroundLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCmaxflagLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCmaxellLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCmincontLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCrejectExposureLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->CSCsaturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSlengthLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSexcludeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->SPSnumbergroupsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->biasNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->darkNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->excludeDetectorsLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatoffNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatMaxLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatMinLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatNhighLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->flatNlowLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->normalxtalkAmplitudeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->rowxtalkAmplitudeLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->saturationLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->separateTargetLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyDMINLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyDTLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyKernelLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); connect(ui->skyMefLineEdit, &QLineEdit::textChanged, this, &ConfDockWidget::validate); }
22,153
C++
.cc
299
69.381271
104
0.764706
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,441
imagestatistics_events.cc
schirmermischa_THELI/src/imagestatistics/imagestatistics_events.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include <QVector> #include <QList> #include <QStringList> // Controls what happens when a key is pressed void ImageStatistics::keyReleaseEvent(QKeyEvent *event) { // 'delete' key: park selected images from one chip in inactive/badStatistics/ // 'a' key: park selected images (including all chips from that exposure) in inactive/badStatistics/ // Left / right key: move selection forward / backward if (!ui->statPlot->hasFocus()) return; if (event->key() != Qt::Key_Delete && event->key() != Qt::Key_A && event->key() != Qt::Key_Left && event->key() != Qt::Key_Right) return; if (selection.isEmpty()) return; if (!scienceDir.exists()) return; QVector<int> badIndexes; if (event->key() == Qt::Key_Delete || event->key() == Qt::Key_A) { // make a "badStatistics" sub-directory QString badStatsDirName = scienceDirName+"/inactive/badStatistics/"; QDir badStatsDir(badStatsDirName); badStatsDir.mkpath(badStatsDirName); // move selected images to inactive/badStatistics/ foreach (QCPDataRange dataRange, selection.dataRanges()) { // QCPGraphDataContainer::const_iterator itBegin = seeingGraph->data()->at(dataRange.begin()); // QCPGraphDataContainer::const_iterator itEnd = seeingGraph->data()->at(dataRange.end()); int begin = dataRange.begin(); int end = dataRange.end(); for (int i=begin; i<end; ++i) { badIndexes.append(i); imgSelectedName = dataName[i]; // 'Delete' key pressed (actually: released) // Deactivate selected *image* if (event->key() == Qt::Key_Delete) { // Add selected image to list of bad images if (!badStatsList.contains(imgSelectedName)) { badStatsList << imgSelectedName; } // Deactivate selected image // allMyImages[i]->setActiveState(MyImage::BADSTATS); // deactivate // emit allMyImages[i]->modelUpdateNeeded(allMyImages[i]->chipName); filteredMyImages[i]->setActiveState(MyImage::BADSTATS); // deactivate emit filteredMyImages[i]->modelUpdateNeeded(filteredMyImages[i]->chipName); } // 'A' key pressed // Deactivate selected *exposure* (all chips belonging to that exposure) if (event->key() == Qt::Key_A) { QString base = removeLastWords(imgSelectedName, 1, '_'); QStringList baseFilter(base+"_*.fits"); QStringList baseList = scienceDir.entryList(baseFilter); // List of all images belonging to that exposure for (auto &it : baseList) { if (!badStatsList.contains(it)) { badStatsList << it; } } for (auto &myimg : allMyImages) { // for (auto &myimg : filteredMyImages) { if (imgSelectedName.contains(myimg->rootName)) { myimg->setActiveState(MyImage::BADSTATS); // deactivate emit myimg->modelUpdateNeeded(myimg->chipName); } } } } } dataImageNr = removeVectorItems_T(dataImageNr, badIndexes); dataSky = removeVectorItems_T(dataSky, badIndexes); dataAirmass = removeVectorItems_T(dataAirmass, badIndexes); dataFWHM = removeVectorItems_T(dataFWHM, badIndexes); dataRZP = removeVectorItems_T(dataRZP, badIndexes); dataEllipticity = removeVectorItems_T(dataEllipticity, badIndexes); numObj = dataSky.length(); clearSelection(); readStatisticsData(); plot(); if (iViewOpen) iView->clearAll(); } // Cycle the selection forth or back by one or more data points, // depending on previous click types if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) { if (lastDataPointClicked == -1) return; int currentDataPoint; if (initKeySelection) { clearSelection(); initKeySelection = false; } if (event->key() == Qt::Key_Left) { if (lastDataPointClicked <= 0) return; currentDataPoint = lastDataPointClicked-1; if (lastKeyPressed == Qt::Key_Right) directionSwitched = "RightToLeft"; else directionSwitched = "noSwitch"; lastKeyPressed = Qt::Key_Left; } else if (event->key() == Qt::Key_Right) { if (lastDataPointClicked >= numObj-1) return; currentDataPoint = lastDataPointClicked+1; if (lastKeyPressed == Qt::Key_Left) directionSwitched = "LeftToRight"; else directionSwitched = "noSwitch"; lastKeyPressed = Qt::Key_Right; } else { // middle mouse click etc return; } lastDataPointClicked = currentDataPoint; QCPDataRange rangeSelected; if (directionSwitched == "noSwitch") { rangeSelected.setBegin(currentDataPoint); rangeSelected.setEnd(currentDataPoint+1); } if (directionSwitched == "RightToLeft") { rangeSelected.setBegin(currentDataPoint); rangeSelected.setEnd(currentDataPoint+2); } if (directionSwitched == "LeftToRight") { rangeSelected.setBegin(currentDataPoint-1); rangeSelected.setEnd(currentDataPoint+1); } QCPDataSelection dpClicked; dpClicked.addDataRange(rangeSelected); // Previously right click: add (or remove) previous or next data point to selection if (lastButtonClicked == Qt::RightButton) { if (!selection.contains(dpClicked)) selection.operator +=(rangeSelected); else selection.operator -=(rangeSelected); } // Previously left click: select previous or next data point if (lastButtonClicked == Qt::LeftButton) { clearSelection(); selection = dpClicked; } selection.simplify(); plotSelection(currentDataPoint); highlightClickedDataPoint(); // Reflect the image in iView if (iViewOpen) { imgSelectedName = dataName[currentDataPoint]; if (!selection.isEmpty()) { emit imageSelected(lastDataPointClicked); } else { if (iViewOpen) iView->clearAll(); imgSelected = false; lastDataPointClicked = -1; } } } }
7,668
C++
.cc
166
35.457831
130
0.601523
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,442
imagestatistics_plotting.cc
schirmermischa_THELI/src/imagestatistics/imagestatistics_plotting.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../instrumentdata.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include "../myimage/myimage.h" #include <QSettings> #include <QValidator> #include <QTest> #include <QVector> #include <QList> #include <QStringList> #include <QRegExpValidator> void ImageStatistics::plot() { if (numObj == 0) { ui->statPlot->replot(); ui->statPlot->update(); } ui->statPlot->clearItems(); ui->statPlot->clearGraphs(); ui->statPlot->plotLayout()->clear(); // create a sub layout that we'll place in first row: QCPLayoutGrid *subLayout = new QCPLayoutGrid(); ui->statPlot->plotLayout()->addElement(0, 0, subLayout); QCPAxisRect *rectSky = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectSeeing = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectRZP = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectAirmass = new QCPAxisRect(ui->statPlot); QCPAxisRect *rectEllipticity = new QCPAxisRect(ui->statPlot); // rectSeeing->axis(QCPAxis::atRight)->setVisible(false); QList< QCPAxisRect* > rectList; rectList << rectSky << rectSeeing << rectRZP << rectAirmass << rectEllipticity; for (auto &it : rectList) { foreach (QCPAxis *axis, it->axes()) { axis->setLayer("axes"); axis->grid()->setLayer("grid"); } it->setupFullAxesBox(true); it->axis(QCPAxis::atBottom)->setLabel("Image #"); } rectSky->axis(QCPAxis::atLeft)->setLabel("Background [ e- ]"); rectAirmass->axis(QCPAxis::atLeft)->setLabel("Airmass"); rectAirmass->axis(QCPAxis::atLeft)->setRangeReversed(true); QString unit = ui->fwhmunitsComboBox->currentText(); if (seeingFromGaia || !seeingData) rectSeeing->axis(QCPAxis::atLeft)->setLabel("Stellar FWHM [ "+unit+" ]"); else rectSeeing->axis(QCPAxis::atLeft)->setLabel("Median FWHM [ "+unit+" ]"); // rectSeeing->addAxis(QCPAxis::atRight)->setLabel("Seeing [ pixel ]"); // QCPAxis *seeingPixelAxis = rectSeeing->axis(QCPAxis::atRight); rectRZP->axis(QCPAxis::atLeft)->setLabel("Relative zeropoint [ mag ]"); if (seeingFromGaia || !ellipticityData) rectEllipticity->axis(QCPAxis::atLeft)->setLabel("Stellar ellipticity [ % ]"); else rectEllipticity->axis(QCPAxis::atLeft)->setLabel("Median ellipticity [ % ]"); subLayout->addElement(0, 0, rectSky); subLayout->addElement(0, 1, rectAirmass); subLayout->addElement(0, 2, rectSeeing); subLayout->addElement(1, 0, rectRZP); subLayout->addElement(1, 1, rectEllipticity); // The graphs graphList.clear(); graphListIview.clear(); skyGraph = ui->statPlot->addGraph(rectSky->axis(QCPAxis::atBottom), rectSky->axis(QCPAxis::atLeft)); seeingGraph = ui->statPlot->addGraph(rectSeeing->axis(QCPAxis::atBottom), rectSeeing->axis(QCPAxis::atLeft)); airmassGraph = ui->statPlot->addGraph(rectAirmass->axis(QCPAxis::atBottom), rectAirmass->axis(QCPAxis::atLeft)); rzpGraph = ui->statPlot->addGraph(rectRZP->axis(QCPAxis::atBottom), rectRZP->axis(QCPAxis::atLeft)); ellipticityGraph = ui->statPlot->addGraph(rectEllipticity->axis(QCPAxis::atBottom), rectEllipticity->axis(QCPAxis::atLeft)); skyGraphIview = ui->statPlot->addGraph(rectSky->axis(QCPAxis::atBottom), rectSky->axis(QCPAxis::atLeft)); seeingGraphIview = ui->statPlot->addGraph(rectSeeing->axis(QCPAxis::atBottom), rectSeeing->axis(QCPAxis::atLeft)); airmassGraphIview = ui->statPlot->addGraph(rectAirmass->axis(QCPAxis::atBottom), rectAirmass->axis(QCPAxis::atLeft)); rzpGraphIview = ui->statPlot->addGraph(rectRZP->axis(QCPAxis::atBottom), rectRZP->axis(QCPAxis::atLeft)); ellipticityGraphIview = ui->statPlot->addGraph(rectEllipticity->axis(QCPAxis::atBottom), rectEllipticity->axis(QCPAxis::atLeft)); graphList << skyGraph << seeingGraph << airmassGraph << rzpGraph << ellipticityGraph; graphListIview << skyGraphIview << seeingGraphIview << airmassGraphIview<< rzpGraphIview << ellipticityGraphIview; // Leave here if we are just initializing the plot panels if (numObj == 0) return; QCPSelectionDecorator *decoratorSky = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorRZP = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorAirmass = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorSeeing = new QCPSelectionDecorator(); QCPSelectionDecorator *decoratorEllipticity = new QCPSelectionDecorator(); // change the last argument to a larger number if you want bigger data points QCPScatterStyle scatterstyle(QCPScatterStyle::ScatterShape::ssDisc, QColor("#ff3300"), QColor("#ff3300"), 6); decoratorSky->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorRZP->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorSeeing->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorAirmass->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); decoratorEllipticity->setScatterStyle(scatterstyle, QCPScatterStyle::spAll); double xmin = minVec_T(dataImageNr); double xmax = maxVec_T(dataImageNr); double dx = (xmax - xmin) * 0.05; QVector<double> dataPtr; for (auto &it : graphList) { it->setSelectable(QCP::stMultipleDataRanges); it->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, QPen(Qt::blue), QBrush(Qt::blue), 6)); it->setLineStyle(myLineStyle); if (it == skyGraph) { dataPtr = dataSky; it->setSelectionDecorator(decoratorSky); it->setData(dataImageNr, dataPtr); } else if (it == seeingGraph) { float unitsRescale = 1.0; if (ui->fwhmunitsComboBox->currentText() == "arcsec") unitsRescale = 1.0; else unitsRescale = instData->pixscale; dataPtr = dataFWHM; for (auto &it : dataPtr) it /= unitsRescale; it->setSelectionDecorator(decoratorSeeing); // if (seeingData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 0.50, 1.80); // } } else if (it == airmassGraph) { dataPtr = dataAirmass; it->setSelectionDecorator(decoratorAirmass); // if (airmassData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 1.80, 0.50); // } } else if (it == rzpGraph) { dataPtr = dataRZP; it->setSelectionDecorator(decoratorRZP); // if (rzpData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 1.8, 1.8); // } } else if (it == ellipticityGraph) { dataPtr = dataEllipticity; it->setSelectionDecorator(decoratorEllipticity); // if (ellipticityData) it->setData(dataImageNr, dataPtr); // else { // showNoData(it, 2.0, 2.0); // } } double ymin = minVec_T(dataPtr); double ymax = maxVec_T(dataPtr); double dy = (ymax - ymin) * 0.05; it->keyAxis()->setRange(xmin-dx, xmax+dx); it->valueAxis()->setRange(ymin-dy, ymax+dy); } ui->statPlot->replot(); ui->statPlot->update(); if (numObj > 0) statisticsDataDisplayed = true; else statisticsDataDisplayed = false; } void ImageStatistics::highlightClickedDataPoint() { if (lastDataPointClicked == -1) return; for (auto &it : graphListIview) { int ldpc = lastDataPointClicked; QVector<double> x; QVector<double> y; x << dataImageNr[ldpc]; it->setSelectable(QCP::SelectionType::stNone); it->setLineStyle(QCPGraph::lsNone); it->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QColor("#000000"), 12)); if (it == skyGraphIview) { y << dataSky[ldpc]; it->setData(x,y); } else if (it == seeingGraphIview) { float unitsRescale = 1.0; if (ui->fwhmunitsComboBox->currentText() == "arcsec") unitsRescale = 1.0; else unitsRescale = instData->pixscale; y << dataFWHM[ldpc]; for (auto &it : y) it /= unitsRescale; it->setData(x,y); } else if (it == airmassGraphIview) { y << dataAirmass[ldpc]; it->setData(x,y); } else if (it == rzpGraphIview) { y << dataRZP[ldpc]; it->setData(x,y); } else if (it == ellipticityGraphIview) { y << dataEllipticity[ldpc]; it->setData(x,y); } } ui->statPlot->replot(); ui->statPlot->update(); } /* void ImageStatistics::showNoData(QCPGraph *graph, float xpos, float ypos) { QCPItemText *noData = new QCPItemText(ui->statPlot); noData->position->setType(QCPItemPosition::ptAxisRectRatio); noData->setPositionAlignment(Qt::AlignLeft|Qt::AlignCenter); noData->position->setCoords(xpos, ypos); noData->setClipToAxisRect(false); noData->setSelectable(false); noData->setText("no data"); noData->setTextAlignment(Qt::AlignLeft); noData->setFont(QFont(font().family(), 9)); noData->setPadding(QMargins(4, 0, 4, 0)); noData->setPen(QPen(Qt::black)); } */ void ImageStatistics::plotSelection(int index) { for (auto &it : graphList) { it->setSelection(selection); } ui->statPlot->replot(); ui->statPlot->update(); } void ImageStatistics::dataPointClicked(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event) { // Clicking on a data point may select or deselect it imgSelectedName = dataName[dataIndex]; imgSelected = true; lastDataPointClicked = dataIndex; // We build the selection by successively clicking into different graphs. // Last index points to point above data range, hence must be +1 to select single data point; QCPDataRange rangeSelected(dataIndex, dataIndex+1); QCPDataSelection dpClicked; dpClicked.addDataRange(rangeSelected); // Right click: // Include/exclude a data point in the selection. // Multiple data points can be selected (we accumulate them in 'selection') if (event->button() == Qt::RightButton) { initKeySelection = true; if (!selection.contains(dpClicked)) selection.operator +=(rangeSelected); else selection.operator -=(rangeSelected); } // Left click: single selection/deselection only if (event->button() == Qt::LeftButton) { if (!selection.contains(dpClicked)) selection = dpClicked; else clearSelection(); } lastButtonClicked = event->button(); selection.simplify(); plotSelection(dataIndex); highlightClickedDataPoint(); // ui->statPlot->setStatusTip(imgSelectedName); if (!selection.isEmpty()) { emit imageSelected(lastDataPointClicked); } else { if (iViewOpen) iView->clearAll(); imgSelected = false; lastDataPointClicked = -1; } } void ImageStatistics::on_invertSelectionPushButton_clicked() { QCPDataRange outerRange(0, numObj); selection = selection.inverse(outerRange); plotSelection(0); } void ImageStatistics::numericSelection() { if (numObj == 0) return; numSelection.clear(); QVector<int> numericIndexes; QString skyMin = ui->skyMinLineEdit->text(); QString skyMax = ui->skyMaxLineEdit->text(); QString airmassMin = ui->airmassMinLineEdit->text(); QString airmassMax = ui->airmassMaxLineEdit->text(); QString seeingMin = ui->seeingMinLineEdit->text(); QString seeingMax = ui->seeingMaxLineEdit->text(); QString rzpMin = ui->rzpMinLineEdit->text(); QString rzpMax = ui->rzpMaxLineEdit->text(); QString ellMin = ui->ellMinLineEdit->text(); QString ellMax = ui->ellMaxLineEdit->text(); QString imageMin = ui->imageMinLineEdit->text(); QString imageMax = ui->imageMaxLineEdit->text(); for (int i=0; i<numObj; ++i) { if (!skyMin.isEmpty() && dataSky[i] < skyMin.toDouble()) numericIndexes.push_back(i); if (!skyMax.isEmpty() && dataSky[i] > skyMax.toDouble()) numericIndexes.push_back(i); if (!airmassMin.isEmpty() && dataAirmass[i] < airmassMin.toDouble()) numericIndexes.push_back(i); if (!airmassMax.isEmpty() && dataAirmass[i] > airmassMax.toDouble()) numericIndexes.push_back(i); if (!seeingMin.isEmpty() && dataFWHM[i] < seeingMin.toDouble()) numericIndexes.push_back(i); if (!seeingMax.isEmpty() && dataFWHM[i] > seeingMax.toDouble()) numericIndexes.push_back(i); if (!rzpMin.isEmpty() && dataRZP[i] < rzpMin.toDouble()) numericIndexes.push_back(i); if (!rzpMax.isEmpty() && dataRZP[i] > rzpMax.toDouble()) numericIndexes.push_back(i); if (!ellMin.isEmpty() && dataEllipticity[i] < ellMin.toDouble()) numericIndexes.push_back(i); if (!ellMax.isEmpty() && dataEllipticity[i] > ellMax.toDouble()) numericIndexes.push_back(i); if (!imageMin.isEmpty() && i < imageMin.toInt()) numericIndexes.push_back(i); if (!imageMax.isEmpty() && i > imageMax.toInt()) numericIndexes.push_back(i); } for (auto &it : numericIndexes) { QCPDataRange range(it,it+1); numSelection.addDataRange(range); } numSelection.simplify(); QList<QCPDataRange> rangeList = numSelection.dataRanges(); // operator += automatically simplifies the selection for (auto &it : rangeList) { selection.operator +=(it); } plotSelection(0); // Have the plot widget grab the focus immediately, such that key press events are processed ui->statPlot->setFocus(); } void ImageStatistics::on_connectDataPointsCheckBox_clicked() { if (ui->connectDataPointsCheckBox->isChecked()) myLineStyle = QCPGraph::lsLine; else myLineStyle = QCPGraph::lsNone; plot(); plotSelection(0); } void ImageStatistics::on_clearSelectionPushButton_clicked() { clearSelection(); for (auto &it : graphList) { it->setSelection(selection); } ui->statPlot->replot(); ui->statPlot->update(); } void ImageStatistics::on_restoreDataPushButton_clicked() { clearData(); clearSelection(); badStatsList.clear(); activateImages(); init(); readStatisticsData(); plot(); } void ImageStatistics::activateImages() { for (auto &it : allMyImages) { it->setActiveState(MyImage::ACTIVE); emit it->modelUpdateNeeded(it->chipName); } }
15,494
C++
.cc
350
37.902857
133
0.663995
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,443
imagestatistics.cc
schirmermischa_THELI/src/imagestatistics/imagestatistics.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagestatistics.h" #include "ui_imagestatistics.h" #include "../instrumentdata.h" #include "../functions.h" #include "../qcustomplot.h" #include "../iview/iview.h" #include "../myimage/myimage.h" #include "../processingStatus/processingStatus.h" #include <QSettings> #include <QValidator> #include <QTest> #include <QVector> #include <QList> #include <QStringList> #include <QRegExpValidator> // ImageStatistics::ImageStatistics(QVector<QList<MyImage*>> &imlist, const QString main, const QString sciencedir, // const instrumentDataType *instrumentData, QWidget *parent): ImageStatistics::ImageStatistics(QList<Data*> &datalist, const QString main, const QString sciencedirname, const instrumentDataType *instrumentData, QWidget *parent): QMainWindow(parent), mainDir(main), instData(instrumentData), dataList(datalist), ui(new Ui::ImageStatistics) { ui->setupUi(this); initEnvironment(thelidir, userdir); makeConnections(); QStringList dirnameList; for (auto &it : dataList) { dirnameList.append(it->subDirName); } ui->scienceComboBox->insertItems(0, dirnameList); scienceDirName = mainDir + "/" + sciencedirname; scienceDir.setPath(scienceDirName); ui->scienceComboBox->setCurrentText(sciencedirname); scienceData = getData(dataList, sciencedirname); // dataList corresponds to DT_SCIENCE in the Controller class scienceData->populateExposureList(); myExposureList = scienceData->exposureList; // if (!myExposureList[instData->validChip]->isEmpty()) statusString = myExposureList[instData->validChip]. // else statusString = ""; // ui->filterLineEdit->setText("*_1"+statusString+".fits"); ui->statPlot->setMultiSelectModifier(Qt::ControlModifier); // ui->statPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); ui->statPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iMultiSelect); setWindowIcon(QIcon(":/icons/sigma.png")); init(); } void ImageStatistics::init() { allMyImages.clear(); for (int k=0; k<myExposureList.length(); ++k) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; auto &it = myExposureList[k][chip]; it->loadHeader(); // if not yet in memory it->getMode(true); allMyImages.append(it); } } processingStatus = new ProcessingStatus(scienceDirName); processingStatus->readFromDrive(); statusString = processingStatus->statusString; ui->statPlot->plotLayout()->clear(); // Plot data right away on_statisticsPushButton_clicked(); } ImageStatistics::~ImageStatistics() { delete processingStatus; processingStatus = nullptr; delete ui; } // cloned from Controller class Data* ImageStatistics::getData(QList<Data *> DT_x, QString dirName) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDir + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); return it; } } return nullptr; } void ImageStatistics::makeConnections() { numericThresholdList << ui->skyMinLineEdit << ui->skyMaxLineEdit << ui->airmassMinLineEdit << ui->airmassMaxLineEdit << ui->seeingMinLineEdit << ui->seeingMaxLineEdit << ui->rzpMinLineEdit << ui->rzpMaxLineEdit << ui->ellMinLineEdit << ui->ellMaxLineEdit << ui->imageMinLineEdit << ui->imageMaxLineEdit; // For a mouse-click in the plot connect(ui->statPlot, &QCustomPlot::plottableClick, this, &ImageStatistics::dataPointClicked); connect(ui->chipsLineEdit, &QLineEdit::editingFinished, this, &ImageStatistics::plot); // Validators connect(ui->raLineEdit, &QLineEdit::textChanged, this, &ImageStatistics::validate); connect(ui->decLineEdit, &QLineEdit::textChanged, this, &ImageStatistics::validate); for (auto &it : numericThresholdList) { connect(it, &QLineEdit::textChanged, this, &ImageStatistics::validate); connect(it, &QLineEdit::editingFinished, this, &ImageStatistics::numericSelection); } // Connections for iView can only be made when iView is instantiated further below. } void ImageStatistics::clearAll() { // if (numObj == 0) return; clearData(); clearSelection(); badStatsList.clear(); ui->statPlot->clearItems(); ui->statPlot->clearGraphs(); ui->statPlot->plotLayout()->clear(); plot(); ui->statPlot->replot(); numObj = 0; statisticsDataDisplayed = false; } // clicking on "update images" void ImageStatistics::on_statisticsPushButton_clicked() { if (!scienceDir.exists()) { QMessageBox::warning( this, "Bad selection", "The selected directory does not exist.\n"); return; } QString chips = ui->chipsLineEdit->text(); // Could be any text, but we just make it a list of detector IDs chips = chips.replace(',', ' ').simplified(); QStringList chipList = chips.split(' '); QVector<int> chipID; if (!chips.isEmpty()) { for (auto &it : chipList) { // instData = instrumentData; chipID.append(it.toInt()); } } filteredImageList.clear(); filteredMyImages.clear(); // Filter for sky coordinates QString ra = ui->raLineEdit->text(); QString dec = ui->decLineEdit->text(); for (int k=0; k<allMyImages.length(); ++k) { if (isImageSelected(allMyImages[k], ra, dec, chipID)) { filteredImageList << allMyImages[k]->chipName; filteredMyImages << allMyImages[k]; } } numObj = filteredImageList.size(); if (numObj == 0) { QMessageBox::warning( this, "No images found", "No images found, check chip filter or sky coordinates if provided.\n"); ui->statisticsPushButton->setEnabled(true); ui->statisticsPushButton->setText("Get statistics ..."); return; } readStatisticsData(); plot(); // Push the filtered list of images to iView if (iViewOpen) { iView->myImageList = filteredMyImages; iView->numImages = numObj; iView->clearAll(); } } bool ImageStatistics::isImageSelected(MyImage *myImage, const QString &ra, const QString &dec, const QVector<int> &chipID) { // RA / DEC filtering if (!ra.isEmpty() && !dec.isEmpty()) { if (!myImage->containsRaDec(ra,dec)) return false; } if (chipID.isEmpty()) return true; // Chip filtering bool correctChip = false; for (auto &chip : chipID) { if (chip == myImage->chipNumber) correctChip = true; } if (correctChip) return true; else return false; } void ImageStatistics::makeListOfBadImages() { // check for bad data on drive QDir badStatsDir(scienceDirName+"/inactive/badStatistics/"); if (badStatsList.isEmpty()) { QStringList filter; filter << "*.fits"; badStatsList = badStatsDir.entryList(filter); } // check for bad data in memory (should always be the same as on drive, but nonetheless) for (int k=0; k<allMyImages.length(); ++k) { auto &it = allMyImages[k]; if (it->activeState == MyImage::BADSTATS) badStatsList << it->chipName; } filteredImageList.removeDuplicates(); } void ImageStatistics::readStatisticsData() { // Must flag bad images makeListOfBadImages(); clearData(); // Compile the statistics data numObj = 0; // check for bad data in memory (should always be the same as on drive, but nonetheless) for (auto &it : allMyImages) { // for (auto &it : myExposureList[chip]) { // skip bad images if (it->activeState != MyImage::ACTIVE) continue; if (badStatsList.contains(it->chipName)) continue; // only include images that match the sky coordinate filter // (always true if no sky coords given) if (!filteredImageList.contains(it->chipName)) continue; dataName.append(it->chipName); dataImageNr.append(numObj+1); // Default values and flags if data not available // Background if (it->skyValue == 0.0) { // poor default of -1e9 in myimage.h skyData = false; dataSky.append(0.0); } else dataSky.append(it->skyValue); // In case GUI is launched, catalogs are present, and statistics is requested, // we need to fetch the data from the catalogs (or the MyImages) if (it->fwhm == -1.0 || it->ellipticity == -1.0) { if (it->objectList.length() > 0) it->calcMedianSeeingEllipticity(); else { QString catName = it->path+"/cat/"+it->rootName+".scamp"; QFile cat; cat.setFileName(catName); if (cat.exists()) { it->calcMedianSeeingEllipticitySex(catName, 2*it->chipNumber + 1); // LDAC_OBJECTS table in extensions 3, 5, 7, etc } } } // Do we have GAIA seeing? we should have, at least if catalogs exist if (it->fwhm == -1.0) { // No. Do we have median estimate? if (it->fwhm_est == -1.0) { // No seeingData = false; dataFWHM.append(0.0); } else { dataFWHM.append(it->fwhm_est); seeingFromGaia = false; } } else { dataFWHM.append(it->fwhm); seeingFromGaia = true; } // Do we have GAIA ellipticity? if (it->ellipticity == -1.0) { // No. Do we have median estimate? if (it->ellipticity_est == -1.0) { // No ellipticityData = false; dataEllipticity.append(-0.1); } else { dataEllipticity.append(it->ellipticity_est); seeingFromGaia = false; } } else { dataEllipticity.append(it->ellipticity); seeingFromGaia = true; } // Airmass if (it->airmass == 0.0) { airmassData = false; dataAirmass.append(2.5); } else dataAirmass.append(it->airmass); // Relative zeropoint if (it->RZP == -1.0) { rzpData = false; dataRZP.append(-0.5); } else dataRZP.append(it->RZP); ++numObj; } } void ImageStatistics::clearData() { dataName.clear(); dataImageNr.clear(); dataSky.clear(); dataFWHM.clear(); dataRZP.clear(); dataAirmass.clear(); dataEllipticity.clear(); numObj = 0; } void ImageStatistics::on_exportPushButton_clicked() { if (numObj == 0) return; if (!scienceDir.exists()) return; QString chips = ui->chipsLineEdit->text(); // Could be any text, but we just make it a list of detector IDs chips = chips.replace(',', ' ').simplified(); chips = chips.replace(' ', '_'); QString chipString = ""; if (!chips.isEmpty()) chipString = "_chip_"+chips; QString name = "statistics"+chipString+".png"; QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save .png Image"), scienceDirName+"/"+name, tr("Graphics file (*.png)")); if ( saveFileName.isEmpty() ) return; QFileInfo graphicsInfo(saveFileName); if (graphicsInfo.suffix() != "png") { QMessageBox::information(this, tr("Invalid graphics type"), tr("Only .png format is currently allowed."), QMessageBox::Ok); return; } else { ui->statPlot->savePng(saveFileName,0,0,1.25); } } // "Clicking on "display images" void ImageStatistics::on_showPushButton_clicked() { if (!scienceDir.exists()) return; if (!ui->showPushButton->isChecked() && iViewOpen) { iView->close(); iViewOpen = false; return; } if (ui->showPushButton->isChecked() && !iViewOpen) { if (!imgSelected && !statisticsDataDisplayed) { iView = new IView("FITSmonochrome", scienceDirName, "*.fits", this); connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // iView->clearAll(); } else if (!imgSelected && statisticsDataDisplayed) { // QCPDataRange range(0,1); // selection.addDataRange(range); // imgSelectedName = dataName[0]; // imgSelected = true; imgSelected = false; lastButtonClicked = Qt::LeftButton; // plotSelection(0); // iView = new IView("MEMview", allMyImages, scienceDirName, this); // dirname is needed to overlay catalogs iView = new IView("MEMview", filteredMyImages, scienceDirName, this); // dirname is needed to overlay catalogs connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // To be implemented // connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::currentlyDisplayedIndexReceived); iView->scene->clear(); } else { if (lastDataPointClicked != -1) { // iView = new IView("MEMview", allMyImages, scienceDirName, this); // dirname is needed to overlay catalogs iView = new IView("MEMview", filteredMyImages, scienceDirName, this); // dirname is needed to overlay catalogs connect(this, &ImageStatistics::imageSelected, iView, &IView::loadFITSexternalRAM); connect(iView, &IView::destroyed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::closed, this, &ImageStatistics::uncheckIviewPushButton); connect(iView, &IView::currentlyDisplayedIndex, this, &ImageStatistics::iviewNewImageShownReceiver); // iView->loadFromRAM(allMyImages[lastDataPointClicked], 0); // '0' refers to dataCurrent (compared to backup levels L1-L3) iView->loadFromRAM(filteredMyImages[lastDataPointClicked], 0); // '0' refers to dataCurrent (compared to backup levels L1-L3) iView->currentId = lastDataPointClicked; } } bool sourcecatShown = iView->sourcecatSourcesShown; bool refcatShown = iView->refcatSourcesShown; iView->clearItems(); iView->setCatalogOverlaysExternally(sourcecatShown, refcatShown); iView->redrawSkyCirclesAndCats(); iView->show(); iViewOpen = true; } else if (ui->showPushButton->isChecked() && iViewOpen) { iView->scene->clear(); iViewOpen = false; } } // To be implemented void ImageStatistics::currentlyDisplayedIndexReceived(int currentId) { qDebug() << currentId; // indicate displayed image, e.g. by a ring around the data point } void ImageStatistics::on_ClearPlotPushButton_clicked() { clearAll(); } void ImageStatistics::uncheckIviewPushButton() { if (ui->showPushButton->isChecked()) ui->showPushButton->setChecked(false); iViewOpen = false; } void ImageStatistics::clearSelection() { selection.clear(); imgSelected = false; for (auto &it : numericThresholdList) { it->clear(); } } void ImageStatistics::validate() { QRegExp RA( "[0-9.:]+" ); QRegExp DEC( "^[-]{0,1}[0-9.:]+" ); QRegExp ripos( "^[0-9]+" ); QRegExp rf( "^[-]{0,1}[0-9]*[.]{0,1}[0-9]+" ); QRegExp rfpos( "^[0-9]*[.]{0,1}[0-9]+" ); QRegExp ricommablank( "^[0-9,\\s]+" ); QValidator* validator_int_pos_comma_blank = new QRegExpValidator( ricommablank, this ); QValidator* validator_ra = new QRegExpValidator( RA, this ); QValidator* validator_dec = new QRegExpValidator( DEC, this ); QValidator* validator_float = new QRegExpValidator(rf, this ); QValidator* validator_float_pos = new QRegExpValidator(rfpos, this ); QValidator* validator_int_pos = new QRegExpValidator( ripos, this ); ui->raLineEdit->setValidator(validator_ra); ui->decLineEdit->setValidator(validator_dec); ui->skyMinLineEdit->setValidator(validator_float); ui->skyMaxLineEdit->setValidator(validator_float); ui->airmassMinLineEdit->setValidator(validator_float_pos); ui->airmassMaxLineEdit->setValidator(validator_float_pos); ui->seeingMinLineEdit->setValidator(validator_float_pos); ui->seeingMaxLineEdit->setValidator(validator_float_pos); ui->rzpMinLineEdit->setValidator(validator_float); ui->rzpMaxLineEdit->setValidator(validator_float); ui->ellMinLineEdit->setValidator(validator_float_pos); ui->ellMaxLineEdit->setValidator(validator_float_pos); ui->imageMinLineEdit->setValidator(validator_int_pos); ui->imageMaxLineEdit->setValidator(validator_int_pos); ui->chipsLineEdit->setValidator( validator_int_pos_comma_blank ); } void ImageStatistics::on_readmePushButton_clicked() { imstatsReadme = new ImstatsReadme(this); imstatsReadme->show(); } void ImageStatistics::on_fwhmunitsComboBox_currentIndexChanged(const QString &arg1) { plot(); } void ImageStatistics::on_actionClose_triggered() { close(); } void ImageStatistics::on_scienceComboBox_activated(const QString &arg1) { scienceDirName = mainDir + "/" + arg1; scienceDir.setPath(scienceDirName); scienceData = getData(dataList, arg1); // dataList corresponds to DT_SCIENCE in the Controller class scienceData->populateExposureList(); myExposureList = scienceData->exposureList; init(); } void ImageStatistics::on_chipsLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::on_raLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::on_decLineEdit_editingFinished() { on_statisticsPushButton_clicked(); } void ImageStatistics::activationChangedReceiver() { // has no effect. in readStatisticsData()->makeListofBadImages(), images are recognized as bad even when they are not. scienceData = getData(dataList, ui->scienceComboBox->currentText()); scienceData->populateExposureList(); myExposureList = scienceData->exposureList; allMyImages.clear(); for (int k=0; k<myExposureList.length(); ++k) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; auto &it = myExposureList[k][chip]; it->loadHeader(); // if not yet in memory it->getMode(true); allMyImages.append(it); } } on_statisticsPushButton_clicked(); } void ImageStatistics::iviewNewImageShownReceiver(int newDataPoint) { lastDataPointClicked = newDataPoint; highlightClickedDataPoint(); }
20,514
C++
.cc
506
33.521739
143
0.648027
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,444
splitter_processingGeneric.cc
schirmermischa_THELI/src/tools/splitter_processingGeneric.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "tools.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "../functions.h" #include "fitsio.h" #include <QString> #include <QVector> #include <QFile> #include <QDir> void Splitter::correctOverscan() { if (!cdw->ui->overscanCheckBox->isChecked()) return; if (multiportOverscanDirections.isEmpty()) return; int numOverscans = multiportOverscanSections.length(); // the number of overscan sections per detector int numDataSections = multiportChannelSections.length(); // the number of data sections per detector. A data section might have a horizontal and a vertical overscan // One overscan per data section // We keep track of the estimate of the overscan value per detector float overscanEffectiveVertical = 0.; float overscanEffectiveHorizontal = 0.; float overscanEffective = 0.; if (numOverscans == numDataSections) { for (int i=0; i<numOverscans; ++i) { if (multiportOverscanDirections[i] == "vertical") { doOverscanVertical(combineOverscan_ptr, multiportOverscanSections[i], multiportChannelSections[i], overscanEffectiveVertical); } if (multiportOverscanDirections[i] == "horizontal") { doOverscanHorizontal(combineOverscan_ptr, multiportOverscanSections[i], multiportChannelSections[i], overscanEffectiveHorizontal); } overscanEffective += overscanEffectiveVertical + overscanEffectiveHorizontal; } overscanEffective /= numOverscans; } // Two overscans per data section, e.g. vertical and horizontal else { for (int i=0; i<numOverscans; ++i) { if (multiportOverscanDirections[i] == "vertical") { doOverscanVertical(combineOverscan_ptr, multiportOverscanSections[i], multiportChannelSections[i/2], overscanEffectiveVertical); } if (multiportOverscanDirections[i] == "horizontal") { doOverscanHorizontal(combineOverscan_ptr, multiportOverscanSections[i], multiportChannelSections[i/2], overscanEffectiveHorizontal); } overscanEffective += overscanEffectiveVertical + overscanEffectiveHorizontal; } overscanEffective /= numOverscans; } // Update the saturation value // qDebug() << saturationValue << overscanEffective; saturationValue -= overscanEffective; } /* void Splitter::doOverscan(float (*combineFunction_ptr) (const QVector<float> &, const QVector<bool> &, long), const QVector<long> &overscanXArea, const QVector<long> &overscanYArea, const QVector<long> vertices) { if (!successProcessing) return; if (!cdw->ui->overscanCheckBox->isChecked()) return; // Overscan correction is done only for optical CCDs if (instData.type != "OPT") return; long i, j, k; long n = naxis1Raw; long m = naxis2Raw; // Overscan correction is applied to a subregion of the detector (including the overscan itself!). // If the detector has a single readout port only (or we can ignore them), then the overscan applies to the full array. // Otherwise, to the subarray defined by 'vertices' long imin; long imax; long jmin; long jmax; if (vertices.isEmpty()) { imin = 0; imax = naxis1Raw; jmin = 0; jmax = naxis2Raw; } else { imin = vertices[0]; imax = vertices[1]; jmin = vertices[2]; jmax = vertices[3]; } // PART 1: Correct vertical overscan if (!overscanXArea.isEmpty()) { QVector<float> spectral(overscanXArea[1]-overscanXArea[0]+1,0); QVector<float> spatial(m,0); // extract representative line for (j=0; j<m; ++j) { k = 0; for (i=overscanXArea[0]; i<=overscanXArea[1]; ++i) { spectral[k] = dataRaw[i+n*j]; ++k; } spatial[j] = combineFunction_ptr(spectral, QVector<bool>(), 0); // spatialv[j] = straightMedianInline(spectralv); } if (*verbosity > 1) emit messageAvailable(baseName + " : Mean vertical overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); // subtract overscan for (i=imin; i<imax; ++i) { for (j=jmin; j<jmax; ++j) { dataRaw[i+n*j] -= spatial[j]; } } } // PART 2: Correct horizontal overscan if (!overscanYArea.isEmpty()) { QVector<float> spectral(overscanYArea[1]-overscanYArea[0]+1,0); QVector<float> spatial(n,0); // extract representative line for (i=0; i<n; ++i) { k = 0; for (j=overscanYArea[0]; j<=overscanYArea[1]; ++j) { spectral[k] = dataRaw[i+n*j]; ++k; } spatial[i] = combineFunction_ptr(spectral, QVector<bool>(), 0); } // subtract overscan if (*verbosity > 1) emit messageAvailable(baseName + " : Mean horizontal overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); for (j=jmin; j<jmax; ++j) { for (i=imin; i<imax; ++i) { dataRaw[i+n*j] -= spatial[i]; } } } } */ // Correct vertical overscan void Splitter::doOverscanVertical(float (*combineFunction_ptr) (const QVector<float> &, const QVector<bool> &, long), const QVector<long> &overscanArea, const QVector<long> dataVertices, float &overscanEstimate) { if (!successProcessing) return; if (overscanArea.isEmpty()) return; long n = naxis1Raw; long m = naxis2Raw; overscanEstimate = 0.; QVector<float> spectral(overscanArea[1]-overscanArea[0]+1,0); // select (xmin, xmax) from [xmin:xmax, ymin:ymax] QVector<float> spatial(m,0); // Line by line correction if (combineFunction_ptr != nullptr) { // extract representative line for (long j=0; j<m; ++j) { long k = 0; for (long i=overscanArea[0]; i<=overscanArea[1]; ++i) { spectral[k] = dataRaw[i+n*j]; ++k; } spatial[j] = combineFunction_ptr(spectral, QVector<bool>(), 0); // spatialv[j] = straightMedianInline(spectralv); } overscanEstimate = meanMask(spatial); if (*verbosity > 1) emit messageAvailable(baseName + " : Mean vertical overscan = " + QString::number(overscanEstimate, 'f', 3), "image"); } // Global correction with constant value else { QVector<float> tmp; tmp.reserve((overscanArea[1]-overscanArea[0]+1)*m); for (long j=0; j<m; ++j) { for (long i=overscanArea[0]; i<=overscanArea[1]; ++i) { tmp << dataRaw[i+n*j]; } } float constOverscan = straightMedianInline(tmp); overscanEstimate = constOverscan; if (*verbosity > 1) emit messageAvailable(baseName + " : Global median overscan = " + QString::number(constOverscan, 'f', 1), "image"); for (long j=0; j<m; ++j) { spatial[j] = constOverscan; } } // Overscan correction is applied to a subregion of the detector (including the overscan itself!). // If the detector has a single readout port only (or we can ignore the ports), then the overscan applies to the full array. long imin = dataVertices[0]; long imax = dataVertices[1]; long jmin = dataVertices[2]; long jmax = dataVertices[3]; for (long i=imin; i<=imax; ++i) { for (long j=jmin; j<=jmax; ++j) { dataRaw[i+n*j] -= spatial[j]; } } } // Correct horizontal overscan void Splitter::doOverscanHorizontal(float (*combineFunction_ptr) (const QVector<float> &, const QVector<bool> &, long), const QVector<long> &overscanArea, const QVector<long> dataVertices, float &overscanEstimate) { if (!successProcessing) return; if (overscanArea.isEmpty()) return; long n = naxis1Raw; overscanEstimate = 0.; QVector<float> spectral(overscanArea[3]-overscanArea[2]+1,0); // select (ymin, ymax) from [xmin:xmax, ymin:ymax] QVector<float> spatial(n,0); // Line by line correction if (combineFunction_ptr != nullptr) { // extract representative line for (long i=0; i<n; ++i) { long k = 0; for (long j=overscanArea[2]; j<=overscanArea[3]; ++j) { spectral[k] = dataRaw[i+n*j]; ++k; } spatial[i] = combineFunction_ptr(spectral, QVector<bool>(), 0); } overscanEstimate = meanMask(spatial); if (*verbosity > 1) emit messageAvailable(baseName + " : Mean horizontal overscan = " + QString::number(meanMask(spatial), 'f', 3), "image"); } // Global correction with constant value else { QVector<float> tmp; tmp.reserve((overscanArea[3]-overscanArea[2]+1)*n); for (long i=0; i<n; ++i) { for (long j=overscanArea[2]; j<=overscanArea[3]; ++j) { tmp << dataRaw[i+n*j]; } } float constOverscan = straightMedianInline(tmp); overscanEstimate = constOverscan; if (*verbosity > 1) emit messageAvailable(baseName + " : Global median overscan = " + QString::number(constOverscan, 'f', 1), "image"); for (long i=0; i<n; ++i) { spatial[i] = constOverscan; } } // Overscan correction is applied to a subregion of the detector (including the overscan itself!). // If the detector has a single readout port only (or we can ignore the ports), then the overscan applies to the full array. long imin = dataVertices[0]; long imax = dataVertices[1]; long jmin = dataVertices[2]; long jmax = dataVertices[3]; for (long j=jmin; j<=jmax; ++j) { for (long i=imin; i<=imax; ++i) { dataRaw[i+n*j] -= spatial[i]; } } } void Splitter::applyMask(int chip) { if (!successProcessing) return; if (instData.name.contains("DUMMY")) return; if (!MEFpastingFinished) return; else { // Must reset 'chip' such that it counts true CCDs, not the extensions with the individual amplifiers (e.g., for GMOS and SOI) chip = chip / numAmpPerChip; } // Override: PISCO chip can be different than zero (other than grond) because we had to maintain its chip id for the chip-dependent pasting if (instData.name == "PISCO@LCO") chip = 0; // (single detector, effectively) if (!checkCorrectMaskSize(chip)) { // QDir unknownFile(path+"/InconsistentGeometry"); // unknownFile.mkpath(path+"/InconsistentGeometry/"); // moveFile(fileName, path, path+"/InconsistentGeometry/"); return; } if (instData.name == "LIRIS_POL@WHT") return; // Further cut-outs happen in writeImage(); mask geometry in camera.ini applies only once these have happened. // if (instData.name == "GROND_NIR@MPGESO") return; // Further cut-outs happen in writeImage(); mask geometry in camera.ini applies only once these have happened. if (instNameFromData == "GROND_NIR@MPGESO") return; // Further cut-outs happen in writeImage(); mask geometry in camera.ini applies only once these have happened. if (*verbosity > 1) emit messageAvailable(baseName + " : Applying mask ...", "image"); long i = 0; if (!instData.name.contains("GROND")) { for (auto &pixel : dataCurrent) { if (mask->globalMask[chip].at(i)) pixel = 0.; ++i; } } // Resolve a mask conflict (two different masks, but only one instrument can be selected at a time) else if (instNameFromData == "GROND_OPT@MPGESO" && instData.name == "GROND_NIR@MPGESO" && altMask != nullptr) { for (auto &pixel : dataCurrent) { if (altMask->globalMask[chip].at(i)) pixel = 0.; ++i; } } } // dataSect contains the exposed (desired) illuminated pixels, [min:max], starting counting at zero, // correctly converted from the camera.ini CUTON_X and SIZE_X parameterization void Splitter::cropDataSection(QVector<long> dataSect) { if (!successProcessing) return; if (instData.name == "LIRIS_POL@WHT") { naxis1 = naxis1Raw; naxis2 = naxis2Raw; dataCurrent = dataRaw; return; } // new image geometry naxis1 = dataSect[1] - dataSect[0] + 1; naxis2 = dataSect[3] - dataSect[2] + 1; if (*verbosity > 1) emit messageAvailable(baseName + " : Cropping to data section, size = " + QString::number(naxis1)+"x"+QString::number(naxis2)+" pixel", "image"); dataCurrent.resize(naxis1*naxis2); dataCurrent.squeeze(); long k = 0; for (long j=dataSect[2]; j<=dataSect[3]; ++j) { for (long i=dataSect[0]; i<=dataSect[1]; ++i) { dataCurrent[k] = dataRaw[i+naxis1Raw*j]; ++k; } } // TODO /* int crpix1 = getKeyword("CRPIX1").toFloat() - dataSection[0]; int crpix2 = getKeyword("CRPIX2").toFloat() - dataSection[2]; updateKeywordInHeader("CRPIX1", QString::number(crpix1)); updateKeywordInHeader("CRPIX2", QString::number(crpix2)); */ // successProcessing = true; } void Splitter::correctNonlinearity(int chip) { if (!successProcessing) return; if (!MEFpastingFinished) return; if (!cdw->ui->nonlinearityCheckBox->isChecked()) return; // Leave if no correction polynomial is known if (nonlinearityCoefficients.isEmpty()) return; if (*verbosity > 1) emit messageAvailable(baseName + " : Nonlinearity correction ...", "image"); // Extract coefficients for the current chip QVector<float> coeffs = nonlinearityCoefficients[chip]; // Apply nonlinearity correction for (auto &pixel : dataCurrent) { pixel = polynomialSum(pixel, coeffs); } // Update saturation value saturationValue = polynomialSum(saturationValue, coeffs); // Individual implementations // Average nonlinearity correction // http://instrumentation.obs.carnegiescience.edu/FourStar/Documents/FourStar_Documentation.pdf if (instData.name == "FourStar@LCO") { float A = 0.; // High gain if (channelGains[0] > 2.) { if (chip == 0) A = 1.203e-8; if (chip == 1) A = 1.337e-8; if (chip == 2) A = 1.157e-8; if (chip == 3) A = 1.195e-8; } // Low gain else { if (chip == 0) A = 5.344e-9; if (chip == 1) A = 7.514e-9; if (chip == 2) A = 3.645e-9; if (chip == 3) A = 5.923e-9; } for (auto &pixel : dataCurrent) { pixel = pixel * (1.+A*pow(pixel,1.5)); } saturationValue *= (1.+A*pow(saturationValue,1.5)); } // http://csp2.lco.cl/manuals/dup_dc_linearity.php if (instData.name == "Direct_2k_DUPONT@LCO") { QString speed = ""; searchKeyValue(headerDictionary.value("SPEED"), speed); float c1 = 1.0; float c2 = 0.0; float c3 = 0.0; float c4 = 0.0; if (speed == "Turbo") { c2 = 0.09907; c3 = -0.06151; c4 = 0.01522; } if (speed == "Fast") { c2 = 0.05022; c3 = -0.02814; c4 = 0.00733; } for (auto &pixel : dataCurrent) { float x = c1 + c2*(pixel/32000.0) + c3*pow(pixel/32000.0,2) + c4*pow(pixel/32000.0,3); pixel /= x; } float x = c1 + c2*(saturationValue/32000.0) + c3*pow(saturationValue/32000.0,2) + c4*pow(saturationValue/32000.0,3); saturationValue /= x; } // http://csp2.lco.cl/manuals/swo_nc_linearity.php (using mean values) // NOTE: linearity test page does not specify for which readout mode it applies if (instData.name == "Direct_4k_SWOPE@LCO") { float c1 = 1.0; float c2 = 0.0; float c3 = 0.0; if (chip == 0) { c2 = -0.03443; c3 = 0.006657; } if (chip == 1) { c2 = -0.01557; c3 = 0.003386; } if (chip == 2) { c2 = -0.01329; c3 = 0.003314; } if (chip == 3) { c2 = -0.01971; c3 = 0.004700; } for (auto &pixel : dataCurrent) { float x = c1 + c2*(pixel/32000.0) + c3*pow(pixel/32000.0,2); pixel /= x; } float x = c1 + c2*(saturationValue/32000.0) + c3*pow(saturationValue/32000.0,2); saturationValue /= x; } } void Splitter::convertToElectrons(int chip) { if (!successProcessing) return; if (!MEFpastingFinished) return; // Update saturation value // done in buildTheliHeaderGAIN(int chip) // saturationValue *= gain[chip]; // cameras with multiple readout channels AND different gain per channel (but no overscan pasted into the data section) // WARNING: ASSUMPTIONS: applies to the size defined in camera.ini if (numReadoutChannels > 1) { // qDebug() << channelGains; if (instData.name == "FORS1_199904-200703@VLT" || instData.name == "FORS2_200004-200203@VLT") { for (long j=0; j<naxis2; ++j) { for (long i=0; i<naxis1; ++i) { auto &pixel = dataCurrent[i+naxis1*j]; if (i<=1022 && j<=1023) pixel *= channelGains[0]; // lower left quadrant if (i>=1023 && j<=1023) pixel *= channelGains[1]; // lower right quadrant if (i<=1022 && j>=1024) pixel *= channelGains[2]; // upper left quadrant if (i>=1023 && j>=1024) pixel *= channelGains[3]; // upper right quadrant } } gainForSaturation = minVec_T(channelGains); // SATURATE keyword shall reflect lowest number at which saturation occurs } } // if (instData.name == "GROND_NIR@MPGESO") { if (instNameFromData == "GROND_NIR@MPGESO") { gain[chip] = 1.0; // Gain is fixed in writeImageIndividual(); saturationValue *= gainForSaturation; return; } if (instData.name == "SuprimeCam_200808-201705@SUBARU") { saturationValue *= gainForSaturation; return; } if (multiChannelMultiExt.contains(instData.name)) { // GMOS, SOI, MOSAIC-II_16@CTIO, etc saturationValue *= gainForSaturation; return; } saturationValue *= gainForSaturation; if (instData.name != "NISP_LE1@EUCLID" && instData.name != "NISP_ERO@EUCLID") { for (auto &pixel : dataCurrent) { pixel *= gain[chip]; } } else { for (auto &pixel : dataCurrent) { pixel = (pixel-1024.)*gain[chip]; // The NISP DPU adds 1024 ADU, for whatever reason, at least for the commissioning data } } } // Calculate the effective gain for a detector with different readout channels. // When we divide the data by the flat field, the effective gain is the harmonic mean float Splitter::harmonicGain(QVector<float> detectorGains) { float harmGain = 0.; for (auto &gain : detectorGains) { harmGain += 1./gain; } harmGain = float(detectorGains.length()) / harmGain; return harmGain; } float Splitter::polynomialSum(float x, QVector<float> coefficients) { // Coefficients contains the coeffs of a polynomial, starting with the lowest term // e.g., for p(x) = c0 + c1*x + c2*x*x we have coefficients = [c0, c1, c2] float sum = 0.; int k = 0; for (auto & it : coefficients) { sum += it * pow(x, k); ++k; } return sum; } // IMPORTANT: xtalk correction assumes NO inter-chip crosstalk, and that the amplitudes are the same for all intra-chip crosstalk int Splitter::getNorXtalkMethod() { int xtalkMethod = -1; if (cdw->ui->normalxtalkCheckBox->isChecked()) { if (cdw->ui->xtalk_nor_2x2ToolButton->isChecked()) xtalkMethod = 1; if (cdw->ui->xtalk_nor_1x2ToolButton->isChecked()) xtalkMethod = 2; if (cdw->ui->xtalk_nor_2x1ToolButton->isChecked()) xtalkMethod = 3; } return xtalkMethod; } int Splitter::getRowXtalkMethod() { int xtalkMethod = -1.; if (cdw->ui->rowxtalkCheckBox->isChecked()) { if (cdw->ui->xtalk_row_2x2ToolButton->isChecked()) xtalkMethod = 4; if (cdw->ui->xtalk_row_1x2ToolButton->isChecked()) xtalkMethod = 5; if (cdw->ui->xtalk_row_2x1ToolButton->isChecked()) xtalkMethod = 6; if (cdw->ui->xtalk_col_2x2ToolButton->isChecked()) xtalkMethod = 7; if (cdw->ui->xtalk_col_1x2ToolButton->isChecked()) xtalkMethod = 8; if (cdw->ui->xtalk_col_2x1ToolButton->isChecked()) xtalkMethod = 9; } return xtalkMethod; } void Splitter::correctXtalk() { if (!successProcessing) return; if (!MEFpastingFinished) return; // Xtalk type bool doXtalkNor = cdw->ui->normalxtalkCheckBox->isChecked(); bool doXtalkRow = cdw->ui->rowxtalkCheckBox->isChecked(); if (!doXtalkNor && !doXtalkRow) return; // Xtalk Amplitudes xtalkNorAmpString = cdw->ui->normalxtalkAmplitudeLineEdit->text(); xtalkRowAmpString = cdw->ui->rowxtalkAmplitudeLineEdit->text(); if (xtalkNorAmpString.isEmpty() && xtalkRowAmpString.isEmpty()) return; if ( (doXtalkNor && xtalkNorAmpString.isEmpty()) || ((doXtalkRow && xtalkRowAmpString.isEmpty()))) { emit messageAvailable("Incomplete cross-talk input. The cross-talk type must be checked as well as an amplitude given.", "warning"); emit messageAvailable("Cross-talk correction will not take place", "warning"); emit warning(); return; } // Ok, proceed with xtalk correction xtalkNorAmp = xtalkNorAmpString.toFloat(); xtalkRowAmp = xtalkRowAmpString.toFloat(); xtalkKappa = 1e6; // No rejection in x-talk correction when doing collapse correction // Holds the pixel corrected data dataXcorr.fill(0, naxis1*naxis2); // Correct point xtalk xtalkNorMethod = getNorXtalkMethod(); if (xtalkNorMethod != -1 && *verbosity > 1) emit messageAvailable(baseName + " : Normal crosstalk correction ...", "image"); if (xtalkNorMethod == 1) xtalk_method1(); // 2x2 quadrants, point xtalk else if (xtalkNorMethod == 2) xtalk_method2(); // 1x2 quadrants, point xtalk, top half bottom half else if (xtalkNorMethod == 3) xtalk_method3(); // 2x1 quadrants, point xtalk, left half right half // Make the corrected data the current data if (xtalkNorMethod != -1) dataCurrent.swap(dataXcorr); // Correct row xtalk xtalkRowMethod = getRowXtalkMethod(); if (xtalkRowMethod != -1 && *verbosity > 1) emit messageAvailable(baseName + " : Row crosstalk correction ...", "image"); if (xtalkRowMethod == 4) xtalk_method4(); // 2x2 quadrants, row xtalk else if (xtalkRowMethod == 5) xtalk_method5(); // 1x2 quadrants, row xtalk, top half bottom half else if (xtalkRowMethod == 6) xtalk_method6(); // 2x1 quadrants, row xtalk, left half right half else if (xtalkRowMethod == 7) xtalk_method7(); // 2x2 quadrants, col xtalk else if (xtalkRowMethod == 8) xtalk_method8(); // 1x2 quadrants, col xtalk, top half bottom half else if (xtalkRowMethod == 9) xtalk_method9(); // 2x1 quadrants, col xtalk, left half right half // Make the corrected data the current data if (xtalkRowMethod != -1) dataCurrent.swap(dataXcorr); dataXcorr.clear(); dataXcorr.squeeze(); // if (method == 10) xtalk_method10(); // Multi-xtalk, HAWAII-2RGs (rudimentary implementation, not supported by the GUI) } // The crosstalk images. We subtract from each quadrant the other quadrants, scaled by the xtalk amplitude. // The amplitude is assumed to be the same for all quadrants void Splitter::xtalk_method1() { int n = naxis1; int m = naxis2; long i, j, ih, jh, il, jl; int xlow1 = 0; // 1 for a 1024x1024 chip int xlow2 = n/2-1; // 512 int xhigh1 = n/2; // 513 int xhigh2 = n-1; // 1024 int ylow1 = 0; // 1 int ylow2 = m/2-1; // 512 int yhigh1 = m/2; // 513 int yhigh2 = m-1; // 1024 for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { ih = i + xhigh1; jh = j + yhigh1; il = i - xhigh1; jl = j - yhigh1; // ll = lr + ul + ur if (i>=xlow1 && i<=xlow2 && j>=ylow1 && j<=ylow2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[ih+n*j] + dataCurrent[i+n*jh] + dataCurrent[ih+n*jh]); // lr = ll + ul + ur if (i>=xhigh1 && i<=xhigh2 && j>=ylow1 && j<=ylow2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[il+n*j] + dataCurrent[il+n*jh] + dataCurrent[i+n*jh]); // ul = lr + ll + ur if (i>=xlow1 && i<=xlow2 && j>=yhigh1 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[ih+n*jl] + dataCurrent[i+n*jl] + dataCurrent[ih+n*j]); // ur = lr + ul + ll if (i>=xhigh1 && i<=xhigh2 && j>=yhigh1 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * (dataCurrent[i+n*jl] + dataCurrent[il+n*j] + dataCurrent[il+n*jl]); } } } void Splitter::xtalk_method2() { int n = naxis1; int m = naxis2; long i, j, jh, jl; int xlow1 = 0; // 1 int xhigh1 = n-1; // 1024 int ylow1 = 0; // 1 int ylow2 = m/2; // 513 int yhigh1 = m/2-1; // 512 int yhigh2 = m-1; // 1024 for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { jh = j + ylow2; jl = j - ylow2; // fix lower quadrant if (i>=xlow1 && i<=xhigh1 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[i+n*jh]; // fix upper quadrant if (i>=xlow1 && i<=xhigh1 && j>=ylow2 && j<=yhigh2) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[i+n*jl]; } } } void Splitter::xtalk_method3() { int n = naxis1; int m = naxis2; long i, j, ih, il; int xlow1 = 0; // 1 int xlow2 = n/2; // 513 int xhigh1 = n/2-1; // 512 int xhigh2 = n-1; // 1024 int ylow1 = 0; // 1 int yhigh1 = m-1; // 1024 for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { ih = i + xlow2; il = i - xlow2; // fix left quadrant if (i>=xlow1 && i<=xhigh1 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[ih+n*j]; // fix right quadrant if (i>=xlow2 && i<=xhigh2 && j>=ylow1 && j<=yhigh1) dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkNorAmp * dataCurrent[il+n*j]; } } } void Splitter::xtalk_method4() { int n = naxis1; int m = naxis2; long i, j, ih, jh, t; int xlow2 = n/2; // 513 int ylow2 = m/2; // 513 QVector<float> ll_input(n/2*m/2,0); QVector<float> lr_input(n/2*m/2,0); QVector<float> ul_input(n/2*m/2,0); QVector<float> ur_input(n/2*m/2,0); t = 0; for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ll_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=0; j<m/2; ++j) { for (i=n/2; i<n; ++i) { lr_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=0; i<n/2; ++i) { ul_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=n/2; i<n; ++i) { ur_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> mask(n/2*m/2,false); QVector<float> ll_mean = collapse_x(ll_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> lr_mean = collapse_x(lr_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> ul_mean = collapse_x(ul_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> ur_mean = collapse_x(ur_input, mask, mask, xtalkKappa, n/2, m/2, "2Dmodel"); // ll = ll - xtalkRowAmp * mean(ll+lr+ul+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // lr = lr - xtalkRowAmp * mean(lr+ll+ul+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; dataXcorr[ih+n*j] = dataCurrent[ih+n*j] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // ul = ul - xtalkRowAmp * mean(ul+lr+ll+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { jh = j + ylow2; dataXcorr[i+n*jh] = dataCurrent[i+n*jh] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // ur = ur - xtalkRowAmp * mean(ur+lr+ul+ll) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; jh = j + ylow2; dataXcorr[ih+n*jh] = dataCurrent[ih+n*jh] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } } void Splitter::xtalk_method5() { int n = naxis1; int m = naxis2; long i, j, jh, t; int ylow2 = m/2; // 513 QVector<float> bo_input(n*m/2,0); QVector<float> up_input(n*m/2,0); t = 0; for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { bo_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=0; i<n; ++i) { up_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> maskLocal(n*m/2,false); QVector<float> bo_mean = collapse_x(bo_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); QVector<float> up_mean = collapse_x(up_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); // bo = bo - xtalkRowAmp * mean(bo+up) for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (bo_mean[i+n*j] + up_mean[i+n*j]); } } // up = up - xtalkRowAmp * mean(bo+up) for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { jh = j + ylow2; dataXcorr[i+n*jh] = dataCurrent[i+n*jh] - xtalkRowAmp * (bo_mean[i+n*j] + up_mean[i+n*j]); } } } void Splitter::xtalk_method6() { int n = naxis1; int m = naxis2; long i, j, ih, t; int xlow2 = n/2; // 513 QVector<float> le_input(n/2*m,0); QVector<float> ri_input(n/2*m,0); t = 0; for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { le_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=0; j<m; ++j) { for (i=n/2; i<n; ++i) { ri_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> maskLocal(n/2*m,false); QVector<float> le_mean = collapse_x(le_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); QVector<float> ri_mean = collapse_x(ri_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); // le = le - xtalkRowAmp * mean(le+ri) for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (le_mean[i+n/2*j] + ri_mean[i+n/2*j]); } } // ri = ri - xtalkRowAmp * mean(le+ri) for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; dataXcorr[ih+n*j] = dataCurrent[ih+n*j] - xtalkRowAmp * (le_mean[i+n/2*j] + ri_mean[i+n/2*j]); } } } void Splitter::xtalk_method7() { int n = naxis1; int m = naxis2; long i, j, ih, jh, t; int xlow2 = n/2; // 513 int ylow2 = m/2; // 513 QVector<float> ll_input(n/2*m/2,0); QVector<float> lr_input(n/2*m/2,0); QVector<float> ul_input(n/2*m/2,0); QVector<float> ur_input(n/2*m/2,0); t = 0; for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ll_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=0; j<m/2; ++j) { for (i=n/2; i<n; ++i) { lr_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=0; i<n/2; ++i) { ul_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=n/2; i<n; ++i) { ur_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> maskLocal(n/2*m/2,false); QVector<float> ll_mean = collapse_y(ll_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> lr_mean = collapse_y(lr_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> ul_mean = collapse_y(ul_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); QVector<float> ur_mean = collapse_y(ur_input, maskLocal, maskLocal, xtalkKappa, n/2, m/2, "2Dmodel"); // ll = ll - xtalkRowAmp * mean(ll+lr+ul+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // lr = lr - xtalkRowAmp * mean(lr+ll+ul+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; dataXcorr[ih+n*j] = dataCurrent[ih+n*j] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // ul = ul - xtalkRowAmp * mean(ul+lr+ll+ur) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { jh = j + ylow2; dataXcorr[i+n*jh] = dataCurrent[i+n*jh] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } // ur = ur - xtalkRowAmp * mean(ur+lr+ul+ll) for (j=0; j<m/2; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; jh = j + ylow2; dataXcorr[ih+n*jh] = dataCurrent[ih+n*jh] - xtalkRowAmp * (ll_mean[i+n/2*j] + lr_mean[i+n/2*j] + ul_mean[i+n/2*j] + ur_mean[i+n/2*j]); } } } void Splitter::xtalk_method8() { int n = naxis1; int m = naxis2; long i, j, jh, t; int ylow2 = m/2; // 513 QVector<float> bo_input(n*m/2,0); QVector<float> up_input(n*m/2,0); t = 0; for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { bo_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=m/2; j<m; ++j) { for (i=0; i<n; ++i) { up_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> maskLocal(n*m/2,false); QVector<float> bo_mean = collapse_y(bo_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); QVector<float> up_mean = collapse_y(up_input, maskLocal, maskLocal, xtalkKappa, n, m/2, "2Dmodel"); // bo = bo - xtalkRowAmp * mean(bo+up) for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (bo_mean[i+n*j] + up_mean[i+n*j]); } } // up = up - xtalkRowAmp * mean(bo+up) for (j=0; j<m/2; ++j) { for (i=0; i<n; ++i) { jh = j + ylow2; dataXcorr[i+n*jh] = dataCurrent[i+n*jh] - xtalkRowAmp * (bo_mean[i+n*j] + up_mean[i+n*j]); } } } void Splitter::xtalk_method9() { int n = naxis1; int m = naxis2; long i, j, ih, t; int xlow2 = n/2; // 513 QVector<float> le_input(n/2*m,0); QVector<float> ri_input(n/2*m,0); t = 0; for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { le_input[t++] = dataCurrent[i+n*j]; } } t = 0; for (j=0; j<m; ++j) { for (i=n/2; i<n; ++i) { ri_input[t++] = dataCurrent[i+n*j]; } } QVector<bool> maskLocal(n/2*m,false); QVector<float> le_mean = collapse_y(le_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); QVector<float> ri_mean = collapse_y(ri_input, maskLocal, maskLocal, xtalkKappa, n/2, m, "2Dmodel"); // le = le - xtalkRowAmp * mean(le+ri) for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { dataXcorr[i+n*j] = dataCurrent[i+n*j] - xtalkRowAmp * (le_mean[i+n/2*j] + ri_mean[i+n/2*j]); } } // ri = ri - xtalkRowAmp * mean(le+ri) for (j=0; j<m; ++j) { for (i=0; i<n/2; ++i) { ih = i + xlow2; dataXcorr[ih+n*j] = dataCurrent[ih+n*j] - xtalkRowAmp * (le_mean[i+n/2*j] + ri_mean[i+n/2*j]); } } } // For the typical point cross talk in HAWAII-2RGs (difficult to correct, not offered in the GUI) void Splitter::xtalk_method10() { if (xtalkDirection.isEmpty() || xtalkNsection < 0) { emit messageAvailable("For crosstalk mode 10 you must specify the readout direction and the number of readout sections!", "error"); emit critical(); return; } if (xtalkNsection < 2) { emit messageAvailable("xtalk(): The number of readout sections must be larger than 1.\n", "error"); emit critical(); return; } int n = naxis1; int m = naxis2; long i, j, k, l; int width; float medianval; // allocate memory QVector<float> h2_median(n*m,0); QVector<float> h2_sample(xtalkNsection,0); if (xtalkDirection.compare("x") == 0) { width = m/xtalkNsection; for (j=0; j<width; ++j) { for (i=0; i<n; ++i) { l = 0; for (k=0; k<xtalkNsection; k++) { h2_sample[l++] = dataCurrent[i+n*(j+width*k)]; } medianval = straightMedian_T(h2_sample); for (k=0; k<xtalkNsection; k++) { h2_median[i+n*(j+width*k)] = medianval; } } } } if (xtalkDirection.compare("y") == 0) { width = n/xtalkNsection; for (j=0; j<m; ++j) { for (i=0; i<width; ++i) { l = 0; for (k=0; k<xtalkNsection; k++) { h2_sample[l++] = dataCurrent[i+width*k+n*j]; } medianval = straightMedian_T(h2_sample); for (k=0; k<xtalkNsection; k++) { h2_median[i+width*k+n*j] = medianval; } } } } for (k=0; k<n*m; k++) { dataXcorr[k] = dataCurrent[k] - h2_median[k]; } }
39,760
C++
.cc
990
32.427273
172
0.569221
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,445
splitter_multiport.cc
schirmermischa_THELI/src/tools/splitter_multiport.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "tools.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "../functions.h" #include "fitsio.h" #include <QString> #include <QVector> #include <QFile> #include <QDir> // The functions below make a fork of the overscan / cropping part for detectors with multiple readout channels // Ultimately, this should become generic enough to also work with "normal" detectors /* void Splitter::pasteMultiPortDataSections(QVector<long> dataSect) { if (!successProcessing) return; if (instData.name == "LIRIS_POL@WHT") { naxis1 = naxis1Raw; naxis2 = naxis2Raw; dataCurrent = dataRaw; return; } // The image that enters this function has the same geometry as the raw data, including all overscan areas. // New image geometry; here, naxis1/2 refers to the total size of the image (after pasting one or more readout channels) // This should match what is given in instrument.ini naxis1 = dataSect[1] - dataSect[0] + 1; naxis2 = dataSect[3] - dataSect[2] + 1; if (*verbosity > 1) emit messageAvailable(baseName + " : Cropping to data section, size = " + QString::number(naxis1)+"x"+QString::number(naxis2)+" pixel", "image"); dataCurrent.resize(naxis1*naxis2); // Loop over readout channels int numChannels = multiportOverscanDirections.length(); // the number of readout channels per detector for (int channel=0; channel<numChannels; ++channel) { } long k = 0; for (long j=dataSect[2]; j<=dataSect[3]; ++j) { for (long i=dataSect[0]; i<=dataSect[1]; ++i) { dataCurrent[k] = dataRaw[i+naxis1Raw*j]; ++k; } } } */ /* void Splitter::computeMultiportDataOffsets() { for (int channel=0; channel<multiportGains.length(); ++channel) { long xoffset = multiportDataSections[channel][0] - multiportImageSections[channel][0]; long yoffset = multiportDataSections[channel][2] - multiportImageSections[channel][2]; } } */ // Collects information where in an image the overscan and illuminated pixel areas are located. // For "normal" cameras which have only a single readout channel, or where the differences between readout channels are negligible, // we just take the information from the camera.ini file. // For others, where multiple channels are pasted into a single FITS extension, or where different channels are in different FITS extensions, // we must rely on the headers and do individual implementations void Splitter::getMultiportInformation(int chip) { if (!successProcessing) return; multiportOverscanSections.clear(); multiportIlluminatedSections.clear(); multiportChannelSections.clear(); multiportGains.clear(); multiportOverscanDirections.clear(); bool individualFixDone = false; // if (instData.name == "GROND_OPT@MPGESO") { if (instNameFromData == "GROND_OPT@MPGESO") { naxis1 = 2048; naxis2 = 2050; multiportOverscanDirections << "vertical" << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BSECA"); multiportOverscanSections << extractVerticesFromKeyword("BSECB"); multiportIlluminatedSections << extractVerticesFromKeyword("DSECA"); multiportIlluminatedSections << extractVerticesFromKeyword("DSECB"); multiportChannelSections << extractVerticesFromKeyword("ASECA"); multiportChannelSections << extractVerticesFromKeyword("ASECB"); float gainValue1 = 0.0; float gainValue2 = 0.0; searchKeyValue(QStringList() << "GAIN", gainValue1); // Nominally, the 2 channels in the optical GROND detectors have the same gain, but that's not exactly true QString detector = ""; searchKeyValue(QStringList() << "EXTNAME", detector); if (detector == "CCDg") gainValue2 = gainValue1 * 1.06947; if (detector == "CCDr") gainValue2 = gainValue1 * 1.00766; if (detector == "CCDi") gainValue2 = gainValue1 * 1.00001; if (detector == "CCDz") gainValue2 = gainValue1 * 0.88904; multiportGains << gainValue1 << gainValue2; individualFixDone = true; } // if (instData.name == "GROND_NIR@MPGESO") { if (instNameFromData == "GROND_NIR@MPGESO") { naxis1 = 3072; naxis2 = 1024; multiportOverscanDirections << "dummy"; QVector<long> section = {0, naxis1-1, 0, naxis2-1}; // all three channels at the same time. Cutting happens separately during writeImage(); multiportIlluminatedSections << section; multiportChannelSections << section; multiportGains << 1.0; individualFixDone = true; } if (instData.name == "SuprimeCam_200808-201705@SUBARU") { // contains 4 vertical data slices, separated by overscans, in a single FITS extension naxis1 = 2048; naxis2 = 4224; // NOTE: The y coordinates of the illuminated sections and overscan sections in the SuprimeCam raw data are wrong. // They are normally contained in keywords "S_EFMN11", "S_EFMX11", "S_EFMN12", "S_EFMX12" for channel 1, etc multiportOverscanDirections << "vertical" << "vertical" << "vertical" << "vertical"; multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN11", "S_OSMX11", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN21", "S_OSMX21", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN31", "S_OSMX31", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("S_OSMN41", "S_OSMX41", 1, naxis2Raw); /* multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN11", "S_EFMX11", "S_EFMN12", "S_EFMX12"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN21", "S_EFMX21", "S_EFMN22", "S_EFMX22"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN31", "S_EFMX31", "S_EFMN32", "S_EFMX32"); multiportIlluminatedSections << extractVerticesFromKeyword("S_EFMN41", "S_EFMX41", "S_EFMN42", "S_EFMX42"); */ int ymin = 49; // in pixel coords (not accounting for C++ indexing starting at 0) int ymax = 4273; // in pixel coords (not accounting for C++ indexing starting at 0) if (chip == 3 || chip == 4 || chip == 5 || chip == 8 || chip == 9) { ymin = 1; ymax = 4225; } multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN11", "S_EFMX11", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN21", "S_EFMX21", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN31", "S_EFMX31", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("S_EFMN41", "S_EFMX41", ymin, ymax); if (chip == 0 || chip == 1 || chip == 2 || chip == 6 || chip == 7) { multiportChannelSections << QVector<long>({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // These nunmbers are not directly accessible in the FITS headers multiportChannelSections << QVector<long>({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); } else { multiportChannelSections << QVector<long>({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // reversed order in FITS headers multiportChannelSections << QVector<long>({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); } float gainValue1 = 1.0; float gainValue2 = 1.0; float gainValue3 = 1.0; float gainValue4 = 1.0; searchKeyValue(QStringList() << "S_GAIN1", gainValue1); searchKeyValue(QStringList() << "S_GAIN2", gainValue2); searchKeyValue(QStringList() << "S_GAIN3", gainValue3); searchKeyValue(QStringList() << "S_GAIN4", gainValue4); multiportGains << gainValue1 << gainValue2 << gainValue3 << gainValue4; channelGains.clear(); channelGains << 1.0 << 1.0 << 1.0 << 1.0; // dummy; not used anywhere else for SuprimeCam_200808-201705 individualFixDone = true; } if (instData.name == "HSC@SUBARU") { // contains 4 vertical data slices, separated by overscans, in a single FITS extension naxis1 = 2048; naxis2 = 4224; // NOTE: The y coordinates of the illuminated sections and overscan sections in the SuprimeCam raw data are wrong. // They are normally contained in keywords "T_EFMN11", "T_EFMX11", "T_EFMN12", "T_EFMX12" for channel 1, etc multiportOverscanDirections << "vertical" << "vertical" << "vertical" << "vertical"; multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN11", "T_OSMX11", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN21", "T_OSMX21", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN31", "T_OSMX31", 1, naxis2Raw); multiportOverscanSections << extractReducedOverscanFromKeyword("T_OSMN41", "T_OSMX41", 1, naxis2Raw); /* multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN11", "T_EFMX11", "T_EFMN12", "T_EFMX12"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN21", "T_EFMX21", "T_EFMN22", "T_EFMX22"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN31", "T_EFMX31", "T_EFMN32", "T_EFMX32"); multiportIlluminatedSections << extractVerticesFromKeyword("T_EFMN41", "T_EFMX41", "T_EFMN42", "T_EFMX42"); */ int ymin = 1; // in pixel coords (not accounting for C++ indexing starting at 0) int ymax = 4224; // in pixel coords (not accounting for C++ indexing starting at 0) multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN11", "T_EFMX11", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN21", "T_EFMX21", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN31", "T_EFMX31", ymin, ymax); multiportIlluminatedSections << extractReducedIlluminationFromKeyword("T_EFMN41", "T_EFMX41", ymin, ymax); // if (chip == 0 || chip == 1 || chip == 2 || chip == 6 || chip == 7) { multiportChannelSections << QVector<long>({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // These numbers are not directly accessible in the FITS headers multiportChannelSections << QVector<long>({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); multiportChannelSections << QVector<long>({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // } // else { // multiportChannelSections << QVector<long>({3*naxis1Raw/4, 4*naxis1Raw/4-1, 0, naxis2Raw-1}); // reversed order in FITS headers // multiportChannelSections << QVector<long>({2*naxis1Raw/4, 3*naxis1Raw/4-1, 0, naxis2Raw-1}); // multiportChannelSections << QVector<long>({1*naxis1Raw/4, 2*naxis1Raw/4-1, 0, naxis2Raw-1}); // multiportChannelSections << QVector<long>({0*naxis1Raw/4, 1*naxis1Raw/4-1, 0, naxis2Raw-1}); // } float gainValue1 = 1.0; float gainValue2 = 1.0; float gainValue3 = 1.0; float gainValue4 = 1.0; searchKeyValue(QStringList() << "T_GAIN1", gainValue1); searchKeyValue(QStringList() << "T_GAIN2", gainValue2); searchKeyValue(QStringList() << "T_GAIN3", gainValue3); searchKeyValue(QStringList() << "T_GAIN4", gainValue4); multiportGains << gainValue1 << gainValue2 << gainValue3 << gainValue4; channelGains.clear(); channelGains << 1.0 << 1.0 << 1.0 << 1.0; // dummy; not used anywhere else for SuprimeCam_200808-201705 individualFixDone = true; } if (instData.name == "LIRIS_POL@WHT") { naxis1 = 1024; naxis2 = 1024; multiportOverscanDirections << "dummy"; QVector<long> section = {0, naxis1-1, 0, naxis2-1}; // all four channels at the same time. Cutting happens separately during writeImage(); multiportIlluminatedSections << section; multiportChannelSections << section; multiportGains << 1.0; individualFixDone = true; } // All Hamamatsu Gemini GMOS configurations. Single channel in single FITS extension if (multiChannelMultiExt.contains(instData.name) && instData.name.contains("GMOS")) { int binning = 1; QString binString = ""; searchKeyValue(QStringList() << "CCDSUM", binString); if (binString.simplified() == "1 1") binning = 1; else if (binString.simplified() == "2 2") binning = 2; else if (binString.simplified() == "4 4") binning = 4; else { emit messageAvailable(fileName + ": Invalid binning encountered: "+binString.simplified(), "error"); emit critical(); successProcessing = false; return; } naxis1 = 2048 / binning; naxis2 = 4224 / binning; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates // for (auto &section : multiportChannelSections) { // for (auto &it : section) it /= binning; // maapping unbinned pixel space to binned pixel space // } if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; if (instData.name == "GMOS-S-HAM@GEMINI" || instData.name == "GMOS-S-HAM_1x1@GEMINI" || instData.name == "GMOS-S-HAM_4x4@GEMINI") { // Accurate amplifier gains are not available in the GMOS FITS headers if (mjdobsValue < 57265.999988) { // before 2015-08-31 // WARNING: these are the LOW gain modes. High gain mode is hardly used if (chip == 0) gainValue = 1.626; else if (chip == 1) gainValue = 1.700; else if (chip == 2) gainValue = 1.720; else if (chip == 3) gainValue = 1.652; else if (chip == 4) gainValue = 1.739; else if (chip == 5) gainValue = 1.673; else if (chip == 6) gainValue = 1.691; else if (chip == 7) gainValue = 1.664; else if (chip == 8) gainValue = 1.613; else if (chip == 9) gainValue = 1.510; else if (chip == 10) gainValue = 1.510; else if (chip == 11) gainValue = 1.519; } else { // after 2015-08-31 if (chip == 0) gainValue = 1.834; else if (chip == 1) gainValue = 1.874; else if (chip == 2) gainValue = 1.878; else if (chip == 3) gainValue = 1.852; else if (chip == 4) gainValue = 1.908; else if (chip == 5) gainValue = 1.933; else if (chip == 6) gainValue = 1.840; else if (chip == 7) gainValue = 1.878; else if (chip == 8) gainValue = 1.813; else if (chip == 9) gainValue = 1.724; else if (chip == 10) gainValue = 1.761; else if (chip == 11) gainValue = 1.652; } } if (instData.name == "GMOS-N-HAM@GEMINI" || instData.name == "GMOS-N-HAM_1x1@GEMINI") { if (chip == 0) gainValue = 1.66; else if (chip == 1) gainValue = 1.63; else if (chip == 2) gainValue = 1.62; else if (chip == 3) gainValue = 1.57; else if (chip == 4) gainValue = 1.68; else if (chip == 5) gainValue = 1.65; else if (chip == 6) gainValue = 1.64; else if (chip == 7) gainValue = 1.68; else if (chip == 8) gainValue = 1.61; else if (chip == 9) gainValue = 1.63; else if (chip == 10) gainValue = 1.58; else if (chip == 11) gainValue = 1.65; } multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "SOI@SOAR") { naxis1 = 1024; naxis2 = 2048; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) gainValue = 2.0; else if (chip == 1) gainValue = 2.0; else if (chip == 2) gainValue = 2.0; else if (chip == 3) gainValue = 2.0; multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "DEIMOS_2AMP@KECK") { naxis1 = 2048; naxis2 = 2601; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector<long> oscan = {1040,1110,0,2600}; // Bias section not present in header multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) gainValue = 1.206; if (chip == 1) gainValue = 1.221; if (chip == 2) gainValue = 1.200; if (chip == 3) gainValue = 1.188; if (chip == 4) gainValue = 1.167; if (chip == 5) gainValue = 1.250; if (chip == 6) gainValue = 1.217; if (chip == 7) gainValue = 1.228; multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { naxis1 = 2048; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector<long> oscan = {1080,1150,0,4095}; // Bias section not present in header; Must respect 0-indexing explicitly multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) searchKeyValue(QStringList() << "CCDGN00", gainValue); if (chip == 1) searchKeyValue(QStringList() << "CCDGN01", gainValue); if (chip == 2) searchKeyValue(QStringList() << "CCDGN02", gainValue); if (chip == 3) searchKeyValue(QStringList() << "CCDGN03", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { if (chip == 0) { naxis1 = 1648; naxis2 = 2520; } if (chip == 2) { naxis1 = 1752; naxis2 = 2520; } int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector<long> oscan; if (chip == 0) oscan = {1040,1100,0,4095}; // Bias section not present in header if (chip == 1) oscan = {650,710,0,4095}; // Bias section not present in header if (chip == 2) oscan = {750,810,0,4095}; // Bias section not present in header if (chip == 3) oscan = {1040,1100,0,4095}; // Bias section not present in header multiportOverscanSections << oscan; multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; // "DETSEC" has the illuminated section in CCD coordinates if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; // Accurate amplifier gains are not available in the FITS headers if (chip == 0) searchKeyValue(QStringList() << "CCDGN01", gainValue); if (chip == 1) searchKeyValue(QStringList() << "CCDGN02", gainValue); if (chip == 2) searchKeyValue(QStringList() << "CCDGN03", gainValue); if (chip == 3) searchKeyValue(QStringList() << "CCDGN04", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "MOSAIC-II_16@CTIO") { naxis1 = 2048; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "GAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "PISCO@LCO") { naxis1 = 3092; naxis2 = 6147; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; QVector<long> oscan; oscan << 1547 << 1577 << 0 << 6146; QVector<long> illum; illum << 0 << 1545 << 0 << 6146; multiportOverscanSections << oscan; multiportIlluminatedSections << illum; QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "EGAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { naxis1 = 4112; naxis2 = 4096; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 1.0; searchKeyValue(QStringList() << "GAIN", gainValue); multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } if (instData.name == "SAMI_2x2@SOAR") { naxis1 = 2048; naxis2 = 2056; int naxis1channel = 0; int naxis2channel = 0; searchKeyValue(QStringList() << "NAXIS1", naxis1channel); searchKeyValue(QStringList() << "NAXIS2", naxis2channel); multiportOverscanDirections << "vertical"; multiportOverscanSections << extractVerticesFromKeyword("BIASSEC"); // given in binned units in the header multiportIlluminatedSections << extractVerticesFromKeyword("DATASEC"); // given in binned units in the header QVector<long> channelSection; channelSection << 0 << naxis1channel - 1 << 0 << naxis2channel - 1; multiportChannelSections << channelSection; if (chip % numAmpPerChip == 0) dataPasted.resize(naxis1 * naxis2); float gainValue = 2.1; // http://www.soartelescope.org/soar/sites/default/files/SAM/archive/sami-manual.pdf searchKeyValue(QStringList() << "GAIN", gainValue); if (gainValue == 0.) { if (chip == 0) gainValue = 2.10000; if (chip == 1) gainValue = 2.20456; if (chip == 2) gainValue = 2.09845; if (chip == 3) gainValue = 2.19494; } multiportGains << gainValue; channelGains.clear(); channelGains << 1.0; // dummy; individualFixDone = true; } // If any instrument-specific stuff happened above, then we do a consistency check if (individualFixDone) { // if (multiportGains.length() != multiportOverscanSections.length() // crashes GROND-NIR data if (multiportGains.length() != multiportIlluminatedSections.length()) { emit messageAvailable("Splitter::getMultiportInformation : Inconsistent number of channels for gain, overscan and data section: " + QString::number(multiportGains.length()) + " " + QString::number(multiportIlluminatedSections.length()), "error"); emit critical(); successProcessing = false; } } else { // What to do for detectors that are not split up by several readout channels and overscans naxis1 = dataSection[chip][1] - dataSection[chip][0] + 1; naxis2 = dataSection[chip][3] - dataSection[chip][2] + 1; // Append the overscan strips from the instrument.ini files, and padd the missing dimension QVector<long> overscan; if (!overscanX[chip].isEmpty()) { overscan << overscanX[chip][0] << overscanX[chip][1] << 0 << naxis2Raw-1; multiportOverscanDirections << "vertical"; } if (!overscanY[chip].isEmpty()) { overscan << 0 << naxis1Raw-1 << overscanY[chip][0] << overscanY[chip][1]; multiportOverscanDirections << "horizontal"; } multiportOverscanSections << overscan; multiportIlluminatedSections << dataSection[chip]; // image section = data section minus the left and bottom overscan pixels (right and upper overscan pixels not counted) // QVector<long> imageSection = {0, dataSection[chip][1] - dataSection[chip][0], 0, dataSection[chip][3] - dataSection[chip][2]}; QVector<long> channelSection = {0, naxis1Raw - 1, 0, naxis2Raw - 1}; multiportChannelSections << channelSection; multiportGains << 1.0; // i.e. leave gain unchanged } } void Splitter::pasteMultiportIlluminatedSections(int chip) { if (!successProcessing) return; // NOTE: multiportGains[channel] does not contain a Vector, just a scalar. Pasting is done one amp at a time // Paste the data sections into a single image of dimensions naxis1, naxis2 if (!multiChannelMultiExt.contains(instData.name)) { dataCurrent.resize(naxis1*naxis2); // long k = 0; // the running 1D index in the pasted image int channel = 0; for (auto &section : multiportIlluminatedSections) { if (section.length() != 4) continue; // skip wrong vertices, for whatever reason they might be here pasteSubArea(dataCurrent, dataRaw, multiportIlluminatedSections[channel], multiportGains[channel], naxis1, naxis2, naxis1Raw); ++channel; } } // Individual exceptions (currently: GMOS, SOI, MOSAIC-II only) else { int channel = 0; for (auto &section : multiportIlluminatedSections) { if (section.length() != 4) continue; // skip wrong vertices, for whatever reason they might be here long offx = 0; long offy = 0; // detectors where the amps form two or more vertical stripes from left to right if (instData.name == "SOI@SOAR" || instData.name.contains("GMOS") || instData.name == "MOSAIC-II_16@CTIO") { offx = (chip % numAmpPerChip) * naxis1 / numAmpPerChip; offy = 0; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { QVector<long> ampsec; ampsec << extractVerticesFromKeyword("CCDSEC"); // unused if (chip == 0) {offx = naxis1 / 2; offy = 0;} if (chip == 1) {offx = 0; offy = 0;} if (chip == 2) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 3) {offx = 0; offy = naxis2 / 2;} if (chip == 4) {offx = naxis1 / 2; offy = 0;} if (chip == 5) {offx = 0; offy = 0;} if (chip == 6) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 7) {offx = 0; offy = naxis2 / 2;} if (chip == 8) {offx = 0; offy = naxis2 / 2;} if (chip == 9) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 10) {offx = 0; offy = 0;} if (chip == 11) {offx = naxis1/2; offy = 0;} if (chip == 12) {offx = 0; offy = naxis2 / 2;} if (chip == 13) {offx = naxis1 / 2; offy = naxis2 / 2;} if (chip == 14) {offx = 0; offy = 0;} if (chip == 15) {offx = naxis1 / 2; offy = 0;} } if (instData.name == "SAMI_2x2@SOAR") { QVector<long> ampsec; ampsec << extractVerticesFromKeyword("CCDSEC"); //unused if (chip == 0) {offx = 0; offy = 0;} if (chip == 1) {offx = naxis1 / 2; offy = 0;} if (chip == 2) {offx = 0; offy = naxis2 / 2;} if (chip == 3) {offx = naxis1 / 2; offy = naxis2 / 2;} } if (instData.name == "DEIMOS_2AMP@KECK") { offy = 0; if (chip % 2 == 0) { offx = naxis1 / 2; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip % 2 == 1) { offx = 0; } } if (instData.name == "LRIS_BLUE@KECK") { offy = 0; if (chip % 2 == 0) { offx = 0; } if (chip % 2 == 1) { offx = naxis1 / 2; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } } if (instData.name == "LRIS_RED@KECK") { offy = 0; if (chip % 2 == 0) { offx = 0; } if (chip % 2 == 1) { offx = 1024; // HARDCODED, because the amplifier sections have unequal sizes!!! (so far, that's the only detector ever I have seen this) flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } } if (instData.name == "PISCO@LCO") { if (chip == 0) { offx = 0; offy = 0; } if (chip == 1) { offx = naxis1 / 2; offy = 0; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip == 2) { offx = naxis1 / 2; offy = -172; flipData(dataRaw, "x", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "x", naxis1Raw, naxis2Raw); } if (chip == 3) { offx = 0; offy = -172; } if (chip == 4) { offx = 0; offy = 150; flipData(dataRaw, "y", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "y", naxis1Raw, naxis2Raw); } if (chip == 5) { offx = naxis1 / 2; offy = 150; flipData(dataRaw, "xy", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "xy", naxis1Raw, naxis2Raw); } if (chip == 6) { offx = naxis1 / 2; offy = -70; flipData(dataRaw, "xy", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "xy", naxis1Raw, naxis2Raw); } if (chip == 7) { offx = 0; offy = -70; flipData(dataRaw, "y", naxis1Raw, naxis2Raw); flipSections(multiportIlluminatedSections[channel], "y", naxis1Raw, naxis2Raw); } } pasteSubArea(dataPasted, dataRaw, multiportIlluminatedSections[channel], multiportGains[channel], offx, offy, naxis1, naxis2, naxis1Raw); ++channel; } if ( (chip+1) % numAmpPerChip == 0) { // all channels have been pasted. Transfer the data to dataCurrent. MEFpastingFinished = true; dataCurrent.swap(dataPasted); dataPasted.clear(); dataPasted.squeeze(); dataCurrent.squeeze(); } } } // paste a subarea 'sector' (xmin, xmax, ymin, ymax) from source image "dataS" to target image "dataT", // Offsets are calculated internally, assuming that data sections have equal sizes void Splitter::pasteSubArea(QVector<float> &dataT, const QVector<float> &dataS, const QVector<long> &section, const float corrFactor, const long nT, const long mT, const long nS) { long iminS = section.at(0); long imaxS = section.at(1); long jminS = section.at(2); long jmaxS = section.at(3); long dimS = dataS.length(); // S = source image long dimT = dataT.length(); // T = target image // The x- and y-offsets for the illuminated sections. Calculated by taking the lower x (or y) value, // and checking how many equally sized sections can fit (safe, as we have usually not more than 4 sections, and the overscan areas are comparatively small) long sizex = section.at(1) - section.at(0) + 1; // section x-size long sizey = section.at(3) - section.at(2) + 1; // section y-size long nsecx = section.at(0) / sizex; // number of sections found to the left, using integer division long nsecy = section.at(2) / sizey; // number of sections found below the botton, using integer division // if the offsets are relatively large, i.e. the detector is very large but only a small part is usually read out, then we need manual resets: if (instData.name == "WFCCD_WF4K_DUPONT@LCO") nsecy = 0; long offx = nsecx * sizex; // The offset for the current section in the pasted output geometry long offy = nsecy * sizey; // The offset for the current section in the pasted output geometry for (long jS=jminS; jS<=jmaxS; ++jS) { for (long iS=iminS; iS<=imaxS; ++iS) { long iT = offx+iS-iminS; long jT = offy+jS-jminS; long sIndex = iS+nS*jS; long tIndex = iT+nT*jT; if (!instData.name.contains("GROND") && !instData.name.contains("DUMMY")) { if (sIndex >= dimS || tIndex >= dimT) { emit messageAvailable("Inconsistent image geometry. " + instData.name + " not fully tested in THELI.", "error"); emit critical(); successProcessing = false; break; } } if (iT>=nT || iT<0 || jT>=mT || jT<0) continue; // don't paste pixels falling outside target area if (!instData.name.contains("DUMMY")) { dataT[tIndex] = dataS[sIndex] * corrFactor; // correcting for gain differences } } } } // paste a subarea 'sector' (xmin, xmax, ymin, ymax) from source image "dataS" to target image "dataT", // offsets dx and dy are given explicitly void Splitter::pasteSubArea(QVector<float> &dataT, const QVector<float> &dataS, const QVector<long> &section, const float corrFactor, const long offx, const long offy, const long nT, const long mT, const long nS) { long iminS = section[0]; long imaxS = section[1]; long jminS = section[2]; long jmaxS = section[3]; long dimS = dataS.length(); long dimT = dataT.length(); for (long jS=jminS; jS<=jmaxS; ++jS) { if (!successProcessing) break; for (long iS=iminS; iS<=imaxS; ++iS) { long iT = offx+iS-iminS; long jT = offy+jS-jminS; if (iT>=nT || iT<0 || jT>=mT || jT<0) continue; // don't paste pixels falling outside target area long sIndex = iS+nS*jS; long tIndex = iT+nT*jT; if (sIndex >= dimS || tIndex >= dimT) { emit messageAvailable("Inconsistent image geometry. " + instData.name + " not fully tested in THELI.", "error"); emit critical(); successProcessing = false; break; } dataT[tIndex] = dataS[sIndex] * corrFactor; // correcting for gain differences } } } // splitting "[xmin:xmax,ymin:ymax]" QVector<long> Splitter::extractVertices(QString vertexString) { vertexString = vertexString.replace(":"," "); vertexString = vertexString.replace(","," "); vertexString = vertexString.replace("[",""); vertexString = vertexString.replace("]",""); vertexString = vertexString.replace("'",""); vertexString = vertexString.simplified(); QStringList list = vertexString.split(" "); QVector<long> vertices; // for loop also works for one-dimensional vertices for (int i=0; i<list.length(); ++i) { vertices << list[i].toFloat() - 1; // The -1 accounts for C++ indexing starting at zero } return vertices; } QVector<long> Splitter::extractVerticesFromKeyword(QString keyword) { QString section = ""; searchKeyValue(QStringList() << keyword, section); return extractVertices(section); } QVector<long> Splitter::extractVerticesFromKeyword(QString keyword1, QString keyword2, QString keyword3, QString keyword4) { int value1 = 0; int value2 = 0; int value3 = 0; int value4 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); searchKeyValue(QStringList() << keyword3, value3); searchKeyValue(QStringList() << keyword4, value4); QVector<long> vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } // For SuprimeCam_200808-201705, only QVector<long> Splitter::extractReducedOverscanFromKeyword(QString keyword1, QString keyword2, int value3, int value4) { int value1 = 0; int value2 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); QVector<long> vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } // For SuprimeCam_200808-201705, only QVector<long> Splitter::extractReducedIlluminationFromKeyword(QString keyword1, QString keyword2, int value3, int value4) { int value1 = 0; int value2 = 0; searchKeyValue(QStringList() << keyword1, value1); searchKeyValue(QStringList() << keyword2, value2); QVector<long> vertices; vertices << value1 - 1 << value2 - 1 << value3 - 1 << value4 - 1; // The -1 accounts for C++ indexing starting at zero return vertices; } void Splitter::updateMEFpastingStatus(int chip) { MEFpastingFinished = false; if (!multiChannelMultiExt.contains(instData.name)) { MEFpastingFinished = true; return; } // The following instruments store the multiple readout channels of their detectors in separate FITS extensions, and must be pasted back together: // Once the last channel has been read, we can paste the chips together if (instData.name.contains("GMOS")) { if ( (chip + 1) % numAmpPerChip == 0) MEFpastingFinished = true; // if (chip == 3 || chip == 7 || chip == 11) MEFpastingFinished = true; } // CHECK: I think SAMI and MOSAIC-III are missing here! if (instData.name == "SOI@SOAR" || instData.name == "DEIMOS_2AMP@KECK" || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "PISCO@LCO") { if ( (chip + 1) % numAmpPerChip == 0) MEFpastingFinished = true; } }
46,056
C++
.cc
856
44.053738
174
0.605533
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,446
cpu.cc
schirmermischa_THELI/src/tools/cpu.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "cpu.h" #include <QVector> #include <QString> #include <QTest> #include <QFile> #include <QThread> #include <QSysInfo> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "fitsio.h" #ifdef __MACH__ #include <mach/mach.h> #define MACOS #elif __LINUX__ #define LINUX #endif CPU::CPU(QObject *parent) : QObject(parent) { file.setFileName("/proc/stat"); if ( !file.open(QIODevice::ReadOnly)) { CPUbarDeactivated = true; return; } instream.setDevice(&file); maxCPU = QThread::idealThreadCount(); if (!fits_is_reentrant()) maxCPU = 1; // new method init(); } CPU::~CPU() { file.close(); } int CPU::getCPUload() { if (CPUbarDeactivated) return 0; // Take two snapshots 250 ms apart if (kernelType == "linux") { readStatsCPU_Linux(tot1, idle1); QTest::qWait(250); readStatsCPU_Linux(tot2, idle2); } else if (kernelType == "darwin") { readStatsCPU_MAC(tot1, idle1); QTest::qWait(250); readStatsCPU_MAC(tot2, idle2); } double dTot = tot2-tot1; double dIdle = idle2-idle1; int CPUload = 100. * maxCPU * (dTot - dIdle) / dTot; return CPUload; } void CPU::readStatsCPU_Linux(double &totval, double &idleval) { // Reset file to beginning instream.seek(0); double tot = 0.; double idle = 0.; QString line = instream.readLine().simplified(); QStringList values = line.split(" "); if (values[0] == "cpu") { for (int i=1; i<values.length(); ++i) { tot += values[i].toDouble(); if (i==4 || i==5) idle += values[i].toDouble(); } } totval = tot; idleval = idle; } void CPU::readStatsCPU_MAC(double &totval, double &idleval) { unsigned long ulSystem; unsigned long ulUser; unsigned long ulNice; unsigned long ulIdle; getCPUInfo_MAC(&ulSystem, &ulUser, &ulNice, &ulIdle); totval = (double)(ulSystem + ulUser + ulNice + ulIdle); idleval = (double) ulIdle; } void CPU::init() { QSysInfo *sysInfo = new QSysInfo; kernelType = sysInfo->kernelType(); if (kernelType == "linux") { // Reset file to beginning lastTotal = 0; lastTotalActive = 0; lastTotalIdle = 0; instream.seek(0); QStringList values = instream.readLine().simplified().split(" "); for (int i=1; i<values.length(); ++i) { if (i!=4 && i!=5) lastTotalActive += values[i].toLongLong(); else lastTotalIdle += values[i].toLongLong(); } lastTotal = lastTotalIdle + lastTotalActive; } if (kernelType == "darwin") { // nothing to be done } delete sysInfo; sysInfo = nullptr; } float CPU::getCurrentValue() { long long total = 0; long long totalActive = 0; long long totalIdle = 0; // Reset file to beginning // We assume the first line contains the total of all CPUs, and starts with string "cpu". // Columns 5 and 6 conmtain the idle times (idle, iowait) instream.seek(0); QStringList values = instream.readLine().simplified().split(" "); for (int i=1; i<values.length(); ++i) { if (i!=4 && i!=5) totalActive += values[i].toLongLong(); else totalIdle += values[i].toLongLong(); } total = totalActive + totalIdle; long diffTotalActive = totalActive - lastTotalActive; // long diffTotalIdle = totalIdle - lastTotalIdle; long diffTotal = total - lastTotal; float CPUload = 100. * maxCPU * diffTotalActive / diffTotal; lastTotal = total; lastTotalActive = totalActive; lastTotalIdle = totalIdle; return CPUload; } void CPU::getCPUInfo_MAC(unsigned long *pulSystem, unsigned long *pulUser, unsigned long *pulNice, unsigned long *pulIdle) { #ifdef __MACH__ mach_msg_type_number_t unCpuMsgCount = 0; processor_flavor_t nCpuFlavor = PROCESSOR_CPU_LOAD_INFO; kern_return_t nErr = 0; natural_t unCPUNum = 0; processor_cpu_load_info_t structCpuData; host_t host = mach_host_self(); *pulSystem = 0; *pulUser = 0; *pulNice = 0; *pulIdle = 0; nErr = host_processor_info(host, nCpuFlavor, &unCPUNum, (processor_info_array_t *)&structCpuData, &unCpuMsgCount); if(nErr != KERN_SUCCESS) { qDebug() << "Kernel error: " << mach_error_string(nErr); } else { for(int i=0; i<(int)unCPUNum; ++i) { *pulSystem += structCpuData[i].cpu_ticks[CPU_STATE_SYSTEM]; *pulUser += structCpuData[i].cpu_ticks[CPU_STATE_USER]; *pulNice += structCpuData[i].cpu_ticks[CPU_STATE_NICE]; *pulIdle += structCpuData[i].cpu_ticks[CPU_STATE_IDLE]; } } #endif }
5,408
C++
.cc
169
27.195266
122
0.655265
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,447
swarpfilter.cc
schirmermischa_THELI/src/tools/swarpfilter.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include <fitsio.h> #include <omp.h> #include "swarpfilter.h" #include "../myimage/myimage.h" #include "../functions.h" #include <QVector> #include <QDebug> #include <QTextStream> SwarpFilter::SwarpFilter(QString coadddirname, QString kappaString, QString clustersizeString, QString borderwidthString, bool checkflux, int maxCPU, int *verbose) { // Probably not needed, unless to case distinct linux and mac initEnvironment(thelidir, userdir); coaddDirName = coadddirname; nthreads = maxCPU; verbosity = verbose; if (!kappaString.isEmpty()) kappa = kappaString.toInt(); if (!borderwidthString.isEmpty()) maskWidth = borderwidthString.toInt(); if (!clustersizeString.isEmpty()) clusterSize = clustersizeString.toInt(); if (clusterSize > 9) clusterSize = 9; // upper limit checkFluxScale = checkflux; coaddDir.setPath(coaddDirName); if (!coaddDir.exists()) { qDebug() << "QDEBUG: SwarpFilter(): Could not find coadd directory" << coaddDirName; return; } omp_init_lock(&lock); } void SwarpFilter::init() { // Collect information about the coadded image and the resampled images getImages(); getCoaddInfo(); getGeometries(); // RAM considerations getBlocksize(); // Set the size for the containers initStorage(); } SwarpFilter::~SwarpFilter() { omp_destroy_lock(&lock); } void SwarpFilter::freeMemoryVectors() { images.clear(); weights.clear(); naxis1.clear(); naxis2.clear(); crpix1.clear(); crpix2.clear(); sky.clear(); fluxscale.clear(); xoffset.clear(); yoffset.clear(); images.squeeze(); weights.squeeze(); naxis1.squeeze(); naxis2.squeeze(); crpix1.squeeze(); crpix2.squeeze(); sky.squeeze(); fluxscale.squeeze(); xoffset.squeeze(); yoffset.squeeze(); } void SwarpFilter::freeMemoryBlocks() { for (long i=0; i<num_images; ++i) { block_coadd_image[i].clear(); block_coadd_index[i].clear(); block_coadd_image[i].squeeze(); block_coadd_index[i].squeeze(); } block_coadd_image.clear(); block_coadd_index.clear(); block_coadd_image.squeeze(); block_coadd_index.squeeze(); } // This does not read the data sections, it just creates MyImage pointers to the resampled images and weights void SwarpFilter::getImages() { if (!successProcessing) return; // Fill the list of MyImage types of individual images and master calibration files in this data directory QStringList filter; filter << "*resamp.fits"; QStringList resampledImages = coaddDir.entryList(filter); num_images = resampledImages.length(); for (auto &it : resampledImages) { QString base = it.remove("resamp.fits"); QFile img(coaddDirName+"/"+base+"resamp.fits"); QFile wgt(coaddDirName+"/"+base+"resamp.weight.fits"); if (!img.exists() || !wgt.exists()) { emit messageAvailable("ERROR: SwarpFilter::getImages(): Image " + base + " resamp.[weight].fits does not exist!", "error"); successProcessing = false; return; } // global masks don't apply here because of different image geometry. Hence passing QVector<bool>() QVector<bool> dummyMask; dummyMask.clear(); MyImage *myImage = new MyImage(coaddDirName, base+"resamp.fits", "", 0, dummyMask, verbosity); MyImage *myWeight = new MyImage(coaddDirName, base+"resamp.weight.fits", "", 0, dummyMask, verbosity); images.append(myImage); weights.append(myWeight); } emit messageAvailable("Including "+QString::number(num_images)+" images ...", "config"); } void SwarpFilter::getCoaddInfo() { if (!successProcessing) return; QFile coaddHead(coaddDirName+"/coadd.head"); if (!coaddHead.open(QIODevice::ReadOnly)) { emit messageAvailable("ERROR: SwarpFilter::getCoaddInfo(): "+coaddHead.fileName() + " " +coaddHead.errorString(), "error"); successProcessing = false; return; } QTextStream in(&coaddHead); while(!in.atEnd()) { QString line = in.readLine(); if (line.contains("NAXIS1 =")) coadd_naxis1 = line.split("=")[1].simplified().split(" ")[0].toLong(); if (line.contains("NAXIS2 =")) coadd_naxis2 = line.split("=")[1].simplified().split(" ")[0].toLong(); if (line.contains("CRPIX1 =")) coadd_crpix1 = line.split("=")[1].simplified().split(" ")[0].toFloat(); if (line.contains("CRPIX2 =")) coadd_crpix2 = line.split("=")[1].simplified().split(" ")[0].toFloat(); } coaddHead.close(); emit messageAvailable("coadd.head found ...", "config"); } void SwarpFilter::getGeometries() { if (!successProcessing) return; double crpix1tmp = 0.; double crpix2tmp = 0.; long naxis1tmp = 0; long naxis2tmp = 0; double skytmp = 0.; double fluxscaletmp = 0.; crpix1.reserve(num_images); crpix2.reserve(num_images); naxis1.reserve(num_images); naxis2.reserve(num_images); sky.reserve(num_images); fluxscale.reserve(num_images); for (auto &it : images) { if (!it->informSwarpfilter(naxis1tmp, naxis2tmp, crpix1tmp, crpix2tmp, skytmp, fluxscaletmp, checkFluxScale)) { // TODO: This error does not lead to an abort in the stack of swarp command threads. QString message = "SwarpFilter::loadGeometries(): One or more keywords not found in resampled images:\nNAXIS1, NAXIS2, CRPIX1, CRPIX2, SKYVALUE, FLXSCALE"; emit messageAvailable(message, "error"); emit critical(); successProcessing = false; return; } naxis1.append(naxis1tmp); naxis2.append(naxis2tmp); crpix1.append(crpix1tmp); crpix2.append(crpix2tmp); sky.append(skytmp * fluxscaletmp); // rescaled sky values (corrected for relative transparency) fluxscale.append(fluxscaletmp); xoffset.append(coadd_crpix1 - crpix1tmp); yoffset.append(coadd_crpix2 - crpix2tmp); } emit messageAvailable("Geometries of the resampled images loaded ...", "config"); } // The maximum number of lines that can be read without filling up the RAM void SwarpFilter::getBlocksize() { if (!successProcessing) return; long systemRAM = 1024 * get_memory(); // maxmimum memory used: 50% of the available RAM blocksize = 0.5 * systemRAM / (coadd_naxis1 * sizeof(float) * num_images * 2); blocksize = 0.1 * systemRAM / (coadd_naxis1 * sizeof(float) * num_images * 2); blocksize = blocksize > coadd_naxis2 ? coadd_naxis2 : blocksize; // upper limit if (blocksize < 1) { emit messageAvailable("ERROR: SwarpFilter::getBlocksize(): Not enough memory available for SwarpFilter", "error"); return; } // TODO: introduce upper limit, like naxis2[i]? Variable between images. // What happens if larger than naxis2[i]? if (blocksize > 300) blocksize = 300; // upper limit (can probably be dropped after some testing) chunksize = coadd_naxis1 * blocksize; nblocks = long(coadd_naxis2 / blocksize + 1.); emit messageAvailable("Block size = "+QString::number(blocksize) + ", Number of blocks = "+QString::number(nblocks), "config"); } void SwarpFilter::initStorage() { if (!successProcessing) return; block_coadd_image.resize(num_images); block_coadd_index.resize(num_images); sky.resize(num_images); badpixindex.resize(num_images); for (long i=0; i<num_images; ++i) { badpixindex[i].reserve(10000); } } //****************************************************************** void SwarpFilter::runCosmicFilter() { // Doing the init here, so that the signals get heard outside (connections are made after the constructor). init(); if (!successProcessing) return; progressStepSize = 66. / nblocks; emit messageAvailable("Identifying outliers ...", "output"); // load the images and identify bad pixels for (long block=0; block<nblocks; ++block) { QVector<long> presentImages; presentImages.reserve(num_images); if (*verbosity >= 2) emit messageAvailable("Processing block " + QString::number(block+1) + "/" + QString::number(nblocks)+" ...", "output"); // read a chunk of data from the images #pragma omp parallel num_threads(nthreads) { // two private temporary containers QVector<float> resampledData; QVector<long> resampledCoaddIndex; // loop over resampled images #pragma omp for for (long i=0; i<num_images; ++i) { // read a chunk of data overlapping with the current block bool isImagePresent = get_coaddblock(i, block, resampledData, resampledCoaddIndex); // transfer of pixel data must be sequential #pragma omp critical (updateBlockData) { if (isImagePresent) presentImages.append(i); block_coadd_image[i].swap(resampledData); block_coadd_index[i].swap(resampledCoaddIndex); } } } // if this block does not contain resampled images (bottom or top borders of coadded image) if (presentImages.isEmpty()) continue; // find the bad pixels #pragma omp parallel num_threads(nthreads) { // bad pixel pair (index in the coadded image and index in the individual frame) QVector<std::pair<long,long>> bpp; bpp.reserve(100000); QVector<float> gooddata; // The pixel values of the images contributing to a coadded pixel QVector<long> gooddataind; // The index of an image contributing to a coadded pixel gooddata.reserve(num_images); // maximally num_images will contribute to a coadded pixel gooddataind.reserve(num_images); #pragma omp for for (long l=0; l<chunksize; ++l) { // loop over coadded pixels for (auto &pi : presentImages) { // Loop over all images present at the current coadded pixel long pixpos = block_coadd_index[pi][l]; // The index of the current coadded pixel in the coord system of the resampled image if (pixpos >= 0) { // Negative if image does not overlap with current pixel float value = block_coadd_image[pi][pixpos]; if (value != 0.) { // If a pixel has value zero then it was most likely masked gooddata.append(value); // pixel value gooddataind.append(pi); // image index } } } long ngoodweight = gooddata.length(); // Number of pixels contributing to a coadded pixel long currentpixel = l + block*chunksize; identify_bad_pixels(gooddata, gooddataind, currentpixel, ngoodweight, bpp); gooddata.clear(); gooddataind.clear(); } #pragma omp critical (updateBadPixels) { updateBadPixelIndex(bpp); } } // Reset the block data. Not sure why this is necessary. Perhaps caused by swap()? for (long i=0; i<num_images; ++i) { block_coadd_image[i].clear(); block_coadd_index[i].clear(); } #pragma omp atomic *progress += progressStepSize; emit progressUpdate(*progress); } // The badpixindex must be sorted! for (auto &bp : badpixindex) { std::sort(bp.begin(), bp.end()); } freeMemoryBlocks(); // Writing results writeWeight(); freeMemoryVectors(); } void SwarpFilter::updateBadPixelIndex(const QVector<std::pair<long,long>> bpp) { if (!successProcessing) return; for (auto &pair : bpp) { badpixindex[pair.first].append(pair.second); } } //*************************************************************************************** // Load a section of one of the resampled images // (a block naxis1 wide and some rows high) //*************************************************************************************** bool SwarpFilter::get_coaddblock(const int index, const long block, QVector<float> &resampledData, QVector<long> &resampledCoaddIndex) { // index == current image long bbs0 = block * blocksize; long bbs1 = bbs0 + blocksize; // nothing to do if the image is entirely below or above the current coadd block if (yoffset[index] + naxis2[index] <= bbs0 || yoffset[index] >= bbs1) { return false; } // The image overlaps with the current coadd block // assume that the image covers the block entirely: long firstline2read = bbs0 - yoffset[index]; // we start counting at 0! long lastline2read = firstline2read + blocksize - 1; // we start counting at 0! // if the image does not cover the lower part of the block // but the upper part entirely if (firstline2read < 0 && yoffset[index] + naxis2[index] >= bbs1) { lastline2read = bbs1 - yoffset[index] - 1; firstline2read = 0; } // if the image does not cover the upper part of the block // but the lower part entirely if (yoffset[index] + naxis2[index] < bbs1 && yoffset[index] <= bbs0) { lastline2read = naxis2[index] - 1; firstline2read = bbs0 - yoffset[index]; } // if the image is entirely contained in the block // without touching its borders if (yoffset[index] > bbs0 && yoffset[index] + naxis2[index] < bbs1) { firstline2read = 0; lastline2read = naxis2[index] - 1; } int nsub = naxis1[index]; int msub = lastline2read - firstline2read + 1; float *data_in = new float[nsub*msub]; // Load the data sections; // One could load the weights too, but that would double the memory load for very little return // We later on reject image pixels with zero value; likely they have zero weight; what would be missed is manually masked areas, such as satellites. // But the algorithm is supposed to detect them anyway, so no harm done by skipping the weights. images[index]->loadDataSection(0, naxis1[index]-1, firstline2read, lastline2read, data_in); long l = 0; // the running index of the image long k = 0; // the running index of the coadd [0,chunksize) resampledData.reserve(naxis1[index]*(lastline2read-firstline2read+1)); // Contains valid data points, only resampledCoaddIndex.resize(coadd_naxis1*blocksize); // Must stretch over the entire chunksize for (auto &it: resampledCoaddIndex) it = -1; // Initialize with invalid index // Map the image pixels onto the coadded image block. // Save some CPU cycles and do array calculations outside the loop long xoff = xoffset[index]; long yoff = yoffset[index]; long nax1 = naxis1[index]; long nax2 = naxis2[index]; float fluxcorr = fluxscale[index]; for (long j=0; j<blocksize; ++j) { long yi = bbs0 + j - yoff; for (long i=0; i<coadd_naxis1; ++i) { long xi = i - xoff; // if the image overlaps with the coadd block if (xi >= 0 && yi >= 0 && xi < nax1 && yi < nax2) { resampledData.append(data_in[l] * fluxcorr); resampledCoaddIndex[k] = l; ++l; } ++k; } } if (l==0) { emit messageAvailable("SwarpFilter:getCoaddBlock(): No overlap was found<br>" +images[index]->name + " : First line / last line: " + QString::number(firstline2read) + " " + QString::number(lastline2read), "error"); return false; } delete [] data_in; data_in = nullptr; return true; } //*************************************************************************************** // Identify the bad pixels in a stack //*************************************************************************************** void SwarpFilter::identify_bad_pixels(const QVector<float> &gooddata, const QVector<long> &gooddataind, const long &currentpixel, const long &ngoodweight, QVector<std::pair<long,long>> &bpp) { if (!successProcessing) return; // no rejection if less than 2 pixels contributing to a coadded pixel if (ngoodweight < 2 ) return; float mean = 0.; float rms = 0.; float thresh = 0.; // we could determine ngoodweight from gooddata itself, but the length is already known // and thus it is cheaper to just take it as an argument // long ngoodweight = gooddata.length(); // NOTE: I tried to compare (it-mean)^2 against thresh*thresh // instead of fabs(it-mean) against thresh, to avoid the expensive sqrt(). // However, the overall performance gain is on the order of 2-3%, hence I drop this for code clarity // 2 pixels in the stack: use poisson rms estimated from sky noise if (ngoodweight == 2) { float sum = gooddata[0] + gooddata[1]; mean = 0.5 * sum; rms = sum + (sky[gooddataind[0]] + sky[gooddataind[1]]); if (rms > 0.) { thresh = sqrt(0.5 * rms); } else return; // no rejection of bad pixels } // 3-4 pixels in the stack: reject max pixel else if (ngoodweight <= 4) { stackfilter_rejectmax(gooddata, mean, rms); if (rms > 0.) { mean /= (ngoodweight - 1); rms = sqrt(((ngoodweight - 1) / (ngoodweight - 2)) * (rms / (ngoodweight - 1) - mean * mean)); thresh = 6. * kappa / ngoodweight * rms; } else return; // no rejection of bad pixels } // 5 or more pixels in the stack: reject min and max pixel else { stackfilter_MAD(gooddata, mean, rms); thresh = kappa * rms; // stackfilter_rejectminmax(gooddata, mean, rms); // if (rms > 0.) { // mean /= (ngoodweight - 2); // rms = sqrt(((ngoodweight - 2) / (ngoodweight - 3)) * (rms / (ngoodweight - 2) - mean * mean)); // adaptive rms threshold // if (ngoodweight < 6) thresh = 6. * kappa / ngoodweight * rms; // else thresh = kappa * rms; // } // else return; // no rejection of bad pixels } if (ngoodweight > 2) { long i=0; for (auto &it : gooddata) { if (fabs(it - mean) > thresh) { bpp.append(std::make_pair(gooddataind[i], currentpixel)); } ++i; } } else { long i=0; for (auto &it : gooddata) { if (fabs(it - mean) > thresh) { // reject pixel only if it is the brighter one if ((i == 0 && gooddata[0] > gooddata[1]) || (i == 1 && gooddata[1] > gooddata[0])) { bpp.append(std::make_pair(gooddataind[i], currentpixel)); } } ++i; } } } //*************************************************************************************** // ID the max value in the stack, reject it, and calculate meansq and rmssq //*************************************************************************************** void SwarpFilter::stackfilter_rejectmax(const QVector<float> &gooddata, float &meanval, float &rmsval) { if (!successProcessing) return; float maxval = gooddata[0]; meanval = 0.; rmsval = 0.; for (auto &it : gooddata) { if (it > maxval) maxval = it; meanval += it; rmsval += it*it; } meanval -= maxval; rmsval -= (maxval*maxval); } //*************************************************************************************** // ID the min and max values in the stack, reject them, and calculate meansq and rmssq //*************************************************************************************** void SwarpFilter::stackfilter_rejectminmax(const QVector<float> &gooddata, float &meanval, float &rmsval) { if (!successProcessing) return; float minval = gooddata[0]; float maxval = gooddata[0]; meanval = 0.; rmsval = 0.; for (auto &it : gooddata) { if (it < minval) minval = it; else if (it > maxval) maxval = it; meanval += it; rmsval += it*it; } meanval -= (minval + maxval); rmsval -= (minval*minval + maxval*maxval); } //*************************************************************************************** // ID the min and max values in the stack, reject them, and calculate meansq and rmssq //*************************************************************************************** void SwarpFilter::stackfilter_MAD(const QVector<float> &gooddata, float &meanval, float &rmsval) { if (!successProcessing) return; rmsval = 1.486*madMask_T(gooddata); QVector<bool> mask = QVector<bool>(gooddata.length(), false); float med = straightMedian_T(gooddata); long i = 0; for (auto &it : gooddata) { if (fabs(it-med) > 3.0*rmsval) mask[i] = true; ++i; } meanval = medianMask_T(gooddata, mask); } //************************************************************** void SwarpFilter::writeWeight() { if (!successProcessing) return; // cout << "This is thread " << args->th << endl; emit messageAvailable("Writing updated weight maps ...", "output"); progressStepSize = 34. / num_images; #pragma omp parallel for num_threads(nthreads) for (long i=0; i<num_images; ++i) { long n = naxis1[i]; long m = naxis2[i]; QVector<char> weight_out(n*m, 1); // 1 = pixel is good, 0 = pixel is bad QVector<char> weight_cpy(n*m, 1); long s = 0; long t = 0; long nbadpix = badpixindex[i].size(); // mask all bad pixels found for (long j=yoffset[i]; j<(yoffset[i] + m); ++j) { if (t==nbadpix) break; for (long l=xoffset[i]; l<(xoffset[i] + n); ++l) { if (t==nbadpix) break; long k = l + coadd_naxis1 * j; // WARNING: THIS IS FAST, BUT ASSUMES A SORTED BADPIX INDEX! if (k == badpixindex[i][t]) { weight_out[s] = 0; if (clusterSize < 2) weight_cpy[s] = 0; ++t; } ++s; } } // NOTE: // There could be many more masked pixels in badpixindex[i] than visibly marked in the end, // if the clustersize is larger than 1. // mask only clusters consisting of at least 'clustersize' pixels if (clusterSize > 1) { // we ignore the 1 pixel wide border of the image for (long j=1; j<m-1; ++j) { for (long k=1; k<n-1; ++k) { if (weight_out[k+n*j] == 0) { long clustercount = 1; for (long l=j-1; l<=j+1; ++l) { for (long o=k-1; o<=k+1; ++o) { clustercount += (weight_out[o+(l*n)] ^ 1); } } if (clustercount >= clusterSize) { for (long l=j-1; l<=j+1; ++l) { for (long o=k-1; o<=k+1; ++o) { weight_cpy[o+(l*n)] = weight_out[o+(l*n)]; } } } } } } // copy the vectors weight_out = weight_cpy; } // if a border of width 'width' pixels should be masked around a // bad pixel, too if (maskWidth > 0) { for (long j=0; j<m; ++j) { for (long k=0; k<n; ++k) { if (weight_cpy[k+n*j] == 0) { long jmW0 = j - maskWidth; long kmW0 = k - maskWidth; long jmW1 = j + maskWidth; long kmW1 = k + maskWidth; long masklinemin = jmW0 < 0 ? 0 : jmW0; long maskcolmin = kmW0 < 0 ? 0 : kmW0; long masklinemax = jmW1 > (m - 1) ? (m - 1) : jmW1; long maskcolmax = kmW1 > (n - 1) ? (n - 1) : kmW1; for (long l=masklinemin; l <= masklinemax; ++l) { for (long o=maskcolmin; o <= maskcolmax; ++o) { weight_out[o+(l*n)] = 0; } } } } } } QString outName = weights[i]->path + "/" + weights[i]->name; // Modify the resampled weight and write it weights[i]->readImage(outName); long k=0; for (auto &pixel : weights[i]->dataCurrent) { pixel *= weight_out[k]; ++k; } weights[i]->writeImage(outName); weights[i]->freeData(); #pragma omp atomic *progress += progressStepSize; emit progressUpdate(*progress); } }
26,102
C++
.cc
603
34.913765
167
0.572047
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,448
correlator.cc
schirmermischa_THELI/src/tools/correlator.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "correlator.h" #include "../myimage/myimage.h" #include <fftw3.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_matrix.h> // #include "Array.h" // #include "fftw++.h" #include <QDebug> Correlator::Correlator(const MyImage *refimg, const MyImage *comimg, QObject *parent) : QObject(parent) { naxis1 = refimg->naxis1; naxis2 = refimg->naxis2; if (refimg->naxis1 != comimg->naxis1 || refimg->naxis2 != comimg->naxis2) { qDebug() << "ERROR: Correlator(): images have different geometries!"; successProcessing = false; } padImages(refimg->dataCurrent, comimg->dataCurrent); } void Correlator::padImages(const QVector<float> &dataref, const QVector<float> &datacom) { if (! successProcessing) return; // Zeropad data, to accomodate very large offsets // Max offset is the full field of view, thus we double the image size n_pad = 2*naxis1-1; m_pad = 2*naxis2-1; dataRef.resize(n_pad*m_pad); dataCom.resize(n_pad*m_pad); dataCorrelated.resize(n_pad*m_pad); dataRef.squeeze(); dataCom.squeeze(); dataCorrelated.squeeze(); int left = naxis1/2; int right = naxis1/2; int bottom = naxis2/2; int top = naxis2/2; for (int j=0; j<m_pad; ++j) { for (int i=0; i<n_pad; ++i) { if (i>=left && i<n_pad-right && j>=bottom && j<m_pad-top) { dataRef[i+n_pad*j] = dataref[i-left + naxis1*(j-bottom)]; dataCom[i+n_pad*j] = datacom[i-left + naxis1*(j-bottom)]; } else { dataRef[i+n_pad*j] = 0.; dataCom[i+n_pad*j] = 0.; } } } } void Correlator::xcorrelate() { /* int n = n_pad; int m = m_pad; int mp = m_pad/2 + 1; size_t align = sizeof(Complex); Array::array2<double> fa(n,m,align), fb(n,m,align); Array::array2<Complex> ga(n,mp,align), gb(n,mp,align); fftwpp::rcfft2d Forward_a(n,m,fa,ga); fftwpp::rcfft2d Forward_b(n,m,fb,gb); fftwpp::crfft2d Backward(n,m,ga,fa); // write the data into arrays for (int i=0; i<n; i++) { for (int j=0; j<m; j++) { fa(i,j) = dataRef[i+n*j]; fb(i,j) = dataCom[i+n*j]; } } // Forward FFT Forward_a.fft0(fa,ga); Forward_b.fft0(fb,gb); Complex scale = 1.0/(n*m); // cross-correlation for (int i=0; i<n; i++) { for (int j=0; j<mp; j++) { ga(i,j) *= conj(gb(i,j)) * scale; } } // Backward FFT Backward.fft0Normalized(ga,fa); // put things back into a vector for (int i=0; i<n; i++) { for (int j=0; j<m; j++) { dataCorrelated[i+n*j] = fa(i,j); } } // swap upper half with lower half for (int i=0; i<n*m/2; i++) { float tmp = dataCorrelated[i]; dataCorrelated[i] = dataCorrelated[i+n*m/2]; dataCorrelated[i+n*m/2] = tmp; } // the cross-correlation image is symmetric, hence we don't need // to swap the left and right halves */ } //*************************************************************** QVector<float> Correlator::find_peak() { if (! successProcessing) return QVector<float>(); /* long ipos = 0; long jpos = 0; double max = 0.; // ignore the boundary (FFT may put spurious pixels there) // we choose a 3 pixel wide boundary, so there won't be any boundary issues when assigning the 7x7 subarray for (int j=3; j<m_pad-3; ++j) { for (int i=3; i<n_pad-3; ++i) { if (dataCorrelated[i+n_pad*j] >= max) { ipos = i; jpos = j; max = (double) dataCorrelated[i+n_pad*j]; } } } double xpos = (double) ipos; double ypos = (double) jpos; // we fit a 7x7 pixel area centred on the maximum pixel const size_t nx = 7, ny = 7, n = 7*7; const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; const size_t p = 4; gsl_matrix *covar = gsl_matrix_alloc (p, p); double z[n], sigma[n]; struct dataGSL d = { nx, ny, z, sigma }; gsl_multifit_function_fdf f; const gsl_rng_type *type; gsl_rng *r; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &gauss_f; f.df = &gauss_df; f.fdf = &gauss_fdf; f.n = n; f.p = p; f.params = &d; // The data in which we search the maximum unsigned int k = 0; for (int j=-3; j<=3; ++j) { for (int i=-3; i<=3; ++i) { z[k] = dataCorrelated[ipos+i+n_pad*(jpos+j)] / max; sigma[k++] = 1.; // same weight for all pixels } } // the initial guess has to be as close as possible (totally sucks...) double x_init[4] = { 1.0, 3.0, 3.0, 2.0 }; gsl_vector_view x = gsl_vector_view_array (x_init, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, &f, &x.vector); unsigned int iter = 0; do { ++iter; status = gsl_multifit_fdfsolver_iterate(s); if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4); } while (status == GSL_CONTINUE && iter < 50000); // gsl_multifit_covar (s->J, 0.0, covar); #define FIT(i) gsl_vector_get(s->x, i) // #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) QVector<float> result; result.append(FIT(1)+xpos-3.0+1.0); result.append(FIT(2)+ypos-3.0+1.0); gsl_multifit_fdfsolver_free(s); gsl_matrix_free(covar); gsl_rng_free(r); return result */ return QVector<float>(); }
6,442
C++
.cc
190
28.094737
111
0.595453
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,449
cfitsioerrorcodes.cc
schirmermischa_THELI/src/tools/cfitsioerrorcodes.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "cfitsioerrorcodes.h" #include <QMap> CfitsioErrorCodes::CfitsioErrorCodes(QObject *parent) : QObject(parent) { populateErrorKeyMap(); } void CfitsioErrorCodes::populateErrorKeyMap() { errorKeyMap.insert(101, "SAME_FILE: input and output files are the same"); errorKeyMap.insert(103, "TOO_MANY_FILES: tried to open too many FITS files"); errorKeyMap.insert(104, "FILE_NOT_OPENED: could not open the named file"); errorKeyMap.insert(105, "FILE_NOT_CREATED: could not create the named file"); errorKeyMap.insert(106, "WRITE_ERROR: error writing to FITS file"); errorKeyMap.insert(107, "END_OF_FILE: tried to move past end of file"); errorKeyMap.insert(108, "READ_ERROR: error reading from FITS file"); errorKeyMap.insert(110, "FILE_NOT_CLOSED: could not close the file"); errorKeyMap.insert(111, "ARRAY_TOO_BIG: array dimensions exceed internal limit"); errorKeyMap.insert(112, "READONLY_FILE: Cannot write to readonly file"); errorKeyMap.insert(113, "MEMORY_ALLOCATION: Could not allocate memory"); errorKeyMap.insert(114, "BAD_FILEPTR: invalid fitsfile pointer"); errorKeyMap.insert(115, "NULL_INPUT_PTR: NULL input pointer to routine"); errorKeyMap.insert(116, "SEEK_ERROR: error seeking position in file"); errorKeyMap.insert(121, "BAD_URL_PREFIX: invalid URL prefix on file name"); errorKeyMap.insert(122, "TOO_MANY_DRIVERS: tried to register too many IO drivers"); errorKeyMap.insert(123, "DRIVER_INIT_FAILED: driver initialization failed"); errorKeyMap.insert(124, "NO_MATCHING_DRIVER: matching driver is not registered"); errorKeyMap.insert(125, "URL_PARSE_ERROR: failed to parse input file URL"); errorKeyMap.insert(126, "RANGE_PARSE_ERROR: failed to parse input file URL"); errorKeyMap.insert(150, "SHARED_ERRBASE"); errorKeyMap.insert(151, "SHARED_BADARG"); errorKeyMap.insert(152, "SHARED_NULPTR"); errorKeyMap.insert(153, "SHARED_TABFULL"); errorKeyMap.insert(154, "SHARED_NOTINIT"); errorKeyMap.insert(155, "SHARED_IPCERR"); errorKeyMap.insert(156, "SHARED_NOMEM"); errorKeyMap.insert(157, "SHARED_AGAIN"); errorKeyMap.insert(158, "SHARED_NOFILE"); errorKeyMap.insert(159, "SHARED_NORESIZE"); errorKeyMap.insert(201, "HEADER_NOT_EMPTY: header already contains keywords"); errorKeyMap.insert(202, "KEY_NO_EXIST: keyword not found in header"); errorKeyMap.insert(203, "KEY_OUT_BOUNDS: keyword record number is out of bounds"); errorKeyMap.insert(204, "VALUE_UNDEFINED: keyword value field is blank"); errorKeyMap.insert(205, "NO_QUOTE: string is missing the closing quote"); errorKeyMap.insert(206, "BAD_INDEX_KEY: illegal indexed keyword name"); errorKeyMap.insert(207, "BAD_KEYCHAR: illegal character in keyword name or card"); errorKeyMap.insert(208, "BAD_ORDER: required keywords out of order"); errorKeyMap.insert(209, "NOT_POS_INT: keyword value is not a positive integer"); errorKeyMap.insert(210, "NO_END: couldn't find END keyword"); errorKeyMap.insert(211, "BAD_BITPIX: illegal BITPIX keyword value"); errorKeyMap.insert(212, "BAD_NAXIS: illegal NAXIS keyword value"); errorKeyMap.insert(213, "BAD_NAXES: illegal NAXISn keyword value"); errorKeyMap.insert(214, "BAD_PCOUNT: illegal PCOUNT keyword value"); errorKeyMap.insert(215, "BAD_GCOUNT: illegal GCOUNT keyword value"); errorKeyMap.insert(216, "BAD_TFIELDS: illegal TFIELDS keyword value"); errorKeyMap.insert(217, "NEG_WIDTH: negative table row size"); errorKeyMap.insert(218, "NEG_ROWS: negative number of rows in table"); errorKeyMap.insert(219, "COL_NOT_FOUND: column with this name not found in table"); errorKeyMap.insert(220, "BAD_SIMPLE: illegal value of SIMPLE keyword "); errorKeyMap.insert(221, "NO_SIMPLE: Primary array doesn't start with SIMPLE"); errorKeyMap.insert(222, "NO_BITPIX: Second keyword not BITPIX"); errorKeyMap.insert(223, "NO_NAXIS: Third keyword not NAXIS"); errorKeyMap.insert(224, "NO_NAXES: Couldn't find all the NAXISn keywords"); errorKeyMap.insert(225, "NO_XTENSION: HDU doesn't start with XTENSION keyword"); errorKeyMap.insert(226, "NOT_ATABLE: the CHDU is not an ASCII table extension"); errorKeyMap.insert(227, "NOT_BTABLE: the CHDU is not a binary table extension"); errorKeyMap.insert(228, "NO_PCOUNT: couldn't find PCOUNT keyword"); errorKeyMap.insert(229, "NO_GCOUNT: couldn't find GCOUNT keyword"); errorKeyMap.insert(230, "NO_TFIELDS: couldn't find TFIELDS keyword"); errorKeyMap.insert(231, "NO_TBCOL: couldn't find TBCOLn keyword"); errorKeyMap.insert(232, "NO_TFORM: couldn't find TFORMn keyword"); errorKeyMap.insert(233, "NOT_IMAGE: the CHDU is not an IMAGE extension"); errorKeyMap.insert(234, "BAD_TBCOL: TBCOLn keyword value < 0 or > rowlength"); errorKeyMap.insert(235, "NOT_TABLE: the CHDU is not a table"); errorKeyMap.insert(236, "COL_TOO_WIDE: column is too wide to fit in table"); errorKeyMap.insert(237, "COL_NOT_UNIQUE: more than 1 column name matches template"); errorKeyMap.insert(241, "BAD_ROW_WIDTH: sum of column widths not = NAXIS1"); errorKeyMap.insert(251, "UNKNOWN_EXT: unrecognizable FITS extension type"); errorKeyMap.insert(252, "UNKNOWN_REC: unrecognizable FITS record"); errorKeyMap.insert(253, "END_JUNK: END keyword is not blank"); errorKeyMap.insert(254, "BAD_HEADER_FILL: Header fill area not blank"); errorKeyMap.insert(255, "BAD_DATA_FILL: Data fill area not blank or zero"); errorKeyMap.insert(261, "BAD_TFORM: illegal TFORM format code"); errorKeyMap.insert(262, "BAD_TFORM_DTYPE: unrecognizable TFORM datatype code"); errorKeyMap.insert(263, "BAD_TDIM: illegal TDIMn keyword value"); errorKeyMap.insert(264, "BAD_HEAP_PTR: invalid BINTABLE heap address"); errorKeyMap.insert(301, "BAD_HDU_NUM: HDU number < 1 or > MAXHDU"); errorKeyMap.insert(302, "BAD_COL_NUM: column number < 1 or > tfields"); errorKeyMap.insert(304, "NEG_FILE_POS: tried to move before beginning of file "); errorKeyMap.insert(306, "NEG_BYTES: tried to read or write negative bytes"); errorKeyMap.insert(307, "BAD_ROW_NUM: illegal starting row number in table"); errorKeyMap.insert(308, "BAD_ELEM_NUM: illegal starting element number in vector"); errorKeyMap.insert(309, "NOT_ASCII_COL: this is not an ASCII string column"); errorKeyMap.insert(310, "NOT_LOGICAL_COL: this is not a logical datatype column"); errorKeyMap.insert(311, "BAD_ATABLE_FORMAT: ASCII table column has wrong format"); errorKeyMap.insert(312, "BAD_BTABLE_FORMAT: Binary table column has wrong format"); errorKeyMap.insert(314, "NO_NULL: null value has not been defined"); errorKeyMap.insert(317, "NOT_VARI_LEN: this is not a variable length column"); errorKeyMap.insert(320, "BAD_DIMEN: illegal number of dimensions in array"); errorKeyMap.insert(321, "BAD_PIX_NUM: first pixel number greater than last pixel"); errorKeyMap.insert(322, "ZERO_SCALE: illegal BSCALE or TSCALn keyword = 0"); errorKeyMap.insert(323, "NEG_AXIS: illegal axis length < 1"); errorKeyMap.insert(340, "NOT_GROUP_TABLE"); errorKeyMap.insert(341, "HDU_ALREADY_MEMBER"); errorKeyMap.insert(342, "MEMBER_NOT_FOUND"); errorKeyMap.insert(343, "GROUP_NOT_FOUND"); errorKeyMap.insert(344, "BAD_GROUP_ID"); errorKeyMap.insert(345, "TOO_MANY_HDUS_TRACKED"); errorKeyMap.insert(346, "HDU_ALREADY_TRACKED"); errorKeyMap.insert(347, "BAD_OPTION"); errorKeyMap.insert(348, "IDENTICAL_POINTERS"); errorKeyMap.insert(349, "BAD_GROUP_ATTACH"); errorKeyMap.insert(350, "BAD_GROUP_DETACH"); errorKeyMap.insert(360, "NGP_NO_MEMORY: malloc failed"); errorKeyMap.insert(361, "NGP_READ_ERR: read error from file"); errorKeyMap.insert(362, "NGP_NUL_PTR: null pointer passed as argument"); errorKeyMap.insert(363, "NGP_EMPTY_CURLINE: line read seems to be empty"); errorKeyMap.insert(364, "NGP_UNREAD_QUEUE_FULL: cannot unread more then 1 line (or single line twice)"); errorKeyMap.insert(365, "NGP_INC_NESTING: too deep include file nesting (inf. loop ?)"); errorKeyMap.insert(366, "NGP_ERR_FOPEN: fopen() failed, cannot open file"); errorKeyMap.insert(367, "NGP_EOF: end of file encountered"); errorKeyMap.insert(368, "NGP_BAD_ARG: bad arguments passed"); errorKeyMap.insert(369, "NGP_TOKEN_NOT_EXPECT: token not expected here"); errorKeyMap.insert(401, "BAD_I2C: bad int to formatted string conversion"); errorKeyMap.insert(402, "BAD_F2C: bad float to formatted string conversion"); errorKeyMap.insert(403, "BAD_INTKEY: can't interprete keyword value as integer"); errorKeyMap.insert(404, "BAD_LOGICALKEY: can't interprete keyword value as logical"); errorKeyMap.insert(405, "BAD_FLOATKEY: can't interprete keyword value as float"); errorKeyMap.insert(406, "BAD_DOUBLEKEY: can't interprete keyword value as double"); errorKeyMap.insert(407, "BAD_C2I: bad formatted string to int conversion"); errorKeyMap.insert(408, "BAD_C2F: bad formatted string to float conversion"); errorKeyMap.insert(409, "BAD_C2D: bad formatted string to double conversion"); errorKeyMap.insert(410, "BAD_DATATYPE: bad keyword datatype code"); errorKeyMap.insert(411, "BAD_DECIM: bad number of decimal places specified"); errorKeyMap.insert(412, "NUM_OVERFLOW: overflow during datatype conversion"); errorKeyMap.insert(413, "DATA_COMPRESSION_ERR: error in imcompress routines"); errorKeyMap.insert(414, "DATA_DECOMPRESSION_ERR: error in imcompress routines"); errorKeyMap.insert(415, "NO_COMPRESSED_TILE: compressed tile doesn't exist"); errorKeyMap.insert(420, "BAD_DATE: error in date or time conversion"); errorKeyMap.insert(431, "PARSE_SYNTAX_ERR: syntax error in parser expression"); errorKeyMap.insert(432, "PARSE_BAD_TYPE: expression did not evaluate to desired type"); errorKeyMap.insert(433, "PARSE_LRG_VECTOR: vector result too large to return in array"); errorKeyMap.insert(434, "PARSE_NO_OUTPUT: data parser failed not sent an out column"); errorKeyMap.insert(435, "PARSE_BAD_COL: bad data encounter while parsing column"); errorKeyMap.insert(436, "PARSE_BAD_OUTPUT: Output file not of proper type"); errorKeyMap.insert(501, "ANGLE_TOO_BIG: celestial angle too large for projection"); errorKeyMap.insert(502, "BAD_WCS_VAL: bad celestial coordinate or pixel value"); errorKeyMap.insert(503, "WCS_ERROR: error in celestial coordinate calculation"); errorKeyMap.insert(504, "BAD_WCS_PROJ: unsupported type of celestial projection"); errorKeyMap.insert(505, "NO_WCS_KEY: celestial coordinate keywords not found"); errorKeyMap.insert(506, "APPROX_WCS_KEY: approximate WCS keywords were calculated"); }
11,497
C++
.cc
165
65.169697
108
0.743841
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,450
fitting.cc
schirmermischa_THELI/src/tools/fitting.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "fitting.h" #include <gsl/gsl_math.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_vector.h> #include <QVector> #include <QFile> #include <QTextStream> #include <QDebug> Fitting::Fitting() { } Fitting::~Fitting() { } // 2D surface fit using polynomial of arbitrary degree // Weights are optional void Fitting::makePolynomialFit2D(const int order, const QVector<double> x_in, const QVector<double> y_in, const QVector<double> z_in, QVector<double> w_in) { if (!FITSUCCESS) return; long lx = x_in.length(); long ly = y_in.length(); long lz = y_in.length(); long lw = w_in.length(); if (lx != ly || lx != lz || ( lx != lw && lw > 0)) { emit messageAvailable("Fitting::makePolynomialFit2D(): Inconsistent size of input arrays:" + QString::number(lx) + " " + QString::number(ly) + " " + QString::number(lz) + " " + QString::number(lw), "error"); emit critical(); FITSUCCESS = false; return; } // Number of measurement positions long N = lx; // weights (optional) if (w_in.isEmpty()) w_in.fill(1.0, N); // Number of free parameters int P = 2*order + 1; if (N < P) { emit messageAvailable("Fitting::makePolynomialFit2D(): Insufficient number of data points (" + QString::number(N) + ") to do a fit of degree " +QString::number(order), "error"); emit critical(); FITSUCCESS = false; return; } // we don't use cross-terms // Linear combinations of various functions // order == 1: // z = p0 + p1 x + p2 y // order == 2: // z = p0 + p1 x + p2 x^2 + p3 y + p3 y^2 // etc ... gsl_vector *y; // observed data () gsl_vector *w; // data weights gsl_matrix *X; // data used to predict: x, y // allocate space for the matrices and vectors X = gsl_matrix_alloc(N, P); // this is an input y = gsl_vector_alloc(N); // this is an input w = gsl_vector_alloc(N); // this is an input c = gsl_vector_alloc(P); // this is an output cov = gsl_matrix_alloc(P, P); // this is an output // Put the data into the X matrix, row by row int ii = 0; for (int i=0; i<N; ++i) { int s = 0; gsl_matrix_set(X, ii, s++, 1.0); // Do not merge these for loops (incrementing s++) for (int k=1; k<=order; ++k) { gsl_matrix_set(X, ii, s++, pow(x_in[i], k)); } for (int k=1; k<=order; ++k) { gsl_matrix_set(X, ii, s++, pow(y_in[i], k)); } ++ii; } // fill vector of observed data ii = 0; for (int i=0; i<N; ++i) { gsl_vector_set(w, ii, w_in[i]); gsl_vector_set(y, ii, z_in[i]); ++ii; } // allocate temporary work space for gsl gsl_multifit_linear_workspace *work; work = gsl_multifit_linear_alloc(N, P); // calculate the fit double chisq; gsl_multifit_wlinear(X, w, y, c, cov, &chisq, work); // deallocate gsl_matrix_free(X); gsl_vector_free(y); gsl_vector_free(w); gsl_multifit_linear_free(work); } // Overloaded void Fitting::makePolynomialFit2D(const int order, QList<QVector<double>> nodes) { long numNodes = nodes.length(); QVector<double> x_in; QVector<double> y_in; QVector<double> z_in; x_in.reserve(numNodes); y_in.reserve(numNodes); z_in.reserve(numNodes); for (auto &it : nodes) { x_in.append(it[0]); y_in.append(it[1]); z_in.append(it[2]); } makePolynomialFit2D(order, x_in, y_in, z_in); }
4,403
C++
.cc
128
29.03125
185
0.615928
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,451
ram.cc
schirmermischa_THELI/src/tools/ram.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "ram.h" #include <QVector> #include <QString> #include <QTest> #include <QFile> #include <QThread> #include <QSysInfo> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #ifdef __MACH__ #include <mach/mach.h> #define MACOS #elif __LINUX__ #define LINUX #endif RAM::RAM(QObject *parent) : QObject(parent) { file.setFileName("/proc/meminfo"); if ( !file.open(QIODevice::ReadOnly)) { RAMbarDeactivated = true; return; } instream.setDevice(&file); QSysInfo *sysInfo = new QSysInfo; kernelType = sysInfo->kernelType(); delete sysInfo; sysInfo = nullptr; } RAM::~RAM() { file.close(); } long RAM::getRAMload() { if (RAMbarDeactivated) return 0; if (kernelType == "linux") { readStatsRAM_Linux(); } else if (kernelType == "darwin") { readStatsRAM_MAC(); } int RAMload = (totalRAM - availableRAM) / 1024; return RAMload; // in [MB] } void RAM::readStatsRAM_Linux() { // Reset file to beginning instream.seek(0); // Files in /proc/ report their size as zero. Hence we can't do "while until EOF", but just read until nothing is read anymore. QString line = instream.readLine().simplified(); while (!line.isNull()) { QStringList values = line.split(" "); if (values[0] == "MemAvailable:") { availableRAM = values[1].toLong(); break; } line = instream.readLine().simplified(); } } void RAM::readStatsRAM_MAC() { unsigned long ulSystem; unsigned long ulUser; unsigned long ulNice; unsigned long ulIdle; getRAMInfo_MAC(&ulSystem, &ulUser, &ulNice, &ulIdle); } float RAM::getCurrentValue() { if (kernelType == "linux") { readStatsRAM_Linux(); } else if (kernelType == "darwin") { readStatsRAM_MAC(); } return (totalRAM - availableRAM) / 1024.; } void RAM::getRAMInfo_MAC(unsigned long *pulSystem, unsigned long *pulUser, unsigned long *pulNice, unsigned long *pulIdle) { #ifdef __MACH__ mach_msg_type_number_t unCpuMsgCount = 0; processor_flavor_t nCpuFlavor = PROCESSOR_CPU_LOAD_INFO; kern_return_t nErr = 0; natural_t unCPUNum = 0; processor_cpu_load_info_t structCpuData; host_t host = mach_host_self(); *pulSystem = 0; *pulUser = 0; *pulNice = 0; *pulIdle = 0; nErr = host_processor_info(host, nCpuFlavor, &unCPUNum, (processor_info_array_t *)&structCpuData, &unCpuMsgCount); if(nErr != KERN_SUCCESS) { qDebug() << "Kernel error: " << mach_error_string(nErr); } else { for(int i=0; i<(int)unCPUNum; ++i) { *pulSystem += structCpuData[i].cpu_ticks[CPU_STATE_SYSTEM]; *pulUser += structCpuData[i].cpu_ticks[CPU_STATE_USER]; *pulNice += structCpuData[i].cpu_ticks[CPU_STATE_NICE]; *pulIdle += structCpuData[i].cpu_ticks[CPU_STATE_IDLE]; } } #endif }
3,634
C++
.cc
120
26.066667
131
0.672967
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,452
splitter_processingSpecific.cc
schirmermischa_THELI/src/tools/splitter_processingSpecific.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "tools.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "fitsio.h" #include <QString> #include <QVector> #include <QFile> #include <QDir> // This source file contains instrument-specific processing routines. // Mainly to deal with peculiarities of the data void Splitter::descrambleLiris() { if (!successProcessing) return; int n = naxis1Raw; // Must use Raw size because we trim it in polarimetry mode int m = naxis2Raw; QVector<QVector<float>> image2D(n); QVector<QVector<float>> image2Dmod(n); int i = 0; int j = 0; for(i=0; i<n; ++i) { image2D[i].fill(0,m); image2Dmod[i].fill(0,m); } // Put the image data into the 2D array for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { image2D[i][j] = dataRaw[i+n*j]; } } // correct 1st quadrant // shift lower left corner to the upper right image2Dmod[510][511] = image2D[0][0]; image2Dmod[511][511] = image2D[1][0]; // shift main block two columns to the left for (i=0; i<=509; ++i) { for (j=0; j<=511; ++j) { image2Dmod[i][j] = image2D[i+2][j]; } } // shift left two columns to the right and one row down for (j=1; j<=511; ++j) { image2Dmod[510][j-1] = image2D[0][j]; image2Dmod[511][j-1] = image2D[1][j]; } // correct 2nd quadrant // shift lower left corner to the upper right image2Dmod[1023][511] = image2D[512][0]; // shift main block one column to the left for (i=512; i<=1022; ++i) { for (j=0; j<=511; ++j) { image2Dmod[i][j] = image2D[i+1][j]; } } // shift left column to the right and one row down for (j=1; j<=511; ++j) { image2Dmod[1023][j-1] = image2D[512][j]; } // correct 3rd quadrant // shift lower left corner to the upper right image2Dmod[511][1023] = image2D[0][512]; // shift main block one column to the left for (i=0; i<=510; ++i) { for (j=512; j<=1023; ++j) { image2Dmod[i][j] = image2D[i+1][j]; } } // shift left column to the right and one row down for (j=513; j<=1023; ++j) { image2Dmod[511][j-1] = image2D[0][j]; } // correct 4th quadrant // shift lower left corner to the upper right image2Dmod[1023][1023] = image2D[512][512]; // shift main block one column to the left for (i=512; i<=1022; ++i) { for (j=513; j<=1023; ++j) { image2Dmod[i][j] = image2D[i+1][j]; } } // shift left column to the right and one row down for (j=513; j<=1023; ++j) { image2Dmod[1023][j-1] = image2D[512][j]; } // Write the result for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { dataRaw[i+n*j] = image2Dmod[i][j]; } } }
3,584
C++
.cc
106
28.575472
89
0.611673
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,453
debayer.cc
schirmermischa_THELI/src/tools/debayer.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include <cmath> #include "tools.h" #include "../myimage/myimage.h" #include <QDebug> // For debayering float hue_transit(float l1, float l2, float l3, float v1, float v3) { //printf("hue_transit: l1 %5.1f l2 %5.1f l3 %5.1f v1 %5.1f v3 %5.1f\n",l1,l2,l3,v1,v3); if ((l1<l2 && l2<l3) || (l1> l2 && l2 > l3)) return (v1+(v3-v1) * (l2-l1)/(l3-l1)); else return ((v1+v3)/2.0 + (l2*2.0-l1-l3)/4.0); } // For debayering int direction(float N, float E, float W, float S) { if (N < E && W < S) { if ( N < W) return 1; else return 3; } else { if (E < S) return 2; else return 4; } } // Qt5 implementation of the PPG (patterened pixel grouping) algorithm by Chuan-Kai Lin, // originally published at https://sites.google.com/site/chklin/demosaic. The URL is no longer available // but can be found here: // https://web.archive.org/web/20160923211135/https://sites.google.com/site/chklin/demosaic/ // First implementation for THELI v2 by Carsten Moos. // The input image becomes the R-band channel void debayer(int chip, MyImage *image, MyImage *imageB, MyImage *imageG, MyImage *imageR) { if (!image->successProcessing) return; QString pattern = image->getKeyword("BAYER"); if ( pattern != "RGGB" && pattern != "GRBG" && pattern != "GBRG" && pattern != "BGGR") { qDebug() << "Tools::debayer(): Bayer pattern not recognised. Nothing will be done.\n"; image->successProcessing = false; return; } // chop the last row / column of pixels if the image dimensions are uneven int n = image->naxis1; int m = image->naxis2; if ( n % 2 != 0) n = n - 1; if ( m % 2 != 0) m = m - 1; // Setup the debayered channels QList<MyImage*> list; list << imageB << imageG << imageR; double mjdOffset = 0.; for (auto &it: list) { it->naxis1 = n; it->naxis2 = m; it->dataCurrent.resize(n*m); it->dataCurrent.squeeze(); it->path = image->path; it->weightPath = image->weightPath; it->baseName = image->rootName; it->rootName = image->rootName; it->chipName = image->rootName+"_"+QString::number(image->chipNumber); it->exptime = image->exptime; it->header = image->header; it->pathBackupL1 = image->pathBackupL1; it->baseNameBackupL1 = image->baseNameBackupL1; it->imageInMemory = true; it->wcs = image->wcs; it->plateScale = image->plateScale; it->wcsInit = image->wcsInit; it->gain = image->gain; it->airmass = image->airmass; it->fwhm = image->fwhm; it->fwhm_est = image->fwhm_est; it->gain = image->gain; it->ellipticity = image->ellipticity; it->ellipticity_est = image->ellipticity_est; it->RZP = image->RZP; it->gainNormalization = image->gainNormalization; it->hasMJDread = image->hasMJDread; it->headerInfoProvided = image->headerInfoProvided; it->skyValue = image->skyValue; it->modeDetermined = image->modeDetermined; it->fullheader = image->fullheader; it->dateobs = image->dateobs; it->cornersToRaDec(); // Data::populateExposureList() will group debayered images into one exposure, and then // mergeScampCatalogs() will create three extensions. But we need them individually. // Hence introducing a 0.1 s offset in MJD-OBS. // Fixing Data::populateExposureList() is non-trivial it->mjdobs = image->mjdobs + mjdOffset; mjdOffset += 1.e-6; } imageB->baseName.append("_B_"+QString::number(chip+1)); // status 'PA' will be appended externally imageG->baseName.append("_G_"+QString::number(chip+1)); imageR->baseName.append("_R_"+QString::number(chip+1)); imageB->rootName.append("_B"); imageG->rootName.append("_G"); imageR->rootName.append("_R"); imageB->chipName = imageB->baseName; imageG->chipName = imageG->baseName; imageR->chipName = imageR->baseName; imageB->filter = "B"; imageG->filter = "G"; imageR->filter = "R"; for (auto &card : imageB->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'B'"; card.resize(80, ' '); } } for (auto &card : imageG->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'G'"; card.resize(80, ' '); } } for (auto &card : imageR->header) { if (card.contains("FILTER = ")) { card = "FILTER = 'R'"; card.resize(80, ' '); } } // ==== BEGIN PPG algorithm === // cut all patterns to RGGB int xoffset; int yoffset; if (pattern == "RGGB") { xoffset = 0; yoffset = 0; } else if (pattern == "GRBG") { xoffset = 1; yoffset = 0; } else if (pattern == "GBRG") { xoffset = 0; yoffset = 1; } else { // pattern == "BGGR" xoffset = 1; yoffset = 1; } /* // The Bayer pattern looks like this RGRGRGRGR gBgBgBgBg RGRGRGRGR gBgBgBgBg */ long k = 0; QVector<float> &I = image->dataCurrent; QVector<float> &R = imageR->dataCurrent; QVector<float> &G = imageG->dataCurrent; QVector<float> &B = imageB->dataCurrent; // Calculate the green values at red and blue pixels for (long j=0; j<m; ++j) { for (long i=0; i<n; ++i) { if( j<=2 || j>=m-3 || i<=2 || i>=n-3) { // 3 rows top bottom left right R[k] = I[(i+n*j)]; // all the same with current color G[k] = I[(i+n*j)]; B[k] = I[(i+n*j)]; ++k; } else{ // gradient calculation for green values at red or blue pixels float DN = fabs(I[(i-2*n+n*j)]-I[(i+n*j)])*2.0 + fabs(I[(i-n+n*j)]-I[(i+n+n*j)]); float DE = fabs(I[(i+n*j)] -I[(i+2+n*j)])*2.0 + fabs(I[(i-1+n*j)]-I[(i+1+n*j)]); float DW = fabs(I[(i-2+n*j)] -I[(i+n*j)])*2.0 + fabs(I[(i-1+n*j)]-I[(i+1+n*j)]); float DS = fabs(I[(i+n*j)] -I[(i+2*n+n*j)])*2.0 + fabs(I[(i-n+n*j)]-I[(i+n+n*j)]); if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0) { // red pixel R[k] = I[(i+n*j)]; switch (direction(DN,DE,DW,DS)) { case 1: G[k] = (I[(i-n+n*j)]*3.0 + I[(i+n*j)] + I[(i+n+n*j)] - I[(i-2*n+n*j)]) / 4.0; break; case 2: G[k] = (I[(i+1+n*j)]*3.0 + I[(i+n*j)] + I[(i-1+n*j)] - I[(i+2+n*j)]) / 4.0; break; case 3: G[k] = (I[(i-1+n*j)]*3.0 + I[(i+n*j)] + I[(i+1+n*j)] - I[(i-2+n*j)]) / 4.0; break; case 4: G[k] = (I[(i+n+n*j)]*3.0 + I[(i+n*j)] + I[(i-n+n*j)] - I[(i+2*n+n*j)]) / 4.0; break; } ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel switch (direction(DN,DE,DW,DS)){ case 1: G[k] = (I[(i-n+n*j)]*3.0 + I[(i+n*j)] + I[(i+n+n*j)] - I[(i-2*n+n*j)]) / 4.0; break; case 2: G[k] = (I[(i+1+n*j)]*3.0 + I[(i+n*j)] + I[(i-1+n*j)] - I[(i+2+n*j)]) / 4.0; break; case 3: G[k] = (I[(i-1+n*j)]*3.0 + I[(i+n*j)] + I[(i+1+n*j)] - I[(i-2+n*j)]) / 4.0; break; case 4: G[k] = (I[(i+n+n*j)]*3.0 + I[(i+n*j)] + I[(i-n+n*j)] - I[(i+2*n+n*j)]) / 4.0; break; } B[k] = I[(i+n*j)]; ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above G[k] = I[(i+n*j)]; ++k; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above G[k] = I[(i+n*j)]; ++k; } } } } k = 0; // Calculating blue and red at green pixels // Calculating blue or red at red or blue pixels for (long j=0; j<m; ++j) { for (long i=0; i<n; ++i) { if (j<=2 || j>=m-3 || i<=2 || i>=n-3) { // 3 rows top bottom left right if (!xoffset && !yoffset) { // RGGB if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+1+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i-n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i-1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i-1-n+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i+n*j)]; } } else if (xoffset && !yoffset) { //GRBG if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i-1+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i-n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i+1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i+1-n+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+n*j)]; } } else if (!xoffset && yoffset) { //GBRG if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-n+n*j)]; B[k] = I[(i+1-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i+n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i+1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i-1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i-1+n+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i+n*j)]; } } else if (xoffset && yoffset) { //BGGR if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0){ // red pixel R[k] = I[(i+n*j)]; G[k] = I[(i-1+n*j)]; B[k] = I[(i-1-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0){ // green pixel, red above R[k] = I[(i+n+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-1+n*j)]; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1){ // green pixel, blue above R[k] = I[(i+1+n*j)]; G[k] = I[(i+n*j)]; B[k] = I[(i-n+n*j)]; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1){ // blue pixel R[k] = I[(i+1+n+n*j)]; G[k] = I[(i+1+n*j)]; B[k] = I[(i+n*j)]; } } ++k; } else{ // diagonal gradients float dne = fabs(I[(i-n+1+n*j)]-I[(i+n-1+n*j)]) + fabs(I[(i-2*n+2+n*j)]-I[(i+n*j)]) + fabs(I[(i+n*j)]-I[(i+2*n-2+n*j)]) + fabs(G[(i-n+1+n*j)]-G[(i+n*j)]) + fabs(G[(i+n*j)]-G[(i+n-1+n*j)]); float dnw = fabs(I[(i-n-1+n*j)]-I[(i+n+1+n*j)]) + fabs(I[(i-2-2*n+n*j)]-I[(i+n*j)]) + fabs(I[(i+n*j)]-I[(i+2+2*n+n*j)]) + fabs(G[(i-n-1+n*j)]-G[(i+n*j)]) + fabs(G[(i+n*j)]-G[(i+n+1+n*j)]); if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 0) { // red pixel if (dne <= dnw) B[k] = hue_transit(G[i-n+1+n*j], G[i+n*j], G[i+n-1+n*j], I[(i-n+1+n*j)], I[(i+n-1+n*j)]); else B[k] = hue_transit(G[i-n-1+n*j], G[i+n*j], G[i+n+1+n*j], I[(i-n-1+n*j)], I[(i+n+1+n*j)]); ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 0) { // green pixel, red above R[k] = hue_transit(G[(i-n+n*j)], I[(i+n*j)], G[(i+n+n*j)], I[(i-n+n*j)], I[(i+n+n*j)]); B[k] = hue_transit(G[(i-1+n*j)], I[(i+n*j)], G[(i+1+n*j)], I[(i-1+n*j)], I[(i+1+n*j)]); ++k; } else if ((j+yoffset)%2 == 0 && (i+xoffset)%2 == 1) { // green pixel, blue above R[k] = hue_transit(G[(i-1+n*j)], I[(i+n*j)], G[(i+1+n*j)], I[(i-1+n*j)], I[(i+1+n*j)]); B[k] = hue_transit(G[(i-n+n*j)], I[(i+n*j)], G[(i+n+n*j)], I[(i-n+n*j)], I[(i+n+n*j)]); ++k; } else if ((j+yoffset)%2 == 1 && (i+xoffset)%2 == 1) { // blue pixel if (dne <= dnw) R[k] = hue_transit(G[(i-n+1+n*j)], G[(i+n*j)], G[(i+n-1+n*j)], I[(i-n+1+n*j)], I[(i+n-1+n*j)]); else R[k] = hue_transit(G[(i-n-1+n*j)], G[(i+n*j)], G[(i+n+1+n*j)], I[(i-n-1+n*j)], I[(i+n+1+n*j)]); ++k; } } } } // === END PPG algorithm === } void updateDebayerMemoryStatus(MyImage *image) { if (!image->successProcessing) return; image->imageInMemory = true; image->dataBackupL1 = image->dataCurrent; image->backupL1InMemory = true; } // Remove the relative sensitivity pattern from the bayerflat // (Calculate an average 2x2 superpixel and divide the flat by it) void equalizeBayerFlat(MyImage *image) { int n = image->naxis1; int m = image->naxis2; // calculate the average 2x2 pixel float ll = 0.; float lr = 0.; float ul = 0.; float ur = 0.; for (int j=0; j<m-1; j+=2) { for (int i=0; i<n-1; i+=2) { ll += image->dataCurrent[i+n*j]; lr += image->dataCurrent[i+1+n*j]; ul += image->dataCurrent[i+n*(j+1)]; ur += image->dataCurrent[i+1+n*(j+1)]; } } ll /= ( n*m / 4. ); lr /= ( n*m / 4. ); ul /= ( n*m / 4. ); ur /= ( n*m / 4. ); // The four values above have the average intensity of the flat. // We want to preserve it after the super pixel normalization float sum = (ll + lr + ul + ur) / 4.; ll /= sum; lr /= sum; ul /= sum; ur /= sum; // Normalize the flat for (int j=0; j<m-1; j+=2) { for (int i=0; i<n-1; i+=2) { image->dataCurrent[i+n*j] /= ll; image->dataCurrent[i+1+n*j] /= lr; image->dataCurrent[i+n*(j+1)] /= ul; image->dataCurrent[i+1+n*(j+1)] /= ur; } } // Update the mode image->updateMode(); }
17,060
C++
.cc
401
30.029925
119
0.428391
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,454
splitter.cc
schirmermischa_THELI/src/tools/splitter.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../processingInternal/mask.h" #include "../processingInternal/data.h" #include "cfitsioerrorcodes.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "fitsio.h" #include "libraw/libraw.h" #include <QString> #include <QStringList> #include <QMessageBox> #include <QVector> #include <QFile> #include <QDir> Splitter::Splitter(const instrumentDataType &instrumentData, const Mask *detectorMask, const Mask *altDetectorMask, Data *someData, QString datatype, const ConfDockWidget *confDockWidget, QString maindirname, QString subdirname, QString filename, int *verbose, QObject *parent) : QObject(parent), mask(detectorMask), altMask(altDetectorMask), instData(instrumentData), // instData is modified locally during splitting, in the Splitter class only cdw(confDockWidget) { fileName = filename; mainDirName = maindirname; subDirName = subdirname; path = mainDirName + "/" + subDirName; name = path+"/"+fileName; dataType = datatype; QFileInfo fi(name); baseName = fi.completeBaseName(); verbosity = verbose; data = someData; QDir rawdata(path+"/RAWDATA"); rawdata.mkpath(path+"/RAWDATA"); // Bypassing a memory leak in cfitsio QFile file(name); if (!file.exists()) { successProcessing = false; } // The remainder of the processing is called externally from the controller } void Splitter::backupRawFile() { if (!successProcessing) return; moveFile(fileName, path, path+"/RAWDATA/"); } void Splitter::determineFileFormat() { if (!successProcessing) return; alreadyProcessed = false; // Try opening as FITS fits_open_file(&rawFptr, name.toUtf8().data(), READONLY, &rawStatus); // CHECK: xtalk correction only works if we maintain the original detector geometry // correctXtalk(); if (!rawStatus) { dataFormat = "FITS"; // Already processed by THELI? long thelipro = 0; fits_read_key_lng(rawFptr, "THELIPRO", &thelipro, nullptr, &rawStatus); if (rawStatus != KEY_NO_EXIST) { // key exists, this file has been processed by the splitter alreay. Must skip. emit messageAvailable(fileName + " : Already processed, skipped.", "image"); rawStatus = 0; alreadyProcessed = true; return; } else { // Key does not exist, meaning file has not been processed. reset raw status rawStatus = 0; } uncompress(); consistencyChecks(); getDetectorSections(); // Read overscan and data sections for the current instrument; resize accordingly, including gain vector getNumberOfAmplifiers(); } else { // Try opening as RAW dataFormat = "RAW"; int ret = rawProcessor.open_file((path+"/"+fileName).toUtf8().data()); if (ret == LIBRAW_SUCCESS) { // Opened. Try unpacking bool unpack = rawProcessor.unpack(); if (unpack != LIBRAW_SUCCESS) { emit messageAvailable(fileName + " : Could not unpack file: " + libraw_strerror(unpack), "warning"); dataFormat = "UnknownFormat"; return; } getNumberOfAmplifiers(); } else dataFormat = "UnknownFormat"; } if (dataFormat == "UnknownFormat") { // FITS opening error? // printCfitsioError("determineFileFormat()", rawStatus); // successProcessing = false; // Don not trigger an error, just skip the file QDir unknownFile(path+"/UnknownFormat"); unknownFile.mkpath(path+"/UnknownFormat/"); moveFile(fileName, path, path+"/UnknownFormat"); emit messageAvailable("File "+fileName+" : Unknown format. Cfitsio error code: "+QString::number(rawStatus) + ". Moved to "+subDirName+"/UnknownFormat/", "warning"); } } void Splitter::uncompress() { if (!successProcessing) return; // Unpack tile-compressed image and write new fits file to disk if (fits_is_compressed_image(rawFptr, &rawStatus)) { if (*verbosity > 1) emit messageAvailable(baseName + " : Uncompressing ...", "image"); fitsfile *outRawPtr; int outRawStatus = 0; QFileInfo fi(name); QString outName = "!" + path + fi.completeBaseName(); if (!outName.contains(".fits") || !outName.contains(".fit") || !outName.contains(".fts")) outName.append(".fits"); fits_create_file(&outRawPtr, outName.toUtf8().data(), &outRawStatus); fits_img_decompress(rawFptr, outRawPtr, &rawStatus); // delete compressed file if uncompression was successful, create new fits pointer to uncompressed file // CHECK: xtalk correction only works if we maintain the original detector geometry // correctXtalk(); // CHECK : No uncompressed FITS files appear after splitting. Where are they? The raw file does not get removed either. if (!rawStatus && !outRawStatus) { fits_close_file(rawFptr, &rawStatus); //QFile compressedFile(name); //compressedFile.remove(); name = outName; name.remove('!'); QFileInfo fi2(name); baseName = fi2.completeBaseName(); fits_open_file(&rawFptr, name.toUtf8().data(), READONLY, &rawStatus); if (rawStatus) { emit messageAvailable(baseName + " : Could not open uncompressed FITS file!", "error"); printCfitsioError(__func__, rawStatus); } } else { emit messageAvailable(fi.fileName() + " : Uncompression did not work as expected!", "error"); printCfitsioError(__func__, rawStatus); printCfitsioError(__func__, outRawStatus); successProcessing = false; } } } void Splitter::consistencyChecks() { if (!successProcessing) return; // TODO: Determine FITS type (SINGLE, MEF or CUBE) fits_get_num_hdus(rawFptr, &numExt, &rawStatus); if (fitsType == "SINGLE" || fitsType == "MEF") { if (numHDU < instData.numChips) { emit messageAvailable(fileName + " : "+QString::number(numHDU)+" HDUs found, "+QString::number(instData.numChips) +" expected.<br>File is moved to "+subDirName+"/INCONSISTENT/", "warning"); emit warning(); QDir inconsistentFile(path+"/INCONSISTENT"); inconsistentFile.mkpath(path+"/INCONSISTENT"); moveFile(name, path, path+"/INCONSISTENT"); successProcessing = false; } // equal or more numHDUs than chips is fine (e.g. multi-channel cameras, or multiple readout ports per detector) } printCfitsioError(__func__, rawStatus); } void Splitter::compileNumericKeys() { numericKeyNames.clear(); numericKeyNames.append(headerDictionary.value("CRVAL1")); numericKeyNames.append(headerDictionary.value("CRVAL2")); numericKeyNames.append(headerDictionary.value("CRPIX1")); numericKeyNames.append(headerDictionary.value("CRPIX2")); numericKeyNames.append(headerDictionary.value("EXPTIME")); numericKeyNames.append(headerDictionary.value("CD1_1")); numericKeyNames.append(headerDictionary.value("CD1_2")); numericKeyNames.append(headerDictionary.value("CD2_1")); numericKeyNames.append(headerDictionary.value("CD2_2")); numericKeyNames.append(headerDictionary.value("CDELT1")); numericKeyNames.append(headerDictionary.value("CDELT2")); numericKeyNames.append(headerDictionary.value("AIRMASS")); numericKeyNames.append(headerDictionary.value("EQUINOX")); numericKeyNames.append(headerDictionary.value("MJD-OBS")); numericKeyNames.append(headerDictionary.value("GAIN")); numericKeyNames.append(headerDictionary.value("DATE")); numericKeyNames.append(headerDictionary.value("TIME")); numericKeyNames.append(headerDictionary.value("LST")); } void Splitter::extractImages() { if (!successProcessing) return; if (alreadyProcessed) return; if (dataFormat == "UnknownFormat") return; emit messageAvailable(fileName + " : HDU reformatting, low-level pixel processing ...", "image"); // adjust progress step size for multi-chip cameras whose detectors are stored in single extension FITS files // (i.e. raw data does not come as a MEF but as separate FITS files) QStringList instruments = {"Direct_4k_SWOPE@LCO", "FORS1_E2V_2x2@VLT", "FORS2_E2V_2x2@VLT", "FORS2_MIT_1x1@VLT", "FORS2_MIT_2x2@VLT", "FourStar@LCO", "HSC@SUBARU", "LDSS3_2004-201401@LCO", "LDSS3_from201402@LCO", "IMACS_F2_200404-2008@LCO", "IMACS_F2_2008-today@LCO", "IMACS_F4_200404-2012@LCO", "IMACS_F4_2012-today@LCO", "IMACS_F4_2012-today_2x2@LCO", "MOIRCS_200406-201006@SUBARU", "MOIRCS_201007-201505@SUBARU", "MOIRCS_201512-today@SUBARU", "SPARTAN@SOAR", "SuprimeCam_200101-200104@SUBARU", "SuprimeCam_200105-200807@SUBARU", "SuprimeCam_200808-201705@SUBARU", "SuprimeCam_200808-201705_SDFRED@SUBARU", "VIMOS@VLT"}; // multiple readout channels in different FITS extensions multiChannelMultiExt << "DEIMOS_2AMP@KECK" << "GMOS-N-HAM@GEMINI" << "GMOS-N-HAM_1x1@GEMINI" << "GMOS-S-HAM@GEMINI" << "GMOS-S-HAM_1x1@GEMINI" << "GMOS-S-HAM_4x4@GEMINI" << "LRIS_BLUE@KECK" << "LRIS_RED@KECK" << "MOSAIC-II_16@CTIO" << "MOSAIC-III_4@KPNO_4m" << "PISCO@LCO" << "SAMI_2x2@SOAR" << "SOI@SOAR"; if (multiChannelMultiExt.contains(instData.name)) ampInSeparateExt = true; if (instruments.contains(instData.name)) { progressStepSize *= instData.numChips; } if (dataFormat == "FITS") extractImagesFITS(); else if (dataFormat == "RAW") extractImagesRAW(); else { // nothing yet } // Lastly, store the raw file in the RAWDATA directory backupRawFile(); } // SINGLE and MEF files can be treated the same way void Splitter::extractImagesFITS() { if (!successProcessing) return; int hduType; int chip = 0; // Start counting at 0 (the output filename will have chip+1) // Step through HDUs, extract extensions if they are images, and process them // IMPORTANT: It is implied that the number of the extension, as encountered in the data, // is identical to the 'chip' number used throughout the rest of this source code readPrimaryHeader(); // Check if the instrument matches the data // This does NOT catch all inconsistent matches at this point (e.g. we are not comparing detector identification strings), // and the INSTRUME keyword has not been determined for all pre-defined instruments yet. In the altter case, the test is skipped. // And this works only for uncompressed data (INSTRUME keyword found in extension header of compressed data, which is not yet read at this point QString instrument = ""; searchKeyValue(headerDictionary.value("INSTRUME"), instrument); if (!checkInstrumentConsistency(instrument)) { if (rawStatus == END_OF_FILE) rawStatus = 0; fits_close_file(rawFptr, &rawStatus); printCfitsioError(__func__, rawStatus); return; } // FORCE a beginning with the absolute first HDU. If I use 'movrel' then I'm not sure it is going to skip // over the first HDU if there is one. To be tested with suitable data. Then we could remove the 'movabs' // and make 'movrel' the first command inside 'while () {}' fits_movabs_hdu(rawFptr, 1, &hduType, &rawStatus); while (rawStatus != END_OF_FILE && successProcessing) { if (hduType == IMAGE_HDU) { // for MMIRS and NOTcam, we only want to keep the first extension if (instData.name.contains("MMIRS") || instData.name.contains("NOTcam")) { if (chip >= 1) break; } // do we have an "image" (as compared to a data unit that is simply a nullptr, or some data quality extensions) int naxis = -1; int bitpix = 1; fits_get_img_dim(rawFptr, &naxis, &rawStatus); fits_get_img_type(rawFptr, &bitpix, &rawStatus); if (naxis == 0 || naxis == 1 || naxis >= 4 || bitpix == 8) { // Empty or peculiar data units. Continue with the next one fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); continue; } if (instData.name == "NISP_LE2@EUCLID" || instData.name == "VIS_LE2@EUCLID") { char extnamechar[FLEN_VALUE]; // To store EXTNAME keyword value fits_read_key(rawFptr, TSTRING, "EXTNAME", extnamechar, NULL, &rawStatus); QString extname(extnamechar); if (!extname.contains("SCI")) { // Not a science extension fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); continue; } } headerTHELI.clear(); readExtHeader(); // some multi-chip cams (FORS, etc) come with separate FITS files. For them, 'chip' would always be zero, // and thus the correct overscan regions etc not identified correctly. // Others such as GROND image simultaneously in different bandpasses on multiple detectors, but they show the // same field of view and should be treated as single-chip cameras. // Hence this mapping int chipMapped = inferChipID(chip) - 1; // same value as chip for normal 'MEF' files; requires readExtheader(), for Euclid. // For HSC@SUBARU, drop the 8 focus CCDs if (instData.name == "HSC@SUBARU" && chipMapped >= 104) break; // HSC chips too difficult for astrometry // "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,22,23,24,29,30,31,32,37,38,39,40,45,46,47,48,53,54,55,56,61 // ,62,63,64,69,70,71,72,77,78,79,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104" if (chipMapped == -1) { emit messageAvailable("Splitter::extractImagesFITS(): Could not infer chip number", "error"); emit critical(); successProcessing = false; break; } // OK, we have either a 2D image or a cube. // Saturation handling if (instData.type == "OPT") saturationValue = pow(2,16)-1.; else saturationValue = pow(2,20)-1.; // HAWAII-2RGs can on-chip coadd exposures, exceeding the usual 16-bit dynamic range if (userSaturationValue != 0) saturationValue = userSaturationValue; // Build the header. Must clear before processing new chip if (!isDetectorAlive(chipMapped)) { fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); ++chip; continue; } if (!isImageUsable(chipMapped)) { fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); ++chip; continue; } testGROND(); // GROND data are an oddball and need to be tested here updateMEFpastingStatus(chip); // Some cameras have readout channels in individual FITS extensions, implying skipping e.g. writeImage() buildTheliHeaderFILTER(chip); buildTheliHeaderWCS(chipMapped); buildTheliHeaderEXPTIME(); buildTheliHeaderDATEOBS(); // must be done before MJD-OBS buildTheliHeaderMJDOBS(); buildTheliHeaderAIRMASS(); // buildTheliHeaderGAIN(chipMapped); // buildTheliHeader(); // Leave if this image is bad if (!successProcessing) continue; // 2D image if (naxis == 2) { getCurrentExtensionData(); // sets naxis1/2Raw, needed by everything below getMultiportInformation(chipMapped); // sets naxis1/2. Updates overscan and data sections for nonstandard multiport readouts // overrideDetectorSections(chip); // TESTING of a more autonomous procedure // gains must be built after multiport chips are assembled buildTheliHeaderGAIN(chipMapped); buildTheliHeader(); if (instData.name.contains("LIRIS")) descrambleLiris(); correctOverscan(); // correctOverscan(combineOverscan_ptr, overscanX[chipMapped], overscanY[chipMapped]); // cropDataSection(dataSection[chipMapped]); pasteMultiportIlluminatedSections(chipMapped); correctXtalk(); // Must maintain original detector geometry for x-talk correction, i.e. do before cropping. Must replace naxisi by naxisiRaw in xtalk methods. correctNonlinearity(chipMapped); convertToElectrons(chipMapped); applyMask(chipMapped); writeImage(chipMapped); // initMyImage(chip); } // Cube if (naxis == 3) { getDataInCube(); getMultiportInformation(chipMapped); // Update overscan and data sections for nonstandard multiport readouts buildTheliHeaderGAIN(chipMapped); buildTheliHeader(); // Test for invalid cube. Not sure such a FIS file can exist? if (naxis3Raw == 0) continue; // Invalid cube. Not sure such a thing can exist? // For these instruments we want to stack (mean) the cube, not slice it QStringList instruments = {"TRECS@GEMINI"}; if (instruments.contains(instData.name)) { stackCube(); correctOverscan(); // correctOverscan(combineOverscan_ptr, overscanX[chipMapped], overscanY[chipMapped]); // cropDataSection(dataSection[chipMapped]); pasteMultiportIlluminatedSections(chipMapped); correctXtalk(); // TODO: how valid is that operation for the stack? correctNonlinearity(chipMapped); // TODO: how valid is that operation for the stack? convertToElectrons(chipMapped); applyMask(chipMapped); writeImage(chipMapped); // initMyImage(chip);16 // TODO: how is the exposure time defined for these data? Probably requires individual solution // Hamamatsus: define temporary data array, larger than the individual FITS extension, // and successively copy pixels as they become available from the individual extensions. // Then introduce an individual exception in writeImage() and applymask() (once all extensions are available). } else { // Loop over slices, extract each of them for (long i=0; i<naxis3Raw; ++i) { sliceCube(i); correctOverscan(); // correctOverscan(combineOverscan_ptr, overscanX[chipMapped], overscanY[chipMapped]); cropDataSection(dataSection[chipMapped]); correctXtalk(); correctNonlinearity(chipMapped); convertToElectrons(chipMapped); applyMask(chipMapped); writeImageSlice(chip, i); // initMyImage(chip); } } } #pragma omp atomic *progress += progressStepSize; } fits_movrel_hdu(rawFptr, 1, &hduType, &rawStatus); //#pragma omp atomic // *progress += progressStepSize; ++chip; } // Reset status (if indicating we moved past end of file, as intended) if (rawStatus == END_OF_FILE) rawStatus = 0; fits_close_file(rawFptr, &rawStatus); printCfitsioError(__func__, rawStatus); } // skip over bad detectors bool Splitter::isDetectorAlive(int &chipMapped) { if (instData.name == "SuprimeCam_200101-200104@SUBARU") { if (chipMapped == 6) return false; else if (chipMapped > 6) --chipMapped; // compensate chip number for lost chip } if (instData.name == "WFI_chips1-6@MPGESO") { if (chipMapped == 7) return false; if (chipMapped == 8) return false; } return true; } // For some cameras, the first (or other) images in a sequence might be unusable bool Splitter::isImageUsable(int &chipMapped) { if (instData.name == "NIRI@GEMINI") { QString value = ""; searchKeyValue(QStringList() << "DATALAB", value); QStringList list = value.split('-'); QString id = list.last(); if (id == "001") { if (*verbosity > 1) emit messageAvailable(baseName + " : First NIRI image in sequence, excluding ...", "ignore"); return false; } } return true; } int Splitter::inferChipID(int chip) { // Data from some cameras, such as SuprimeCam and FORS, come in separate FITS files instead of a MEF file. // Multichannel imagers also need to be treated here // We need to identify the chip number correctly: int chipID = chip + 1; // external counting starts with zero; 'chipID' is the number we return for most instruments // These need special treatment. The 'chip' variable is not necessarily used for all of them if (instData.name.contains("FORS1_E2V") // The FORSes with their newer 2-detector configuration || instData.name.contains("FORS2_E2V") || instData.name.contains("FORS2_MIT")) { QString value = ""; searchKeyValue(QStringList() << "ORIGFILE", value); // e.g. FORS2_IMG141.43.CHIP1.fits or FORS2_IMG141.43.CHIP2.fits QStringList valueList = value.split("CHIP"); if (valueList.length() == 2) { value = valueList.at(1); chipID = value.remove(".fits").toInt(); return chipID; } else { emit messageAvailable("Could not determine chip number for " + instData.name, "error"); emit critical(); return 1; } } else if (instData.name == "VIMOS@VLT") { int value = 0; searchKeyValue(QStringList() << "HIERARCH ESO OCS CON QUAD", value); // running from 1 to 4 chipID = value; return chipID; } else if (instData.name == "Direct_4k_SWOPE@LCO" || instData.name.contains("LDSS3")) { int value = 0; searchKeyValue(QStringList() << "OPAMP", value); // running from 1-2 (LDSS3) and from 1-4 (Direct_4k) chipID = value; return chipID; } else if (instData.name == "SuprimeCam_200105-200807@SUBARU" || instData.name == "SuprimeCam_200101-200104@SUBARU" || instData.name == "SuprimeCam_200808-201705@SUBARU" || instData.name == "HSC@SUBARU") { int value = 0; searchKeyValue(QStringList() << "DET-ID", value); // running from 0 to 9 (and 0 to 111 for HSC) chipID = value + 1; return chipID; } else if (instData.name.contains("MOIRCS")) { int value = 0; searchKeyValue(QStringList() << "DET-ID", value); // running from 1 to 2 chipID = value; return chipID; } else if (instData.name == "FourStar@LCO") { int value = 0; searchKeyValue(QStringList() << "CHIP", value); // running from 1 to 4 chipID = value; return chipID; } else if (instData.name == "NISP_LE1@EUCLID" || instData.name == "NISP_ERO@EUCLID") { QString value = ""; // can't use searchKeyValue(), as that internal makes a relative HDU offset if a key is not found searchKeyInHeaderValue(QStringList() << "EXTNAME", extHeader, value); if (value == "DET11.SCI") chipID = 1; else if (value == "DET12.SCI") chipID = 2; else if (value == "DET13.SCI") chipID = 3; else if (value == "DET14.SCI") chipID = 4; else if (value == "DET21.SCI") chipID = 5; else if (value == "DET22.SCI") chipID = 6; else if (value == "DET23.SCI") chipID = 7; else if (value == "DET24.SCI") chipID = 8; else if (value == "DET31.SCI") chipID = 9; else if (value == "DET32.SCI") chipID = 10; else if (value == "DET33.SCI") chipID = 11; else if (value == "DET34.SCI") chipID = 12; else if (value == "DET41.SCI") chipID = 13; else if (value == "DET42.SCI") chipID = 14; else if (value == "DET43.SCI") chipID = 15; else if (value == "DET44.SCI") chipID = 16; if (value.isEmpty()) return 0; else return chipID; } else if (instData.name == "VIS_LE1@EUCLID" || instData.name == "VIS_ERO@EUCLID") { // we need this to be robust against turned-off detector units QString value = ""; // can't use searchKeyValue(), as that internal makes a relative HDU offset if a key is not found searchKeyInHeaderValue(QStringList() << "EXTNAME", extHeader, value); if (value == "1-1.E") chipID = 1; else if (value == "1-1.F") chipID = 2; else if (value == "1-1.G") chipID = 3; else if (value == "1-1.H") chipID = 4; else if (value == "1-2.E") chipID = 5; else if (value == "1-2.F") chipID = 6; else if (value == "1-2.G") chipID = 7; else if (value == "1-2.H") chipID = 8; else if (value == "1-3.E") chipID = 9; else if (value == "1-3.F") chipID = 10; else if (value == "1-3.G") chipID = 11; else if (value == "1-3.H") chipID = 12; else if (value == "2-1.E") chipID = 13; else if (value == "2-1.F") chipID = 14; else if (value == "2-1.G") chipID = 15; else if (value == "2-1.H") chipID = 16; else if (value == "2-2.E") chipID = 17; else if (value == "2-2.F") chipID = 18; else if (value == "2-2.G") chipID = 19; else if (value == "2-2.H") chipID = 20; else if (value == "2-3.E") chipID = 21; else if (value == "2-3.F") chipID = 22; else if (value == "2-3.G") chipID = 23; else if (value == "2-3.H") chipID = 24; else if (value == "3-1.E") chipID = 25; else if (value == "3-1.F") chipID = 26; else if (value == "3-1.G") chipID = 27; else if (value == "3-1.H") chipID = 28; else if (value == "3-2.E") chipID = 29; else if (value == "3-2.F") chipID = 30; else if (value == "3-2.G") chipID = 31; else if (value == "3-2.H") chipID = 32; else if (value == "3-3.E") chipID = 33; else if (value == "3-3.F") chipID = 34; else if (value == "3-3.G") chipID = 35; else if (value == "3-3.H") chipID = 36; else if (value == "4-1.E") chipID = 37; else if (value == "4-1.F") chipID = 38; else if (value == "4-1.G") chipID = 39; else if (value == "4-1.H") chipID = 40; else if (value == "4-2.E") chipID = 41; else if (value == "4-2.F") chipID = 42; else if (value == "4-2.G") chipID = 43; else if (value == "4-2.H") chipID = 44; else if (value == "4-3.E") chipID = 45; else if (value == "4-3.F") chipID = 46; else if (value == "4-3.G") chipID = 47; else if (value == "4-3.H") chipID = 48; else if (value == "5-1.E") chipID = 49; else if (value == "5-1.F") chipID = 50; else if (value == "5-1.G") chipID = 51; else if (value == "5-1.H") chipID = 52; else if (value == "5-2.E") chipID = 53; else if (value == "5-2.F") chipID = 54; else if (value == "5-2.G") chipID = 55; else if (value == "5-2.H") chipID = 56; else if (value == "5-3.E") chipID = 57; else if (value == "5-3.F") chipID = 58; else if (value == "5-3.G") chipID = 59; else if (value == "5-3.H") chipID = 60; else if (value == "6-1.E") chipID = 61; else if (value == "6-1.F") chipID = 62; else if (value == "6-1.G") chipID = 63; else if (value == "6-1.H") chipID = 64; else if (value == "6-2.E") chipID = 65; else if (value == "6-2.F") chipID = 66; else if (value == "6-2.G") chipID = 67; else if (value == "6-2.H") chipID = 68; else if (value == "6-3.E") chipID = 69; else if (value == "6-3.F") chipID = 70; else if (value == "6-3.G") chipID = 71; else if (value == "6-3.H") chipID = 72; else if (value == "1-6.E") chipID = 73; else if (value == "1-6.F") chipID = 74; else if (value == "1-6.G") chipID = 75; else if (value == "1-6.H") chipID = 76; else if (value == "1-5.E") chipID = 77; else if (value == "1-5.F") chipID = 78; else if (value == "1-5.G") chipID = 79; else if (value == "1-5.H") chipID = 80; else if (value == "1-4.E") chipID = 81; else if (value == "1-4.F") chipID = 82; else if (value == "1-4.G") chipID = 83; else if (value == "1-4.H") chipID = 84; else if (value == "2-6.E") chipID = 85; else if (value == "2-6.F") chipID = 86; else if (value == "2-6.G") chipID = 87; else if (value == "2-6.H") chipID = 88; else if (value == "2-5.E") chipID = 89; else if (value == "2-5.F") chipID = 90; else if (value == "2-5.G") chipID = 91; else if (value == "2-5.H") chipID = 92; else if (value == "2-4.E") chipID = 93; else if (value == "2-4.F") chipID = 94; else if (value == "2-4.G") chipID = 95; else if (value == "2-4.H") chipID = 96; else if (value == "3-6.E") chipID = 97; else if (value == "3-6.F") chipID = 98; else if (value == "3-6.G") chipID = 99; else if (value == "3-6.H") chipID = 100; else if (value == "3-5.E") chipID = 101; else if (value == "3-5.F") chipID = 102; else if (value == "3-5.G") chipID = 103; else if (value == "3-5.H") chipID = 104; else if (value == "3-4.E") chipID = 105; else if (value == "3-4.F") chipID = 106; else if (value == "3-4.G") chipID = 107; else if (value == "3-4.H") chipID = 108; else if (value == "4-6.E") chipID = 109; else if (value == "4-6.F") chipID = 110; else if (value == "4-6.G") chipID = 111; else if (value == "4-6.H") chipID = 112; else if (value == "4-5.E") chipID = 113; else if (value == "4-5.F") chipID = 114; else if (value == "4-5.G") chipID = 115; else if (value == "4-5.H") chipID = 116; else if (value == "4-4.E") chipID = 117; else if (value == "4-4.F") chipID = 118; else if (value == "4-4.G") chipID = 119; else if (value == "4-4.H") chipID = 120; else if (value == "5-6.E") chipID = 121; else if (value == "5-6.F") chipID = 122; else if (value == "5-6.G") chipID = 123; else if (value == "5-6.H") chipID = 124; else if (value == "5-5.E") chipID = 125; else if (value == "5-5.F") chipID = 126; else if (value == "5-5.G") chipID = 127; else if (value == "5-5.H") chipID = 128; else if (value == "5-4.E") chipID = 129; else if (value == "5-4.F") chipID = 130; else if (value == "5-4.G") chipID = 131; else if (value == "5-4.H") chipID = 132; else if (value == "6-6.E") chipID = 133; else if (value == "6-6.F") chipID = 134; else if (value == "6-6.G") chipID = 135; else if (value == "6-6.H") chipID = 136; else if (value == "6-5.E") chipID = 137; else if (value == "6-5.F") chipID = 138; else if (value == "6-5.G") chipID = 139; else if (value == "6-5.H") chipID = 140; else if (value == "6-4.E") chipID = 141; else if (value == "6-4.F") chipID = 142; else if (value == "6-4.G") chipID = 143; else if (value == "6-4.H") chipID = 144; if (value.isEmpty()) return 0; else return chipID; } else if (instData.name.contains("IMACS")) { int value = 0; searchKeyValue(QStringList() << "CHIP", value); // running from 1 to 8 chipID = value; return chipID; } else if (instData.name == "SPARTAN@SOAR") { int value = 0; searchKeyValue(QStringList() << "DETSERNO", value); // detector serial number if (value == 102) chipID = 1; else if (value == 108) chipID = 2; else if (value == 97) chipID = 3; else if (value == 66) chipID = 4; else { emit messageAvailable("Unknown SPARTAN detector serial number: " + QString::number(value), "error"); return 0; } return chipID; } // Multichannel imagers: have just one (so far) detector number per channel, and the camera.ini specifies just 1 chip // Otherwise chipID runs to values larger than 1 which crashes queries of the Mask class else if (instData.name == "GROND_OPT@MPGESO" || instData.name == "GROND_NIR@MPGESO") { // || instData.name == "PISCO@LCO") { // must maintain chip id because of chip-dependent pasting // Simultaneous observations in multiple bands, but just a single detector per band return 1; // (reduced by -1 in caller) } return chipID; } // Retrieve the raw data pixel values void Splitter::getCurrentExtensionData() { if (!successProcessing) return; long naxis[2]; // Get image geometry fits_get_img_size(rawFptr, 2, naxis, &rawStatus); // Read the data block naxis1Raw = naxis[0]; naxis2Raw = naxis[1]; long nelements = naxis1Raw*naxis2Raw; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fits_read_img(rawFptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, &rawStatus); if (!rawStatus) { dataRaw.clear(); dataRaw.resize(nelements); dataRaw.squeeze(); for (long i=0; i<nelements; ++i) { float val = buffer[i]; if (std::isinf(val) || std::isnan(val)) val = 0.; // set peculiar values to zero dataRaw[i] = val; } } else { successProcessing = false; } delete [] buffer; buffer = nullptr; printCfitsioError(__func__, rawStatus); } // UNUSED void Splitter::getDataInFirstCubeSlice() { if (!successProcessing) return; long naxis[3]; // Get image geometry fits_get_img_size(rawFptr, 3, naxis, &rawStatus); // Read the data block naxis1Raw = naxis[0]; naxis2Raw = naxis[1]; long nelements = naxis1Raw*naxis2Raw; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long *fpixel = new long[3]; fpixel[0] = 1; fpixel[1] = 1; fpixel[2] = 1; fits_read_pix(rawFptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, &rawStatus); if (!rawStatus) { dataRaw.clear(); dataRaw.reserve(nelements); for (long i=0; i<nelements; ++i) { float val = buffer[i]; if (std::isinf(val) || std::isnan(val)) val = 0.; dataRaw.append(val); } dataRaw.squeeze(); } delete [] buffer; delete [] fpixel; buffer = nullptr; fpixel = nullptr; printCfitsioError(__func__, rawStatus); } void Splitter::getDataInCube() { if (!successProcessing) return; long naxis[3]; // Get image geometry fits_get_img_size(rawFptr, 3, naxis, &rawStatus); // Read the data block naxis1Raw = naxis[0]; naxis2Raw = naxis[1]; naxis3Raw = naxis[2]; long nelementsAll = naxis1Raw*naxis2Raw*naxis3Raw; float *bufferAll = new float[nelementsAll]; int anynull; fits_read_3d_flt(rawFptr, 0, TFLOAT, naxis1Raw, naxis2Raw, naxis1Raw, naxis2Raw, naxis3Raw, bufferAll, &anynull, &rawStatus); if (!rawStatus) { dataCubeRaw.clear(); dataCubeRaw.reserve(nelementsAll); for (long i=0; i<nelementsAll; ++i) { float val = bufferAll[i]; if (std::isinf(val) || std::isnan(val)) val = 0.; dataCubeRaw.append(val); } } delete [] bufferAll; bufferAll = nullptr; printCfitsioError(__func__, rawStatus); } void Splitter::sliceCube(long slice) { if (!successProcessing) return; dataRaw.clear(); dataRaw.resize(naxis1Raw*naxis2Raw); dataRaw.squeeze(); long k = 0; long step = naxis1Raw*naxis2Raw; for (long i=slice*step; i<(slice+1)*step; ++i) { dataRaw[k] = dataCubeRaw[i]; ++k; } } void Splitter::stackCube() { if (!successProcessing) return; dataRaw.clear(); dataRaw.resize(naxis1Raw*naxis2Raw); dataRaw.squeeze(); long k = 0; long step = naxis1Raw * naxis2Raw; long dim = naxis1Raw * naxis2Raw * naxis3Raw; for (long i=0; i<dim; ++i) { if (k == step) k = 0; // reset counter when we come back to the first pixel dataRaw[k] += dataCubeRaw[i]; ++k; } } void Splitter::getDetectorSections() { if (!successProcessing) return; // WARNING // This is for detectors only which have a single amplifier per detector, at least without injected overscan data between illuminated pixels // Other configurations are handled separately overscanX.clear(); overscanY.clear(); dataSection.clear(); gain.clear(); overscanX.resize(instData.numChips); overscanY.resize(instData.numChips); dataSection.resize(instData.numChips); gain.resize(instData.numChips); QVector<int> xmin = instData.overscan_xmin; QVector<int> xmax = instData.overscan_xmax; QVector<int> ymin = instData.overscan_ymin; QVector<int> ymax = instData.overscan_ymax; for (int chip=0; chip<instData.numChips; ++chip) { // Overscan X QVector<long> overscanxRegion; if (!xmin.isEmpty() && !xmax.isEmpty()) overscanxRegion << xmin[chip] << xmax[chip]; overscanX[chip] << overscanxRegion; // Overscan Y QVector<long> overscanyRegion; if (!ymin.isEmpty() && !ymax.isEmpty()) overscanyRegion << ymin[chip] << ymax[chip]; overscanY[chip] << overscanyRegion; // Data Section QVector<long> section; section << instData.cutx[chip]; section << instData.cutx[chip] + instData.sizex[chip] - 1; // sizex is not a coordinate, but the number of pixels along this axis. Hence -1 section << instData.cuty[chip]; section << instData.cuty[chip] + instData.sizey[chip] - 1; // sizey is not a coordinate, but the number of pixels along this axis. Hence -1 dataSection[chip] << section; } } // TESTING void Splitter::overrideDetectorSections(int chip) { if (instData.name == "MOSAIC-III@KPNO_4m" || instData.name == "WFC@INT" || instData.name == "WFC_2x2@INT") { multiportOverscanDirections << "vertical"; QVector<long> tmp = extractVerticesFromKeyword("BIASSEC"); overscanX[chip] << tmp.at(0) << tmp.at(1); dataSection[chip] = extractVerticesFromKeyword("DATASEC"); dataSection[chip] = extractVerticesFromKeyword("TRIMSEC"); naxis1 = dataSection[chip].at(1) - dataSection[chip].at(0); naxis2 = dataSection[chip].at(3) - dataSection[chip].at(2); } } void Splitter::getNumberOfAmplifiers() { if (!successProcessing) return; numAmpPerChip = 1; // The number of amplifiers forming data for a single detector. Always 1, unless stored in separate FITS extensions if (instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM")) { // update numAmpPerChip with NAMPS keyword fits_read_key_lng(rawFptr, "NAMPS", &numAmpPerChip, nullptr, &rawStatus); if (rawStatus) { emit messageAvailable("Splitter::getNumberOfAmplifiers(): Could not read NAMPS keyword!", "error"); numAmpPerChip = 1; rawStatus = 0; } } // 2 amps per detector if (instData.name == "SOI@SOAR" || instData.name == "DEIMOS_2AMP@KECK" || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "PISCO@LCO") { numAmpPerChip = 2; rawStatus = 0; } // 4 amps per detector (geometric layout doesn't matter here) if (instData.name == "MOSAIC-III_4@KPNO_4m" || instData.name == "SAMI_2x2@SOAR") { numAmpPerChip = 4; rawStatus = 0; } // multiple readout channels in different FITS extensions multiChannelMultiExt << "DEIMOS_2AMP@KECK" << "GMOS-N-HAM@GEMINI" << "GMOS-N-HAM_1x1@GEMINI" << "GMOS-S-HAM@GEMINI" << "GMOS-S-HAM_1x1@GEMINI" << "GMOS-S-HAM_4x4@GEMINI" << "LRIS_BLUE@KECK" << "LRIS_RED@KECK" << "MOSAIC-II_16@CTIO" << "MOSAIC-III_4@KPNO_4m" << "PISCO@LCO" << "SAMI_2x2@SOAR" << "SOI@SOAR"; if (multiChannelMultiExt.contains(instData.name)) ampInSeparateExt = true; if (numAmpPerChip > 1 && ampInSeparateExt) { overscanX.clear(); overscanY.clear(); dataSection.clear(); gain.clear(); overscanX.resize(instData.numChips * numAmpPerChip); overscanY.resize(instData.numChips * numAmpPerChip); dataSection.resize(instData.numChips * numAmpPerChip); gain.resize(instData.numChips * numAmpPerChip); } } // Write the pixel-corrected extension as a separate FITS file to disk void Splitter::writeImage(int chipMapped) { if (!successProcessing) return; if (!MEFpastingFinished) return; // Do not write bad detectors // Easiest done here, and not further above, in case of detectors with multiple readout amps if (instData.badChips.contains(chipMapped)) return; // Exceptions. Return if successful. if (individualFixWriteImage(chipMapped)) return; // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i<nelements; ++i) { array[i] = dataCurrent[i]; } long naxis = 2; long naxes[2] = { naxis1, naxis2 }; // Infer true chip number: // int chipID = inferChipID(chip); int chipID = chipMapped + 1; // adjust chipID for data where multiple channels are in separate extensions if (multiChannelMultiExt.contains(instData.name)) { if (instData.name.contains("GMOS")) { if (chipMapped == 3) chipID = 1; if (chipMapped == 7) chipID = 2; if (chipMapped == 11) chipID = 3; } if (instData.name == "SOI@SOAR") { if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 2; } if (instData.name == "DEIMOS_2AMP@KECK") { if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 2; if (chipMapped == 5) chipID = 3; if (chipMapped == 7) chipID = 4; } if (instData.name == "LRIS_BLUE@KECK") { if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 2; } if (instData.name == "LRIS_RED@KECK") { if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 2; } if (instData.name == "MOSAIC-II_16@CTIO") { if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 2; if (chipMapped == 5) chipID = 3; if (chipMapped == 7) chipID = 4; if (chipMapped == 9) chipID = 5; if (chipMapped == 11) chipID = 6; if (chipMapped == 13) chipID = 7; if (chipMapped == 15) chipID = 8; } if (instData.name == "PISCO@LCO") { // multi-channel imager if (chipMapped == 1) chipID = 1; if (chipMapped == 3) chipID = 1; if (chipMapped == 5) chipID = 1; if (chipMapped == 7) chipID = 1; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { if (chipMapped == 3) chipID = 1; if (chipMapped == 7) chipID = 2; if (chipMapped == 11) chipID = 3; if (chipMapped == 15) chipID = 4; } if (instData.name == "SAMI_2x2@SOAR") { if (chipMapped == 3) chipID = 1; } MEFpastingFinished = false; } // Replace blanks and other unwanted chars in file names baseName.replace(' ','_'); baseName.replace('[','_'); baseName.replace(']','_'); baseName.remove('$'); baseName.remove('&'); baseName.remove('#'); // Output file name splitFileName = "!"+path+"/"+baseName+"_"+QString::number(chipID)+"P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { if (dataFormat == "RAW" || !instData.bayer.isEmpty()) { // No filter name for bayer matrix images splitFileName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; } else { // general case splitFileName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; // special cases (overrides outName) individualFixOutName(chipID); } } fits_create_file(&fptr, splitFileName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i<headerTHELI.length(); ++i) { fits_write_record(fptr, headerTHELI[i].toUtf8().constData(), &status); } // Update the SATURATE keyword fits_update_key_flt(fptr, "SATURATE", saturationValue, 6, nullptr, &status); fits_update_key_str(fptr, "ORIGIN", fileName.toUtf8().data(), nullptr, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } void Splitter::individualFixOutName(const int chipID) { bool individualFixDone = false; bool test = true; if (instData.name == "VIMOS@VLT") { test = searchKeyValue(QStringList() << "HIERARCH ESO DET EXP NO", uniqueID); uniqueID = uniqueID.split('_').at(0); // " / char was already replaced by _ in searchKeyInHeaderValue()" uniqueID = uniqueID.simplified(); individualFixDone = true; } // if (instData.name == "Direct_4k_SWOPE@LCO") { // test = searchKeyValue(QStringList() << "FILENAME", uniqueID); // uniqueID = uniqueID.remove(7,2); // individualFixDone = true; // } else if (instData.name.contains("MOIRCS")) { test = searchKeyValue(QStringList() << "EXP-ID", uniqueID); // e.g. MCSE00012193 individualFixDone = true; } else if (instNameFromData == "GROND_OPT@MPGESO") { individualFixDone = true; } else if (instData.name == "PISCO@LCO") { individualFixDone = true; } if (individualFixDone) { if (!test) { emit messageAvailable(baseName + " : Could not determine unambiguous file name!", "error"); emit critical(); successProcessing = false; } else { if (instNameFromData == "GROND_OPT@MPGESO") { QString newPath = path+"_"+filter; QDir newDir(newPath); newDir.mkpath(newPath); splitFileName = "!"+newPath+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; } else if (instData.name == "PISCO@LCO") { QString newPath = path+"_"+filter; QDir newDir(newPath); newDir.mkpath(newPath); splitFileName = "!"+newPath+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; } else { splitFileName = "!"+path+"/"+instData.shortName+"."+filter+"."+uniqueID+"_"+QString::number(chipID)+"P.fits"; } } } } // Some instrument modes need special treatment bool Splitter::individualFixWriteImage(int chipMapped) { bool individualFixDone = false; if (instData.name == "LIRIS_POL@WHT") { // Write the four subregions with the different polarization angles as separate FITS files for (int channel=0; channel<=3; ++channel) { fitsfile *fptr; int status = 0; long fpixel = 1; // WARNING: If the SIZEx/y vectors in instrument.ini change, we must also change the ijminmax below! long nax1 = instData.sizex[0]; long nax2 = instData.sizey[0]; long nelements = nax1*nax2; long imin = 43; // same for all channels long imax = 980; // same for all channels long jmin = 0; long jmax = 0; QString channelID = ""; if (channel == 0) { // 0 deg jmin = 739; // always 200 pixels high jmax = 938; channelID = "PA000"; } else if (channel == 1) { // 90 deg jmin = 513; jmax = 712; channelID = "PA090"; } else if (channel == 2) { // 135 deg jmin = 285; jmax = 484; channelID = "PA135"; } else if (channel == 3) { // 45 deg jmin = 62; jmax = 261; channelID = "PA045"; } float *array = new float[nelements]; long k = 0; for (long j=0; j<naxis2Raw; ++j) { for (long i=0; i<naxis2Raw; ++i) { if (i>=imin && i<=imax && j>=jmin && j<=jmax) { array[k] = dataCurrent[i+naxis1Raw*j]; ++k; } } } long naxis = 2; long naxes[2] = {nax1, nax2}; // Replace blanks in file names baseName.replace(' ','_'); // Output file goes to a separate directory to account for different detectors / filters QString newPath = path+"_"+channelID; QDir newDir(newPath); newDir.mkpath(newPath); QString outName = "!"+newPath+"/"+baseName+"_"+channelID+"_1P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { outName = "!"+newPath+"/"+instData.shortName+"."+filter+"_"+channelID+"."+dateObsValue+"_1P.fits"; } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i<headerTHELI.length(); ++i) { fits_write_record(fptr, headerTHELI[i].toUtf8().constData(), &status); } // Update the filter keyword with the polarization angle QString newFilter = filter+"_"+channelID; fits_update_key_str(fptr, "FILTER", newFilter.toUtf8().data(), nullptr, &status); fits_update_key_str(fptr, "ORIGIN", fileName.toUtf8().data(), nullptr, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } individualFixDone = true; } if (instNameFromData == "GROND_NIR@MPGESO") { // Write the three channels as separate FITS files for (int channel=0; channel<=2; ++channel) { fitsfile *fptr; int status = 0; long fpixel = 1; long nax1 = 1024; long nax2 = 1024; long nelements = nax1*nax2; long imin = 0; long imax = 0; long jmin = 0; // same for all channels long jmax = 1023; // same for all channels float gain = 1.0; QString channelID = ""; if (channel == 0) { imin = 0; imax = 1023; channelID = "J"; searchKeyValue(QStringList() << "J_GAIN", gain); } else if (channel == 1) { imin = 1024; imax = 2047; channelID = "H"; searchKeyValue(QStringList() << "H_GAIN", gain); } else if (channel == 2) { imin = 2048; imax = 3071; channelID = "K"; searchKeyValue(QStringList() << "K_GAIN", gain); } float *array = new float[nelements]; long k = 0; for (long j=0; j<naxis2Raw; ++j) { for (long i=0; i<naxis1Raw; ++i) { if (i>=imin && i<=imax && j>=jmin && j<=jmax) { array[k] = -1.0 * dataCurrent[i+naxis1Raw*j] * gain; // ADUs counting negative?? I thought I have seen it all ... ++k; } } } long naxis = 2; long naxes[2] = {nax1, nax2}; // Replace blanks in file names baseName.replace(' ','_'); // Output file goes to a separate directory to account for different detectors / filters QString newPath = path+"_"+channelID; QDir newDir(newPath); newDir.mkpath(newPath); QString outName = "!"+newPath+"/"+baseName+"_"+channelID+"_1P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { outName = "!"+newPath+"/"+instData.shortName+"."+channelID+"."+dateObsValue+"_1P.fits"; } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i<headerTHELI.length(); ++i) { fits_write_record(fptr, headerTHELI[i].toUtf8().constData(), &status); } // Update the filter keyword with the polarization angle QString newFilter = channelID; fits_update_key_str(fptr, "FILTER", newFilter.toUtf8().data(), nullptr, &status); fits_update_key_str(fptr, "ORIGIN", fileName.toUtf8().data(), nullptr, &status); // Update the gain fits_update_key_flt(fptr, "GAINORIG", gain, 6, nullptr, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } individualFixDone = true; } return individualFixDone; } void Splitter::writeImageSlice(int chip, long slice) { if (!successProcessing) return; // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i<nelements; ++i) { array[i] = dataCurrent[i]; } long naxis = 2; long naxes[2] = { naxis1, naxis2 }; // Infer true chip number: int chipID = inferChipID(chip); // Output file name QString outName; if (naxis3Raw == 1) outName = "!"+path+"/"+baseName+"_"+QString::number(chipID)+"P.fits"; else outName = "!"+path+"/"+baseName+"_sl"+QString::number(slice)+"_"+QString::number(chipID)+"P.fits"; // If renaming active, and dateobs was determined successfully if (cdw->ui->theliRenamingCheckBox->isChecked() && dateObsValue != "2020-01-01T00:00:00.000") { if (dataFormat == "RAW") { // No filter name for bayer matrix images if (naxis3Raw == 1) outName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; else outName = "!"+path+"/"+instData.shortName+"."+dateObsValue+"_sl"+QString::number(slice)+"_"+QString::number(chipID)+"P.fits"; } else { if (naxis3Raw == 1) outName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_"+QString::number(chipID)+"P.fits"; else outName = "!"+path+"/"+instData.shortName+"."+filter+"."+dateObsValue+"_sl"+QString::number(slice)+"_"+QString::number(chipID)+"P.fits"; } } fits_create_file(&fptr, outName.toUtf8().data(), &status); fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Propagate header for (int i=0; i<headerTHELI.length(); ++i) { fits_write_record(fptr, headerTHELI[i].toUtf8().constData(), &status); } // Update the SATURATE keyword fits_update_key_flt(fptr, "SATURATE", saturationValue, 6, nullptr, &status); // WARNING: POOR TIMIMG! Increment MJD-OBS by 0.1 s per slice double mjdobs = 0.; fits_read_key_dbl(fptr, "MJD-OBS", &mjdobs, NULL, &status); mjdobs += slice*1.157e-6; fits_update_key_dbl(fptr, "MJD-OBS", mjdobs, 12, NULL, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } // UNUSED. Not sure whether I need the MyImages sorted // Crashes with an out-of-range error on mask->globalMask (or mask->isChipMasked) vector when restoring data from RAWDATA and rerunning. // Works fine if done the first time. void Splitter::initMyImage(int chip) { if (!successProcessing) return; // TODO: must use chipID instead of "chip", e.g. for FORS2 MyImage *myImage = new MyImage(path, baseName+"_"+QString::number(chip+1)+"P.fits", "P", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->imageOnDrive = true; omp_set_lock(genericLock); data->myImageList[chip].append(myImage); if (!data->uniqueChips.contains(chip+1)) data->uniqueChips.push_back(chip+1); omp_unset_lock(genericLock); connect(myImage, &MyImage::modelUpdateNeeded, data, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, data, &Data::pushCritical); connect(myImage, &MyImage::warning, data, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, data, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, data, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, data, &Data::setWCSLockReceived, Qt::DirectConnection); myImage->emitModelUpdateNeeded(); myImage->readImage(splitFileName.remove("!")); ++data->numImages; } void Splitter::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable(baseName + " Splitter::"+funcName+":<br>" + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } } void Splitter::testGROND() { // we want to identify for each exposure whether it comes from the optical or the NIR camera // so that we can use the appropriate branch to deal with the data if (instData.name.contains("GROND")) { int nax1 = 0; searchKeyValue(QStringList() << "NAXIS1", nax1); if (nax1 == 3072) instNameFromData = "GROND_NIR@MPGESO"; else instNameFromData = "GROND_OPT@MPGESO"; } } void Splitter::readExtHeader() { if (rawStatus) return; // Read the entire header. This should always work! char *fullheader = nullptr; int numHeaderKeys = 0; fits_hdr2str(rawFptr, TRUE, NULL, 0, &fullheader, &numHeaderKeys, &rawStatus); printCfitsioError(__func__, rawStatus); if (rawStatus) return; fullExtHeaderString = QString::fromUtf8(fullheader); fits_free_memory(fullheader, &rawStatus); // Map the header onto a QVector<QString> int cardLength = 80; long length = fullExtHeaderString.length(); if (length<80) return; extHeader.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullExtHeaderString, i, cardLength); QString string = subString.toString(); extHeader.push_back(string); } } void Splitter::readPrimaryHeader() { if (rawStatus) return; if (!successProcessing) return; // Read the entire header. This should always work! char *fullheader = nullptr; int numHeaderKeys = 0; fits_hdr2str(rawFptr, TRUE, NULL, 0, &fullheader, &numHeaderKeys, &rawStatus); printCfitsioError(__func__, rawStatus); if (rawStatus) return; fullPrimaryHeaderString = QString::fromUtf8(fullheader); fits_free_memory(fullheader, &rawStatus); // Map the header onto a QVector<QString> int cardLength = 80; long length = fullPrimaryHeaderString.length(); if (length<80) return; primaryHeader.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullPrimaryHeaderString, i, cardLength); QString string = subString.toString(); primaryHeader.push_back(string); } } bool Splitter::checkCorrectMaskSize(const int chip) { if (instData.name.contains("DUMMY")) return true; long n_mask = mask->globalMask[chip].length(); long n_data = dataCurrent.length(); // detectors with multi-amps (one amp per FITS extension): masked at a later stage (calibration) if (instNameFromData == "GROND_NIR@MPGESO" && instData.name == "GROND_NIR@MPGESO") return true; if (n_mask > 0 && n_data > 0 && n_mask != n_data) { if (!maskSizeWarningShown) { emit messageAvailable(fileName + ": Inconsistent image size detected between data and instrument configuration" " (overscan and / or data section) in\n"+instData.nameFullPath+ " \n. The image will not be processed, please remove it manually.", "warning"); emit warning(); // successProcessing = false; // maskSizeWarningShown = true; return false; } } return true; } bool Splitter::checkInstrumentConsistency(QString foundInstrumentName) { QString expectedInstrumentName = instrumentDictionary.value(instData.name); if (!expectedInstrumentName.isEmpty() && expectedInstrumentName != foundInstrumentName) { emit messageAvailable(fileName + ": Wrong instrument selected: Expected " + instData.name + ", but \"INSTRUME= " + foundInstrumentName+"\"", "error"); emit critical(); successProcessing = false; return false; } return true; }
64,883
C++
.cc
1,410
36.856738
202
0.589452
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,455
splitter_buildHeader.cc
schirmermischa_THELI/src/tools/splitter_buildHeader.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "cfitsioerrorcodes.h" #include <QString> #include <QStringList> #include <QVector> #include <QFile> #include <QDir> /* // TODO Instrument slike FORS1/2 come with different collimators, changing the plate scale but not the detector geometries. What to do with PIXSCALE in this respect/ Do we still need it in the instrument.ini files, or is it better derived from the CD matrix directly? Binning: include as separate option? need to check various instruments whether their overscan and gain stay the same or not. Could alternatively offer separate overscan / size vectors in the .ini files. Or even better: automatic detection of the binning mode Take CRPIX from .ahead file for multi-chip cameras. Don't take CD matrix from ahead file because of changing position angles ... */ void Splitter::buildTheliHeader() { if (!successProcessing) return; // The following keywords must be present in the THELI headers, // AND the values taken from the raw data QStringList mandatoryKeys = {"OBJECT"}; // Loop over all mandatory keywords and try to find a match. // Certainly not the most efficient way of doing it, but the overhead should be small // as we operate on QStringLists and not FITS files QString fallback = ""; for (auto &mandatoryKey : mandatoryKeys) { // Search key in primary and extension header, and append it to 'headerTHELI' if found bool keyFound = searchKey(mandatoryKey, headerDictionary.value(mandatoryKey), headerTHELI); // Default fallback values if (mandatoryKey == "OBJECT" && !keyFound) fallback = "OBJECT = 'Unknown'"; if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+mandatoryKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerTHELI.append(fallback); } } // Append geographic coordinates QString geolon = "GEOLON = "+QString::number(instData.obslon, 'f', 4); QString geolat = "GEOLAT = "+QString::number(instData.obslat, 'f', 4); geolon.resize(80, ' '); geolat.resize(80, ' '); headerTHELI.append(geolon); headerTHELI.append(geolat); // Append BUNIT QString bunit = "BUNIT = 'e-'"; bunit.resize(80, ' '); headerTHELI.append(bunit); // Instrument-specific optional keys bool keyFoundOptional = true; QString instSpecificKey = ""; if (instData.name == "SPARTAN@SOAR") instSpecificKey = "ROTATOR"; if (!instSpecificKey.isEmpty()) keyFoundOptional = searchKey(instSpecificKey, {instSpecificKey}, headerTHELI); if (!keyFoundOptional) emit messageAvailable(fileName + " : Could not determine instrument-specific keyword: "+instSpecificKey, "warning"); // Propagate Bayer matrix ID for color CCD chips if (!instData.bayer.isEmpty()) { QString card = "BAYER = '"+instData.bayer+"'"; card.resize(80, ' '); headerTHELI.append(card); } // Append DUMMY keywords headerTHELI.append(dummyKeys); // Append the THELIPRO keyword to indicate that this FITS file underwent initial THELI processing QString card = "THELIPRO= 1 / Processed by THELI"; card.resize(80, ' '); headerTHELI.append(card); } void Splitter::buildTheliHeaderMJDOBS() { if (!successProcessing) return; // List of instruments for which MJD-OBS is not reliable and should be constructed from DATE-OBS QStringList instruments = {"GSAOI@GEMINI", "GSAOI_CHIP1@GEMINI", "GSAOI_CHIP2@GEMINI", "GSAOI_CHIP3@GEMINI", "GSAOI_CHIP4@GEMINI", "FLAMINGOS2@GEMINI", "FLAMINGOS2_CANOPUS@GEMINI", "SAMI_2x2@SOAR" // integer }; if (instruments.contains(instData.name)) { if (!dateObsValue.isEmpty()) { mjdobsValue = dateobsToMJD(); QString mjdCard = "MJD-OBS = "+QString::number(mjdobsValue,'f',7); mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); } else { mjdobsValue = 58849.000000; QString mjdCard = "MJD-OBS = 58849.000000"; mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); emit messageAvailable(fileName + " : Could not determine keyword: MJD-OBS, set to 58849.000000 (2020-01-01)<br>"+ "Some processing tasks (background modeling, proper motion correction, catalog creation) will not work correctly.", "warning"); emit warning(); } return; } // Search key in primary and extension header, and append it to 'headerTHELI' if found bool keyFound = searchKey("MJD-OBS", headerDictionary.value("MJD-OBS"), headerTHELI); if (keyFound) return; // Calculate MJD-OBS from DATE-OBS if not found if (!keyFound && !dateObsValue.isEmpty()) { mjdobsValue = dateobsToMJD(); QString mjdCard = "MJD-OBS = "+QString::number(mjdobsValue,'f',7); mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); } else { mjdobsValue = 58849.000000; QString mjdCard = "MJD-OBS = 58849.000000"; mjdCard.resize(80, ' '); headerTHELI.append(mjdCard); emit messageAvailable(fileName + " : Could not determine keyword: MJD-OBS, set to 58849.000000 (2020-01-01)<br>"+ "Some processing tasks (background modeling, proper motion correction) will not work correctly.", "warning"); emit warning(); } } // UNUSED void Splitter::buildTheliHeaderSATURATION() { QString card = "SATURATE= " + QString::number(saturationValue, 'f', 6) + " / Saturation level for this image"; card.resize(80, ' '); headerTHELI.append(card); } void Splitter::buildTheliHeaderWCS(int chip) { if (!successProcessing) return; // Each of the following handles their own exceptions for specific instruments // (which don't carry a proper and consistent FITS header) WCSbuildCTYPE(); WCSbuildCRVAL(); WCSbuildCRPIX(chip); WCSbuildCDmatrix(chip); WCSbuildRADESYS(); WCSbuildEQUINOX(); } void Splitter::WCSbuildCRPIX(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCRPIX(chip)) return; if (chip >= instData.crpix1.length()) { QString nfound = QString::number(chip+1); QString nexpected = QString::number(instData.numChips); emit messageAvailable(fileName + ": " + nfound + " detectors found, " + nexpected + " expected. Check instrument selection." , "error"); emit critical(); successProcessing = false; return; } QStringList headerWCS; // Use dedicated lookup if (instData.name == "HSC@SUBARU" || instData.name == "NISP_LE2@EUCLID" || instData.name == "VIS_LE2@EUCLID") { searchKeyCRVAL("CRPIX1", headerDictionary.value("CRPIX1"), headerWCS); searchKeyCRVAL("CRPIX2", headerDictionary.value("CRPIX2"), headerWCS); } // if (instData.name == "VIS_LE1@EUCLID") { // searchKeyCRVAL("CRPIX1", headerDictionary.value("CRPIX1"), headerWCS); // searchKeyCRVAL("CRPIX2", headerDictionary.value("CRPIX2"), headerWCS); // } else { // CRPIXi: Rely on instrument.ini (Todo: scan .ahead files directly for multi-chip cameras) QString crpix1_card = "CRPIX1 = "+QString::number(instData.crpix1[chip]); QString crpix2_card = "CRPIX2 = "+QString::number(instData.crpix2[chip]); crpix1_card.resize(80, ' '); crpix2_card.resize(80, ' '); headerWCS.append(crpix1_card); headerWCS.append(crpix2_card); } headerTHELI.append(headerWCS); } // Instrument dependent void Splitter::WCSbuildCRVAL() { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCRVAL()) return; QStringList headerWCS; // Use dedicated lookup searchKeyCRVAL("CRVAL1", headerDictionary.value("CRVAL1"), headerWCS); searchKeyCRVAL("CRVAL2", headerDictionary.value("CRVAL2"), headerWCS); headerTHELI.append(headerWCS); } void Splitter::WCSbuildCTYPE() { if (!successProcessing) return; QStringList headerWCS; // CTYPEi are fixed no matter what! QString ctype1_card = "CTYPE1 = 'RA---TAN'"; QString ctype2_card = "CTYPE2 = 'DEC--TAN'"; ctype1_card.resize(80, ' '); ctype2_card.resize(80, ' '); headerWCS.append(ctype1_card); headerWCS.append(ctype2_card); headerTHELI.append(headerWCS); } // Instrument dependent /* void Splitter::WCSbuildCDmatrix(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCDmatrix(chip)) return; QStringList headerWCS; QString fallback = ""; QStringList wcsKeys = {"CD1_1", "CD1_2", "CD2_1", "CD2_2"}; float flipcd11 = 1.0; float flipcd22 = 1.0; if (instData.flip == "FLIPX") flipcd11 = -1.0; else if (instData.flip == "FLIPY") flipcd22 = -1.0; else if (instData.flip == "ROT180") { flipcd11 = -1.0; flipcd22 = -1.0; } for (auto &wcsKey : wcsKeys) { bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); // fallback double cd = 0.0; if (!keyFound && wcsKey == "CD1_1") { bool success = CDfromCDELTandPC("CDELT1", "PC1_1", cd); if (success) fallback = "CD1_1 = "+QString::number(cd, 'g', 6); else fallback = "CD1_1 = "+QString::number(-1.*flipcd11*instData.pixscale/3600., 'g', 6); } if (!keyFound && wcsKey == "CD2_2") { bool success = CDfromCDELTandPC("CDELT2", "PC2_2", cd); if (success) fallback = "CD2_2 = "+QString::number(cd, 'g', 6); else fallback = "CD2_2 = "+QString::number(flipcd22*instData.pixscale/3600., 'g', 6); } if (!keyFound && wcsKey == "CD1_2") { bool success = CDfromCDELTandPC("CDELT2", "PC1_2", cd); if (success) fallback = "CD1_2 = "+QString::number(cd, 'g', 6); else fallback = "CD1_2 = 0.0"; } if (!keyFound && wcsKey == "CD2_1") { bool success = CDfromCDELTandPC("CDELT1", "PC2_1", cd); if (success) fallback = "CD2_1 = "+QString::number(cd, 'g', 6); else fallback = "CD2_1 = 0.0"; } if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerWCS.append(fallback); } } headerTHELI.append(headerWCS); } */ // Instrument dependent void Splitter::WCSbuildCDmatrix(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixCDmatrix(chip)) return; QStringList headerWCS; QString fallback = ""; QStringList wcsKeys = {"CD1_1", "CD1_2", "CD2_1", "CD2_2"}; // Create fallback CD matrix from CDELT keywords, if later determination of CDij fails QVector<double> cd_fallback; cd_fallback = CDfromCDELT(); // Try reading CDij matrix directly, sue fallback if failing for (auto &wcsKey : wcsKeys) { bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); // fallback if (!keyFound && wcsKey == "CD1_1") fallback = "CD1_1 = "+QString::number(cd_fallback[0], 'g', 6); if (!keyFound && wcsKey == "CD1_2") fallback = "CD1_2 = "+QString::number(cd_fallback[1], 'g', 6); if (!keyFound && wcsKey == "CD2_1") fallback = "CD2_1 = "+QString::number(cd_fallback[2], 'g', 6); if (!keyFound && wcsKey == "CD2_2") fallback = "CD2_2 = "+QString::number(cd_fallback[3], 'g', 6); if (!keyFound) { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+fallback, "ignore"); fallback.resize(80, ' '); headerWCS.append(fallback); } } headerTHELI.append(headerWCS); } /* bool Splitter::CDfromCDELTandPC(const QString cdeltstr, const QString pcstr, double &cd) { double cdelt = -1.0; double pc = -1.0; bool cdtest = searchKeyValue(headerDictionary.value(cdeltstr), cdelt); bool pctest = searchKeyValue(headerDictionary.value(pcstr), pc); if (cdtest && pctest) { cd = cdelt*pc; if (fabs(cd) > 0.5) cd *= instData.pixscale/3600.; // recover plate scale if not available return true; } else if (cdtest && !pctest) { cd = cdelt; if (fabs(cd) > 0.5) cd *= instData.pixscale/3600.; qDebug() << cdeltstr << cd; return true; } else { cd = 0.; return false; } } */ QVector<double> Splitter::CDfromCDELT() { double cdelt1 = 0.; double cdelt2 = 0.; double pc11 = 1.; // matching crota2 = 0. double pc12 = 0.; // matching crota2 = 0. double pc21 = 0.; // matching crota2 = 0. double pc22 = 1.; // matching crota2 = 0. double crota2 = 0.; bool cdelt1test = searchKeyValue(headerDictionary.value("CDELT1"), cdelt1); bool cdelt2test = searchKeyValue(headerDictionary.value("CDELT2"), cdelt2); bool crota2test = searchKeyValue(headerDictionary.value("CROTA2"), crota2); bool pc11test = searchKeyValue(headerDictionary.value("PC1_1"), pc11); bool pc12test = searchKeyValue(headerDictionary.value("PC1_2"), pc12); bool pc21test = searchKeyValue(headerDictionary.value("PC2_1"), pc21); bool pc22test = searchKeyValue(headerDictionary.value("PC2_2"), pc22); bool pctest = true; pctest = pc11test && pc12test && pc21test && pc22test; if (!pctest) { // check for really old convention pc11test = searchKeyValue(headerDictionary.value("PC001001"), pc11); pc12test = searchKeyValue(headerDictionary.value("PC001002"), pc12); pc21test = searchKeyValue(headerDictionary.value("PC002001"), pc21); pc22test = searchKeyValue(headerDictionary.value("PC002002"), pc22); pctest = pc11test && pc12test && pc21test && pc22test; } // Only if no CD matrix information is present in the raw FITS headers: float flipcd11 = 1.0; float flipcd22 = 1.0; if (instData.flip == "FLIPX") flipcd11 = -1.0; else if (instData.flip == "FLIPY") flipcd22 = -1.0; else if (instData.flip == "ROT180") { flipcd11 = -1.0; flipcd22 = -1.0; } double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; // Now build the CD matrix QVector<double> cd; // No information whatsoever: return standard "North up East left" if (!cdelt1test || !cdelt2test) { cd11 = -flipcd11*instData.pixscale/3600.; cd22 = flipcd22*instData.pixscale/3600.; cd << cd11 << cd12 << cd21 << cd22; return cd; } // CDELT yes, but no information about sky position angle if (!pctest && !crota2test) { cd11 = cdelt1; cd22 = cdelt2; cd << cd11 << cd12 << cd21 << cd22; return cd; } // CROTA2 but no PC matrix else if (!pctest && crota2test) { pc11 = cos(crota2*rad); pc12 = -sin(crota2*rad); pc21 = sin(crota2*rad); pc22 = cos(crota2*rad); } // PC matrix and CROTA2 // According to the FITS standard, this combination is not allowed, but still some headers have it else if (pctest && crota2test) { pc11 = cos(crota2*rad); pc12 = -sin(crota2*rad); pc21 = sin(crota2*rad); pc22 = cos(crota2*rad); emit messageAvailable(name + " : PC matrix and CROTA2 found. Using CROTA2 to compute CD matrix.", "warning"); } else { // (pctest && !crota2test) { // already handled above by determining the PCij elements directly from FITS header } // Compute the CD matrix cd11 = cdelt1 * pc11; cd12 = cdelt2 * pc12; cd21 = cdelt1 * pc21; cd22 = cdelt2 * pc22; // safety check if (fabs(cd11) > 0.5 || fabs(cd11) > 0.5 || fabs(cd21) > 0.5 || fabs(cd22) > 0.5) { cd11 = -flipcd11*instData.pixscale/3600.; cd22 = flipcd22*instData.pixscale/3600.; cd12 = 0.; cd21 = 0.; } cd << cd11 << cd12 << cd21 << cd22; return cd; } void Splitter::WCSbuildRADESYS() { if (!successProcessing) return; QStringList headerWCS; QString wcsKey = "RADESYS"; bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); if (!keyFound) { QString card = "RADESYS = 'ICRS'"; if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+card, "ignore"); card.resize(80, ' '); headerWCS.append(card); } headerTHELI.append(headerWCS); } void Splitter::WCSbuildEQUINOX() { if (!successProcessing) return; if (individualFixEQUINOX()) return; QStringList headerWCS; QString wcsKey = "EQUINOX"; bool keyFound = searchKey(wcsKey, headerDictionary.value(wcsKey), headerWCS); if (!keyFound) { QString card = "EQUINOX = 2000.0"; if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: "+wcsKey+", using default: "+card, "ignore"); card.resize(80, ' '); headerWCS.append(card); } headerTHELI.append(headerWCS); } bool Splitter::individualFixEQUINOX() { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString equinoxCard = ""; if (instData.name == "SITe3_SWOPE@LCO") { equinoxCard = equinoxCard = "EQUINOX = 2000.0"; // SITe3_SWOPE@LCO has EPOCH written to EQUINOX, which makes scamp fail since the coords are in J2000. individualFixDone = true; } if (instData.name == "VIS_LE1@EUCLID" || instData.name == "VIS_ERO@EUCLID") { equinoxCard = equinoxCard = "EQUINOX = 2000.0"; individualFixDone = true; } if (individualFixDone) { equinoxCard.resize(80, ' '); headerWCS.append(equinoxCard); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCRVAL() { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString crval1_card = ""; QString crval2_card = ""; QString crval1 = ""; QString crval2 = ""; // List of instruments that we have to consider QStringList list = {"WFC@INT", "WFC_2x2@INT", "SUSI1@NTT", "PISCO@LCO"}; // Leave if no individual fix is required. if (!list.contains(instData.name)) return false; // Prepare fix. // First, read coords and fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') // Convert to decimal format if necessary searchKeyValue(headerDictionary.value("CRVAL1"), crval1); searchKeyValue(headerDictionary.value("CRVAL2"), crval2); crval1.replace(' ', ':'); crval2.replace(' ', ':'); if (crval1.contains(':')) crval1 = hmsToDecimal(crval1); if (crval2.contains(':')) crval2 = dmsToDecimal(crval2); // Here are the individual fixes if (instData.name == "WFC@INT" || instData.name == "WFC_2x2@INT") { double alpha = crval1.toDouble(); double delta = crval2.toDouble(); // reset the coordinates such that scamp does not get confused (optical axis != crpix by ~4 arcminutes) alpha = alpha - 0.0733 / cos(delta*rad); if (alpha > 360.) alpha -= 360.; if (alpha < 0.) alpha += 360.; delta = delta - 0.02907; crval1_card = "CRVAL1 = "+QString::number(alpha, 'f', 6); crval2_card = "CRVAL2 = "+QString::number(delta, 'f', 6); individualFixDone = true; } if (instData.name == "SUSI1@NTT") { searchKeyValue(QStringList() << "RA", crval1); searchKeyValue(QStringList() << "DEC", crval2); crval1_card = "CRVAL1 = "+crval1; crval2_card = "CRVAL2 = "+crval2; individualFixDone = true; } if (instData.name == "PISCO@LCO") { searchKeyValue(QStringList() << "TELRA", crval1); // CRVALij in FITS extensions are highly inaccurate searchKeyValue(QStringList() << "TELDC", crval2); if (crval1.contains(":")) crval1 = hmsToDecimal(crval1); if (crval2.contains(":")) crval2 = dmsToDecimal(crval2); crval1_card = "CRVAL1 = "+crval1; crval2_card = "CRVAL2 = "+crval2; individualFixDone = true; } if (instData.name == "Omega2000@CAHA") { searchKeyValue(QStringList() << "RA", crval1); // CRVAL1/2 is sometimes set to 1.0 searchKeyValue(QStringList() << "DEC", crval2); if (crval1.contains(":")) crval1 = hmsToDecimal(crval1); if (crval2.contains(":")) crval2 = dmsToDecimal(crval2); crval1_card = "CRVAL1 = "+crval1; crval2_card = "CRVAL2 = "+crval2; individualFixDone = true; } if (individualFixDone) { crval1_card.resize(80, ' '); crval2_card.resize(80, ' '); headerWCS.append(crval1_card); headerWCS.append(crval2_card); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCRPIX(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; QString crpix1_card = ""; QString crpix2_card = ""; float crpix1 = 0.; float crpix2 = 0.; // Leave if no individual fix is required. if (!multiChannelMultiExt.contains(instData.name)) return false; // Prepare fix. // Convert to decimal format if necessary searchKeyValue(headerDictionary.value("CRPIX1"), crpix1); searchKeyValue(headerDictionary.value("CRPIX2"), crpix2); // Solutions per individual channel (will be ignored) crpix1_card = "CRPIX1 = "+QString::number(crpix1, 'f', 2); crpix2_card = "CRPIX2 = "+QString::number(crpix2, 'f', 2); // Here are the individual fixes if (instData.name == "GMOS-N-HAM_1x1@GEMINI" || instData.name == "GMOS-S-HAM_1x1@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 3180"; if (chip == 7) crpix1_card = "CRPIX1 = 1088"; if (chip == 11) crpix1_card = "CRPIX1 = -1004"; crpix2_card = "CRPIX2 = 2304"; individualFixDone = true; } if (instData.name == "GMOS-N-HAM@GEMINI" || instData.name == "GMOS-S-HAM@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 1589"; if (chip == 7) crpix1_card = "CRPIX1 = 544"; if (chip == 11) crpix1_card = "CRPIX1 = -502"; crpix2_card = "CRPIX2 = 1152"; individualFixDone = true; } if (instData.name == "GMOS-S-HAM_4x4@GEMINI") { if (chip == 3) crpix1_card = "CRPIX1 = 794"; if (chip == 7) crpix1_card = "CRPIX1 = 272"; if (chip == 11) crpix1_card = "CRPIX1 = -251"; crpix2_card = "CRPIX2 = 576"; individualFixDone = true; } if (instData.name == "SOI@SOAR") { if (chip == 1) crpix1_card = "CRPIX1 = 1051"; if (chip == 3) crpix1_card = "CRPIX1 = -26"; crpix2_card = "CRPIX2 = 1024"; individualFixDone = true; } if (instData.name == "DEIMOS_2AMP@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = 4253"; if (chip == 3) crpix1_card = "CRPIX1 = 2097"; if (chip == 5) crpix1_card = "CRPIX1 = -53"; if (chip == 7) crpix1_card = "CRPIX1 = -2200"; crpix2_card = "CRPIX2 = 1301"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = 2099"; if (chip == 3) crpix1_card = "CRPIX1 = -52"; crpix2_card = "CRPIX2 = 2052"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { if (chip == 1) crpix1_card = "CRPIX1 = -126"; if (chip == 3) crpix1_card = "CRPIX1 = 1835"; crpix2_card = "CRPIX2 = 1260"; individualFixDone = true; } if (instData.name == "MOSAIC-II_16@CTIO") { if (chip == 1) crpix1_card = "CRPIX1 = 4219"; if (chip == 3) crpix1_card = "CRPIX1 = 2078"; if (chip == 5) crpix1_card = "CRPIX1 = -33"; if (chip == 7) crpix1_card = "CRPIX1 = -2166"; if (chip == 9) crpix1_card = "CRPIX1 = 4221"; if (chip == 11) crpix1_card = "CRPIX1 = 2081"; if (chip == 13) crpix1_card = "CRPIX1 = -31"; if (chip == 15) crpix1_card = "CRPIX1 = -2169"; if (chip == 1) crpix2_card = "CRPIX2 = 4148"; if (chip == 3) crpix2_card = "CRPIX2 = 4121"; if (chip == 5) crpix2_card = "CRPIX2 = 4119"; if (chip == 7) crpix2_card = "CRPIX2 = 4136"; if (chip == 9) crpix2_card = "CRPIX2 = -34"; if (chip == 11) crpix2_card = "CRPIX2 = -24"; if (chip == 13) crpix2_card = "CRPIX2 = -26"; if (chip == 15) crpix2_card = "CRPIX2 = -56"; individualFixDone = true; } if (instData.name == "PISCO@LCO") { if (chip == 1) crpix1_card = "CRPIX1 = 1500"; if (chip == 3) crpix1_card = "CRPIX1 = 1500"; if (chip == 5) crpix1_card = "CRPIX1 = 1500"; if (chip == 7) crpix1_card = "CRPIX1 = 1500"; if (chip == 1) crpix2_card = "CRPIX2 = 3000"; if (chip == 3) crpix2_card = "CRPIX2 = 3000"; if (chip == 5) crpix2_card = "CRPIX2 = 3000"; if (chip == 7) crpix2_card = "CRPIX2 = 3000"; individualFixDone = true; } if (instData.name == "MOSAIC-III_4@KPNO_4m") { if (chip == 3) crpix1_card = "CRPIX1 = 4219"; if (chip == 7) crpix1_card = "CRPIX1 = 2078"; if (chip == 11) crpix1_card = "CRPIX1 = -33"; if (chip == 15) crpix1_card = "CRPIX1 = -2166"; if (chip == 3) crpix2_card = "CRPIX2 = 4148"; if (chip == 7) crpix2_card = "CRPIX2 = 4121"; if (chip == 11) crpix2_card = "CRPIX2 = 4119"; if (chip == 15) crpix2_card = "CRPIX2 = 4136"; individualFixDone = true; } if (instData.name == "SAMI_2x2@SOAR") { if (chip == 3) { crpix1_card = "CRPIX1 = 1024"; crpix1_card = "CRPIX1 = 1024"; } individualFixDone = true; } // Append only when all channels of one chip have been read (i.e., 'individualFixDone' == true) if (individualFixDone) { crpix1_card.resize(80, ' '); crpix2_card.resize(80, ' '); headerWCS.append(crpix1_card); headerWCS.append(crpix2_card); headerTHELI.append(headerWCS); } return individualFixDone; } bool Splitter::individualFixCDmatrix(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QStringList headerWCS; double cd11 = 0.; double cd12 = 0.; double cd21 = 0.; double cd22 = 0.; QString cd11_card = ""; QString cd12_card = ""; QString cd21_card = ""; QString cd22_card = ""; if (instData.name == "Direct_2k_DUPONT@LCO") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = -7.2273e-5"; cd21_card = "CD2_1 = -7.2273e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "Omega2000@CAHA") { cd11_card = "CD1_1 = -0.000124639"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 0.000124639"; individualFixDone = true; } if (instData.name == "SITe3_SWOPE@LCO") { cd11_card = "CD1_1 = -1.2083e-4"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -1.2083e-4"; individualFixDone = true; } if (instData.name == "Direct_4k_SWOPE@LCO") { if (chip == 0) { cd11_card = "CD1_1 = 8.839493716E-07"; cd12_card = "CD1_2 = -1.209379295E-04"; cd21_card = "CD2_1 = -1.209379295E-04"; cd22_card = "CD2_2 = -8.839493716E-07"; } if (chip == 1) { cd11_card = "CD1_1 = -8.861927404E-07"; cd12_card = "CD1_2 = -1.209344868E-04"; cd21_card = "CD2_1 = 1.209344868E-04"; cd22_card = "CD2_2 = -8.861927404E-07"; } if (chip == 2) { cd11_card = "CD1_1 = -7.788683939E-07"; cd12_card = "CD1_2 = 1.211132665E-04"; cd21_card = "CD2_1 = 1.211132665E-04"; cd22_card = "CD2_2 = 7.788683939E-07"; } if (chip == 3) { cd11_card = "CD1_1 = 8.755109826E-07"; cd12_card = "CD1_2 = 1.208828016E-04"; cd21_card = "CD2_1 = -1.208828016E-04"; cd22_card = "CD2_2 = 8.755109826E-07"; } individualFixDone = true; } if (instData.name == "LDSS3_from201402@LCO") { if (chip == 0) { cd11_card = "CD1_1 = -5.213e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 5.213e-5"; } if (chip == 1) { cd11_card = "CD1_1 = 5.230e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 5.230e-5"; } individualFixDone = true; } if (instData.name == "WFI@MPGESO") { cd11_card = "CD1_1 = -6.611e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 6.611e-5"; individualFixDone = true; } if (instData.name == "DEIMOS_1AMP@KECK" || instData.name == "DEIMOS_2AMP@KECK") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = 3.28000e-5"; cd21_card = "CD2_1 = 3.28000e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { cd11_card = "CD1_1 = 0.0"; cd12_card = "CD1_2 = -3.76e-5"; cd21_card = "CD2_1 = 3.76e-5"; cd22_card = "CD2_2 = 0.0"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { cd11_card = "CD1_1 = -3.76e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -3.76e-5"; individualFixDone = true; } if (instData.name == "ESI@KECK") { cd11_card = "CD1_1 = -4.28333e-5"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = -4.28333e-5"; individualFixDone = true; } if (instData.name.contains("WFI_2x2") && instData.name.contains("MPGESO") ) { cd11_card = "CD1_1 = -1.322e-4"; cd12_card = "CD1_2 = 0.0"; cd21_card = "CD2_1 = 0.0"; cd22_card = "CD2_2 = 1.322e-4"; individualFixDone = true; } if (instData.name == "WFC@INT") { if (chip == 0) { cd11_card = "CD1_1 = -1.186589131599E-06"; cd12_card = "CD1_2 = -9.208350034543E-05"; cd21_card = "CD2_1 = -9.202558574925E-05"; cd22_card = "CD2_2 = 9.373099270996E-07"; } if (chip == 1) { cd11_card = "CD1_1 = 9.158969785153E-05"; cd12_card = "CD1_2 = 1.000429584977E-07"; cd21_card = "CD2_1 = -8.707577386754E-08"; cd22_card = "CD2_2 = -9.204121646891E-05"; } if (chip == 2) { cd11_card = "CD1_1 = -1.101867868104E-06"; cd12_card = "CD1_2 = -9.186460105657E-05"; cd21_card = "CD2_1 = -9.119982231051E-05"; cd22_card = "CD2_2 = 1.393090409586E-06"; } if (chip == 3) { cd11_card = "CD1_1 = -9.862265741128E-07"; cd12_card = "CD1_2 = -9.221689418834E-05"; cd21_card = "CD2_1 = -9.224461667406E-05"; cd22_card = "CD2_2 = 1.077599414761E-06"; } individualFixDone = true; } if (instData.name == "WFC_2x2@INT") { if (chip == 0) { cd11_card = "CD1_1 = -2.187595402632E-06"; cd12_card = "CD1_2 = -1.836774933953E-04"; cd21_card = "CD2_1 = -1.836774933953E-04"; cd22_card = "CD2_2 = 2.196693471198E-06"; } if (chip == 1) { cd11_card = "CD1_1 = 1.838979962523E-04"; cd12_card = "CD1_2 = -1.530619041314E-08"; cd21_card = "CD2_1 = -7.465373169364E-08"; cd22_card = "CD2_2 = -1.837749990795E-04"; } if (chip == 2) { cd11_card = "CD1_1 = -2.526051008644E-06"; cd12_card = "CD1_2 = -1.839716072858E-04"; cd21_card = "CD2_1 = -1.839315570910E-04"; cd22_card = "CD2_2 = 2.415393914242E-06"; } if (chip == 3) { cd11_card = "CD1_1 = -2.049772957061E-06"; cd12_card = "CD1_2 = -1.847202572582E-04"; cd21_card = "CD2_1 = -1.847377035556E-04"; cd22_card = "CD2_2 = 2.053889958265E-06"; } individualFixDone = true; } if (instData.name == "VIS_LE1@EUCLID" || instData.name == "VIS_ERO@EUCLID") { if (chip == 0) { cd11_card = "CD1_1 = 1.485336085825E-05"; cd12_card = "CD1_2 = 2.373020263256E-05"; cd21_card = "CD2_1 = 2.362023502688E-05"; cd22_card = "CD2_2 = -1.476723307336E-05"; } if (chip == 1) { cd11_card = "CD1_1 = 1.484838705414E-05"; cd12_card = "CD1_2 = 2.371946211532E-05"; cd21_card = "CD2_1 = 2.359023016259E-05"; cd22_card = "CD2_2 = -1.475883937263E-05"; } if (chip == 2) { cd11_card = "CD1_1 = 1.484493267117E-05"; cd12_card = "CD1_2 = 2.372961666401E-05"; cd21_card = "CD2_1 = 2.360527033961E-05"; cd22_card = "CD2_2 = -1.478049990387E-05"; } if (chip == 3) { cd11_card = "CD1_1 = 1.485549671799E-05"; cd12_card = "CD1_2 = 2.373830735312E-05"; cd21_card = "CD2_1 = 2.363212771872E-05"; cd22_card = "CD2_2 = -1.479105693637E-05"; } if (chip == 4) { cd11_card = "CD1_1 = 1.482322577805E-05"; cd12_card = "CD1_2 = 2.371507215907E-05"; cd21_card = "CD2_1 = 2.355093676088E-05"; cd22_card = "CD2_2 = -1.474000475642E-05"; } if (chip == 5) { cd11_card = "CD1_1 = 1.481650650650E-05"; cd12_card = "CD1_2 = 2.370735654076E-05"; cd21_card = "CD2_1 = 2.351796332508E-05"; cd22_card = "CD2_2 = -1.473037411308E-05"; } if (chip == 6) { cd11_card = "CD1_1 = 1.480737929504E-05"; cd12_card = "CD1_2 = 2.371652791694E-05"; cd21_card = "CD2_1 = 2.353124251720E-05"; cd22_card = "CD2_2 = -1.474913230516E-05"; } if (chip == 7) { cd11_card = "CD1_1 = 1.482929756570E-05"; cd12_card = "CD1_2 = 2.372790077018E-05"; cd21_card = "CD2_1 = 2.356524319612E-05"; cd22_card = "CD2_2 = -1.476447491535E-05"; } if (chip == 8) { cd11_card = "CD1_1 = 1.479396480012E-05"; cd12_card = "CD1_2 = 2.370220372208E-05"; cd21_card = "CD2_1 = 2.347900007563E-05"; cd22_card = "CD2_2 = -1.470872804752E-05"; } if (chip == 9) { cd11_card = "CD1_1 = 1.477691388604E-05"; cd12_card = "CD1_2 = 2.369248796008E-05"; cd21_card = "CD2_1 = 2.343738090092E-05"; cd22_card = "CD2_2 = -1.469482038591E-05"; } if (chip == 10) { cd11_card = "CD1_1 = 1.476551327445E-05"; cd12_card = "CD1_2 = 2.370156642127E-05"; cd21_card = "CD2_1 = 2.345080483108E-05"; cd22_card = "CD2_2 = -1.471937620807E-05"; } if (chip == 11) { cd11_card = "CD1_1 = 1.478379590078E-05"; cd12_card = "CD1_2 = 2.371207468444E-05"; cd21_card = "CD2_1 = 2.348982580685E-05"; cd22_card = "CD2_2 = -1.473464502900E-05"; } if (chip == 12) { cd11_card = "CD1_1 = 1.487203121520E-05"; cd12_card = "CD1_2 = 2.373002440295E-05"; cd21_card = "CD2_1 = 2.363536510299E-05"; cd22_card = "CD2_2 = -1.483722108352E-05"; } if (chip == 13) { cd11_card = "CD1_1 = 1.485657138737E-05"; cd12_card = "CD1_2 = 2.372771830310E-05"; cd21_card = "CD2_1 = 2.359808207965E-05"; cd22_card = "CD2_2 = -1.482579682551E-05"; } if (chip == 14) { cd11_card = "CD1_1 = 1.484828058745E-05"; cd12_card = "CD1_2 = 2.373047734707E-05"; cd21_card = "CD2_1 = 2.360957766250E-05"; cd22_card = "CD2_2 = -1.484199198313E-05"; } if (chip == 15) { cd11_card = "CD1_1 = 1.486613575122E-05"; cd12_card = "CD1_2 = 2.373662212645E-05"; cd21_card = "CD2_1 = 2.363997591790E-05"; cd22_card = "CD2_2 = -1.485285912782E-05"; } if (chip == 16) { cd11_card = "CD1_1 = 1.482235929435E-05"; cd12_card = "CD1_2 = 2.373403750698E-05"; cd21_card = "CD2_1 = 2.357839940013E-05"; cd22_card = "CD2_2 = -1.479552989005E-05"; } if (chip == 17) { cd11_card = "CD1_1 = 1.480298048702E-05"; cd12_card = "CD1_2 = 2.372386460655E-05"; cd21_card = "CD2_1 = 2.354054106341E-05"; cd22_card = "CD2_2 = -1.478343953883E-05"; } if (chip == 18) { cd11_card = "CD1_1 = 1.479332688673E-05"; cd12_card = "CD1_2 = 2.372739845340E-05"; cd21_card = "CD2_1 = 2.355246989508E-05"; cd22_card = "CD2_2 = -1.480296647578E-05"; } if (chip == 19) { cd11_card = "CD1_1 = 1.481176557493E-05"; cd12_card = "CD1_2 = 2.373576401162E-05"; cd21_card = "CD2_1 = 2.358932226099E-05"; cd22_card = "CD2_2 = -1.481249922856E-05"; } if (chip == 20) { cd11_card = "CD1_1 = 1.476899848422E-05"; cd12_card = "CD1_2 = 2.372049602314E-05"; cd21_card = "CD2_1 = 2.350902412408E-05"; cd22_card = "CD2_2 = -1.475631705174E-05"; } if (chip == 21) { cd11_card = "CD1_1 = 1.474866589659E-05"; cd12_card = "CD1_2 = 2.371075877642E-05"; cd21_card = "CD2_1 = 2.347150980654E-05"; cd22_card = "CD2_2 = -1.474852920014E-05"; } if (chip == 22) { cd11_card = "CD1_1 = 1.474244947610E-05"; cd12_card = "CD1_2 = 2.371605247177E-05"; cd21_card = "CD2_1 = 2.348366279118E-05"; cd22_card = "CD2_2 = -1.476632120557E-05"; } if (chip == 23) { cd11_card = "CD1_1 = 1.476081058159E-05"; cd12_card = "CD1_2 = 2.372464651027E-05"; cd21_card = "CD2_1 = 2.352366201702E-05"; cd22_card = "CD2_2 = -1.477616621816E-05"; } if (chip == 24) { cd11_card = "CD1_1 = 1.482490632217E-05"; cd12_card = "CD1_2 = 2.376345948269E-05"; cd21_card = "CD2_1 = 2.367364145233E-05"; cd22_card = "CD2_2 = -1.483692107467E-05"; } if (chip == 25) { cd11_card = "CD1_1 = 1.480842187087E-05"; cd12_card = "CD1_2 = 2.374972514562E-05"; cd21_card = "CD2_1 = 2.364037948810E-05"; cd22_card = "CD2_2 = -1.482872011652E-05"; } if (chip == 26) { cd11_card = "CD1_1 = 1.479868376454E-05"; cd12_card = "CD1_2 = 2.375868783686E-05"; cd21_card = "CD2_1 = 2.365930970970E-05"; cd22_card = "CD2_2 = -1.484174797878E-05"; } if (chip == 27) { cd11_card = "CD1_1 = 1.481338629988E-05"; cd12_card = "CD1_2 = 2.375896252243E-05"; cd21_card = "CD2_1 = 2.367629258239E-05"; cd22_card = "CD2_2 = -1.484820604855E-05"; } if (chip == 28) { cd11_card = "CD1_1 = 1.479771156173E-05"; cd12_card = "CD1_2 = 2.373660473100E-05"; cd21_card = "CD2_1 = 2.360461508886E-05"; cd22_card = "CD2_2 = -1.482336515784E-05"; } if (chip == 29) { cd11_card = "CD1_1 = 1.477160669198E-05"; cd12_card = "CD1_2 = 2.372752267865E-05"; cd21_card = "CD2_1 = 2.356955675634E-05"; cd22_card = "CD2_2 = -1.482064997568E-05"; } if (chip == 30) { cd11_card = "CD1_1 = 1.476300152064E-05"; cd12_card = "CD1_2 = 2.372729560742E-05"; cd21_card = "CD2_1 = 2.358270538891E-05"; cd22_card = "CD2_2 = -1.483080761587E-05"; } if (chip == 31) { cd11_card = "CD1_1 = 1.478245341966E-05"; cd12_card = "CD1_2 = 2.373768659001E-05"; cd21_card = "CD2_1 = 2.360701711570E-05"; cd22_card = "CD2_2 = -1.483381351690E-05"; } if (chip == 32) { cd11_card = "CD1_1 = 1.476071214974E-05"; cd12_card = "CD1_2 = 2.371434903027E-05"; cd21_card = "CD2_1 = 2.352579693693E-05"; cd22_card = "CD2_2 = -1.481092847704E-05"; } if (chip == 33) { cd11_card = "CD1_1 = 1.473804741719E-05"; cd12_card = "CD1_2 = 2.370013163467E-05"; cd21_card = "CD2_1 = 2.348240115738E-05"; cd22_card = "CD2_2 = -1.480444602931E-05"; } if (chip == 34) { cd11_card = "CD1_1 = 1.472321857718E-05"; cd12_card = "CD1_2 = 2.369680176884E-05"; cd21_card = "CD2_1 = 2.349400065458E-05"; cd22_card = "CD2_2 = -1.482086342218E-05"; } if (chip == 35) { cd11_card = "CD1_1 = 1.474940269291E-05"; cd12_card = "CD1_2 = 2.370719980710E-05"; cd21_card = "CD2_1 = 2.353372033718E-05"; cd22_card = "CD2_2 = -1.483043777321E-05"; } if (chip == 36) { cd11_card = "CD1_1 = 1.483266562799E-05"; cd12_card = "CD1_2 = 2.373474981797E-05"; cd21_card = "CD2_1 = 2.366690010902E-05"; cd22_card = "CD2_2 = -1.488938895944E-05"; } if (chip == 37) { cd11_card = "CD1_1 = 1.481706063147E-05"; cd12_card = "CD1_2 = 2.372187197666E-05"; cd21_card = "CD2_1 = 2.363968637556E-05"; cd22_card = "CD2_2 = -1.488787750055E-05"; } if (chip == 38) { cd11_card = "CD1_1 = 1.480442864514E-05"; cd12_card = "CD1_2 = 2.371637909172E-05"; cd21_card = "CD2_1 = 2.364701924466E-05"; cd22_card = "CD2_2 = -1.489374132529E-05"; } if (chip == 39) { cd11_card = "CD1_1 = 1.482328765591E-05"; cd12_card = "CD1_2 = 2.372643224791E-05"; cd21_card = "CD2_1 = 2.366930385093E-05"; cd22_card = "CD2_2 = -1.490091264662E-05"; } if (chip == 40) { cd11_card = "CD1_1 = 1.478409043333E-05"; cd12_card = "CD1_2 = 2.371827610991E-05"; cd21_card = "CD2_1 = 2.360276399711E-05"; cd22_card = "CD2_2 = -1.488004579365E-05"; } if (chip == 41) { cd11_card = "CD1_1 = 1.476844233775E-05"; cd12_card = "CD1_2 = 2.370633000480E-05"; cd21_card = "CD2_1 = 2.357446147361E-05"; cd22_card = "CD2_2 = -1.486253816396E-05"; } if (chip == 42) { cd11_card = "CD1_1 = 1.475583824840E-05"; cd12_card = "CD1_2 = 2.369774429479E-05"; cd21_card = "CD2_1 = 2.358530136273E-05"; cd22_card = "CD2_2 = -1.487411315137E-05"; } if (chip == 43) { cd11_card = "CD1_1 = 1.477268993505E-05"; cd12_card = "CD1_2 = 2.370487618427E-05"; cd21_card = "CD2_1 = 2.361235945727E-05"; cd22_card = "CD2_2 = -1.488510059522E-05"; } if (chip == 44) { cd11_card = "CD1_1 = 1.473979955025E-05"; cd12_card = "CD1_2 = 2.369486167104E-05"; cd21_card = "CD2_1 = 2.354838495889E-05"; cd22_card = "CD2_2 = -1.485818169386E-05"; } if (chip == 45) { cd11_card = "CD1_1 = 1.471233560797E-05"; cd12_card = "CD1_2 = 2.368244946054E-05"; cd21_card = "CD2_1 = 2.350467678519E-05"; cd22_card = "CD2_2 = -1.484601375457E-05"; } if (chip == 46) { cd11_card = "CD1_1 = 1.469545025106E-05"; cd12_card = "CD1_2 = 2.366460966794E-05"; cd21_card = "CD2_1 = 2.351267625062E-05"; cd22_card = "CD2_2 = -1.485458627996E-05"; } if (chip == 47) { cd11_card = "CD1_1 = 1.472638787796E-05"; cd12_card = "CD1_2 = 2.368447426808E-05"; cd21_card = "CD2_1 = 2.355104392732E-05"; cd22_card = "CD2_2 = -1.486633411282E-05"; } if (chip == 48) { cd11_card = "CD1_1 = 1.480265297552E-05"; cd12_card = "CD1_2 = 2.371613147278E-05"; cd21_card = "CD2_1 = 2.368134767313E-05"; cd22_card = "CD2_2 = -1.489496866550E-05"; } if (chip == 49) { cd11_card = "CD1_1 = 1.478155552655E-05"; cd12_card = "CD1_2 = 2.370347313527E-05"; cd21_card = "CD2_1 = 2.365697115492E-05"; cd22_card = "CD2_2 = -1.489785441643E-05"; } if (chip == 50) { cd11_card = "CD1_1 = 1.476994240617E-05"; cd12_card = "CD1_2 = 2.369086672177E-05"; cd21_card = "CD2_1 = 2.365742117490E-05"; cd22_card = "CD2_2 = -1.489378997731E-05"; } if (chip == 51) { cd11_card = "CD1_1 = 1.478492533105E-05"; cd12_card = "CD1_2 = 2.369055900304E-05"; cd21_card = "CD2_1 = 2.368652501783E-05"; cd22_card = "CD2_2 = -1.489526501757E-05"; } if (chip == 52) { cd11_card = "CD1_1 = 1.472595270652E-05"; cd12_card = "CD1_2 = 2.370078550371E-05"; cd21_card = "CD2_1 = 2.363383299694E-05"; cd22_card = "CD2_2 = -1.487286301875E-05"; } if (chip == 53) { cd11_card = "CD1_1 = 1.471547802237E-05"; cd12_card = "CD1_2 = 2.368522505315E-05"; cd21_card = "CD2_1 = 2.360387905790E-05"; cd22_card = "CD2_2 = -1.486062510217E-05"; } if (chip == 54) { cd11_card = "CD1_1 = 1.470190584653E-05"; cd12_card = "CD1_2 = 2.367817302493E-05"; cd21_card = "CD2_1 = 2.361064765619E-05"; cd22_card = "CD2_2 = -1.486269179826E-05"; } if (chip == 55) { cd11_card = "CD1_1 = 1.472319671133E-05"; cd12_card = "CD1_2 = 2.368552191383E-05"; cd21_card = "CD2_1 = 2.363984180456E-05"; cd22_card = "CD2_2 = -1.487300688192E-05"; } if (chip == 56) { cd11_card = "CD1_1 = 1.471419851256E-05"; cd12_card = "CD1_2 = 2.366675182697E-05"; cd21_card = "CD2_1 = 2.355729554680E-05"; cd22_card = "CD2_2 = -1.487664514811E-05"; } if (chip == 57) { cd11_card = "CD1_1 = 1.467365082641E-05"; cd12_card = "CD1_2 = 2.364986175970E-05"; cd21_card = "CD2_1 = 2.351806476181E-05"; cd22_card = "CD2_2 = -1.486822153269E-05"; } if (chip == 58) { cd11_card = "CD1_1 = 1.465859549935E-05"; cd12_card = "CD1_2 = 2.363040265601E-05"; cd21_card = "CD2_1 = 2.352625206882E-05"; cd22_card = "CD2_2 = -1.487553301948E-05"; } if (chip == 59) { cd11_card = "CD1_1 = 1.468979257510E-05"; cd12_card = "CD1_2 = 2.365012028980E-05"; cd21_card = "CD2_1 = 2.355435253574E-05"; cd22_card = "CD2_2 = -1.487992213247E-05"; } if (chip == 60) { cd11_card = "CD1_1 = 1.477385612500E-05"; cd12_card = "CD1_2 = 2.367300762014E-05"; cd21_card = "CD2_1 = 2.368195293828E-05"; cd22_card = "CD2_2 = -1.489190111272E-05"; } if (chip == 61) { cd11_card = "CD1_1 = 1.474612980621E-05"; cd12_card = "CD1_2 = 2.366677021901E-05"; cd21_card = "CD2_1 = 2.365736450435E-05"; cd22_card = "CD2_2 = -1.489060092810E-05"; } if (chip == 62) { cd11_card = "CD1_1 = 1.473964150124E-05"; cd12_card = "CD1_2 = 2.364014974408E-05"; cd21_card = "CD2_1 = 2.366313413875E-05"; cd22_card = "CD2_2 = -1.489646713107E-05"; } if (chip == 63) { cd11_card = "CD1_1 = 1.476122894456E-05"; cd12_card = "CD1_2 = 2.365815860275E-05"; cd21_card = "CD2_1 = 2.369404662738E-05"; cd22_card = "CD2_2 = -1.489493372553E-05"; } if (chip == 64) { cd11_card = "CD1_1 = 1.472869858669E-05"; cd12_card = "CD1_2 = 2.365251305151E-05"; cd21_card = "CD2_1 = 2.363363556931E-05"; cd22_card = "CD2_2 = -1.489349814040E-05"; } if (chip == 65) { cd11_card = "CD1_1 = 1.469835417334E-05"; cd12_card = "CD1_2 = 2.363529590844E-05"; cd21_card = "CD2_1 = 2.360275139313E-05"; cd22_card = "CD2_2 = -1.488993845526E-05"; } if (chip == 66) { cd11_card = "CD1_1 = 1.468254065174E-05"; cd12_card = "CD1_2 = 2.361133010803E-05"; cd21_card = "CD2_1 = 2.360460257948E-05"; cd22_card = "CD2_2 = -1.488945433594E-05"; } if (chip == 67) { cd11_card = "CD1_1 = 1.470394028686E-05"; cd12_card = "CD1_2 = 2.363340760562E-05"; cd21_card = "CD2_1 = 2.363343400795E-05"; cd22_card = "CD2_2 = -1.488666545689E-05"; } if (chip == 68) { cd11_card = "CD1_1 = 1.466161048713E-05"; cd12_card = "CD1_2 = 2.362368550307E-05"; cd21_card = "CD2_1 = 2.357517911142E-05"; cd22_card = "CD2_2 = -1.488370966528E-05"; } if (chip == 69) { cd11_card = "CD1_1 = 1.462759963111E-05"; cd12_card = "CD1_2 = 2.360365943094E-05"; cd21_card = "CD2_1 = 2.353580424207E-05"; cd22_card = "CD2_2 = -1.488123767256E-05"; } if (chip == 70) { cd11_card = "CD1_1 = 1.462216984283E-05"; cd12_card = "CD1_2 = 2.357819440271E-05"; cd21_card = "CD2_1 = 2.354540087739E-05"; cd22_card = "CD2_2 = -1.488328900453E-05"; } if (chip == 71) { cd11_card = "CD1_1 = 1.463710540116E-05"; cd12_card = "CD1_2 = 2.358986242328E-05"; cd21_card = "CD2_1 = 2.358209539028E-05"; cd22_card = "CD2_2 = -1.487236335446E-05"; } if (chip == 72) { cd11_card = "CD1_1 = 1.460167143932E-05"; cd12_card = "CD1_2 = 2.362113331512E-05"; cd21_card = "CD2_1 = 2.313226618970E-05"; cd22_card = "CD2_2 = -1.461953920748E-05"; } if (chip == 73) { cd11_card = "CD1_1 = 1.463049691728E-05"; cd12_card = "CD1_2 = 2.363587710052E-05"; cd21_card = "CD2_1 = 2.319256805457E-05"; cd22_card = "CD2_2 = -1.463738521476E-05"; } if (chip == 74) { cd11_card = "CD1_1 = 1.464835579722E-05"; cd12_card = "CD1_2 = 2.362485221778E-05"; cd21_card = "CD2_1 = 2.316946563998E-05"; cd22_card = "CD2_2 = -1.461103509427E-05"; } if (chip == 75) { cd11_card = "CD1_1 = 1.462160818792E-05"; cd12_card = "CD1_2 = 2.362044454073E-05"; cd21_card = "CD2_1 = 2.312230016690E-05"; cd22_card = "CD2_2 = -1.457968969807E-05"; } if (chip == 76) { cd11_card = "CD1_1 = 1.467158766951E-05"; cd12_card = "CD1_2 = 2.364793975825E-05"; cd21_card = "CD2_1 = 2.324792846003E-05"; cd22_card = "CD2_2 = -1.465793571435E-05"; } if (chip == 77) { cd11_card = "CD1_1 = 1.469756788593E-05"; cd12_card = "CD1_2 = 2.366201864040E-05"; cd21_card = "CD2_1 = 2.329843908245E-05"; cd22_card = "CD2_2 = -1.467202245220E-05"; } if (chip == 78) { cd11_card = "CD1_1 = 1.471167380870E-05"; cd12_card = "CD1_2 = 2.365627525284E-05"; cd21_card = "CD2_1 = 2.328363706462E-05"; cd22_card = "CD2_2 = -1.465166335715E-05"; } if (chip == 79) { cd11_card = "CD1_1 = 1.468569911282E-05"; cd12_card = "CD1_2 = 2.364459595314E-05"; cd21_card = "CD2_1 = 2.323250396221E-05"; cd22_card = "CD2_2 = -1.462883644723E-05"; } if (chip == 80) { cd11_card = "CD1_1 = 1.472197483927E-05"; cd12_card = "CD1_2 = 2.367811618709E-05"; cd21_card = "CD2_1 = 2.335250814351E-05"; cd22_card = "CD2_2 = -1.469135278831E-05"; } if (chip == 81) { cd11_card = "CD1_1 = 1.475627418500E-05"; cd12_card = "CD1_2 = 2.368523756432E-05"; cd21_card = "CD2_1 = 2.340381802311E-05"; cd22_card = "CD2_2 = -1.471132856216E-05"; } if (chip == 82) { cd11_card = "CD1_1 = 1.476470901503E-05"; cd12_card = "CD1_2 = 2.367849772818E-05"; cd21_card = "CD2_1 = 2.338060017038E-05"; cd22_card = "CD2_2 = -1.468103334798E-05"; } if (chip == 83) { cd11_card = "CD1_1 = 1.473647663282E-05"; cd12_card = "CD1_2 = 2.367022179581E-05"; cd21_card = "CD2_1 = 2.333680383602E-05"; cd22_card = "CD2_2 = -1.466669276512E-05"; } if (chip == 84) { cd11_card = "CD1_1 = 1.459583891284E-05"; cd12_card = "CD1_2 = 2.360468676475E-05"; cd21_card = "CD2_1 = 2.315136210467E-05"; cd22_card = "CD2_2 = -1.471182524167E-05"; } if (chip == 85) { cd11_card = "CD1_1 = 1.462802881900E-05"; cd12_card = "CD1_2 = 2.361573941147E-05"; cd21_card = "CD2_1 = 2.320216679244E-05"; cd22_card = "CD2_2 = -1.473120251213E-05"; } if (chip == 86) { cd11_card = "CD1_1 = 1.464145002837E-05"; cd12_card = "CD1_2 = 2.362334275379E-05"; cd21_card = "CD2_1 = 2.319131313402E-05"; cd22_card = "CD2_2 = -1.469912460557E-05"; } if (chip == 87) { cd11_card = "CD1_1 = 1.461209059743E-05"; cd12_card = "CD1_2 = 2.360317586365E-05"; cd21_card = "CD2_1 = 2.313445824869E-05"; cd22_card = "CD2_2 = -1.468736955297E-05"; } if (chip == 88) { cd11_card = "CD1_1 = 1.463437481455E-05"; cd12_card = "CD1_2 = 2.364952986949E-05"; cd21_card = "CD2_1 = 2.327685788792E-05"; cd22_card = "CD2_2 = -1.471731941297E-05"; } if (chip == 89) { cd11_card = "CD1_1 = 1.466768996471E-05"; cd12_card = "CD1_2 = 2.366421464210E-05"; cd21_card = "CD2_1 = 2.333461458667E-05"; cd22_card = "CD2_2 = -1.473193340030E-05"; } if (chip == 90) { cd11_card = "CD1_1 = 1.468231121721E-05"; cd12_card = "CD1_2 = 2.366551503785E-05"; cd21_card = "CD2_1 = 2.332012688928E-05"; cd22_card = "CD2_2 = -1.470382462918E-05"; } if (chip == 91) { cd11_card = "CD1_1 = 1.465185282869E-05"; cd12_card = "CD1_2 = 2.365754379977E-05"; cd21_card = "CD2_1 = 2.327205981300E-05"; cd22_card = "CD2_2 = -1.469446074606E-05"; } if (chip == 92) { cd11_card = "CD1_1 = 1.469171647638E-05"; cd12_card = "CD1_2 = 2.367871061499E-05"; cd21_card = "CD2_1 = 2.337904156740E-05"; cd22_card = "CD2_2 = -1.474686984779E-05"; } if (chip == 93) { cd11_card = "CD1_1 = 1.472119201091E-05"; cd12_card = "CD1_2 = 2.369107932912E-05"; cd21_card = "CD2_1 = 2.343173663283E-05"; cd22_card = "CD2_2 = -1.476324598712E-05"; } if (chip == 94) { cd11_card = "CD1_1 = 1.473300460551E-05"; cd12_card = "CD1_2 = 2.369390254272E-05"; cd21_card = "CD2_1 = 2.341481631303E-05"; cd22_card = "CD2_2 = -1.473265062469E-05"; } if (chip == 95) { cd11_card = "CD1_1 = 1.470735143725E-05"; cd12_card = "CD1_2 = 2.368044608439E-05"; cd21_card = "CD2_1 = 2.336644349089E-05"; cd22_card = "CD2_2 = -1.472299248630E-05"; } if (chip == 96) { cd11_card = "CD1_1 = 1.453006346410E-05"; cd12_card = "CD1_2 = 2.359887760184E-05"; cd21_card = "CD2_1 = 2.319625302791E-05"; cd22_card = "CD2_2 = -1.474321432668E-05"; } if (chip == 97) { cd11_card = "CD1_1 = 1.456844614546E-05"; cd12_card = "CD1_2 = 2.362361286477E-05"; cd21_card = "CD2_1 = 2.325262227103E-05"; cd22_card = "CD2_2 = -1.475820545534E-05"; } if (chip == 98) { cd11_card = "CD1_1 = 1.458144581497E-05"; cd12_card = "CD1_2 = 2.362707666313E-05"; cd21_card = "CD2_1 = 2.324160624225E-05"; cd22_card = "CD2_2 = -1.473312328235E-05"; } if (chip == 99) { cd11_card = "CD1_1 = 1.455019852321E-05"; cd12_card = "CD1_2 = 2.360971083963E-05"; cd21_card = "CD2_1 = 2.318569887528E-05"; cd22_card = "CD2_2 = -1.471748287733E-05"; } if (chip == 100) { cd11_card = "CD1_1 = 1.459466798577E-05"; cd12_card = "CD1_2 = 2.363835279112E-05"; cd21_card = "CD2_1 = 2.331021658366E-05"; cd22_card = "CD2_2 = -1.476555865262E-05"; } if (chip == 101) { cd11_card = "CD1_1 = 1.462889578684E-05"; cd12_card = "CD1_2 = 2.365455717479E-05"; cd21_card = "CD2_1 = 2.336691549319E-05"; cd22_card = "CD2_2 = -1.478140488864E-05"; } if (chip == 102) { cd11_card = "CD1_1 = 1.465097909728E-05"; cd12_card = "CD1_2 = 2.366082213840E-05"; cd21_card = "CD2_1 = 2.335481236225E-05"; cd22_card = "CD2_2 = -1.476240665323E-05"; } if (chip == 103) { cd11_card = "CD1_1 = 1.461348335527E-05"; cd12_card = "CD1_2 = 2.364297143664E-05"; cd21_card = "CD2_1 = 2.329920005989E-05"; cd22_card = "CD2_2 = -1.474878459863E-05"; } if (chip == 104) { cd11_card = "CD1_1 = 1.467529271185E-05"; cd12_card = "CD1_2 = 2.366308936433E-05"; cd21_card = "CD2_1 = 2.340746995323E-05"; cd22_card = "CD2_2 = -1.480404342127E-05"; } if (chip == 105) { cd11_card = "CD1_1 = 1.470429597672E-05"; cd12_card = "CD1_2 = 2.368083243432E-05"; cd21_card = "CD2_1 = 2.344817511825E-05"; cd22_card = "CD2_2 = -1.481562362596E-05"; } if (chip == 106) { cd11_card = "CD1_1 = 1.471378714922E-05"; cd12_card = "CD1_2 = 2.368480705449E-05"; cd21_card = "CD2_1 = 2.344528329644E-05"; cd22_card = "CD2_2 = -1.479264705253E-05"; } if (chip == 107) { cd11_card = "CD1_1 = 1.469039646450E-05"; cd12_card = "CD1_2 = 2.366622872944E-05"; cd21_card = "CD2_1 = 2.339280811626E-05"; cd22_card = "CD2_2 = -1.478679123857E-05"; } if (chip == 108) { cd11_card = "CD1_1 = 1.448456124781E-05"; cd12_card = "CD1_2 = 2.356870480893E-05"; cd21_card = "CD2_1 = 2.322672350865E-05"; cd22_card = "CD2_2 = -1.478620501272E-05"; } if (chip == 109) { cd11_card = "CD1_1 = 1.451624810953E-05"; cd12_card = "CD1_2 = 2.359201431979E-05"; cd21_card = "CD2_1 = 2.328267364599E-05"; cd22_card = "CD2_2 = -1.479878593260E-05"; } if (chip == 110) { cd11_card = "CD1_1 = 1.453821329730E-05"; cd12_card = "CD1_2 = 2.360556424422E-05"; cd21_card = "CD2_1 = 2.327366929494E-05"; cd22_card = "CD2_2 = -1.478074454091E-05"; } if (chip == 111) { cd11_card = "CD1_1 = 1.450171049883E-05"; cd12_card = "CD1_2 = 2.358652838198E-05"; cd21_card = "CD2_1 = 2.321395066344E-05"; cd22_card = "CD2_2 = -1.476656298734E-05"; } if (chip == 112) { cd11_card = "CD1_1 = 1.456535647000E-05"; cd12_card = "CD1_2 = 2.360732791496E-05"; cd21_card = "CD2_1 = 2.332848426836E-05"; cd22_card = "CD2_2 = -1.481636744939E-05"; } if (chip == 113) { cd11_card = "CD1_1 = 1.459539293765E-05"; cd12_card = "CD1_2 = 2.362392642047E-05"; cd21_card = "CD2_1 = 2.337757042428E-05"; cd22_card = "CD2_2 = -1.482275905507E-05"; } if (chip == 114) { cd11_card = "CD1_1 = 1.461737683576E-05"; cd12_card = "CD1_2 = 2.363458505163E-05"; cd21_card = "CD2_1 = 2.336816423325E-05"; cd22_card = "CD2_2 = -1.481251124587E-05"; } if (chip == 115) { cd11_card = "CD1_1 = 1.458199845963E-05"; cd12_card = "CD1_2 = 2.361519968791E-05"; cd21_card = "CD2_1 = 2.331733143272E-05"; cd22_card = "CD2_2 = -1.479661337260E-05"; } if (chip == 116) { cd11_card = "CD1_1 = 1.463924696974E-05"; cd12_card = "CD1_2 = 2.364079310047E-05"; cd21_card = "CD2_1 = 2.343309376212E-05"; cd22_card = "CD2_2 = -1.483434678051E-05"; } if (chip == 117) { cd11_card = "CD1_1 = 1.465806282379E-05"; cd12_card = "CD1_2 = 2.365727606928E-05"; cd21_card = "CD2_1 = 2.347474552836E-05"; cd22_card = "CD2_2 = -1.484455269629E-05"; } if (chip == 118) { cd11_card = "CD1_1 = 1.467449621510E-05"; cd12_card = "CD1_2 = 2.366915437751E-05"; cd21_card = "CD2_1 = 2.346164367254E-05"; cd22_card = "CD2_2 = -1.483091767604E-05"; } if (chip == 119) { cd11_card = "CD1_1 = 1.464607810124E-05"; cd12_card = "CD1_2 = 2.365246911953E-05"; cd21_card = "CD2_1 = 2.341976251802E-05"; cd22_card = "CD2_2 = -1.482166603044E-05"; } if (chip == 120) { cd11_card = "CD1_1 = 1.444335830848E-05"; cd12_card = "CD1_2 = 2.352213652959E-05"; cd21_card = "CD2_1 = 2.324912548309E-05"; cd22_card = "CD2_2 = -1.482173634290E-05"; } if (chip == 121) { cd11_card = "CD1_1 = 1.447437555213E-05"; cd12_card = "CD1_2 = 2.354212082960E-05"; cd21_card = "CD2_1 = 2.329125788986E-05"; cd22_card = "CD2_2 = -1.483333581566E-05"; } if (chip == 122) { cd11_card = "CD1_1 = 1.450406249551E-05"; cd12_card = "CD1_2 = 2.357194888358E-05"; cd21_card = "CD2_1 = 2.328733246547E-05"; cd22_card = "CD2_2 = -1.482635384992E-05"; } if (chip == 123) { cd11_card = "CD1_1 = 1.446887435936E-05"; cd12_card = "CD1_2 = 2.355132541950E-05"; cd21_card = "CD2_1 = 2.323652214511E-05"; cd22_card = "CD2_2 = -1.481003758771E-05"; } if (chip == 124) { cd11_card = "CD1_1 = 1.452207857252E-05"; cd12_card = "CD1_2 = 2.356246000914E-05"; cd21_card = "CD2_1 = 2.334874579102E-05"; cd22_card = "CD2_2 = -1.484438600811E-05"; } if (chip == 125) { cd11_card = "CD1_1 = 1.455472502248E-05"; cd12_card = "CD1_2 = 2.358120746189E-05"; cd21_card = "CD2_1 = 2.339514205919E-05"; cd22_card = "CD2_2 = -1.484757631193E-05"; } if (chip == 126) { cd11_card = "CD1_1 = 1.457348396577E-05"; cd12_card = "CD1_2 = 2.360195486445E-05"; cd21_card = "CD2_1 = 2.339133293538E-05"; cd22_card = "CD2_2 = -1.483895066403E-05"; } if (chip == 127) { cd11_card = "CD1_1 = 1.454008195769E-05"; cd12_card = "CD1_2 = 2.358410900742E-05"; cd21_card = "CD2_1 = 2.334275603655E-05"; cd22_card = "CD2_2 = -1.483080248943E-05"; } if (chip == 128) { cd11_card = "CD1_1 = 1.458901562113E-05"; cd12_card = "CD1_2 = 2.359178549552E-05"; cd21_card = "CD2_1 = 2.344306428878E-05"; cd22_card = "CD2_2 = -1.486337104280E-05"; } if (chip == 129) { cd11_card = "CD1_1 = 1.462175986402E-05"; cd12_card = "CD1_2 = 2.361733887704E-05"; cd21_card = "CD2_1 = 2.348607546703E-05"; cd22_card = "CD2_2 = -1.486513424075E-05"; } if (chip == 130) { cd11_card = "CD1_1 = 1.463529593407E-05"; cd12_card = "CD1_2 = 2.364178867895E-05"; cd21_card = "CD2_1 = 2.348601948871E-05"; cd22_card = "CD2_2 = -1.485575720965E-05"; } if (chip == 131) { cd11_card = "CD1_1 = 1.460986224421E-05"; cd12_card = "CD1_2 = 2.361203114887E-05"; cd21_card = "CD2_1 = 2.343949597677E-05"; cd22_card = "CD2_2 = -1.485566411533E-05"; } if (chip == 132) { cd11_card = "CD1_1 = 1.439902433134E-05"; cd12_card = "CD1_2 = 2.345629610913E-05"; cd21_card = "CD2_1 = 2.325740535484E-05"; cd22_card = "CD2_2 = -1.485596236971E-05"; } if (chip == 133) { cd11_card = "CD1_1 = 1.443298642922E-05"; cd12_card = "CD1_2 = 2.347635387290E-05"; cd21_card = "CD2_1 = 2.330621667414E-05"; cd22_card = "CD2_2 = -1.486033282241E-05"; } if (chip == 134) { cd11_card = "CD1_1 = 1.445781151314E-05"; cd12_card = "CD1_2 = 2.350565643289E-05"; cd21_card = "CD2_1 = 2.330167260556E-05"; cd22_card = "CD2_2 = -1.484873085712E-05"; } if (chip == 135) { cd11_card = "CD1_1 = 1.441809713258E-05"; cd12_card = "CD1_2 = 2.348311689798E-05"; cd21_card = "CD2_1 = 2.325596352129E-05"; cd22_card = "CD2_2 = -1.484304513657E-05"; } if (chip == 136) { cd11_card = "CD1_1 = 1.447546727940E-05"; cd12_card = "CD1_2 = 2.350013156095E-05"; cd21_card = "CD2_1 = 2.336394669080E-05"; cd22_card = "CD2_2 = -1.486967033189E-05"; } if (chip == 137) { cd11_card = "CD1_1 = 1.450311305828E-05"; cd12_card = "CD1_2 = 2.352760541293E-05"; cd21_card = "CD2_1 = 2.341159788465E-05"; cd22_card = "CD2_2 = -1.487196208818E-05"; } if (chip == 138) { cd11_card = "CD1_1 = 1.453072035878E-05"; cd12_card = "CD1_2 = 2.354794773212E-05"; cd21_card = "CD2_1 = 2.339943611848E-05"; cd22_card = "CD2_2 = -1.487102562063E-05"; } if (chip == 139) { cd11_card = "CD1_1 = 1.450500310877E-05"; cd12_card = "CD1_2 = 2.352971109315E-05"; cd21_card = "CD2_1 = 2.335309015628E-05"; cd22_card = "CD2_2 = -1.486063065637E-05"; } if (chip == 140) { cd11_card = "CD1_1 = 1.454752168874E-05"; cd12_card = "CD1_2 = 2.354646194800E-05"; cd21_card = "CD2_1 = 2.345742103297E-05"; cd22_card = "CD2_2 = -1.487783136191E-05"; } if (chip == 141) { cd11_card = "CD1_1 = 1.458005675672E-05"; cd12_card = "CD1_2 = 2.356162882797E-05"; cd21_card = "CD2_1 = 2.350611783105E-05"; cd22_card = "CD2_2 = -1.487779943882E-05"; } if (chip == 142) { cd11_card = "CD1_1 = 1.459564236634E-05"; cd12_card = "CD1_2 = 2.359293940495E-05"; cd21_card = "CD2_1 = 2.349497570450E-05"; cd22_card = "CD2_2 = -1.487429906181E-05"; } if (chip == 143) { cd11_card = "CD1_1 = 1.456847619401E-05"; cd12_card = "CD1_2 = 2.356804605434E-05"; cd21_card = "CD2_1 = 2.346290171106E-05"; cd22_card = "CD2_2 = -1.487358881329E-05"; } individualFixDone = true; } if (instData.name == "FourStar@LCO") { // FourStar has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTANGLE", positionAngle)) { emit messageAvailable(name + " : Could not find ROTANGLE keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = -1.*instData.pixscale / 3600.; cd12 = 0.0; cd21 = 0.0; cd22 = instData.pixscale / 3600.; rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "NISP_LE1@EUCLID" || instData.name == "NISP_ERO@EUCLID") { // NISP has no CD matrix in the header if (chip == 0) { cd11_card = "CD1_1 = -5.886422865036E-05"; cd12_card = "CD1_2 = -5.743639424946E-05"; cd21_card = "CD2_1 = 5.788921377473E-05"; cd22_card = "CD2_2 = -5.887302780080E-05"; } if (chip == 1) { cd11_card = "CD1_1 = -5.914966392140E-05"; cd12_card = "CD1_2 = -5.759149759629E-05"; cd21_card = "CD2_1 = 5.776736334384E-05"; cd22_card = "CD2_2 = -5.913068518893E-05"; } if (chip == 2) { cd11_card = "CD1_1 = 5.935736419562E-05"; cd12_card = "CD1_2 = 5.752797005926E-05"; cd21_card = "CD2_1 = -5.756251582627E-05"; cd22_card = "CD2_2 = 5.920571505390E-05"; } if (chip == 3) { cd11_card = "CD1_1 = 5.951153395316E-05"; cd12_card = "CD1_2 = 5.725374562834E-05"; cd21_card = "CD2_1 = -5.728508415452E-05"; cd22_card = "CD2_2 = 5.906814963917E-05"; } if (chip == 4) { cd11_card = "CD1_1 = -5.922555543981E-05"; cd12_card = "CD1_2 = -5.763869498892E-05"; cd21_card = "CD2_1 = 5.797721341433E-05"; cd22_card = "CD2_2 = -5.894532691269E-05"; } if (chip == 5) { cd11_card = "CD1_1 = -5.941123531160E-05"; cd12_card = "CD1_2 = -5.773464398630E-05"; cd21_card = "CD2_1 = 5.792775654037E-05"; cd22_card = "CD2_2 = -5.924661198980E-05"; } if (chip == 6) { cd11_card = "CD1_1 = 5.951571922974E-05"; cd12_card = "CD1_2 = 5.766240197977E-05"; cd21_card = "CD2_1 = -5.782596634915E-05"; cd22_card = "CD2_2 = 5.932992255598E-05"; } if (chip == 7) { cd11_card = "CD1_1 = 5.955186774092E-05"; cd12_card = "CD1_2 = 5.735834523100E-05"; cd21_card = "CD2_1 = -5.763875899209E-05"; cd22_card = "CD2_2 = 5.919899220225E-05"; } if (chip == 8) { cd11_card = "CD1_1 = -5.932573993181E-05"; cd12_card = "CD1_2 = -5.785754646444E-05"; cd21_card = "CD2_1 = 5.796015804982E-05"; cd22_card = "CD2_2 = -5.887891455138E-05"; } if (chip == 9) { cd11_card = "CD1_1 = -5.951467201240E-05"; cd12_card = "CD1_2 = -5.782821161523E-05"; cd21_card = "CD2_1 = 5.791087236789E-05"; cd22_card = "CD2_2 = -5.932487090136E-05"; } if (chip == 10) { cd11_card = "CD1_1 = 5.957632227151E-05"; cd12_card = "CD1_2 = 5.763989746900E-05"; cd21_card = "CD2_1 = -5.783209380794E-05"; cd22_card = "CD2_2 = 5.950631652612E-05"; } if (chip == 11) { cd11_card = "CD1_1 = 5.949725970344E-05"; cd12_card = "CD1_2 = 5.734021781623E-05"; cd21_card = "CD2_1 = -5.777658591941E-05"; cd22_card = "CD2_2 = 5.938342280809E-05"; } if (chip == 12) { cd11_card = "CD1_1 = -5.938955059245E-05"; cd12_card = "CD1_2 = -5.784928501429E-05"; cd21_card = "CD2_1 = 5.761353212784E-05"; cd22_card = "CD2_2 = -5.892635069251E-05"; } if (chip == 13) { cd11_card = "CD1_1 = -5.938694355029E-05"; cd12_card = "CD1_2 = -5.789368665162E-05"; cd21_card = "CD2_1 = 5.776226919165E-05"; cd22_card = "CD2_2 = -5.930369256560E-05"; } if (chip == 14) { cd11_card = "CD1_1 = 5.934932476071E-05"; cd12_card = "CD1_2 = 5.771632641403E-05"; cd21_card = "CD2_1 = -5.780014521852E-05"; cd22_card = "CD2_2 = 5.947635061551E-05"; } if (chip == 15) { cd11_card = "CD1_1 = 5.935256738574E-05"; cd12_card = "CD1_2 = 5.724101286139E-05"; cd21_card = "CD2_1 = -5.768322818501E-05"; cd22_card = "CD2_2 = 5.956870310124E-05"; } individualFixDone = true; } if (instData.name.contains("IMACS_F2")) { // IMACS has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTATORE", positionAngle)) { emit messageAvailable(name + " : Could not find ROTANGLE keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } if (chip<=3) { cd11 = 0.; cd12 = -instData.pixscale / 3600.; cd21 = instData.pixscale / 3600.; cd22 = 0.; } if (chip>=4) { cd11 = 0.; cd12 = instData.pixscale / 3600.; cd21 = -instData.pixscale / 3600.; cd22 = 0.; } cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name.contains("IMACS_F4")) { // IMACS has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTATORE", positionAngle)) { emit messageAvailable(name + " : Could not find ROTANGLE keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = instData.pixscale / 3600.; cd12 = 0.; cd21 = 0.; cd22 = -instData.pixscale / 3600.; // Chips 1-4 are rotated by 180 degrees if (chip >= 4) rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); else rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle+180.); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "LIRIS@WHT" || instData.name == "LIRIS_POL@WHT") { // LIRIS has no CD matrix in the header if (!searchKeyValue(QStringList() << "ROTSKYPA", positionAngle)) { emit messageAvailable(name + " : Could not find ROTSKYPA keyword, set to zero! CD matrix might have wrong orientation.", "warning"); emit warning(); positionAngle = 0.0; } cd11 = -1.*instData.pixscale / 3600.; cd12 = 0.0; cd21 = 0.0; cd22 = instData.pixscale / 3600.; rotateCDmatrix(cd11, cd12, cd21, cd22, positionAngle); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "SUSI1@NTT") { cd11 = -3.611e-5; cd12 = 0.; cd21 = 0.; cd22 = 3.611e-5; cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instNameFromData == "GROND_OPT@MPGESO") { // GROND optical data has both the NIR and OPT CD matrices in the header. // With the current scheme, the NIR matrix in the HDU gets picked over // OPT matrix in the extension searchKeyValue(QStringList() << "CD1_1", cd11); searchKeyValue(QStringList() << "CD1_2", cd12); searchKeyValue(QStringList() << "CD2_1", cd21); searchKeyValue(QStringList() << "CD2_2", cd22); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instNameFromData == "GROND_NIR@MPGESO") { // just double tapping searchKeyValue(QStringList() << "J_CD1_1", cd11); searchKeyValue(QStringList() << "J_CD1_2", cd12); searchKeyValue(QStringList() << "J_CD2_1", cd21); searchKeyValue(QStringList() << "J_CD2_2", cd22); cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "PFC_old@WHT") { cd11 = 6.55e-5; cd12 = 5.0e-7; cd21 = 5.0e-7; cd22 = -6.55e-5; cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "PISCO@LCO") { cd11 = -instData.pixscale / 3600.; cd12 = 0.; cd21 = 0.; cd22 = -instData.pixscale / 3600.; // headers appear unreliable (pixel scale wrong by a factor of two) /* searchKeyValue(QStringList() << "CD1_1", cd11); searchKeyValue(QStringList() << "CD1_2", cd12); searchKeyValue(QStringList() << "CD2_1", cd21); searchKeyValue(QStringList() << "CD2_2", cd22); // readout amplifiers are flipped, depending on chip if (chip == 1 || chip == 2) {cd11 *= -1.; cd21 *= -1.;} if (chip == 4 || chip == 7) {cd12 *= -1.; cd22 *= -1.;} if (chip == 5 || chip == 6) {cd11 *= -1.; cd21 *= -1.; cd12 *= -1.; cd22 *= -1.;} */ cd11_card = "CD1_1 = "+QString::number(cd11, 'g', 6); cd12_card = "CD1_2 = "+QString::number(cd12, 'g', 6); cd21_card = "CD2_1 = "+QString::number(cd21, 'g', 6); cd22_card = "CD2_2 = "+QString::number(cd22, 'g', 6); individualFixDone = true; } if (instData.name == "90Prime@BOK2.3m") { // CD matrix appears to assume a plate scale of 1.0 instead of 0.452 arcsec/pixel. It is also rotated by 90 degrees and flipped. // We fix it manually, and hope that it doesn't change. cd11_card = "CD1_1 = 0."; cd22_card = "CD2_2 = 0."; if (chip == 0 || chip == 4 || chip == 11 || chip == 15) { cd12_card = "CD1_2 = 1.258E-04 "; cd21_card = "CD2_1 = 1.258E-04 "; } if (chip == 1 || chip == 5 || chip == 10 || chip == 14) { cd12_card = "CD1_2 = 1.258E-04 "; cd21_card = "CD2_1 = -1.258E-04 "; } if (chip == 2 || chip == 6 || chip == 9 || chip == 13) { cd12_card = "CD1_2 = -1.258E-04 "; cd21_card = "CD2_1 = 1.258E-04 "; } if (chip == 3 || chip == 7 || chip == 8 || chip == 12) { cd12_card = "CD1_2 = -1.258E-04 "; cd21_card = "CD2_1 = -1.258E-04 "; } individualFixDone = true; } if (individualFixDone) { cd11_card.resize(80, ' '); cd12_card.resize(80, ' '); cd21_card.resize(80, ' '); cd22_card.resize(80, ' '); headerWCS.append(cd11_card); headerWCS.append(cd12_card); headerWCS.append(cd21_card); headerWCS.append(cd22_card); headerTHELI.append(headerWCS); } return individualFixDone; } // Build the EXPTIME keyword void Splitter::buildTheliHeaderEXPTIME() { if (!successProcessing) return; // List of instruments that have separate DITs and NDITs QStringList nditInstruments = {"GSAOI@GEMINI", "GSAOI_CHIP1@GEMINI", "GSAOI_CHIP2@GEMINI", "GSAOI_CHIP3@GEMINI", "GSAOI_CHIP4@GEMINI", "HAWKI@VLT", "INGRID@WHT", "IRCS_HIGHRES@SUBARU", "IRCS_LOWRES@SUBARU", "ISAAC@VLT", "ISPI@CTIO", "LIRIS@WHT", "LIRIS_POL@WHT", "MOIRCS@SUBARU", "MOSFIRE@KECK", "NEWFIRM@CTIO", "NICS@TNG", "NIRC2@KECK", "NIRI@GEMINI", "PISCES@LBT", "SOFI@NTT", "VIRCAM@VISTA"}; // The following instruments also have DITs and NDITs, but they are coadded instead of coaveraged and thus can be treated normally: // MOIRCS QString exptimeKey; // Instruments for which we don't have to do anything special if (!nditInstruments.contains(instData.name)) { bool keyFound = searchKey("EXPTIME", headerDictionary.value("EXPTIME"), headerTHELI); if (!keyFound) { exptimeKey = "EXPTIME = 1.0"; exptimeKey.resize(80, ' '); headerTHELI.append(exptimeKey); emit messageAvailable(fileName + " : Could not determine keyword: EXPTIME, set to 1.0", "warning"); emit warning(); } return; } // Instruments (see list above) for which we have to determine the true total EXPTIME keyword, and rescale the data. // In THELI, EXPTIME always represents the total effective integration time. If images are averaged from several coadds, // they also need to be rescaled. float dit = -1.0; float ndit = -1.0; bool foundDIT = searchKeyValue(headerDictionary.value("DIT"), dit); bool foundNDIT = searchKeyValue(headerDictionary.value("NDIT"), ndit); // default values if failed if (!foundDIT) { emit messageAvailable(fileName + " : Could not determine keyword: DIT, set to 1.0", "warning"); dit = 1.0; } if (!foundNDIT) { emit messageAvailable(fileName + " : Could not determine keyword: NDIT, set to 1", "warning"); ndit = 1.0; } if (!foundDIT || !foundNDIT) { emit messageAvailable("This is a serious issue with data from "+instData.name+" .<br>The true exposure time is unknown."+ "You can continue, but a correct calibration of the stacked image is not guaranteed.", "warning"); emit warning(); } exptimeValue = dit*ndit; exptimeKey = "EXPTIME = "+QString::number(exptimeValue, 'f', 5); QString ditKey = "DIT = "+QString::number(dit, 'f', 5); QString nditKey = "NDIT = "+QString::number(int(ndit)); exptimeKey.resize(80, ' '); ditKey.resize(80, ' '); nditKey.resize(80, ' '); headerTHELI.append(exptimeKey); headerTHELI.append(ditKey); headerTHELI.append(nditKey); // Rescale the pixels. NDIT is actually an integer and must be >= 1. // The following cameras DO NOT average the NDITs but add them directly, hence we must not rescale them. // TODO: this list must be verified! QStringList directCoaddition = {"IRCS_HIGHRES@SUBARU", "IRCS_LOWRES@SUBARU", "ISPI@CTIO", "MOSFIRE@KECK", "NIRC2@KECK", "NIRI@GEMINI", "PISCES@LBT", "VIRCAM@VISTA"}; if (!directCoaddition.contains(instData.name)) { if (ndit > 1.) { for (auto &pixel : dataCurrent) pixel *= ndit; } } } // Build the DATE-OBS keyword void Splitter::buildTheliHeaderDATEOBS() { if (!successProcessing) return; if (individualFixDATEOBS()) return; bool found = false; // Loop over all possible dateobs keywords, and break once we found one that is valid. // This is different from the general strategy to go over all possible keyword variants and take the first one that exists for (auto &keyword : headerDictionary.value("DATE-OBS")) { dateObsValue = ""; searchKeyValue(QStringList() << keyword, dateObsValue); if (!dateObsValue.isEmpty() && checkFormatDATEOBS()) { found = true; break; } } // bool keyFound = searchKey("DATE-OBS", headerDictionary.value("DATE-OBS"), headerTHELI); // if (keyFound && checkFormatDATEOBS()) return; // Fallback: Try and reconstruct DATE-OBS keyword from other keywords // DATE-OBS has not been appended yet by searchKey() child function if format is wrong if (!found) { QString dateValue; QString timeValue; bool foundDATE = searchKeyValue(headerDictionary.value("DATE"), dateValue); bool foundTIME = searchKeyValue(headerDictionary.value("TIME"), timeValue); if (foundDATE && foundTIME) { if (timeValue.contains(" ")) timeValue.replace(" ",":"); // E.g. SITe_SWOPE@LCO has a time stamp without colons if (dateValue.contains("-") && timeValue.contains(":")) { dateObsValue = dateValue+"T"+timeValue; } else { // Construct a unique dummy DATE-OBS keyword, incremented by 0.1 seconds. #pragma omp critical { *dateObsIncrementor += 0.1; QString timeStamp = decimalSecondsToHms(*dateObsIncrementor); dateObsValue = "2020-01-01T"+timeStamp; } emit messageAvailable(fileName + " : Could not determine keyword: DATE-OBS, set to "+dateObsValue, "warning"); emit warning(); // dateObsValue = "2020-01-01T00:00:00.000"; // dateObsValid = false; } } } QString card = "DATE-OBS= '"+dateObsValue+"'"; card.resize(80, ' '); headerTHELI.append(card); } bool Splitter::individualFixDATEOBS() { bool individualFixDone = false; if (instData.name == "WHIRC@WIYN") { double mjdValue = 0; bool foundMJDOBS = searchKeyValue(headerDictionary.value("MJD-OBS"), mjdValue); // DATE-OBS has the start time of a sequence if (foundMJDOBS) { dateObsValue = mjdobsToDATEOBS(mjdValue); individualFixDone = true; } } if (instData.name == "PISCO@LCO") { // wrong order of DATE and DATEOBS keyword QString dateValue; QString timeValue; bool foundDATE = searchKeyValue(QStringList() << "DATEOBS", dateValue); bool foundTIME = searchKeyValue(QStringList() << "TELUT", timeValue); if (foundDATE && foundTIME) { if (dateValue.contains("-") && timeValue.contains(":")) { dateObsValue = dateValue+"T"+timeValue; } else { // Construct a unique dummy DATE-OBS keyword, incremented by 0.1 seconds. #pragma omp critical { *dateObsIncrementor += 0.1; QString timeStamp = decimalSecondsToHms(*dateObsIncrementor); dateObsValue = "2020-01-01T"+timeStamp; } emit messageAvailable(fileName + " : Could not determine keyword: DATE-OBS, set to "+dateObsValue, "warning"); emit warning(); } } individualFixDone = true; } if (individualFixDone) { QString card = "DATE-OBS= '"+dateObsValue+"'"; card.resize(80, ' '); headerTHELI.append(card); } return individualFixDone; } // Build the GAIN keyword void Splitter::buildTheliHeaderGAIN(int chip) { if (!successProcessing) return; // Exceptions. Return if successful. if (individualFixGAIN(chip)) return; // normal cases chipGain = 1.0; if (!searchKeyValue(headerDictionary.value("GAIN"), chipGain)) { // if (instData.name != "GROND_NIR@MPGESO") { // GROND: gain determined in writeImageIndividual() if (instNameFromData != "GROND_NIR@MPGESO") { // GROND: gain determined in writeImageIndividual() emit messageAvailable(fileName + " : Could not determine keyword: GAIN, set to 1.0.", "warning"); emit warning(); } chipGain = 1.0; } // Consistency checks if (chipGain < 0.02 || chipGain > 30.) { emit messageAvailable(fileName + " : GAIN keyword outside plausible range (0.02-30 e-/ADU): " + QString::number(chipGain)+", set to 1.0.", "warning"); emit warning(); chipGain = 1.0; } QString card1 = "GAINORIG= "+QString::number(chipGain, 'f', 6) + " / Original gain in the raw data for this image"; QString card2 = "GAIN = 1.0 / ADUs were converted to e- in this image using GAINORIG"; card1.resize(80, ' '); card2.resize(80, ' '); headerTHELI.append(card1); headerTHELI.append(card2); gainForSaturation = chipGain; gain[chip] = chipGain; // used to convert the pixel data from ADU to electrons } bool Splitter::individualFixGAIN(int chip) { if (!successProcessing) return false; bool individualFixDone = false; chipGain = 1.0; if (instData.name == "HAWKI@VLT") { // https://www.eso.org/sci/facilities/paranal/instruments/hawki/inst.html if (chip == 0) chipGain = 1.705; if (chip == 1) chipGain = 1.870; if (chip == 2) chipGain = 1.735; if (chip == 3) chipGain = 2.110; individualFixDone = true; } if (instData.name == "SOFI@NTT") { // https://www.eso.org/sci/facilities/lasilla/instruments/sofi/inst/setup/Detector_characteristic.html chipGain = 5.3; individualFixDone = true; } if (instData.name == "Lukas@IAS") { chipGain = 0.34; individualFixDone = true; } if (instData.name == "NISP_LE1@EUCLID" || instData.name == "NISP_ERO@EUCLID") { chipGain = 2.0; individualFixDone = true; } if (instData.name == "NEWFIRM@KPNO_4m") { // https://www.noao.edu/ets/newfirm/documents/ORION_SCA_lab_tests_final.pdf chipGain = 7.6; // same for all 4 chips individualFixDone = true; } if (instData.name == "HDI@KPNO_0.9m") { // https://www.noao.edu/0.9m/observe/hdi/hdi_manual.html chipGain = 1.3; individualFixDone = true; } if (instData.name == "INOLA@INO") { // https://www.sbig.de/stf-8300/stf-8300-techdat.pdf chipGain = 0.37; individualFixDone = true; } if (instData.name == "WHIRC@WIYN") { // https://www.noao.edu/kpno/manuals/whirc/whirc.user.html chipGain = 3.4; individualFixDone = true; } else if (instData.name == "NIRI@GEMINI") { // https://www.gemini.edu/sciops/instruments/niri/imaging/detector-array chipGain = 12.3; // No gain keyword in FITS header individualFixDone = true; } /* * UPDATE: The gain in the LIRIS headers follows the actual gain setting, might not be accurate to the decimal, though. * (email from R. Karjalainen, ING, 2019-11-07) else if (instData.name == "LIRIS@WHT" || instData.name == "LIRIS_POL@WHT") { // http://www.ing.iac.es/astronomy/instruments/liris/detector.html chipGain = 3.6; // Wrong gain in header individualFixDone = true; } */ else if (instData.name == "MOIRCS_200807-201505@SUBARU") { // https://www.naoj.org/Observing/Instruments/MOIRCS/OLD/inst_detector_oldMOIRCS.html if (chip == 0) chipGain = 3.50; // Wrong in headers between August 2008 and April 2010 if (chip == 1) chipGain = 3.30; individualFixDone = true; } else if (instData.name.contains("WFI") && instData.name.contains("MPGESO")) { // http://www.ls.eso.org:8081/sci/facilities/lasilla/sciops/CCDs/WFI/qc_suite/plots/plot1.png if (chip == 0) chipGain = 1.99; // Does not have GAIN keywords for all detectors if (chip == 1) chipGain = 2.02; if (chip == 2) chipGain = 2.29; if (chip == 3) chipGain = 2.68; if (chip == 4) chipGain = 2.24; if (chip == 5) chipGain = 2.25; if (chip == 6) chipGain = 2.16; if (chip == 7) chipGain = 2.03; individualFixDone = true; } else if (instData.name == "DEIMOS_1AMP@KECK") { if (chip == 0) chipGain = 1.206; if (chip == 1) chipGain = 1.200; if (chip == 2) chipGain = 1.167; if (chip == 3) chipGain = 1.217; individualFixDone = true; } // multi-amp cameras where the gain is NOT available in the header else if (instData.name == "DEIMOS_2AMP@KECK") { // https://www2.keck.hawaii.edu/inst/obsdata/inst/deimos/www/detector_data/deimos_detector_data.html if (chip == 0) chipGain = 1.206; if (chip == 1) chipGain = 1.221; if (chip == 2) chipGain = 1.200; if (chip == 3) chipGain = 1.188; if (chip == 4) chipGain = 1.167; if (chip == 5) chipGain = 1.250; if (chip == 6) chipGain = 1.217; if (chip == 7) chipGain = 1.228; chipGain = harmonicGain(multiportGains); individualFixDone = true; } else if (instData.name == "VIRCAM@VISTA") { // https://www.eso.org/sci/facilities/paranal/instruments/vircam/doc/VIS-MAN-ESO-06000-0002_v108.pdf if (chip == 0) chipGain = 3.7; if (chip == 1) chipGain = 4.2; if (chip == 2) chipGain = 4.0; if (chip == 3) chipGain = 4.2; if (chip == 4) chipGain = 4.2; if (chip == 5) chipGain = 4.1; if (chip == 6) chipGain = 3.9; if (chip == 7) chipGain = 4.2; if (chip == 8) chipGain = 4.6; if (chip == 9) chipGain = 4.0; if (chip == 10) chipGain = 4.6; if (chip == 11) chipGain = 4.0; if (chip == 12) chipGain = 5.8; if (chip == 13) chipGain = 4.8; if (chip == 14) chipGain = 4.0; if (chip == 15) chipGain = 5.0; chipGain = harmonicGain(multiportGains); individualFixDone = true; } // multi-amp cameras where the gain is available in the header else if (instData.name == "SuprimeCam_200808-201705@SUBARU" || instData.name == "HSC@SUBARU" || instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM") || instData.name.contains("SAMI") // have not added yet 1x1 confog || instData.name.contains("SOI@SOAR") || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "MOSAIC-III_4@KPNO_4m" || instData.name == "PISCO@LCO" ) { chipGain = harmonicGain(multiportGains); individualFixDone = true; } else if (instData.name == "FORS1_199904-200703@VLT" || instData.name == "FORS2_200004-200203@VLT") { // 1-port read mode or 4-port read mode? numReadoutChannels = 0; if (!searchKeyValue(QStringList() << "HIERARCH ESO DET OUTPUTS", numReadoutChannels)) { emit messageAvailable(baseName + " : Could not determine number of readout channels!", "error"); emit critical(); successProcessing = false; } else { if (numReadoutChannels == 4) { float gain1 = 0.0; float gain2 = 0.0; float gain3 = 0.0; float gain4 = 0.0; searchKeyValue(QStringList() << "HIERARCH ESO DET OUT1 CONAD", gain1); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT2 CONAD", gain2); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT3 CONAD", gain3); searchKeyValue(QStringList() << "HIERARCH ESO DET OUT4 CONAD", gain4); channelGains.clear(); channelGains << gain1 << gain2 << gain3 << gain4; chipGain = harmonicGain(channelGains); individualFixDone = true; } } } else if (instData.name.contains("NOTcam")) { float gain1 = 0.0; float gain2 = 0.0; float gain3 = 0.0; float gain4 = 0.0; searchKeyValue(QStringList() << "GAIN1", gain1); searchKeyValue(QStringList() << "GAIN2", gain2); searchKeyValue(QStringList() << "GAIN3", gain3); searchKeyValue(QStringList() << "GAIN4", gain4); channelGains.clear(); channelGains << gain1 << gain2 << gain3 << gain4; chipGain = harmonicGain(channelGains); individualFixDone = true; } else if (instData.name == "90Prime@BOK2.3m") { // QString gainkeyword = "GAIN"+QString::number(chip+1); // searchKeyValue(QStringList() << gainkeyword, chipGain); if (chip == 0) {searchKeyValue(QStringList() << "GAIN1", chipGain); chipGain /= 1.0000;} if (chip == 1) {searchKeyValue(QStringList() << "GAIN2", chipGain); chipGain /= 1.0033;} if (chip == 2) {searchKeyValue(QStringList() << "GAIN3", chipGain); chipGain /= 1.0113;} if (chip == 3) {searchKeyValue(QStringList() << "GAIN4", chipGain); chipGain /= 0.9681;} if (chip == 4) {searchKeyValue(QStringList() << "GAIN5", chipGain); chipGain /= 1.0000;} if (chip == 5) {searchKeyValue(QStringList() << "GAIN6", chipGain); chipGain /= 0.9406;} if (chip == 6) {searchKeyValue(QStringList() << "GAIN7", chipGain); chipGain /= 0.9823;} if (chip == 7) {searchKeyValue(QStringList() << "GAIN8", chipGain); chipGain /= 0.9504;} if (chip == 8) {searchKeyValue(QStringList() << "GAIN9", chipGain); chipGain /= 1.0000;} if (chip == 9) {searchKeyValue(QStringList() << "GAIN10", chipGain); chipGain /= 0.9729;} if (chip == 10) {searchKeyValue(QStringList() << "GAIN11", chipGain); chipGain /= 1.0204;} if (chip == 11) {searchKeyValue(QStringList() << "GAIN12", chipGain); chipGain /= 0.9789;} if (chip == 12) {searchKeyValue(QStringList() << "GAIN13", chipGain); chipGain /= 1.0000;} if (chip == 13) {searchKeyValue(QStringList() << "GAIN14", chipGain); chipGain /= 0.9982;} if (chip == 14) {searchKeyValue(QStringList() << "GAIN15", chipGain); chipGain /= 1.0366;} if (chip == 15) {searchKeyValue(QStringList() << "GAIN16", chipGain); chipGain /= 0.9660;} individualFixDone = true; } else if (instData.name == "VIS_LE1@EUCLID" || instData.name == "VIS_ERO@EUCLID") { if (chip == 0) chipGain = 3.559; if (chip == 1) chipGain = 3.556; if (chip == 2) chipGain = 3.537; if (chip == 3) chipGain = 3.515; if (chip == 4) chipGain = 3.525; if (chip == 5) chipGain = 3.561; if (chip == 6) chipGain = 3.486; if (chip == 7) chipGain = 3.445; if (chip == 8) chipGain = 3.579; if (chip == 9) chipGain = 3.520; if (chip == 10) chipGain = 3.477; if (chip == 11) chipGain = 3.496; if (chip == 12) chipGain = 3.531; if (chip == 13) chipGain = 3.621; if (chip == 14) chipGain = 3.448; if (chip == 15) chipGain = 3.503; if (chip == 16) chipGain = 3.418; if (chip == 17) chipGain = 3.425; if (chip == 18) chipGain = 3.619; if (chip == 19) chipGain = 3.513; if (chip == 20) chipGain = 3.580; if (chip == 21) chipGain = 3.548; if (chip == 22) chipGain = 3.454; if (chip == 23) chipGain = 3.471; if (chip == 24) chipGain = 3.387; if (chip == 25) chipGain = 3.416; if (chip == 26) chipGain = 3.440; if (chip == 27) chipGain = 3.449; if (chip == 28) chipGain = 3.483; if (chip == 29) chipGain = 3.469; if (chip == 30) chipGain = 3.477; if (chip == 31) chipGain = 3.457; if (chip == 32) chipGain = 3.430; if (chip == 33) chipGain = 3.446; if (chip == 34) chipGain = 3.464; if (chip == 35) chipGain = 3.483; if (chip == 36) chipGain = 3.406; if (chip == 37) chipGain = 3.514; if (chip == 38) chipGain = 3.437; if (chip == 39) chipGain = 3.476; if (chip == 40) chipGain = 3.575; if (chip == 41) chipGain = 3.571; if (chip == 42) chipGain = 3.582; if (chip == 43) chipGain = 3.489; if (chip == 44) chipGain = 3.345; if (chip == 45) chipGain = 3.515; if (chip == 46) chipGain = 3.527; if (chip == 47) chipGain = 3.431; if (chip == 48) chipGain = 3.539; if (chip == 49) chipGain = 3.476; if (chip == 50) chipGain = 3.513; if (chip == 51) chipGain = 3.501; if (chip == 52) chipGain = 3.535; if (chip == 53) chipGain = 3.504; if (chip == 54) chipGain = 3.593; if (chip == 55) chipGain = 3.520; if (chip == 56) chipGain = 3.597; if (chip == 57) chipGain = 3.626; if (chip == 58) chipGain = 3.645; if (chip == 59) chipGain = 3.630; if (chip == 60) chipGain = 3.597; if (chip == 61) chipGain = 3.657; if (chip == 62) chipGain = 3.586; if (chip == 63) chipGain = 3.627; if (chip == 64) chipGain = 3.466; if (chip == 65) chipGain = 3.477; if (chip == 66) chipGain = 3.471; if (chip == 67) chipGain = 3.504; if (chip == 68) chipGain = 3.467; if (chip == 69) chipGain = 3.466; if (chip == 70) chipGain = 3.439; if (chip == 71) chipGain = 3.442; if (chip == 72) chipGain = 3.389; if (chip == 73) chipGain = 3.372; if (chip == 74) chipGain = 3.393; if (chip == 75) chipGain = 3.448; if (chip == 76) chipGain = 3.443; if (chip == 77) chipGain = 3.409; if (chip == 78) chipGain = 3.405; if (chip == 79) chipGain = 3.454; if (chip == 80) chipGain = 3.395; if (chip == 81) chipGain = 3.409; if (chip == 82) chipGain = 3.405; if (chip == 83) chipGain = 3.465; if (chip == 84) chipGain = 3.396; if (chip == 85) chipGain = 3.412; if (chip == 86) chipGain = 3.463; if (chip == 87) chipGain = 3.343; if (chip == 88) chipGain = 3.491; if (chip == 89) chipGain = 3.438; if (chip == 90) chipGain = 3.573; if (chip == 91) chipGain = 3.463; if (chip == 92) chipGain = 3.344; if (chip == 93) chipGain = 3.385; if (chip == 94) chipGain = 3.498; if (chip == 95) chipGain = 3.378; if (chip == 96) chipGain = 3.526; if (chip == 97) chipGain = 3.484; if (chip == 98) chipGain = 3.534; if (chip == 99) chipGain = 3.480; if (chip == 100) chipGain = 3.517; if (chip == 101) chipGain = 3.456; if (chip == 102) chipGain = 3.559; if (chip == 103) chipGain = 3.556; if (chip == 104) chipGain = 3.665; if (chip == 105) chipGain = 3.679; if (chip == 106) chipGain = 3.586; if (chip == 107) chipGain = 3.493; if (chip == 108) chipGain = 3.553; if (chip == 109) chipGain = 3.501; if (chip == 110) chipGain = 3.627; if (chip == 111) chipGain = 3.556; if (chip == 112) chipGain = 3.583; if (chip == 113) chipGain = 3.566; if (chip == 114) chipGain = 3.529; if (chip == 115) chipGain = 3.545; if (chip == 116) chipGain = 3.498; if (chip == 117) chipGain = 3.567; if (chip == 118) chipGain = 3.585; if (chip == 119) chipGain = 3.540; if (chip == 120) chipGain = 3.500; if (chip == 121) chipGain = 3.444; if (chip == 122) chipGain = 3.541; if (chip == 123) chipGain = 3.578; if (chip == 124) chipGain = 3.578; if (chip == 125) chipGain = 3.582; if (chip == 126) chipGain = 3.548; if (chip == 127) chipGain = 3.577; if (chip == 128) chipGain = 3.572; if (chip == 129) chipGain = 3.535; if (chip == 130) chipGain = 3.509; if (chip == 131) chipGain = 3.491; if (chip == 132) chipGain = 3.440; if (chip == 133) chipGain = 3.365; if (chip == 134) chipGain = 3.436; if (chip == 135) chipGain = 3.459; if (chip == 136) chipGain = 3.525; if (chip == 137) chipGain = 3.479; if (chip == 138) chipGain = 3.453; if (chip == 139) chipGain = 3.463; if (chip == 140) chipGain = 3.673; if (chip == 141) chipGain = 3.599; if (chip == 142) chipGain = 3.563; if (chip == 143) chipGain = 3.636; individualFixDone = true; } if (individualFixDone) { QString card1 = "GAINORIG= "+QString::number(chipGain, 'f', 6) + " / Original gain in the raw data for this image"; QString card2 = "GAIN = 1.0 / ADUs were converted to e- in this image using GAINORIG"; card1.resize(80, ' '); card2.resize(80, ' '); headerTHELI.append(card1); headerTHELI.append(card2); if (instData.name.contains("GMOS-N-HAM") || instData.name.contains("GMOS-S-HAM") || instData.name.contains("SAMI") || instData.name.contains("SOI@SOAR") || instData.name == "LRIS_BLUE@KECK" || instData.name == "LRIS_RED@KECK" || instData.name == "MOSAIC-II_16@CTIO" || instData.name == "MOSAIC-III_4@KPNO_4m" ) { gain[chip/numAmpPerChip] = chipGain; } // multichannel imagers have less chips than gain.length() ('chip' counts higher than gain.length() ) else if (instData.name == "PISCO@LCO") { gain[0] = chipGain; gain[1] = chipGain; } else { gain[chip] = chipGain; // not applied for e.g. SuprimeCam_200808-201705 and the others (why?) } gainForSaturation = chipGain; } return individualFixDone; } // Build the AIRMASS keyword void Splitter::buildTheliHeaderAIRMASS() { if (!successProcessing) return; if (instData.name.contains("EUCLID")) { QString card = "AIRMASS = 1.000"; // Not sure what happens if I set it to zero card.resize(80, ' '); headerTHELI.append(card); return; // without errors } bool keyFound = searchKey("AIRMASS", headerDictionary.value("AIRMASS"), headerTHELI); if (keyFound) return; // Fallback: Calculate airmass from RA, DEC, OBSLAT and LST bool foundLST = searchKeyLST(headerDictionary.value("LST")); if (!foundLST) lstValue = dateobsToLST(); double airmass = 1.0; if (foundLST && lstValue != 58849.0000) airmass = localSiderealTimeToAirmass(); // numeric value indicates that dateobs is unknown else airmass = 1.0; QString card = "AIRMASS = "+QString::number(airmass, 'f', 4); card.resize(80, ' '); headerTHELI.append(card); if (!foundLST || lstValue != 58849.0000) { if (dataType == "SCIENCE" || dataType == "SKY" || dataType == "STD") { emit messageAvailable(fileName + " : Could not determine keyword: AIRMASS, set to 1.0", "warning"); } } } void Splitter::buildTheliHeaderFILTER(int chip) { // Exceptions. Return if successful. if (individualFixFILTER(chip)) return; QStringList filterKeywordList; QStringList possibleKeyNames = headerDictionary.value("FILTER"); QList<QStringList> headers = {primaryHeader, extHeader}; bool keyFound = false; bool clearFound = false; bool darkFound = false; // Loop over headers for (auto &header : headers) { for (auto &possibleKey : possibleKeyNames) { for (auto &card : header) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString filterName = card.split("=")[1]; if (filterName.contains("'")) { // FILTER keyword is a string starting with a single quote filterName = filterName.split("'").at(1); } else { int slashPosition = filterName.lastIndexOf('/'); // TODO: the slash might occur further in front! In particular for HIERARCH ESO cards if (slashPosition > 12) filterName.truncate(slashPosition); } filterName = filterName.simplified(); // Clean the string filterName.remove("'"); filterName.remove("#"); filterName.remove("["); filterName.remove("]"); filterName.remove("("); filterName.remove(")"); filterName.remove("/"); filterName.remove(";"); filterName.remove("$"); filterName.remove(" "); // Skip if filter name suggests that the slot was empty if (filterName.contains("clear", Qt::CaseInsensitive) || filterName.contains("empty", Qt::CaseInsensitive) || filterName.contains("clr", Qt::CaseInsensitive) || filterName.contains("csl", Qt::CaseInsensitive) // MOIRCS || filterName.contains("hole", Qt::CaseInsensitive) // MOIRCS || filterName.contains("unavailable", Qt::CaseInsensitive) // SAMI || filterName.contains("open", Qt::CaseInsensitive)) { clearFound = true; continue; } // Skip if filter name suggests that a dark was taken if (filterName.contains("dark", Qt::CaseInsensitive) || filterName.contains("close", Qt::CaseInsensitive) || filterName.contains("blocked", Qt::CaseInsensitive)) { darkFound = true; continue; } // Seems we found a valid FILTER keyword filterKeywordList.append(filterName); keyFound = true; } } } } QString filterCard = ""; if (!keyFound && darkFound) filterCard = "FILTER = 'Dark'"; else if (!keyFound && !darkFound && clearFound) filterCard = "FILTER = 'Clear'"; else if (!keyFound && !darkFound && !clearFound) { if (dataType != "BIAS" && dataType != "DARK") { if (*verbosity > 1) emit messageAvailable(fileName + " : Could not determine keyword: FILTER, set to 'Unknown'", "warning"); } filter = "Unknown"; filterCard = "FILTER = '"+filter+"'"; } else { filterKeywordList.removeDuplicates(); filter = filterKeywordList.join("+"); // Replace by short filter name (if mapped) QString replacement = filterDictionary.value(filter); if (!replacement.isEmpty()) filter = replacement; filterCard = "FILTER = '"+filter+"'"; } filterCard.resize(80, ' '); headerTHELI.append(filterCard); } bool Splitter::individualFixFILTER(int chip) { if (!successProcessing) return false; bool individualFixDone = false; QString filterCard = ""; if (instData.name == "PISCO@LCO") { if (chip == 0 || chip == 1) filter = "g"; if (chip == 2 || chip == 3) filter = "r"; if (chip == 4 || chip == 5) filter = "i"; if (chip == 6 || chip == 7) filter = "z"; filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "VIS_LE1@EUCLID" || instData.name == "VIS_LE2@EUCLID" || instData.name == "VIS_ERO@EUCLID") { filter = "IE"; filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "LRIS_BLUE@KECK") { searchKeyValue(QStringList() << "BLUFILT", filter); filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "LRIS_RED@KECK") { searchKeyValue(QStringList() << "REDFILT", filter); filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (instData.name == "NISP_LE1@EUCLID" || instData.name == "NISP_LE2@EUCLID" || instData.name == "NISP_ERO@EUCLID") { QString fpos = ""; QString gpos = ""; searchKeyValue(QStringList() << "FWA_POS", fpos); searchKeyValue(QStringList() << "GWA_POS", gpos); if (fpos == "CLOSED") filter = "DARK"; else if (fpos == "OPEN") filter = gpos; else if (gpos == "OPEN" && fpos != "OPEN") filter = fpos; else { // nothing yet } filter = filter.remove("FW-"); filterCard = "FILTER = '"+filter+"'"; individualFixDone = true; } if (individualFixDone) { filterCard.resize(80, ' '); headerTHELI.append(filterCard); } return individualFixDone; } bool Splitter::checkFormatDATEOBS() { // dateobs format: YYYY-MM-DDTHH:MM:SS.sss if (!dateObsValue.contains("T") || !dateObsValue.contains(":") || !dateObsValue.contains("-")) { return false; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); if (datelist.length() != 3 || timelist.length() != 3) { return false; } return true; } QString Splitter::mjdobsToDATEOBS(double mjd) { // Code taken and adjusted from: // https://api.kde.org/4.12-api/kdeedu-apidocs/marble/html/astrolib_8cpp_source.html // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright : Gerhard HOLTKAMP 11-JAN-2012 long jd0 = long(mjd + 2400001.0); long b = long ((jd0 - 1867216.25) / 36524.25); // Gregorian calendar long c = jd0 + b - (b/4) + 1525; // Gregorian calendar long d = long ((c - 122.1) / 365.25); long e = 365 * d + (d/4); long f = long ((c - e) / 30.6001); int day = c - e - long(30.6001 * f); int month = f - 1 - 12 * (f / 14); int year = d - 4715 - ((7 + month) / 10); double hour = 24.0 * (mjd - floor(mjd)); QString date = QString::number(year)+"-"+QString::number(month)+"-"+QString::number(day)+"T"; QString time = decimalToDms(hour); return date+time; } double Splitter::dateobsToMJD() { if (!checkFormatDATEOBS()) { emit messageAvailable(fileName + " : Splitter::dateobsToMJD(): Invalid DATE-OBS format:" + dateObsValue + "Setting MJD-OBS to 58849.000000 (2020-01-01).<br>" + "Background modeling and proper motion correction will not work correctly.", "warning"); emit warning(); return 58849.000000; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); double year = datelist[0].toDouble(); double month = datelist[1].toDouble(); double day = datelist[2].toDouble(); double hh = timelist[0].toDouble(); double mm = timelist[1].toDouble(); double ss = timelist[2].toDouble(); // Explanation: See http://aa.usno.navy.mil/faq/docs/JD_Formula.html // UT in decimal hours double ut = hh + mm / 60.0 + ss / 3600.0; double A = year * 367.0; double B = floor((month + 9.0) / 12.0); double C = floor(((year + B) * 7.0) / 4.0); double D = floor((275.0 * month) / 9.0); double E = day + 1721013.5 + (ut / 24.0); double F = (((100.0 * year) + month - 190002.5) >= 0) ? 1.0 : -1.0; double julian_date = A - C + D + E - (0.5 * F) + 0.5; double mjd = julian_date - 2400000.5; return mjd; } double Splitter::dateobsToLST() { if (!checkFormatDATEOBS()) { emit messageAvailable(fileName + " : Splitter::dateobsToMJD(): Invalid DATE-OBS format:" + dateObsValue + "Setting MJD-OBS to 58849.000000 (2020-01-01).<br>" + "Background modeling and proper motion correction will not work correctly.", "warning"); emit warning(); return 58849.000000; } QStringList list = dateObsValue.split("T"); QString date = list[0]; QString time = list[1]; QStringList datelist = date.split("-"); QStringList timelist = time.split(":"); double year = datelist[0].toDouble(); double month = datelist[1].toDouble(); double day = datelist[2].toDouble(); double hh = timelist[0].toDouble(); double mm = timelist[1].toDouble(); double ss = timelist[2].toDouble(); // Explanation: See http://www.xylem.f2s.com/kepler/index.html#top // UT in decimal hours double ut = hh + mm/60. + ss/3600.; // The integer and fractional days from J2000 double dwhole = 367 * year - (int)(7*(year+(int)((month+9)/12))/4) + (int)(275*month/9) + day - 730531.5; double dfrac = ut / 24.; double d = dwhole + dfrac; double lst = 100.46 + 0.985647*d + instData.obslon + 15.*ut; // LST must be between 0 and 360 degrees int idummy = (int)(lst/360.); if(lst > 0) lst -= (float)(idummy*360.); else lst -= (float)((idummy-1)*360.); // Convert to seconds lst = (lst/15.)*3600.; return lst; } double Splitter::localSiderealTimeToAirmass() { double LSTbegin = lstValue; double LSTmiddle = lstValue + 0.5 * exptimeValue; double LSTend = lstValue + exptimeValue; // double lst = lstValue * RAD; double hourangle_begin = (LSTbegin/240. - crval1) * rad; double hourangle_middle = (LSTmiddle/240. - crval1) * rad; double hourangle_end = (LSTend/240. - crval1) * rad; // The effective airmass is estimated using the 'mean airmass' estimator in // "Some Factors Affecting the Accuracy of Stellar Photometry with CCDs" (P. Stetson, DAO preprint, September 1988) double airmass_begin = calcAirmass(hourangle_begin); double airmass_middle = calcAirmass(hourangle_middle); double airmass_end = calcAirmass(hourangle_end); double airmass = (airmass_begin + 4.0*airmass_middle + airmass_end) / 6.0; return airmass; } // ahourangle is already in [rad] double Splitter::calcAirmass(double ahourangle) { double sh = sin(ahourangle); double ch = cos(ahourangle); double sd = sin(crval2 * rad); double cd = cos(crval2 * rad); double sp = sin(instData.obslat * rad); double cp = cos(instData.obslat * rad); double x = ch*cd*sp - sd*cp; double y = sh*cd; double z = ch*cd*cp + sd*sp; double zn = sqrt(x*x+y*y); double zf = zn/z; double zd = atan(zf); double seczm = 1.0 / (cos(std::min(1.52, zd))) - 1.0; // Convert zenith distance to airmass following // "R.H. Hardie in _Astronomical Techniques_ (W.A. Hiltner, ed.) (Chicago: U. Chicago Press), p. 180 (1962)." double airmass = 1.0 + seczm * (0.9981833 - seczm * (0.002875 + seczm * 0.008083)); return airmass; }
125,501
C++
.cc
2,825
35.059115
176
0.53609
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,456
splitter_RAW.cc
schirmermischa_THELI/src/tools/splitter_RAW.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../myimage/myimage.h" #include "../functions.h" #include "libraw/libraw.h" #include "libraw/libraw_version.h" #include <QString> #include <QStringList> #include <QVector> #include <QFile> #include <QDir> // Handles RAW files from CMOS-type cameras void Splitter::importRAW() { if (!successProcessing) return; // The file has been opened successfully already by Splitter::determineFileType() #define S rawProcessor.imgdata.sizes // TODO: check what that means. Do we have to return? if (!(rawProcessor.imgdata.idata.filters || rawProcessor.imgdata.idata.colors == 1)) { emit messageAvailable(fileName + " : Only Bayer-pattern RAW files supported.", "warning"); emit warning(); // return; } // Extract pixels naxis1Raw = S.raw_width; naxis2Raw = S.raw_height; naxis1 = S.iwidth; naxis2 = S.iheight; // if (!checkChipGeometry()) return; long dim = naxis1Raw*naxis2Raw; dataRaw.clear(); dataRaw.resize(dim); dataRaw.squeeze(); for (int i=0; i<dim; ++i) { dataRaw[i] = rawProcessor.imgdata.rawdata.raw_image[i]; } // Extract metadata #define P1 rawProcessor.imgdata.idata #define P2 rawProcessor.imgdata.other #if defined(LIBRAW_MAJOR_VERSION) && LIBRAW_MAJOR_VERSION == 0 && defined(LIBRAW_MINOR_VERSION) && LIBRAW_MINOR_VERSION >= 20 #define P3 rawProcessor.imgdata.makernotes.common #endif QString timeStamp = ctime(&(P2.timestamp)); timeStamp = timeStamp.simplified(); QStringList timeStampList = timeStamp.split(' '); if (timeStampList.length() < 5) { dateObsValue = "2020-01-01T00:00:00.0"; } else { QString yy = timeStampList[4]; QString mm = timeStampList[1]; QString dd = timeStampList[2]; QString hours = timeStampList[3]; if (mm == "Jan") mm = "01"; else if (mm == "Feb") mm = "02"; else if (mm == "Mar") mm = "03"; else if (mm == "Apr") mm = "04"; else if (mm == "May") mm = "05"; else if (mm == "Jun") mm = "06"; else if (mm == "Jul") mm = "07"; else if (mm == "Aug") mm = "08"; else if (mm == "Sep") mm = "09"; else if (mm == "Oct") mm = "10"; else if (mm == "Nov") mm = "11"; else if (mm == "Dec") mm = "12"; dateObsValue = yy+"-"+mm+"-"+dd+"T"+hours; if (!checkFormatDATEOBS()) dateObsValue = "2020-01-01T00:00:00.0"; } mjdobsValue = dateobsToMJD(); exptimeValue = P2.shutter; #if defined(LIBRAW_MAJOR_VERSION) && LIBRAW_MAJOR_VERSION == 0 && defined(LIBRAW_MINOR_VERSION) && LIBRAW_MINOR_VERSION >= 20 sensorTemp = P3.SensorTemperature; cameraTemp = P3.CameraTemperature; #else sensorTemp = P2.SensorTemperature; cameraTemp = P2.CameraTemperature; #endif isoSpeed = QString::number(int(P2.iso_speed)); saturationValue = pow(2,12)-1; // 12 bit // From RAW data (unreliable, because of potential trimming) /* bayerPattern = ""; if (P1.filters) { if (!P1.cdesc[3]) P1.cdesc[3] = 'G'; for (int i=0; i<4; ++i) { bayerPattern.append(P1.cdesc[rawProcessor.fcol(i >> 1, i & 1)]); } } */ // Rather, take user-defined setup bayerPattern = instData.bayer; } // UNUSED // For RAW files we force the SIZE settings in the camera.ini bool Splitter::checkChipGeometry() { if (!successProcessing) return false; for (int chip=0; chip<instData.numChips; ++chip) { if (instData.sizex[chip] != naxis1 || instData.sizey[chip] != naxis2) { emit showMessageBox("Splitter::IncompatibleSizeRAW", instData.name, QString::number(naxis1)+" "+QString::number(naxis2)); emit messageAvailable("Splitter::checkChipGeometry(): Inconsistent detector geometry", "error"); emit critical(); successProcessing = false; return false; } } return true; } void Splitter::buildHeaderRAW() { if (!successProcessing) return; float flipcd11 = 1.0; float flipcd22 = 1.0; if (instData.flip == "FLIPX") flipcd11 = -1.0; else if (instData.flip == "FLIPY") flipcd22 = -1.0; else if (instData.flip == "ROT180") { flipcd11 = -1.0; flipcd22 = -1.0; } QStringList cards; cards.append("OBJECT = 'Unknown'"); cards.append("CTYPE1 = 'RA---TAN'"); cards.append("CTYPE2 = 'DEC--TAN'"); cards.append("CRVAL1 = 0.0"); cards.append("CRVAL2 = 0.0"); cards.append("CRPIX1 = "+QString::number(naxis1/2)); cards.append("CRPIX2 = "+QString::number(naxis2/2)); cards.append("CD1_1 = "+QString::number(-1.*flipcd11*instData.pixscale/3600.)); cards.append("CD1_2 = 0.0"); cards.append("CD2_1 = 0.0"); cards.append("CD2_2 = "+QString::number(flipcd22*instData.pixscale/3600.)); cards.append("EQUINOX = 2000.0"); cards.append("RADESYS = 'ICRS'"); cards.append("EXPTIME = "+QString::number(exptimeValue)); cards.append("DATE-OBS= "+dateObsValue); cards.append("MJD-OBS = "+QString::number(mjdobsValue, 'f', 12)); cards.append("FILTER = 'RGB'"); cards.append("AIRMASS = 1.0"); cards.append("THELIPRO= 1"); cards.append("BAYER = '"+bayerPattern+"'"); cards.append("GEOLON = "+QString::number(instData.obslon, 'f', 4)); cards.append("GEOLAT = "+QString::number(instData.obslat, 'f', 4)); if (sensorTemp > -1000.) cards.append("DET_TEMP= "+QString::number(sensorTemp, 'f', 2)); if (cameraTemp > -1000.) cards.append("CAM_TEMP= "+QString::number(cameraTemp, 'f', 2)); if (!isoSpeed.isEmpty()) cards.append("ISOSPEED= "+isoSpeed); for (auto &card : cards) { card.resize(80, ' '); } headerTHELI.clear(); headerTHELI.append(cards); QString card1 = "GAINORIG= 1.0 / Original gain in the raw data for this image"; QString card2 = "GAIN = 1.0 / ADUs were converted to e- in this image using GAINORIG"; card1.resize(80, ' '); card2.resize(80, ' '); headerTHELI.append(card1); headerTHELI.append(card2); headerTHELI.append(dummyKeys); } void Splitter::extractImagesRAW() { if (!successProcessing) return; // Keeping multi-chip code structure for consistency, even though we have just a single chip for (int chip=0; chip<instData.numChips; ++chip) { importRAW(); overwriteCameraIniRAW(); getDetectorSections(); getMultiportInformation(chip); correctOverscan(); cropDataSection(dataSection[chip]); correctXtalk(); correctNonlinearity(chip); applyMask(chip); buildHeaderRAW(); writeImage(chip); #pragma omp atomic *progress += progressStepSize; } } void Splitter::overwriteCameraIniRAW() { if (!successProcessing) return; // For the sake of generality I keep the multi-chip architecture. // RAW files can contain multiple extensions (which are not supported yet by THELI) // WARNING: we OVERWRITE the overscan and data section entries in camera.ini // Trusting that metadata in RAW files are correct // No overscan correction if less than 5 pixels wide for (int chip=0; chip<instData.numChips; ++chip) { // If overscan == 0 in camera.ini, the overscan_xmin etc vectors are set to empty to indicate no overscan shall be done for FITS files. // However, for RAW files, we do want an overscan if available. instData.overscan_xmin.resize(1); instData.overscan_xmax.resize(1); instData.overscan_ymin.resize(1); instData.overscan_ymax.resize(1); instData.overscan_xmin[chip] = 0; instData.overscan_xmax[chip] = S.left_margin < 5 ? 0 : S.left_margin - 1; instData.overscan_ymin[chip] = 0; instData.overscan_ymax[chip] = S.top_margin < 5 ? 0 : S.top_margin - 1; // Deactivate overscan if area is less than 5 pixels wide if (instData.overscan_xmin[chip] == 0 && instData.overscan_xmax[chip] == 0) { instData.overscan_xmin.clear(); instData.overscan_xmax.clear(); } if (instData.overscan_ymin[chip] == 0 && instData.overscan_ymax[chip] == 0) { instData.overscan_ymin.clear(); instData.overscan_ymax.clear(); } instData.cutx[chip] = S.left_margin; instData.cuty[chip] = S.top_margin; instData.sizex[chip] = S.iwidth; instData.sizey[chip] = S.iheight; if (S.iwidth % 2 != 0) { instData.cutx[chip] += 1; instData.sizex[chip] -= 1; } if (S.iheight % 2 != 0) { instData.cuty[chip] += 1; instData.sizey[chip] -= 1; } } // Don't need RAW data and metadata anymore rawProcessor.recycle(); }
9,513
C++
.cc
236
34.466102
143
0.642563
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,457
splitter_queryHeaderLists.cc
schirmermischa_THELI/src/tools/splitter_queryHeaderLists.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "splitter.h" #include "../instrumentdata.h" #include "../functions.h" #include <QString> #include <QStringList> #include <QVector> #include <QFile> #include <QDir> // These routines do not query the FITS header itself, but rather the QStringList version // Retrieve the key and update the output header bool Splitter::searchKey(const QString &searchKeyName, const QStringList &possibleKeyNames, QStringList &outputHeader) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, primaryHeader, outputHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, extHeader, outputHeader); // bool inPrimaryHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, extHeader, outputHeader); // if (!inPrimaryHeader) inExtHeader = searchKeyInHeader(searchKeyName, possibleKeyNames, primaryHeader, outputHeader); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the floating point value of a key, don't update output header void Splitter::searchKeyCRVAL(const QString searchKey, const QStringList &possibleKeyNames, QStringList &outputHeader) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, primaryHeader, outputHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, extHeader, outputHeader); // bool inPrimaryHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, extHeader, outputHeader); // if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderCRVAL(searchKey, possibleKeyNames, primaryHeader, outputHeader); // Fallback: if (!inPrimaryHeader && !inExtHeader) { QString card; if (searchKey == "CRVAL1") card = "CRVAL1 = 0.0"; if (searchKey == "CRVAL2") card = "CRVAL2 = 0.0"; card.resize(80, ' '); outputHeader.append(card); } } // Retrieve the floating point value of a key, don't update output header bool Splitter::searchKeyLST(const QStringList &possibleKeyNames) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderLST(possibleKeyNames, primaryHeader); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderLST(possibleKeyNames, extHeader); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the int value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, int &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (possibleKeyNames.contains("NAMPS")) qDebug() << __func__ << fileName << possibleKeyNames << primaryHeader.length() << inPrimaryHeader << value; if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the floating point value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, float &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the double value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, double &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } // Retrieve the QString value of a key, don't update output header bool Splitter::searchKeyValue(const QStringList &possibleKeyNames, QString &value) { bool inExtHeader = false; bool inPrimaryHeader = searchKeyInHeaderValue(possibleKeyNames, primaryHeader, value); if (!inPrimaryHeader) inExtHeader = searchKeyInHeaderValue(possibleKeyNames, extHeader, value); if (!inExtHeader && !inPrimaryHeader) return false; else return true; } bool Splitter::searchKeyInHeader(const QString &searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader) { // TODO: enforce that numeric values are numeric, and string values have single quotes // some raw data don't obey this rule // TODO: preference to key in EXT if also found in PHDU, or the other way round? // Right now it will take the PHDU value if present there (because PHDU is searched first) bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); keyFound = true; int slashPosition = keyValue.lastIndexOf('/'); // (can be -1 if not found, treated as 0 by truncate(), i.e. entire string is set to empty if (searchKey == "DATE-OBS") { if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); dateObsValue = keyValue.simplified(); if (!checkFormatDATEOBS()) break; // do not append wrong format to output header! dealing with this elsewhere } if (searchKey == "MJD-OBS") { if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); mjdobsValue = keyValue.simplified().toDouble(); } QString newCard = searchKey; // If input is numeric and has decimal comma, replace it with a decimal dot newCard.resize(8, ' '); // Keyword must be 8 chars long newCard.append("= "+keyValue); newCard.resize(80, ' '); // Header card must be 80 chars long outputHeader.append(newCard); // if (searchKey == "CD1_1" && possibleKey == "CDELT1") qDebug() << card << "\n" << keyValue << slashPosition << "\n" << newCard; break; } } if (keyFound) break; } return keyFound; } bool Splitter::searchKeyInHeaderCRVAL(const QString searchKey, const QStringList &possibleKeyNames, const QStringList &inputHeader, QStringList &outputHeader) { bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // Isolate CRVAL value int slashPosition = keyValue.lastIndexOf('/'); if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); keyValue = keyValue.simplified(); // Fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') keyValue.replace(' ', ':'); // Convert to decimal format if necessary QString crval = keyValue; if (keyValue.contains(':')) { if (searchKey == "CRVAL1") crval = hmsToDecimal(keyValue); if (searchKey == "CRVAL2") crval = dmsToDecimal(keyValue); } // Some instruments store CRVAL1 in decimal hours, oh well ... if (possibleKey == "RA-HOURS" || instData.name == "SITe@TLS") { crval = QString::number(15.*crval.toDouble(), 'f', 12); } // And sometimes it may under- or overrun the [0,360] degree boundary if (searchKey == "CRVAL1") { if (crval.toDouble() > 360.) crval = QString::number(crval.toDouble()-360., 'f', 12); else if (crval.toDouble() < 0.) crval = QString::number(crval.toDouble()+360., 'f', 12); } if (searchKey == "CRVAL2") { if (crval.toDouble() > 90.) crval = "90.0"; else if (crval.toDouble() < -90.) crval = "-90.0"; } // The William Herschel Telescope has its own funny "apertures" ... if (instData.name.contains("@WHT") && !instData.name.contains("PF_QHY")) { double ra_off1 = 0.; double ra_off2 = 0.; double dec_off1 = 0.; double dec_off2 = 0.; QStringList ra1 = {"XAPNOM"}; QStringList ra2 = {"XAPOFF"}; QStringList dec1 = {"YAPNOM"}; QStringList dec2 = {"YAPOFF"}; searchKeyInHeaderValue(ra1, inputHeader, ra_off1); searchKeyInHeaderValue(ra2, inputHeader, ra_off2); searchKeyInHeaderValue(dec1, inputHeader, dec_off1); searchKeyInHeaderValue(dec2, inputHeader, dec_off2); if (searchKey == "CRVAL1") crval = QString::number(crval.toDouble() + ra_off1 + ra_off2, 'f', 12); if (searchKey == "CRVAL2") crval = QString::number(crval.toDouble() + dec_off1 + dec_off2, 'f', 12); } // GSAOI must apply offsets, too if (instData.name.contains("GSAOI")) { double ra_off = 0.; double dec_off = 0.; QStringList ra = {"RAOFFSET"}; QStringList dec = {"DECOFFSE"}; searchKeyInHeaderValue(ra, inputHeader, ra_off); searchKeyInHeaderValue(dec, inputHeader, dec_off); if (searchKey == "CRVAL1") { double dec_pointing = 0.; QStringList decpoint = {"DEC"}; searchKeyInHeaderValue(decpoint, inputHeader, dec_pointing); crval = QString::number(crval.toDouble() + ra_off / 3600. / cos(dec_pointing*rad), 'f', 12); } if (searchKey == "CRVAL2") crval = QString::number(crval.toDouble() + dec_off/3600., 'f', 12); } // Construct the key card QString newCard = searchKey; newCard.resize(8, ' '); // Keyword must be 8 chars long newCard.append("= "+crval); newCard.resize(80, ' '); // Header card must be 80 chars long outputHeader.append(newCard); keyFound = true; break; } } if (keyFound) break; } return keyFound; } bool Splitter::searchKeyInHeaderLST(const QStringList &possibleKeyNames, const QStringList &inputHeader) { bool keyFound = false; // Loop over list of possible key names to find match for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // Isolate LST value int slashPosition = keyValue.lastIndexOf('/'); if (slashPosition > 12) keyValue.truncate(slashPosition); keyValue.remove("'"); keyValue = keyValue.simplified(); // Fix format (sometimes we have 'HH MM SS' instead of 'HH:MM:SS') keyValue.replace(' ', ':'); // Convert to decimal format (decimal hours and then to seconds) // So far, I never found different units // TODO: check PANIC@LCO and CFH12K99@CFHT QString lst = keyValue; if (keyValue.contains(':')) { lst = dmsToDecimal(keyValue); // use dmstodecimal instead of hmstodecimal because we need LST in seconds } lstValue = 3600.*lst.toDouble(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // int version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, int &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toInt(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // float version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, float &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toFloat(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // double version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, double &value) { bool keyFound = false; // Loop over possible keywords for (auto &possibleKey : possibleKeyNames) { // Loop over header for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); // Loop over list of possible key names to find match if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; to_EN_US(keyName, keyValue); // We are looking for a numeric value: remove quotes, simplify white space keyValue.remove("'"); keyValue = keyValue.simplified(); // Split (/, and potential comment), take the first element value = keyValue.split(' ').at(0).toDouble(); keyFound = true; break; } } if (keyFound) break; } return keyFound; } // QString version bool Splitter::searchKeyInHeaderValue(const QStringList &possibleKeyNames, const QStringList &inputHeader, QString &value) { bool keyFound = false; // Loop over possible keywords // WARNING: Assume we look for DATE-OBS, and the header contains both DATE-OBS and DATE keywords. // DATE-OBS is found first and is assumed to be correct (compared to DATE) // If we loop first over the header, DATE would be taken if it appears first in the header for (auto &possibleKey : possibleKeyNames) { // Loop over header to find a match for (auto &card : inputHeader) { QString keyName = card.split("=")[0].simplified(); if (keyName == possibleKey) { QString keyValue = card.split("=")[1]; // Correct header: string value enclosed in single quotes if (keyValue.contains("'")) { keyValue = keyValue.split("'").at(1); } else { int slashPosition = keyValue.lastIndexOf('/'); // TODO: the slash might occur further in front! In particular for HIERARCH ESO cards if (slashPosition > 12) keyValue.truncate(slashPosition); } keyValue.replace('/', '_'); // Some filter names contain a slash keyValue.remove("'"); // Remove potential quotes from string value keyValue = keyValue.simplified(); value = keyValue; keyFound = true; break; } } if (keyFound) break; } return keyFound; } void Splitter::to_EN_US(QString &keyName, QString &keyValue) { // If a key value, that can be potentially expressed as a decimal number, has a decimal comma, replace the comma with a decimal dot. // Actually, keyValue is everything following the "=" char in the header card, hence just replace the first comma before the / comment starts if (numericKeyNames.contains(keyName) && keyValue.contains(",")) { int commaPosition = keyValue.indexOf(','); int commentPosition = keyValue.indexOf('/'); // replace if no comment field, or if comma occurs before comment field starts if (commentPosition == -1 || commaPosition < commentPosition) { keyValue.replace(commaPosition, 1, '.'); commaDetected = true; } } }
19,226
C++
.cc
387
39.002584
160
0.607893
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,458
tools.cc
schirmermischa_THELI/src/tools/tools.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "tools.h" #include "instrumentdata.h" #include "../functions.h" #include "../myimage/myimage.h" #include <algorithm> #include <omp.h> #include <QDebug> #include <QMessageBox> // Get the max size of a mosaic-ed exposure void getBinnedSize(const instrumentDataType *instData, const QVector<QVector<int>> Tmatrices, int &n_bin, int &m_bin, int binFactor, int &xminOffset, int &yminOffset) { // The extreme vertices of a mosaic-ed image QVector<long> xLimits; QVector<long> yLimits; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; QVector<int> T = Tmatrices[chip]; int x0 = -instData->crpix1[chip] + 0; int x1 = -instData->crpix1[chip] + instData->sizex[chip]; int y0 = -instData->crpix2[chip] + 0; int y1 = -instData->crpix2[chip] + instData->sizey[chip]; // Push the x and y coords of the four corners xLimits.push_back(T[0]*x0 + T[2]*y0); // lower left xLimits.push_back(T[0]*x1 + T[2]*y0); // lower right xLimits.push_back(T[0]*x0 + T[2]*y1); // upper left xLimits.push_back(T[0]*x1 + T[2]*y1); // upper right yLimits.push_back(T[1]*x0 + T[3]*y0); // lower left yLimits.push_back(T[1]*x1 + T[3]*y0); // lower right yLimits.push_back(T[1]*x0 + T[3]*y1); // upper left yLimits.push_back(T[1]*x1 + T[3]*y1); // upper right } // We need these for later use outside this function xminOffset = minVec_T(xLimits) / binFactor; yminOffset = minVec_T(yLimits) / binFactor; // The size of the binned image, with a safety margin of 10 pixels on each side n_bin = (maxVec_T(xLimits) - minVec_T(xLimits)) / binFactor + 20; m_bin = (maxVec_T(yLimits) - minVec_T(yLimits)) / binFactor + 20; } // Remove the plate scale and position angle component from a CD matrix // (required to create binned images) QVector<int> CDmatrixToTransformationMatrix(QVector<double> CD, QString instName) { if (instName != "WFC@INT" && instName != "WFC_2x2@INT" && instName != "90Prime@BOK2.3m") rotateCDmatrix(CD, 0.); double pscale = sqrt(CD[0]*CD[0] + CD[2]*CD[2]); QVector<int> T; T.push_back(round(CD[0]/pscale)); T.push_back(round(CD[1]/pscale)); T.push_back(round(CD[2]/pscale)); T.push_back(round(CD[3]/pscale)); if (instName != "WFC@INT" && instName != "WFC_2x2@INT" && instName != "90Prime@BOK2.3m") { // Take out any flips. Only rotations are allowed for binned mosaics if (T[0] == -1 && T[3] == 1) T[0] = 1; else if (T[0] == 1 && T[3] == -1) T[3] = 1; else if (T[1] == -1 && T[2] == 1) T[1] = 1; else if (T[1] == 1 && T[2] == -1) T[2] = 1; } return T; } // Rotate a CD matrix to a new position angle // input angle in [deg] void rotateCDmatrix(QVector<double> &CD, float pa_new) { double cd11 = CD[0]; double cd12 = CD[1]; double cd21 = CD[2]; double cd22 = CD[3]; double rad = 3.1415926535 / 180.; // is the matrix flipped (det(CD) > 0 if flipped) double det = cd11*cd22 - cd12*cd21; double f11; if (det < 0) f11 = 1.; else f11 = -1.; double f12 = 0.; double f21 = 0.; double f22 = 1.; // unflip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); // rotate the matrix to the new position angle // the current position angle of the CD matrix double pa_old = posangle(CD); // in [deg] double pa_diff = rad * (pa_new - pa_old); matrixMult_T(cos(pa_diff), -sin(pa_diff), sin(pa_diff), cos(pa_diff), cd11, cd12, cd21, cd22); // flip the matrix matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22); CD[0] = cd11; CD[1] = cd12; CD[2] = cd21; CD[3] = cd22; } // Get the position angle of a CD matrix [deg] float posangle(const QVector<double> CD) { double cd11 = CD[0]; double cd12 = CD[1]; double cd21 = CD[2]; double cd22 = CD[3]; // the pixel scale double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21); double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22); // take out the pixel scale cd11 /= pscale1; cd12 /= pscale2; cd21 /= pscale1; cd22 /= pscale2; // sqrt(CD elements) is very close to one, but not perfectly // as coordinate system is not necessarily orthogonal (shear + contraction) double nfac1 = sqrt(cd11 * cd11 + cd21 * cd21); double nfac2 = sqrt(cd12 * cd12 + cd22 * cd22); // make sure sqrt(CD elements) = 1, // so that we can do the inverse trig functions cd11 /= nfac1; cd21 /= nfac1; cd12 /= nfac2; cd22 /= nfac2; // due to flipping the rotation angle is ambiguous. // possibly, the following could be simplified with det(CD), // but at the moment I don't see how to identify the additional 2*PI easily double pa; double PI = 3.1415926535; // normal if (cd11 < 0 && cd12 <= 0 && cd21 <= 0 && cd22 > 0) pa = acos(-cd11); // 0 <= phi < 90 else if (cd11 >= 0 && cd12 < 0 && cd21 < 0 && cd22 <= 0) pa = acos(-cd11); // 90 <= phi < 180 else if (cd11 > 0 && cd12 >= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(-cd11); // 180 <= phi < 270 else if (cd11 <= 0 && cd12 > 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(-cd11); // 270 <= phi < 360 // flipped else if (cd11 >= 0 && cd12 >= 0 && cd21 <= 0 && cd22 >= 0) pa = acos(cd11); // 0 <= phi < 90 else if (cd11 < 0 && cd12 > 0 && cd21 < 0 && cd22 < 0) pa = acos(cd11); // 90 <= phi < 180 else if (cd11 < 0 && cd12 <= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(cd11); // 180 <= phi < 270 else if (cd11 >= 0 && cd12 < 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(cd11); // 270 <= phi < 360 else { // we are very likely close to 0, 90, 180 or 270 degrees, and the CD matrix is slightly non-orthogonal. // In this case, lock onto 0, 90, 180 or 270 degrees. Otherwise, exit with an error. double cd11cd12 = fabs(cd11/cd12); double cd22cd21 = fabs(cd22/cd21); if (cd11cd12 > 20. && cd22cd21 > 20.) { if (cd11 > 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 < 0. && cd22 > 0.) pa = 0.*PI/2.; if (cd11 > 0. && cd22 < 0.) pa = 2.*PI/2.; if (cd11 < 0. && cd22 < 0.) pa = 2.*PI/2.; } else if (cd11cd12 < 0.05 && cd22cd21 < 0.05) { if (cd12 > 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 < 0. && cd21 < 0.) pa = 1.*PI/2.; if (cd12 > 0. && cd21 > 0.) pa = 3.*PI/2.; if (cd12 < 0. && cd21 > 0.) pa = 3.*PI/2.; } else { qDebug() << "Tools::posangle(): ERROR: Could not determine position angle from CD matrix!"; pa = 0.; } } double rad = PI / 180.; return pa / rad; } // Calculate binned image (using median filter) void binData(const QVector<float> &data, QVector<float> &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY) { long bsq = binX * binY; QVector<float> chunk(bsq,0); // Do the binning for (long j=0; j<mb; ++j) { for (long i=0; i<nb; ++i) { long k = 0; for (int jt=j*binY;jt<(j+1)*binY;++jt) { for (int it=i*binX;it<(i+1)*binX;++it) { chunk[k] = data[it+n*jt]; ++k; } } // Median filter dataBinned[i+nb*j] = medianMask(chunk); } } } // Calculate binned image (using mean filter) void binDataMean(const QVector<float> &data, QVector<float> &dataBinned, const int n, const int nb, const int mb, const int binX, const int binY) { long bsq = binX * binY; QVector<float> chunk(bsq,0); // Do the binning for (long j=0; j<mb; ++j) { for (long i=0; i<nb; ++i) { long k = 0; for (int jt=j*binY;jt<(j+1)*binY;++jt) { for (int it=i*binX;it<(i+1)*binX;++it) { if (k>=bsq) qDebug() << "error1" << k << bsq; if (it+n*jt >= data.length()) qDebug() << "error2" << it << n << jt << it+n*jt << data.length(); chunk[k] = data[it+n*jt]; ++k; } } // Median filter dataBinned[i+nb*j] = meanMask(chunk); } } } // Map an individual binned image onto a global output image, using // the transformation matrix void mapBinnedData(QVector<float> &dataBinnedGlobal, const QVector<float> &dataBinnedIndividual, const QVector<int> T, const int nGlobal, const int mGlobal, const int nInd, const int mInd, const long crpix1, const long crpix2, const int xminOffset, const int yminOffset, const QString instName) { // Transformation matrix, derived from CD matrix, for relative positioning int T0 = T[0]; int T1 = T[1]; int T2 = T[2]; int T3 = T[3]; for (int j=0; j<mInd; ++j) { int jj = j - crpix2; for (int i=0; i<nInd; ++i) { int ii = i - crpix1; // The output pixel position int iBin = T0*ii + T2*jj - xminOffset + 10; int jBin = T1*ii + T3*jj - yminOffset + 10; // The following 4 lines should never be evaluated. // If the binned images always look fine, then this can be removed. if (iBin >= nGlobal) iBin = nGlobal - 1; if (jBin >= mGlobal) jBin = mGlobal - 1; if (iBin < 0) iBin = 0; if (jBin < 0) jBin = 0; // if (!instName.contains("MOIRCS")) { // dataBinnedGlobal[iBin+nGlobal*jBin] = dataBinnedIndividual[i+nInd*j]; // } // else { // "Adding" instead of replacing. MOIRCS detectors are partially masked and these areas // do overlap because of the beam splitter (masking valid pixels) // And that holds for quite a few other others as well, e.g. LRIS@KECK, so let's do it like this by default dataBinnedGlobal[iBin+nGlobal*jBin] += dataBinnedIndividual[i+nInd*j]; // } } } } QVector<float> collapse_x(QVector<float> &data, const QVector<bool> &globalMask, QVector<bool> &objectMask, const float kappa, const long n, const long m, const QString returnMode) { long i, j; int iterMax = 5; // average columns / rows QVector<float> row; QVector<float> col; row.reserve(n); col.reserve(m); // Object mask can be empty if defect detection is the first step after launching the GUI if (objectMask.isEmpty()) objectMask.fill(false, n*m); // extract representative line for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { if (!globalMask[i+n*j] && !objectMask[i+n*j]) row.append(data[i+n*j]); } col.push_back( meanIterative(row, kappa, iterMax) ); row.clear(); } // Return 1D collapsed profile if (returnMode == "1Dmodel") { return col; } // Return 2D collapsed image else if (returnMode == "2Dmodel") { QVector<float> collapsed(n*m); for (i=0; i<n; ++i) { for (j=0; j<m; ++j) { collapsed[i+n*j] = col[j]; } } return collapsed; } else { // "2Dsubtract" : Subtract 2D model from data for (i=0; i<n; ++i) { for (j=0; j<m; ++j) { if (!globalMask.at(i+n*j)) data[i+n*j] -= col[j]; else data[i+n*j] = 0.; } } return QVector<float>(); // return value ignored. Updating data directly } } // Keeping a functor version as comments for future reference QVector<float> collapse_y(QVector<float> &data, const QVector<bool> &globalMask, QVector<bool> &objectMask, // float (*statisticsMode)(QVector<float>, float, int), const float kappa, const long n, const long m, const QString returnMode) { long i, j; int iterMax = 5; // average columns / rows QVector<float> row; QVector<float> col; row.reserve(n); col.reserve(m); if (objectMask.isEmpty()) objectMask.fill(false, n*m); // extract representative line for (i=0; i<n; ++i) { for (j=0; j<m; ++j) { if (!globalMask[i+n*j] && !objectMask[i+n*j]) col.append(data[i+n*j]); } // row.push_back( (*statisticsMode)(col, kappa, iterMax) ); row.append( meanIterative(col, kappa, iterMax) ); col.clear(); } // Return 1D collapsed profile if (returnMode == "1Dmodel") { return row; } // Return 2D collapsed image else if (returnMode == "2Dmodel") { QVector<float> collapsed(n*m); for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { collapsed[i+n*j] = row[i]; } } return collapsed; } else { // "2Dsubtract" : Subtract 2D model from data for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { if (!globalMask.at(i+n*j)) data[i+n*j] -= row[i]; else data[i+n*j] = 0.; } } return QVector<float>(); // return value ignored. Updating data directly } } // collapse along vhhv (vertical, horizontal, horizontal, // vertical readout quadrants) or hvvh, hhhh, vvvv directions QVector<float> collapse_quad(QVector<float> &data, const QVector<bool> &globalMask, QVector<bool> &objectMask, const float kappa, const long n, const long m, const QString direction, const QString returnMode) { long i, j; if (n % 2 != 0 || m % 2 != 0) { qDebug() << "ERROR: image must have even numbered dimensions for this operation!\n"; qDebug() << " Dimensions: " << n << "x" << m; return QVector<float>(); } long n1 = 0; long m1 = 0; long nh = n/2; long mh = m/2; QVector<float> quadrant(nh*mh, 0); QVector<float> collquad(nh*mh, 0); QVector<float> collapsed2D(n*m, 0); QVector<bool> globalMaskquad(nh*mh, false); QVector<bool> objectMaskquad(nh*mh, false); if (objectMask.isEmpty()) objectMask.fill(false, n*m); // do the four quadrants long loop = 0; while (loop <= 3) { // the four quadrants // lower left if (loop == 0) { n1 = 0; m1 = 0; } // lower right if (loop == 1) { n1 = nh; m1 = 0; } // upper left if (loop == 2) { n1 = 0; m1 = mh; } // upper right if (loop == 3) { n1 = nh; m1 = mh; } // copy the quadrant and the mask for (j=0; j<mh; ++j) { for (i=0; i<nh; ++i) { quadrant[i+nh*j] = data[i+n1+n*(j+m1)]; globalMaskquad[i+nh*j] = globalMask[i+n1+n*(j+m1)]; objectMaskquad[i+nh*j] = objectMask[i+n1+n*(j+m1)]; } } // collapse the quadrant if (direction == "yxxy") { if (loop == 0) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 1) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 2) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 3) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); } else if (direction == "xyyx") { if (loop == 0) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 1) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 2) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 3) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); } else if (direction == "xxxx") { if (loop == 0) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 1) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 2) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 3) collquad = collapse_x(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); } else if (direction == "yyyy") { if (loop == 0) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 1) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 2) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); if (loop == 3) collquad = collapse_y(quadrant, globalMaskquad, objectMaskquad, kappa, nh, mh, "2Dmodel"); } else { qDebug() << "QDEBUG: collapseQuad(): Invalid collapse direction" << direction; } // reconstruct the full (n x m) sized image for (j=0; j<mh; ++j) { for (i=0; i<nh; ++i) { collapsed2D[i+n1+n*(j+m1)] = collquad[i+nh*j]; } } ++loop; } if (returnMode == "2Dmodel") return collapsed2D; else { // subtract 2D model long i = 0; for (auto &pixel : data) { if (!globalMask.at(i)) pixel -= collapsed2D.at(i); else pixel = 0.; ++i; } return QVector<float>(); } } // Sort a 2D QVector by its first element // UNUSED; implemented explicitly in function void sort2DVector(QVector<QVector<double>> &data) { std::sort(data.begin(), data.end(), [](const QVector<double>& left, const QVector<double>& right)->bool { // if (left.empty()) return true; // if (right.empty()) return true; // return left.first() < right.first(); if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); } // returns distance between two points on the sky [deg] double haversine(double ra1, double ra2, double dec1, double dec2) { double rad = 3.1415926535 / 180.; ra1 *= rad; ra2 *= rad; dec1 *= rad; dec2 *= rad; double ddec = dec2 - dec1; double dra = ra2 - ra1; return 2. * asin( sqrt( pow(sin(ddec/2.),2) + cos(dec1) * cos(dec2) * pow(sin(dra/2.),2) ) ) / rad; } /* // Copy magnitudes and mag errors from a {DEC, RA, <MAG>, <MAGERR>} vector to another {DEC, RA, <MAG>, <MAGERR>} vector (matching) // <MAG> can be one or more numbers, e.g. 2 ref mags, or several aperture mags // tolerance is in [deg] void match2D(const QVector<QVector<double>> vec1, const QVector<QVector<double>> vec2, QVector<QVector<double>> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector<int> numMatched1; QVector<int> numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references //#pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { bool inside_previous = false; bool inside_current = false; for (long j=0; j<dim2; ++j) { // calc DEC offset and see if we are "within reach" (list is sorted with respect to DEC) double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone ("zone" refers to the range in the sorted list that could match) // if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { ++numMatched1[i]; ++numMatched2[j]; } } inside_previous = inside_current; } } multiple1 = 0; multiple2 = 0; for (auto &mult : numMatched1) { if (mult>1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { // if (numMatched1[i] > 1) continue; bool inside_previous = false; bool inside_current = false; QVector<double> dummy; for (long j=0; j<dim2; ++j) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); // if (nthreads == 0) qDebug() << qSetRealNumberPrecision(10) << vec2.at(j)[1] << vec1.at(i)[1] << vec2.at(j)[0] << vec1.at(i)[0] << distance << tolerance; if (distance < tolerance) { dummy << vec1.at(i)[0]; // RA OBJ dummy << vec1.at(i)[1]; // DEC OBJ for (int k=2; k<vec2.at(j).length(); ++k) { dummy << vec2.at(j)[k]; // MAG and MAGERR for reference sources } for (int k=2; k<vec1.at(i).length(); ++k) { dummy << vec1.at(i)[k]; // MAG and MAGERR for objects } #pragma omp critical { matched.append(dummy); } } inside_previous = inside_current; } } omp_destroy_lock(&lock); } */ // Copy magnitudes and mag errors from a {DEC, RA, <MAG>, <MAGERR>} vector to another {DEC, RA, <MAG>, <MAGERR>} vector (matching) // <MAG> can be one or more numbers, e.g. 2 ref mags, or several aperture mags // tolerance is in [deg] void match2D(const QVector<QVector<double>> vec1, QVector<QVector<double>> vec2, QVector<QVector<double>> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) std::sort(vec2.begin(), vec2.end(), [](const QVector<double>& left, const QVector<double>& right)->bool { if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); // sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector<int> numMatched1; QVector<int> numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references //#pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { bool inside_previous = false; bool inside_current = false; for (long j=0; j<dim2; ++j) { // calc DEC offset and see if we are "within reach" (list is sorted with respect to DEC) double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone ("zone" refers to the range in the sorted list that could match) if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { ++numMatched1[i]; ++numMatched2[j]; } } inside_previous = inside_current; } } multiple1 = 0; multiple2 = 0; for (auto &mult : numMatched1) { if (mult>1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // qDebug() << multiple1 << multiple2; // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { if (numMatched1[i] > 1) continue; bool inside_previous = false; bool inside_current = false; QVector<double> dummy; for (long j=0; j<dim2; ++j) { if (numMatched2[j] > 1) continue; // calc DEC offset and see if we are "within reach" double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { dummy << vec1.at(i)[0]; // DEC OBJ dummy << vec1.at(i)[1]; // RA OBJ for (int k=2; k<vec2.at(j).length(); ++k) { dummy << vec2.at(j)[k]; // MAG and MAGERR for reference sources } for (int k=2; k<vec1.at(i).length(); ++k) { dummy << vec1.at(i)[k]; // MAG and MAGERR for objects } #pragma omp critical { matched.append(dummy); } } } inside_previous = inside_current; } } omp_destroy_lock(&lock); } // same as match2d, just uses the reference coordinates in the output catalog void match2D_refcoords(const QVector<QVector<double>> vec1, QVector<QVector<double>> vec2, QVector<QVector<double>> &matched, double tolerance, int &multiple1, int &multiple2, int nthreads) { if (vec1.isEmpty() || vec2.isEmpty()) return; // Only the reference vector needs to be sorted, using the first column (DEC) std::sort(vec2.begin(), vec2.end(), [](const QVector<double>& left, const QVector<double>& right)->bool { if (left.empty() && right.empty()) return false; if (left.empty()) return true; if (right.empty()) return false; return left.first() < right.first(); } ); // sort2DVector(vec2); long dim1 = vec1.length(); // Objects long dim2 = vec2.length(); // Reference sources matched.reserve(dim1); QVector<int> numMatched1; QVector<int> numMatched2; numMatched1.fill(0, dim1); // How many times an object got matched with different reference sources numMatched2.fill(0, dim2); // How many times a reference source got matched with different objects omp_lock_t lock; omp_init_lock(&lock); // First pass: identify ambiguous sources and references // #pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { bool inside_previous = false; bool inside_current = false; for (long j=0; j<dim2; ++j) { // calc DEC offset and see if we are "within reach" (list is sorted with respect to DEC) double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone ("zone" refers to the range in the sorted list that could match) if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { ++numMatched1[i]; ++numMatched2[j]; } } inside_previous = inside_current; } } multiple1 = 0; multiple2 = 0; for (auto &mult : numMatched1) { if (mult>1) ++multiple1; } for (auto &mult : numMatched2) { if (mult>1) ++multiple2; } // Second pass, match unambiguous sources, only #pragma omp parallel for num_threads(nthreads) for (long i=0; i<dim1; ++i) { // if (numMatched1[i] > 1) continue; bool inside_previous = false; bool inside_current = false; QVector<double> dummy; for (long j=0; j<dim2; ++j) { if (numMatched2[j] > 1) continue; // calc DEC offset and see if we are "within reach" double ddec = fabs(vec2.at(j)[0] - vec1.at(i)[0]); if (ddec < tolerance) inside_current = true; else inside_current = false; // Leave if we passed the plausible matching zone if (inside_previous && !inside_current) break; if (inside_current) { // distance between the two points (in [deg]) double distance = haversine(vec2.at(j)[1], vec1.at(i)[1], vec2.at(j)[0], vec1.at(i)[0]); if (distance < tolerance) { dummy << vec2.at(j)[0]; // DEC OBJ dummy << vec2.at(j)[1]; // RA OBJ for (int k=2; k<vec2.at(j).length(); ++k) { dummy << vec2.at(j)[k]; // MAG and MAGERR for reference sources } for (int k=2; k<vec1.at(i).length(); ++k) { dummy << vec1.at(i)[k]; // MAG and MAGERR for objects } #pragma omp critical { matched.append(dummy); } } } inside_previous = inside_current; } } omp_destroy_lock(&lock); }
31,923
C++
.cc
742
34.385445
166
0.561967
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,459
polygon.cc
schirmermischa_THELI/src/tools/polygon.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "polygon.h" #include <QVector> #include <QString> #include <QFile> #include <QTextStream> #include <QDebug> // Split a ds9 region POLYGON string into x- and y vertice arrays void polygon2vertices(QString polystring, QVector<float> &vertx, QVector<float> &verty) { // extract vertices polystring = polystring.split("(")[1].remove(")").simplified(); // split the polygon string into its vertices QStringList list = polystring.split(','); // number of vertices // int nvert = (polystring.count(',') + 1) / 2; // populate for (int i=0; i<list.length(); i+=2) { vertx.append(list[i].toFloat()); verty.append(list[i+1].toFloat()); } } void region2circle(QString circlestring, float &x, float &y, float &r) { // extract circle parameters Directory not found in Data class circlestring = circlestring.split('(')[1].remove(')').simplified(); // midpoint and the radius QStringList list = circlestring.split(','); x = list[0].toFloat(); y = list[1].toFloat(); r = list[2].toFloat(); } /* void addPolygon_bool(const long n, const long m, const QVector<float> &vertx, const QVector<float> &verty, const QString senseMode, QVector<bool> &mask) { float x, y; // apply the polygon mask // NOT THREADSAFE! // #pragma omp parallel for firstprivate(vertx, verty, senseMode) for (long j=0; j<m; ++j) { // we have to add +1 to compensate for arrays in C starting with 0 // because the polygon system starts with 1, not 0 y = (float) j + 1; for (long i=0; i<n; ++i) { x = (float) i + 1; // if a pixel is masked already (value = true) then it must remain masked no matter what. // that is, we only check whether still unmasked pixels need to be masked if (!mask.at(i+n*j)) { // test if the pixel is inside or outside the polygon bool polytest = pnpoly_T(vertx, verty, x, y); // Mask pixels inside or outside the polygon if (senseMode == "in") { // Pixels inside the polygon are good // pnpoly() returns 0 if a pixel is outside the polygon if (polytest == 0) { mask[i+n*j] = true; } } else { if (polytest == 1) { mask[i+n*j] = true; } } } } } } */ void addPolygon_bool(const long n, const long m, const QVector<float> &vertx, const QVector<float> &verty, const QString senseMode, QVector<bool> &mask) { // apply the polygon mask // NOT THREADSAFE! // #pragma omp parallel for firstprivate(vertx, verty, senseMode) for (long j=0; j<m; ++j) { // we have to add +1 to compensate for arrays in C starting with 0 // because the polygon system starts with 1, not 0 float y = (float) j + 1; for (long i=0; i<n; ++i) { float x = (float) i + 1; // if a pixel is masked already (value = true) then it must remain masked no matter what. // that is, we only check whether still unmasked pixels need to be masked // if (!mask.at(i+n*j)) { // test if the pixel is inside or outside the polygon bool polytest = pnpoly_T(vertx, verty, x, y); // Mask pixels inside or outside the polygon if (senseMode == "in") { // everything masked by default in the beginning // Pixels inside the polygon are good // pnpoly() returns 0 if a pixel is outside the polygon if (polytest == 1) { mask[i+n*j] = false; } } else { // everything unmasked by default in the beginning // Pixels outside the polygon are good if (polytest == 1) { // pixels inside the polygon must remain masked mask[i+n*j] = true; } } // } } } } void addPolygon_float(const long n, const long m, const QVector<float> &vertx, const QVector<float> &verty, QString senseMode, QVector<float> &weight) { // apply the polygon mask // NOT THREADSAFE //#pragma omp parallel for for (long j=0; j<m; ++j) { // we have to add +1 to compensate for arrays in C starting with 0 // because the polygon system starts with 1, not 0 float y = (float) j + 1; for (long i=0; i<n; ++i) { float x = (float) i + 1; // if a pixel has weight zero already then it must retain that weight no matter what. // that is, we check only pixels with weight > 0 if (weight[i+n*j] > 0.) { // test if the pixel is inside or outside the polygon bool polytest = pnpoly_T(vertx, verty, x, y); // Mask pixels inside or outside the polygon if (senseMode == "in") { // Pixels inside the polygon are bad // pnpoly() returns 0 if a pixel is outside the polygon if (polytest == 1) weight[i+n*j] = 0.; } else { if (polytest == 0) weight[i+n*j] = 0; } } } } } void addCircle_bool(const long n, const long m, float x, float y, float r, QString senseMode, QVector<bool> &mask) { // NOT THREADSAFE // #pragma omp parallel for for (long j=0; j<m; ++j) { float jj = (float) j; for (long i=0; i<n; ++i) { float ii = (float) i; // if a pixel is masked already (value = true) then it must remain masked no matter what. // that is, we only check whether still unmasked pixels need to be masked if (!mask[i+n*j]) { // Mask pixels inside or outside the circle float d = (ii-x) * (ii-x) + (jj-y) * (jj-y); if (senseMode == "in") { // mask pixels outside the circle if (d >= r*r) mask[i+n*j] = true; } else { // mask pixels inside the circle if (d <= r*r) mask[i+n*j] = true; } } } } } void addCircle_float(const long n, const long m, float x, float y, float r, QString senseMode, QVector<float> &weight) { // NOT THREADSAFE // #pragma omp parallel for for (long j=0; j<m; ++j) { float jj = (float) j; for (long i=0; i<n; ++i) { float ii = (float) i; // if a pixel has weight zero already then it must retain that weight no matter what. // that is, we check only pixels with weight > 0 if (weight[i+n*j] > 0.) { // Mask pixels inside or outside the circle float d = (ii-x) * (ii-x) + (jj-y) * (jj-y); if (senseMode == "in") { // mask pixels inside the circle if (d <= r*r) weight[i+n*j] = 0.; } else { // mask pixels inside the circle if (d >= r*r) weight[i+n*j] = 0.; } } } } } void addRegionFilesToMask(const long n, const long m, QString regionFile, QVector<bool> &mask, bool &isChipMasked) { QFile file(regionFile); if (!file.exists()) return; if ( !file.open(QIODevice::ReadOnly)) { qDebug() << "polygon::addRegionFilesToWeight: could not open "+regionFile; return; } isChipMasked = false; QString senseMode = "in"; QString combineMode = "or"; // not used QTextStream in(&(file)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; if (line.contains("# Sense: ")) { senseMode = line.split(":")[1].simplified(); if (senseMode == "in") mask.fill(true); // default, everything masked. Only keep pixels inside polygons and circles else mask.fill(false); // default, everything unmasked. Only keep pixels inside polygons and circles } // if (line.contains("# Combine: ")) combineMode = line.split(":")[1].simplified(); // There can be an arbitrary sequence of polygons and circles // The masks will be combined in the sense that a pixel will be masked if it is masked at least once. // Mask a polygon if (line.contains("polygon(") || line.contains("POLYGON(")) { QVector<float> vertx; QVector<float> verty; polygon2vertices(line, vertx, verty); addPolygon_bool(n, m, vertx, verty, senseMode, mask); isChipMasked = true; } // Mask a circle if (line.contains("circle(") || line.contains("CIRCLE(")) { float x = 0.; float y = 0.; float r = 0.; region2circle(line, x, y, r); addCircle_bool(n, m, x, y, r, senseMode, mask); isChipMasked = true; } } file.close(); } void addRegionFilesToWeight(const long n, const long m, QString regionFile, QVector<float> &weight) { QFile file(regionFile); if (!file.exists()) return; if ( !file.open(QIODevice::ReadOnly)) { qDebug() << "QDEBUG: polygon::addRegionFilesToWeight: could not open "+regionFile; return; } QString senseMode = "in"; QString combineMode = "or"; // not used QTextStream in(&(file)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; if (line.contains("# Sense: ")) senseMode = line.split(":")[1].simplified(); // if (line.contains("# Combine: ")) combineMode = line.split(":")[1].simplified(); // There can be an arbitrary sequence of polygons and circles // The masks will be combined in the sense that a pixel will be masked if it is masked at least once. // Mask a polygon if (line.contains("polygon(") || line.contains("POLYGON(")) { QVector<float> vertx; QVector<float> verty; polygon2vertices(line, vertx, verty); addPolygon_float(n, m, vertx, verty, senseMode, weight); } // Mask a circle if (line.contains("circle(") || line.contains("CIRCLE(")) { float x = 0.; float y = 0.; float r = 0.; region2circle(line, x, y, r); addCircle_float(n, m, x, y, r, senseMode, weight); } } file.close(); }
11,501
C++
.cc
273
32.509158
152
0.55891
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,460
imagequality.cc
schirmermischa_THELI/src/tools/imagequality.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imagequality.h" #include "../myimage/myimage.h" #include "../instrumentdata.h" #include "../processingInternal/data.h" #include "../tools/tools.h" #include "../functions.h" #include <QDebug> #include <QString> #include <QFile> ImageQuality::ImageQuality(const instrumentDataType *instrumentData, QString maindirname, QObject *parent) : QObject(parent), instData(instrumentData) { // instData = instrumentData; mainDirName = maindirname; } void ImageQuality::displayMessageReceived(QString message, QString type) { emit messageAvailable(message, type); } void ImageQuality::criticalReceived() { emit critical(); } bool ImageQuality::getSeeingFromGaia() { // Match GAIA point sources with detections in the image // refCat and sourceCat are populated externally in Controller::doImageQualityAnalysis() int dummy1; int dummy2; QVector<QVector<double>> matchedCat; int maxCPU = 1; // external parallelization match2D(sourceCat, refCat, matchedCat, matchingTolerance, dummy1, dummy2, maxCPU); if (matchedCat.isEmpty()) { emit messageAvailable(baseName + " : No usable reference point sources identified for IQ analysis.", "warning"); // emit messageAvailable(baseName + " : No usable reference point sources identified for IQ analysis. Using rh-mag method ...", "warning"); fwhm = -1.0; ellipticity = -1.0; numSources = 0; return false; } emit messageAvailable(baseName + " : Matched "+QString::number(matchedCat.length()) + " sources identified for IQ analysis.", "image"); QVector<double> fwhmVec; QVector<double> ellipticityVec; fwhmVec.reserve(matchedCat.length()); ellipticityVec.reserve(matchedCat.length()); for (auto &source : matchedCat) { fwhmVec << source[3]; // matched vector contains: RA, DEC, MAG, FWHM, ELL ellipticityVec << source[4]; } // fwhm = meanMask_T(fwhmVec, QVector<bool>()) * instData->pixscale; // ellipticity = meanMask_T(ellipticityVec, QVector<bool>()); fwhm = straightMedian_T(fwhmVec); ellipticity = straightMedian_T(ellipticityVec); numSources = fwhmVec.length(); return true; } bool ImageQuality::getSeeingFromRhMag() { return true; }
2,949
C++
.cc
75
35.973333
146
0.735829
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,461
detectedobject.cc
schirmermischa_THELI/src/tools/detectedobject.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // THELI internal source detection, (mostly) using the definitions and nomenclature from // https://sextractor.readthedocs.io/en/latest/index.html #include "detectedobject.h" #include <cmath> #include "functions.h" #include <QVector> #include "wcs.h" #include "wcshdr.h" // ======== WARNING ========================================== // // Image position parameters X, Y, XWIN and YWIN are zero-indexed // (must add +1 to be consistent with FITS convention) // // ============================================================== DetectedObject::DetectedObject(const QList<long> &objectIndices, const QVector<float> &data, const QVector<float> &background, const QVector<float> &weight, const QVector<bool> &_mask, bool weightinmemory, const long nax1, const long nax2, const long objid, const float satVal, const float gainval, wcsprm &wcsImage, QObject *parent) : QObject(parent), dataMeasure(data), dataBackground(background), dataWeight(weight), mask(_mask), weightInMemory(weightinmemory), wcs(wcsImage), saturationValue(0.98*satVal), // 98%: some margin against effective saturation, which might occur at slightly lower values already gain(gainval) // GAIN is 1.0 always as we convert ADU to electrons during HDU reformatting, already. Kept for clarity { area = objectIndices.length(); objID = objid; pixels_x.reserve(area); pixels_y.reserve(area); pixels_flux.reserve(area); pixels_back.reserve(area); pixels_weight.reserve(area); naxis1 = nax1; naxis2 = nax2; bitflags.resize(16); /* bit flags 0: at least 10% of object area is masked 1: object has been deblended (not implemented) 2: at least one pixel is saturated 3: the isophotal footprint of the detected object is truncated (too close to an image boundary) 4: the windowed footprint of the detected object is truncated (too close to an image boundary) 5: at least one photometric aperture has masked pixels or is truncated by the image boundary or has zero weight pixels 6: at least one pixel has zero weight 7: spurious or corrupted detection. Could be e.g. a bad column 8: */ // copy the pixel position and pixel value for all pixels comprising this object for (auto &index : objectIndices) { pixels_x.append(index % naxis1); pixels_y.append(index / naxis1); pixels_flux.append(data.at(index)); pixels_back.append(background.at(index)); if (weightInMemory) pixels_weight.append(weight.at(index)); else pixels_weight.append(1.0); } } DetectedObject::~DetectedObject() { remove(); } void DetectedObject::remove() { pixels_flux.clear(); pixels_back.clear(); pixels_weight.clear(); pixelsAper_back.clear(); pixelsAper_flux.clear(); pixelsAper_weight.clear(); pixelsWin_back.clear(); pixelsWin_flux.clear(); pixelsWin_weight.clear(); pixelsWin_x.clear(); pixelsWin_y.clear(); apertures.clear(); pixelsAper_x.clear(); pixelsAper_y.clear(); pixels_x.clear(); pixels_y.clear(); pixels_flux.squeeze(); pixels_back.squeeze(); pixels_weight.squeeze(); pixels_x.squeeze(); pixels_y.squeeze(); pixelsAper_back.squeeze(); pixelsAper_flux.squeeze(); pixelsAper_weight.squeeze(); pixelsWin_back.squeeze(); pixelsWin_flux.squeeze(); pixelsWin_weight.squeeze(); pixelsWin_x.squeeze(); pixelsWin_y.squeeze(); apertures.squeeze(); pixelsAper_x.squeeze(); pixelsAper_y.squeeze(); } void DetectedObject::computeObjectParams() { // Must be done in a specific order // ISOPHOTAL calcFlux(); calcMoments(); calcVariance(); calcEllipticity(); calcMomentsErrors(); calcApertureMagnitudes(); // WINDOWED calcFluxRadius(); calcFWHM(); calcMagAuto(); calcWindowedMoments(); calcWindowedEllipticity(); calcWindowedMomentsErrors(); filterSpuriousDetections(); // Applied only when writing catalogs to disk for scamp // correctOriginOffset(); calcSkyCoords(); } void DetectedObject::calcFlux() { if (badDetection) return; FLUX_ISO = std::accumulate(pixels_flux.begin(), pixels_flux.end(), .0); if (FLUX_ISO < 0.) { bitflags.setBit(7,true); badDetection = true; return; } MAG_ISO = -2.5*log10(FLUX_ISO) + ZP; } QVector<double> DetectedObject::calcFluxAper(float aperture) { // get aperture pixels long xminAper = floor(X-0.5*aperture); long xmaxAper = ceil(X+0.5*aperture); long yminAper = floor(Y-0.5*aperture); long ymaxAper = ceil(Y+0.5*aperture); // Check truncation by image frame if (isTruncated(xminAper, xmaxAper, yminAper, ymaxAper)) bitflags.setBit(5,true); // Truncate if necessary xminAper = xminAper < 0 ? 0 : xminAper; xmaxAper = xmaxAper >=naxis1 ? naxis1-1 : xmaxAper; yminAper = yminAper < 0 ? 0 : yminAper; ymaxAper = ymaxAper >=naxis2 ? naxis2-1 : ymaxAper; long npixAper = (xmaxAper-xminAper+1) * (ymaxAper-yminAper+1); pixelsAper_flux.resize(npixAper); pixelsAper_back.resize(npixAper); pixelsAper_weight.fill(1.0, npixAper); // fill vector with dummy weight (if weight map is not available, e.g. during background object masking) pixelsAper_x.resize(npixAper); pixelsAper_y.resize(npixAper); long k = 0; for (long j=yminAper; j<=ymaxAper; ++j) { for (long i=xminAper; i<=xmaxAper; ++i) { pixelsAper_flux[k] = dataMeasure.at(i+naxis1*j); pixelsAper_back[k] = dataBackground.at(i+naxis1*j); if (weightInMemory) pixelsAper_weight[k] = dataWeight.at(i+naxis1*j); // update weight if weight map is available pixelsAper_x[k] = i; pixelsAper_y[k] = j; ++k; } } // We use a 4 times sub-sampled grid for finer resolution for compact objects smaller than 10 pixels int s = 0; if (XMAX-XMIN <= 10 && YMAX - YMIN <= 10) s = 4; else s = 1; // The measurement window is defined by the aperture long nn = (xmaxAper-xminAper+1) * s; long mm = (ymaxAper-yminAper+1) * s; QVector<double> dataSub(nn*mm, 0); QVector<double> backSub(nn*mm, 0); QVector<double> weightSub(nn*mm, 0); // Subsample the original pixel data. The window is the minimum rectangular envelope long dim = pixelsAper_flux.length(); for (long k=0; k<dim; ++k) { double flux = pixelsAper_flux.at(k); double back = pixelsAper_back.at(k); double weight = pixelsAper_weight.at(k); double spx = s*(pixelsAper_x.at(k)-xminAper); double spy = s*(pixelsAper_y.at(k)-yminAper); for (int ss1=0; ss1<s; ++ss1) { long jj = spy + ss1; for (int ss2=0; ss2<s; ++ss2) { long ii = spx + ss2; dataSub[ii+nn*jj] = flux; backSub[ii+nn*jj] = back; weightSub[ii+nn*jj] = weight; } } } // The object centroid in the subsampled coordinate system double xcen = (X-xminAper) * double(s); double ycen = (Y-yminAper) * double(s); double fluxAper = 0.; double fluxErrAper = 0.; for (long j=0; j<=ycen*2; ++j) { double jj = double(j); for (long i=0; i<=xcen*2; ++i) { double ii = double(i); if (ii<0 || ii>=nn || jj<0 || jj>=mm) continue; double rsq = (xcen-ii)*(xcen-ii) + (ycen-jj)*(ycen-jj); if (rsq <= 0.25*aperture*aperture*s*s) { fluxAper += dataSub[ii+nn*jj]; fluxErrAper += backSub[ii+nn*jj]/gain + dataSub[ii+nn*jj]/gain; if (weightSub[ii+nn*jj] == 0.) bitflags.setBit(5,true); if (dataSub[ii+nn*jj] > saturationValue) bitflags.setBit(2,true); dataSub[ii+nn*jj] = 0.; // just making sure we don't count a pixel twice } } } // correct for subsampling of aperture fluxAper = fluxAper / (s*s); fluxErrAper = fluxErrAper / (s*s); fluxErrAper = sqrt(fluxErrAper); double magAper = -2.5*log10(fluxAper) + ZP; double magErrAper = 99.; if (fluxAper > 0.) magErrAper = 2.5*log10(1.+fluxErrAper/fluxAper); QVector<double> result; result << fluxAper << fluxErrAper << magAper << magErrAper; if ((fluxAper < 0. || std::isnan(magErrAper))) { bitflags.setBit(7,true); badDetection = true; } return result; } void DetectedObject::calcApertureMagnitudes() { if (badDetection) return; if (apertures.isEmpty()) return; FLUX_APER.reserve(apertures.length()); MAG_APER.reserve(apertures.length()); FLUXERR_APER.reserve(apertures.length()); MAGERR_APER.reserve(apertures.length()); QVector<double> result; for (auto &aperture : apertures) { result = calcFluxAper(aperture); FLUX_APER.append(result[0]); FLUXERR_APER.append(result[1]); MAG_APER.append(result[2]); MAGERR_APER.append(result[3]); } } void DetectedObject::calcMoments() { if (badDetection) return; double xsum = 0.; double ysum = 0.; double xxsum = 0.; double yysum = 0.; double xysum = 0.; double xysumsq = 0.; for (long i=0; i<area; ++i) { double pi = pixels_flux.at(i); double px = pixels_x.at(i); double py = pixels_y.at(i); if (pi >= saturationValue) bitflags.setBit(2,true); if (pixels_weight.at(i) == 0.) bitflags.setBit(6,true); xsum += px*pi; ysum += py*pi; xxsum += px*px*pi; yysum += py*py*pi; xysum += px*py*pi; xysumsq += px*px*py*py*pi; } X = xsum / FLUX_ISO; Y = ysum / FLUX_ISO; if (X < 0. || X > naxis1 || Y < 0. || Y > naxis2) { bitflags.setBit(7,true); badDetection = true; return; } X2 = xxsum / FLUX_ISO - X*X; Y2 = yysum / FLUX_ISO - Y*Y; XY = xysum / FLUX_ISO - X*Y; X2Y2 = xysumsq / FLUX_ISO - X*X*Y*Y; // Handling of infinitely thin objects (pathological cases, such as bad columns) double rho = 1/12.; if (X2*Y2 - XY*XY < rho*rho) { bitflags.setBit(7,true); badDetection = true; return; } XMIN = minVec_T(pixels_x); XMAX = maxVec_T(pixels_x); YMIN = minVec_T(pixels_y); YMAX = maxVec_T(pixels_y); double s1 = (X2+Y2) / 2.; double s2 = sqrt((X2-Y2) * (X2-Y2) / 4. + XY*XY); if (s1<s2) { bitflags.setBit(7,true); badDetection = true; } } // weighted variance // https://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weighvar.pdf void DetectedObject::calcVariance() { if (badDetection) return; if (area>1) { double xsum = 0.; double ysum = 0.; double psum = 0.; double n_nonzero = 0; for (long i=0; i<area; ++i) { double pi = pixels_flux.at(i); double px = pixels_x.at(i); double py = pixels_y.at(i); xsum += pi*pow(px - X,2); ysum += pi*pow(py - Y,2); if (pi!= 0.) ++n_nonzero; psum += pi; } XVAR = xsum / ( (n_nonzero-1.) / n_nonzero * psum); YVAR = ysum / ( (n_nonzero-1.) / n_nonzero * psum); } else { XVAR = 1.; YVAR = 1.; } } void DetectedObject::calcWindowedMoments() { if (badDetection) return; getWindowedPixels(); XWIN = X; YWIN = Y; if (FLUX_RADIUS>10.) return; // Windowed parameters useful for small objects, only double dsq = 4.*FLUX_RADIUS*FLUX_RADIUS / (8.*log(2.)); double rmaxsq = 4.*FLUX_RADIUS*FLUX_RADIUS; double eps = 2e-4; long iter = 0; long iterMax = 10; // verified that this converges indeed within less than 10 iterations, even for oddities like cosmics double diff = 1.; // Iterate to obtain first moments while (iter < iterMax && diff > eps) { double xwsum = 0.; double ywsum = 0.; double wsum = 0.; double XWIN0 = XWIN; double YWIN0 = YWIN; long i=0; for (auto &pixel : pixelsWin_flux) { double rsq = pow((pixelsWin_x.at(i) - XWIN0),2.) + pow((pixelsWin_y.at(i) - YWIN0),2.); if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xwsum += w*pixel*(pixelsWin_x.at(i)-XWIN0); ywsum += w*pixel*(pixelsWin_y.at(i)-YWIN0); wsum += w*pixel; } ++i; } XWIN = XWIN0 + 2.*xwsum/wsum; // didn't have the prefactor 2, but doesn't seem to make a difference; probably faster conversion like this YWIN = YWIN0 + 2.*xwsum/wsum; diff = sqrt( pow(XWIN-XWIN0,2) + pow(YWIN-YWIN0,2)); ++iter; } if (XWIN < 0. || XWIN > naxis1 || YWIN < 0. || YWIN > naxis2) { bitflags.setBit(7,true); badDetection = true; return; } // Second moments double xxwsum = 0.; double yywsum = 0.; double xywsum = 0.; double wsum = 0.; long i=0; for (auto &pixel : pixelsWin_flux) { double px = pixelsWin_x.at(i); double py = pixelsWin_y.at(i); double rsq = pow((px - XWIN),2.) + pow((py - YWIN),2.); if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xxwsum += w*pixel*(px-XWIN)*(px-XWIN); yywsum += w*pixel*(py-YWIN)*(py-YWIN); xywsum += w*pixel*(px-XWIN)*(py-YWIN); wsum += w*pixel; } ++i; } X2WIN = xxwsum / wsum; Y2WIN = yywsum / wsum; XYWIN = xywsum / wsum; } void DetectedObject::calcMomentsErrors() { if (badDetection) return; double xsum = 0.; double ysum = 0.; double xysum = 0.; double psum = 0.; for (long i=0; i<area; ++i) { double pi = pixels_flux.at(i); double px = pixels_x.at(i); double py = pixels_y.at(i); double sisq = sigma_back*sigma_back + pi / gain; xsum += sisq*(px-X)*(px-X); ysum += sisq*(py-Y)*(py-Y); xysum += sisq*(px-X)*(py-Y); psum += pi; } ERRX2 = xsum / (psum*psum); ERRY2 = ysum / (psum*psum); ERRXY = xysum / (psum*psum); ERRA = 0.5*(ERRX2+ERRY2) + sqrt( 0.25*(ERRX2-ERRY2)*(ERRX2-ERRY2) + ERRXY*ERRXY); ERRB = 0.5*(ERRX2+ERRY2) - sqrt( 0.25*(ERRX2-ERRY2)*(ERRX2-ERRY2) + ERRXY*ERRXY); ERRA = sqrt(ERRA); ERRB = sqrt(ERRB); ERRTHETA = 2.*ERRXY / (ERRX2-ERRY2); ERRTHETA = fabs(0.5*atan(ERRTHETA)/rad); // noise floor if (ERRTHETA < 0.01) ERRTHETA = 0.01; } void DetectedObject::calcWindowedMomentsErrors() { if (badDetection) return; if (FLUX_RADIUS>10.) return; // Windowed parameters useful for small objects, only double dsq = 4.*FLUX_RADIUS*FLUX_RADIUS / (8.*log(2.)); double rmaxsq = 4.*FLUX_RADIUS*FLUX_RADIUS; double xwsum = 0.; double ywsum = 0.; double xywsum = 0.; double wsum = 0.; long i=0; for (auto &pixel : pixelsWin_flux) { double px = pixelsWin_x.at(i); double py = pixelsWin_y.at(i); double rsq = pow((px - XWIN),2.) + pow((py - YWIN),2.); double sisq = sigma_back*sigma_back + pixel / gain; // I think this is wrong, should divide sigma_back by gain, too! if (rsq < rmaxsq) { double w = exp(-rsq / (2.*dsq)); xwsum += w*w*sisq*(px-XWIN)*(px-XWIN); ywsum += w*w*sisq*(py-YWIN)*(py-YWIN); xywsum += w*w*sisq*(px-XWIN)*(py-YWIN); wsum += w*w*pixel*pixel; } ++i; } if (wsum > 0.) { ERRX2WIN = 4.*xwsum/wsum; ERRY2WIN = 4.*ywsum/wsum; ERRXYWIN = 4.*xywsum/wsum; ERRAWIN = 0.5*(ERRX2WIN+ERRY2WIN) + sqrt( 0.25*(ERRX2WIN-ERRY2WIN)*(ERRX2WIN-ERRY2WIN) + ERRXYWIN*ERRXYWIN); ERRBWIN = 0.5*(ERRX2WIN+ERRY2WIN) - sqrt( 0.25*(ERRX2WIN-ERRY2WIN)*(ERRX2WIN-ERRY2WIN) + ERRXYWIN*ERRXYWIN); ERRAWIN = sqrt(ERRAWIN); ERRBWIN = sqrt(ERRBWIN); ERRTHETAWIN = 2.*ERRXYWIN / (ERRX2WIN-ERRY2WIN); ERRTHETAWIN = fabs(0.5*atan(ERRTHETAWIN)/rad); } else { ERRX2WIN = 0.; ERRY2WIN = 0.; ERRXYWIN = 0.; ERRAWIN = 0.; ERRBWIN = 0.; ERRTHETAWIN = 0.; bitflags.setBit(7,true); badDetection = true; } // noise floor if (ERRTHETAWIN < 0.01) ERRTHETAWIN = 0.01; } void DetectedObject::calcSkyCoords() { if (badDetection) return; double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; // CAREFUL! wcslib starts pixels counting at 1, hence must add +1 to zero-indexed C++ vectors pixcrd[0] = XWIN + 1.; pixcrd[1] = YWIN + 1.; int stat[1]; wcsp2s(&wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); ALPHA_J2000 = world[0]; DELTA_J2000 = world[1]; } void DetectedObject::calcEllipticity() { // if (badDetection) return; if (XY == 0. || X2 == Y2) THETA = 0.; else { THETA = atan(2.*XY / (X2-Y2)) / 2. / rad; // THETA should have the same sign as XY if ( (THETA<0 && XY>0) || (THETA>0 && XY<0)) THETA *= -1.; } double s1 = (X2+Y2) / 2.; double s2 = sqrt((X2-Y2) * (X2-Y2) / 4. + XY*XY); if (s1<s2) { bitflags.setBit(7,true); badDetection = true; // return; } A = sqrt(s1+s2); B = sqrt(s1-s2); XERR = sqrt( pow(A*cos(THETA*rad), 2) + pow(B*sin(THETA*rad), 2)); YERR = sqrt( pow(A*sin(THETA*rad), 2) + pow(B*cos(THETA*rad), 2)); // This is what the printed source extractor documentation says (v. 2.13), but not the online doc https://sextractor.readthedocs.io/ (The latter seems wrong) CXX = Y2 / s2; CYY = X2 / s2; CXY = -2. * XY / s2; ELLIPTICITY = 1. - B/A; } void DetectedObject::calcWindowedEllipticity() { if (badDetection) return; if (XYWIN == 0. || X2WIN == Y2WIN) THETAWIN = 0.; else { THETAWIN = atan(2.*XYWIN / (X2WIN-Y2WIN)) / 2. / rad; // THETA should have the same sign as XY if ( (THETAWIN<0 && XYWIN>0) || (THETAWIN>0 && XYWIN<0)) THETAWIN *= -1.; } double s1 = (X2WIN+Y2WIN) / 2.; double s2 = sqrt((X2WIN-Y2WIN) * (X2WIN-Y2WIN) / 4. + XYWIN*XYWIN); if (s1<s2) { bitflags.setBit(7,true); badDetection = true; return; } AWIN = sqrt(s1+s2); BWIN = sqrt(s1-s2); XWINERR = sqrt( pow(AWIN*cos(THETAWIN*rad), 2) + pow(BWIN*sin(THETAWIN*rad), 2)); YWINERR = sqrt( pow(AWIN*sin(THETAWIN*rad), 2) + pow(BWIN*cos(THETAWIN*rad), 2)); CXXWIN = Y2WIN / s2; CYYWIN = X2WIN / s2; CXYWIN = -2.*XYWIN / s2; } void DetectedObject::calcFluxRadius() { if (badDetection) return; if (FLUX_ISO == 0.) return; // We use a 5 times sub-sampled grid for finer resolution // for compact objects smaller than 10 pixels, and 3 times sub-sampled if smaller than 20 pixels int s = 0; if (XMAX-XMIN <= 10 && YMAX - YMIN <= 10) s = 5; else if (XMAX-XMIN <= 20 && YMAX - YMIN <= 20) s = 3; else if (XMAX-XMIN>100 || YMAX-YMIN > 100) { // don't calculate flux radius for very large objects (algorithm is very inefficient) FLUX_RADIUS = sqrt((XMAX-XMIN)*(XMAX-XMIN) + (YMAX-YMIN)*(YMAX-YMIN)); return; } else s = 1; long nn = (XMAX-XMIN+1) * s; long mm = (YMAX-YMIN+1) * s; QVector<double> dataSub(nn*mm, 0); // Subsample the original pixel data. The window is the minimum rectangular envelope for (long k=0; k<area; ++k) { double flux = pixels_flux[k]; double spx = s*(pixels_x[k]-XMIN); double spy = s*(pixels_y[k]-YMIN); for (int ss1=0; ss1<s; ++ss1) { long jj = spy + ss1; for (int ss2=0; ss2<s; ++ss2) { long ii = spx + ss2; dataSub[ii+nn*jj] = flux; } } } // The object centroid in the subsampled coordinate system double xcen = (X-XMIN) * double(s); double ycen = (Y-YMIN) * double(s); // Integrate outwards until we reach 50% of the total flux // Really inefficient, because we do the same calculations again and again. double fluxInt = 0.; double step = 1.; double maxStep = sqrt(nn*nn+mm*mm) / 2.; // to avoid runaway loop (pathological cases, not that I know what that would be) /* while (fluxInt < 0.5*flux*s*s && step < maxStep) { double r = step; fluxInt = 0.; for (long jj=0; jj<mm; ++jj) { double dy2 = (ycen - jj)*(ycen-jj); for (long ii=0; ii<nn; ++ii) { double dx2 = (xcen - ii)*(xcen-ii); if (dx2+dy2 <= r*r) fluxInt += dataSub[ii+nn*jj]; } } FLUX_RADIUS = r; ++step; } */ FLUX_RADIUS = 0.; long ixcen = long(xcen); long iycen = long(ycen); double flux_previous = 0.; double flux_current = 0.; while (fluxInt < 0.5*FLUX_ISO*s*s && step < maxStep) { // from the centroid, stepping outside in quadratic "rings" flux_previous = flux_current; for (long jj=iycen-step; jj<=iycen+step; ++jj) { for (long ii=ixcen-step; ii<=ixcen+step; ++ii) { if (jj == iycen-step || jj == iycen+step || ii == ixcen-step || ii == ixcen+step) { // running along horizontal border if (ii<0 || ii>=nn || jj<0 || jj>=mm) continue; fluxInt += dataSub[ii+nn*jj]; dataSub[ii+nn*jj] = 0.; // making sure we don't count a pixel twice } } } flux_current = fluxInt; FLUX_RADIUS = step; ++step; } FLUX_RADIUS /= double(s); // Interpolate 0.1 pixel step size double intp = (0.5-flux_previous) / (flux_current - 0.5) / s; FLUX_RADIUS += intp; } void DetectedObject::calcFWHM() { // FWHM = 1.995*FLUX_RADIUS; // For a theoretical 2D gaussian FWHM = 2.355*sqrt(XVAR+YVAR); } void DetectedObject::getWindowedPixels() { if (badDetection) return; long xminWin = floor(X-2.*FLUX_RADIUS); long xmaxWin = ceil(X+2.*FLUX_RADIUS); long yminWin = floor(Y-2.*FLUX_RADIUS); long ymaxWin = ceil(Y+2.*FLUX_RADIUS); // Check truncation by image frame if (isTruncated(xminWin, xmaxWin, yminWin, ymaxWin)) bitflags.setBit(4,true); // Truncate if necessary xminWin = xminWin < 0 ? 0 : xminWin; xmaxWin = xmaxWin >=naxis1 ? naxis1-1 : xmaxWin; yminWin = yminWin < 0 ? 0 : yminWin; ymaxWin = ymaxWin >=naxis2 ? naxis2-1 : ymaxWin; long npixWin = (xmaxWin-xminWin+1) * (ymaxWin-yminWin+1); pixelsWin_flux.reserve(npixWin); pixelsWin_x.reserve(npixWin); pixelsWin_y.reserve(npixWin); for (long j=yminWin; j<=ymaxWin; ++j) { double jj = double(j); for (long i=xminWin; i<=xmaxWin; ++i) { double ii = double(i); double rsq = (X-ii)*(X-ii) + (Y-jj)*(Y-jj); if (rsq <= 4.*FLUX_RADIUS*FLUX_RADIUS) { if (weightInMemory && dataWeight.at(i+naxis1*j) == 0.) { bitflags.setBit(6,true); continue; } pixelsWin_flux.append(dataMeasure.at(i+naxis1*j)); pixelsWin_x.append(i); pixelsWin_y.append(j); } } } } bool DetectedObject::isTruncated(const long xmin, const long xmax, const long ymin, const long ymax) { bool truncation = false; if (xmin < 0) truncation = true; if (ymin < 0) truncation = true; if (xmax >= naxis1) truncation = true; if (ymax >= naxis2) truncation = true; return truncation; } void DetectedObject::calcMagAuto() { if (badDetection) return; // TODO: check that this parameterisation actually encompasses 6 times the best fit isophote long imin = floor(X - 6.*A); long imax = ceil(X + 6.*A); long jmin = floor(Y - 6.*A); long jmax = ceil(Y + 6.*A); imin = imin < 0 ? 0 : imin; imax = imax >=naxis1 ? naxis1-1 : imax; jmin = jmin < 0 ? 0 : jmin; jmax = jmax >=naxis2 ? naxis2-1 : jmax; // Loop over the rectangular subset of pixels that encompass the object double rkron = 0.; double fsum = 0.; for (long j=jmin; j<=jmax; ++j) { float dy = j - Y; for (long i=imin; i<=imax; ++i) { float dx = i - X; // Work on pixels within 6x the ellipse double rsq = CXX*dx*dx + CYY*dy*dy + CXY*dx*dy; if (rsq <= 36.*A*A) { rkron += sqrt(rsq) * dataMeasure.at(i+naxis1*j); fsum += dataMeasure.at(i+naxis1*j); } } } /* debugging // objects close to the detection limit may not fulfil the "rsq <= 36.*A*A" requirement if (fsum == 0.) { for (long j=jmin; j<=jmax; ++j) { float dy = j - Y; for (long i=imin; i<=imax; ++i) { float dx = i - X; double rsq = CXX*dx*dx + CYY*dy*dy + CXY*dx*dy; qDebug() << i << j << dx << dy << CXX << CYY << CXY << rsq << 36.*A*A << dataMeasure.at(i+naxis1*j); } } } */ if (fsum == 0.) rkron = 3.5; else rkron /= fsum; // enforce a minimum radius of 3.5 pixels for noisy objects rkron = rkron < 3.5 ? 3.5 : rkron; double auto_radius = 2.5*rkron; imin = floor(X - auto_radius); imax = ceil(X + auto_radius); jmin = floor(Y - auto_radius); jmax = ceil(Y + auto_radius); imin = imin < 0 ? 0 : int(imin); imax = imax >=naxis1 ? naxis1-1 : int(imax); jmin = jmin < 0 ? 0 : int(jmin); jmax = jmax >=naxis2 ? naxis2-1 : int(jmax); if (isTruncated(imin, imax, jmin, jmax)) bitflags.setBit(3,true); FLUX_AUTO = 0; FLUXERR_AUTO = 0; float numMasked = 0.; float numTot = 0.; for (long j=jmin; j<=jmax; ++j) { float dy = Y - j; for (long i=imin; i<=imax; ++i) { float dx = X - i; // Work on pixels within auto_radius if (dx*dx + dy*dy < auto_radius*auto_radius) { if (weightInMemory && dataWeight.at(i+naxis1*j) == 0.) bitflags.setBit(6,true); // With global mask if (globalMaskAvailable) { if (!mask.at(i+naxis1*j)) { FLUX_AUTO += dataMeasure.at(i+naxis1*j); FLUXERR_AUTO += dataBackground.at(i+naxis1*j)/gain + dataMeasure.at(i+naxis1*j)/gain; // neglecting readout noise } else { ++numMasked; } } // without global mask else { FLUX_AUTO += dataMeasure.at(i+naxis1*j); FLUXERR_AUTO += dataBackground.at(i+naxis1*j)/gain + dataMeasure.at(i+naxis1*j)/gain; // neglecting readout noise } ++numTot; } } } if (FLUX_AUTO < 0.) { bitflags.setBit(7,true); badDetection = true; MAGERR_AUTO = 99.; MAG_AUTO = 99.; FLUXERR_AUTO = 0.; } else { FLUXERR_AUTO = sqrt(FLUXERR_AUTO); MAG_AUTO = -2.5*log10(FLUX_AUTO) + ZP; MAGERR_AUTO = 2.5*log10(1.+FLUXERR_AUTO/FLUX_AUTO); } if (numMasked / numTot > 0.1) bitflags.setBit(1,true); } void DetectedObject::filterSpuriousDetections() { if (std::isnan(XWIN) || std::isnan(YWIN) || std::isnan(AWIN) || std::isnan(BWIN) || std::isnan(ERRAWIN) || std::isnan(ERRBWIN) || std::isnan(ERRTHETAWIN) || std::isnan(FLUX_RADIUS) || XWIN < 1. || YWIN < 1. || XWIN > naxis1-1 || YWIN > naxis2-1 || (AWIN==0 && BWIN==0)) { bitflags.setBit(7,true); badDetection = true; } FLAGS = 0; for (int i=0; i<bitflags.size(); ++i) { if (bitflags.testBit(i)) FLAGS += pow(2,i); } // qDebug() << X << XWIN << Y << YWIN << AWIN << BWIN << ERRAWIN << ERRBWIN << ERRTHETAWIN << FLUX_RADIUS << ERRX2WIN << ERRY2WIN << ERRXYWIN << badDetection; } // In C++, arrays start counting a 0. // However, for object detection in FITS images, we start counting at 1. // Verified by comparing with Source Extractor positions // UNUSED. Offset applied when writing source catalogs to disk for scamp void DetectedObject::correctOriginOffset() { X += 1.; Y += 1.; XWIN += 1.; YWIN += 1.; }
29,881
C++
.cc
813
29.087331
169
0.570047
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,462
fileprogresscounter.cc
schirmermischa_THELI/src/tools/fileprogresscounter.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "fileprogresscounter.h" #include <QDir> #include <QString> #include <QDebug> FileProgressCounter::FileProgressCounter(QString dirname, QString filter, int numtotimages, float *progressDep, QObject *parent) : QObject(parent) { dir.setPath(dirname); filterList << filter; numTotImages = numtotimages; timer = new QTimer(this); progress = progressDep; } FileProgressCounter::FileProgressCounter(QString dirname, long finalsize, float *progressDep, QObject *parent) : QObject(parent) { dirName = dirname; timer = new QTimer(this); finalSize = finalsize; progress = progressDep; } void FileProgressCounter::numberFileProgress() { int numImages = dir.entryList(filterList).length(); *progress = 100. * float(numImages) / float(numTotImages); // emit progressUpdate(progress); } void FileProgressCounter::sizeFileProgress() { fi.setFile(dirName+"/coadd.fits"); long currentSize = fi.size(); *progress = 100. * float(currentSize) / float(finalSize); // emit progressUpdate(progress); } void FileProgressCounter::stopFileProgressTimerReceived() { timer->stop(); }
1,902
C++
.cc
52
32.5
95
0.736928
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,463
fitgauss1d.cc
schirmermischa_THELI/src/tools/fitgauss1d.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "fitgauss1d.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <QDebug> #include <QVector> // A Levenberg-Markquardt solver with geodesic acceleration, see e.g. // https://www.gnu.org/software/gsl/doc/html/nls.html#examples // WARNING: for some reason this does not work. It returns the initial values, only! // UNUSED, kept for reference // model function: a * exp( -1/2 * [ (t - b) / c ]^2 ) double gaussian(const double a, const double b, const double c, const double t) { const double z = (t - b) / c; return (a * exp(-0.5 * z * z)); } int func_f (const gsl_vector *x, void *params, gsl_vector *f) { // long n = ((struct fitData *)params)->n; double *xdata = ((struct fitData *)params)->t; double *ydata = ((struct fitData *)params)->y; struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); for (long i=0; i<d->n; ++i) { double ti = xdata[i]; double yi = ydata[i]; double y = gaussian(a, b, c, ti); gsl_vector_set(f, i, yi - y); } return GSL_SUCCESS; } int func_df (const gsl_vector *x, void *params, gsl_matrix *J) { struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); for (long i=0; i<d->n; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); gsl_matrix_set(J, i, 0, -ei); gsl_matrix_set(J, i, 1, -(a / c) * ei * zi); gsl_matrix_set(J, i, 2, -(a / c) * ei * zi * zi); } return GSL_SUCCESS; } int func_fvv (const gsl_vector *x, const gsl_vector *v, void *params, gsl_vector *fvv) { struct fitData *d = (struct fitData*) params; double a = gsl_vector_get(x, 0); double b = gsl_vector_get(x, 1); double c = gsl_vector_get(x, 2); double va = gsl_vector_get(v, 0); double vb = gsl_vector_get(v, 1); double vc = gsl_vector_get(v, 2); for (long i=0; i<d->n; ++i) { double ti = d->t[i]; double zi = (ti - b) / c; double ei = exp(-0.5 * zi * zi); double Dab = -zi * ei / c; double Dac = -zi * zi * ei / c; double Dbb = a * ei / (c * c) * (1.0 - zi*zi); double Dbc = a * zi * ei / (c * c) * (2.0 - zi*zi); double Dcc = a * zi * zi * ei / (c * c) * (3.0 - zi*zi); double sum; sum = 2.0 * va * vb * Dab + 2.0 * va * vc * Dac + vb * vb * Dbb + 2.0 * vb * vc * Dbc + vc * vc * Dcc; gsl_vector_set(fvv, i, sum); } return GSL_SUCCESS; } void solve_system(gsl_vector *x, gsl_multifit_nlinear_fdf *fdf, gsl_multifit_nlinear_parameters *params) { const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; const size_t max_iter = 200; const double xtol = 1.0e-8; const double gtol = 1.0e-8; const double ftol = 1.0e-8; const size_t n = fdf->n; const size_t p = fdf->p; gsl_multifit_nlinear_workspace *work = gsl_multifit_nlinear_alloc(T, params, n, p); gsl_vector * f = gsl_multifit_nlinear_residual(work); gsl_vector * y = gsl_multifit_nlinear_position(work); int info; double chisq0, chisq, rcond; // initialize solver gsl_multifit_nlinear_init(x, fdf, work); // store initial cost gsl_blas_ddot(f, f, &chisq0); // iterate until convergence gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol, NULL, NULL, &info, work); // store final cost gsl_blas_ddot(f, f, &chisq); // store cond(J(x)) gsl_multifit_nlinear_rcond(&rcond, work); gsl_vector_memcpy(x, y); gsl_multifit_nlinear_free(work); }
4,597
C++
.cc
121
33.115702
104
0.618619
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,464
displayconfig.cc
schirmermischa_THELI/src/processingInternal/displayconfig.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../dockwidgets/confdockwidget.h" #include "../dockwidgets/monitor.h" #include "ui_confdockwidget.h" #include <QString> void Controller::populateCommentMap() { commentMap.clear(); commentMap.insert("HDUreformat", "HDU reformatting"); commentMap.insert("Processbias", "Processing biases in"); commentMap.insert("Processdark", "Processing darks in"); commentMap.insert("Processflatoff", "Processing flat off/darks in"); commentMap.insert("Processflat", "Processing flats in"); commentMap.insert("Processscience", "Debiasing and flatfielding data in"); commentMap.insert("Chopnod", "Doing chopnod background correction for"); commentMap.insert("Background", "Applying background model to"); commentMap.insert("Collapse", "Applying collapse correction to"); commentMap.insert("Binnedpreview", "Creating binned previews for"); commentMap.insert("Globalweight", "Creating global weights for"); commentMap.insert("Individualweight", "Creating individual weights for"); commentMap.insert("Separate", "Separating different targes in"); commentMap.insert("Absphotindirect", "Performing indirect absolute photometry"); commentMap.insert("Createsourcecat", "Creating source catalogs for"); commentMap.insert("GetCatalogFromWEB", "Downloading astrometric reference catalog for"); commentMap.insert("GetCatalogFromIMAGE", "Extracting astrometric reference catalog for"); commentMap.insert("Astromphotom", "Calculating astrometric solution for"); commentMap.insert("Resolvetarget", "Resolving target coordinates for"); commentMap.insert("RestoreHeader", "Restoring original astrometry in images for"); commentMap.insert("CopyZeroOrder", "Updating images with 0th order WCS solution for"); commentMap.insert("ImageQuality", "Analyzing image quality for"); commentMap.insert("SkysubModel", "Subtracting the sky for"); commentMap.insert("SkysubConst", "Subtracting the sky for"); commentMap.insert("SkysubPoly", "Subtracting the sky for"); commentMap.insert("Coaddition", "Performing coaddition for"); commentMap.insert("CoaddSmoothWeights", "Smoothing edges in weight maps for"); commentMap.insert("CoaddPrepare", "Preparing coaddition for"); commentMap.insert("CoaddResample", "Resampling images for"); commentMap.insert("CoaddSwarpFilter", "Outlier filtering for"); commentMap.insert("CoaddCoadd", "Coaddition images for"); commentMap.insert("CoaddUpdate", "Updating header of coadd.fits for"); } void Controller::pushConfigHDUreformat() { QString config; config = "<tt>"; config += "Overscan correction = "+ boolToString(cdw->ui->overscanCheckBox->isChecked()) + "<br>"; config += "Overscan method = "+ cdw->ui->overscanMethodComboBox->currentText() + "<br>"; config += "Nonlinearity correction = "+ boolToString(cdw->ui->nonlinearityCheckBox->isChecked()) + "<br>"; config += "Point crosstalk correction = "+ boolToString(cdw->ui->normalxtalkCheckBox->isChecked()) + "<br>"; config += "Point crosstalk amplitude = "+ cdw->ui->normalxtalkAmplitudeLineEdit->text() + "<br>"; config += "Row crosstalk correction = "+ boolToString(cdw->ui->rowxtalkCheckBox->isChecked()) + "<br>"; config += "Row crosstalk amplitude = "+ cdw->ui->rowxtalkAmplitudeLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessbias() { QString config; config = "<tt>"; config += "Number of low rejected pixels / stack = " + cdw->ui->biasNlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels / stack = " + cdw->ui->biasNhighLineEdit->text() + "<br>"; config += "Min mode allowed [e-] = " + cdw->ui->biasMinLineEdit->text() + "<br>"; config += "Max mode allowed [e-] = " + cdw->ui->biasMaxLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessdark() { QString config; config = "<tt>"; config += "Number of low rejected pixels / stack = " + cdw->ui->darkNlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels / stack = " + cdw->ui->darkNhighLineEdit->text() + "<br>"; config += "Min mode allowed [e-] = " + cdw->ui->darkMinLineEdit->text() + "<br>"; config += "Max mode allowed [e-] = " + cdw->ui->darkMaxLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessflat() { QString config; QString note1 = ""; QString note2 = ""; if (!cdw->ui->flatMinLineEdit->text().isEmpty()) note1 = " (NOTE: before DARK / FLATOFF subtraction!)"; if (!cdw->ui->flatMaxLineEdit->text().isEmpty()) note2 = " (NOTE: before DARK / FLATOFF subtraction!)"; config = "<tt>"; config += "Number of low rejected pixels / stack = " + cdw->ui->flatNlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels / stack = " + cdw->ui->flatNhighLineEdit->text() + "<br>"; config += "Min mode allowed [e-] = " + cdw->ui->flatMinLineEdit->text() + note1 + "<br>"; config += "Max mode allowed [e-] = " + cdw->ui->flatMaxLineEdit->text() + note2 + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigProcessflatoff() { QString config; config = "<tt>"; config += "Number of low rejected pixels / stack = " + cdw->ui->flatoffNlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels / stack = " + cdw->ui->flatoffNhighLineEdit->text() + "<br>"; config += "Min mode allowed [e-] = " + cdw->ui->flatoffMinLineEdit->text() + "<br>"; config += "Max mode allowed [e-] = " + cdw->ui->flatoffMaxLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigBackground() { QString mode = " (STATIC)"; if (cdw->ui->BACwindowLineEdit->text() != "0") mode = " (DYNAMIC)"; QString config; config = "<tt>"; config += "Detection threshold (DT) = " + cdw->ui->BACDTLineEdit->text() + "<br>"; config += "Detection min area (DMIN) = " + cdw->ui->BACDMINLineEdit->text() + "<br>"; config += "Two-pass background model = " + boolToString(cdw->ui->BAC2passCheckBox->isChecked()) + "<br>"; config += "Convolve detections before masking = " + boolToString(cdw->ui->BACconvolutionCheckBox->isChecked()) + "<br>"; config += "Mask expansion factor = " + cdw->ui->BACmefLineEdit->text() + "<br>"; config += "Combination method = " + cdw->ui->BACmethodComboBox->currentText() + "<br>"; config += "Number of low rejected pixels (1st pass) = " + cdw->ui->BAC1nlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels (1st pass) = " + cdw->ui->BAC1nhighLineEdit->text() + "<br>"; config += "Number of low rejected pixels (2nd pass) = " + cdw->ui->BAC2nlowLineEdit->text() + "<br>"; config += "Number of high rejected pixels (2nd pass) = " + cdw->ui->BAC2nhighLineEdit->text() + "<br>"; config += "Reject detectors with stars brighter than [mag] = " + cdw->ui->BACmagLineEdit->text() + "<br>"; config += "Minimum distance from detector edge ['] = " + cdw->ui->BACdistLineEdit->text() + "<br>"; config += "Correction method = " + cdw->ui->BACapplyComboBox->currentText() + "<br>"; config += "Model smoothing kernel width [pixel] = " + cdw->ui->BACbacksmoothscaleLineEdit->text() + "<br>"; config += "Rescale model to individual exposure = " + boolToString(cdw->ui->BACrescaleCheckBox->isChecked()) + "<br>"; config += "Window size = " + cdw->ui->BACwindowLineEdit->text() + mode + "<br>"; config += "Min useful window size = " + cdw->ui->BACminWindowLineEdit->text() + "<br>"; config += "Max gap size [hour] = " + cdw->ui->BACgapsizeLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigCollapse() { QString config; config = "<tt>"; config += "Detection threshold (DT) = " + cdw->ui->COCDTLineEdit->text() + "<br>"; config += "Detection min area (DMIN) = " + cdw->ui->COCDMINLineEdit->text() + "<br>"; config += "Mask expansion factor = " + cdw->ui->COCmefLineEdit->text() + "<br>"; config += "Rejection threshold [sigma] = " + cdw->ui->COCrejectLineEdit->text() + "<br>"; config += "Collapse direction = " + cdw->ui->COCdirectionComboBox->currentText() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigBinnedpreview() { QString config; config = "<tt>"; config += "Binning factor = " + cdw->ui->BIPSpinBox->text() + "<br>"; config += "Reject outliers = " + boolToString(cdw->ui->BIPrejectCheckBox->isChecked()) + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigGlobalweight() { QString config; config = "<tt>"; config += "Same weight for all pixels = " + boolToString(cdw->ui->CGWsameweightCheckBox->isChecked()) + "<br>"; config += "Min value allowed for BIAS / DARK [e-] = " + cdw->ui->CGWdarkminLineEdit->text() + "<br>"; config += "Max value allowed for BIAS / DARK [e-] = " + cdw->ui->CGWdarkmaxLineEdit->text() + "<br>"; config += "Min value allowed for norm. FLAT [e-] = " + cdw->ui->CGWflatminLineEdit->text() + "<br>"; config += "Max value allowed for norm. FLAT [e-] = " + cdw->ui->CGWflatmaxLineEdit->text() + "<br>"; config += "Min value allowed for background model [e-] = " + cdw->ui->CGWbackminLineEdit->text() + "<br>"; config += "Max value allowed for background model [e-] = " + cdw->ui->CGWbackmaxLineEdit->text() + "<br>"; config += "Defect detection in FLAT: Kernel size = " + cdw->ui->CGWflatsmoothLineEdit->text() + "<br>"; config += "Defect detection in FLAT: Row tolerance = " + cdw->ui->CGWflatrowtolLineEdit->text() + "<br>"; config += "Defect detection in FLAT: Column tolerance = " + cdw->ui->CGWflatcoltolLineEdit->text() + "<br>"; config += "Defect detection in FLAT: Cluster tolerance = " + cdw->ui->CGWflatclustolLineEdit->text() + "<br>"; config += "Defect detection in BACK: Kernel size for = " + cdw->ui->CGWbacksmoothLineEdit->text() + "<br>"; config += "Defect detection in BACK: Row tolerance = " + cdw->ui->CGWbackrowtolLineEdit->text() + "<br>"; config += "Defect detection in BACK: Column tolerance = " + cdw->ui->CGWbackcoltolLineEdit->text() + "<br>"; config += "Defect detection in BACK: Cluster tolerance = " + cdw->ui->CGWbackclustolLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigIndividualweight() { QString config; config = "<tt>"; config += "Min value allowed in image [e-] = " + cdw->ui->CIWminaduLineEdit->text() + "<br>"; config += "Max value allowed in image [e-] = " + cdw->ui->CIWmaxaduLineEdit->text() + "<br>"; config += "Detection aggressiveness for cosmics = " + cdw->ui->CIWaggressivenessLineEdit->text() + "<br>"; config += "Mask blooming spikes = " + boolToString(cdw->ui->CIWmaskbloomingCheckBox->isChecked()) + "<br>"; config += "Blooming spike min value [e-] = " + cdw->ui->CIWbloomMinaduLineEdit->text() + "<br>"; config += "Blooming spike dynamic range [e-] = " + cdw->ui->CIWbloomRangeLineEdit->text() + "<br>"; config += "Mask persistent pixels = " + boolToString(cdw->ui->CIWpersistenceCheckBox->isChecked()) + "<br>"; config += "Maximum lookback time [min] = " + cdw->ui->CIWpersistenceTimescaleLineEdit->text() + "<br>"; config += "Persistence trigger level [e-] = " + cdw->ui->CIWpersistenceMinaduLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigCreatesourcecat() { QString config; config = "<tt>"; config += "Detection threshold (DT) = " + cdw->ui->CSCDTLineEdit->text() + "<br>"; config += "Detection min area (DMIN) = " + cdw->ui->CSCDMINLineEdit->text() + "<br>"; config += "DEBLEND = " + cdw->ui->CSCmincontLineEdit->text() + "<br>"; config += "Minimum FWHM [pixel] = " + cdw->ui->CSCFWHMLineEdit->text() + "<br>"; config += "Convolve detections = " + boolToString(cdw->ui->CSCconvolutionCheckBox->isChecked()) + "<br>"; config += "Max FLAG = " + cdw->ui->CSCmaxflagLineEdit->text() + "<br>"; config += "Saturation [e-] = " + cdw->ui->CSCsaturationLineEdit->text() + "<br>"; config += "Background level [e-] = " + cdw->ui->CSCbackgroundLineEdit->text() + "<br>"; config += "Many hot pixels = " + boolToString(cdw->ui->CSCsamplingCheckBox->isChecked()) + "<br>"; config += "Min # of objects per detector = " + cdw->ui->CSCrejectExposureLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigGetCatalogFromWeb() { QString config; QString pm; QString ra = cdw->ui->ARCraLineEdit->text(); QString dec = cdw->ui->ARCdecLineEdit->text(); QString mag = cdw->ui->ARCminmagLineEdit->text(); QString rad = cdw->ui->ARCradiusLineEdit->text(); if (cdw->ui->ARCmaxpmLineEdit->text().isEmpty()) pm = "unconstrained"; if (ra.isEmpty()) ra = "automatic"; if (dec.isEmpty()) dec = "automatic"; if (mag.isEmpty()) mag = "unconstrained"; if (rad.isEmpty()) rad = "automatic"; else rad.append("'"); config = "<tt>"; config += "Catalog = " + cdw->ui->ARCcatalogComboBox->currentText() + "<br>"; config += "Max allowed pm = " + pm + "<br>"; config += "Field center RA = " + ra + "<br>"; config += "Field center DEC = " + dec + "<br>"; config += "Target name = " + cdw->ui->ARCtargetresolverLineEdit->text() + "<br>"; config += "Magnitude limit = " + mag + "<br>"; config += "Radius = " + rad + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigGetCatalogFromImage() { QString config; config = "<tt>"; config += "FITS file = " + cdw->ui->ARCselectimageLineEdit->text() + "<br>"; config += "DT = " + cdw->ui->ARCDTLineEdit->text() + "<br>"; config += "DMIN = " + cdw->ui->ARCDMINLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigAstromphotom() { QString config; config = "<tt>"; config += "POSANGLE_MAXERR = " + cdw->ui->ASTposangleLineEdit->text() + "<br>"; config += "POSITION_MAXERR = " + cdw->ui->ASTpositionLineEdit->text() + "<br>"; config += "PIXSCALE_MAXERR = " + cdw->ui->ASTpixscaleLineEdit->text() + "<br>"; config += "CROSSID_RADIUS = " + cdw->ui->ASTcrossidLineEdit->text() + "<br>"; config += "ASTREF_WEIGHT = " + cdw->ui->ASTastrefweightLineEdit->text() + "<br>"; config += "SN_THRESHOLDS = " + cdw->ui->ASTsnthreshLineEdit->text() + "<br>"; config += "ASTR_INSTRUKEY = " + cdw->ui->ASTastrinstrukeyLineEdit->text() + "<br>"; config += "PHOT_INSTRUKEY = " + cdw->ui->ASTphotinstrukeyLineEdit->text() + "<br>"; config += "DISTORT_DEGREES = " + cdw->ui->ASTdistortLineEdit->text() + "<br>"; config += "DISTORT_GROUPS = " + cdw->ui->ASTdistortgroupsLineEdit->text() + "<br>"; config += "DISTORT_KEYS = " + cdw->ui->ASTdistortkeysLineEdit->text() + "<br>"; config += "Astrometric solver = " + cdw->ui->ASTmethodComboBox->currentText() + "<br>"; config += "Matching method = " + cdw->ui->ASTmatchMethodComboBox->currentText() + "<br>"; config += "STABILITY_TYPE = " + cdw->ui->ASTstabilityComboBox->currentText() + "<br>"; config += "MOSAIC_TYPE = " + cdw->ui->ASTmosaictypeComboBox->currentText() + "<br>"; config += "FPA mode = " + cdw->ui->ASTfocalplaneComboBox->currentText() + "<br>"; config += "Match flipped images = " + boolToString(cdw->ui->ASTmatchflippedCheckBox->isChecked()) + "<br>"; config += "Checkplot resolution = " + cdw->ui->ASTresolutionLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubModel() { QString config; config = "<tt>"; config += "Detection threshold (DT) = " + cdw->ui->skyDTLineEdit->text() + "<br>"; config += "Detection min area (DMIN) = " + cdw->ui->skyDMINLineEdit->text() + "<br>"; config += "Kernel width [pixel] = " + cdw->ui->skyKernelLineEdit->text() + "<br>"; config += "Mask expansion factor = " + cdw->ui->skyMefLineEdit->text() + "<br>"; emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubConst() { QString config; config = "<tt>"; config += "Constant sky measurement area = " + cdw->ui->skyAreaComboBox->currentText() + "<br>"; if (cdw->ui->skyAreaComboBox->currentIndex() != 0) { config += "Detection threshold (DT) = " + cdw->ui->skyDTLineEdit->text() + "<br>"; config += "Detection min area (DMIN) = " + cdw->ui->skyDMINLineEdit->text() + "<br>"; config += "Kernel width [pixel] = " + cdw->ui->skyKernelLineEdit->text() + "<br>"; config += "Mask expansion factor = " + cdw->ui->skyMefLineEdit->text() + "<br>"; } emit messageAvailable(config, "config"); } void Controller::pushConfigSkysubPoly() { QString config; config = "<tt>"; emit messageAvailable(config, "config"); } void Controller::pushConfigCoadd() { QString config; config = "<tt>"; config += "Reference RA = " + cdw->ui->COAraLineEdit->text() + "<br>"; config += "Reference DEC = " + cdw->ui->COAdecLineEdit->text() + "<br>"; config += "Plate scale = " + cdw->ui->COApixscaleLineEdit->text() + "<br>"; config += "Sky PA = " + cdw->ui->COAskypaLineEdit->text() + "<br>"; config += "COMBINETYPE = " + cdw->ui->COAcombinetypeComboBox->currentText() + "<br>"; config += "Resamp Kernel = " + cdw->ui->COAkernelComboBox->currentText() + "<br>"; config += "Sky projection = " + cdw->ui->COAprojectionComboBox->currentText() + "<br>"; config += "Celestial type = " + cdw->ui->COAcelestialtypeComboBox->currentText() + "<br>"; config += "Rescale weights = " + boolToString(cdw->ui->COArescaleweightsCheckBox->isChecked()) + "<br>"; config += "Apply fluxscale = " + boolToString(cdw->ui->COArzpCheckBox->isChecked()) + "<br>"; config += "Outlier thresh = " + cdw->ui->COAoutthreshLineEdit->text() + "<br>"; config += "Outlier numpix = " + cdw->ui->COAoutsizeLineEdit->text() + "<br>"; config += "Outlier border = " + cdw->ui->COAoutborderLineEdit->text() + "<br>"; config += "Identifier = " + cdw->ui->COAuniqueidLineEdit->text() + "<br>"; config += "Coadd chips = " + cdw->ui->COAchipsLineEdit->text() + "<br>"; config += "Min MJDOBS = " + cdw->ui->COAminMJDOBSLineEdit->text() + "<br>"; config += "Max MJDOBS = " + cdw->ui->COAmaxMJDOBSLineEdit->text() + "<br>"; config += "Edge smoothing = " + cdw->ui->COAedgesmoothingLineEdit->text() + "<br>";; config += "NAXIS1 = " + cdw->ui->COAsizexLineEdit->text() + "<br>";; config += "NAXIS2 = " + cdw->ui->COAsizeyLineEdit->text() + "<br>";; config += "Nonsidereal RA = " + cdw->ui->COApmraLineEdit->text() + " " + cdw->ui->COApmComboBox->currentText() + "<br>"; config += "Nonsidereal DEC = " + cdw->ui->COApmdecLineEdit->text() + " " + cdw->ui->COApmComboBox->currentText() + "<br>"; config += "Perform fluxcal = " + boolToString(cdw->ui->COAfluxcalibCheckBox->isChecked()) + "<br>"; config += "</tt>"; emit messageAvailable(config, "config"); }
19,996
C++
.cc
327
56.972477
126
0.647948
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,465
controller.cc
schirmermischa_THELI/src/processingInternal/controller.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "instrumentdata.h" #include "../mainwindow.h" #include "ui_mainwindow.h" #include "../dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include "ui_memoryviewer.h" #include "../dockwidgets/monitor.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../preferences.h" #include "../tools/cfitsioerrorcodes.h" #include <omp.h> #include <QMainWindow> #include <QString> #include <QList> #include <QSettings> #include <QTest> #include <QMutex> #include <QTimer> #include <QProgressBar> #include <unistd.h> Controller::Controller(const instrumentDataType *instrumentData, QString statusold, ConfDockWidget *confDockWidget, Monitor *processMonitor, MainWindow *parent) : QMainWindow(parent), cdw(confDockWidget), instData(instrumentData) { mainGUI = parent; // cdw = confDockWidget; // instData = instrumentData; statusOld = statusold; monitor = processMonitor; // Load detector info only if an instrument has been selected // In some instances, e.g. deleting all manually defined user insts, this command would fail // Same for the masks if (!instrumentData->nameFullPath.isEmpty()) { getDetectorSections(); mask = new Mask(instData, this); } // Before populating all Data objects omp_init_lock(&lock); omp_init_lock(&memoryLock); omp_init_lock(&wcsLock); omp_init_lock(&genericLock); omp_init_lock(&progressLock); omp_init_lock(&backgroundLock); loadPreferences(); // Populate data tree mapDataTree(); // Tell DT_x about the memory preference updateMemoryPreference(minimizeMemoryUsage); // Initialization initEnvironment(thelidir, userdir); instrument_dir = mainGUI->instrument_dir; // loadPreferences(); externalProcess = new QProcess(this); // connect(externalProcess, &QProcess::readyReadStandardOutput, this, &Controller::processExternalStdout); // connect(externalProcess, &QProcess::readyReadStandardError, this, &Controller::processExternalStderr); stdoutByteArray = new QByteArray(); stderrByteArray = new QByteArray(); stdoutByteArray->reserve(10000); stderrByteArray->reserve(10000); // setupExternalProcesses(); populateCommentMap(); // Done at top level, so it is not repeated many times by the Splitter class populateHeaderDictionary(); populateFilterDictionary(); populateInstrumentDictionary(); // Daisy-chaining scamp, and the coadditions connect(this, &Controller::showScampCheckPlots, this, &Controller::showScampCheckPlotsReceived); connect(this, &Controller::swarpStartResampling, this, &Controller::coaddResample); connect(this, &Controller::swarpStartSwarpfilter, this, &Controller::coaddSwarpfilter); connect(this, &Controller::swarpStartCoaddition, this, &Controller::coaddCoaddition); connect(this, &Controller::swarpStartUpdate, this, &Controller::coaddUpdate); progressTimer = new QTimer(this); connect(progressTimer, SIGNAL(timeout()), SLOT(displayProgress())); progressTimer->start(100); } void Controller::getNumberOfActiveImages(Data *&data) { numActiveImages = 0; progress = 0.; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : data->myImageList.at(chip)) { if (it->activeState == MyImage::ACTIVE) ++numActiveImages; } } progressStepSize = 100./(float(numActiveImages)); progressHalfStepSize = 0.5*progressStepSize; // Last 5% are reserved for mode determination and writing to drive // 45% are in Data::combineImagesCalib() for combination progressCombinedStepSize = 5./instData->numUsedChips; } Controller::~Controller() { for (auto &DT_x : masterListDT) { for (auto &it : DT_x) { delete it; it = nullptr; } } delete GLOBALWEIGHTS; GLOBALWEIGHTS = nullptr; // mask->reset(); delete mask; mask = nullptr; omp_destroy_lock(&lock); omp_destroy_lock(&memoryLock); omp_destroy_lock(&genericLock); omp_destroy_lock(&progressLock); omp_destroy_lock(&backgroundLock); for (auto &it : externalProcesses) { delete it; it = nullptr; } // delete externalProcess; delete stdoutByteArray; delete stderrByteArray; stdoutByteArray = nullptr; stderrByteArray = nullptr; } bool Controller::isMainDirHome() { // Must compare string values, not QDirs themselves, as they could be initialized differently (e.g. "." vs /home/.../) if (QDir(mainDirName).absolutePath() == QDir::home().absolutePath()) { if (!homeDirWarningShowed) emit messageAvailable("For safety reasons, your home directory is not permitted as the main directory.", "error"); // emit criticalReceived(); homeDirWarningShowed = true; successProcessing = false; return true; } else { homeDirWarningShowed = false; successProcessing = true; return false; } } // Reads whatever is defined in the Setup data tree section, and maps it onto the various lists void Controller::mapDataTree() { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); mainDirName = mainGUI->ui->setupMainLineEdit->text(); if (isMainDirHome()) { omp_unset_lock(&memoryLock); return; } recurseCounter = 0; parseDataDir(mainGUI->ui->setupBiasLineEdit, DT_BIAS); recurseCounter = 0; parseDataDir(mainGUI->ui->setupDarkLineEdit, DT_DARK); recurseCounter = 0; parseDataDir(mainGUI->ui->setupFlatoffLineEdit, DT_FLATOFF); recurseCounter = 0; parseDataDir(mainGUI->ui->setupFlatLineEdit, DT_FLAT); recurseCounter = 0; parseDataDir(mainGUI->ui->setupScienceLineEdit, DT_SCIENCE); recurseCounter = 0; parseDataDir(mainGUI->ui->setupSkyLineEdit, DT_SKY); recurseCounter = 0; parseDataDir(mainGUI->ui->setupStandardLineEdit, DT_STANDARD); recurseCounter = 0; updateMasterList(); if (QDir(mainDirName+"/GLOBALWEIGHTS/").exists()) { GLOBALWEIGHTS = new Data(instData, mask, mainDirName, "GLOBALWEIGHTS", &verbosity); GLOBALWEIGHTS->maxExternalThreads = maxExternalThreads; GLOBALWEIGHTS->progress = &progress; GLOBALWEIGHTS->dataType = "GLOBALWEIGHT"; connect(GLOBALWEIGHTS, &Data::statusChanged, mainGUI, &MainWindow::statusChangedReceived); connect(GLOBALWEIGHTS, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(GLOBALWEIGHTS, &Data::appendOK, this, &Controller::appendOKReceived); connect(GLOBALWEIGHTS, &Data::critical, this, &Controller::criticalReceived); connect(GLOBALWEIGHTS, &Data::warning, this, &Controller::warningReceived); connect(GLOBALWEIGHTS, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(GLOBALWEIGHTS, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(GLOBALWEIGHTS, &Data::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); // if (memoryViewer != nullptr) { // connect(GLOBALWEIGHTS, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); // } GLOBALWEIGHTS->setParent(this); globalweights_created = true; } emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } // Parse the data tree entries // Construct the Data entities void Controller::parseDataDir(QLineEdit *le, QList<Data *> &DT_x) { DT_x.clear(); if (!QDir(mainDirName).exists() || mainDirName.isEmpty() || le->text().isEmpty()) return; bool successFileScan = true; QString badDirName = ""; QStringList dirs = le->text().replace(","," ").simplified().split(" "); for (auto &it : dirs) { // do not accept any wrong entries; empty the list if (!QDir(mainDirName+"/"+it).exists()) { DT_x.clear(); return; } if (isMainDirHome()) return; Data *data = new Data(instData, mask, mainDirName, it, &verbosity); connect(data, &Data::statusChanged, mainGUI, &MainWindow::statusChangedReceived); connect(data, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(data, &Data::appendOK, this, &Controller::appendOKReceived); connect(data, &Data::critical, this, &Controller::criticalReceived); connect(data, &Data::warning, this, &Controller::warningReceived); connect(data, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(data, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(data, &Data::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); connect(data, &Data::addToProgressBar, this, &Controller::addToProgressBarReceived); connect(data, &Data::errorOccurredInMyImage, this, &Controller::criticalReceived); // if (memoryViewer != nullptr) { // connect(data, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); // } data->setParent(this); data->maxExternalThreads = maxExternalThreads; data->progress = &progress; if (le == mainGUI->ui->setupBiasLineEdit) data->dataType = "BIAS"; else if (le == mainGUI->ui->setupDarkLineEdit) data->dataType = "DARK"; else if (le == mainGUI->ui->setupFlatoffLineEdit) data->dataType = "FLATOFF"; else if (le == mainGUI->ui->setupFlatLineEdit) data->dataType = "FLAT"; else if (le == mainGUI->ui->setupScienceLineEdit) data->dataType = "SCIENCE"; else if (le == mainGUI->ui->setupSkyLineEdit) data->dataType = "SKY"; else if (le == mainGUI->ui->setupStandardLineEdit) data->dataType = "STANDARD"; else { // nothing yet } // Check status consistency successFileScan = data->checkStatusConsistency(); if (!successFileScan) { badDirName = data->dirName; break; } // Needs to know the dataType, hence here and not further up data->broadcastNumberOfFiles(); DT_x << data; } if (!successFileScan) { emit messageAvailable(badDirName + " : Inconsistency detected between FITS file names and recorded processing status.<br>Inferring status from file names ...", "warning"); /* if (recurseCounter > 1) { qDebug() << badDirName << ": The FITS files found do not match the recorded status"; qDebug() << "Either restore the files manually, or use the memory viewer to set the correct status."; qDebug() << "Restart recommended."; // TODO: the signal emitted is received by the controller and re-emitted, but not received by MainWindow. very odd. hence the message Available(); // Edit: even that signal is not received! emit messageAvailable("<br>" + badDirName + tr(": The FITS files found do not match the recorded status.\n")+ tr("Either restore the files manually, or use the 'Processing status' menu to reflect the current status.<br> Restart recommended."), "error"); emit criticalReceived(); emit showMessageBox("Data::INCONSISTENT_DATA_STATUS", badDirName, "status"); return; } */ // RECURSIVE // must repeat everything (simplest implementation), at max once if (recurseCounter == 0) { ++recurseCounter; // Must set before entering same function again! parseDataDir(le, DT_x); } } } void Controller::updateMasterList() { // A full refresh of the master list, e.g. if a data directory was edited in the UI (triggering a parse); masterListDT.clear(); masterListDT << DT_BIAS << DT_DARK << DT_FLATOFF << DT_FLAT << DT_SCIENCE << DT_SKY << DT_STANDARD; } void Controller::rereadScienceDataDirReceived() { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); for (auto &data: DT_SCIENCE) { delete data; data = nullptr; } DT_SCIENCE.clear(); parseDataDir(mainGUI->ui->setupScienceLineEdit, DT_SCIENCE); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; // And do the final GUI updates to signal processing has finished if (successProcessing) { emit progressUpdate(100); pushEndMessage(taskBasename, "SCIENCE"); } } // Receiving end from setMemoryLock calls within other classes void Controller::setMemoryLockReceived(bool locked) { if (locked) omp_set_lock(&memoryLock); else omp_unset_lock(&memoryLock); } // Receiving end from setWCSLock calls within other classes void Controller::setWCSLockReceived(bool locked) { if (locked) omp_set_lock(&wcsLock); else omp_unset_lock(&wcsLock); } long Controller::makeListofAllImages(QList<MyImage*> &allMyImages, Data *data) { allMyImages.clear(); for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; // incrementCurrentThreads(lock); for (auto &it : data->myImageList[chip]) { allMyImages.append(it); } } return allMyImages.length(); } // Rescan the data tree if a LineEdit was successfully edited void Controller::dataTreeEditedReceived() { // Do not do anything while loading a new project (causes crashes in memoryviewer) if (mainGUI->readingSettings) return; QLineEdit* lineEdit = qobject_cast<QLineEdit*>(sender()); // CASE 1: The main data dir has changed. Must update everything. QString maindir = mainGUI->ui->setupMainLineEdit->text(); if (lineEdit == mainGUI->ui->setupMainLineEdit) { QDir dir(maindir); if (dir.exists()) mapDataTree(); return; } // CASE 2: A single element of the data tree has changed QStringList list = datadir2StringList(lineEdit); // Loop over the directories and check whether they exist for (int i=0; i<list.size(); ++i) { // check if path is absolute, if not, prepend main path QString dirname = list.at(i); QDir dir(dirname); if (!dir.isAbsolute()) { dirname = maindir + "/" + dirname; dir = QDir(dirname); } if (!dir.exists()) { return; } } dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); QString name = sender()->objectName(); if (name == "setupBiasLineEdit") parseDataDir(lineEdit, DT_BIAS); else if (name == "setupDarkLineEdit") parseDataDir(lineEdit, DT_DARK); else if (name == "setupFlatoffLineEdit") parseDataDir(lineEdit, DT_FLATOFF); else if (name == "setupFlatLineEdit") parseDataDir(lineEdit, DT_FLAT); else if (name == "setupScienceLineEdit") parseDataDir(lineEdit, DT_SCIENCE); else if (name == "setupSkyLineEdit") parseDataDir(lineEdit, DT_SKY); else if (name == "setupStandardLineEdit") parseDataDir(lineEdit, DT_STANDARD); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } void Controller::checkForUnsavedImages(long &numUnsavedLatest, long &numUnsavedBackup) { numUnsavedLatest = 0; numUnsavedBackup = 0; for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { data->countUnsavedImages(numUnsavedLatest, numUnsavedBackup); } } } void Controller::writeUnsavedImagesToDrive(bool includeBackup) { emit messageAvailable("Writing images to disk", "controller"); criticalReceived(); // Do not need to loop over globalweights (they are always saved) for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { data->writeUnsavedImagesToDrive(includeBackup); } } emit messageAvailable("Done writing images ...", "controller"); } void Controller::wipeDataTree() { // Lock, so it doesn't interfere with memory progress bar dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); releaseAllMemory(); // The call above just releases the processed pixels kept in memory, it does NOT clear the image lists as such for (auto &DT_x : masterListDT) { if (!DT_x.isEmpty()) { for (auto &it : DT_x) { it->dataInitialized = false; it->processingStatus = nullptr; it->myImageList.clear(); delete it; it = nullptr; } DT_x.clear(); } } if (globalweights_created) { delete GLOBALWEIGHTS; GLOBALWEIGHTS = nullptr; globalweights_created = false; } masterListDT.clear(); emit clearMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } void Controller::newProjectLoadedReceived() { // wipeDataTree(); // Done in MainWindow::on_setupProjectLoadPushButton_clicked(); // Must be done then because e.g. the number of chips changes. // Infer the status of the project statusOld = mainGUI->status.getStatusFromHistory(); // Re-read full data tree mapDataTree(); } void Controller::displayProgress() { emit progressUpdate(progress); } void Controller::updateAll() { // Reset all masks mask->reset(); mask->instData = instData; mask->initMasks(); // For GROND (and other multi-channel instruments) provideAlternativeMask(); // instData member is a pointer and does not need updating when a new instrument is selected (true? must check!) mapDataTree(); // updates the memory view } // so far called in MainGUIWorker::runTask(); should be done better by signal emission void Controller::loadPreferences() { // Start with max number of CPUs (updated with user preference below) QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt(); useGPU = settings.value("prefGPUCheckBox", false).toBool(); maxRAM = 0.75 * settings.value("prefMemorySpinBox").toInt(); // 75% of RAM verbosity = settings.value("prefVerbosityComboBox", 1).toInt(); if (settings.value("prefIntermediateDataComboBox", "If necessary") == "If necessary") alwaysStoreData = false; else alwaysStoreData = true; minimizeMemoryUsage = settings.value("prefMemoryCheckBox", false).toBool(); availableThreads = maxCPU; verbosity = settings.value("prefVerbosityComboBox").toInt(); if (settings.status() != QSettings::NoError) { emit messageAvailable("WARNING: Could not retrieve CPU and GPU parameters from preferences. Parallelization deactivated.", "warning"); maxCPU = 1; maxThreadsIO = 1; maxExternalThreads = 1; maxInternalThreads = 1; maxRAM = 1024; useGPU = false; verbosity = 1; } // We have maxExternalThreads, which is the max number of threads working on independent detectors. // If more CPUs than detectors, limit this number so that we have left-over threads for further parallelization // (internal threads in Data class) if (maxCPU > instData->numUsedChips) { // maxExternalThreads = instData->numUsedChips; // NO! The loops skipped for a bad chip will just wait until another CPU becomes available. maxExternalThreads = instData->numChips; // keep full number of CPUs instead maxInternalThreads = maxCPU - maxExternalThreads + 1; } else { maxExternalThreads = maxCPU; maxInternalThreads = 1; } pushParallelizationToData(DT_BIAS); pushParallelizationToData(DT_DARK); pushParallelizationToData(DT_FLATOFF); pushParallelizationToData(DT_FLAT); pushParallelizationToData(DT_SCIENCE); pushParallelizationToData(DT_SKY); pushParallelizationToData(DT_STANDARD); if (GLOBALWEIGHTS != nullptr) pushParallelizationToData(GLOBALWEIGHTS); // For Swarp coaddition externalProcesses.resize(maxCPU); for (int i=0; i<maxCPU; ++i) { QProcess *process = new QProcess(); // connect(process, &QProcess::readyReadStandardOutput, this, &Controller::processExternalStdout); // connect(process, &QProcess::readyReadStandardError, this, &Controller::processExternalStderr); externalProcesses[i] = process; } swarpCommands.resize(maxCPU); threadsFinished.fill(false, maxCPU); swarpWorkers.resize(maxCPU); workerThreads.resize(maxCPU); } void Controller::pushParallelizationToData(QList<Data*> DT_x) { if (DT_x.isEmpty()) return; for (auto &it : DT_x) { if (it == nullptr) continue; it->maxCPU = maxCPU; it->maxExternalThreads = maxExternalThreads; it->maxThreadsIO = maxThreadsIO; it->useGPU = useGPU; it->maxRAM = maxRAM; } } void Controller::pushParallelizationToData(Data *data) { if (data == nullptr) return; data->maxCPU = maxCPU; data->maxExternalThreads = maxExternalThreads; data->maxThreadsIO = maxThreadsIO; data->useGPU = useGPU; data->maxRAM = maxRAM; } void Controller::addToProgressBarReceived(const float differential) { omp_set_lock(&progressLock); progress += differential; emit progressUpdate(progress); omp_unset_lock(&progressLock); } void Controller::releaseAllMemory() { // memory lock set in caller // Globalweights if (GLOBALWEIGHTS != nullptr) { GLOBALWEIGHTS->releaseAllMemory(); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { if (data == nullptr) continue; data->releaseAllMemory(); } } } void Controller::doDataFitInRAM(const long nImages, const long storageSize) { if (alwaysStoreData) return; // we are good if (nImages*storageSize > maxRAM) { alwaysStoreData = true; QSettings settings("THELI", "PREFERENCES"); settings.setValue("prefIntermediateDataComboBox", "Always"); if (settings.status() != QSettings::NoError) { emit messageAvailable("Could not update preferences concerning intermediate data storage", "warning"); } else { emit messageAvailable("******************************************************", "note"); emit messageAvailable("High memory use expected. Will write FITS images to drive on the fly.", "note"); emit messageAvailable("******************************************************<br>", "note"); } } } void Controller::releaseMemory(float RAMneededThisThread, int numThreads, QString mode) { // Requested by several threads, hence this must be locked omp_set_lock(&memoryLock); float RAMfreed = 0.; bool RAMwasReallyReleased = false; float currentTotalMemoryUsed = mainGUI->myRAM->getRAMload(); // Globalweights if (GLOBALWEIGHTS != nullptr && globalweights_created) { GLOBALWEIGHTS->releaseMemory(RAMneededThisThread, RAMneededThisThread*numThreads, currentTotalMemoryUsed, mode); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { if (data == nullptr) continue; // memviewer is updated by signals emitted by MyImage class float released = data->releaseMemory(RAMneededThisThread, RAMneededThisThread*numThreads, currentTotalMemoryUsed, mode); if (released >= 0.) { RAMfreed += released; RAMwasReallyReleased = true; } } } // float RAMstillneeded = RAMneededThisThread - RAMfreed; if (RAMfreed < RAMneededThisThread && RAMwasReallyReleased && currentTotalMemoryUsed > 0. && RAMfreed < currentTotalMemoryUsed - 100 // 100 is to suppress insignificant warnings && RAMneededThisThread > maxRAM - currentTotalMemoryUsed) { // && !swapWarningShown) { if (verbosity > 1) { emit messageAvailable(QString::number(long(RAMneededThisThread)) + " MB requested, " + QString::number(long(RAMfreed)) + " MB released. Try fewer CPUs to avoid swapping.", "warning"); } swapWarningShown = true; } // emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); if (RAMfreed >= RAMneededThisThread && RAMwasReallyReleased) { if (verbosity >= 2) emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); } omp_unset_lock(&memoryLock); } // This function is called after each task to respect the maximum amount of memory allowed by the user. // Actual use may overshoot during processing void Controller::satisfyMaxMemorySetting() { // Requested by several threads, hence this must be locked omp_set_lock(&memoryLock); float RAMfreed = 0.; bool RAMwasReallyReleased = false; float currentTotalMemoryUsed = mainGUI->myRAM->getRAMload(); float mustReleaseRAM = currentTotalMemoryUsed - maxRAM; // Globalweights if (GLOBALWEIGHTS!= nullptr) { GLOBALWEIGHTS->releaseMemory(mustReleaseRAM, mustReleaseRAM, currentTotalMemoryUsed); } // Pass through normal data tree for (auto &DT_x : masterListDT) { for (auto &data : DT_x) { float released = data->releaseMemory(mustReleaseRAM, mustReleaseRAM, currentTotalMemoryUsed); if (released >= 0.) { RAMfreed += released; RAMwasReallyReleased = true; } } } if (RAMfreed < mustReleaseRAM && RAMwasReallyReleased && !swapWarningShown) { emit messageAvailable("Tried to release "+QString::number(long(mustReleaseRAM)) + " MB, " + QString::number(long(RAMfreed)) + " MB actually released.", "warning"); swapWarningShown = true; } if (RAMfreed >= mustReleaseRAM && RAMwasReallyReleased) { if (verbosity >= 2) emit messageAvailable("Released "+QString::number(long(RAMfreed)) + " MB", "note"); } omp_unset_lock(&memoryLock); } void Controller::checkSuccessProcessing(const Data *data) { if (userStop || userKill) { emit messageAvailable("Aborted", "stop"); return; } if (!data->successProcessing) { successProcessing = false; emit messageAvailable("Data processing in " + data->dirName + " unsuccessful.", "error"); criticalReceived(); } } // Shows a message box where the user can optionally trigger a clearance of the error state. // The task that triggers this bool Controller::testResetDesire(const Data *data) { if (!data->successProcessing) { emit showMessageBox("Controller::RESET_REQUESTED", data->subDirName, ""); return false; } return true; } void Controller::getDetectorSections() { overscanX.clear(); overscanY.clear(); dataSection.clear(); overscanX.resize(instData->numChips); overscanY.resize(instData->numChips); dataSection.resize(instData->numChips); QVector<int> xmin = instData->overscan_xmin; QVector<int> xmax = instData->overscan_xmax; QVector<int> ymin = instData->overscan_ymin; QVector<int> ymax = instData->overscan_ymax; // to stay safe, i include chips that are not used for (int chip=0; chip<instData->numChips; ++chip) { // Overscan X QVector<long> overscanxRegion; if (!xmin.isEmpty() && !xmax.isEmpty()) overscanxRegion << xmin[chip] << xmax[chip]; overscanX[chip] << overscanxRegion; // Overscan Y QVector<long> overscanyRegion; if (!ymin.isEmpty() && !ymax.isEmpty()) overscanyRegion << ymin[chip] << ymax[chip]; overscanY[chip] << overscanyRegion; // Data Section QVector<long> section; section << instData->cutx[chip]; section << instData->cutx[chip] + instData->sizex[chip] - 1; // sizex is not a coordinate, but the number of pixels along this axis. Hence -1 section << instData->cuty[chip]; section << instData->cuty[chip] + instData->sizey[chip] - 1; // sizey is not a coordinate, but the number of pixels along this axis. Hence -1 dataSection[chip] << section; } } QList<QVector<float>> Controller::getNonlinearityCoefficients() { QList<QVector<float>> coeffs; QString coeffsFileName = instrument_dir+"/"+instData->name+".nldat"; QFile coeffsFile(coeffsFileName); // Read the coefficients if( !coeffsFile.open(QIODevice::ReadOnly)) { // return empty list if file does not exist return coeffs; } QTextStream in(&coeffsFile); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; // Extract the coefficients and put them into a QVector<float> line = line.simplified(); QStringList values = line.split(" "); QVector<float> vecData; for (auto &it : values) { vecData.push_back(it.toFloat()); } coeffs.append(vecData); } coeffsFile.close(); if (coeffs.length() != instData->numChips) { QMessageBox::warning(this, tr("Inconsistent number of nonlinearity coefficients"), tr("The file with nonlinearity coefficients,\n")+coeffsFileName+ tr("contains entries (lines) for")+QString::number(coeffs.length())+" detectors.\n"+ tr("However, ")+instData->name+tr(" has")+QString::number(instData->numChips)+tr(" detectors.")+ tr("Data processing will continue without non-linearity correction."), QMessageBox::Ok); coeffs.clear(); } return coeffs; } void Controller::resetErrorStatusReceived(QString dirName) { Data *data = getDataAll(dirName); if (data != nullptr) { data->resetSuccessProcessing(); } } QVector<QString> Controller::getBackgroundThresholds(const int loop, const bool twoPass, const QString DT, const QString DMIN, bool &doSourceDetection) { QVector<QString> thresholds; // No thresholds specified, or in first loop of twoPass mode: don't do source detection if (DT.isEmpty() || DMIN.isEmpty() || (twoPass && loop == 0)) { doSourceDetection = false; thresholds << "" << ""; // not evaluated later-on return thresholds; } // Thresholds specified: detection depends on whether we are in twopass mode or not else if (!twoPass || loop == 1) { // loop == 1 implies twoPass = true doSourceDetection = true; thresholds << DT << DMIN; return thresholds; } else { // should be cought by previous 'else if' emit messageAvailable("Controller::getBackgroundThresholds(): Code should never enter here!", "error"); criticalReceived(); successProcessing = false; doSourceDetection = false; thresholds << DT << DMIN; return thresholds; } } // Updates the processing status, and also creates a backup file on drive (if the FITS file exists) void Controller::updateImageAndData(MyImage *image, Data *data) { bool *s = nullptr; if (taskBasename == "HDUreformat") s = &image->processingStatus->HDUreformat; else if (taskBasename == "Processscience") s = &image->processingStatus->Processscience; else if (taskBasename == "Chopnod") s = &image->processingStatus->Chopnod; else if (taskBasename == "Background") s = &image->processingStatus->Background; else if (taskBasename == "Collapse") s = &image->processingStatus->Collapse; else if (taskBasename == "Starflat") s = &image->processingStatus->Starflat; else if (taskBasename == "Skysub") s = &image->processingStatus->Skysub; else { emit messageAvailable("Controller::updateProcessingStatus(): Invalid taskBasename. This is a bug!", "error"); criticalReceived(); return; } // Status of Data class becomes immediately false if the status of a single image is false if (image->successProcessing) { // Update the status (processing was successful) *s = true; QString statusNew = image->processingStatus->getStatusString(); // Update members in MyImage class image->processingStatus->statusString = statusNew; image->baseName = image->chipName + statusNew; // New pixel data are not yet on drive image->imageOnDrive = false; } else { *s = false; data->successProcessing = false; } } // The top level entry function for MainWindow to initiate a task void Controller::runTask() { if (!successProcessing) return; // Reset the process progress bar emit resetProgressBar(); // call the function by its string representation (needs a const char *) bool test = true; if (taskBasename == "processScience") { // Calls test = QMetaObject::invokeMethod(this, ("taskInternal"+taskBasename).toStdString().c_str(), Qt::DirectConnection, Q_ARG(QList<Data*>, DT_SCIENCE)); } else { test = QMetaObject::invokeMethod(this, ("taskInternal"+taskBasename).toStdString().c_str(), Qt::DirectConnection); } if (!test) { emit messageAvailable("Controller::runTask(): Could not evaluate QMetaObject for " +taskBasename, "error"); criticalReceived(); return; } } // Identify the Data class that corresponds to directory dirName, and return a link to that class Data* Controller::getData(QList<Data *> DT_x, QString dirName) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDirName + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); // if (it->isEmpty()) return nullptr; if (it->hasAllMasterCalibs) return it; // otherwise a dir with only the master calibs will not be accepted if (it->isEmpty()) return nullptr; else return it; } } emit messageAvailable("Controller::getData(): Directory " + dirName + " not found in Data class for " + DT_x[0]->dirName, "error"); criticalReceived(); return nullptr; } // Identify the Data class that corresponds to directory dirName, and return a link to that class // Used if we don't know the top level category of that directory // TODO: Check what happens if we use e.g. the same science directory as a science directory as well as a flat directory. Prohibit this at software level? Data* Controller::getDataAll(QString dirName) { for (auto &DT_x : masterListDT) { for (auto &it : DT_x) { if (QDir::cleanPath(it->dirName) == QDir::cleanPath(mainDirName + "/" + dirName)) { // check if it contains mastercalib data it->checkPresenceOfMasterCalibs(); return it; } } } emit messageAvailable(QString(__func__)+": Directory " + dirName + " not found in Data classes.", "error"); criticalReceived(); return nullptr; } // Decide which data can (or cannot) be deleted from memory void Controller::memoryDecideDeletableStatus(Data *data, bool deletable) { for (int chip=0; chip<instData->numChips; ++chip) { data->memorySetDeletable(chip, "dataBackupL1", deletable); } } QString Controller::getUserParamLineEdit(const QLineEdit *le) { QString value = le->text(); if (value == "") value = cdw->defaultMap[le->objectName()]; return value; } QString Controller::getUserParamCheckBox(const QCheckBox *cb) { if (cb->isChecked()) return "Y"; else return "N"; } QString Controller::getUserParamComboBox(const QComboBox *cb) { return cb->currentText(); } void Controller::pushBeginMessage(const QString idstring, const QString targetdir) { QString message = commentMap.value(idstring); emit messageAvailable("<br>##############################################", "output"); emit messageAvailable(message+" "+targetdir, "controller"); emit messageAvailable("##############################################<br>\n", "output"); } void Controller::pushEndMessage(const QString idstring, const QString targetdir) { QString message = commentMap.value(idstring); emit messageAvailable("<br>##############################################", "output"); emit messageAvailable(message+" "+targetdir+"... DONE.", "controller"); emit messageAvailable("##############################################<br>\n", "output"); } void Controller::updateMemoryPreference(bool isRAMminimized) { minimizeMemoryUsage = isRAMminimized; sendMemoryPreferenceToImages(DT_BIAS); sendMemoryPreferenceToImages(DT_DARK); sendMemoryPreferenceToImages(DT_FLATOFF); sendMemoryPreferenceToImages(DT_FLAT); sendMemoryPreferenceToImages(DT_SCIENCE); sendMemoryPreferenceToImages(DT_SKY); sendMemoryPreferenceToImages(DT_STANDARD); if (GLOBALWEIGHTS != nullptr) sendMemoryPreferenceToImages(DT_STANDARD); } void Controller::updateIntermediateDataPreference(QString intermediateDataPreference) { if (intermediateDataPreference == "Always") alwaysStoreData = true; else alwaysStoreData = false; } void Controller::criticalReceived() { abortProcess = true; emit messageAvailable("Abort.", "stop"); monitor->raise(); } void Controller::warningReceived() { monitor->raise(); } void Controller::messageAvailableReceived(QString message, QString type) { emit messageAvailable(message, type); } void Controller::appendOKReceived() { emit appendOK(); } void Controller::showMessageBoxReceived(QString trigger, QString part1, QString part2) { emit showMessageBox(trigger, part1, part2); } void Controller::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void Controller::sendMemoryPreferenceToImages(QList<Data*> DT_x) { if (DT_x.isEmpty()) return; // including chips the user does not want to use for (auto &data : DT_x) { for (int chip=0; chip<data->instData->numChips; ++chip) { for (auto &it : data->myImageList[chip]) { it->minimizeMemoryUsage = minimizeMemoryUsage; } } } } void Controller::restoreAllRawData() { // memory lock set in caller; NO IT IS NOT! // restore button deactivated while task is running #pragma omp parallel for num_threads(maxCPU) for (int i=0; i<masterListDT.length(); ++i) { auto &DT_x = masterListDT[i]; for (auto &it : DT_x) { // Just a paranoid safety barrier, in case the user provides incomplete data and then clicks on 'restore' if (it->dir.absolutePath() == QDir::homePath()) { QMessageBox::warning( this, "Dangerous data tree", "The full path to " + it->dirName+"is identical to your home directory!\nTHELI will not delete / restore any data in this directory."); continue; } else { it->restoreRAWDATA(); } } } if (GLOBALWEIGHTS != nullptr) GLOBALWEIGHTS->releaseAllMemory(); QDir globalweightsDir(mainDirName+"/GLOBALWEIGHTS/"); if (globalweightsDir.exists()) { emit messageAvailable("Deleting " + mainDirName+"/GLOBALWEIGHTS/" + "...", "controller"); globalweightsDir.removeRecursively(); } QDir weightsDir(mainDirName+"/WEIGHTS/"); if (weightsDir.exists()) { emit messageAvailable("Deleting " + mainDirName+"/WEIGHTS/" + "...", "controller"); weightsDir.removeRecursively(); } updateMasterList(); mainGUI->status.clearAllCheckBoxes(); cdw->ui->ARCpmRALineEdit->clear(); cdw->ui->ARCpmDECLineEdit->clear(); } void Controller::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Controller::"+funcName+":<br>" + errorCodes->errorKeyMap.value(status), "error"); criticalReceived(); successProcessing = false; } } bool Controller::isImageTooBig(QString name) { fitsfile *fptr = nullptr; int status = 0; if (name.isNull() || name.isEmpty()) { status = 1; emit messageAvailable(QString(__func__) + ": file name empty or not initialized!", "warning"); return false; } long naxis1 = 0; long naxis2 = 0; fits_open_file(&fptr, name.toUtf8().data(), READWRITE, &status); fits_update_key_lng(fptr, "NAXIS1", naxis1, NULL, &status); fits_update_key_lng(fptr, "NAXIS2", naxis2, NULL, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (naxis1*naxis2 > pow(2,29)) return false; else return true; } void Controller::printCfitsioWarning(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Controller::"+funcName+":<br>" + errorCodes->errorKeyMap.value(status), "warning"); warningReceived(); } } // Cannot be done above when data classes are defined (because memoryviewer has not been declared in mainwindow.cc when the controller is defined. void Controller::connectDataWithMemoryViewer() { for (auto &DT_x : masterListDT) { if (!DT_x.isEmpty()) { for (auto &it : DT_x) { connect(it, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); } } } if (globalweights_created && GLOBALWEIGHTS != nullptr) { connect(GLOBALWEIGHTS, &Data::statusChanged, memoryViewer, &MemoryViewer::updateStatusCheckBoxesReceived); } } void Controller::activationWarningReceived(QString imagestatus, QString drivestatus) { QMessageBox::warning( this, "THELI: Incoherent processing states", "This image has a different processing status (" + imagestatus + ") " +"than the currently active images (" + drivestatus + "). It cannot be reactivated like this.\n" +"To include this image in the processing, you must either restore the corresponding processing status for all active images, " "or close THELI and manually restore all suitable images, or start from the raw data."); } bool Controller::isExposureActive(QList<MyImage*> exposure) { bool active = false; for (auto &it : exposure) { if (it->activeState == MyImage::ACTIVE) { active = true; break; } } return active; } /* void Controller::decrementCurrentThreads(omp_lock_t &lock) { omp_set_lock(&lock); // --currentExternalThreads; --currentThreadsRunning; if (availableThreads < maxCPU) ++availableThreads; omp_unset_lock(&lock); } */ /* void Controller::incrementCurrentThreads(omp_lock_t &lock) { omp_set_lock(&lock); // ++currentExternalThreads; ++currentThreadsRunning; if (availableThreads > 0) --availableThreads; omp_unset_lock(&lock); } */ /* int Controller::reserveAvailableThreads(omp_lock_t &lock) { int numInternalThreads = 1; // Consume remaining available threads. while (availableThreads > 0) { omp_set_lock(&lock); ++numInternalThreads; --availableThreads; omp_unset_lock(&lock); // Give the other threads a chance QTest::qWait(100); } return numInternalThreads; } */ /* void Controller::makeThreadsAvailable(omp_lock_t &lock, int numberThreadsBlocked) { omp_set_lock(&lock); availableThreads += numberThreadsBlocked; omp_unset_lock(&lock); } */ /* void Controller::restoreData(MyImage *myImage, QString backupDirName) { // Moves an image from the backupDir to the current Dir QString currentPath = myImage->path; QString backupPath = myImage->path + "/" + backupDirName + "/"; // DO NOT use append() because it will also change the variable one appends to. QFile image(backupPath+"/"+myImage->name); if (!image.exists()) return; if (!image.rename(currentPath+"/"+myImage->name)) { QString command = "mv " + backupPath+"/"+myImage->name + currentPath+"/"+myImage->name; emit messageAvailable("CTRL: restoreData(): Could not execute the following operation: <br> " + command, "error"); criticalReceived(); } } */ /* int Controller::getInternalThreads(int chip) { QVector<QString> PARA(instData->numChips); maxExternalThreads; int i=1; while (i<=instData->numChips) { PARA[i] = ""; ++i; } // Assign chips to CPUs int k = 1; while (k <= maxExternalThreads) { int ACTUPROC = 1; while (ACTUPROC <= instData->numChips && k <= maxExternalThreads) { PARA[ACTUPROC].append(QString::number(k)); ++k; ++ACTUPROC; } } k = 1; QString nthread = ""; while (k <= instData->numChips) { int numthread = PARA[k].split(" ").length(); if (numthread == 0) numthread = 1; nthread.append(numthread); ++k; } return nthread.split(" ").at(chip); } */ /* void Controller::incrementProgress() { omp_set_lock(&progressLock); progress += progressStepSize; emit progressUpdate(progress); omp_unset_lock(&progressLock); } */ /* void Controller::incrementProgressHalfStep() { // omp_set_lock(&progressLock); progress += progressStepSize/2.; emit progressUpdate(progress); // omp_unset_lock(&progressLock); } */ /* void Controller::incrementProgressCombinedStep() { // omp_set_lock(&progressLock); progress += progressCombinedStepSize; emit progressUpdate(progress); // omp_unset_lock(&progressLock); } */ /* void Controller::rereadDataDir(QLineEdit *le, QList<Data *> &DT_x) { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); for (auto &data: DT_x) { delete data; } DT_x.clear(); parseDataDir(le, DT_x); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } */ /* void Controller::displayDriveSpace() { // Storage space in the main/home directory QString maindir = mainGUI->ui->setupMainLineEdit->text(); double GBtotal_data, GBfree_data, GBused_data; double GBtotal_home, GBfree_home, GBused_home; QStorageInfo storage_home(QDir::homePath()); if (storage_home.isValid() && storage_home.isReady()) { GBtotal_home = storage_home.bytesTotal()/1024./1024./1024.; GBfree_home = storage_home.bytesAvailable()/1024./1024./1024.; GBused_home = GBtotal_home - GBfree_home; } else { emit messageAvailable("Controller::displayDriveSpace(): Cannot determine home directory!", "error"); return; } QStorageInfo storage_data(maindir); if (storage_data.isValid() && storage_data.isReady()) { GBtotal_data = storage_data.bytesTotal()/1024./1024./1024.; GBfree_data = storage_data.bytesAvailable()/1024./1024./1024.; GBused_data = GBtotal_data - GBfree_data; } else { GBtotal_data = GBtotal_home; GBfree_data = GBfree_home; GBused_data = GBused_home; } mainGUI->driveProgressBar->setRange(0, GBtotal_data); QString datadiskstring = QString::number(GBfree_data,'f',2) + " GB left"; // check if the data disk warning should be activated if (GBfree_data <= mainGUI->diskwarnPreference/1024.) { // preference is given in MB if (!mainGUI->datadiskspace_warned) { mainGUI->datadiskspace_warned = true; if (maindir.isEmpty()) maindir = QDir::homePath(); QMessageBox::warning( this, "THELI: DATA DISK SPACE LOW", "The remaining disk space on\n\n" + maindir+"\n\nis less than your warning threshold of " + QString::number(mainGUI->diskwarnPreference)+" MB.\n" "The threshold can be set under Edit->Preferences in the main menu. " "This warning will not be shown anymore in this session, " "unless you update the threshold to a new value."); } } else mainGUI->datadiskspace_warned = false; if (GBfree_home <= 0.1) { if (!mainGUI->homediskspace_warned) { mainGUI->homediskspace_warned = true; QMessageBox::warning( this, "THELI: HOME DISK SPACE LOW", "THELI: You are running low (<100 MB) on disk space in your home directory!\n"); } } else mainGUI->homediskspace_warned = false; mainGUI->driveProgressBar->setFormat("Drive: "+datadiskstring); mainGUI->driveProgressBar->setValue(GBused_data); } */ /* void Controller::processExternalStdout() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); // emit messageAvailable(stdout, "normal"); } void Controller::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stderr(process->readAllStandardError()); emit messageAvailable(stderr, "normal"); } */ /* void Controller::splitterMemoryReceived(long memoryUsed) { #pragma omp atomic splitterMemoryUsed += memoryUsed; emit updateMemoryProgressBar(splitterMemoryUsed / 1024 / 1024); } */ /* void Controller::displayCPUload() { // int CPUload = myCPU->getCPUload(); float CPUload = myCPU->getCurrentValue(); QString CPUstring = QString::number(int(CPUload)) + " %"; mainGUI->cpuProgressBar->setFormat("CPU: "+CPUstring); mainGUI->cpuProgressBar->setValue(int(CPUload)); } void Controller::displayRAMload() { float RAMload = myRAM->getCurrentValue(); QString RAMstring = QString::number(long(RAMload)) + " MB"; mainGUI->memoryProgressBar->setFormat("RAM: %p% ("+RAMstring+")"); mainGUI->memoryProgressBar->setValue(int(RAMload)); } */ /* void Controller::displayMemoryTotalUsed() { // CHECK: in principle, the memoryLock should be sufficient to avoid crashes if (dataTreeUpdateOngoing) return; // Interferes with releaseMemory(), e.g. when memoryCurrentFootprint() evaluates the // capacity of a vector while it is being squeezed at the same time. // Cannot do this inside getMemoryTotalUsed() itself, because that is called by releasememory(), which in turn sets the lock omp_set_lock(&memoryLock); float totalMemory = getMemoryTotalUsed(); omp_unset_lock(&memoryLock); QString memoryString = QString::number(long(totalMemory)) + " MB"; mainGUI->memoryProgressBar->setFormat("RAM: %p% ("+memoryString+")"); mainGUI->memoryProgressBar->setValue(long(totalMemory)); } */ /* // crashes when used right at startup // CHECK: still crashes? QStringList Controller::getFilterList(QString scienceDir) { Data *scienceData = getData(DT_SCIENCE, scienceDir); QStringList filterList; QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { auto &it = allMyImages[k]; it->loadHeader(); #pragma omp critical { if (!filterList.contains(it->filter)) filterList << it->filter; } } return filterList; } */ /* void Controller::progressUpdateReceived(float progress) { emit progressUpdate(progress); } */ // UNUSED /* void Controller::updateSingle() { dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); emit clearMemoryView(); QLineEdit *le = qobject_cast<QLineEdit*>(sender()); if (le == mainGUI->ui->setupMainLineEdit) mainDirName = le->text(); else if (le == mainGUI->ui->setupBiasLineEdit) parseDataDir(le, DT_BIAS); else if (le == mainGUI->ui->setupDarkLineEdit) parseDataDir(le, DT_DARK); else if (le == mainGUI->ui->setupFlatLineEdit) parseDataDir(le, DT_FLATOFF); else if (le == mainGUI->ui->setupFlatoffLineEdit) parseDataDir(le, DT_FLAT); else if (le == mainGUI->ui->setupScienceLineEdit) parseDataDir(le, DT_SCIENCE); else if (le == mainGUI->ui->setupSkyLineEdit) parseDataDir(le, DT_SKY); else if (le == mainGUI->ui->setupStandardLineEdit) parseDataDir(le, DT_STANDARD); updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; } */
54,373
C++
.cc
1,352
33.947485
181
0.664154
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,466
photinst.cc
schirmermischa_THELI/src/processingInternal/photinst.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "photinst.h" #include "../functions.h" #include <QVector> PhotInst::PhotInst(QObject *parent) : QObject(parent) { fluxScale.clear(); expTime.clear(); RZP.clear(); indexMap.clear(); baseName.clear(); } void PhotInst::getRZP() { numExp = fluxScale.length(); for (int j=0; j<numExp; ++j) { RZP << -2.5*log10(fluxScale[j] * expTime[j]); } double meanRZP = meanMask_T(RZP); // Mean relative ZP for (auto &it : RZP) { it -= meanRZP; } // THELI FLXSCALE for (int j=0; j<numExp; ++j) { fluxScale[j] = pow(10., -0.4*RZP[j]) / expTime[j]; } }
1,311
C++
.cc
41
28.634146
75
0.702703
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,467
processingBackground.cc
schirmermischa_THELI/src/processingInternal/processingBackground.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include "../query/query.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalBackground() { QString scienceDir = instructions.split(" ").at(1); QString skyDir = instructions.split(" ").at(2); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigBackground(); // Need to fill myImageList to get Filter keyword (if the user starts fresh with this task after launching THELI) if (scienceData->myImageList[instData->validChip].isEmpty()) scienceData->populate(scienceData->processingStatus->statusString); if (!scienceData->hasImages()) return; if (!scienceData->collectMJD()) return; // Leave if identical MJD entries are found (or no MJD entries at all) scienceData->resetProcessbackground(); scienceData->resetObjectMasking(); Data *skyData = nullptr; if (skyDir == "noskydir") skyData = scienceData; // The background is calculated either from science or from sky images else { skyData = getData(DT_SKY, skyDir); if (skyData == nullptr) return; // Error triggered by getData(); if (!skyData->hasImages()) return; if (!skyData->collectMJD()) return; skyData->resetProcessbackground(); skyData->resetObjectMasking(); } skyData->rescaleFlag = true; // Background images must be rescaled before combination into the final model memoryDecideDeletableStatus(scienceData, false); backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Static or dynamic mode ? scienceData->resetStaticModel(); skyData->resetStaticModel(); QString window = cdw->ui->BACwindowLineEdit->text(); QString mode = "dynamic"; if (window.isEmpty() || window.toInt() == 0) { mode = "static"; } scienceData->checkModeIsPresent(); skyData->checkModeIsPresent(); // Flag images with bright stars, leave if definitely too few images left QList<QVector<double>> brightStarList; retrieveBrightStars(skyData, brightStarList); if (!idChipsWithBrightStars(skyData, brightStarList)) return; bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); QVector<QString> numBackExpList(instData->numChips); float windowsize; if (window.isEmpty() || window == "0") windowsize = scienceData->myImageList[instData->validChip].length(); else windowsize = window.toInt(); float nimg = 7 + windowsize; // image, combined image, new image, background, measure, segment, mask + window data; modify for SKY images? releaseMemory(nimg*instData->storage*maxExternalThreads, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); skyData->protectMemory(); doDataFitInRAM(scienceData->myImageList[instData->validChip].length()*instData->numUsedChips, instData->storage); QString dt = cdw->ui->BACDTLineEdit->text(); QString dmin = cdw->ui->BACDMINLineEdit->text(); QString expFactor = cdw->ui->BACmefLineEdit->text(); QString nlow1 = cdw->ui->BAC1nlowLineEdit->text(); QString nhigh1 = cdw->ui->BAC1nhighLineEdit->text(); QString nlow2 = cdw->ui->BAC2nlowLineEdit->text(); QString nhigh2 = cdw->ui->BAC2nhighLineEdit->text(); bool twoPass = cdw->ui->BAC2passCheckBox->isChecked(); bool convolution = cdw->ui->BACconvolutionCheckBox->isChecked(); bool rescaleModel = cdw->ui->BACrescaleCheckBox->isChecked(); int nGroups = cdw->ui->SPSnumbergroupsLineEdit->text().toInt(); int nLength = cdw->ui->SPSlengthLineEdit->text().toInt(); QVector<bool> staticImagesWritten(instData->numChips); for (auto &it : staticImagesWritten) it = false; // **************************************** // OLD PARALLELIZATION SCHEME (good if numCPU <= numChips) // **************************************** processBackground(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, mode, staticImagesWritten); // **************************************** // NEW PARALLELIZATION SCHEME (good if numCPU > numChips); still not thread-safe // **************************************** /* if (mode == "static") { processBackgroundStatic(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, staticImagesWritten); } else { processBackgroundDynamic(scienceData, skyData, nimg, numBackExpList, dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, twoPass, convolution, rescaleModel, nGroups, nLength, staticImagesWritten); } */ if (!successProcessing) return; emit messageAvailable("<br>", "output"); emit messageAvailable("Number of images used in the background models:<br>", "controller"); for (auto &str : numBackExpList) { emit messageAvailable(str, "ignore"); } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); // Clean-up, otherwise interference with any source detection / masking task scienceData->cleanBackgroundModelStatus(); skyData->cleanBackgroundModelStatus(); if (successProcessing) { scienceData->processingStatus->Background = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header } } //void Controller::processBackground(Data *scienceData, Data *skyData, const float nimg, QVector<QString> &numBackExpList, // const QString dt, const QString dmin, const QString expFactor, const QString nlow1, // const QString nhigh1, const QString nlow2, const QString nhigh2, // const bool twoPass, const bool convolution, const bool rescaleModel, // const int nGroups, const int nLength, const QString mode, QVector<bool> &staticImagesWritten) void Controller::processBackground(Data *scienceData, Data *skyData, const float nimg, QVector<QString> &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QString mode, QVector<bool> &staticImagesWritten) { QString dataDirName = scienceData->dirName; QString dataSubDirName = scienceData->subDirName; QVector<bool> dataStaticModelDone = skyData->staticModelDone; #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, mode, dataDirName, dataSubDirName, dataStaticModelDone) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; int currentExposure = 0; // only relevant for LIRIS@WHT-type detectors where we need to select specific images QString backExpList = ""; bool pass2staticDone = false; for (auto &it : scienceData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; // The list of background images. // Each image has a flag whether it contributes to the model. Initially, all are set to 'false' if (!setupBackgroundList(chip, skyData, it->chipName)) continue; // cannot use break in OMP loop if (!filterBackgroundList(chip, skyData, it, backExpList, nGroups, nLength, currentExposure, mode)) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage(mode, dataStaticModelDone[chip], it->chipName, 1); maskObjectsInSkyImagesPass1(chip, skyData, scienceData, twoPass, dt, dmin, convolution, expFactor); skyData->combineImages(chip, nlow1, nhigh1, it->chipName, mode, dataDirName, dataSubDirName, dataStaticModelDone); skyData->combinedImage[chip]->modeDetermined = false; // must redetermine! skyData->getModeCombineImages(chip); // PASS 2: if (twoPass) { sendBackgroundMessage(mode, dataStaticModelDone[chip], it->chipName, 2); maskObjectsInSkyImagesPass2(chip, skyData, scienceData, twoPass, dt, dmin, convolution, expFactor, rescaleModel); if (mode == "static" && !pass2staticDone) dataStaticModelDone[chip] = false; // must recalculate static model (dynamic model will always be recalculated) skyData->combineImages(chip, nlow2, nhigh2, it->chipName, mode, dataDirName, dataSubDirName, dataStaticModelDone); pass2staticDone = true; skyData->combinedImage[chip]->modeDetermined = false; // must redetermine! skyData->getModeCombineImages(chip); } skyData->writeBackgroundModel(chip, mode, it->baseName, staticImagesWritten[chip]); if (mode == "static") dataStaticModelDone[chip] = true; it->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } // if (mode == "dynamic") it->releaseMemoryForBackground(); if (mode == "dynamic") scienceData->unprotectMemoryForBackground(chip); #pragma omp atomic progress += progressStepSize; ++currentExposure; } // In critical section because length of QString backexpList is variable, and Qvector<QString> is probably not thread safe because of this #pragma omp critical { numBackExpList[chip] = backExpList; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } /* //void Controller::processBackgroundStatic(Data *scienceData, Data *skyData, const float &nimg, QVector<QString> &numBackExpList, // const QString &dt, const QString &dmin, const QString &expFactor, const QString &nlow1, // const QString &nhigh1, const QString &nlow2, const QString &nhigh2, // const bool &twoPass, const bool &convolution, const bool &rescaleModel, // const int &nGroups, const int &nLength, QVector<bool> &staticImagesWritten) void Controller::processBackgroundStatic(Data *scienceData, Data *skyData, const float nimg, QVector<QString> &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector<bool> &staticImagesWritten) { // The following is needed for the new scheme QVector<QString> backExpList(maxCPU); QVector<int> currentExposure(instData->numChips); // relevant only for LIRIS@WHT-type detectors QVector<bool> staticImagesCombined(instData->numChips); QVector<MyImage*> combinedBackgroundImages(maxCPU); for (auto &it : backExpList) it = ""; for (auto &it : backExpListRescaleFactors) it = ""; for (auto &it : currentExposure) it = 0; for (auto &it : staticImagesCombined) it = false; for (auto &it : combinedBackgroundImages) it = nullptr; QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QString dataSubDirName = scienceData->subDirName; #pragma omp parallel for num_threads(maxCPU) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, dataSubDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; int threadID = omp_get_thread_num(); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData_newParallel(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; internal lock // The list of background images. Each image has a flag whether it contributes to the model. No locking required QList<MyImage*> backgroundList; if (!filterBackgroundList(chip, skyData, it, backExpList[threadID], backgroundList, nGroups, nLength, currentExposure[chip], "static")) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage("static", skyData->staticModelDone[chip], it->chipName, 1); maskObjectsInSkyImagesPass1_newParallel(skyData, scienceData, backgroundList, twoPass, dt, dmin, convolution, expFactor, threadID); MyImage *masterCombined = new MyImage(dirName, "dummy.fits", "", chip+1, skyData->mask->globalMask[chip], skyData->mask->isChipMasked[chip], &verbosity); // do this only once per chip omp_set_lock(&backgroundLock); if (!staticImagesCombined[chip]) { skyData->combineImages_newParallel(chip, masterCombined, backgroundList, nlow1, nhigh1, it->chipName, "static", dataSubDirName); skyData->combinedImage[chip] = masterCombined; skyData->combinedImage[chip]->naxis1 = it->naxis1; skyData->combinedImage[chip]->naxis2 = it->naxis2; skyData->combinedImage[chip]->dataCurrent.swap(masterCombined->dataCurrent); skyData->getModeCombineImages(chip); staticImagesCombined[chip] = true; } omp_unset_lock(&backgroundLock); // PASS 2: if (twoPass) { sendBackgroundMessage("static", skyData->staticModelDone[chip], it->chipName, 2); maskObjectsInSkyImagesPass2_newParallel(skyData, scienceData, masterCombined, backgroundList, twoPass, dt, dmin, convolution, expFactor, chip, rescaleModel, threadID, "static"); // do this only once per chip omp_set_lock(&backgroundLock); // CHECK: must recalculate 2nd-pass static model (?) // also, in pass2_newparalell, must check for maskObjectsDonePass2 if (!staticImagesCombined[chip]) { skyData->combineImages_newParallel(chip, skyData->combinedImage[chip], backgroundList, nlow2, nhigh2, it->chipName, "static", dataSubDirName); skyData->getModeCombineImages(chip); } omp_unset_lock(&backgroundLock); } skyData->writeBackgroundModel_newParallel(chip, skyData->combinedImage[chip], "static", it->baseName, threadID, backgroundLock, staticImagesWritten[chip]); skyData->staticModelDone[chip] = true; it->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel, backExpListRescaleFactors); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } #pragma omp atomic progress += progressStepSize; ++currentExposure[chip]; // In critical section because length of QString backexpList is variable, and Qvector<QString> is probably not thread safe because of this #pragma omp critical { // Join the number of exposures with the rescale factors QVector<QString> joinedList(maxCPU); numBackExpList[chip] = backExpList[chip]; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } //void Controller::processBackgroundDynamic(Data *scienceData, Data *skyData, const float &nimg, QVector<QString> &numBackExpList, // const QString &dt, const QString &dmin, const QString &expFactor, const QString &nlow1, // const QString &nhigh1, const QString &nlow2, const QString &nhigh2, // const bool &twoPass, const bool &convolution, const bool &rescaleModel, // const int &nGroups, const int &nLength, QVector<bool> &staticImagesWritten) void Controller::processBackgroundDynamic(Data *scienceData, Data *skyData, const float nimg, QVector<QString> &numBackExpList, QString dt, QString dmin, QString expFactor, QString nlow1, QString nhigh1, QString nlow2, QString nhigh2, const bool twoPass, const bool convolution, const bool rescaleModel, const int nGroups, const int nLength, QVector<bool> &staticImagesWritten) { // The following is needed for the new scheme QVector<QString> backExpList(maxCPU); QVector<int> currentExposure(instData->numChips); // relevant only for LIRIS@WHT-type detectors QVector<bool> staticImagesCombined(instData->numChips); QVector<MyImage*> combinedBackgroundImages(maxCPU); for (auto &it : backExpList) it = ""; for (auto &it : currentExposure) it = 0; for (auto &it : staticImagesCombined) it = false; for (auto &it : combinedBackgroundImages) it = nullptr; QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QString dataSubDirName = scienceData->subDirName; #pragma omp parallel for num_threads(maxCPU backExpRescaleFactors.append("1.000; no rescaling when dividing model");) firstprivate(dt, dmin, expFactor, nlow1, nhigh1, nlow2, nhigh2, backExpList, allMyImages, dataSubDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; int threadID = omp_get_thread_num(); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Modeling background ...", "image"); it->processingStatus->Background = false; it->setupBackgroundData_newParallel(scienceData->isTaskRepeated, backupDirName); // Put original flat-fielded data in dataBackupL1; internal lock // The list of background images. Each image has a flag whether it contributes to the model. No locking required QList<MyImage*> backgroundList; if (!filterBackgroundList(chip, skyData, it, backExpList[threadID], backgroundList, nGroups, nLength, currentExposure[chip], "dynamic")) { continue; // cannot use break in OMP loop } // PASS 1: sendBackgroundMessage("dynamic", skyData, it->chipName, 1); maskObjectsInSkyImagesPass1_newParallel(skyData, scienceData, backgroundList, twoPass, dt, dmin, convolution, expFactor, threadID); MyImage *masterCombined = new MyImage(dirName, "dummy.fits", "", chip+1, skyData->mask->globalMask[chip], skyData->mask->isChipMasked[chip], &verbosity); skyData->combineImages_newParallel(chip, masterCombined, backgroundList, nlow1, nhigh1, it->chipName, "dynamic", dataSubDirName); skyData->getModeCombineImagesBackground(chip, masterCombined); masterCombined->naxis1 = it->naxis1; masterCombined->naxis2 = it->naxis2; combinedBackgroundImages[threadID] = masterCombined; // PASS 2: if (twoPass) { sendBackgroundMessage("dynamic", skyData, it->chipName, 2); maskObjectsInSkyImagesPass2_newParallel(skyData, scienceData, masterCombined, backgroundList, twoPass, dt, dmin, convolution, expFactor, chip, rescaleModel, threadID, "dynamic"); skyData->combineImages_newParallel(chip, combinedBackgroundImages[threadID], backgroundList, nlow2, nhigh2, it->chipName, "dynamic", dataSubDirName); skyData->getModeCombineImagesBackground(chip, combinedBackgroundImages[threadID]); } skyData->writeBackgroundModel_newParallel(chip, combinedBackgroundImages[threadID], "dynamic", it->baseName, threadID, backgroundLock, staticImagesWritten[chip]); it->applyBackgroundModel(combinedBackgroundImages[threadID], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); // DO NOT UNPROTECT MEMORY HERE (could be needed elsewhere) } #pragma omp atomic progress += progressStepSize; ++currentExposure[chip]; // In critical section because length of QString backexpList is variable, and Qvector<QString> is probably not thread safe because of this #pragma omp critical { numBackExpList[chip] = backExpList[chip]; } // L1 always contains the data before any modification, hence we do not need to create a backup copy. if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { it->makeBackgroundBackup(); backExpRescaleFactors.append("1.000; no rescaling when dividing model"); // just a FITS file operation if necessary } scienceData->unprotectMemory(chip); skyData->unprotectMemory(chip); } } } */ void Controller::maskObjectsInSkyImagesPass1(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor) { // Loop over the list of valid background images and mask the objects bool doSourceDetection = false; QVector<QString> thresholds = getBackgroundThresholds(0, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : skyData->myImageList[chip]) { if (!back->successProcessing) break; if (!back->useForBackground) continue; // that should never be the case because the backgroundlist contains 'valid' images, only, at this point // if (!back->useForBackground) { // back->unprotectMemory(); // TODO: check if possibly dangerous. Can we do this here? Or elsewhere? // continue; // } // reads from dataBackupL1; if not then from disk and creates backup in L1, measures the mode if not yet available back->setupBackgroundData(isTaskRepeated, backupDirName); // Already in memory if skyData == scienceData if (doSourceDetection && !twoPass && !back->objectMaskDonePass1) { // only detect if requested and not yet done; objectMaskDone set to false in skydata outside loops if (verbosity >= 2) emit messageAvailable(back->chipName + " : Detecting and masking sources ...", "image"); back->backgroundModel(256, "interpolate"); back->segmentImage(DT, DMIN, convolution, false); back->transferObjectsToMask(); back->maskExpand(expFactor, false); back->objectMaskDonePass1 = true; } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } void Controller::maskObjectsInSkyImagesPass2(const int chip, Data *skyData, Data *scienceData, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const bool rescaleModel) { bool doSourceDetection = false; QVector<QString> thresholds = getBackgroundThresholds(1, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : skyData->myImageList[chip]) { if (!back->successProcessing) break; if (!back->useForBackground) continue; if (doSourceDetection && !back->objectMaskDonePass2) { if (verbosity >= 2) emit messageAvailable(back->chipName + " : Detecting and masking sources ...", "image"); // Mask objects if not yet done for this sky (science) image // No masking has taken place in PASS 1 if we are in twopass mode! // Subtract 1st pass model: dataCurrent = dataBackupL1 - 1stPassModel back->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); // back->backgroundModelDone = false; // IMPORTANT, otherwise background model step will be skipped back->backgroundModel(256, "interpolate"); // create background model back->segmentImage(DT, DMIN, convolution, false); // detect sources (if requested), do not write seg image back->transferObjectsToMask(); // sets objectMaskDone to true back->maskExpand(expFactor, false); // expand the object mask (if requested) back->objectMaskDonePass2 = true; } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } bool Controller::setupBackgroundList(int chip, Data *skyData, const QString &chipName) { if (!successProcessing) return false; // First, collect all images of this chip, and reset their usability for background modeling to 'false' (or 'true' depending which ones is easier to code) for (auto &it : skyData->myImageList[chip]) { it->useForBackground = false; it->useForBackgroundSequence = true; it->useForBackgroundWindowed = false; it->useForBackgroundStars = true; } if (skyData->myImageList[chip].length() < 2) { emit messageAvailable(chipName + " : At least two images are required for background modeling.", "error"); emit criticalReceived(); successProcessing = false; return false; } return true; } bool Controller::filterBackgroundList(const int chip, Data *skyData, MyImage *it, QString &backExpList, const int nGroups, const int nLength, const int currentExposure, const QString mode) { if (!successProcessing) return false; if (!it->successProcessing) return false; selectImagesFromSequence(skyData->myImageList[chip], nGroups, nLength, currentExposure); // Update flag: Select every n-th image, only, if requested // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackgroundSequence; // qDebug() << ""; if (mode == "dynamic") selectImagesDynamically(skyData->myImageList[chip], it->mjdobs); // Update flag: dynamic or static mode else selectImagesStatically(skyData->myImageList[chip], it); // Already sets BADBACK flag if necessary // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackgroundSequence << back->useForBackgroundWindowed; // qDebug() << ""; flagImagesWithBrightStars(skyData->myImageList[chip]); // Update flag: Exclude images affected by bright stars if (!it->successProcessing) return false; // Leave if not sufficiently many images found for background modeling // Combine the flags from all three tests combineAllBackgroundUsabilityFlags(skyData->myImageList[chip]); // for (auto &back : skyData->myImageList[chip]) qDebug() << back->baseName << back->useForBackground; // qDebug() << ""; int nback = countBackgroundImages(skyData->myImageList[chip], it->chipName); QString outstring = it->chipName + " : " + QString::number(nback) + "<br>"; if (nback < 4) backExpList.append("<font color=#ee5500>" + outstring + "</font>"); // color coding to highlight potentially poor images else backExpList.append(outstring); if (!successProcessing || nback < 2 || !it->successProcessing) { emit messageAvailable(it->chipName + " : No (or not sufficiently many) suitable background images found", "warning"); it->activeState = MyImage::BADBACK; it->successProcessing = false; return false; } return true; } /* void Controller::maskObjectsInSkyImagesPass1_newParallel(Data *skyData, Data *scienceData, const QList<MyImage*> &backgroundList, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const int threadID) { // Loop over the list of valid background images and calculate the model bool doSourceDetection = false; QVector<QString> thresholds = getBackgroundThresholds(0, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : backgroundList) { if (!back->successProcessing) break; // if (!back->useForBackground) { // back->unprotectMemory(); // TODO: check if possibly dangerous. Can we do this here? Or elsewhere? // continue; // } // reads from dataBackupL1; if not then from disk and creates backup in L1, measures the mode if not yet available back->setupBackgroundData_newParallel(isTaskRepeated, backupDirName); // Already in memory if skyData == scienceData if (doSourceDetection && !twoPass) { // only detect if requested and not yet done previously; objectMaskDone set to false in skydata outside loops back->setObjectLock(true); if (!back->objectMaskDone) { back->backgroundModel(256, "interpolate"); back->segmentImage(DT, DMIN, convolution, false); back->transferObjectsToMask(); back->maskExpand(expFactor, false); } back->setObjectLock(false); } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } void Controller::maskObjectsInSkyImagesPass2_newParallel(Data *skyData, Data *scienceData, MyImage *combinedImage, const QList<MyImage*> &backgroundList, const bool twoPass, const QString dt, const QString dmin, const bool convolution, const QString expFactor, const int chip, const bool rescaleModel, const int threadID, const QString mode) { bool doSourceDetection = false; QVector<QString> thresholds = getBackgroundThresholds(1, twoPass, dt, dmin, doSourceDetection); QString DT = thresholds[0]; QString DMIN = thresholds[1]; for (auto &back : backgroundList) { if (!back->successProcessing) break; if (!back->useForBackground) continue; if (doSourceDetection) { back->setObjectLock(true); // Mask objects if not yet done for this sky (science) image // No masking has taken place in PASS 1 if we are in twopass mode! // Subtract 1st pass model: dataCurrent = dataBackupL1 - 1stPassModel if (!back->objectMaskDone) { if (mode == "dynamic") back->applyBackgroundModel(combinedImage, cdw->ui->BACapplyComboBox->currentText(), rescaleModel); else back->applyBackgroundModel(skyData->combinedImage[chip], cdw->ui->BACapplyComboBox->currentText(), rescaleModel); // back->backgroundModelDone = false; // IMPORTANT, otherwise background model step will be skipped back->backgroundModel(256, "interpolate"); // create background model back->segmentImage(DT, DMIN, convolution, false); // detect sources (if requested), do not write seg image back->transferObjectsToMask(); // sets objectMaskDone to true back->maskExpand(expFactor, false); // expand the object mask (if requested) } back->setObjectLock(false); } if (!back->successProcessing) { skyData->successProcessing = false; scienceData->successProcessing = false; } } } */ void Controller::sendBackgroundMessage(const QString mode, const bool staticmodeldone, const QString basename, const int pass) { if (verbosity >= 0) { if ( (mode == "static" && !staticmodeldone) || mode == "dynamic") { if (pass == 1) emit messageAvailable(basename + " : Image combination 1st pass ...", "image"); if (pass == 2) emit messageAvailable(basename + " : Image combination 2nd pass ...", "image"); } } } // Select the 'windowSize' images that are closest in time to the targetMJD void Controller::selectImagesDynamically(const QList<MyImage*> &backgroundList, const double &mjd_ref) { if (!successProcessing) return; if (verbosity == 3) emit messageAvailable("Entering dynamic image selection ...", "image"); QList<QPair<MyImage*, double>> imageListAbs; // sorted with respect to fabs(mjd_diff) QList<QPair<MyImage*, double>> imageListDiff; // sorted with respect to mjd_diff // Reset, and map data onto a list for (auto &it : backgroundList) { // qDebug() << qSetRealNumberPrecision(12) << it->baseName << it->mjdobs; imageListAbs.append(qMakePair(it,fabs(it->mjdobs-mjd_ref))); imageListDiff.append(qMakePair(it,it->mjdobs-mjd_ref)); } // Sort with respect to mjd difference std::sort(imageListAbs.begin(), imageListAbs.end(), QPairSecondComparer()); std::sort(imageListDiff.begin(), imageListDiff.end(), QPairSecondComparer()); // Mark the first 'windowSize' images, using fabs(mjd_diff), provided they passed the 'spread sequence' test int selected = 0; int windowSize = cdw->ui->BACwindowLineEdit->text().toInt(); if (windowSize > backgroundList.length()) { QString part1 = QString::number(windowSize); QString part2 = QString::number(backgroundList.length()); emit showMessageBox("Controller::WINDOWSIZE_TOO_LARGE", part1, part2); successProcessing = false; return; } // Here's the selection function for (auto &it : imageListAbs) { // Do not use the current image to contribute to its own background model (it->useForBackgroundWindowed remains 'false') if (it.second > 0.) { if (selected < windowSize && it.first->activeState == MyImage::ACTIVE && it.first->useForBackgroundSequence) { it.first->useForBackgroundWindowed = true; it.first->enteredBackgroundWindow = true; ++selected; } else { it.first->useForBackgroundWindowed = false; // redundant. Set to false by default when entering this function // free RAM if (it.first->enteredBackgroundWindow && !it.first->leftBackgroundWindow) { it.first->leftBackgroundWindow = true; it.first->releaseBackgroundMemoryBackgroundModel(); it.first->releaseAllDetectionMemory(); // if (minimizeMemoryUsage) { // it.first->freeAll(); // } } } } } // Check if there is a gap larger than the max gap size in the window QString maxGapString = cdw->ui->BACgapsizeLineEdit->text(); if (!maxGapString.isEmpty()) { int count = 0; double mjd_previous = 0.; bool gapViolated = false; double currentGap = 0.; double maxGap = maxGapString.toDouble() / 24.; // convert from hours to days (MJD) for (auto &it : imageListDiff) { if (it.first->useForBackgroundWindowed) { if (count == 0) { mjd_previous = it.first->mjdobs; ++count; } else { currentGap = it.first->mjdobs - mjd_previous; mjd_previous = it.first->mjdobs; ++count; if (currentGap > maxGap) { gapViolated = true; break; } } } } if (gapViolated) { QString part1 = QString::number(currentGap*24,'f',3); emit showMessageBox("Controller::GAP_DYNAMIC_FOUND", part1, maxGapString); successProcessing = false; } } QString minWindowSizeString = cdw->ui->BACminWindowLineEdit->text(); int minWindowSize; if (minWindowSizeString.isEmpty()) minWindowSize = windowSize; else minWindowSize = minWindowSizeString.toInt(); if (selected < minWindowSize) { QString part1 = QString::number(selected); QString part2 = QString::number(minWindowSize); emit showMessageBox("Controller::INSUFFICIENT_BACKGROUND_NUMBER", part1, part2); successProcessing = false; } } // Select the images that are closest in time to the targetMJD and within a valid block defined by gap sizes void Controller::selectImagesStatically(const QList<MyImage*> &backgroundList, MyImage *scienceImage) { if (!successProcessing) return; if (!scienceImage->successProcessing) return; double mjd_ref = scienceImage->mjdobs; if (verbosity == 3) emit messageAvailable("Entering static image selection ...", "image"); QList<QPair<MyImage*, double>> imageListDiff; // sorted with respect to mjd_diff // Reset, and map data onto a list for (auto &it : backgroundList) { // it->useForBackground = false; imageListDiff.append(qMakePair(it, it->mjdobs - mjd_ref)); } // Sort with respect to mjd difference std::sort(imageListDiff.begin(), imageListDiff.end(), QPairSecondComparer()); // Identify blocks (if a gap was defined) // Use a giant maxGap (longer than an observer's lifetime) if no gap was defined QString maxGapString = cdw->ui->BACgapsizeLineEdit->text(); double maxGap = 1e9; if (!maxGapString.isEmpty()) maxGap = maxGapString.toDouble() / 24.; int blockCount = 0; double mjd_previous = imageListDiff[0].first->mjdobs; for (auto &it : imageListDiff) { double currentGap = it.first->mjdobs - mjd_previous; if (currentGap > maxGap) ++blockCount; it.first->backgroundBlock = blockCount; mjd_previous = it.first->mjdobs; } // Decide which block is the best (if any) to correct the image with mjd_ref int scienceBlockId = -1; int nSky = imageListDiff.length(); for (int i=0; i<nSky; ++i) { double mjd_obs1; double mjd_obs2; if (i<nSky-1) { mjd_obs1 = imageListDiff[i].first->mjdobs; mjd_obs2 = imageListDiff[i+1].first->mjdobs; } else { mjd_obs1 = imageListDiff[i].first->mjdobs; mjd_obs2 = imageListDiff[i-1].first->mjdobs; } double d1 = fabs(mjd_ref - mjd_obs1); double d2 = fabs(mjd_ref - mjd_obs2); int blockID1; int blockID2; if (i<nSky-1) { blockID1 = imageListDiff[i].first->backgroundBlock; blockID2 = imageListDiff[i+1].first->backgroundBlock; } else { blockID1 = imageListDiff[i].first->backgroundBlock; blockID2 = imageListDiff[i-1].first->backgroundBlock; } // Cases where a science exposure has a valid sky block if (i==0 && mjd_ref < mjd_obs1 && d1 < maxGap) scienceBlockId = blockID1; // image before first sky exposure if (i==nSky-1 && mjd_ref > mjd_obs1 && d1 < maxGap) scienceBlockId = blockID1; // image after last sky exposure if (mjd_ref == mjd_obs1) scienceBlockId = blockID1; // image identical to sky image if (scienceBlockId != -1) break; // Leave if matching block was found if (i==nSky-1) break; // stay within bounds for mjd_obs2, d2, and blockID2 // Image must have been taken within the sky sequence // science image between two sky exposures // if (mjd_ref > mjd_obs1 && mjd_ref < mjd_obs2) { // excluding the science image from the model if (mjd_ref >= mjd_obs1 && mjd_ref <= mjd_obs2) { // including the science image from the model // within a block or between blocks if (blockID1 == blockID2) scienceBlockId = blockID1; else { // Assign the closer block, if within maxGap if (d1 <= d2 && d1 < maxGap) scienceBlockId = blockID1; if (d2 < d1 && d2 < maxGap) scienceBlockId = blockID2; } } if (scienceBlockId != -1) break; } // Set the flag for all sky exposures that have the same block ID as the science exposure, and passed the 'spread sequence' test // Remember, imageListDiff just contains pointers into backgroundList, so we // are indeed updating the flags in the backgroundList int countSky = 0; // the number of sky images used for correction for (auto &it : imageListDiff) { if (it.first->backgroundBlock == scienceBlockId && it.first->activeState == MyImage::ACTIVE && it.first->useForBackgroundSequence) { it.first->useForBackgroundWindowed = true; ++countSky; } } // Always use all images for the static model: comment out the following /* // Do not use the current image to contribute to its own background model for (auto &it : imageListDiff) { if (it.second == 0.) { it.first->useForBackgroundWindowed = false; --countSky; } } */ if (scienceBlockId == -1) { emit messageAvailable(scienceImage->chipName + " : Could not identify suitable sky images. Image deactivated.", "warning"); emit warningReceived(); scienceImage->activeState = MyImage::BADBACK; scienceImage->successProcessing = false; if (scienceImage->imageOnDrive) { moveFile(scienceImage->baseName+".fits", scienceImage->path, scienceImage->path+"/inactive/badBackground/"); scienceImage->path = scienceImage->path+"/inactive/badBackground/"; scienceImage->emitModelUpdateNeeded(); } return; } if (countSky < 3) { emit messageAvailable(scienceImage->chipName + " : Less than three images found for background modeling. Image deactivated.", "warning"); emit warningReceived(); scienceImage->activeState = MyImage::BADBACK; scienceImage->successProcessing = false; if (scienceImage->imageOnDrive) { moveFile(scienceImage->baseName+".fits", scienceImage->path, scienceImage->path+"/inactive/badBackground/"); scienceImage->path = scienceImage->path+"/inactive/badBackground/"; scienceImage->emitModelUpdateNeeded(); } return; } successProcessing = true; } // If several exposures were taken at the same dither position before an offset, // then sometimes the first and perhaps 2nd image must be corrected separately // from all other first or second exposures. void Controller::selectImagesFromSequence(QList<MyImage*> &backgroundList, const int &nGroups, const int &nLength, const int &currentExp) { if (!successProcessing) return; // Nothing to be done if (nGroups == 0 || nLength == 0) return; // returning with all flags set to 'true', i.e. no contraints // set all flags to false for a start for (auto &it : backgroundList) { it->useForBackgroundSequence = false; } // To which group does the current image belong int groupReference = currentExp % nLength; if (groupReference >= nGroups) groupReference = nGroups - 1; // Assign group numbers to background images int group = 0; int count = 0; for (auto &it : backgroundList) { if (group == groupReference) { it->useForBackgroundSequence = true; // image usable for background modeling } // qDebug() << it->chipName << group << count << groupReference << it->useForBackground; // qDebug() << "AAA" << it->chipName << group << count << groupReference << it->useForBackgroundSequence << currentExp; if (group < nGroups-1) ++group; ++count; if (count == nLength) { count = 0; group = 0; } } // Keep only background images that belong to the same group as the science exposure /* QList<MyImage*>::iterator it = backgroundList.begin(); while (it != backgroundList.end()) { if (! (*it)->useForBackground) it = backgroundList.erase(it); else ++it; } */ /* for (auto &it : backgroundList) { qDebug() << it->chipName; } qDebug() << " " ; */ } // Obtain a list of bright stars from the UCAC catalog. // This is done before we enter the big loops that process the images (because we want to retrieve it only once) void Controller::retrieveBrightStars(Data *skyData, QList<QVector<double>> &brightStarList) { // Leave if not requested QString brightMag = cdw->ui->BACmagLineEdit->text(); if (brightMag.isEmpty()) return; QString mag = ""; QString refcat = ""; if (instData->type == "OPT") { refcat = "UCAC5"; mag = "Rmag"; } else { refcat = "2MASS"; mag = "Hmag"; } emit messageAvailable("Retrieving stars brighter than "+mag+" = "+brightMag+" from "+refcat+" ...", "controller"); skyData->getPointingCharacteristics(); Query *query = new Query(&verbosity); // connect(query, &Query::bulkMotionObtained, cdw, &ConfDockWidget::updateGaiaBulkMotion); connect(query, &Query::messageAvailable, mainGUI, &MainWindow::processMessage); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); query->scienceData = skyData; query->mainDirName = mainDirName; query->refcatName = refcat; query->alpha_manual = QString::number(skyData->RAcenter, 'f', 4); // the query uses QStrings because we execute vizquery.py query->delta_manual = QString::number(skyData->DECcenter, 'f', 4); query->radius_manual = QString::number(skyData->searchRadius, 'f', 2); query->magLimit_string = cdw->ui->BACmagLineEdit->text(); query->maxProperMotion_string = cdw->ui->ARCmaxpmLineEdit->text(); query->doBrightStarQueryFromWeb(); brightStarList.reserve(query->numSources); for (long i=0; i<query->numSources; ++i) { QVector<double> star; star << query->ra_out[i]; star << query->de_out[i]; star << query->mag1_out[i]; brightStarList << star; } QString numstars = QString::number(query->numSources) + " bright stars found "; QString pointing = "within r = "+query->radius_manual+"'"+" of RA = "+query->alpha_manual +", DEC = "+query->delta_manual; emit messageAvailable(numstars+pointing, "controller"); delete query; query = nullptr; } bool Controller::idChipsWithBrightStars(Data *skyData, QList<QVector<double>> &brightStarList) { QString safetyDistanceString = cdw->ui->BACdistLineEdit->text(); QString magLimit = cdw->ui->BACmagLineEdit->text(); if (magLimit.isEmpty()) return true; float safetyDistance = safetyDistanceString.toFloat(); int numImagesAffected = 0; QString imagesAffected = ""; QVector<int> numChipsRejected(instData->numChips, 0); /* // TODO: when collapsing loops, make sure each chip has the same number of exposures #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : skyData->myImageList[chip]) { it->loadHeader(); it->checkBrightStars(brightStarList, safetyDistance, instData->pixscale); if (it->hasBrightStars) { ++numImagesAffected; ++numChipsRejected[chip]; imagesAffected.append(it->baseName + "<br>"); } } } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, skyData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; it->loadHeader(); it->checkBrightStars(brightStarList, safetyDistance, instData->pixscale); if (it->hasBrightStars) { #pragma omp critical { ++numImagesAffected; ++numChipsRejected[chip]; imagesAffected.append(it->chipName + "<br>"); } } } if (numImagesAffected > 0) { emit messageAvailable("Excluding "+QString::number(numImagesAffected) + " images from entering the background model due to bright stars:", "controller"); emit messageAvailable(imagesAffected, "ignore"); } bool critical = false; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; int chipsAvailable = skyData->myImageList[chip].length() - numChipsRejected[chip]; if (chipsAvailable == 0) { emit messageAvailable("Chip "+QString::number(chip+1) + " : No images available for background modeling after bright star filtering.", "error"); critical = true; } else if (chipsAvailable == 1) { emit messageAvailable("Chip "+QString::number(chip+1) + " : Only 1 image available for background modeling after bright star filtering.", "error"); critical = true; } else if (chipsAvailable <= 4) { emit messageAvailable("Chip "+QString::number(chip+1) + " : Only " + QString::number(chipsAvailable) + " images available for background modeling after bright star filtering,<br>"+ "expecting poor performance. Ideally, at least 5 images should remain.", "warning"); } } if (critical) { criticalReceived(); successProcessing = false; return false; } else return true; } void Controller::flagImagesWithBrightStars(const QList<MyImage*> &backgroundList) { for (auto &it : backgroundList) { if (it->hasBrightStars) it->useForBackgroundStars = false; } } // Set an image as usable for background correction only if everything holds void Controller::combineAllBackgroundUsabilityFlags(const QList<MyImage*> &backgroundList) { for (auto &it : backgroundList) { if (it->useForBackgroundSequence && it->useForBackgroundWindowed && it->useForBackgroundStars) { it->useForBackground = true; } } } int Controller::countBackgroundImages(QList<MyImage*> list, QString baseName) { if (!successProcessing) return 0; int count = 0; for (auto &it : list) { if (it->useForBackground) ++count; } if (count < 2) { emit messageAvailable(baseName + " : Less than two images (" + QString::number(count) + ") were found to create the background model.", "warning"); warningReceived(); successProcessing = false; return count; } if (count < 4) { emit messageAvailable(baseName + " : Only " + QString::number(count) + " images contribute to the background model, expecting poor performance.", "warning"); warningReceived(); return count; } return count; }
55,690
C++
.cc
1,004
46.468127
187
0.645319
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,468
mask.cc
schirmermischa_THELI/src/processingInternal/mask.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mask.h" #include "../functions.h" #include "../tools/polygon.h" #include <omp.h> #include <QTextStream> #include <QString> Mask::Mask(const instrumentDataType *instrumentData, QObject *parent) : QObject(parent), instData(instrumentData) { // Initialize the masks initMasks(); } void Mask::initMasks() { // We need as many masks as we have chips // Masks are fully populated, even for chips the user does not want to use, because the latter may change, // but the mask is initialized when the instrument is selected, so we need it for all chips. globalMask.resize(instData->numChips); isChipMasked.resize(instData->numChips); // Resize each mask, and set it to false for (int chip=0; chip<instData->numChips; ++chip) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming globalMask[chip].fill(false, n*m); // Initiate all pixels to be unmasked ("masked = false") isChipMasked[chip] = false; globalMask[chip].squeeze(); // shed excess memory } // The basename of the region mask. // There can be a global mask (without chip number), ending in .reg which is valid for all chips. // And there can be additional, individual masks, ending in_chip.reg QString baseName = instData->nameFullPath; baseName = baseName.remove(".ini"); // Global mask: create the mask for chip 1, then copy it to all other chips. // This assumes that all chips have identical geometries! QString globalMaskName = baseName+".reg"; long n_ref = instData->sizex[0]; long m_ref = instData->sizey[0]; QFile file(globalMaskName); if (file.exists()) { addRegionFilesToMask(n_ref, m_ref, globalMaskName, globalMask[0], isChipMasked[0]); for (int chip=1; chip<instData->numChips; ++chip) { long n = instData->sizex[chip]; long m = instData->sizey[chip]; if (n != n_ref || m != m_ref) { qDebug() << QString(__func__) + " Error: chip geometries must be identical for all chips for a global mask."; break; } isChipMasked[chip] = true; globalMask[chip] = globalMask[0]; } } // Individual mask (addRegionFiles exists immediately if file does not exist) #pragma omp parallel for // NOT parallelized internally (polygon::addPolygon_bool() for (int chip=0; chip<instData->numChips; ++chip) { QString individualMaskName = baseName+"_"+QString::number(chip+1)+".reg"; long n = instData->sizex[chip]; long m = instData->sizey[chip]; addRegionFilesToMask(n, m, individualMaskName, globalMask[chip], isChipMasked[chip]); } } void Mask::invert() { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : globalMask[chip]) { it = !it; } } } /* void Mask::addRectangle(int chip, QVector<long> rect, bool invert) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming // Add rectangular area to mask, possibly inverted long xmin = rect[0]; long xmax = rect[1]; long ymin = rect[2]; long ymax = rect[3]; long i, j; if (xmin >= 0 && xmax >= 0 && ymin >= 0 && ymax >= 0) { if (!invert) { for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { if (i >= xmin && i <= xmax && j >= ymin && j <= ymax) globalMask[chip][i+n*j] = true; } } } else { for (j=0; j<m; ++j) { for (i=0; i<n; ++i) { if (!(i >= xmin && i <= xmax && j >= ymin && j <= ymax)) globalMask[chip][i+n*j] = true; } } } } } */ void Mask::addImage(int chip, QVector<float> segmentationMap, bool invert) { long n = instData->sizex[chip]; // naxis1 after overscan trimming long m = instData->sizey[chip]; // naxis2 after overscan trimming // segmentation map (zero for good p Directory not found in Data classixels, i.e. "no object") for (long i=0; i<n*m; ++i) { if (!invert) { if (segmentationMap[i] != 0.) globalMask[chip][i] = true; } else { if (segmentationMap[i] == 0.) globalMask[chip][i] = true; } } } void Mask::reset() { // Warning: after instrument change, instData->numchips is already the new number of chips, while // the globalMask vector still has the old number! for (auto &it : globalMask) { it.clear(); it.squeeze(); } globalMask.resize(0); }
5,427
C++
.cc
136
33.742647
125
0.630361
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,469
processingSkysub.cc
schirmermischa_THELI/src/processingInternal/processingSkysub.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QStandardPaths> #include <QProgressBar> void Controller::taskInternalSkysub() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; memoryDecideDeletableStatus(scienceData, false); if (!scienceData->hasMatchingPartnerFiles(mainDirName+"/WEIGHTS/", ".weight.fits")) return; // Loop over all chips backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Parameters for sky subtraction QString DT = cdw->ui->skyDTLineEdit->text(); QString DMIN = cdw->ui->skyDMINLineEdit->text(); QString expFactor = cdw->ui->skyMefLineEdit->text(); QString kernelWidth = cdw->ui->skyKernelLineEdit->text(); // Polyfit: read the sky values here, do the polynomial fit, store the gsl_vector with the solution // and evaluate inside the function getNumberOfActiveImages(scienceData); scienceData->cleanBackgroundModelStatus(); bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; if (cdw->ui->skyModelRadioButton->isChecked()) { skysubModel(scienceData, DT, DMIN, expFactor, kernelWidth); } else if (cdw->ui->skyPolynomialRadioButton->isChecked()) { skysubPolynomialFit(scienceData); } else if (cdw->ui->skyConstsubRadioButton->isChecked()) { if (cdw->ui->skyAreaComboBox->currentIndex() == 0) { skysubConstantFromArea(scienceData); } else if (cdw->ui->skyAreaComboBox->currentIndex() == 1) { skysubConstantEachChip(scienceData, DT, DMIN, expFactor, kernelWidth); } else { skysubConstantReferenceChip(scienceData, DT, DMIN, expFactor, kernelWidth); } } else { // Other methods to be implemented } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Skysub = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } } void Controller::skysubPolynomialFit(Data *scienceData) { if (!successProcessing) return; pushBeginMessage("SkysubPoly", scienceData->subDirName); pushConfigSkysubPoly(); scienceData->populateExposureList(); // Measure the sky in all blank regions, update the list of sky nodes in each chip QList<MyImage*> ignoreReturnValue = measureSkyInBlankRegions(scienceData); // Loop over all exposures int order = cdw->ui->skyPolynomialSpinBox->value(); int numExposures = scienceData->exposureList.length(); // Overriding getNumberOfActiveImages() progressStepSize = 100. / (float) numExposures; float nimg = 4; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numExposures, instData->storageExposure); #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; i<numExposures; ++i) { if (abortProcess || !successProcessing) continue; // Skip deactivated exposures (all chips inactive) if (!isExposureActive(scienceData->exposureList[i])) continue; emit messageAvailable("Building polynomial fit for exposure " + QString::number(i) + " / " + QString::number(numExposures), "controller"); QList<QVector<double>> skyPolyfitNodes; // Collect sky nodes from all images belonging to that exposure for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; skyPolyfitNodes.append(it->skyPolyfitNodes); } // Fit a polynomial to the nodes, subtract the model from the images Fitting skyFit; connect(&skyFit, &Fitting::messageAvailable, this, &Controller::messageAvailableReceived); skyFit.makePolynomialFit2D(order, skyPolyfitNodes); if (!skyFit.FITSUCCESS) continue; // TODO: large multi-chip cameras would profit from an internal parallelization // I THINK a simple '#pragma omp for' would take care of this automatically for (auto &it : scienceData->exposureList[i]) { if (abortProcess) break; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtractSkyFit(order, skyFit.c, cdw->ui->skySavemodelCheckBox->isChecked()); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } } } void Controller::skysubConstantFromArea(Data *scienceData) { if (!successProcessing) return; pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); // scienceData->populateExposureList(); // Measure the sky in all blank regions, update the list of sky nodes in each chip QList<MyImage*> listOfAllImages = measureSkyInBlankRegions(scienceData); emit messageAvailable("Calculating mean sky level per exposure ...", "controller"); int numExposures = scienceData->exposureList.length(); doDataFitInRAM(numExposures, instData->storageExposure); progressStepSize = 50. / float(scienceData->exposureList.length()); // Loop over all exposures (consisting of n chips) #pragma omp parallel for num_threads(maxCPU) for (long i=0; i<numExposures; ++i) { if (abortProcess || !successProcessing) continue; // Skip deactivated exposures (all chips inactive) if (!isExposureActive(scienceData->exposureList[i])) continue; // Calculate the mean sky background for the exposure QVector<float> skyBackground; for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) continue; for (auto &position : it->skyPolyfitNodes) { skyBackground.append(position[2]); } } float meanExposureBackground; if (skyBackground.isEmpty()) { QString part1 = scienceData->exposureList[i][0]->rootName; emit showMessageBox("Controller::NO_OVERLAP_WITH_SKYAREA", part1, ""); meanExposureBackground = 0.; successProcessing = false; continue; } else { meanExposureBackground = meanMask(skyBackground); } for (auto &it : scienceData->exposureList[i]) { int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) continue; it->meanExposureBackground = meanExposureBackground; emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); // sky subtraction outsourced below for faster parallelisation } #pragma omp atomic progress += progressStepSize; } if (!successProcessing) return; progressStepSize = 50. / float(listOfAllImages.length()); float nimg = 3; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); emit messageAvailable("Subtracting mean sky level ...", "controller"); // In principle this could be done in nicer form by including it in the last for-loop above #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; i<listOfAllImages.length(); ++i) { if (abortProcess || !successProcessing) continue; auto &it = listOfAllImages[i]; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; releaseMemory(nimg*instData->storage, maxCPU); // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtract(it->meanExposureBackground); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(it->meanExposureBackground); } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } } void Controller::skysubConstantReferenceChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); scienceData->populateExposureList(); // TODO: add a mode that does not require blank sky fields (i.e., if no coords file found, use entire chip) // Measure the sky in all blank regions, update the list of sky nodes in each chip QList<MyImage*> listOfAllImages = measureSkyInBlankRegions(scienceData, "listOnly"); int referenceChip = cdw->ui->skyAreaComboBox->currentIndex(); if (referenceChip < 2) { emit messageAvailable("Controller::skysubConstantReferenceChip(): invalid chip index returned. This is a bug.", "error"); criticalReceived(); successProcessing = false; return; } // Calculate the corrrect chip number (subtract the first two entries of the combo box) referenceChip -= 2; // Loop over all exposures (consisting of n chips) int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } // Create object masks (does not change pixels) progressStepSize = 50. / float(scienceData->exposureList.length()); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); int numExposures = scienceData->exposureList.length(); doDataFitInRAM(numExposures, instData->storageExposure); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor) for (long i=0; i<numExposures; ++i) { if (abortProcess || !successProcessing) continue; // Skip deactivated exposures (all chips inactive) if (!isExposureActive(scienceData->exposureList[i])) continue; releaseMemory(nimg*instData->storage, maxCPU); // Measure the sky background from the reference chip auto &it = scienceData->exposureList[i][referenceChip]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; // Already done in measureSkyInBlankRegions; // Does nothing if image is still in memory. // If not in memory, will just read it again from drive it->setupData(scienceData->isTaskRepeated, false, false); if (!it->successProcessing) { abortProcess = true; continue; } it->resetObjectMasking(); it->backgroundModelDone = false; it->readWeight(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); if (!it->successProcessing) scienceData->successProcessing = false; float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; emit messageAvailable(scienceData->exposureList[0][0]->rootName + " : Exposure background = " + QString::number(meanExposureBackground,'f',2), "image"); for (auto &it : scienceData->exposureList[i]) { it->meanExposureBackground = meanExposureBackground; } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } it->releaseBackgroundMemory("entirely"); it->releaseAllDetectionMemory(); #pragma omp atomic progress += progressStepSize; } if (!successProcessing) return; // Subtract sky (does change pixels) progressStepSize = 50. / float(listOfAllImages.length()); #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName) for (long i=0; i<listOfAllImages.length(); ++i) { if (abortProcess || !successProcessing) continue; auto &it = listOfAllImages[i]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->subtract(it->meanExposureBackground); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(it->meanExposureBackground); } it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp atomic progress += progressStepSize; } } void Controller::skysubConstantEachChip(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; // Loop over all exposures (consisting of n chips) int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } pushBeginMessage("SkysubConst", scienceData->subDirName); pushConfigSkysubConst(); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { it->setupDataInMemory(isTaskRepeated, true, true); it->resetObjectMasking(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; it->subtract(meanExposureBackground); it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; it->writeImage(); emit messageAvailable(it->baseName + " : sky = "+QString::number(meanExposureBackground,'f',2), "controller"); incrementProgress(); } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } decrementCurrentThreads(lock); } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); progressStepSize = 100. / float(numMyImages); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor, backupDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; releaseMemory(nimg*instData->storage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; it->processingStatus->Skysub = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->resetObjectMasking(); it->backgroundModelDone = false; it->readWeight(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); it->mergeObjectWithGlobalMask(); float meanExposureBackground = modeMask(it->dataCurrent, "stable", it->objectMask)[0]; it->subtract(meanExposureBackground); it->saturationValue -= meanExposureBackground; it->updateHeaderSaturation(); updateImageAndData(it, scienceData); // Must write for SWarp! it->writeImage(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeConstSkyImage(meanExposureBackground); } it->unprotectMemory(); it->releaseBackgroundMemory("entirely"); it->releaseAllDetectionMemory(); if (minimizeMemoryUsage) { it->freeAll(); } emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(meanExposureBackground,'f',2) + " e-", "image"); #pragma omp atomic progress += progressStepSize; } /* // Just file moving, no parallelization required for (int chip=0; chip<instData->numChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } } */ } void Controller::skysubModel(Data *scienceData, QString DT, QString DMIN, QString expFactor, QString kernelWidth) { if (!successProcessing) return; pushBeginMessage("SkysubModel", scienceData->subDirName); pushConfigSkysubModel(); int kernel = kernelWidth.toInt(); if (!kernel) { // a kernel width of zero will cause a floating-point-exception // in the calculation of grid points for background modelling emit messageAvailable("Controller::skysubModel(): Kernel width is zero", "error"); criticalReceived(); return; } /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { emit messageAvailable(it->baseName + " : Modeling the sky ...", "controller"); it->setupDataInMemory(isTaskRepeated, true, true); it->readWeight(); // Model background so we can detect objects it->resetObjectMasking(); it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // Model background once more, including object masks, and detect objects it->backgroundModel(kernel, "interpolate"); it->resetObjectMasking(); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor); // Model background once more, including object masks, and subtract it from the image it->backgroundModel(kernel, "interpolate"); it->subtractBackgroundModel(); it->freeAncillaryData(it->dataBackground); // We don't need that anymore it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; // it->freeAncillaryData(it->dataSegmentation); // We don't need that anymore // boolean it->writeImage(); incrementProgress(); } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); scienceData->memorySetDeletable(chip, "databackgroundL1", true); // potential double free? see 10 lines above } } decrementCurrentThreads(lock); } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); progressStepSize = 100. / float(numMyImages); float nimg = 5; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); emit messageAvailable(" Calculating sky models ...", "controller"); #pragma omp parallel for num_threads(maxCPU) firstprivate(DT, DMIN, expFactor, backupDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; releaseMemory(nimg*instData->storage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; // emit messageAvailable(it->baseName + " : Modeling the sky ...", "controller"); it->processingStatus->Skysub = false; // it->setupData(scienceData->isTaskRepeated, false, true, backupDirName); it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); if (!it->successProcessing) { abortProcess = true; continue; } it->readWeight(); // Model background so we can detect objects it->resetObjectMasking(); it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // Model background once more, including object masks, and detect objects it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->resetObjectMasking(); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); // overwrites previous mask it->maskExpand(expFactor, false); // false -> true to write the mask FITS files // Model background once more, including object masks, and subtract it from the image it->backgroundModelDone = false; it->backgroundModel(kernel, "interpolate"); it->subtractBackgroundModel(); if (cdw->ui->skySavemodelCheckBox->isChecked()) { it->writeBackgroundModel(); } it->getMeanBackground(); it->saturationValue -= it->meanExposureBackground; it->updateHeaderSaturation(); if (!isnan(it->meanExposureBackground)) { emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "image"); } else { emit messageAvailable(it->chipName + " : &lt;sky&gt; = " + QString::number(it->meanExposureBackground,'f',2) + " e-", "warning"); warningReceived(); it->setActiveState(MyImage::BADBACK); continue; } it->releaseAllDetectionMemory(); it->releaseBackgroundMemory("entirely"); updateImageAndData(it, scienceData); // Must write for SWarp it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp atomic progress += progressStepSize; } /* // Just file moving, no parallelization required for (int chip=0; chip<instData->numChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); // scienceData->memorySetDeletable(chip, "databackgroundL1", true); // potential double free? see 10 lines above } } } */ } QList<MyImage*> Controller::measureSkyInBlankRegions(Data *scienceData, QString method) { QList<MyImage*> listOfAllImages; if (!successProcessing) return listOfAllImages; emit messageAvailable("Measuring sky level in user-defined areas ...", "controller"); // Measure background at all sky positions // For full parallelisation, I collapse the loops. Since some images from some detectors might // have been removed, the loops are not prefectly rectangular // (one could use a 'continue' statement, though, but would have to determine the max number of exposures per chip for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; listOfAllImages.append(it); } } if (listOfAllImages.isEmpty()) { successProcessing = false; return listOfAllImages; } if (method.isEmpty()) { QVector<double> alpha; QVector<double> delta; QVector<double> radius; // Retrieve sky positions from maindir/subdir/skysamples.dat if (verbosity > 1) emit messageAvailable("Reading blank sky positions from " + scienceData->dirName+"/skysamples.dat", "controller"); if (!readData3D(scienceData->dirName+"/skysamples.dat", alpha, delta, radius) || alpha.isEmpty()) { if (verbosity > 1) emit messageAvailable("Fallback: Reading blank sky positions from " + mainDirName+"/skysamples.dat", "controller"); if (!readData3D(mainDirName+"/skysamples.dat", alpha, delta, radius) || alpha.isEmpty()) { QString part1 = scienceData->dirName; emit showMessageBox("Controller::SKY_FILE_NOT_FOUND", part1, ""); successProcessing = false; return listOfAllImages; } } #pragma omp parallel for num_threads(maxCPU) firstprivate(backupDirName, alpha, delta, radius) for (int i=0; i<listOfAllImages.length(); ++i) { listOfAllImages[i]->setupData(scienceData->isTaskRepeated, false, true, backupDirName); // 'false': do not move images to backup dir yet listOfAllImages[i]->evaluateSkyNodes(alpha, delta, radius); listOfAllImages[i]->unprotectMemory(); if (minimizeMemoryUsage) { listOfAllImages[i]->freeAll(); } } } // Get all images that belong to one exposure (number could vary from exposure to exposure) scienceData->populateExposureList(); return listOfAllImages; }
30,949
C++
.cc
653
38.909648
160
0.654782
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,470
processingAncillary.cc
schirmermischa_THELI/src/processingInternal/processingAncillary.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../query/query.h" #include "dockwidgets/confdockwidget.h" #include "ui_confdockwidget.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalGetCatalogFromWEB() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (instData->validChip == -1) { emit messageAvailable("No images found for "+scienceData->subDirName+". Could not determine sky coordinates for catalog download.", "warning"); emit warningReceived(); return; } pushBeginMessage(taskBasename, scienceDir); pushConfigGetCatalogFromWeb(); Query *query = new Query(&verbosity); connect(query, &Query::bulkMotionObtained, cdw, &ConfDockWidget::updateGaiaBulkMotion); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); connect(query, &Query::critical, scienceData, &Data::criticalFromQueryReceived); query->mainDirName = mainDirName; query->refcatName = cdw->ui->ARCcatalogComboBox->currentText(); query->alpha_manual = cdw->ui->ARCraLineEdit->text(); query->delta_manual = cdw->ui->ARCdecLineEdit->text(); query->radius_manual = cdw->ui->ARCradiusLineEdit->text(); query->magLimit_string = cdw->ui->ARCminmagLineEdit->text(); query->maxProperMotion_string = cdw->ui->ARCmaxpmLineEdit->text(); query->scienceData = scienceData; query->naxis1 = instData->sizex[0]; query->naxis2 = instData->sizey[0]; query->pixscale = instData->pixscale; query->doAstromQueryFromWeb(); delete query; query = nullptr; // pushEndMessage(taskBasename, scienceDir); } // UNUSED /* void Controller::provideHeaderInfo(Data *scienceData) { if (verbosity>1) emit messageAvailable("Collecting metadata from FITS files ...", "controller"); for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); } } } */ void Controller::downloadGaiaCatalog(Data *scienceData) { // int verbosity = 0; gaiaQuery = new Query(&verbosity); connect(gaiaQuery, &Query::messageAvailable, this, &Controller::messageAvailableReceived); connect(gaiaQuery, &Query::critical, this, &Controller::criticalReceived); gaiaQuery->mainDirName = mainDirName; gaiaQuery->scienceData = scienceData; gaiaQuery->naxis1 = instData->sizex[0]; gaiaQuery->naxis2 = instData->sizey[0]; gaiaQuery->pixscale = instData->pixscale; gaiaQuery->suppressCatalogWarning = true; emit messageAvailable("Querying point source catalog from GAIA ...", "ignore"); gaiaQuery->doGaiaQuery(); emit messageAvailable(QString::number(gaiaQuery->numSources) + " point sources retrieved for analysis of image quality ...", "ignore"); // DO NOT 'delete' gaia query here. It is still used elsewhere } // Overload, to set the image size from the coadded image, and not from the images in the Data class void Controller::downloadGaiaCatalog(Data *scienceData, QString radius) { // int verbosity = 0; gaiaQuery = new Query(&verbosity); connect(gaiaQuery, &Query::messageAvailable, this, &Controller::messageAvailableReceived); connect(gaiaQuery, &Query::critical, this, &Controller::criticalReceived); gaiaQuery->mainDirName = mainDirName; gaiaQuery->scienceData = scienceData; gaiaQuery->radius_string = radius; gaiaQuery->suppressCatalogWarning = true; emit messageAvailable("Querying point source catalog from GAIA ...", "ignore"); gaiaQuery->doGaiaQuery(); emit messageAvailable(QString::number(gaiaQuery->numSources) + " point sources retrieved for analysis of image quality ...", "ignore"); // DO NOT 'delete' gaia query here. It is still used elsewhere } void Controller::collectGaiaRaDec(MyImage *image, QVector<double> &dec, QVector<double> &ra, QVector<QVector<double>> &output) { long dim = dec.length(); output.reserve(dim); QVector<double> alpha; QVector<double> delta; alpha.reserve(4); delta.reserve(4); alpha << image->alpha_ll << image->alpha_lr << image->alpha_ul<< image->alpha_ur; delta << image->delta_ll << image->delta_lr << image->delta_ul<< image->delta_ur; double alpha_min = minVec_T(alpha); double alpha_max = maxVec_T(alpha); double delta_min = minVec_T(delta); double delta_max = maxVec_T(delta); for (long i=0; i<dim; ++i) { // Only include refcat sources that are within the footprint of the image. // Otherwise, with very large multichip cameras, there is a severe overhead for every chip if (ra[i] >= alpha_min && ra[i] <= alpha_max && dec[i] >= delta_min && dec[i] <= delta_max) { QVector<double> result(3); result[0] = dec[i]; result[1] = ra[i]; result[2] = 0.0; // dummy magnitude output << result; } } } void Controller::taskInternalGetCatalogFromIMAGE() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); pushBeginMessage(taskBasename, scienceDir); pushConfigGetCatalogFromImage(); QString DT = cdw->ui->ARCDTLineEdit->text(); QString DMIN = cdw->ui->ARCDMINLineEdit->text(); if (DT == "") DT = cdw->defaultMap["ARCDTLineEdit"]; if (DMIN == "") DMIN = cdw->defaultMap["ARCMINLineEdit"]; QString image = cdw->ui->ARCselectimageLineEdit->text(); QFileInfo fi; fi.setFile(image); QString imagePath = fi.absolutePath(); QString imageName = fi.fileName(); QVector<bool> dummyMask; dummyMask.clear(); MyImage *detectionImage = new MyImage(imagePath, imageName, "", 1, dummyMask, &verbosity); connect(detectionImage, &MyImage::critical, this, &Controller::criticalReceived); connect(detectionImage, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); detectionImage->setupCoaddMode(); // Read image, add a dummy global mask, and add a weight map if any detectionImage->backgroundModel(256, "interpolate"); detectionImage->segmentImage(DT, DMIN, true); Query *query = new Query(&verbosity); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); query->mainDirName = mainDirName; query->scienceData = scienceData; query->fromImage = true; for (auto &object : detectionImage->objectList) { query->ra_out.append(object->ALPHA_J2000); query->de_out.append(object->DELTA_J2000); query->mag1_out.append(object->MAG_AUTO); } query->writeAstromScamp(); query->writeAstromANET(); query->writeAstromIview(); query->pushNumberOfSources(); delete query; query = nullptr; detectionImage->releaseAllDetectionMemory(); detectionImage->releaseBackgroundMemory("entirely"); delete detectionImage; detectionImage = nullptr; // dump reference catalog ID QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/refcat/"; mkAbsDir(outpath); QFile file(outpath+"/.refcatID"); QTextStream stream(&file); if( !file.open(QIODevice::WriteOnly)) { emit messageAvailable("Query::dumpRefcatID(): ERROR writing "+outpath+file.fileName()+" : "+file.errorString(), "error"); emit criticalReceived(); return; } stream << image+"_"+cdw->ui->ARCDTLineEdit->text()+"_"+cdw->ui->ARCDMINLineEdit->text() << "\n"; file.close(); } void Controller::taskInternalResolveTargetSidereal() { cdw->ui->ARCpmRALineEdit->clear(); cdw->ui->ARCpmDECLineEdit->clear(); QString targetName = cdw->ui->ARCtargetresolverLineEdit->text(); if (targetName.isEmpty()) return; targetName = targetName.simplified().replace(" ", "_"); Query *query = new Query(&verbosity); connect(query, &Query::messageAvailable, monitor, &Monitor::displayMessage); connect(query, &Query::critical, this, &Controller::criticalReceived); QString check = query->resolveTargetSidereal(targetName); if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta); else if (check == "Unresolved") emit showMessageBox("Controller::TARGET_UNRESOLVED", cdw->ui->ARCtargetresolverLineEdit->text(), ""); else { // nothing yet. } delete query; query = nullptr; } void Controller::taskInternalRestoreHeader() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); pushBeginMessage(taskBasename, scienceDir); QDir headerDir; headerDir.setPath(mainDirName+"/"+scienceDir+"/headers/"); if (!headerDir.exists()) { emit messageAvailable("Could not restore the original WCS solution. The headers/ subdirectory does not exist in<br>"+scienceDir, "error"); successProcessing = false; monitor->raise(); return; } QDir origDir; origDir.setPath(mainDirName+"/"+scienceDir+"/.origheader_backup/"); if (!origDir.exists()) { emit messageAvailable("Cannot restore headers. The backup copy was not found.", "error"); successProcessing = false; monitor->raise(); return; } #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->loadHeader(); // Restore the header if a backup exists if (it->scanAstromHeader(chip, "inBackupDir")) { it->updateZeroOrderOnDrive("restore"); // it->updateZeroOrderInMemory(); } } } successProcessing = true; // pushEndMessage(taskBasename, scienceDir); } // Cloned from Query::getCatalogSearchLocationAstrom() void Controller::getFieldCenter(Data *data, QString &alphaCenter, QString &deltaCenter) { if (!successProcessing) return; QVector<double> crval1 = data->getKeyFromAllImages("CRVAL1"); QVector<double> crval2 = data->getKeyFromAllImages("CRVAL2"); if (crval1.isEmpty() || crval2.isEmpty()) { emit messageAvailable("Query::getCatalogSearchLocationAstrom(): CRVAL vectors are empty", "error"); emit criticalReceived(); successProcessing = false; return; } // Use median to calculate field center (avoiding issues with RA=0|360 deg boundary) // Do not average central two elements if number of data points is even alphaCenter = QString::number(straightMedian_T(crval1, 0, false), 'f', 3); deltaCenter = QString::number(straightMedian_T(crval2, 0, false), 'f', 3); }
11,910
C++
.cc
260
40.688462
151
0.700009
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,471
processingCreateSourceCat.cc
schirmermischa_THELI/src/processingInternal/processingCreateSourceCat.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "../tools/imagequality.h" #include "../tools/correlator.h" #include "photinst.h" #include "ui_confdockwidget.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QTextStream> #include <QStandardPaths> #include <QProgressBar> #include <QTest> void Controller::taskInternalCreatesourcecat() { QString scienceDir = instructions.split(" ").at(1); QString updateMode = instructions.split(" ").at(2); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; // Ensure that the output path exists QString outpath = mainDirName+"/"+scienceData->subDirName+"/cat/"; mkAbsDir(outpath); pushBeginMessage(taskBasename, scienceDir); pushConfigCreatesourcecat(); memoryDecideDeletableStatus(scienceData, false); if (!scienceData->hasMatchingPartnerFiles(mainDirName+"/WEIGHTS/", ".weight.fits")) return; // Update coordinates if necessary. Leave if cancelled by the user bool check = manualCoordsUpdate(scienceData, updateMode); if (!check) return; QString minFWHM = cdw->ui->CSCFWHMLineEdit->text(); QString maxFlag = cdw->ui->CSCmaxflagLineEdit->text(); QString maxEll = cdw->ui->CSCmaxellLineEdit->text(); getNumberOfActiveImages(scienceData); // Cleanup the catalog directory from the results of a previous run scienceData->removeCatalogs(); // Check if exposures have unambiguous MJD-OBS keywords, otherwise the construction of scamp catalogs will fail if (!scienceData->collectMJD()) { emit messageAvailable("Duplicate MJD-OBS entries found!", "error"); emit criticalReceived(); return; } emit messageAvailable("Running source extraction ...", "data"); // INTERNAL if (cdw->ui->CSCMethodComboBox->currentText() == "THELI") { detectionInternal(scienceData, minFWHM, maxFlag, maxEll); emit resetProgressBar(); progressStepSize = 100. / float(scienceData->exposureList.length()); mergeInternal(scienceData, minFWHM, maxFlag, maxEll); } // EXTERNAL (SourceExtractor) else { detectionSourceExtractor(scienceData, minFWHM, maxFlag, maxEll); emit resetProgressBar(); progressStepSize = 100. / float(scienceData->exposureList.length()); mergeSourceExtractor(scienceData); } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::detectionInternal(Data *scienceData, QString minFWHM, QString maxFlag, QString maxEll) { // Parameters for source detection QString DT = cdw->ui->CSCDTLineEdit->text(); QString DMIN = cdw->ui->CSCDMINLineEdit->text(); QString background = cdw->ui->CSCbackgroundLineEdit->text(); bool convolution = cdw->ui->CSCconvolutionCheckBox->isChecked(); QString saturation = cdw->ui->CSCsaturationLineEdit->text(); // Create source catalogs for each exposure (keep them in memory!) /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { if (verbosity >=0 ) emit messageAvailable(it->baseName + " : Creating source catalog ...", "image"); it->setupDataInMemory(isTaskRepeated, true, true); it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, convolution, false); it->writeCatalog(minFWHM, maxFlag); // filters out objects that don't match flag or fwhm incrementProgress(); } } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // detection releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (!it->successProcessing) continue; if (instData->badChips.contains(chip)) continue; if (it->activeState != MyImage::ACTIVE) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity > 1 ) emit messageAvailable(it->chipName + " : Creating source catalog ...", "image"); it->setupDataInMemorySimple(true); if (!it->successProcessing) { abortProcess = true; continue; } it->checkWCSsanity(); it->readWeight(); it->backgroundModel(256, "interpolate"); // it->updateSaturation(saturation); // Handled during splitting if (it->dataBackground.capacity() == 0) { if (successProcessing) emit messageAvailable(it->chipName + " : Background vector has zero capacity!", "error"); criticalReceived(); successProcessing = false; } it->segmentImage(DT, DMIN, convolution, false); it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); it->calcMedianSeeingEllipticity(); // Also propagate to FITS header if file is on drive it->writeCatalog(minFWHM, maxFlag, maxEll); // filters out objects that don't match flag or fwhm it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (it->successProcessing) { long nobj = it->objectList.length(); emitSourceCountMessage(nobj, it->chipName); if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long nReject = cdw->ui->CSCrejectExposureLineEdit->text().toLong(); if (nobj < nReject) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } } } else { scienceData->successProcessing = false; } #pragma omp atomic progress += progressStepSize; } // Deactivate exposures with low detections if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long numExpRejected = 0; long numImgRejected = 0; flagLowDetectionImages(scienceData, numExpRejected, numImgRejected); if (numImgRejected > 0) { QString addedString = ""; if (instData->numChips > 1) addedString = "("+QString::number(numImgRejected)+ " detector images)"; emit messageAvailable("<br>"+QString::number(numExpRejected) + " exposures "+addedString+ " deactivated " + "(low source count). Corresponding FITS files were moved to <br>" + scienceData->subDirName+"/inactive/lowDetections/<br>", "warning"); emit warningReceived(); } } } void Controller::detectionSourceExtractor(Data *scienceData, QString minFWHM, QString maxFlag, QString maxEll) { buildSourceExtractorCommandOptions(); // Create source catalogs for each exposure /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { if (verbosity >=0 ) emit messageAvailable(it->baseName + " : Creating SourceExtractor catalog ...", "image"); it->setupDataInMemory(isTaskRepeated, true, true); it->buildSourceExtractorCommand(); it->sourceExtractorCommand.append(sourceExtractorCommandOptions); it->createSourceExtractorCatalog(); it->filterSourceExtractorCatalog(minFWHM, maxFlag); it->sourceExtractorCatToIview(); incrementProgress(); } } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // some breathing space for SourceExtractor releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity > 1) emit messageAvailable(it->chipName + " : Creating source catalog ...", "image"); it->setupDataInMemorySimple(true); if (!it->successProcessing) { abortProcess = true; continue; } it->checkWCSsanity(); it->buildSourceExtractorCommand(); it->sourceExtractorCommand.append(sourceExtractorCommandOptions); if (!it->imageOnDrive) it->writeImage(); // Must be on drive for SourceExtractor it->createSourceExtractorCatalog(); it->filterSourceExtractorCatalog(minFWHM, maxFlag, maxEll); it->calcMedianSeeingEllipticitySex(); it->sourceExtractorCatToIview(); it->sourceExtractorCatToAnet(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (it->successProcessing) { long nobj = getNumObjectsSourceExtractorCat(it->path+"/cat/"+it->chipName+".cat"); emitSourceCountMessage(nobj, it->chipName); if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long nReject = cdw->ui->CSCrejectExposureLineEdit->text().toLong(); if (nobj < nReject) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } } } else { scienceData->successProcessing = false; successProcessing = false; } #pragma omp atomic progress += progressStepSize; } // Deactivate exposures with low detections if (!cdw->ui->CSCrejectExposureLineEdit->text().isEmpty()) { long numExpRejected = 0; long numImgRejected = 0; flagLowDetectionImages(scienceData, numExpRejected, numImgRejected); if (numImgRejected > 0) { QString addedString = ""; if (instData->numChips > 1) addedString = "("+QString::number(numImgRejected)+ " detector images)"; emit messageAvailable("<br>"+QString::number(numExpRejected) + " exposures "+addedString+ " deactivated " + "(low source count). Corresponding FITS files were moved to <br>" + scienceData->subDirName+"/inactive/lowDetections/", "warning"); emit warningReceived(); } } } void Controller::emitSourceCountMessage(long &nobj, QString baseName) { // Color-coding output lines QString detStatus = ""; QString level = "image"; if (nobj<10 && nobj>3) { detStatus = " (low source count)"; level = "warning"; } if (nobj<=3) { detStatus = " (very low source count)"; level = "stop"; } emit messageAvailable(baseName + " : " + QString::number(nobj) + " sources detected..."+detStatus, level); } void Controller::flagLowDetectionImages(Data *scienceData, long &numExpRejected, long &numImgRejected) { numExpRejected = 0; numImgRejected = 0; scienceData->populateExposureList(); int numExposures = scienceData->exposureList.length(); for (long i=0; i<numExposures; ++i) { if (abortProcess || !successProcessing) continue; // Test if a single chip has low detection numbers bool exposureIsBad = false; for (auto &it : scienceData->exposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) { exposureIsBad = true; break; } } // Reject all chips if a single one is bad if (exposureIsBad) { for (auto &it : scienceData->exposureList[i]) { ++numImgRejected; if (it->activeState != MyImage::LOWDETECTION) { it->setActiveState(MyImage::LOWDETECTION); it->emitModelUpdateNeeded(); it->removeSourceCatalogs(); } it->emitModelUpdateNeeded(); } ++numExpRejected; } } } void Controller::mergeInternal(Data *scienceData, QString minFWHM, QString maxFlag, QString maxEll) { scienceData->populateExposureList(); emit messageAvailable("Merging source catalogs ...", "controller"); for (long i=0; i<scienceData->exposureList.length(); ++i) { // if one detector has been rejected due to low source counts, then skip this exposure bool lowCounts = false; int inactiveCounter = 0; for (auto &it : scienceData->exposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) lowCounts = true; if (!it->isActive()) ++inactiveCounter; } // WARNING: skipping images where some detectors have no data / deactivated if (lowCounts || inactiveCounter > 0) { emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Omitted. One or more images inactive or with low counts.", "warning"); continue; } fitsfile *fptr; int status = 0; QString filename = scienceData->dirName+"/cat/"+scienceData->exposureList[i][0]->rootName+".scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); int counter = 0; for (auto &it : scienceData->exposureList[i]) { // Exclude inactive exposures // if (!it->isActive()) continue; it->appendToScampCatalogInternal(fptr, minFWHM, maxFlag, maxEll); ++counter; } // if (counter != instData->numChips) { if (counter != instData->numUsedChips) { emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Merged only " + QString::number(counter) + " out of " + QString::number(instData->numUsedChips) + " catalogs for scamp!", "error"); emit criticalReceived(); } fits_close_file(fptr, &status); printCfitsioError(__func__, status); #pragma omp atomic progress += progressStepSize; } } void Controller::mergeSourceExtractor(Data *scienceData) { // Merge SourceExtractor catalogs to final scamp catalog // Loop over exposures scienceData->populateExposureList(); emit messageAvailable("Merging source catalogs ...", "controller"); progress = 0.; progressStepSize = 100./float(scienceData->exposureList.length()); #pragma omp parallel for num_threads(maxCPU) for (long i=0; i<scienceData->exposureList.length(); ++i) { if (abortProcess || !successProcessing) continue; // if one detector has been rejected due to low source counts, then skip this exposure bool lowCounts = false; for (auto &it : scienceData->exposureList[i]) { if (it->activeState == MyImage::LOWDETECTION) lowCounts = true; } if (lowCounts) continue; fitsfile *fptr; int status = 0; QString filename = scienceData->dirName+"/cat/"+scienceData->exposureList[i][0]->rootName+".scamp"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); for (auto &it : scienceData->exposureList[i]) { it->appendToScampCatalogSourceExtractor(fptr); if (!it->successProcessing) scienceData->successProcessing = false; } fits_close_file(fptr, &status); printCfitsioError(__func__, status); #pragma omp atomic progress += progressStepSize; } } void Controller::buildSourceExtractorCommandOptions() { // This builds the major part of the SourceExtractor command based on the chosen GUI settings. // The MyImage class adds the variable rest (catalog name, weight name, image name) if (!successProcessing) return; sourceExtractorCommandOptions = " -PARAMETERS_NAME " + thelidir + "/config/default.param"; sourceExtractorCommandOptions += " -FILTER_NAME " + thelidir + "/config/default.conv"; sourceExtractorCommandOptions += " -STARNNW_NAME " + thelidir + "/config/default.nnw"; sourceExtractorCommandOptions += " -DETECT_MINAREA " + getUserParamLineEdit(cdw->ui->CSCDMINLineEdit); sourceExtractorCommandOptions += " -DETECT_THRESH " + getUserParamLineEdit(cdw->ui->CSCDTLineEdit); sourceExtractorCommandOptions += " -ANALYSIS_THRESH " + getUserParamLineEdit(cdw->ui->CSCDTLineEdit); sourceExtractorCommandOptions += " -FILTER " + getUserParamCheckBox(cdw->ui->CSCconvolutionCheckBox); sourceExtractorCommandOptions += " -DEBLEND_MINCONT " + getUserParamLineEdit(cdw->ui->CSCmincontLineEdit); sourceExtractorCommandOptions += " -SATUR_LEVEL " + getUserParamLineEdit(cdw->ui->CSCsaturationLineEdit); sourceExtractorCommandOptions += " -CATALOG_TYPE FITS_LDAC "; sourceExtractorCommandOptions += " -WEIGHT_TYPE MAP_WEIGHT "; sourceExtractorCommandOptions += " -PIXEL_SCALE 0.0 "; QString backString = cdw->ui->CSCbackgroundLineEdit->text(); if (backString.isEmpty()) sourceExtractorCommandOptions += " -BACK_TYPE AUTO " ; else sourceExtractorCommandOptions += " -BACK_TYPE MANUAL -BACK_VALUE "+backString; } bool Controller::manualCoordsUpdate(Data *scienceData, QString mode) { if (!successProcessing) return false; if (mode == "Cancel") return false; if (mode.isEmpty() || mode == "empty") return true; QString targetAlpha = cdw->ui->ARCraLineEdit->text(); QString targetDelta = cdw->ui->ARCdecLineEdit->text(); if (targetAlpha.contains(':')) targetAlpha = hmsToDecimal(targetAlpha); if (targetDelta.contains(':')) targetDelta = dmsToDecimal(targetDelta); emit messageAvailable("Updating WCS:", "controller"); if (mode == "crval") { emit messageAvailable("CRVAL1 = "+targetAlpha + "<br>" + "CRVAL2 = "+targetDelta, "data"); } else if (mode == "crval+cd") { emit messageAvailable("CRVAL1 = "+targetAlpha + "<br>" + "CRVAL2 = "+targetDelta + "<br>" + "CD1_1 = "+QString::number(-1.*instData->pixscale/3600.) + "<br>" + "CD1_2 = 0.0<br>" + "CD2_1 = 0.0<br>" + "CD2_2 = "+QString::number(instData->pixscale/3600.), "data"); } getNumberOfActiveImages(scienceData); QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; if (!it->successProcessing) continue; it->loadHeader(); if (!it->successProcessing) { abortProcess = true; continue; } // TODO: should be sufficient, but crashes when executed right after launch // it->loadHeader(); if (mode == "crval") { it->wcs->crval[0] = targetAlpha.toDouble(); it->wcs->crval[1] = targetDelta.toDouble(); it->wcs->flag = 0; it->updateCRVALinHeader(); it->updateCRVALinHeaderOnDrive(); } if (mode == "crval+cd") { it->wcs->crval[0] = targetAlpha.toDouble(); it->wcs->crval[1] = targetDelta.toDouble(); it->wcs->cd[0] = -1.*it->plateScale/3600.; it->wcs->cd[1] = 0.; it->wcs->cd[2] = 0.; it->wcs->cd[3] = it->plateScale/3600.; it->wcs->flag = 0; it->updateCRVALCDinHeader(); it->updateCRVALCDinHeaderOnDrive(); } if (!it->successProcessing) scienceData->successProcessing = false; #pragma omp atomic progress += progressStepSize; } successProcessing = true; // emit appendOK(); return true; }
21,615
C++
.cc
468
37.777778
140
0.642037
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,472
data.cc
schirmermischa_THELI/src/processingInternal/data.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "data.h" #include "mask.h" #include "../myimage/myimage.h" #include "../functions.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../preferences.h" #include "../instrumentdata.h" #include "../threading/memoryworker.h" #include "../processingStatus/processingStatus.h" #include "fitsio.h" #include <omp.h> #include <QDir> #include <QMessageBox> #include <QString> #include <QDebug> #include <QFile> #include <QPushButton> #include <QSettings> #include <QMainWindow> #include <QVector> #include <QProgressBar> // Ctor, given an absolute path name (dirName), status string, and optionally chip number // It creates a list of all matching images in that directory, and also reads some // essential FITS header keywords. Data::Data(const instrumentDataType *instrumentData, Mask *detectorMask, QString maindirname, QString subdirname, int *verbose) : instData(instrumentData) { emit messageAvailable("DATA: Setting up "+subdirname, "data"); initEnvironment(thelidir, userdir); resetSuccessProcessing(); // Must compare string values, not QDirs themselves, as they could be initialized differently (e.g. "." vs /home/.../) if (QDir(maindirname).absolutePath() == QDir::home().absolutePath()) { emit messageAvailable(QString(__func__)+": For safety reasons, your home directory is not permitted as the main directory.", "error"); emit critical(); return; } omp_init_lock(&progressLock); mainDirName = maindirname; subDirName = subdirname; dirName = mainDirName + "/" + subDirName; myImageList.resize(instData->numChips); combinedImage.resize(instData->numChips); dataInitialized = false; verbosity = verbose; // globalMask.resize(instData->numChips); // Pointer to the detector masks defined in the top-level controller; // We don't need a separate entity for each 'Data' instance mask = detectorMask; // Get the recorded processing status from the .processingStatus file (if any) processingStatus = new ProcessingStatus(dirName, this); // connect(processingStatus, &ProcessingStatus::processingStatusChanged, mainGUI, &MainWindow::statusChangedReceived); connect(processingStatus, &ProcessingStatus::messageAvailable, this, &Data::pushMessageAvailable); connect(processingStatus, &ProcessingStatus::critical, this, &Data::pushCritical); processingStatus->readFromDrive(); QString backupStatus = processingStatus->statusString; backupStatus.chop(1); pathBackupL1 = dirName + "/" + backupStatus + "_IMAGES"; dir.setPath(dirName); if (!dir.exists()) { emit messageAvailable("DATA: Could not create Data structure for "+mainDirName+"/"+subDirName, "error"); emit critical(); return; } // start fresh clearImageInfo(); // Check whether this directory contains RAW data (and thus must be processed by HDUreformat first) if (subDirName != "GLOBALWEIGHTS") { // crashes otherwise when creating globalweights if (checkForRawData()) return; } if (subDirName == "GLOBALWEIGHTS") { numMasterCalibs = 0; numImages = 0; for (int chip=0; chip<instData->numChips; ++chip) { // The list is fully populated, even for chips the user might decide not to use myImageList[chip].clear(); // in case we run globalweights several times QStringList filter; filter << "globalweight_"+instData->name+"*_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); for (auto &it : fitsFiles) { MyImage *myImage = new MyImage(dirName, it, "", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->readFILTER(dirName+"/"+it); myImage->imageOnDrive = true; myImageList[chip].append(myImage); ++numImages; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::errorOccurred, this, &Data::errorOccurredInMyImage); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); // Use a direct connection to execute the slot in the signaler's thread, not the receiver's thread connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } if (numImages < instData->numChips && numImages > 0) { emit messageAvailable("DATA: " + QString::number(numImages) + " found, expected "+QString::number(instData->numChips), "warning"); emit warning(); } dataInitialized = true; return; } // Fill the list of MyImage types of individual images and master calibration files in this data directory QStringList filter; filter << "*.fits"; QStringList allFitsFiles = dir.entryList(filter); numImages = allFitsFiles.length(); numMasterCalibs = 0; // The master calibration FITS files (if any). (i.e. if we are reading a calibration directory) for (int chip=0; chip<instData->numChips; ++chip) { QStringList filter; filter << subDirName+"_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); if (!fitsFiles.isEmpty()) { // Only one entry in this QStringList because it is the master MyImage *myImage = new MyImage(dirName, fitsFiles.at(0), "", chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->imageOnDrive = true; combinedImage[chip] = myImage; ++numMasterCalibs; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } if (numMasterCalibs == instData->numChips) { hasAllMasterCalibs = true; dataInitialized = true; } if (numMasterCalibs < instData->numChips && numMasterCalibs > 0) { emit messageAvailable("DATA: " + QString::number(numMasterCalibs) + " found, expected "+QString::number(instData->numChips), "warning"); } // The other images (minus master calibs etc), i.e. the science exposures numImages = 0; for (int chip=0; chip<instData->numChips; ++chip) { QStringList filter; filter << "*_"+QString::number(chip+1)+processingStatus->statusString+".fits"; QStringList fitsFiles = dir.entryList(filter); // TODO: when splitting data, we must use a filter that does not contain the _chip string (raw data) // if list == empty then reset string and reload for (auto &it : fitsFiles) { bool skip = false; // skip master calibs if (it == subDirName+"_"+QString::number(chip+1)+".fits") skip = true; if (skip) continue; MyImage *myImage = new MyImage(dirName, it, processingStatus->statusString, chip+1, mask->globalMask[chip], verbosity); myImage->setParent(this); myImage->readFILTER(dirName+"/"+it); myImage->imageOnDrive = true; myImage->pathBackupL1 = pathBackupL1; myImage->baseNameBackupL1 = myImage->chipName + backupStatus; QFile weight(myImage->weightPath+"/"+myImage->weightName+".fits"); if (weight.exists()) myImage->weightOnDrive = true; myImageList[chip].append(myImage); if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } // Add deactivated images QStringList deactiveDirList; deactiveDirList << "/inactive/" << "/inactive/badStatistics/" << "/inactive/badBackground/" << "/inactive/lowDetections/" << "/inactive/noAstrometry/"; for (auto &pathExtension : deactiveDirList) { QDir deactiveDir(dirName+pathExtension); QStringList deactiveFilter; deactiveFilter << "*.fits"; // selects all images, not just those of a specific chip QStringList files = deactiveDir.entryList(deactiveFilter); for (auto &it : files) { // check if the image belongs to the currently processed chip. If not, continue; QFileInfo fi(dirName+pathExtension+"/"+it); QString rootName = fi.completeBaseName(); rootName.truncate(rootName.lastIndexOf('_')); QString chipName = rootName+"_"+QString::number(chip+1); QString status = processingStatus->extractStatusFromFilename(it); if (chipName+status+".fits" != it) continue; // Ok, image belongs to current chip QString deactiveBackupStatus = status; deactiveBackupStatus.chop(1); QString deactivePathBackupL1 = dirName + "/" + deactiveBackupStatus + "_IMAGES"; MyImage *myImage = new MyImage(dirName, it, status, chip+1, mask->globalMask[chip], verbosity); myImage->pathExtension = pathExtension; myImage->setParent(this); myImage->readFILTER(deactiveDir.absolutePath()+"/"+it); myImage->imageOnDrive = true; myImage->pathBackupL1 = deactivePathBackupL1; myImage->baseNameBackupL1 = myImage->chipName + deactiveBackupStatus; myImage->weightPath = dirName+"/../WEIGHTS/"; QFile weight(myImage->weightPath+"/"+myImage->weightName+".fits"); if (weight.exists()) myImage->weightOnDrive = true; if (pathExtension == "inactive/badStatistics/") myImage->activeState = MyImage::BADSTATS; else if (pathExtension == "inactive/badBackground/") myImage->activeState = MyImage::BADBACK; else if (pathExtension == "inactive/lowDetections/") myImage->activeState = MyImage::LOWDETECTION; else if (pathExtension == "inactive/noAstrometry/") myImage->activeState = MyImage::NOASTROM; else myImage->activeState = MyImage::INACTIVE; myImageList[chip].append(myImage); if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); } } numImages += myImageList[chip].length(); } if (numImages > 0) dataInitialized = true; // Sort the vector with the chip numbers (no particular reason, yet) std::sort(uniqueChips.begin(), uniqueChips.end()); // Parallelization is set externally by controller; // Listen to images // establish_connections(); } Data::~Data() { for (auto &it: combinedImage) { delete it; it = nullptr; } deleteMyImageList(); omp_destroy_lock(&progressLock); } // Upon launch, check if the status on record matches the FITS files on drive bool Data::checkStatusConsistency() { // only do this if (!processingStatus->doesStatusFileExist()) return true; // Figure out a chip that must be present (not excluded by the user int testChip = -1; for (int chip=0; chip<instData->numChips; ++chip) { if (!instData->badChips.contains(chip)) { testChip = chip; break; } } if (testChip == -1) { qDebug() << __func__ << "error: no data left after filtering"; } if (dataType == "SCIENCE" || dataType == "SKY" || dataType == "STD") { QStringList expectedFileList = dir.entryList(QStringList() << "*_"+QString::number(testChip+1)+processingStatus->statusString+".fits"); QStringList observedFileList = dir.entryList(QStringList() << "*_"+QString::number(testChip+1)+"P*.fits"); // write found status to disk. Controller will then retry if necessary if (expectedFileList.isEmpty() && !observedFileList.isEmpty()) { processingStatus->inferStatusFromFilenames(); processingStatus->statusToBoolean(processingStatus->statusString); processingStatus->writeToDrive(); return false; } } return true; } bool Data::checkForRawData() { // Only checking .fits files. Everything else ("*.fit", "*.cr2", "*.fz" etc) it is clear that we have raw data (or other files) QStringList filter = {"*.fits"}; QStringList filter2 = {"*.fits", "*.fit", "*.FIT", "*.fz", "*.cr2", "*.CR2", "*.arw", "*.ARW", "*.dng", "*.DNG", "*.nef", "*.NEF", "*.pef", "*.PEF"}; dir.setFilter(QDir::Files); QStringList fileNames = dir.entryList(filter); // Contains processed images and potential raw data QStringList allFileNames = dir.entryList(filter2); // Everything int numRawFiles = 0; for (QString &allFileName : allFileNames) { if (!allFileName.endsWith(".fits")) ++numRawFiles; // Does not matter whether imaging data or other stuff } int numProcessedFiles = 0; for (auto &fileName : fileNames) { fitsfile *fptr; int status = 0; QString name = dirName + "/" + fileName; fits_open_file(&fptr, name.toUtf8().data(), READONLY, &status); long thelipro = 0; fits_read_key_lng(fptr, "THELIPRO", &thelipro, nullptr, &status); if (status == KEY_NO_EXIST) { ++numRawFiles; status = 0; } else { ++numProcessedFiles; } fits_close_file(fptr, &status); } if (numProcessedFiles == 0 && numRawFiles > 0) { processingStatus->deleteFromDrive(); processingStatus->reset(); return true; } else if (numProcessedFiles == 0 && numRawFiles == 0) return true; else if (numProcessedFiles > 0 && numRawFiles == 0) return false; else { processingStatus->deleteFromDrive(); processingStatus->reset(); // TODO: this does not show! emit showMessageBox("DATA::RAW_AND_PROCESSED_FOUND", dirName, ""); // qDebug() << "Data::checkForRawData(): " << subDirName << numProcessedFiles << numRawFiles; // qDebug() << "Both processed and RAW files were found. This status is not allowed"; // (numProcessedFiles > 0 && numRawFiles > 0) { // TODO: this does not show! emit messageAvailable(dirName + " : Both processed and RAW files were found. This status is not allowed. You must clean the directory manually.", "error"); emit critical(); successProcessing = false; return false; } } void Data::broadcastNumberOfFiles() { emit messageAvailable(subDirName + ": " + QString::number(numImages)+" images initialized", "data"); if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF" || dataType == "FLAT") { emit messageAvailable(subDirName + ": " + QString::number(numMasterCalibs)+" master "+dataType+" images initialized", "data"); } } // Needed for aborting a task void Data::setSuccess(bool state) { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { it->successProcessing = state; } successProcessing = state; } } void Data::writeUnsavedImagesToDrive(bool includeBackup) { emit resetProgressBar(); /* * TODO: Run it as a separate process * CRASHES, because processes are started by the controller, which then immediately calls the destructor. * Better if we can wait for the processes and then delete 'data', e.g. if handled by controller directly workerThread = new QThread(this); worker = new MyWorker(this); workerInit = true; workerThreadInit = true; worker->moveToThread(workerThread); QObject::connect(workerThread, &QThread::started, worker, &MyWorker::DataDumpImagesToDrive); QObject::connect(worker, &MyWorker::finished, worker, &QObject::deleteLater); QObject::connect(worker, &QObject::destroyed, workerThread, &QThread::quit); workerThread->start(); workerThread->wait(); */ // freezes the GUI while running ... progressStepSize = 1. / float(numImages); emit resetProgressBar(); populateExposureList(); #pragma omp parallel for num_threads(maxCPU) for (long i=0; i<exposureList.length(); ++i) { for (auto &it : exposureList[i]) { if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); if (includeBackup) { it->writeImageBackupL1(); it->writeImageBackupL2(); it->writeImageBackupL3(); } #pragma omp atomic *progress += progressStepSize; } } } emit progressUpdate(100.); } bool Data::checkTaskRepeatStatus(QString taskBasename) { isTaskRepeated = false; // Check the Data class. If the current task matches the status, then the task is being repeated if (taskBasename == "HDUreformat" && processingStatus->HDUreformat) isTaskRepeated = true; else if (taskBasename == "Processscience" && processingStatus->Processscience) isTaskRepeated = true; else if (taskBasename == "Chopnod" && processingStatus->Chopnod) isTaskRepeated = true; else if (taskBasename == "Background" && processingStatus->Background) isTaskRepeated = true; else if (taskBasename == "Collapse" && processingStatus->Collapse) isTaskRepeated = true; else if (taskBasename == "Starflat" && processingStatus->Starflat) isTaskRepeated = true; else if (taskBasename == "Skysub" && processingStatus->Skysub) isTaskRepeated = true; // Check that all images have the same status myImageList[instData->validChip][0]->checkTaskRepeatStatus(taskBasename); bool imageStatus = myImageList[instData->validChip][0]->isTaskRepeated; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (it->activeState != MyImage::ACTIVE) continue; it->checkTaskRepeatStatus(taskBasename); if (imageStatus != it->isTaskRepeated) { emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Inconsistent processing status detected among images!<br>You must clean-up the data directory manually. Restart recommended.", "error"); emit critical(); it->successProcessing = false; successProcessing = false; return false; } } } // If the Data class status does not match the image status, then map the image status onto the Data class if (isTaskRepeated != imageStatus) { // Map the imaging status onto the Data structure emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Inconsistent processing status detected between images and Data class. Reset to image status", "warning"); emit warning(); processingStatus->statusToBoolean(myImageList[instData->validChip][0]->processingStatus->statusString); processingStatus->getStatusString(); } // Now check if we can actually retrieve all the data with the previous status bool success = true; if (isTaskRepeated) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (it->activeState != MyImage::ACTIVE) continue; // If the image is not in memory, check if it is on disk if (!it->backupL1InMemory) { QString fileName = it->pathBackupL1 + "/" + it->baseNameBackupL1 + ".fits"; QFile file(fileName); if (it->backupL1OnDrive && !file.exists()) success = false; else if (!it->backupL1OnDrive && !file.exists()) success = false; else if (!it->backupL1OnDrive && file.exists()) { it->backupL1OnDrive = true; if (*verbosity > 2) emit messageAvailable(dirName + " : Data::checkTaskRepeatStatus(): Fixed wrong backup status flag, file was found on drive.", "warning"); } } } } if (!success) { emit showMessageBox("Data::BACKUP_DATA_NOT_FOUND", "",""); } } return success; } void Data::checkPresenceOfMasterCalibs() { // Check if master calibration FITS files are present int numMasterCalibs = 0; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; QStringList filter; filter << subDirName+"_"+QString::number(chip+1)+".fits"; QStringList fitsFiles = dir.entryList(filter); if (!fitsFiles.isEmpty()) ++numMasterCalibs; } if (numMasterCalibs == instData->numUsedChips) hasAllMasterCalibs = true; else hasAllMasterCalibs = false; } void Data::populateExposureList() { if (*verbosity > 0) emit messageAvailable(subDirName + " : Collecting metadata from images ...", "data"); // Create a list of unique MJDOBS QVector<double> mjdList; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { // TODO: this is only necessary if the GUI is launched and files have not been read yet! // There should be a member boolean that keeps track of this if (!it->headerInfoProvided) it->loadHeader(); if (!mjdList.contains(it->mjdobs)) mjdList.append(it->mjdobs); } } // Sort list of mjdobs std::sort(mjdList.begin(), mjdList.end()); exposureList.clear(); exposureList.resize(mjdList.length()); // Collect all MyImages that belong to one mjdobs long expNumber = 0; for (auto &mjdobs : mjdList) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (it->mjdobs == mjdobs) { exposureList[expNumber].append(it); } } } ++expNumber; } emit appendOK(); } void Data::resetGlobalWeight(QString filter) { // CHECK: not sure whether i need to exclude badChips here if (myImageList.isEmpty()) return; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; int removeIndex = 0; int i = 0; bool remove = false; for (auto &it: myImageList[chip]) { if (filter == it->filter) { removeIndex = i; remove = true; break; } ++i; } if (remove) { myImageList[chip][removeIndex]->freeAll(); myImageList[chip].removeAt(removeIndex); } } } void Data::loadCombinedImage(const int chip) { if (!successProcessing) return; if (userStop || userKill) return; if (instData->badChips.contains(chip)) { combinedImage[chip]->modeDetermined = true; combinedImage[chip]->imageInMemory = true; return; } if (*verbosity > 0 && !combinedImage.at(chip)->imageInMemory) { emit messageAvailable("Chip " + QString::number(chip+1) + " : Loading master "+ subDirName + " ...", "data"); } bool determineMode = false; // Must be threadsafe only if running process science as a first taskafter GUI re-launch combinedImage[chip]->readImageThreadSafe(determineMode); // Do we have the mode already (i.e. this function was executed previously for this chip) if (!combinedImage[chip]->modeDetermined) { // the mode determination will fail if we have mostly integer values (e.g. darks) if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) combinedImage[chip]->skyValue = meanMask(combinedImage[chip]->dataCurrent, mask->globalMask[chip]); } else { combinedImage[chip]->skyValue = modeMask(combinedImage[chip]->dataCurrent, "stable", mask->globalMask[chip])[0]; } if (*verbosity > 0) { emit messageAvailable(subDirName + " : Master calib mean : "+QString::number(combinedImage[chip]->skyValue, 'f', 3), "data"); } } combinedImage[chip]->modeDetermined = true; combinedImage[chip]->imageInMemory = true; successProcessing = combinedImage[chip]->successProcessing; } // Usually, the mode / SKYVALUE is computed when applying the master BIAS/FLAT // However, a user might skip these steps, and then the mode remains undetermined void Data::checkModeIsPresent() { if (!successProcessing) return; #pragma omp parallel for num_threads(maxCPU) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->getMode(true); } } } void Data::resetSuccessProcessing() { successProcessing = true; if (!dataInitialized) return; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->successProcessing = true; } } } // Used for creating master calibrators void Data::combineImagesCalib(int chip, float (*combineFunction_ptr) (const QVector<float> &, const QVector<bool> &, long), const QString nlowString, const QString nhighString, const QString dirName, const QString subDirName, const QString dataType) { if (!successProcessing) return; if (userStop || userKill) return; if (instData->badChips.contains(chip)) return; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining images for chip "+QString::number(chip+1)+" ...", "data"); int nlow = nlowString.toInt(); // returns 0 for empty string (desired) int nhigh = nhighString.toInt(); // returns 0 for empty string (desired) int numImages = myImageList.at(chip).length(); // Delete an old master calibration frame if it exists if (!deleteFile(subDirName+"_"+QString::number(chip+1)+".fits", dirName)) { emit messageAvailable(subDirName + " : Data::combineImgesCalib(): Could not delete old master calibration file!", "error"); emit critical(); successProcessing = false; return; } if (nhigh+nlow >= numImages) { emit messageAvailable("Number of low and high pixels rejected is equal or larger than the number of available images.", "error"); emit critical(); successProcessing = false; return; } if (numImages <= 3) { emit messageAvailable("Only "+QString::number(numImages)+" exposures are used to compute the combined master calibration file. More are recommended.", "warning"); emit warning(); } // Get image geometry from first image in list long n = myImageList.at(chip).at(0)->naxis1; long m = myImageList.at(chip).at(0)->naxis2; if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImgesCalib(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; // Container for the temporary pixel stack // Instantiate a MyImage object for the combined set of images. // It does not create a FITS object yet. // Delete the instance if it exists already from a previous run of this task to not (re)create it // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; if (combinedImage.at(chip) == nullptr) { MyImage *combinedImageDummy = new MyImage(dirName, subDirName+"_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); connect(combinedImageDummy, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(combinedImageDummy, &MyImage::critical, this, &Data::pushCritical); connect(combinedImageDummy, &MyImage::warning, this, &Data::pushWarning); connect(combinedImageDummy, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(combinedImageDummy, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(combinedImageDummy, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); combinedImage[chip] = combinedImageDummy; } combinedImage[chip]->naxis1 = n; combinedImage[chip]->naxis2 = m; combinedImage[chip]->dataCurrent.resize(dim); combinedImage[chip]->dataCurrent.squeeze(); // shed excess memory combinedImage[chip]->wcs = new wcsprm(); combinedImage[chip]->initWCS(); // loop over all pixels, and images; rescaling is optional QVector<long> goodIndex; goodIndex.reserve(numImages); // Also checks whether the mode is within valid range (for calibrators): QVector<float> rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forCalibration"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } long ngood = goodIndex.length(); if (nhigh+nlow >= ngood) { emit messageAvailable("The number of nlow and nhigh rejected pixels is equal to or larger than the number of input exposures. Using zero instead", "warning"); nlow = 0; nhigh = 0; } QString goodImages; int k = 0; for (auto &gi : goodIndex) { goodImages.append(myImageList[chip][gi]->baseName + ": " + QString::number(myImageList[chip][gi]->skyValue, 'f', 3) + " e-, rescaled with " + QString::number(rescaleFactors[k], 'f', 3)); if (k<goodIndex.length()-1) goodImages.append("<br>"); ++k; } QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Calculating master "+dataType+" for chip "+QString::number(chip+1) + rescaled + " from : <br>"+goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // 45% of the progress counter is reserved for combining the images. We update the progress bar for every 10% of these 45% float localProgressStepSize = 0.45 / 10. / instData->numUsedChips * 100.; int progCount = 1; // runs from 1 to 10; long progCountComparison = dim / 10; // works on dataCurrent dim = combinedImage.at(chip)->dataCurrent.length(); // Crashed by stack.append(), but not when running through valgrind (no multi-threading)? // Update: does not crash anymore ... (at least for single-chip cameras) // TODO: more efficient with semaphore if numcpu and numchips divide with remainder //#pragma omp parallel for num_threads(maxCPU) if (instData->numChips == 1) //int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; // QList<MyImage*> imglist = myImageList[chip]; omp_set_nested(false); // somehow not yet threadsafe! // we still parallelise though for single-chip cameras: int localMaxThreads = 1; // NOT THREADSAFE // if (instData->numChips == 1) localMaxThreads = maxCPU; #pragma omp parallel for num_threads(localMaxThreads) firstprivate(rescaleFactors) // firstprivate(imglist, goodIndex, rescaleFactors) for (long i=0; i<dim; ++i) { QVector<float> stack; stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { // if clause: needed because objectmask can be empty and the lookup will segfault if (myImageList[chip][gi]->objectMaskDone) { if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataCurrent.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataCurrent.at(i) * rescaleFactors[k]); } /* if (imglist[gi]->objectMaskDone) { if (!imglist[gi]->objectMask[i]) { stack.append(imglist[gi]->dataCurrent[i] * rescaleFactors[k]); } } else { stack.append(imglist[gi]->dataCurrent[i] * rescaleFactors[k]); } */ ++k; } // auto &stackedPixel = combinedImage[chip]->dataCurrent[pix]; combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); // stackedPixel = combineFunction_ptr(stack, QVector<bool>(), ngood); // Increment the progressBar every 10 % if (i+1 == progCount * progCountComparison) { #pragma omp atomic *progress += localProgressStepSize; // emit addToProgressBar(localProgressStepSize); ++progCount; } } combinedImage[chip]->imageInMemory = true; successProcessing = true; combinedImage[chip]->emitModelUpdateNeeded(); } void Data::resetStaticModel() { staticModelDone.clear(); staticModelDone.resize(instData->numChips); for (auto &it : staticModelDone) it = false; } // Used for creating a background model void Data::combineImages(const int chip, const QString nlowString, const QString nhighString, const QString currentImage, const QString mode, const QString dirName, const QString subDirName, QVector<bool> &dataStaticModelDone) { if (!successProcessing) return; if (userStop || userKill) return; if (instData->badChips.contains(chip)) return; if (mode == "static" && dataStaticModelDone[chip]) return; QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining these images" +rescaled+" for " +currentImage + " : ", "data"); // Get image geometry from first image in list that has its size measured long n = 0; long m = 0; for (auto &back : myImageList.at(chip)) { if (back->useForBackground) { n = back->naxis1; m = back->naxis2; break; } } if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImges(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; int nlow = nlowString.toInt(); // returns 0 for empty string int nhigh = nhighString.toInt(); // returns 0 for empty string int numImages = myImageList.at(chip).length(); if (nhigh+nlow >= numImages) { emit messageAvailable("Number of low and high pixels rejected is equal or larger than the number of available images.", "error"); emit critical(); successProcessing = false; return; } // Instantiate a MyImage object for the combined set of images. It does not create a FITS object yet. // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; if (combinedImage.at(chip) == nullptr) { // re-using previously created object MyImage *masterCombined = new MyImage(dirName, currentImage, "", chip+1, mask->globalMask[chip], verbosity); connect(masterCombined, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(masterCombined, &MyImage::critical, this, &Data::pushCritical); connect(masterCombined, &MyImage::warning, this, &Data::pushWarning); connect(masterCombined, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(masterCombined, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(masterCombined, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); combinedImage[chip] = masterCombined; combinedImage[chip]->wcs = new wcsprm(); combinedImage[chip]->wcsInit = true; } combinedImage[chip]->naxis1 = n; combinedImage[chip]->naxis2 = m; combinedImage[chip]->dataCurrent.resize(dim); combinedImage[chip]->dataCurrent.squeeze(); // loop over all pixels, and images; rescaling is optional QVector<long> goodIndex; goodIndex.reserve(numImages); QVector<float> rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forBackground"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } QString goodImages; #pragma omp critical // QString thread safety it->chipname could be accessed simultaneously { int k = 0; for (auto &gi : goodIndex) { goodImages.append(myImageList[chip][gi]->chipName + ": " + QString::number(myImageList[chip][gi]->skyValue, 'f', 3) + " e-, rescaled with " + QString::number(rescaleFactors[k], 'f', 3)); if (k<goodIndex.length()-1) goodImages.append("<br>"); ++k; } } if (*verbosity > 0) emit messageAvailable(goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // works on dataBackupLx (?) long ngood = goodIndex.length(); if (nhigh+nlow >= ngood) { emit messageAvailable("The number of nlow and nhigh rejected pixels is equal to or larger than the number of input exposures. Using zero instead", "warning"); nlow = 0; nhigh = 0; } // int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; if (instData->numChips > 1) { QList<float> stack; // Not thread safe // long ngood = goodIndex.length(); // stack.reserve(ngood); // #pragma omp parallel for num_threads(localMaxThreads) for (long i=0; i<dim; ++i) { // not thread safe // QVector<float> stack; // stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { if (myImageList[chip][gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } ++k; } combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); stack.clear(); } } // Single chip: we can use inner parallelization! // UPDATE: identical to the section above, just 'stack' is declared inside the for loop and not outside else { // NOPE! we cannot, still crashing sometimes // #pragma omp parallel for num_threads(localMaxThreads) firstprivate(rescaleFactors) for (long i=0; i<dim; ++i) { QList<float> stack; long k = 0; for (auto &gi : goodIndex) { if (myImageList[chip][gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!myImageList[chip][gi]->objectMask[i]) { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } } else { stack.append(myImageList.at(chip).at(gi)->dataBackupL1.at(i) * rescaleFactors[k]); } ++k; } combinedImage[chip]->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); } } if (mode == "static") dataStaticModelDone[chip] = true; combinedImage[chip]->imageInMemory = true; successProcessing = true; } /* // Used for creating a background model void Data::combineImages_newParallel(int chip, MyImage *masterCombined, QList<MyImage*> &backgroundList, QString nlowString, QString nhighString, QString currentImage, QString mode, const QString subDirName) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticModelDone[chip]) return; masterCombined->setBackgroundLock(true); QString rescaled = ""; if (!rescaleFlag) rescaled = ", without rescaling, "; if (*verbosity > 0) emit messageAvailable(subDirName + " : Combining these images" +rescaled+" for " +currentImage + " : ", "data"); int nlow = nlowString.toInt(); // returns 0 for empty string (desired) int nhigh = nhighString.toInt(); // returns 0 for empty string (desired) // Get image geometry from first image in list that has its size measured long n = 0; long m = 0; for (auto &back : backgroundList) { if (back->useForBackground) { n = back->naxis1; m = back->naxis2; break; } } if (n == 0 || m == 0) { emit messageAvailable(subDirName + " : Data::combineImges(): Could not determine size of combined image.", "error"); emit critical(); successProcessing = false; return; } long dim = n*m; // Container for the temporary pixel stack int numImages = backgroundList.length(); // Instantiate a MyImage object for the combined set of images. // It does not create a FITS object yet. // Delete the instance if it exists already from a previous run of this task to not (re)create it // if (combinedImage[chip] != nullptr) delete combinedImage[chip]; connect(masterCombined, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(masterCombined, &MyImage::critical, this, &Data::pushCritical); connect(masterCombined, &MyImage::warning, this, &Data::pushWarning); connect(masterCombined, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(masterCombined, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(masterCombined, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); masterCombined->naxis1 = n; masterCombined->naxis2 = m; masterCombined->dataCurrent.resize(dim); masterCombined->dataCurrent.squeeze(); // loop over all pixels, and images; rescaling is optional QVector<long> goodIndex; goodIndex.reserve(numImages); // Also checks whether the mode is within valid range (for calibrators): QVector<float> rescaleFactors = getNormalizedRescaleFactors(chip, goodIndex, "forBackground"); if (rescaleFactors.isEmpty()) { // we should never enter here. Error handling in getNormalizedRescaleFactors() successProcessing = false; return; } QString goodImages; int k = 0; for (auto &gi : goodIndex) { MyImage *it = backgroundList[gi]; goodImages.append(it->chipName + ": " + QString::number(it->skyValue,'f',3) + " e-, rescaled with " + QString::number(rescaleFactors[k],'f',3)); if (k<goodIndex.length()-1) goodImages.append("<br>"); ++k; } if (*verbosity > 0) emit messageAvailable(goodImages, "image"); if (*verbosity > 0) emit messageAvailable(subDirName + " : Median combination running ...", "data"); // works on dataBackupLx (?) dim = masterCombined->dataCurrent.length(); // int localMaxThreads = maxCPU/instData->numChips; // if (instData->numChips > maxCPU) localMaxThreads = 1; // for some unknown reason this parallelization results in a massive memory chaos. somewhere, something is overflowing and I just can't figure out where. QList<float> stack; // long ngood = goodIndex.length(); // stack.reserve(ngood); // #pragma omp parallel for num_threads(localMaxThreads) for (long i=0; i<dim; ++i) { // QVector<float> stack; // stack.reserve(ngood); long k = 0; for (auto &gi : goodIndex) { // Not sure why I have included the requirement on dataBackupL1[i] != 0. // For flat-fielded data (not sky subtracted), the pixel values should always be positive. Commented out for the time being // if (!backgroundList[gi]->objectMask[i] && backgroundList[gi]->dataBackupL1[i] > 0.) { // stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); // } // } // else { // if (backgroundList[gi]->dataBackupL1[i] > 0.) { // stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); // } // } // Crash caused by dataBackgroundL1. Stack, rescaleFactors, backgroundList[gi] MyImages are all fine. // It appears to be the actual data vectors, but the debugger shows that everything gets mixed up. if (backgroundList[gi]->objectMaskDone) { // needed because objectmask can be empty and the lookup will segfault if (!backgroundList[gi]->objectMask[i]) { stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); } } else { stack.append(backgroundList[gi]->dataBackupL1[i] * rescaleFactors[k]); } ++k; } masterCombined->dataCurrent[i] = straightMedian_MinMax(stack, nlow, nhigh); stack.clear(); // stackedPixel = combineFunction_ptr(stack, QVector<bool>(), ngood); } masterCombined->imageInMemory = true; successProcessing = true; masterCombined->setBackgroundLock(false); } */ void Data::getModeCombineImages(int chip) { if (!successProcessing) return; if (userStop || userKill) return; if (combinedImage[chip]->modeDetermined) return; if (instData->badChips.contains(chip)) return; // Get the mean / mode of the combined image if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) combinedImage[chip]->skyValue = meanMask(combinedImage[chip]->dataCurrent, mask->globalMask[chip]); // if (*verbosity > 0) emit messageAvailable("Mean of chip "+QString::number(chip+1) + " for master "+dataType + " : " // + QString::number(combinedImage[chip]->skyValue) + " e-", "data"); } else { combinedImage[chip]->skyValue = modeMask(combinedImage[chip]->dataCurrent, "stable", mask->globalMask[chip])[0]; // if (*verbosity > 0) emit messageAvailable("Mode of chip "+QString::number(chip+1) + " for master "+dataType + " : " // + QString::number(combinedImage[chip]->skyValue) + " e-", "data"); } combinedImage[chip]->modeDetermined = true; successProcessing = true; } void Data::reportModeCombineImages() { // Report the mean / mode of the combined image QString report = ""; if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { report = "Statistics (mean) for master "+dataType+" : <br>"; } else { report = "Statistics (mode) for master "+dataType+" : <br>"; } for (int chip=0; chip<instData->numChips; ++chip) { if (!successProcessing) { if (!userStop && !userKill) { report.append("Chip " + QString::number(chip+1) + " : failed<br>"); } } else { if (instData->badChips.contains(chip)) { report.append("Chip " + QString::number(chip+1) + " : Bad detector, skipped.<br>"); } else { report.append("Chip " + QString::number(chip+1) + " : " + QString::number(combinedImage[chip]->skyValue, 'f', 3) + " e-<br>"); } } } emit messageAvailable(report, "data"); } QVector<float> Data::getNormalizedRescaleFactors(int chip, QVector<long> &goodIndex, QString mode) { long nImages = myImageList[chip].length(); QVector<float> rescaleFactors; rescaleFactors.reserve(nImages); goodIndex.reserve(nImages); if (userStop || userKill) return rescaleFactors; if (mode == "forBackground") { for (auto &it: myImageList[chip]) { if (it->useForBackground && !it->modeDetermined) { emit messageAvailable("Data::getNormalizedRescaleFactors(): Mode should have been determined in taskInternal()!", "error"); emit critical(); successProcessing = false; return rescaleFactors; // empty } } } if (!rescaleFlag) { // Combining a BIAS or DARK long j=0; for (auto &it : myImageList.at(chip)) { if (it->validMode) { rescaleFactors.append(1.0); goodIndex.append(j); } else { if (*verbosity > 0) emit messageAvailable(it->chipName + " : Not used, mode outside user limits : " + QString::number(it->skyValue), "warning"); } ++j; } return rescaleFactors; } else if (mode == "forCalibration") { // Combining a FLAT long j=0; for (auto &it : myImageList.at(chip) ) { if (it->validMode) { rescaleFactors.append(it->skyValue); goodIndex.append(j); } else { if (*verbosity > 0) emit messageAvailable(it->chipName + " : Not used, mode outside user limits : " + QString::number(it->skyValue), "warning"); } ++j; } } else if (mode == "forBackground") { // Combining a SCIENCE / SKY image long j=0; for (auto &it : myImageList.at(chip) ) { if (it->useForBackground) { rescaleFactors.append(it->skyValue); goodIndex.append(j); } ++j; } } else { emit messageAvailable("Data::getNormalizedRescaleFactors(): Invalid operating mode: " + mode, "error"); emit critical(); } // Rescale modes relative to mean mode float meanMode = meanMask(rescaleFactors); for (auto &it : rescaleFactors) it = meanMode / it; return rescaleFactors; } // copy the master flat field, threshold it void Data::initGlobalWeight(int chip, Data *flatData, QString filter, bool sameWeight, QString flatMin, QString flatMax) { if (!successProcessing) return; if (instData->badChips.contains(chip)) return; // myImageList[chip].clear(); QString globalWeightName = "globalweight_"+instData->name+"_"+filter+"_"+QString::number(chip+1)+".fits"; MyImage *myImage = new MyImage(mainDirName, globalWeightName, "", chip+1, mask->globalMask[chip], verbosity); // myImage->setParent(this); myImage->filter = filter; myImage->path = mainDirName+"/GLOBALWEIGHTS/"; myImage->naxis1 = instData->sizex[chip]; myImage->naxis2 = instData->sizey[chip]; connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); myImage->wcs = new wcsprm(); myImage->initWCS(); // Potential masking long i=0; float flatMinVal = 0.; float flatMaxVal = 1.e9; QString thresholds = ", no thresholding"; if (!flatMin.isEmpty() && !flatMax.isEmpty()) { flatMinVal = flatMin.toFloat(); flatMaxVal = flatMax.toFloat(); thresholds = ", thresholds = ["+flatMin+", "+flatMax+"]"; } else if (!flatMin.isEmpty()) { flatMinVal = flatMin.toFloat(); thresholds = ", thresholds = ["+flatMin+", unlimited]"; } else if (!flatMax.isEmpty()) { flatMaxVal = flatMax.toFloat(); thresholds = ", thresholds = [unlimited, "+flatMax+"]"; } // Initiate with the flat field, or unity everywhere if (!sameWeight) { if (flatData == nullptr) { emit messageAvailable("No FLAT data defined. Initializing globalweight for chip " + QString::number(chip+1) + " with constant value 1.0", "warning"); emit warning(); long dim = instData->sizex[chip] * instData->sizey[chip]; myImage->dataCurrent.fill(1.0, dim); } else { if (flatData->successProcessing) { if (*verbosity > 0) emit messageAvailable("Initializing globalweight for chip " + QString::number(chip+1) + " from master flat"+thresholds, "data"); // done before calling this function // if (!flatData->combinedImage[chip]->imageInMemory) flatData->combinedImage[chip]->setupDataInMemorySimple(true); myImage->dataCurrent = flatData->combinedImage[chip]->dataCurrent; // shallow copy } } } else { if (*verbosity > 0) emit messageAvailable("Initializing globalweight for chip " + QString::number(chip+1) + " with constant value 1.0", "data"); long dim = instData->sizex[chip] * instData->sizey[chip]; myImage->dataCurrent.fill(1.0, dim); myImage->dataCurrent.resize(dim); // CHECK: do we still need that given the previous line? myImage->dataCurrent.squeeze(); // shed excess memory } for (auto &it: myImage->dataCurrent) { if (it < flatMinVal || it > flatMaxVal || mask->globalMask[chip][i]) { it = 0.; } ++i; } myImage->imageInMemory = true; myImageList[chip].append(myImage); } // Threshold the global weight based on clipping values for the current combined image void Data::thresholdGlobalWeight(int chip, const Data *comparisonData, const QString filter, const QString threshMin, const QString threshMax) { if (!successProcessing) return; if (instData->badChips.contains(chip)) return; if (comparisonData == nullptr) return; if (!comparisonData->successProcessing) return; if (threshMin.isEmpty() && threshMax.isEmpty()) return; if (userStop || userKill) return; float threshMinVal = -1.e9; float threshMaxVal = 1.e9; QString thresholds = ""; if (!threshMin.isEmpty() && !threshMax.isEmpty()) { threshMinVal = threshMin.toFloat(); threshMaxVal = threshMax.toFloat(); thresholds = "[threshMin, threshMax]"; } else if (!threshMin.isEmpty()) { threshMinVal = threshMin.toFloat(); thresholds = "["+threshMin+", unlimited]"; } else if (!threshMax.isEmpty()) { threshMaxVal = threshMax.toFloat(); thresholds = "[unlimited, "+threshMax+"]"; } if (*verbosity > 0) emit messageAvailable("Thresholding chip "+QString::number(chip+1)+ " of globalweight, " +comparisonData->dataType + " must be within "+ thresholds, "data"); for (auto &it: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == it->filter) { // done before calling this function // if (!comparisonData->combinedImage[chip]->imageInMemory) comparisonData->combinedImage[chip]->setupDataInMemorySimple(true); long k = 0; for (auto &jt: it->dataCurrent) { float compVal = comparisonData->combinedImage[chip]->dataCurrent[k]; if (compVal < threshMinVal || compVal > threshMaxVal) { jt = 0.; } ++k; } } } } void Data::detectDefects(int chip, Data *comparisonData, const QString filter, const bool sameWeight, const QString defectKernel, const QString defectRowTol, const QString defectColTol, const QString defectClusTol) { if (!successProcessing) return; if (instData->badChips.contains(chip)) return; if (sameWeight) return; if (defectKernel.isEmpty()) return; if (defectRowTol.isEmpty() && defectColTol.isEmpty() && defectClusTol.isEmpty()) return; if (!comparisonData->successProcessing) return; if (userStop || userKill) return; QString params = "kernel size = "+defectKernel; if (!defectClusTol.isEmpty()) params += (" clusTol = "+defectClusTol); if (!defectRowTol.isEmpty()) params += (" rowTol = "+defectRowTol); if (!defectColTol.isEmpty()) params += (" colTol = "+defectColTol); if (*verbosity > 0) emit messageAvailable("Defect detection for chip "+QString::number(chip+1)+": "+params, "data"); // Smooth the flatfield int filtersize = defectKernel.toInt(); QString splinemode = "spline"; comparisonData->combinedImage[chip]->backgroundModel(filtersize, splinemode); // Normalize the flat field by the smoothed image long n = comparisonData->combinedImage.at(chip)->naxis1; long m = comparisonData->combinedImage.at(chip)->naxis2; QVector<float> divImage(n*m); long i = 0; for (auto &it : divImage) { it = comparisonData->combinedImage.at(chip)->dataCurrent.at(i) / comparisonData->combinedImage.at(chip)->dataBackground.at(i); ++i; } comparisonData->combinedImage[chip]->releaseBackgroundMemory(); // Bad clusters if (!defectClusTol.isEmpty()) { for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { i = 0; for (auto &it : divImage) { if ( fabs(it-1.0) > defectClusTol.toFloat()) gw->dataCurrent[i] = 0.; ++i; } } } } // Bad rows float kappa = 1.5; if (!defectRowTol.isEmpty()) { QVector<float> column1D = collapse_x(divImage, comparisonData->combinedImage[chip]->globalMask, comparisonData->combinedImage[chip]->objectMask, kappa, n, m, "1Dmodel"); for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { long badIndex = 0; // Set all rows to zero where the row index in column1D is outside the thresholds for (auto &it : column1D) { if ( fabs(it-1.0) > defectRowTol.toFloat()) { for (long i=0; i<n; ++i) gw->dataCurrent[i+n*badIndex] = 0.; } ++badIndex; } } } } // Bad cols if (!defectColTol.isEmpty()) { QVector<float> row1D = collapse_y(divImage, comparisonData->combinedImage[chip]->globalMask, comparisonData->combinedImage[chip]->objectMask, kappa, n, m, "1Dmodel"); for (auto &gw: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == gw->filter) { long badIndex = 0; // Set all columns to zero where the column index in row1D is outside the thresholds for (auto &it : row1D) { if ( fabs(it-1.0) > defectColTol.toFloat()) { for (long j=0; j<m; ++j) gw->dataCurrent[badIndex+n*j] = 0.; } ++badIndex; } } } } } void Data::applyMask(int chip, QString filter) { if (instData->badChips.contains(chip)) return; for (auto &it: myImageList[chip]) { // Only process global weights that match the current science filter if (filter == it->filter) { long i = 0; for (auto &jt: it->dataCurrent) { if (mask->globalMask.at(chip).at(i)) { jt = 0.; } ++i; } } } } void Data::writeGlobalWeights(int chip, QString filter) { if (!successProcessing) return; if (instData->badChips.contains(chip)) return; if (*verbosity > 0) emit messageAvailable("Writing globalweight for chip " + QString::number(chip+1), "data"); if (instData->bayer.isEmpty()) { for (auto &gw: myImageList[chip]) { if (filter == gw->filter) { gw->writeImage(gw->path + "/" + gw->name, filter); } } } else { QString name; // WARNING! The following assumes that "B" is the filter of the first image in scienceData->myImageList. // The order in which we insert the images in processingCalibration is therefore important! for (auto &gw: myImageList[chip]) { // Create 3 FITS files name = "globalweight_"+instData->name+"_B_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "B"); name = "globalweight_"+instData->name+"_G_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "G"); name = "globalweight_"+instData->name+"_R_"+QString::number(chip+1)+".fits"; gw->writeImage(gw->path + "/" + name, "R"); } // Duplicate the gw image twice in myImageList: if (myImageList[chip].length() == 1) { MyImage *gw2 = new MyImage(mainDirName+"/GLOBALWEIGHTS/", "globalweight_"+instData->name+"_G_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); gw2->filter = "G"; gw2->dataCurrent = myImageList[chip][0]->dataCurrent; connect(gw2, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(gw2, &MyImage::critical, this, &Data::pushCritical); connect(gw2, &MyImage::warning, this, &Data::pushWarning); connect(gw2, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(gw2, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(gw2, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); MyImage *gw3 = new MyImage(mainDirName+"/GLOBALWEIGHTS/", "globalweight_"+instData->name+"_R_"+QString::number(chip+1)+".fits", "", chip+1, mask->globalMask[chip], verbosity); gw3->filter = "R"; gw3->dataCurrent = myImageList[chip][0]->dataCurrent; connect(gw3, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(gw3, &MyImage::critical, this, &Data::pushCritical); connect(gw3, &MyImage::warning, this, &Data::pushWarning); connect(gw3, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(gw3, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(gw3, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); myImageList[chip].append(gw2); myImageList[chip].append(gw3); } } } void Data::getGainNormalization() { if (!successProcessing) return; if (userStop || userKill) return; // Calculate the gain normalization factor. // The gains are normalized to the chip with the lowest effective gain // (the one with brightest image in a FLAT) QVector<float> gainNormalization; QVector<float> tmpNormalizationData; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) { gainNormalization << 1.0; // a dummy value to maintain the vector's structure (need one entry per chip) continue; } if (combinedImage[chip]->modeDetermined) { gainNormalization << combinedImage[chip]->skyValue; tmpNormalizationData << combinedImage[chip]->skyValue; } else { emit messageAvailable("Controller::getGainNormalization(): mode was not determined in flat!", "error"); emit critical(); successProcessing = false; return; } } float maxVal = maxVec_T(gainNormalization); if (*verbosity > 0 && instData->numChips>1) emit messageAvailable("Gain normalization factors (multi-chip cameras):", "data"); for (int chip=0; chip<instData->numChips; ++chip) { QString space = " "; if (chip > 9) space = ""; if (instData->badChips.contains(chip)) { if (*verbosity > 0) emit messageAvailable("Chip "+QString::number(chip+1) + space + " : Bad detector, skipped.", "ignore"); continue; } gainNormalization[chip] /= maxVal; combinedImage[chip]->gainNormalization = gainNormalization[chip]; if (*verbosity > 0) emit messageAvailable("Chip "+QString::number(chip+1) + space + " : " + QString::number(gainNormalization[chip], 'f', 6), "ignore"); } } void Data::protectMemory() { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { it->protectMemory(); } if (combinedImage[chip] != nullptr) { combinedImage[chip]->protectMemory(); } } } void Data::unprotectMemory(int chip) { for (auto &it : myImageList[chip]) { it->unprotectMemory(); } if (combinedImage[chip] != nullptr) { combinedImage[chip]->unprotectMemory(); } } void Data::unprotectMemoryForBackground(int chip) { for (auto &it : myImageList[chip]) { it->unprotectMemoryForBackground(); } } float Data::releaseMemory(float RAMneededThisThread, float RAMneededAllThreads, float currentTotalMemoryUsed, QString mode) { // Return if we have enough RAM available // qDebug() << RAMneededThisThread << RAMneededAllThreads << maxRAM << currentTotalMemoryUsed; if (RAMneededAllThreads < maxRAM - currentTotalMemoryUsed) return -1.; // Free RAM // Simply loop over data structure and free everything that is set to deletable, irrespective of chip, starting with lowest priority QStringList datalist; datalist << "dataBackground" << "dataBackupL3" << "dataBackupL2" << "dataBackupL1" << "dataWeight" << "dataCurrent"; float RAMfreed = 0.; // We release memory in a different order, depending on the process: // If creating master calibrators, we release the previous master calibs and then the raw data. // If we calibrate the science data, we release the raw data in the calibrators first, and then the combined images if (mode == "calibrator") { releaseMemoryCombined(RAMfreed, RAMneededThisThread); releaseMemoryIndividual(datalist, RAMfreed, RAMneededThisThread); } else { releaseMemoryIndividual(datalist, RAMfreed, RAMneededThisThread); releaseMemoryDebayer(RAMfreed, RAMneededThisThread); releaseMemoryCombined(RAMfreed, RAMneededThisThread); } return RAMfreed; } void Data::releaseAllMemory() { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { if (it == nullptr) continue; else it->freeData("all"); } if (combinedImage[chip] == nullptr) continue; else combinedImage[chip]->freeData("all"); } emit globalModelUpdateNeeded(); } void Data::releaseMemoryIndividual(const QStringList &datalist, float &RAMfreed, const float RAMneededThisThread) { for (auto &datatype : datalist) { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { RAMfreed += it->freeData(datatype); if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } } void Data::releaseMemoryDebayer(float &RAMfreed, const float RAMneededThisThread) { if (!currentlyDebayering) return; for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : bayerList[chip]) { RAMfreed += it->freeData("dataCurrent"); if (RAMfreed > RAMneededThisThread) break; } if (RAMfreed > RAMneededThisThread) break; } } void Data::releaseMemoryCombined(float &RAMfreed, const float RAMneededThisThread) { // Release memory occupied by combined images for (int chip=0; chip<instData->numChips; ++chip) { // if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF" || dataType == "FLAT") { // If executed without data structure having loaded a combined image (or if it wasn't created yet) // it would crash, because none of the class members were instantiated if (combinedImage[chip] == nullptr) continue; RAMfreed += combinedImage[chip]->freeData("dataBackground"); RAMfreed += combinedImage[chip]->freeData("dataBackupL1"); RAMfreed += combinedImage[chip]->freeData("dataCurrent"); // } if (RAMfreed > RAMneededThisThread) break; } } void Data::setMemoryLockReceived(bool locked) { emit setMemoryLock(locked); } void Data::setWCSLockReceived(bool locked) { emit setWCSLock(locked); } // Set which data can (or cannot) be deleted from memory void Data::memorySetDeletable(int chip, QString dataX, bool deletable) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(dataX + " for chip " + QString::number(chip+1) + " marked 'deletable'", "data"); for (auto &it : myImageList[chip]) { if (dataX == "dataCurrent") it->dataCurrent_deletable = deletable; else if (dataX == "dataBackupL1") it->dataBackupL1_deletable = deletable; else if (dataX == "dataBackupL2") it->dataBackupL2_deletable = deletable; else if (dataX == "dataBackupL3") it->dataBackupL3_deletable = deletable; else if (dataX == "dataWeight") it->dataWeight_deletable = deletable; } successProcessing = true; } void Data::writeCombinedImage(int chip) { if (!successProcessing) return; if (userStop || userKill) return; QString name = dirName+"/"+subDirName+"_"+QString::number(chip+1)+".fits"; float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = true; if (*verbosity > 0) emit messageAvailable("Writing "+subDirName+"_"+QString::number(chip+1)+".fits", "data"); combinedImage[chip]->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedImage[chip]->successProcessing; } void Data::writeBackgroundModel(const int &chip, const QString &mode, const QString &basename, bool &staticImageWritten) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticImageWritten) return; QDir backgroundDir(dirName+"/BACKGROUND/"); backgroundDir.mkdir(dirName+"/BACKGROUND/"); float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = false; QString shortName; if (mode == "static") shortName = subDirName+"/BACKGROUND/"+subDirName+"_"+QString::number(chip+1)+".fits"; else shortName = subDirName+"/BACKGROUND/"+basename+".back.fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedImage[chip]->writeImage(name, filter, exptime, addGainNormalization); if (mode == "static") staticImageWritten = true; successProcessing = combinedImage[chip]->successProcessing; } /* void Data::writeBackgroundModel_newParallel(int chip, MyImage *combinedBackgroundImage, QString mode, QString basename, int threadID, omp_lock_t &backLock, bool &staticImageWritten) { if (!successProcessing) return; if (userStop || userKill) return; if (mode == "static" && staticImageWritten) return; QDir backgroundDir(dirName+"/BACKGROUND/"); backgroundDir.mkdir(dirName+"/BACKGROUND/"); float exptime = myImageList[chip][0]->exptime; QString filter = myImageList[chip][0]->filter; bool addGainNormalization = false; if (mode == "dynamic") { QString shortName = subDirName+"/BACKGROUND/"+basename+".back.fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedBackgroundImage->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedBackgroundImage->successProcessing; } else { // static mode // We need a lock so that the model for a given chip is written only once // Some paranoia with checks concerning the state of the model and thread safety. if (staticImageWritten) return; omp_set_lock(&backLock); if (!staticImageWritten) { QString shortName = subDirName+"/BACKGROUND/"+subDirName+"_"+QString::number(chip+1)+".fits"; QString name = mainDirName+"/"+shortName; if (*verbosity > 0) emit messageAvailable("Writing "+mode+" background model "+shortName, "data"); combinedBackgroundImage->writeImage(name, filter, exptime, addGainNormalization); successProcessing = combinedBackgroundImage->successProcessing; staticImageWritten = true; } omp_unset_lock(&backLock); } } */ void Data::resetUserAbort() { userYield = false; userStop = false; userKill = false; } void Data::resetObjectMasking() { // Reset object masks from a potential previous pass if (*verbosity > 0) emit messageAvailable("Resetting object masks ...", "data"); for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->resetObjectMasking(); } } } // only used for debayering void Data::repopulate(int chip, QList<MyImage*> replacementList) { for (auto &it : myImageList[chip]) { it->freeAll(); // delete it; // Must not delete in case of debayering!!! will cause crash in DataModel } myImageList[chip].clear(); for (auto &it : replacementList) { myImageList[chip].append(it); } } void Data::populate(QString statusString) { if (*verbosity > 2) emit messageAvailable(subDirName + " : Initializing images ...", "data"); // Read either raw or processed images (master calibs are handled in the c'tor) numImages = 0; #pragma omp parallel for num_threads(maxCPU) firstprivate(dirName, subDirName, statusString) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; QStringList filter; filter << "*_"+QString::number(chip+1)+statusString+".fits"; QStringList fitsFiles = dir.entryList(filter); // TODO: when splitting data, we must use a filter that does not contain the _chip string (raw data) // if list == empty then reset string and reload myImageList[chip].clear(); for (auto &it : fitsFiles) { bool skip = false; // skip master calibs and normalized flats if (it == subDirName+"_"+QString::number(chip+1)+".fits") skip = true; if (skip) continue; MyImage *myImage = new MyImage(dirName, it, statusString, chip+1, mask->globalMask[chip], verbosity); // myImage->setParent(this); connect(myImage, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); connect(myImage, &MyImage::critical, this, &Data::pushCritical); connect(myImage, &MyImage::warning, this, &Data::pushWarning); connect(myImage, &MyImage::messageAvailable, this, &Data::pushMessageAvailable); connect(myImage, &MyImage::setMemoryLock, this, &Data::setMemoryLockReceived, Qt::DirectConnection); connect(myImage, &MyImage::setWCSLock, this, &Data::setWCSLockReceived, Qt::DirectConnection); myImage->imageOnDrive = true; myImageList[chip].append(myImage); #pragma omp critical { if (!uniqueChips.contains(chip+1)) uniqueChips.push_back(chip+1); } } #pragma omp atomic numImages += myImageList[chip].length(); } // Sort the vector with the chip numbers (no particular reason, yet) std::sort(uniqueChips.begin(), uniqueChips.end()); if (*verbosity > 0) emit messageAvailable(subDirName + " : " + QString::number(numImages) + " Images initialized ...", "data"); } void Data::countUnsavedImages(long &numUnsavedLatest, long &numUnsavedBackup) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList.at(chip)) { if (!it->imageOnDrive) ++numUnsavedLatest; if (it->backupL1InMemory && !it->backupL1OnDrive) ++numUnsavedBackup; if (it->backupL2InMemory && !it->backupL2OnDrive) ++numUnsavedBackup; if (it->backupL3InMemory && !it->backupL3OnDrive) ++numUnsavedBackup; } } } bool Data::isEmpty() { if (myImageList.isEmpty()) return true; bool empty = true; for (int chip=0; chip<instData->numChips; ++chip) { empty = myImageList.at(chip).isEmpty() & empty; } if (empty) return true; else return false; } void Data::clearImageInfo() { imageInfo.baseName.clear(); imageInfo.fullName.clear(); imageInfo.naxis1.clear(); imageInfo.naxis2.clear(); imageInfo.filter.clear(); imageInfo.mjdobs.clear(); imageInfo.chip.clear(); } bool Data::collectMJD() { if (!successProcessing) return false; // Get the MJD for all images in all chips if it hasn't been read yet // (e.g., if the user starts THELI and continues some processing) // The FITS handles are always present in MyImage, even if it hasn't been read yet if (*verbosity > 0) emit messageAvailable("Retrieving Modified Julian Dates ...<br>", "data"); bool duplicateFound = false; // The MJD is the same for all chips, hence we could just test it for chip 1. // But if one of the images of chip 1 was removed because it was bad, then this would break down; // Therefore, read it for every chip in every exposure #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(subDirName) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; QVector<double> mjdData; mjdData.reserve(myImageList[chip].length()); if (duplicateFound) continue; for (auto &it : myImageList[chip]) { // if (!it->hasMJDread) { // it->imageFITS->getMJD(); it->getMJD(); // it->mjdobs = it->imageFITS->mjdobs; // it->hasMJDread = true; // } if (*verbosity == 3) emit messageAvailable(it->chipName + " : MJD-OBS = " +QString::number(it->mjdobs, 'f', 12), "image"); mjdData.append(it->mjdobs); } if (!duplicateFound && hasDuplicates_T(mjdData)) { // QmessageBox displayed only once (cannot break from loop because of omp parallel) emit showMessageBox("Data::DUPLICATE_MJDOBS", subDirName, ""); duplicateFound = true; } } if (duplicateFound) return false; else return true; } // The background header correction tasks needs a number of header keywords // before processing the actual exposures bool Data::getPointingCharacteristics() { if (!successProcessing) return false; if (*verbosity > 0) emit messageAvailable("Retrieving pointing characteristics for "+subDirName + " ...", "data"); QVector<double> crval1Exposure; QVector<double> crval2Exposure; QVector<double> crval1Vertex; QVector<double> crval2Vertex; // we include unused chips here because otherwise any centroids our boundaries might be biased for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { it->loadHeader(); crval1Exposure << it->wcs->crval[0]; crval2Exposure << it->wcs->crval[1]; crval1Vertex << it->alpha_ll; crval1Vertex << it->alpha_lr; crval1Vertex << it->alpha_ul; crval1Vertex << it->alpha_ur; crval2Vertex << it->delta_ll; crval2Vertex << it->delta_lr; crval2Vertex << it->delta_ul; crval2Vertex << it->delta_ur; } } RAcenter = straightMedian_T(crval1Exposure, false); DECcenter = straightMedian_T(crval2Exposure, false); // Declination double crval2Min = minVec_T(crval2Vertex); double crval2Max = maxVec_T(crval2Vertex); double crval2Radius = 60.*(crval2Max - crval2Min) / 2.; // Right ascension double crval1Min = minVec_T(crval1Vertex); double crval1Max = maxVec_T(crval1Vertex); // Did we cross the origin (qualitative check)? // If yes, then we need to correct the values if (crval1Max - crval1Min > 350.) { for (auto &it : crval1Vertex) { if (it > 180.) it -= 180.; } crval1Min = minVec_T(crval1Vertex); crval1Max = maxVec_T(crval1Vertex); } double crval1Radius = 60.*(crval1Max - crval1Min) / 2. * cos(DECcenter*rad); // Maximum search radius, plus 10% safety margin searchRadius = 1.1*sqrt(crval1Radius*crval1Radius + crval2Radius*crval2Radius); if (RAcenter == -100. || DECcenter == -100. || searchRadius == -100.) return false; else return true; } bool Data::hasImages() { if (numImages == 0) { emit showMessageBox("Data::IMAGES_NOT_FOUND", processingStatus->statusString, dirName); emit critical(); return false; } else return true; } void Data::resetProcessbackground() { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->resetObjectMasking(); it->hasBrightStarsChecked = false; it->backgroundModelDone = false; it->segmentationDone = false; it->maskExpansionDone = false; it->backupCopyBackgroundMade = false; it->leftBackgroundWindow = false; // possibly squeeze some of the data vectors, but then we'd just need to reserve them again [...] } } } void Data::cleanBackgroundModelStatus() { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { it->resetObjectMasking(); it->backgroundModelDone = false; it->segmentationDone = false; it->maskExpansionDone = false; } } } QVector<double> Data::getKeyFromAllImages(const QString key) { if (*verbosity > 1) emit messageAvailable("Retrieving key " + key + " for images in " + subDirName + " ...", "data"); // dumping everything to a double vector QVector<double> data; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (!it->metadataTransferred) it->loadHeader(); // needed if data requested immediately after launch if (key == "CRVAL1") data << it->wcs->crval[0]; else if (key == "CRVAL2") data << it->wcs->crval[1]; else if (key == "CRPIX1") data << it->wcs->crpix[0]; else if (key == "CRPIX2") data << it->wcs->crpix[1]; else if (key == "NAXIS1") data << it->naxis1; else if (key == "NAXIS2") data << it->naxis2; else if (key == "CORNERS_CRVAL1") { data << it->alpha_ll; data << it->alpha_lr; data << it->alpha_ul; data << it->alpha_ur; } else if (key == "CORNERS_CRVAL2") { data << it->delta_ll; data << it->delta_lr; data << it->delta_ul; data << it->delta_ur; } else if (key == "DATE-OBS") { double tmp = dateobsToDecimal(it->dateobs); // Only append if dateobs is valid (we won't have data taken before the year 1000) if (tmp > 1000.) data << tmp; } } } return data; } void Data::modelUpdateReceiver(QString chipName) { emit modelUpdateNeeded(chipName); } void Data::pushMessageAvailable(QString message, QString type) { emit messageAvailable(message, type); } void Data::pushCritical() { emit critical(); } void Data::pushWarning() { emit warning(); } int Data::identifyClusters(QString toleranceString) { if (!successProcessing) return 0; // This routine detects associations of images that are overlapping, and assigns a unique number int groupNumber = 0; int groupNumberOld = 0; float tolerance = 0.; if (!toleranceString.isEmpty()) tolerance = toleranceString.toFloat() / 60.; // Initiate the first of all images myImageList[instData->validChip][0]->groupNumber = groupNumber; for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { it->loadHeader(); } } bool unassigned = true; int loop = 0; while (unassigned) { // Loop over all images to see if they overlap with the current image for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : myImageList[chip]) { // Jump over images that have been assigned already if (loop > 0 && it->groupNumber == groupNumberOld) continue; // Check distance of all other images to the current image, and update their groupNumber if matching findOverlappingImages(it, tolerance); } } // Check if images remain unassigned groupNumberOld = groupNumber; unassigned = checkForUnassignedImages(groupNumber); ++loop; } if (*verbosity >= 0) { if (groupNumber == 0) { emit messageAvailable("A single image association was identified. It is left unchanged.", "data"); } else { emit messageAvailable(QString::number(groupNumber+1)+" image associations identified ...", "data"); } } return groupNumber; } void Data::doImagesOverlap(const MyImage &imgRef, MyImage &imgTest, const float tolerance) { if (!successProcessing) return; double alpha1 = rad * imgRef.wcs->crval[0]; double delta1 = rad * imgRef.wcs->crval[1]; double alpha2 = rad * imgTest.wcs->crval[0]; double delta2 = rad * imgTest.wcs->crval[1]; double dDelta = delta2 - delta1; double dAlpha = alpha2 - alpha1; // Haversine formula to calculate angular distance between two points on a sphere double distance = 2.*asin( sqrt( pow(sin(dDelta/2.),2) + cos(delta1)*cos(delta2)*pow(sin(dAlpha/2.),2))) / rad; if (distance <= 2.* instData->radius + tolerance) imgTest.groupNumber = imgRef.groupNumber; } void Data::findOverlappingImages(const MyImage *img, const float tolerance) { if (!successProcessing) return; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { // If unassigned, check overlap and if positive, assign same group number if (it->groupNumber == -1) { doImagesOverlap(*img, *it, tolerance); } } } } bool Data::checkForUnassignedImages(int &groupNumber) { if (!successProcessing) return false; bool unassigned = false; for (int chip=0; chip<instData->numChips; ++chip) { bool breaked = false; for (auto &it : myImageList[chip]) { if (it->groupNumber == -1) { unassigned = true; // Another group exists, increase group counter, and start group ++groupNumber; it->groupNumber = groupNumber; breaked = true; break; } } if (breaked) break; } return unassigned; } // Restores FITS images from backupDirName; replaces dataCurrent with dataBackup (if in memory) void Data::restoreBackupLevel(QString backupDirName) { emit messageAvailable("Restoring "+backupDirName + " images ...", "data"); if (backupDirName == "_IMAGES") { emit messageAvailable("Inconsistency detected in backup structure. This is likely a bug.", "error"); emit critical(); return; } QDir backupDir(dirName+"/"+backupDirName); // Qt 5.7 compatibility backupDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); if (!backupDir.exists() || backupDir.count() == 0) { emit messageAvailable(dirName+"/"+backupDirName+": No backup FITS files found, restoring memory only.", "data"); } /* * QT5.9 if (!backupDir.exists() || backupDir.isEmpty()) { emit messageAvailable(dirName+"/"+backupDirName+": No backup FITS files found, restoring memory only.", "data"); } */ // Remove all currently present FITS files removeCurrentFITSfiles(); // CASE 1: Restore the raw data if (backupDirName == "RAWDATA") { restoreRAWDATA(); return; } // CASE 2: Data in memory (and on drive) // Comparing output from QDir::absolutePath() because it removes double // and trailing / QDir d1(pathBackupL1); QDir d2(pathBackupL2); QDir d3(pathBackupL3); QDir dc(dirName+"/"+backupDirName); bool success = true; QString newStatusRAM = ""; if (d1.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L1", newStatusRAM); else if (d2.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L2", newStatusRAM); else if (d3.absolutePath() == dc.absolutePath()) success = success && restoreFromBackupLevel("L3", newStatusRAM); // qDebug() << "success = " << success << newStatusRAM; // Leave if there was an error during file operations if (!success) { emit messageAvailable("Data::restoreBackupLevel(): Error restoring FITS files from " + backupDirName, "error"); emit critical(); return; } else { // If newStatusRAM has changed then the operation was successful, and we can remove the directory if (!newStatusRAM.isEmpty()) { if (backupDir != QDir::home()) backupDir.removeRecursively(); emit statusChanged(newStatusRAM); emit updateModelHeaderLine(); return; } } // qDebug() << "BLEVEL CASE3"; // CASE 3: We are still here. That means the user selected a backup dir on drive that is not mapped in one of the backup levels restoreFromDirectory(backupDirName); } void Data::removeCurrentFITSfiles() { QStringList fitsFileNames = dir.entryList(QStringList() << "*.fits"); for (auto &it : fitsFileNames) { QFile fitsFile(dirName+"/"+it); if (!fitsFile.remove()) { emit messageAvailable("Could not delete " + it + "! Manual cleanup required.", "error"); emit critical(); } } } void Data::removeCatalogs() { // Remove all scamp, SourceExtractor and .anet catalogs. Keep the iview catalogs // Used when recreating source catalogs QDir catalogDir(dirName + "/cat/"); QStringList catFileNames = catalogDir.entryList(QStringList() << "*.cat" << "*.scamp" << "*.anet" ); for (auto &it : catFileNames) { QFile catFile(dirName+"/cat/"+it); if (!catFile.remove()) { emit messageAvailable("Could not delete " + it, "warning"); emit warning(); } } } // Reflecting backup parameters in Data after successful processing void Data::transferBackupInfo() { if (!successProcessing) return; MyImage *it = myImageList[instData->validChip][0]; pathBackupL1 = it->pathBackupL1; pathBackupL2 = it->pathBackupL2; pathBackupL3 = it->pathBackupL3; statusBackupL1 = it->statusBackupL1; statusBackupL2 = it->statusBackupL2; statusBackupL3 = it->statusBackupL3; } // Reset status (when restoring original data) void Data::resetBackupInfo() { processingStatus->statusString = ""; pathBackupL1 = ""; pathBackupL2 = ""; pathBackupL3 = ""; statusBackupL1 = ""; statusBackupL2 = ""; statusBackupL3 = ""; } // Used if data is restored from a backup dir alone, i.e. data are not present in RAM in any backup level void Data::restoreFromDirectory(QString backupDirName) { // Check if any data can be restored QDir backupDir(dirName+"/"+backupDirName); if (!backupDir.exists()) { emit messageAvailable("Data::restoreFromDirectory(): " + subDirName+"/"+backupDirName+" does not exist, no data were restored or deleted.", "error"); emit critical(); return; } backupDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // Qt 5.7 compatibility // if (backupDir.isEmpty()) { Qt 5.9 if (backupDir.count() == 0) { emit messageAvailable(subDirName+"/"+backupDirName+" is empty, no data were restored or deleted.", "error"); emit critical(); return; } // Remove all currently present FITS files removeCurrentFITSfiles(); QString newStatusDrive = ""; if (backupDirName == "RAWDATA") newStatusDrive = ""; else newStatusDrive = backupDirName.split("_").at(0); processingStatus->statusToBoolean(newStatusDrive); processingStatus->getStatusString(); processingStatus->writeToDrive(); if (!moveFiles("*.fits", dirName+"/"+backupDirName, dirName)) { emit messageAvailable(backupDirName + " : Restoring failed for some or all FITS files", "error"); emit critical(); return; } else { // Paranoia check (afaik this can never happen, but nonetheless ...) if (backupDirName == QDir::homePath()) { emit messageAvailable("Data::restoreFromDirectory(): STOP: Was about to remove your home directory! This should never happen.", "error"); emit critical(); return; } if (!backupDir.removeRecursively()) { emit messageAvailable("Data::restoreFromDirectory(): Could not completely remove " + backupDirName, "error"); emit critical(); return; } } emit statusChanged(newStatusDrive); emit updateModelHeaderLine(); } // Returns false if anything goes wrong with the file operations bool Data::restoreFromBackupLevel(QString level, QString &newStatusRAM) { long i = 0; bool success = true; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: myImageList[chip]) { // Continue if no backup data in RAM if (level == "L1") success = success && it->makeL1Current(); else if (level == "L2") success = success && it->makeL2Current(); else if (level == "L3") success = success && it->makeL3Current(); emit it->modelUpdateNeeded(it->chipName); if (i==0) newStatusRAM = it->processingStatus->statusString; QString statusTmp2 = it->processingStatus->statusString; if (statusTmp2 != newStatusRAM) { emit messageAvailable("Data::restoreBackupLevel(): Inconsistent processing status detected in RAM", "error"); emit critical(); return false; } ++i; } } // Obsolete images have been removed. Now also remove the corresponding backup directories. // Some paranoia making sure we don't accidentally delete the user's home directory. if (level == "L1") { QDir backupL3(pathBackupL3); if (!pathBackupL3.isEmpty() && backupL3 != QDir::home()) backupL3.removeRecursively(); } if (level == "L2") { QDir backupL1(pathBackupL1); QDir backupL3(pathBackupL3); if (!pathBackupL1.isEmpty() && backupL1 == QDir::home()) backupL1.removeRecursively(); if (!pathBackupL3.isEmpty() && backupL3 == QDir::home()) backupL3.removeRecursively(); } if (level == "L3") { QDir backupL1(pathBackupL1); QDir backupL2(pathBackupL2); if (!pathBackupL1.isEmpty() && backupL1 == QDir::home()) backupL1.removeRecursively(); if (!pathBackupL2.isEmpty() && backupL2 != QDir::home()) backupL2.removeRecursively(); } transferBackupInfo(); processingStatus->statusToBoolean(newStatusRAM); processingStatus->getStatusString(); processingStatus->writeToDrive(); return success; } void Data::restoreRAWDATA() { QDir rawdataDir(dirName+"/RAWDATA"); if (!rawdataDir.exists()) { emit messageAvailable(subDirName+"/RAWDATA does not exist, "+subDirName+" remains unmodified.", "note"); emit warning(); return; } rawdataDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // Qt 5.7 compatibility // if (rawdataDir.isEmpty()) { Qt 5.9 if (rawdataDir.count() == 0) { emit messageAvailable(subDirName+"/RAWDATA is empty, "+subDirName+" remains unmodified.", "note"); emit warning(); return; } // Protect RAWDATA by moving it if (!rawdataDir.rename(dirName+"/RAWDATA", mainDirName+"/"+subDirName+"_rawdata")) { emit messageAvailable("Could not create temporary directory "+mainDirName+"/"+subDirName+"_rawdata!", "error"); emit critical(); return; } emit messageAvailable("Restoring " + dirName+"/RAWDATA ...", "data"); // Paranoia check (afaik this can never happen, but nonetheless ...) if (dirName == QDir::homePath()) { emit messageAvailable("Data::restoreRAWDATA(): STOP: Was about to remove your home directory! This should never happen.", "error"); emit critical(); return; } // remove current dir dir.removeRecursively(); // restore rawdataDir.rename(mainDirName+"/"+subDirName+"_rawdata", dirName); emit setMemoryLock(true); releaseAllMemory(); resetBackupInfo(); myImageList.clear(); combinedImage.clear(); myImageList.resize(instData->numChips); combinedImage.resize(instData->numChips); dataInitialized = false; emit globalModelUpdateNeeded(); // CHECK: not necessarily threadsafe, depending on the thread in which the slot gets executed emit setMemoryLock(false); QString newStatus = ""; processingStatus->deleteFromDrive(); processingStatus->reset(); // processingStatus->writeToDrive(); emit statusChanged(newStatus); emit updateModelHeaderLine(); } void Data::emitStatusChanged() { emit statusChanged(processingStatus->statusString); emit updateModelHeaderLine(); } bool Data::hasMatchingPartnerFiles(QString testDirName, QString suffix, bool abort) { if (!successProcessing) return false; // This function checks whether e.g. all science exposures have a weight, or astrometric header // List of images QStringList imageList; if (suffix == ".scamp") { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (!imageList.contains(it->rootName) && it->activeState == MyImage::ACTIVE) { imageList.append(it->rootName); } } } } else { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList.append(it->chipName); } } } // List of reference data (weights, catalogs, headers, etc ...) QDir testDir(testDirName); QStringList notMatched; QStringList filter("*"+suffix); QStringList testList = testDir.entryList(filter); testList.replaceInStrings(suffix,""); imageList.sort(); testList.sort(); // If entries are equal, or list1 is fully contained in list2, then we can leave // Equal? if (imageList.operator ==(testList)) { return true; } else { // Fully contained? for (auto & it : imageList) { // If not contained in list2, add it to the list of missing items if (!testList.contains(it)) notMatched << it; } } if (notMatched.isEmpty()) return true; else { QString missingItems; int i = 0; for (auto &it: notMatched) { if (i>19) { missingItems.append("...\n"); break; // Do not show more than 20 items } missingItems.append(it); // missingItems.append(suffix); missingItems.append("\n"); ++i; } if (abort) { emit messageAvailable(subDirName + " : Not all images have matching "+suffix+ " files!", "error"); emit critical(); successProcessing = false; } else { emit messageAvailable(subDirName + " : Not all images have matching "+suffix+ " files!", "warning"); emit warning(); } long nbad = notMatched.length(); if (suffix.contains("weight")) { emit showMessageBox("Data::WEIGHT_DATA_NOT_FOUND", QString::number(nbad), missingItems); } else if (suffix.contains("head")) { emit showMessageBox("Data::HEADER_DATA_NOT_FOUND", QString::number(nbad), missingItems); } else if (suffix.contains("scamp")) { emit showMessageBox("Data::SCAMP_CATS_NOT_FOUND", QString::number(nbad), missingItems); } return false; } } void Data::criticalFromQueryReceived() { successProcessing = false; } bool Data::doesCoaddContainRaDec(const QString &refRA, const QString &refDEC) { if (refRA.isEmpty() && refDEC.isEmpty()) return true; // Start assuming that no chip of a multi-chip camera contains this coordinate. If a single chip does contain it, we can break and exit bool containsRADEC = false; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList.at(chip)) { if (it->containsRaDec(refRA, refDEC)) { containsRADEC = true; break; } } } return containsRADEC; } // Data is listening to all its MyImages /* void Data::establish_connections() { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &image : myImageList[chip]) { connect(image, &MyImage::modelUpdateNeeded, this, &Data::modelUpdateReceiver); } } } */ void Data::deleteMyImageList() { if (myImageList.isEmpty()) return; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: myImageList[chip]) { delete it; it = nullptr; } } } /* void Data::forceStatus(int chip, QString status) { for (auto &it : myImageList[chip]) { it->processingStatus->statusString = status; } } */ /* void Data::getFixedHeaderKeys(QString filename, QStringList &badImages) { if (userStop || userKill) return; long naxis1 = 0; long naxis2; QString filter = "UNKNOWN"; double mjdobs = 0.; fitsfile *fptr = nullptr; int status = 0; fits_open_file(&fptr, filename.toUtf8().data(), READONLY, &status); if (!status) { char *filterName = new char(filename.length()+10); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdobs, NULL, &status); fits_read_key_str(fptr, "FILTER", filterName, NULL, &status); if (status && !badImages.contains(filename)) { badImages.push_back(filename); imageInfo.naxis1.push_back(0); imageInfo.naxis2.push_back(0); imageInfo.mjdobs.push_back(0.); imageInfo.filter.push_back("UNKNOWN"); } else { filter = QString(filterName); imageInfo.naxis1.push_back(naxis1); imageInfo.naxis2.push_back(naxis2); imageInfo.mjdobs.push_back(mjdobs); imageInfo.filter.push_back(filter); // qDebug() << qSetRealNumberPrecision(12) << mjdobs; } delete filterName; filterName = nullptr; } fits_close_file(fptr, &status); if (status) { emit messageAvailable(subDirName + " : Data::getFixedHeaderKeys(): Could not read NAXIS1/2, MJD-OBS, and/or FILTER in" + filename, "error"); printCfitsioError("getFixedHeaderKeys()", status); } } */ // Reads relevant keywords from the headers /* bool Data::getHeaders() { QStringList badImages; for (auto &it : imageInfo.fullName) { getFixedHeaderKeys(dirName+"/"+it, badImages); } if (!badImages.isEmpty()) { // Truncate (in case of lots of images) QString summary = truncateImageList(badImages,10); emit messageAvailable(tr("Could not read one or more of the following keywords:<br>NAXIS1, NAXIS2, FILTER, MJD-OBS")+ tr("<br>Add the keywords manually, or the remove the corrupted images.<br>")+summary, "error"); emit critical(); emit showMessageBox("Data::CANNOT_READ_HEADER_KEYS", summary, ""); return false; } else { return true; } } */ // Calculates the median geometry for the images of a chip. // Identifies outliers and moves them to a 'badGeometry/' sub-directory // UNUSED /* QString Data::checkGeometry() { if (!successProcessing) return ""; QStringList badImages; for (auto &chip : uniqueChips) { // Find images matching that chip, extract their geometries QStringList imageList = collectNamesForChip(chip); QVector<int> tmp1; QVector<int> tmp2; for (auto &it : imageList) { tmp1.push_back(imageInfo.naxis1[mapName.value(it)]); tmp2.push_back(imageInfo.naxis2[mapName.value(it)]); } // Median image geometry for chip 'chip': int medianNaxis1 = straightMedian_T(tmp1); int medianNaxis2 = straightMedian_T(tmp2); mapNaxis1.insert(chip, medianNaxis1); mapNaxis2.insert(chip, medianNaxis2); // Collect images whose geometry deviates from the median geometry for (auto &it : imageList) { if (imageInfo.naxis1[mapName.value(it)] != medianNaxis1 || imageInfo.naxis2[mapName.value(it)] != medianNaxis2) { badImages << it; } } } if (badImages.isEmpty()) return "success"; // What to do with the bad images QString summary = truncateImageList(badImages, 10); emit messageAvailable(subDirName + " : WARNING: The 2D dimensions of the following images deviate from the median dimension:<br>" +summary+"<br>"+ "This can be a result of inconsistent binning or readout modes.<br> " "THELI can move these images to a 'badGeometries/' sub-directory " "and re-attempt the process. Alternatively, you can cancel and inspect the data yourself " "before trying again.\n", "warning"); QMessageBox msgBox; msgBox.setText(tr("ERROR: The 2D dimensions of the following images deviate from the median dimension:")); msgBox.setInformativeText(summary+ "This can be a result of inconsistent binning or readout modes. " "THELI can move these images to a 'badGeometries/' sub-directory " "and re-attempt the process. Alternatively, you can cancel and inspect the data yourself " "before trying again.\n"); QAbstractButton *pButtonOk = msgBox.addButton(tr("Move images and re-try"), QMessageBox::YesRole); QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole); msgBox.exec(); if (msgBox.clickedButton()==pButtonOk) { // make a "badGeometry" sub-directory QString badDirName = dirName+"/badGeometry/"; QDir badDir(badDirName); badDir.mkpath(badDirName); // move selected images to badstats for (auto &it : badImages ) { QFile badFile(dirName+"/"+it); if (!badFile.rename(badDirName+"/"+it)) { emit messageAvailable(subDirName + " : Data::checkGeometry(): Could not execute the following operation:<br>"+ "mv " + dirName+"/"+it + badDirName+"/"+it, "error"); emit critical(); return "cancel"; } } return "recurse"; } else { return "cancel"; } } */ /* void Data::incrementCurrentThreads(int &currentThreads, omp_lock_t &lock) { omp_set_lock(&lock); ++currentThreads; omp_unset_lock(&lock); } void Data::decrementCurrentThreads(int &currentThreads, omp_lock_t &lock) { omp_set_lock(&lock); --currentThreads; omp_unset_lock(&lock); } */ /* void Data::getModeCombineImagesBackground(int chip, MyImage *image) { if (!successProcessing) return; if (userStop || userKill) return; if (image->modeDetermined) return; // Get the mean / mode of the combined image if (dataType == "BIAS" || dataType == "DARK" || dataType == "FLATOFF") { // mode doesn't work, as all values are very very narrowly distributed around a single value (which might be integer on top of that) image->skyValue = meanMask(image->dataCurrent, mask->globalMask[chip]); } else { image->skyValue = modeMask(image->dataCurrent, "stable", mask->globalMask[chip])[0]; } image->modeDetermined = true; successProcessing = true; } */ /* void Data::writeGlobalflags(int chip, QString filter) { if (*verbosity > 0) emit messageAvailable("Writing globalflag for chip " + QString::number(chip+1), "data"); // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; long naxis1 = instData->sizex[chip]; long naxis2 = instData->sizey[chip]; long nelements = naxis1*naxis2; unsigned int *array = new unsigned int[nelements]; for (long i=0; i<nelements; ++i) { array[i] = 0; } int bitpix = BYTE_IMG; long naxis = 2; long naxes[2] = { naxis1, naxis2 }; QString globalFlagName = mainDirName+"/GLOBALWEIGHTS/globalflag_"+instData->name+"_"+filter+"_"+QString::number(chip+1)+".fits"; // Overwrite file if it exists globalFlagName = "!"+globalFlagName; fits_create_file(&fptr, globalFlagName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TBYTE, fpixel, nelements, array, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError("writeGlobalflags()", status); } */ /* float Data::memoryNeeded(int chip) { float footprint = 0; for (auto &it: myImageList[chip]) { footprint += it->dataCurrent.size() * sizeof(float); } return footprint / 1024. / 1024.; } */ /* float Data::memoryCurrentFootprint(bool globalweights) { float footprint = 0.; // Storage (in MB) used for all images currently held in memory // CHECK: crashes here when clicking the project reset button right after launching the GUI. // still crashes despite this if-clause. MyImageList[chip] seems undefined (innermost for loop) if (processingStatus == nullptr || !processingStatus->HDUreformat || !dataInitialized) return 0.; // MyImageList undefined, or no data loaded yet // For an unknown reason, I cannot access myImageList for GLOBALWEIGHTS when changing a project; memoryprogressbar then crashes the UI if (!globalweights) { if (!myImageList.isEmpty()) { // e.g. if RAWDATA are restored for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: myImageList[chip]) { footprint += it->dataCurrent.capacity() * sizeof(float); footprint += it->dataBackupL1.capacity() * sizeof(float); footprint += it->dataBackupL2.capacity() * sizeof(float); footprint += it->dataBackupL3.capacity() * sizeof(float); footprint += it->dataMeasure.capacity() * sizeof(float); footprint += it->objectMask.capacity() * sizeof(bool); footprint += it->dataWeight.capacity() * sizeof(float); footprint += it->dataWeightSmooth.capacity() * sizeof(float); footprint += it->dataBackground.capacity() * sizeof(float); footprint += it->dataSegmentation.capacity() * sizeof(long); } } } // Also check for debayered images that are not yet in the nominal myimage list if (!bayerList.isEmpty()) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it: bayerList[chip]) { footprint += it->dataCurrent.capacity() * sizeof(float); } } } } if (!combinedImage.isEmpty()) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; // Crashes if equal to nullptr if (combinedImage[chip] != nullptr) { footprint += combinedImage[chip]->dataCurrent.capacity() * sizeof(float); } } } return footprint /= (1024 * 1024); } */ // UNUSED // Force free // should use the controller's 'lock' /* void Data::memoryFreeDataX(int chip, QString dataX) { // if (!successProcessing) return; QVector<float> empty {}; if (dataX != "combined") { long memReleased = myImageList[chip][0]->dataCurrent.length()*4*myImageList[chip].length(); if (*verbosity > 1) emit messageAvailable("Freeing "+QString::number(memReleased) + " MB", "data"); for (auto &it : myImageList[chip]) { if (dataX == "dataCurrent") it->dataCurrent.swap(empty); else if (dataX == "dataBackupL1") it->dataBackupL1.swap(empty); else if (dataX == "dataBackupL2") it->dataBackupL2.swap(empty); else if (dataX == "dataBackupL3") it->dataBackupL3.swap(empty); else if (dataX == "dataWeight") it->dataWeight.swap(empty); } } else { long memReleased = combinedImage[chip]->dataCurrent.length()*4; if (*verbosity > 1) emit messageAvailable("Freeing "+QString::number(memReleased) + " MB", "data"); combinedImage[chip]->dataCurrent.swap(empty); } // successProcessing = true; } */ /* bool Data::setModeFlag(int chip, QString min, QString max) { if (!successProcessing) return false; QString thresholds = "[" + min + "," + max + "]"; for (auto &it : myImageList[chip] ) { // Try and read image; readImage() returns true immediately if image is already in memory // if (!(it->readImage())) return false; // if (!it->modeDetermined) { // qDebug() << "QDEBUG: Data::setModeFlag(): Error: Mode should have been determined."; // return false; // } if (!min.isEmpty()) { if (it->skyValue < min.toFloat()) { it->validMode = false; } } if (!max.isEmpty()) { if (it->skyValue > max.toFloat()) it->validMode = false; } if (!it->validMode) { if (*verbosity > 0) emit messageAvailable(it->baseName + " : Mode "+it->skyValue+" is outside user-defined thresholds " + thresholds + ". Image will be ignored when calculating master calibs.", "data"); } } return true; } */ // UNUSED /* bool Data::writeImages(int chip, QString statusString) { if (!successProcessing) return false; if (userStop || userKill) return false; bool success = true; // unused for (auto &it : myImageList[chip]) { it->processingStatus->statusString = statusString; it->writeImage(); } return success; } */ /* QString Data::getMasterFilename(QString type, int chip) { return mainDirName+"/"+type+"/"+type+"_"+QString::number(chip+1)+".fits"; } */ /* QVector<long> Data::getOverscanArea(QString axis, int chip) { QVector<long> overscanArea; // X-axis if (axis == "x") { QVector<int> min = instData->overscan_xmin; QVector<int> max = instData->overscan_xmax; if (!min.isEmpty() && !max.isEmpty()) { overscanArea << min[chip]; overscanArea << max[chip]; } } // Y-axis if (axis == "y") { QVector<int> min = instData->overscan_ymin; QVector<int> max = instData->overscan_ymax; if (!min.isEmpty() && !max.isEmpty()) { overscanArea << min[chip]; overscanArea << max[chip]; } } return overscanArea; } */ /* QStringList Data::collectNamesForChip(int chip) { QStringList names; long k = 0; for (auto &it: imageInfo.chip) { if (it == chip) names << imageInfo.fullName[k]; ++k; } return names; } */ // UNUSED /* bool Data::containsUnsavedImages() { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : myImageList[chip]) { if (!it->imageOnDrive) return false; } } return true; } */ /* QStringList Data::collectNamesForFilter(QString filter) { QStringList names; long k = 0; for (auto &it: imageInfo.filter) { if (it == filter) names << imageInfo.fullName[k]; ++k; } return names; } */ /* void Data::pushErrorOccurred() { emit errorOccurredInMyImage(); } */ /* void Data::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("Data::"+funcName+":<br>" + subDirName + " : " + errorCodes->errorKeyMap.value(status), "error"); emit critical(); } } */
123,703
C++
.cc
2,755
36.824682
219
0.628615
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,473
processingCollapse.cc
schirmermischa_THELI/src/processingInternal/processingCollapse.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalCollapse() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigCollapse(); memoryDecideDeletableStatus(scienceData, false); backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; // Parameters for collapse correction QString DT = cdw->ui->COCDTLineEdit->text(); QString DMIN = cdw->ui->COCDMINLineEdit->text(); QString expFactor = cdw->ui->COCmefLineEdit->text(); QString direction = cdw->ui->COCdirectionComboBox->currentText(); QString threshold = cdw->ui->COCrejectLineEdit->text(); bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { if (verbosity >= 0) emit messageAvailable(it->baseName + " : Collapse correction ...", "controller"); it->setupDataInMemory(isTaskRepeated, true, true); it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor, false); it->collapseCorrection(threshold, direction); it->makeMemoryBackup(); it->statusCurrent = statusNew; it->baseName = it->chipName + statusNew; it->imageOnDrive = false; if (alwaysStoreData) it->writeImage(); incrementProgress();64 } if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } decrementCurrentThreads(lock); } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); // Release as much memory as maximally necessary float nimg = 7; // old, new, background, segmentation, measure, mask, margin releaseMemory(nimg*instData->storage*maxCPU, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); long imin = 0; long imax = 0; long jmin = 0; long jmax = 0; if (!cdw->ui->COCxminLineEdit->text().isEmpty()) imin = cdw->ui->COCxminLineEdit->text().toLong() - 1; if (!cdw->ui->COCxmaxLineEdit->text().isEmpty()) imax = cdw->ui->COCxmaxLineEdit->text().toLong() - 1; if (!cdw->ui->COCyminLineEdit->text().isEmpty()) jmin = cdw->ui->COCyminLineEdit->text().toLong() - 1; if (!cdw->ui->COCymaxLineEdit->text().isEmpty()) jmax = cdw->ui->COCymaxLineEdit->text().toLong() - 1; #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Collapse correction ...", "image"); it->processingStatus->Collapse = false; it->setupData(scienceData->isTaskRepeated, true, true, backupDirName); // CHECK: why do we determine the mode here? if (!it->successProcessing) { abortProcess = true; continue; } it->backgroundModel(256, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->transferObjectsToMask(); it->maskExpand(expFactor, false); it->addExludedRegionToMask(imin, imax, jmin, jmax); it->collapseCorrection(threshold, direction); it->releaseAllDetectionMemory(); it->releaseBackgroundMemory("entirely"); updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } #pragma omp atomic progress += progressStepSize; } /* // Just file movements (if on drive), does not require parallelization for (int chip=0; chip<instData->numChips; ++chip) { if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); it->makeDriveBackup(statusOld+"_IMAGES", statusOld); } } } */ checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Collapse = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalBinnedpreview() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigBinnedpreview(); // Collect CD matrices (from first exposure in the list) // The transformation matrix is the CD matrix with rotation angle and plate scale stripped QVector< QVector<double>> CDmatrices; QVector< QVector<int>> Tmatrices; for (int chip=0; chip<instData->numChips; ++chip) { if (!instData->badChips.contains(chip) && !scienceData->myImageList[chip].isEmpty()) { scienceData->myImageList[chip][0]->readImage(false); QVector<double> CDmatrix = scienceData->myImageList[chip][0]->extractCDmatrix(); CDmatrices << CDmatrix; Tmatrices << CDmatrixToTransformationMatrix(CDmatrix, instData->name); } else { // a dummy QVector<double> CDmatrix = {-0.001, 0.0, 0.0, 0.001}; CDmatrices << CDmatrix; Tmatrices << CDmatrixToTransformationMatrix(CDmatrix, instData->name); } } // Determine overall image size int nGlobal; int mGlobal; int xminOffset; int yminOffset; int binFactor = cdw->ui->BIPSpinBox->value(); getBinnedSize(instData, Tmatrices, nGlobal, mGlobal, binFactor, xminOffset, yminOffset); memoryDecideDeletableStatus(scienceData, false); int numExp = scienceData->myImageList[instData->validChip].length(); getNumberOfActiveImages(scienceData); float nimg = (1 + 1./(binFactor*binFactor)) * instData->numChips; releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numExp, instData->storageExposure); QString statusString = scienceData->processingStatus->statusString; // Loop over all exposures #pragma omp parallel for num_threads(maxCPU) firstprivate(statusString) for (int img=0; img<numExp; ++img) { if (abortProcess || !successProcessing) continue; releaseMemory(nimg*instData->storage, maxCPU); // Loop over all chips if (verbosity >= 0) emit messageAvailable("Binning and mapping chips in exposure " + QString::number(img) + " / " + QString::number(numExp), "controller"); QVector<float> dataBinnedGlobal(nGlobal*mGlobal,0); int binnedChipCounter = 0; for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess) break; if (instData->badChips.contains(chip)) continue; scienceData->myImageList[chip][img]->setupDataInMemorySimple(false); if (!scienceData->myImageList[chip][img]->successProcessing) continue; int n = scienceData->myImageList[chip][img]->naxis1; int m = scienceData->myImageList[chip][img]->naxis2; int crpix1 = scienceData->myImageList[chip][img]->getKeyword("CRPIX1").toFloat() / binFactor; int crpix2 = scienceData->myImageList[chip][img]->getKeyword("CRPIX2").toFloat() / binFactor; int nb = floor(n/binFactor); int mb = floor(m/binFactor); QVector<float> dataBinned(nb*mb,0); // Bin the image; map it onto the output binned image; if (verbosity >= 1) emit messageAvailable(scienceData->myImageList[chip][img]->chipName + " : Binning ...", "image"); binData(scienceData->myImageList[chip][img]->dataCurrent, dataBinned, n, nb, mb, binFactor, binFactor); mapBinnedData(dataBinnedGlobal, dataBinned, Tmatrices[chip], nGlobal, mGlobal, nb, mb, crpix1, crpix2, xminOffset, yminOffset, instData->name); scienceData->myImageList[chip][img]->unprotectMemory(); if (minimizeMemoryUsage) { scienceData->myImageList[chip][img]->freeAll(); } ++binnedChipCounter; #pragma omp atomic progress += progressStepSize; } if (binnedChipCounter == 0) continue; // skip inactive images QString outName = scienceData->myImageList[instData->validChip][img]->rootName; outName.append("_"+statusString+".mosaic.fits"); QString outDirName = scienceData->dirName+"/BINNED/"; QDir outDir(outDirName); if (!outDir.exists()) outDir.mkdir(outDirName); QFile out(outDirName+outName); if (out.exists()) out.remove(); MyImage *myBinnedImage = new MyImage(outDirName, outName, "", 1, QVector<bool>(), &verbosity); connect(myBinnedImage, &MyImage::critical, this, &Controller::criticalReceived); connect(myBinnedImage, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(myBinnedImage, &MyImage::warning, this, &Controller::warningReceived); connect(myBinnedImage, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(myBinnedImage, &MyImage::setMemoryLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); myBinnedImage->naxis1 = nGlobal; myBinnedImage->naxis2 = mGlobal; myBinnedImage->dataCurrent.swap(dataBinnedGlobal); myBinnedImage->writeImage(outDirName+outName); // TODO: preserve for iView; set memory flags accordingly; could create myImageList and construct iView accordingly delete myBinnedImage; myBinnedImage = nullptr; } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } // Load the plot viewer emit loadViewer(scienceData->dirName+"/BINNED/", "*_"+scienceData->processingStatus->statusString+".mosaic.fits", "DragMode"); }
12,681
C++
.cc
258
41.20155
130
0.669333
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,474
dictionaries.cc
schirmermischa_THELI/src/processingInternal/dictionaries.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include <QMap> #include <QString> #include <QStringList> void Controller::populateHeaderDictionary() { // The mandatory THELI header keywords, and possible corresponding key names in the raw data of other instruments // headerDictionary.insert("CTYPE1", {"CTYPE1"}); // Forced, hence not read from headers // headerDictionary.insert("CTYPE2", {"CTYPE2"}); // Forced, hence not read from headers headerDictionary.insert("CRPIX1", {"CRPIX1", "J_CRPIX1"}); headerDictionary.insert("CRPIX2", {"CRPIX2", "J_CRPIX2"}); headerDictionary.insert("CD1_1", {"CD1_1", "J_CD1_1"}); headerDictionary.insert("CD1_2", {"CD1_2", "J_CD1_2"}); headerDictionary.insert("CD2_1", {"CD2_1", "J_CD2_1"}); headerDictionary.insert("CD2_2", {"CD2_2", "J_CD2_2"}); headerDictionary.insert("CDELT1", {"CDELT1"}); headerDictionary.insert("CDELT2", {"CDELT2"}); headerDictionary.insert("CRVAL1", {"CRVAL1", "RA", "OBJCTRA", "MEANRA", "OBSRA", "CRVAL1A", "RA-D", "RA_DEG", "RA-HOURS", "RASTRNG", "TELRA"}); headerDictionary.insert("CRVAL2", {"CRVAL2", "DEC", "OBJCTDEC", "MEANDEC", "OBSDEC", "CRVAL2A", "DEC-D", "DEC_DEG", "DECSTRNG", "TELDEC"}); headerDictionary.insert("RADESYS", {"RADESYS", "RADECSYS"}); headerDictionary.insert("OBJECT", {"OBJECT", "QUEUEID", "TARGET", "TARGNAME"}); headerDictionary.insert("AIRMASS", {"AIRMASS", "AMSTART", "HIERARCH ESO TEL AIRM START", "SECZ", "FZ_MP", "TELAM"}); headerDictionary.insert("EXPTIME", {"EXPTIME", "EXPOSURE", "EXPOS", "EXPOSED", "EXP_TIME", "TTIME"}); headerDictionary.insert("EQUINOX", {"EQUINOX", "EPOCH", "RADECEQ", "TELEP"}); headerDictionary.insert("DATE-OBS", {"DATE-OBS", "DATEOBS", "DATE_OBS", "DATE_BEG", "DATE", "UTSHUT", "TIME"}); headerDictionary.insert("MJD-OBS", {"MJD-OBS", "MJD_OBS"}); headerDictionary.insert("NAMPS", {"NAMPS"}); headerDictionary.insert("GAIN", {"EGAIN", "ELECGAIN", "GAIN", "HIERARCH ESO DET CHIP GAIN", "HIERARCH ESO DET OUT1 CONAD", "HIERARCH ESO DET OUT-1 ADU"}); // careful with gain and inverse gain! headerDictionary.insert("FILTER", {"FILTER", "FILTER1", "FILTER2", "FILTER3", "FILTER01", "FILTER02", "FILTER03", "FILTERID", "FILT1", "FILT2", "FILTERS", "FILTNAME", "SUBSET", "HIERARCH ESO INS FILT1 NAME", "HIERARCH ESO INS FILT2 NAME", "HIERARCH ESO INS FILT3 NAME", "HIERARCH ESO INS FILT4 NAME", "HIERARCH ESO INS OPTI-2 NAME", "HIERARCH ESO INS2 NXFW NAME", "AFT", "ALFLTNM", "FAFLTNM", "FBFLTNM", "FILTRE", "FLTRNAME", "PFMFNAME", "WFFBAND", "ACAMFSLI", "ACAMWH1", "ACAMWH2", "INGF1NAM", "INGF2NAM", "LIRF1NAM", "LIRF2NAM", "NCFLTNM1", "NCFLTNM2", "FWA_POS"}); // Other keywords of interest (to calculate others, or preserve information) headerDictionary.insert("INSTRUME", {"INSTRUME", "DETECTOR"}); headerDictionary.insert("PC1_1", {"PC1_1"}); headerDictionary.insert("PC1_2", {"PC1_2"}); headerDictionary.insert("PC2_1", {"PC2_1"}); headerDictionary.insert("PC2_2", {"PC2_2"}); headerDictionary.insert("DATE", {"DATE", "DATE-OBS", "DATEOBS", "UT-DATE"}); headerDictionary.insert("TIME", {"EXPSTART", "TIME", "TIME-OBS", "UT", "UT-TIME", "UTSTART", "UT-STR", "TELUT"}); headerDictionary.insert("LST", {"LST", "LST-OBS", "LSTHDR", "LST_OBS", "OBS-LST", "SD_TIME", "ST"}); headerDictionary.insert("DIT", {"EXP1TIME", "EXPCOADD", "EXPTIME", "HIERARCH ESO DET DIT", "ITIME", "K_DETEP1", "TRUITIME", "DIT"}); headerDictionary.insert("NDIT", {"COADD", "COADDONE", "COADDS", "COAVERAG", "HIERARCH ESO DET NDIT", "NCOADD", "NDIT"}); // headerDictionary.insert("IMAGEID", {}); // headerDictionary.insert("GABODSID", {}); // headerDictionary.insert("ZP", {}); // headerDictionary.insert("COEFF", {}); /* * ABOUT GAIN: * FourStar has a GAIN keyword, but the correct one is EGAIN" */ } // Used to replace long filter names by short ones void Controller::populateFilterDictionary() { // FLAMINGOS2 filterDictionary.insert("DK_G0807+J_G0802", "DARK"); filterDictionary.insert("DK_G0807", "DARK"); filterDictionary.insert("J_G0802", "J"); filterDictionary.insert("H_G0803", "H"); filterDictionary.insert("Ks_G0804", "Ks"); filterDictionary.insert("Y_G0811", "Y"); filterDictionary.insert("J-lo_G0801", "Jlo"); filterDictionary.insert("JH_G0809", "JH"); filterDictionary.insert("HK_G0806_good", "HK"); // GSAOI filterDictionary.insert("Blocked1_G1114", "DARK"); filterDictionary.insert("Blocked2_G1128", "DARK"); filterDictionary.insert("Z_G1101", "Z"); filterDictionary.insert("J_G1102", "J"); filterDictionary.insert("H_G1103", "H"); filterDictionary.insert("Kprime_G1104", "Kp"); filterDictionary.insert("Kshort_G1105", "Ks"); filterDictionary.insert("K_G1106", "K"); filterDictionary.insert("Jcont_G1107", "Jc"); filterDictionary.insert("Hcont_G1108", "Hc"); filterDictionary.insert("CH4short_G1109", "CH4s"); filterDictionary.insert("CH4long_G1110", "CH4l"); filterDictionary.insert("Kcntshrt_G1111", "Kcs"); filterDictionary.insert("Kcntlong_G1112", "Kcl"); filterDictionary.insert("HeI1083_G1115", "HeI"); filterDictionary.insert("PaG_G1116", "PaG"); filterDictionary.insert("PaB_G1117", "PaB"); filterDictionary.insert("FeII_G1118", "FeII"); filterDictionary.insert("H2(1-0)_G1121", "H210"); filterDictionary.insert("BrG_G1122", "BrG"); filterDictionary.insert("H2(2-1)_G1123", "H221"); filterDictionary.insert("CO2360_G1124", "CO2360"); // NIRI filterDictionary.insert("H_G0203", "H"); filterDictionary.insert("J_G0202", "J"); filterDictionary.insert("Kshort_G0205", "Ks"); filterDictionary.insert("Y_G0241", "Y"); filterDictionary.insert("Lprime_G0207", "Lp"); // MOIRCS filterDictionary.insert("J_SUB", "J"); // GROND_OPT filterDictionary.insert("grond_g", "g"); filterDictionary.insert("grond_r", "r"); filterDictionary.insert("grond_i", "i"); filterDictionary.insert("grond_z", "z"); // MOSCA@NOT filterDictionary.insert("U_Bes361_62", "U"); filterDictionary.insert("B_Bes428_108", "B"); filterDictionary.insert("V_Bes536_89", "V"); filterDictionary.insert("R_Bes646_124", "R"); filterDictionary.insert("I_int817_163", "I"); filterDictionary.insert("u_SDSS353_55", "u"); filterDictionary.insert("g_SDSS480_145", "g"); filterDictionary.insert("r_SDSS618_148", "r"); filterDictionary.insert("i_SDSS771_171", "i"); filterDictionary.insert("z_SDSS832_LP", "z"); // WFI@MPGESO filterDictionary.insert("BBB99_ESO842", "B"); filterDictionary.insert("BBV89_ESO843", "V"); filterDictionary.insert("BBRc162_ESO844", "Rc"); filterDictionary.insert("BBB/123_ESO878", "Bnew"); filterDictionary.insert("BBI/203_ESO879", "I"); filterDictionary.insert("BBIclwp_ESO845", "Ic"); filterDictionary.insert("BBIcIwp_ESO845", "Ic"); filterDictionary.insert("BBU38_ESO841", "U38"); filterDictionary.insert("BBU50_ESO877", "U50"); // IMACS filterDictionary.insert("Sloan_u", "u"); filterDictionary.insert("Sloan_g", "g"); filterDictionary.insert("Sloan_r", "r"); filterDictionary.insert("Sloan_i", "i"); filterDictionary.insert("Sloan_z", "z"); // MOSAIC-III filterDictionary.insert("Usparek1029", "U"); filterDictionary.insert("Uk1001", "U"); filterDictionary.insert("BHarrisk1002", "B"); filterDictionary.insert("VHarrisk1003", "V"); filterDictionary.insert("RHarrisk1004", "R"); filterDictionary.insert("INearly-Mouldk1005", "I"); filterDictionary.insert("CWashingtonk1006", "C"); filterDictionary.insert("MWashingtonk1007", "M"); filterDictionary.insert("haH-alphak1009", "Ha"); filterDictionary.insert("ha4H-alpha+4nmk1010", "Ha+4"); filterDictionary.insert("ha8H-alpha+8nmk1011", "Ha+8"); filterDictionary.insert("ha12H-alpha+12nmk1012", "Ha+12"); filterDictionary.insert("ha16H-alpha+16nmk1013", "SII"); filterDictionary.insert("O3OIIIN2k1014", "OIII"); filterDictionary.insert("OoffOIII+30nmk1015", "OIII+30"); filterDictionary.insert("gSDSSk1017", "g"); filterDictionary.insert("rSDSSk1018", "r"); filterDictionary.insert("iSDSSk1019", "i"); filterDictionary.insert("zSDSSk1020", "z"); filterDictionary.insert("OoffOIII+30nmk1030", "OIII+30"); filterDictionary.insert("OoffOIII+30nmk1031", "OIII+30"); filterDictionary.insert("gdDECcamk1035", "gd"); filterDictionary.insert("rdDECcamk1036", "rd"); filterDictionary.insert("zdDECcamk1038", "zd"); filterDictionary.insert("VRk1039", "VR"); filterDictionary.insert("UnSteidelk1041", "U"); filterDictionary.insert("GnSteidelk1042", "B"); filterDictionary.insert("RsSteidelk1043", "R"); filterDictionary.insert("UssolidUk1044", "U"); filterDictionary.insert("UdDeyk1045", "U"); filterDictionary.insert("815815_v2k1046", "820B"); filterDictionary.insert("823823_v2k1047", "820R"); filterDictionary.insert("337BATCk1051", "337_BATC"); filterDictionary.insert("390BATCk1052", "390_BATC"); filterDictionary.insert("420BATCk1053", "420_BATC"); filterDictionary.insert("454BATCk1054", "454_BATC"); filterDictionary.insert("493BATCk1055", "493_BATC"); filterDictionary.insert("527BATCk1056", "527_BATC"); filterDictionary.insert("579BATCk1057", "579_BATC"); filterDictionary.insert("607BATCk1058", "607_BATC"); filterDictionary.insert("666BATCk1059", "666_BATC"); filterDictionary.insert("705BATCk1060", "705_BATC"); filterDictionary.insert("755BATCk1061", "755_BATC"); filterDictionary.insert("802BATCk1062", "802_BATC"); filterDictionary.insert("848BATCk1063", "848_BATC"); filterDictionary.insert("918BATCk1064", "918_BATC"); filterDictionary.insert("973BATCk1065", "973_BATC"); // SAMI filterDictionary.insert("s0012rSDSS+s0012", "r"); // MEGACAM@LCO filterDictionary.insert("u,gblk", "u"); filterDictionary.insert("g,gblk", "g"); filterDictionary.insert("r,gblk", "r"); filterDictionary.insert("i,gblk", "i"); filterDictionary.insert("z,gblk", "z"); filterDictionary.insert("gblk,u", "u"); filterDictionary.insert("gblk,g", "g"); filterDictionary.insert("gblk,r", "r"); filterDictionary.insert("gblk,i", "i"); filterDictionary.insert("gblk,z", "z"); // GMOS filterDictionary.insert("u_G0308", "u"); filterDictionary.insert("u_G0332", "u"); filterDictionary.insert("g_G0301", "g"); filterDictionary.insert("g_G0325", "g"); filterDictionary.insert("r_G0303", "r"); filterDictionary.insert("r_G0326", "r"); filterDictionary.insert("i_G0302", "i"); filterDictionary.insert("i_G0327", "i"); filterDictionary.insert("z_G0304", "z"); filterDictionary.insert("z_G0328", "z"); filterDictionary.insert("Ha_G0336", "Ha"); filterDictionary.insert("Ha_G0310", "Ha"); filterDictionary.insert("HaC_G0337", "HaC"); filterDictionary.insert("HaC_G0311", "HaC"); filterDictionary.insert("SII_G0335", "SII"); filterDictionary.insert("SII_G0317", "SII"); filterDictionary.insert("OIII_G0338", "OIII"); filterDictionary.insert("OIII_G0318", "OIII"); filterDictionary.insert("OIIIC_G0339", "OIIIC"); filterDictionary.insert("OIIIC_G0319", "OIIIC"); filterDictionary.insert("OVI_G0345", "OVI"); filterDictionary.insert("OVI_G0347", "OVI"); filterDictionary.insert("OVIC_G0346", "OVIC"); filterDictionary.insert("OVIC_G0348", "OVIC"); filterDictionary.insert("HeII_G0320", "HeII"); filterDictionary.insert("HeII_G0340", "HeII"); filterDictionary.insert("HeIIC_G0321", "HeIIC"); filterDictionary.insert("HeIIC_G0341", "HeIIC"); // LDSS3 filterDictionary.insert("g_Sloan", "g"); filterDictionary.insert("r_Sloan", "r"); filterDictionary.insert("i_Sloan", "i"); filterDictionary.insert("z_Sloan", "z"); // HSC filterDictionary.insert("HSC-g", "g"); filterDictionary.insert("HSC-r", "r"); filterDictionary.insert("HSC-i", "i"); filterDictionary.insert("HSC-z", "z"); filterDictionary.insert("HSC-r2", "r"); filterDictionary.insert("HSC-i2", "i"); filterDictionary.insert("HSC-Y", "Y"); // OMEGACAM filterDictionary.insert("u_SDSS", "u"); filterDictionary.insert("g_SDSS", "g"); filterDictionary.insert("r_SDSS", "r"); filterDictionary.insert("i_SDSS", "i"); filterDictionary.insert("z_SDSS", "z"); // filterDictionary.insert(, ); } // Matching THELI instrument configuration with FITS file INSTRUME keyword, to detect wrong matchups. void Controller::populateInstrumentDictionary() { instrumentDictionary.insert("90Prime@BOK2.3m", "90prime"); instrumentDictionary.insert("ACAM@WHT", "ACAM"); instrumentDictionary.insert("ACS@HST", ""); instrumentDictionary.insert("ALFOSC@NOT", ""); instrumentDictionary.insert("ALTAU16M@VYSOS06", ""); instrumentDictionary.insert("AltaU42_HIGHRES@ASV", ""); instrumentDictionary.insert("AltaU42_LOWRES@ASV", ""); instrumentDictionary.insert("ApogeeAlta@PROMPT4", ""); instrumentDictionary.insert("ApogeeAlta@PROMPT5", ""); instrumentDictionary.insert("CFH12K@CFHT", ""); instrumentDictionary.insert("CFH12K@CFHT99", ""); instrumentDictionary.insert("DECam@CTIO", ""); instrumentDictionary.insert("DEIMOS_1AMP@KECK", "DEIMOS"); instrumentDictionary.insert("DEIMOS_2AMP@KECK", "DEIMOS"); instrumentDictionary.insert("Direct_4k_SWOPE@LCO", "Direct_4Kx4K-4"); // must replace a '/' in the INSTRUME keyword with '_ instrumentDictionary.insert("Direct_2k_DUPONT@LCO", "Direct_SITe2K-1"); // must replace a '/' in the INSTRUME keyword with '_' instrumentDictionary.insert("EFOSC2@ESO3.6m", "EFOSC"); instrumentDictionary.insert("EFOSC2@NTT", "EFOSC"); instrumentDictionary.insert("EFOSC2_2x2@ESO3.6m", "EFOSC"); instrumentDictionary.insert("EFOSC2_2x2@NTT", "EFOSC"); instrumentDictionary.insert("EMIR@GTC", ""); instrumentDictionary.insert("EMMI_BIMG@NTT", ""); instrumentDictionary.insert("EMMI_RILD@NTT", ""); instrumentDictionary.insert("ENZIAN_CAS@HOLI_1M", ""); instrumentDictionary.insert("ESI@KECK", "ESI"); instrumentDictionary.insert("FL03_LCOGT@CTIO", ""); instrumentDictionary.insert("FL04_LCOGT@CTIO", ""); instrumentDictionary.insert("FLAMINGOS2@GEMINI", "F2"); instrumentDictionary.insert("FLI-PL16801@WISE", ""); instrumentDictionary.insert("FORS1_199904-200703@VLT", "FORS1"); instrumentDictionary.insert("FORS1_E2V_2x2@VLT", "FORS1"); instrumentDictionary.insert("FORS2_200004-200203@VLT", "FORS2"); instrumentDictionary.insert("FORS2_E2V_2x2@VLT", "FORS2"); instrumentDictionary.insert("FORS2_MIT_1x1@VLT", "FORS2"); instrumentDictionary.insert("FORS2_MIT_2x2@VLT", "FORS2"); instrumentDictionary.insert("FourStar@LCO", "FourStar"); instrumentDictionary.insert("FourStar_Chips1+4@LCO", "FourStar"); instrumentDictionary.insert("GMOS-N-EEV-3ports@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-EEV-6ports@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-HAM@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-N-HAM_1x1@GEMINI", "GMOS-N"); instrumentDictionary.insert("GMOS-S-EEV@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM_1x1@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S-HAM_4x4@GEMINI", "GMOS-S"); instrumentDictionary.insert("GMOS-S_EEV_GeMS@GEMINI", "GMOS-S"); instrumentDictionary.insert("GOODMAN_1x1@SOAR", ""); instrumentDictionary.insert("GOODMAN_2x2@SOAR", ""); instrumentDictionary.insert("GPC1@PS1", ""); instrumentDictionary.insert("GROND_NIR@MPGESO", "GROND"); instrumentDictionary.insert("GROND_OPT@MPGESO", "GROND"); instrumentDictionary.insert("GSAOI@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_1k@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP1@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP2@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP3@GEMINI", "GSAOI"); instrumentDictionary.insert("GSAOI_CHIP4@GEMINI", "GSAOI"); instrumentDictionary.insert("HAWKI@VLT", "HAWKI"); instrumentDictionary.insert("HDI@KPNO_0.9m", "hdi"); instrumentDictionary.insert("HSC@SUBARU", "Hyper Suprime-Cam"); instrumentDictionary.insert("IMACS_F2_NEW@LCO", "IMACS Short-Camera"); instrumentDictionary.insert("IMACS_F2_OLD@LCO", ""); instrumentDictionary.insert("IMACS_F4_NEW@LCO", "IMACS Long-Camera"); instrumentDictionary.insert("IMACS_F4_NEW_2x2@LCO", "IMACS Long-Camera"); instrumentDictionary.insert("IMACS_F4_OLD@LCO", ""); instrumentDictionary.insert("INGRID@WHT", ""); instrumentDictionary.insert("IRCS_HIGHRES@SUBARU", ""); instrumentDictionary.insert("IRCS_LOWRES@SUBARU", ""); instrumentDictionary.insert("ISAAC@VLT", ""); instrumentDictionary.insert("ISPI@CTIO", ""); instrumentDictionary.insert("KTMC@CTIO", ""); instrumentDictionary.insert("LAICA@CAHA", ""); instrumentDictionary.insert("LAICA_2x2@CAHA", ""); instrumentDictionary.insert("LBC_BLUE@LBT", ""); instrumentDictionary.insert("LBC_RED@LBT", ""); instrumentDictionary.insert("LDSS3_from201402@LCO", "LDSS3-C"); instrumentDictionary.insert("LDSS3_2004-201401@LCO", ""); instrumentDictionary.insert("LIRIS@WHT", "LIRIS"); instrumentDictionary.insert("LIRIS_POL@WHT", "LIRIS"); instrumentDictionary.insert("LORRI@NewHorizons", ""); instrumentDictionary.insert("LRIS_BLUE@KECK", "LRISBLUE"); instrumentDictionary.insert("LRIS_RED@KECK", "LRIS"); instrumentDictionary.insert("MEGACAM_2x2@LCO", "megacam"); instrumentDictionary.insert("MEGAPRIME@CFHT", ""); instrumentDictionary.insert("MEGAPRIME_ELIXIR@CFHT", ""); instrumentDictionary.insert("MEROPE@MERCATOR", ""); instrumentDictionary.insert("MMIRS@LCO", ""); instrumentDictionary.insert("MOIRCS_200406-200806@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOIRCS_200807-201505@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOIRCS_201512-today@SUBARU", "MOIRCS"); instrumentDictionary.insert("MOSAIC-III_4@KPNO_4m", "Mosaic3"); instrumentDictionary.insert("MOSAIC-III@KPNO_4m", "Mosaic3"); instrumentDictionary.insert("MOSAIC-II_15@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_16@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_16_old@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_8@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-II_8_2x2@CTIO", "Mosaic2"); instrumentDictionary.insert("MOSAIC-I_old@KPNO_0.9m", ""); instrumentDictionary.insert("MOSAIC-I_old@KPNO_4.0m", ""); instrumentDictionary.insert("MOSCA_2x2@NOT", "MOSAIC 4*2kx2k"); instrumentDictionary.insert("MOSFIRE@KECK", ""); instrumentDictionary.insert("NACO@VLT", "NAOS+CONICA"); instrumentDictionary.insert("NACOSDI@VLT", ""); instrumentDictionary.insert("NEWFIRM@CTIO", "NEWFIRM"); instrumentDictionary.insert("NEWFIRM@KPNO_4m", "NEWFIRM"); instrumentDictionary.insert("NICI@GEMINI", ""); instrumentDictionary.insert("NICS@TNG", ""); instrumentDictionary.insert("NIRC2@KECK", ""); instrumentDictionary.insert("NIRI@GEMINI", "NIRI"); instrumentDictionary.insert("NISP@EUCLID", "NISP"); instrumentDictionary.insert("NOTcam_highres@NOT", ""); instrumentDictionary.insert("NOTcam_lowres@NOT", ""); instrumentDictionary.insert("OASIS4x4@WHT", ""); instrumentDictionary.insert("OASIS@WHT", ""); instrumentDictionary.insert("OMEGACAM@VST", "OMEGACAM"); instrumentDictionary.insert("Omega2000@CAHA", "Omega2000"); instrumentDictionary.insert("OSIRIS@GTC", ""); instrumentDictionary.insert("OSIRIS_F3@SOAR", ""); instrumentDictionary.insert("OSIRIS_F7@SOAR", ""); instrumentDictionary.insert("Omega2000@CAHA", ""); instrumentDictionary.insert("PANIC@LCO", ""); instrumentDictionary.insert("PANIC_OLD_4det@CAHA2.2", ""); instrumentDictionary.insert("PAUCam@WHT", ""); instrumentDictionary.insert("PFC_new@WHT", ""); instrumentDictionary.insert("PFC_old@WHT", "Prime Imaging"); instrumentDictionary.insert("PF_QHY2x2", "QHY CCD QHY600M-929ba64"); instrumentDictionary.insert("PICCD@WISE", ""); instrumentDictionary.insert("PISCES@LBT", ""); instrumentDictionary.insert("PISCO@LCO", "PISCO"); instrumentDictionary.insert("RetroCam_SWOPE@LCO", "RetroCam"); instrumentDictionary.insert("RetroCam_DUPONT@LCO", "RetroCam"); instrumentDictionary.insert("SAMI_2x2@SOAR", "SAM"); instrumentDictionary.insert("SDSS", ""); instrumentDictionary.insert("SITe@TLS", ""); instrumentDictionary.insert("SOFI@NTT", ""); instrumentDictionary.insert("SOI@SOAR", "SOI"); instrumentDictionary.insert("SPARTAN@SOAR", ""); instrumentDictionary.insert("SUSI1@NTT", "SUSI"); instrumentDictionary.insert("SUSI2_2x2@NTT", ""); instrumentDictionary.insert("SUSI2old_2x2@NTT", ""); instrumentDictionary.insert("SWOPE@LCO", ""); instrumentDictionary.insert("SuprimeCam_200101-200104@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200105-200807@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200808-201705@SUBARU", "SuprimeCam"); instrumentDictionary.insert("SuprimeCam_200808-201705_SDFRED@SUBARU", "SuprimeCam"); instrumentDictionary.insert("TRECS@GEMINI", "TReCS"); instrumentDictionary.insert("TRIPOL_1x1@SAAO", ""); instrumentDictionary.insert("TRIPOL_2x2@SAAO", ""); instrumentDictionary.insert("Tek2K@CTIO", ""); instrumentDictionary.insert("VIMOS@VLT", "VIMOS"); instrumentDictionary.insert("VIRCAM@VISTA", ""); instrumentDictionary.insert("VIS@EUCLID", "VIS"); instrumentDictionary.insert("VISIR@VLT", ""); instrumentDictionary.insert("WFC@INT", "WFC"); instrumentDictionary.insert("WFC_2x2@INT", "WFC"); instrumentDictionary.insert("WFC_IPHAS@INT", "WFC"); instrumentDictionary.insert("WFCCD_WF4K_DUPONT", "WFCCD_WF4K-1"); instrumentDictionary.insert("WFI@AAT", ""); instrumentDictionary.insert("WFI@MPGESO", "WFI"); instrumentDictionary.insert("WFI@SSO_40inch", ""); instrumentDictionary.insert("WFI_2x2_2006@MPGESO", ""); instrumentDictionary.insert("WFI_2x2_2017@MPGESO", ""); instrumentDictionary.insert("WHIRC@WIYN", "WHIRC"); instrumentDictionary.insert("WIRC@Hale", ""); instrumentDictionary.insert("WIRCam@CFHT", ""); instrumentDictionary.insert("Y4KCam@CTIO", ""); // instrumentDictionary.insert(); }
23,730
C++
.cc
429
49.913753
147
0.692258
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,475
processingCoadd.cc
schirmermischa_THELI/src/processingInternal/processingCoadd.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/swarpfilter.h" #include "../tools/fitting.h" #include "../tools/fileprogresscounter.h" #include "ui_confdockwidget.h" #include "../threading/scampworker.h" #include "../readmes/swarpreadme.h" #include "../tools/imagequality.h" #include "unistd.h" // To query max number of open files #include <QMetaObject> #include <QVector> #include <QStringList> #include <QStandardPaths> #include <QTextStream> #include <QTest> #include <QTimer> #include <QProgressBar> void Controller::taskInternalCoaddition() { coaddScienceDir = instructions.split(" ").at(1); QString filterArg = instructions.split(" ").at(2); coaddScienceData = getData(DT_SCIENCE, coaddScienceDir); if (coaddScienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(coaddScienceData)) return; currentData = coaddScienceData; currentDirName = coaddScienceDir; // Initialise, so we always have the correct values even when the coaddition is repeated several times coaddTexptime = 0.; coaddSkyvalue = 0.; coaddFilter = ""; coaddGain = 0.; mjdStart = 0.; mjdEnd = 0.; mjdMedian = 0.; // If coming here right after launch: // #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : coaddScienceData->myImageList[chip]) { it->loadHeader(); } } coaddScienceData->checkModeIsPresent(); memoryDecideDeletableStatus(coaddScienceData, false); QString coaddSubDir = "coadd_"+filterArg; QString coaddUniqueID = cdw->ui->COAuniqueidLineEdit->text(); if (!coaddUniqueID.isEmpty()) coaddSubDir.append("_"+coaddUniqueID); coaddDirName = mainDirName + "/" + coaddScienceDir + "/" + coaddSubDir; QString headerDirName = mainDirName + "/" + coaddScienceDir + "/headers/"; if (!coaddScienceData->hasMatchingPartnerFiles(headerDirName, ".head")) return; // if all chips are stacked, make sure the reference point is within the covered area. // If selected chips are present, then the user might want the same ref coords for all chip stacks, which might be outside if (cdw->ui->COAchipsLineEdit->text().isEmpty()) { if (!coaddScienceData->doesCoaddContainRaDec(cdw->ui->COAraLineEdit->text(), cdw->ui->COAdecLineEdit->text())) { emit showMessageBox("Controller::POOR_COORD", cdw->ui->COAraLineEdit->text(), cdw->ui->COAdecLineEdit->text()); return; } } // qDebug() << "taskInternalCoaddition() : " << filterArg; // TODO // The following is very fast and does not need a parallel loop on top. getMinimumSaturationValue(); // The various coadd tasks are daisy-chained through signals and slots coaddSmoothEdge(); QTest::qWait(1000); coaddPrepare(filterArg); // entry point to daisy chain } void Controller::coaddSmoothEdge() { if (!successProcessing) return; QString edgeString = cdw->ui->COAedgesmoothingLineEdit->text(); if (edgeString.isEmpty()) return; float edge = edgeString.toFloat(); bool roundEdge = true; pushBeginMessage("CoaddSmoothWeights", coaddScienceData->subDirName); getNumberOfActiveImages(coaddScienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : coaddScienceData->myImageList[chip]) { emit messageAvailable(it->baseName + " : Smoothing weight edge ...", "controller"); it->readWeight(); it->roundEdgeOfWeight(edge, roundEdge); it->writeWeightSmoothed(mainDirName+ "/WEIGHTS/" + it->chipName + ".weightsmooth.fits"); it->weightName = it->chipName + ".weight"; QVector<float>().swap(it->dataWeightSmooth); // immediately release the memory incrementProgress(); } } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, coaddScienceData); progressStepSize = 100. / float(numMyImages); float nimg = 2; // wild guess releaseMemory(nimg*instData->storage*maxCPU, 1); coaddScienceData->protectMemory(); #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; releaseMemory(nimg*instData->storage, maxCPU); auto &it = allMyImages[k]; if (!it->successProcessing) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; emit messageAvailable(it->baseName + " : Smoothing weight edge ...", "controller"); it->readWeight(); it->roundEdgeOfWeight(edge, roundEdge); it->writeWeightSmoothed(mainDirName+ "/WEIGHTS/" + it->chipName + ".weightsmooth.fits"); it->weightName = it->chipName + ".weight"; // immediately release the memory it->dataWeightSmooth.clear(); it->dataWeightSmooth.squeeze(); it->unprotectMemory(); if (it->successProcessing) coaddScienceData->successProcessing = false; #pragma omp atomic progress += progressStepSize; } checkSuccessProcessing(coaddScienceData); satisfyMaxMemorySetting(); if (successProcessing) { coaddScienceData->status = statusNew; emit progressUpdate(100); // pushEndMessage("CoaddSmoothWeights", coaddScienceData->subDirName); } } void Controller::coaddPrepare(QString filterArg) { if (!successProcessing) return; pushBeginMessage("CoaddPrepare", coaddScienceDir); pushConfigCoadd(); emit resetProgressBar(); // Release at least as much RAM as nCPU*nchip*2 releaseMemory(maxCPU*instData->numChips*2*instData->storage, 1); QString ident = cdw->ui->COAuniqueidLineEdit->text(); QString chips = cdw->ui->COAchipsLineEdit->text(); QVector<int> chipList; QStringList chipStringList = chips.replace(","," ").simplified().split(" "); if (!chips.isEmpty()) { for (auto &chip : chipStringList) chipList.append(chip.toInt()-1); } else { // include all chips for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; chipList.append(chip); } } QString edgeSmooth = cdw->ui->COAedgesmoothingLineEdit->text(); // Check if coaddDir exists. Delete everything in it if yes. Then recreate it. QDir coaddDir(coaddDirName); if (coaddDir.exists()) coaddDir.removeRecursively(); coaddDir.mkpath(coaddDirName); // Calculate median RA / DEC if not given manually QString refRA = cdw->ui->COAraLineEdit->text(); QString refDE = cdw->ui->COAdecLineEdit->text(); if (!refRA.isEmpty() && refRA.contains(":")) refRA = hmsToDecimal(refRA); if (!refDE.isEmpty() && refDE.contains(":")) refDE = dmsToDecimal(refDE); if (refRA.isEmpty() || refDE.isEmpty()) { QVector<double> alpha; QVector<double> delta; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : coaddScienceData->myImageList[chip]) { if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; alpha.append(it->alpha_ctr); delta.append(it->delta_ctr); } } double alphaMedian = straightMedian_T(alpha, 0, false); // do not average center two elements because of the RA 0|360 deg boundary double deltaMedian = straightMedian_T(delta); refRA = QString::number(alphaMedian, 'f', 9); refDE = QString::number(deltaMedian, 'f', 9); } // Progress bar is updated every some fraction of a second. We just need to set the variable. progress = 30.; // emit progressUpdate(progress); // We also want accurate start and end DATE-OBS keywords. // Initialise user-defined MJD-OBS thresholds bool mjd_minconstraint = false; bool mjd_maxconstraint = false; if (!cdw->ui->COAminMJDOBSLineEdit->text().isEmpty()) mjd_minconstraint = true; if (!cdw->ui->COAmaxMJDOBSLineEdit->text().isEmpty()) mjd_maxconstraint = true; double minMJD = 0.; // Always safe double maxMJD = 1.e6; // Large enough for a few generations of astronomers to come mjdStart = 1.e6; // Actual MJD start in the data to be coadded mjdEnd = 0.; // Actual MJD end in the data to be coadded if (mjd_minconstraint) minMJD = cdw->ui->COAminMJDOBSLineEdit->text().toDouble(); if (mjd_maxconstraint) maxMJD = cdw->ui->COAmaxMJDOBSLineEdit->text().toDouble(); // We first need to collect the MJD-OBS values of all exposures that will be coadded. // This loop is similar to the one below, but below we need the MJD-OBS info already. QVector<double> mjdobsData; float lastExpTime = 0.; // to be added to DATE-OBS of the last exposure for (int chip=0; chip<instData->numChips; ++chip) { if (!chipList.contains(chip) || instData->badChips.contains(chip)) continue; // Skip chips that should not be coadded for (auto &it : coaddScienceData->myImageList[chip]) { if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; it->loadHeader(); if (it->mjdobs < minMJD || it->mjdobs > maxMJD) continue; if (filterArg == "all" || (filterArg != "all" && it->filter == filterArg)) { // Update begin and end values for MJD-OBS and DATE-OBS if (it->mjdobs < mjdStart) { mjdStart = it->mjdobs; minDateObs = it->dateobs; } if (it->mjdobs > mjdEnd) { mjdEnd = it->mjdobs; maxDateObs = it->dateobs; lastExpTime = it->exptime; } if (it->mjdobs >= minMJD && it->mjdobs <= maxMJD) mjdobsData.append(it->mjdobs); } } } mjdEnd += lastExpTime / 86400.; mjdMedian = straightMedian_T(mjdobsData, 0, false); double mjdobsZero = minVec_T(mjdobsData); // will be 0. if vector is empty // For proper motion correction we need to make sure that there are MJD-OBS data present // The list will be updated further below, depending on MJD-OBS filtering. bool doPMupdate = false; if (!cdw->ui->COApmraLineEdit->text().isEmpty() && !cdw->ui->COApmdecLineEdit->text().isEmpty()) doPMupdate = true; if (mjdobsZero == 0. && doPMupdate) { emit showMessageBox("Controller::NO_MJDOBS_FOR_PM", "", ""); successProcessing = false; return; } // Now copy the headers (might be modified), link the images and weights, if they match the filterArg and MJD-OBS criteria coaddNumImages = 0; QList<QString> filterNames; for (int chip=0; chip<instData->numChips; ++chip) { if (!chipList.contains(chip) || instData->badChips.contains(chip)) continue; // Skip chips that should not be coadded for (auto &it : coaddScienceData->myImageList[chip]) { if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; it->loadHeader(); if (it->mjdobs < minMJD || it->mjdobs > maxMJD) continue; QFile image(it->path + "/" + it->baseName + ".fits"); QFile weight(it->weightPath + "/" + it->weightName + ".fits"); if (!edgeSmooth.isEmpty()) weight.setFileName(it->weightPath + "/" + it->weightName + "smooth.fits"); QString headerNewName = coaddDirName+"/" + it->baseName + ".head"; QFile header(it->path + "/headers/" + it->chipName + ".head"); if (filterArg == "all" || (filterArg != "all" && it->filter == filterArg)) { image.link(coaddDirName+"/" + it->baseName + ".fits"); weight.link(coaddDirName+"/" + it->baseName + ".weight.fits"); if (!doPMupdate) header.copy(headerNewName); else coaddPrepareProjectPM(header, headerNewName, refDE, mjdobsZero, it->mjdobs); if (!filterNames.contains(it->filter)) filterNames.append(it->filter); coaddTexptime += it->exptime; coaddSkyvalue += it->skyValue / it->exptime; ++coaddNumImages; } } } coaddTexptime /= instData->numUsedChips; coaddSkyvalue /= coaddNumImages; for (auto &filter : filterNames) { coaddFilter.append(filter); coaddFilter.append("+"); } coaddFilter.truncate(coaddFilter.length()-1); coaddGain = coaddTexptime; // Check if Swarp will open more file handles than the system currently allows long maxOpenFiles = sysconf(_SC_OPEN_MAX); if (2*coaddNumImages > maxOpenFiles) { successProcessing = false; SwarpReadme *swarpReadme = new SwarpReadme(2*coaddNumImages, maxOpenFiles, this); swarpReadme->show(); return; } // Run swarp to create coadd.head // tmpCoaddDir = coaddDirName; // tmpCoaddData = scienceData; progress = 50.; // emit progressUpdate(progress); coaddPrepareBuildSwarpCommand(refRA, refDE); // Run the Swarp command currentSwarpProcess = "swarpPreparation"; workerThreadPrepare = new QThread(); swarpWorker = new SwarpWorker(swarpCommand, coaddDirName, currentSwarpProcess); workerInit = true; workerThreadInit = true; swarpWorker->moveToThread(workerThreadPrepare); connect(workerThreadPrepare, &QThread::started, swarpWorker, &SwarpWorker::runSwarp, Qt::DirectConnection); // connect(workerThreadPrepare, &QThread::finished, workerThreadPrepare, &QThread::deleteLater, Qt::DirectConnection); connect(workerThreadPrepare, &QThread::finished, workerThreadPrepare, &QThread::deleteLater); connect(swarpWorker, &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); connect(swarpWorker, &SwarpWorker::finishedPreparation, this, &Controller::finishedPreparationReceived); // MUST NOT connect to quit, otherwise control returns immediately to the controller, which might start another coaddition // right away in case of multi-color data // connect(swarpWorker, &SwarpWorker::finished, workerThreadPrepare, &QThread::quit, Qt::DirectConnection); // connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater, Qt::DirectConnection); // connect(swarpWorker, &SwarpWorker::finished, workerThreadPrepare, &QThread::quit); connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); //qDebug() << "coaddPrepare(): before threadstart" << coaddDirName; workerThreadPrepare->start(); workerThreadPrepare->wait(); // finishedXXX signal triggers next step } void Controller::swarpErrorFoundReceived() { successProcessing = false; } // UNUSED void Controller::finishedPreparationReceived() { progress = 70.; // emit progressUpdate(progress); foldCoaddFits(); if (!successProcessing) return; // If requested, rotate coadd.head to user-specified position angle coaddPrepareProjectRotation(); progress = 100.; // emit progressUpdate(progress); // Trigger resampling emit swarpStartResampling(); } void Controller::coaddPrepareProjectPM(QFile &headerFileOld, QString newHeaderName, QString refDE, double mjdobsZero, double mjdobsNow) { if (!successProcessing) return; double pmRA = cdw->ui->COApmraLineEdit->text().toDouble(); double pmDE = cdw->ui->COApmdecLineEdit->text().toDouble(); int unitIndex = cdw->ui->COApmComboBox->currentIndex(); double timeConversion = 1.; if (unitIndex == 0) timeConversion = 1./60.; // arcsec / sec else if (unitIndex == 1) timeConversion = 1.; // arcsec / min else if (unitIndex == 2) timeConversion = 60.; // arcsec / hr else if (unitIndex == 3) timeConversion = 1440.; // arcsec / day // Calculate speed in CRVAL1/2 per minute double crval2 = refDE.toDouble(); double crval1Speed = pmRA / 3600. / timeConversion / cos(crval2*rad); double crval2Speed = pmDE / 3600. / timeConversion; // How many minutes passed since the first image was taken double timeDiff = (mjdobsNow - mjdobsZero) * 1440.; // New CRVAL1/2 for the current exposure // double crval1New = crval1 + timeDiff * crval1Speed; // double crval2New = crval2 + timeDiff * crval2Speed; // Update CRVAL1/2 (and write to a new header file) QTextStream streamIn(&headerFileOld); if( !headerFileOld.open(QIODevice::ReadOnly)) { QString part1 = headerFileOld.fileName(); QString part2 = headerFileOld.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PM_READ", part1, part2); successProcessing = false; return; } QFile headerFileNew(newHeaderName); QTextStream streamOut(&headerFileNew); if( !headerFileNew.open(QIODevice::WriteOnly)) { QString part1 = headerFileNew.fileName(); QString part2 = headerFileNew.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PM_WRITE", part1, part2); successProcessing = false; return; } // CHECK CHECK CHECK: // MPC: what is the difference between coordinate motion and sky motion? // It seems I got it right, but for a target at DEC=3. Higher declinations? don't need to divide crval1speed by cosine dec(?) while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (!line.contains("CRVAL")) streamOut << line << "\n"; else { QString value = line.split("=").at(1); int slashPosition = value.lastIndexOf('/'); // (can be -1 if not found, treated as 0 by truncate(), i.e. entire string is set to empty if (slashPosition > 10) value.truncate(slashPosition); double crval1New = value.simplified().toDouble() - timeDiff * crval1Speed; double crval2New = value.simplified().toDouble() - timeDiff * crval2Speed; QString crval1String = "CRVAL1 = " + QString::number(crval1New, 'f', 12); QString crval2String = "CRVAL2 = " + QString::number(crval2New, 'f', 12); crval1String.resize(79, ' '); // Must be 80 chars long to conform with FITS standard. crval2String.resize(79, ' '); // We use 79 here because the read in stream also contains a carriage return! if (line.contains("CRVAL1")) streamOut << crval1String << "\n"; if (line.contains("CRVAL2")) streamOut << crval2String << "\n"; } } headerFileOld.close(); headerFileNew.close(); headerFileNew.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::coaddPrepareProjectRotation() { if (!successProcessing) return; if (cdw->ui->COAskypaLineEdit->text().isEmpty()) return; // Rename coadd.head QFile coaddHeadOld(coaddDirName+"/coadd.head"); coaddHeadOld.rename(coaddDirName+"/coadd.head_orig"); // Read the CD matrix in coadd.head if(!coaddHeadOld.open(QIODevice::ReadOnly)) { QString part1 = coaddHeadOld.fileName(); QString part2 = coaddHeadOld.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return; } double cd11_coadd = 0.; double cd12_coadd = 0.; double cd21_coadd = 0.; double cd22_coadd = 0.; long naxis1_coadd = 0; long naxis2_coadd = 0; QTextStream streamIn(&coaddHeadOld); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1 =")) naxis1_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("NAXIS2 =")) naxis2_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("CD1_1 =")) cd11_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD1_2 =")) cd12_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD2_1 =")) cd21_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("CD2_2 =")) cd22_coadd = line.split("=")[1].split("/")[0].simplified().toDouble(); } // PA of the original data (taken from first image and its valid chip) double cd11 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[0]; double cd12 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[1]; double cd21 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[2]; double cd22 = coaddScienceData->myImageList[instData->validChip][0]->wcs->cd[3]; double PAold = getPosAnglefromCD(cd11, cd12, cd21, cd22); // in [deg]; not sure about the minus here double PAnew = cdw->ui->COAskypaLineEdit->text().toDouble(); // in [deg]; if image is flipped, the angle to get "parallel" axes should be 180 - the automatically determined angle. rotateCDmatrix(cd11_coadd, cd12_coadd, cd21_coadd, cd22_coadd, PAnew); long naxis1New = 0; long naxis2New = 0; get_rotimsize(naxis1_coadd, naxis2_coadd, PAold, PAnew, naxis1New, naxis2New); // Updated header lines: QString str_naxis1 = "NAXIS1 = "+QString::number(naxis1New); QString str_naxis2 = "NAXIS2 = "+QString::number(naxis1New); QString str_crpix1 = "CRPIX1 = "+QString::number(naxis1New/2); QString str_crpix2 = "CRPIX2 = "+QString::number(naxis1New/2); QString str_cd11 = "CD1_1 = "+QString::number(cd11_coadd, 'f', 12); QString str_cd12 = "CD1_2 = "+QString::number(cd12_coadd, 'f', 12); QString str_cd21 = "CD2_1 = "+QString::number(cd21_coadd, 'f', 12); QString str_cd22 = "CD2_2 = "+QString::number(cd22_coadd, 'f', 12); str_naxis1.resize(80, ' '); str_naxis2.resize(80, ' '); str_crpix1.resize(80, ' '); str_crpix2.resize(80, ' '); str_cd11.resize(80, ' '); str_cd12.resize(80, ' '); str_cd21.resize(80, ' '); str_cd22.resize(80, ' '); // Open new coadd.head QFile coaddHeadNew(coaddDirName+"/coadd.head"); if(!coaddHeadNew.open(QIODevice::WriteOnly)) { QString part1 = coaddHeadNew.fileName(); QString part2 = coaddHeadNew.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return; } // Reset the old stream, and scan the file once more streamIn.seek(0); QTextStream streamOut(&coaddHeadNew); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1")) streamOut << str_naxis1 << "\n"; else if (line.contains("NAXIS2")) streamOut << str_naxis2 << "\n"; else if (line.contains("CRPIX1")) streamOut << str_crpix1 << "\n"; else if (line.contains("CRPIX2")) streamOut << str_crpix2 << "\n"; else if (line.contains("CD1_1")) streamOut << str_cd11 << "\n"; else if (line.contains("CD1_2")) streamOut << str_cd12 << "\n"; else if (line.contains("CD2_1")) streamOut << str_cd21 << "\n"; else if (line.contains("CD2_2")) streamOut << str_cd22 << "\n"; else streamOut << line << "\n"; } coaddHeadOld.close(); coaddHeadNew.close(); coaddHeadOld.remove(); coaddHeadNew.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::coaddPrepareBuildSwarpCommand(QString refRA, QString refDE) { if (!successProcessing) return; QString coaddSize = ""; QString naxis1 = cdw->ui->COAsizexLineEdit->text(); QString naxis2 = cdw->ui->COAsizeyLineEdit->text(); if (!naxis1.isEmpty() && !naxis2.isEmpty()) coaddSize = " -IMAGE_SIZE "+naxis1+","+naxis2; QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp + " *"+statusOld+".fits"; swarpCommand += " -NTHREADS " + QString::number(maxCPU); swarpCommand += " -CENTER "+refRA+","+refDE; swarpCommand += " -CENTER_TYPE MANUAL"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -HEADER_ONLY Y"; // only in v2.40.1, not in earlier versions. Current latest official release: 2.38 // swarpCommand += " -HEADEROUT_NAME coadd.head"; swarpCommand += " -PIXELSCALE_TYPE MANUAL"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -PIXEL_SCALE "+pixelScale; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += coaddSize; appendToFile(coaddDirName+"/swarpcommands.txt", swarpCommand); if (verbosity > 1) emit messageAvailable("Executing the following swarp command :<br><br>"+swarpCommand+"<br><br>in directory: <br><br>"+coaddDirName+"<br>", "info"); if (verbosity > 1) emit messageAvailable("<br>Swarp output<br>", "ignore"); } void Controller::coaddResampleBuildSwarpCommand(QString imageList, int i) { if (!successProcessing) return; QString swarpCommand; // shadowing the class member 'swarpCommand' for a moment QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); QString rescaleWeights = "N"; if (cdw->ui->COArescaleweightsCheckBox->isChecked()) rescaleWeights = "Y"; // Reset the FLXSCALE keyword if necessary (to the inverse exposure time) if (!cdw->ui->COArzpCheckBox->isChecked()) { if (verbosity > 1) emit messageAvailable("Ignoring scamp flux scaling, resetting the FLXSCALE keyword to 1./EXPTIME)", "warning"); QDir coaddDir(coaddDirName); QStringList filter; filter << "*.head"; QStringList headerList = coaddDir.entryList(filter); for (auto &it : headerList) { if (it == "coadd.head") continue; QString fitsfile = it; fitsfile.replace(".head", ".fits"); double exptime = extractFitsKeywordValue(coaddDirName+"/"+fitsfile, "EXPTIME"); replaceLineInFile(coaddDirName+"/"+it, "FLXSCALE", "FLXSCALE= "+QString::number(1./exptime)); } } statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp +" @"+imageList; swarpCommand += " -NTHREADS 1"; // Launching maxCPU externally // swarpCommand += " -NTHREADS " + QString::number(maxExternalThreads); swarpCommand += " -RESAMPLE Y"; swarpCommand += " -RESAMPLE_SUFFIX ."+coaddUniqueID+"resamp.fits"; swarpCommand += " -COMBINE N"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -WEIGHT_TYPE MAP_WEIGHT"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -SUBTRACT_BACK N"; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += " -COMBINE_TYPE " + cdw->ui->COAcombinetypeComboBox->currentText(); swarpCommand += " -RESCALE_WEIGHTS " + rescaleWeights; swarpCommand += " -NOPENFILES_MAX " + QString::number(coaddNumImages); swarpCommand += " -COPY_KEYWORDS OBJECT,SKYVALUE,EXPTIME,DATE-OBS"; swarpCommands[i] = swarpCommand; #pragma omp critical { appendToFile(coaddDirName+"/swarpcommands.txt", swarpCommands[i]); } if (verbosity > 1) emit messageAvailable("Executing the following swarp command :<br><br>"+swarpCommands[i]+"<br><br>in directory: <br><br>"+coaddDirName+"<br>", "info"); if (verbosity > 1) emit messageAvailable("<br>Swarp output<br>", "ignore"); } void Controller::coaddCoadditionBuildSwarpCommand(QString imageList) { if (!successProcessing) return; QString pixelScale = cdw->ui->COApixscaleLineEdit->text(); if (pixelScale.isEmpty()) pixelScale = QString::number(instData->pixscale, 'f', 9); QString rescaleWeights = "N"; if (cdw->ui->COArescaleweightsCheckBox->isChecked()) rescaleWeights = "Y"; statusOld = coaddScienceData->processingStatus->statusString; QString swarp = findExecutableName("swarp"); swarpCommand = swarp +" @"+imageList; swarpCommand += " -NTHREADS " + QString::number(maxCPU); swarpCommand += " -RESAMPLE N"; swarpCommand += " -COMBINE Y"; swarpCommand += " -VERBOSE_TYPE FULL"; swarpCommand += " -WEIGHT_TYPE MAP_WEIGHT"; swarpCommand += " -BLANK_BADPIXELS Y"; swarpCommand += " -SUBTRACT_BACK N"; swarpCommand += " -GAIN_KEYWORD GAIN"; swarpCommand += " -PROJECTION_TYPE " + cdw->ui->COAprojectionComboBox->currentText(); swarpCommand += " -CELESTIAL_TYPE " + cdw->ui->COAcelestialtypeComboBox->currentText(); swarpCommand += " -RESAMPLING_TYPE " + cdw->ui->COAkernelComboBox->currentText(); swarpCommand += " -COMBINE_TYPE " + cdw->ui->COAcombinetypeComboBox->currentText(); swarpCommand += " -RESCALE_WEIGHTS " + rescaleWeights; swarpCommand += " -NOPENFILES_MAX " + QString::number(coaddNumImages); swarpCommand += " -COPY_KEYWORDS OBJECT"; appendToFile(coaddDirName+"/swarpcommands.txt", swarpCommand); if (verbosity > 0) emit messageAvailable("Executing the following swarp command :<br><br>"+swarpCommand+"<br><br>in directory: <br><br>"+coaddDirName+"<br>", "info"); if (verbosity > 1) emit messageAvailable("<br>Swarp output<br>", "ignore"); } void Controller::coaddResample() { if (!successProcessing) { // if (workerThreadPrepare) workerThreadPrepare->quit(); // crashing sometimes, not sure why; crashes when process is user-aborted return; } progress = 0.; emit resetProgressBar(); pushBeginMessage("CoaddResample", coaddScienceDir); statusOld = coaddScienceData->processingStatus->statusString; // List of all images QDir coaddDir(coaddDirName); QStringList filter("*"+statusOld+".fits"); QStringList imageList = coaddDir.entryList(filter); // Lists containing output files and streams QString listName; QFile file; QTextStream stream; QStringList listNames; int i = 0; int fileCount = 0; int highGroup = imageList.length() % maxCPU - 1; for (auto &imageName : imageList) { if (i==0) { listName = coaddDirName+"/listCoadd_"+QString::number(fileCount); listNames << listName; file.setFileName(listName); stream.setDevice(&file); if (!file.open(QIODevice::WriteOnly)) { QString part1 = listName; QString part2 = file.errorString(); emit showMessageBox("Controller::CANNOT_WRITE_RESAMPLE_LIST", part1, part2); successProcessing = false; return; } } stream << imageName << "\n"; ++i; /* if (i == imageList.length() / maxCPU) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } */ // Spread images as evenly as possible across the threads if (fileCount <= highGroup && i == imageList.length() / maxCPU + 1) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } if (fileCount > highGroup && i == imageList.length() / maxCPU) { i = 0; ++fileCount; file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } } if (file.isOpen()) { file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } numberFileCounter = new FileProgressCounter(coaddDirName, "*resamp.fits", imageList.length(), &progress, this); connect(numberFileCounter->timer, &QTimer::timeout, numberFileCounter, &FileProgressCounter::numberFileProgress); // connect(numberFileCounter, &FileProgressCounter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived, Qt::DirectConnection); numberFileCounter->timer->start(2000); // We can use at most as many threads as we have files in listname: localMaxCPU = maxCPU > listNames.length() ? listNames.length() : maxCPU; currentSwarpProcess = "swarpResampling"; #pragma omp parallel for num_threads(localMaxCPU) firstprivate(coaddDirName) for (int i=0; i<localMaxCPU; ++i) { coaddResampleBuildSwarpCommand(listNames[i], i); // Run the Swarp command #pragma omp critical { workerThreads[i] = new QThread(); swarpWorkers[i] = new SwarpWorker(swarpCommands[i], coaddDirName, currentSwarpProcess); workersInit = true; workerThreadsInit = true; swarpWorkers[i]->threadID = i; swarpWorkers[i]->moveToThread(workerThreads[i]); } connect(workerThreads[i], &QThread::started, swarpWorkers[i], &SwarpWorker::runSwarp); connect(workerThreads[i], &QThread::finished, workerThreads[i], &QThread::deleteLater); connect(swarpWorkers[i], &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); // connect(workerThreads[i], &QThread::finished, workerThreads[i], &QThread::deleteLater); connect(swarpWorkers[i], &SwarpWorker::finishedResampling, this, &Controller::waitForResamplingThreads); // connect(swarpWorkers[i], &SwarpWorker::finished, workerThreads[i], &QThread::quit); connect(swarpWorkers[i], &SwarpWorker::finished, swarpWorkers[i], &QObject::deleteLater); connect(swarpWorkers[i], &SwarpWorker::finished, workerThreads[i], &QThread::quit); // connect(swarpWorkers[i], &SwarpWorker::finished, swarpWorkers[i], &QObject::deleteLater); connect(swarpWorkers[i], &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); workerThreads[i]->start(); // workerThreads[i]->wait(); } // emit progressUpdate(100); } void Controller::waitForResamplingThreads(int threadID) { omp_set_lock(&genericLock); threadsFinished[threadID] = true; // Trigger Swarpfilter if all resampling threads have finished bool allTrue = true; for (int i=0; i<localMaxCPU; ++i) { if (threadsFinished[i] == false) allTrue = false; } if (allTrue) { progress = 100.; // emit progressUpdate(100); emit swarpStartSwarpfilter(); numberFileCounter->timer->stop(); // We don't have to delete the swarpWorkers because they are "movedTo" the threads // for (auto &it : workerThreads) { // delete it; // } } omp_unset_lock(&genericLock); } void Controller::coaddSwarpfilter() { if (!successProcessing) { emit swarpStartCoaddition(); // Must continue through the chain 'naturally' until its end return; } QString kappa = cdw->ui->COAoutthreshLineEdit->text(); QString clustersize = cdw->ui->COAoutsizeLineEdit->text(); QString borderwidth = cdw->ui->COAoutborderLineEdit->text(); if (kappa.isEmpty()) { // Trigger coaddition emit swarpStartCoaddition(); return; } progress = 0.; emit resetProgressBar(); pushBeginMessage("CoaddSwarpFilter", coaddScienceDir); SwarpFilter swarpFilter(coaddDirName, kappa, clustersize, borderwidth, cdw->ui->COArzpCheckBox->isChecked(), maxCPU, &verbosity); swarpFilter.progress = &progress; connect(&swarpFilter, &SwarpFilter::messageAvailable, monitor, &Monitor::displayMessage); connect(&swarpFilter, &SwarpFilter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived); connect(&swarpFilter, &SwarpFilter::critical, this, &Controller::criticalReceived); swarpFilter.runCosmicFilter(); // TODO: introduce successProcessing to swarpfilter(); // TODO: swarpfilter blocks the update of the CPU and memory progress bar (normal progress bar increases as intended). Check timers? checkSuccessProcessing(coaddScienceData); if (successProcessing) { emit progressUpdate(100); } // Trigger coaddition emit swarpStartCoaddition(); } void Controller::coaddCoaddition() { if (!successProcessing) { // if (workerThreadPrepare) workerThreadPrepare->quit(); // crashing sometimes, not sure why; crashes when process is user-aborted return; } emit resetProgressBar(); statusOld = coaddScienceData->processingStatus->statusString; pushBeginMessage("CoaddCoadd", coaddScienceDir); // List of all images QDir coaddDir(coaddDirName); QStringList filter("*"+statusOld+"*resamp.fits"); QStringList imageList = coaddDir.entryList(filter); QString listName = coaddDirName+"/listCoadd"; QFile file(listName); QTextStream stream(&file); if (!file.open(QIODevice::WriteOnly)) { QString part1 = listName; QString part2 = file.errorString(); emit showMessageBox("Controller::CANNOT_WRITE_RESAMPLE_LIST", part1, part2); successProcessing = false; return; } for (auto &imageName : imageList) { stream << imageName << "\n"; } file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); sizeFileCounter = new FileProgressCounter(coaddDirName, coaddCoadditionGetSize(), &progress, this); connect(sizeFileCounter->timer, &QTimer::timeout, sizeFileCounter, &FileProgressCounter::sizeFileProgress); connect(sizeFileCounter, &FileProgressCounter::progressUpdate, mainGUI, &MainWindow::progressUpdateReceived); connect(this, &Controller::stopFileProgressTimer, sizeFileCounter, &FileProgressCounter::stopFileProgressTimerReceived); sizeFileCounter->timer->start(1000); coaddCoadditionBuildSwarpCommand(listName); // delete a previous Thread from the preparation. // workerThreadPrepare->quit(); // delete workerThreadPrepare; // Run the Swarp command currentSwarpProcess = "swarpCoaddition"; workerThreadCoadd = new QThread(); swarpWorker = new SwarpWorker(swarpCommand, coaddDirName, currentSwarpProcess); workerInit = true; workerThreadInit = true; swarpWorker->moveToThread(workerThreadCoadd); connect(workerThreadCoadd, &QThread::started, swarpWorker, &SwarpWorker::runSwarp); connect(workerThreadCoadd, &QThread::finished, workerThreadCoadd, &QThread::deleteLater); // connect(workerThreadCoadd, &QThread::finished, workerThreadCoadd, &QThread::deleteLater); connect(swarpWorker, &SwarpWorker::finishedCoaddition, this, &Controller::coaddUpdate, Qt::DirectConnection); connect(swarpWorker, &SwarpWorker::finished, workerThreadCoadd, &QThread::quit); connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::errorFound, this, &Controller::swarpErrorFoundReceived); //connect(swarpWorker, &SwarpWorker::finished, workerThreadCoadd, &QThread::quit); //connect(swarpWorker, &SwarpWorker::finished, swarpWorker, &QObject::deleteLater); connect(swarpWorker, &SwarpWorker::messageAvailable, monitor, &Monitor::displayMessage); workerThreadCoadd->start(); // workerThreadCoadd->wait(); // TODO: does not continue with next filter if scheduled as "separately"! QTconnection issue? } long Controller::coaddCoadditionGetSize() { // Read NAXIS1/2 in coadd.head QFile coaddHead(coaddDirName+"/coadd.head"); if(!coaddHead.open(QIODevice::ReadOnly)) { QString part1 = coaddHead.fileName(); QString part2 = coaddHead.errorString(); emit showMessageBox("Controller::CANNOT_UPDATE_HEADER_WITH_PA", part1, part2); successProcessing = false; return 0; } long naxis1_coadd = 0; long naxis2_coadd = 0; QTextStream streamIn(&coaddHead); while(!streamIn.atEnd()) { QString line = streamIn.readLine(); if (line.contains("NAXIS1 =")) naxis1_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); if (line.contains("NAXIS2 =")) naxis2_coadd = line.split("=")[1].split("/")[0].simplified().toLong(); } return 4 * naxis1_coadd * naxis2_coadd; } void Controller::coaddUpdate() { if (!successProcessing) { // emit forceFinish(); // if (workerThreadPrepare) workerThreadPrepare->quit(); // crashing sometimes, not sure why return; } // Stop "measuring" the file size of coadd.fits emit stopFileProgressTimer(); progress = 0.; emit resetProgressBar(); // Can't process too large images: // if (isImageTooBig(coaddDirName+"/coadd.fits")) qDebug() << "tooBig"; // else qDebug() << "small"; // cleanup temporary files /* QDir coaddDir(coaddDirName); QStringList filter = {"listCoadd*", "coadd.head"}; coaddDir.setNameFilters(filter); coaddDir.setSorting(QDir::Name); QStringList tempFiles = coaddDir.entryList(filter); for (auto &it : tempFiles) { QFile tmpFile(coaddDirName+"/"+it); if (tmpFile.exists()) tmpFile.remove(); } */ pushBeginMessage("CoaddUpdate", coaddScienceDir); bool skippedIQ = true; float seeing_world = 0.; float seeing_image = 0.; // float maxVal = 100.; emit loadViewer(coaddDirName, "coadd.fits", "DragMode"); // Do IQ analysis only for small images with "normal" plate scales if (instData->pixscale <= 2.0 && instData->radius <= 0.5) { skippedIQ = false; emit messageAvailable("coadd.fits : Loading image data ...", "image"); QVector<bool> dummyMask; dummyMask.clear(); MyImage *coadd = new MyImage(coaddDirName, "coadd.fits", "", 1, dummyMask, &verbosity); if (coadd->isTooBig()) { coadd->freeAll(); delete coadd; coadd = nullptr; } else { connect(coadd, &MyImage::critical, this, &Controller::criticalReceived); connect(coadd, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(coadd, &MyImage::warning, this, &Controller::warningReceived); connect(coadd, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); connect(coadd, &MyImage::setWCSLock, this, &Controller::setWCSLockReceived, Qt::DirectConnection); coadd->chipName = "coadd"; coadd->setupData(false, false, true); coadd->globalMaskAvailable = false; coadd->objectMaskDone = false; coadd->weightInMemory = false; coadd->weightPath = coaddDirName; coadd->weightName = "coadd"; coadd->readWeight(); coadd->gain = 1.0; coadd->saturationValue = minCoaddSaturationValue; // maxVal = maxVec_T(coadd->dataCurrent); float radius = sqrt(coadd->naxis1*coadd->naxis1 + coadd->naxis2*coadd->naxis2) / 2. * coadd->plateScale / 60.; // in arcmin // Enforce an upper limit to the download catalog (the query also has a built-in limit of # sources < 1e6) if (radius > 60) radius = 60.; emit messageAvailable("coadd.fits : Downloading GAIA point sources ...", "image"); downloadGaiaCatalog(coaddScienceData, QString::number(radius, 'f', 1)); // Point sources // Measure the seeing if we have reference sources if (gaiaQuery->numSources > 0) { emit messageAvailable("coadd.fits : Modeling background ...", "image"); coadd->backgroundModel(256, "interpolate"); emit messageAvailable("coadd.fits : Detecting sources ...", "image"); coadd->segmentImage("10", "3", true, false); coadd->estimateMatchingTolerance(); ImageQuality *imageQuality = new ImageQuality(instData, mainDirName); imageQuality->matchingTolerance = coadd->matchingTolerance; imageQuality->baseName = "coadd.fits"; connect(imageQuality, &ImageQuality::messageAvailable, this, &Controller::messageAvailableReceived); // pass the reference data collectGaiaRaDec(coadd, gaiaQuery->de_out, gaiaQuery->ra_out, imageQuality->refCat); // pass the source data (dec, ra, fwhm, ell on one hand, and mag separately) coadd->collectSeeingParameters(imageQuality->sourceCat, imageQuality->sourceMag, 0); // match static_cast<void> (imageQuality->getSeeingFromGaia()); // if (!gaia) imageQuality->getSeeingFromRhMag(); TODO: not yet implemented seeing_image = imageQuality->fwhm; // in pixel seeing_world = imageQuality->fwhm * coadd->plateScale; // in pixel if (imageQuality->numSources > 0) { emit messageAvailable("coadd.fits : FWHM = " + QString::number(seeing_world, 'f', 2) + "\" (" + QString::number(seeing_image, 'f', 2) + " pixel)", "image"); emit messageAvailable("coadd.fits : Ellipticity = " + QString::number(imageQuality->ellipticity, 'f', 3), "image"); // emit messageAvailable("coadd.fits : # stars used for IQ analysis = " + QString::number(imageQuality->numSources), "image"); } else { emit messageAvailable("coadd.fits : FWHM = undetermined", "image"); emit messageAvailable("coadd.fits : Ellipticity = undetermined", "image"); // emit messageAvailable("coadd.fits : # stars used for IQ analysis = 0", "image"); } if (seeing_image < 2.0 && seeing_image > 0. && (cdw->ui->COAkernelComboBox->currentText() == "LANCZOS3" || cdw->ui->COAkernelComboBox->currentText() == "LANCZOS4")) { emit messageAvailable("Undersampling detected. The chosen "+cdw->ui->COAkernelComboBox->currentText() +" resampling kernel could lead to artifacts in compact sources (stars). In this case, consider the LANCZOS2 kernel.", "warning"); } coadd->releaseAllDetectionMemory(); coadd->releaseBackgroundMemory("entirely"); } else { emit messageAvailable("Seeing will not be determined because no reference point sources were retrieved.", "warning"); } } coadd->freeAll(); delete coadd; coadd = nullptr; delete gaiaQuery; gaiaQuery = nullptr; /* // TODO: that should be redone using the new gaia matching method QVector<float> fluxRadius(coadd->objectList.length()); for (auto &obj : coadd->objectList) { if (obj->FLAGS == 0) fluxRadius.append(obj->FLUX_RADIUS); } float seeing_image = modeMask(fluxRadius, "classic", QVector<bool>(), false)[0]; float seeing_world = seeing_image * instData->pixscale; emit messageAvailable("coadd.fits : FWHM = " + QString::number(seeing_world, 'f', 2) + "\" (" + QString::number(seeing_image, 'f', 2) + " pixel)" */ } else { skippedIQ = true; emit messageAvailable("<br>The coadded image covers a very large area on sky. The image quality analysis is skipped, as it would require the download of a very large point source catalog.<br>", "data"); } // IQ analysis ended. Update FITS header fitsfile *fptr = nullptr; QString name = coaddDirName+"/coadd.fits"; int status = 0; // declared above if (name.isNull() || name.isEmpty()) { status = 1; emit messageAvailable("Controller::coaddUpdate(): file name empty or not initialized!", "error"); emit criticalReceived(); return; } fits_open_file(&fptr, name.toUtf8().data(), READWRITE, &status); fits_update_key_str(fptr, "FILTER", coaddFilter.toUtf8().data(), NULL, &status); fits_update_key_flt(fptr, "EXPTIME", 1.0, 1, "Exposure time is normalized to 1s", &status); fits_update_key_flt(fptr, "TEXPTIME", coaddTexptime, 3, "Total exposure time [s]", &status); fits_update_key_flt(fptr, "SKYVALUE", coaddSkyvalue, 3, "Effective background value [e-/s]", &status); fits_update_key_flt(fptr, "GAIN", coaddGain, 3, "Effective gain. This image is already in e-/s!", &status); fits_update_key_str(fptr, "BUNIT", "e-/s", "Pixels are photo-electrons / second", &status); fits_update_key_flt(fptr, "SATURATE", minCoaddSaturationValue, 3, "Lowest value at which saturation occurs [e-/s]", &status); if (!skippedIQ) { fits_update_key_flt(fptr, "FWHM_I", seeing_image, 3, "FWHM (pixel)", &status); fits_update_key_flt(fptr, "FWHM_W", seeing_world, 3, "FWHM (arcsec)", &status); } fits_update_key_str(fptr, "DATEOBS1", minDateObs.toUtf8().data(), "Begin of the first observation (DATE-OBS)", &status); fits_update_key_str(fptr, "DATEOBS2", maxDateObs.toUtf8().data(), "Begin of the last observation (DATE-OBS)", &status); fits_update_key_dbl(fptr, "MJDSTART", mjdStart, 12, "Begin of the first observation (MJD-OBS)", &status); fits_update_key_dbl(fptr, "MJDMED", mjdMedian, 12, "Median MJD-OBS of all observations", &status); fits_update_key_dbl(fptr, "MJDEND", mjdEnd, 12, "End of the last observation (MJD-OBS + EXPTIME)", &status); fits_update_key_str(fptr, "THELIRUN", mainGUI->ui->setupProjectLineEdit->text().toUtf8().data(), "THELI project name", &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); emit progressUpdate(100); // pushEndMessage(taskBasename, coaddScienceDir); // Now we can quit the first coaddition thread (which spawned all the other threads). // This will return control to mainGUI() (i.e. enable the start button again) // workerThreadPrepare->quit(); // Finally, do flux calibration if requested if (cdw->ui->COAfluxcalibCheckBox->isChecked()) { emit messageAvailable("coadd.fits : Loading flux calibration module ...", "image"); // emit loadAbsZP(coaddDirName+"/coadd.fits", maxVal); emit loadAbsZP(coaddDirName+"/coadd.fits", minCoaddSaturationValue); } else { // Now we can quit the first coaddition thread (which spawned all the other threads). // This will return control to mainGUI() (i.e. enable the start button again) if (workerThreadPrepare) workerThreadPrepare->quit(); } } void Controller::getMinimumSaturationValue() { minCoaddSaturationValue = 1e12; QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, coaddScienceData); // Update minimum saturation value (normalized to exposure time) // TODO: update wrt fluxscaling for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; if (!it->successProcessing) continue; if (it->saturationValue / it->exptime < minCoaddSaturationValue) { minCoaddSaturationValue = it->saturationValue / it->exptime; } } } void Controller::absZeroPointCloseReceived() { if (workerThreadPrepare) workerThreadPrepare->quit(); } // write the initial empty coadd.fits into a coadd.head void Controller::foldCoaddFits() { QFile fileIn(coaddDirName+"/coadd.fits"); QFile fileOut(coaddDirName+"/coadd.head"); QTextStream streamIn(&fileIn); QTextStream streamOut(&fileOut); if (!fileIn.open(QIODevice::ReadOnly)) { QString part1 = coaddDirName+"/coadd.fits"; QString part2 = fileIn.errorString(); emit showMessageBox("Controller::CANNOT_OPEN_FILE", part1, part2); successProcessing = false; return; } if (!fileOut.open(QIODevice::WriteOnly)) { QString part1 = coaddDirName+"/coadd.head"; QString part2 = fileIn.errorString(); emit showMessageBox("Controller::CANNOT_OPEN_FILE", part1, part2); successProcessing = false; return; } QString line; int cardLength = 80; while (streamIn.readLineInto(&line)) { if (line.isEmpty()) continue; long length = line.length(); if (length<80) return; for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&line, i, cardLength); QString string = subString.toString(); streamOut << string << "\n"; } } fileIn.close(); fileOut.close(); fileOut.setPermissions(QFile::ReadUser | QFile::WriteUser); fileIn.remove(); // If the user provided a manual coadd size, then force the CRPIX to be at the image center. // This enables making coadds with exactly the same size and projection, from different sets of images, without having to crop them QString sizex = cdw->ui->COAsizexLineEdit->text(); QString sizey = cdw->ui->COAsizeyLineEdit->text(); if (!sizex.isEmpty() && !sizey.isEmpty()) { int crpix1 = sizex.toFloat()/2.; int crpix2 = sizey.toFloat()/2.; replaceLineInFile(coaddDirName+"/coadd.head", "CRPIX1", "CRPIX1 = "+QString::number(crpix1)); replaceLineInFile(coaddDirName+"/coadd.head", "CRPIX2", "CRPIX2 = "+QString::number(crpix2)); } }
55,263
C++
.cc
1,073
44.15657
210
0.659841
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,476
processingAstrometry.cc
schirmermischa_THELI/src/processingInternal/processingAstrometry.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../dockwidgets/monitor.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "../tools/imagequality.h" #include "../tools/correlator.h" #include "photinst.h" #include "ui_confdockwidget.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QTextStream> #include <QStandardPaths> #include <QProgressBar> #include <QTest> void Controller::taskInternalAstromphotom() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; if (!scienceData->successProcessing) return; mainGUI->ui->processProgressBar->setDisabled(true); scampScienceDir = mainDirName+"/"+scienceDir; scampDir = scampScienceDir+"/astrom_photom_scamp/"; scampPlotsDir = mainDirName+"/"+scienceDir + "/plots/"; scampHeadersDir = mainDirName+"/"+scienceDir + "/headers/"; scampScienceData = scienceData; anetDir = scampScienceDir+"/astrom_photom_anet/"; pushBeginMessage(taskBasename, scienceDir); pushConfigAstromphotom(); // DAISY-CHAINING. The end of the scamp run triggers the iView display of the checkplots, // which in turn triggers the header update if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp") { QString catDirName = mainDirName + "/" + scienceDir + "/cat/"; if (!scienceData->hasMatchingPartnerFiles(catDirName, ".scamp", false)) { emit messageAvailable("Not all exposures have complete .scamp catalogs. They will be skipped.", "warning"); // return; } if (cdw->ui->ASTmatchMethodComboBox->currentText() == "Astrometry.net") { if (!scienceData->hasMatchingPartnerFiles(catDirName, ".anet", false)) { emit messageAvailable("Not all exposures have complete .anet catalogs. They will be skipped.", "warning"); // return; } prepareAnetRun(scienceData); progress = 0.; runAnet(scienceData); } // run scamp and retrieval of point source catalog in parallel #pragma omp parallel sections { #pragma omp section { // Prepare scamp directories and perform consistency checks prepareScampRun(scienceData); // Collect scamp input catalogs long totNumObjects = 0; long numCats = prepareScampCats(scienceData, totNumObjects); // if (numCats == 0) return; // no exiting in openMP construct if (numCats > 0) { // Release memory: // 140 bytes per detection // "a few 10 kB" per FITS table // long totBytes = 0; int degrees = cdw->ui->ASTdistortLineEdit->text().toInt(); totBytes += totNumObjects * 140 + (2*50000*instData->numChips)*numCats; long Nt = numCats * 1 * (degrees*degrees+2) + numCats*6; totBytes += 8*Nt*Nt; totBytes = 2*totBytes/ 1024. / 1024.; if (verbosity >= 1) emit messageAvailable("Scamp memory estimate: " + QString::number(long(totBytes)) + " MB", "controller"); releaseMemory(totBytes, 1); progress = 0.; progressStepSize = 80. / (float) numCats; // 80%, leaving some space for distortion solution. // Build the scamp command buildScampCommand(scienceData); // Run the Scamp command workerThread = new QThread(); scampWorker = new ScampWorker(scampCommand, scampDir, instData->shortName); workerInit = true; workerThreadInit = true; scampWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, scampWorker, &ScampWorker::runScamp); // Qt::DirectConnection is bad here, because this task runs in a different thread than the main controller, // meaning that if e.g. sky sub is activated as well it will start immediately even before the scamp checkplots are shown // connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, scampWorker, &QObject::deleteLater, Qt::DirectConnection); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); connect(scampWorker, &ScampWorker::errorFound, this, &Controller::scampErrorFoundReceived); connect(scampWorker, &ScampWorker::finishedScamp, this, &Controller::finishedScampReceived); // Need the direct connection if we want the thread to actually return control to the main thread (activating the start button again). // But then sky sub would start before checkplots are evaluated. // CORRECT WAY: call workerThread->quit() at the end of the image quality analysis // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); // connect(scampWorker, &ScampWorker::finished, workerThread, &QThread::quit); connect(scampWorker, &ScampWorker::finished, scampWorker, &QObject::deleteLater); connect(scampWorker, &ScampWorker::messageAvailable, monitor, &Monitor::displayMessage); connect(scampWorker, &ScampWorker::fieldMatched, this, &Controller::fieldMatchedReceived); workerThread->start(); workerThread->wait(); } } #pragma omp section { downloadGaiaCatalog(scampScienceData); // Point sources } } } // Not implemented (greyed out) if (cdw->ui->ASTmethodComboBox->currentText() == "Astrometry.net") { QString catDirName = mainDirName + "/" + scienceDir + "/cat/"; if (!scienceData->hasMatchingPartnerFiles(catDirName, ".anet")) return; // Prepare anet directories and perform consistency checks prepareAnetRun(scienceData); /* // Release memory (assuming it is the same for a.net) // 140 bytes per detection // "a few 10 kB" per FITS table // long totBytes = 0; int degrees = cdw->ui->ASTdistortLineEdit->text().toInt(); totBytes += totNumObjects * 140 + (2*50000*instData->numChips)*numCats; long Nt = numCats * 1 * (degrees*degrees+2) + numCats*6; totBytes += 8*Nt*Nt; totBytes = 2*totBytes/ 1024. / 1024.; if (verbosity >= 1) emit messageAvailable("Astrometry.net memory estimate: " + QString::number(long(totBytes)) + " MB", "controller"); releaseMemory(totBytes, 1); */ progress = 0.; runAnet(scienceData); } else if (cdw->ui->ASTmethodComboBox->currentText() == "Cross-correlation") { } else if (cdw->ui->ASTmethodComboBox->currentText() == "Header") { // TODO } else { // No other method yet } } void Controller::scampErrorFoundReceived() { successProcessing = false; criticalReceived(); if (workerThread) workerThread->quit(); } int Controller::getMaxPhotInst() { if (!successProcessing) return 0; // Parse the output headers and extract fluxscales and exposure times QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); int maxPhotInst = 0; for (auto &it : MEFheaders) { QFile MEF(scampDir+"/"+it); QTextStream inStream(&MEF); if (!MEF.open(QIODevice::ReadOnly)) { continue; } QString line; int photinst = 0; while (inStream.readLineInto(&line)) { if (line.contains("PHOTINST=")) photinst = line.split("=")[1].split("/")[0].simplified().toInt(); } MEF.close(); if (photinst > maxPhotInst) maxPhotInst = photinst; } return maxPhotInst; } void Controller::scampCalcFluxscale() { if (!successProcessing) return; // Parse the output headers and extract fluxscales and exposure times QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); if (MEFheaders.isEmpty()) { successProcessing = false; emit messageAvailable("Could not find scamp output headers.", "error"); criticalReceived(); if (workerThread) workerThread->quit(); return; } bool success = true; int maxPhotInst = getMaxPhotInst(); for (int i=0; i<maxPhotInst; ++i) { PhotInst *photInst = new PhotInst(this); photInstruments.append(photInst); } long MEFindex = 0; for (auto &it : MEFheaders) { QFile MEF(scampDir+"/"+it); QFileInfo MEFinfo(MEF); QString MEFbasename = MEFinfo.completeBaseName(); QTextStream inStream(&MEF); if (!MEF.open(QIODevice::ReadOnly)) { success = false; continue; } QString line; double fluxscale = -1.; double exptime = -1.; QString basename = ""; int photinst_idx = 0; while (inStream.readLineInto(&line)) { if (line.contains("FLXSCALE=")) fluxscale = line.split("=")[1].split("/")[0].simplified().toDouble(); if (line.contains("PHOTINST=")) photinst_idx = line.split("=")[1].split("/")[0].simplified().toInt() - 1; } MEF.close(); // Find the associated exposure time if (instData->validChip == -1) { successProcessing = false; return; } for (auto &it : scampScienceData->myImageList[instData->validChip]) { it->loadHeader(); if (it->baseName.contains(MEFbasename)) { exptime = it->exptime; basename = it->baseName; break; } } photInstruments[photinst_idx]->fluxScale.append(fluxscale); photInstruments[photinst_idx]->expTime.append(exptime); photInstruments[photinst_idx]->baseName.append(basename); // Mapping the running overall MEF file index to the running index of MEF file index for the current phot instrument photInstruments[photinst_idx]->indexMap.insert(MEFindex, photInstruments[photinst_idx]->fluxScale.length()-1); ++MEFindex; } // Calculate RZP and FLXSCALE for each photometric instrument for (auto &pi : photInstruments) { pi->getRZP(); } if (!success) { successProcessing = false; } } void Controller::finishedScampReceived() { if (!successProcessing) return; // Move the checkplots to their final place moveFiles("*.png", scampDir, scampPlotsDir); // Calculate the mean RZP and FLXSCALE per photometric instrument scampCalcFluxscale(); // Split the scamp headers into individual chips, adding RZP and FLXSCALE splitScampHeaders(); mainGUI->ui->processProgressBar->setEnabled(true); emit progressUpdate(100); // pushEndMessage(taskBasename, scampScienceDir); photInstruments.clear(); emit showScampCheckPlots(); } void Controller::fieldMatchedReceived() { #pragma omp atomic progress += progressStepSize; } void Controller::splitScampHeaders() { if (!successProcessing) return; // Split the MEF scamp header files into individual chips and move them to their final place QDir dir(scampDir); QStringList filterList("*.head"); QStringList MEFheaders = dir.entryList(filterList); bool success = true; long MEFindex = 0; for (auto &it : MEFheaders) { QFile MEF(scampDir+"/"+it); QFileInfo MEFinfo(MEF); QTextStream inStream(&MEF); if (!MEF.open(QIODevice::ReadOnly)) { success = false; break; } QFile HEAD; QTextStream outStream; QString line; int i=0; int headCount = 0; while (inStream.readLineInto(&line)) { if (i==0) { int chip = instData->chipMap.key(headCount) + 1; // dealing with user defined bad chips HEAD.setFileName(scampHeadersDir+"/"+MEFinfo.completeBaseName()+"_"+QString::number(chip)+".head"); outStream.setDevice(&HEAD); if (!HEAD.open(QIODevice::WriteOnly)) { success = false; break; } } // THELI style flux scaling if (line.contains("FLXSCALE=")) line.replace("FLXSCALE=","FLSCALE ="); // copying the original FLXSCALE keyword to FLSCALE (original will be replaced below) if (line.contains("PHOTINST")) { int photinst_idx = line.split("=")[1].split("/")[0].simplified().toInt() - 1; long idx = photInstruments[photinst_idx]->indexMap.value(MEFindex); QString line1 = "FLXSCALE= "+QString::number(photInstruments[photinst_idx]->fluxScale[idx],'g',12) + " / THELI relative flux scale"; QString line2 = "RZP = "+QString::number(photInstruments[photinst_idx]->RZP[idx],'g',12) + " / THELI relative zeropoint"; outStream << line1 << "\n"; outStream << line2 << "\n"; } outStream << line << "\n"; ++i; if (line.simplified() == "END") { HEAD.close(); HEAD.setPermissions(QFile::ReadUser | QFile::WriteUser); i=0; ++headCount; } } MEF.close(); ++MEFindex; } if (!success) { successProcessing = false; emit messageAvailable("Could not parse one or more of the scamp output header files.", "error"); criticalReceived(); } } // unused, done in copy_zero_order() /* void Controller::updateMyImagesWithScampSolution(Data *scienceData) { for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : scienceData->myImageList[chip]) { // header file QFile headerFile(scienceData->dirName + "/headers/" + it->chipName + ".head"); QString RZP = get_fileHeaderParameter(&headerFile, "RZP"); it->RZP = RZP.toFloat(); it->updateHeaderValue("RZP", RZP); // like that it will be included in the FITS file when written it->updateHeaderValueInFITS("RZP", RZP); // Optionally, updates the FITS file as well (if on drive) } } } */ void Controller::showScampCheckPlotsReceived() { if (!successProcessing) return; emit messageAvailable("<br>*** Inspect the astrometric solution and accept or reject it. ***<br>", "warning"); IView *checkplotViewer = new IView("SCAMP", scampPlotsDir, this); // blocks until seeing determination is done, which is silly and i don't understand why // checkplotViewer->setWindowModality(Qt::ApplicationModal); checkplotViewer->show(); connect(checkplotViewer, &IView::solutionAcceptanceState, this, &Controller::registerScampSolutionAcceptance); // Avoid THELI hogging memory during the session with every call to iview connect(checkplotViewer, &IView::closed, checkplotViewer, &IView::deleteLater); connect(checkplotViewer, &IView::closed, this, &Controller::continueWithCopyZeroOrder); } void Controller::registerScampSolutionAcceptance(bool scampSolutionAccepted) { scampSolutionAcceptanceState = scampSolutionAccepted; if (scampSolutionAccepted) { emit messageAvailable("*** Scamp solution accepted ***<br>", "note"); } else { emit messageAvailable("*** Scamp solution rejected ***<br>", "warning"); } } void Controller::continueWithCopyZeroOrder() { if (!successProcessing) return; if (scampSolutionAcceptanceState) copyZeroOrder(); else { monitor->raise(); successProcessing = false; if (workerThread) workerThread->quit(); successProcessing = true; } } void Controller::copyZeroOrder() { if (!successProcessing) return; pushBeginMessage("CopyZeroOrder", scampScienceDir); if (!QDir(scampHeadersDir).exists()) { emit messageAvailable("Could not update images with 0th order WCS solution.<br>The headers/ subdirectory does not exist in<br>"+scampScienceDir, "error"); successProcessing = false; monitor->raise(); if (workerThread) workerThread->quit(); successProcessing = true; return; } #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; for (auto &it : scampScienceData->myImageList[chip]) { if (abortProcess) break; it->setupDataInMemorySimple(false); if (it->activeState != MyImage::ACTIVE) continue; if (!it->successProcessing) { abortProcess = true; continue; } // it->backupOrigHeader(chip); // Create a backup copy of the original FITS headers if it doesn't exist yet if (it->scanAstromHeader(chip, "inHeadersDir")) { // reads the header, and updates the wcs struct in MyImage class (i.e. the memory) it->updateZeroOrderOnDrive("update"); // Overwrite 0-th order solution in FITS header (if on drive) // it->updateZeroOrderInMemory(); // Overwrite 0-th order solution in memory } // The following is done by scanAstromheader and updateZeroOrderOnDrive /* // Copy RZP from header file QFile headerFile(scampScienceData->dirName + "/headers/" + it->chipName + ".head"); QString RZP = get_fileHeaderParameter(&headerFile, "RZP"); it->RZP = RZP.toFloat(); it->updateHeaderValue("RZP", RZP); // like that it will be included in the FITS file when written it->updateHeaderValueInFITS("RZP", RZP); // Optionally, updates the FITS file as well (if on drive) */ it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } if (!it->successProcessing) successProcessing = false; } } // pushEndMessage("CopyZeroOrder", scampScienceDir); doImageQualityAnalysis(); } void Controller::prepareAnetRun(Data *scienceData) { if (!successProcessing) return; if (verbosity > 0) emit messageAvailable("Setting up astrometry.net run ...", "controller"); QString scienceDir = mainDirName+"/"+scienceData->subDirName; QString headersPath = scienceDir+"/headers/"; // Clean-up and recreate the anet directory trees QDir dir(anetDir); dir.removeRecursively(); dir.mkpath(anetDir); QDir headersDir(headersPath); headersDir.removeRecursively(); headersDir.mkpath(headersPath); // Check if the reference catalog exists QFile refcat(scienceDir+"/cat/refcat/theli_mystd.index"); if (!refcat.exists()) { emit messageAvailable("The astrometric reference catalog does not exist, or was not created!", "error"); successProcessing = false; monitor->raise(); return; } // Write the config file for the solver QFile backendConfig(scienceDir+"/astrom_photom_anet/backend.cfg"); if (backendConfig.exists()) backendConfig.remove(); QTextStream stream(&backendConfig); if( !backendConfig.open(QIODevice::WriteOnly)) { emit messageAvailable("Controller::prepareAnetRun(): ERROR writing "+scienceDir+"/astrom_photom_anet/backend.cfg : "+backendConfig.errorString(), "error"); emit criticalReceived(); return; } stream << "#inparallel" << "\n"; stream << "#depths 10 20 30 40 50 60 70 80 90 100" << "\n"; stream << "#cpulimit 300" << "\n"; stream << "add_path " << scienceDir+"/cat/refcat/" << "\n"; stream << "index theli_mystd.index" << "\n"; backendConfig.close(); backendConfig.setPermissions(QFile::ReadUser | QFile::WriteUser); } void Controller::runAnet(Data *scienceData) { QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 1; // wild guess, don't know the memory needs of a.net releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); QString pixscaleMaxerr = cdw->ui->ASTpixscaleLineEdit->text(); scienceData->populateExposureList(); progressStepSize = 100. / float(numMyImages); QStringList failedImages = QStringList(); QStringList failedExposures = QStringList(); #pragma omp parallel for num_threads(maxCPU) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (!it->successProcessing) continue; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 1) emit messageAvailable(it->chipName + " : Running astrometry.net ...", "data"); it->loadHeader(); // don't need pixels, but metadata it->checkWCSsanity(); it->buildAnetCommand(pixscaleMaxerr); it->runAnetCommand(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } #pragma omp critical { if (!it->anetSolved) { failedImages.append(it->baseName); failedExposures.append(it->rootName); } progress += progressStepSize; } } emit messageAvailable("<br>Astrometry.net summary : ", "data"); if (!failedImages.isEmpty()) { emit messageAvailable("The following images did not solve:", "warning"); for (auto &it : failedImages) { emit messageAvailable(it, "warning"); } emit warningReceived(); } // merge the anet output of multi-chip cameras, and extract relevant keywords, only for (long i=0; i<scienceData->exposureList.length(); ++i) { if (abortProcess || !successProcessing) continue; // open stream for merged output file QString aheaderName = anetDir+"/"+scienceData->exposureList[i][0]->rootName+".ahead"; QFile aheaderFile(aheaderName); QTextStream stream(&aheaderFile); if( !aheaderFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Could not write astrometry.net reformatted output to "+aheaderFile.fileName(), "error"); emit messageAvailable(aheaderFile.errorString(), "error"); emit criticalReceived(); successProcessing = false; break; } // Loop over chips and extract anet header data bool consistent = false; int count = 0; for (auto &it : scienceData->exposureList[i]) { stream << it->extractAnetOutput(); ++count; } if (count == instData->numUsedChips) consistent = true; aheaderFile.close(); aheaderFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (!consistent) { aheaderFile.remove(); emit messageAvailable(scienceData->exposureList[i][0]->rootName + " : Controller::runAnet(): Inconsistent number of detectors", "warning"); } } // Collect a list of the header files for scamp makeAnetHeaderList(scienceData); } void Controller::doImageQualityAnalysis() { if (!successProcessing) return; // Only do this for cameras which have a meaningful plate scale for this purpose, i.e. where there is // a risk that background galaxies contaminate a global statistical seeing and ellipticity measurement done during 'create source cat'. // Same for huge cameras such as DECam, but here simply because the catalog download would take forever. if (instData->pixscale > 2.0 || instData->radius > 1.0) { if (workerThread) workerThread->quit(); successProcessing = true; return; } pushBeginMessage("ImageQuality", scampScienceDir); // Todo: replace with GAIA catalog if that was the reference catalog already! // downloadGaiaCatalog(scampScienceData); // Point sources QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scampScienceData); #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName, gaiaQuery, instData) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } // Setup seeing measurement it->estimateMatchingTolerance(); ImageQuality *imageQuality = new ImageQuality(instData, mainDirName); imageQuality->matchingTolerance = it->matchingTolerance; imageQuality->baseName = it->chipName; // pass the reference data collectGaiaRaDec(it, gaiaQuery->de_out, gaiaQuery->ra_out, imageQuality->refCat); // pass the source data (dec, ra, fwhm, ell on one hand, and mag separately) it->collectSeeingParameters(imageQuality->sourceCat, imageQuality->sourceMag, instData->chipMap.value(chip)); // match static_cast<void> (imageQuality->getSeeingFromGaia()); it->fwhm = imageQuality->fwhm * instData->pixscale; // Updating MyImage fwhm parameter, in arcsec it->updateHeaderValue("FWHM", it->fwhm); // Updating MyImage header string it->updateHeaderValue("ELLIP", imageQuality->ellipticity); it->updateHeaderValueInFITS("FWHM", QString::number(it->fwhm, 'f', 3)); // Updating the current FITS image on drive it->updateHeaderValueInFITS("ELLIP", QString::number(imageQuality->ellipticity, 'f', 3)); // if (!gaia) imageQuality->getSeeingFromRhMag(); TODO: Not yet implemented if (verbosity > 1) emit messageAvailable(it->chipName + " : FWHM / Ellipticity / # stars = " + QString::number(it->fwhm, 'f', 3) + " / " + QString::number(imageQuality->ellipticity, 'f', 3) + " / " + QString::number(imageQuality->numSources), "ignore"); delete imageQuality; imageQuality = nullptr; it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } if (workerThread) workerThread->quit(); delete gaiaQuery; gaiaQuery = nullptr; // emit messageAvailable("You can display the results of the image quality analysis in the statistics module", "note"); successProcessing = true; // pushEndMessage("ImageQuality", scampScienceDir); } // X-correlation works only for instruments with a single chip! void Controller::doCrossCorrelation(Data *scienceData) { if (!successProcessing) return; QString DT = cdw->ui->ASTxcorrDTLineEdit->text(); QString DMIN = cdw->ui->ASTxcorrDMINLineEdit->text(); if (DT.isEmpty()) DT = "3.0"; if (DMIN.isEmpty()) DMIN = "5"; //#pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; emit messageAvailable(it->baseName + " : Building xcorrelation pixel map ...", "controller"); it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } if (it->activeState != MyImage::ACTIVE) continue; it->readWeight(); it->resetObjectMasking(); it->backgroundModel(64, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->makeXcorrData(); if (!it->successProcessing) successProcessing = false; // TODO // write image // run python script instead of fftw /* // Correlate image with reference image (first in series) Correlator correlator(it, scienceData->myImageList[chip][0]); correlator.xcorrelate(); QVector<float> peakPos = correlator.find_peak(); if (peakPos.isEmpty()) it->successProcessing = false; */ it->releaseAllDetectionMemory(); } } satisfyMaxMemorySetting(); } void Controller::prepareScampRun(Data *scienceData) { if (!successProcessing) return; if (verbosity > 0) emit messageAvailable("Setting up Scamp run ...", "controller"); QString scienceDir = mainDirName+"/"+scienceData->subDirName; QString headersPath = scienceDir+"/headers/"; QString plotsPath = scienceDir+"/plots/"; // Clean-up and recreate the scamp directory trees QDir dir(scampDir); dir.removeRecursively(); dir.mkpath(scampDir); QDir plotsDir(plotsPath); plotsDir.removeRecursively(); plotsDir.mkpath(plotsPath); QDir headersDir(headersPath); headersDir.removeRecursively(); headersDir.mkpath(headersPath); QFile file(scampDir+"/scamp_global.ahead"); file.remove(); // Check if the reference catalog exists QFile refcat(scienceDir+"/cat/refcat/theli_mystd.scamp"); if (!refcat.exists()) { emit messageAvailable("The astrometric reference catalog does not exist, or was not created!", "error"); successProcessing = false; monitor->raise(); return; } // emit appendOK(); } long Controller::prepareScampCats(Data *scienceData, long &totNumObjects) { if (!successProcessing) return 0; QString scienceDir = mainDirName+"/"+scienceData->subDirName; if (verbosity > 0) emit messageAvailable("Linking scamp catalogs to "+scampDir+" ...", "controller"); // Prepare a file that contains all scamp catalogs (only those for which an image is currently present in scienceDir); QFile catFile(scampDir+"/scamp_cats"); catFile.remove(); QTextStream stream(&catFile); if( !catFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Writing list of scamp catalogs to "+scampDir+catFile.fileName(), "error"); emit messageAvailable(catFile.errorString(), "error"); successProcessing = false; monitor->raise(); return 0; } // Link scamp catalogs (only those for currently active images) long numCat = 0; QStringList imageList; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList << it->chipName; } } QDir catDir(scienceDir+"/cat/"); QStringList catList = catDir.entryList(QStringList("*.scamp")); for (auto &cat : catList) { QString catbase = cat; totNumObjects += getNumObjectsScampCat(scienceDir+"/cat/"+catbase); catbase.remove(".scamp"); for (auto &image : imageList) { if (image.contains(catbase)) { QFile catFile(scienceDir+"/cat/"+cat); catFile.link(scampDir+"/"+cat); stream << scampDir+"/"+cat+"\n"; ++numCat; break; } } } catFile.close(); catFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (numCat == 0) { emit messageAvailable("No cat/*.scamp catalogs were found matching the exposures in "+scienceDir+"<br>Did you create the source catalogs?", "error"); monitor->raise(); successProcessing = false; return 0; } // emit appendOK(); return numCat; } long Controller::makeAnetHeaderList(Data *scienceData) { if (!successProcessing) return 0; // Prepare a list of all anet .ahead files (only those for which an image is currently present); QFile aheadFile(anetDir+"/anet_headers"); aheadFile.remove(); QTextStream stream(&aheadFile); if( !aheadFile.open(QIODevice::WriteOnly)) { emit messageAvailable("Writing list of anet headers to "+anetDir+aheadFile.fileName(), "error"); emit messageAvailable(aheadFile.errorString(), "error"); successProcessing = false; monitor->raise(); return 0; } // Link anet headers (only those for currently active images) long numCat = 0; QStringList imageList; for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (it->activeState == MyImage::ACTIVE) imageList << it->chipName; } } QDir aheadDir(anetDir); QStringList aheadList = aheadDir.entryList(QStringList("*.ahead")); for (auto &ahead : aheadList) { QString aheadbase = ahead; int numChips = getNumAnetChips(anetDir+"/"+aheadbase); if (numChips != instData->numUsedChips) continue; // skip bad entry. Error triggered by getNumAnetChips() aheadbase.remove(".ahead"); for (auto &image : imageList) { if (image.contains(aheadbase)) { stream << anetDir+"/"+ahead+"\n"; ++numCat; break; } } } aheadFile.close(); aheadFile.setPermissions(QFile::ReadUser | QFile::WriteUser); if (numCat == 0) { QString scienceDir = mainDirName+"/"+scienceData->subDirName; emit messageAvailable("No *.ahead catalogs were found matching the exposures in "+scienceDir, "error"); monitor->raise(); successProcessing = false; return 0; } return numCat; } long Controller::getNumObjectsScampCat(QString cat) { int status = 0; fitsfile *fptr; fits_open_file(&fptr, cat.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS tables are found in extensions 3, 5, 7, ..., internally referred to as 2, 4, 6, ... int hduType = 0; long nobj = 0; for (int chip=1; chip<=instData->numUsedChips; ++chip) { fits_movabs_hdu(fptr, 2*chip+1, &hduType, &status); long nrows = 0; fits_get_num_rows(fptr, &nrows, &status); nobj += nrows; } fits_close_file(fptr, &status); QString out = __func__; out.append( " :<br> " +cat); printCfitsioError(out, status); return nobj; } long Controller::getNumAnetChips(QString ahead) { // Count the number of "END" strings QFile file(ahead); QTextStream inStream(&file); if (!file.open(QIODevice::ReadOnly)) { emit messageAvailable("Controller::getNumAnetChips(): Could not open "+ahead+" " + file.errorString(), "error"); emit criticalReceived(); monitor->raise(); successProcessing = false; return 0; } QString line; int numChips = 0; while (inStream.readLineInto(&line)) { if (line == "END") ++numChips; } file.close(); if (numChips == instData->numUsedChips) return numChips; else { emit messageAvailable(ahead + ":<br>Expected "+QString::number(instData->numUsedChips)+" chips, but found "+QString::number(numChips), "error"); emit criticalReceived(); monitor->raise(); successProcessing = false; return 0; } } long Controller::getNumObjectsSourceExtractorCat(QString cat) { int status = 0; fitsfile *fptr; fits_open_file(&fptr, cat.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS table is found in extensions 3, internally referred to as 2 int hduType = 0; fits_movabs_hdu(fptr, 3, &hduType, &status); long nrows = 0; fits_get_num_rows(fptr, &nrows, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); return nrows; } void Controller::buildScampCommand(Data *scienceData) { if (!successProcessing) return; QString refcat = mainDirName+"/"+scienceData->subDirName; refcat.append("/cat/refcat/theli_mystd.scamp"); QString distGroups = "1,1"; QString distGroupsUser = cdw->ui->ASTdistortgroupsLineEdit->text(); if (!distGroupsUser.isEmpty()) distGroups.append(","+distGroupsUser); QString distKeys = "XWIN_IMAGE,YWIN_IMAGE"; QString distKeysUser = cdw->ui->ASTdistortkeysLineEdit->text(); if (!distKeysUser.isEmpty()) distKeys.append(","+distKeysUser); scampCommand = findExecutableName("scamp"); scampCommand += " @"+scampDir+"/scamp_cats"; scampCommand += " -NTHREADS " + QString::number(maxCPU); scampCommand += " -ASTREF_CATALOG FILE"; scampCommand += " -ASTREFCAT_NAME " + refcat; scampCommand += " -ASTREF_WEIGHT " + getUserParamLineEdit(cdw->ui->ASTastrefweightLineEdit); scampCommand += " -ASTRINSTRU_KEY " + getUserParamLineEdit(cdw->ui->ASTastrinstrukeyLineEdit); scampCommand += " -CROSSID_RADIUS " + getUserParamLineEdit(cdw->ui->ASTcrossidLineEdit); scampCommand += " -DISTORT_DEGREES " + getUserParamLineEdit(cdw->ui->ASTdistortLineEdit); scampCommand += " -DISTORT_GROUPS " + distGroups; scampCommand += " -DISTORT_KEYS " + distKeys; scampCommand += " -PIXSCALE_MAXERR " + getUserParamLineEdit(cdw->ui->ASTpixscaleLineEdit); scampCommand += " -POSANGLE_MAXERR " + getUserParamLineEdit(cdw->ui->ASTposangleLineEdit); scampCommand += " -POSITION_MAXERR " + getUserParamLineEdit(cdw->ui->ASTpositionLineEdit); scampCommand += " -SN_THRESHOLDS " + getUserParamLineEdit(cdw->ui->ASTsnthreshLineEdit); scampCommand += " -STABILITY_TYPE " + getUserParamComboBox(cdw->ui->ASTstabilityComboBox); scampCommand += " -MOSAIC_TYPE " + getUserParamComboBox(cdw->ui->ASTmosaictypeComboBox); scampCommand += " -MATCH_FLIPPED " + getUserParamCheckBox(cdw->ui->ASTmatchflippedCheckBox); scampCommand += " -CHECKPLOT_RES " + getUserParamLineEdit(cdw->ui->ASTresolutionLineEdit); if (cdw->ui->ASTmatchMethodComboBox->currentText() == "Astrometry.net") { scampCommand += " -AHEADER_NAME @"+anetDir+"/anet_headers"; } QString value = cdw->ui->ASTastrinstrukeyLineEdit->text(); if (value == "") value = "NONE"; scampCommand += " -ASTRINSTRU_KEY " + value; value = cdw->ui->ASTphotinstrukeyLineEdit->text(); if (value == "") value = "NONE"; scampCommand += " -PHOTINSTRU_KEY " + value; QString matching = "Y"; if (cdw->ui->ASTmatchMethodComboBox->currentIndex() > 0) matching = "N"; scampCommand += " -MATCH " + matching; if (verbosity >= 1) emit messageAvailable("Executing the following scamp command :<br><br>"+scampCommand+"<br><br>in directory: <br><br>"+scampDir+"<br>", "info"); if (verbosity >= 1) emit messageAvailable("<br>Scamp output<br>", "ignore"); }
40,847
C++
.cc
891
37.567901
175
0.637186
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,477
processingWeight.cc
schirmermischa_THELI/src/processingInternal/processingWeight.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "ui_confdockwidget.h" #include "ui_monitor.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalGlobalweight() { QString scienceDir = instructions.split(" ").at(1); QString flatDir = instructions.split(" ").at(2); QString biasDir = instructions.split(" ").at(3); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; Data *biasData = nullptr; // Can also point to a dark Data *flatData = nullptr; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigGlobalweight(); // Link with the correct bias data, if any; dark preferred over bias // I have to select dark / bias again even though it is done in tasks.cc already if (!mainGUI->ui->setupDarkLineEdit->text().isEmpty()) { biasData = getData(DT_DARK, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Same for the flat if (!mainGUI->ui->setupFlatLineEdit->text().isEmpty()) { flatData = getData(DT_FLAT, flatDir); // Should we check the filter string? } // Check if calib data exist) if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_?.fits\n"; emit showMessageBox("Controller::MASTER_BIAS_NOT_FOUND_GLOBW", part1, ""); successProcessing = false; return; } if (flatData != nullptr && !flatData->hasAllMasterCalibs) { QString part1 = flatData->dirName+"/"+flatData->subDirName+"_?.fits\n"; emit showMessageBox("Controller::MASTER_FLAT_NOT_FOUND_GLOBW", part1, ""); successProcessing = false; return; } memoryDecideDeletableStatus(scienceData, false); // Need to fill myImageList to get Filter keyword (if the user starts fresh with this task after launching THELI) if (scienceData->myImageList[instData->validChip].isEmpty()) scienceData->populate(scienceData->processingStatus->statusString); // Get the filter name, first exposure in SCIENCE (assuming same filter for all exposures) QStringList filterList; QString filter; for (auto &it : scienceData->myImageList[instData->validChip]) { if (!it->filter.isEmpty()) { filter = it->filter; if (!filterList.contains(filter)) filterList.append(filter); } else { it->readFILTER(); filter = it->filter; if (!filter.isEmpty()) { if (!filterList.contains(filter)) filterList.append(filter); } } } QDir globalweightDir(mainDirName+"/GLOBALWEIGHTS/"); if (!globalweightDir.exists()) { globalweightDir.mkpath(mainDirName+"/GLOBALWEIGHTS/"); GLOBALWEIGHTS = new Data(instData, mask, mainDirName, "GLOBALWEIGHTS", &verbosity); connect(GLOBALWEIGHTS, &Data::messageAvailable, this, &Controller::messageAvailableReceived); connect(GLOBALWEIGHTS, &Data::appendOK, this, &Controller::appendOKReceived); connect(GLOBALWEIGHTS, &Data::critical, this, &Controller::criticalReceived); connect(GLOBALWEIGHTS, &Data::warning, this, &Controller::warningReceived); connect(GLOBALWEIGHTS, &Data::showMessageBox, this, &Controller::showMessageBoxReceived); connect(GLOBALWEIGHTS, &Data::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); GLOBALWEIGHTS->progress = &progress; GLOBALWEIGHTS->dataType = "GLOBALWEIGHT"; // GLOBALWEIGHTS->myImageList is empty at this point // TODO: should we not make all the connections here for Data class? } else { // remove the globalweight for the present filter only, in this science directory (and then re-create it) for (auto &it: filterList) { GLOBALWEIGHTS->resetGlobalWeight(it); } } bool sameWeight = cdw->ui->CGWsameweightCheckBox->isChecked(); QString flatMin = cdw->ui->CGWflatminLineEdit->text(); QString flatMax = cdw->ui->CGWflatmaxLineEdit->text(); QString threshMin = cdw->ui->CGWdarkminLineEdit->text(); QString threshMax = cdw->ui->CGWdarkmaxLineEdit->text(); QString defectKernel = cdw->ui->CGWflatsmoothLineEdit->text(); QString defectRowTol = cdw->ui->CGWflatrowtolLineEdit->text(); QString defectColTol = cdw->ui->CGWflatcoltolLineEdit->text(); QString defectClusTol = cdw->ui->CGWflatclustolLineEdit->text(); if (defectKernel.isEmpty() && ( !defectRowTol.isEmpty() || !defectColTol.isEmpty() || !defectClusTol.isEmpty())) { emit messageAvailable("For defect detection, a kernel size must be specified as well!", "error"); emit criticalReceived(); return; } if (!defectKernel.isEmpty() && ( defectRowTol.isEmpty() && defectColTol.isEmpty() && defectClusTol.isEmpty())) { emit messageAvailable("For defect detection, at least one of row, column or cluster tolerance must be specified as well", "error"); emit criticalReceived(); return; } progressStepSize = 100./(float(instData->numChips)); float nimg = 6; // bias, flat, 4 for image detection back, seg, measure, mask) releaseMemory(nimg*instData->storage*maxExternalThreads, 1); // Only need as many threads as chips, max #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxExternalThreads); // not sure why i had this in a critical section. libwcs not being threadsafe i think. // should be fixed now that the MyImage::initWCS is always called inside a omp critical section //#pragma omp critical // { if (biasData != nullptr) biasData->loadCombinedImage(chip); // skipped if already in memory if (flatData != nullptr) flatData->loadCombinedImage(chip); // skipped if already in memory // } for (auto &it: filterList) { GLOBALWEIGHTS->initGlobalWeight(chip, flatData, it, sameWeight, flatMin, flatMax); GLOBALWEIGHTS->thresholdGlobalWeight(chip, biasData, it, threshMin, threshMax); GLOBALWEIGHTS->detectDefects(chip, flatData, it, sameWeight, defectKernel, defectRowTol, defectColTol, defectClusTol); GLOBALWEIGHTS->applyMask(chip, it); GLOBALWEIGHTS->writeGlobalWeights(chip, it); } if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); GLOBALWEIGHTS->myImageList[chip][0]->unprotectMemory(); // List with one entry per chip, only #pragma omp atomic progress += progressStepSize; } checkSuccessProcessing(GLOBALWEIGHTS); satisfyMaxMemorySetting(); if (successProcessing) { emit populateMemoryView(); emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalIndividualweight() { QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); pushConfigIndividualweight(); memoryDecideDeletableStatus(scienceData, false); QDir globalweightDir(mainDirName+"/GLOBALWEIGHTS/"); if (!globalweightDir.exists()) { emit messageAvailable("The global weight maps must be created before the individual weight maps.", "error"); emit criticalReceived(); successProcessing = false; return; } QDir individualweightDir(mainDirName+"/WEIGHTS/"); individualweightDir.mkdir(mainDirName+"/WEIGHTS/"); QString imageMin = cdw->ui->CIWminaduLineEdit->text(); QString imageMax = cdw->ui->CIWmaxaduLineEdit->text(); QString range = cdw->ui->CIWbloomRangeLineEdit->text(); QString minVal = cdw->ui->CIWbloomMinaduLineEdit->text(); QString aggressiveness = cdw->ui->CIWaggressivenessLineEdit->text(); getNumberOfActiveImages(scienceData); /* #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { incrementCurrentThreads(lock); for (auto &it : scienceData->myImageList[chip]) { if (verbosity >= 0) emit messageAvailable(it->baseName + " : Creating weight map ...", "controller"); it->readImage(false); // no dataBackupL1 required; just use dataCurrent, or read from disk if not yet in memory it->initWeightfromGlobalWeight(GLOBALWEIGHTS->myImageList[chip]); it->thresholdWeight(imageMin, imageMax); it->applyPolygons(chip); it->maskBloomingSpike(instData->type, range, minVal, cdw->ui->CIWmaskbloomingCheckBox->isChecked()); incrementProgress(); it->cosmicsFilter(aggressiveness); it->writeWeight(mainDirName+ "/WEIGHTS/" + it->chipName + ".weight.fits"); it->weightName = it->chipName + ".weight"; incrementProgress(); } } */ QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); float nimg = 4; // weight, global weight, margins releaseMemory(nimg*instData->storage*maxCPU, 1); scienceData->protectMemory(); doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); QString instType = instData->type; #pragma omp parallel for num_threads(maxCPU) firstprivate(instType, mainDirName) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; int chip = it->chipNumber - 1; if (instData->badChips.contains(chip)) continue; releaseMemory(nimg*instData->storage, maxCPU); if (verbosity >= 0) emit messageAvailable(it->chipName + " : Creating weight map ...", "image"); it->setupDataInMemorySimple(false); if (!it->successProcessing) { abortProcess = true; continue; } it->weightModified = false; it->initWeightfromGlobalWeight(GLOBALWEIGHTS->myImageList[chip]); // calls a threadsafe version of MyImage::loadData() to avoid parallel reads of the same globalweight map it->thresholdWeight(imageMin, imageMax); it->applyPolygons(); it->maskSaturatedPixels(cdw->ui->CIWsaturationLineEdit->text(), cdw->ui->CIWmasksaturationCheckBox->isChecked()); it->maskBloomingSpike(instType, range, minVal, cdw->ui->CIWmaskbloomingCheckBox->isChecked()); #pragma omp atomic progress += progressHalfStepSize; it->cosmicsFilter(aggressiveness); // Must write or link weights to drive for swarp if (it->weightModified) it->writeWeight(mainDirName+ "/WEIGHTS/" + it->chipName + ".weight.fits"); else it->linkWeight(mainDirName+"/GLOBALWEIGHTS/globalweight_"+instData->name+"_"+it->filter+"_"+QString::number(chip+1)+".fits", mainDirName+ "/WEIGHTS/" + it->chipName + ".weight.fits"); it->weightOnDrive = true; it->weightName = it->chipName + ".weight"; it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } GLOBALWEIGHTS->myImageList[chip][0]->unprotectMemory(); // List with one entry per chip, only; could also do: // GLOBALWEIGHTS->unprotectMemory(chip); #pragma omp atomic progress += progressHalfStepSize; } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { emit populateMemoryView(); emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } } void Controller::taskInternalSeparate() { // TODO: // Shouldn't there be a successprocessing step at the beginning of every task? QString scienceDir = instructions.split(" ").at(1); Data *scienceData = getData(DT_SCIENCE, scienceDir); if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); memoryDecideDeletableStatus(scienceData, false); getNumberOfActiveImages(scienceData); QString tolerance = cdw->ui->separateTargetLineEdit->text(); int numGroups = scienceData->identifyClusters(tolerance); if (numGroups == 0) return; if (verbosity >= 0) emit messageAvailable("Moving images ...", "controller"); QStringList newSubDirNames; QString dataSubDirName = scienceData->subDirName; QString statusString = scienceData->processingStatus->statusString; // Delete previously created directories, then add files in another loop for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { QString subDirName = dataSubDirName+"_"+QString::number(it->groupNumber); QString pathNew = mainDirName+"/"+subDirName; QDir groupDir(pathNew); if (groupDir.exists()) groupDir.removeRecursively(); } } #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(dataSubDirName, mainDirName, statusString) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { if (!it->successProcessing) continue; QString pathOld = it->path; QString subDirName = dataSubDirName+"_"+QString::number(it->groupNumber); #pragma omp critical { if (!newSubDirNames.contains(subDirName)) newSubDirNames.append(subDirName); } QString pathNew = mainDirName+"/"+subDirName; QDir groupDir(pathNew); groupDir.mkpath(pathNew); it->path = pathNew; it->loadHeader(); // Always write the new image, even if until now it was kept in memory. if (it->imageOnDrive) { moveFile(it->chipName+statusString+".fits", pathOld, it->path); } else { it->writeImage(); it->unprotectMemory(); } #pragma omp atomic progress += progressStepSize; } } checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); // Now we have to create new 'Data' instances for each image association emit messageAvailable("Setting up "+QString::number(numGroups+1)+" image associations ...", "controller"); // First, update the line edit // In case several dirs are entered, we must replace the current one, only QString newDirs = newSubDirNames.join(" "); // New dirs forming one blank-separated string QStringList dirList = mainGUI->ui->setupScienceLineEdit->text().split(" "); for (auto &dir : dirList) { if (dir == scienceData->subDirName) { // replace old dir with new dirs dir = newDirs; } } QString allDirs = dirList.join(" "); scienceData->myImageList.clear(); // We run in a processing thread inside the controller. To change anything "outside" we need signals and slots // Trigger an update of the science dir LineEdit. The MainWindow will then trigger the controller to parse the new data dirs. // For that we need to have access to the status (of which the controller knows nothing, only the Data class) statusAtDistribute = scienceData->processingStatus->statusString; emit scienceDataDirUpdated(allDirs); /* if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, scienceDir); } */ }
17,225
C++
.cc
344
42.81686
196
0.681607
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,478
processingCalibration.cc
schirmermischa_THELI/src/processingInternal/processingCalibration.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/fitting.h" #include "ui_confdockwidget.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalProcessbias() { if (!successProcessing) return; QString biasDir = instructions.split(" ").at(1); Data *biasData = getData(DT_BIAS, biasDir); if (biasData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(biasData)) return; QString min = cdw->ui->biasMinLineEdit->text(); QString max = cdw->ui->biasMaxLineEdit->text(); QString nlow = cdw->ui->biasNlowLineEdit->text(); QString nhigh = cdw->ui->biasNhighLineEdit->text(); currentData = biasData; currentDirName = biasDir; memoryDecideDeletableStatus(biasData, false); pushBeginMessage(taskBasename, biasDir); pushConfigProcessbias(); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // The biasData imagelist is empty after splitting because the Data constructor only looks for *_chip.fits, not for raw files. // if (biasData->myImageList[instData->validChip].isEmpty()) { // biasData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(biasData); // Release as much memory as maximally necessary float nimg = biasData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed biasData->protectMemory(); QString dataDirName = biasData->dirName; // copies for thread safety QString dataSubDirName = biasData->subDirName; // copies for thread safety QString dataDataType = biasData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips // NOTE: QString is not threadsafe, must create copies for threads! // NOTE: a 'bad' chip will 'continue', but openMP waits until at least one of the other threads has finished #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = biasData->myImageList[chip].length() + 1; // The number of images we must keep in memory // Release memory cannot touch any dataCurrent read by MyImage::readImage, because we 'protected' it outside the loop. // Initially, this call might not do anything because everything is protected. On systems with less RAM than // a single exposure this might cause swapping. We test for this elsewhere (when loading images). releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : biasData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); // Read image (if not already in memory), do not create backup, do get mode it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); // Flag the image if its mode is outside a user-provided acceptable range #pragma omp atomic progress += progressHalfStepSize; } if (biasData->myImageList[chip].length() == 0) { biasData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+biasData->subDirName, "error"); emit criticalReceived(); continue; } biasData->combineImagesCalib(chip, combineBias_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); // Combine images biasData->getModeCombineImages(chip); biasData->writeCombinedImage(chip); biasData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : biasData->myImageList[chip]) { it->freeAll(); } } biasData->combinedImage[chip]->emitModelUpdateNeeded(); if (!biasData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } biasData->reportModeCombineImages(); checkSuccessProcessing(biasData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, biasDir); } } void Controller::taskInternalProcessdark() { if (!successProcessing) return; QString darkDir = instructions.split(" ").at(1); Data *darkData = getData(DT_DARK, darkDir); if (darkData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(darkData)) return; QString min = cdw->ui->darkMinLineEdit->text(); QString max = cdw->ui->darkMaxLineEdit->text(); QString nlow = cdw->ui->darkNlowLineEdit->text(); QString nhigh = cdw->ui->darkNhighLineEdit->text(); currentData = darkData; currentDirName = darkDir; memoryDecideDeletableStatus(darkData, false); pushBeginMessage(taskBasename, darkDir); pushConfigProcessdark(); getNumberOfActiveImages(darkData); // // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (darkData->myImageList[instData->validChip].isEmpty()) { // darkData->populate(""); // emit populateMemoryView(); // } // Release as much memory as maximally necessary float nimg = darkData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed darkData->protectMemory(); QString dataDirName = darkData->dirName; // copies for thread safety QString dataSubDirName = darkData->subDirName; // copies for thread safety QString dataDataType = darkData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = darkData->myImageList[chip].length() + 1; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : darkData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); #pragma omp atomic progress += progressHalfStepSize; } if (darkData->myImageList[chip].length() == 0) { darkData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+darkData->subDirName, "error"); emit criticalReceived(); continue; } darkData->combineImagesCalib(chip, combineDark_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); darkData->getModeCombineImages(chip); darkData->writeCombinedImage(chip); darkData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : darkData->myImageList[chip]) it->freeAll(); } if (!darkData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } darkData->reportModeCombineImages(); checkSuccessProcessing(darkData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, darkDir); } } void Controller::taskInternalProcessflatoff() { QString flatoffDir = instructions.split(" ").at(1); Data *flatoffData = getData(DT_FLATOFF, flatoffDir); if (flatoffData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(flatoffData)) return; QString min = cdw->ui->flatoffMinLineEdit->text(); QString max = cdw->ui->flatoffMaxLineEdit->text(); QString nlow = cdw->ui->flatoffNlowLineEdit->text(); QString nhigh = cdw->ui->flatoffNhighLineEdit->text(); currentData = flatoffData; currentDirName = flatoffDir; memoryDecideDeletableStatus(flatoffData, false); pushBeginMessage(taskBasename, flatoffDir); pushConfigProcessflatoff(); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (flatoffData->myImageList[instData->validChip].isEmpty()) { // flatoffData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(flatoffData); // Release as much memory as maximally necessary float nimg = flatoffData->myImageList[instData->validChip].length() + 1; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed flatoffData->protectMemory(); QString dataDirName = flatoffData->dirName; // copies for thread safety QString dataSubDirName = flatoffData->subDirName; // copies for thread safety QString dataDataType = flatoffData->dataType; doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = flatoffData->myImageList[chip].length() + 1; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); for (auto &it : flatoffData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; it->setupCalibDataInMemory(false, true, false); it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); #pragma omp atomic progress += progressHalfStepSize; } if (flatoffData->myImageList[chip].length() == 0) { flatoffData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+flatoffData->subDirName, "error"); emit criticalReceived(); continue; } flatoffData->combineImagesCalib(chip, combineFlatoff_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); flatoffData->getModeCombineImages(chip); flatoffData->writeCombinedImage(chip); flatoffData->unprotectMemory(chip); if (minimizeMemoryUsage) { for (auto &it : flatoffData->myImageList[chip]) it->freeAll(); } if (!flatoffData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; } if (!successProcessing) { emit progressUpdate(100); return; } flatoffData->reportModeCombineImages(); checkSuccessProcessing(flatoffData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, flatoffDir); } } void Controller::taskInternalProcessflat() { QString flatDir = instructions.split(" ").at(1); QString biasDir = instructions.split(" ").at(2); Data *flatData = getData(DT_FLAT, flatDir); if (flatData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(flatData)) return; Data *biasData = nullptr; QString min = cdw->ui->flatMinLineEdit->text(); QString max = cdw->ui->flatMaxLineEdit->text(); QString nlow = cdw->ui->flatNlowLineEdit->text(); QString nhigh = cdw->ui->flatNhighLineEdit->text(); currentData = flatData; currentDirName = flatDir; pushBeginMessage(taskBasename, flatDir); pushConfigProcessflat(); // flatoff, or bias, or no bias; we call it "bias" for simplicity if (!mainGUI->ui->setupFlatoffLineEdit->text().isEmpty()) { biasData = getData(DT_FLATOFF, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Must rescale flats when combining them flatData->rescaleFlag = true; if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_FLATOFF_NOT_FOUND", part1, ""); successProcessing = false; return; } // Check if all flats have the same filter // TODO: imageInfo.filter is not yet populated at this point! // Actually, as far as I can see it never gets populated at all! /* QStringList filters = flatData->imageInfo.filter; filters.removeDuplicates(); if (filters.length() > 1) { QString filtersJoined = filters.join(' '); QMessageBox::warning(this, tr("Non-identical filters found."), tr("The flat-field directory ")+flatData->dirName+tr(" contains several different filters:\n")+ filtersJoined+"\n"+ tr("You must first remove the unwanted images."), QMessageBox::Ok); return; } QString filter = filters[0]; */ // Retrieve nonlinearity information (checks internally if available, otherwise returns empty list) QList<QVector<float>> nonlinearityCoefficients; if (cdw->ui->nonlinearityCheckBox->isChecked()) { nonlinearityCoefficients = getNonlinearityCoefficients(); } memoryDecideDeletableStatus(flatData, false); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (flatData->myImageList[instData->validChip].isEmpty()) { // flatData->populate(""); // emit populateMemoryView(); // } getNumberOfActiveImages(flatData); // Release as much memory as maximally necessary float nimg = flatData->myImageList[instData->validChip].length() + 2; // The number of images one thread keeps in memory releaseMemory(nimg*instData->storage*maxExternalThreads, 1, "calibrator"); // Protect the rest, will be unprotected as needed flatData->protectMemory(); QString dataDirName = flatData->dirName; // copies for thread safety QString dataSubDirName = flatData->subDirName; // copies for thread safety QString dataDataType = flatData->dataType; QString biasDataType; if (biasData != nullptr) biasDataType = biasData->dataType; if (biasData != nullptr) biasData->protectMemory(); doDataFitInRAM(nimg*instData->numUsedChips, instData->storage); // Loop over all chips #pragma omp parallel for num_threads(maxExternalThreads) firstprivate(nlow, nhigh, min, max, dataDirName, dataSubDirName) for (int chip=0; chip<instData->numChips; ++chip) { if (abortProcess || !successProcessing || instData->badChips.contains(chip)) continue; float nimg = flatData->myImageList[chip].length() + 2; // The number of images we must keep in memory releaseMemory(nimg*instData->storage, maxExternalThreads, "calibrator"); QString message = ""; if (biasData != nullptr) { biasData->loadCombinedImage(chip); message = biasData->subDirName; } for (auto &it : flatData->myImageList[chip]) { if (abortProcess) break; if (!it->successProcessing) continue; if (verbosity >= 0 && !message.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message+"_"+QString::number(chip+1)+".fits", "image"); // careful with the booleans, they make sure the data is correctly reread from disk or memory if task is repeated it->setupCalibDataInMemory(true, true, true); // read from backupL1, if not then from disk. Makes backup copy if not yet done it->checkCorrectMaskSize(instData); it->setModeFlag(min, max); // Must set mode flags before subtracting dark component (flatoffs can have really high levels in NIR data) if (biasData != nullptr && biasData->successProcessing) { // cannot pass nullptr to subtractBias() // it->subtractBias(ref, biasDataType); it->subtractBias(biasData->combinedImage[chip], biasDataType); // it->subtractBias(biasData->combinedImage[chip]->dataCurrent, biasDataType); it->skyValue -= biasData->combinedImage[chip]->skyValue; it->saturationValue -= biasData->combinedImage[chip]->skyValue; } // it->getMode(true); // it->setModeFlag(min, max); if (!it->successProcessing) flatData->successProcessing = false; // does not need to be threadsafe # pragma omp atomic progress += progressHalfStepSize; } if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData->myImageList[chip].length() == 0) { flatData->successProcessing = false; successProcessing = false; emit messageAvailable("Could not find data for chip "+QString::number(chip+1)+ " in "+flatData->subDirName, "error"); emit criticalReceived(); continue; } flatData->combineImagesCalib(chip, combineFlat_ptr, nlow, nhigh, dataDirName, dataSubDirName, dataDataType); // Remove Bayer intensity variations within a 2x2 superpixel if (!instData->bayer.isEmpty()) equalizeBayerFlat(flatData->combinedImage[chip]); flatData->getModeCombineImages(chip); // Individual images may be released; must keep master calib for further below flatData->memorySetDeletable(chip, "dataCurrent", true); for (auto &it : flatData->myImageList[chip]) it->freeData("dataCurrent"); // Bias subtracted pixels, not needed anymore flatData->memorySetDeletable(chip, "dataBackupL1", true); if (minimizeMemoryUsage) { for (auto &it : flatData->myImageList[chip]) it->freeAll(); if (biasData != nullptr) biasData->combinedImage[chip]->freeAll(); } if (!flatData->successProcessing) successProcessing = false; #pragma omp atomic progress += progressCombinedStepSize; // Apply illumination correction (if available, e.g. for DECam; does nothing if not available) // TODO: can be uncommented once the filter is known (see commented block above) // flatData->combinedImage[chip]->illuminationCorrection(chip, thelidir, instData->name, filter); } if (!successProcessing) { emit progressUpdate(100); return; } // Obtain gain normalizations. Must be done once all images have been combined. flatData->getGainNormalization(); // Normalize flats to one. Gain corrections are stored in member variable for later use #pragma omp parallel for num_threads(maxExternalThreads) for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; flatData->combinedImage[chip]->normalizeFlat(); flatData->combinedImage[chip]->applyMask(); flatData->writeCombinedImage(chip); flatData->unprotectMemory(chip); } flatData->reportModeCombineImages(); checkSuccessProcessing(flatData); satisfyMaxMemorySetting(); if (successProcessing) { emit progressUpdate(100); // pushEndMessage(taskBasename, flatDir); } } void Controller::taskInternalProcessscience() { QString scienceDir = instructions.split(" ").at(1); QString biasDir = instructions.split(" ").at(2); QString flatDir = instructions.split(" ").at(3); QString scienceMode = instructions.split(" ").at(4); Data *scienceData; if (scienceMode == "theli_DT_SCIENCE") scienceData = getData(DT_SCIENCE, scienceDir); else if (scienceMode == "theli_DT_SKY") scienceData = getData(DT_SKY, scienceDir); else if (scienceMode == "theli_DT_STANDARD") scienceData = getData(DT_STANDARD, scienceDir); else { return; } if (scienceData == nullptr) return; // Error triggered by getData(); if (!testResetDesire(scienceData)) return; Data *biasData = nullptr; // Can also point to a dark Data *flatData = nullptr; currentData = scienceData; currentDirName = scienceDir; pushBeginMessage(taskBasename, scienceDir); // Link with the correct bias data, if any; dark preferred over bias // I have to select dark / bias again even though it is done in tasks.cc already if (!mainGUI->ui->setupDarkLineEdit->text().isEmpty()) { biasData = getData(DT_DARK, biasDir); } else if (!mainGUI->ui->setupBiasLineEdit->text().isEmpty()) { biasData = getData(DT_BIAS, biasDir); } // Same for the flat if (!mainGUI->ui->setupFlatLineEdit->text().isEmpty()) { flatData = getData(DT_FLAT, flatDir); } if (biasData == nullptr && flatData == nullptr) { emit messageAvailable("No Bias / Dark or Flat calibrators defined. Nothing will be done.", "warning"); return; } // Check if calib data exist (at least chip 1) if (biasData != nullptr && !biasData->hasAllMasterCalibs) { QString part1 = biasData->dirName+"/"+biasData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_BIAS_NOT_FOUND", part1, ""); successProcessing = false; return; } if (flatData != nullptr && !flatData->hasAllMasterCalibs) { QString part1 = flatData->dirName+"/"+flatData->subDirName+"_*.fits\n"; emit showMessageBox("Controller::MASTER_FLAT_NOT_FOUND", part1, ""); successProcessing = false; return; } memoryDecideDeletableStatus(scienceData, false); // TODO: The following line is needed only as long as we are handling splitting of raw data by scripts. // if (scienceData->myImageList[instData->validChip].isEmpty()) { // scienceData->populate(""); // emit populateMemoryView(); // } // Loop over all chips backupDirName = scienceData->processingStatus->getStatusString() + "_IMAGES"; bool success = scienceData->checkTaskRepeatStatus(taskBasename); if (!success) return; getNumberOfActiveImages(scienceData); scienceData->bayerList.clear(); scienceData->bayerList.resize(instData->numChips); QList<MyImage*> allMyImages; long numMyImages = makeListofAllImages(allMyImages, scienceData); QVector<long> numProcessedImages; numProcessedImages.fill(0, instData->numChips); // Release as much memory as maximally necessary float nimg = 0; if (instData->bayer.isEmpty()) nimg = 4; // old, new, bias, flat else nimg = 6; // old, 3 new, bias, flat releaseMemory(nimg*instData->storage*maxCPU, 1); // Protect the rest, will be unprotected as needed scienceData->protectMemory(); if (biasData != nullptr) biasData->protectMemory(); if (flatData != nullptr) flatData->protectMemory(); QString dataDirName = scienceData->dirName; // copies for thread safety QString biasDataType; if (biasData != nullptr) biasDataType = biasData->dataType; // get rid of bad detectors, should they still be here for (int chip=0; chip<instData->numChips; ++chip) { if (!instData->badChips.contains(chip)) continue; // skip good detectors for (auto &it : scienceData->myImageList[chip]) { if (it->imageOnDrive) { // delete FITS file for bad detectors (if still present after splitting) so they cannot interfere deleteFile(it->baseName+".fits", it->path); it->imageOnDrive = false; it->activeState = MyImage::DELETED; } } } if (instData->bayer.isEmpty()) doDataFitInRAM(numMyImages*instData->numUsedChips, instData->storage); else { scienceData->currentlyDebayering = true; doDataFitInRAM(4*numMyImages*instData->numUsedChips, instData->storage); } if (instData->bayer.isEmpty()) { QStringList filters; for (auto &it : allMyImages) { filters.append(it->filter); } filters.removeDuplicates(); if (filters.length() > 1) { QString filtersJoined = filters.join(", "); emit messageAvailable("Files with different FILTER keywords found in "+scienceData->dirName+" :", "error"); emit messageAvailable(filtersJoined, "error"); emit warningReceived(); return; } } // Must keep track of memory consumption scienceData->bayerList.clear(); scienceData->bayerList.resize(instData->numChips); #pragma omp parallel for num_threads(maxCPU) firstprivate(dataDirName, biasDataType) for (int k=0; k<numMyImages; ++k) { if (abortProcess || !successProcessing) continue; auto &it = allMyImages[k]; int chip = it->chipNumber - 1; if (!it->successProcessing) continue; if (it->activeState != MyImage::ACTIVE) continue; if (instData->badChips.contains(chip)) continue; // redundant. Image not even in allMyImages[k]; releaseMemory(nimg*instData->storage, maxCPU); // Don't remember why we need a lock here. I think it had to do with the headers. Will crash otherwise // TODO: probably not needed anymore with latest memory scheme QString message; // #pragma omp critical // { if (biasData != nullptr) { biasData->loadCombinedImage(chip); // skipped if already in memory message.append(biasData->subDirName); } if (flatData != nullptr) { flatData->loadCombinedImage(chip); // skipped if already in memory if (message.isEmpty()) message.append(flatData->subDirName); else message.append(" and " + flatData->subDirName); } // } if (verbosity >= 0) { if (!message.isEmpty() && instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message, "image"); if (!message.isEmpty() && !instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Correcting with "+message+", debayering", "image"); if (message.isEmpty() && !instData->bayer.isEmpty()) emit messageAvailable(it->chipName + " : Debayering", "image"); } it->processingStatus->Processscience = false; it->setupData(scienceData->isTaskRepeated, true, false, backupDirName); it->checkCorrectMaskSize(instData); if (!it->successProcessing) { abortProcess = true; continue; } // TODO: check if we can just pass the data structure and chip number, // and test internally for nullptr and 'successProcessing'. // Then the "if" could go away if (biasData != nullptr && biasData->successProcessing) { it->subtractBias(biasData->combinedImage[chip], biasDataType); } if (flatData != nullptr && flatData->successProcessing) { it->divideFlat(flatData->combinedImage[chip]); } it->bitpix = -32; // so that mode calculations later on use the right algorithm // Without Bayer pattern if (instData->bayer.isEmpty()) { it->getMode(true); it->applyMask(); it->backupOrigHeader(chip); // Write out the zero order solution (before everything is kept in memory). This requires a FITS file updateImageAndData(it, scienceData); if (alwaysStoreData) { it->writeImage(); it->unprotectMemory(); if (minimizeMemoryUsage) { it->freeAll(); } } } else { // Create 3 new MyImages for R, G, and B MyImage *debayerB = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); MyImage *debayerG = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); MyImage *debayerR = new MyImage(dataDirName, it->baseName, "P", chip+1, mask->globalMask[chip], &verbosity); debayer(chip, it, debayerB, debayerG, debayerR); it->unprotectMemory(); it->freeAll(); #pragma omp critical { // The order in which we insert the images here is important for data::writeGlobalWeights()! scienceData->bayerList[chip] << debayerB << debayerG << debayerR; } QList<MyImage*> list; // Contains the current 3 debayered images list << debayerB << debayerG << debayerR; for (auto &it_deb: list) { if (abortProcess) break; connect(it_deb, &MyImage::modelUpdateNeeded, scienceData, &Data::modelUpdateReceiver); connect(it_deb, &MyImage::critical, this, &Controller::criticalReceived); connect(it_deb, &MyImage::warning, this, &Controller::warningReceived); connect(it_deb, &MyImage::messageAvailable, this, &Controller::messageAvailableReceived); connect(it_deb, &MyImage::setMemoryLock, this, &Controller::setMemoryLockReceived, Qt::DirectConnection); it_deb->getMode(true); it_deb->applyMask(); it_deb->backupOrigHeader(chip); it_deb->imageInMemory = true; it_deb->backupL1InMemory = true; it_deb->processingStatus->HDUreformat = true; updateImageAndData(it_deb, scienceData); // Must provide filter string explicitly (and therefore also the full path and file name. // Always store debayered images // it->writeImageDebayer(it->path + "/" + it->chipName + "PA.fits", it->filter, it->exptime, it->mjdobs); it_deb->writeImageDebayer(); it_deb->unprotectMemory(); if (minimizeMemoryUsage) { it_deb->freeAll(); } } } #pragma omp atomic progress += progressStepSize; ++numProcessedImages[chip]; if ((minimizeMemoryUsage && instData->numChips > 1) || numProcessedImages[chip] == numMyImages/instData->numUsedChips) { // all images of this chip have been processed, and the calib data can be set deletable if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); } } // Clear memory from pre-debayered data if (!instData->bayer.isEmpty()) { for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; for (auto &it : scienceData->myImageList[chip]) { it->freeAll(); } } } for (int chip=0; chip<instData->numChips; ++chip) { if (instData->badChips.contains(chip)) continue; // Update image list; remove bayer images, insert debayered images if (!instData->bayer.isEmpty()) { scienceData->repopulate(chip, scienceData->bayerList[chip]); emit populateMemoryView(); } /* if (scienceData->successProcessing) { for (auto &it : scienceData->myImageList[chip]) { // it->makeMemoryBackup(); // qDebug() << "taskInternalProcessscience():" << scienceData->successProcessing << instData->bayer; if (instData->bayer != "Y") it->makeDriveBackup("P_IMAGES", statusOld); // scienceData->memorySetDeletable(chip, "dataBackupL1", true); } } */ // Double tapping ... if (biasData != nullptr) biasData->unprotectMemory(chip); if (flatData != nullptr) flatData->unprotectMemory(chip); if (minimizeMemoryUsage) { if (biasData != nullptr) biasData->releaseAllMemory(); if (flatData != nullptr) flatData->releaseAllMemory(); } } if (!instData->bayer.isEmpty()) scienceData->currentlyDebayering = false; scienceData->bayerList.clear(); checkSuccessProcessing(scienceData); satisfyMaxMemorySetting(); if (successProcessing) { scienceData->processingStatus->Processscience = true; scienceData->processingStatus->writeToDrive(); scienceData->transferBackupInfo(); scienceData->emitStatusChanged(); emit addBackupDirToMemoryviewer(scienceDir); emit progressUpdate(100); emit refreshMemoryViewer(); // Update TableView header // pushEndMessage(taskBasename, scienceDir); } }
34,817
C++
.cc
682
42.98827
168
0.657861
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,479
processingSplitter.cc
schirmermischa_THELI/src/processingInternal/processingSplitter.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "controller.h" #include "../mainwindow.h" #include "../tools/tools.h" #include "../tools/splitter.h" #include "ui_confdockwidget.h" #include "fitsio.h" #include <QMetaObject> #include <QVector> #include <QStringList> #include <QProgressBar> void Controller::taskInternalHDUreformat() { if (!successProcessing) return; QString dataDir = instructions.split(" ").at(1); currentDirName = dataDir; Data *data = getDataAll(dataDir); if (data == nullptr) return; // Error triggered by getDataAll(); data->numImages = 0; pushBeginMessage(taskBasename, dataDir); pushConfigHDUreformat(); // Obtain a list of files in this directory, including non-FITS files QString path = mainDirName + "/" + dataDir; QDir dir(path); QStringList filter; filter << "*.*"; QStringList files = dir.entryList(filter, QDir::Files); numActiveImages = files.length(); progressStepSize = 100./(float(numActiveImages) * instData->numChips); progress = 0.; // Saturation value float userSaturationValue = 0.; if (!cdw->ui->saturationLineEdit->text().isEmpty()) { userSaturationValue = cdw->ui->saturationLineEdit->text().toFloat(); } // Retrieve nonlinearity information (checks internally if available, otherwise returns empty list) QList<QVector<float>> nonlinearityCoefficients; if (cdw->ui->nonlinearityCheckBox->isChecked()) { nonlinearityCoefficients = getNonlinearityCoefficients(); } // DUMMY keywords, and others needed later-on QStringList dummyKeys; QString newCard; newCard = "FWHM = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); newCard = "ELLIP = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); newCard = "RZP = -1.0"; newCard.resize(80, ' '); dummyKeys.append(newCard); for (int i=0; i<20; ++i) { QString newCard = "DUMMY"+QString::number(i+1); newCard.resize(8, ' '); newCard.append("= 0.0 / Placeholder card"); newCard.resize(80, ' '); dummyKeys.append(newCard); } QString dataType = data->dataType; // Stop memory bar. Updated internally because data classes are not yet available // Must use signals instead, timer lives in a different thread // memTimer->stop(); float dateObsIncrementor = 0; bool commaDetected = false; // Loop over all chips #pragma omp parallel for num_threads(maxCPU) firstprivate(mainDirName, dataDir, dummyKeys, nonlinearityCoefficients, headerDictionary, filterDictionary, dataType) for (int i=0; i<numActiveImages; ++i) { if (!successProcessing) continue; if (userStop || userKill || abortProcess) continue; // Only place we do it this way, because Data class is not yet instantiated // Setup the splitter class for the current file QString fileName = files.at(i); Splitter *splitter = new Splitter(*instData, mask, altMask, data, dataType, cdw, mainDirName, dataDir, fileName, &verbosity); splitter->headerDictionary = headerDictionary; splitter->filterDictionary = filterDictionary; splitter->instrumentDictionary = instrumentDictionary; splitter->dummyKeys = dummyKeys; splitter->combineOverscan_ptr = combineOverscan_ptr; // set by MainWindow::updateControllerFunctors() splitter->nonlinearityCoefficients = nonlinearityCoefficients; splitter->progressStepSize = progressStepSize; splitter->progressLock = &progressLock; splitter->genericLock = &genericLock; splitter->progress = &progress; splitter->dateObsIncrementor = &dateObsIncrementor; splitter->userSaturationValue = userSaturationValue; splitter->compileNumericKeys(); connect(splitter, &Splitter::messageAvailable, this, &Controller::messageAvailableReceived); connect(splitter, &Splitter::critical, this, &Controller::criticalReceived); connect(splitter, &Splitter::warning, this, &Controller::warningReceived); connect(splitter, &Splitter::showMessageBox, this, &Controller::showMessageBoxReceived); // Extract images. This also handles all low-level pixel processing. splitter->determineFileFormat(); splitter->extractImages(); if (splitter->commaDetected) commaDetected = true; if (!splitter->successProcessing) successProcessing = false; delete splitter; // Hogging lots of memory otherwise! splitter = nullptr; // splitter handles the progress counter // No memory management needed, splitter simply runs out of scope } checkSuccessProcessing(data); if (verbosity > 1 && commaDetected) { emit messageAvailable("Decimal commas found in raw data, converted to decimal dots in output.", "warning"); emit warningReceived(); } if (successProcessing) { uniformMJDOBS(dir); // rename file and update MJDOBS for a few specific instruments, only if (!updateDataDirs(data)) { // Some instruments need to split the original data dir into several more, e.g. GROND and LIRIS_POL finalizeSplitter(data); } emit progressUpdate(100); } // Restart memory bar // memTimer->start(1000); } void Controller::finalizeSplitter(Data *data) { data->processingStatus->HDUreformat = true; data->processingStatus->writeToDrive(); if (!data->dataInitialized) { data->dataInitialized = true; data->populate("P"); } for (int chip=0; chip<instData->numChips; ++chip) { for (auto &it : data->myImageList[chip]) { it->processingStatus->HDUreformat = true; } } data->emitStatusChanged(); emit populateMemoryView(); } // Multi-chip cameras must have uniform MJD-OBS, otherwise "exposures" cannot be identified unambiguously and scamp catalogs cannot be built // The following instruments do not have this void Controller::uniformMJDOBS(QDir &dir) { if (instData->name == "VIMOS@VLT" // VIMOS has no unique DATE-OBS || instData->name.contains("MOIRCS")) { // MOIRCS has no unique DATE-OBS QString path = dir.absolutePath(); // Look up MJD-OBS etc in the images of chip 1 QStringList filter = {instData->shortName+"*_1P.fits"}; dir.setNameFilters(filter); dir.setSorting(QDir::Name); QStringList fileNames = dir.entryList(); char filterChip1[80]; char dateObsChip1[80]; double mjdObsChip1 = 0.; for (auto &fileName : fileNames) { QFileInfo fi(path+"/"+fileName); QString baseName = fi.completeBaseName(); QString rootName = fileName.remove("_1P.fits"); // Extract DATE-OBS and MJD-OBS from chip 1 fitsfile *fptr; int status = 0; QString completeName = path+"/"+fileName+"_1P.fits"; fits_open_file(&fptr, completeName.toUtf8().data(), READWRITE, &status); fits_read_key_str(fptr, "DATE-OBS", dateObsChip1, nullptr, &status); fits_read_key_str(fptr, "FILTER", filterChip1, nullptr, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdObsChip1, nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); for (int i=1; i<=instData->numChips; ++i) { fitsfile *fptr; int status = 0; QString completeName = path+"/"+rootName+"_"+QString::number(i)+"P.fits"; fits_open_file(&fptr, completeName.toUtf8().data(), READWRITE, &status); fits_update_key_str(fptr, "DATE-OBS", dateObsChip1, nullptr, &status); fits_update_key_dbl(fptr, "MJD-OBS", mjdObsChip1, -13, nullptr, &status); // the '-' enforces floating point notation over exponential notation fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Rename image file to THELI standard QString dateObsString(dateObsChip1); QString filterString(filterChip1); QFile file(path+"/"+fileName); file.rename(path+"/"+instData->shortName+"."+filterString+"."+dateObsString+"_"+QString::number(i)+"P.fits"); } } } } bool Controller::updateDataDirs(Data *data) { bool updateDataDirDone = false; QLineEdit *le = nullptr; QString newDirs = ""; QString d = data->subDirName; // Erase and update the data tree LineEdits if (instData->name == "LIRIS_POL@WHT") { newDirs = d+"_PA000 "; newDirs.append(d+"_PA045 "); newDirs.append(d+"_PA090 "); newDirs.append(d+"_PA135"); le = getDataTreeLineEdit(data); } if (instData->name == "GROND_OPT@MPGESO") { newDirs = d+"_g "; newDirs.append(d+"_r "); newDirs.append(d+"_i "); newDirs.append(d+"_z "); le = getDataTreeLineEdit(data); } if (instData->name == "GROND_NIR@MPGESO") { newDirs = d+"_J "; newDirs.append(d+"_H "); newDirs.append(d+"_K"); le = getDataTreeLineEdit(data); } if (instData->name == "PISCO@LCO") { newDirs = d+"_g "; newDirs.append(d+"_r "); newDirs.append(d+"_i "); newDirs.append(d+"_z "); le = getDataTreeLineEdit(data); } if (le != nullptr) { le->clear(); le->setText(newDirs); if (!mainGUI->checkPathsLineEdit(le)) { le->clear(); return false; // return if some data do not exist (e.g. optical GROND might not have darks, but NIR does) } dataTreeUpdateOngoing = true; omp_set_lock(&memoryLock); // emit clearMemoryView(); // Manipulate sobject in different thread despite just emitting a signal. Strange mainDirName = mainGUI->ui->setupMainLineEdit->text(); recurseCounter = 0; QList<Data*> *DT_x; // = new QList<Data*>(); if (data->dataType == "BIAS") DT_x = &DT_BIAS; else if (data->dataType == "DARK") DT_x = &DT_DARK; else if (data->dataType == "FLATOFF") DT_x = &DT_FLATOFF; else if (data->dataType == "FLAT") DT_x = &DT_FLAT; else if (data->dataType == "SCIENCE") DT_x = &DT_SCIENCE; else if (data->dataType == "SKY") DT_x = &DT_SKY; else { // data->dataType == "STD") DT_x = &DT_STANDARD; } updateMasterList(); emit populateMemoryView(); omp_unset_lock(&memoryLock); dataTreeUpdateOngoing = false; for (auto &data : *DT_x) { finalizeSplitter(data); } updateDataDirDone = true; // delete DT_x; } return updateDataDirDone; } QLineEdit* Controller::getDataTreeLineEdit(Data *data) { QLineEdit *le = nullptr; if (data->dataType == "BIAS") le = mainGUI->ui->setupBiasLineEdit; else if (data->dataType == "DARK") le = mainGUI->ui->setupDarkLineEdit; else if (data->dataType == "FLATOFF") le = mainGUI->ui->setupFlatoffLineEdit; else if (data->dataType == "FLAT") le = mainGUI->ui->setupFlatLineEdit; else if (data->dataType == "SCIENCE") le = mainGUI->ui->setupScienceLineEdit; else if (data->dataType == "SKY") le = mainGUI->ui->setupSkyLineEdit; else if (data->dataType == "STD") le = mainGUI->ui->setupStandardLineEdit; else { // nothing to be done } return le; } // copied from MainWindow void Controller::resetAltInstrumentData() { altInstData.numChips = 1; altInstData.numUsedChips = 1; altInstData.name = ""; altInstData.shortName = ""; altInstData.nameFullPath = ""; altInstData.obslat = 0.; altInstData.obslon = 0.; altInstData.bayer = ""; altInstData.type = "OPT"; altInstData.pixscale = 1.0; // in arcsec // altInstData.gain = 1.0; altInstData.radius = 0.1; // exposure coverage radius in degrees altInstData.storage = 0; // MB used for a single image altInstData.storageExposure = 0.; // MB used for the entire (multi-chip) exposure altInstData.overscan_xmin.clear(); altInstData.overscan_xmax.clear(); altInstData.overscan_ymin.clear(); altInstData.overscan_ymax.clear(); altInstData.cutx.clear(); altInstData.cuty.clear(); altInstData.sizex.clear(); altInstData.sizey.clear(); altInstData.crpix1.clear(); altInstData.crpix2.clear(); } // copied and modified (shortened) from MainWindow, to handle the two GROND detector types void Controller::initAltInstrumentData(QString instrumentNameFullPath) { resetAltInstrumentData(); QFile altInstDataFile(instrumentNameFullPath); altInstDataFile.setFileName(instrumentNameFullPath); altInstData.nameFullPath = instrumentNameFullPath; // read the instrument specific data if( !altInstDataFile.open(QIODevice::ReadOnly)) { emit messageAvailable("Controller::initAltInstrumentData(): "+instrumentNameFullPath+" "+altInstDataFile.errorString(), "error"); return; } bool bayerFound = false; QTextStream in(&(altInstDataFile)); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty() || line.contains("#")) continue; // scalars if (line.contains("INSTRUMENT=")) altInstData.name = line.split("=")[1]; if (line.contains("INSTSHORT=")) altInstData.shortName = line.split("=")[1]; if (line.contains("NCHIPS=")) altInstData.numChips = line.split("=")[1].toInt(); if (line.contains("TYPE=")) altInstData.type = line.split("=")[1]; if (line.contains("BAYER=")) { // BAYER is not mandatory; if not found, we must set it to blank altInstData.bayer = line.split("=")[1]; bayerFound = true; } if (line.contains("OBSLAT=")) altInstData.obslat = line.split("=")[1].toFloat(); if (line.contains("OBSLONG=")) altInstData.obslon = line.split("=")[1].toFloat(); if (line.contains("PIXSCALE=")) altInstData.pixscale = line.split("=")[1].toFloat(); // if (line.contains("GAIN=")) altInstData.gain = line.split("=")[1].toFloat(); // vectors if (line.contains("OVSCANX1=") || line.contains("OVSCANX2=") || line.contains("OVSCANY1=") || line.contains("OVSCANY2=") || line.contains("CUTX=") || line.contains("CUTY=") || line.contains("SIZEX=") || line.contains("SIZEY=") || line.contains("REFPIXX=") || line.contains("REFPIXY=")) { line = line.replace('=',' ').replace(')',' ').replace(')',""); line = line.simplified(); QStringList values = line.split(" "); QVector<int> vecData; // NOTE: already subtracting -1 to make it conform with C++ indexing // (apart from SIZEX/Y, which is the actual number of pixels per axis and not a coordinate) for (int i=2; i<values.length(); i=i+2) { if (line.contains("SIZE")) vecData.push_back(values.at(i).toInt()); else vecData.push_back(values.at(i).toInt() - 1); // vecData.push_back(values.at(i).toInt() - 1); } if (line.contains("OVSCANX1")) altInstData.overscan_xmin = vecData; if (line.contains("OVSCANX2")) altInstData.overscan_xmax = vecData; if (line.contains("OVSCANY1")) altInstData.overscan_ymin = vecData; if (line.contains("OVSCANY2")) altInstData.overscan_ymax = vecData; if (line.contains("CUTX")) altInstData.cutx = vecData; if (line.contains("CUTY")) altInstData.cuty = vecData; if (line.contains("SIZEX")) altInstData.sizex = vecData; if (line.contains("SIZEY")) altInstData.sizey = vecData; if (line.contains("REFPIXX")) altInstData.crpix1 = vecData; if (line.contains("REFPIXY")) altInstData.crpix2 = vecData; } } if (!bayerFound) altInstData.bayer = ""; // Backwards compatibility: if (altInstData.type.isEmpty()) altInstData.type = "OPT"; QString shortstring = altInstData.name.split('@').at(0); if (altInstData.shortName.isEmpty()) altInstData.shortName = shortstring; altInstDataFile.close(); // The overscan needs special treatment: // if it is consistently -1, or the string wasn't found, // then the vector must be empty testOverscan(altInstData.overscan_xmin); testOverscan(altInstData.overscan_xmax); testOverscan(altInstData.overscan_ymin); testOverscan(altInstData.overscan_ymax); } // copied from MainWindow void Controller::testOverscan(QVector<int> &overscan) { if (overscan.isEmpty()) return; // if the overscan is consistently -1, then the vector must be empty bool flag = true; for (auto &it : overscan) { if (it != -1) { flag = false; break; } } if (flag) overscan.clear(); } // Runs outside the processing thread, but kept here for consistency void Controller::provideAlternativeMask() { // If the NIR detector config is chosen for GROND, then we must create separate masks for the optical data. // Not the other way round, as the masking for the NIR data is handled elsewhere. if (instData->name == "GROND_NIR@MPGESO") { initAltInstrumentData(instrument_dir+"/GROND_OPT@MPGESO.ini"); altMask = new Mask(&altInstData, this); } }
18,395
C++
.cc
406
37.849754
162
0.640981
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,480
scampreadme.cc
schirmermischa_THELI/src/readmes/scampreadme.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "scampreadme.h" #include "ui_scampreadme.h" ScampReadme::ScampReadme(QWidget *parent) : QDialog(parent), ui(new Ui::ScampReadme) { ui->setupUi(this); } ScampReadme::~ScampReadme() { delete ui; }
900
C++
.cc
26
32.730769
75
0.787774
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,481
imstatsreadme.cc
schirmermischa_THELI/src/readmes/imstatsreadme.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "imstatsreadme.h" #include "ui_imstatsreadme.h" ImstatsReadme::ImstatsReadme(QWidget *parent) : QDialog(parent), ui(new Ui::ImstatsReadme) { ui->setupUi(this); } ImstatsReadme::~ImstatsReadme() { delete ui; }
914
C++
.cc
26
33.269231
75
0.791146
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,484
acknowledging.cc
schirmermischa_THELI/src/readmes/acknowledging.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "acknowledging.h" #include "ui_acknowledging.h" Acknowledging::Acknowledging(QWidget *parent) : QDialog(parent), ui(new Ui::Acknowledging) { ui->setupUi(this); } Acknowledging::~Acknowledging() { delete ui; }
914
C++
.cc
26
33.269231
75
0.791146
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,485
license.cc
schirmermischa_THELI/src/readmes/license.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "license.h" #include "ui_license.h" License::License(QWidget *parent) : QDialog(parent), ui(new Ui::License) { ui->setupUi(this); } License::~License() { delete ui; }
872
C++
.cc
26
31.653846
75
0.780691
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
1,534,486
swarpreadme.cc
schirmermischa_THELI/src/readmes/swarpreadme.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "swarpreadme.h" #include "ui_swarpreadme.h" SwarpReadme::SwarpReadme(long openfiles, long maxopenfiles, QWidget *parent) : QDialog(parent), ui(new Ui::SwarpReadme) { ui->setupUi(this); openFiles = openfiles; maxOpenFiles = maxopenfiles; ui->maxOpenFileLineEdit->setText(QString::number(maxOpenFiles)); ui->openFileLineEdit->setText(QString::number(openFiles)); } SwarpReadme::~SwarpReadme() { delete ui; }
1,129
C++
.cc
30
35.266667
78
0.783486
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,487
datamodel.cc
schirmermischa_THELI/src/datamodel/datamodel.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "datamodel.h" #include <QDebug> #include <QString> #include "../myimage/myimage.h" DataModel::DataModel(Data *someData, QObject *parent) : QAbstractTableModel(parent) { myData = someData; if (myData->dataType == "BIAS" || myData->dataType == "DARK" || myData->dataType == "FLATOFF" || myData->dataType == "FLAT") { modelType = "calib"; } else { if (myData->dataType == "GLOBALWEIGHT") modelType = "globalweight"; else modelType = "science"; } // Create the image list updateImageList(); connect(myData, &Data::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); connect(myData, &Data::globalModelUpdateNeeded, this, &DataModel::updateImageList); connect(myData, &Data::updateModelHeaderLine, this, &DataModel::updateHeaderLineGlobal); } DataModel::DataModel(Data *someData, QString weight, QObject *parent) : QAbstractTableModel(parent) { myData = someData; modelType = weight; // must be "weight" // Create the image list updateImageList(); connect(myData, &Data::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); } // Empty data model (displayed when switching projects) DataModel::DataModel(QObject *parent) : QAbstractTableModel(parent) { myData = nullptr; imageList.clear(); } void DataModel::updateImageList() { if (myData == nullptr) return; imageList.clear(); // Master calibrators if (modelType == "calib" && !myData->combinedImage.isEmpty()) { for (auto &image: myData->combinedImage) { if (image == nullptr) break; if (!image->baseName.isEmpty()) { imageList.append(image); } } } // Individual images if (!myData->myImageList.isEmpty()) { for (int chip=0; chip<myData->instData->numChips; ++chip) { // Exposure list if (chip == 0) { for (auto &image: myData->myImageList[chip]) { exposureList.append(image); } } // All images list for (auto &image: myData->myImageList[chip]) { imageList.append(image); } } } } QVariant DataModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QString("Image"); case 1: return QString("Active"); case 2: return QString("On\nDrive"); case 3: { QString add = ""; if (myData != nullptr) add = myData->processingStatus->statusString; return QString("L0 in\nRAM\n("+add+")"); } case 4: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL1; return QString("L1 in\nRAM\n("+add+")"); } case 5: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL2; return QString("L2 in\nRAM\n("+add+")"); } case 6: { QString add = ""; if (myData != nullptr) add = myData->statusBackupL3; return QString("L3 in\nRAM\n("+add+")"); } case 7: return QString("Comment"); } } return QVariant(); } int DataModel::rowCount(const QModelIndex &parent) const { if (parent.isValid() || myData == nullptr) return 0; // Total length is given by the images and master calibration files // Master cals only exist for calibration data, hence the check against nullptr long numMasterCals = myData->numMasterCalibs; // Single exposures long numExposures = 0; if (myData->myImageList.isEmpty()) return numMasterCals; for (int chip=0; chip<myData->instData->numChips; ++chip) { numExposures += myData->myImageList[chip].length(); } return numMasterCals + numExposures; } int DataModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 8; } QVariant DataModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || imageList.isEmpty()) return QVariant(); int row = index.row(); int col = index.column(); if (row >= imageList.length()) { // qDebug() << "DataModel::data(): invalid row index" << row <<", max num images =" << imageList.length(); return QVariant(); } switch (role) { case Qt::DisplayRole: // First column contains the image name. Blanks are added for a little extra space if (modelType == "weight") { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + ".weight "; // Y/N indicators if (col==2) { if (!imageList[row]->weightOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->weightInMemory) return "N"; else return "Y"; } else if (col==4 || col == 5 || col == 6) return "N"; else if (col == 7) return ""; } if (modelType == "globalweight") { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + " "; // Y/N indicators if (col==2) { if (!imageList[row]->imageOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->imageInMemory) return "N"; else return "Y"; } else if (col==4 || col == 5 || col == 6) return "N"; else if (col == 7) return ""; } else { if (col == 0) return imageList[row]->rootName + "_" + QString::number(imageList[row]->chipNumber) + " "; // Y/N indicators if (col==2) { if (!imageList[row]->imageOnDrive) return "N"; else return "Y"; } else if (col==3) { if (!imageList[row]->imageInMemory) return "N"; else return "Y"; } else if (col==4) { if (!imageList[row]->backupL1InMemory) return "N"; else return "Y"; } else if (col==5) { if (!imageList[row]->backupL2InMemory) return "N"; else return "Y"; } else if (col==6) { if (!imageList[row]->backupL3InMemory) return "N"; else return "Y"; } else if (col==7) { if (imageList[row]->activeState == MyImage::ACTIVE) return ""; else if (imageList[row]->activeState == MyImage::INACTIVE) return "Deactivated"; else if (imageList[row]->activeState == MyImage::BADBACK) return "Poor background model"; else if (imageList[row]->activeState == MyImage::BADSTATS) return "Poor data quality"; else if (imageList[row]->activeState == MyImage::NOASTROM) return "No astrometric solution for at least one detector"; else if (imageList[row]->activeState == MyImage::LOWDETECTION) return "Insufficient sources for astrometry"; else if (imageList[row]->activeState == MyImage::DELETED) return "Image not found or deleted"; else return ""; } } break; case Qt::BackgroundRole: // Color coding if (modelType == "weight") { if (col==0) return QBrush(white); if (col==1) return QBrush(turquois); if (col==2) { if (!imageList[row]->weightOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->weightInMemory) return QBrush(orange); else return QBrush(blue); } if (col == 4 || col == 5 || col == 6) return QBrush(orange); } else if (modelType == "globalweight") { if (col==0) return QBrush(white); if (col==1) return QBrush(turquois); if (col==2) { if (!imageList[row]->imageOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->imageInMemory) return QBrush(orange); else return QBrush(blue); } if (col == 4 || col == 5 || col == 6) return QBrush(orange); } else { if (col==0) { if (imageList[row]->activeState != MyImage::ACTIVE) return QBrush(grey); else return QBrush(white); } if (col==1) { if (imageList[row]->activeState != MyImage::ACTIVE) return QBrush(grey); else return QBrush(turquois); } if (col==2) { if (!imageList[row]->imageOnDrive) return QBrush(red); else return QBrush(green); } else if (col==3) { if (!imageList[row]->imageInMemory) return QBrush(orange); else return QBrush(blue); } else if (col==4) { if (!imageList[row]->backupL1InMemory) return QBrush(orange); else return QBrush(blue); } else if (col==5) { if (!imageList[row]->backupL2InMemory) return QBrush(orange); else return QBrush(blue); } else if (col==6) { if (!imageList[row]->backupL3InMemory) return QBrush(orange); else return QBrush(blue); } } break; case Qt::TextAlignmentRole: if (col == 0 || col == 7) return Qt::AlignLeft; else return Qt::AlignCenter; break; case Qt::CheckStateRole: if (modelType == "weight") { if (col == 1) return Qt::Checked; if (col == 2) { if (!imageList[row]->weightOnDrive) return Qt::Unchecked; else return Qt::Checked; } } else if (modelType == "globalweight") { if (col == 1) return Qt::Checked; if (col == 2) { if (!imageList[row]->imageOnDrive) return Qt::Unchecked; else return Qt::Checked; } } else { if (col == 1) { if (imageList[row]->activeState != MyImage::ACTIVE) return Qt::Unchecked; else return Qt::Checked; } if (col == 2) { if (!imageList[row]->imageOnDrive) return Qt::Unchecked; else return Qt::Checked; } } break; } return QVariant(); } Qt::ItemFlags DataModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; // Inherit and append mode Qt::ItemFlags result = QAbstractTableModel::flags(index); if (modelType == "weight" || modelType == "globalweight") { // Toggle active / inactive state (triggers physical move of file on disk) if (index.column() == 1) { result = Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; } // Clicking on an unchecked box will check it (dumps data to disk) if (index.column() == 2) { result = Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; } if (index.column() == 3) result = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; if (index.column() > 3) result = Qt::ItemIsEnabled |Qt::ItemNeverHasChildren; } else { // Toggle active / inactive state (triggers physical move of file on disk) if (index.column() == 1) { result = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemNeverHasChildren; } // Clicking on an unchecked box will check it (dumps data to disk) if (index.column() == 2) { result = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemNeverHasChildren; } if (index.column() > 2) result = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; } return result; } bool DataModel::setData(const QModelIndex & index, const QVariant & value, int role) { if (!index.isValid()) return false; if (modelType == "weight" || modelType == "globalweight") return false; // Activate / deactivate images if (role == Qt::CheckStateRole && index.column() == 1) { // CONFUSING! Example: // The user clicks on a checked 'active' box to deactivate the image. // The 'active' checkbox state e.g. changes from checked to unchecked, // but only THEN this slot is invoked, at which point the checkbox is already unchecked. if ((Qt::CheckState)value.toInt() == Qt::Checked) { // the user clicked an unchecked box, which is now checked, hence we must activate the image // ONLY do this if the deactivated image has the same processing state as the active images! QString imagestatus = imageList[index.row()]->processingStatus->statusString; QString drivestatus = myData->processingStatus->whatIsStatusOnDrive(); if (imagestatus == drivestatus) { imageList[index.row()]->oldState = imageList[index.row()]->activeState; imageList[index.row()]->setActiveState(MyImage::ACTIVE); // Setting this value automatically moves the image on drive accordingly! } else { emit activationWarning(imagestatus, drivestatus); } } else { // the user clicked an checked box, which is now unchecked, hence we must deactivate the image imageList[index.row()]->oldState = imageList[index.row()]->activeState; imageList[index.row()]->setActiveState(MyImage::INACTIVE); // Setting this value automatically moves the image on drive accordingly! } emit dataChanged(index,index); emit activationChanged(); // meant to update image statistics module; has no effect emit refreshMemoryViewer(); return true; } // Force write to drive if (role == Qt::CheckStateRole && index.column() == 2) { if ((Qt::CheckState)value.toInt() == Qt::Checked) { MyImage *it = imageList[index.row()]; if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; } } emit dataChanged(index,index); return true; } return false; } void DataModel::modelUpdateReceiver(QString chipName) { // Find the index of the MyImage that has emitted the original signal QModelIndexList list = match(index(0,0), Qt::DisplayRole, chipName); if (list.isEmpty()) { // An image was removed // Consistency check (required for debayering, which adds images that were not there previously) updateImageList(); return; } // retrieve the indices of the various cells for the current exposure long row = list[0].row(); QModelIndex indexImage = index(row, 0); QModelIndex indexState = index(row, 1); QModelIndex indexDrive = index(row, 2); QModelIndex indexL0 = index(row, 3); QModelIndex indexL1 = index(row, 4); QModelIndex indexL2 = index(row, 5); QModelIndex indexL3 = index(row, 6); // QModelIndex indexComment = index(row, 7); // unused // Update the background colors setData(indexImage, getColorImage(imageList[row]->activeState), Qt::BackgroundRole); setData(indexState, getColorState(imageList[row]->activeState), Qt::BackgroundRole); setData(indexDrive, getColorDrive(imageList[row]->imageOnDrive), Qt::BackgroundRole); setData(indexL0, getColorRAM(imageList[row]->imageInMemory), Qt::BackgroundRole); setData(indexL1, getColorRAM(imageList[row]->backupL1InMemory), Qt::BackgroundRole); setData(indexL2, getColorRAM(imageList[row]->backupL2InMemory), Qt::BackgroundRole); setData(indexL3, getColorRAM(imageList[row]->backupL3InMemory), Qt::BackgroundRole); // Update the Y/N chars setData(indexDrive, getIndicator(imageList[row]->imageOnDrive), Qt::DisplayRole); setData(indexL0, getIndicator(imageList[row]->imageInMemory), Qt::DisplayRole); setData(indexL1, getIndicator(imageList[row]->backupL1InMemory), Qt::DisplayRole); setData(indexL2, getIndicator(imageList[row]->backupL2InMemory), Qt::DisplayRole); setData(indexL3, getIndicator(imageList[row]->backupL3InMemory), Qt::DisplayRole); updateHeaderLine(row); // Inform the view that the model has changed emit dataChanged(indexDrive,indexL3); } void DataModel::updateheaderLineExternal() { updateHeaderLine(0); emit dataChanged(index(0, 0), index(0,5)); } void DataModel::updateHeaderLine(long row) { setHeaderData(3, Qt::Horizontal, "L0 in\nRAM\n("+imageList[row]->processingStatus->statusString+")"); setHeaderData(4, Qt::Horizontal, "L1 in\nRAM\n("+imageList[row]->statusBackupL1+")"); setHeaderData(5, Qt::Horizontal, "L2 in\nRAM\n("+imageList[row]->statusBackupL2+")"); setHeaderData(6, Qt::Horizontal, "L3 in\nRAM\n("+imageList[row]->statusBackupL3+")"); } void DataModel::updateHeaderLineGlobal() { setHeaderData(3, Qt::Horizontal, "L0 in\nRAM\n("+myData->processingStatus->statusString+")"); setHeaderData(4, Qt::Horizontal, "L1 in\nRAM\n("+myData->statusBackupL1+")"); setHeaderData(5, Qt::Horizontal, "L2 in\nRAM\n("+myData->statusBackupL2+")"); setHeaderData(6, Qt::Horizontal, "L3 in\nRAM\n("+myData->statusBackupL3+")"); } void DataModel::beginResetModelReceived() { beginResetModel(); } void DataModel::endResetModelReceived() { endResetModel(); } QColor DataModel::getColorImage(MyImage::active_type state) { if (state == MyImage::ACTIVE) return white; else return grey; } QColor DataModel::getColorState(MyImage::active_type state) { if (state == MyImage::ACTIVE) return turquois; else return grey; } QColor DataModel::getColorDrive(bool flag) { if (flag) return green; else return red; } QColor DataModel::getColorRAM(bool flag) { if (flag) return blue; else return orange; } QString DataModel::getIndicator(bool flag) { if (flag) return "Y"; else return "N"; } // E.g. master calibrations are created bool DataModel::insertRows(int row, int count, const QModelIndex &parent) { beginInsertRows(parent, row, row + count - 1); QVector<bool> dummyMask; dummyMask.clear(); MyImage *newImage = new MyImage("path", "file", "", 1, dummyMask, myData->verbosity); connect(newImage, &MyImage::modelUpdateNeeded, this, &DataModel::modelUpdateReceiver); imageList.insert(row, newImage); endInsertRows(); return true; } bool DataModel::insertColumns(int column, int count, const QModelIndex &parent) { beginInsertColumns(parent, column, column + count - 1); // Nothing to be done endInsertColumns(); return true; } // E.g. input images after they were debayered bool DataModel::removeRows(int row, int count, const QModelIndex &parent) { beginRemoveRows(parent, row, row + count - 1); imageList.removeAt(row); endRemoveRows(); return true; } bool DataModel::removeColumns(int column, int count, const QModelIndex &parent) { beginRemoveColumns(parent, column, column + count - 1); // Nothing to be done endRemoveColumns(); return true; }
20,466
C++
.cc
510
31.723529
146
0.604754
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,488
scampworker.cc
schirmermischa_THELI/src/threading/scampworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "scampworker.h" #include "../functions.h" #include <QProcess> #include <QTest> ScampWorker::ScampWorker(QString command, QString dir, QString shortname, QObject *parent) : Worker(parent) { scampCommand = command; scampDirName = dir; shortname = shortname; } void ScampWorker::runScamp() { // If using QProcess instead of QProcess*, we get a "cannot create child in different thread" error extProcess = new QProcess(); // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &ScampWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &ScampWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(scampDirName); extProcess->start("/bin/sh -c \""+scampCommand+"\""); extProcess->waitForFinished(-1); emit finishedScamp(); emit finished(); delete extProcess; extProcess = nullptr; // stdout and stderr channels are slotted into the monitor's plainTextEdit } /* void ScampWorker::runScamp() { // If using QProcess instead of QProcess*, we get a "cannot create child in different thread" error QProcess extProcess1; // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &ScampWorker::processExternalStdout); connect(&extProcess1, &QProcess::readyReadStandardError, this, &ScampWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess1.setWorkingDirectory(scampDirName); extProcess1.start("/bin/sh -c \""+scampCommand+"\""); extProcess1.waitForFinished(-1); emit finishedScamp(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } */ void ScampWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); } void ScampWorker::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); // have to remove the '\x1B[1A' and '\x1B[1M' escape sequences. QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s\\.\\:\\-\\_/]")); stderr.remove("1A1M "); stderr.remove("1A "); stderr.remove("1M "); // stderr.remove(QRegExp("![^0131m]")); stderr.remove("0131m"); stderr.remove("WARNING: scamp.conf not found using internal defaults"); stderr = stderr.simplified(); stderr.replace(" WARNING: ", "<br>WARNING: "); stderr.replace(" Error: ", "<br>Error: "); stderr.replace("... Matching ", "... <br>Matching "); stderr.replace("detections ", "detections<br>"); stderr.replace("scamp Examining", "scamp<br>Examining"); stderr.replace(" ----- Astrometric stats internal :All detections", "<br>----- Astrometric stats internal: All detections"); stderr.replace(" ----- Astrometric stats external:All detections", "<br>----- Astrometric stats external: All detections"); stderr.replace(" ----- Photometric stats internal:All detections", "<br>----- Photometric stats internal: All detections"); stderr.replace(" ----- Photometric stats external:All detections", "<br>----- Photometric stats external: All detections"); stderr.replace(" Instrument", "<br>Instrument"); stderr.replace(" Grouping fields:", "<br>Grouping fields:"); stderr.replace(" Matching field", "<br>Matching field"); stderr.replace(" Grouping fields on the sky", "<br>Grouping fields on the sky"); stderr.replace(" Group ", "<br>Group "); stderr.replace(" Generating ", "<br>Generating "); // if (!stderr.contains("Matching field") && !stderr.contains("Examining Catalog")) { // stderr.replace(" "+shortName, "<br>"+shortName); // } stderr.replace(" Making mosaic adjustments","<br>Making mosaic adjustments"); stderr.replace("7m instruments pos.angle scale cont. shift cont.0m", "instruments pos.angle scale cont. shift cont."); stderr.replace(" Solving the global astrometry matrix", "<br>Solving the global astrometry matrix"); stderr.replace(" Solving the global photometry matrix", "<br>Solving the global photometry matrix"); stderr.replace(" Initializing the global astrometry matrix", "<br>Initializing the global astrometry matrix"); stderr.replace(" Initializing the global photometry matrix", "<br>Initializing the global photometry matrix"); stderr.replace("instruments epoch center coordinates radius scale","<br>instruments epoch center coordinates radius scale<br>"); stderr.replace(" instrument found for astrometry:", " instrument found for astrometry:<br>"); stderr.replace(" instrument found for photometry:", "<br>instrument found for photometry:<br>"); stderr.replace(" Filling the global astrometry matrix", "<br>Filling the global astrometry matrix"); stderr.replace(" Computing set shifts for field", "<br>Computing set shifts for field"); stderr.replace(" Initializing detection weight factors", "<br>Initializing detection weight factors"); stderr.remove(QRegExp("^1A")); stderr.remove(" 0m "); stderr.remove(" 7m "); if (stderr.contains(" deg ")) emit fieldMatched(); QStringList warnings; warnings << "WARNING: "; warnings << "Not enough matched detections"; warnings << "inaccuracies likely to occur"; QStringList errors; errors << "Error: "; errors << "fatal: division by zero attempted"; errors << "no match with reference catalog"; errors << "Not enough memory"; errors << "buffer overflow detected"; errors << "Could not allocate memory"; errors << "Invalid deprojected coordinates"; errors << "keyword out of range"; errors << "WARNING: Not a positive definite matrix in astrometry solver"; errors << "Segmentation fault"; QString type = "normal"; for (auto &warning : warnings) { if (stderr.contains(warning)) { type = "warning"; break; } } for (auto &error : errors) { if (stderr.contains(error)) { type = "error"; stderr.remove("Error: "); stderr.remove("WARNING: "); stderr.replace("Segmentation fault", "Scamp ended with a segmentation fault."); emit errorFound(); break; } } emit messageAvailable(stderr.simplified(), type); }
7,408
C++
.cc
150
44.626667
147
0.699917
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,489
swarpworker.cc
schirmermischa_THELI/src/threading/swarpworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "swarpworker.h" #include "../functions.h" #include <QProcess> #include <QTest> SwarpWorker::SwarpWorker(QString command, QString dir, QString type, QObject *parent) : Worker(parent) { swarpCommand = command; coaddDirName = dir; swarpType = type; } void SwarpWorker::runSwarp() { extProcess = new QProcess(); // connect(&extProcess, &QProcess::readyReadStandardOutput, this, &Controller::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &SwarpWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(coaddDirName); extProcess->start("/bin/sh -c \""+swarpCommand+"\""); extProcess->waitForFinished(-1); if (swarpType == "swarpPreparation") emit finishedPreparation(); if (swarpType == "swarpResampling") emit finishedResampling(threadID); if (swarpType == "swarpCoaddition") emit finishedCoaddition(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void SwarpWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // Then kill the process that invokes the commandline task extProcess->kill(); emit finished(); } void SwarpWorker::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); // have to remove the '\x1B[1A' and '\x1B[1M' escape sequences. QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s\\.\\:\\-\\_/]")); stderr.remove("1A1M "); stderr.remove("1A "); stderr.remove("1M "); stderr = stderr.simplified(); stderr.replace(" Center:", "<br>Center:"); stderr.replace(" Gain:", "<br>Gain:"); stderr.replace(" Scale:", "<br>Scale:"); stderr.replace(" Background:", "<br>Background:"); stderr.replace(" RMS:", "<br>RMS:"); stderr.replace(" Weight scale:", "<br>Weight scale:"); stderr.replace("... Looking for ", "<br>Looking for "); stderr.replace(" Examining input data ...", "<br>Examining input data"); stderr.replace(" Creating NEW output image ", "<br>Creating NEW output image "); stderr.replace(" Creating NEW weight-map ", "<br>Creating NEW weight-map "); stderr.replace(" ----- SWarp ", "<br>----- SWarp "); stderr.replace(" ------- Output File coadd.fits:", "<br>------- Output File coadd.fits:"); stderr.replace(" Flux scaling astrom/photom:", "<br>Flux scaling astrom/photom:"); stderr.replace(" -------------- File", "<br>-------------- File"); stderr.remove(QRegExp("^1A")); stderr.remove(" 0m "); stderr.remove(" 7m "); QStringList warnings; warnings << "WARNING: Astrometric approximation too inaccurate for this re-projection"; warnings << "Significant inaccuracy likely to occur in projection"; warnings << "inaccuracies likely to occur"; QStringList errors; errors << "Error:"; errors << "FATAL ERROR"; errors << "Null or negative global weighting factor"; errors << "Not enough memory"; errors << "Buffer overflow detected"; errors << "core dumped"; errors << "has flux scale = 0: I will take 1 instead"; errors << "Could not allocate memory"; errors << "set to an unknown keyword"; errors << "Unknown FITS type in fitswrite()"; QString type = "normal"; for (auto &warning : warnings) { if (stderr.contains(warning)) { type = "warning"; break; } } for (auto &error : errors) { if (stderr.contains(error)) { type = "error"; emit errorFound(); break; } } emit messageAvailable(stderr.simplified(), type); }
4,610
C++
.cc
110
37.254545
147
0.674253
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,490
memoryworker.cc
schirmermischa_THELI/src/threading/memoryworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "memoryworker.h" #include "functions.h" #include "../dockwidgets/memoryviewer.h" #include "../processingInternal/data.h" #include "ui_memoryviewer.h" #include "../myimage/myimage.h" #include <omp.h> #include <QObject> #include <QTest> MemoryWorker::MemoryWorker(MemoryViewer *memViewer, QObject *parent) : Worker(parent) { memoryViewer = memViewer; } MemoryWorker::MemoryWorker(Data *datadir, QObject *parent) : Worker(parent) { data = datadir; } /* * Done internally to MyImage by calling setActiveStatus() void MemoryWorker::processActiveStatusChanged() { if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); // Previously active image is now inactive if (myImage->oldState == MyImage::ACTIVE && myImage->activeState == MyImage::INACTIVE) { moveFile(myImage->baseName+".fits", path, path+"/inactive/"); } // Restore inactive images QString inactivePath = path+"/inactive/"; if (myImage->activeState == MyImage::BADSTATS) inactivePath.append("/badStatistics/"); if (myImage->activeState == MyImage::BADBACK) inactivePath.append("/badBackground/"); if (myImage->activeState != MyImage::ACTIVE && myImage->activeState != MyImage::DELETED) { moveFile(myImage->baseName+".fits", inactivePath, path); } emit finished(); } */ void MemoryWorker::MemoryViewerDumpImagesToDrive() { emit resetProgressBar(); if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); memoryViewer->ui->downloadToolButton->setText("Wait "); memoryViewer->ui->downloadToolButton->setDisabled(true); QTest::qWait(50); int index = memoryViewer->ui->datadirComboBox->currentIndex(); if (index == -1) return; int numImages = memoryViewer->dataModelList[index]->imageList.length(); progressStepSize = 1./float(numImages); #pragma omp parallel for num_threads(memoryViewer->controller->maxExternalThreads) for (int i=0; i<numImages; ++i) { MyImage *it = memoryViewer->dataModelList[index]->imageList[i]; if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); incrementProgress(); emit progressUpdate(progress); } } memoryViewer->ui->downloadToolButton->setText("Write"); memoryViewer->ui->downloadToolButton->setEnabled(true); emit progressUpdate(100.); emit finished(); } void MemoryWorker::DataDumpImagesToDrive() { emit resetProgressBar(); if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); // memoryViewer->ui->downloadToolButton->setText("Wait "); // memoryViewer->ui->downloadToolButton->setDisabled(true); QTest::qWait(50); progressStepSize = 1. / float(data->numImages); emit progressUpdate(0.); data->populateExposureList(); #pragma omp parallel for num_threads(data->maxExternalThreads) for (long i=0; i<data->exposureList.length(); ++i) { for (auto &it : data->exposureList[i]) { if (!it->imageOnDrive) { it->writeImage(); it->imageOnDrive = true; it->emitModelUpdateNeeded(); incrementProgress(); emit progressUpdate(progress); } } } // memoryViewer->ui->downloadToolButton->setText("Write"); // memoryViewer->ui->downloadToolButton->setEnabled(true); emit progressUpdate(100.); emit finished(); } void MemoryWorker::incrementProgress() { omp_set_lock(&progressLock); progress += progressStepSize; emit progressUpdate(progress); omp_unset_lock(&progressLock); } void MemoryWorker::dumpImageToDrive() { if (state == PAUSED) state = RUNNING; // Treat as resume if (state == RUNNING) return; state = RUNNING; emit started(); myImage->writeImage(); myImage->imageOnDrive = true; emit finished(); }
4,812
C++
.cc
131
31.900763
92
0.692937
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,491
anetworker.cc
schirmermischa_THELI/src/threading/anetworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "anetworker.h" #include "../functions.h" #include <QProcess> #include <QTest> AnetWorker::AnetWorker(QString command, QString dir, QObject *parent) : Worker(parent) { anetCommand = command; anetDirName = dir; } void AnetWorker::runAnet() { extProcess = new QProcess(); connect(extProcess, &QProcess::readyReadStandardOutput, this, &AnetWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &AnetWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(anetDirName); extProcess->start("/bin/sh -c \""+anetCommand+"\""); extProcess->waitForFinished(-1); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void AnetWorker::processExternalStdout() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stdout(process->readAllStandardOutput()); stdout.replace(" Field", "<br>Field"); stdout.replace("\nField", "<br>Field"); stdout.replace("Hit/miss: Hit/miss:", "<br>Hit/miss:"); // stdout.replace("Field 1 did not solve (index theli_mystd.index, field objects 1-10",""); // stdout.replace("Field 1 did not solve", ""); // stdout.replace("Solving...", ""); // stdout.replace("Reading sort column \"MAG\" Sorting sort column mmapping input file Copying table header. Writing row 0 Done", ""); // stdout.replace("(index theli_mystd.index",""); // stdout.replace(", field objects 1-10",""); QStringList errors; errors << "Did not solve (or no WCS file was written)." << "Error" << "ERROR"; // Highlight a successful solve // Sometimes neighboring lines are included in one push to stdout, and then they are colored green as well. if (stdout.contains("solved with index theli_mystd.index")) { emit messageAvailable(stdout.simplified(), "note"); return; } // And a field that did not solve for (auto &error : errors) { if (stdout.contains(error)) { failedImages.append(stdout.split(" ").at(1)); // emit errorFound(); // do not abort the run just because of one field that did not solve. There might be more. emit didNotSolve(); emit messageAvailable(stdout.simplified(), "warning"); break; } } emit messageAvailable(stdout.simplified(), "image"); } void AnetWorker::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stderr(process->readAllStandardError()); stderr.replace("> *Error*:", "<br><br>> *Error*:"); stderr.replace("> *ERROR*:", "<br><br>> *ERROR*:"); QStringList errors; errors << "*Error*:" << "*ERROR*:"; for (auto &error : errors) { if (stderr.contains(error)) { emit errorFound(); emit messageAvailable("Astrometry.net: " + stderr.simplified(), "stop"); break; } } } void AnetWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); }
4,069
C++
.cc
97
37.453608
147
0.685743
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,492
colorpictureworker.cc
schirmermischa_THELI/src/threading/colorpictureworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpictureworker.h" #include "../colorpicture/colorpicture.h" #include <QTest> ColorPictureWorker::ColorPictureWorker(ColorPicture *colorpicture, QString workmode, QObject *parent) : Worker(parent) { colorPicture = colorpicture; workMode = workmode; } void ColorPictureWorker::runTask() { QTest::qWait(50); if (yield) { emit finished(); return; } if (workMode == "CropCoadds") colorPicture->taskInternalCropCoadds(); else if (workMode == "ColorCalib") colorPicture->taskInternalColorCalib(); else if (workMode == "Fits2Tiff") colorPicture->taskInternalFits2Tiff(); else if (workMode == "BBNBratio") colorPicture->taskInternalBBNBratio(); else if (workMode == "BBNBcombine") colorPicture->taskInternalBBNBcombine(); else { // nothing yet } emit tasknameReturned(workMode); }
1,545
C++
.cc
39
36.410256
118
0.759358
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,493
mainguiworker.cc
schirmermischa_THELI/src/threading/mainguiworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "mainguiworker.h" #include "../processingInternal/controller.h" #include <QProcess> #include <QTest> #include <QString> #include <QStringList> MainGUIWorker::MainGUIWorker(Controller *mycontroller, QStringList mycommands, QObject *parent) : Worker(parent) { commands = mycommands; controller = mycontroller; } void MainGUIWorker::runTask() { // isWorkerRunning = true; // Grab the command list, read the keywords, and process it accordingly QString key; QString instructions; QStringList list; // The following loop handles 4 different types of 'key events' // yield can be triggered from outside for (auto &it : commands) { // We need a little wait here (50msec) to allow for the parent process to update "abort" // in case the process is aborted by the user. QTest::qWait(50); if (yield || !controller->successProcessing) { emit messageAvailable("Aborted.\n", "stop"); emit finished(); break; } list = it.split("::"); key = list.at(0); // EVENT 1: Used to show which task is currently executed if (key == "MESSAGE") { int length = list.length(); // Only emit non-empty messages if (length > 1) { instructions = list.at(1).simplified(); emit messageAvailable(instructions+" ... ", "output"); } } // EVENT 2: execute the task else if (key == "RUN") { QString taskBasename = list.at(1); instructions = list.at(2).simplified(); // Set up the controller with the taskname, the arguments, and the parallelization, then run the task controller->taskBasename = taskBasename; controller->instructions = instructions; controller->loadPreferences(); // update the data tree here? controller->runTask(); } // EVENT 3: show in the GUI which task has just successfully finished else if (key == "UPDATESTATUS") { QString taskBasename = list.at(1); emit updateStatus(taskBasename, true); } // EVENT 4: show that everything is done. else if (key == "END") { emit messageAvailable("All tasks finished.\n", "info"); emit finished(); } } }
3,072
C++
.cc
77
32.831169
113
0.650134
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,494
abszpworker.cc
schirmermischa_THELI/src/threading/abszpworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "abszpworker.h" #include "../abszp/abszeropoint.h" #include <QProcess> #include <QTest> AbszpWorker::AbszpWorker(AbsZeroPoint *abszeropoint, QObject *parent) : Worker(parent) { // abszpCommand = command; // abszpDirName = dir; absZeroPoint = abszeropoint; } void AbszpWorker::runTask() { QTest::qWait(50); if (yield) { emit finished(); return; } absZeroPoint->taskInternalAbszeropoint(); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void AbszpWorker::processExternalStdout() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); stdout.remove(QRegExp("[^a-zA-Z.:-\\d\\s]")); emit messageAvailable(stdout.simplified(), "normal"); } void AbszpWorker::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stderr(process->readAllStandardError()); stderr.remove(QRegExp("[^a-zA-Z\\d\\s]")); emit messageAvailable(stderr.simplified(), "normal"); }
1,810
C++
.cc
50
33.38
86
0.746141
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,495
worker.cc
schirmermischa_THELI/src/threading/worker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "worker.h" Worker:: Worker(QObject *parent) : QObject(parent) { } void Worker::pause() { auto const dispatcher = QThread::currentThread()->eventDispatcher(); if (!dispatcher) { // qDebug() << "thread with no dispatcher"; return; } if (state != RUNNING) return; state = PAUSED; // qDebug() << "paused"; do { dispatcher->processEvents(QEventLoop::WaitForMoreEvents); } while (state == PAUSED); } void Worker::resume() { if (state == PAUSED) { state = RUNNING; // qDebug() << "resumed"; } } void Worker::cancel() { if (state != IDLE) { state = IDLE; // qDebug() << "cancelled"; } } bool Worker::isCancelled() { auto const dispatcher = QThread::currentThread()->eventDispatcher(); if (!dispatcher) { // qDebug() << "thread with no dispatcher"; return false; } dispatcher->processEvents(QEventLoop::AllEvents); return state == IDLE; }
1,671
C++
.cc
58
25.603448
75
0.687071
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,496
sourceextractorworker.cc
schirmermischa_THELI/src/threading/sourceextractorworker.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "sourceextractorworker.h" #include "../functions.h" #include <QProcess> #include <QTest> SourceExtractorWorker::SourceExtractorWorker(QString command, QString dir, QObject *parent) : Worker(parent) { sourceExtractorCommand = command; sourceExtractorDirName = dir; } void SourceExtractorWorker::runSourceExtractor() { extProcess = new QProcess(); connect(extProcess, &QProcess::readyReadStandardOutput, this, &SourceExtractorWorker::processExternalStdout); connect(extProcess, &QProcess::readyReadStandardError, this, &SourceExtractorWorker::processExternalStderr); QTest::qWait(300); // If I don't do this, the GUI crashes. It seems the process produces an output faster than the connection can be made ... extProcess->setWorkingDirectory(sourceExtractorDirName); extProcess->start("/bin/sh -c \""+sourceExtractorCommand+"\""); extProcess->waitForFinished(-1); emit finished(); // stdout and stderr channels are slotted into the monitor's plainTextEdit } void SourceExtractorWorker::processExternalStdout() { // Ignoring stdout /* QProcess *process = qobject_cast<QProcess*>(sender()); QString stdout(process->readAllStandardOutput()); // QString stdout(externalProcess->readLine()); stdout.remove(QRegExp("[^a-zA-Z.:-\\d\\s]")); emit messageAvailable(stdout.simplified(), "normal"); */ } void SourceExtractorWorker::processExternalStderr() { QProcess *process = qobject_cast<QProcess*>(sender()); QString stderr(process->readAllStandardError()); stderr.replace("> *Error*:", "<br><br>> *Error*:"); stderr.replace("> *ERROR*:", "<br><br>> *ERROR*:"); QStringList errors; errors << "*Error*:" << "*ERROR*:"; for (auto &error : errors) { if (stderr.contains(error)) { emit errorFound(); emit messageAvailable("Source Extractor: " + stderr.simplified(), "stop"); break; } } } void SourceExtractorWorker::abort() { if (!extProcess) { emit finished(); return; } // First, kill the children long pid = extProcess->processId(); killProcessChildren(pid); // The kill the process that invokes the commandline task extProcess->kill(); emit finished(); }
2,957
C++
.cc
75
35.413333
147
0.722765
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,497
refcatdata.cc
schirmermischa_THELI/src/colorpicture/refcatdata.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "refcatdata.h" RefCatData::RefCatData(QString refcatname, QObject *parent) : QObject(parent) { name = refcatname; } void RefCatData::clear() { ra.clear(); de.clear(); mag1.clear(); mag2.clear(); mag3.clear(); mag4.clear(); mag5.clear(); }
960
C++
.cc
29
30.758621
77
0.765152
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,498
subtaskColorcalib.cc
schirmermischa_THELI/src/colorpicture/subtaskColorcalib.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include <omp.h> #include <QFileDialog> #include <QStringList> #include <QStringListModel> #include <QDateTime> #include <QTest> #include <QSettings> #include <QMessageBox> void ColorPicture::on_calibratePushButton_clicked() { photcatresult[0].catname = "PANSTARRS"; photcatresult[1].catname = "SDSS"; photcatresult[2].catname = "SKYMAPPER"; photcatresult[3].catname = "ATLAS-REFCAT2"; photcatresult[4].catname = "AVGWHITE"; ui->redFactorLineEdit->setText(""); ui->greenFactorLineEdit->setText("1.000"); ui->blueFactorLineEdit->setText(""); ui->redErrorLineEdit->setText(""); ui->greenErrorLineEdit->setText("0.000"); ui->blueErrorLineEdit->setText(""); if (ui->DTLineEdit->text().isEmpty()) ui->DTLineEdit->setText("3.0"); if (ui->DMINLineEdit->text().isEmpty()) ui->DMINLineEdit->setText("5.0"); QDir colorCalibDir(mainDir+"/color_theli/PHOTCAT_calibration/"); if (! colorCalibDir.exists()) { if (!colorCalibDir.mkdir(mainDir+"/color_theli/PHOTCAT_calibration/")) { emit messageAvailable("Could not create <br>"+mainDir+"/color_theli/PHOTCAT_calibration/", "error"); return; } } ui->calibratePushButton->setText("Running ..."); ui->calibratePushButton->setDisabled(true); ui->redComboBox->setDisabled(true); ui->greenComboBox->setDisabled(true); ui->blueComboBox->setDisabled(true); resetResultButtonGroup("alsoResetLabels"); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "ColorCalib"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalColorCalib() { // get platescale if (croppedList.isEmpty()) return; croppedList.at(0)->loadHeader(); // get access to platescale and radius QList<Query*> queryList; if (croppedList.at(0)->plateScale > 3. || croppedList.at(0)->radius > 1.5) { queryList = {ATLASquery}; ui->resultPANSTARRSPushButton->setDisabled(true); ui->resultSDSSPushButton->setDisabled(true); ui->resultSKYMAPPERPushButton->setDisabled(true); ui->numPANSTARRSLabel->setText("0 stars"); ui->numSDSSLabel->setText("0 stars"); ui->numSKYMAPPERLabel->setText("0 stars"); emit messageAvailable("PANSTARRS, SDSS and SKYMAPPER queries deactivated, field of view is too large.", "warning"); } else { queryList = {PANSTARRSquery, SDSSquery, SKYMAPPERquery, ATLASquery}; } // Retrieve the photometric reference catalogs and identify solar type analogs // nested parallelism within colorCalibSegmentImages(); #pragma omp parallel sections { #pragma omp section { // Detect sources in all images colorCalibSegmentImages(); } #pragma omp section { // retrieve catalogs colorCalibRetrieveCatalogs(queryList); // Extract solar analogs filterSolarTypeStars(queryList); } } // } //#pragma omp section // { // } // } // Match the object catalogs with the reference catalogs, and calculate the various correction factors colorCalibMatchCatalogs(); } void ColorPicture::colorCalibMatchCatalogs() { emit messageAvailable("Matching object and reference catalogs ...", "ignore"); MyImage *imageR = identifyCroppedMyImage(ui->redComboBox->currentText()); MyImage *imageG = identifyCroppedMyImage(ui->greenComboBox->currentText()); MyImage *imageB = identifyCroppedMyImage(ui->blueComboBox->currentText()); if (imageR == nullptr || imageG == nullptr || imageB == nullptr) { emit messageAvailable("Could not identify the three RGB channel images!", "error"); return; } QVector<QVector<double>> objDatR = getObjectData(imageR); QVector<QVector<double>> objDatG = getObjectData(imageG); QVector<QVector<double>> objDatB = getObjectData(imageB); // Match R with G int multipleR = 0; int multipleG = 0; int multipleB = 0; double toleranceRG = (imageR->matchingTolerance + imageG->matchingTolerance) / 2.; // upper cap of 1.5 pixels if (toleranceRG*3600/imageR->plateScale > 2.0) toleranceRG = 1.5*imageR->plateScale/3600.; QVector<QVector<double>> matchedRG; // if filter order is changed, must update rCorr and bCorr below! match2D(objDatR, objDatG, matchedRG, toleranceRG, multipleR, multipleG, 0); // Match R+G with B double toleranceRB = (imageR->matchingTolerance + imageB->matchingTolerance) / 2.; // upper cap of 1.5 pixels if (toleranceRB*3600/imageR->plateScale > 2.0) toleranceRB = 1.5*imageR->plateScale/3600.; // print matching radius in pixels // qDebug() << imageR->matchingTolerance*3600/imageR->plateScale << imageG->matchingTolerance*3600/imageG->plateScale << imageB->matchingTolerance*3600/imageB->plateScale; QVector<QVector<double>> matchedRGB; match2D(matchedRG, objDatB, matchedRGB, toleranceRB, multipleR, multipleB, maxCPU); QString meanTol = QString::number(0.5*(toleranceRB+toleranceRG)*3600,'f',1) + "\" (" + QString::number(0.5*(toleranceRB+toleranceRG)*3600/imageB->plateScale,'f',1) + " pix)"; if (verbosity >= 2) emit messageAvailable("RGB mean matching tolerances: " + meanTol, "ignore"); if (verbosity >= 2) emit messageAvailable("RGB # of matched sources: " + QString::number(matchedRGB.length()), "ignore"); // Extract AVGWHITE color correction factors QVector<double> rCorr; // red correction factors wrt. green channel QVector<double> bCorr; // blue correction factors wrt. green channel rCorr.clear(); bCorr.clear(); rCorr.reserve(matchedRGB.length()); bCorr.reserve(matchedRGB.length()); for (auto &obj : matchedRGB) { // 'obj' contains RA, DEC, flux_b, flux_g, flux_r // CAREFUL: mag order depends on which filter is loaded into match2D as source and which one as reference rCorr.append(obj[3] / obj[4]); bCorr.append(obj[3] / obj[2]); } double num = rCorr.length(); // copy result for AVGWHITE into photcatresult int nrefcat = 4; photcatresult[nrefcat].rfac = QString::number(medianMask_T(rCorr),'f',3); photcatresult[nrefcat].rfacerr = QString::number(medianerrMask(rCorr) / sqrt(num),'f',3); photcatresult[nrefcat].gfac = "1.000"; photcatresult[nrefcat].gfacerr = "0.000"; photcatresult[nrefcat].bfac = QString::number(medianMask_T(bCorr),'f',3); photcatresult[nrefcat].bfacerr = QString::number(medianerrMask(bCorr) / sqrt(num),'f',3); photcatresult[nrefcat].nstars = QString::number(num); emit updateNrefStars("AVGWHITE", rCorr.length()); // Match with reference catalogs // TODO: take into account proper motions double toleranceRGB = (imageR->matchingTolerance + imageG->matchingTolerance + imageB->matchingTolerance) / 3.; filterReferenceCatalog(PANSTARRS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, PANSTARRS, toleranceRGB); filterReferenceCatalog(SDSS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, SDSS, toleranceRGB); filterReferenceCatalog(SKYMAPPER, imageG); colorCalibMatchReferenceCatalog(matchedRGB, SKYMAPPER, toleranceRGB); filterReferenceCatalog(ATLAS, imageG); colorCalibMatchReferenceCatalog(matchedRGB, ATLAS, toleranceRGB); } // Remove objects outside the actual field of view (simply for clarity) // We need to test a single exposure, only. Does not matter whether it is the red, green or blue channel void ColorPicture::filterReferenceCatalog(RefCatData *REFCAT, MyImage *channelImage) { long countG2inside = 0; for (int i=0; i<REFCAT->ra.length(); ++i) { // is the reference source within the FITS image? if (channelImage->containsRaDec(REFCAT->ra[i], REFCAT->de[i])) { // if yes, is it covered by valid pixels (rejecting empty image borders) double x = 0.; double y = 0.; channelImage->sky2xy(REFCAT->ra[i], REFCAT->de[i], x, y); long n = channelImage->naxis1; if (channelImage->dataCurrent[x + n * y] != 0.) ++countG2inside; } } if (REFCAT->ra.length() > 0) { REFCAT->resultString = REFCAT->name + " : " + QString::number(countG2inside) + " G2 references inside image"; } } void ColorPicture::colorCalibMatchReferenceCatalog(const QVector<QVector<double>> &matchedRGB, RefCatData *REFCAT, float tolerance) { int index = 0; if (REFCAT->name == "PANSTARRS") index = 0; else if (REFCAT->name == "SDSS") index = 1; else if (REFCAT->name == "SKYMAPPER") index = 2; else if (REFCAT->name == "ATLAS-REFCAT2") index = 3; if (matchedRGB.isEmpty() || REFCAT->ra.isEmpty()) { photcatresult[index].rfac = "1.000"; photcatresult[index].rfacerr = "0.000"; photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = "1.000"; photcatresult[index].bfacerr = "0.000"; photcatresult[index].nstars = "0"; QString nstars = "0 stars"; if (REFCAT->ra.isEmpty()) { if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); } return; } QVector<QVector<double>> refDat; QVector<QVector<double>> matchedREFCAT; int dummy1; int dummy2; for (int i=0; i<REFCAT->ra.length(); ++i) { QVector<double> refdata; // Add the two coords, and a dummy magnitude of 0.0 (required by match2D algorithm) refdata << REFCAT->de[i] << REFCAT->ra[i] << 0.0; refDat.append(refdata); } match2D(matchedRGB, refDat, matchedREFCAT, tolerance, dummy1, dummy2, maxCPU); if (matchedREFCAT.isEmpty()) { emit messageAvailable("None of the G2-like sources in " + REFCAT->name + " were detected.", "warning"); photcatresult[index].rfac = "1.000"; photcatresult[index].rfacerr = "0.000"; photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = "1.000"; photcatresult[index].bfacerr = "0.000"; photcatresult[index].nstars = "0"; writeG2refcat(REFCAT->name, matchedREFCAT); QString nstars = "0 stars"; if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); return; } // Calculate the color correction factors // matchRGB contains magnitudes in the order BGR, i.e. matchREFCAT contains: magref-B-G-R QVector<float> rCorr; // red correction factors wrt. green channel QVector<float> bCorr; // cblue orrection factors wrt. green channel rCorr.reserve(matchedREFCAT.length()); bCorr.reserve(matchedREFCAT.length()); for (auto &obj : matchedREFCAT) { // 'obj' contains RA, DEC, 0.0, flux_b, flux_g, flux_r // 0.0 is the dummy magnitude rCorr.append(obj[4] / obj[5]); bCorr.append(obj[4] / obj[3]); } photcatresult[index].rfac = QString::number(meanMask_T(rCorr),'f',3); photcatresult[index].rfacerr = QString::number(rmsMask_T(rCorr),'f',3); photcatresult[index].gfac = "1.000"; photcatresult[index].gfacerr = "0.000"; photcatresult[index].bfac = QString::number(meanMask_T(bCorr),'f',3); photcatresult[index].bfacerr = QString::number(rmsMask_T(bCorr),'f',3); photcatresult[index].nstars = QString::number(rCorr.length()); writeG2refcat(REFCAT->name, matchedREFCAT); QString nstars = QString::number(matchedREFCAT.length()) + " stars"; if (REFCAT->name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (REFCAT->name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (REFCAT->name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (REFCAT->name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); else if (REFCAT->name == "AVGWHITE") ui->numAVGWHITELabel->setText(nstars); QString type = "note"; if (matchedREFCAT.length() == 0) { REFCAT->resultString = REFCAT->name + " : None of the G2 references were detected in the image."; type = "warning"; } else { REFCAT->resultString.append(", " +QString::number(matchedREFCAT.length()) + " of which detected."); } emit messageAvailable(REFCAT->resultString, type); } void ColorPicture::writeG2refcat(const QString refcatName, const QVector<QVector<double>> matchedREFCAT) { // The iView catalog (ASCII) QString outpath = mainDir+"/color_theli/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); QFile outcat_iview(outpath+"/PHOTCAT_calibration/PHOTCAT_sources_matched_"+refcatName+".iview"); QTextStream stream_iview(&outcat_iview); if( !outcat_iview.open(QIODevice::WriteOnly)) { emit messageAvailable(QString(__func__) + ": ERROR writing "+outpath+outcat_iview.fileName()+" : "+outcat_iview.errorString(), "error"); emit criticalReceived(); return; } // Write iView catalog for (auto &source : matchedREFCAT) { // RA first, then DEC! (matching is done with DEC in first column) stream_iview << QString::number(source[1], 'f', 9) << " " << QString::number(source[0], 'f', 9) << "\n"; } outcat_iview.close(); outcat_iview.setPermissions(QFile::ReadUser | QFile::WriteUser); } void ColorPicture::colorCalibRetrieveCatalogs(QList<Query*> queryList) { emit messageAvailable("Querying reference sources, this may take a while ...", "ignore"); // Collector for meta data from the queries QStringList queryResult; for (int i=0; i<queryList.length(); ++i) queryResult << ""; // It appears that the parallel query is not threadsafe. // Results in not reproducible errors, at least when run through Qt5 debugger (but when run through valgrind) // #pragma omp parallel for num_threads(maxCPU) for (int i=0; i<queryList.length(); ++i) { auto &query = queryList[i]; query->photomDir = ui->dirLineEdit->text() + "/color_theli/"; query->photomImage = croppedList[0]; query->doColorCalibQueryFromWeb(); query->identifySolarTypeStars(); QString info = "G2 sources " + query->refcatName + " : " + QString::number(query->numG2sources) + " (out of : " + QString::number(query->numSources) + ")"; queryResult[i] = info; emit messageAvailable(info, "append"); // emit updateNrefStars(query->refcatName, query->numG2sources); } } void ColorPicture::filterSolarTypeStars(QList<Query*> queryList) { PANSTARRS->clear(); SDSS->clear(); SKYMAPPER->clear(); ATLAS->clear(); for (auto &query : queryList) { if (query->numSources == 0) continue; for (long k=0; k<query->mag1_out.length(); ++k) { if (!query->G2type[k]) continue; if (query->refcatName == "PANSTARRS") { PANSTARRS->ra.append(query->ra_out[k]); PANSTARRS->de.append(query->de_out[k]); } if (query->refcatName == "SDSS") { SDSS->ra.append(query->ra_out[k]); SDSS->de.append(query->de_out[k]); } if (query->refcatName == "SKYMAPPER") { SKYMAPPER->ra.append(query->ra_out[k]); SKYMAPPER->de.append(query->de_out[k]); } if (query->refcatName == "ATLAS-REFCAT2") { ATLAS->ra.append(query->ra_out[k]); ATLAS->de.append(query->de_out[k]); } } } } void ColorPicture::colorCalibSegmentImages() { emit messageAvailable("Detecting sources ...", "ignore"); // Create object catalogs, get matching tolerance QString DT = ui->DTLineEdit->text(); QString DMIN = ui->DMINLineEdit->text(); #pragma omp parallel for num_threads(maxCPU) // ignored since we run it in a parallel section for (int i=0; i<croppedList.length(); ++i) { auto &it = croppedList[i]; // only do source detection if the image is also present in one of the RGB channels: if (it->name != ui->redComboBox->currentText() && it->name != ui->greenComboBox->currentText() && it->name != ui->blueComboBox->currentText()) { continue; } // Do nothing if we have the catalog already if (it->segmentationDone) continue; // Obtain catalog // emit messageAvailable("Detecting sources in " + it->baseName +" ...", "ignore"); it->maxCPU = maxCPU / croppedList.length(); // TODO: introduce a 90% dynrange cutoff to avoid saturated sources it->resetObjectMasking(); it->readImage(it->path + "/" +it->name); it->readWeight(); it->backgroundModel(100, "interpolate"); it->segmentImage(DT, DMIN, true, false); it->estimateMatchingTolerance(); it->matchingTolerance *= 3.; it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); QString channelName = ""; if (it->name == ui->redComboBox->currentText()) channelName = "R"; if (it->name == ui->greenComboBox->currentText()) channelName = "G"; if (it->name == ui->blueComboBox->currentText()) channelName = "B"; if (verbosity >= 2) emit messageAvailable(channelName + " : " + QString::number(it->objectList.length()) + " sources", "ignore"); } } void ColorPicture::updateNrefStarsReceived(QString name, long number) { QString nstars = QString::number(number) + " stars"; if (name == "PANSTARRS") ui->numPANSTARRSLabel->setText(nstars); else if (name == "SDSS") ui->numSDSSLabel->setText(nstars); else if (name == "SKYMAPPER") ui->numSKYMAPPERLabel->setText(nstars); else if (name == "ATLAS-REFCAT2") ui->numATLASLabel->setText(nstars); else if (name == "AVGWHITE") ui->numAVGWHITELabel->setText(nstars); }
20,083
C++
.cc
405
43.232099
178
0.669385
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,499
subtaskCropcoadd.cc
schirmermischa_THELI/src/colorpicture/subtaskCropcoadd.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include <omp.h> #include <QFileDialog> #include <QStringList> #include <QStringListModel> #include <QDateTime> #include <QTest> #include <QSettings> #include <QMessageBox> void ColorPicture::on_getCoaddsPushButton_clicked() { // FIRST, fetch the selected images. This is fast because we link only, and hence we don't need an external thread. QItemSelectionModel *selectionModel = ui->coaddDirListView->selectionModel(); QStringList list = coaddDirModel->stringList(); QStringList imageList; QString dirName = ui->dirLineEdit->text(); for (int i=0; i<ui->coaddDirListView->model()->rowCount(); ++i) { QModelIndex index = ui->coaddDirListView->model()->index(i,0); if (selectionModel->isSelected(index)) imageList.append(list.at(i)); } // Stop if no images were selected if (imageList.length() < 2) { emit messageAvailable("At least two images must be chosen from the list of coadded images.", "warning"); return; } emit messageAvailable("Linking selected coadded images to "+dirName+"/color_theli/", "info"); QPalette palette; palette.setColor(QPalette::Base,QColor("#a9ffe6")); ui->getCoaddsPushButton->setText("Running ..."); ui->getCoaddsPushButton->setPalette(palette); ui->getCoaddsPushButton->setDisabled(true); QTest::qWait(50); // Create the directory containing the images QDir colorTheli(dirName+"/color_theli"); if (colorTheli.exists()) { colorTheli.rename(dirName+"/color_theli", dirName+"/color_theli_"+QDateTime::currentDateTime().toString(Qt::ISODate)); } colorTheli.mkdir(dirName+"/color_theli"); // Link the images QString coaddImageName; QString coaddWeightName; QFile coaddImage; QFile coaddWeight; QString identifier; QStringList coaddImageList; for (auto &it : imageList) { if (it.contains("coadd_")) { identifier = it.split("coadd_").at(1); } else continue; coaddImageName = dirName+"/"+it+"/coadd.fits"; coaddWeightName = dirName+"/"+it+"/coadd.weight.fits"; coaddImage.setFileName(coaddImageName); coaddWeight.setFileName(coaddWeightName); if (coaddImage.exists()) { coaddImage.link(dirName+"/color_theli/"+identifier+".fits"); coaddImageList.append(identifier+".fits"); // populate the coaddImage listView coaddImageModel->setStringList(coaddImageList); } if (coaddWeight.exists()) coaddWeight.link(dirName+"/color_theli/"+identifier+".weight.fits"); } coaddImageModel->sort(0); // Next, crop the images to their maximum overlap // Reset the button now, so we don't have to do it from within another thread buttonPalette = ui->getCoaddsPushButton->palette(); ui->getCoaddsPushButton->setText("Cropping images, please wait ..."); ui->getCoaddsPushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "CropCoadds"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalCropCoadds() { if (verbosity <= 1) emit messageAvailable("Cropping images ...", "ignore"); QString dirName = ui->dirLineEdit->text() + "/color_theli/"; QDir colorTheli(dirName); QStringList filter("*.fits"); QStringList imageList = colorTheli.entryList(filter); coaddList.clear(); for (auto &it : imageList) { QVector<bool> dummyMask; dummyMask.clear(); MyImage *myImage = new MyImage(dirName+it, dummyMask, &verbosity); connect(myImage, &MyImage::messageAvailable, this, &ColorPicture::displayMessage); connect(myImage, &MyImage::critical, this, &ColorPicture::criticalReceived); // WCSlock not necessary, as the corresponding initWCS() call is inside a critical section // Besides, the following line stalls the execution of the cropping, because the unlocking signal apparently never gets received ... // connect(myImage, &MyImage::setWCSLock, this, &ColorPicture::setWCSLockReceived, Qt::DirectConnection); myImage->globalMaskAvailable = false; myImage->maxCPU = maxCPU / imageList.length(); myImage->loadHeader(); coaddList.append(myImage); } // for consistency checks QVector<float> crval1; QVector<float> crval2; QVector<float> cd11; QVector<float> cd12; QVector<float> cd21; QVector<float> cd22; int length = coaddList.length(); for (int i=0; i<length; ++i) { auto &it = coaddList[i]; crval1 << it->wcs->crval[0]; crval2 << it->wcs->crval[1]; cd11 << it->wcs->cd[0]; cd12 << it->wcs->cd[1]; cd21 << it->wcs->cd[2]; cd22 << it->wcs->cd[3]; } if (numberOfDuplicates_T(crval1) != length - 1 || numberOfDuplicates_T(crval2) != length - 1 || numberOfDuplicates_T(cd11) != length - 1 || numberOfDuplicates_T(cd12) != length - 1 || numberOfDuplicates_T(cd21) != length - 1 || numberOfDuplicates_T(cd22) != length - 1) { emit messageAvailable("The coadditions do not share the same astrometric projection. You must use identical reference coordinates when creating the coadditions.", "error"); emit messageAvailable("Done.", "info"); return; } QVector<float> crpix1; QVector<float> crpix2; QVector<float> naxis1; QVector<float> naxis2; QVector<float> d1; QVector<float> d2; for (int i=0; i<coaddList.length(); ++i) { auto &it = coaddList[i]; crpix1 << it->wcs->crpix[0]; crpix2 << it->wcs->crpix[1]; naxis1 << it->naxis1; naxis2 << it->naxis2; d1 << it->naxis1 - it->wcs->crpix[0]; d2 << it->naxis2 - it->wcs->crpix[1]; } float xlow = -1.*minVec_T(crpix1); float ylow = -1.*minVec_T(crpix2); float xhigh = minVec_T(d1); float yhigh = minVec_T(d2); CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(); #pragma omp parallel for num_threads(maxCPU) for (int i=0; i<coaddList.length(); ++i) { auto &it = coaddList[i]; if (verbosity >= 2) emit messageAvailable("Cropping "+it->name, "ignore"); // crop image float xlowNew = xlow + crpix1[i]; float ylowNew = ylow + crpix2[i]; float xhighNew = xhigh + crpix1[i] - 1; float yhighNew = yhigh + crpix2[i] - 1; QString tmpName = it->name; QString name; if (it->name.contains(".weight.fits")) { tmpName.remove(".weight.fits"); name = tmpName + "_cropped.weight.fits"; it->baseName = tmpName + "_cropped.weight.fits"; } else { name = it->baseName + "_cropped.fits"; } it->readImage(it->path+"/"+it->name); it->makeCutout(xlowNew, xhighNew, ylowNew, yhighNew); it->writeImage(dirName + name); it->name = name; // update fits header int status = 0; float crpix1New = crpix1[i] - xlowNew + 1; float crpix2New = crpix2[i] - ylowNew + 1; fitsfile *fptr = nullptr; fits_open_file(&fptr, (dirName+name).toUtf8().data(), READWRITE, &status); fits_update_key_flt(fptr, "CRPIX1", crpix1New, 6, nullptr, &status); fits_update_key_flt(fptr, "CRPIX2", crpix2New, 6, nullptr, &status); fits_close_file(fptr, &status); QString code = errorCodes->errorKeyMap.value(status); if (status) { emit messageAvailable("CFITSIO: Could not update CRPIX keywords in "+name+":<br>"+code, "error"); } } delete errorCodes; errorCodes = nullptr; // Prepare for segmentation // Move the cropped weights over into the cropped coadd croppedList.clear(); for (auto &coadd : coaddList) { if (coadd->name.contains("weight.fits")) continue; QString baseCoadd = coadd->name; baseCoadd.remove("_cropped.fits"); for (auto &weight : coaddList) { if (!weight->name.contains("weight.fits")) continue; QString baseWeight = weight->name; baseWeight.remove("_cropped.weight.fits"); if (baseCoadd == baseWeight) { coadd->dataWeight.swap(weight->dataCurrent); coadd->weightInMemory = true; coadd->globalMaskAvailable = false; croppedList.append(coadd); } } } emit messageAvailable("Done.", "info"); }
10,142
C++
.cc
229
37.419214
180
0.661272
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,500
subtaskbbnb.cc
schirmermischa_THELI/src/colorpicture/subtaskbbnb.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../instrumentdata.h" #include "../preferences.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include <omp.h> #include <QStringList> #include <QStringListModel> #include <QDateTime> #include <QTest> #include <QMessageBox> void ColorPicture::on_getRatioPushButton_clicked() { ui->filterRatioLineEdit->setText(""); QDir colorCalibDir(mainDir+"/color_theli/PHOTCAT_calibration/"); if (! colorCalibDir.exists()) { if (!colorCalibDir.mkdir(mainDir+"/color_theli/PHOTCAT_calibration/")) { emit messageAvailable("Could not create "+mainDir+"/color_theli/PHOTCAT_calibration/", "error"); return; } } ui->getRatioPushButton->setText("Running ..."); ui->getRatioPushButton->setDisabled(true); ui->narrowbandComboBox->setDisabled(true); ui->broadbandComboBox->setDisabled(true); ui->BBNBcombinePushButton->setDisabled(true); QTest::qWait(50); QString n_image = ui->narrowbandComboBox->currentText(); QString b_image = ui->broadbandComboBox->currentText(); // leave conditions if (n_image == b_image) { emit messageAvailable("You must choose different images to combine.", "warning"); ui->getRatioPushButton->setText("Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); return; } workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "BBNBratio"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalBBNBratio() { MyImage *bbImage = identifyCroppedMyImage(ui->broadbandComboBox->currentText()); MyImage *nbImage = identifyCroppedMyImage(ui->narrowbandComboBox->currentText()); if (bbImage == nullptr || nbImage == nullptr) return; // This should never happen QList<MyImage*> bbnbList; bbnbList << bbImage << nbImage; // Create object catalogs #pragma omp parallel for num_threads(maxCPU) for (int i=0; i<bbnbList.length(); ++i) { auto &it = bbnbList[i]; // Do nothing if we have the catalog already if (it->segmentationDone) continue; // Obtain catalog emit messageAvailable("Detecting sources in " + it->baseName +" ...", "ignore"); it->maxCPU = maxCPU / bbnbList.length(); it->resetObjectMasking(); it->readImage(it->path+"/"+it->name); it->readWeight(); it->backgroundModel(100, "interpolate"); it->segmentImage("5", "5", true, true); it->estimateMatchingTolerance(); it->releaseBackgroundMemory(); it->releaseDetectionPixelMemory(); } emit messageAvailable("Matching broadband and narrowband catalogs ...", "ignore"); QVector<QVector<double>> objDataBB = getObjectData(bbImage); QVector<QVector<double>> objDataNB = getObjectData(nbImage); QVector<QVector<double>> matched; float tolerance = (bbImage->matchingTolerance + nbImage->matchingTolerance) / 2.; int dummy1; int dummy2; match2D(objDataNB, objDataBB, matched, tolerance, dummy1, dummy2, maxCPU); // Calculate mean flux ratio QVector<float> fluxRatios; // compute flux_narrowband / flux_broadband fluxRatios.reserve(matched.length()); for (auto &obj : matched) { // Skip objects with negative fluxes (could be OK though if background is oversubtracted) // CAREFUL: ORDER in 'obj': RA DE FLUX_BB FLUX_NB // match2D inserts the properties of the reference catalog 'in between' if (obj[2] <= 0. || obj[3] <= 0.) continue; fluxRatios.append(obj[3] / obj[2]); } if (fluxRatios.length() <= 1) { bbnbFluxRatio = 1.0; bbnbFluxRatioError = 0.0; } bbnbFluxRatio = straightMedian_T(fluxRatios); bbnbFluxRatioError = rmsMask_T(fluxRatios) / sqrt(fluxRatios.length()); emit messageAvailable("Done.", "info"); } void ColorPicture::on_BBNBcombinePushButton_clicked() { QString BBimage = ui->broadbandComboBox->currentText(); QString NBimage = ui->narrowbandComboBox->currentText(); // leave conditions if (BBimage == NBimage) { emit messageAvailable("You must choose two different images for this task.", "warning"); ui->getRatioPushButton->setText("Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); return; } ui->BBNBcombinePushButton->setText("Running..."); ui->BBNBcombinePushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "BBNBcombine"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalBBNBcombine() { MyImage *bbImage = identifyCroppedMyImage(ui->broadbandComboBox->currentText()); MyImage *nbImage = identifyCroppedMyImage(ui->narrowbandComboBox->currentText()); if (bbImage == nullptr || nbImage == nullptr) return; // This should never happen emit messageAvailable("Combining narrowband and broadband images into: " +bbImage->baseName + nbImage->baseName + "_cropped.fits", "ignore"); long n = bbImage->naxis1; long m = bbImage->naxis2; QString path = bbImage->path + "/"; QVector<bool> dummyMask; dummyMask.clear(); QString newName = bbImage->baseName + nbImage->baseName + "_cropped.fits"; QString newNameWeight = bbImage->baseName + nbImage->baseName + "_cropped.weight.fits"; MyImage *combinedImage = new MyImage(path, bbImage->name, "", 1, dummyMask, &verbosity); MyImage *combinedWeight = new MyImage(path, bbImage->name, "", 1, dummyMask, &verbosity); combinedImage->loadHeader(); combinedWeight->loadHeader(); // Compute and write the combined image as follows: // newImage = (1 - weight * width(NB) / width(BB)) * BB + weight * NB; float weight = ui->narrowbandWeightLineEdit->text().toFloat(); if (ui->narrowbandWeightLineEdit->text().isEmpty()) weight = 1.0; float scale = 1. - weight * bbnbFluxRatio; combinedImage->baseName = bbImage->baseName + nbImage->baseName; combinedImage->name = bbImage->baseName + nbImage->baseName + "_cropped.fits"; combinedImage->weightPath = combinedImage->path; combinedImage->weightName = bbImage->baseName + nbImage->baseName + "_cropped.weight"; combinedImage->dataCurrent.resize(n*m); combinedWeight->dataCurrent.resize(n*m); for (long i=0; i<n*m; ++i) { combinedImage->dataCurrent[i] = scale * bbImage->dataCurrent[i] + weight * nbImage->dataCurrent[i]; combinedWeight->dataCurrent[i] = bbImage->dataWeight[i] + nbImage->dataWeight[i]; } combinedImage->writeImage(path+newName); combinedWeight->writeImage(path+newNameWeight); emit addCombinedImage(combinedImage); emit messageAvailable("Done.", "info"); delete combinedWeight; combinedWeight = nullptr; }
9,323
C++
.cc
185
45.032432
128
0.718287
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,501
subtaskfits2tiff.cc
schirmermischa_THELI/src/colorpicture/subtaskfits2tiff.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include "tiffio.h" #include <omp.h> #include <QStringList> #include <QStringListModel> #include <QDateTime> #include <QTest> #include <QMessageBox> void ColorPicture::on_createTiffPushButton_clicked() { ui->createTiffPushButton->setText("Running ..."); ui->createTiffPushButton->setDisabled(true); QTest::qWait(50); workerThread = new QThread(); colorpictureWorker = new ColorPictureWorker(this, "Fits2Tiff"); colorpictureWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, colorpictureWorker, &ColorPictureWorker::runTask); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::finished, colorpictureWorker, &QObject::deleteLater, Qt::DirectConnection); connect(colorpictureWorker, &ColorPictureWorker::messageAvailable, this, &ColorPicture::displayMessage); connect(colorpictureWorker, &ColorPictureWorker::tasknameReturned, this, &ColorPicture::taskFinished); workerThread->start(); } void ColorPicture::taskInternalFits2Tiff() { int nrows = ui->statisticsTableWidget->rowCount(); int ncols = ui->statisticsTableWidget->columnCount(); // Leave if the table hasn't been initialized if (ncols != 5 || !statisticsRetrieved) { emit messageAvailable("You must first determine the background level.", "warning"); return; } QString bfac = ui->blueFactorLineEdit->text(); QString rfac = ui->redFactorLineEdit->text(); if (bfac.isEmpty()) bfac = "1.0"; if (rfac.isEmpty()) rfac = "1.0"; // retrieve the black and white points for the RGB channels (must have the same range) float maxMax = 0.; float minMin = 0.; float rescale = 1.0; for (int i=0; i<nrows; ++i) { QString name = ui->statisticsTableWidget->item(i,0)->data(Qt::DisplayRole).toString(); float min = ui->statisticsTableWidget->item(i,3)->data(Qt::DisplayRole).toFloat(); float max = ui->statisticsTableWidget->item(i,4)->data(Qt::DisplayRole).toFloat(); if (name == ui->redComboBox->currentText()) rescale = rfac.toFloat(); if (name == ui->blueComboBox->currentText()) rescale = bfac.toFloat(); // Clip only the RGB images to the same min/max values if (name == ui->redComboBox->currentText() || name == ui->greenComboBox->currentText() || name == ui->blueComboBox->currentText()) { if (rescale*max > maxMax) maxMax = rescale*max; if (rescale*min < minMin) minMin = rescale*min; } } // Convert FITS to TIFF #pragma omp parallel for num_threads(maxCPU) for (int i=0; i<nrows; ++i) { QString name = coaddImageModel->index(i,0).data().toString(); MyImage *myImage = identifyCroppedMyImage(name); if (myImage == nullptr) continue; float factor = 1.0; if (name == ui->redComboBox->currentText()) factor = ui->redFactorLineEdit->text().toFloat(); else if (name == ui->blueComboBox->currentText()) factor = ui->blueFactorLineEdit->text().toFloat(); else factor = 1.0; float medVal = ui->statisticsTableWidget->item(i,1)->data(Qt::DisplayRole).toFloat(); // Do the rescaling on a separate data vector myImage->dataTIFF = myImage->dataCurrent; myImage->subtract(medVal, "TIFF"); myImage->multiply(factor, "TIFF"); myImage->toTIFF(16, minMin, maxMax); myImage->writeImageTIFF(myImage->path + "/"+myImage->baseName + "_2tiff.fits"); emit messageAvailable("Wrote " + myImage->path + "/"+myImage->baseName + ".tiff", "ignore"); myImage->dataTIFF.clear(); myImage->dataTIFF.squeeze(); } } // Implementation not finished. void ColorPicture::writeRGBTIFF(QVector<float> &R, QVector<float> &G, QVector<float> &B, long n, long m, float min, float max, QString path) { emit messageAvailable("Creating RGB.tiff ...", "ignore"); // Clipping min and max values QVector<QVector<float>> RGBlist; RGBlist << R << G << B; #pragma omp parallel for for (int i=0; i<3; ++i) { for (auto &pixel : RGBlist[i]) { if (pixel <= min) pixel = min; if (pixel >= max) pixel = max; } } float grey = 0.; // inactive grey = grey / 100. * 65000.; float blowup = (65000. - grey) / (max - min); std::vector< std::vector<long> > imtiff(n); for (long i=0; i<n; ++i) { imtiff[i].resize(m,0); } #pragma omp parallel for for (int img=0; img<3; ++img) { for (long i=0; i<n; ++i) { for (long j=0; j<m; ++j) { RGBlist[img][i+n*j] = blowup * (RGBlist[img][i+n*j] - min) + grey; // flipping TIFF in y dir imtiff[i][m-j-1] = (long) RGBlist[img][i+n*j]; } } } QString outname = path+"/RGB.tiff"; TIFF *outtiff; // pointer to the TIFF file, defined in tiffio.h outtiff = TIFFOpen(outname.toUtf8().data(), "w"); TIFFSetField(outtiff, TIFFTAG_IMAGEWIDTH, n); TIFFSetField(outtiff, TIFFTAG_IMAGELENGTH, m); TIFFSetField(outtiff, TIFFTAG_COMPRESSION, 1); TIFFSetField(outtiff, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(outtiff, TIFFTAG_SAMPLESPERPIXEL, 3); TIFFSetField(outtiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); TIFFSetField(outtiff, TIFFTAG_PLANARCONFIG, 1); // store pixel values as sequential RGB RGB RGB TIFFSetField(outtiff, TIFFTAG_SOFTWARE, "THELI"); TIFFSetField(outtiff, TIFFTAG_IMAGEDESCRIPTION, "Created by THELI"); uint16 *outbuf = (uint16 *)_TIFFmalloc(TIFFScanlineSize(outtiff)); for (long row=0; row<m; ++row) { uint16 *outb = outbuf; for (long column=0; column<n; ++column) { *outb++ = (uint16) (imtiff[column][row]); } TIFFWriteScanline(outtiff, outbuf, row, 0); } TIFFClose(outtiff); _TIFFfree(outbuf); }
6,960
C++
.cc
150
40.593333
140
0.669023
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,502
colorpicture.cc
schirmermischa_THELI/src/colorpicture/colorpicture.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "colorpicture.h" #include "ui_colorpicture.h" #include "../functions.h" #include "../instrumentdata.h" #include "../preferences.h" #include "../iview/iview.h" #include "../tools/tools.h" #include "../query/query.h" #include "../tools/cfitsioerrorcodes.h" #include <omp.h> #include <QFileDialog> #include <QStringList> #include <QStringListModel> #include <QDateTime> #include <QTest> #include <QSettings> #include <QMessageBox> ColorPicture::ColorPicture(QString main, QWidget *parent) : QMainWindow(parent), mainDir(main), ui(new Ui::ColorPicture) { ui->setupUi(this); initEnvironment(thelidir, userdir); // Model views coaddDirModel = new QStringListModel(this); coaddImageModel = new QStringListModel(this); ui->coaddDirListView->setModel(coaddDirModel); ui->coaddImageListView->setModel(coaddImageModel); ui->redComboBox->setModel(coaddImageModel); ui->greenComboBox->setModel(coaddImageModel); ui->blueComboBox->setModel(coaddImageModel); ui->broadbandComboBox ->setModel(coaddImageModel); ui->narrowbandComboBox->setModel(coaddImageModel); ui->dirLineEdit->setText(mainDir); paintPathLineEdit(ui->dirLineEdit, mainDir, "dir"); addDirectories(); connect(ui->blueFactorLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->redFactorLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->filterRatioLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->narrowbandWeightLineEdit, &QLineEdit::textChanged, this, &ColorPicture::validate ); connect(ui->resultSDSSPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultPANSTARRSPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultSKYMAPPERPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultATLASPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->resultAVGWHITEPushButton, &QPushButton::clicked, this, &ColorPicture::toggleCalibResult ); connect(ui->redFactorLineEdit, &QLineEdit::textEdited, this, &ColorPicture::sendColorFactors); connect(ui->blueFactorLineEdit, &QLineEdit::textEdited, this, &ColorPicture::sendColorFactors); connect(ui->resultSDSSPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultPANSTARRSPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultSKYMAPPERPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultATLASPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->resultAVGWHITEPushButton, &QPushButton::clicked, this, &ColorPicture::sendColorFactors); connect(ui->getStatisticsPushButton, &QPushButton::clicked, this, &ColorPicture::on_previewCalibPushButton_clicked); connect(this, &ColorPicture::messageAvailable, this, &ColorPicture::displayMessage); connect(this, &ColorPicture::updateNrefStars, this, &ColorPicture::updateNrefStarsReceived); connect(this, &ColorPicture::addCombinedImage, this, &ColorPicture::addCombinedImageReceived); ui->tabWidget->setCurrentIndex(0); resultButtonGroup->setExclusive(true); resultButtonGroup->addButton(ui->resultPANSTARRSPushButton); resultButtonGroup->addButton(ui->resultSDSSPushButton); resultButtonGroup->addButton(ui->resultSKYMAPPERPushButton); resultButtonGroup->addButton(ui->resultATLASPushButton); resultButtonGroup->addButton(ui->resultAVGWHITEPushButton); QPalette palette; palette.setColor(QPalette::Background, QColor("#c6c6c6")); ui->statusbar->setPalette(palette); setWindowIcon(QIcon(":/icons/color.png")); loadPreferences(); // Init queries PANSTARRSquery->refcatName = "PANSTARRS"; SDSSquery->refcatName = "SDSS"; SKYMAPPERquery->refcatName = "SKYMAPPER"; ATLASquery->refcatName = "ATLAS-REFCAT2"; connect(PANSTARRSquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(SDSSquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(SKYMAPPERquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); connect(ATLASquery, &Query::messageAvailable, this, &ColorPicture::displayMessage); } ColorPicture::~ColorPicture() { delete PANSTARRSquery; delete SDSSquery; delete SKYMAPPERquery; delete ATLASquery; PANSTARRSquery = nullptr; SDSSquery = nullptr; SKYMAPPERquery = nullptr; ATLASquery = nullptr; delete ui; } void ColorPicture::updateVerbosity(int verbosityLevel) { verbosity = verbosityLevel; } void ColorPicture::loadPreferences() { QSettings settings("THELI", "PREFERENCES"); maxCPU = settings.value("prefCPUSpinBox").toInt(); // verbosity = settings.value("prefVerbosityComboBox").toInt(); verbosity = 0; } // Receiving end from setWCSLock call void ColorPicture::setWCSLockReceived(bool locked) { if (locked) omp_set_lock(&wcsLock); else omp_unset_lock(&wcsLock); } void ColorPicture::displayMessage(QString message, QString type) { if (type == "error") { ui->processingTextEdit->appendHtml("<font color=\"#ee0000\">ERROR: " + message + "</font>"); } else if (type == "warning") { ui->processingTextEdit->appendHtml("<font color=\"#ee5500\">" + message + "</font>"); } else if (type == "info") { ui->processingTextEdit->appendHtml("<font color=\"#0000dd\">" + message + "</font>"); } else if (type == "note") { ui->processingTextEdit->appendHtml("<font color=\"#009955\">" + message + "</font>"); } else if (type == "append") { ui->processingTextEdit->moveCursor(QTextCursor::End); ui->processingTextEdit->appendHtml(" "+message); ui->processingTextEdit->moveCursor(QTextCursor::End); } else ui->processingTextEdit->appendHtml(message); } void ColorPicture::criticalReceived() { emit finished(); } void ColorPicture::checkCalibrationFactor(QLineEdit *le) { if (le->text().isEmpty()) le->setText("1.000"); } void ColorPicture::sendColorFactors() { checkCalibrationFactor(ui->redFactorLineEdit); checkCalibrationFactor(ui->blueFactorLineEdit); // green is always 1.0 float redFactor = ui->redFactorLineEdit->text().toFloat(); float blueFactor = ui->blueFactorLineEdit->text().toFloat(); emit colorFactorChanged(redFactor, blueFactor); } void ColorPicture::on_selectDirPushButton_clicked() { // get parent directory QFileDialog qfd(this); qfd.setFileMode(QFileDialog::DirectoryOnly); qfd.setOption(QFileDialog::ShowDirsOnly); qfd.setDirectory(mainDir); qfd.setWindowTitle(tr("Select directory")); QString dirName; if (qfd.exec()) dirName = qfd.selectedFiles().at(0); ui->dirLineEdit->setText(dirName); paintPathLineEdit(ui->dirLineEdit, dirName, "dir"); addDirectories(); } void ColorPicture::addDirectories() { QString dirName = ui->dirLineEdit->text(); if (!QDir(dirName).exists()) return; mainDir = ui->dirLineEdit->text(); // find all coadd_xxx subdirectories QStringList subDirList; findRecursion(dirName, &subDirList); QStringList coaddList; // Keep coadd_xxx only for (auto &it : subDirList) { QString tmp = it.remove(0, dirName.length()); if (tmp.startsWith('/')) tmp = tmp.remove(0,1); if (tmp.startsWith("coadd_") || tmp.contains("/coadd_")) { QFile coaddedImage(dirName+"/"+tmp+"/coadd.fits"); if (coaddedImage.exists()) coaddList.append(tmp); } } coaddDirModel->setStringList(coaddList); } void ColorPicture::findRecursion(const QString &path, QStringList *result) { // recursive QDir currentDir(path); const QString prefix = path + QLatin1Char('/'); foreach (const QString &match, currentDir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)) result->append(prefix + match); foreach (const QString &dir, currentDir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot)) findRecursion(prefix + dir, result); } void ColorPicture::refreshComboBoxes() { QStringList filters; filters << "*cropped.fits"; QString dirName = ui->dirLineEdit->text(); QStringList fileList = QDir(dirName+"/color_theli/").entryList(filters); coaddImageModel->setStringList(fileList); coaddImageModel->sort(0); ui->redComboBox->setCurrentIndex(0); ui->greenComboBox->setCurrentIndex(0); ui->blueComboBox->setCurrentIndex(0); ui->broadbandComboBox->setCurrentIndex(0); ui->narrowbandComboBox->setCurrentIndex(0); } void ColorPicture::taskFinished(QString taskname) { if (taskname == "CropCoadds") updateImageListView(); if (taskname == "ColorCalib") updateCalibFactors(); if (taskname == "BBNBratio") updateFilterRatio(); if (taskname == "BBNBcombine") updateBBNBcombine(); if (taskname == "Fits2Tiff") updateTiff(); } void ColorPicture::updateTiff() { ui->createTiffPushButton->setEnabled(true); showDone(ui->createTiffPushButton, "(4) Create TIFFs"); emit messageAvailable("Done.", "info"); } void ColorPicture::updateImageListView() { // Repopulate the comboboxes refreshComboBoxes(); buttonPalette.setColor(QPalette::Button, QColor("#44d8cc")); ui->getCoaddsPushButton->setPalette(buttonPalette); ui->getCoaddsPushButton->setEnabled(true); showDone(ui->getCoaddsPushButton, "Get selected coadded images"); } void ColorPicture::on_clearCoaddsPushButton_clicked() { coaddImageModel->removeRows(0, coaddImageModel->rowCount()); } void ColorPicture::validate() { // Floating point validators QRegExp rf( "^[-]{0,1}[0-9]+[.]{0,1}[0-9]+" ); QValidator* validator = new QRegExpValidator( rf, this ); ui->blueFactorLineEdit->setValidator( validator ); ui->redFactorLineEdit->setValidator( validator ); ui->filterRatioLineEdit->setValidator( validator ); ui->narrowbandWeightLineEdit->setValidator( validator ); ui->DTLineEdit->setValidator( validator ); // Positive integer validator QRegExp ri( "^[0-9]+" ); QValidator* validator_int_pos = new QRegExpValidator( ri, this ); ui->DMINLineEdit->setValidator( validator_int_pos ); } void ColorPicture::showDone(QPushButton *pushButton, QString text) { // pushButton->setText("Done"); // QTest::qWait(1000); pushButton->setText(text); } void ColorPicture::updateCalibFactors() { int nrefcat = 4; // Select the best result (the ones with the most matches, other than AVGWHITE int maxStars = 0; int maxIndex = -1; for (int i=0; i<nrefcat; ++i) { if (photcatresult[i].nstars.toInt() > maxStars) { maxStars = photcatresult[i].nstars.toInt(); maxIndex = i; } } if (maxIndex == 0) ui->resultPANSTARRSPushButton->setChecked(true); else if (maxIndex == 1) ui->resultSDSSPushButton->setChecked(true); else if (maxIndex == 2) ui->resultSKYMAPPERPushButton->setChecked(true); else if (maxIndex == 3) ui->resultATLASPushButton->setChecked(true); else { // Fallback onto AVGWHITE solution maxIndex = nrefcat; ui->resultAVGWHITEPushButton->setChecked(true); } toggleCalibResult(); buttonPalette.setColor(QPalette::Button, QColor("#44d8cc")); ui->calibratePushButton->setPalette(buttonPalette); ui->calibratePushButton->setEnabled(true); showDone(ui->calibratePushButton, "(1) Calibrate"); emit messageAvailable("Done.", "info"); ui->redComboBox->setEnabled(true); ui->greenComboBox->setEnabled(true); ui->blueComboBox->setEnabled(true); // send the new color factors to iview (if opened) sendColorFactors(); // If no reference stars were retrieved if (photcatresult[maxIndex].nstars.toInt() == 0 || maxIndex == nrefcat) { emit messageAvailable("No G2-type references could be matched for this field. Falling back on 'average white'.", "warning"); } } // Given a name, find the corresponding MyImage* in memory MyImage* ColorPicture::identifyCroppedMyImage(QString name) { for (auto &myImage : croppedList) { if (myImage->name == name) return myImage; } emit messageAvailable("Could not identify "+name+"<br>in the list of cropped images!", "error"); return nullptr; } QVector<QVector<double>> ColorPicture::getObjectData(MyImage *myImage) { QVector<QVector<double>> objData; objData.reserve(myImage->objectList.length()); if (myImage->objectList.length() == 0) { emit messageAvailable("No objects detected in "+myImage->baseName+" !", "error"); } else { for (auto &object : myImage->objectList) { QVector<double> tmp; if (object->FLAGS == 0 && object->FLUX_AUTO > 0.) { // DEC comes first in the catalogs, because the matching alg sorts the vectors for DEC tmp << object->DELTA_J2000 << object->ALPHA_J2000 << object->FLUX_AUTO; objData.append(tmp); } } } return objData; } void ColorPicture::updateFilterRatio() { // Read results QString ratio = QString::number(bbnbFluxRatio, 'f', 3); QString ratioError = QString::number(bbnbFluxRatioError, 'f', 3); ui->filterRatioLineEdit->setText(ratio+" +/- "+ratioError); ui->getRatioPushButton->setText("(1) Estimate flux ratio"); ui->getRatioPushButton->setEnabled(true); ui->narrowbandComboBox->setEnabled(true); ui->broadbandComboBox->setEnabled(true); ui->BBNBcombinePushButton->setEnabled(true); } void ColorPicture::updateBBNBcombine() { QString oldBB = ui->broadbandComboBox->currentText(); QString oldNB = ui->narrowbandComboBox->currentText(); // Update the model (which refreshes all combo boxes) refreshComboBoxes(); // Restore previous combobox selection ui->broadbandComboBox->setCurrentText(oldBB); ui->narrowbandComboBox->setCurrentText(oldNB); ui->BBNBcombinePushButton->setEnabled(true); ui->BBNBcombinePushButton->setText("(2) Combine images"); } void ColorPicture::toggleCalibResult() { int i = 4; int nrefcat = 4; if (ui->resultPANSTARRSPushButton->isChecked()) i = 0; else if (ui->resultSDSSPushButton->isChecked()) i = 1; else if (ui->resultSKYMAPPERPushButton->isChecked()) i = 2; else if (ui->resultATLASPushButton->isChecked()) i = 3; else if (ui->resultAVGWHITEPushButton->isChecked()) i = 4; if (i<=nrefcat) { ui->redFactorLineEdit->setText(photcatresult[i].rfac); ui->redErrorLineEdit->setText(photcatresult[i].rfacerr); ui->greenFactorLineEdit->setText("1.000"); ui->greenErrorLineEdit->setText("0.000"); ui->blueFactorLineEdit->setText(photcatresult[i].bfac); ui->blueErrorLineEdit->setText(photcatresult[i].bfacerr); } else { emit messageAvailable("BUG: code should never enter here", "error"); ui->redFactorLineEdit->clear(); ui->redErrorLineEdit->clear(); ui->greenFactorLineEdit->setText("1.000"); ui->greenErrorLineEdit->setText("0.000"); ui->blueFactorLineEdit->clear(); ui->blueErrorLineEdit->clear(); } } void ColorPicture::readFilterRatioResults(QString filename) { QString path = mainDir+"/color_theli/PHOTCAT_calibration/"; QFile file(path+"/"+filename); QStringList list; QString line; QString ratio = ""; QString ratio_error = ""; if ( file.open(QIODevice::ReadOnly)) { QTextStream stream( &file ); while ( !stream.atEnd() ) { line = stream.readLine().simplified(); list = line.split(" "); if (!line.isEmpty() && list.length() == 2) { ratio = list.at(0); ratio_error = list.at(1); } } file.close(); if (!ratio.isEmpty() && !ratio_error.isEmpty()) { ui->filterRatioLineEdit->setText(ratio+" +/- "+ratio_error); } else { ui->filterRatioLineEdit->clear(); } } else { QMessageBox::warning(this, tr("Could not read filter ratio result."), tr("The file ")+path+"/"+filename+tr(" could not be opened."), QMessageBox::Ok); } } void ColorPicture::updateColorFactorsExternal(QString redFactor, QString blueFactor) { ui->redFactorLineEdit->setText(redFactor); ui->blueFactorLineEdit->setText(blueFactor); resetResultButtonGroup(); } // Invoked by the preview button, as well as by the "get statistics" push button void ColorPicture::on_previewCalibPushButton_clicked() { if (iViewOpen) { iView->raise(); QMessageBox msgBox; msgBox.setText("Left-click into a blank region of the image to obtain image statistics. " "Ideally, this should be the darkest region of the image with few stars.\n\n" "Statistics will be measured in a 9x9 pixel area."); msgBox.exec(); return; } // Load the image viewer checkCalibrationFactor(ui->redFactorLineEdit); checkCalibrationFactor(ui->blueFactorLineEdit); iView = new IView("FITScolor", mainDir+"/color_theli/", ui->redComboBox->currentText(), ui->greenComboBox->currentText(), ui->blueComboBox->currentText(), ui->redFactorLineEdit->text().toFloat(), ui->blueFactorLineEdit->text().toFloat(), this); connect(this, &ColorPicture::colorFactorChanged, iView, &IView::updateColorViewExternal); connect(iView, &IView::colorFactorChanged, this, &ColorPicture::updateColorFactorsExternal); connect(iView, &IView::closed, this, &ColorPicture::updateIviewStatus); connect(iView, &IView::statisticsRequested, this, &ColorPicture::measureStatistics); iViewOpen = true; iView->G2referencePathName = mainDir+"/color_theli/PHOTCAT_calibration/"; iView->show(); if (sender() == ui->getStatisticsPushButton) { QMessageBox msgBox; msgBox.setText("Left-click into a blank region of the image to obtain image statistics. " "Ideally, this should be the darkest region of the image with few stars.\n\n" "Statistics will be measured in a 9x9 pixel area."); msgBox.exec(); } } void ColorPicture::updateIviewStatus() { iViewOpen = false; } void ColorPicture::addCombinedImageReceived(MyImage *combinedImage) { croppedList.append(combinedImage); } void ColorPicture::measureStatistics(long x, long y) { ui->statisticsTableWidget->clear(); int nrows = coaddImageModel->rowCount(); int ncols = 5; ui->statisticsTableWidget->setRowCount(nrows); ui->statisticsTableWidget->setColumnCount(ncols); QStringList header; header << "Image" << "median" << "rms" << "min (black point)" << "max (white point)"; ui->statisticsTableWidget->setHorizontalHeaderLabels(header); // Get the min and max values first QVector<float> minValues; QVector<float> maxValues; for (int i=0; i<nrows; ++i) { QString name = coaddImageModel->index(i,0).data().toString(); for (auto &myImage : croppedList) { if (myImage->name == name) { long xmin = x - 1 - 4; long xmax = x - 1 + 4; long ymin = y - 1 - 4; long ymax = y - 1 + 4; QVector<float> data = myImage->extractPixelValues(xmin, xmax, ymin, ymax); float medVal = medianMask_T(data); float rmsVal = madMask_T(data)*1.486; float minVal = medVal - 6.*rmsVal; // an estimate for the black point float maxVal = medVal + 250.*rmsVal; // an estimate for the white point minValues.append(minVal); maxValues.append(maxVal); QTableWidgetItem *item0 = new QTableWidgetItem(name); QTableWidgetItem *item1 = new QTableWidgetItem(QString::number(medVal, 'f', 3)); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(rmsVal, 'f', 2)); item0->setFlags(item0->flags() ^ Qt::ItemIsEditable); item1->setFlags(item1->flags() ^ Qt::ItemIsEditable); item2->setFlags(item2->flags() ^ Qt::ItemIsEditable); ui->statisticsTableWidget->setItem(i, 0, item0); ui->statisticsTableWidget->setItem(i, 1, item1); ui->statisticsTableWidget->setItem(i, 2, item2); } } } // Black and white points should be the same for all images to preserve colors float commonMin = minVec_T(minValues); float commonMax = maxVec_T(maxValues); for (int i=0; i<nrows; ++i) { QTableWidgetItem *item3 = new QTableWidgetItem(QString::number(commonMin, 'f', 3)); QTableWidgetItem *item4 = new QTableWidgetItem(QString::number(commonMax, 'f', 2)); ui->statisticsTableWidget->setItem(i, 3, item3); ui->statisticsTableWidget->setItem(i, 4, item4); } ui->statisticsTableWidget->resizeColumnsToContents(); statisticsRetrieved = true; } void ColorPicture::resetResultButtonGroup(QString resetLabels) { resultButtonGroup->setExclusive(false); ui->resultSDSSPushButton->setChecked(false); ui->resultSKYMAPPERPushButton->setChecked(false); ui->resultPANSTARRSPushButton->setChecked(false); ui->resultATLASPushButton->setChecked(false); ui->resultAVGWHITEPushButton->setChecked(false); resultButtonGroup->setExclusive(true); if (!resetLabels.isEmpty()) { ui->numPANSTARRSLabel->setText("? stars"); ui->numSDSSLabel->setText("? stars"); ui->numSKYMAPPERLabel->setText("? stars"); ui->numATLASLabel->setText("? stars"); ui->numAVGWHITELabel->setText("? stars"); } } void ColorPicture::on_actionClose_triggered() { this->close(); } void ColorPicture::on_redComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_greenComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_blueComboBox_currentIndexChanged(int index) { if (iViewOpen) { iView->close(); on_previewCalibPushButton_clicked(); } } void ColorPicture::on_narrowbandComboBox_currentTextChanged(const QString &arg1) { ui->filterRatioLineEdit->setText("0"); } void ColorPicture::on_broadbandComboBox_currentTextChanged(const QString &arg1) { ui->filterRatioLineEdit->setText("0"); } void ColorPicture::on_abortPushButton_clicked() { if (workerThread) workerThread->quit(); if (workerThread) workerThread->wait(); }
23,822
C++
.cc
572
35.902098
132
0.692331
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,503
background.cc
schirmermischa_THELI/src/myimage/background.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "instrumentdata.h" #include "../functions.h" #include "myimage.h" #include <gsl/gsl_math.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <vector> #include <QDebug> #include <QMessageBox> void MyImage::backgroundModel(int filtersize, QString splinemode) { // Currently, we always do an interpolation, independently of 'splinemode' if (!successProcessing) return; if (backgroundModelDone) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Background mapping ... ", "image"); filterSize = filtersize; splineMode = splinemode; gridStep = filterSize / subSample; dataBackground_deletable = false; // QVector<bool> maskData(naxis1*naxis2, false); // The dimensions of the padded image (margins) getPadDimensions(); // Pad the image // padImage(); // Place a grid over the image planGrid(); // Calculate background value at each grid point getGridStatistics(); // replace blank grid points with local estimate replaceBlankGridStatistics(); // Spatial median filter of the statistics filterGridStatistics(); // Do the spline fit fitBackgroundGSL(); backgroundModelDone = true; } void MyImage::getMeanBackground() { if (!successProcessing) return; float skysum = 0.; for (auto &pixel : dataBackground) { skysum += pixel; } meanExposureBackground = skysum / (naxis1*naxis2); } void MyImage::fitBackgroundGSL() { if (!successProcessing) return; double *xa = new double[n_grid]; double *ya = new double[m_grid]; double *za = new double[nGridPoints]; // Prepare the input data for (int i=1; i<=n_grid; ++i) xa[i-1] = i*gridStep; for (int j=1; j<=m_grid; ++j) ya[j-1] = j*gridStep; long k=0; for (int j=0; j<m_grid; ++j) { for (int i=0; i<n_grid; ++i) { za[k] = backStatsGrid[k]; ++k; } } const gsl_interp2d_type *T = gsl_interp2d_bicubic; gsl_spline2d *spline = gsl_spline2d_alloc(T, n_grid, m_grid); gsl_interp_accel *xacc = gsl_interp_accel_alloc(); gsl_interp_accel *yacc = gsl_interp_accel_alloc(); // initialize interpolation gsl_spline2d_init(spline, xa, ya, za, n_grid, m_grid); // interpolate; remove padding at the same time dataBackground.clear(); dataBackground.resize(naxis1*naxis2); // dataBackground.squeeze(); // deactivated; causes random crash I don't understand (perhaps not anymore after reading memory directly from /proc/meminfo for (long j=pad_b; j<m_pad-pad_t; ++j) { double y = double(j); for (long i=pad_l; i<n_pad-pad_r; ++i) { if (i-pad_l < 0 || i-pad_l >= naxis1 || j-pad_b < 0 || j-pad_b >= naxis2) qDebug() << "MyImage::background: GSLFIT: padding error"; double x = double(i); dataBackground[i-pad_l+naxis1*(j-pad_b)] = gsl_spline2d_eval(spline, x, y, xacc, yacc); } } gsl_spline2d_free(spline); gsl_interp_accel_free(xacc); gsl_interp_accel_free(yacc); delete [] xa; delete [] ya; delete [] za; xa = nullptr; ya = nullptr; za = nullptr; } void MyImage::getGridStatistics() { if (!successProcessing) return; // Calculate modes by stepping through grid points backStatsGrid.clear(); backStatsGrid.fill(-1e9, nGridPoints); rmsStatsGrid.clear(); rmsStatsGrid.fill(-1., nGridPoints); long sampleSize = gridStep * gridStep / 4; // This many pixels are evaluated at each grid point QVector<float> backgroundSample; backgroundSample.reserve(sampleSize); // for (long index=0; index<nGridPoints; ++index) { // TODO: grid size must be at least twice smaller than the smoothing kernel! for (long jg=1; jg<m_grid-1; ++jg) { for (long ig=1; ig<n_grid-1; ++ig) { long index = ig+n_grid*jg; // Select data points in a square around the current grid point for (long j=grid[1][index]-gridStep/2; j<grid[1][index]+gridStep/2; ++j) { for (long i=grid[0][index]-gridStep/2; i<grid[0][index]+gridStep/2; ++i) { // if (!mask_padded[i+n_pad*j]) backgroundSample.append(data_padded[i+n_pad*j]); if (i-pad_l < 0 || i-pad_l >= naxis1 || j-pad_b < 0 || j-pad_b>=naxis2) continue; // Take into account global mask, and possibly object masks as well (if defined) // With global mask long ii = i-pad_l+naxis1*(j-pad_b); if (globalMaskAvailable && !globalMask[ii]) { if (!weightInMemory) { if (!objectMaskDone || !objectMask[ii]) { // !objectMask[ii] implies objectMaskDone = true backgroundSample.append(dataCurrent[ii]); } } else { if (dataWeight[ii] > 0. && (!objectMaskDone || !objectMask[ii])) { backgroundSample.append(dataCurrent[ii]); } } } // without global mask: external image, e.g. for absZP else { if (!weightInMemory) { if (!objectMaskDone || !objectMask[ii]) { backgroundSample.append(dataCurrent[ii]); } } else { if (dataWeight[ii] > 0. && (!objectMaskDone || !objectMask[ii])) { backgroundSample.append(dataCurrent[ii]); } } } } } QVector<float> sky = modeMask(backgroundSample, "stable"); if (sky[1] > 0.) backStatsGrid[index] = sky[0]; // Histogram peak location (if rms could be evaluated, or data were present) if (sky[1] > 0.) rmsStatsGrid[index] = sky[1]; backgroundSample.clear(); } } // calculate average stdev (ignoring the padded border) skySigma = 0.; float count = 0.; for (auto &sigma : rmsStatsGrid) { if (sigma > 0.) { skySigma += sigma; ++count; } } skySigma /= count; // data_padded.clear(); // data_padded.squeeze(); // mask_padded.clear(); // mask_padded.squeeze(); } // replace a grid point that could not be evaluated with the mean of its closest neighbors void MyImage::replaceBlankGridStatistics() { if (!successProcessing) return; QVector<float> backup = backStatsGrid; long gmax = n_grid < m_grid ? m_grid : n_grid; for (long j=0; j<m_grid; ++j) { for (long i=0; i<n_grid; ++i) { if (backup[i+n_grid*j] == -1e9) { // found a blank grid point long s = 0; float nfound = 0.; float sum = 0.; // search around this point with increasing radius while (nfound < 1. && s<gmax) { int imin = i-s < 0 ? 0 : i-s; int jmin = j-s < 0 ? 0 : j-s; int imax = i+s >= n_grid ? n_grid-1 : i+s; int jmax = j+s >= m_grid ? m_grid-1 : j+s; sum = 0.; nfound = 0.; for (int jj=jmin; jj<=jmax; ++jj) { for (int ii=imin; ii<=imax; ++ii) { float gridVal = backup[ii+n_grid*jj]; if (gridVal > -1e9) { sum += gridVal; ++nfound; } } } ++s; } backStatsGrid[i+n_grid*j] = sum / nfound; } } } if (*verbosity > 1) { emit messageAvailable(chipName + " : mean / stdev = " + QString::number(meanMask_T(backStatsGrid), 'f', 3) + " / " + QString::number(skySigma, 'f', 3), "image"); } } void MyImage::filterGridStatistics() { if (!successProcessing) return; // WARNING: this function alters the values of 'backStatsGrid' // Create a copy QVector<float> backStatsGridOrig = backStatsGrid; // Median filter QVector<float> medianSample; medianSample.reserve(9); // maximally 3x3 for (long j=0; j<m_grid; ++j) { // Stay within bounds // It would be good to include more grid points for the statistics, in particular in the corners int jmin = j-1 < 0 ? 0 : j-1; int jmax = j+1 >= m_grid ? m_grid-1 : j+1; for (long i=0; i<n_grid; ++i) { int imin = i-1 < 0 ? 0 : i-1; int imax = i+1 >= n_grid ? n_grid-1 : i+1; for (int jj=jmin; jj<=jmax; ++jj) { for (int ii=imin; ii<=imax; ++ii) { medianSample.push_back(backStatsGridOrig[ii+n_grid*jj]); } } backStatsGrid[i+n_grid*j] = straightMedian_T(medianSample); medianSample.clear(); } } } void MyImage::getPadDimensions() { if (!successProcessing) return; // The actual padding width is twice as large as the gridStep // to ensure we have enough space to evaluate the grid without having to care for boundaries int w = 2 * gridStep; // Output contains left, bottom, right, top pad widths, and overall dimensions padDims.clear(); pad_r = w; // same as padWidth w unless +1 to make even dimension pad_t = w; pad_l = w; pad_b = w; if (padMode == "normal") { // make an image with even dimensions to avoid unclear quadrant swapping (if we FFT the padded image elsewhere) if ( naxis1 % 2 != 0) pad_r++; if ( naxis2 % 2 != 0) pad_t++; n_pad = naxis1 + pad_l + pad_r; m_pad = naxis2 + pad_b + pad_t; } else { // padMode = "dyadic" // pad first, then make dyadic image size n_pad = pow(2, ceilf( logf(naxis1+2*w) / logf(2.))); m_pad = pow(2, ceilf( logf(naxis2+2*w) / logf(2.))); pad_l = (n_pad - naxis1) / 2; pad_b = (m_pad - naxis2) / 2; pad_r = n_pad - naxis1 - pad_l; pad_t = m_pad - naxis2 - pad_b; } } /* // The following code pads the image with data. However, we don't need that. // The grid positions in the padded data are filled using known grid points inside the image. // Code is kept in case I need it in the future // Pads an image with a given border width. If mode="dyadic", expands it to the next largest power of 2 // We use twice the grid step so that we have sufficient space to comfortably place a grid over the image including the boundaries. // By making it twice as large, we don't need to introduce boundary conditions when evaluating histograms outside the nominal image area. void MyImage::padImage() { // resize the vector correspondingly data_padded.resize(n_pad*m_pad); mask_padded.fill(true, n_pad*m_pad); // everything is masked per default, then unmask the true image area long n = naxis1; long m = naxis2; // copy image to center of padded image for (long j=pad_b; j<m+pad_b; ++j) { for (long i=pad_l; i<n+pad_l; ++i) { data_padded[i+n_pad*j] = dataCurrent[(i-pad_l)+n*(j-pad_b)]; mask_padded[i+n_pad*j] = globalMask[(i-pad_l)+n*(j-pad_b)]; } } int width = 100; // size of the moving window (in both dimensions) // pad edges padEdgeLR(width, "l", 0, pad_l, pad_b, m+pad_b); padEdgeLR(width, "r", n+pad_l, n_pad, pad_b, m+pad_b); padEdgeBT(width, "b", pad_l, n+pad_l, 0, pad_b); padEdgeBT(width, "t", pad_l, n+pad_l, m+pad_b, m_pad); // pad corners padCorner(width, "ll", 0, pad_l, 0, pad_b); padCorner(width, "lr", n+pad_l, n_pad, 0, pad_b); padCorner(width, "ul", 0, pad_l, m+pad_b, m_pad); padCorner(width, "ur", n+pad_l, n_pad, m+pad_b, m_pad); } // This function provides a small correction when approaching the lower and upper boundary of an array // with a sliding window. The size of the sliding window is maintained; // Example: // i=0: 0 1 2 3 4 // i=1: 0 1 2 3 4 // i=2: 0 1 2 3 4 // i=3: 1 2 3 4 5 // i=4: 2 3 4 5 6 // i=5: 3 4 5 6 7 // i=6: 4 5 6 7 8 // i=7: 5 6 7 8 9 // i=8: 5 6 7 8 9 // i=9: 5 6 7 8 9 int MyImage::padCorr(int i, int w, int max) { if (w-i>0) return w-i; else if (w+i>=max) return max-w-i-1; else return 0; } // Calculate a local moving median around the left and right edge void MyImage::padEdgeLR(int width, QString edge, long ipadmin, long ipadmax, long jpadmin, long jpadmax) { long n = naxis1; long m = naxis2; long imin; long imax; if (edge == "l") { imin = 0; imax = width; } else if (edge == "r") { imin = n-width; imax = n; } else return; // Containers for the median edge values, the mask, and the sample QVector<float> edgeData; QVector<bool> edgeMask; QVector<float> sample; edgeData.reserve(m); edgeMask.reserve(m); sample.reserve(width*width); // Calculate the padded values int wh = width / 2; int step = 3; // accelerator (if larger than 1; not implemented in GUI) for (long j=0; j<m; ++j) { // run up the vertical edge for (long jj=j-wh+padCorr(j,wh,m); jj<=j+wh+padCorr(j,wh,m); jj+=step) { // local samples along NAXIS2 for (long i=imin; i<imax; i+=step) { // local samples along NAXIS1 if (!globalMask[i+n*jj]) sample.push_back(dataCurrent[i+n*jj]); } } edgeData.push_back(straightMedian_T(sample)); if (sample.length() == 0) edgeMask.push_back(true); else edgeMask.push_back(false); sample.clear(); } // Update the padded image for (long j=jpadmin; j<jpadmax; ++j) { for (long i=ipadmin; i<ipadmax; ++i) { data_padded[i+n_pad*j] = edgeData[j-pad_b]; mask_padded[i+n_pad*j] = edgeMask[j-pad_b]; } } } // Calculate a local moving median around the bottom and top edge void MyImage::padEdgeBT(int width, QString edge, long ipadmin, long ipadmax, long jpadmin, long jpadmax) { long n = naxis1; long m = naxis2; long jmin; long jmax; if (edge == "b") { jmin = 0; jmax = width; } else if (edge == "t") { jmin = m-width; jmax = m; } else return; // Containers for the median edge values, the mask, and the sample QVector<float> edgeData; QVector<bool> edgeMask; QVector<float> sample; edgeData.reserve(n); edgeMask.reserve(n); sample.reserve(width*width); // Calculate the padded values int wh = width / 2; int step = 3; // accelerator (if larger than 1; sparse sampling) for (long i=0; i<n; ++i) { // run along the horizontal edge for (long ii=i-wh+padCorr(i,wh,n); ii<i+wh+padCorr(i,wh,n); ii+=step) { // local samples along NAXIS1 for (long j=jmin; j<jmax; j+=step) { // local samples along NAXIS2 if (!globalMask[ii+n*j]) sample.push_back(dataCurrent[ii+n*j]); } } edgeData.push_back(straightMedian_T(sample)); if (sample.length() == 0) edgeMask.push_back(true); else edgeMask.push_back(false); sample.clear(); } // Update the padded image for (long j=jpadmin; j<jpadmax; ++j) { for (long i=ipadmin; i<ipadmax; ++i) { data_padded[i+n_pad*j] = edgeData[i-pad_l]; mask_padded[i+n_pad*j] = edgeMask[i-pad_l]; } } } // Calculate a local median for every image corner void MyImage::padCorner(int width, QString corner, long ipadmin, long ipadmax, long jpadmin, long jpadmax) { long n = naxis1; long m = naxis2; long imin = 0; long imax = 0; long jmin = 0; long jmax = 0; if (corner == "ll") { imin = 0; imax = width; jmin = 0; jmax = width; } else if (corner == "lr") { imin = n-width; imax = n; jmin = 0; jmax = width; } else if (corner == "ul") { imin = 0; imax = width; jmin = m-width; jmax = m; } else { // ur imin = n-width; imax = n; jmin = m-width; jmax = m; } // Container for the statistical sample QVector<float> sample; sample.reserve(width*width); for (long j=jmin; j<jmax; ++j) { for (long i=imin; i<imax; ++i) { if (!globalMask[i+n*j]) sample.push_back(dataCurrent[i+n*j]); } } float cornerData = straightMedian_T(sample); bool cornerMask; if (sample.length() == 0) cornerMask = true; else cornerMask = false; // Update the padded image with the corner values for (long j=jpadmin; j<jpadmax; ++j) { for (long i=ipadmin; i<ipadmax; ++i) { data_padded[i+n_pad*j] = cornerData; mask_padded[i+n_pad*j] = cornerMask; } } } */ // Calculate grid points for a (padded) image // The grid "starts" gridSize inside each dimension (so we don't have to consider boundaries) void MyImage::planGrid() { if (!successProcessing) return; // Reset the grid grid.clear(); // Number of grid points in each dimension and overall number of grid points n_grid = n_pad / gridStep; m_grid = m_pad / gridStep; // The first grid point in one dimension is located gridStep pixels in that dimension. // The last point must be at least half a gridStep away from the border // Some integer math is at work here if (n_pad - n_grid*gridStep < gridStep/2) n_grid--; if (m_pad - m_grid*gridStep < gridStep/2) m_grid--; nGridPoints = n_grid * m_grid; QVector<long> grid_x(nGridPoints); QVector<long> grid_y(nGridPoints); long count = 0; for (int j=1; j<=m_grid; ++j) { long jgrid = j*gridStep; for (int i=1; i<=n_grid; ++i) { long igrid = i*gridStep; grid_x[count] = igrid; // points along NAXIS1 grid_y[count] = jgrid; // points along NAXIS2 ++count; } } grid << grid_x << grid_y; } void MyImage::releaseBackgroundMemory(QString mode) { emit setMemoryLock(true); if (minimizeMemoryUsage || mode == "entirely") { dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; } else { dataBackground_deletable = true; } grid.clear(); grid.squeeze(); backStatsGrid.clear(); backStatsGrid.squeeze(); rmsStatsGrid.clear(); rmsStatsGrid.squeeze(); emit setMemoryLock(false); } void MyImage::releaseBackgroundMemoryBackgroundModel() { emit setMemoryLock(true); if (leftBackgroundWindow) { dataBackground.clear(); dataBackground.squeeze(); grid.clear(); grid.squeeze(); backStatsGrid.clear(); backStatsGrid.squeeze(); rmsStatsGrid.clear(); rmsStatsGrid.squeeze(); backgroundModelDone = false; } emit setMemoryLock(false); } void MyImage::subtractBackgroundModel() { if (!successProcessing) return; long i=0; for (auto &pixel : dataCurrent) { if (!globalMask.isEmpty()) { if (!globalMask[i]) pixel -= dataBackground[i]; } else { pixel -= dataBackground[i]; } ++i; } }
20,709
C++
.cc
549
29.728597
168
0.569784
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,504
weighting.cc
schirmermischa_THELI/src/myimage/weighting.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/tools.h" #include "../tools/polygon.h" #include "../processingInternal/data.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> void MyImage::readWeight() { dataWeight_deletable = false; // Leave if image is already loaded if (weightInMemory) return; else { int status = 0; fitsfile *fptr = nullptr; QString fileName = weightPath+"/"+weightName+".fits"; initFITS(&fptr, fileName, &status); readDataWeight(&fptr, &status); fits_close_file(fptr, &status); if (status) { printCfitsioError(__func__, status); successProcessing = false; weightInMemory = false; } else { weightInMemory = true; weightOnDrive = true; successProcessing = true; } } } void MyImage::initWeightfromGlobalWeight(const QList<MyImage*> &gwList) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Init weight from global weight ...", "image"); // Load the matching global weight bool loadSuccess = false; for (auto &gw: gwList) { if (gw->filter == filter && filter == "RGB") { emit messageAvailable("MyImage::initWeightFromGlobalWeight(): You must first apply the flatfield to the science data!", "error"); emit critical(); successProcessing = false; loadSuccess = false; break; } if (gw->filter == filter) { if (!gw->imageInMemory) gw->readImageThreadSafe(); // if (!gw->imageInMemory) gw->readImage(); dataWeight = gw->dataCurrent; loadSuccess = true; weightInMemory = true; break; } } if (!loadSuccess) { emit messageAvailable(chipName + " : MyImage::initWeightFromGlobalWeight(): Did not find the globalweight for filter " + filter, "error"); emit critical(); successProcessing = false; } // An oddball, not sure that will ever happen if (loadSuccess && dataWeight.length() != dataCurrent.length()) { emit messageAvailable(chipName + " : MyImage::initWeightFromGlobalWeight(): weight and science image do not have the same size!", "error"); emit critical(); successProcessing = false; } } void MyImage::thresholdWeight(QString imageMin, QString imageMax) { if (imageMin.isEmpty() && imageMax.isEmpty()) return; if (imageMin == imageMax) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Thresholding weight if image is outside ["+imageMin+","+imageMax+"] ...", "image"); float minVal = imageMin.toFloat(); float maxVal = imageMax.toFloat(); if (imageMin.isEmpty()) minVal = -1.e9; if (imageMax.isEmpty()) maxVal = 1.e9; if (minVal > maxVal) std::swap(minVal, maxVal); long i=0; for (auto &pixel : dataWeight) { if (dataCurrent.at(i) < minVal) pixel = 0.; if (dataCurrent.at(i) > maxVal) pixel = 0.; ++i; } weightModified = true; } void MyImage::maskSaturatedPixels(QString tolerance, bool requested) { if (!successProcessing) return; if (!requested) return; float toleranceFloat = 1.0; if (!tolerance.isEmpty()) toleranceFloat = tolerance.toFloat(); long i=0; for (auto &pixel : dataWeight) { if (dataCurrent.at(i) >= saturationValue*toleranceFloat) pixel = 0.; ++i; } weightModified = true; } void MyImage::roundEdgeOfWeight(float edge, bool roundEdge) { dataWeightSmooth = dataWeight; for (long j=0; j<naxis2; ++j) { float dymin = (j <= naxis2-j) ? j : naxis2-j; for (long i=0; i<naxis1; ++i) { float dxmin = (i <= naxis1-i) ? i : naxis1-i; float d = (dxmin <= dymin) ? dxmin : dymin; // Optionally, round the edge if (roundEdge) { if (dymin <= edge && dxmin <= edge) { d = edge - sqrt((edge-dxmin) * (edge-dxmin) + (edge-dymin) * (edge-dymin)); if (d < 0.) d = 0.; } } if (d <= edge) { dataWeightSmooth[i+naxis1*j] = 0.5*(1.-cos(d/edge*3.14159)) * dataWeight.at(i+naxis1*j); } } } } void MyImage::applyPolygons() { if (!successProcessing) return; // QString rootName = baseName; // rootName.truncate(rootName.lastIndexOf('_')); QString regionFileName = path+"/reg/"+chipName+".reg"; QFile regionFile(regionFileName); if (!regionFile.exists()) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Mask found, applying mask to weight ...", "image"); addRegionFilesToWeight(naxis1, naxis2, regionFileName, dataWeight); weightModified = true; } void MyImage::freeWeight() { emit setMemoryLock(true); if (minimizeMemoryUsage) { dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; weightModified = false; } else { dataWeight_deletable = true; } emit setMemoryLock(false); } void MyImage::maskBloomingSpike(QString instType, QString range, QString minVal, bool requested, QString bloomMin, QString bloomMax) { if (!successProcessing) return; if (!requested) return; if (instType != "OPT") return; if (*verbosity > 1) emit messageAvailable(chipName + " : Detecting blooming spikes ...", "image"); float histstep = 1000.; float maxval = maxVec_T(dataCurrent); float minval = minVal.toFloat(); if (minVal.isEmpty()) minval = meanMask_T(dataCurrent) + 10.*rmsMask_T(dataCurrent); if (maxval > 200000.) maxval = 200000.; QVector<bool> mask(naxis1*naxis2, true); // false if pixel is good, true if pixel is "bloomed" // masking long l = 0; long k = 0; for (auto &pixel : dataCurrent) { if (pixel < minval) mask[k] = false; else ++l; ++k; } long npix1 = l; // number of potentially bloomed pixels if (npix1 == 0) { if (*verbosity > 1) emit messageAvailable(chipName + " : No pixels found above blooming threshold ...", "image"); return; } // detect value of blooming spike QVector<float> pixels(npix1,0); QVector<long> pixelcoords(npix1,0); l = 0; k = 0; for (auto &pixel : dataCurrent) { if (mask[k]) { pixels[l] = pixel; pixelcoords[l] = k; ++l; } ++k; } // The count thresholds for blooming spikes float bloommin = 0.; float bloommax = 0.; if (!bloomMin.isEmpty() && !bloomMax.isEmpty()) { // manually given; NOT IMPLEMENTED in GUI. I think the auto mode works just fine bloommin = bloomMin.toFloat(); bloommax = bloomMax.toFloat(); } else { // auto long nhist = ceil( (maxval-minval) / histstep); QVector<float> hist(nhist,0); for (long j=0; j<npix1; ++j) { for (k=0; k<nhist; ++k) { if (pixels[j] >= minval + histstep * k && pixels[j] < minval + histstep * (k+1)) { ++hist[k]; } } } float maxhist = maxVec_T(hist); long bloommaxindex = maxIndex(hist); float bloomval = minval + bloommaxindex * histstep; // detect a reasonable dynamic range for the blooming spike long max_int = bloommaxindex; long i = 0; // was i=1; dont understand why; fails if the highest value is at the last position in hist, hence i=0 long maxindex_int = 0; while (max_int < nhist && hist[max_int] > 0.1 * maxhist) { // max_int < nhist is always fulfilled, but used here for safe coding practices max_int = bloommaxindex + i; if (max_int > nhist-1) { max_int = nhist-1; break; } maxindex_int = max_int; ++i; } long min_int = bloommaxindex; i = 0; // was i=1; dont understand why; fails if the highest value is at the last position in hist, hence i=0 long minindex_int = 0; while (hist[min_int] > 0.1 * maxhist && min_int > 0) { min_int = bloommaxindex - i; if (min_int < 0) { min_int = 0; break; } minindex_int = min_int; ++i; } float rangeval = range.toFloat(); bloommin = minval + (minindex_int - 1) * histstep - rangeval; bloommax = minval + (maxindex_int + 1) * histstep + rangeval; bloommax = bloomval + 1.5 * (bloommax - bloomval); } // qDebug() << bloommin << bloommax; // Blooming range: bloommin bloommax // keep only pixels with values within the blooming range l = 0; for (long i=0; i<npix1; ++i) { if (pixels[i] >= bloommin && pixels[i] <= bloommax) { ++l; } } long npix2 = l; // Number of bloomed pixels QVector<float> pixels2; QVector<long> pixelcoords2; pixels2.reserve(npix2); pixelcoords2.reserve(npix2); for (long i=0; i<npix1; ++i) { if (pixels[i] >= bloommin && pixels[i] <= bloommax) { pixels2.append(pixels[i]); pixelcoords2.append(pixelcoords[i]); } } // Mask the bloomed pixels in the weight for (long i=0; i<npix2; ++i) { dataWeight[pixelcoords2[i]] = 0.; } weightModified = true; QString bloomRange = "["+QString::number(long(bloommin))+","+QString::number(long(bloommax))+"]"; if (*verbosity > 1) emit messageAvailable(chipName + " : Bloomed pixels masked. Dynamic range: "+bloomRange, "image"); } void MyImage::laplaceFilter(QVector<float> &dataFiltered) { // Laplace kernel QVector<float> kernel = {-1., -2., -1., -2., +12., -2., -1., -2., -1.}; // Laplace filtering using direct convolution, to enhance local defects long n = naxis1; long m = naxis2; float datatmp = 0.; float baseLevel = medianMask(dataCurrent); for (long j=1; j<m-1; ++j) { for (long i=1; i<n-1; ++i) { long k = i+n*j; float sum = 0.; int l = 0; for (int jt=j-1; jt<=j+1; ++jt) { for (int it=i-1; it<=i+1; ++it) { long t = it+n*jt; datatmp = dataCurrent.at(t) - baseLevel + 1000.; // make sure the image has a positive background sum += datatmp; dataFiltered[k] += datatmp * kernel[l]; ++l; } } // the filtered image is flux-normalized. // Purely empirical, suppresses stars much better (when afterwards subtracting a local median of the laplace filtered image) // than if a local median or mean background is subtracted instead. // Since we divide, we must make sure the local level is significantly larger than zero, hence the +1000. dataFiltered[k] /= sum; } } } void MyImage::median2D(const QVector<float> &data_in, QVector<float> &data_out, int filtersize) { int s = 2*filtersize+1; int n = naxis1; int m = naxis2; s = s*s; QVector<float> chunk(s,0); for (int j=0; j<m; ++j) { for (int i=0; i<n; ++i) { if (!globalMask.isEmpty()) { if (globalMask[i+n*j]) continue; } long k = 0; for (int jt=j-filtersize; jt<=j+filtersize; ++jt) { for (int it=i-filtersize; it<=i+filtersize; ++it) { long t = it+n*jt; if (!globalMask.isEmpty()) { if (it>=0 && jt>=0 && it<n && jt<m && !globalMask[t]) { chunk[k++] = data_in[t]; } } else { if (it>=0 && jt>=0 && it<n && jt<m) { chunk[k++] = data_in[t]; } } } } data_out[i+n*j] = straightMedianInline(chunk); } } } // Turns out this algorithm is similar to "LAcosmic" (http://www.astro.yale.edu/dokkum/lacosmic/) void MyImage::cosmicsFilter(QString aggressiveness) { if (!successProcessing) return; if (aggressiveness.isEmpty()) return; float aggressiveFactor = aggressiveness.toFloat(); if (aggressiveFactor == 0.) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Filtering spurious pixels ...", "image"); long n = naxis1; long m = naxis2; QVector<float> dataLaplace(n*m); QVector<float> dataMedian(n*m); // Laplace filter, then median filter the Laplace filtered image laplaceFilter(dataLaplace); // CHECK: hogging some memory median2D(dataLaplace, dataMedian, 1); // CHECK: hogging some memory // Remove the median image from the Laplace image. // Suppresses residuals from bright but unsaturated stars long k = 0; for (auto &pixel : dataLaplace) { pixel -= dataMedian[k]; ++k; } float rms = 1.48 * madMask_T(dataLaplace, globalMask); float thresh = 8.0 / aggressiveFactor; // user-adjusted threshold; the higher, the lower the threshold. Default: 8 sigma detection float cutoff = thresh*rms; // Initiate cosmics mask QVector<bool> cosmicsMask(n*m, false); // Thresholding step 1 // Everything deviating by more than 'cutoff' k = 0; for (auto &pixel : dataLaplace) { // not masking negative outliers because of the compensation of the laplace kernel if (pixel > cutoff) cosmicsMask[k] = true; ++k; } // Thresholding step 2 // If pixels above and below, or left and right are masked, then the current pixel gets also masked QVector<bool> mask_tmp = cosmicsMask; for (int j=1; j<m-1; ++j) { for (int i=1; i<n-1; ++i) { if ((mask_tmp[i-1+n*j] && mask_tmp[i+1+n*j]) || (mask_tmp[i+n*(j-1)] && mask_tmp[i+n*(j+1)])) { cosmicsMask[i+n*j] = true; } } } // Thresholding step 3 // If at least 2 of the 8 surrounding pixels deviate by more than 'cutoff', and are not in the same row or column, // then the current pixel gets also masked. for (int j=1; j<m-1; ++j) { for (int i=1; i<n-1; ++i) { int count = 0; int isum = 0; int jsum = 0; for (int jt=j-1; jt<=j+1; ++jt) { for (int it=i-1; it<=i+1; ++it) { long t = it+n*jt; if (dataLaplace[t] > cutoff) { isum += it; jsum += jt; ++count; } } } // Using the mean i and j to make sure pixels are not in the same column; // This is to avoid that a single bad column/row gets tripled in width. float meani = float(isum)/float(count); float meanj = float(jsum)/float(count); if (count >= 2 && fabs(meani-i) < 1. && fabs(meanj-j) < 1. ) cosmicsMask[i+n*j] = true; } } // Thresholding step 4 // If at least 4 out of the 8 surrounding pixels deviate by more than 0.5*cutoff, then the current pixel gets also masked for (int j=1; j<m-1; ++j) { for (int i=1; i<n-1; ++i) { int count = 0; for (int jt=j-1; jt<=j+1; ++jt) { for (int it=i-1; it<=i+1; ++it) { long t = it+n*jt; if (dataLaplace[t] > 0.5*cutoff) ++count; } } if (count >= 4) cosmicsMask[i+n*j] = true; } } // Apply the cosmics mask to the weight map k = 0; for (auto &pixel : dataWeight) { if (cosmicsMask[k]) pixel = 0.; ++k; } weightModified = true; }
16,852
C++
.cc
437
29.97254
155
0.569383
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,505
tifftools.cc
schirmermischa_THELI/src/myimage/tifftools.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "../functions.h" #include "myimage.h" #include "tiffio.h" // nothing #include <QDebug> void MyImage::toTIFF(int bit, float minthresh, float maxthresh, bool zscaleing, float grey, float gamma) { /* // If no dynamic range provided, use the data min/max values if (!zscaleing) { minthresh = minVec_T(dataCurrent); maxthresh = maxVec_T(dataCurrent); } */ if (*verbosity >= 2) emit messageAvailable("Creating "+baseName+".tiff ...", "ignore"); if (dataTIFF.isEmpty()) dataTIFF = dataCurrent; long n = naxis1; long m = naxis2; long dim = n*m; // If z-scale is requested if (zscaleing) { float medVal = medianMask_T(dataTIFF); float rmsVal = rmsMask_T(dataTIFF); minthresh = medVal - 2.*rmsVal; maxthresh = medVal + 10.*rmsVal; } // If gamma correction if requested if ( gamma != 1.0 ) { gamma = 1./gamma; double gmaxlevel = pow(maxthresh, gamma); #pragma omp parallel for for (long k=0; k<dim; ++k) { dataTIFF[k] = pow(dataTIFF[k], gamma) / gmaxlevel * maxthresh; } } // Clipping min and max values #pragma omp parallel for for (long k=0; k<dim; k++) { if (dataTIFF[k] <= minthresh) dataTIFF[k] = minthresh; if (dataTIFF[k] >= maxthresh) dataTIFF[k] = maxthresh; } float blowup = 0.; if (bit == 8) { grey = grey / 100. * 253.; blowup = (253. - grey) / (maxthresh - minthresh); } else { grey = grey / 100. * 65000.; blowup = (65000. - grey) / (maxthresh - minthresh); } std::vector< std::vector<long> > imtiff(n); for (long i=0; i<n; ++i) { imtiff[i].resize(m,0); } #pragma omp parallel for for (long i=0; i<n; ++i) { for (long j=0; j<m; ++j) { dataTIFF[i+n*j] = blowup * (dataTIFF[i+n*j] - minthresh) + grey; // flipping TIFF in y dir imtiff[i][naxis2-j-1] = (long) dataTIFF[i+n*j]; } } QString outname = path+"/"+baseName+".tiff"; TIFF *outtiff; // pointer to the TIFF file, defined in tiffio.h outtiff = TIFFOpen(outname.toUtf8().data(), "w"); TIFFSetField(outtiff, TIFFTAG_IMAGEWIDTH, n); TIFFSetField(outtiff, TIFFTAG_IMAGELENGTH, m); TIFFSetField(outtiff, TIFFTAG_COMPRESSION, 1); if (bit == 8) TIFFSetField(outtiff, TIFFTAG_BITSPERSAMPLE, 8); if (bit == 16) TIFFSetField(outtiff, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(outtiff, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(outtiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); TIFFSetField(outtiff, TIFFTAG_PLANARCONFIG, 1); TIFFSetField(outtiff, TIFFTAG_SOFTWARE, "THELI"); TIFFSetField(outtiff, TIFFTAG_IMAGEDESCRIPTION, "Created by THELI"); if (bit == 8) { uint8 *outbuf = (uint8 *)_TIFFmalloc(TIFFScanlineSize(outtiff)); for (long row=0; row<m; ++row) { uint8 *outb = outbuf; for (long column=0; column<n; ++column) { *outb++ = (uint8) (imtiff[column][row]); } TIFFWriteScanline(outtiff, outbuf, row, 0); } TIFFClose(outtiff); _TIFFfree(outbuf); } else { // bit == 16 uint16 *outbuf = (uint16 *)_TIFFmalloc(TIFFScanlineSize(outtiff)); for (long row=0; row<m; ++row) { uint16 *outb = outbuf; for (long column=0; column<n; ++column) { *outb++ = (uint16) (imtiff[column][row]); } TIFFWriteScanline(outtiff, outbuf, row, 0); } TIFFClose(outtiff); _TIFFfree(outbuf); } }
4,340
C++
.cc
115
31.356522
104
0.62078
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,506
fitsinterface.cc
schirmermischa_THELI/src/myimage/fitsinterface.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include <omp.h> #include "../tools/cfitsioerrorcodes.h" #include "wcs.h" #include "wcshdr.h" #include "../functions.h" #include <QMessageBox> #include <QFile> #include <QFileInfo> #include <QDebug> // Extract the FILTER keyword from a yet unopened FITS file void MyImage::readFILTER(QString loadFileName) { if (loadFileName.isEmpty()) loadFileName = path + pathExtension + "/" + baseName + ".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); char filterchar[80]; fits_read_key_str(fptr, "FILTER", filterchar, NULL, &status); fits_close_file(fptr, &status); QString filterstring(filterchar); printCfitsioError(__func__, status); filter = filterstring.simplified(); } // Extract the NAXIS1, NAXIS2, CRPIX1, CRPIX2, SKYVALUE and FLXSCALE keywords from a yet unopened (resampled) FITS file for swarpfilter() bool MyImage::informSwarpfilter(long &naxis1, long &naxis2, double &crpix1, double &crpix2, double &sky, double &fluxscale, bool checkFluxScale) { QString loadFileName = path + "/" + name; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); fits_read_key_dbl(fptr, "CRPIX1", &crpix1, NULL, &status); fits_read_key_dbl(fptr, "CRPIX2", &crpix2, NULL, &status); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); if (checkFluxScale) fits_read_key_dbl(fptr, "FLXSCALE", &fluxscale, NULL, &status); else fluxscale = 1.0; // get the sky value from the MyImage if not present in the header of the FITS file // (in case the user did not run the calibration step) int preSky = status; fits_read_key_dbl(fptr, "SKYVALUE", &sky, NULL, &status); int postSky = status; if (!preSky && postSky) { sky = skyValue; if (sky != 0.) status = 0; else status = 1; } fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (fluxscale == 0.) { emit messageAvailable(name + ": FLXSCALE = 0 in resampled FITS header. Relative photometry failed or not propagated correctly during scamp run", "error"); emit critical(); return false; } if (status) return false; else return true; } void MyImage::initFITS(fitsfile **fptr, QString loadFileName, int *status) { if (loadFileName.isNull() || loadFileName.isEmpty()) { *status = 1; emit messageAvailable(name+"MyImage::initFITS(): file name empty or not initialized!", "error"); return; } // Bypassing a memory leak in cfitsio QFile file(loadFileName); if (!file.exists()) { emit messageAvailable(name+" MyImage::initFITS(): File does not exist at current location!", "error"); *status = 104; return; } fits_open_file(fptr, loadFileName.toUtf8().data(), READONLY, status); fits_get_num_hdus(*fptr, &numExt, status); if (numExt > 1) { QMessageBox msgBox; msgBox.setText(name+" is a multi-extension FITS file, which is currently not supported."); msgBox.exec(); *status = 1; } } void MyImage::readHeader(fitsfile **fptr, int *status) { if (*status) return; // Read the entire header. This should always work! fits_hdr2str(*fptr, 0, NULL, 0, &fullheader, &numHeaderKeys, status); fullheaderAllocated = true; if (*status) return; // Not reading all keywords from coadded FITS header // qDebug() << fullheader; fullHeaderString = QString::fromUtf8(fullheader); // Map the header onto a QVector<QString> int cardLength = 80; long length = fullHeaderString.length(); if (length<80) return; header.clear(); for (long i=0; i<=length-cardLength; i+=cardLength) { QStringRef subString(&fullHeaderString, i, cardLength); QString string = subString.toString(); header.push_back(string); } } void MyImage::readData(fitsfile **fptr, int *status) { if (*status) return; long naxis[2]; // Get image geometry fits_get_img_size(*fptr, 2, naxis, status); // Read the data block naxis1 = naxis[0]; naxis2 = naxis[1]; long nelements = naxis1*naxis2; // QVector<float> cannot hold more than 2^29 elements!!! float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fits_read_img(*fptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, status); if (! *status) { dataCurrent.resize(nelements); for (long i=0; i<nelements; ++i) { // if (isinf(buffer[i])) data[i] = 0.; // else data[i] = buffer[i]; dataCurrent[i] = buffer[i]; } imageInMemory = true; } dataCurrent.squeeze(); // shed excess memory delete [] buffer; buffer = nullptr; } void MyImage::readDataWeight(fitsfile **fptr, int *status) { if (*status) return; long naxis[2]; // Get image geometry fits_get_img_size(*fptr, 2, naxis, status); // Read the data block long nax1 = naxis[0]; long nax2 = naxis[1]; long nelements = nax1*nax2; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fits_read_img(*fptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, status); if (! *status) { dataWeight.resize(nelements); for (long i=0; i<nelements; ++i) { // if (isinf(buffer[i])) data[i] = 0.; // else data[i] = buffer[i]; dataWeight[i] = buffer[i]; } } dataWeight.squeeze(); // shed excess memory // if the weight image is loaded before the science data, // e.g. the GUI is started and the user goes into the memory viewer to load the weight directly, // then naxis1/2 is not defined, leading to a crash if (naxis1 == 0 && naxis2 == 0) { naxis1 = nax1; naxis2 = nax2; } delete [] buffer; buffer = nullptr; } bool MyImage::loadData(QString loadFileName) { // pathExtension needed to load image when clicking on deactivated filename in memory table viewer if (loadFileName.isEmpty()) loadFileName = path + "/" + pathExtension + "/" + chipName+processingStatus->statusString+".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); readData(&fptr, &status); #pragma omp critical { initWCS(); } initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; if (status) return false; else return true; } // for weights only, when having to read the globalweights bool MyImage::loadDataThreadSafe(QString loadFileName) { int status = 0; #pragma omp critical { if (loadFileName.isEmpty()) loadFileName = path + "/" + chipName+processingStatus->statusString+".fits"; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); readData(&fptr, &status); initWCS(); initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; } if (status) return false; else return true; } // Setup the WCS void MyImage::initWCS() { // CHECK: This line must be commented so that the redshift module works. // For a reason I don't understand 'successProcessing' is wrong for the spectra when loaded. // if (!successProcessing) return; emit setWCSLock(true); // It appears that not everything in the wcslib is threadsafe int nreject; int nwcs; int check = wcspih(fullheader, numHeaderKeys, 0, 0, &nreject, &nwcs, &wcs); if (check > 1) { emit messageAvailable("MyImage::initWCS(): " + baseName + ": wcspih() returned" + QString::number(check), "error" ); emit critical(); successProcessing = false; wcsInit = false; emit setWCSLock(false); return; } if (nwcs == 0 || check == 1) { // OK state, e.g. for master calibrators which don't have a valid WCS if (*verbosity > 2) emit messageAvailable(chipName + " : No WCS representation found", "image"); wcsInit = false; emit setWCSLock(false); return; } int wcsCheck = wcsset(wcs); if (wcsCheck > 0) { QString wcsError = ""; if (wcsCheck == 1) wcsError = "Null wcsprm pointer passed"; // Should be caught by 'if' conditions above if (wcsCheck == 2) wcsError = "Memory allocation failed"; if (wcsCheck == 3) wcsError = "Linear transformation matrix is singular"; if (wcsCheck == 4) wcsError = "Inconsistent or unrecognized coordinate axis types"; if (wcsCheck == 5) wcsError = "Invalid parameter value"; if (wcsCheck == 6) wcsError = "Invalid coordinate transformation parameters"; if (wcsCheck == 7) wcsError = "Ill-conditioned coordinate transformation parameters"; emit messageAvailable("MyImage::initWCS(): wcsset() error : " + wcsError, "error"); emit critical(); successProcessing = false; wcsInit = false; emit setWCSLock(false); return; } wcsInit = true; plateScale = sqrt(wcs->cd[0] * wcs->cd[0] + wcs->cd[2] * wcs->cd[2]) * 3600.; // in arcsec; technically, this is the increment in the x-axis if (plateScale == 0.) plateScale = 1.0; if (*verbosity > 2) { emit messageAvailable(chipName + " : RA / DEC = " + QString::number(wcs->crval[0], 'f', 6) + " " + QString::number(wcs->crval[1], 'f', 6), "image"); } emit setWCSLock(false); } // If header data are needed, but not (yet) the data block. // E.g. if the GUI is started, and the first task is to download the reference catalog or to update the zero-th order solution void MyImage::loadHeader(QString loadFileName) { if (headerInfoProvided) return; if (loadFileName.isEmpty()) loadFileName = path+pathExtension+"/"+baseName+".fits"; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, loadFileName, &status); readHeader(&fptr, &status); #pragma omp critical { initWCS(); } initTHELIheader(&status); checkTHELIheader(&status); cornersToRaDec(); radius = sqrt(naxis1*naxis1 + naxis2*naxis2)/2. * plateScale / 3600; // image radius in degrees. Must be determined after initWCS and initTHELIheader when naxis_i/j are known fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (!status) headerInfoProvided = true; else headerInfoProvided = false; } void MyImage::getMJD() { if (hasMJDread) return; fitsfile *fptr = nullptr; QString fileName = path+pathExtension+"/"+chipName+processingStatus->statusString+".fits"; int status = 0; fits_open_file(&fptr, fileName.toUtf8().data(), READONLY, &status); fits_read_key_dbl(fptr, "MJD-OBS", &mjdobs, NULL, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); if (status) hasMJDread = false; else hasMJDread = true; } void MyImage::initTHELIheader(int *status) { if (*status) return; for (auto &it : header) { extractKeywordLong(it, "NAXIS1", naxis1); extractKeywordLong(it, "NAXIS2", naxis2); extractKeywordDouble(it, "MJD-OBS", mjdobs); extractKeywordString(it, "FILTER", filter); extractKeywordString(it, "BUNIT", bunit); extractKeywordString(it, "DATE-OBS", dateobs); extractKeywordFloat(it, "EXPTIME", exptime); extractKeywordFloat(it, "GAINCORR", gainNormalization); extractKeywordFloat(it, "SKYVALUE", skyValue); extractKeywordInt(it, "BITPIX", bitpix); extractKeywordFloat(it, "SKYVALUE", skyValue); extractKeywordFloat(it, "AIRMASS", airmass); extractKeywordFloat(it, "GEOLON", geolon); extractKeywordFloat(it, "GEOLAT", geolat); extractKeywordFloat(it, "FWHM", fwhm); extractKeywordFloat(it, "FWHMEST", fwhm_est); extractKeywordFloat(it, "GAIN", gain); extractKeywordFloat(it, "ELLIP", ellipticity); extractKeywordFloat(it, "ELLIPEST", ellipticity_est); extractKeywordFloat(it, "RZP", RZP); extractKeywordFloat(it, "SATURATE", saturationValue); } if (mjdobs != 0.0) hasMJDread = true; else hasMJDread = false; filter = filter.simplified(); dim = naxis1*naxis2; isTooBig(); if (skyValue != -1e9) modeDetermined = true; else modeDetermined = false; metadataTransferred = true; } void MyImage::checkTHELIheader(int *status) { if (*status) return; if (fullHeaderString.contains("NAXIS1 =") && fullHeaderString.contains("NAXIS2 =") && fullHeaderString.contains("CRPIX1 =") && fullHeaderString.contains("CRPIX2 =") && fullHeaderString.contains("CRVAL1 =") && fullHeaderString.contains("CRVAL2 =") && fullHeaderString.contains("CD1_1 =") && fullHeaderString.contains("CD1_2 =") && fullHeaderString.contains("CD2_1 =") && fullHeaderString.contains("CD2_2 =") && fullHeaderString.contains("EQUINOX =") && fullHeaderString.contains("EXPTIME =") && fullHeaderString.contains("FILTER =") && fullHeaderString.contains("GAIN =") && fullHeaderString.contains("BUNIT =") && fullHeaderString.contains("OBJECT =") && fullHeaderString.contains("MJD-OBS =")) { hasTHELIheader = true; } else { hasTHELIheader = false; } } void MyImage::extractKeywordDouble(QString card, QString key, double &value) { // Make keys unique (e.g. EXPTIME vs TEXPTIME) by constructing full keyword key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toDouble(); } void MyImage::extractKeywordFloat(QString card, QString key, float &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toFloat(); } void MyImage::extractKeywordLong(QString card, QString key, long &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toLong(); } void MyImage::extractKeywordInt(QString card, QString key, int &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'").toInt(); } void MyImage::extractKeywordString(QString card, QString key, QString &value) { key.resize(8, ' '); key.append("="); if (card.contains(key)) value = card.split("=")[1].split("/")[0].simplified().remove("'"); } void MyImage::propagateHeader(fitsfile *fptr, QVector<QString> header) { if (header.isEmpty()) return; int status = 0; // DO NOT COPY BITPIX, NAXIS, NAXIS1/2, EXTEND keywords for (int i=0; i<header.length(); ++i) { QString key = header[i].split("=")[0].simplified(); if (key == "SIMPLE" || key == "END" || key == "BZERO" || key.contains("NAXIS") || key.contains("BITPIX") || key.contains("EXTEND") || key.contains("END")) { continue; } fits_write_record(fptr, header[i].toUtf8().constData(), &status); } } void MyImage::stayWithinBounds(long &coord, QString axis) { if (coord < 0) coord = 0; if (axis == "x") { if (coord >= naxis1) coord = naxis1 - 1; } else { if (coord >= naxis2) coord = naxis2 - 1; } } // Make sure a vector with xmin xmax ymin ymax stays within the image boundaries void MyImage::stayWithinBounds(QVector<long> &vertices) { if (vertices[0] < 0) vertices[0] = 0; if (vertices[1] > naxis1-1) vertices[1] = naxis1-1; if (vertices[2] < 0) vertices[2] = 0; if (vertices[3] > naxis2-1) vertices[3] = naxis2-1; } // used in swarpfilter (using arrays instead of vectors, for performance reasons; unnecessary data copying) void MyImage::loadDataSection(long xmin, long xmax, long ymin, long ymax, float *dataSect) { QString fileName = path + "/" + name; int status = 0; fitsfile *fptr = nullptr; initFITS(&fptr, fileName, &status); fits_read_key_lng(fptr, "NAXIS1", &naxis1, NULL, &status); fits_read_key_lng(fptr, "NAXIS2", &naxis2, NULL, &status); long xmin_old = xmin; long xmax_old = xmax; long ymin_old = ymin; long ymax_old = ymax; stayWithinBounds(xmin, "x"); stayWithinBounds(xmax, "x"); stayWithinBounds(ymin, "y"); stayWithinBounds(ymax, "y"); if (xmin != xmin_old || xmax != xmax_old || ymin != ymin_old || ymax != ymax_old) { emit messageAvailable("MyImage::loadDataSection() / swarpfilter: image size was modified!", "error"); return; } float nullval = 0.; int anynull = 0; long fpixel[2] = {xmin+1, ymin+1}; // cfitsio starts counting at 1, at least here long lpixel[2] = {xmax+1, ymax+1}; // cfitsio starts counting at 1, at least here long strides[2] = {1, 1}; fits_read_subset(fptr, TFLOAT, fpixel, lpixel, strides, &nullval, dataSect, &anynull, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); }
18,609
C++
.cc
473
33.53277
186
0.643193
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,507
myimage.cc
schirmermischa_THELI/src/myimage/myimage.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../processingStatus/processingStatus.h" #include "../instrumentdata.h" #include "wcs.h" #include "wcshdr.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> #include <QTest> // C'tor MyImage::MyImage(QString pathname, QString filename, QString statusString, int chipnumber, const QVector<bool> &mask, int *verbose, QObject *parent) : QObject(parent), globalMask(mask) { path = pathname; name = filename; chipNumber = chipnumber; QFileInfo fi(path+"/"+name); if (globalMask.isEmpty()) globalMaskAvailable = false; baseName = fi.completeBaseName(); rootName = baseName; rootName.truncate(rootName.lastIndexOf('_')); chipName = rootName+"_"+QString::number(chipNumber); weightName = chipName+".weight"; processingStatus = new ProcessingStatus(path, this); processingStatus->statusString = statusString; processingStatus->statusToBoolean(processingStatus->statusString); if (! QFile(path+"/"+filename).exists()) { // A new file is being created validFile = false; validMode = false; validBackground = false; validDetector = false; } else { // An existing file is being read validFile = true; validMode = true; validBackground = true; validDetector = true; weightPath = path+"/../WEIGHTS/"; } verbosity = verbose; wcs = new wcsprm(); wcsInit = true; omp_init_lock(&backgroundLock); omp_init_lock(&objectLock); } void MyImage::checkTaskRepeatStatus(QString taskBasename) { isTaskRepeated = false; if (taskBasename == "HDUreformat" && processingStatus->HDUreformat) isTaskRepeated = true; else if (taskBasename == "Processscience" && processingStatus->Processscience) isTaskRepeated = true; else if (taskBasename == "Chopnod" && processingStatus->Chopnod) isTaskRepeated = true; else if (taskBasename == "Background" && processingStatus->Background) isTaskRepeated = true; else if (taskBasename == "Collapse" && processingStatus->Collapse) isTaskRepeated = true; else if (taskBasename == "Starflat" && processingStatus->Starflat) isTaskRepeated = true; else if (taskBasename == "Skysub" && processingStatus->Skysub) isTaskRepeated = true; } MyImage::MyImage(QString fullPathName, const QVector<bool> &mask, int *verbose, QObject *parent) : QObject(parent), globalMask(mask) { QFileInfo fi(fullPathName); path = fi.absolutePath(); name = fi.fileName(); chipNumber = 1; baseName = fi.completeBaseName(); rootName = baseName; rootName.truncate(rootName.lastIndexOf('_')); chipName = rootName+"_"+QString::number(chipNumber); if (rootName.isEmpty()) rootName = baseName; if (chipName.isEmpty()) chipName = baseName; weightName = baseName+".weight"; if (globalMask.isEmpty()) globalMaskAvailable = false; processingStatus = new ProcessingStatus(path); processingStatus->statusString = ""; processingStatus->statusToBoolean(processingStatus->statusString); if (! QFile(fullPathName).exists()) { // A new file is being created validFile = false; validMode = false; validBackground = false; validDetector = false; } else { // An existing file is being read validFile = true; validMode = true; validBackground = true; validDetector = true; // Create the FITS instance, but do not open and read it yet. weightPath = path; } verbosity = verbose; wcs = new wcsprm(); wcsInit = true; omp_init_lock(&backgroundLock); omp_init_lock(&objectLock); } MyImage::~MyImage() { for (auto &object : objectList) { delete object; object = nullptr; } if (wcsInit) wcsfree(wcs); if (wcsInit) { delete wcs; // valgrind does not like that wcs = nullptr; } int status = 0; if (fullheaderAllocated) fits_free_memory(fullheader, &status); delete processingStatus; processingStatus = nullptr; omp_destroy_lock(&backgroundLock); omp_destroy_lock(&objectLock); } void MyImage::setObjectLock(bool locked) { if (locked) omp_set_lock(&objectLock); else omp_unset_lock(&objectLock); } void MyImage::setBackgroundLock(bool locked) { if (locked) omp_set_lock(&backgroundLock); else omp_unset_lock(&backgroundLock); } void MyImage::updateProcInfo(QString text) { if (procInfo.isEmpty()) procInfo.append(text); else procInfo.append(", "+text); } void MyImage::showProcInfo() { if (*verbosity > 1) emit messageAvailable(chipName + " : " + procInfo, "image"); } bool MyImage::isTooBig() { // QVector can only hold 2^29 elements if (naxis1*naxis2 > pow(2,29)) { successProcessing = false; emit messageAvailable("Image has more than 2^29 elements and cannot be analysed within THELI.", "image"); return true; } else return false; } void MyImage::checkCorrectMaskSize(const instrumentDataType *instData) { if (instData->name.contains("DUMMY")) return; long n_mask = globalMask.length(); long n_data = naxis1*naxis2; if (n_mask > 0 && n_mask != n_data) { QString part1 = "Data: XDIM="+QString::number(naxis1) + " YDIM="+QString::number(naxis2) +"\n" + "Config: XSIZE="+QString::number(instData->sizex[chipNumber]) + " YSIZE="+QString::number(instData->sizey[chipNumber]) +"\n"; emit messageAvailable("Inconsistent image size detected between data and instrument configuration" " (overscan and / or data section) in\n"+instData->nameFullPath+"\n"+part1, "error"); emit critical(); successProcessing = false; } } void MyImage::readImage(bool determineMode) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadData()) { getMode(determineMode); imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } // Only needed for initialising the global weights void MyImage::readImageThreadSafe(bool determineMode) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadDataThreadSafe()) { getMode(determineMode); imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } // Used by iview when loading directly from FITS files, by swarpfilter when reading weights, // and by color picture when cropping images void MyImage::readImage(QString loadFileName) { dataCurrent_deletable = false; dataWeight_deletable = false; // Leave if image is already loaded if (imageInMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(chipName+" : Already in memory", "image"); return; } else { if (loadData(loadFileName)) { imageOnDrive = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(chipName+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImage(): Could not load " + baseName + ".fits", "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } } bool MyImage::isActive() { if (activeState == MyImage::ACTIVE) return true; else return false; } // When having to read from a backup file right after launch (task repeated) void MyImage::readImageBackupL1Launch() { dataCurrent_deletable = false; dataWeight_deletable = false; dataBackupL1_deletable = false; QString loadFileName = pathBackupL1 + "/" + baseNameBackupL1 + ".fits"; if (loadData(loadFileName)) { bool determineMode = true; getMode(determineMode); dataBackupL1 = dataCurrent; backupL1OnDrive = true; backupL1InMemory = true; successProcessing = true; updateProcInfo("Loaded"); if (*verbosity > 2) emit messageAvailable(baseNameBackupL1+" : Loaded", "image"); } else { emit messageAvailable("MyImage::readImageBackupL1Launch(): Could not load " + baseNameBackupL1, "error"); emit critical(); successProcessing = false; } emit modelUpdateNeeded(chipName); } // when MyImage has been read before and all members are setup correctly, just the pixel data are missing. // This function is used if the pixel data were discarded due to memory constraints, and now they are needed again void MyImage::readImageBackupL1() { dataCurrent_deletable = false; dataBackupL1_deletable = false; // Leave if image is already loaded if (backupL1InMemory) { updateProcInfo("Already in memory"); if (*verbosity > 2) emit messageAvailable(baseNameBackupL1+" : Already in memory", "image"); return; } else { QString backupName = pathBackupL1 + "/" + baseNameBackupL1 + ".fits"; QFile backupFile(backupName); if (!backupFile.exists()) { emit messageAvailable(baseName + " : Could not read data backup file " + pathBackupL1 + "/" + baseNameBackupL1 + " (does not exist)!", "error"); emit critical(); successProcessing = false; return; } int status = 0; long nelements = naxis1*naxis2; float *buffer = new float[nelements]; float nullval = 0.; int anynull; long fpixel = 1; fitsfile *fptr = nullptr; fits_open_file(&fptr, backupName.toUtf8().data(), READONLY, &status); fits_read_img(fptr, TFLOAT, fpixel, nelements, &nullval, buffer, &anynull, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); dataBackupL1.resize(nelements); for (long i=0; i<nelements; ++i) { dataBackupL1[i] = buffer[i]; } delete [] buffer; buffer = nullptr; backupL1InMemory = true; dataCurrent = dataBackupL1; // probably unnecessary, as we operate on databackupL1, updating dataCurrent dataBackupL1.squeeze(); // shed excess memory dataCurrent.squeeze(); // shed excess memory imageInMemory = true; } } // Retrieve the zero order solution from the currently created header file, or restore it from the original backup copy; // This includes FLXSCALE and RZP bool MyImage::scanAstromHeader(int chip, QString mode) { QFile file; if (mode == "inBackupDir") { file.setFileName(path+"/.origheader_backup/"+rootName+"_"+QString::number(chip+1)+".origastrom.head"); if (!file.open(QIODevice::ReadOnly)) { // emit messageAvailable("MyImage::scanAstromHeader(): " + file.fileName() + " " + file.errorString(), "error"); // emit critical(); emit messageAvailable(baseName + ": origastrom.head not found, image deactivated", "warning"); if (*verbosity >= 2) emit messageAvailable(file.fileName() + ": " + file.errorString() + ", image deactivated", "warning"); setActiveState(MyImage::NOASTROM); return false; } } else { // mode == "inHeadersDir" file.setFileName(path+"/headers/"+rootName+"_"+QString::number(chip+1)+".head"); if (!file.open(QIODevice::ReadOnly)) { // emit messageAvailable("MyImage::scanAstromHeader(): " + file.fileName() + " " + file.errorString(), "error"); // emit critical(); emit messageAvailable(baseName + ": .head not found, image deactivated", "warning"); if (*verbosity >= 2) emit messageAvailable(file.fileName() + " " + file.errorString() + ", image deactivated", "warning"); setActiveState(MyImage::NOASTROM); // emit critical(); return false; } } double cd11_orig = wcs->cd[0]; double cd12_orig = wcs->cd[1]; double cd21_orig = wcs->cd[2]; double cd22_orig = wcs->cd[3]; QTextStream in(&file); while(!in.atEnd()) { QString line = in.readLine().simplified(); if (line.isEmpty()) continue; QStringList list = line.split("="); if (list.length() < 2) continue; QString value = list.at(1).simplified().split(" ").at(0); /*if (line.contains("CRVAL1")) wcs->crval[0] = list[2].toDouble(); if (line.contains("CRVAL2")) wcs->crval[1] = list[2].toDouble(); if (line.contains("CRPIX1")) wcs->crpix[0] = list[2].toFloat(); if (line.contains("CRPIX2")) wcs->crpix[1] = list[2].toFloat(); if (line.contains("CD1_1")) wcs->cd[0] = list[2].toDouble(); if (line.contains("CD1_2")) wcs->cd[1] = list[2].toDouble(); if (line.contains("CD2_1")) wcs->cd[2] = list[2].toDouble(); if (line.contains("CD2_2")) wcs->cd[3] = list[2].toDouble(); if (line.contains("FLXSCALE")) FLXSCALE = list[2].toFloat(); if (line.contains("RZP")) RZP = list[2].toFloat(); */ if (line.contains("CRVAL1")) wcs->crval[0] = value.toDouble(); if (line.contains("CRVAL2")) wcs->crval[1] = value.toDouble(); if (line.contains("CRPIX1")) wcs->crpix[0] = value.toFloat(); if (line.contains("CRPIX2")) wcs->crpix[1] = value.toFloat(); if (line.contains("CD1_1")) wcs->cd[0] = value.toDouble(); if (line.contains("CD1_2")) wcs->cd[1] = value.toDouble(); if (line.contains("CD2_1")) wcs->cd[2] = value.toDouble(); if (line.contains("CD2_2")) wcs->cd[3] = value.toDouble(); if (line.contains("FLXSCALE")) FLXSCALE = value.toFloat(); if (line.contains("RZP")) RZP = value.toFloat(); } file.close(); // Do not update the WCS matrix if it is significantly flawed if (sanityCheckWCS(wcs).isEmpty()) { wcs->flag = 0; // Trigger recomputation cornersToRaDec(); updateCRVALCRPIXCDinHeader(); emit WCSupdated(); return true; } else { // Restore original values wcs->cd[0] = cd11_orig; wcs->cd[1] = cd12_orig; wcs->cd[2] = cd21_orig; wcs->cd[3] = cd22_orig; cornersToRaDec(); return false; } } void MyImage::checkWCSsanity() { // Do not update the WCS matrix if it is significantly flawed if (sanityCheckWCS(wcs).isEmpty()) return; else { wcs->cd[0] = -1.*plateScale/3600.; wcs->cd[1] = 0.; wcs->cd[2] = 0.; wcs->cd[3] = plateScale/3600.; wcs->flag = 0; updateCRVALCDinHeader(); updateCRVALCDinHeaderOnDrive(); emit messageAvailable("Singular or skewed CD matrix detected, reset to default values!", "warning"); emit warning(); } } void MyImage::backupOrigHeader(int chip) { QDir dir(path+ "/.origheader_backup/"); dir.mkpath(path+ "/.origheader_backup/"); // DO NOT OVERWRITE EXISTING BACKUP COPY QFile file(path+"/.origheader_backup/"+rootName+"_"+QString::number(chip+1)+".origastrom.head"); if (file.exists()) return; // Backup copy does not exist, create it if(!file.open(QIODevice::WriteOnly)) { emit messageAvailable("MyImage::backupOrigHeader(): " + file.fileName() + " " + file.errorString(), "error"); emit critical(); return; } QTextStream stream(&file); fitsfile *fptr; int status = 0; int nkeys = 0; int keypos = 0; char card[FLEN_CARD]; // Must read from pathBackupL1 QString filename = pathBackupL1+"/"+baseNameBackupL1+".fits"; // QString filename = path+"/"+baseName+".fits"; fits_open_file(&fptr, filename.toUtf8().data(), READWRITE, &status); fits_get_hdrpos(fptr, &nkeys, &keypos, &status); // get number of keywords for (int i=1; i<=nkeys; ++i) { fits_read_record(fptr, i, card, &status); stream << card << "\n"; } if (status == END_OF_FILE) status = 0; else { printCfitsioError(__func__, status); } fits_close_file(fptr, &status); file.close(); file.setPermissions(QFile::ReadUser | QFile::WriteUser); } void MyImage::replaceCardInFullHeaderString(QString keyname, double value) { QString card = keyname; card.resize(8, ' '); card.append("= "); card.append(QString::number(value, 'g', 12)); card.resize(80, ' '); long dim = strlen(fullheader); for (long i=0; i<dim-9; ++i) { if (fullheader[i] == card.at(0) && fullheader[i+1] == card.at(1) && fullheader[i+2] == card.at(2) && fullheader[i+3] == card.at(3) && fullheader[i+4] == card.at(4) && fullheader[i+5] == card.at(5) && fullheader[i+6] == card.at(6) && fullheader[i+7] == card.at(7) && fullheader[i+8] == card.at(8)) { for (int j=0; j<80; ++j) fullheader[i+j] = card.toUtf8().data()[j]; } } } void MyImage::updateMode() { if (!successProcessing) return; // Force an update of the mode skyValue = modeMask(dataCurrent, "stable", globalMask)[0]; modeDetermined = true; QString skyvalue = "SKYVALUE= "+QString::number(skyValue); if (*verbosity > 1) emit messageAvailable(chipName + " : " + skyvalue, "image"); skyvalue.resize(80,' '); // header is empty when running equalizeBayerFlat if (!doesHeaderContain("SKYVALUE=") && !header.isEmpty()) { header.insert(header.end()-1, skyvalue); } } bool MyImage::doesHeaderContain(QString keyword) { for (auto &it : header) { if (it.contains(keyword)) return true; } return false; } void MyImage::updateHeaderValue(QString keyName, float keyValue, char format) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(QString::number(keyValue, format, 6)); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { // Replace old entry it = card; break; } } } } void MyImage::updateHeaderValue(QString keyName, double keyValue, char format) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(QString::number(keyValue, format, 12)); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { it = card; // Replace old keyword break; } } } } void MyImage::updateHeaderValue(QString keyName, QString keyValue) { if (!successProcessing) return; QString card = keyName; card.resize(8, ' '); card.append("= "); QString keyword = card; card.append(keyValue); card.resize(80, ' '); if (!doesHeaderContain(keyword) && !header.isEmpty()) { header.insert(header.end()-1, card); } else { for (auto &it : header) { if (it.contains(keyword)) { // Replace old entry it = card; break; } } } } void MyImage::updateHeaderSaturation() { updateHeaderValue("SATURATE", saturationValue); } void MyImage::updateHeaderValueInFITS(QString keyName, QString keyValue) { if (!successProcessing) return; // Don't do anything if file doesn't exist on drive QFile file(path+"/"+name); if (!file.exists()) return; int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (path+"/"+name).toUtf8().data(), READWRITE, &status); fits_update_key_str(fptr, keyName.toUtf8().data(), keyValue.toUtf8().data(), nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } double MyImage::getPlateScale() { if (!wcsInit) { if (*verbosity > 2) emit messageAvailable(chipName + " : No WCS. PlateScale set to 1.0", "info"); return 1.0; } // replace with sth more sophisticated plateScale = sqrt(wcs->cd[0] * wcs->cd[0] + wcs->cd[2] * wcs->cd[2]) * 3600.; if (plateScale == 0.) plateScale = 1.0; return plateScale; } void MyImage::getMode(bool determineMode) { if (!successProcessing) return; // Get the mode only if requested, and measure it only if it hasn't been measured already // (in which case it is available as the SKYVALUE header keyword) if (determineMode && !modeDetermined) { if (!imageInMemory) loadData(); skyValue = modeMask(dataCurrent, "stable", globalMask)[0]; modeDetermined = true; QString skyvalue = "SKYVALUE= "+QString::number(skyValue); if (*verbosity > 1) emit messageAvailable(chipName + " : " + skyvalue, "image"); skyvalue.resize(80,' '); if (!header.isEmpty()) { if (!doesHeaderContain("SKYVALUE=")) { header.insert(header.end()-1, skyvalue); } } else { emit messageAvailable("MyImage::getMode():" + baseName + " : header vector is empty.", "error"); successProcessing = false; } } } // Flag the image if its mode is outside the acceptable range void MyImage::setModeFlag(QString min, QString max) { if (!successProcessing) return; if (min.isEmpty() && max.isEmpty()) return; if (!modeDetermined) { // TODO: implement mode() for integer FITS files, and measure it here (raw data, e.g. darks or flats) return; } else { validMode = true; if (!min.isEmpty() && skyValue < min.toFloat()) validMode = false; if (!max.isEmpty() && skyValue > max.toFloat()) validMode = false; if (!validMode) { if (*verbosity > 1) emit messageAvailable(chipName + " : Mode = " + QString::number(skyValue,'f',3) + " outside user-defined limits ["+min+","+max+"]", "output"); } successProcessing = true; } } // does the same as "updateHeaderValue()" void MyImage::updateKeywordInHeader(QString key, QString value) { for (auto &it : header) { if (!it.contains("=")) continue; QStringList list = it.split("="); QString keyword = list[0]; // QString value = list[1].simplified(); if (keyword.simplified() == key) { it = keyword+"= "+value; // pad with empty chars until 80 chars long while (it.length() < 80) { it.append(' '); } return; } } } // Here, 'biasData' may also refer to a dark or flatoff image //void MyImage::subtractBias(MyImage *&biasImage, QString dataType) void MyImage::subtractBias(const MyImage *biasImage, QString dataType) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= biasImage->dataCurrent.at(i); // pixel -= 0.; // testing memory accumulation ++i; } saturationValue -= biasImage->skyValue; updateHeaderValue("SATURATE", saturationValue); QString mode = ""; if (dataType == "BIAS") mode = "bias subtracted"; else if (dataType == "DARK") mode = "dark subtracted"; else if (dataType == "FLATOFF") mode = "flatoff subtracted"; else { // nothing } if (*verbosity > 1) emit messageAvailable(chipName + " : "+mode, "image"); successProcessing = true; } // UNUSED, for memory testing // Here, 'biasData' may also refer to a dark or flatoff image void MyImage::subtractBias(QVector<float> const &dataCorr, QString dataType) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= dataCorr.at(i); ++i; } QString mode = ""; if (dataType == "BIAS") mode = "bias subtracted"; else if (dataType == "DARK") mode = "dark subtracted"; else if (dataType == "FLATOFF") mode = "flatoff subtracted"; else { // nothing } if (*verbosity > 1) emit messageAvailable(chipName + " : "+mode, "image"); successProcessing = true; } // UNUSED, for memory testing // Here, 'biasData' may also refer to a dark or flatoff image /* void MyImage::subtractBias() { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the bias was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { pixel -= 0.; ++i; } } */ void MyImage::divideFlat(const MyImage *flatImage) { if (!successProcessing) return; if (!validMode) return; // We have verified "above" that the flat was successfully loaded long i = 0; for (auto &pixel : dataCurrent) { // Divide by flat, and correct for gain differences pixel /= (flatImage->dataCurrent.at(i) * flatImage->gainNormalization); // NaN pixels slow down SourceExtractor enourmously (and make it fail). // we can probably get rid of this once we have completely thrown out SourceExtractor if (std::isnan(pixel) || std::isinf(pixel)) pixel = 0.; ++i; } saturationValue /= flatImage->gainNormalization; updateHeaderValue("SATURATE", saturationValue); if (*verbosity > 1) emit messageAvailable(chipName + " : Flat fielded", "image"); successProcessing = true; } void MyImage::applyBackgroundModel(const MyImage *backgroundImage, QString mode, bool rescaleFlag) { if (!successProcessing) return; long i = 0; if (mode == "Subtract model" ) { float rescale = 1.0; if (rescaleFlag) rescale = skyValue / backgroundImage->skyValue; for (auto &pixel : dataCurrent) { if (backgroundImage->dataCurrent.at(i) != 0.) { pixel = dataBackupL1.at(i) - backgroundImage->dataCurrent.at(i) * rescale; } else { pixel = 0.; } ++i; } saturationValue -= backgroundImage->skyValue * rescale; updateHeaderValue("SATURATE", saturationValue); QString img = " IMG = "+QString::number(skyValue, 'f', 3) + ";"; QString back = " BACK = "+QString::number(backgroundImage->skyValue, 'f', 3) + ";"; QString fac = " rescale = "+QString::number(rescale, 'f', 3); if (*verbosity > 1) emit messageAvailable(chipName + " : Background model subtracted;"+img+back+fac, "image"); } else if (mode == "Divide model") { // rescaling switched off. Background image is always normalized to its own mode for (auto &pixel : dataCurrent) { if (backgroundImage->dataCurrent.at(i) != 0) { pixel = dataBackupL1.at(i) / (backgroundImage->dataCurrent.at(i) / backgroundImage->skyValue); } else { pixel = backgroundImage->skyValue; } ++i; } // No normalization of saturation keyword required // saturationValue /= backgroundImage->skyValue; updateHeaderValue("SATURATE", saturationValue); QString img = " IMG = "+QString::number(skyValue, 'f', 3) + ";"; QString back = " BACK = "+QString::number(backgroundImage->skyValue, 'f', 3) + ";"; if (*verbosity > 1) emit messageAvailable(chipName + " : Divided by normalized background model;"+img+back, "image"); } successProcessing = true; } // Normalize Flat to one. Gain differences are corrected separately. void MyImage::normalizeFlat() { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Normalizing flat field, dividing by "+QString::number(skyValue, 'f', 3), "image"); for (auto &pixel : dataCurrent) { pixel /= skyValue; } successProcessing = true; } // Normalize Flat to one. Gain differences are corrected separately. void MyImage::illuminationCorrection(int chip, QString thelidir, QString instName, QString filter) { if (!successProcessing) return; // It is ok to look up and read the illum correction files in MyImage (instead of Controller) // because it is applied to the master flat, and therefore executed only once. // If we applied it to every science frame, then it would be better to implement it in Controller // so it gets executed only once // TODO: must provide in distribution? QString illumcorrPath = thelidir+"/ExtCal/"+instName+"/illumcorr/"; QString illumcorrFileName = "illumcorr_"+filter+"_"+QString::number(chip)+".fits"; if (QFile(illumcorrPath+illumcorrFileName).exists()) { if (*verbosity > 1) emit messageAvailable(chipName + " : External illumination correction : <br>" + illumcorrPath+illumcorrFileName, "image"); QVector<bool> dummyMask; dummyMask.clear(); MyImage *illumCorrFlat = new MyImage(illumcorrPath, illumcorrFileName, "", chip+1, dummyMask, verbosity); illumCorrFlat->readImage(); if (naxis1 != illumCorrFlat->naxis1 || naxis2 != illumCorrFlat->naxis2 ) { emit messageAvailable("MyImage::illuminationCorrection(): " + baseName + " : illumination correction image does not have the same size as the master flat!", "error"); emit critical(); successProcessing = false; } else { long i = 0; for (auto &pixel : dataCurrent) { pixel *= illumCorrFlat->dataCurrent.at(i); ++i; } successProcessing = true; } delete illumCorrFlat; illumCorrFlat = nullptr; } } void MyImage::collapseCorrection(QString threshold, QString direction) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Collapse correction along " + direction, "image"); if (direction == "x") { static_cast<void> (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "y") { static_cast<void> (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "xy") { static_cast<void> (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); static_cast<void> (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else if (direction == "yx") { static_cast<void> (collapse_y(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); static_cast<void> (collapse_x(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, "2Dsubtract")); } else { static_cast<void> (collapse_quad(dataCurrent, globalMask, objectMask, threshold.toFloat(), naxis1, naxis2, direction, "2Dsubtract")); } } QVector<float> MyImage::extractPixelValues(long xmin, long xmax, long ymin, long ymax) { // CHECK: if not in memory then load from drive if (xmin < 0) xmin = 0; if (xmax >= naxis1-1) xmax = naxis1-1; if (ymin < 0) ymin = 0; if (ymax >= naxis2-1) ymax = naxis2-1; long nsub = xmax - xmin + 1; long msub = ymax - ymin + 1; QVector<float> section; /* section.reserve(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { section.append(dataCurrent[i+naxis1*j]); } } */ section.resize(nsub*msub); long k = 0; for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { section[k] = dataCurrent.at(i+naxis1*j); ++k; } } return section; } void MyImage::makeCutout(long xmin, long xmax, long ymin, long ymax) { long nsub = xmax - xmin + 1; long msub = ymax - ymin + 1; QVector<float> dataCut; /* dataCut.reserve(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { dataCut.append(dataCurrent[i+naxis1*j]); } } */ long k = 0; dataCut.resize(nsub*msub); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { dataCut[k] = dataCurrent.at(i+naxis1*j); ++k; } } naxis1 = nsub; naxis2 = msub; if (wcsInit) { wcs->crpix[0] = wcs->crpix[0] - xmin + 1; wcs->crpix[1] = wcs->crpix[1] - ymin + 1; wcs->flag = 0; } dataCurrent.swap(dataCut); } // UNUSED float MyImage::polynomialSum(float x, QVector<float> coefficients) { // Coefficients contains the coeffs of a polynomial, starting with the lowest term // e.g., for p(x) = c0 + c1*x + c2*x*x we have coefficients = [c0, c1, c2] float sum = 0.; int k = 0; for (auto & it : coefficients) { sum += it * pow(x, k); ++k; } return sum; } void MyImage::removeSourceCatalogs() { QString catName = path+"/cat/"+chipName+".cat"; QFile catFile1(catName); if (catFile1.exists()) catFile1.remove(); catName = path+"/cat/"+chipName+".anet"; QFile catFile2(catName); if (catFile2.exists()) catFile2.remove(); } // This routine is used when reading an external image // (and possibly its existing weight in the same directory, such as a pair of coadd.fits and coadd.weight.fits) // So far only used for creating astrometric reference catalogs void MyImage::setupCoaddMode() { readImage(path+"/"+name); // Setup an empty dummy globalMask // globalMask = QVector<bool>(); globalMaskAvailable = false; // Load a matching weight image, if one exists // weightName.append(".fits"); weightName = baseName + ".weight.fits"; QFile file(path+"/"+weightName); if (!file.exists()) return; QVector<bool> dummyMask; dummyMask.clear(); MyImage *myWeight = new MyImage(path, weightName, "", 1, dummyMask, verbosity); myWeight->readImage(); dataWeight.swap(myWeight->dataCurrent); delete myWeight; myWeight = nullptr; } void MyImage::updateZeroOrderOnDrive(QString updateMode) { if (!successProcessing) return; if (!imageOnDrive) return; // Must write file to disk (scamp reads the header information) if it does not exist yet // QFile file(path+ "/" + baseName + ".fits"); // if (!file.exists()) writeImage(path+ "/" + baseName + ".fits"); int status = 0; char zerohead[80] = {0}; QString zeroheadString = ""; fitsfile *fptr = nullptr; fits_open_file(&fptr, (path+"/"+chipName+processingStatus->statusString+".fits").toUtf8().data(), READWRITE, &status); fits_read_key_str(fptr, "ZEROHEAD", zerohead, nullptr, &status); if (status > 0) { // Add the key if it doesn't exist // Not used for anything, just informative fits_update_key_str(fptr, "ZEROHEAD", "NO", "Astrometric header update", &status); // reset the update flag zeroheadString = "NO"; status = 0; } else zeroheadString.fromLatin1(zerohead); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 9, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 9, nullptr, &status); fits_update_key_flt(fptr, "CRPIX1", wcs->crpix[0], 3, nullptr, &status); fits_update_key_flt(fptr, "CRPIX2", wcs->crpix[1], 3, nullptr, &status); fits_update_key_dbl(fptr, "CD1_1", wcs->cd[0], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD1_2", wcs->cd[1], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD2_1", wcs->cd[2], 9, nullptr, &status); fits_update_key_dbl(fptr, "CD2_2", wcs->cd[3], 9, nullptr, &status); if (std::isnan(RZP)) { RZP = 0.; FLXSCALE = 0.0; emit messageAvailable(chipName + " : Scamp could not determine the relative zeropoint. Set to 0!", "error"); emit critical(); } fits_update_key_flt(fptr, "RZP", RZP, 5, nullptr, &status); fits_update_key_flt(fptr, "FLXSCALE", FLXSCALE, 5, nullptr, &status); if (updateMode == "restore") { fits_update_key_str(fptr, "ZEROHEAD", "NO", "Astrometric header update", &status); // reset the update flag } else { // updateMode == "update" fits_update_key_str(fptr, "ZEROHEAD", "YES", "Astrometric header update", &status); // reset the update flag } fits_close_file(fptr, &status); printCfitsioError(__func__, status); } /* void MyImage::updateZeroOrderInMemory() { if (!successProcessing) return; // Update the data in memory // WCSLIB threading issue (probably solved by wcsLock in initWCS() // Can be removed if we don't see this again if (wcs->naxis != 2) { emit messageAvailable(chipName + " : MyImage::updateZeroOrder(): Incompatible NAXIS WCS dimension: " + QString::number(wcs->naxis) + ", attempting reload (actually, this is a bug!)", "warning"); imageInMemory = false; readImage(false); if (wcs->naxis != 2) { emit messageAvailable(chipName + " : Reload failed!", "error"); return; } else { emit messageAvailable(chipName + " : Reload success!", "note"); } } cornersToRaDec(); } */ // Update the 'header' QVector passed onto any newly written FITS file void MyImage::updateCRVALinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); } // Update the 'header' QVector passed onto any FITS file written in the future void MyImage::updateCRVALCDinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); updateHeaderValue("CD1_1", wcs->cd[0], 'e'); updateHeaderValue("CD1_2", wcs->cd[1], 'e'); updateHeaderValue("CD2_1", wcs->cd[2], 'e'); updateHeaderValue("CD2_2", wcs->cd[3], 'e'); } // Update the 'header' QVector passed onto any FITS file written in the future void MyImage::updateCRVALCRPIXCDinHeader() { updateHeaderValue("CRVAL1", wcs->crval[0]); updateHeaderValue("CRVAL2", wcs->crval[1]); updateHeaderValue("CRPIX1", wcs->crpix[0]); updateHeaderValue("CRPIX2", wcs->crpix[1]); updateHeaderValue("CD1_1", wcs->cd[0], 'e'); updateHeaderValue("CD1_2", wcs->cd[1], 'e'); updateHeaderValue("CD2_1", wcs->cd[2], 'e'); updateHeaderValue("CD2_2", wcs->cd[3], 'e'); } void MyImage::updateCRVALinHeaderOnDrive() { // Must write file to drive (scamp reads the header information) if it does not exist yet QString outfile = path+"/"+chipName+processingStatus->statusString+".fits"; // QFile file(path+ "/" + baseName + ".fits"); QFile file(outfile); if (!file.exists()) writeImage(outfile); int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (outfile).toUtf8().data(), READWRITE, &status); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 6, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 6, nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::updateCRVALCDinHeaderOnDrive() { // Must write file to disk (scamp reads the header information) if it does not exist yet QString outfile = path+"/"+chipName+processingStatus->statusString+".fits"; QFile file(outfile); if (!file.exists()) writeImage(outfile); int status = 0; fitsfile *fptr = nullptr; fits_open_file(&fptr, (outfile).toUtf8().data(), READWRITE, &status); fits_update_key_dbl(fptr, "CRVAL1", wcs->crval[0], 6, nullptr, &status); fits_update_key_dbl(fptr, "CRVAL2", wcs->crval[1], 6, nullptr, &status); fits_update_key_flt(fptr, "CD1_1", wcs->cd[0], 6, nullptr, &status); fits_update_key_flt(fptr, "CD1_2", wcs->cd[1], 6, nullptr, &status); fits_update_key_flt(fptr, "CD2_1", wcs->cd[2], 6, nullptr, &status); fits_update_key_flt(fptr, "CD2_2", wcs->cd[3], 6, nullptr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::updateInactivePath() { if (activeState == MyImage::ACTIVE) pathExtension = ""; else if (activeState == MyImage::INACTIVE) pathExtension = "/inactive/"; else if (activeState == MyImage::BADSTATS) pathExtension = "/inactive/badStatistics/"; else if (activeState == MyImage::BADBACK) pathExtension = "/inactive/badBackground/"; else if (activeState == MyImage::NOASTROM) pathExtension = "/inactive/noAstrometry/"; else if (activeState == MyImage::LOWDETECTION) pathExtension = "/inactive/lowDetections/"; else if (activeState == MyImage::DELETED) pathExtension = "/inactive/"; } void MyImage::applyMask() { // Leave if the chip has no mask (save some CPU cycles) if (!globalMaskAvailable) return; if (globalMask.length() != dataCurrent.length()) { emit messageAvailable("MyImage::applyMask(): " + baseName + " : inconsistent sizes of mask and image", "error"); emit critical(); return; } long i=0; for (auto &it : dataCurrent) { if (globalMask[i]) it = maskValue; ++i; } } QString MyImage::getKeyword(QString key) { QString value; key.resize(8,' '); for (auto &it : header) { if (it.contains(key)) { value = it.split("=")[1].split("/")[0].simplified().remove("'"); break; } } return value; } void MyImage::messageAvailableReceived(QString message, QString type) { if (type == "error" || type == "stop") { emit messageAvailable(message, type); emit critical(); } else { if (*verbosity > 1) emit messageAvailable(message, type); } } void MyImage::anetOutputReceived(QString message, QString type) { if (type == "error" || type == "stop") { emit messageAvailable(message, type); emit critical(); } else { if (*verbosity >= 1) emit messageAvailable(message, type); } } QVector<double> MyImage::extractCDmatrix() { QVector<double> cd; cd.push_back(getKeyword("CD1_1").toDouble()); cd.push_back(getKeyword("CD1_2").toDouble()); cd.push_back(getKeyword("CD2_1").toDouble()); cd.push_back(getKeyword("CD2_2").toDouble()); return cd; } // TODO: update to use wcslib functions void MyImage::checkBrightStars(const QList<QVector<double>> &brightStarList, float safetyDistance, float plateScale) { if (!successProcessing) return; hasBrightStars = false; // Loop over all bright stars and check whether they are inside the chip for (auto &it : brightStarList) { QVector<double> raVec; QVector<double> decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; double alpha = it.at(0); double delta = it.at(1); if (pnpoly_T(raVec, decVec, alpha, delta)) { hasBrightStars = true; return; } } // if we are still here, then check for bright stars outside the chip // within the minimum safety distance safetyDistance *= (60. / plateScale); // convert to pixel for (auto &it : brightStarList) { double xstar; double ystar; double alpha = it.at(0); double delta = it.at(1); sky2xy(alpha, delta, xstar, ystar); if (xstar > -1*safetyDistance && xstar < naxis1+safetyDistance && ystar > -1*safetyDistance && ystar < naxis2+safetyDistance) { hasBrightStars = true; return; } } } bool MyImage::containsRaDec(QString alphaStr, QString deltaStr) { loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd // Convert to decimal if required if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr); if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr); double x = 0.; double y = 0.; sky2xy(alphaStr.toDouble(), deltaStr.toDouble(), x, y); if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) return true; else return false; /* * pnpoly() does not work if the image crosses the RA=0|360 boundary. Must use wcslib (see code above) double alpha_ul; double alpha_ur; double alpha_ll; double alpha_lr; double delta_ul; double delta_ur; double delta_ll; double delta_lr; xy2sky(1, 1, alpha_ll, delta_ll); xy2sky(naxis1, 1, alpha_lr, delta_lr); xy2sky(1, naxis2, alpha_ul, delta_ul); xy2sky(naxis1, naxis2, alpha_ur, delta_ur); // Check if the sky coordinates are contained in this picture frame QVector<double> raVec; QVector<double> decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; // Convert to decimal if required if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr); if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr); return pnpoly_T(raVec, decVec, alphaStr.toDouble(), deltaStr.toDouble()); */ } bool MyImage::containsRaDec(double alpha, double delta) { loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd double x = 0.; double y = 0.; sky2xy(alpha, delta, x, y); if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) return true; else return false; /* double alpha_ul; double alpha_ur; double alpha_ll; double alpha_lr; double delta_ul; double delta_ur; double delta_ll; double delta_lr; // Convert the cartesian image vertices to RA/DEC loadHeader(); // if not yet provided, e.g. UI was just started and we are doing a coadd xy2sky(1, 1, alpha_ll, delta_ll); xy2sky(naxis1, 1, alpha_lr, delta_lr); xy2sky(1, naxis2, alpha_ul, delta_ul); xy2sky(naxis1, naxis2, alpha_ur, delta_ur); // Check if the sky coordinates are contained in this picture frame QVector<double> raVec; QVector<double> decVec; // order is important! we don't want a line crossing in the polygon line raVec << alpha_ll << alpha_lr << alpha_ur << alpha_ul; decVec << delta_ll << delta_lr << delta_ur << delta_ul; return pnpoly_T(raVec, decVec, alpha, delta); */ } void MyImage::cornersToRaDec() { xy2sky(0., 0., alpha_ll, delta_ll); xy2sky(naxis1-1., 0., alpha_lr, delta_lr); xy2sky(0., naxis2-1., alpha_ul, delta_ul); xy2sky(naxis1-1., naxis2-1., alpha_ur, delta_ur); xy2sky(naxis1/2.-1., naxis2/2.-1., alpha_ctr, delta_ctr); } // UNUSED /* QVector<float> MyImage::retainUnmaskedDataThresholded(float minVal, float maxVal, int sampleDensity) { if (sampleDensity == 0) sampleDensity = 1; QVector<float> dataThresholded; long n = dataCurrent.length(); dataThresholded.reserve(n/sampleDensity); if (!globalMask.isEmpty()) { for (long i=0; i<n; i+=sampleDensity) { float it = dataCurrent[i]; if (it > minVal && it < maxVal && !globalMask[i]) { dataThresholded.append(it); } } } else { for (long i=0; i<n; i+=sampleDensity) { float it = dataCurrent[i]; if (it > minVal && it < maxVal) { dataThresholded.append(it); } } } return dataThresholded; } QVector<float> MyImage::retainUnmaskedData(int sampleDensity) { if (sampleDensity == 0) sampleDensity = 1; QVector<float> dataThresholded; long n = dataCurrent.length(); dataThresholded.reserve(n/sampleDensity); if (!globalMask.isEmpty()) { for (long i=0; i<n; i+=sampleDensity) { if (!globalMask.at(i)) dataThresholded.append(dataCurrent[i]); } } else { if (sampleDensity == 1) dataThresholded = dataCurrent; else { for (long i=0; i<n; i+=sampleDensity) { dataThresholded.append(dataCurrent[i]); } } } return dataThresholded; } */ void MyImage::mergeObjectWithGlobalMask() { if (objectMask.isEmpty()) objectMask = globalMask; else { long i=0; for (auto &pixel : objectMask) { // pixel = pixel && globalMask.at(i); // wrong! // a masked value is true. If && is used, then false && true == false, i.e. unmasked && masked == unmasked, but should be masked pixel = pixel || globalMask.at(i); ++i; } } } void MyImage::subtract(float value, QString mode) { if (mode.isEmpty()) { for (auto &it : dataCurrent) { it -= value; } } else if (mode == "TIFF") { if (dataTIFF.isEmpty()) dataTIFF = dataCurrent; for (auto &it : dataTIFF) { it -= value; } } } void MyImage::add(float value) { for (auto &it : dataCurrent) { it += value; } } void MyImage::multiply(float value, QString mode) { if (mode.isEmpty()) { for (auto &it : dataCurrent) { it *= value; } } else if (mode == "TIFF") { if (dataTIFF.isEmpty()) dataTIFF = dataCurrent; for (auto &it : dataTIFF) { it *= value; } } } void MyImage::divide(float value) { if (value == 0.) { emit messageAvailable("MyImage::divide(): " + baseName + " : Division by zero encountered!", "error"); emit critical(); return; } for (auto &it : dataCurrent) { it /= value; } } void MyImage::sky2xy(const double alpha, const double delta, double &x, double &y) { double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; world[0] = alpha; world[1] = delta; int stat[1]; wcss2p(wcs, 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat); x = pixcrd[0]; y = pixcrd[1]; } // WARNING: cartesian arguments must be zero-indexed! void MyImage::xy2sky(const double x, const double y, double &alpha, double &delta) { double world[2]; double phi; double theta; double imgcrd[2]; double pixcrd[2]; // CAREFUL! wcslib starts pixels counting at 1, hence must add +1 to zero-indexed C++ vectors pixcrd[0] = x + 1.; pixcrd[1] = y + 1.; int stat[1]; wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat); alpha = world[0]; delta = world[1]; } void MyImage::emitModelUpdateNeeded() { emit modelUpdateNeeded(chipName); } // For use from within the memory viewer; also called by the statistics module void MyImage::setActiveState(active_type state) { // Do nothing if the requested state equals the current state (otherwise, image might get deleted before moving it onto itself) if (activeState == state) return; // Always use this function when setting the active status activeState = state; // If the file is currently inactive, check whether the processing state is the same as that of currently active images. // Otherwise, the file must not be moved // Check done externally before calling setActiveState() /* if (state == MyImage::INACTIVE) { if (processingStatus->statusString != processingStatus->whatIsStatusOnDrive()) { // } } */ // Move the image accordingly QString currentPath = path + pathExtension; // The path where the image is currently located (if on disk) updateInactivePath(); // Update pathextension according to the set state QString newPath = path + pathExtension; // The path where the image should go if (!imageOnDrive) return; moveFile(baseName+".fits", currentPath, newPath); } void MyImage::printCfitsioError(QString funcName, int status) { if (status) { CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this); emit messageAvailable("MyImage::"+funcName+":<br>" + baseName + " : " + errorCodes->errorKeyMap.value(status), "error"); emit critical(); successProcessing = false; } }
54,884
C++
.cc
1,439
31.814454
178
0.628336
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,508
memoryoperations.cc
schirmermischa_THELI/src/myimage/memoryoperations.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../processingStatus/processingStatus.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> #include <QTest> // same as pushdown(), without file movement void MyImage::makeMemoryBackup() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // TODO: implement a finer granularity memory check (sufficient RAM available?) if (!minimizeMemoryUsage) { dataBackupL3 = dataBackupL2; dataBackupL2 = dataBackupL1; } dataBackupL1 = dataCurrent; statusBackupL3 = statusBackupL2; statusBackupL2 = statusBackupL1; statusBackupL1 = processingStatus->statusString; emit modelUpdateNeeded(chipName); // implement: // processingStatus->statusString = statusCurrentNew; } // UNUSED? void MyImage::makeDriveBackup(QString backupDirName, QString statusOld) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Current and backup paths QString currentPath = path; QString backupPath = path+"/"+backupDirName+"/"; QString oldName = chipName+statusOld+".fits"; QFile image(currentPath+"/"+oldName); // Do nothing if the image does not exist on drive (i.e. is in memory only) if (!image.exists()) return; moveFile(oldName, currentPath, backupPath); } void MyImage::makeBackgroundBackup() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // make backup file (if the FITS file exists) mkAbsDir(pathBackupL1); moveFile(baseNameBackupL1+".fits", path, pathBackupL1, true); backupL1OnDrive = true; emit modelUpdateNeeded(chipName); } // Push data one step into the backup structure void MyImage::pushDown(QString backupDir) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // MEMORY pushDownToL3(); pushDownToL2(); pushDownToL1(backupDir); // DRIVE // make backup file (if the FITS file exists) mkAbsDir(pathBackupL1); moveFile(baseNameBackupL1+".fits", path, pathBackupL1, true); // backupL1OnDrive = true; emit modelUpdateNeeded(chipName); } // Push dataCurrent to backupL1 void MyImage::pushDownToL1(QString backupDir) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // MEMORY dataBackupL1 = dataCurrent; backupL1InMemory = imageInMemory; backupL1OnDrive = imageOnDrive; statusBackupL1 = processingStatus->statusString; dataBackupL1_deletable = dataCurrent_deletable; pathBackupL1 = path+"/"+backupDir; baseNameBackupL1 = baseName; saturationValueL1 = saturationValue; } // Push backupL1 to backupL2 void MyImage::pushDownToL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images if (!minimizeMemoryUsage) { dataBackupL2 = dataBackupL1; backupL2InMemory = backupL1InMemory; backupL2OnDrive = backupL1OnDrive; statusBackupL2 = statusBackupL1; pathBackupL2 = pathBackupL1; baseNameBackupL2 = baseNameBackupL1; dataBackupL2_deletable = dataBackupL1_deletable; saturationValueL2 = saturationValueL1; } } // Push backupL2 to backupL3 void MyImage::pushDownToL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images if (!minimizeMemoryUsage) { dataBackupL3 = dataBackupL2; backupL3InMemory = backupL2InMemory; backupL3OnDrive = backupL2OnDrive; statusBackupL3 = statusBackupL2; pathBackupL3 = pathBackupL2; baseNameBackupL3 = baseNameBackupL2; dataBackupL3_deletable = dataBackupL2_deletable; saturationValueL3 = saturationValueL2; } } // Pull data up one step from the backup structure // UNUSED void MyImage::pullUp() { if (activeState != ACTIVE) return; // Don't change location of deactivated images // DRIVE deleteFile(baseName+".fits", path); // restore backup FITS file moveFile(baseNameBackupL1+".fits", pathBackupL1, path, true); // MEMORY pullUpFromL1(); pullUpFromL2(); pullUpFromL3(); emit modelUpdateNeeded(chipName); } // Pull data up one step from the backup structure bool MyImage::makeL1Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE // The following construct gives a compiler warning with gcc7 // success *= deleteFile(baseName+".fits", path); success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL1+".fits", pathBackupL1, path, true); // L1 to L0 dataCurrent = dataBackupL1; processingStatus->statusString = statusBackupL1; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL1; imageInMemory = backupL1InMemory; imageOnDrive = backupL1OnDrive; saturationValue = saturationValueL1; // MEMORY pullUpFromL2(); pullUpFromL3(); wipeL3(); emit modelUpdateNeeded(chipName); return success; } // Make L2 current bool MyImage::makeL2Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL2+".fits", pathBackupL2, path, true); // L2 to L0 dataCurrent = dataBackupL2; processingStatus->statusString = statusBackupL2; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL2; imageInMemory = backupL2InMemory; imageOnDrive = backupL2OnDrive; saturationValue = saturationValueL2; // L3 to L2 pullUpFromL3(); // wipe L1 and L3 wipeL1(); wipeL3(); emit modelUpdateNeeded(chipName); return success; } // make L3 current bool MyImage::makeL3Current() { if (activeState != ACTIVE) return true; // Don't change location of deactivated images; don't trigger error bool success = true; // DRIVE success = success && deleteFile(baseName+".fits", path); // restore backup FITS file success = success && moveFile(baseNameBackupL3+".fits", pathBackupL3, path, true); // L3 to L0 dataCurrent = dataBackupL3; processingStatus->statusString = statusBackupL3; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL3; imageInMemory = backupL3InMemory; imageOnDrive = backupL3OnDrive; saturationValue = saturationValueL3; // wipe L1 and L2 wipeL1(); wipeL2(); emit modelUpdateNeeded(chipName); return success; } void MyImage::pullUpFromL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL2 = dataBackupL3; statusBackupL2 = statusBackupL3; pathBackupL2 = pathBackupL3; dataBackupL2_deletable = dataBackupL3_deletable; baseNameBackupL2 = baseNameBackupL3; backupL2InMemory = backupL3InMemory; dataBackupL3_deletable = true; dataBackupL3.clear(); dataBackupL3.squeeze(); saturationValueL2 = saturationValueL3; } void MyImage::pullUpFromL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL1 = dataBackupL2; statusBackupL1 = statusBackupL2; pathBackupL1 = pathBackupL2; dataBackupL1_deletable = dataBackupL2_deletable; baseNameBackupL1 = baseNameBackupL2; backupL1InMemory = backupL2InMemory; saturationValueL1 = saturationValueL2; } void MyImage::pullUpFromL1() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataCurrent = dataBackupL1; processingStatus->statusString = statusBackupL1; processingStatus->statusToBoolean(processingStatus->statusString); dataCurrent_deletable = false; baseName = baseNameBackupL1; imageInMemory = backupL1InMemory; saturationValue = saturationValueL1; } void MyImage::wipeL1() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL1.clear(); dataBackupL1.squeeze(); statusBackupL1 = ""; pathBackupL1 = ""; dataBackupL1_deletable = true; baseNameBackupL1 = ""; backupL1InMemory = false; } void MyImage::wipeL2() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL2.clear(); dataBackupL2.squeeze(); statusBackupL2 = ""; pathBackupL2 = ""; dataBackupL2_deletable = true; baseNameBackupL2 = ""; backupL2InMemory = false; } void MyImage::wipeL3() { if (activeState != ACTIVE) return; // Don't change location of deactivated images dataBackupL3.clear(); dataBackupL3.squeeze(); statusBackupL3 = ""; pathBackupL3 = ""; dataBackupL3_deletable = true; baseNameBackupL3 = ""; backupL3InMemory = false; } // For some tasks (e.g. source cat creation) we do not need to push down data into the backup levels void MyImage::setupDataInMemorySimple(bool determineMode) { if (activeState != ACTIVE) return; // Don't change location of deactivated images // Load the image if not in yet memory readImage(determineMode); emit modelUpdateNeeded(chipName); } // CHECK: Last argument probably not needed void MyImage::setupData(bool isTaskRepeated, bool createBackup, bool determineMode, QString backupDir) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Protect dataCurrent dataCurrent_deletable = false; // if (createBackup && backupDir.isEmpty()) emit messageAvailable("MyImage::setupData(): Cannot restore backup data from backup dir!", "error"); // CASE 1: The task has not been executed before if (!isTaskRepeated) { readImage(determineMode); // Push down data by one level (at all levels) if required if (createBackup) pushDown(backupDir); } // CASE 2: The task has been executed before and we re-do it: Restore level 1 backup if (isTaskRepeated) { // Restoring from memory if (backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from RAM (backup level L1)", "image"); pullUpFromL1(); } // Restoring from drive else { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); // Right after launch, nothing is initialized and we must do that first using the full approach. Otherwise, we just read the data array. if (!headerInfoProvided) readImageBackupL1Launch(); else readImageBackupL1(); imageInMemory = true; backupL1InMemory = true; } } emit modelUpdateNeeded(chipName); } // If a task is repeated, replace dataCurrent with the backup copy. // Otherwise continue with data current, and push down the backup data one level void MyImage::setupBackgroundData(const bool &isTaskRepeated, const QString &backupDir) { if (!successProcessing) return; if (backgroundPushedDown) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images dataCurrent_deletable = false; dataBackupL1_deletable = false; // CASE 1: The task has not been executed before if (!isTaskRepeated) { // Nothing is in backupL1 yet, either after restart, or because RAM is low. // No push-down has happened yet if (!backgroundPushedDown) { if (!minimizeMemoryUsage) { pushDownToL3(); pushDownToL2(); } readImage(true); // if not yet in memory pushDownToL1(backupDir); // Create a safe copy of the non-subtracted data dataBackupL1_deletable = false; // set to 'true' in pushDownToL1(), but we must protect it backgroundPushedDown = true; } } // CASE 2: The task has been executed before (we have PAB images present in dataCurrent and PA images in backupL1) else { // Restoring from drive if not yet in memory if (!backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); if (!headerInfoProvided) readImageBackupL1Launch(); // Right after launch, nothing is initialized and we must do that first using the full approach. else readImageBackupL1(); // Otherwise, we just read the data array. backgroundPushedDown = true; } } emit modelUpdateNeeded(chipName); } void MyImage::setupBackgroundData_newParallel(const bool &isTaskRepeated, const QString &backupDir) { if (!successProcessing) return; if (backgroundPushedDown) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images omp_set_lock(&backgroundLock); // Must not be done simultaneously dataCurrent_deletable = false; dataBackupL1_deletable = false; // CASE 1: The task has not been executed before if (!isTaskRepeated) { // Nothing is in backupL1 yet, either after restart, or because RAM is low. // No push-down has happened yet if (!backgroundPushedDown) { if (!minimizeMemoryUsage) { pushDownToL3(); pushDownToL2(); } readImage(true); // if not yet in memory pushDownToL1(backupDir); // Create a safe copy of the non-subtracted data dataBackupL1_deletable = false; // set to 'true' in pushDownToL1() backgroundPushedDown = true; } } // CASE 2: The task has been executed before (we have PAB images present in dataCurrent and PA images in backupL1) else { // Restoring from drive if not yet in memory if (!backupL1InMemory) { if (*verbosity > 2) emit messageAvailable(baseName + " : Task repeated, restoring data from backup FITS in "+pathBackupL1, "image"); if (!headerInfoProvided) readImageBackupL1Launch(); // Right after launch, nothing is initialized and we must do that first using the full approach. else readImageBackupL1(); // Otherwise, we just read the data array. backgroundPushedDown = true; } } emit modelUpdateNeeded(chipName); omp_unset_lock(&backgroundLock); } // If a task is repeated, replace dataCurrent with the backup copy. // Otherwise continue with data current, and push down the backup data one level void MyImage::setupCalibDataInMemory(bool createBackup, bool determineMode, bool mustRereadFromDisk) { if (!successProcessing) return; if (activeState != ACTIVE) return; // Don't change location of deactivated images // Restore level 1 backup (in case we reprocess the data). // Either get it from memory, or read it from disk // Backup only needed for FLATS (biases, darks and flatoff are not 'processed' at this point, but flats are bias-subtracted) if (backupL1InMemory) { // we are here only for flats; bias/darks are created without backup copy // TODO: this is not very safe. it would be better if we pass the Data type (BIAS, FLAT etc) along, and then // make the case distinctions concerning this value dataCurrent = dataBackupL1; imageInMemory = backupL1InMemory; } else { // In case of flats, the pixels were bias-subtracted. If the machine has low RAM, then "backupL1inMemory == false" // but it could be that "imageInMemory == true", then readImage() does not actually restore the original pixel values. // In this case, we must force a reread to refresh dataCurrent, but only for flats) if (mustRereadFromDisk) imageInMemory = false; readImage(determineMode); // Create backup copy, unless we don't need it (e.g. swarpfilter, or for bias/dark/flatoff) if (createBackup) { // true if not specified dataBackupL1 = dataCurrent; backupL1InMemory = true; } } emit modelUpdateNeeded(chipName); } // unused void MyImage::dumpToDriveIfPossible() { if (processingFinished && !imageOnDrive && imageInMemory) { writeImage(); unprotectMemory(); } } void MyImage::freeData(QVector<float> &data) { data.clear(); data.squeeze(); if (&data == &dataCurrent) imageInMemory = false; else if (&data == &dataWeight) weightInMemory = false; else if (&data == &dataBackupL1) backupL1InMemory = false; else if (&data == &dataBackupL2) backupL2InMemory = false; else if (&data == &dataBackupL3) backupL3InMemory = false; emit modelUpdateNeeded(chipName); } void MyImage::freeData() { dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; emit modelUpdateNeeded(chipName); } // this happens only inside memoryLock set in the controller // MUST USE MEMORY LOCCK! float MyImage::freeData(QString type) { bool released = false; // If the image has never been loaded, this function will crash in several places. // Why is not clear to me, perhaps because some strings and e.g. databackground are not initialized; if (type == "dataBackground" && dataBackground_deletable && dataBackground.capacity() > 0) { // TODO / CHECK: comment these if causing problems dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; released = true; } else if (type == "dataBackupL1" && dataBackupL1_deletable && dataBackupL1.capacity() > 0) { dataBackupL1.clear(); dataBackupL1.squeeze(); backupL1InMemory = false; released = true; } else if (type == "dataBackupL2" && dataBackupL2_deletable && dataBackupL2.capacity() > 0) { dataBackupL2.clear(); dataBackupL2.squeeze(); backupL2InMemory = false; released = true; } else if (type == "dataBackupL3" && dataBackupL3_deletable && dataBackupL3.capacity() > 0) { dataBackupL3.clear(); dataBackupL3.squeeze(); backupL3InMemory = false; released = true; } else if (type == "dataWeight" && dataWeight_deletable && dataWeight.capacity() > 0) { // weights are always writtwen to drive (for swarp) dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; released = true; } else if (type == "dataCurrent" && dataCurrent_deletable && dataCurrent.capacity() > 0) { // Must write image to drive if not yet the case if (!imageOnDrive) { writeImage(); imageOnDrive = true; } dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; released = true; } else if (type == "all") { // used if a project is changed; release all memory if (dataBackground.capacity() > 0) { dataBackground.clear(); dataBackground.squeeze(); backgroundModelDone = false; } if (dataBackupL1.capacity() > 0) { dataBackupL1.clear(); dataBackupL1.squeeze(); backupL1InMemory = false; } if (dataBackupL2.capacity() > 0) { dataBackupL2.clear(); dataBackupL2.squeeze(); backupL2InMemory = false; } if (dataBackupL3.capacity() > 0) { dataBackupL3.clear(); dataBackupL3.squeeze(); backupL3InMemory = false; } if (dataWeight.capacity() > 0) { // weights are always writtwen to drive (for swarp) dataWeight.clear(); dataWeight.squeeze(); weightInMemory = false; } if (dataCurrent.capacity() > 0) { dataCurrent.clear(); dataCurrent.squeeze(); imageInMemory = false; } } emit modelUpdateNeeded(chipName); if (released) return naxis1*naxis2*sizeof(float) / 1024. / 1024.; else return 0.; } void MyImage::protectMemory() { // Nothing we might change during nominal processing may be touched dataCurrent_deletable = false; dataBackground_deletable = false; dataBackupL1_deletable = false; dataWeight_deletable = false; } // After an image was written to drive (or isn't needed right away elsewhere) we can set all memory to deletable void MyImage::unprotectMemory() { // Memory is up for grabs dataCurrent_deletable = true; dataBackground_deletable = true; dataBackupL1_deletable = true; dataBackupL2_deletable = true; dataBackupL3_deletable = true; dataWeight_deletable = true; } void MyImage::unprotectMemoryWeight() { // Memory is up for grabs dataWeight_deletable = true; } // UNUSED /* // Selective deletable status void MyImage::setDeletable(QString dataX, bool deletable) { if (dataX == "dataCurrent") dataCurrent_deletable = deletable; else if (dataX == "dataBackupL1") dataBackupL1_deletable = deletable; else if (dataX == "dataBackupL2") dataBackupL2_deletable = deletable; else if (dataX == "dataBackupL3") dataBackupL3_deletable = deletable; else if (dataX == "dataWeight") dataWeight_deletable = deletable; else if (dataX == "dataBackground") dataBackground_deletable = deletable; } */ void MyImage::releaseMemoryForBackground() { if (enteredBackgroundWindow && leftBackgroundWindow) { if (!backupL1OnDrive) writeImageBackupL1(); freeData("dataBackupL1"); if (minimizeMemoryUsage) freeAll(); } } void MyImage::unprotectMemoryForBackground() { if (enteredBackgroundWindow && leftBackgroundWindow) { dataBackupL1_deletable = true; dataBackground_deletable = true; if (minimizeMemoryUsage) freeAll(); // implies that we write the FITS image before calling this function! } } void MyImage::freeAncillaryData(QVector<float> &data) { QVector<float>().swap(data); } void MyImage::freeAll() { emit setMemoryLock(true); freeData(dataBackupL1); freeData(dataBackupL2); freeData(dataBackupL3); freeData(dataCurrent); freeData(dataWeight); emit modelUpdateNeeded(chipName); emit setMemoryLock(false); }
23,817
C++
.cc
611
33.378069
163
0.690266
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,509
skysub.cc
schirmermischa_THELI/src/myimage/skysub.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "../functions.h" #include "myimage.h" #include "wcs.h" #include <gsl/gsl_vector.h> #include <QDebug> #include <QMessageBox> #include <QTextStream> #include <QFile> /* // subtract a polynomial fit void MyImage::subtractPolynomialSkyFit(gsl_vector* c, int order) { if (!successProcessing) return; QVector<double> ra; QVector<double> dec; QVector<double> radius; // readSkyPositions(ra, dec, sky); // calculateSkyFit(ra, dec, sky, order); } */ // Needed for polynomial fit QVector<long> MyImage::locateSkyNode(const double alpha, const double delta, const double radius) { double xpos = 0.; double ypos = 0.; sky2xy(alpha, delta, xpos, ypos); long xcen = xpos; long ycen = ypos; // maximally inscribe a square, of half width 'w' into the circular aperture long w = radius*0.7 / plateScale; if (w<1) return QVector<long>(); QVector<long> aperture; // If center is outside image (e.g. stray skysample file, bad user input, etc) if (xcen >= naxis1 || xcen <= 0. || ycen >= naxis2 || ycen <= 0) return aperture; long xmin = xcen - w < 0 ? 0 : xcen - w; long ymin = ycen - w < 0 ? 0 : ycen - w; long xmax = xcen + w >= naxis1 ? naxis1-1 : xcen + w; long ymax = ycen + w >= naxis2 ? naxis2-1 : ycen + w; long numPixels = (xmax-xmin+1)*(ymax-ymin+1); if (numPixels < 10) return QVector<long>(); // return if insufficient number of data points aperture << xmin << xmax << ymin << ymax; return aperture; } // Needed for polynomial fit and constant sky sub void MyImage::evaluateSkyNodes(const QVector<double> alpha, const QVector<double> delta, const QVector<double> radius) { if (alpha.length() != delta.length() || alpha.length() != radius.length() || alpha.isEmpty()) { return; } skyPolyfitNodes.clear(); for (long k=0; k<alpha.length(); ++k) { QVector<long> aperture = locateSkyNode(alpha[k], delta[k], radius[k]); if (aperture.isEmpty()) continue; QVector<float> sample; long xmin = aperture[0]; long xmax = aperture[1]; long ymin = aperture[2]; long ymax = aperture[3]; sample.reserve((xmax-xmin+1)*(ymax-ymin+1)); for (long j=ymin; j<=ymax; ++j) { for (long i=xmin; i<=xmax; ++i) { if (globalMaskAvailable) { if (!globalMask[i+naxis1*j]) sample.append(dataCurrent[i+naxis1*j]); } else { sample.append(dataCurrent[i+naxis1*j]); } } } float sky; if (sample.length() < 10) continue; // insufficient number of data points if (sample.length() < 1000) sky = straightMedian_T(sample); // Mode won't work if sample is small. else sky = modeMask(sample, "stable")[0]; QVector<double> node = {alpha[k], delta[k], sky}; skyPolyfitNodes.append(node); } } void MyImage::subtractSkyFit(int order, gsl_vector *c, bool saveSkyModel) { QVector<float> skymodel; if (saveSkyModel) skymodel.resize(naxis1*naxis2); skymodel.squeeze(); float skysum = 0.; if (*verbosity > 1) emit messageAvailable(baseName + " : Subtracting polynomial fit ...", "image"); long t = 0; for (long j=0; j<naxis2; ++j) { for (long i=0; i<naxis1; ++i) { // Calculate RA / DEC from linear WCS model // double ra_pix = wcs->cd[0] * (double(i)-wcs->crpix[0]) + wcs->cd[1] * (double(j)-wcs->crpix[1]) + wcs->crval[0]; // double dec_pix = wcs->cd[2] * (double(i)-wcs->crpix[0]) + wcs->cd[3] * (double(j)-wcs->crpix[1]) + wcs->crval[1]; // Potentially very slow! double ra_pix; double dec_pix; xy2sky(double(i), double(j), ra_pix, dec_pix); // Evaluate the background model double s = 0; double sky = gsl_vector_get(c, s++); // Do not combine the following two for loops, because of the s++ for (int k=1; k<=order; ++k) { sky += gsl_vector_get(c, s++) * pow(ra_pix, k); } for (int k=1; k<=order; ++k) { sky += gsl_vector_get(c, s++) * pow(dec_pix, k); } dataCurrent[i+naxis1*j] -= sky; skysum += sky; if (saveSkyModel) { skymodel[t] = sky; ++t; } } } meanExposureBackground = skysum / (naxis1*naxis2); if (saveSkyModel) { mkAbsDir(path + "/SKY_IMAGES"); QString fileName = path+"/SKY_IMAGES/"+baseName+".sky.fits"; write(fileName, skymodel, exptime, filter, header); } }
5,478
C++
.cc
136
33.073529
128
0.599285
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,510
segmentation.cc
schirmermischa_THELI/src/myimage/segmentation.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "instrumentdata.h" #include "../functions.h" #include "../tools/detectedobject.h" #include "myimage.h" #include <QDebug> #include <QMessageBox> #include <QQueue> void MyImage::resetObjectMasking() { // The background will always be the same, hence let's leave it in place // backgroundModelDone = false; // dataBackground.clear(); // dataBackground.squeeze(); segmentationDone = false; maskExpansionDone = false; objectMaskDone = false; objectMaskDonePass1 = false; objectMaskDonePass2 = false; for (auto object : objectList) { object->pixels_flux.clear(); object->pixels_x.clear(); object->pixels_y.clear(); object->pixels_flux.squeeze(); object->pixels_x.squeeze(); object->pixels_y.squeeze(); } objectList.clear(); objectMask.clear(); objectMask.squeeze(); } void MyImage::segmentImage(const QString DTstring, const QString DMINstring, const bool convolution, const bool writeSegImage) { // Catch internal QVector limitation (cannot hold more than 2^29 float elements) // if (naxis1*naxis2>=pow(2,29)) { // return; // } if (*verbosity > 1) emit messageAvailable(chipName + " : Detecting objects ... ", "image"); // Start fresh resetObjectMasking(); if (!successProcessing) return; if (DTstring.isEmpty() || DMINstring.isEmpty()) return; // Update the rms Value if it hasn't been determined yet // This is a fallback, because we get it through background modeling already at an earlier step. if (skySigma < 0.) { emit messageAvailable("MyImage::segmentImage(): sky noise not yet estimated, re-computing", "warning"); emit critical(); skySigma = modeMask(dataCurrent, "stable", QVector<bool>())[1]; } // Noise clipping // if this doesn't work, then make controller a member of each myimage emit setMemoryLock(true); dataSegmentation.resize(naxis1*naxis2); // this crashes for very large images (e.g. coadded omegacam data); likely internal Qvector limitation dataMeasure.clear(); // Must clear (if we run the detection twice, e.g. for sky modeling) // dataMeasure.reserve(naxis1*naxis2); dataMeasure.resize(naxis1*naxis2); emit setMemoryLock(false); // //deactivated; causes random crashes I don't understand // dataSegmentation.squeeze(); // shed excess memory // dataMeasure.squeeze(); // shed excess memory QList<long> allObjectPixelIndices; allObjectPixelIndices.reserve(naxis1*naxis2/2); // Avoid initial memory reallocations; assume half the pixels belong to objects // Noise filter (for detection only) QVector<float> dataConv; if (convolution) dataConv = directConvolve(dataCurrent); else dataConv = dataCurrent; float DT = DTstring.toFloat(); float threshold = DT*skySigma; float maxWeight = 1.0; // Adapt threshold concerning the weight, if available if (weightInMemory) { maxWeight = maxVec_T(dataWeight); // Could sort a sub-sample and use the 90% highest value or sth like that, more stable } long i = 0; for (auto &pixel: dataCurrent) { // subtract background model float dorig = pixel - dataBackground.at(i); float dconv = dataConv.at(i) - dataBackground.at(i); // dataMeasure.append(dorig); dataMeasure[i] = dorig; // Initialize objects in the segmentation map with a negative value (meaning it is still unprocessed) // WARNING: Using the globalMask is essential, otherwise the floodfill alg seems to run forever. Really? // With global mask if (globalMaskAvailable) { if (!weightInMemory) { if (dconv > threshold && !globalMask.at(i)) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } else { float rescale = sqrt(maxWeight/dataWeight.at(i)); if (dataWeight.at(i) > 0. && !globalMask.at(i) && dconv > threshold*rescale) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } } // Without global mask else { if (!weightInMemory) { if (dconv > threshold) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } else { float rescale = sqrt(maxWeight/dataWeight.at(i)); if (dataWeight.at(i) > 0. && dconv > threshold*rescale) { dataSegmentation[i] = -1; allObjectPixelIndices.append(i); } } } ++i; } if (allObjectPixelIndices.isEmpty()) { emit messageAvailable(chipName + " : No objects detected!" , "error"); emit critical(); successProcessing = false; return; } // Create segmentation map objectList.clear(); bool scanning = true; long startindex = allObjectPixelIndices[0]; long DMIN = DMINstring.toLong(); QPoint startPoint(startindex % naxis1, startindex / naxis1); long objID = 1; // Number of the first object; we start counting at 1 not 0 while (scanning) { // Flood fill the current object belonging to that pixel, and update dataSegmentation and allObjectPixelIndices floodFill(startPoint, allObjectPixelIndices, objID, dataSegmentation, DMIN); // Retrieve next non-zero pixel index from 'objectPixelIndices' if (!allObjectPixelIndices.isEmpty()) { long nextIndex = allObjectPixelIndices.first(); startPoint.setX(nextIndex % naxis1); startPoint.setY(nextIndex / naxis1); } else { scanning = false; } } segmentationDone = true; // Lastly, compute object parameters (which we need for masking) if (*verbosity > 1) emit messageAvailable(chipName + " : Measuring object parameters ... ", "image"); // #pragma omp parallel for num_threads(maxCPU) for (long i=0; i<objectList.length(); ++i) { objectList[i]->apertures = apertures; objectList[i]->computeObjectParams(); objectList[i]->remove(); } if (*verbosity > 1) emit messageAvailable(chipName + " : " + QString::number(objectList.length()) + " objects detected.", "image"); segmentationDone = true; if (writeSegImage) writeSegmentation(path + "/" + baseName+".seg.fits"); } // getting a rough first estimate on image quality; refined after astrometric solution void MyImage::calcMedianSeeingEllipticity() { QVector<double> fwhmVec; QVector<double> ellipticityVec; fwhmVec.reserve(objectList.length()); ellipticityVec.reserve(objectList.length()); for (auto &object : objectList) { if (object->FLAGS == 0) { fwhmVec.append(float(object->FWHM)); ellipticityVec.append(float(object->ELLIPTICITY)); } } fwhm_est = straightMedianInline(fwhmVec) * plateScale; ellipticity_est = straightMedianInline(ellipticityVec); updateHeaderValueInFITS("FWHMEST", QString::number(fwhm_est, 'f', 2)); updateHeaderValueInFITS("ELLIPEST", QString::number(ellipticity_est, 'f', 3)); } // Flood fill an individual object with the objectID and calculate object area void MyImage::floodFill(const QPoint startPoint, QList<long> &allObjectPixelIndices, long &objID, QVector<long> &dataSegmentation, const long DMIN) { if (!insideImage(startPoint)) return; // Did we process this point already? If so, remove it from the list of indices long index = startPoint.x() + naxis1*startPoint.y(); if (dataSegmentation[index] != -1) { allObjectPixelIndices.pop_front(); return; } // temporary storage to mark pixels for deletion (if area less than DMIN) QList<long> currentObjectPixels; currentObjectPixels.reserve(10000); QQueue<QPoint> pointQueue; pointQueue.enqueue(startPoint); // This is the actual flood filling long area = 0; while (!pointQueue.isEmpty()) { QPoint p = pointQueue.first(); pointQueue.pop_front(); if (insideImage(p)) { if (dataSegmentation[p.x()+naxis1*p.y()] == -1) { dataSegmentation[p.x()+naxis1*p.y()] = objID; // queue the edges pointQueue.enqueue(QPoint(p.x() + 1, p.y())); pointQueue.enqueue(QPoint(p.x() - 1, p.y())); pointQueue.enqueue(QPoint(p.x(), p.y() + 1)); pointQueue.enqueue(QPoint(p.x(), p.y() - 1)); // queue the corners (8-connectivity) pointQueue.enqueue(QPoint(p.x()-1, p.y()-1)); pointQueue.enqueue(QPoint(p.x()+1, p.y()-1)); pointQueue.enqueue(QPoint(p.x()-1, p.y()+1)); pointQueue.enqueue(QPoint(p.x()+1, p.y()+1)); currentObjectPixels.push_back(p.x()+naxis1*p.y()); } } } area = currentObjectPixels.length(); // remove object from segmentation map if too small if (area < DMIN) { for (auto &pixel: currentObjectPixels) { dataSegmentation[pixel] = 0; } return; } // Initialize the object and add it to the list of detected sources for this image float effectiveGain = 1.0; // ADUs converted during HDU reformatting DetectedObject *newObject = new DetectedObject(currentObjectPixels, dataMeasure, dataBackground, dataWeight, globalMask, weightInMemory, naxis1, naxis2, ++objID, saturationValue, effectiveGain, *wcs); newObject->globalMaskAvailable = globalMaskAvailable; objectList.append(newObject); // Remove the current pixel we just processed, // and potentially a few more if they happen to be at the beginning of the list while (!allObjectPixelIndices.isEmpty() && !currentObjectPixels.isEmpty() && allObjectPixelIndices.first() == currentObjectPixels.first()) { allObjectPixelIndices.pop_front(); currentObjectPixels.pop_front(); } } bool MyImage::insideImage(QPoint p) { if (p.rx() >= 0 && p.rx() < naxis1 && p.ry() >= 0 && p.ry() < naxis2) return true; else return false; } // convolve with a general purpose noise filter QVector<float> MyImage::directConvolve(const QVector<float> &data) { float kernel[] = { 1./16., 2./16., 1./16., 2./16., 4./16., 2./16., 1./16., 2./16., 1./16.}; long n = naxis1; long m = naxis2; QVector<float> dataConv(n*m); // direct convolution. We ignore the border long s = 1; // half the kernel size - 1 for (long j=1; j<naxis2-1; ++j) { for (long i=1; i<naxis1-1; ++i) { for (long ii=-s; ii<=s; ++ii) { for (long jj=-s; jj<=s; ++jj) { dataConv[i+n*j] += data[i+ii + n*(j+jj)] * kernel[ii+s + (2*s+1)*(jj+s)]; } } } } return dataConv; } // Transfer the detections to the object mask void MyImage::transferObjectsToMask() { if (!successProcessing) return; objectMask.fill(false, naxis1*naxis2); if (objectList.isEmpty()) return; long i=0; for (auto &segment : dataSegmentation) { if (segment > 0.) objectMask[i] = true; ++i; } objectMaskDone = true; } void MyImage::estimateMatchingTolerance() { QVector<float> sizes; for (auto &object : objectList) { if (object->FLAGS == 0) sizes.append(object->FLUX_RADIUS); } if (sizes.isEmpty()) { matchingTolerance = 5.*plateScale/3600.; // 5 pixel if (*verbosity > 2) emit messageAvailable(chipName + " : IQ matching tolerance defaulted to "+QString::number(5.*plateScale, 'f', 1)+" arcsec (5 pixel)", "image"); emit warning(); } else { float radius = straightMedian_T(sizes); // used to be twice as large matchingTolerance = radius * plateScale / 3600.; if (*verbosity > 2) emit messageAvailable(chipName + " : IQ matching tolerance = "+QString::number(matchingTolerance*3600, 'f', 1)+" arcsec", "image"); } } // Unused QVector<double> MyImage::collectObjectParameter(QString paramName) { QVector<double> param; param.reserve(objectList.length()); if (paramName == "RA") { for (auto &object : objectList) { param << object->ALPHA_J2000; } } if (paramName == "DEC") { for (auto &object : objectList) { param << object->DELTA_J2000; } } if (paramName == "FWHM") { for (auto &object : objectList) { param << object->FLUX_RADIUS; } } if (paramName == "ELLIPTICITY") { for (auto &object : objectList) { param << object->ELLIPTICITY; } } return param; } void MyImage::collectSeeingParameters(QVector<QVector<double>> &outputParams, QVector<double> &outputMag, int goodChip) { QVector<double> param; param.reserve(4); outputParams.clear(); // Must clear because each image will fill this data repeatedly outputMag.clear(); // Try memory access in MyImage if (!objectList.isEmpty()) { outputParams.reserve(objectList.length()); outputMag.reserve(objectList.length()); for (auto &object : objectList) { // Must recalculate RA and DEC after astrometry double raNew; double decNew; xy2sky(object->XWIN, object->YWIN, raNew, decNew); // must pass dec first for tools::match2D() method if (object->FLAGS == 0) { param << decNew << raNew << object->FWHM << object->ELLIPTICITY; outputParams << param; outputMag << object->MAG_AUTO; param.clear(); } } return; } // Not present (if GUI launched at this position, or Source Extractor was used to compute catalogs) // Try external catalog else { QString catalogName = "cat/" + rootName+".scamp"; QString fullCatalogName = path + "/" + catalogName; QFile catalog(fullCatalogName); if (!catalog.exists()) { emit messageAvailable(chipName + " : Could not find catalog for seeing measurement:<br>" + catalogName, "warning"); emit warning(); } int status = 0; fitsfile *fptr; fits_open_file(&fptr, fullCatalogName.toUtf8().data(), READONLY, &status); // LDAC_OBJECTS tables are found in extensions 3, 5, 7, ..., internally referred to as 2, 4, 6, ... int hduType = 0; fits_movabs_hdu(fptr, 2*(goodChip+1)+1, &hduType, &status); // fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); long nrows = 0; int xwinColNum = -1; int ywinColNum = -1; int alphaColNum = -1; int deltaColNum = -1; int fwhmColNum = -1; int ellColNum = -1; int magColNum = -1; int flagColNum = -1; fits_get_num_rows(fptr, &nrows, &status); char xwinName[100] = "XWIN_IMAGE"; char ywinName[100] = "YWIN_IMAGE"; char alphaName[100] = "ALPHA_J2000"; char deltaName[100] = "DELTA_J2000"; char fwhmName[100] = "FWHM_IMAGE"; char ellName[100] = "ELLIPTICITY"; char magName[100] = "MAG_AUTO"; char flagName[100] = "FLAGS"; fits_get_colnum(fptr, CASESEN, xwinName, &xwinColNum, &status); fits_get_colnum(fptr, CASESEN, ywinName, &ywinColNum, &status); fits_get_colnum(fptr, CASESEN, alphaName, &alphaColNum, &status); fits_get_colnum(fptr, CASESEN, deltaName, &deltaColNum, &status); fits_get_colnum(fptr, CASESEN, fwhmName, &fwhmColNum, &status); fits_get_colnum(fptr, CASESEN, ellName, &ellColNum, &status); fits_get_colnum(fptr, CASESEN, magName, &magColNum, &status); fits_get_colnum(fptr, CASESEN, flagName, &flagColNum, &status); int firstrow = 1; int firstelem = 1; int anynul = 0; double *xwin = new double[nrows]; double *ywin = new double[nrows]; double *alpha = new double[nrows]; double *delta = new double[nrows]; float *fwhm = new float[nrows]; float *ell = new float[nrows]; float *mag = new float[nrows]; int *flag = new int[nrows]; QString missing = ""; fits_read_col(fptr, TDOUBLE, xwinColNum, firstrow, firstelem, nrows, NULL, xwin, &anynul, &status); if (status != 0) missing.append("XWIN_IMAGE, "); status = 0; fits_read_col(fptr, TDOUBLE, ywinColNum, firstrow, firstelem, nrows, NULL, ywin, &anynul, &status); if (status != 0) missing.append("YWIN_IMAGE, "); status = 0; fits_read_col(fptr, TDOUBLE, alphaColNum, firstrow, firstelem, nrows, NULL, alpha, &anynul, &status); if (status != 0) missing.append("ALPHA_J2000, "); status = 0; fits_read_col(fptr, TDOUBLE, deltaColNum, firstrow, firstelem, nrows, NULL, delta, &anynul, &status); if (status != 0) missing.append("DELTA_J2000, "); status = 0; fits_read_col(fptr, TFLOAT, fwhmColNum, firstrow, firstelem, nrows, NULL, fwhm, &anynul, &status); if (status != 0) missing.append("FWHM_IMAGE, "); status = 0; fits_read_col(fptr, TFLOAT, ellColNum, firstrow, firstelem, nrows, NULL, ell, &anynul, &status); if (status != 0) missing.append("ELLIPTICITY, "); status = 0; fits_read_col(fptr, TFLOAT, magColNum, firstrow, firstelem, nrows, NULL, mag, &anynul, &status); if (status != 0) missing.append("MAG_AUTO, "); status = 0; fits_read_col(fptr, TINT, flagColNum, firstrow, firstelem, nrows, NULL, flag, &anynul, &status); if (status != 0) missing.append("FLAGS, "); status = 0; fits_close_file(fptr, &status); if (!missing.isEmpty()) { emit messageAvailable(chipName + " : Could not find " + missing + " in " + catalogName, "warning"); } outputParams.reserve(nrows); outputMag.reserve(nrows); for (long i=0; i<nrows; ++i) { // Must recalculate RA and DEC after astrometry double raNew; double decNew; xy2sky(xwin[i]-1., ywin[i]-1., raNew, decNew); // xy2sky expects zero-indexed cartesian coordinates // must pass dec first for tools::match2D() method // Only clean detections wanted! if (flag[i] == 0) { param << decNew << raNew << fwhm[i] << ell[i]; outputParams << param; outputMag << mag[i]; param.clear(); } } } } void MyImage::maskExpand(QString expFactor, bool writeObjectmaskImage) { if (!successProcessing) return; if (maskExpansionDone) return; // Don't redo the mask expansion (when calculating a dynamic model, revisiting the same image) if (expFactor.isEmpty()) { if (writeObjectmaskImage) writeObjectMask(path + "/" + baseName+".mask.fits"); return; } float factor = expFactor.toFloat(); if (factor < 1.0) { emit messageAvailable(chipName + " : Mask expansion factor less than 1.0; ignored ...", "warning"); emit warning(); return; } if (*verbosity > 1) emit messageAvailable(chipName + " : Expanding object mask ...", "image"); factor *= 3.; // We need an extra factor of 3 to encompass the outer isophote long n = naxis1; long m = naxis2; for (auto &it : objectMask) it = false; // Loop over all objects for (auto &object : objectList) { // skip spurious and bad detections if (object->badDetection) continue; // Do not mask expand extremely small objects (hot pixels etc) if (object->B < 1.0) continue; // Do not mask expand very large and extremely elongated objects (bad columns, saturation spikes) if (object->ELLIPTICITY > 0.9 && object->A > 50) continue; float oX = object->X; float oY = object->Y; float oAf = object->A * factor; float xextent = 3. * pow(object->A*factor, 2); // max ellipse extent in x direction float yextent = 3. * object->A * object->B * factor * factor; // max ellipse extent in y direction long imin = (oX - xextent > 0) ? int(oX - xextent) : 0; long imax = (oX + xextent < n) ? int(oX + xextent) : n-1; long jmin = (oY - yextent > 0) ? int(oY - yextent) : 0; long jmax = (oY + yextent < m) ? int(oY + yextent) : m-1; // Loop over the rectangular subset of pixels that encompass the object for (long j=jmin; j<=jmax; ++j) { float dy = oY - j; for (long i=imin; i<=imax; ++i) { float dx = oX - i; if (object->CXX*dx*dx + object->CYY*dy*dy + object->CXY*dx*dy <= oAf*oAf) { objectMask[i+naxis1*j] = true; } } } } maskExpansionDone = true; if (writeObjectmaskImage) writeObjectMask(path + "/" + baseName+".mask.fits"); } // not part of the segmentation process, actually void MyImage::addExludedRegionToMask(long imin, long imax, long jmin, long jmax) { if (imin < 0) imin = 0; if (imax > naxis1 - 1) imax = naxis1 - 1; if (jmin < 0) jmin = 0; if (jmax > naxis2 - 1) jmax = naxis2 - 1; if (jmin == 0) for (long j=jmin; j<=jmax; ++j) { for (long i=imin; i<=imax; ++i) { objectMask[i+naxis2*j] = true; } } } void MyImage::releaseAllDetectionMemory() { for (auto &object : objectList) { delete object; object = nullptr; } objectList.clear(); releaseDetectionPixelMemory(); } void MyImage::releaseDetectionPixelMemory() { emit setMemoryLock(true); dataSegmentation.clear(); dataSegmentation.squeeze(); dataMeasure.clear(); dataMeasure.squeeze(); objectMask.clear(); objectMask.squeeze(); objectMaskDone = false; objectMaskDonePass1 = false; objectMaskDonePass2 = false; segmentationDone = false; emit setMemoryLock(false); } void MyImage::writeCatalog(QString minFWHM_string, QString maxFlag_string, QString maxEll_string) { QString outpath = path+"/cat/iview/"; QDir outdir(outpath); if (!outdir.exists()) outdir.mkpath(outpath); float minFWHM = minFWHM_string.toFloat(); float maxFlag = maxFlag_string.toFloat(); float maxEll = maxEll_string.toFloat(); if (maxFlag_string.isEmpty()) maxFlag = 100; if (maxEll_string.isEmpty()) maxEll = 0.7; // Write iview catalog QFile file(path+"/cat/iview/"+chipName+".iview"); if (file.open(QIODevice::WriteOnly)) { QTextStream outputStream(&file); for (auto &object : objectList) { outputStream.setRealNumberPrecision(9); if (3.*object->AWIN >= minFWHM && object->FLAGS <= maxFlag && object->ELLIPTICITY <= maxEll && object->FLUX_AUTO > 0.) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) outputStream << object->XWIN + 1. << " " << object->YWIN + 1. << " " << object->AWIN << " " << object->BWIN << " " << object->THETAWIN << "\n"; } } file.close(); } else { emit messageAvailable("Could not create IView source catalog: "+path+"/cat/iview/"+chipName+".iview", "error"); emit critical(); } // Write anet catalog char x[100] = "X"; char y[100] = "Y"; char mag[100] = "MAG"; char *ttype[3] = {x, y, mag}; char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char *tform[3] = {tf1, tf2, tf3}; long numSources = objectList.length(); long numSourcesRetained = 0.; for (long i=0; i<numSources; ++i) { if (3.*objectList[i]->AWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->ELLIPTICITY <= maxEll && objectList[i]->FLUX_AUTO > 0.) { ++numSourcesRetained; } } long nrows = numSourcesRetained; double x_arr[nrows]; double y_arr[nrows]; float mag_arr[nrows]; long k = 0; for (long i=0; i<numSources; ++i) { if (3.*objectList[i]->AWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->ELLIPTICITY <= maxEll && objectList[i]->FLUX_AUTO > 0.) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) x_arr[k] = objectList[i]->XWIN + 1.; y_arr[k] = objectList[i]->YWIN + 1.; mag_arr[k] = objectList[i]->MAG_AUTO; ++k; } } int status = 0; fitsfile *fptr; long firstrow = 1; long firstelem = 1; int tfields = 3; QString filename = path+"/cat/"+chipName+".anet"; filename = "!"+filename; fits_create_file(&fptr, filename.toUtf8().data(), &status); fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype, tform, nullptr, "OBJECTS", &status); fits_write_col(fptr, TDOUBLE, 1, firstrow, firstelem, nrows, x_arr, &status); fits_write_col(fptr, TDOUBLE, 2, firstrow, firstelem, nrows, y_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, mag_arr, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); } void MyImage::makeXcorrData() { dataXcorr = dataCurrent; // Xcorrelation works best if we mask all unrelevant pixels long i = 0; for (auto &pixel: dataXcorr) { if (globalMaskAvailable && globalMask.at(i)) pixel = 0.; if (dataSegmentation.at(i) == -1) pixel = 0.; if (weightInMemory && dataWeight.at(i) == 0.) pixel = 0.; ++i; } } // Appends a new binary table to an already opened FITS file (handled by Controller class) void MyImage::appendToScampCatalogInternal(fitsfile *fptr, QString minFWHM_string, QString maxFlag_string, QString maxEll_string, bool empty) { float minFWHM = minFWHM_string.toFloat(); float maxFlag = maxFlag_string.toFloat(); float maxEll = maxEll_string.toFloat(); if (maxFlag_string.isEmpty()) maxFlag = 100; if (maxEll_string.isEmpty()) maxEll = 0.7; if (minFWHM_string.isEmpty()) minFWHM = 0.01; // STEP 1: LDAC_IMHEAD table, containing the FITS header int status = 0; long firstrow = 1; long firstelem = 1; int tfields = 1; long nrows = 1; char name[100] = "Field Header Card"; char *ttype1[1] = {name}; // Awkward C-stuff. This is the only way I could get this to work. // If the tf0 string is built differently, if strcmp says they are identical, the TTYPE1 keyword is not written properly. // And it cannot be udpated properly with fits_update_key() either // Update the WCS keywords in fullheader so the LDAC_IMHEAD string is correct. Not sure scamp cares, but nonetheless replaceCardInFullHeaderString("CRVAL1", wcs->crval[0]); replaceCardInFullHeaderString("CRVAL2", wcs->crval[1]); replaceCardInFullHeaderString("CRPIX1", wcs->crpix[0]); replaceCardInFullHeaderString("CRPIX2", wcs->crpix[1]); replaceCardInFullHeaderString("CD1_1", wcs->cd[0]); replaceCardInFullHeaderString("CD1_2", wcs->cd[1]); replaceCardInFullHeaderString("CD2_1", wcs->cd[2]); replaceCardInFullHeaderString("CD2_2", wcs->cd[3]); long headerLength = strlen(fullheader); char tf0[100]; sprintf(tf0, "%ldA", headerLength); char *tform1[1] = {tf0}; const char *headerstring[1]; headerstring[0] = fullheader; fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype1, tform1, nullptr, "LDAC_IMHEAD", &status); fits_write_col(fptr, TSTRING, 1, firstrow, firstelem, nrows, headerstring, &status); // STEP 2: LDAC_OBJECTS table char xwin[100] = "XWIN_IMAGE"; char ywin[100] = "YWIN_IMAGE"; char erra[100] = "ERRAWIN_IMAGE"; char errb[100] = "ERRBWIN_IMAGE"; char errt[100] = "ERRTHETAWIN_IMAGE"; char flux[100] = "FLUX_AUTO"; char fluxerr[100] = "FLUXERR_AUTO"; char flags[100] = "FLAGS"; char alpha[100] = "ALPHA_J2000"; char delta[100] = "DELTA_J2000"; char fwhm[100] = "FWHM_IMAGE"; char mag[100] = "MAG_AUTO"; char ell[100] = "ELLIPTICITY"; char *ttype2[13] = {xwin, ywin, erra, errb, errt, flux, fluxerr, flags, alpha, delta, fwhm, mag, ell}; char tf1[10] = "1E"; char tf2[10] = "1E"; char tf3[10] = "1E"; char tf4[10] = "1E"; char tf5[10] = "1E"; char tf6[10] = "1E"; char tf7[10] = "1E"; char tf8[10] = "1I"; char tf9[10] = "1D"; char tf10[10] = "1D"; char tf11[10] = "1E"; char tf12[10] = "1E"; char tf13[10] = "1E"; char *tform2[13] = {tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11, tf12, tf13}; long numSources = objectList.length(); // if (empty) numSources = 0; // empty table for deactivated images long numSourcesRetained = 0; for (long i=0; i<numSources; ++i) { if (3.*objectList[i]->AWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->ELLIPTICITY <= maxEll && objectList[i]->FLUX_AUTO > 0.) { ++numSourcesRetained; } } nrows = numSourcesRetained; // one row per source // if (empty) nrows = 0; // empty table for deactivated images float xwin_arr[nrows]; float ywin_arr[nrows]; float erra_arr[nrows]; float errb_arr[nrows]; float errt_arr[nrows]; float flux_arr[nrows]; float fluxerr_arr[nrows]; short flags_arr[nrows]; double alpha_arr[nrows]; double delta_arr[nrows]; float fwhm_arr[nrows]; float mag_arr[nrows]; float ell_arr[nrows]; long k = 0; for (long i=0; i<numSources; ++i) { if (3.*objectList[i]->AWIN >= minFWHM && objectList[i]->FLAGS <= maxFlag && objectList[i]->ELLIPTICITY <= maxEll && objectList[i]->FLUX_AUTO > 0.) { // MUST APPLY ORIGIN OFFSET CORRECTION (+1), because calculations were done starting counting at 0 (in FITS files we start at 1) xwin_arr[k] = objectList[i]->XWIN + 1.; ywin_arr[k] = objectList[i]->YWIN + 1.; erra_arr[k] = objectList[i]->ERRAWIN; errb_arr[k] = objectList[i]->ERRBWIN; errt_arr[k] = objectList[i]->ERRTHETAWIN; flux_arr[k] = objectList[i]->FLUX_AUTO; fluxerr_arr[k] = sqrt(objectList[i]->FLUX_AUTO); flags_arr[k] = objectList[i]->FLAGS; // The following are not needed by scamp. They are just for completeness. alpha_arr[k] = objectList[i]->ALPHA_J2000; delta_arr[k] = objectList[i]->DELTA_J2000; fwhm_arr[k] = objectList[i]->FWHM; mag_arr[k] = objectList[i]->MAG_AUTO; ell_arr[k] = objectList[i]->ELLIPTICITY; ++k; } } firstrow = 1; firstelem = 1; tfields = 13; fits_create_tbl(fptr, BINARY_TBL, nrows, tfields, ttype2, tform2, nullptr, "LDAC_OBJECTS", &status); fits_write_col(fptr, TFLOAT, 1, firstrow, firstelem, nrows, xwin_arr, &status); fits_write_col(fptr, TFLOAT, 2, firstrow, firstelem, nrows, ywin_arr, &status); fits_write_col(fptr, TFLOAT, 3, firstrow, firstelem, nrows, erra_arr, &status); fits_write_col(fptr, TFLOAT, 4, firstrow, firstelem, nrows, errb_arr, &status); fits_write_col(fptr, TFLOAT, 5, firstrow, firstelem, nrows, errt_arr, &status); fits_write_col(fptr, TFLOAT, 6, firstrow, firstelem, nrows, flux_arr, &status); fits_write_col(fptr, TFLOAT, 7, firstrow, firstelem, nrows, fluxerr_arr, &status); fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, flags_arr, &status); fits_write_col(fptr, TDOUBLE, 9, firstrow, firstelem, nrows, alpha_arr, &status); fits_write_col(fptr, TDOUBLE, 10, firstrow, firstelem, nrows, delta_arr, &status); fits_write_col(fptr, TFLOAT, 11, firstrow, firstelem, nrows, fwhm_arr, &status); fits_write_col(fptr, TFLOAT, 12, firstrow, firstelem, nrows, mag_arr, &status); fits_write_col(fptr, TFLOAT, 13, firstrow, firstelem, nrows, ell_arr, &status); // fits_write_col(fptr, TSHORT, 8, firstrow, firstelem, nrows, fieldpos, &status); // Color-coding output lines QString detStatus = ""; QString level = "image"; if (nrows<10 && nrows>3) { detStatus = " (low source count)"; level = "warning"; } if (nrows<=3 && nrows >= 1) { detStatus = " (very low source count)"; level = "stop"; } if (nrows==0) { detStatus = " (no sources detected, or image deactivated)"; level = "stop"; } messageAvailable(rootName + " : " + QString::number(nrows) + " sources after filtering..." +detStatus, level); printCfitsioError(__func__, status); }
34,296
C++
.cc
799
35.116395
171
0.611926
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,511
astrometrynet.cc
schirmermischa_THELI/src/myimage/astrometrynet.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // This file deals with running anettractor as an external tool #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../threading/anetworker.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> #include <QProcess> #include <QTest> void MyImage::buildAnetCommand(QString pixscale_maxerr) { if (!successProcessing) return; anetCommand = findExecutableName("solve-field"); anetCommand += " -w "+QString::number(naxis1); anetCommand += " -e "+QString::number(naxis2); anetCommand += " -L "+QString::number(plateScale / pixscale_maxerr.toFloat(), 'f', 5); anetCommand += " -H "+QString::number(plateScale * pixscale_maxerr.toFloat(), 'f', 5); anetCommand += " -O"; // suppress output anetCommand += " -p"; // suppress output plots anetCommand += " -u app"; // units arcsec per pixel anetCommand += " -l 5"; // CPU timeout after 5 seconds anetCommand += " -T"; // don't compute SIP polynomials anetCommand += " -s MAG"; // sort column anetCommand += " -a "; // sort order: ascending (bright sources first) anetCommand += " -b " + path + "/astrom_photom_anet/backend.cfg"; // config file anetCommand += " -R none"; // suppress output anetCommand += " -B none"; // suppress output anetCommand += " -S none"; // suppress output anetCommand += " -M none"; // suppress output anetCommand += " -U none"; // suppress output anetCommand += " --temp-axy"; // suppress output anetCommand += " -W " + path + "/astrom_photom_anet/"+chipName+".wcs"; // output file anetCommand += " " + path + "/cat/"+chipName+".anet"; if (*verbosity > 1) emit messageAvailable("Executing the following astrometry.net command :<br><br>"+anetCommand+"<br>", "info"); } // start in new thread void MyImage::runAnetCommand() { if (!successProcessing) return; // Run the solve-field command anetSolved = true; workerThread = new QThread(); anetWorker = new AnetWorker(anetCommand, path); anetWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, anetWorker, &AnetWorker::runAnet); connect(anetWorker, &AnetWorker::errorFound, this, &MyImage::errorFoundReceived); connect(anetWorker, &AnetWorker::didNotSolve, this, &MyImage::didNotSolveReceived); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); // Direct connection required, otherwise the task hangs after the first solve-field command // (does not proceed to the next step in the controller's for loop) connect(anetWorker, &AnetWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(anetWorker, &AnetWorker::finished, anetWorker, &QObject::deleteLater); connect(anetWorker, &AnetWorker::messageAvailable, this, &MyImage::anetOutputReceived); workerThread->start(); workerThread->wait(); } void MyImage::didNotSolveReceived() { anetSolved = false; } QString MyImage::extractAnetOutput() { QString anetOutput = path + "/astrom_photom_anet/"+chipName+".wcs"; QFile wcsOutput(anetOutput); if (!wcsOutput.exists()) { emit messageAvailable(chipName + " : Did not solve!", "error"); emit critical(); return ""; } else { emit messageAvailable(chipName + " : Successfully solved", "note"); } QString header; fitsfile *fptr; int status = 0; int nkeys = 0; int keypos = 0; char card[FLEN_CARD]; fits_open_file(&fptr, anetOutput.toUtf8().data(), READONLY, &status); fits_get_hdrpos(fptr, &nkeys, &keypos, &status); for (int jj = 1; jj <= nkeys; ++jj) { fits_read_record(fptr, jj, card, &status); QString cardString(card); if (cardString.contains("EQUINOX =") || cardString.contains("RADESYS =") || cardString.contains("CTYPE1 =") || cardString.contains("CTYPE2 =") || cardString.contains("CUNIT1 =") || cardString.contains("CUNIT2 =") || cardString.contains("CRVAL1 =") || cardString.contains("CRVAL2 =") || cardString.contains("CRPIX1 =") || cardString.contains("CRPIX2 =") || cardString.contains("CD1_1 =") || cardString.contains("CD1_2 =") || cardString.contains("CD2_1 =") || cardString.contains("CD2_2 =")) { header.append(cardString); header.append("\n"); } } header.append("END\n"); if (status == END_OF_FILE) status = 0; else printCfitsioError(__func__, status); fits_close_file(fptr, &status); return header; }
5,782
C++
.cc
126
40.428571
133
0.632074
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,512
writefits.cc
schirmermischa_THELI/src/myimage/writefits.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #include "myimage.h" #include "../functions.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingStatus/processingStatus.h" #include "wcs.h" #include "wcshdr.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> void MyImage::writeImage(QString fileName, QString filter, float exptime, bool addGain) { if (!successProcessing) return; if (fileName.isEmpty()) { fileName = path+"/"+chipName+processingStatus->statusString+".fits"; } if (addGain) addGainNormalization = true; else addGainNormalization = false; bool success = write(fileName, dataCurrent, exptime, filter, header); if (success) imageOnDrive = true; else imageOnDrive = false; emit modelUpdateNeeded(chipName); } // same as above, just writes the dataTIFF vector instead void MyImage::writeImageTIFF(QString fileName, QString filter, float exptime, bool addGain) { if (!successProcessing) return; if (addGain) addGainNormalization = true; else addGainNormalization = false; static_cast<void> (write(fileName, dataTIFF, exptime, filter, header)); } void MyImage::writeImageBackupL1() { if (!successProcessing) return; if (dataBackupL1.isEmpty() || !backupL1InMemory) return; QString fileName = pathBackupL1+"/"+chipName+statusBackupL1+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL1, exptime, filter, header); if (success) backupL1OnDrive = true; else backupL1OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeImageBackupL2() { if (!successProcessing) return; if (dataBackupL2.isEmpty() || !backupL2InMemory) return; QString fileName = pathBackupL2+"/"+chipName+statusBackupL2+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL2, exptime, filter, header); if (success) backupL2OnDrive = true; else backupL2OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeImageBackupL3() { if (!successProcessing) return; if (dataBackupL3.isEmpty() || !backupL3InMemory) return; QString fileName = pathBackupL3+"/"+chipName+statusBackupL3+".fits"; addGainNormalization = true; bool success = write(fileName, dataBackupL3, exptime, filter, header); if (success) backupL3OnDrive = true; else backupL3OnDrive = false; // emit modelUpdateNeeded(chipName); } void MyImage::writeBackgroundModel() { if (!successProcessing) return; mkAbsDir(path + "/SKY_IMAGES"); QString fileName = path + "/SKY_IMAGES/" + baseName+".sky.fits"; write(fileName, dataBackground, exptime, filter, header); } void MyImage::writeWeight(QString fileName) { if (!successProcessing) return; bool success = write(fileName, dataWeight, exptime, filter, header); if (success) weightOnDrive = true; else weightOnDrive = false; } void MyImage::linkWeight(QString globalWeightName, QString linkName) { if (!successProcessing) return; bool success = QFile::link(globalWeightName, linkName); if (success) weightOnDrive = true; else weightOnDrive = false; } void MyImage::writeWeightSmoothed(QString fileName) { if (!successProcessing) return; bool success = write(fileName, dataWeightSmooth, exptime, filter, header); if (success) weightOnDrive = true; else weightOnDrive = false; } void MyImage::writeConstSkyImage(float constValue) { if (!successProcessing) return; mkAbsDir(path+"/SKY_IMAGES"); QString fileName = path+"/SKY_IMAGES/"+baseName+".sky.fits"; writeConstImage(fileName, constValue, header); } void MyImage::writeImageDebayer(bool addGain) { if (!successProcessing) return; QString fileName = path+"/"+chipName+processingStatus->statusString+".fits"; if (addGain) addGainNormalization = true; else addGainNormalization = false; bool success = write(fileName, dataCurrent, exptime, filter, header); if (success) imageOnDrive = true; else imageOnDrive = false; emit modelUpdateNeeded(chipName); } // If the 'headerRef' member is set, the header from that image will be copied. bool MyImage::write(QString fileName, const QVector<float> &data, const float exptime, const QString filter, const QVector<QString> header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i<nelements; ++i) { array[i] = data[i]; } // Overwrite file if it exists fileName = "!"+fileName; fits_create_file(&fptr, fileName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // header stuff updateHeaderValue("SATURATE", saturationValue, 'e'); // Could be done explicitly every time saturation is changed if (!header.isEmpty()) propagateHeader(fptr, header); if (exptime >= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } fits_update_key_dbl(fptr, "MJD-OBS", mjdobs, 15, nullptr, &status); // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; if (status) { printCfitsioError(__func__, status); successProcessing = false; return false; } else { successProcessing = true; if (*verbosity > 1) emit messageAvailable(fileName + " : Written to drive.", "image"); return true; } // If requested, copy a reference header. This assumes that the image geometries are identical! /* if (!headerRef.isEmpty()) { fitsfile *reference_fptr = nullptr; int status_ref = 0; fits_open_file(&reference_fptr, headerRef.toUtf8().data(), READONLY, &status_ref); fits_copy_header(reference_fptr, fptr, &status_ref); fits_close_file(reference_fptr, &status_ref); printCfitsioError(__func__, status_ref); } */ } void MyImage::writeSegmentation(QString fileName) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Writing segmentation map ("+fileName+") ...", "image"); fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = LONG_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; long *array = new long[nelements]; for (long i=0; i<nelements; ++i) { array[i] = dataSegmentation[i]; } // Overwrite file if it exists fileName = "!"+fileName; fits_create_file(&fptr, fileName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TLONG, fpixel, nelements, array, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } void MyImage::writeObjectMask(QString fileName) { if (!successProcessing) return; if (*verbosity > 1) emit messageAvailable(chipName + " : Writing object mask ("+fileName+") ...", "image"); fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = LONG_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; long *array = new long[nelements]; for (long i=0; i<nelements; ++i) { if (objectMask[i]) array[i] = 0; else array[i] = 1; } // Overwrite file if it exists fileName = "!"+fileName; fits_create_file(&fptr, fileName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TLONG, fpixel, nelements, array, &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } // If the 'headerRef' member is set, the header from that image will be copied. void MyImage::writeConstImage(QString fileName, float constValue, const QVector<QString> header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i<nelements; ++i) { array[i] = constValue; } // Overwrite file if it exists fileName = "!"+fileName; fits_create_file(&fptr, fileName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // Header stuff if (!header.isEmpty()) propagateHeader(fptr, header); if (exptime >= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; printCfitsioError(__func__, status); } /* // same as write(), but also adds MJDOBS bool MyImage::writeDebayer(QString fileName, const float exptime, const QString filter, const QVector<QString> header) { // The new output file fitsfile *fptr; int status = 0; long fpixel = 1; int bitpix = FLOAT_IMG; long naxis = 2; long naxes[2] = {naxis1, naxis2}; long nelements = naxis1*naxis2; float *array = new float[nelements]; for (long i=0; i<nelements; ++i) { array[i] = dataCurrent[i]; } // Overwrite file if it exists fileName = "!"+fileName; fits_create_file(&fptr, fileName.toUtf8().data(), &status); fits_create_img(fptr, bitpix, naxis, naxes, &status); fits_write_img(fptr, TFLOAT, fpixel, nelements, array, &status); // header stuff if (!header.isEmpty()) propagateHeader(fptr, header); if (exptime >= 0.) { fits_write_key_flt(fptr, "EXPTIME", exptime, 6, nullptr, &status); } if (!filter.isEmpty()) { fits_update_key_str(fptr, "FILTER", filter.toUtf8().data(), nullptr, &status); } if (addGainNormalization) { fits_update_key_flt(fptr, "GAINCORR", gainNormalization, 6, nullptr, &status); } fits_update_key_dbl(fptr, "MJD-OBS", mjdobs, 15, nullptr, &status); // BZERO should be 0 after THELI processing. Pixels are scaled by cfitsio already when loading images. fits_update_key_flt(fptr, "BZERO", 0.0, 6, nullptr, &status); // This image has been processed by THELI fits_update_key_lng(fptr, "THELIPRO", 1, "Indicates that this is a THELI FITS file", &status); fits_close_file(fptr, &status); delete [] array; array = nullptr; if (status) { printCfitsioError(__func__, status); successProcessing = false; return false; } else { successProcessing = true; if (*verbosity > 1) emit messageAvailable(fileName + " : Written to drive.", "image"); return true; } } */
12,850
C++
.cc
332
33.849398
122
0.682656
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,513
sourceextractor.cc
schirmermischa_THELI/src/myimage/sourceextractor.cc
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ // This file deals with running Source Extractor as an external tool #include "myimage.h" #include "../functions.h" #include "../tools/polygon.h" #include "../tools/tools.h" #include "../tools/cfitsioerrorcodes.h" #include "../processingInternal/data.h" #include "../threading/sourceextractorworker.h" #include <QFile> #include <QFileInfo> #include <QDebug> #include <QString> #include <QProcess> #include <QTest> void MyImage::buildSourceExtractorCommand() { if (!successProcessing) return; // Create the 'cat/' sub-directory if it does not exist yet. mkAbsDir(path+"/cat/iview/"); QString sourceExtractor = findExecutableName("source-extractor"); sourceExtractorCommand = sourceExtractor + " "; sourceExtractorCommand += path + "/" + chipName + processingStatus->statusString + ".fits"; sourceExtractorCommand += " -CATALOG_NAME " + path+"/cat/" + chipName + ".cat"; sourceExtractorCommand += " -WEIGHT_IMAGE " + weightPath + "/" + chipName + ".weight.fits"; // NOTE: further options are appended in controller::detectionSourceExtractor() // Check if weight exists QFile weight(weightPath+"/"+chipName+".weight.fits"); if (!weight.exists()) { emit messageAvailable(baseName + " : associated weight map not found:<br>" + weightPath + "/" + chipName + ".weight.fits<br>" + "The weight is required for the creation of source catalogs.", "error"); emit critical(); successProcessing = false; } } // start in same thread void MyImage::createSourceExtractorCatalog_old() { if (!successProcessing) return; QProcess process; process.start("/bin/sh -c \""+sourceExtractorCommand+"\""); process.waitForFinished(-1); } // start in new thread void MyImage::createSourceExtractorCatalog() { if (!successProcessing) return; if (*verbosity >= 2) emit messageAvailable("Running the following command in " + path + " : <br>"+sourceExtractorCommand, "image"); // Run the SourceExtractor command workerThread = new QThread(); sourceExtractorWorker = new SourceExtractorWorker(sourceExtractorCommand, path); sourceExtractorWorker->moveToThread(workerThread); connect(workerThread, &QThread::started, sourceExtractorWorker, &SourceExtractorWorker::runSourceExtractor); connect(sourceExtractorWorker, &SourceExtractorWorker::errorFound, this, &MyImage::errorFoundReceived); connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); // Direct connection required, otherwise the task hangs after the first SourceExtractor command // (does not proceed to the next step in the controller's for loop) connect(sourceExtractorWorker, &SourceExtractorWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection); connect(sourceExtractorWorker, &SourceExtractorWorker::finished, sourceExtractorWorker, &QObject::deleteLater); connect(sourceExtractorWorker, &SourceExtractorWorker::messageAvailable, this, &MyImage::messageAvailableReceived); workerThread->start(); workerThread->wait(); } void MyImage::errorFoundReceived() { successProcessing = false; } void MyImage::filterSourceExtractorCatalog(QString minFWHM, QString maxFlag, QString maxEll) { if (!successProcessing) return; fitsfile *fptr; int status = 0; QString filterString = ""; if (!maxFlag.isEmpty() ) filterString = "FLAGS <= "+ maxFlag; if (!minFWHM.isEmpty()) { if (filterString.isEmpty()) filterString = "FWHM_IMAGE >= "+minFWHM; else filterString += " && FWHM_IMAGE >= "+minFWHM; } if (!maxEll.isEmpty()) { if (filterString.isEmpty()) filterString = "ELLIPTICITY <= "+maxEll; else filterString += " && ELLIPTICITY <= "+maxEll; } if (filterString.isEmpty()) return; QString catName = path+"/cat/"+chipName+".cat"; fits_open_file(&fptr, catName.toUtf8().data(), READWRITE, &status); char tblname[100] = "LDAC_OBJECTS"; int extver = 0; fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); fits_select_rows(fptr, fptr, filterString.toUtf8().data(), &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Cannot do that, creating a child for a parent in a different thread; // should push the message directly to monitor instead; // printCfitsioError(__func__, status); } void MyImage::calcMedianSeeingEllipticitySex(QString catName, int extnum) { if (!successProcessing) return; fitsfile *fptr; int status = 0; if (catName.isEmpty()) catName = path+"/cat/"+chipName+".cat"; fits_open_file(&fptr, catName.toUtf8().data(), READONLY, &status); // Move to the LDAC_OBJECTS table if (extnum == 0) { // working on single source extractor catalogs before being merged into scamp catalog char tblname[100] = "LDAC_OBJECTS"; int extver = 0; fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); } else { int hduType = 0; fits_movabs_hdu(fptr, extnum, &hduType, &status); } long nrows = 0; int fwhmColNum = -1; int ellColNum = -1; fits_get_num_rows(fptr, &nrows, &status); char fwhmName[100] = "FWHM_IMAGE"; char ellName[100] = "ELLIPTICITY"; fits_get_colnum(fptr, CASESEN, fwhmName, &fwhmColNum, &status); fits_get_colnum(fptr, CASESEN, ellName, &ellColNum, &status); int firstrow = 1; int firstelem = 1; int anynul = 0; double *fwhm = new double[nrows]; double *ell = new double[nrows]; fits_read_col(fptr, TDOUBLE, fwhmColNum, firstrow, firstelem, nrows, NULL, fwhm, &anynul, &status); fits_read_col(fptr, TDOUBLE, ellColNum, firstrow, firstelem, nrows, NULL, ell, &anynul, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); // Put into a vector so we can do calculations QVector<double> fwhmVec(nrows); QVector<double> ellVec(nrows); for (long i=0; i<nrows; ++i) { fwhmVec[i] = fwhm[i]; ellVec[i] = ell[i]; } fwhm_est = straightMedianInline(fwhmVec) * plateScale; ellipticity_est = straightMedianInline(ellVec); updateHeaderValueInFITS("FWHMEST", QString::number(fwhm_est, 'f', 2)); updateHeaderValueInFITS("ELLIPEST", QString::number(ellipticity_est, 'f', 3)); delete [] fwhm; delete [] ell; fwhm = nullptr; ell = nullptr; } void MyImage::sourceExtractorCatToIview() { if (!successProcessing) return; fitsfile *fptr; int status = 0; QString catName = path+"/cat/"+chipName+".cat"; fits_open_file(&fptr, catName.toUtf8().data(), READONLY, &status); // Move to the LDAC_OBJECTS table char tblname[100] = "LDAC_OBJECTS"; int extver = 0; fits_movnam_hdu(fptr, BINARY_TBL, tblname, extver, &status); long nrows = 0; int xwinColNum = -1; int ywinColNum = -1; int awinColNum = -1; int bwinColNum = -1; int thetawinColNum = -1; fits_get_num_rows(fptr, &nrows, &status); char xwinName[100] = "XWIN_IMAGE"; char ywinName[100] = "YWIN_IMAGE"; char awinName[100] = "AWIN_IMAGE"; char bwinName[100] = "BWIN_IMAGE"; char thetawinName[100] = "THETAWIN_IMAGE"; fits_get_colnum(fptr, CASESEN, xwinName, &xwinColNum, &status); fits_get_colnum(fptr, CASESEN, ywinName, &ywinColNum, &status); fits_get_colnum(fptr, CASESEN, awinName, &awinColNum, &status); fits_get_colnum(fptr, CASESEN, bwinName, &bwinColNum, &status); fits_get_colnum(fptr, CASESEN, thetawinName, &thetawinColNum, &status); int firstrow = 1; int firstelem = 1; int anynul = 0; double *xwin = new double[nrows]; double *ywin = new double[nrows]; float *awin = new float[nrows]; float *bwin = new float[nrows]; float *thetawin = new float[nrows]; fits_read_col(fptr, TDOUBLE, xwinColNum, firstrow, firstelem, nrows, NULL, xwin, &anynul, &status); fits_read_col(fptr, TDOUBLE, ywinColNum, firstrow, firstelem, nrows, NULL, ywin, &anynul, &status); fits_read_col(fptr, TFLOAT, awinColNum, firstrow, firstelem, nrows, NULL, awin, &anynul, &status); fits_read_col(fptr, TFLOAT, bwinColNum, firstrow, firstelem, nrows, NULL, bwin, &anynul, &status); fits_read_col(fptr, TFLOAT, thetawinColNum, firstrow, firstelem, nrows, NULL, thetawin, &anynul, &status); fits_close_file(fptr, &status); printCfitsioError(__func__, status); QString iviewName = path+"/cat/iview/"+chipName+".iview"; QFile file(iviewName); if (file.open(QIODevice::WriteOnly)) { QTextStream outputStream(&file); for (int i=0; i<nrows; ++i) { outputStream.setRealNumberPrecision(9); outputStream << xwin[i] << " " << ywin[i] << " " << awin[i] << " " << bwin[i] << " " << thetawin[i] << "\n"; } file.close(); } else { emit messageAvailable("MyImage::sourceExtractorCatToIview(): Could not write to "+iviewName, "error"); emit critical(); successProcessing = false; } delete [] xwin; delete [] ywin; delete [] awin; delete [] bwin; delete [] thetawin; xwin = nullptr; ywin = nullptr; awin = nullptr; bwin = nullptr; thetawin = nullptr; } void MyImage::appendToScampCatalogSourceExtractor(fitsfile *fptr) { if (!successProcessing) return; // Copy the LDAC_IMHEAD and LDAC_OBJECTS tables to fptr fitsfile *fptrSex; int status = 0; int hduType = 0; QString filename = path+"/cat/"+chipName+".cat"; fits_open_file(&fptrSex, filename.toUtf8().data(), READONLY, &status); fits_movabs_hdu(fptrSex, 2, &hduType, &status); fits_copy_hdu(fptrSex, fptr, 0, &status); fits_movabs_hdu(fptrSex, 3, &hduType, &status); fits_copy_hdu(fptrSex, fptr, 0, &status); fits_close_file(fptrSex, &status); printCfitsioError(__func__, status); } void MyImage::sourceExtractorCatToAnet() { if (!successProcessing) return; // Copy the XWIN_IMAGE, YWIN_IMAGE and MAG_AUTO columns to a new FITS table fitsfile *fptrAnet; int statusAnet = 0; char x[100] = "X"; char y[100] = "Y"; char mag[100] = "MAG"; char *ttype[3] = {x, y, mag}; char tf1[10] = "1D"; char tf2[10] = "1D"; char tf3[10] = "1E"; char *tform[3] = {tf1, tf2, tf3}; QString anetName = path+"/cat/"+chipName+".anet"; fits_create_file(&fptrAnet, anetName.toUtf8().data(), &statusAnet); fitsfile *fptrSex; int statusSex = 0; int hduType = 0; int xColNum = -1; int yColNum = -1; int magColNum = -1; long nrows = -1; char xName[100] = "XWIN_IMAGE"; char yName[100] = "YWIN_IMAGE"; char magName[100] = "MAG_AUTO"; QString filename = path+"/cat/"+chipName+".cat"; fits_open_file(&fptrSex, filename.toUtf8().data(), READONLY, &statusSex); fits_movabs_hdu(fptrSex, 3, &hduType, &statusSex); fits_get_colnum(fptrSex, CASESEN, xName, &xColNum, &statusSex); fits_get_colnum(fptrSex, CASESEN, yName, &yColNum, &statusSex); fits_get_colnum(fptrSex, CASESEN, magName, &magColNum, &statusSex); fits_get_num_rows(fptrSex, &nrows, &statusSex); fits_create_tbl(fptrAnet, BINARY_TBL, nrows, 3, ttype, tform, nullptr, "OBJECTS", &statusAnet); fits_copy_col(fptrSex, fptrAnet, xColNum, 1, FALSE, &statusSex); fits_copy_col(fptrSex, fptrAnet, yColNum, 2, FALSE, &statusSex); fits_copy_col(fptrSex, fptrAnet, magColNum, 3, FALSE, &statusSex); fits_close_file(fptrSex, &statusSex); printCfitsioError(__func__, statusSex); fits_close_file(fptrAnet, &statusAnet); printCfitsioError(__func__, statusAnet); }
12,453
C++
.cc
290
37.724138
135
0.677403
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,514
instrumentdefinition.h
schirmermischa_THELI/src/instrumentdefinition.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef INSTRUMENT_H #define INSTRUMENT_H #include <QDialog> #include <QLineEdit> #include <QButtonGroup> #include <QTextStream> #include <QStatusBar> #include <QMainWindow> namespace Ui { class Instrument; } class Instrument : public QMainWindow { Q_OBJECT public: explicit Instrument(QWidget *parent = nullptr); ~Instrument(); private slots: void paintNumLineEdits(QString geometry); void on_numchipSpinBox_valueChanged(int arg1); void validate(QString arg1); void on_saveConfigPushButton_clicked(); void on_instrumentTypeComboBox_currentIndexChanged(int index); void on_loadConfigPushButton_clicked(); void toggle_bayer_ToolButtons(); void timerConfigDone(); void on_clearPushButton_clicked(); void on_bayerCheckBox_clicked(bool checked); void on_actionClose_triggered(); void toggleFormatPushButton(); void on_readRAWgeometryPushButton_clicked(); private: Ui::Instrument *ui; QString thelidir; QString userdir; QList<QLineEdit*> geometryList; QList<QLineEdit*> geometryNumList; int numChips = 1; QString geometryToConfig(QString geometry); QString configToGeometry(QString config); void altStream(QTextStream &stream, QString keyword, QString altValue); QButtonGroup *bayerButtonGroup = new QButtonGroup(this); bool compareChipNumbers(); void getKey(QTextStream &stream, QString bashkey, QString fitsKey, QString mode = ""); void truncateFITSkey(QString &key); void applyStyleSheets(); }; #endif // INSTRUMENT_H
2,224
C++
.h
62
32.693548
90
0.77783
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,515
datadir.h
schirmermischa_THELI/src/datadir.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef DATADIR_H #define DATADIR_H #include <QString> #include <QDir> class DataDir { public: DataDir(QString data, QString main = ""); DataDir(); QString name; // the full path name QString subdirname; // the data subdir name alone QDir dir; bool exists(); long numFITS; long numCHIP; long numChips = 1; bool hasMaster(); bool isEmpty(); bool hasType(QString type); long numEXT(QString type); void setPaths(QString data, QString main = ""); }; #endif // DATADIR_H
1,206
C++
.h
37
29.837838
75
0.751724
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,516
status.h
schirmermischa_THELI/src/status.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef STATUS_H #define STATUS_H #include <QString> #include <QCheckBox> #include <QToolButton> #include <QList> #include <QLineEdit> #include <QObject> // This class keeps track of the data processing, mainly so that the GUI displays background color of tasks correctly. // The 'status' is not used to reflect the actual processing status of data. This is handled internally to the Data and MyImage classes. class Status : public QObject { Q_OBJECT public: Status(); void history2checkbox(); QString getStatusFromHistory(bool keepblanks = false); QString checkboxStatus(QCheckBox *cb); // These lists contain the tasks, in the order in which they occur in the GUI QList<bool> listHistory; // Whether a task has been executed or not; this is the central piece that rules it all QList<QCheckBox*> listCheckBox; // the list of all task checkboxes QList<QToolButton*> listToolButtons; // the list of all tool buttons QList<QString> listName; // The unique ID string common to checkbox, undo Button and Action QList<QLineEdit*> listDataDirs; // The list of all data dir LineEdits QList<QString> listCurrentValue; // The current string value (A,B,C,M,D or empty) associated with the checkbox QList<QString> listFixedValue; // (constant). A character for each task box, used to comprise the processing string QList<bool> listBreakpoints; // (constant). The character associated to each processing task (mostly blanks) QMap<QString, int> indexMap; // Identifies the index of a task (the order in which the task appears) // The number of task checkboxes in the GUI; sorry, hardcoded. const int numtasks = 19; void statusstringToHistory(QString &statusstring); void clearAllCheckBoxes(); private: // int lastExecutedTaskId(); signals: void statusChanged(); public slots: void updateStatus(); void updateStatusReceived(QString taskBasename, bool success); }; #endif // STATUS_H
2,736
C++
.h
55
46.854545
136
0.745216
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,517
preferences.h
schirmermischa_THELI/src/preferences.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef PREFERENCES_H #define PREFERENCES_H #include <QDialog> #include <QFont> namespace Ui { class Preferences; } class Preferences : public QDialog { Q_OBJECT signals: int diskspacewarnChanged(int); int fontSizeChanged(int); int fontChanged(QFont); int instPreferenceChanged(int); int numcpuChanged(int); int serverChanged(QString); int memoryUsageChanged(bool); int intermediateDataChanged(QString); void verbosityLevelChanged(int index); void preferencesUpdated(); int switchProcessMonitorChanged(bool); void messageAvailable(QString message, QString type); void warning(); public: explicit Preferences(bool running, QWidget *parent = nullptr); ~Preferences(); private slots: void on_prefFontdialogPushButton_clicked(); void on_prefFontsizeSpinBox_valueChanged(int arg1); void on_prefDefaultFontPushButton_clicked(); void on_prefDiskspacewarnSpinBox_valueChanged(int arg1); void on_prefCPUSpinBox_valueChanged(int arg1); void on_prefMemoryCheckBox_clicked(); void on_prefIntermediateDataComboBox_currentTextChanged(const QString &arg1); void on_prefVerbosityComboBox_currentIndexChanged(int index); void on_prefSwitchProcessMonitorCheckBox_clicked(); void on_prefCancelButton_clicked(); void on_prefCloseButton_clicked(); public slots: void receiveDefaultFont(QFont); void updateParallelization(bool running); private: Ui::Preferences *ui; QFont defaultFont; float totalMemory; int maxMemoryUsed; void applyStyleSheets(); void configureMemory(); int readSettings(); int writeSettings(); }; #endif // PREFERENCES_H
2,354
C++
.h
67
31.716418
81
0.781346
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,518
instrumentdata.h
schirmermischa_THELI/src/instrumentdata.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef INSTRUMENTDATA_H #define INSTRUMENTDATA_H #include <QVector> #include <QFile> #include <QMap> typedef struct { int numChips; QString name = ""; QString shortName = ""; QString nameFullPath = ""; float obslat = 0.; float obslon = 0.; QString bayer; QString type; QString flip = ""; float pixscale = 1.0; // in arcsec // float gain = 1.0; float radius = 0.1; // exposure coverage radius in degrees float storage = 0; // MB used for a single image float storageExposure = 0.; // MB used for the entire (multi-chip) exposure int numUsedChips; long nGlobal = 1; // Overall focal plane size in x-direction long mGlobal = 1; // Overall focal plane size in x-direction QVector<int> badChips; QVector<int> goodChips; int validChip = -1; QMap<int, int> chipMap; // in case of bad detectors, we need to map e.g. chip #4 to index #3 (e.g. if data from chip #2 is missing) QVector<int> overscan_xmin; QVector<int> overscan_xmax; QVector<int> overscan_ymin; QVector<int> overscan_ymax; QVector<int> cutx; QVector<int> cuty; QVector<int> sizex; QVector<int> sizey; QVector<int> crpix1; QVector<int> crpix2; } instrumentDataType; #endif // INSTRUMENTDATA_H
1,974
C++
.h
53
33.773585
140
0.716754
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,519
mainwindow.h
schirmermischa_THELI/src/mainwindow.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "readmes/multidirreadme.h" #include "readmes/license.h" #include "readmes/acknowledging.h" #include "readmes/tutorials.h" #include "abszp/abszeropoint.h" #include "instrumentdefinition.h" #include "instrumentdata.h" #include "colorpicture/colorpicture.h" #include "imagestatistics/imagestatistics.h" #include "threading/mainguiworker.h" #include "functions.h" #include "status.h" #include "processingExternal/errordialog.h" #include "processingInternal/controller.h" #include "preferences.h" #include "datadir.h" #include "ui_mainwindow.h" #include "dockwidgets/confdockwidget.h" #include "dockwidgets/monitor.h" #include "dockwidgets/memoryviewer.h" #include "tools/cpu.h" #include "tools/ram.h" #include <QMainWindow> #include <QLineEdit> #include <QProgressBar> #include <QProcessEnvironment> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QFile> #include <QDebug> #include <QStringListModel> namespace Ui { class MainWindow; } // Forward declaration class MyStringListModel; class MyStringValidator; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QString pid, QWidget *parent = nullptr); ~MainWindow(); QString GUIVERSION = "3.1.5"; QString instrument_dir; QString instrument_userDir; QString mainPID; IView *solutionViewer; Controller *controller = nullptr; ConfDockWidget *cdw; Monitor *monitor; MemoryViewer *memoryViewer = nullptr; Ui::MainWindow *ui; CPU *myCPU; RAM *myRAM; QTimer *ramTimer; QTimer *cpuTimer; QTimer *driveTimer; Status status; QMap<QString,QString> taskCommentMap; QList<QThread*> threadList; instrumentDataType instData; QProgressBar *cpuProgressBar; QProgressBar *memoryProgressBar; QProgressBar *driveProgressBar; bool datadiskspace_warned; bool homediskspace_warned; int diskwarnPreference; bool doingInitialLaunch = false; bool readingSettings = false; bool checkPathsLineEdit(QLineEdit *lineEdit); void refreshMemoryViewerReceiver(); signals: QFont sendingDefaultFont(QFont); // implemented in designer void runningStatusChanged(bool running); void ControllerScanDataTree(QLineEdit *lineEdit); void newProjectLoaded(); void rereadScienceDataDir(); void messageAvailable(QString message, QString type); void warning(); void resetErrorStatus(QString dirName); public slots: void processMessage(QString text, QString type); void taskFinished(); void launchViewer(QString dirname, QString filter, QString mode); // void launchCoaddFluxcal(QString coaddImage); void appendOK(); // void resumeWorkerThread(QString acceptanceState); void on_startPushButton_clicked(); void showMessageBoxReceived(QString trigger, QString part1, QString part2); void progressUpdateReceived(float progress); void resetProgressBarReceived(); void updateSwitchProcessMonitorPreference(bool switchToMonitor); void statusChangedReceived(QString newStatus); void updateExcludedDetectors(QString badDetectors); protected: // Don't know yet what the 'override' means void closeEvent(QCloseEvent *event) override; QString thelidir; QString userdir; QFile instrument_file; QString instrument_name; QString instrument_type; QString instrument_bayer; int instrumentPreference; int numCPU = 1; int nframes = 1; int instrument_nchips = 1; long systemRAM; QString kernelType; QString productName; private slots: void resetParameters(); void checkPaths(); void connect_validators(); void establish_connections(); void initGUI(); void link_ConfToolButtons_confStackedWidget(); void link_taskCheckBoxes_confStackedWidget(); void loadPreferences(); void loadIView(); void load_dialog_newinst(); void load_dialog_imageStatistics(); void load_dialog_abszeropoint(); void load_dialog_colorpicture(); void cdw_dockLocationChanged(const Qt::DockWidgetArea &area); void cdw_topLevelChanged(bool topLevel); void on_actionAdd_new_instrument_configuration_triggered(); void on_actionEdit_preferences_triggered(); void on_actionKill_triggered(); void on_yieldToolButton_clicked(); void on_stopToolButton_clicked(); void on_processingTabWidget_currentChanged(int index); void on_setupInstrumentComboBox_currentTextChanged(const QString &arg1); void on_setupProjectLoadToolButton_clicked(); void on_setupReadmePushButton_clicked(); void scienceDataDirUpdatedReceived(QString allDirs); void startPushButton_clicked_dummy(QString string); void shutDown(); // void undoToolButton_clicked(); void updateFontSize(int index); void updateFont(QFont font); void updateDiskspaceWarning(int newLimit); void updateNumcpu(int cpu); void updateController(); void updateControllerFunctors(QString text); void validate(); int writePreferenceSettings(); int writeGUISettings(); // The following can also be under 'private', but then the declaration must be preceded like this: // Q_INVOKABLE QString taskHDUreformat(); QStringList taskHDUreformat(bool &stop, const QString mode); QStringList taskProcessbias(bool &stop, const QString mode); QStringList taskProcessdark(bool &stop, const QString mode); QStringList taskProcessflatoff(bool &stop, const QString mode); QStringList taskProcessflat(bool &stop, const QString mode); QStringList taskProcessscience(bool &stop, const QString mode); QStringList taskChopnod(bool &stop, const QString mode); QStringList taskBackground(bool &stop, const QString mode); QStringList taskCollapse(bool &stop, const QString mode); QStringList taskBinnedpreview(bool &stop, const QString mode); QStringList taskGlobalweight(bool &stop, const QString mode); QStringList taskIndividualweight(bool &stop, const QString mode); QStringList taskSeparate(bool &stop, const QString mode); QStringList taskCreatesourcecat(bool &stop, const QString mode); QStringList taskAstromphotom(bool &stop, const QString mode); QStringList taskAbsphotindirect(bool &stop, const QString mode); QStringList taskGetCatalogFromWEB(bool &stop, const QString mode); QStringList taskGetCatalogFromIMAGE(bool &stop, const QString mode); QStringList taskRestoreHeader(bool &stop, const QString mode); QStringList taskSkysub(bool &stop, const QString mode); QStringList taskCoaddition(bool &stop, const QString mode); QStringList taskResolveTargetSidereal(bool &stop, const QString mode); void check_taskHDUreformat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessbias(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessdark(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessflatoff(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessflat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskProcessscience(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskChopnod(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskBackground(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCollapse(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskBinnedpreview(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGlobalweight(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskIndividualweight(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskSeparate(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCreatesourcecat(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskAstromphotom(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskAbsphotindirect(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGetCatalogFromWEB(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskGetCatalogFromIMAGE(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskRestoreHeader(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskSkysub(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskCoaddition(DataDir *datadir, bool &stop, bool &skip, const QString mode); void check_taskResolveTargetSidereal(DataDir *datadir, bool &stop, bool &skip, const QString mode); void restoreOriginalData(); void emitEditingFinished(const QString &arg1); void on_actionLicense_triggered(); void on_actionAcknowledging_triggered(); void on_actionDocumentation_triggered(); void loadCoaddAbsZP(QString coaddImage, float maxVal); void updateMemoryProgressBarReceived(long memoryUsed); void on_setupProjectLineEdit_textChanged(const QString &arg1); void displayCPUload(); void displayRAMload(); void displayDriveSpace(); private: // Variables we need to access frequently bool preventLoop_WriteSettings = false; QWidget *emptyWidget; MyStringListModel *instrument_model; Preferences *preferences; Instrument *instrument = new Instrument(this); MultidirReadme *multidirReadme; License *license; Acknowledging *acknowledging; Tutorials *tutorials; ErrorDialog *errordialog = new ErrorDialog(this); QSettings *settingsp; QMap<QCheckBox*,QString> checkboxMap; QStringList totalCommandList; QStringList cleanCommandList; QThread *workerThread; MainGUIWorker *mainGUIWorker; bool processSkyImages = false; // Flags that tell whether an error message has been shown or not. bool GAP_DYNAMIC_FOUND_shown = false; bool WINDOWSIZE_TOO_LARGE_shown = false; bool INSUFFICIENT_BACKGROUND_NUMBER_shown = false; bool SKY_FILE_NOT_FOUND_shown = false; bool NO_OVERLAP_WITH_SKYAREA_shown = false; bool MASTER_BIAS_NOT_FOUND_shown = false; bool MASTER_FLAT_NOT_FOUND_shown = false; bool MASTER_FLATOFF_NOT_FOUND_shown = false; bool MASTER_BIAS_NOT_FOUND_GLOBW_shown = false; bool MASTER_FLAT_NOT_FOUND_GLOBW_shown = false; bool NO_MJDOBS_FOR_PM_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PM_READ_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown = false; bool CANNOT_UPDATE_HEADER_WITH_PA_shown = false; bool CANNOT_WRITE_RESAMPLE_LIST_shown = false; bool CANNOT_OPEN_FILE_shown = false; bool CANNOT_READ_HEADER_KEYS_shown = false; bool DUPLICATE_MJDOBS_shown = false; bool IMAGES_NOT_FOUND_shown = false; bool IncompatibleSizeRAW_shown = false; bool INCONSISTENT_DATA_STATUS_shown = false; bool switchProcessMonitorPreference = true; bool areAllPathsValid(); bool checkMultipledirConsistency(QString mode); QStringList createCommandlistBlock(QString taskBasename, QStringList goodDirList, bool &stop, const QString mode); QStringList displayCoaddFilterChoice(QString dirname, QString &filterChoice, QString mode); QString estimateStatusFromFilename(DataDir *datadir); void fill_setupInstrumentComboBox(); QString getStatusForSettings(); void handleDataDirs(QStringList &goodDirList, QLineEdit *scienceLineEdit, QLineEdit *calib1LineEdit, QLineEdit *calib2LineEdit, QString statusString, bool &success); void hasDirCurrentData(DataDir *datadir, bool &stop); void initProcessingStatus(); void initInstrumentData(QString instrumentNameFullPath); bool isRefcatRecent(QString dirname); void linkPrefInst_with_MainInst(int index); QString manualCoordsUpdate(QString science, QString coordsMode); QStringList matchCalibToScience(const QStringList scienceList, const QStringList calibList); // bool maybeSave(); void on_setupInstrumentComboBox_clicked(); void populateTaskCommentMap(); int readPreferenceSettings(QString &projectname); int readGUISettings(QString projectname); void repaintDataDirs(); QString sameRefCoords(QString coordsMode); void setStatusFromSettings(QString statusString); void testOverscan(QVector<int> &overscan); void toggleButtonsWhileRunning(); void updatePreferences(); void updateInstrumentComboBoxBackgroundColor(); void updateProcessList(QStringList &commandList, QString taskBasename, QString arg1); void updateProcessList(QStringList &commandList, QString taskBasename, QString arg1, QString arg2); void addDockWidgets(); void resetProcessingErrorFlags(); bool sufficientSpaceAvailable(long spaceNeeded); QString getInstDir(QString instname); bool OSPBC_addCommandBlock(const QString taskBasename, const QString mode, bool &stop); bool OSPBC_isTaskCurrentlyVisible(QCheckBox *cb); QString OSPBC_determineExecutionMode(QObject *sender); bool OSPBC_multipleDirConsistencyCheck(); void displayMessage(QString messagestring, QString type); void checkMemoryConstraints(); void addProgressBars(); void resetInstrumentData(); int estimateBinningFactor(); void printCfitsioError(QString funcName, int status); bool checkCatalogUsability(QString mode); void startProgressBars(); void setHomeDir(); }; // Subclassing QStringListModel to allow certain entries being shown with different colors class MyStringListModel : public QStringListModel { public: MyStringListModel() { ; } QString instrument_dir; QString instrument_userDir; QVariant data(const QModelIndex & index, int role) const { if(!index.isValid()) return QVariant(); int row = index.row(); switch(role) { case Qt::DisplayRole: return this->stringList().at(row); case Qt::ForegroundRole: QFile file; QString name1 = instrument_dir+"/"+stringList().at(row)+".ini"; QString name2 = instrument_userDir+"/"+stringList().at(row)+".ini"; // Search until we found the instrument.ini file file.setFileName(name1); if (!file.exists()) file.setFileName(name2); QString type = get_fileparameter(&file, "TYPE"); if (type == "OPT") return QBrush(QColor("#0000cc")); else if (type == "NIR") return QBrush(QColor("#009900")); else if (type == "NIRMIR") return QBrush(QColor("#cc5500")); else if (type == "MIR") return QBrush(QColor("#ff0000")); else return QBrush(QColor("#0000cc")); } return QVariant(); } }; #endif // MAINWINDOW_H
15,608
C++
.h
351
39.712251
118
0.754009
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,520
functions.h
schirmermischa_THELI/src/functions.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef FUNCTIONS_H #define FUNCTIONS_H #include <valarray> #include "fitsio2.h" #include <wcs.h> #include "instrumentdata.h" #include <QString> #include <QFile> #include <QDir> #include <QComboBox> #include <QLineEdit> #include <QVector> #include <QDebug> #include <QProcess> #include <QProgressBar> #include <QPlainTextEdit> #include <QStringList> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> struct dataGSL { size_t nx, ny; double* z; // pointer to values of 2D function double* sigma; // dito for sigmas }; QString boolToString(bool test); double getPosAnglefromCD(double cd11, double cd12, double cd21, double cd22, bool lock = true); void rotateCDmatrix(double &cd11, double &cd12, double &cd21, double &cd22, double PAnew); void get_rotimsize(long naxis1, long naxis2, double PAold, double PAnew, long &Nnew, long &Mnew); QStringList datadir2StringList(QLineEdit *lineEdit); QString get_fileparameter(QFile *, QString, QString warn = ""); // QString get_fileHeaderParameter(QFile *file, QString parametername); // QString get_fileparameter_vector(QFile *, QString, QString warn = ""); // QVector<int> get_fileparameter_FullVector(QFile *file, QString parametername); void appendToFile(QString path, QString string); void replaceLineInFile(const QString& filePath, const QString& searchString, const QString& replacementLine); double extractFitsKeywordValue(const QString& filePath, const QString& keyword); QString findExecutableName(QString program); QString sanityCheckWCS(const wcsprm *wcs); void killProcessChildren(qint64 parentProcessId); long get_memory(); void showLogfile(QString logname, QString line = ""); void fill_combobox(QComboBox *, QString); void paintPathLineEdit(QLineEdit *, QString, QString check = "dir"); bool listContains(QStringList stringList, QString string); // void exec_system_command(QString); QVector<float> getSmallSample(const QVector<float> &data, const QVector<bool> &mask = QVector<bool>()); void initEnvironment(QString &thelidir, QString &userdir); // void listSwapLastPairs(QStringList &stringlist, int n); long numFilesDir(QString path, QString filter); bool hasMatchingPartnerFiles(QString dirname1, QString suffix1, QString dirname2, QString suffix2, QString infomessage); QString removeLastWords(QString string, int n=1, const QChar sep=' '); QString getNthWord(QString string, int n, const QChar sep=' '); QString read_system_command(QString); // QString read_MultipleLines_system_command(QString shell_command); // QString translateServer(QString downloadServer); QString truncateImageList(QStringList list, int dim); void message(QPlainTextEdit *pte, QString text, QString type=""); void selectFirstActiveItem(QComboBox *cb); void get_array_subsample(const QVector<float> &data, QVector<double> &datasub, int stepSize); double medianerrMask(const QVector<double> &vector_in, const QVector<bool> &mask = QVector<bool>()); double madMask(const QVector<double> &vector_in, const QVector<bool> &mask = QVector<bool>(), QString ignoreZeroes = ""); float meanIterative(const QVector<float> data, float kappa, int iterMax); QString hmsToDecimal(QString hms); QString dmsToDecimal(QString dms); QString decimalSecondsToHms(float value); QString decimalToHms(float value); QString decimalToDms(float value); double dateobsToDecimal(QString dateobs); QString getLastWord(QString string, const QChar sep); QString get2ndLastWord(QString string, const QChar sep); void removeLastCharIf(QString &string, const QChar character); bool moveFiles(QString filter, QString sourceDirName, QString targetDirName); bool moveFile(QString filename, QString sourceDirPath, QString targetDirPath, bool skipNonExistingFile = false); bool deleteFile(QString fileName, QString path); QVector<float> modeMask(const QVector<float> &data, QString mode, const QVector<bool> &mask = QVector<bool>(), bool smooth = true); int modeMask_sampleDensity(long numDataPoints, int numBins, float SNdesired); QVector<float> modeMask_clipData(const QVector<float> &data, const QVector<bool> &mask, int sampleDensity = 1, float minVal = 0., float maxVal = 0.); QVector<long> modeMask_buildHistogram(QVector<float> &data, float &rescale, const int numBins, const float minVal, const float maxVal, const float madVal, const bool smooth = true); void modeMask_classic(const QVector<long> histogram, float &skyValue); void modeMask_gaussian(QVector<long> histogram, float &skyValue); void modeMask_stable(const QVector<long> histogram, float &skyValue); float meanMask(const QVector<float> &data, const QVector<bool> &mask = QVector<bool>(), long maxLength = 0); float medianMask(const QVector<float> &data, const QVector<bool> &mask = QVector<bool>(), long maxLength = 0); float straightMedian_MinMax(QVector<float> &data, const int nlow, const int nhigh); float straightMedian_MinMax(QList<float> &data, const int nlow, const int nhigh); bool readData3D(QString path, QVector<double> &x, QVector<double> &y, QVector<double> &z); long remainingDataDriveSpace(QString maindir); int gauss_f(const gsl_vector *x, void *params, gsl_vector *f); int gauss_df(const gsl_vector *x, void *params, gsl_matrix *J); int gauss_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J); void mkAbsDir(QString absDirName); void flipData(QVector<float> &data, const QString dir, const int naxis1, const int naxis2); void flipSections(QVector<long> &sections, const QString dir, const int naxis1, const int naxis2); int getValidChip(const instrumentDataType *instData); // template functions end in "_T" // This is to distinguish them from the same functions // which are needed explicitly because they are select through functors // Test if a RA/DEC coordinate is contained within an image //*************************************************************** // Template for matrix multiplication. // Stores the result in the elements of the second matrix //*************************************************************** template<class T1, class T2> void matrixMult_T(const T1 a11, const T1 a12, const T1 a21, const T1 a22, T2 &b11, T2 &b12, T2 &b21, T2 &b22) { // qDebug() << "rot" << a11 << a12 << a21 << a22; T2 c11 = a11 * b11 + a12 * b21; T2 c12 = a11 * b12 + a12 * b22; T2 c21 = a21 * b11 + a22 * b21; T2 c22 = a21 * b12 + a22 * b22; // qDebug() << a21 << b12 << a22 << b22 << c22; b11 = c11; b12 = c12; b21 = c21; b22 = c22; } template<class T> QVector<T> removeVectorItems_T(QVector<T> data, QVector<int> badIndexes) { int i=0; QVector<bool> removeFlag = QVector<bool>(data.length(), false); for (i=0; i<badIndexes.length(); ++i) { removeFlag.operator[](i) = true; } QVector<T> filtered = QVector<T>(); for (i=0; i<removeFlag.length(); ++i) { if (!removeFlag.at(i)) filtered.push_back(data[i]); } return filtered; } template<class T> T minVec_T(const QVector<T> &qv) { if (qv.length() == 0) { return 0; } T extreme = qv.at(0); for ( const auto &i : qv) { if (i < extreme) extreme = i; } return (extreme); } template<class T> T maxVec_T(const QVector<T> &qv) { if (qv.length() == 0) { return 0; } T extreme = qv.at(0); for ( const auto &i : qv) { if (i > extreme) extreme = i; } return (extreme); } template<class T> T meanQuantile_T(const QVector<float> &data, const long start, const long end) { T mean = 0.; long numpixels = 0; long naned = 0; for (long i=start; i<end; ++i) { if (!std::isnan(data[i])) { mean += data[i]; ++numpixels; } else ++naned; } if (numpixels != 0.) mean /= numpixels; else mean = 0.; if (naned > (end-start) / 2) mean = nan("0x12345"); // return NaN return (mean); } template<class T> T straightMedian_T(const QVector<T> &vector_in, long maxLength = 0, bool center = true) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // Usually, we take all elements in a vector. // However, in some cases it may be that elements get masked and the vector is not entirely filled. // In this case, an optional maxLength argument is provided if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength; QVector<T> vector(maxDim); for (long i=0; i<maxDim; ++i) vector[i] = vector_in[i]; std::sort(vector.begin(), vector.end()); T med; if (center) { // Calculate average of central two elements if number is even med = (vector.size() % 2) ? vector[vector.size() / 2.] : ((T)vector[vector.size() / 2. - 1] + vector[vector.size() / 2.]) * .5; } else { // Do not calculate average (needed when calculate median CRVAL1 to avoid issues when crossing the 360/0 degree boundary) med = vector[vector.size() / 2.]; } return med; } // A faster implementation that can be used if the input data is already "clean", and does not need to be preserved template<class T> T straightMedianInline(QVector<T> &data) { long dim = data.length(); if (dim == 0) return 0.; std::sort(data.begin(), data.end()); T med; med = (dim % 2) ? data[dim/2] : ((T)data[dim/2-1] + data[dim/2]) * .5; return med; } // Masked median template<class T> T medianMask_T(const QVector<T> vector_in, QVector<bool> mask = QVector<bool>(), QString ignoreZeroes = "") { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // fast-track if (mask.isEmpty() && ignoreZeroes == "") { return straightMedian_T(vector_in); } // slower median with masks, and potentially pixel with value zero that are to be ignored if (mask.isEmpty()) { mask.fill(false, maxDim); } QVector<T> vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask.at(i) && ignoreZeroes == "") vector.append(it); if (!mask.at(i) && ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } if (vector.size() == 0) return 0.; else { return straightMedian_T(vector); } } // Masked mean template<class T> T meanMask_T(const QVector<T> &vector_in, QVector<bool> mask = QVector<bool>()) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; // fast-track if (mask.isEmpty()) { return std::accumulate(vector_in.begin(), vector_in.end(), .0) / vector_in.size(); } else { QVector<T> vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask.at(i)) vector.append(it); ++i; } if (vector.size() == 0) return 0.; else return std::accumulate(vector.begin(), vector.end(), .0) / vector.size(); } } template<class T> T rmsMask_T(const QVector<T> &vector_in, QVector<bool> mask = QVector<bool>()) { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; if (mask.isEmpty()) { mask.fill(false, maxDim); } QVector<T> vector; vector.reserve(maxDim); int i = 0; for (auto &it: vector_in) { if (!mask[i]) vector.append(it); ++i; } T rmsval = 0.; T meanval = meanMask_T(vector_in, mask); if (vector.size() <= 1) return 0.; else { for (auto &it: vector) { rmsval += (meanval - it) * (meanval - it); } return std::sqrt(rmsval / (vector.size()-1) ); } } // Masked mad template<class T> T madMask_T(const QVector<T> vector_in, const QVector<bool> mask = QVector<bool>(), QString ignoreZeroes = "") { long maxDim = vector_in.length(); if (maxDim == 0) return 0.; QVector<T> vector; vector.reserve(maxDim); if (!mask.isEmpty()) { long i = 0; for (auto &it: vector_in) { if (!mask.at(i) && ignoreZeroes == "") vector.append(it); if (!mask.at(i) && ignoreZeroes != "" && it != 0.) vector.append(it); ++i; } } else { for (auto &it: vector_in) { if (ignoreZeroes == "") vector.append(it); if (ignoreZeroes != "" && it != 0.) vector.append(it); } } QVector<T> diff; diff.reserve(maxDim); if (vector.size() == 0) return 0.; else { T med = straightMedian_T(vector); for (long i=0; i<vector.size(); ++i) { diff.append(fabs(vector.at(i)-med)); } return straightMedian_T(diff); } } template <typename T> int sgn(T x) { if (x >= 0) return 1; else return -1; } // Check a QVector for duplicates template<class T> bool hasDuplicates_T(QVector<T> data) { std::sort(data.begin(), data.end()); T old = data[0]; long j = 0; long nDuplicates = 0; for (auto &it : data) { if (j>0 && it == old) ++nDuplicates; old = it; ++j; } if (nDuplicates > 0) return true; else return false; } // Count the number of duplicates in a Qvector template<class T> int numberOfDuplicates_T(QVector<T> data) { std::sort(data.begin(), data.end()); T old = data[0]; long j = 0; long nDuplicates = 0; for (auto &it : data) { if (j>0 && it == old) ++nDuplicates; old = it; ++j; } return nDuplicates; } // The index of the entry with the highest value template<class T> T maxIndex(const QVector<T> &data) { long index = 0; T maxval = data[0]; long i=0; for (auto &pixel : data) { if (pixel > maxval) { maxval = pixel; index = i; } ++i; } return index; } // Convolve a 1D array with a Gaussian of width sigma (units of array elements) // The footprint of the Gaussian is +/- 1 sigma template<class T1, class T2> void smooth_array_T(QVector<T1> &data, T2 sigma) { float ss2 = 2.*sigma*sigma; long dim = data.length(); float footprint = 1.0; QVector<float> tmp(dim); for (long i=0; i<dim; ++i) { float wsum = 0.; long jmin = i-footprint*sigma < 0 ? 0 : i-footprint*sigma; long jmax = i+footprint*sigma >= dim ? dim : i+footprint*sigma; for (long j=jmin; j<jmax; ++j) { float r = float(i-j); float weight = exp(-r*r/ss2); tmp[i] += (float(data[j]) * weight); wsum += weight; } tmp[i] /= wsum; } long i=0; for (auto &it : data) { it = T1(tmp[i]); ++i; } //data = tmp; } // The following is implemented, but not yet used anywhere /* Out : one element Job : find the kth smallest element in the array Notice : use the median() macro defined below to get the median. Reference: Author: Wirth, Niklaus Title: Algorithms + data structures = programs Publisher: Englewood Cliffs: Prentice-Hall, 1976 Physical description: 366 p. Series: Prentice-Hall Series in Automatic Computation */ template<class T> T kth_smallest(QVector<T> &data, int k) // WARNING: modifies input vector { T x; long l = 0; long n = data.length(); long m = n - 1; while (l < m) { x = data[k]; long i = l; long j = m; do { while (data.at(i) < x) ++i; while (x<data.at(j)) --j; if (i <= j) { T tmp = data[i]; data[j] = data[i]; data[i] = tmp; ++i; --j; } } while (i <= j); if (j<k) l = i; if (k<i) m = j; } return data[k]; } // WARNING: this method is biased because kth_smallest() does not return the // average of two values in ase the data vector has even length. hence unused for the time being template<class T> T fastMedian(QVector<T> &data) { long n = data.length(); kth_smallest(data,(((n)&1)?((n)/2):(((n)/2)-1))); } #endif // FUNCTIONS_H
16,635
C++
.h
459
31.618736
149
0.648902
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,521
myaxis.h
schirmermischa_THELI/src/iview/myaxis.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYAXIS_H #define MYAXIS_H #include <math.h> #include <QObject> #include <QLineF> #include <QStringList> #include <QPen> #include <QColor> #include <QVector> class MyAxis : public QObject { Q_OBJECT double wavelengthToPixel(double lambda); void initSpectrumTickmarks(); public: explicit MyAxis(QObject *parent = nullptr); QLineF axisLine; QList<QLineF> tickMarks; QStringList tickLabels; QString tickDirection = "down"; QPen pen; float finesse = 2000.; long naxis1 = 0; long naxis2 = 0; double crval = 0.; double cd = 1.0; float z = 0.; // redshift float z_0 = 0.; // the previous value held by z; float x_0 = 0.; // The x coordinate of the mouse cursor when the left button is clicked float lambdaMin = 0.; // wavelength range maximally covered by the axis float lambdaMax = 0.; int tickLength = 10; int ybase = 0.; // The y coordinate at which the axis is drawn. int axisOffset = 0; // draw the observed axis line this much below the center of the image int tickstep = 100; // Wavelength interval at which tickmarks are drawn void init(double crval_in, double cd_in, long naxis1_in, long naxis2_in, int offset, QString direction, QColor color, QString type = ""); void addSpecies(const QList<QPair<QString, float> > &list); void clear(); void getTickmarks(); signals: void redshiftRecomputed(); void redshiftUpdated(float z_0); public slots: double pixelToWavelength(double x); void getWavelengthRange(); void redshiftChangedReceiver(QString zstring); void initRedshift(QPointF pointStart); void redshiftSpectrum(QPointF pointStart, QPointF currentPoint); void closeRedshift(); }; #endif // MYAXIS_H
2,513
C++
.h
65
35.215385
141
0.718403
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,522
mygraphicsscene.h
schirmermischa_THELI/src/iview/mygraphicsscene.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSSCENE_H #define MYGRAPHICSSCENE_H #include <QObject> #include <QGraphicsScene> #include <QKeyEvent> #include <QGraphicsEllipseItem> class MyGraphicsScene : public QGraphicsScene { Q_OBJECT public: MyGraphicsScene(); void leaveEvent(QEvent *event); QGraphicsEllipseItem *crosshairCircleItem = nullptr; QGraphicsEllipseItem *crosshairCircleBlackItem = nullptr; QGraphicsLineItem *crosshairLineNItem = nullptr; QGraphicsLineItem *crosshairLineSItem = nullptr; QGraphicsLineItem *crosshairLineEItem = nullptr; QGraphicsLineItem *crosshairLineWItem = nullptr; bool crosshairShown = false; double zoomScale = 1.0; signals: void itemDeleted(); void mouseLeftScene(); protected: void keyReleaseEvent(QKeyEvent * keyEvent); public slots: void removeCrosshair(); void addCrosshair(double x, double y); }; #endif // MYGRAPHICSSCENE_H
1,592
C++
.h
44
33.409091
75
0.795306
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,523
mygraphicsellipseitem.h
schirmermischa_THELI/src/iview/mygraphicsellipseitem.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSELLIPSEITEM_H #define MYGRAPHICSELLIPSEITEM_H #include <QObject> #include <QGraphicsSceneMouseEvent> #include <QGraphicsEllipseItem> class MyGraphicsEllipseItem : public QGraphicsEllipseItem { public: MyGraphicsEllipseItem(); void mousePressEvent(QGraphicsSceneMouseEvent *event); }; #endif // MYGRAPHICSELLIPSEITEM_H
1,025
C++
.h
26
37.807692
75
0.823411
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,524
mymagnifiedgraphicsview.h
schirmermischa_THELI/src/iview/mymagnifiedgraphicsview.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYMAGNIFIEDGRAPHICSVIEW_H #define MYMAGNIFIEDGRAPHICSVIEW_H #include <QGraphicsView> #include <QDebug> #include <QMouseEvent> #include <QScrollBar> class MyMagnifiedGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyMagnifiedGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int x = 0; int y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYMAGNIFIEDGRAPHICSVIEW_H
2,440
C++
.h
70
31.257143
75
0.775467
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,525
mybinnedgraphicsview.h
schirmermischa_THELI/src/iview/mybinnedgraphicsview.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYBINNEDGRAPHICSVIEW_H #define MYBINNEDGRAPHICSVIEW_H #include <QGraphicsView> #include <QGraphicsRectItem> #include <QDebug> #include <QMouseEvent> #include <QScrollBar> #include "myqgraphicsrectitem.h" class MyBinnedGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyBinnedGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int nx = 0; int ny = 0; QRectF binnedSceneRect; MyQGraphicsRectItem *fovRectItem = new MyQGraphicsRectItem(); // QGraphicsRectItem *fovRectItem = new QGraphicsRectItem(); int x = 0; int y = 0; bool fovBeingDragged = false; int old_x = 0; int old_y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); void fovRectCenterChanged(QPointF point); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYBINNEDGRAPHICSVIEW_H
2,801
C++
.h
81
30.864198
75
0.767407
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,526
iview.h
schirmermischa_THELI/src/iview/iview.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVIEW_H #define IVIEW_H #include "mygraphicsview.h" #include "mygraphicsscene.h" #include "mygraphicsellipseitem.h" #include "dockwidgets/ivconfdockwidget.h" #include "dockwidgets/ivscampdockwidget.h" #include "dockwidgets/ivcolordockwidget.h" #include "dockwidgets/ivwcsdockwidget.h" #include "dockwidgets/ivstatisticsdockwidget.h" #include "dockwidgets/ivfinderdockwidget.h" #include "dockwidgets/ivredshiftdockwidget.h" #include "../myimage/myimage.h" #include "myaxis.h" #include "fitsio2.h" #include "wcs.h" #include "wcshdr.h" #include <QMainWindow> #include <QGraphicsScene> #include <QLabel> #include <QMouseEvent> #include <QGraphicsView> #include <QDebug> #include <QLayout> #include <QTimer> #include <QSpinBox> #include <QVector> #include <QLineEdit> #include <QPushButton> #include <QActionGroup> namespace Ui { class IView; } class IView : public QMainWindow { Q_OBJECT public: explicit IView(QWidget *parent = nullptr); explicit IView(QString mode, QWidget *parent = nullptr); explicit IView(QString mode, QList<MyImage *> &list, QString dirname, QWidget *parent = nullptr); explicit IView(QString mode, QString name, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString filter, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString fileName, QString filter, QWidget *parent = nullptr); explicit IView(QString mode, QString dirname, QString rChannel, QString gChannel, QString bChannel, float factorR, float factorB, QWidget *parent = nullptr); ~IView(); QString dirName; QString startDirName = ""; // the dir name of the first image loaded (never changed after init) QString filterName; QString currentSuffix; QString middleMouseMode = "DragMode"; bool startDirNameSet = false; bool scampInteractiveMode = false; bool scampCorrectlyClosed = false; void setMiddleMouseMode(QString mode); void switchMode(QString mode = ""); void loadPNG(QString filename, int currentId = 0); void autoContrast(); void setImageList(QString filter); void redrawSkyCirclesAndCats(); void clearItems(); void updateCDmatrixFITS(); void setCatalogOverlaysExternally(bool sourcecatShown, bool refcatShown); void xy2sky(double x, double y, QString button = ""); bool weightMode = false; // whether iview displays the image data or the weight bool refcatSourcesShown = false; bool sourcecatSourcesShown = false; QString G2referencePathName = ""; QString AbsPhotReferencePathName = ""; IvConfDockWidget *icdw; IvScampDockWidget *scampdw; IvColorDockWidget *colordw; IvStatisticsDockWidget *statdw = new IvStatisticsDockWidget(this); IvFinderDockWidget *finderdw = new IvFinderDockWidget(this); IvWCSDockWidget *wcsdw = new IvWCSDockWidget(this); IvRedshiftDockWidget *zdw = new IvRedshiftDockWidget(this); QList<QGraphicsLineItem*> observedAxisLineItems; QList<QGraphicsLineItem*> restframeAxisLineItems; QList<QGraphicsLineItem*> spectrumAxisLineItems; QList<QGraphicsLineItem*> observedAxisMainLineItems; QList<QGraphicsLineItem*> restframeAxisMainLineItems; QList<QGraphicsLineItem*> spectrumAxisMainLineItems; QList<QGraphicsTextItem*> observedAxisTextItems; QList<QGraphicsTextItem*> restframeAxisTextItems; QList<QGraphicsTextItem*> spectrumAxisTextItems; MyGraphicsView *myGraphicsView; // MyGraphicsScene *scene = new MyGraphicsScene(this); MyGraphicsScene *scene = new MyGraphicsScene(); int numImages = 0; int zoomLevel = 0; float dynRangeMin; float dynRangeMax; QLabel *pageLabel = new QLabel(this); QStringList imageList; QStringList imageListChipName; QList<QGraphicsEllipseItem*> skyCircleItems; QList<QGraphicsEllipseItem*> acceptedSkyCircleItems; int currentId = 0; int verbosity = 0; float globalMedian = 0.; float globalMedianR = 0.; float globalMedianG = 0.; float globalMedianB = 0.; float globalRMS = 0.; float globalMean = 0.; QList<MyImage*> myImageList; MyImage *currentMyImage = nullptr; QString currentFileName = ""; int naxis1 = 0; int naxis2 = 0; QVector<float> fitsData; QVector<float> fitsDataR; QVector<float> fitsDataG; QVector<float> fitsDataB; QString displayMode = "CLEAR"; void qimageToBinned(qreal qx, qreal qy, qreal &bx, qreal &by); QRect qimageToBinned(const QRectF qrect); QPointF qimageToBinned(const QPointF qpoint); void binnedToQimage(qreal bx, qreal by, qreal &qx, qreal &qy); QPointF binnedToQimage(const QPointF bpoint); MyAxis observedAxis; MyAxis restframeAxis; MyAxis spectrumAxis; signals: void abortPlay(); void colorFactorChanged(QString redFactor, QString blueFactor); void closed(); void statisticsRequested(long x, long y); void solutionAcceptanceState(bool state); void middleMouseModeChanged(QString mode); void currentlyDisplayedIndex(int index); void updateNavigatorMagnified(QGraphicsPixmapItem *magnifiedPixmapItem, qreal scaleFactor, float dx, float dy); void updateNavigatorBinned(QGraphicsPixmapItem *binnedPixmapItem); void updateNavigatorBinnedViewport(QRect rect); void statisticsSampleAvailable(const QVector<float> &sample); void statisticsSampleColorAvailable(const QVector<float> &sampleR, const QVector<float> &sampleG, const QVector<float> &sampleB); void updateNavigatorBinnedWCS(wcsprm *cd, bool wcsinit); void clearMagnifiedScene(); void newImageLoaded(); void wavelengthUpdated(QString lobs, QString lrest); private slots: void adjustBrightnessContrast(QPointF point); void appendSkyCircle(); void backAction_triggered(); void clearSeparationVector(); void drawSeparationVector(QPointF pointStart, QPointF pointEnd); void drawSkyCircle(QPointF pointStart, QPointF pointEnd); void drawMaskingPolygon(QPointF pointStart, QPointF pointEnd); void drawSkyRectangle(QPointF pointStart, QPointF pointEnd); void endAction_triggered(); void forwardAction_triggered(); void initDynrangeDrag(); void initSeparationVector(QPointF pointStart); void loadImage(); void middlePressResetCRPIXreceived(); void nextAction_triggered(); void on_actionDragMode_triggered(); void on_actionSkyMode_triggered(); void on_actionWCSMode_triggered(); void on_actionMaskingMode_triggered(); void previousAction_triggered(); // void startAction_triggered(); // public void showCurrentMousePos(QPointF point); void sendStatisticsCenter(QPointF point); void showSourceCat(); void showReferenceCat(); void updateSkyCircles(); void updateCRPIX(QPointF pointStart, QPointF pointEnd); void updateCRPIXFITS(); void updateCDmatrix(double cd11, double cd12, double cd21, double cd22); void updateNavigatorMagnifiedReceived(QPointF point); // void mouseEnteredViewReceived(); // void mouseLeftViewReceived(); void on_actionImage_statistics_triggered(); void filterLineEdit_textChanged(const QString &arg1); void collectLocalStatisticsSample(QPointF point); void updateStatisticsButton(); void updateRedshiftButton(); void updateFinderButton(); void fovCenterChangedReceiver(QPointF newCenter); void on_actionFinder_triggered(); void WCSupdatedReceived(); void on_actionRedshift_triggered(); void showWavelength(QPointF point); void redrawUpdateAxes(); public slots: void autoContrastPushButton_toggled_receiver(bool checked); void clearAll(); void colorFactorChanged_receiver(QString redFactor, QString blueFactor); void loadFITSexternal(QString fileName, QString filter); void loadFromRAM(MyImage *it, int level); // void loadFromRAMlist(const QModelIndex &index); void loadFITSexternalRAM(int index); void mapFITS(); void minmaxLineEdit_returnPressed_receiver(QString rangeMin, QString rangeMax); void showG2References(bool checked); void showAbsPhotReferences(bool checked); void solutionAcceptanceStateReceived(bool state); void startAction_triggered(); void updateColorViewInternal(float redFactor, float blueFactor); void updateColorViewExternal(float redFactor, float blueFactor); void zoomFitPushButton_clicked_receiver(bool checked); void zoomInPushButton_clicked_receiver(); void zoomOutPushButton_clicked_receiver(); void zoomZeroPushButton_clicked_receiver(); void viewportChangedReceived(QRect viewport_rect); void targetResolvedReceived(QString alphaStr, QString deltaStr); void updateAxes(); void updateFinesse(int value); void resetRedshift(); void redshiftChanged(QString text); protected: void closeEvent(QCloseEvent *event) override; void resizeEvent(QResizeEvent *event); private: Ui::IView *ui; QLabel *coordsLabel; QActionGroup *middleMouseActionGroup = new QActionGroup(this); int screenHeight; int screenWidth; float dynRangeMinDragStart = 0.; float dynRangeMaxDragStart = 0.; double crpix1_start = 0.; // set when the middle mouse button is pressed in wcs mode double crpix2_start = 0.; // set when the middle mouse button is pressed in wcs mode double plateScale = 0.; double skyRa = 0.; double skyDec = 0.; bool startLeftClickInsideItem = false; int timerId; QString ChannelR; QString ChannelG; QString ChannelB; bool allChannelsRead = false; unsigned char *dataInt; unsigned char *dataIntR; unsigned char *dataIntG; unsigned char *dataIntB; unsigned char *dataBinnedInt; unsigned char *dataBinnedIntR; unsigned char *dataBinnedIntG; unsigned char *dataBinnedIntB; QGraphicsPixmapItem *pixmapItem = nullptr; QGraphicsPixmapItem *magnifiedPixmapItem = nullptr; QGraphicsPixmapItem *binnedPixmapItem = nullptr; bool dataBinnedIntSet = false; bool dataBinnedIntRSet = false; bool dataBinnedIntGSet = false; bool dataBinnedIntBSet = false; bool dataIntSet = false; bool dataIntRSet = false; bool dataIntGSet = false; bool dataIntBSet = false; int magnify = 7; double rad = 3.1415926535 / 180.; bool fromMemory = false; struct wcsprm *wcs; bool wcsInit = false; char *fullheader = nullptr; QTimer *timer = new QTimer(this); QList<QGraphicsLineItem*> vectorLineItems; QList<QGraphicsTextItem*> vectorTextItems; QList<QGraphicsEllipseItem*> sourceCatItems; QList<QGraphicsRectItem*> refCatItems; QList<QGraphicsRectItem*> G2refCatItems; QList<QGraphicsRectItem*> AbsPhotRefCatItems; QList<QGraphicsRectItem*> skyRectItems; QList<QGraphicsTextItem*> skyTextItems; QList<QGraphicsPolygonItem*> maskPolygonItems; QList<QGraphicsRectItem*> maskRectItems; QLabel *speedLabel = new QLabel(this); QSpinBox *speedSpinBox = new QSpinBox(this); QLabel *filterLabel = new QLabel(this); QLineEdit *filterLineEdit = new QLineEdit(this); bool icdwDefined = false; bool scampdwDefined = false; bool binnedPixmapUptodate = false; void addDockWidgets(); QRect adjustGeometry(); void clearSkyCircleItems(); void clearSkyRectItems(); void clearMaskPolygonItems(); void clearMaskRectItems(); void clearVectorItems(); void compressDynrange(const QVector<float> &fitsdata, unsigned char *intdata, float colorCorrectionFactor = 1.0); QString dec2hex(double angle); void dumpSkyCircleCoordinates(); void getGlobalImageStatistics(QString colorMode = ""); QString getVectorLabel(double separation); void getVectorOffsets(const qreal dx, const qreal dy, qreal &x_yoffset, qreal &y_xoffset, qreal &d_xoffset, qreal &d_yoffset); double haversine(double x1, double y1, double x2, double y2); void hideWCSdockWidget(); void imageListToChipName(); void initGUI(); void initGUIstep2(); void loadColorFITS(qreal scaleFactor); void loadFITS(QString filename, int currentId = 0, qreal scaleFactor = 1.0); bool loadFITSdata(QString filename, QVector<float> &data, QString colorMode = ""); void makeConnections(); void measureAngularSeparations(QPointF pointStart, QPointF pointEnd, double &sepX, double &sepY, double &sepD); void readPreferenceSettings(); bool readRaDecCatalog(QString fileName, QList<QGraphicsRectItem *> &items, double size, int width, QColor color); void replotCatalogAfterZoom(); void setCurrentId(QString filename); void setImageListFromMemory(); void showWCSdockWidget(); void showAxes(); void sky2xyQImage(double ra, double dec, double &x, double &y); void sky2xyFITS(double ra, double dec, double &x, double &y); void writePreferenceSettings(); template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } void sendWCStoWCSdockWidget(); void checkFinder(); void checkFinderBypass(); void showAxesHelper(QList<QGraphicsLineItem *> &lineItemList, QList<QGraphicsLineItem *> &mainLineItemList, QList<QGraphicsTextItem *> &textItemList, const MyAxis &axis, QString type); void clearAxesHelper(QList<QGraphicsLineItem *> &lineItemList, QList<QGraphicsLineItem *> &mainLineItemList, QList<QGraphicsTextItem*> &textItemList); void clearAxes(); void updateAxesHelper(); }; #endif // IVIEW_H
14,162
C++
.h
335
37.823881
188
0.758598
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,527
myqgraphicsrectitem.h
schirmermischa_THELI/src/iview/myqgraphicsrectitem.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYQGRAPHICSRECTITEM_H #define MYQGRAPHICSRECTITEM_H #include <QGraphicsRectItem> class MyQGraphicsRectItem : public QObject, public QGraphicsRectItem { Q_OBJECT // inherit constructors using QGraphicsRectItem::QGraphicsRectItem; public: explicit MyQGraphicsRectItem(); protected: virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); signals: public slots: }; #endif // MYQGRAPHICSRECTITEM_H
1,130
C++
.h
30
35.6
82
0.815257
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,528
mygraphicsview.h
schirmermischa_THELI/src/iview/mygraphicsview.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef MYGRAPHICSVIEW_H #define MYGRAPHICSVIEW_H #include <QGraphicsView> #include <QDebug> #include <QMouseEvent> #include <QScrollBar> class MyGraphicsView : public QGraphicsView { Q_OBJECT private: QPointF rightDragStartPos; QPointF rightDragCurrentPos; QPointF rightDragEndPos; QPointF leftDragStartPos; QPointF leftDragCurrentPos; QPointF leftDragEndPos; // unused QPointF middleDragStartPos; QPointF middleDragCurrentPos; QPointF middleDragEndPos; bool rightButtonPressed = false; bool leftButtonPressed = false; bool middleButtonPressed = false; QPoint previousMousePoint; bool _pan = false; int _panStartX = 0; int _panStartY = 0; bool _wcs = false; QPoint wcsStart; public: explicit MyGraphicsView(); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void leaveEvent(QEvent *event); void enterEvent(QEvent *event); void paintEvent(QPaintEvent *event); QScrollBar *sxbar = nullptr; QScrollBar *sybar = nullptr; QString middleMouseMode = "DragMode"; int x = 0; int y = 0; signals: void currentMousePos(QPointF); void rightDragTravelled(QPointF); void middleSkyDragTravelled(QPointF pointStart, QPointF pointEnd); void middleMaskingDragTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSTravelled(QPointF pointStart, QPointF pointEnd); void middleWCSreleased(); void leftDragTravelled(QPointF pointStart, QPointF pointEnd); void rightPress(); void leftPress(QPointF pointStart); void middlePress(QPointF point); void leftButtonReleased(); void rightButtonReleased(); void middleButtonReleased(); void middlePressResetCRPIX(); void mouseLeftView(); void mouseEnteredView(); void viewportChanged(QRect viewport_rect); public slots: void updateMiddleMouseMode(QString mode); }; #endif // MYGRAPHICSVIEW_H
2,688
C++
.h
77
31.181818
75
0.770119
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,529
ivstatisticsdockwidget.h
schirmermischa_THELI/src/iview/dockwidgets/ivstatisticsdockwidget.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVSTATISTICSDOCKWIDGET_H #define IVSTATISTICSDOCKWIDGET_H #include <QDockWidget> namespace Ui { class IvStatisticsDockWidget; } class IView; // Forward declaration to access members class IvStatisticsDockWidget : public QDockWidget { Q_OBJECT public: explicit IvStatisticsDockWidget(IView *parent = 0); ~IvStatisticsDockWidget(); Ui::IvStatisticsDockWidget *ui; IView *iview; int statWidth = 3; void init(); public slots: void statisticsSampleReceiver(const QVector<float> &sample); void statisticsSampleColorReceiver(const QVector<float> &sampleR, const QVector<float> &sampleG, const QVector<float> &sampleB); private slots: void on_localWindowComboBox_currentIndexChanged(const QString &arg1); private: float localMedian = 0.; float localSigma = 0.; float localMean = 0.; float localMedianR = 0.; float localMedianG = 0.; float localMedianB = 0.; }; #endif // IVSTATISTICSDOCKWIDGET_H
1,653
C++
.h
45
33.888889
132
0.783512
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,530
ivcolordockwidget.h
schirmermischa_THELI/src/iview/dockwidgets/ivcolordockwidget.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVCOLORDOCKWIDGET_H #define IVCOLORDOCKWIDGET_H #include <QDockWidget> #include <QSlider> #include <QString> #include <QLineEdit> #include <QPushButton> namespace Ui { class IvColorDockWidget; } class IView; // Forward declaration to access members class IvColorDockWidget : public QDockWidget { Q_OBJECT public: explicit IvColorDockWidget(IView *parent = 0); ~IvColorDockWidget(); Ui::IvColorDockWidget *ui; void textToSlider(QString value, QString channel); QVector<float> colorFactorApplied = QVector<float>(3, 1.0); // stores current RGB factors QVector<float> colorFactorZeropoint = QVector<float>(3, 1.0); // stores fixed RGB factors as determined by calibration IView *iview; private: void sliderToText(int sliderValue, QString channel); int sliderSteps = 100; signals: void colorFactorChanged(QString redFactor, QString blueFactor); void showG2references(bool checked); private slots: void blueSliderMoved(const int &sliderValue); void blueFactorEdited(const QString &value); void redSliderMoved(const int &sliderValue); void redFactorEdited(const QString &value); void validate(); void on_blueResetPushButton_clicked(); void on_redResetPushButton_clicked(); }; #endif // IVCOLORDOCKWIDGET_H
1,974
C++
.h
52
35.192308
122
0.785414
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,531
ivfinderdockwidget.h
schirmermischa_THELI/src/iview/dockwidgets/ivfinderdockwidget.h
/* Copyright (C) 2019 Mischa Schirmer This file is part of THELI. THELI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program in the LICENSE file. If not, see https://www.gnu.org/licenses/ . */ #ifndef IVFINDERDOCKWIDGET_H #define IVFINDERDOCKWIDGET_H #include <QDockWidget> namespace Ui { class IvFinderDockWidget; } class IvFinderDockWidget : public QDockWidget { Q_OBJECT public: explicit IvFinderDockWidget(QWidget *parent = 0); ~IvFinderDockWidget(); Ui::IvFinderDockWidget *ui; QString dateObs = "2020-01-01T00:00:00"; float geoLon = 0.0; float geoLat = 0.0; void bypassResolver(); public slots: void updateDateObsAndGeo(QString dateobs, float geolon, float geolat); void on_targetresolverToolButton_clicked(); void on_MPCresolverToolButton_clicked(); void on_locatePushButton_clicked(); private slots: void targetResolvedReceived(QString alpha, QString delta); void validate(); void on_clearPushButton_clicked(); signals: void targetResolved(QString alpha, QString delta); void clearTargetResolved(); private: }; #endif // IVFINDERDOCKWIDGET_H
1,614
C++
.h
46
32.26087
75
0.784149
schirmermischa/THELI
35
5
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false