Kstars

focusadvisor.cpp
1/*
2 SPDX-FileCopyrightText: 2024 John Evans <john.e.evans.email@googlemail.com>
3
4 SPDX-License-Identifier: GPL-2.0-or-later
5*/
6
7#include "focusadvisor.h"
8#include "focus.h"
9#include "focusalgorithms.h"
10#include "Options.h"
11#include "ekos/auxiliary/opticaltrainmanager.h"
12#include "ekos/auxiliary/opticaltrainsettings.h"
13#include "ekos/auxiliary/stellarsolverprofile.h"
14
15#include <QScrollBar>
16
17namespace Ekos
18{
19
20const char * FOCUSER_SIMULATOR = "Focuser Simulator";
21const int MAXIMUM_FOCUS_ADVISOR_ITERATIONS = 1001;
22const int NUM_JUMPS_PER_SECTOR = 10;
23const int FIND_STARS_MIN_STARS = 2;
24const double TARGET_MAXMIN_HFR_RATIO = 3.0;
25const double INITIAL_MAXMIN_HFR_RATIO = 2.0;
26const int NUM_STEPS_PRE_AF = 11;
27
28FocusAdvisor::FocusAdvisor(QWidget *parent) : QDialog(parent)
29{
30#ifdef Q_OS_MACOS
31 setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
32#endif
33
34 setupUi(this);
35 m_focus = static_cast<Focus *>(parent);
36
37 processUI();
38 setupHelpTable();
39}
40
41FocusAdvisor::~FocusAdvisor()
42{
43}
44
45void FocusAdvisor::processUI()
46{
47 // Setup the help dialog
48 m_helpDialog = new QDialog(this);
49 m_helpUI.reset(new Ui::focusAdvisorHelpDialog());
50 m_helpUI->setupUi(m_helpDialog);
51#ifdef Q_OS_MACOS
52 m_helpDialog->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);
53#endif
54
55 m_runButton = focusAdvButtonBox->addButton("Run", QDialogButtonBox::ActionRole);
56 m_stopButton = focusAdvButtonBox->addButton("Stop", QDialogButtonBox::ActionRole);
57 m_helpButton = focusAdvButtonBox->addButton("Help", QDialogButtonBox::HelpRole);
58
59 // Set tooltips for the buttons
60 m_runButton->setToolTip("Run Focus Advisor");
61 m_stopButton->setToolTip("Stop Focus Advisor");
62 m_helpButton->setToolTip("List parameter settings");
63
64 // Connect up button callbacks
65 connect(m_runButton, &QPushButton::clicked, this, &FocusAdvisor::start);
66 connect(m_stopButton, &QPushButton::clicked, this, &FocusAdvisor::stop);
67 connect(m_helpButton, &QPushButton::clicked, this, &FocusAdvisor::help);
68
69 // Initialise buttons
70 setButtons(false);
71
72 // Setup the results table
73 setupResultsTable();
74}
75
76void FocusAdvisor::setupResultsTable()
77{
78 focusAdvTable->setColumnCount(RESULTS_MAX_COLS);
79 focusAdvTable->setRowCount(0);
80
81 QTableWidgetItem *itemSection = new QTableWidgetItem(i18n ("Section"));
82 itemSection->setToolTip(i18n("Section"));
83 focusAdvTable->setHorizontalHeaderItem(RESULTS_SECTION, itemSection);
84
85 QTableWidgetItem *itemRunNumber = new QTableWidgetItem(i18n ("Run"));
86 itemRunNumber->setToolTip(i18n("Run number"));
87 focusAdvTable->setHorizontalHeaderItem(RESULTS_RUN_NUMBER, itemRunNumber);
88
89 QTableWidgetItem *itemStartPosition = new QTableWidgetItem(i18n ("Start Pos"));
90 itemStartPosition->setToolTip(i18n("Start position"));
91 focusAdvTable->setHorizontalHeaderItem(RESULTS_START_POSITION, itemStartPosition);
92
93 QTableWidgetItem *itemStepSize = new QTableWidgetItem(i18n ("Step/Jump Size"));
94 itemStepSize->setToolTip(i18n("Step Size"));
95 focusAdvTable->setHorizontalHeaderItem(RESULTS_STEP_SIZE, itemStepSize);
96
97 QTableWidgetItem *itemAFOverscan = new QTableWidgetItem(i18n ("Overscan"));
98 itemAFOverscan->setToolTip(i18n("AF Overscan"));
99 focusAdvTable->setHorizontalHeaderItem(RESULTS_AFOVERSCAN, itemAFOverscan);
100
101 QTableWidgetItem *itemText = new QTableWidgetItem(i18n ("Comments"));
102 itemText->setToolTip(i18n("Additional Text"));
103 focusAdvTable->setHorizontalHeaderItem(RESULTS_TEXT, itemText);
104
105 focusAdvTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
106 focusAdvTable->hide();
107 resizeDialog();
108}
109
110
111void FocusAdvisor::setupHelpTable()
112{
113 QTableWidgetItem *itemParameter = new QTableWidgetItem(i18n ("Parameter"));
114 itemParameter->setToolTip(i18n("Parameter Name"));
115 m_helpUI->table->setHorizontalHeaderItem(HELP_PARAMETER, itemParameter);
116
117 QTableWidgetItem *itemCurrentValue = new QTableWidgetItem(i18n ("Current Value"));
118 itemCurrentValue->setToolTip(i18n("Current value of the parameter"));
119 m_helpUI->table->setHorizontalHeaderItem(HELP_CURRENT_VALUE, itemCurrentValue);
120
121 QTableWidgetItem *itemProposedValue = new QTableWidgetItem(i18n ("Proposed Value"));
122 itemProposedValue->setToolTip(i18n("Focus Advisor proposed value for the parameter"));
123 m_helpUI->table->setHorizontalHeaderItem(HELP_NEW_VALUE, itemProposedValue);
124
125 connect(m_helpUI->focusAdvHelpOnlyChanges, static_cast<void (QCheckBox::*)(int)>(&QCheckBox::stateChanged), this, [this]()
126 {
127 setupParams("");
128 });
129}
130
131void FocusAdvisor::setButtons(const bool running)
132{
133 bool canRun = m_focus->m_Focuser && m_focus->m_Focuser->isConnected() && m_focus->m_Focuser->canAbsMove();
134 m_runButton->setEnabled(!running && canRun);
135 m_stopButton->setEnabled(running);
136 m_helpButton->setEnabled(!running);
137 focusAdvButtonBox->button(QDialogButtonBox::Close)->setEnabled(!running);
138}
139
140bool FocusAdvisor::canFocusAdvisorRun()
141{
142 // Focus Advisor can only be run if the following...
143 return m_focus->m_Focuser && m_focus->m_Focuser->isConnected() && m_focus->m_Focuser->canAbsMove() &&
144 m_focus->m_FocusAlgorithm == Focus::FOCUS_LINEAR1PASS &&
145 (m_focus->m_StarMeasure == Focus::FOCUS_STAR_HFR || m_focus->m_StarMeasure == Focus::FOCUS_STAR_HFR_ADJ
146 || m_focus->m_StarMeasure == Focus::FOCUS_STAR_FWHM) &&
147 (m_focus->m_CurveFit == CurveFitting::FOCUS_HYPERBOLA || m_focus->m_CurveFit == CurveFitting::FOCUS_PARABOLA);
148}
149
150bool FocusAdvisor::start()
151{
152 // Reset the results table
153 focusAdvTable->setRowCount(0);
154 focusAdvTable->sizePolicy();
155
156 if (!m_focus)
157 return false;
158
159 if (m_focus->inFocusLoop || m_focus->inAdjustFocus || m_focus->inAutoFocus || m_focus->inBuildOffsets
160 || m_focus->inScanStartPos || inFocusAdvisor())
161 {
162 m_focus->appendLogText(i18n("Focus Advisor: another focus action in progress. Please try again."));
163 return false;
164 }
165
166 if (focusAdvUpdateParams->isChecked())
167 {
168 updateParams();
169 focusAdvUpdateParamsLabel->setText(i18n("Done"));
170 emit newStage(UpdatingParameters);
171 }
172
173 m_inFindStars = focusAdvFindStars->isChecked();
174 m_inPreAFAdj = focusAdvCoarseAdj->isChecked();
175 m_inAFAdj = focusAdvFineAdj->isChecked();
176 if (m_inFindStars || m_inPreAFAdj || m_inAFAdj)
177 {
178 if (canFocusAdvisorRun())
179 {
180 // Deselect ScanStartPos to stop interference with Focus Advisor
181 m_initialScanStartPos = m_focus->m_OpsFocusProcess->focusScanStartPos->isChecked();
182 m_focus->m_OpsFocusProcess->focusScanStartPos->setChecked(false);
183 m_focus->runAutoFocus(FOCUS_FOCUS_ADVISOR, "");
184 }
185 else
186 {
187 m_focus->appendLogText(i18n("Focus Advisor cannot run with current params."));
188 return false;
189 }
190 }
191
192 return true;
193}
194
195void FocusAdvisor::stop()
196{
197 abort(i18n("Focus Advisor stopped"));
198 emit newStage(Idle);
199}
200
201// Focus Advisor help popup
202void FocusAdvisor::help()
203{
204 setupParams("");
205 m_helpDialog->show();
206 m_helpDialog->raise();
207}
208
209void FocusAdvisor::addSectionToHelpTable(int &row, const QString &section)
210{
211 if (++row >= m_helpUI->table->rowCount())
212 m_helpUI->table->setRowCount(row + 1);
214 item->setText(section);
215 QFont font = item->font();
216 font.setUnderline(true);
217 font.setPointSize(font.pointSize() + 2);
218 item->setFont(font);
219 m_helpUI->table->setItem(row, HELP_PARAMETER, item);
220}
221
222void FocusAdvisor::addParamToHelpTable(int &row, const QString &parameter, const QString &currentValue,
223 const QString &newValue)
224{
225 if (m_helpUI->focusAdvHelpOnlyChanges->isChecked() && newValue == currentValue)
226 return;
227
228 if (++row >= m_helpUI->table->rowCount())
229 m_helpUI->table->setRowCount(row + 1);
230 QTableWidgetItem *itemParameter = new QTableWidgetItem(parameter);
231 m_helpUI->table->setItem(row, HELP_PARAMETER, itemParameter);
232 QTableWidgetItem *itemCurrentValue = new QTableWidgetItem(currentValue);
233 m_helpUI->table->setItem(row, HELP_CURRENT_VALUE, itemCurrentValue);
234 QTableWidgetItem *itemNewValue = new QTableWidgetItem(newValue);
235 if (newValue != currentValue)
236 {
237 // Highlight changes
238 QFont font = itemNewValue->font();
239 font.setBold(true);
240 itemNewValue->setFont(font);
241 }
242 m_helpUI->table->setItem(row, HELP_NEW_VALUE, itemNewValue);
243}
244
245// Resize the help dialog to the data
246void FocusAdvisor::resizeHelpDialog()
247{
248 // Resize the columns to the data
249 m_helpUI->table->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
250
251 // Resize the dialog to the width of the table widget + decoration
252 int left, right, top, bottom;
253 m_helpUI->verticalLayout->layout()->getContentsMargins(&left, &top, &right, &bottom);
254
255 const int width = m_helpUI->table->horizontalHeader()->length() +
256 m_helpUI->table->verticalHeader()->width() +
257 m_helpUI->table->verticalScrollBar()->width() +
258 m_helpUI->table->frameWidth() * 2 +
259 left + right +
260 m_helpDialog->contentsMargins().left() + m_helpDialog->contentsMargins().right() + 8;
261
262 m_helpDialog->resize(width, m_helpDialog->height());
263}
264
265// Action the focus params recommendations
266void FocusAdvisor::updateParams()
267{
268 m_focus->setAllSettings(m_map);
269 addResultsTable(i18n("Update Parameters"), -1, -1, -1, -1, "Done");
270}
271
272// Load up the Focus Advisor recommendations
273void FocusAdvisor::setupParams(const QString &OTName)
274{
275 // See if there is another OT that can be used to default parameters
276 m_map = getOTDefaults(OTName);
277 bool noDefaults = m_map.isEmpty();
278
279 if (!m_map.isEmpty())
280 // If we have found parameters from another OT that fit then we're done
281 return;
282
283 bool longFL = m_focus->m_FocalLength > 1500;
284 double imageScale = m_focus->getStarUnits(Focus::FOCUS_STAR_HFR, Focus::FOCUS_UNITS_ARCSEC);
285 bool centralObstruction = scopeHasObstruction(m_focus->m_ScopeType);
286
287 // Set the label based on the optical train
288 m_helpUI->helpLabel->setText(QString("Recommendations: %1 FL=%2 ImageScale=%3")
289 .arg(m_focus->m_ScopeType).arg(m_focus->m_FocalLength).arg(imageScale, 0, 'f', 2));
290
291 bool ok;
292 // Reset the table
293 m_helpUI->table->setRowCount(0);
294
295 // Camera options
296 int row = -1;
297 addSectionToHelpTable(row, i18n("Camera & Filter Wheel Parameters"));
298
299 // Exposure
300 double exposure = longFL ? 4.0 : 2.0;
301 processParam(exposure, row, m_map, m_focus->focusExposure, "Exposure");
302
303 // Binning
304 QString binning;
305 if (m_focus->focusBinning->isEnabled())
306 {
307 // Only try and update binning if camera supports it (binning field enabled)
308 QString binTarget = (imageScale < 1.0) ? "2x2" : "1x1";
309
310 for (int i = 0; i < m_focus->focusBinning->count(); i++)
311 {
312 if (m_focus->focusBinning->itemText(i) == binTarget)
313 {
314 binning = binTarget;
315 break;
316 }
317 }
318 }
319 processParam(binning, row, m_map, m_focus->focusBinning, "Binning");
320
321 // Gain - don't know a generic way to default to Unity gain so use current setting
322 processParam(m_focus->focusGain->value(), row, m_map, m_focus->focusGain, "Gain");
323
324 // ISO - default to current value
325 processParam(m_focus->focusISO->currentText(), row, m_map, m_focus->focusISO, "ISO");
326
327 // Filter
328 processParam(m_focus->focusFilter->currentText(), row, m_map, m_focus->focusFilter, "Filter");
329
330 // Settings
331 addSectionToHelpTable(row, i18n("Settings Parameters"));
332
333 // Auto Select Star
334 processParam(false, row, m_map, m_focus->m_OpsFocusSettings->focusAutoStarEnabled, "Auto Select Star");
335
336 // Suspend Guiding - leave alone
337 processParam(m_focus->m_OpsFocusSettings->focusSuspendGuiding->isChecked(), row, m_map,
338 m_focus->m_OpsFocusSettings->focusSuspendGuiding, "Auto Select Star");
339
340 // Use Dark Frame
341 processParam(false, row, m_map, m_focus->m_OpsFocusSettings->useFocusDarkFrame, "Dark Frame");
342
343 // Full Field & Subframe
344 processParam(true, row, m_map, m_focus->m_OpsFocusSettings->focusUseFullField, "Full Field");
345 processParam(false, row, m_map, m_focus->m_OpsFocusSettings->focusSubFrame, "Sub Frame");
346
347 // Subframe box
348 processParam(32, row, m_map, m_focus->m_OpsFocusSettings->focusBoxSize, "Box");
349
350 // Display Units - leave alone
351 processParam(m_focus->m_OpsFocusSettings->focusUnits->currentText(), row, m_map, m_focus->m_OpsFocusSettings->focusUnits,
352 "Display Units");
353
354 // Guide Settle - leave alone
355 processParam(m_focus->m_OpsFocusSettings->focusGuideSettleTime->value(), row, m_map,
356 m_focus->m_OpsFocusSettings->focusGuideSettleTime, "Guide Settle");
357
358 // Mask
359 QString maskCurrent, maskNew;
360 if (m_focus->m_OpsFocusSettings->focusNoMaskRB->isChecked())
361 maskCurrent = "Use all stars";
362 else if (m_focus->m_OpsFocusSettings->focusRingMaskRB->isChecked())
363 {
364 double inner = m_focus->m_OpsFocusSettings->focusFullFieldInnerRadius->value();
365 double outer = m_focus->m_OpsFocusSettings->focusFullFieldOuterRadius->value();
366 maskCurrent = QString("Ring Mask %1%-%2%").arg(inner, 0, 'f', 1).arg(outer, 0, 'f', 1);
367 }
368 else
369 {
370 int width = m_focus->m_OpsFocusSettings->focusMosaicTileWidth->value();
371 int spacer = m_focus->m_OpsFocusSettings->focusMosaicSpace->value();
372 maskCurrent = QString("Mosaic Mask %1% (%2 px)").arg(width).arg(spacer);
373 }
374
375 if (noDefaults)
376 {
377 // Set a Ring Mask 0% - 80%
378 m_map.insert("focusNoMaskRB", false);
379 m_map.insert("focusRingMaskRB", true);
380 m_map.insert("focusMosaicMaskRB", false);
381 m_map.insert("focusFullFieldInnerRadius", 0.0);
382 m_map.insert("focusFullFieldOuterRadius", 80.0);
383 maskNew = QString("Ring Mask %1%-%2%").arg(0.0, 0, 'f', 1).arg(80.0, 0, 'f', 1);
384 }
385 else
386 {
387 bool noMask = m_map.value("focusNoMaskRB", false).toBool();
388 bool ringMask = m_map.value("focusRingMaskRB", false).toBool();
389 bool mosaicMask = m_map.value("focusMosaicMaskRB", false).toBool();
390 if (noMask)
391 maskNew = "Use all stars";
392 else if (ringMask)
393 {
394 double inner = m_map.value("focusFullFieldInnerRadius", 0.0).toDouble(&ok);
395 if (!ok || inner < 0.0 || inner > 100.0)
396 inner = 0.0;
397 double outer = m_map.value("focusFullFieldOuterRadius", 80.0).toDouble(&ok);
398 if (!ok || outer < 0.0 || outer > 100.0)
399 outer = 80.0;
400 maskNew = QString("Ring Mask %1%-%2%").arg(inner, 0, 'f', 1).arg(outer, 0, 'f', 1);
401 }
402 else if (mosaicMask)
403 {
404 int width = m_map.value("focusMosaicTileWidth", 0.0).toInt(&ok);
405 if (!ok || width < 0 || width > 100)
406 width = 0.0;
407 int spacer = m_map.value("focusMosaicSpace", 0.0).toInt(&ok);
408 if (!ok || spacer < 0 || spacer > 100)
409 spacer = 0.0;
410 maskNew = QString("Mosaic Mask %1% (%2 px)").arg(width).arg(spacer);
411 }
412 }
413 addParamToHelpTable(row, i18n("Mask"), maskCurrent, maskNew);
414
415 // Adaptive Focus
416 processParam(false, row, m_map, m_focus->m_OpsFocusSettings->focusAdaptive, "Adaptive Focus");
417
418 // Min Move - leave default
419 processParam(m_focus->m_OpsFocusSettings->focusAdaptiveMinMove->value(), row, m_map,
420 m_focus->m_OpsFocusSettings->focusAdaptiveMinMove, "Min Move");
421
422 // Adapt Start Pos
423 processParam(false, row, m_map, m_focus->m_OpsFocusSettings->focusAdaptStart, "Adapt Start Pos");
424
425 // Max Movement - leave default
426 processParam(m_focus->m_OpsFocusSettings->focusAdaptiveMaxMove->value(), row, m_map,
427 m_focus->m_OpsFocusSettings->focusAdaptiveMaxMove, "Max Total Move");
428
429 // Process
430 addSectionToHelpTable(row, i18n("Process Parameters"));
431
432 // Detection method
433 processParam(QString("SEP"), row, m_map, m_focus->m_OpsFocusProcess->focusDetection, "Detection");
434
435 // SEP profile
436 QString profile = centralObstruction ? FOCUS_DEFAULT_DONUT_NAME : FOCUS_DEFAULT_NAME;
437 processParam(profile, row, m_map, m_focus->m_OpsFocusProcess->focusSEPProfile, "SEP Profile");
438
439 // Algorithm
440 processParam(QString("Linear 1 Pass"), row, m_map, m_focus->m_OpsFocusProcess->focusAlgorithm, "Algorithm");
441
442 // Curve Fit
443 processParam(QString("Hyperbola"), row, m_map, m_focus->m_OpsFocusProcess->focusCurveFit, "Curve Fit");
444
445 // Measure
446 processParam(QString("HFR"), row, m_map, m_focus->m_OpsFocusProcess->focusStarMeasure, "Measure");
447
448 // Use Weights
449 processParam(true, row, m_map, m_focus->m_OpsFocusProcess->focusUseWeights, "Use Weights");
450
451 // R2 limit
452 processParam(0.8, row, m_map, m_focus->m_OpsFocusProcess->focusR2Limit, "R² Limit");
453
454 // Refine Curve Fit
455 processParam(true, row, m_map, m_focus->m_OpsFocusProcess->focusRefineCurveFit, "Refine Curve Fit");
456
457 // Frames Count
458 processParam(1, row, m_map, m_focus->m_OpsFocusProcess->focusFramesCount, "Average Over");
459
460 // HFR Frames Count
461 processParam(1, row, m_map, m_focus->m_OpsFocusProcess->focusHFRFramesCount, "Average HFR Check");
462
463 // Donut buster
464 processParam(centralObstruction, row, m_map, m_focus->m_OpsFocusProcess->focusDonut, "Donut Buster");
465 processParam(1.0, row, m_map, m_focus->m_OpsFocusProcess->focusTimeDilation, "Time Dilation x");
466 processParam(0.2, row, m_map, m_focus->m_OpsFocusProcess->focusOutlierRejection, "Outlier Rejection");
467
468 // Scan for Start Position
469 processParam(true, row, m_map, m_focus->m_OpsFocusProcess->focusScanStartPos, "Scan for Start Position");
470 processParam(false, row, m_map, m_focus->m_OpsFocusProcess->focusScanAlwaysOn, "Always On");
471 processParam(5, row, m_map, m_focus->m_OpsFocusProcess->focusScanDatapoints, "Num Datapoints");
472 processParam(1.0, row, m_map, m_focus->m_OpsFocusProcess->focusScanStepSizeFactor, "Initial Step Sixe x");
473
474 // Mechanics
475 addSectionToHelpTable(row, i18n("Mechanics Parameters"));
476
477 // Walk
478 processParam(QString("Fixed Steps"), row, m_map, m_focus->m_OpsFocusMechanics->focusWalk, "Walk");
479
480 // Settle Time
481 processParam(1.0, row, m_map, m_focus->m_OpsFocusMechanics->focusSettleTime, "Focuser Settle");
482
483 // Initial Step Size - Sim = 5000 otherwise 20
484 int stepSize = m_focus->m_Focuser && m_focus->m_Focuser->getDeviceName() == FOCUSER_SIMULATOR ? 5000 : 20;
485 processParam(stepSize, row, m_map, m_focus->m_OpsFocusMechanics->focusTicks, "Initial Step Size");
486
487 // Number of steps
488 processParam(11, row, m_map, m_focus->m_OpsFocusMechanics->focusNumSteps, "Number Steps");
489
490 // Max Travel - leave default
491 processParam(m_focus->m_OpsFocusMechanics->focusMaxTravel->maximum(), row, m_map,
492 m_focus->m_OpsFocusMechanics->focusMaxTravel, "Max Travel");
493
494 // Backlash - leave default
495 processParam(m_focus->m_OpsFocusMechanics->focusBacklash->value(), row, m_map, m_focus->m_OpsFocusMechanics->focusBacklash,
496 "Driver Backlash");
497
498 // AF Overscan - leave default
499 processParam(m_focus->m_OpsFocusMechanics->focusAFOverscan->value(), row, m_map,
500 m_focus->m_OpsFocusMechanics->focusAFOverscan, "AF Overscan");
501
502 // Overscan Delay
503 processParam(0.0, row, m_map, m_focus->m_OpsFocusMechanics->focusOverscanDelay, "AF Overscan Delay");
504
505 // Capture timeout
506 processParam(30, row, m_map, m_focus->m_OpsFocusMechanics->focusCaptureTimeout, "Capture Timeout");
507
508 // Motion timeout
509 processParam(30, row, m_map, m_focus->m_OpsFocusMechanics->focusMotionTimeout, "Motion Timeout");
510
511 resizeHelpDialog();
512 setButtons(false);
513}
514
515QString FocusAdvisor::boolText(const bool flag)
516{
517 return flag ? "On" : "Off";
518}
519
520// Function to set inFocusAdvisor
521void FocusAdvisor::setInFocusAdvisor(bool value)
522{
523 m_inFocusAdvisor = value;
524}
525
526// Return a prefix to use when Focus saves off a focus frame
527QString FocusAdvisor::getFocusFramePrefix()
528{
529 QString prefix;
530 if (inFocusAdvisor() && m_inFindStars)
531 prefix = "_fs_" + QString("%1_%2").arg(m_findStarsRunNum).arg(m_focus->absIterations + 1);
532 else if (inFocusAdvisor() && m_inPreAFAdj)
533 prefix = "_ca_" + QString("%1_%2").arg(m_preAFRunNum).arg(m_focus->absIterations + 1);
534 else if (inFocusAdvisor() && m_focus->inScanStartPos)
535 prefix = "_ssp_" + QString("%1_%2").arg(m_focus->m_AFRun).arg(m_focus->absIterations + 1);
536 return prefix;
537}
538
539// Find similar OTs to seed defaults
540QVariantMap FocusAdvisor::getOTDefaults(const QString &OTName)
541{
542 QVariantMap map;
543
544 // If a blank OTName is passed in return an empty map
545 if (OTName.isEmpty())
546 return map;
547
548 for (auto &tName : OpticalTrainManager::Instance()->getTrainNames())
549 {
550 if (tName == OTName)
551 continue;
552 auto tFocuser = OpticalTrainManager::Instance()->getFocuser(tName);
553 if (tFocuser != m_focus->m_Focuser)
554 continue;
555 auto tScope = OpticalTrainManager::Instance()->getScope(tName);
556 auto tScopeType = tScope["type"].toString();
557 if (tScopeType != m_focus->m_ScopeType)
558 continue;
559
560 // We have an OT with the same Focuser and scope type so see if we have any parameters
561 auto tID = OpticalTrainManager::Instance()->id(tName);
562 OpticalTrainSettings::Instance()->setOpticalTrainID(tID);
563 auto settings = OpticalTrainSettings::Instance()->getOneSetting(OpticalTrainSettings::Focus);
564 if (settings.isValid())
565 {
566 // We have a set of parameters
567 map = settings.toJsonObject().toVariantMap();
568 // We will adjust the step size here
569 // We will use the CFZ. The CFZ scales with f#^2, so adjust step size in the same way
570 auto tAperture = tScope["aperture"].toDouble(-1);
571 auto tFocalLength = tScope["focal_length"].toDouble(-1);
572 auto tFocalRatio = tScope["focal_ratio"].toDouble(-1);
573 auto tReducer = OpticalTrainManager::Instance()->getReducer(tName);
574 if (tFocalLength > 0.0)
575 tFocalLength *= tReducer;
576
577 // Use the adjusted focal length to calculate an adjusted focal ratio
578 if (tFocalRatio <= 0.0)
579 // For a scope, FL and aperture are specified so calc the F#
580 tFocalRatio = (tAperture > 0.001) ? tFocalLength / tAperture : 0.0f;
581 // else if (tAperture < 0.0)
582 // // DSLR Lens. FL and F# are specified so calc the aperture
583 // tAperture = tFocalLength / tFocalRatio;
584
585 int stepSize = 5000;
586 if (m_focus->m_Focuser && m_focus->m_Focuser->getDeviceName() == FOCUSER_SIMULATOR)
587 // The Simulator is a special case so use 5000 as that works well
588 stepSize = 5000;
589 else
590 stepSize = map.value("focusTicks", stepSize).toInt() * pow(m_focus->m_FocalRatio, 2.0) / pow(tFocalRatio, 2.0);
591 // Add the value to map if one doesn't exist or update it if it does
592 map.insert("focusTicks", stepSize);
593 break;
594 }
595 }
596 // Reset Optical Train Manager to the original OT
597 auto id = OpticalTrainManager::Instance()->id(OTName);
598 OpticalTrainSettings::Instance()->setOpticalTrainID(id);
599 return map;
600}
601
602// Returns whether or not the passed in scopeType has a central obstruction or not. The scopeTypes
603// are defined in the equipmentWriter code. It would be better, probably, if that code included
604// a flag for central obstruction, rather than hard coding strings for the scopeType that are compared
605// in this routine.
606bool FocusAdvisor::scopeHasObstruction(const QString &scopeType)
607{
608 return (scopeType != "Refractor" && scopeType != "Kutter (Schiefspiegler)");
609}
610
611// Focus Advisor control function initialiser
612void FocusAdvisor::initControl()
613{
614 setInFocusAdvisor(true);
615 setButtons(true);
616 m_initialStepSize = m_focus->m_OpsFocusMechanics->focusTicks->value();
617 m_initialBacklash = m_focus->m_OpsFocusMechanics->focusBacklash->value();
618 m_initialAFOverscan = m_focus->m_OpsFocusMechanics->focusAFOverscan->value();
619 m_initialUseWeights = m_focus->m_OpsFocusProcess->focusUseWeights->isChecked();
620
621 if (m_inFindStars)
622 initFindStars(m_focus->currentPosition);
623 else if (m_inPreAFAdj)
624 initPreAFAdj(m_focus->currentPosition);
625 else if (m_inAFAdj)
626 initAFAdj(m_focus->currentPosition, false);
627}
628
629// Focus Advisor control function
630void FocusAdvisor::control()
631{
632 if (!inFocusAdvisor())
633 return;
634
635 if (m_inFindStars)
636 findStars();
637 else if (m_inPreAFAdj)
638 preAFAdj();
639 else
640 abort(i18n("Focus Advisor aborted due to internal error"));
641}
642
643// Prepare the Find Stars algorithm
644void FocusAdvisor::initFindStars(const int startPos)
645{
646 // check whether Focus Advisor can run with the current parameters
647 if (!canFocusAdvisorRun())
648 {
649 abort(i18n("Focus Advisor cannot run with current params"));
650 return;
651 }
652
653 focusAdvFindStarsLabel->setText(i18n("In progress..."));
654 emit newStage(FindingStars);
655
656 // Set the initial position, which we'll fallback to in case of failure
657 m_focus->initialFocuserAbsPosition = startPos;
658 m_focus->linearRequestedPosition = startPos;
659
660 // Set useWeights off as it makes the v-graph display unnecessarily complex whilst adding nothing
661 m_focus->m_OpsFocusProcess->focusUseWeights->setChecked(false);
662
663 m_focus->absIterations = 0;
664 m_position.clear();
665 m_measure.clear();
666 m_focus->clearDataPoints();
667 m_jumpsToGo = NUM_JUMPS_PER_SECTOR;
668 m_jumpSize = m_focus->m_OpsFocusMechanics->focusTicks->value() * NUM_JUMPS_PER_SECTOR;
669 m_findStarsIn = false;
670 m_findStarsMaxBound = m_findStarsMinBound = false;
671 m_findStarsSector = 0;
672 m_findStarsRange = false;
673 m_findStarsRangeIn = false;
674 m_findStarsFindInEdge = false;
675 m_findStarsInRange = -1;
676 m_findStarsOutRange = -1;
677 m_findStarsRunNum++;
678
679 // Set backlash and Overscan off as its not needed at this stage - we'll calculate later
680 m_focus->m_OpsFocusMechanics->focusBacklash->setValue(0);
681 m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(0);
682
683 addResultsTable(i18n("Find Stars"), m_findStarsRunNum, startPos, m_jumpSize,
684 m_focus->m_OpsFocusMechanics->focusAFOverscan->value(), "");
685 emit m_focus->setTitle(QString(i18n("Find Stars: Scanning for stars...")), true);
686 if (!m_focus->changeFocus(startPos - m_focus->currentPosition))
687 abort(i18n("Find Stars: Failed"));
688}
689
690// Algorithm to scan the focuser's range of motion to find stars
691// The algorithm is seeded with a start value, jump size and number of jumps and it sweeps out by num jumps,
692// then sweeps in taking a frame and looking for stars. Once some stars have been found it searches the range
693// of motion containing stars to get the central position which is passed as start point to the next stage.
694void FocusAdvisor::findStars()
695{
696 // Plot the datapoint
697 emit m_focus->newHFRPlotPosition(static_cast<double>(m_focus->currentPosition), m_focus->currentMeasure,
698 std::pow(m_focus->currentWeight, -0.5), false, m_jumpSize, true);
699
700 int offset = 0;
701 bool starsExist = starsFound();
702 if (m_findStarsRange)
703 {
704 bool outOfRange = false;
705 if (starsExist)
706 {
707 // We have some stars but check we're not about to run out of range
708 if (m_findStarsRangeIn)
709 outOfRange = (m_focus->currentPosition - m_jumpSize) < static_cast<int>(m_focus->absMotionMin);
710 else
711 outOfRange = (m_focus->currentPosition + m_jumpSize) > static_cast<int>(m_focus->absMotionMax);
712 }
713
714 if (m_findStarsFindInEdge)
715 {
716 if (starsExist)
717 {
718 // We found the inner boundary of stars / no stars
719 m_findStarsFindInEdge = false;
720 m_findStarsInRange = m_focus->currentPosition - m_jumpSize;
721 }
722 }
723 else if (!starsExist && m_findStarsInRange < 0 && m_findStarsOutRange < 0)
724 {
725 // We have 1 side of the stars range, but not the other... so reverse motion to get the other side
726 // Calculate the offset to get back to the start position where stars were found
727 if (m_findStarsRangeIn)
728 {
729 m_findStarsInRange = m_focus->currentPosition;
730 auto max = std::max_element(std::begin(m_position), std::end(m_position));
731 offset = *max - m_focus->currentPosition;
732 }
733 else
734 {
735 m_findStarsOutRange = m_focus->currentPosition;
736 auto min = std::min_element(std::begin(m_position), std::end(m_position));
737 offset = *min - m_focus->currentPosition;
738 }
739 m_findStarsRangeIn = !m_findStarsRangeIn;
740 }
741 else if (!starsExist || outOfRange)
742 {
743 // We're reached the other side of the zone in which stars can be detected so we're done
744 // A good place to use for the next phase will be the centre of the zone
745 m_inFindStars = false;
746 if (m_findStarsRangeIn)
747 // Range for stars is inwards
748 m_findStarsInRange = m_focus->currentPosition;
749 else
750 // Range for stars is outwards
751 m_findStarsOutRange = m_focus->currentPosition;
752 const int zoneCentre = (m_findStarsInRange + m_findStarsOutRange) / 2;
753 focusAdvFindStarsLabel->setText(i18n("Done"));
754 updateResultsTable(i18n("Stars detected, range center %1", QString::number(zoneCentre)));
755 // Now move onto the next stage or stop if nothing more to do
756 if (m_inPreAFAdj)
757 initPreAFAdj(zoneCentre);
758 else if (m_inAFAdj)
759 initAFAdj(zoneCentre, true);
760 else
761 {
762 m_focus->absTicksSpin->setValue(zoneCentre);
763 emit m_focus->setTitle(QString(i18n("Stars detected, range centre %1", zoneCentre)), true);
764 complete(false, i18n("Focus Advisor Find Stars completed"));
765 }
766 return;
767 }
768 }
769
770 // Log the results
771 m_position.push_back(m_focus->currentPosition);
772 m_measure.push_back(m_focus->currentMeasure);
773
774 // Now check if we have any stars
775 if (starsExist)
776 {
777 // We have stars! Now try and find the centre of range where stars exist. We'll be conservative here
778 // and set the range to the point where stars disappear.
779 if (!m_findStarsRange)
780 {
781 m_findStarsRange = true;
782
783 // If stars found first position we don't know where we are in the zone so explore both ends
784 // Otherwise we know where 1 boundary is so we only need to expore the other
785 if (m_position.size() > 1)
786 {
787 if (m_position.last() < m_position[m_position.size() - 2])
788 {
789 // Stars were found whilst moving inwards so we know the outer boundary
790 QVector<int> positionsCopy = m_position;
791 std::sort(positionsCopy.begin(), positionsCopy.end(), std::greater<int>());
792 m_findStarsOutRange = positionsCopy[1];
793 m_findStarsOutRange = m_position[m_position.size() - 2];
794 m_findStarsRangeIn = true;
795 }
796 else
797 {
798 // Stars found whilst moving outwards. Firstly we need to find the inward edge of no stars / stars
799 // so set the position back to the previous max position before the current point.
800 m_findStarsFindInEdge = true;
801 QVector<int> positionsCopy = m_position;
802 std::sort(positionsCopy.begin(), positionsCopy.end(), std::greater<int>());
803 offset = positionsCopy[1] - m_focus->currentPosition;
804 }
805 }
806 }
807 }
808
809 // Cap the maximum number of iterations before failing
810 if (++m_focus->absIterations > MAXIMUM_FOCUS_ADVISOR_ITERATIONS)
811 {
812 abort(i18n("Find Stars: exceeded max iterations %1", MAXIMUM_FOCUS_ADVISOR_ITERATIONS));
813 return;
814 }
815
816 int deltaPos;
817 if (m_findStarsRange)
818 {
819 // Collect more data to find the range of focuser motion with stars
820 emit m_focus->setTitle(QString(i18n("Stars detected, centering range")), true);
821 updateResultsTable(i18n("Stars detected, centering range"));
822 int nextPos;
823 if (m_findStarsRangeIn)
824 nextPos = std::max(m_focus->currentPosition + offset - m_jumpSize, static_cast<int>(m_focus->absMotionMin));
825 else
826 nextPos = std::min(m_focus->currentPosition + offset + m_jumpSize, static_cast<int>(m_focus->absMotionMax));
827 deltaPos = nextPos - m_focus->currentPosition;
828 }
829 else if (m_position.size() == 1)
830 {
831 // No luck with stars at the seed position so jump outwards and start an inward sweep
832 deltaPos = m_jumpSize * m_jumpsToGo;
833 // Check the proposed move is within bounds
834 if (m_focus->currentPosition + deltaPos >= m_focus->absMotionMax)
835 {
836 deltaPos = m_focus->absMotionMax - m_focus->currentPosition;
837 m_jumpsToGo = deltaPos / m_jumpSize + (deltaPos % m_jumpSize != 0);
838 m_findStarsMaxBound = true;
839 }
840 m_findStarsJumpsInSector = m_jumpsToGo;
841 m_findStarsSector = 1;
842 emit m_focus->setTitle(QString(i18n("Find Stars Run %1: No stars at start %2, scanning...", m_findStarsRunNum,
843 m_focus->currentPosition)), true);
844 }
845 else if (m_jumpsToGo > 0)
846 {
847 // Collect more data in the current sweep
848 emit m_focus->setTitle(QString(i18n("Find Stars Run %1 Sector %2: Scanning %3/%4", m_findStarsRunNum, m_findStarsSector,
849 m_jumpsToGo, m_findStarsJumpsInSector)), true);
850 updateResultsTable(i18n("Find Stars Run %1: Scanning Sector %2", m_findStarsRunNum, m_findStarsSector));
851 int nextPos = std::max(m_focus->currentPosition - m_jumpSize, static_cast<int>(m_focus->absMotionMin));
852 deltaPos = nextPos - m_focus->currentPosition;
853 }
854 else
855 {
856 // We've completed the current sweep, but still no stars so check if we still have focuser range to search...
857 if(m_findStarsMaxBound && m_findStarsMinBound)
858 {
859 // We're out of road... covered the entire focuser range of motion but couldn't find any stars
860 // halve the step size and go again
861 updateResultsTable(i18n("No stars detected"));
862 int newStepSize = m_focus->m_OpsFocusMechanics->focusTicks->value() / 2;
863 if (newStepSize > 1)
864 {
865 m_focus->m_OpsFocusMechanics->focusTicks->setValue(newStepSize);
866 initFindStars(m_focus->initialFocuserAbsPosition);
867 }
868 else
869 abort(i18n("Find Stars Run %1: failed to find any stars", m_findStarsRunNum));
870 return;
871 }
872
873 // Setup the next sweep sector...
874 m_jumpsToGo = NUM_JUMPS_PER_SECTOR;
875 if (m_findStarsIn)
876 {
877 // We're "inside" the starting point so flip to the outside unless max bound already hit
878 if (m_findStarsMaxBound)
879 {
880 // Ensure deltaPos doesn't go below minimum
881 if (m_focus->currentPosition - m_jumpSize < static_cast<int>(m_focus->absMotionMin))
882 deltaPos = static_cast<int>(m_focus->absMotionMin) - m_focus->currentPosition;
883 else
884 deltaPos = -m_jumpSize;
885 }
886 else
887 {
888 auto max = std::max_element(std::begin(m_position), std::end(m_position));
889 int sweepMax = *max + (m_jumpSize * m_jumpsToGo);
890 if (sweepMax >= static_cast<int>(m_focus->absMotionMax))
891 {
892 sweepMax = static_cast<int>(m_focus->absMotionMax);
893 m_jumpsToGo = (sweepMax - *max) / m_jumpSize + ((sweepMax - *max) % m_jumpSize != 0);
894 m_findStarsMaxBound = true;
895 }
896 m_findStarsIn = false;
897 deltaPos = sweepMax - m_focus->currentPosition;
898 }
899 }
900 else
901 {
902 // We're "outside" the starting point so continue inwards unless min bound already hit
903 if (m_findStarsMinBound)
904 {
905 auto max = std::max_element(std::begin(m_position), std::end(m_position));
906 int sweepMax = *max + (m_jumpSize * m_jumpsToGo);
907 if (sweepMax >= static_cast<int>(m_focus->absMotionMax))
908 {
909 sweepMax = static_cast<int>(m_focus->absMotionMax);
910 m_jumpsToGo = (sweepMax - *max) / m_jumpSize + ((sweepMax - *max) % m_jumpSize != 0);
911 m_findStarsMaxBound = true;
912 }
913 deltaPos = sweepMax - m_focus->currentPosition;
914 }
915 else
916 {
917 auto min = std::min_element(std::begin(m_position), std::end(m_position));
918 int sweepMin = *min - (m_jumpSize * m_jumpsToGo);
919 if (sweepMin <= static_cast<int>(m_focus->absMotionMin))
920 {
921 // This sweep will hit the min bound
922 m_findStarsMinBound = true;
923 sweepMin = static_cast<int>(m_focus->absMotionMin);
924 m_jumpsToGo = (*min - sweepMin) / m_jumpSize + ((*min - sweepMin) % m_jumpSize != 0);
925 }
926 // We've already done the most inward point of a sweep at the start so jump to the next point.
927 m_findStarsIn = true;
928 int nextJumpPos = std::max(*min - m_jumpSize, static_cast<int>(m_focus->absMotionMin));
929 deltaPos = nextJumpPos - m_focus->currentPosition;
930 }
931 }
932 m_findStarsSector++;
933 m_findStarsJumpsInSector = m_jumpsToGo;
934 emit m_focus->setTitle(QString(i18n("Find Stars Run %1 Sector %2: scanning %3/%4", m_findStarsRunNum, m_findStarsSector,
935 m_jumpsToGo, m_findStarsJumpsInSector)), true);
936 }
937 if (!m_findStarsRange)
938 m_jumpsToGo--;
939 m_focus->linearRequestedPosition = m_focus->currentPosition + deltaPos;
940 if (!m_focus->changeFocus(deltaPos))
941 abort(i18n("Focus Advisor Find Stars run %1: failed to move focuser", m_findStarsRunNum));
942}
943
944bool FocusAdvisor::starsFound()
945{
946 return (m_focus->currentMeasure != INVALID_STAR_MEASURE && m_focus->currentNumStars > FIND_STARS_MIN_STARS);
947
948}
949
950// Initialise the pre-Autofocus adjustment algorithm
951void FocusAdvisor::initPreAFAdj(const int startPos)
952{
953 // check whether Focus Advisor can run with the current parameters
954 if (!canFocusAdvisorRun())
955 {
956 abort(i18n("Focus Advisor cannot run with current params"));
957 return;
958 }
959
960 // Check we're not looping
961 if (m_preAFRunNum > 50)
962 {
963 abort(i18n("Focus Advisor Coarse Adjustment aborted after %1 runs", m_preAFRunNum));
964 return;
965 }
966
967 focusAdvCoarseAdjLabel->setText(i18n("In progress..."));
968 emit newStage(CoarseAdjustments);
969
970 m_focus->initialFocuserAbsPosition = startPos;
971 m_focus->absIterations = 0;
972 m_position.clear();
973 m_measure.clear();
974 m_preAFInner = 0;
975 m_preAFNoStarsOut = m_preAFNoStarsIn = false;
976 m_preAFRunNum++;
977
978 // Reset the v-curve - otherwise there's too much data to see what's going on
979 m_focus->clearDataPoints();
980 emit m_focus->setTitle(QString(i18n("Coarse Adjustment Scan...")), true);
981
982 // Setup a sweep of m_jumpSize either side of startPos
983 m_jumpSize = m_focus->m_OpsFocusMechanics->focusTicks->value() * NUM_STEPS_PRE_AF;
984
985 // Check that the sweep can fit into the focuser's motion range
986 if (m_jumpSize > m_focus->absMotionMax - m_focus->absMotionMin)
987 {
988 m_jumpSize = m_focus->absMotionMax - m_focus->absMotionMin;
989 m_focus->m_OpsFocusMechanics->focusTicks->setValue(m_jumpSize / NUM_STEPS_PRE_AF);
990 }
991
992 int deltaPos = (startPos - m_focus->currentPosition) + m_jumpSize / 2;
993 if (m_focus->currentPosition + deltaPos > maxStarsLimit())
994 deltaPos = maxStarsLimit() - m_focus->currentPosition;
995
996 m_preAFInner = startPos - m_jumpSize / 2;
997 if (m_preAFInner < minStarsLimit())
998 m_preAFInner = minStarsLimit();
999
1000 // Set backlash and AF Overscan off on first run, and reset useWeights
1001 if (m_preAFRunNum == 1)
1002 {
1003 m_focus->m_OpsFocusMechanics->focusBacklash->setValue(0);
1004 m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(0);
1005 m_focus->m_OpsFocusProcess->focusUseWeights->setChecked(m_initialUseWeights);
1006 }
1007
1008 addResultsTable(i18n("Coarse Adjustment"), m_preAFRunNum, startPos,
1009 m_focus->m_OpsFocusMechanics->focusTicks->value(),
1010 m_focus->m_OpsFocusMechanics->focusAFOverscan->value(), "");
1011
1012 m_focus->linearRequestedPosition = m_focus->currentPosition + deltaPos;
1013 if (!m_focus->changeFocus(deltaPos))
1014 abort(i18n("Focus Advisor Coarse Adjustment failed to move focuser"));
1015}
1016
1017// Pre Autofocus coarse adjustment algorithm.
1018// Move the focuser until we get a reasonable movement in measure (x2)
1019void FocusAdvisor::preAFAdj()
1020{
1021 // Cap the maximum number of iterations before failing
1022 if (++m_focus->absIterations > MAXIMUM_FOCUS_ADVISOR_ITERATIONS)
1023 {
1024 abort(i18n("Focus Advisor Coarse Adjustment: exceeded max iterations %1", MAXIMUM_FOCUS_ADVISOR_ITERATIONS));
1025 return;
1026 }
1027
1028 int deltaPos;
1029 const int step = m_focus->m_OpsFocusMechanics->focusTicks->value();
1030
1031 bool starsExist = starsFound();
1032 if (starsExist)
1033 {
1034 // If we have stars, persist the results for later analysis
1035 m_position.push_back(m_focus->currentPosition);
1036 m_measure.push_back(m_focus->currentMeasure);
1037
1038 if (m_preAFNoStarsOut && (m_position.size() == 0))
1039 {
1040 if (m_findStarsOutRange < 0)
1041 m_findStarsOutRange = m_focus->currentPosition;
1042 else
1043 m_findStarsOutRange = std::max(m_findStarsOutRange, m_focus->currentPosition);
1044 }
1045 }
1046 else
1047 {
1048 // No stars - record whether this is at the inward or outward. If in the middle, just ignore
1049 if (m_position.size() < 2)
1050 m_preAFNoStarsOut = true;
1051 else if (m_focus->currentPosition - (2 * step) <= m_preAFInner)
1052 {
1053 m_preAFNoStarsIn = true;
1054 if (m_findStarsInRange < 0)
1055 m_findStarsInRange = m_position.last();
1056 else
1057 m_findStarsInRange = std::min(m_findStarsInRange, m_position.last());
1058 }
1059 }
1060
1061 emit m_focus->newHFRPlotPosition(static_cast<double>(m_focus->currentPosition), m_focus->currentMeasure,
1062 std::pow(m_focus->currentWeight, -0.5), false, step, true);
1063
1064 // See if we need to extend the sweep
1065 if (m_focus->currentPosition - step < m_preAFInner && starsExist)
1066 {
1067 // Next step would take us beyond our bound, so see if we have enough data or want to extend the sweep
1068 auto it = std::min_element(std::begin(m_measure), std::end(m_measure));
1069 auto min = std::distance(std::begin(m_measure), it);
1070 if (m_position.size() < 5 || (m_position.size() < 2 * NUM_STEPS_PRE_AF && m_position.size() - min < 3))
1071 {
1072 // Not much data or minimum is at the edge so continue for a bit, if we can
1073 if (m_preAFInner - step >= minStarsLimit())
1074 m_preAFInner -= step;
1075 }
1076 }
1077
1078 if (m_focus->currentPosition - step >= m_preAFInner)
1079 {
1080 // Collect more data in the current sweep
1081 emit m_focus->setTitle(QString(i18n("Coarse Adjustment Run %1 scan...", m_preAFRunNum)), true);
1082 deltaPos = -step;
1083 }
1084 else
1085 {
1086 // We've completed the current sweep, so analyse the data...
1087 if (m_position.size() < 5)
1088 {
1089 abort(i18n("Focus Advisor Coarse Adjustment Run %1: insufficient data to proceed", m_preAFRunNum));
1090 return;
1091 }
1092 else
1093 {
1094 auto it = std::min_element(std::begin(m_measure), std::end(m_measure));
1095 auto min = std::distance(std::begin(m_measure), it);
1096 const double minMeasure = *it;
1097 int minPos = m_position[min];
1098
1099 auto it2 = std::max_element(std::begin(m_measure), std::end(m_measure));
1100 const double maxMeasure = *it2;
1101 // Get a ratio of max to min scaled to NUM_STEPS_PRE_AF
1102 const double scaling = static_cast<double>(NUM_STEPS_PRE_AF) / static_cast<double>(m_measure.count());
1103 const double measureRatio = maxMeasure / minMeasure * scaling;
1104
1105 // Is the minimum near the centre of the sweep?
1106 double whereInRange = static_cast<double>(minPos - m_position.last()) / static_cast<double>
1107 (m_position.first() - m_position.last());
1108 bool nearCenter = whereInRange > 0.3 && whereInRange < 0.7;
1109
1110 QVector<double> gradients;
1111 for (int i = 0; i < m_position.size() - 1; i++)
1112 {
1113 double gradient = (m_measure[i] - m_measure[i + 1]) / (m_position[i] - m_position[i + 1]);
1114 gradients.push_back(std::abs(gradient));
1115 }
1116
1117 // Average the largest 3 gradients (to stop distortion by a single value). The largest gradients should occur
1118 // at the furthest out position. Assume smaller gradients at furthest out position are caused by backlash
1119 QVector<double> gradientsCopy = gradients;
1120 std::sort(gradientsCopy.begin(), gradientsCopy.end(), std::greater<double>());
1121 std::vector<double> gradientsMax;
1122 for (int i = 0; i < 3; i++)
1123 gradientsMax.push_back(gradientsCopy[i]);
1124
1125 double gradientsMean = Mathematics::RobustStatistics::ComputeLocation(Mathematics::RobustStatistics::LOCATION_MEAN,
1126 gradientsMax);
1127
1128 const double threshold = gradientsMean * 0.5;
1129 int overscan = m_focus->m_OpsFocusMechanics->focusAFOverscan->value();
1130 for (int i = 0; i < gradients.size(); i++)
1131 {
1132 if (gradients[i] <= threshold)
1133 overscan += m_position[i] - m_position[i + 1];
1134 else
1135 break;
1136 }
1137 overscan = std::max(overscan, step);
1138 m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(overscan);
1139
1140 const bool hitNoStarsRegion = m_preAFNoStarsIn || m_preAFNoStarsOut;
1141
1142 // Is everything good enough to proceed, or do we need to run again?
1143 if (nearCenter && maxMinRatioOK(INITIAL_MAXMIN_HFR_RATIO, measureRatio) && !hitNoStarsRegion)
1144 {
1145 // We're done with the coarse adjustment step so prepare for the next step
1146 updateResultsTable(i18n("Max/Min Ratio: %1", QString::number(measureRatio, 'f', 1)));
1147 m_inPreAFAdj = false;
1148 focusAdvCoarseAdjLabel->setText(i18n("Done"));
1149 m_focus->absIterations = 0;
1150 m_position.clear();
1151 m_measure.clear();
1152 if (m_inAFAdj)
1153 {
1154 // Reset the v-curve - otherwise there's too much data to see what's going on
1155 m_focus->clearDataPoints();
1156 // run Autofocus
1157 m_nearFocus = true;
1158 initAFAdj(minPos, true);
1159 }
1160 else
1161 {
1162 m_focus->absTicksSpin->setValue(minPos);
1163 complete(false, i18n("Focus Advisor Coarse Adjustment completed."));
1164 }
1165 return;
1166 }
1167 else
1168 {
1169 // Curve is too flat / steep - so we need to change the range, select a better start position and rerun...
1170 int startPosition;
1171 const double expansion = TARGET_MAXMIN_HFR_RATIO / measureRatio;
1172 int newStepSize = m_focus->m_OpsFocusMechanics->focusTicks->value() * expansion;
1173
1174 if (m_preAFNoStarsIn && m_preAFNoStarsOut)
1175 {
1176 // We have no stars both inwards and outwards
1177 const int range = m_position.first() - m_position.last();
1178 newStepSize = range / NUM_STEPS_PRE_AF;
1179 startPosition = (m_position.first() + m_position.last()) / 2;
1180 m_preAFMaxRange = true;
1181 if (newStepSize < 1)
1182 {
1183 // Looks like data is inconsistent so stop here
1184 abort(i18n("Focus Advisor Coarse Adjustment: data quality too poor to continue"));
1185 return;
1186 }
1187 }
1188 else if (m_preAFNoStarsIn)
1189 {
1190 // Shift start position outwards as we had no stars inwards
1191 int range = NUM_STEPS_PRE_AF * newStepSize;
1192 int jumpPosition = m_position.last() + range;
1193 if (jumpPosition > maxStarsLimit())
1194 {
1195 range = maxStarsLimit() - m_position.last();
1196 newStepSize = range / NUM_STEPS_PRE_AF;
1197 m_preAFMaxRange = true;
1198 }
1199 startPosition = m_position.last() + (range / 2);
1200 }
1201 else if (m_preAFNoStarsOut)
1202 {
1203 // Shift start position inwards as we had no stars outwards
1204 int range = NUM_STEPS_PRE_AF * newStepSize;
1205 int endPosition = m_position.first() - range;
1206 if (endPosition < minStarsLimit())
1207 {
1208 range = m_position.first() - minStarsLimit();
1209 newStepSize = range / NUM_STEPS_PRE_AF;
1210 m_preAFMaxRange = true;
1211 }
1212 startPosition = m_position.first() - (range / 2);
1213 }
1214 else
1215 // Set the start position to the previous minimum
1216 startPosition = minPos;
1217
1218 updateResultsTable(i18n("Max/Min Ratio: %1, Next Step Size: %2, Next Overscan: %3", QString::number(measureRatio, 'f', 1),
1219 QString::number(newStepSize), QString::number(overscan)));
1220 m_focus->m_OpsFocusMechanics->focusTicks->setValue(newStepSize);
1221 initPreAFAdj(startPosition);
1222 return;
1223 }
1224 }
1225 }
1226 m_focus->linearRequestedPosition = m_focus->currentPosition + deltaPos;
1227 if (!m_focus->changeFocus(deltaPos))
1228 abort(i18n("Focus Advisor Coarse Adjustment failed to move focuser"));
1229}
1230
1231// Check whether the Max / Min star measure ratio is good enough
1232bool FocusAdvisor::maxMinRatioOK(const double limit, const double maxMinRatio)
1233{
1234 if (m_preAFMaxRange)
1235 // We've hit the maximum focuser range where we have stars so go with what we've got in terms of maxMinRatio
1236 return true;
1237 return maxMinRatio >= limit;
1238}
1239
1240// Minimum focuser position where stars exist - if unsure about stars return min focuser position
1241int FocusAdvisor::minStarsLimit()
1242{
1243 return std::max(static_cast<int>(m_focus->absMotionMin), m_findStarsInRange);
1244}
1245
1246// Maximum focuser position where stars exist - if unsure about stars return max focuser position
1247int FocusAdvisor::maxStarsLimit()
1248{
1249 if (m_findStarsOutRange < 0)
1250 return m_focus->absMotionMax;
1251 else
1252 return std::min(static_cast<int>(m_focus->absMotionMax), m_findStarsOutRange);
1253}
1254
1255void FocusAdvisor::initAFAdj(const int startPos, const bool retryOverscan)
1256{
1257 // check whether Focus Advisor can run with the current parameters
1258 if (!canFocusAdvisorRun())
1259 {
1260 abort(i18n("Focus Advisor cannot run with current params"));
1261 return;
1262 }
1263
1264 focusAdvFineAdjLabel->setText(i18n("In progress..."));
1265 emit newStage(FineAdjustments);
1266
1267 // The preAF routine will have estimated AF Overscan but because its a crude measure its likely to be an overestimate.
1268 // We will try and refine the estimate by halving the current Overscan
1269 if (retryOverscan)
1270 {
1271 const int newOverscan = m_focus->m_OpsFocusMechanics->focusAFOverscan->value() / 2;
1272 m_focus->m_OpsFocusMechanics->focusBacklash->setValue(0);
1273 m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(newOverscan);
1274 }
1275
1276 // Reset useWeights setting
1277 m_focus->m_OpsFocusProcess->focusUseWeights->setChecked(m_initialUseWeights);
1278
1279 addResultsTable(i18n("Fine Adjustment"), ++m_AFRunCount, startPos,
1280 m_focus->m_OpsFocusMechanics->focusTicks->value(),
1281 m_focus->m_OpsFocusMechanics->focusAFOverscan->value(), "");
1282
1283 startAF(startPos);
1284}
1285
1286void FocusAdvisor::startAF(const int startPos)
1287{
1288 if (m_nearFocus)
1289 {
1290 setInFocusAdvisor(false);
1291 m_focus->absIterations = 0;
1292 m_focus->setupLinearFocuser(startPos);
1293 if (!m_focus->changeFocus(m_focus->linearRequestedPosition - m_focus->currentPosition))
1294 m_focus->completeFocusProcedure(Ekos::FOCUS_ABORTED, Ekos::FOCUS_FAIL_FOCUSER_NO_MOVE);
1295 }
1296 else
1297 {
1298 m_nearFocus = true;
1299 m_focus->initScanStartPos(true, startPos);
1300 }
1301}
1302
1303bool FocusAdvisor::analyseAF()
1304{
1305 if (m_focus->m_FocusAlgorithm != Focus::FOCUS_LINEAR1PASS || !m_focus->linearFocuser || !m_focus->linearFocuser->isDone()
1306 || m_focus->linearFocuser->solution() == -1)
1307 return false;
1308
1309 bool runAgainRatio = false;
1310 QVector<int> positions;
1311 QVector<double> measures, weights;
1312 QVector<bool> outliers;
1313 m_focus->linearFocuser->getPass1Measurements(&positions, &measures, &weights, &outliers);
1314
1315 int minPosition = m_focus->linearFocuser->solution();
1316 double minMeasure = m_focus->linearFocuser->solutionValue();
1317
1318 int maxPositon = positions[0];
1319 double maxMeasure = m_focus->curveFitting->f(maxPositon);
1320
1321 const int stepSize = m_focus->m_OpsFocusMechanics->focusTicks->value();
1322 int newStepSize = stepSize;
1323 // Firstly check that the step size is giving a good measureRatio
1324 double measureRatio = maxMeasure / minMeasure;
1325 if (measureRatio > 2.5 && measureRatio < 3.5)
1326 // Sweet spot
1327 runAgainRatio = false;
1328 else
1329 {
1330 runAgainRatio = true;
1331 // Adjust the step size to try and get the measureRatio around 3
1332 int pos = m_focus->curveFitting->fy(minMeasure * TARGET_MAXMIN_HFR_RATIO);
1333 newStepSize = (pos - minPosition) / ((positions.size() - 1.0) / 2.0);
1334 // Throttle newStepSize. Usually this stage should be close to good parameters so changes in step size
1335 // should be small, but if run with poor parameters changes should be throttled to prevent big swings that
1336 // can lead to Autofocus failure.
1337 double ratio = static_cast<double>(newStepSize) / static_cast<double>(stepSize);
1338 ratio = std::max(std::min(ratio, 2.0), 0.5);
1339 newStepSize = stepSize * ratio;
1340 m_focus->m_OpsFocusMechanics->focusTicks->setValue(newStepSize);
1341 }
1342
1343 // Look at the backlash
1344 // So assume flatness of curve at the outward point is all due to backlash.
1345 if (!m_overscanFound)
1346 {
1347 double backlashPoints = 0.0;
1348 for (int i = 0; i < positions.size() / 2; i++)
1349 {
1350 double deltaAct = measures[i] - measures[i + 1];
1351 double deltaExp = m_focus->curveFitting->f(positions[i]) - m_focus->curveFitting->f(positions[i + 1]);
1352 double delta = std::abs(deltaAct / deltaExp);
1353 // May have to play around with this threshold
1354 if (delta > 0.75)
1355 break;
1356 if (delta > 0.5)
1357 backlashPoints += 0.5;
1358 else
1359 backlashPoints++;
1360 }
1361
1362 const int overscan = m_focus->m_OpsFocusMechanics->focusAFOverscan->value();
1363 int newOverscan = overscan;
1364
1365 if (backlashPoints > 0.0)
1366 {
1367 // We've found some additional Overscan so we know the current value is too low and now have a reasonable estimate
1368 newOverscan = overscan + (stepSize * backlashPoints);
1369 m_overscanFound = true;
1370 }
1371 else if (overscan == 0)
1372 m_overscanFound = true;
1373 else if (!m_overscanFound)
1374 // No additional Overscan was detected so the current Overscan estimate may be too high so try reducing it
1375 newOverscan = overscan <= 2 * stepSize ? 0 : overscan / 2;
1376
1377 m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(newOverscan);
1378 }
1379
1380 // Try again for a poor R2 - but retry just once (unless something else changes so we don't get stuck in a loop
1381 if (m_runAgainR2)
1382 m_runAgainR2 = false;
1383 else
1384 m_runAgainR2 = m_focus->R2 < m_focus->m_OpsFocusProcess->focusR2Limit->value();
1385 bool runAgain = runAgainRatio || m_runAgainR2 || !m_overscanFound;
1386
1387 updateResultsTable(i18n("Max/Min Ratio: %1, R2: %2, Step Size: %3, Overscan: %4", QString::number(measureRatio, 'f', 1),
1388 QString::number(m_focus->R2, 'f', 3), QString::number(newStepSize),
1389 QString::number(m_focus->m_OpsFocusMechanics->focusAFOverscan->value())));
1390 if (!runAgain)
1391 {
1392 m_inAFAdj = false;
1393 focusAdvFineAdjLabel->setText(i18n("Done"));
1394 complete(true, i18n("Focus Advisor Fine Adjustment completed"));
1395 emit newStage(Idle);
1396 }
1397 return runAgain;
1398}
1399
1400// Reset the Focus Advisor
1401void FocusAdvisor::reset()
1402{
1403 m_inFocusAdvisor = false;
1404 m_initialStepSize = -1;
1405 m_initialBacklash = -1;
1406 m_initialAFOverscan = -1;
1407 m_initialUseWeights = false;
1408 m_initialScanStartPos = false;
1409 m_position.clear();
1410 m_measure.clear();
1411 m_inFindStars = false;
1412 m_inPreAFAdj = false;
1413 m_inAFAdj = false;
1414 m_jumpsToGo = 0;
1415 m_jumpSize = 0;
1416 m_findStarsIn = false;
1417 m_findStarsMaxBound = false;
1418 m_findStarsMinBound = false;
1419 m_findStarsSector = 0;
1420 m_findStarsRunNum = 0;
1421 m_findStarsRange = false;
1422 m_findStarsRangeIn = false;
1423 m_findStarsFindInEdge = false;
1424 m_findStarsInRange = -1;
1425 m_findStarsOutRange = -1;
1426 m_preAFInner = 0;
1427 m_preAFNoStarsOut = false;
1428 m_preAFNoStarsIn = false;
1429 m_preAFMaxRange = false;
1430 m_preAFRunNum = 0;
1431 m_overscanFound = false;
1432 m_runAgainR2 = false;
1433 m_nearFocus = false;
1434 m_AFRunCount = 0;
1435 setButtons(false);
1436 focusAdvUpdateParamsLabel->setText("");
1437 focusAdvFindStarsLabel->setText("");
1438 focusAdvCoarseAdjLabel->setText("");
1439 focusAdvFineAdjLabel->setText("");
1440}
1441
1442// Abort the Focus Advisor
1443void FocusAdvisor::abort(const QString &msg)
1444{
1445 m_focus->appendLogText(msg);
1446
1447 // Restore settings to initial value
1448 resetSavedSettings(false);
1449 m_focus->processAbort();
1450}
1451
1452// Focus Advisor completed successfully
1453// If Autofocus was run then do the usual processing / notification of success, otherwise treat it as an autofocus fail
1454void FocusAdvisor::complete(const bool autofocus, const QString &msg)
1455{
1456 m_focus->appendLogText(msg);
1457 // Restore settings to initial value
1458 resetSavedSettings(true);
1459
1460 if (!autofocus)
1461 {
1462 if (m_initialBacklash > -1) m_focus->m_OpsFocusMechanics->focusBacklash->setValue(m_initialBacklash);
1463 if (m_initialAFOverscan > -1) m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(m_initialAFOverscan);
1464 m_focus->completeFocusProcedure(Ekos::FOCUS_IDLE, Ekos::FOCUS_FAIL_ADVISOR_COMPLETE);
1465 }
1466}
1467
1468void FocusAdvisor::resetSavedSettings(const bool success)
1469{
1470 m_focus->m_OpsFocusProcess->focusUseWeights->setChecked(m_initialUseWeights);
1471 m_focus->m_OpsFocusProcess->focusScanStartPos->setChecked(m_initialScanStartPos);
1472
1473 if (!success)
1474 {
1475 // Restore settings to initial value since Focus Advisor failed
1476 if (m_initialStepSize > -1) m_focus->m_OpsFocusMechanics->focusTicks->setValue(m_initialStepSize);
1477 if (m_initialBacklash > -1) m_focus->m_OpsFocusMechanics->focusBacklash->setValue(m_initialBacklash);
1478 if (m_initialAFOverscan > -1) m_focus->m_OpsFocusMechanics->focusAFOverscan->setValue(m_initialAFOverscan);
1479 }
1480}
1481
1482// Add a new row to the results table
1483void FocusAdvisor::addResultsTable(QString section, int run, int startPos, int stepSize, int overscan, QString text)
1484{
1485 m_focus->appendLogText(i18n("Focus Advisor Result (%1): Run: %2 startPos: %3 stepSize: %4 overscan: %5",
1486 section, run, startPos, stepSize, overscan));
1487
1488 focusAdvTable->insertRow(0);
1489 QTableWidgetItem *itemSection = new QTableWidgetItem(section);
1490 focusAdvTable->setItem(0, RESULTS_SECTION, itemSection);
1491 QString runStr = (run >= 0) ? QString("%1").arg(run) : "N/A";
1492 QTableWidgetItem *itemRunNumber = new QTableWidgetItem(runStr);
1494 focusAdvTable->setItem(0, RESULTS_RUN_NUMBER, itemRunNumber);
1495 QString startPosStr = (startPos >= 0) ? QString("%1").arg(startPos) : "N/A";
1496 QTableWidgetItem *itemStartPos = new QTableWidgetItem(startPosStr);
1498 focusAdvTable->setItem(0, RESULTS_START_POSITION, itemStartPos);
1499 QString stepSizeStr = (stepSize >= 0) ? QString("%1").arg(stepSize) : "N/A";
1500 QTableWidgetItem *itemStepSize = new QTableWidgetItem(stepSizeStr);
1502 focusAdvTable->setItem(0, RESULTS_STEP_SIZE, itemStepSize);
1503 QString overscanStr = (stepSize >= 0) ? QString("%1").arg(overscan) : "N/A";
1504 QTableWidgetItem *itemAFOverscan = new QTableWidgetItem(overscanStr);
1506 focusAdvTable->setItem(0, RESULTS_AFOVERSCAN, itemAFOverscan);
1507 QTableWidgetItem *itemText = new QTableWidgetItem(text);
1508 focusAdvTable->setItem(0, RESULTS_TEXT, itemText);
1509
1510 emit newMessage(text);
1511
1512 if (focusAdvTable->rowCount() == 1)
1513 {
1514 focusAdvTable->show();
1515 resizeDialog();
1516 }
1517}
1518
1519// Update text for current row (0) in the results table with the passed in value
1520void FocusAdvisor::updateResultsTable(QString text)
1521{
1522 m_focus->appendLogText(i18n("Focus Advisor Result Update: %1", text));
1523
1524 QTableWidgetItem *itemText = new QTableWidgetItem(text);
1525 focusAdvTable->setItem(0, RESULTS_TEXT, itemText);
1526 focusAdvTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
1527}
1528
1529void FocusAdvisor::resizeDialog()
1530{
1531 focusAdvTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
1532 int left, right, top, bottom;
1533 this->verticalLayout->layout()->getContentsMargins(&left, &top, &right, &bottom);
1534
1535 int width = left + right;
1536 for (int i = 0; i < focusAdvTable->horizontalHeader()->count(); i++)
1537 width += focusAdvTable->columnWidth(i);
1538 const int height = focusAdvGroupBox->height() + focusAdvTable->height() + focusAdvButtonBox->height();
1539 focusAdvTable->horizontalHeader()->height() + focusAdvTable->rowHeight(0);
1540 this->resize(width, height);
1541}
1542}
QString i18n(const char *text, const TYPE &arg...)
Ekos is an advanced Astrophotography tool for Linux.
Definition align.cpp:83
void clicked(bool checked)
void stateChanged(int state)
int pointSize() const const
void setBold(bool enable)
void setPointSize(int pointSize)
void setUnderline(bool enable)
iterator begin()
iterator end()
void push_back(parameter_type value)
qsizetype size() const const
QString arg(Args &&... args) const const
bool isEmpty() const const
QString number(double n, char format, int precision)
AlignRight
QTextStream & left(QTextStream &stream)
QTextStream & right(QTextStream &stream)
QFont font() const const
void setFont(const QFont &font)
void setText(const QString &text)
void setTextAlignment(Qt::Alignment alignment)
void setToolTip(const QString &toolTip)
QFuture< void > map(Iterator begin, Iterator end, MapFunctor &&function)
QFuture< T > run(Function function,...)
QFuture< ArgsType< Signal > > connect(Sender *sender, Signal signal)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Nov 29 2024 11:57:48 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.