LibreVNA/Software/PC_Application/Traces/tracexyplot.cpp

962 lines
35 KiB
C++
Raw Normal View History

2020-10-28 05:07:14 +08:00
#include "tracexyplot.h"
2021-10-21 19:00:34 +08:00
#include "trace.h"
2021-10-21 19:00:34 +08:00
#include "CustomWidgets/informationbox.h"
#include "Marker/marker.h"
2020-10-28 05:07:14 +08:00
#include "xyplotaxisdialog.h"
#include "Util/util.h"
#include "unit.h"
2021-10-21 19:00:34 +08:00
#include "preferences.h"
#include "appwindow.h"
2021-10-21 19:00:34 +08:00
#include <QGridLayout>
#include <cmath>
#include <QFrame>
#include <QPainter>
#include <QDebug>
2021-04-13 02:15:38 +08:00
#include <QFileDialog>
using namespace std;
2020-10-28 05:07:14 +08:00
TraceXYPlot::TraceXYPlot(TraceModel &model, QWidget *parent)
: TracePlot(model, parent)
{
2022-03-16 21:45:59 +08:00
xAxisMode = XAxisMode::UseSpan;
// Setup default axis
2022-03-16 21:45:59 +08:00
setYAxis(0, YAxis::Type::Magnitude, false, false, -120, 20, 10);
setYAxis(1, YAxis::Type::Phase, false, false, -180, 180, 30);
// enable autoscaling and set for full span (no information about actual span available yet)
2020-11-02 05:56:31 +08:00
updateSpan(0, 6000000000);
2022-03-16 21:45:59 +08:00
setXAxis(XAxis::Type::Frequency, XAxisMode::UseSpan, false, 0, 6000000000, 600000000);
initializeTraceInfo();
}
2022-03-16 21:45:59 +08:00
void TraceXYPlot::setYAxis(int axis, YAxis::Type type, bool log, bool autorange, double min, double max, double div)
{
2022-03-16 22:02:15 +08:00
if(yAxis[axis].getType() != type) {
// remove traces that are active but not supported with the new axis type
bool erased = false;
do {
erased = false;
for(auto t : tracesAxis[axis]) {
if(!supported(t, type)) {
enableTraceAxis(t, axis, false);
erased = true;
break;
}
}
} while(erased);
}
2022-03-16 22:02:15 +08:00
yAxis[axis].set(type, log, autorange, min, max, div);
traceRemovalPending = true;
updateContextMenu();
replot();
}
2022-03-16 21:45:59 +08:00
void TraceXYPlot::setXAxis(XAxis::Type type, XAxisMode mode, bool log, double min, double max, double div)
{
2022-03-16 21:45:59 +08:00
bool autorange = false;
if(mode == XAxisMode::FitTraces || mode == XAxisMode::UseSpan) {
autorange = true;
}
2022-03-16 22:02:15 +08:00
xAxis.set(type, log, autorange, min, max, div);
2022-03-16 21:45:59 +08:00
xAxisMode = mode;
traceRemovalPending = true;
updateContextMenu();
replot();
}
2020-10-28 05:07:14 +08:00
void TraceXYPlot::enableTrace(Trace *t, bool enabled)
{
for(int axis = 0;axis < 2;axis++) {
2022-03-16 22:02:15 +08:00
enableTraceAxis(t, axis, enabled && supported(t, yAxis[axis].getType()));
}
}
void TraceXYPlot::updateSpan(double min, double max)
2020-10-23 03:12:33 +08:00
{
TracePlot::updateSpan(min, max);
updateAxisTicks();
2020-10-23 03:12:33 +08:00
}
void TraceXYPlot::replot()
{
2022-03-16 22:02:15 +08:00
if(xAxisMode != XAxisMode::Manual || yAxis[0].getAutorange() || yAxis[1].getAutorange()) {
updateAxisTicks();
}
TracePlot::replot();
}
2020-12-05 06:49:52 +08:00
nlohmann::json TraceXYPlot::toJSON()
{
nlohmann::json j;
nlohmann::json jX;
2022-03-16 22:02:15 +08:00
jX["type"] = xAxis.TypeToName().toStdString();
2022-03-16 21:45:59 +08:00
jX["mode"] = AxisModeToName(xAxisMode).toStdString();
2022-03-16 22:02:15 +08:00
jX["log"] = xAxis.getLog();
jX["min"] = xAxis.getRangeMin();
jX["max"] = xAxis.getRangeMax();
jX["div"] = xAxis.getRangeDiv();
2020-12-05 06:49:52 +08:00
j["XAxis"] = jX;
for(unsigned int i=0;i<2;i++) {
nlohmann::json jY;
2022-03-16 22:02:15 +08:00
jY["type"] = yAxis[i].TypeToName().toStdString();
jY["log"] = yAxis[i].getLog();
jY["autorange"] = yAxis[i].getAutorange();
jY["min"] = yAxis[i].getRangeMin();
jY["max"] = yAxis[i].getRangeMax();
jY["div"] = yAxis[i].getRangeDiv();
2020-12-05 06:49:52 +08:00
nlohmann::json jtraces;
for(auto t : tracesAxis[i]) {
jtraces.push_back(t->toHash());
}
jY["traces"] = jtraces;
if(i==0) {
j["YPrimary"] = jY;
} else {
j["YSecondary"] = jY;
}
}
return j;
}
void TraceXYPlot::fromJSON(nlohmann::json j)
{
auto jX = j["XAxis"];
// old format used enum value for type and mode, new format uses string encoding (more robust when additional enum values are added).
// Check which format is used and parse accordingly
2022-03-16 21:45:59 +08:00
XAxis::Type xtype;
if(jX["type"].type() == nlohmann::json::value_t::string) {
2022-03-16 21:45:59 +08:00
xtype = XAxis::TypeFromName(QString::fromStdString(jX["type"]));
} else {
2022-03-16 21:45:59 +08:00
xtype = jX.value("type", XAxis::Type::Frequency);
}
XAxisMode xmode;
if(jX["mode"].type() == nlohmann::json::value_t::string) {
xmode = AxisModeFromName(QString::fromStdString(jX["mode"]));
} else {
xmode = jX.value("mode", XAxisMode::UseSpan);
}
2020-12-05 06:49:52 +08:00
// auto xlog = jX.value("log", false);
auto xmin = jX.value("min", 0.0);
auto xmax = jX.value("max", 6000000000.0);
auto xdiv = jX.value("div", 600000000.0);
auto xlog = jX.value("log", false);
setXAxis(xtype, xmode, xlog, xmin, xmax, xdiv);
2020-12-05 06:49:52 +08:00
nlohmann::json jY[2] = {j["YPrimary"], j["YSecondary"]};
for(unsigned int i=0;i<2;i++) {
2022-03-16 21:45:59 +08:00
YAxis::Type ytype;
if(jY[i]["type"].type() == nlohmann::json::value_t::string) {
2022-03-16 21:45:59 +08:00
ytype = YAxis::TypeFromName(QString::fromStdString(jY[i]["type"]));
} else {
2022-03-16 21:45:59 +08:00
ytype = jY[i].value("type", YAxis::Type::Disabled);
}
2020-12-05 06:49:52 +08:00
auto yauto = jY[i].value("autorange", true);
auto ylog = jY[i].value("log", false);
auto ymin = jY[i].value("min", -120.0);
auto ymax = jY[i].value("max", 20.0);
auto ydiv = jY[i].value("div", 10.0);
2020-12-05 06:49:52 +08:00
setYAxis(i, ytype, ylog, yauto, ymin, ymax, ydiv);
for(unsigned int hash : jY[i]["traces"]) {
// attempt to find the traces with this hash
bool found = false;
for(auto t : model.getTraces()) {
if(t->toHash() == hash) {
enableTraceAxis(t, i, true);
found = true;
break;
}
}
if(!found) {
qWarning() << "Unable to find trace with hash" << hash;
}
}
}
}
2022-03-16 21:45:59 +08:00
bool TraceXYPlot::isTDRtype(YAxis::Type type)
2020-10-28 05:07:14 +08:00
{
switch(type) {
2022-03-16 21:45:59 +08:00
case YAxis::Type::ImpulseReal:
case YAxis::Type::ImpulseMag:
case YAxis::Type::Step:
case YAxis::Type::Impedance:
2020-10-28 05:07:14 +08:00
return true;
default:
return false;
}
}
2020-11-02 05:56:31 +08:00
void TraceXYPlot::axisSetupDialog()
{
auto setup = new XYplotAxisDialog(this);
if(AppWindow::showGUI()) {
setup->show();
}
2020-11-02 05:56:31 +08:00
}
bool TraceXYPlot::configureForTrace(Trace *t)
{
switch(t->outputType()) {
case Trace::DataType::Frequency:
2022-03-16 21:45:59 +08:00
setXAxis(XAxis::Type::Frequency, XAxisMode::FitTraces, false, 0, 1, 0.1);
setYAxis(0, YAxis::Type::Magnitude, false, true, 0, 1, 1.0);
setYAxis(1, YAxis::Type::Phase, false, true, 0, 1, 1.0);
break;
case Trace::DataType::Time:
2022-03-16 21:45:59 +08:00
setXAxis(XAxis::Type::Time, XAxisMode::FitTraces, false, 0, 1, 0.1);
setYAxis(0, YAxis::Type::ImpulseMag, false, true, 0, 1, 1.0);
setYAxis(1, YAxis::Type::Disabled, false, true, 0, 1, 1.0);
break;
case Trace::DataType::Power:
2022-03-16 21:45:59 +08:00
setXAxis(XAxis::Type::Power, XAxisMode::FitTraces, false, 0, 1, 0.1);
setYAxis(0, YAxis::Type::Magnitude, false, true, 0, 1, 1.0);
setYAxis(1, YAxis::Type::Phase, false, true, 0, 1, 1.0);
break;
case Trace::DataType::Invalid:
// unable to add
return false;
}
traceRemovalPending = true;
return true;
}
2020-10-28 05:07:14 +08:00
void TraceXYPlot::updateContextMenu()
{
contextmenu->clear();
auto setup = new QAction("Axis setup...", contextmenu);
2020-11-02 05:56:31 +08:00
connect(setup, &QAction::triggered, this, &TraceXYPlot::axisSetupDialog);
contextmenu->addAction(setup);
2021-05-15 02:34:23 +08:00
contextmenu->addSeparator();
auto image = new QAction("Save image...", contextmenu);
contextmenu->addAction(image);
connect(image, &QAction::triggered, [=]() {
auto filename = QFileDialog::getSaveFileName(nullptr, "Save plot image", "", "PNG image files (*.png)", nullptr, QFileDialog::DontUseNativeDialog);
if(filename.isEmpty()) {
// aborted selection
return;
}
if(filename.endsWith(".png")) {
filename.chop(4);
}
filename += ".png";
grab().save(filename);
});
auto createMarker = contextmenu->addAction("Add marker here");
bool activeTraces = false;
for(auto t : traces) {
if(t.second) {
activeTraces = true;
break;
}
}
if(!activeTraces) {
createMarker->setEnabled(false);
}
connect(createMarker, &QAction::triggered, [=](){
createMarkerAtPosition(contextmenuClickpoint);
});
for(int axis = 0;axis < 2;axis++) {
2022-03-16 22:02:15 +08:00
if(yAxis[axis].getType() == YAxis::Type::Disabled) {
continue;
}
if(axis == 0) {
contextmenu->addSection("Primary Traces");
} else {
contextmenu->addSection("Secondary Traces");
}
for(auto t : traces) {
// Skip traces that are not applicable for the selected axis type
2022-03-16 22:02:15 +08:00
if(!supported(t.first, yAxis[axis].getType())) {
continue;
}
auto action = new QAction(t.first->name(), contextmenu);
action->setCheckable(true);
if(tracesAxis[axis].find(t.first) != tracesAxis[axis].end()) {
action->setChecked(true);
}
connect(action, &QAction::toggled, [=](bool active) {
enableTraceAxis(t.first, axis, active);
});
contextmenu->addAction(action);
}
}
2021-05-15 02:34:23 +08:00
2021-04-13 02:15:38 +08:00
contextmenu->addSeparator();
auto close = new QAction("Close", contextmenu);
contextmenu->addAction(close);
connect(close, &QAction::triggered, [=]() {
markedForDeletion = true;
});
}
bool TraceXYPlot::dropSupported(Trace *t)
{
2021-12-11 06:36:28 +08:00
if(domainMatch(t) && !supported(t)) {
// correct domain configured but Y axis do not match, prevent drop
return false;
}
// either directly compatible or domain change required
return true;
}
2020-11-29 05:34:40 +08:00
bool TraceXYPlot::supported(Trace *t)
{
// potentially possible to add every kind of trace (depends on axis)
2022-03-16 22:02:15 +08:00
if(supported(t, yAxis[0].getType()) || supported(t, yAxis[1].getType())) {
return true;
} else {
// no axis
return false;
}
}
void TraceXYPlot::draw(QPainter &p)
{
auto pref = Preferences::getInstance();
constexpr int yAxisSpace = 55;
constexpr int yAxisDisabledSpace = 10;
constexpr int xAxisSpace = 30;
auto w = p.window();
auto pen = QPen(pref.Graphs.Color.axis, 0);
pen.setCosmetic(true);
p.setPen(pen);
2022-03-16 22:02:15 +08:00
plotAreaLeft = yAxis[0].getType() == YAxis::Type::Disabled ? yAxisDisabledSpace : yAxisSpace;
plotAreaWidth = w.width();
plotAreaTop = 10;
plotAreaBottom = w.height() - xAxisSpace;
2022-03-16 22:02:15 +08:00
if(yAxis[0].getType() != YAxis::Type::Disabled) {
plotAreaWidth -= yAxisSpace;
} else {
plotAreaWidth -= yAxisDisabledSpace;
}
2022-03-16 22:02:15 +08:00
if(yAxis[1].getType() != YAxis::Type::Disabled) {
plotAreaWidth -= yAxisSpace;
} else {
plotAreaWidth -= yAxisDisabledSpace;
}
auto plotRect = QRect(plotAreaLeft, plotAreaTop, plotAreaWidth + 1, plotAreaBottom-plotAreaTop);
p.drawRect(plotRect);
// draw axis types
auto font = p.font();
font.setPixelSize(AxisLabelSize);
p.setFont(font);
2022-03-16 22:02:15 +08:00
p.drawText(QRect(0, w.height()-AxisLabelSize*1.5, w.width(), AxisLabelSize*1.5), Qt::AlignHCenter, xAxis.TypeToName());
for(int i=0;i<2;i++) {
2022-03-16 22:02:15 +08:00
if(yAxis[i].getType() == YAxis::Type::Disabled) {
continue;
}
2022-03-16 22:02:15 +08:00
QString labelY = yAxis[i].TypeToName();
p.setPen(QPen(pref.Graphs.Color.axis, 1));
auto xStart = i == 0 ? 0 : w.width() - AxisLabelSize * 1.5;
p.save();
p.translate(xStart, w.height()-xAxisSpace);
p.rotate(-90);
p.drawText(QRect(0, 0, w.height()-xAxisSpace, AxisLabelSize*1.5), Qt::AlignHCenter, labelY);
p.restore();
// draw ticks
2022-03-16 22:02:15 +08:00
if(yAxis[i].getType() != YAxis::Type::Disabled && yAxis[i].getTicks().size() > 0) {
// this only works for evenly distributed ticks:
2022-03-16 22:02:15 +08:00
auto max = qMax(abs(yAxis[i].getTicks().front()), abs(yAxis[i].getTicks().back()));
2020-11-30 01:33:25 +08:00
double step;
2022-03-16 22:02:15 +08:00
if(yAxis[i].getTicks().size() >= 2) {
step = abs(yAxis[i].getTicks()[0] - yAxis[i].getTicks()[1]);
2020-11-30 01:33:25 +08:00
} else {
// only one tick, set arbitrary number of digits
step = max / 1000;
}
int significantDigits = floor(log10(max)) - floor(log10(step)) + 1;
2022-03-16 22:02:15 +08:00
for(unsigned int j = 0; j < yAxis[i].getTicks().size(); j++) {
auto yCoord = yAxis[i].transform(yAxis[i].getTicks()[j], w.height() - xAxisSpace, plotAreaTop);
p.setPen(QPen(pref.Graphs.Color.axis, 1));
// draw tickmark on axis
auto tickStart = i == 0 ? plotAreaLeft : plotAreaLeft + plotAreaWidth;
auto tickLen = i == 0 ? -2 : 2;
p.drawLine(tickStart, yCoord, tickStart + tickLen, yCoord);
2021-12-27 23:13:03 +08:00
QString unit = "";
QString prefix = " ";
2021-12-27 23:13:03 +08:00
if(pref.Graphs.showUnits) {
2022-03-16 22:02:15 +08:00
unit = yAxis[i].Unit();
prefix = yAxis[i].Prefixes();
2021-12-27 23:13:03 +08:00
}
2022-03-16 22:02:15 +08:00
auto tickValue = Unit::ToString(yAxis[i].getTicks()[j], unit, prefix, significantDigits);
if(i == 0) {
p.drawText(QRectF(0, yCoord - AxisLabelSize/2 - 2, tickStart + 2 * tickLen, AxisLabelSize), Qt::AlignRight, tickValue);
} else {
p.drawText(QRectF(tickStart + 2 * tickLen + 2, yCoord - AxisLabelSize/2 - 2, yAxisSpace, AxisLabelSize), Qt::AlignLeft, tickValue);
}
// tick lines
if(yCoord == plotAreaTop || yCoord == w.height() - xAxisSpace) {
// skip tick lines right on the plot borders
continue;
}
if(i == 0) {
// only draw tick lines for primary axis
if (pref.Graphs.Color.Ticks.Background.enabled) {
if (j%2)
{
2022-03-16 22:02:15 +08:00
int yCoordTop = yAxis[i].transform(yAxis[i].getTicks()[j], plotAreaTop, w.height() - xAxisSpace);
int yCoordBot = yAxis[i].transform(yAxis[i].getTicks()[j-1], plotAreaTop, w.height() - xAxisSpace);
2021-11-02 02:15:22 +08:00
if(yCoordTop > yCoordBot) {
auto buf = yCoordBot;
yCoordBot = yCoordTop;
yCoordTop = buf;
}
p.setBrush(pref.Graphs.Color.Ticks.Background.background);
p.setPen(pref.Graphs.Color.Ticks.Background.background);
auto rect = QRect(plotAreaLeft+1, yCoordTop+1, plotAreaWidth-2, yCoordBot-yCoordTop-2);
p.drawRect(rect);
}
}
p.setPen(QPen(pref.Graphs.Color.Ticks.divisions, 0.5, Qt::DashLine));
p.drawLine(plotAreaLeft, yCoord, plotAreaLeft + plotAreaWidth, yCoord);
}
}
}
// plot traces
p.setClipRect(QRect(plotRect.x()+1, plotRect.y()+1, plotRect.width()-2, plotRect.height()-2));
for(auto t : tracesAxis[i]) {
if(!t->isVisible()) {
continue;
}
pen = QPen(t->color(), pref.Graphs.lineWidth);
pen.setCosmetic(true);
if(i == 1) {
pen.setStyle(Qt::DotLine);
} else {
pen.setStyle(Qt::SolidLine);
}
p.setPen(pen);
2020-11-29 05:34:40 +08:00
auto nPoints = t->size();
for(unsigned int j=1;j<nPoints;j++) {
2022-03-16 22:02:15 +08:00
auto last = traceToCoordinate(t, j-1, yAxis[i]);
auto now = traceToCoordinate(t, j, yAxis[i]);
if(isnan(last.y()) || isnan(now.y()) || isinf(last.y()) || isinf(now.y())) {
continue;
}
// scale to plot coordinates
2020-11-23 04:25:41 +08:00
auto p1 = plotValueToPixel(last, i);
auto p2 = plotValueToPixel(now, i);
if(!plotRect.contains(p1) && !plotRect.contains(p2)) {
// completely out of frame
continue;
}
// draw line
p.drawLine(p1, p2);
}
if(i == 0 && nPoints > 0) {
// only draw markers on primary YAxis and if the trace has at least one point
auto markers = t->getMarkers();
for(auto m : markers) {
double xPosition = m->getPosition();
2022-03-16 22:02:15 +08:00
if (xPosition < xAxis.getRangeMin() || xPosition > xAxis.getRangeMax()) {
2020-12-05 19:59:23 +08:00
// marker not in graph range
continue;
}
if(xPosition < t->minX() || xPosition > t->maxX()) {
// marker not in trace range
continue;
}
2020-11-29 05:34:40 +08:00
auto t = m->getTrace();
2022-01-07 19:37:47 +08:00
auto index = t->index(xPosition);
QPointF markerPoint;
if(xPosition < t->sample(index).x && index > 0) {
// marker is not located exactly at this point, interpolate display location
2022-03-16 22:02:15 +08:00
QPointF l0 = traceToCoordinate(t, index - 1, yAxis[i]);
QPointF l1 = traceToCoordinate(t, index, yAxis[i]);
2022-01-07 19:37:47 +08:00
auto t0 = (xPosition - t->sample(index - 1).x) / (t->sample(index).x - t->sample(index - 1).x);
markerPoint = l0 + (l1 - l0) * t0;
} else {
2022-03-16 22:02:15 +08:00
markerPoint = traceToCoordinate(t, t->index(xPosition), yAxis[i]);
2022-01-07 19:37:47 +08:00
}
2020-11-23 04:25:41 +08:00
auto point = plotValueToPixel(markerPoint, i);
if(!plotRect.contains(point)) {
// out of screen
continue;
}
auto symbol = m->getSymbol();
point += QPoint(-symbol.width()/2, -symbol.height());
p.drawPixmap(point, symbol);
}
}
}
p.setClipping(false);
}
2022-03-16 22:02:15 +08:00
if(xAxis.getTicks().size() >= 1) {
// draw X ticks
int significantDigits;
bool displayFullFreq;
2022-03-16 22:02:15 +08:00
if(xAxis.getLog()) {
significantDigits = 5;
displayFullFreq = true;
} else {
// this only works for evenly distributed ticks:
2022-03-16 22:02:15 +08:00
auto max = qMax(abs(xAxis.getTicks().front()), abs(xAxis.getTicks().back()));
double step;
2022-03-16 22:02:15 +08:00
if(xAxis.getTicks().size() >= 2) {
step = abs(xAxis.getTicks()[0] - xAxis.getTicks()[1]);
} else {
// only one tick, set arbitrary number of digits
step = max / 1000;
}
significantDigits = floor(log10(max)) - floor(log10(step)) + 1;
displayFullFreq = significantDigits <= 5;
}
constexpr int displayLastDigits = 4;
QString prefixes = "fpnum kMG";
2021-12-27 23:13:03 +08:00
QString unit = "";
if(pref.Graphs.showUnits) {
2022-03-16 22:02:15 +08:00
unit = xAxis.Unit();
2021-12-27 23:13:03 +08:00
}
QString commonPrefix = QString();
if(!displayFullFreq) {
2022-03-16 22:02:15 +08:00
auto fullFreq = Unit::ToString(xAxis.getTicks().front(), unit, prefixes, significantDigits);
commonPrefix = fullFreq.at(fullFreq.size() - 1);
auto front = fullFreq;
2021-12-27 23:13:03 +08:00
front.truncate(fullFreq.size() - displayLastDigits - unit.length());
auto back = fullFreq;
back.remove(0, front.size());
back.append("..");
p.setPen(QPen(QColor("orange")));
QRect bounding;
p.drawText(QRect(2, plotAreaBottom + AxisLabelSize + 5, w.width(), AxisLabelSize), 0, front, &bounding);
p.setPen(pref.Graphs.Color.axis);
p.drawText(QRect(bounding.x() + bounding.width(), plotAreaBottom + AxisLabelSize + 5, w.width(), AxisLabelSize), 0, back);
}
int lastTickLabelEnd = 0;
2022-03-16 22:02:15 +08:00
for(auto t : xAxis.getTicks()) {
auto xCoord = xAxis.transform(t, plotAreaLeft, plotAreaLeft + plotAreaWidth);
p.setPen(QPen(pref.Graphs.Color.axis, 1));
p.drawLine(xCoord, plotAreaBottom, xCoord, plotAreaBottom + 2);
if(xCoord != plotAreaLeft && xCoord != plotAreaLeft + plotAreaWidth) {
p.setPen(QPen(pref.Graphs.Color.Ticks.divisions, 0.5, Qt::DashLine));
p.drawLine(xCoord, plotAreaTop, xCoord, plotAreaBottom);
}
if(xCoord - 40 <= lastTickLabelEnd) {
// would overlap previous tick label, skip
continue;
}
2021-12-27 23:13:03 +08:00
auto tickValue = Unit::ToString(t, unit, prefixes, significantDigits);
p.setPen(QPen(pref.Graphs.Color.axis, 1));
if(displayFullFreq) {
QRect bounding;
p.drawText(QRect(xCoord - 40, plotAreaBottom + 5, 80, AxisLabelSize), Qt::AlignHCenter, tickValue, &bounding);
lastTickLabelEnd = bounding.x() + bounding.width();
} else {
// check if the same prefix was used as in the fullFreq string
if(tickValue.at(tickValue.size() - 1) != commonPrefix) {
// prefix changed, we reached the next order of magnitude. Force same prefix as in fullFreq and add extra digit
tickValue = Unit::ToString(t, "", commonPrefix, significantDigits + 1);
}
2021-12-27 23:13:03 +08:00
tickValue.remove(0, tickValue.size() - displayLastDigits - unit.length());
QRect bounding;
p.drawText(QRect(xCoord - 40, plotAreaBottom + 5, 80, AxisLabelSize), Qt::AlignHCenter, tickValue, &bounding);
lastTickLabelEnd = bounding.x() + bounding.width();
p.setPen(QPen(QColor("orange")));
p.drawText(QRect(0, plotAreaBottom + 5, bounding.x() - 1, AxisLabelSize), Qt::AlignRight, "..", &bounding);
}
}
}
if(dropPending) {
p.setOpacity(0.5);
p.setBrush(Qt::white);
p.setPen(Qt::white);
2022-03-16 22:02:15 +08:00
if((yAxis[0].getType() == YAxis::Type::Disabled || !supported(dropTrace, yAxis[0].getType()))
|| (yAxis[1].getType() == YAxis::Type::Disabled || !supported(dropTrace, yAxis[1].getType()))) {
// only one axis enabled, show drop area over whole plot
p.drawRect(plotRect);
auto font = p.font();
font.setPixelSize(20);
p.setFont(font);
p.setOpacity(1.0);
p.setPen(Qt::white);
auto text = "Drop here to add\n" + dropTrace->name() + "\nto XY-plot";
p.drawText(plotRect, Qt::AlignCenter, text);
} else {
2020-11-23 04:25:41 +08:00
// both axis enabled, show regions
auto leftRect = plotRect;
leftRect.setWidth(plotRect.width() * 0.3);
auto centerRect = plotRect;
centerRect.setX(centerRect.x() + plotRect.width() * 0.35);
centerRect.setWidth(plotRect.width() * 0.3);
auto rightRect = plotRect;
rightRect.setX(rightRect.x() + plotRect.width() * 0.7);
rightRect.setWidth(plotRect.width() * 0.3);
p.drawRect(leftRect);
p.drawRect(centerRect);
p.drawRect(rightRect);
p.setOpacity(1.0);
p.setPen(Qt::white);
auto font = p.font();
font.setPixelSize(20);
p.setFont(font);
p.drawText(leftRect, Qt::AlignCenter, "Drop here to add\nto primary axis");
p.drawText(centerRect, Qt::AlignCenter, "Drop here to add\nto boths axes");
p.drawText(rightRect, Qt::AlignCenter, "Drop here to add\nto secondary axis");
}
}
}
void TraceXYPlot::updateAxisTicks()
{
2022-03-16 21:45:59 +08:00
if(xAxisMode != XAxisMode::Manual) {
// automatic mode, figure out limits
double max = std::numeric_limits<double>::lowest();
double min = std::numeric_limits<double>::max();
2022-03-16 21:45:59 +08:00
if(xAxisMode == XAxisMode::UseSpan) {
min = sweep_fmin;
max = sweep_fmax;
2022-03-16 21:45:59 +08:00
} else if(xAxisMode == XAxisMode::FitTraces) {
for(auto t : traces) {
bool enabled = (tracesAxis[0].find(t.first) != tracesAxis[0].end()
|| tracesAxis[1].find(t.first) != tracesAxis[1].end());
auto trace = t.first;
if(enabled && trace->isVisible()) {
2020-11-29 05:34:40 +08:00
if(!trace->size()) {
2020-11-27 00:45:55 +08:00
// empty trace, do not use for automatic axis calculation
continue;
}
// this trace is currently displayed
2020-11-29 05:34:40 +08:00
double trace_min = trace->minX();
double trace_max = trace->maxX();
2022-03-16 22:02:15 +08:00
if(xAxis.getType() == XAxis::Type::Distance) {
trace_min = trace->timeToDistance(trace_min);
trace_max = trace->timeToDistance(trace_max);
}
if(trace_min < min) {
min = trace_min;
}
if(trace_max > max) {
max = trace_max;
}
}
}
}
2020-11-27 00:45:55 +08:00
if(min < max) {
2022-03-16 22:02:15 +08:00
xAxis.set(xAxis.getType(), xAxis.getLog(), true, min, max, 0);
}
}
for(int i=0;i<2;i++) {
2022-03-16 22:02:15 +08:00
if(yAxis[i].getAutorange()) {
// automatic mode, figure out limits
double max = std::numeric_limits<double>::lowest();
double min = std::numeric_limits<double>::max();
for(auto t : tracesAxis[i]) {
if(!t->isVisible()) {
continue;
}
2020-11-29 05:34:40 +08:00
unsigned int samples = t->size();
for(unsigned int j=0;j<samples;j++) {
2022-03-16 22:02:15 +08:00
auto point = traceToCoordinate(t, j, yAxis[i]);
2020-11-27 00:45:55 +08:00
2022-03-16 22:02:15 +08:00
if(point.x() < xAxis.getRangeMin() || point.x() > xAxis.getRangeMax()) {
2020-11-27 00:45:55 +08:00
// this point is not in the displayed X range, skip for auto Y range calculation
continue;
}
if(point.y() > max) {
max = point.y();
2020-11-29 05:34:40 +08:00
}
if(point.y() < min) {
min = point.y();
}
}
}
if(max >= min) {
auto range = max - min;
if(range == 0.0) {
// this could happen if all values in a trace are identical (e.g. imported ideal touchstone files)
if(max == 0.0) {
// simply use +/-1 range
max = 1.0;
min = -1.0;
} else {
// +/-5% around value
max += abs(max * 0.05);
min -= abs(max * 0.05);
}
} else {
// add 5% of range at both ends
min -= range * 0.05;
max += range * 0.05;
}
} else {
// max/min still at default values, no valid samples are available for this axis, use default range
max = 1.0;
min = -1.0;
}
2022-03-16 22:02:15 +08:00
yAxis[i].set(yAxis[i].getType(), yAxis[i].getLog(), true, min, max, 0);
}
}
}
2022-03-16 21:45:59 +08:00
TraceXYPlot::XAxisMode TraceXYPlot::AxisModeFromName(QString name)
{
2022-03-16 21:45:59 +08:00
for(unsigned int i=0;i<(int) XAxisMode::Last;i++) {
if(AxisModeToName((XAxisMode) i) == name) {
return (XAxisMode) i;
}
}
// not found, use default
return XAxisMode::UseSpan;
}
QString TraceXYPlot::AxisModeToName(TraceXYPlot::XAxisMode mode)
{
switch(mode) {
case XAxisMode::Manual: return "Manual"; break;
case XAxisMode::FitTraces: return "Fit Traces"; break;
case XAxisMode::UseSpan: return "Use Span"; break;
default: return "Unknown";
}
}
2020-10-28 05:07:14 +08:00
void TraceXYPlot::enableTraceAxis(Trace *t, int axis, bool enabled)
{
2022-03-16 22:02:15 +08:00
if(enabled && !supported(t, yAxis[axis].getType())) {
// unable to add trace to the requested axis
return;
}
if(axis == 0) {
TracePlot::enableTrace(t, enabled);
}
bool alreadyEnabled = tracesAxis[axis].find(t) != tracesAxis[axis].end();
if(alreadyEnabled != enabled) {
if(enabled) {
tracesAxis[axis].insert(t);
} else {
tracesAxis[axis].erase(t);
if(axis == 0) {
2020-10-28 05:07:14 +08:00
disconnect(t, &Trace::markerAdded, this, &TraceXYPlot::markerAdded);
disconnect(t, &Trace::markerRemoved, this, &TraceXYPlot::markerRemoved);
auto tracemarkers = t->getMarkers();
for(auto m : tracemarkers) {
markerRemoved(m);
}
}
}
updateContextMenu();
replot();
}
}
2021-12-11 06:36:28 +08:00
bool TraceXYPlot::domainMatch(Trace *t)
{
2022-03-16 22:02:15 +08:00
switch(xAxis.getType()) {
2022-03-16 21:45:59 +08:00
case XAxis::Type::Frequency:
2021-12-11 06:36:28 +08:00
return t->outputType() == Trace::DataType::Frequency;
2022-03-16 21:45:59 +08:00
case XAxis::Type::Distance:
case XAxis::Type::Time:
2021-12-11 06:36:28 +08:00
return t->outputType() == Trace::DataType::Time;
2022-03-16 21:45:59 +08:00
case XAxis::Type::Power:
2021-12-11 06:36:28 +08:00
return t->outputType() == Trace::DataType::Power;
2022-03-16 21:45:59 +08:00
case XAxis::Type::Last:
2021-12-11 06:36:28 +08:00
return false;
}
return false;
}
2022-03-16 21:45:59 +08:00
bool TraceXYPlot::supported(Trace *t, YAxis::Type type)
2021-12-11 06:36:28 +08:00
{
if(!domainMatch(t)) {
return false;
2020-11-29 05:34:40 +08:00
}
switch(type) {
2022-03-16 21:45:59 +08:00
case YAxis::Type::Disabled:
return false;
2022-03-16 21:45:59 +08:00
case YAxis::Type::VSWR:
case YAxis::Type::SeriesR:
case YAxis::Type::Reactance:
case YAxis::Type::Capacitance:
case YAxis::Type::Inductance:
case YAxis::Type::QualityFactor:
if(!t->isReflection()) {
return false;
}
break;
2022-03-16 21:45:59 +08:00
case YAxis::Type::GroupDelay:
2021-12-11 06:36:28 +08:00
if(t->isReflection()) {
return false;
}
break;
default:
break;
}
return true;
}
2022-03-16 22:02:15 +08:00
QPointF TraceXYPlot::traceToCoordinate(Trace *t, unsigned int sample, YAxis &yaxis)
{
QPointF ret = QPointF(numeric_limits<double>::quiet_NaN(), numeric_limits<double>::quiet_NaN());
2022-03-16 22:02:15 +08:00
ret.setX(xAxis.sampleToCoordinate(t->sample(sample), t, sample));
2022-03-16 21:45:59 +08:00
ret.setY(yaxis.sampleToCoordinate(t->sample(sample), t, sample));
return ret;
}
2020-10-23 03:12:33 +08:00
2020-11-23 04:25:41 +08:00
QPoint TraceXYPlot::plotValueToPixel(QPointF plotValue, int Yaxis)
{
QPoint p;
2022-03-16 22:02:15 +08:00
p.setX(xAxis.transform(plotValue.x(), plotAreaLeft, plotAreaLeft + plotAreaWidth));
p.setY(yAxis[Yaxis].transform(plotValue.y(), plotAreaBottom, plotAreaTop));
2020-11-23 04:25:41 +08:00
return p;
}
QPointF TraceXYPlot::pixelToPlotValue(QPoint pixel, int Yaxis)
{
QPointF p;
2022-03-16 22:02:15 +08:00
p.setX(xAxis.inverseTransform(pixel.x(), plotAreaLeft, plotAreaLeft + plotAreaWidth));
p.setY(yAxis[Yaxis].inverseTransform(pixel.y(), plotAreaBottom, plotAreaTop));
return p;
}
QPoint TraceXYPlot::markerToPixel(Marker *m)
2020-11-23 04:25:41 +08:00
{
2020-11-29 05:34:40 +08:00
auto t = m->getTrace();
2022-03-16 22:02:15 +08:00
QPointF plotPoint = traceToCoordinate(t, t->index(m->getPosition()), yAxis[0]);
2020-11-23 04:25:41 +08:00
return plotValueToPixel(plotPoint, 0);
}
2021-05-15 02:34:23 +08:00
double TraceXYPlot::nearestTracePoint(Trace *t, QPoint pixel, double *distance)
2020-11-23 04:25:41 +08:00
{
if(!tracesAxis[0].count(t)) {
// trace not enabled
return 0;
}
double closestDistance = numeric_limits<double>::max();
double closestXpos = 0;
2022-01-07 19:37:47 +08:00
unsigned int closestIndex = 0;
2020-11-29 05:34:40 +08:00
auto samples = t->size();
2020-11-23 04:25:41 +08:00
for(unsigned int i=0;i<samples;i++) {
2022-03-16 22:02:15 +08:00
auto point = traceToCoordinate(t, i, yAxis[0]);
2020-11-23 04:25:41 +08:00
if(isnan(point.x()) || isnan(point.y())) {
continue;
}
auto plotPoint = plotValueToPixel(point, 0);
QPointF diff = plotPoint - pixel;
auto distance = diff.x() * diff.x() + diff.y() * diff.y();
2020-11-23 04:25:41 +08:00
if(distance < closestDistance) {
closestDistance = distance;
closestXpos = point.x();
2022-01-07 19:37:47 +08:00
closestIndex = i;
}
}
closestDistance = sqrt(closestDistance);
if(closestIndex > 0) {
2022-03-16 22:02:15 +08:00
auto l1 = plotValueToPixel(traceToCoordinate(t, closestIndex - 1, yAxis[0]), 0);
auto l2 = plotValueToPixel(traceToCoordinate(t, closestIndex, yAxis[0]), 0);
2022-01-07 19:37:47 +08:00
double ratio;
auto distance = Util::distanceToLine(pixel, l1, l2, nullptr, &ratio);
if(distance < closestDistance) {
closestDistance = distance;
closestXpos = t->sample(closestIndex-1).x + (t->sample(closestIndex).x - t->sample(closestIndex-1).x) * ratio;
}
}
if(closestIndex < t->size() - 1) {
2022-03-16 22:02:15 +08:00
auto l1 = plotValueToPixel(traceToCoordinate(t, closestIndex, yAxis[0]), 0);
auto l2 = plotValueToPixel(traceToCoordinate(t, closestIndex + 1, yAxis[0]), 0);
2022-01-07 19:37:47 +08:00
double ratio;
auto distance = Util::distanceToLine(pixel, l1, l2, nullptr, &ratio);
if(distance < closestDistance) {
closestDistance = distance;
closestXpos = t->sample(closestIndex).x + (t->sample(closestIndex+1).x - t->sample(closestIndex).x) * ratio;
2020-11-23 04:25:41 +08:00
}
}
2022-03-16 22:02:15 +08:00
if(xAxis.getType() == XAxis::Type::Distance) {
closestXpos = t->distanceToTime(closestXpos);
2021-05-15 02:34:23 +08:00
}
if(distance) {
*distance = closestDistance;
}
2020-11-23 04:25:41 +08:00
return closestXpos;
}
2022-03-16 21:45:59 +08:00
bool TraceXYPlot::markerVisible(double x)
{
2022-03-16 22:02:15 +08:00
if(x >= min(xAxis.getRangeMin(), xAxis.getRangeMax()) && x <= max(xAxis.getRangeMax(), xAxis.getRangeMin())) {
return true;
} else {
return false;
}
}
void TraceXYPlot::traceDropped(Trace *t, QPoint position)
{
2021-07-10 00:42:22 +08:00
if(!supported(t)) {
// needs to switch to a different domain for the graph
if(!InformationBox::AskQuestion("X Axis Domain Change", "You dropped a trace that is not supported with the currently selected X axis domain."
" Do you want to remove all traces and change the graph to the correct domain?", true, "DomainChangeRequest")) {
// user declined to change domain, to not add trace
return;
}
if(!configureForTrace(t)) {
// failed to configure
return;
}
}
2022-03-16 22:02:15 +08:00
if(yAxis[0].getType() == YAxis::Type::Disabled && yAxis[1].getType() == YAxis::Type::Disabled) {
// no Y axis enabled, unable to drop
return;
}
2022-03-16 22:02:15 +08:00
if(yAxis[0].getType() == YAxis::Type::Disabled) {
// only axis 1 enabled
enableTraceAxis(t, 1, true);
return;
}
2022-03-16 22:02:15 +08:00
if(yAxis[1].getType() == YAxis::Type::Disabled) {
// only axis 0 enabled
enableTraceAxis(t, 0, true);
return;
}
// both axis enabled, check drop position
auto drop = Util::Scale<double>(position.x(), plotAreaLeft, plotAreaLeft + plotAreaWidth, 0.0, 1.0);
if(drop < 0.66) {
enableTraceAxis(t, 0, true);
}
if(drop > 0.33) {
enableTraceAxis(t, 1, true);
}
}
QString TraceXYPlot::mouseText(QPoint pos)
{
QString ret;
if(QRect(plotAreaLeft, 0, plotAreaWidth + 1, plotAreaBottom).contains(pos)) {
// cursor within plot area
QPointF coords[2];
coords[0] = pixelToPlotValue(pos, 0);
coords[1] = pixelToPlotValue(pos, 1);
2022-03-16 22:02:15 +08:00
int significantDigits = floor(log10(abs(xAxis.getRangeMax()))) - floor(log10((abs(xAxis.getRangeMax() - xAxis.getRangeMin())) / 1000.0)) + 1;
ret += Unit::ToString(coords[0].x(), xAxis.Unit(), "fpnum kMG", significantDigits) + "\n";
for(int i=0;i<2;i++) {
2022-03-16 22:02:15 +08:00
if(yAxis[i].getType() != YAxis::Type::Disabled) {
auto max = qMax(abs(yAxis[i].getRangeMax()), abs(yAxis[i].getRangeMin()));
auto step = abs(yAxis[i].getRangeMax() - yAxis[i].getRangeMin()) / 1000.0;
significantDigits = floor(log10(max)) - floor(log10(step)) + 1;
2022-03-16 22:02:15 +08:00
ret += Unit::ToString(coords[i].y(), yAxis[i].Unit(), yAxis[i].Prefixes(), significantDigits) + "\n";
}
}
}
return ret;
}