API
psfAcq.hpp
Go to the documentation of this file.
1 /** \file psfAcq.hpp
2  * \brief The MagAO-X PSF Fitter application header
3  *
4  * \ingroup psfAcq_files
5  */
6 
7 #ifndef psfAcq_hpp
8 #define psfAcq_hpp
9 
10 #include "../../libMagAOX/libMagAOX.hpp" //Note this is included on command line to trigger pch
11 #include "../../magaox_git_version.h"
12 
13 #include <mx/math/fit/fitGaussian.hpp>
14 #include <mx/improc/imageFilters.hpp>
15 
16 /** \defgroup psfAcq
17  * \brief The MagAO-X PSF fitter.
18  *
19  * <a href="../handbook/operating/software/apps/psfAcq.html">Application Documentation</a>
20  *
21  * \ingroup apps
22  *
23  */
24 
25 /** \defgroup psfAcq_files
26  * \ingroup psfAcq
27  */
28 
29 namespace MagAOX
30 {
31 namespace app
32 {
33 
34 struct darkShmimT
35 {
36  static std::string configSection()
37  {
38  return "darkShmim";
39  };
40 
41  static std::string indiPrefix()
42  {
43  return "dark";
44  };
45 };
46 
47 struct Star
48 {
49 public:
50 
51  float x, y; // Star coordinates
52  float max; // Star brightness
53  float fwhm; // Star FWHM
54  float seeing; // Star's seeing
55 
56 private:
57 
58  pcf::IndiProperty * m_prop {nullptr};
59 
60 public:
61 
62  pcf::IndiProperty & prop()
63  {
64  if(m_prop == nullptr)
65  {
66  throw std::runtime_error("attempt to access nullptr prop");
67  }
68 
69  return *m_prop;
70  }
71 
72  void allocate()
73  {
74  m_prop = new pcf::IndiProperty;
75  }
76 
77  void deallocate()
78  {
79  pcf::IndiProperty * mp = m_prop;
80  m_prop = nullptr;
81  delete mp;
82  }
83 
84 
85 };
86 
87 /// The MagAO-X PSF Fitter
88 /**
89  * \ingroup psfAcq
90  */
91 class psfAcq : public MagAOXApp<true>,
92  public dev::shmimMonitor<psfAcq>,
93  public dev::shmimMonitor<psfAcq, darkShmimT>
94 {
95  // Give the test harness access.
96  friend class psfAcq_test;
97 
98  friend class dev::shmimMonitor<psfAcq>;
99  friend class dev::shmimMonitor<psfAcq, darkShmimT>;
100 
101  public:
102  // The base shmimMonitor type
104 
106 
107  /// Floating point type in which to do all calculations.
108  typedef float realT;
109 
110  /** \name app::dev Configurations
111  *@{
112  */
113  ///@}
114 
115  protected:
116  /** \name Configurable Parameters
117  *@{
118  */
119 
120  std::string m_fpsSource; ///< Device name for getting fps if time-based averaging is used. This device should have
121  ///< *.fps.current.
122 
123  uint16_t m_fitCircBuffMaxLength{ 3600 }; ///< Maximum length of the latency measurement circular buffers
124  float m_fitCircBuffMaxTime{ 5 }; ///< Maximum time of the latency meaurement circular buffers
125 
126  float m_fwhmGuess{ 4 };
127  ///@}
128 
129  mx::improc::eigenImage<float> m_image;
130  mx::improc::eigenImage<float> m_sm;
131 
132  mx::improc::eigenImage<float> m_dark;
133 
134  double m_acqQuitTime {0};
135  double m_acqPauseTime{2};
136 
138  bool m_updated{ false };
139  float m_x{ 0 };
140  float m_y{ 0 };
141  int m_max_loops{ 5 }; // default to detecting a max of 5 stars
142  int m_zero_area{ 8 }; // default to zeroing an 8x8 pixel area around stars it finds
143  float m_threshold = { 7.0 }; // how many sigma away from the mean you want to classify a detection, default to
144  // 7sigma
145  float m_fwhm_threshold = { 4.0 }; // minumum fwhm to consider something a star
146  float m_max_fwhm = { 40.0 }; // max fwhm to consider a star
147 
148  std::vector<float> m_first_x_vals = {};
149  std::vector<float> m_first_y_vals = {};
150  std::vector<Star> m_detectedStars; // vector to store all the stars and properties
151 
152  float m_dx{ 0 };
153  float m_dy{ 0 };
154 
155  double m_plate_scale = .0795336;
156  int m_old_num_stars{ 0 };
157  int m_num_stars{ 0 };
158  float m_seeing{ 0 };
159  int m_acquire_star{ -1 }; // Testing for user to select star
160  int m_x_center{}; // 'center' of image or hot spot
161  int m_y_center{};
162 
163  float m_fps{ 0 };
164 
165  void resetAcq(); // class member for resetAcq function
166  void reportSeeing(); // class member for reportSeeing function
167 
168  // Working memory for poke fitting
169  mx::math::fit::fitGaussian2Dsym<float> m_gfit;
170 
171  public:
172  /// Default c'tor.
173  psfAcq();
174 
175  /// D'tor, declared and defined for noexcept.
176  ~psfAcq() noexcept;
177 
178  virtual void setupConfig();
179 
180  /// Implementation of loadConfig logic, separated for testing.
181  /** This is called by loadConfig().
182  */
183  int loadConfigImpl(
184  mx::app::appConfigurator &_config /**< [in] an application configuration from which to load values*/ );
185 
186  virtual void loadConfig();
187 
188  /// Startup function
189  /**
190  *
191  */
192  virtual int appStartup();
193 
194  /// Implementation of the FSM for psfAcq.
195  /**
196  * \returns 0 on no critical error
197  * \returns -1 on an error requiring shutdown
198  */
199  virtual int appLogic();
200 
201  /// Shutdown the app.
202  /**
203  *
204  */
205  virtual int appShutdown();
206 
207  // shmimMonitor interface:
208  int allocate( const dev::shmimT & );
209 
210  int processImage( void *curr_src, const dev::shmimT & );
211 
212  // shmimMonitor interface for referenc:
213  int allocate( const darkShmimT & );
214 
215  int processImage( void *curr_src, const darkShmimT & );
216 
217  protected:
218  std::mutex m_imageMutex;
219 
220  protected:
221  /** \name INDI
222  * @{
223  */
224 
225  // Testing for num stars prop
226  pcf::IndiProperty m_indiP_num_stars;
227  pcf::IndiProperty m_indiP_seeing;
228 
229  pcf::IndiProperty m_indiP_fpsSource;
231 
232  // Testing for user to select star
233  pcf::IndiProperty m_indiP_acquire_star;
235 
236  // toggling
237  pcf::IndiProperty m_indiP_restartAcq;
239 
240  pcf::IndiProperty m_indiP_calcSeeing;
242 
243  ///@}
244 
245  /** \name Telemeter Interface
246  *
247  * @{
248  */
250 
251  int recordTelem( const telem_fgtimings * );
252 
253  ///@}
254 };
255 
256 inline psfAcq::psfAcq() : MagAOXApp( MAGAOX_CURRENT_SHA1, MAGAOX_REPO_MODIFIED )
257 {
259  return;
260 }
261 
262 inline psfAcq::~psfAcq() noexcept
263 {
264  for(size_t n = 0; n < m_detectedStars.size(); ++n)
265  {
266  m_detectedStars[n].deallocate();
267  }
268 }
269 
270 inline void psfAcq::setupConfig()
271 {
272  shmimMonitorT::setupConfig( config );
274 
275  config.add(
276  "fitter.fpsSource",
277  "",
278  "fitter.fpsSource",
279  argType::Required,
280  "fitter",
281  "fpsSource",
282  false,
283  "string",
284  "Device name for getting fps if time-based averaging is used. This device should have *.fps.current." );
285  config.add( "fitter.max_loops",
286  "",
287  "fitter.max_loops",
288  argType::Required,
289  "fitter",
290  "max_loops",
291  false,
292  "int",
293  "Setting the number of stars to detect in processImage function." );
294  config.add( "fitter.zero_area",
295  "",
296  "fitter.zero_area",
297  argType::Required,
298  "fitter",
299  "zero_area",
300  false,
301  "int",
302  "Setting the pixel area to zero out after detecting stars in processImage function." );
303  config.add( "fitter.threshold",
304  "",
305  "fitter.threshold",
306  argType::Required,
307  "fitter",
308  "threshold",
309  false,
310  "float",
311  "setting how many sigma away from the mean you want to classify a detection." );
312  config.add( "fitter.fwhm_threshold",
313  "",
314  "fitter.fwhm_threshold",
315  argType::Required,
316  "fitter",
317  "fwhm_threshold",
318  false,
319  "float",
320  "minumum fwhm to consider something a star." );
321  config.add( "acquisition.x_center",
322  "",
323  "acquisition.x_center",
324  argType::Required,
325  "acquisition",
326  "x_center",
327  false,
328  "int",
329  "X value for 'center' of image." );
330  config.add( "acquisition.y_center",
331  "",
332  "acquisition.y_center",
333  argType::Required,
334  "acquisition",
335  "y_center",
336  false,
337  "int",
338  "Y value for 'center' of image." );
339 }
340 
341 inline int psfAcq::loadConfigImpl( mx::app::appConfigurator &_config )
342 {
343  shmimMonitorT::loadConfig( _config );
345 
346  _config( m_fpsSource, "fitter.fpsSource" );
347  _config( m_max_loops, "fitter.max_loops" ); // Max number of stars to detect in processImage
348  _config( m_zero_area, "fitter.zero_area" ); // pixel area to zero out in processImage when a star is detected
349  _config( m_threshold, "fitter.threshold" ); // how many sigma away from the mean you want to classify a detection
350  _config( m_fwhm_threshold,
351  "fitter.fwhm_threshold" ); // how many sigma away from the mean you want to classify a detection
352 
353  _config( m_x_center, "acquisition.x_center" ); // star number to acquire
354  _config( m_y_center, "acquisition.y_center" ); // star number to acquire
355 
356  return 0;
357 }
358 
359 inline void psfAcq::loadConfig()
360 {
361  loadConfigImpl( config );
362 }
363 
364 inline int psfAcq::appStartup()
365 {
366  if( shmimMonitorT::appStartup() < 0 )
367  {
368  return log<software_error, -1>( { __FILE__, __LINE__ } );
369  }
370 
372  {
373  return log<software_error, -1>( { __FILE__, __LINE__ } );
374  }
375 
376  if( m_fpsSource != "" )
377  {
378  REG_INDI_SETPROP( m_indiP_fpsSource, m_fpsSource, std::string( "fps" ) );
379  }
380 
381  // creating toggling to restart the acquisition
382  createStandardIndiRequestSw( m_indiP_restartAcq, "restart_acq", "Restart Acquisition", "psfAcq");
384 
385  // INDI prop for seeing
387  m_indiP_seeing.add(pcf::IndiElement("current"));
388  m_indiP_seeing["current"].setValue( m_seeing ); //m_seeing gets assigned the seeing values of the star that is acquired
390 
391  // create toggling for calculating seeing
392  createStandardIndiRequestSw( m_indiP_calcSeeing, "calc_seeing", "Calculate Seeing", "psfAcq");
394 
395  // INDI prop for user to select star
396  CREATE_REG_INDI_NEW_NUMBERF( m_indiP_acquire_star, "acquire_star", 0, 20, 1, "%d", "", "" );
397  m_indiP_acquire_star["current"].setValue( m_acquire_star );
398  m_indiP_acquire_star["target"].setValue( m_acquire_star );
399 
400  // number of stars INDI prop
402  m_indiP_num_stars.add(pcf::IndiElement("current"));
403  m_indiP_num_stars["current"].setValue( m_num_stars );
405 
407 
408  return 0;
409 }
410 
411 inline int psfAcq::appLogic()
412 {
413  if( shmimMonitorT::appLogic() < 0 )
414  {
415  return log<software_error, -1>( { __FILE__, __LINE__ } );
416  }
417 
418  if( darkShmimMonitorT::appLogic() < 0 )
419  {
420  return log<software_error, -1>( { __FILE__, __LINE__ } );
421  }
422 
423  std::unique_lock<std::mutex> lock( m_indiMutex );
424 
427 
429  updateIfChanged( m_indiP_seeing, "current", m_seeing );
430 
431  for( size_t n = 0; n < m_detectedStars.size() ; ++n )
432  {
433 
434  updateIfChanged( m_detectedStars[n].prop(), "x", m_detectedStars[n].x );
435  updateIfChanged( m_detectedStars[n].prop(), "y", m_detectedStars[n].y );
436  updateIfChanged( m_detectedStars[n].prop(), "peak", m_detectedStars[n].max );
437  updateIfChanged( m_detectedStars[n].prop(), "fwhm", m_detectedStars[n].fwhm );
438  }
439  return 0;
440 }
441 
443 {
446 
447  return 0;
448 }
449 
450 inline int psfAcq::allocate( const dev::shmimT &dummy )
451 {
452  static_cast<void>( dummy );
453 
454  std::lock_guard<std::mutex> guard( m_imageMutex );
455 
457  m_image.setZero();
458 
459  m_sm.resize( m_image.rows(), m_image.cols() );
460 
461  m_updated = false;
462  return 0;
463 }
464 
465 // Function to calculate Euclidean distance between two stars
466 float calculateDistance( float x1, float y1, float x2, float y2 )
467 {
468  return sqrt( ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) );
469 }
470 
471 inline int psfAcq::processImage( void *curr_src, const dev::shmimT &dummy )
472 {
473  if(mx::sys::get_curr_time() - m_acqQuitTime < m_acqPauseTime ) return 0; // Pausing while telescope moves to star
474  static_cast<void>( dummy );
475 
476  std::unique_lock<std::mutex> lock( m_imageMutex );
477 
478  if( m_dark.rows() == m_image.rows() && m_dark.cols() == m_image.cols() )
479  {
480  for( unsigned nn = 0; nn < shmimMonitorT::m_width * shmimMonitorT::m_height; ++nn )
481  {
482  m_image.data()[nn] = ( (uint16_t *)curr_src )[nn] - m_dark.data()[nn];
483  }
484  }
485  else
486  {
487  for( unsigned nn = 0; nn < shmimMonitorT::m_width * shmimMonitorT::m_height; ++nn )
488  {
489  m_image.data()[nn] = ( (uint16_t *)curr_src )[nn];
490  }
491  }
492 
493  lock.unlock();
494  float max;
495  float seeing = 0;
496  // int max_loops=5;
497  int x = 0;
498  int y = 0;
499  int N_loops = 0;
500  // 1. find brightest star
501  max = m_image.maxCoeff( &x, &y );
502  // mx::improc::medianSmooth(m_sm, x, y, max, m_image, 3);
503 
504  // mx::improc::imageCenterOfLight(m_x, m_y, m_image);
505  // std::cerr << __LINE__ << std::endl;
506 
507  /*if(fabs(m_x-x) > 2 || fabs(m_y-y) > 2)
508  {
509  std::cerr << "skip frame\n";
510  return 0;
511  }*/
512 
513  eigenImage<float> llcorn = m_image.block( 0, 0, 32, 32 ); // calc std dev of 32x32 block in lower left corner
514  float mean = llcorn.mean(); // Calculate the mean
515  float variance = ( llcorn.array() - mean ).square().sum() / ( llcorn.size() ); // calculate variance
516  float stddev = std::sqrt( variance ); // Calculate the standard deviation
517  float z_score = ( max - mean ) / stddev; // how many std dev away from mean
518  float fwhm = m_fwhm_threshold + 1; // getting intial fwhm before entering while loop
519  std::size_t numStars = m_detectedStars.size();
520  if( numStars == 0 )
521  { // This runs when the vector of stars is empty (usually the first time)
522  while( ( z_score > m_threshold ) && ( fwhm > m_fwhm_threshold ) && ( N_loops < m_max_loops ) )
523  { // m_max_loops, m_fwhm_threshold, and m_threshold are configurable variables
524  N_loops = N_loops + 1;
525  m_gfit.set_itmax( 1000 );
526  // m_zero_area is used to zero out the pixel array once a star is detected but can also be used to set up a
527  // sub image around the max pixel
528  if( x < m_zero_area )
529  {
530  x = m_zero_area;
531  }
532  if( x >= ( m_image.rows() - m_zero_area ) )
533  {
534  x = m_image.rows() - m_zero_area;
535  }
536  if( y < m_zero_area )
537  {
538  y = m_zero_area;
539  }
540  if( y >= ( m_image.cols() - m_zero_area ) )
541  {
542  y = m_image.cols() - m_zero_area;
543  }
544  eigenImage<float> subImage = m_image.block(
545  x - m_zero_area,
546  y - m_zero_area,
547  m_zero_area * 2,
548  m_zero_area * 2 ); // set m_image to subImage to speed up gaussian, x,y is position of max pixel
549  m_gfit.setArray( subImage.data(), subImage.rows(), subImage.cols() );
550  // m_gfit.setArray(m_image.data(), m_image.rows(), m_image.cols());
551  m_gfit.setGuess( 0, max, m_zero_area, m_zero_area, mx::math::func::fwhm2sigma( m_fwhmGuess ) );
552  m_gfit.fit();
553  m_x = ( x - m_zero_area ) + m_gfit.x0();
554  m_y = ( y - m_zero_area ) + m_gfit.y0();
555  m_first_x_vals.push_back( m_x ); // adding first detected x value to vector
556  m_first_y_vals.push_back( m_y ); // adding first detected y value to vector
557  fwhm = m_gfit.fwhm() ;
558  max = m_gfit.G();
559  seeing = fwhm * m_plate_scale;
560  int x_value = static_cast<int>(
561  m_x ); // convert m_x to an int so we can 0 out a rectangular area around the detected star
562  int y_value = static_cast<int>( m_y );
563  if (fwhm > m_fwhm_threshold && fwhm < m_max_fwhm ){
564  Star newStar;
565  newStar.x = m_x; // Adding attributes to the new star
566  newStar.y = m_y;
567  newStar.max = max;
568  newStar.fwhm = fwhm;
569  newStar.seeing = seeing;
570  std::unique_lock<std::mutex> lock( m_indiMutex );
571  newStar.allocate();
572  m_detectedStars.push_back( newStar );
573  int index = m_detectedStars.size() - 1;
574  std::string starPrefix = "star_" + std::to_string( index );
575  createROIndiNumber(m_detectedStars.back().prop(), starPrefix); //, "Star " + std::to_string( m_detectedStars.size() ) + " Properties", "Star Acq" );
576  m_detectedStars.back().prop().add( pcf::IndiElement( "x" ) );
577  m_detectedStars.back().prop()["x"].set( m_detectedStars.back().x );
578  m_detectedStars.back().prop().add( pcf::IndiElement( "y" ) );
579  m_detectedStars.back().prop()["y"].set( m_detectedStars.back().y );
580  m_detectedStars.back().prop().add( pcf::IndiElement( "peak" ) );
581  m_detectedStars.back().prop()["peak"].set( m_detectedStars.back().max );
582  m_detectedStars.back().prop().add( pcf::IndiElement( "fwhm" ) );
583  m_detectedStars.back().prop()["fwhm"].set( m_detectedStars.back().fwhm );
585  }
586  if( x_value < m_zero_area )
587  {
588  x_value = m_zero_area;
589  }
590  if( x_value >= ( m_image.rows() - m_zero_area ) )
591  {
592  x_value = m_image.rows() - m_zero_area;
593  }
594  if( y_value < m_zero_area )
595  {
596  y_value = m_zero_area;
597  }
598  if( y_value >= ( m_image.cols() - m_zero_area ) )
599  {
600  y_value = m_image.cols() - m_zero_area;
601  }
602  for( int i = x_value - m_zero_area; i < ( x_value + m_zero_area ); i++ )
603  { // zeroing out area around the star centered at m_x and m_y(8x8 pixel area)
604  for( int j = y_value - m_zero_area; j < ( y_value + m_zero_area ); j++ )
605  {
606  m_image( i, j ) = 0; // m_zero_area is defaulted to 20 to zero out a pixel array around the star
607  }
608  }
609  max = m_image.maxCoeff( &x, &y );
610  z_score = ( max - mean ) / stddev;
611  }
612  }
613 
614  else
615  {
616  // In here is where we track the stars using cross correlation between the first frame and subsequent frames
617  while( ( z_score > m_threshold ) && ( fwhm > m_fwhm_threshold ) && ( N_loops < m_max_loops ) )
618  {
619  N_loops = N_loops + 1;
620  m_gfit.set_itmax( 1000 );
621  // m_zero_area is used to zero out the pixel array once a star is detected but can also be used to set up a
622  // sub image around the max pixel
623  if( x < m_zero_area )
624  {
625  x = m_zero_area;
626  }
627  if( x >= ( m_image.rows() - m_zero_area ) )
628  {
629  x = m_image.rows() - m_zero_area;
630  }
631  if( y < m_zero_area )
632  {
633  y = m_zero_area;
634  }
635  if( y >= ( m_image.cols() - m_zero_area ) )
636  {
637  y = m_image.cols() - m_zero_area;
638  }
639  eigenImage<float> subImage = m_image.block(
640  x - m_zero_area,
641  y - m_zero_area,
642  m_zero_area * 2,
643  m_zero_area * 2 ); // set m_image to subImage to speed up gaussian, x,y is position of max pixel
644  // 2. fit it's position
645  m_gfit.setArray( subImage.data(), subImage.rows(), subImage.cols() );
646  m_gfit.setGuess( 0, max, m_zero_area, m_zero_area, mx::math::func::fwhm2sigma( m_fwhmGuess ) );
647  m_gfit.fit();
648  fwhm = m_gfit.fwhm() ;
649  max = m_gfit.G();
650  seeing = fwhm * m_plate_scale;
651  m_x = ( x - m_zero_area ) + m_gfit.x0();
652  m_y = ( y - m_zero_area ) + m_gfit.y0();
653  int x_value = static_cast<int>(
654  m_x ); // convert m_x to an int so we can 0 out a rectangular area around the detected star
655  int y_value = static_cast<int>( m_y );
656  if( x_value < m_zero_area )
657  {
658  x_value = m_zero_area;
659  }
660  if( x_value >= ( m_image.rows() - m_zero_area ) )
661  {
662  x_value = m_image.rows() - m_zero_area;
663  }
664  if( y_value < m_zero_area )
665  {
666  y_value = m_zero_area;
667  }
668  if( y_value >= ( m_image.cols() - m_zero_area ) )
669  {
670  y_value = m_image.cols() - m_zero_area;
671  }
672  for( int i = x_value - m_zero_area; i < ( x_value + m_zero_area ); i++ )
673  { // zeroing out area around the star centered at m_x and m_y(8x8 pixel area)
674  for( int j = y_value - m_zero_area; j < ( y_value + m_zero_area ); j++ )
675  {
676  m_image( i, j ) = 0; // m_zero_area is defaulted to 20 to zero out a pixel array around the star
677  }
678  }
679  // 3. search through all known stars to figure out which one it corresponds to. You can NOT assume it is in the order of the vector.
680  // This simple for loop calculate the distance from the detected star to the cloest star already in the list
681  // and updates the values
682  int threshold_distance = 20; // distance between new stars should be a small positive number so this updates
683  int tracker = 0; // tracks if the current star detected updated an already known star
684  if (fwhm > m_fwhm_threshold && fwhm < m_max_fwhm ){
685  for( Star &star : m_detectedStars )
686  {
687  float dist = calculateDistance( star.x, star.y, x_value, y_value );
688  // 4. if it is found, update that star's data in the vector
689  if( dist < threshold_distance )
690  {
691  star.x = m_x;
692  star.y = m_y;
693  star.max = max;
694  star.fwhm = fwhm;
695  star.seeing = seeing;
696  tracker = 1;
697  continue;
698  }
699  }
700  if (tracker == 0 && m_detectedStars.size() < m_max_loops) { // 5. if it is not found, add a star and corresponding INDI Property using push_back
701  Star newStar;
702  newStar.x = m_x; // Adding attributes to the new star
703  newStar.y = m_y;
704  newStar.max = max;
705  newStar.fwhm = fwhm;
706  newStar.seeing = seeing;
707  std::unique_lock<std::mutex> lock( m_indiMutex );
708  newStar.allocate();
709  m_detectedStars.push_back( newStar );
710  int index = m_detectedStars.size() - 1;
711  std::string starPrefix = "star_" + std::to_string( index );
712  createROIndiNumber(m_detectedStars.back().prop(), starPrefix, "Star " + std::to_string( index ) + " Properties", "Star Acq" );
713  m_detectedStars.back().prop().add( pcf::IndiElement( "x" ) );
714  m_detectedStars.back().prop()["x"].set( m_detectedStars.back().x );
715  m_detectedStars.back().prop().add( pcf::IndiElement( "y" ) );
716  m_detectedStars.back().prop()["y"].set( m_detectedStars.back().y );
717  m_detectedStars.back().prop().add( pcf::IndiElement( "peak" ) );
718  m_detectedStars.back().prop()["peak"].set( m_detectedStars.back().max );
719  m_detectedStars.back().prop().add( pcf::IndiElement( "fwhm" ) );
720  m_detectedStars.back().prop()["fwhm"].set( m_detectedStars.back().fwhm );
722  }
723  }
724  max = m_image.maxCoeff( &x, &y );
725  z_score = ( max - mean ) / stddev;
726  }
727  }
728 
729  m_num_stars = m_detectedStars.size();
730  // If statement that get the delta x and delta y from the 'center' of image
731  static int delta_x;
732  static int delta_y;
733  double plate_scale = .0795336; // plate scale factor: deltatheta/deltapixel, calculated in python, arcsec/pixel
734  //deltatheta -> Angular seperation between two stars in arcsec (from published data)
735  //deltapixel -> Pixel seperation between same two stars on our detector
736  if ( m_acquire_star != -1 && (m_acquire_star > m_detectedStars.size() - 1 || m_acquire_star < 0 )){
737  std::cout << "Please enter a star number between 0 and " << m_detectedStars.size() - 1 << "." << std::endl;
738  m_acquire_star = -1;
739  }
740 
741  if( m_acquire_star >= 0 && m_acquire_star < m_detectedStars.size())
742  {
743  m_acqQuitTime = mx::sys::get_curr_time();
747  std::cout << "seeing=" << m_detectedStars[m_acquire_star].seeing << std::endl;
748  std::cout << "delta_x = " << delta_x << " delta_y = " << delta_y << std::endl;
749 
750  // negative signs because we want to move scope opposite of how far it is from 'center'
751  double x_arcsec = -1*delta_y * plate_scale; //positive x_arcsec moves up, negetive moves down
752  double y_arcsec = -1*delta_x * plate_scale; //positive y_arcsec moves right, negetive moves left
753  std::cout << "x_arcsec=" << x_arcsec << " y_arcsec=" << y_arcsec << std::endl;
754 
755  // for moving telescope
756  pcf::IndiProperty ip( pcf::IndiProperty::Number );
757 
758  ip.setDevice( "tcsi" );
759  ip.setName( "pyrNudge" );
760  //send telescope x and y offsets in acrsec
761  ip.add( pcf::IndiElement( "y" ) );
762  ip["y"] = x_arcsec; //how far to move in y direction in arcsec?
763  ip.add( pcf::IndiElement( "x" ) );
764  ip["x"] = y_arcsec; //how far to move in x direction in arcsec?
765 
766  sendNewProperty( ip );
767  resetAcq();
768  m_acquire_star = -1;
769  }
770 
771  m_updated = true;
772  return 0;
773 }
774 
775 inline int psfAcq::allocate( const darkShmimT &dummy )
776 {
777  static_cast<void>( dummy );
778 
779  std::lock_guard<std::mutex> guard( m_imageMutex );
780 
782  {
783  return log<software_error, -1>( { __FILE__, __LINE__, "dark is not float" } );
784  }
785 
787  m_dark.setZero();
788 
789  return 0;
790 }
791 
792 inline int psfAcq::processImage( void *curr_src, const darkShmimT &dummy )
793 {
794  static_cast<void>( dummy );
795 
796  std::unique_lock<std::mutex> lock( m_imageMutex );
797 
798  for( unsigned nn = 0; nn < darkShmimMonitorT::m_width * darkShmimMonitorT::m_height; ++nn )
799  {
800  m_dark.data()[nn] += ( (float *)curr_src )[nn];
801  }
802 
803  lock.unlock();
804 
805  log<text_log>( "dark updated", logPrio::LOG_INFO );
806 
807  return 0;
808 }
809 
810 //delete m_detectedStars Properties
812  for(size_t n=0; n < m_detectedStars.size(); ++n)
813  {
814  if(m_indiDriver) m_indiDriver->sendDelProperty(m_detectedStars[n].prop());
815  if(!m_indiNewCallBacks.erase(m_detectedStars[n].prop().createUniqueKey()))
816  {
817  log<software_error>({__FILE__, __LINE__, "failed to erase " + m_detectedStars[n].prop().createUniqueKey()});
818  }
819  }
820  std::cout << "size=" << m_detectedStars.size() << std::endl;
821  m_detectedStars.clear();
822 }
823 
824 //for toggling Restart Acquisition
826 {
828  if(!ipRecv.find("request")) return 0;
829  std::unique_lock<std::mutex> lock(m_indiMutex);
830 
831  if( ipRecv["request"].getSwitchState() == pcf::IndiElement::On)
832  {
833  std::cout << "size=" << m_detectedStars.size() << std::endl;
834  resetAcq();
835  std::cout << "size=" << m_detectedStars.size() << std::endl;
836  return 0;
837  }
838  else if( ipRecv["request"].getSwitchState() == pcf::IndiElement::Off)
839  {
840  return 0;
841  }
842 
843  log<software_error>({__FILE__,__LINE__, "switch state fall through."});
844  return -1;
845 }
846 
847 //for toggling Calculating Seeing
849 {
851  if(!ipRecv.find("request")) return 0;
852  std::unique_lock<std::mutex> lock(m_indiMutex);
853 
854  if( ipRecv["request"].getSwitchState() == pcf::IndiElement::On)
855  {
857  return 0;
858  }
859  else if( ipRecv["request"].getSwitchState() == pcf::IndiElement::Off)
860  {
861  return 0;
862  }
863 
864  log<software_error>({__FILE__,__LINE__, "switch state fall through."});
865  return -1;
866 }
867 
868 // Testing for user to select star number
870 {
871  if( ipRecv.getName() != m_indiP_acquire_star.getName() )
872  {
873  log<software_error>( { __FILE__, __LINE__, "wrong INDI property received." } );
874  return -1;
875  }
876 
877  float target;
878 
879  if( indiTargetUpdate( m_indiP_acquire_star, target, ipRecv, true ) < 0 )
880  {
881  log<software_error>( { __FILE__, __LINE__ } );
882  return -1;
883  }
884 
885  m_acquire_star = target;
886 
887  log<text_log>( "set acquire_star = " + std::to_string( m_acquire_star ), logPrio::LOG_NOTICE );
888  return 0;
889 }
890 
891 INDI_SETCALLBACK_DEFN( psfAcq, m_indiP_fpsSource )( const pcf::IndiProperty &ipRecv )
892 {
893  if( ipRecv.getName() != m_indiP_fpsSource.getName() )
894  {
895  log<software_error>( { __FILE__, __LINE__, "Invalid INDI property." } );
896  return -1;
897  }
898 
899  if( ipRecv.find( "current" ) != true ) // this isn't valie
900  {
901  return 0;
902  }
903 
904  std::lock_guard<std::mutex> guard( m_indiMutex );
905 
906  realT fps = ipRecv["current"].get<float>();
907 
908  if( fps != m_fps )
909  {
910  m_fps = fps;
912  }
913 
914  return 0;
915 }
916 
917 } // namespace app
918 } // namespace MagAOX
919 
920 #endif // psfAcq_hpp
#define IMAGESTRUCT_FLOAT
Definition: ImageStruct.hpp:22
The base-class for MagAO-X applications.
Definition: MagAOXApp.hpp:73
void updateIfChanged(pcf::IndiProperty &p, const std::string &el, const T &newVal, pcf::IndiProperty::PropertyStateType ipState=pcf::IndiProperty::Ok)
Update an INDI property element value if it has changed.
Definition: MagAOXApp.hpp:3120
int createStandardIndiRequestSw(pcf::IndiProperty &prop, const std::string &name, const std::string &label="", const std::string &group="")
Create a standard R/W INDI switch with a single request element.
Definition: MagAOXApp.hpp:2573
stateCodes::stateCodeT state()
Get the current state code.
Definition: MagAOXApp.hpp:2297
int registerIndiPropertyNew(pcf::IndiProperty &prop, int(*)(void *, const pcf::IndiProperty &))
Register an INDI property which is exposed for others to request a New Property for.
std::unordered_map< std::string, indiCallBack > m_indiNewCallBacks
Map to hold the NewProperty indiCallBacks for this App, with fast lookup by property name.
Definition: MagAOXApp.hpp:573
indiDriver< MagAOXApp > * m_indiDriver
The INDI driver wrapper. Constructed and initialized by execute, which starts and stops communication...
Definition: MagAOXApp.hpp:542
static int log(const typename logT::messageT &msg, logPrioT level=logPrio::LOG_DEFAULT)
Make a log entry.
Definition: MagAOXApp.hpp:1804
int createROIndiNumber(pcf::IndiProperty &prop, const std::string &propName, const std::string &propLabel="", const std::string &propGroup="")
Create a ReadOnly INDI Number property.
Definition: MagAOXApp.hpp:2517
int registerIndiPropertyReadOnly(pcf::IndiProperty &prop)
Register an INDI property which is read only.
Definition: MagAOXApp.hpp:2655
std::mutex m_indiMutex
Mutex for locking INDI communications.
Definition: MagAOXApp.hpp:545
int sendNewProperty(const pcf::IndiProperty &ipSend, const std::string &el, const T &newVal)
Send a newProperty command to another device (using the INDI Client interface)
Definition: MagAOXApp.hpp:3268
int indiTargetUpdate(pcf::IndiProperty &localProperty, T &localTarget, const pcf::IndiProperty &remoteProperty, bool setBusy=true)
Get the target element value from an new property.
Definition: MagAOXApp.hpp:3197
uint32_t m_width
The width of the images in the stream.
int setupConfig(mx::app::appConfigurator &config)
Setup the configuration system.
int updateINDI()
Update the INDI properties for this device controller.
int appLogic()
Checks the shmimMonitor thread.
uint32_t m_height
The height of the images in the stream.
int appShutdown()
Shuts down the shmimMonitor thread.
uint8_t m_dataType
The ImageStreamIO type code.
bool m_restart
Flag indicating tha the shared memory should be reinitialized.
int loadConfig(mx::app::appConfigurator &config)
load the configuration system results
bool m_getExistingFirst
If set to true by derivedT, any existing image will be grabbed and sent to processImage before waitin...
The MagAO-X PSF Fitter.
Definition: psfAcq.hpp:94
mx::improc::eigenImage< float > m_sm
Definition: psfAcq.hpp:130
int loadConfigImpl(mx::app::appConfigurator &_config)
Implementation of loadConfig logic, separated for testing.
Definition: psfAcq.hpp:341
virtual void loadConfig()
Definition: psfAcq.hpp:359
INDI_SETCALLBACK_DECL(psfAcq, m_indiP_fpsSource)
mx::improc::eigenImage< float > m_image
Definition: psfAcq.hpp:129
double m_acqQuitTime
Definition: psfAcq.hpp:134
std::string m_fpsSource
Definition: psfAcq.hpp:120
dev::shmimMonitor< psfAcq, darkShmimT > darkShmimMonitorT
Definition: psfAcq.hpp:105
float m_fwhm_threshold
Definition: psfAcq.hpp:145
psfAcq()
Default c'tor.
Definition: psfAcq.hpp:256
int processImage(void *curr_src, const dev::shmimT &)
Definition: psfAcq.hpp:471
pcf::IndiProperty m_indiP_num_stars
Definition: psfAcq.hpp:226
float realT
Floating point type in which to do all calculations.
Definition: psfAcq.hpp:108
virtual int appLogic()
Implementation of the FSM for psfAcq.
Definition: psfAcq.hpp:411
friend class psfAcq_test
Definition: psfAcq.hpp:96
std::vector< float > m_first_x_vals
Definition: psfAcq.hpp:148
double m_plate_scale
Definition: psfAcq.hpp:155
std::mutex m_imageMutex
Definition: psfAcq.hpp:218
int recordTelem(const telem_fgtimings *)
uint16_t m_fitCircBuffMaxLength
Maximum length of the latency measurement circular buffers.
Definition: psfAcq.hpp:123
virtual int appStartup()
Startup function.
Definition: psfAcq.hpp:364
~psfAcq() noexcept
D'tor, declared and defined for noexcept.
Definition: psfAcq.hpp:262
mx::improc::eigenImage< float > m_dark
Definition: psfAcq.hpp:132
double m_acqPauseTime
Definition: psfAcq.hpp:135
pcf::IndiProperty m_indiP_seeing
Definition: psfAcq.hpp:227
INDI_NEWCALLBACK_DECL(psfAcq, m_indiP_acquire_star)
virtual void setupConfig()
Definition: psfAcq.hpp:270
int allocate(const dev::shmimT &)
Definition: psfAcq.hpp:450
pcf::IndiProperty m_indiP_calcSeeing
Definition: psfAcq.hpp:240
virtual int appShutdown()
Shutdown the app.
Definition: psfAcq.hpp:442
mx::math::fit::fitGaussian2Dsym< float > m_gfit
Definition: psfAcq.hpp:169
dev::shmimMonitor< psfAcq > shmimMonitorT
Definition: psfAcq.hpp:103
float m_fitCircBuffMaxTime
Maximum time of the latency meaurement circular buffers.
Definition: psfAcq.hpp:124
pcf::IndiProperty m_indiP_fpsSource
Definition: psfAcq.hpp:229
std::vector< float > m_first_y_vals
Definition: psfAcq.hpp:149
pcf::IndiProperty m_indiP_acquire_star
Definition: psfAcq.hpp:233
std::vector< Star > m_detectedStars
Definition: psfAcq.hpp:150
pcf::IndiProperty m_indiP_restartAcq
Definition: psfAcq.hpp:237
#define INDI_NEWCALLBACK(prop)
Get the name of the static callback wrapper for a new property.
Definition: indiMacros.hpp:208
#define CREATE_REG_INDI_NEW_NUMBERF(prop, name, min, max, step, format, label, group)
Create and register a NEW INDI property as a standard number as float, using the standard callback na...
Definition: indiMacros.hpp:309
#define REG_INDI_SETPROP(prop, devName, propName)
Register a SET INDI property with the class, using the standard callback name.
Definition: indiMacros.hpp:282
@ OPERATING
The device is operating, other than homing.
Definition: stateCodes.hpp:55
std::ostream & cout()
INDI_VALIDATE_CALLBACK_PROPS(function, ipRecv)
float calculateDistance(float x1, float y1, float x2, float y2)
Definition: psfAcq.hpp:466
const pcf::IndiProperty & ipRecv
Definition: MagAOXApp.hpp:3434
INDI_SETCALLBACK_DEFN(adcTracker, m_indiP_teldata)(const pcf
Definition: adcTracker.hpp:461
INDI_NEWCALLBACK_DEFN(acesxeCtrl, m_indiP_windspeed)(const pcf
Definition: acesxeCtrl.hpp:687
std::unique_lock< std::mutex > lock(m_indiMutex)
Definition: dm.hpp:24
constexpr static logPrioT LOG_INFO
Informational. The info log level is the lowest level recorded during normal operations.
Definition: logPriority.hpp:49
constexpr static logPrioT LOG_NOTICE
A normal but significant condition.
Definition: logPriority.hpp:46
void deallocate()
Definition: psfAcq.hpp:77
void allocate()
Definition: psfAcq.hpp:72
pcf::IndiProperty * m_prop
Definition: psfAcq.hpp:58
pcf::IndiProperty & prop()
Definition: psfAcq.hpp:62
static std::string configSection()
Definition: psfAcq.hpp:36
static std::string indiPrefix()
Definition: psfAcq.hpp:41
Software ERR log entry.
Log entry recording framegrabber timings.