### CRAN Package Policy Examples Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Illustrates key CRAN policies that R package developers must adhere to, such as ensuring examples run without errors, using tempdir() for file operations, and maintaining fast execution times. ```r # Use `tmp <- tempdir()` for file operations # Add error handling to examples # Use \donttest{} for slow/external package examples ``` -------------------------------- ### Roxygen2 Package Documentation Setup Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Details the creation of the `R/packagename-package.R` file for package-level documentation. It includes essential tags like @docType package, @name, and @aliases for package metadata. ```r '@keywords internal "_PACKAGE" #' packagename: Package Title #' #' Package description paragraph. #' #' @docType package #' @name packagename-package #' @aliases packagename NULL ``` -------------------------------- ### Roxygen2 Documentation Template for Functions Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Provides a standard template for documenting R functions using roxygen2 tags. It includes essential tags like @title, @description, @param, @return, @export, and @examples, along with guidelines for different types of examples. ```r #' Title in Sentence Case (no period, <60 chars) #' #' Brief description in 1-2 sentences. No code here. #' #' @param x Parameter description (type and purpose) #' @param ... Additional arguments passed to methods #' @return Type and structure of return value #' @export #' @examples #' # Quick example (<5 seconds) #' my_function(1:10) #' #' \donttest{ #' # Slower example or requiring special conditions #' if (requireNamespace("suggested_pkg", quietly = TRUE)) { #' # Example using suggested package #' } #' } ``` -------------------------------- ### Basic Functionality Example Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html A fundamental example demonstrating a core programming concept or task. This snippet might be used as a starting point for more complex operations. ```python def greet(name): return f"Hello, {name}!" print(greet("World")) ``` -------------------------------- ### Fix Priority Order for R Packages Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Outlines a systematic approach to fixing issues in R packages, prioritizing documentation errors, NAMESPACE conflicts, example failures, file system violations, and performance problems. ```r # Fix Priority Order: # 1. Documentation errors (Missing @export, Undocumented parameters, Missing @return) # 2. NAMESPACE issues (S3 method registration, Import conflicts) # 3. Example failures (Add error handling, Use \donttest{}) # 4. File system violations (Replace with tempdir(), Add cleanup code) # 5. Performance issues (Optimize slow examples, Reduce data sizes) ``` -------------------------------- ### Run Initial CRAN Checks with devtools Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Executes quick documentation checks and comprehensive CRAN compliance checks using the devtools package. These are the first steps in assessing package readiness for CRAN. ```r # Quick documentation check devtools::check_man() # Full CRAN check devtools::check(cran = TRUE) ``` -------------------------------- ### Initial State Check for CRAN Compliance Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Performs an initial check of the package's documentation status to identify any immediate issues before proceeding with fixes. ```r # Initial state check devtools::check_man() ``` -------------------------------- ### Roxygen2 Documentation for Datasets Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Shows the required format for documenting datasets included in an R package. It specifies the use of @format and @source tags to describe the data structure and origin. ```r #' Dataset Title #' #' Dataset description paragraph. #' #' @format A data frame with X rows and Y columns: #' \describe{ #' \item{col1}{Description of column 1.} #' \item{col2}{Description of column 2.} #' } #' @source Where the data came from "dataset_name" ``` -------------------------------- ### Shift Regressor Onsets Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html Creates an original regressor and then shifts its onsets by a specified amount using the `shift()` function. The example displays the original and shifted onsets. ```R # Original regressor reg_orig <- regressor(onsets = c(10, 30, 50), hrf = HRF_SPMG1) # Shifted regressor (delay by 5 seconds) reg_shifted <- shift(reg_orig, shift_amount = 5) onsets(reg_orig) #> [1] 10 30 50 onsets(reg_shifted) # Onsets are now 15, 35, 55 #> [1] 15 35 55 ``` -------------------------------- ### Roxygen2 Documentation for S3 Methods (Imported Generics) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Illustrates how to document S3 methods for generics that are imported from other packages (e.g., print, plot). This includes using @method and @export tags for proper registration. ```r #' Print Method for myclass #' #' @param x Object of class myclass #' @param ... Additional print arguments #' @return Invisibly returns x #' @method print myclass #' @export print.myclass <- function(x, ...) { } ``` -------------------------------- ### NAMESPACE Management with Roxygen2 Imports Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Demonstrates how to manage package NAMESPACE imports using roxygen2 tags. It shows preferred methods for importing specific functions and handling S3 methods for imported generics. ```r # Specific imports (preferred) #' @importFrom stats median sd #' @importFrom utils head tail # For S3 methods on imported generics #' @importFrom base print #' @method print myclass #' @export ``` -------------------------------- ### Roxygen2 Documentation for S3 Methods (User-Defined Generics) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Demonstrates how to document S3 methods for generics defined within the package. It shows the structure for documenting the generic function itself and its specific methods using @rdname and @method tags. ```r #' Generic Title #' #' @param x Object to process #' @param ... Additional arguments #' @return Processed object #' @export my_generic <- function(x, ...) UseMethod("my_generic") #' @rdname my_generic #' @method my_generic data.frame #' @export my_generic.data.frame <- function(x, ...) { } ``` -------------------------------- ### File Reading Example Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html Demonstrates how to read data from a file. This snippet typically involves opening a file, reading its content, and processing it. Error handling for file not found might be included. ```python try: with open('data.txt', 'r') as f: content = f.read() print(content) except FileNotFoundError: print("File not found.") ``` -------------------------------- ### R Package Development Workflow Commands Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Provides essential commands for maintaining and checking R packages, including regenerating documentation, checking man pages, and performing comprehensive CRAN checks. ```r # Regenerate docs devtools::document() # Verify fix devtools::check_man() # Test changes with CRAN checks devtools::check(cran = TRUE) ``` -------------------------------- ### Workflow: Quick Documentation Fix Cycle Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Outlines a simplified workflow for addressing documentation issues. It involves checking documentation, making edits in source files (not man/ files), regenerating documentation, and re-verifying the fixes. ```r # IMPORTANT: Edit ONLY the R source files, NOT man/ files! # The man/ directory is auto-generated by roxygen2 # Find undocumented objects devtools::check_man() # Make changes to roxygen comments in R/*.R files # Then regenerate documentation devtools::document() # Verify fixes devtools::check_man() ``` -------------------------------- ### Load fMRI Data with Python Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet demonstrates how to load fMRI data using a Python library, likely for further analysis. It assumes the existence of necessary data files and library installations. ```python import nibabel as nib def load_fmri_data(file_path): """Loads fMRI data from a NIfTI file. Args: file_path (str): The path to the NIfTI file. Returns: nibabel.Nifti1Image: The loaded NIfTI image object. """ try: img = nib.load(file_path) return img except FileNotFoundError: print(f"Error: File not found at {file_path}") return None except Exception as e: print(f"An error occurred: {e}") return None # Example usage: # data_path = "/path/to/your/fmri_data.nii.gz" # fmri_image = load_fmri_data(data_path) # if fmri_image: # print("fMRI data loaded successfully.") # print("Image shape:", fmri_image.shape) # print("Image affine:", fmri_image.affine) ``` -------------------------------- ### Workflow: Full CRAN Check Cycle Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Describes a comprehensive workflow for ensuring CRAN compliance. This includes documenting the package, performing a full CRAN check, spell checking, validating URLs, and conducting cross-platform checks. ```r # 1. Document devtools::document() # 2. Full check devtools::check(cran = TRUE) # 3. Spell check devtools::spell_check() # 4. URL check urlchecker::url_check() # 5. Cross-platform devtools::check_win_devel() rhub::check_for_cran() ``` -------------------------------- ### Add Undocumented Parameters using roxygen2 Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/CRAN_prompt.md Demonstrates how to add missing @param tags to R source files for documenting function arguments, using roxygen2 syntax. This is a common fix for documentation errors. ```r # Open R/analyze_data.R and add: #' @param method Character string specifying analysis method #' @param threshold Numeric threshold for filtering (default: 0.05) # Regenerate docs devtools::document() # Verify fix devtools::check_man() ``` -------------------------------- ### Get the keys of a dictionary Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function returns a view object that displays a list of all the keys in a given dictionary. This is a common operation for accessing the structure of a dictionary. ```python def get_dict_keys(dictionary): """Returns a view object of the dictionary's keys.""" return dictionary.keys() # Example Usage: # my_dict = {'name': 'Alice', 'age': 30} # print(get_dict_keys(my_dict)) # Output: dict_keys(['name', 'age']) ``` -------------------------------- ### Regressor with Varying Event Durations (R) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html Creates an fMRI regressor where event durations vary. This is achieved by passing a vector to the `duration` argument of the `regressor()` function, allowing for more flexible modeling of experimental paradigms. The example visualizes the predicted response, showing the effect of the changing durations. ```r # Example onsets and durations onsets_var_dur <- seq(0, 5 * 12, length.out = 6) durations_var <- 1:length(onsets_var_dur) # Durations increase from 1s to 6s # Create regressor with varying durations reg_var_dur <- regressor(onsets_var_dur, HRF_SPMG1, duration = durations_var) print(reg_var_dur) # Evaluate and plot scan_times_dur <- seq(0, max(onsets_var_dur) + 30, by = TR) pred_var_dur <- evaluate(reg_var_dur, scan_times_dur) plot_df_dur <- data.frame(Time = scan_times_dur, Response = pred_var_dur) ggplot(plot_df_dur, aes(x = Time, y = Response)) + geom_line(linewidth = 1) + geom_vline(xintercept = onsets(reg_var_dur), linetype = "dashed", color = "red", alpha = 0.7) + labs(title = "Regressor with Varying Event Durations", subtitle = "Duration increases over time", x = "Time (seconds)", y = "Predicted Response") + theme_minimal() ``` -------------------------------- ### Generate sequence of numbers with a step Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function generates a sequence of numbers starting from a given value, incrementing by a specified step, up to a limit. It's equivalent to using `numpy.arange`. This is useful for creating time vectors or sequences for simulations. ```python import numpy as np def generate_sequence(start, stop, step): """Generates a sequence of numbers with a given step.""" return np.arange(start, stop, step) # Example Usage: # print(generate_sequence(0, 10, 2)) # Output: [0 2 4 6 8] ``` -------------------------------- ### Get the values of a dictionary Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function returns a view object that displays a list of all the values in a given dictionary. This is useful for iterating over or processing the values stored within a dictionary. ```python def get_dict_values(dictionary): """Returns a view object of the dictionary's values.""" return dictionary.values() # Example Usage: # my_dict = {'name': 'Alice', 'age': 30} # print(get_dict_values(my_dict)) # Output: dict_values(['Alice', 30]) ``` -------------------------------- ### Generate a random floating-point number Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function generates a random floating-point number in the range [0.0, 1.0). It uses the `random.random` function, which is a standard way to get uniformly distributed random floats. ```python import random def get_random_float(): """Generates a random float in the range [0.0, 1.0).""" return random.random() # Example Usage: # print(get_random_float()) # Output: a random float between 0.0 and 0.999... ``` -------------------------------- ### Generate a list of Fibonacci numbers Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function generates a list of Fibonacci numbers up to a specified count. The Fibonacci sequence is a series where each number is the sum of the two preceding ones, usually starting with 0 and 1. ```python def fibonacci_sequence(n): """Generates the first n Fibonacci numbers.""" if n <= 0: return [] elif n == 1: return [0] else: list_fib = [0, 1] while len(list_fib) < n: next_fib = list_fib[-1] + list_fib[-2] list_fib.append(next_fib) return list_fib # Example Usage: # print(fibonacci_sequence(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` -------------------------------- ### Load and Preprocess fMRI Data (General) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html Demonstrates loading and initial preprocessing steps for fMRI data, potentially using a command-line tool or a script. ```bash mkdir fmri_preprocessed fslrealign -a fmri_data.nii.gz fmri_preprocessed/preprocessed_fmri.nii.gz ``` -------------------------------- ### Python: Load and Process fMRI Data Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet demonstrates loading fMRI data using NiBabel and performing basic preprocessing steps. It handles NIfTI files and prepares data for further analysis. Dependencies include NiBabel and NumPy. ```python import nibabel as nib import numpy as np def load_fmri_data(filepath): """Loads fMRI data from a NIfTI file.""" img = nib.load(filepath) data = img.get_fdata() affine = img.affine return data, affine # Example usage: # data, affine = load_fmri_data('path/to/your/fmri_data.nii.gz') # print(f"Data shape: {data.shape}") ``` -------------------------------- ### CSS: General page and table styling Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This CSS provides foundational styling for the web page, including background color, margins, font settings, and TOC (Table of Contents) appearance. It also includes basic styling for HTML tables. ```css body { background-color: #fff; margin: 1em auto; max-width: 700px; overflow: visible; padding-left: 2em; padding-right: 2em; font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.35; } #TOC { clear: both; margin: 0 0 10px 10px; padding: 4px; width: 400px; border: 1px solid #CCCCCC; border-radius: 5px; background-color: #f6f6f6; font-size: 13px; line-height: 1.3; } #TOC .toctitle { font-weight: bold; font-size: 15px; margin-left: 5px; } #TOC ul { padding-left: 40px; margin-left: -1.5em; margin-top: 5px; margin-bottom: 5px; } #TOC ul ul { margin-left: -2em; } #TOC li { line-height: 16px; } table { margin: 1em auto; border-width: 1px; border-color: #DDDDDD; border-style: outset; border-collapse: co ``` -------------------------------- ### Load and Prepare fMRI Data (Python) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html Loads fMRI data from a file (e.g., NIfTI) and performs initial preparation steps. This often involves libraries like NiBabel. ```python import nibabel as nib img = nib.load('fmri_data.nii.gz') data = img.get_fdata() ``` -------------------------------- ### JavaScript: Apply Pandoc div.sourceCode styles to pre.sourceCode Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This JavaScript snippet iterates through style sheets to find Pandoc-specific rules for 'div.sourceCode' and applies those styles to 'pre.sourceCode' elements. This ensures consistent code block presentation across different contexts. ```javascript (function() { var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue; try { var rules = sheets[i].cssRules; } catch (e) { continue; } var j = 0; while (j < rules.length) { var rule = rules[j]; if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") { j++; continue; } var style = rule.style.cssText; if (rule.style.color === '' && rule.style.backgroundColor === '') { j++; continue; } sheets[i].deleteRule(j); sheets[i].insertRule('pre.sourceCode{' + style + '}', j); } } })(); ``` -------------------------------- ### Python: Load and process fMRI data Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet demonstrates how to load and preprocess fMRI data using Python libraries. It typically involves reading NIfTI files, performing spatial smoothing, and preparing data for statistical analysis. Dependencies include libraries like NiBabel and SciPy. ```python import nibabel as nib import numpy as np from scipy import ndimage def load_and_process_fmri(file_path, smoothing_fwhm=6): """Loads and applies smoothing to fMRI data.""" img = nib.load(file_path) data = img.get_fdata() # Apply Gaussian smoothing sigma = smoothing_fwhm / (2 * np.sqrt(2 * np.log(2))) smoothed_data = ndimage.gaussian_filter(data, sigma=sigma) return nib.Nifti1Image(smoothed_data, img.affine, img.header) ``` -------------------------------- ### Convert Principal Components to HRF Functions Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This R code snippet converts the top principal components obtained from PCA into empirical HRF functions. Each PC vector is adjusted to start at zero, normalized to have a peak absolute value of 1, and then used to create an HRF function via `gen_empirical_hrf`. These are stored in `list_pc_hrfs`. ```r # Create list to store our empirical HRF functions list_pc_hrfs <- list() for (i in 1:n_components) { # Get the PC vector pc_vec <- pc_vectors[, i] # Start at 0 (shift so first value is 0) pc_vec_zeroed <- pc_vec - pc_vec[1] # Normalize peak to 1 (or -1 if the peak is negative) max_abs <- max(abs(pc_vec_zeroed)) pc_vec_norm <- pc_vec_zeroed / max_abs # Create empirical HRF function list_pc_hrfs[[i]] <- gen_empirical_hrf(sim_times, pc_vec_norm) } ``` -------------------------------- ### Python: fMRI Data Handling Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This snippet demonstrates basic fMRI data handling in Python, likely involving loading, manipulation, and preprocessing of neuroimaging data. It may utilize libraries like NiBabel and NumPy. ```Python import nibabel as nib import numpy as np # Load an example fMRI image img = nib.load('example.nii.gz') data = img.get_fdata() # Perform some basic manipulation (e.g., get shape) print(f"Data shape: {data.shape}") # Example: Calculate mean signal across all voxels mean_signal = np.mean(data) print(f"Mean signal: {mean_signal}") ``` -------------------------------- ### JavaScript: Initialize and configure event listeners Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This JavaScript code initializes an event listener for a button with the ID 'getDataButton'. When clicked, it retrieves data from a specified URL and updates the UI with the processed data. This is a standard approach for handling user interactions in web applications. ```javascript document.getElementById("getDataButton").addEventListener("click", function() { fetch('data.txt').then(function(response) { return response.text(); }).then(function(text) { update(text); }); }); ``` -------------------------------- ### Generate Empirical HRF from Simulated Profile (R) Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html Demonstrates how to simulate an average measured response profile and then use `gen_empirical_hrf` to create an HRF function from this profile. The resulting HRF is then evaluated and plotted against the original points. ```r sim_times <- 0:24 set.seed(42) # For reproducibility sim_profile <- rowMeans(replicate(20, { h <- HRF_SPMG1 %>% lag_hrf(lag = runif(n = 1, min = -1, max = 1)) %>% block_hrf(width = runif(n = 1, min = 0, max = 2)) h(sim_times) })) # Normalize profile to max = 1 for better visualization sim_profile_norm <- sim_profile / max(sim_profile) # Create the empirical HRF function from the normalized profile emp_hrf <- gen_empirical_hrf(sim_times, sim_profile_norm) print(emp_hrf) #> function (v) #> .approxfun(x, y, v, method, yleft, yright, f, na.rm) #> #> #> attr(,"class") #> [1] "HRF" "function" #> attr(,"name") #> [1] "empirical_hrf" #> attr(,"nbasis") #> [1] 1 #> attr(,"span") #> [1] 24 #> attr(,"params") #> list() # Evaluate and plot (using a finer time grid for interpolation) fine_times <- seq(0, 24, by = 0.1) resp_emp <- emp_hrf(fine_times) # Plot the interpolated curve with the original points plot(fine_times, resp_emp, type = 'l', lwd = 1.5, xlab = "Time (seconds)", ylab = "BOLD Response", main = "Empirical HRF from Simulated Average Profile") points(sim_times, sim_profile_norm, pch = 16, col = "red", cex = 1) # Show original points ``` -------------------------------- ### Execute fMRI HRF Model Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This snippet demonstrates how to execute an fMRI HRF model. It takes subject data and model parameters as input and returns processed HRF data. Dependencies include scientific computing libraries. ```python def execute_fmri_hrf_model(subject_data, model_params): # Placeholder for HRF model execution logic processed_data = ... # Process subject_data using model_params return processed_data # Example usage: # subject_data = load_subject_data('subject1.nii') # model_params = {'TR': 2, 'hrf_type': 'canonical'} # hrf_output = execute_fmri_hrf_model(subject_data, model_params) # print(hrf_output) ``` -------------------------------- ### Creating a Simple Plot Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html Shows how to generate a basic plot using a plotting library like Matplotlib. This involves defining data points and using plotting functions to visualize them. Requires Matplotlib. ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 20, 25, 15] plt.plot(x, y) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Simple Plot") plt.show() ``` -------------------------------- ### Load and Process fMRI Data Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet demonstrates how to load and potentially process fMRI data. It likely involves reading data from a file format common in neuroimaging and performing initial data cleaning or preparation steps. Dependencies may include neuroimaging libraries. ```python import nibabel as nib import numpy as np def load_fmri_data(filepath): """Loads fMRI data from a NIfTI file. Args: filepath (str): Path to the NIfTI (.nii or .nii.gz) file. Returns: tuple: A tuple containing the image data (numpy array) and the affine transformation matrix. """ try: img = nib.load(filepath) data = img.get_fdata() affine = img.affine return data, affine except nib.FileError as e: print(f"Error loading file: {e}") return None, None # Example usage: # fmri_data, fmri_affine = load_fmri_data('path/to/your/fmri_data.nii.gz') ``` -------------------------------- ### CSS: Styling code blocks and elements Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This CSS defines styles for code blocks, including font properties, overflow handling, and specific styling for numbered source code lines. It also includes styles for various text elements like keywords, comments, and literals. ```css code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} ul.task-list{list-style: none;} code { white-space: pre; } .sourceCode { overflow: visible; } html { -webkit-text-size-adjust: 100%; } pre > code.sourceCode { white-space: pre; position: relative; } pre > code.sourceCode > span { display: inline-block; line-height: 1.25; } pre > code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode > span { color: inherit; text-decoration: inherit; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { pre > code.sourceCode { white-space: pre-wrap; } pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } ``` ```css pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; color: #aaaaaa; } pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; } div.sourceCode { } @media screen { pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; } } ``` ```css code span.al { color: #ff0000; font-weight: bold; } code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } code span.at { color: #7d9029; } code span.bn { color: #40a070; } code span.bu { color: #008000; } code span.cf { color: #007020; font-weight: bold; } code span.ch { color: #4070a0; } code span.cn { color: #880000; } code span.co { color: #60a0b0; font-style: italic; } code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } code span.do { color: #ba2121; font-style: italic; } code span.dt { color: #902000; } code span.dv { color: #40a070; } code span.er { color: #ff0000; font-weight: bold; } code span.ex { } code span.fl { color: #40a070; } code span.fu { color: #06287e; } code span.im { color: #008000; font-weight: bold; } code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } code span.kw { color: #007020; font-weight: bold; } code span.op { color: #666666; } code span.ot { color: #007020; } code span.pp { color: #bc7a00; } code span.sc { color: #4070a0; } code span.ss { color: #bb6688; } code span.st { color: #4070a0; } code span.va { color: #19177c; } code span.vs { color: #4070a0; } code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } ``` -------------------------------- ### Load MathJax Dynamically with JavaScript Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet demonstrates how to dynamically load the MathJax library into an HTML document. It creates a script element, sets its type and source to the MathJax CDN, and appends it to the head of the document. This allows for on-demand rendering of mathematical content using TeX, AMS, and MML configurations. ```javascript (function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"; document.getElementsByTagName("head")[0].appendChild(script); })(); ``` -------------------------------- ### R: fMRI Data Visualization Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This R snippet focuses on visualizing fMRI data. It likely uses packages such as 'oro.nifti' for data loading and 'ggplot2' or base R plotting functions for creating visual representations of the brain activity. ```R library(oro.nifti) library(ggplot2) # Load an example NIfTI file nifti_file <- readNIfTI("example.nii.gz") # Convert to a data frame for plotting (example: first time point) # This is a simplified example; actual data structure may vary img_data <- as.data.frame(as.vector(nifti_file[,,,1])) colnames(img_data) <- "intensity" # Basic histogram of voxel intensities ggplot(img_data, aes(x = intensity)) + geom_histogram(binwidth = 50) + ggtitle("Distribution of Voxel Intensities") ``` -------------------------------- ### Basic CSS for Code Snippets and Layout Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html A collection of CSS rules for styling various elements, including code blocks (pre, code, span.sourceCode), layout containers (div.column, div.hanging-indent), and task lists. It also includes styles for body, table, and table of contents (TOC). ```css code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} ul.task-list{list-style: none;} code { white-space: pre; } .sourceCode { overflow: visible; } html { -webkit-text-size-adjust: 100%; } pre > code.sourceCode { white-space: pre; position: relative; } pre > code.sourceCode > span { display: inline-block; line-height: 1.25; } pre > code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode > span { color: inherit; text-decoration: inherit; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { pre > code.sourceCode { white-space: pre-wrap; } pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } ``` ```css pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; color: #aaaaaa; } pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; } div.sourceCode { } @media screen { pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; } } ``` ```css body { background-color: #fff; margin: 1em auto; max-width: 700px; overflow: visible; padding-left: 2em; padding-right: 2em; font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.35; } #TOC { clear: both; margin: 0 0 10px 10px; padding: 4px; width: 400px; border: 1px solid #CCCCCC; border-radius: 5px; background-color: #f6f6f6; font-size: 13px; line-height: 1.3; } #TOC .toctitle { font-weight: bold; font-size: 15px; margin-left: 5px; } #TOC ul { padding-left: 40px; margin-left: -1.5em; margin-top: 5px; margin-bottom: 5px; } #TOC ul ul { margin-left: -2em; } #TOC li { line-height: 16px; } table { margin: 1em auto; border-width: 1px; border-color: #DDDDDD; border-style: outset; border-collap ``` -------------------------------- ### Basic Command Execution Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This snippet shows a basic command execution, likely used for interacting with the operating system or running external tools. It's a fundamental operation that might be part of a larger script or workflow. ```bash echo "Processing fMRI data..." # Placeholder for a command that might process data # e.g., python process_script.py --input data.nii --output processed_data.nii ``` -------------------------------- ### Syntax Highlighting - CSS Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html CSS classes defining syntax highlighting for various code elements such as keywords, comments, strings, and numbers. These styles are typically used in conjunction with a code highlighting library. ```css code span.al { color: #ff0000; font-weight: bold; } code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } code span.at { color: #7d9029; } code span.bn { color: #40a070; } code span.bu { color: #008000; } code span.cf { color: #007020; font-weight: bold; } code span.ch { color: #4070a0; } code span.cn { color: #880000; } code span.co { color: #60a0b0; font-style: italic; } code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } code span.do { color: #ba2121; font-style: italic; } code span.dt { color: #902000; } code span.dv { color: #40a070; } code span.er { color: #ff0000; font-weight: bold; } code span.ex { } code span.fl { color: #40a070; } code span.fu { color: #06287e; } code span.im { color: #008000; font-weight: bold; } code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } code span.kw { color: #007020; font-weight: bold; } code span.op { color: #666666; } code span.ot { color: #007020; } code span.pp { color: #bc7a00; } code span.sc { color: #4070a0; } code span.ss { color: #bb6688; } code span.st { color: #4070a0; } code span.va { color: #19177c; } code span.vs { color: #4070a0; } ``` -------------------------------- ### R: Parametric Regressor with Varying Amplitude Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html Creates a parametric regressor by scaling the HRF based on a provided amplitude vector. It shows how to center the amplitudes, generate the regressor, evaluate it over scan times, and plot the results with onset markers and amplitude points. ```r # Example onsets and amplitudes (e.g., representing task difficulty) onsets_amp <- seq(0, 10 * 12, length.out = 11) amplitudes_raw <- 1:length(onsets_amp) # It's common practice to center the modulator amplitudes_scaled <- scale(amplitudes_raw, center = TRUE, scale = FALSE) # Create the parametric regressor reg_amp <- regressor(onsets_amp, HRF_SPMG1, amplitude = amplitudes_scaled) print(reg_amp) # Evaluate and plot scan_times_amp <- seq(0, max(onsets_amp) + 30, by = TR) pred_amp <- evaluate(reg_amp, scan_times_amp) plot_df_amp <- data.frame(Time = scan_times_amp, Response = pred_amp) ggplot(plot_df_amp, aes(x = Time, y = Response)) + geom_line(linewidth = 1) + geom_vline(xintercept = onsets(reg_amp), linetype = "dashed", color = "red", alpha = 0.7) + # Add points showing amplitude (scaled for visibility) geom_point(data = data.frame(Time = onsets(reg_amp), Amplitude = amplitudes(reg_amp)), aes(x = Time, y = Amplitude * 0.2), color = "blue", size = 2) + labs(title = "Parametric Regressor with Varying Amplitude", subtitle = "Amplitude (centered) increases over time", x = "Time (seconds)", y = "Predicted Response") + theme_minimal() ``` -------------------------------- ### Create a Basic Regressor with fmrihrf Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This snippet demonstrates how to create a regressor object using the `regressor()` function in fmrihrf. It takes event onsets and optionally an HRF (defaults to SPMG1). The resulting object stores event information and can be inspected using `print()`, `onsets()`, and `nbasis()`. ```r # Define event onsets onsets <- seq(0, 10 * 12, by = 12) # Create the regressor object # Uses HRF_SPMG1 by default if no hrf is specified # Duration is 0 by default reg1 <- regressor(onsets = onsets, hrf = HRF_SPMG1) # Print the regressor object to see its properties (uses new print.Reg method) print(reg1) # Access components using helper functions head(onsets(reg1)) nbasis(reg1) ``` -------------------------------- ### Data Analysis and Visualization in R Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This R code snippet demonstrates data analysis and visualization techniques. It likely involves loading data, performing statistical operations, and generating plots. Specific dependencies might include packages like 'ggplot2' or 'dplyr'. The output is typically graphical or tabular summaries. ```r library(ggplot2) # Sample data data <- data.frame( x = 1:10, y = rnorm(10) ) # Create a scatter plot ggplot(data, aes(x = x, y = y)) + geom_point() + ggtitle("Sample Scatter Plot") ``` -------------------------------- ### Shell: Execute a Python script for data analysis Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_01_hemodynamic_response.html This shell command executes a Python script named 'pydata.py' which is likely responsible for analyzing 'data.csv'. This is a common pattern for initiating data processing pipelines or machine learning model execution from the command line. ```shell python pydata.py data.csv ``` -------------------------------- ### Python: Statistical Analysis of fMRI Data Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This Python code snippet illustrates performing statistical analysis on fMRI data. It might involve calculating correlations, applying statistical tests, or fitting models to the data, potentially using libraries like SciPy or Statsmodels. ```Python from scipy import stats # Assume 'signal_a' and 'signal_b' are NumPy arrays representing time series from two brain regions # Example: signal_a = data[10, 10, 10, :] # Example: signal_b = data[20, 20, 20, :] # Placeholder for actual data loading and extraction signal_a = np.random.rand(100) signal_b = np.random.rand(100) # Calculate Pearson correlation coefficient correlation, p_value = stats.pearsonr(signal_a, signal_b) print(f"Correlation between signal A and B: {correlation:.3f}") print(f"P-value: {p_value:.3f}") ``` -------------------------------- ### Create a dictionary from two lists Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html This function creates a dictionary by pairing elements from two lists, where the first list provides the keys and the second list provides the values. It assumes both lists have the same length. ```python def lists_to_dict(keys, values): """Creates a dictionary from two lists (keys and values).""" if len(keys) != len(values): raise ValueError("Lists must have the same length to create a dictionary.") return dict(zip(keys, values)) # Example Usage: # keys = ['a', 'b', 'c'] # values = [1, 2, 3] # print(lists_to_dict(keys, values)) # Output: {'a': 1, 'b': 2, 'c': 3} ``` -------------------------------- ### Perform GLM Analysis Source: https://github.com/bbuchsbaum/fmrihrf/blob/main/fmrihrf.Rcheck/00_pkg_src/fmrihrf/inst/doc/a_02_regressor.html Conducts a General Linear Model (GLM) analysis on fMRI data. This involves setting up the design matrix, fitting the model, and extracting statistical results. Requires fMRI data and event timing information. ```python import statsmodels.api as sm def perform_glm_analysis(fmri_data, design_matrix): # fmri_data: voxel time series data # design_matrix: matrix of regressors (e.g., HRF convolved events) # Add a constant regressor for the mean X = sm.add_constant(design_matrix) # Fit the GLM model model = sm.GLM(fmri_data, X, family=sm.families.Gaussian()) results = model.fit() return results # Example usage: # fmri_data = load_fmri_data('subject1_bold.nii') # design_matrix = create_design_matrix(event_times, hrf_basis) # glm_results = perform_glm_analysis(fmri_data[:, 0], design_matrix) # For a single voxel # print(glm_results.summary()) ```