namespace OINA.Extender.Testharness
{
using System;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using System.Windows.Media;
using OINA.Extender.Acquisition.Quant;
using OINA.Extender.Controls;
using OINA.Extender.Controls.Spectrum;
///
/// Calibrate Form.
///
public partial class Calibrate : Form
{
///
/// The quant calibration controller
///
private readonly IQuantCalibrationController controller;
///
/// The quant calibration settings
///
private readonly IQuantCalibrationSettings settings;
///
/// SpectrumViewer object
///
private SpectrumViewer spectrumViewer;
///
/// Flag to show if the use has been warned about insignificant calibration peak for a particular run
///
private bool userWarnedOnCalibrationPeakInsignificant;
///
/// Calibrate constructor
///
public Calibrate()
{
this.InitializeComponent();
this.settings = OIHelper.QuantCalibrationSettings;
// use the same Ed settings as spectrum acquistion
var spectrumSettings = OIHelper.EdSpectrumSettings;
this.settings.EdSettings.CopyFrom(spectrumSettings.EdSettings);
this.ElementCombo.Items = this.settings.Capabilities.AllowedCalibrationElements;
this.ElementCombo.CurrentElement = this.settings.CalibrationElementAtomicNumber;
if (this.settings.CalibrationMode == QuantCalibrationMode.EnergyCalibration)
{
this.RoutineCombobox.SelectedIndex = 0;
this.SettingsButton.Visible = false;
}
else if (this.settings.CalibrationMode == QuantCalibrationMode.BeamMeasurement)
{
this.RoutineCombobox.SelectedIndex = 1;
this.SettingsButton.Visible = true;
}
this.settings.PropertyChanged += this.OnSettingsPropertyChanged;
this.settings.Capabilities.PropertyChanged += this.OnCapabilitiesPropertyChanged;
this.CurrentStatusTextbox.Text = string.Empty;
this.controller = OIHelper.QuantCalibrationController;
// beam measurement
this.controller.BeamMeasurementAcquisitionStarted += this.OnBeamMeasurementAcquisitionStarted;
this.controller.BeamMeasurementAcquisitionFinished += this.OnBeamMeasurementAcquisitionFinished;
this.controller.BeamMeasurementResult += this.OnBeamMeasurementResult;
this.controller.BeamMeasurementFinished += this.OnBeamMeasurementFinished;
// common
this.controller.CalibrationPeakInsignificant += this.OnCalibrationPeakInsignificant;
// energy calibration
this.controller.EnergyCalibrationAcquisitionStarted += this.OnEnergyCalibrationAcquisitionStarted;
this.controller.EnergyCalibrationAcquisitionFinished += this.OnEnergyCalibrationAcquisitionFinished;
this.controller.EnergyCalibrationFinished += this.OnEnergyCalibrationFinished;
this.controller.PropertyChanged += this.OnControllerPropertyChanged;
this.HostSpectrumViewer();
}
///
/// Host the WPF Spectrum viewer control
///
private void HostSpectrumViewer()
{
this.spectrumViewer = new SpectrumViewer();
this.ehSpectrumViewer.Child = this.spectrumViewer;
this.spectrumViewer.IsXAxisAutoScaleEnabled = false;
this.spectrumViewer.IsYAxisAutoScaleEnabled = true;
}
///
/// The calibration routine has changed, update the settings
///
/// The sender
/// The event args
private void RoutineCombobox_SelectionChangeCommitted(object sender, EventArgs e)
{
if (this.RoutineCombobox.SelectedIndex == 0)
{
this.SettingsButton.Visible = false;
this.settings.CalibrationMode = QuantCalibrationMode.EnergyCalibration;
}
else
{
this.SettingsButton.Visible = true;
this.settings.CalibrationMode = QuantCalibrationMode.BeamMeasurement;
}
}
///
/// Handle quant calibration settings property changed notifications
///
/// The sender
/// The event args
private void OnSettingsPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == @"CalibrationElementAtomicNumber")
{
this.ElementCombo.CurrentElement = this.settings.CalibrationElementAtomicNumber;
}
else if (e.PropertyName == @"CalibrationMode")
{
if (this.settings.CalibrationMode == QuantCalibrationMode.EnergyCalibration)
{
this.RoutineCombobox.SelectedIndex = 0;
}
else if (this.settings.CalibrationMode == QuantCalibrationMode.BeamMeasurement)
{
this.RoutineCombobox.SelectedIndex = 1;
}
}
}
///
/// Handle quant calibration capabilites property changed notifications
///
/// The sender
/// The event args
private void OnCapabilitiesPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == @"AllowedCalibrationElements")
{
this.ElementCombo.Items = this.settings.Capabilities.AllowedCalibrationElements;
this.ElementCombo.CurrentElement = this.settings.CalibrationElementAtomicNumber;
}
}
///
/// Handle property changed notifications from the controller
///
/// sender
/// PropertyChangedEventArgs
private void OnControllerPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "CurrentCalibrationSpectrum":
// execute on UI thread
this.BeginInvoke((Action)delegate
{
this.spectrumViewer.Spectrum = this.controller.CurrentCalibrationSpectrum;
});
break;
case "PercentageComplete":
// execute on UI thread
this.BeginInvoke((Action)delegate
{
this.CalibrateProgressBar.Value = int.Parse(this.controller.PercentageComplete.ToString(CultureInfo.CurrentCulture), CultureInfo.CurrentCulture);
this.EstimateTimeLabel.Text = this.controller.EstimatedTimeToCompletion.Ticks == 0 ? string.Empty : this.controller.EstimatedTimeToCompletion.ToString(@"hh\:mm\:ss", CultureInfo.CurrentCulture);
});
break;
case "CurrentEnergyWindow":
var window = this.controller.CurrentEnergyWindow;
if (window != null)
{
var windowColor = Color.FromArgb(255, 255, 0, 119);
var windows = new[]
{
new EnergyWindow(window.LowerEnergy, window.UpperEnergy, windowColor)
};
// execute on UI thread
this.BeginInvoke((Action)delegate
{
this.spectrumViewer.EnergyWindowsSource = windows;
});
}
break;
case "IsIdle":
// execute on UI thread
this.BeginInvoke((Action)delegate
{
if (this.controller.IsIdle)
{
this.CurrentStatusTextbox.Text = @"Data acquisition is Idle.";
}
else
{
this.CurrentStatusTextbox.Text = @"Data is currently acquiring.";
}
});
break;
}
}
///
/// Validate the settings and start the calibration routine
///
/// The sender
/// The event args
private void StartCalibrateButton_Click(object sender, EventArgs e)
{
this.settings.CalibrationElementAtomicNumber = this.ElementCombo.CurrentElement;
var results = this.settings.Validate();
if (!results.IsValid)
{
string message = string.Format(CultureInfo.CurrentCulture, @"The settings are not valid{0}", Environment.NewLine);
message += string.Join(Environment.NewLine, results.ValidationErrors);
MessageBox.Show(message, @"Invalid settings");
return;
}
this.CalibrateProgressBar.Value = 0;
try
{
this.controller.StartCalibration(this.settings);
this.userWarnedOnCalibrationPeakInsignificant = false;
}
catch (Exception ex)
{
string message = string.Format(CultureInfo.CurrentCulture, @"An error occured when starting calibration. {0} {1}", Environment.NewLine, ex.Message);
MessageBox.Show(message, @"Quant optimization");
}
}
///
/// Stops the calibration routine
///
/// The sender
/// The event args
private void StopCalibrateButton_Click(object sender, EventArgs e)
{
this.controller.StopCalibration();
}
///
/// The beam measurement acquisition has started
///
/// The sender
/// The event args
private void OnBeamMeasurementAcquisitionStarted(object sender, EventArgs e)
{
this.EnableCalibrationControls(false);
}
///
/// The beam measurement acquisition has finished
///
/// The sender
/// The event args
private void OnBeamMeasurementAcquisitionFinished(object sender, CalibrationAcquisitionFinishedEventArgs e)
{
if (!e.Success)
{
// Acquisition was stopped by the user, or an error occured
if (e.Error != null)
{
string message = string.Format(CultureInfo.CurrentCulture, @"Beam measurement acquisition did not complete successfully {0} {1}", Environment.NewLine, e.Error.Message);
MessageBox.Show(message, @"Beam measurement");
}
e.Cancel = true; // should already be set to true
this.EnableCalibrationControls(true);
}
}
///
/// The beam measurement has been compared to the previous measurement
///
/// The sender
/// The event args
private void OnBeamMeasurementResult(object sender, BeamMeasurementResultEventArgs e)
{
string content = string.Empty;
if (e.Status == BeamMeasurementResultStatus.MeasurementDifference)
{
content = string.Format(CultureInfo.CurrentCulture, @"The beam current is {0:0.00}% of the last value", e.Percent);
}
else if (e.Status == BeamMeasurementResultStatus.MeasurementOK)
{
content = @"Measurement OK";
}
else
{
throw new InvalidOperationException("Unexpected result status");
}
string message = string.Format(CultureInfo.CurrentCulture, @"Do you want to save the beam measurement?{0}{0}{1}", Environment.NewLine, content);
if (MessageBox.Show(message, @"Beam measurement", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
this.EnableCalibrationControls(true);
}
}
///
/// The beam measurement has been saved
///
/// The sender
/// The event args
private void OnBeamMeasurementFinished(object sender, CalibrationFinishedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(string.Format(CultureInfo.CurrentCulture, @"Failed to perform beam measurement:{0}{0}{1}", Environment.NewLine, e.Error.Message), @"Beam measurement", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
this.EnableCalibrationControls(true);
}
///
/// The calibration peak is not significant.
/// Can occur during both Beam measurement and Energy calibration
///
/// The sender
/// The event args
private void OnCalibrationPeakInsignificant(object sender, CalibrationPeakInsignificantEventArgs e)
{
if (this.userWarnedOnCalibrationPeakInsignificant)
{
return;
}
var message = new StringBuilder();
message.AppendFormat(
CultureInfo.CurrentCulture,
@"The calibration peak is not significantly greater than the background:{0}Peak counts: {1}{0}Low energy background: {2}{0}high energy background: {3}{0}{0}",
Environment.NewLine,
e.PeakCounts,
e.LowEnergyBackgroundCounts,
e.HighEnergyBackgroundCounts);
message.AppendFormat(CultureInfo.CurrentCulture, @"The calibration process has been running for {0:hh\:mm\:ss}", e.ElapsedTime);
if (e.EstimatedTimeToCompletion.TotalSeconds > 0)
{
message.AppendFormat(CultureInfo.CurrentCulture, @" and an estimated time to completion is {0:hh\:mm\:ss}. ", e.EstimatedTimeToCompletion);
}
message.AppendFormat(CultureInfo.CurrentCulture, @"{0}{0}The wrong element may have been selected. Would you like to continue?", Environment.NewLine);
if (MessageBox.Show(message.ToString(), @"Quant optimization", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
this.controller.StopCalibration();
}
this.userWarnedOnCalibrationPeakInsignificant = true;
}
///
/// The energy calibration acquisition has started
///
/// The sender
/// The event args
private void OnEnergyCalibrationAcquisitionStarted(object sender, EventArgs e)
{
this.EnableCalibrationControls(false);
}
///
/// The energy calibration acquisition has finished
///
/// The sender
/// The event args
private void OnEnergyCalibrationAcquisitionFinished(object sender, CalibrationAcquisitionFinishedEventArgs e)
{
if (e.Success)
{
string message = @"Perform Energy calibration using the acquired spectra?";
if (MessageBox.Show(message, @"Energy calibration", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
this.EnableCalibrationControls(true);
}
}
else
{
// Acquisition was stopped by the user, or an error occured
if (e.Error != null)
{
string message = string.Format(CultureInfo.CurrentCulture, @"Energy calibration acquisition did not complete successfully {0} {1}", Environment.NewLine, e.Error.Message);
MessageBox.Show(message, @"Energy calibration");
}
e.Cancel = true; // should already be set to true
this.EnableCalibrationControls(true);
}
}
///
/// The Energy calibration has been saved
///
/// The sender
/// The event args
private void OnEnergyCalibrationFinished(object sender, CalibrationFinishedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(string.Format(CultureInfo.CurrentCulture, @"Failed to perform energy calibration:{0}{0}{1}", Environment.NewLine, e.Error.Message), @"Energy calibration", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
this.EnableCalibrationControls(true);
}
///
/// Display the settings for Beam measurement
///
/// The sender
/// The event args
private void SettingsButton_Click(object sender, EventArgs e)
{
BeamMeasurementSettings beamSettings = new BeamMeasurementSettings();
beamSettings.StartPosition = FormStartPosition.CenterScreen;
beamSettings.ShowDialog();
}
///
/// Unsubscribe from the events
///
/// The event args
protected override void OnClosing(CancelEventArgs e)
{
this.settings.PropertyChanged -= this.OnSettingsPropertyChanged;
this.settings.Capabilities.PropertyChanged -= this.OnCapabilitiesPropertyChanged;
this.controller.BeamMeasurementAcquisitionStarted -= this.OnBeamMeasurementAcquisitionStarted;
this.controller.BeamMeasurementAcquisitionFinished -= this.OnBeamMeasurementAcquisitionFinished;
this.controller.BeamMeasurementResult -= this.OnBeamMeasurementResult;
this.controller.BeamMeasurementFinished -= this.OnBeamMeasurementFinished;
this.controller.CalibrationPeakInsignificant -= this.OnCalibrationPeakInsignificant;
this.controller.EnergyCalibrationAcquisitionStarted -= this.OnEnergyCalibrationAcquisitionStarted;
this.controller.EnergyCalibrationAcquisitionFinished -= this.OnEnergyCalibrationAcquisitionFinished;
this.controller.EnergyCalibrationFinished -= this.OnEnergyCalibrationFinished;
this.controller.PropertyChanged -= this.OnControllerPropertyChanged;
base.OnClosing(e);
}
///
/// Enable/disable the controls for starting the acquisition
///
/// Whether to enable or not
private void EnableCalibrationControls(bool enable)
{
this.BeginInvoke(
(Action)delegate
{
this.StartCalibrateButton.Enabled = enable;
this.RoutineCombobox.Enabled = enable;
this.SettingsButton.Enabled = enable;
this.ElementCombo.IsEnabled = enable;
this.StopCalibrateButton.Enabled = !enable;
if (enable)
{
this.EstimateTimeLabel.Text = string.Empty;
}
},
null);
}
}
}