Zurück zu Fähigkeiten

add-rcpp-integration

pjt222
Aktualisiert Yesterday
1 Ansichten
17
2
17
Auf GitHub ansehen
Metatesting

Über

Diese Fähigkeit integriert Rcpp oder RcppArmadillo in ein R-Paket, um leistungskritische R-Funktionen durch hochperformanten C++-Code zu ersetzen. Sie behandelt den gesamten Workflow von der Einrichtung und dem Schreiben von C++-Funktionen bis zur Generierung von RcppExports, zum Testen und Debuggen. Nutzen Sie sie, wenn das Profiling einen Engpass in R bestätigt, bei der Anbindung an bestehende C/C++-Bibliotheken oder bei der Implementierung von Algorithmen wie Schleifen und linearer Algebra, die von Kompilierung profitieren.

Schnellinstallation

Claude Code

Empfohlen
Primär
npx skills add pjt222/agent-almanac -a claude-code
Plugin-BefehlAlternativ
/plugin add https://github.com/pjt222/agent-almanac
Git CloneAlternativ
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integration

Kopieren Sie diesen Befehl und fügen Sie ihn in Claude Code ein, um diese Fähigkeit zu installieren

Dokumentation

Add Rcpp Integration

Integrate C++ into R pkg via Rcpp → perf-critical ops.

Use When

  • R fn too slow, profile confirms bottleneck
  • Interface existing C/C++ libs
  • Algos benefit compiled (loops, recursion)
  • RcppArmadillo → linear algebra

In

  • Required: Existing R pkg
  • Required: R fn to replace/augment w/ C++
  • Optional: External C++ lib
  • Optional: RcppArmadillo? (default: plain Rcpp)

Do

Step 1: Rcpp Infra Setup

usethis::use_rcpp()

Does:

  • Creates src/ dir
  • Adds Rcpp → LinkingTo + Imports in DESCRIPTION
  • Creates R/packagename-package.R w/ @useDynLib + @importFrom Rcpp sourceCpp
  • Updates .gitignore for compiled

RcppArmadillo:

usethis::use_rcpp_armadillo()

src/ created, DESCRIPTION updated Rcpp LinkingTo + Imports, R/packagename-package.R has @useDynLib.

If err: usethis::use_rcpp() fails → manually create src/, add LinkingTo: Rcpp + Imports: Rcpp, add #' @useDynLib packagename, .registration = TRUE + #' @importFrom Rcpp sourceCpp to pkg doc file.

Step 2: Write C++ Fn

Create src/my_function.cpp:

#include <Rcpp.h>
using namespace Rcpp;

//' Compute cumulative sum efficiently
//'
//' @param x A numeric vector
//' @return A numeric vector of cumulative sums
//' @export
// [[Rcpp::export]]
NumericVector cumsum_cpp(NumericVector x) {
  int n = x.size();
  NumericVector out(n);
  out[0] = x[0];
  for (int i = 1; i < n; i++) {
    out[i] = out[i - 1] + x[i];
  }
  return out;
}

RcppArmadillo:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

//' Matrix multiplication using Armadillo
//'
//' @param A A numeric matrix
//' @param B A numeric matrix
//' @return The matrix product A * B
//' @export
// [[Rcpp::export]]
arma::mat mat_mult(const arma::mat& A, const arma::mat& B) {
  return A * B;
}

C++ src at src/my_function.cpp w/ valid // [[Rcpp::export]] + roxygen //' docs.

If err: Verify #include <Rcpp.h> (or <RcppArmadillo.h>), export annotation own line directly above signature, return types map valid Rcpp.

Step 3: Generate RcppExports

Rcpp::compileAttributes()
devtools::document()

R/RcppExports.R + src/RcppExports.cpp auto-generated.

If err: Check C++ syntax. Ensure // [[Rcpp::export]] above each exported fn.

Step 4: Verify Compilation

devtools::load_all()

Pkg compiles + loads no err.

If err: Check compiler out. Common:

  • Missing system headers → install dev libs
  • Syntax err → compiler msgs point to line
  • Missing Rcpp::depends for RcppArmadillo

Step 5: Tests for Compiled

test_that("cumsum_cpp matches base R", {
  x <- c(1, 2, 3, 4, 5)
  expect_equal(cumsum_cpp(x), cumsum(x))
})

test_that("cumsum_cpp handles edge cases", {
  expect_equal(cumsum_cpp(numeric(0)), numeric(0))
  expect_equal(cumsum_cpp(c(NA_real_, 1)), c(NA_real_, NA_real_))
})

Tests pass → C++ identical to R + edge cases (empty, NA) correct.

If err: NA fail → add explicit NA checks via NumericVector::is_na(). Empty fail → guard clause zero-length at top.

Step 6: Cleanup Script

Create src/Makevars:

PKG_CXXFLAGS = -O2

Create cleanup in pkg root (CRAN):

#!/bin/sh
rm -f src/*.o src/*.so src/*.dll

Make executable: chmod +x cleanup

src/Makevars sets compiler flags, cleanup removes objects. Both at pkg root.

If err: Verify cleanup has exec perms (chmod +x cleanup), Makevars tabs (not spaces) for Makefile rules.

Step 7: Update .Rbuildignore

Handle compiled artifacts:

^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$

.Rbuildignore patterns prevent compiled objects in tarball, preserve src + Makevars.

If err: devtools::check() → NOTEs about unexpected files in src/. Adjust patterns → exclude only .o, .so, .dll.

Check

  • devtools::load_all() compiles no warn
  • Compiled fn produces correct results
  • Tests pass edge cases (NA, empty, large)
  • R CMD check passes no compile warn
  • RcppExports generated + committed
  • Perf improvement via benchmarks

Traps

  • Forget compileAttributes(): Must regen RcppExports after C++ changes
  • Int overflow: double not int for large numerics
  • Memory mgmt: Rcpp auto-handles for Rcpp types; no manual delete
  • NA handling: C++ doesn't know R's NA. Check Rcpp::NumericVector::is_na()
  • Platform portability: Avoid platform-specific C++. Test Win, macOS, Linux.
  • Missing @useDynLib: Pkg doc must @useDynLib packagename, .registration = TRUE

  • create-r-package — pkg setup before Rcpp
  • write-testthat-tests — testing compiled fns
  • setup-github-actions-ci — CI needs C++ toolchain
  • submit-to-cran — compiled pkgs need extra CRAN checks

GitHub Repository

pjt222/agent-almanac
Pfad: i18n/caveman-ultra/skills/add-rcpp-integration
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

Verwandte Skills

content-collections

Meta

Diese Skill bietet eine produktionsgetestete Einrichtung für Content Collections – ein TypeScript-first-Tool, das Markdown/MDX-Dateien in typsichere Datensammlungen mit Zod-Validierung umwandelt. Verwenden Sie ihn beim Erstellen von Blogs, Dokumentationsseiten oder inhaltsstarken Vite + React-Anwendungen, um Typsicherheit und automatische Inhaltsvalidierung zu gewährleisten. Er behandelt alles von der Vite-Plugin-Konfiguration und MDX-Kompilierung bis hin zur Deployment-Optimierung und Schema-Validierung.

Skill ansehen

polymarket

Meta

Diese Fähigkeit ermöglicht es Entwicklern, Anwendungen mit der Polymarket-Prognosemärkte-Plattform zu erstellen, einschließlich API-Integration für Handel und Marktdaten. Sie bietet außerdem Echtzeit-Datenstreaming über WebSocket, um Live-Trades und Marktaktivitäten zu überwachen. Nutzen Sie sie zur Implementierung von Handelsstrategien oder zur Erstellung von Tools, die Live-Marktaktualisierungen verarbeiten.

Skill ansehen

creating-opencode-plugins

Meta

Diese Fähigkeit unterstützt Entwickler dabei, OpenCode-Plugins zu erstellen, die in über 25 Ereignistypen wie Befehle, Dateien und LSP-Operationen eingreifen. Sie bietet die Plugin-Struktur, Event-API-Spezifikationen und Implementierungsmuster für JavaScript/TypeScript-Module. Nutzen Sie sie, wenn Sie den Lebenszyklus des OpenCode KI-Assistenten mit benutzerdefinierter ereignisgesteuerter Logik abfangen, überwachen oder erweitern müssen.

Skill ansehen

sglang

Meta

SGLang ist ein hochperformantes LLM-Serving-Framework, das sich auf schnelle, strukturierte Generierung für JSON, Regex und agentenbasierte Workflows unter Verwendung seines RadixAttention-Prefix-Cachings spezialisiert. Es bietet deutlich schnellere Inferenz, insbesondere für Aufgaben mit wiederholten Präfixen, was es ideal für komplexe, strukturierte Ausgaben und Mehrfachdialoge macht. Wählen Sie SGLang gegenüber Alternativen wie vLLM, wenn Sie constrained decoding benötigen oder Anwendungen mit umfangreicher Präfix-Weitergabe entwickeln.

Skill ansehen