#include "tracesmithchart.h" #include "Marker/marker.h" #include "preferences.h" #include "ui_smithchartdialog.h" #include "unit.h" #include "QFileDialog" #include #include #include #include using namespace std; TraceSmithChart::TraceSmithChart(TraceModel &model, QWidget *parent) : TracePlot(model, parent) { limitToSpan = true; edgeReflection = 1.0; initializeTraceInfo(); } nlohmann::json TraceSmithChart::toJSON() { nlohmann::json j; j["limit_to_span"] = limitToSpan; j["limit_to_edge"] = limitToEdge; j["edge_reflection"] = edgeReflection; nlohmann::json jtraces; for(auto t : traces) { if(t.second) { jtraces.push_back(t.first->toHash()); } } j["traces"] = jtraces; return j; } void TraceSmithChart::fromJSON(nlohmann::json j) { limitToSpan = j.value("limit_to_span", true); limitToEdge = j.value("limit_to_edge", false); edgeReflection = j.value("edge_reflection", 1.0); for(unsigned int hash : j["traces"]) { // attempt to find the traces with this hash bool found = false; for(auto t : model.getTraces()) { if(t->toHash() == hash) { enableTrace(t, true); found = true; break; } } if(!found) { qWarning() << "Unable to find trace with hash" << hash; } } } void TraceSmithChart::wheelEvent(QWheelEvent *event) { // most mousewheel have 15 degree increments, the reported delta is in 1/8th degree -> 120 auto increment = event->angleDelta().y() / 120.0; // round toward bigger step in case of special higher resolution mousewheel int steps = increment > 0 ? ceil(increment) : floor(increment); constexpr double zoomfactor = 1.1; auto zoom = pow(zoomfactor, steps); edgeReflection /= zoom; triggerReplot(); } void TraceSmithChart::axisSetupDialog() { auto dialog = new QDialog(); auto ui = new Ui::SmithChartDialog(); ui->setupUi(dialog); if(limitToSpan) { ui->displayModeFreq->setCurrentIndex(1); } else { ui->displayModeFreq->setCurrentIndex(0); } if(limitToEdge) { ui->displayModeImp->setCurrentIndex(1); } else { ui->displayModeImp->setCurrentIndex(0); } ui->zoomReflection->setPrecision(3); ui->zoomFactor->setPrecision(3); ui->zoomReflection->setValue(edgeReflection); ui->zoomFactor->setValue(1.0/edgeReflection); connect(ui->buttonBox, &QDialogButtonBox::accepted, [=](){ limitToSpan = ui->displayModeFreq->currentIndex() == 1; limitToEdge = ui->displayModeImp->currentIndex() == 1; triggerReplot(); }); connect(ui->zoomFactor, &SIUnitEdit::valueChanged, [=](){ edgeReflection = 1.0 / ui->zoomFactor->value(); ui->zoomReflection->setValueQuiet(edgeReflection); }); connect(ui->zoomReflection, &SIUnitEdit::valueChanged, [=](){ edgeReflection = ui->zoomReflection->value(); ui->zoomFactor->setValueQuiet(1.0 / edgeReflection); }); dialog->show(); } QPoint TraceSmithChart::dataToPixel(std::complex d) { return transform.map(QPoint(d.real() * smithCoordMax * (1.0 / edgeReflection), -d.imag() * smithCoordMax * (1.0 / edgeReflection))); } QPoint TraceSmithChart::dataToPixel(Trace::Data d) { if(d.x < sweep_fmin || d.x > sweep_fmax) { return QPoint(); } return dataToPixel(d.y); } std::complex TraceSmithChart::pixelToData(QPoint p) { auto data = transform.inverted().map(QPointF(p)); return complex(data.x() / smithCoordMax * edgeReflection, -data.y() / smithCoordMax * edgeReflection); } QPoint TraceSmithChart::markerToPixel(Marker *m) { QPoint ret = QPoint(); // if(!m->isTimeDomain()) { if(m->getPosition() >= sweep_fmin && m->getPosition() <= sweep_fmax) { auto d = m->getData(); ret = dataToPixel(d); } // } return ret; } double TraceSmithChart::nearestTracePoint(Trace *t, QPoint pixel, double *distance) { double closestDistance = numeric_limits::max(); double closestXpos = 0; auto samples = t->size(); for(unsigned int i=0;isample(i); auto plotPoint = dataToPixel(data); if (plotPoint.isNull()) { // destination point outside of currently displayed range continue; } auto diff = plotPoint - pixel; unsigned int distance = diff.x() * diff.x() + diff.y() * diff.y(); if(distance < closestDistance) { closestDistance = distance; closestXpos = t->sample(i).x; } } if(distance) { *distance = closestDistance; } return closestXpos; } bool TraceSmithChart::xCoordinateVisible(double x) { if(limitToSpan) { if(x >= sweep_fmin && x <= sweep_fmax) { return true; } else { return false; } } else { // complete traces visible return true; } } void TraceSmithChart::draw(QPainter &p) { auto pref = Preferences::getInstance(); // translate coordinate system so that the smith chart sits in the origin and has a size of 1 auto w = p.window(); p.save(); p.translate(w.width()/2, w.height()/2); auto scale = qMin(w.height(), w.width()) / (2.0 * smithCoordMax); p.scale(scale, scale); transform = p.transform(); p.restore(); auto drawArc = [&](Arc a) { a.constrainToCircle(QPointF(0,0), edgeReflection); auto topleft = dataToPixel(complex(a.center.x() - a.radius, a.center.y() - a.radius)); auto bottomright = dataToPixel(complex(a.center.x() + a.radius, a.center.y() + a.radius)); a.startAngle *= 5760 / (2*M_PI); a.spanAngle *= 5760 / (2*M_PI); p.drawArc(QRect(topleft, bottomright), a.startAngle, a.spanAngle); }; // Outer circle auto pen = QPen(pref.Graphs.Color.axis); pen.setCosmetic(true); p.setPen(pen); drawArc(Arc(QPointF(0, 0), edgeReflection, 0, 2*M_PI)); constexpr int Circles = 6; pen = QPen(pref.Graphs.Color.Ticks.divisions, 0.5, Qt::DashLine); pen.setCosmetic(true); p.setPen(pen); for(int i=1;i(edgeReflection,0)),dataToPixel(complex(-edgeReflection,0))); constexpr std::array impedanceLines = {10, 25, 50, 100, 250}; for(auto z : impedanceLines) { z /= ReferenceImpedance; auto radius = 1.0/z; drawArc(Arc(QPointF(1.0, radius), radius, 0, 2*M_PI)); drawArc(Arc(QPointF(1.0, -radius), radius, 0, 2*M_PI)); } for(auto t : traces) { if(!t.second) { // trace not enabled in plot continue; } auto trace = t.first; if(!trace->isVisible()) { // trace marked invisible continue; } pen = QPen(trace->color(), pref.Graphs.lineWidth); pen.setCosmetic(true); p.setPen(pen); int nPoints = trace->size(); for(int i=1;isample(i-1); auto now = trace->sample(i); if (limitToSpan && (trace->getDataType() == Trace::DataType::Frequency) && (last.x < sweep_fmin || now.x > sweep_fmax)) { continue; } if(isnan(now.y.real())) { break; } if (limitToEdge && (abs(last.y) > edgeReflection || abs(now.y) > edgeReflection)) { // outside of visible area continue; } // scale to size of smith diagram auto p1 = dataToPixel(last); auto p2 = dataToPixel(now); // draw line p.drawLine(p1, p2); } if(trace->size() > 0) { // only draw markers if the trace has at least one point auto markers = t.first->getMarkers(); for(auto m : markers) { // if (m->isTimeDomain()) { // continue; // } if (limitToSpan && (m->getPosition() < sweep_fmin || m->getPosition() > sweep_fmax)) { continue; } if(m->getPosition() < trace->minX() || m->getPosition() > trace->maxX()) { // marker not in trace range continue; } auto coords = m->getData(); if (limitToEdge && abs(coords) > edgeReflection) { // outside of visible area continue; } auto point = dataToPixel(coords); auto symbol = m->getSymbol(); p.drawPixmap(point.x() - symbol.width()/2, point.y() - symbol.height(), symbol); } } } if(dropPending) { // TODO adjust coords due to shifted restore p.setOpacity(0.5); p.setBrush(Qt::white); p.setPen(Qt::white); p.drawEllipse(-smithCoordMax, -smithCoordMax, 2*smithCoordMax, 2*smithCoordMax); 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 Smith chart"; p.drawText(p.window(), Qt::AlignCenter, text); } else { } } void TraceSmithChart::traceDropped(Trace *t, QPoint position) { Q_UNUSED(t) Q_UNUSED(position); if(supported(t)) { enableTrace(t, true); } } QString TraceSmithChart::mouseText(QPoint pos) { auto data = pixelToData(pos); if(abs(data) <= edgeReflection) { data = 50.0 * (1.0 + data) / (1.0 - data); auto ret = Unit::ToString(data.real(), "", " ", 3); if(data.imag() >= 0) { ret += "+"; } ret += Unit::ToString(data.imag(), "j", " ", 3); return ret; } else { return QString(); } } void TraceSmithChart::updateContextMenu() { contextmenu->clear(); auto setup = new QAction("Setup...", contextmenu); connect(setup, &QAction::triggered, this, &TraceSmithChart::axisSetupDialog); contextmenu->addAction(setup); 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); }); contextmenu->addSection("Traces"); // Populate context menu for(auto t : traces) { if(!supported(t.first)) { continue; } auto action = new QAction(t.first->name(), contextmenu); action->setCheckable(true); if(t.second) { action->setChecked(true); } connect(action, &QAction::toggled, [=](bool active) { enableTrace(t.first, active); }); contextmenu->addAction(action); } contextmenu->addSeparator(); auto close = new QAction("Close", contextmenu); contextmenu->addAction(close); connect(close, &QAction::triggered, [=]() { markedForDeletion = true; }); } bool TraceSmithChart::supported(Trace *t) { return dropSupported(t); } bool TraceSmithChart::dropSupported(Trace *t) { if(!t->isReflection()) { return false; } switch(t->outputType()) { case Trace::DataType::Frequency: case Trace::DataType::Power: return true; default: return false; } } TraceSmithChart::Arc::Arc(QPointF center, double radius, double startAngle, double spanAngle) : center(center), radius(radius), startAngle(startAngle), spanAngle(spanAngle) { } void TraceSmithChart::Arc::constrainToCircle(QPointF center, double radius) { // check if arc/circle intersect auto centerDiff = this->center - center; auto centerDistSquared = centerDiff.x() * centerDiff.x() + centerDiff.y() * centerDiff.y(); if (centerDistSquared >= (radius + this->radius) * (radius + this->radius)) { // arc completely outside of constraining circle spanAngle = 0.0; return; } else if (centerDistSquared <= (radius - this->radius) * (radius - this->radius)) { if (radius >= this->radius) { // arc completely in constraining circle, do nothing return; } else { // arc completely outside of circle spanAngle = 0.0; return; } } else { // there are intersections between the arc and the circle. Calculate points according to https://stackoverflow.com/questions/3349125/circle-circle-intersection-points auto distance = sqrt(centerDistSquared); auto a = (this->radius*this->radius-radius*radius+distance*distance) / (2*distance); auto h = sqrt(this->radius*this->radius - a*a); auto intersectMiddle = this->center + a*(center - this->center) / distance; auto rotatedCenterDiff = center - this->center; swap(rotatedCenterDiff.rx(), rotatedCenterDiff.ry()); rotatedCenterDiff.setY(-rotatedCenterDiff.y()); auto intersect1 = intersectMiddle + h * rotatedCenterDiff / distance; auto intersect2 = intersectMiddle - h * rotatedCenterDiff / distance; // got intersection points, convert into angles from arc center auto wrapAngle = [](double angle) -> double { double ret = fmod(angle, 2*M_PI); if(ret < 0) { ret += 2*M_PI; } return ret; }; auto angle1 = wrapAngle(atan2((intersect1 - this->center).y(), (intersect1 - this->center).x())); auto angle2 = wrapAngle(atan2((intersect2 - this->center).y(), (intersect2 - this->center).x())); auto angleDiff = wrapAngle(angle2 - angle1); if ((angleDiff >= M_PI) ^ (a > 0.0)) { // allowed angles go from intersect1 to intersect2 if(startAngle < angle1) { startAngle = angle1; } auto maxSpan = wrapAngle(angle2 - startAngle); if(spanAngle > maxSpan) { spanAngle = maxSpan; } } else { // allowed angles go from intersect2 to intersect1 if(startAngle < angle2) { startAngle = angle2; } auto maxSpan = wrapAngle(angle1 - startAngle); if(spanAngle > maxSpan) { spanAngle = maxSpan; } } } }