zyratlo commented on code in PR #8911: URL: https://github.com/apache/texera/pull/8911#discussion_r4428834722
########## frontend/src/app/workspace/service/notebook-migration/migration-prompts-r.ts: ########## @@ -0,0 +1,448 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// Prompts for converting R sources into RUDF operators (Table API only). + +export const R_TEXERA_OVERVIEW = ` +You are a robust compiler that takes R code and translates it into R user-defined functions (UDFs) for our workflow environment Texera. + +Texera is a data analytics tool that uses workflows to do machine learning and data analytics computation. Users drag and drop operators and connect their inputs and outputs in a graphical workflow editor, and the code we create runs inside those operators. + +Texera runs R UDFs with its Table API. The code of a Table API UDF ends with a function of two arguments, and that function is the value the code evaluates to: + +function(table, port) { + return(table) +} + +table is an R data.frame holding every row that arrived on the input port, and port is the index of that port, starting at 0. The function returns a data.frame, or NULL to output nothing. Each returned row becomes an output row and each column an output column. +Code before the function, such as library() calls, runs once when the operator starts. +`; + +export const R_UDF_DOCUMENTATION = ` +Rules for writing Texera R UDF code: +1. Always use the Table API template above. Never use coro::generator or the Tuple API. +2. Load packages with library() before the function. Never call install.packages(). +3. Read columns with table$column or table[['column']]. Check missing values with is.na() before comparing them. +4. Do not read or write files, and do not call setwd(). Data arrives only through the table argument. +5. Output that the original code prints or displays is returned as columns instead. +6. Keep each UDF focused on one step of the original code. +`; + +export const R_DATA_PASSING_DOCUMENTATION = ` +Texera R UDFs pass data to each other in data.frame columns, so R objects travel in serialized form. + +A UDF whose output another UDF reads returns a data.frame with exactly one row. Every column holds one R object, serialized: + +data.frame( + data = I(list(serialize(data, NULL))), + model = I(list(serialize(model, NULL))) +) + +Any R object can be passed this way: data.frames, vectors, lists, and fitted models. The receiving UDF restores each object with unserialize(): + +data <- unserialize(table$data[[1]]) +model <- unserialize(table$model[[1]]) + +A UDF that no other UDF reads is shown to the user, so every column it returns must be character. Convert other values with as.character(), sprintf(), or paste(capture.output(print(x)), collapse = '\\n'). +`; + +export const R_VISUALIZER_DOCUMENTATION = ` +To show a plot, a UDF returns a single column named html-content holding a complete HTML page. +1. Build the plot with plotly. Convert an existing ggplot2 plot with ggplotly(p) so the original plot code is kept. +2. Turn the plot into a page that loads Plotly from a CDN. Do not use htmlwidgets::saveWidget, it needs pandoc, which is not available. +3. If the input has no rows, return an html-content page explaining that the plot is not available. + +json <- plotly_json(ggplotly(p), jsonedit = FALSE) +html <- paste0( + '<html><head><script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script></head>', + '<body><div id="plot" style="width:100%;height:100%"></div><script>', + 'var fig = ', json, '; Plotly.newPlot("plot", fig.data, fig.layout);', + '</script></body></html>' +) +data.frame('html-content' = html, check.names = FALSE) +`; + +export const R_EXAMPLE_OF_MULTIPLE_UDF_CONVERSION = ` +Here is an example of breaking up R code into multiple Texera R UDFs. Format your response structure exactly like the given example. The "code" key contains a dictionary of the UDF IDs with their respective code. The "edges" key contains a list of pairs that contains the connections between UDFs. The "outputs" key contains a dictionary of the UDF IDs with a list of the output column names of the data.frame that the UDF returns. The UDFs can branch, so it does not have to be a linear chain, but each UDF reads from at most one other UDF. + +Original Code: +\`\`\`r +# START CELL1 +library(ggplot2) +library(rpart) +# END CELL1 + +# START CELL2 +# Load the dataset +data <- read.csv('diabetes.csv') +# END CELL2 + +# START CELL3 +# Remove duplicate rows +data <- unique(data) + +# Remove rows with missing values +data <- na.omit(data) +# END CELL3 + +# START CELL4 +# Print the minimum, maximum, and mean for all fields +print(sapply(data, min)) +print(sapply(data, max)) +print(colMeans(data)) +# END CELL4 + +# START CELL5 +# Boxplot of glucose by outcome +ggplot(data, aes(x = factor(Outcome), y = Glucose)) + + geom_boxplot() + + labs(x = 'Outcome', y = 'Glucose', title = 'Glucose by Outcome') +# END CELL5 + +# START CELL6 +# Split data into training and testing sets (80% train, 20% test) +set.seed(42) +train_idx <- sample(seq_len(nrow(data)), size = floor(0.8 * nrow(data))) +train <- data[train_idx, ] +test <- data[-train_idx, ] +# END CELL6 + +# START CELL7 +# Scale features using the training set center and spread +features <- setdiff(names(data), 'Outcome') +centers <- sapply(train[features], mean) +spreads <- sapply(train[features], sd) +train[features] <- scale(train[features], center = centers, scale = spreads) +test[features] <- scale(test[features], center = centers, scale = spreads) +# END CELL7 + +# START CELL8 +# Train logistic regression model +glm_model <- glm(Outcome ~ ., data = train, family = binomial) +glm_pred <- ifelse(predict(glm_model, test, type = 'response') > 0.5, 1, 0) +glm_accuracy <- mean(glm_pred == test$Outcome) +print(sprintf('Logistic Regression Accuracy: %.2f%%', 100 * glm_accuracy)) +# END CELL8 + +# START CELL9 +# Train decision tree model +tree_model <- rpart(factor(Outcome) ~ ., data = train, method = 'class') +tree_pred <- predict(tree_model, test, type = 'class') +tree_accuracy <- mean(as.character(tree_pred) == as.character(test$Outcome)) +print(sprintf('Decision Tree Accuracy: %.2f%%', 100 * tree_accuracy)) +# END CELL9 +\`\`\` + +Texera UDF conversion: +\`\`\`json +{ + "code": { + "UDF1": "# UDF1\\nfunction(table, port) {\\n # Remove duplicate rows\\n data <- unique(table)\\n\\n # Remove rows with missing values\\n data <- na.omit(data)\\n\\n # Calculate statistics\\n min_values <- sapply(data, min)\\n max_values <- sapply(data, max)\\n mean_values <- colMeans(data)\\n\\n # One row of serialized objects for the downstream UDFs\\n data.frame(\\n min_values = I(list(serialize(min_values, NULL))),\\n max_values = I(list(serialize(max_values, NULL))),\\n mean_values = I(list(serialize(mean_values, NULL))),\\n data = I(list(serialize(data, NULL)))\\n )\\n}", Review Comment: Fixed in [6722ac5](https://github.com/apache/texera/pull/8911/commits/6722ac54e3c4fce40f881fe0de8e90c45a1e01d9) for both examples. UDF1 now only cleans and serializes the data, and a new UDF2 reads it and returns the minimum, maximum, and mean as character columns. The later UDFs, edges, outputs, mappings, and the format template were updated to match. All six UDFs were run through texera-rudf on diabetes.csv. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
