### PhenEx Quick Start Example Workflow (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Provides a minimal example demonstrating the quick start usage pattern for PhenEx, including initializing the package and running a sample workflow with simulated data. ```r library(phenexr) # Create phenotype age <- AgePhenotype$new() # Run example results <- phenex_example_workflow(use_example_data = TRUE) ``` -------------------------------- ### PhenEx R Package Development Setup (Bash) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Provides shell commands for setting up the development environment for the PhenEx R package. This includes installing Python dependencies, R package dependencies, and running integration tests before building the package. ```bash # Ensure Python and PhenEx are installed pip install phenex # Install R package dependencies R -e "install.packages(c('reticulate', 'R6', 'devtools', 'testthat'))" # Test integration cd r-package ./test_integration.R # Build and install ./build.R ``` -------------------------------- ### Install PhenEx from Source Source: https://github.com/bayer-group/phenex/blob/main/docs/installation.md For developers or users who need the latest unreleased features. This involves cloning the repository, installing dependencies, and then installing the package. Ensure you are in an activated Python virtual environment. ```bash git clone https://github.com/Bayer-Group/PhenEx.git && cd PhenEx && pip install -r requirements.txt && pip install . ``` -------------------------------- ### Run Interactive Cohort Example Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Executes an R script that provides an interactive workflow for cohort analysis using mock OMOP data. This example guides the user through the PhenEx workflow with prompts and explanations. ```r source("r-package/examples/cohort_example.R") ``` -------------------------------- ### Install PhenEx using Pip Source: https://github.com/bayer-group/phenex/blob/main/docs/installation.md Recommended method for installing PhenEx. Requires an activated Python virtual environment. This command fetches and installs the latest stable version of PhenEx from the Python Package Index (PyPI). ```bash pip install PhenEx ``` -------------------------------- ### PhenEx R Package User Installation (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Shows R commands for installing the PhenEx R package for end-users, either directly from GitHub or from a local source directory. It also lists necessary R package dependencies. ```r # Install dependencies install.packages(c("reticulate", "R6")) # Install PhenEx R package devtools::install_github("Bayer-Group/PhenEx/r-package") # Or from local source devtools::install_local("path/to/r-package") ``` -------------------------------- ### Check PhenEx Installation Version Source: https://github.com/bayer-group/phenex/blob/main/docs/installation.md Verifies that PhenEx has been successfully installed by importing the library and printing its version. This command should be run in the activated Python virtual environment where PhenEx was installed. ```python python -c "import phenex;print(phenex.__version__)" ``` -------------------------------- ### Set Up Time to Event Analysis Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This code initializes the setup for a time-to-event analysis in PhenEx. It defines phenotypes for the end of follow-up and death censoring, crucial for survival analysis. ```python import datetime from phenex.reporting import TimeToEvent from phenex.phenotypes import DeathPhenotype end_of_followup = TimeRangePhenotype( name='end_of_followup', relative_time_range=RelativeTimeRangeFilter(when='after') ) death_right_censor = DeathPhenotype( name = 'death_censoring', domain='DEATH', relative_time_range=f_postindex ) right_censor_phenotypes = [end_of_followup, death_right_censor] ``` -------------------------------- ### Install PhenEx R Package from GitHub Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Installs the PhenEx R package directly from its GitHub repository, specifically from the 'feat/rbindings' branch. This is the recommended installation method. ```r devtools::install_github("Bayer-Group/PhenEx", subdir = "r-package", ref = "feat/rbindings") ``` -------------------------------- ### Install PhenEx R Package from Local Directory Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Installs the PhenEx R package from a local directory on your machine. This is useful if you have cloned the repository and want to install from a local copy, with the `force = TRUE` option to overwrite existing installations. ```r devtools::install_local("r-package", force = TRUE) ``` -------------------------------- ### PhenEx Python Imports Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Demonstrates how to import PhenEx components, including individual imports and multiple imports at once. It is recommended to keep import statements at the top of the file. Ensure PhenEx is installed before importing. ```python # import phenotypes one by on from phenex.phenotypes import CodelistPhenotype from phenex.phenotypes import MeasurementPhenotype # import multiple phenotypes at once. This is identical to above from phenex.phenotypes import ( CodelistPhenotype, MeasurementPhenotype ) ``` -------------------------------- ### Python Class Instantiation for Phenex Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Shows how to instantiate a 'CodelistPhenotype' class, likely used within the Phenex project. This example highlights the creation of an object with specific parameters like name, domain, and a 'codelist' property, which itself is an instance of another class. It demonstrates practical application of class instantiation in a project context. ```python # creating an instance of the class CodelistPhenotype myPhenotypeObject = CodelistPhenotype( name = 'atrial fibrillation', domain = 'CONDITION_OCCURRENCE', codelist = Codelist(['c1']), # creating an instance of the class Codelist ) ``` -------------------------------- ### Set up Python Environment with venv (System Python) Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Creates and activates a Python virtual environment using the system's Python interpreter. It then installs the `phenex` Python library within this environment. ```bash python3 -m venv phenex-venv source phenex-venv/bin/activate pip install phenex ``` -------------------------------- ### Install PhenEx R Package Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This R command installs the phenexr R package directly from source. It is used when the package is not available through standard repositories or when installing a development version. ```r install.packages("r-package", repos = NULL, type = "source") ``` -------------------------------- ### Set up Python Environment with venv (ARM64) Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Creates and activates a Python virtual environment using the `venv` module, specifically for ARM64 architecture (common on Apple Silicon). It then installs the `phenex` Python library within this environment. ```bash # Use Homebrew Python (ARM64 native) - recommended path /opt/homebrew/bin/python3.12 -m venv .venv source .venv/bin/activate pip install phenex ``` -------------------------------- ### Verify PhenEx Python Installation Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Runs a Python command to import the `phenex` library and print a success message. This verifies that the PhenEx Python library has been correctly installed and is accessible in the current Python environment. ```bash python -c "import phenex; print('PhenEx installed successfully')" ``` -------------------------------- ### Get OMOP Mapped Tables Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Demonstrates how to retrieve OMOP-mapped tables from a database connection. This involves first getting the available OMOP domains and then querying for mapped tables. ```r # Get OMOP-mapped tables omop <- omop_domains() tables <- omop$get_mapped_tables(conn) ``` -------------------------------- ### Python Class with Properties and Methods Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Illustrates a Python class 'Animal' with an initializer that accepts an argument to set a property and a method to display that property. This example shows how to define class properties using 'self' and create class methods. It also demonstrates object instantiation and accessing properties and methods using dot notation. ```python class Animal: # modify our init function to take a single argument, type, with a defined default value def __init__(self, type_of_animal = "generic_animal"): # create class property called 'type_of_animal_property' and set it to the keyword argument type_of_animal self.type_of_animal_property = type_of_animal # add a new function/class_method called what_type_of_animal_am_i def what_type_of_animal_am_i(self): print("I am a", self.type_of_animal_property) # create three animal objects animal1 = Animal() animal2 = Animal(type_of_animal="Flamingo") animal3 = Animal(type_of_animal="Bear") # we can access data (class properties) with dot notation! # Note: The original text had a typo here, accessing 'type_of_animal' instead of 'type_of_animal_property' # print(animal2.type_of_animal) # This would cause an error print(animal2.type_of_animal_property) # we can access functions (class methods) with dot notation, and call them like we call all functions animal3.what_type_of_animal_am_i() ``` -------------------------------- ### Data Integration with PhenEx (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Shows how PhenEx facilitates data integration by supporting connections to databases (like Snowflake), direct use of CSV files or data frames, and generation of example OMOP data for testing purposes. ```r # Database connections conn <- SnowflakeConnector$new(account = "...", user = "...", ...) tables <- omop_domains()$get_mapped_tables(conn) # CSV/data.frame integration df <- read.csv("patient_data.csv") table <- df_to_phenex_table(df, "patients") # Example/simulated data example_data <- create_example_omop_data(n_patients = 1000) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Lists the R packages required for developing the PhenEx R package. These include tools for documentation generation and package building. ```r # Install development dependencies install.packages(c("roxygen2", "devtools", "pkgdown")) ``` -------------------------------- ### Set up Python Environment with Conda (ARM64) Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Sets up a Python 3.12 environment named 'phenex-r' using Conda, activates it, and installs the `phenex` Python library. This is an alternative method for managing Python environments, particularly for ARM64. ```bash conda create -n phenex-r python=3.12 conda activate phenex-r pip install phenex ``` -------------------------------- ### Snowflake Database Connection Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Provides an example of establishing a connection to a Snowflake database using the `SnowflakeConnector` class. It includes parameters for account, user, password, warehouse, database, and schema. ```r # Snowflake connection conn <- SnowflakeConnector$new( account = "your_account", user = "your_user", password = "your_password", warehouse = "your_warehouse", database = "your_database", schema = "your_schema" ) ``` -------------------------------- ### Creating and Accessing Python Lists Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Demonstrates how to create a Python list, a fundamental data structure for storing ordered collections of items. Lists are used in PhenEx for defining inclusion/exclusion criteria and baseline characteristics. Accessing items is done via their index, starting from 0. ```python # a list containing phenotypes! list_of_phenotypes = [phenotype1, phenotype2] ``` ```python # write the name of the list you want to access, followed by square brackets containing the index of the item you want to access list_of_phenotypes[0] # this will be phenotype1, the first item in the list list_of_phenotypes[1] # this will be phenotype2, the second item in the list ``` -------------------------------- ### Reinstall/Reload PhenEx R Package Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This R code snippet addresses the 'could not find function phenex_initialize' error by ensuring the phenex R package is properly installed and loaded. It includes commands to reinstall the package from source and reload the library. ```r # Package not properly installed or loaded install.packages("r-package", repos = NULL, type = "source") # Reinstall library(phenexr) # Reload ``` -------------------------------- ### Update PhenEx to Latest Version Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This Python snippet installs or updates the PhenEx library to the latest released version using pip. It ensures the user has the most current features and bug fixes. ```python # For updating PhenEx to latest released version # !pip install -Uq PhenEx ``` -------------------------------- ### Get Mapped OMOP Tables using PhenEx Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This Python snippet imports `OMOPDomains` from PhenEx and retrieves mapped tables from a Snowflake connection. This is essential for PhenEx to understand the structure and content of OMOP-formatted data. ```python from phenex.mappers import OMOPDomains mapped_tables = OMOPDomains.get_mapped_tables(con) list(mapped_tables.keys()) ``` -------------------------------- ### Build Patient Cohorts Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Demonstrates how to construct a patient cohort by defining inclusion criteria using various phenotypes. This example creates a cohort for a type 2 diabetes study including adult patients. ```r # Define inclusion criteria inclusion_phenotypes <- list( diabetes, AgePhenotype$new() # Will filter for adults ) # Create cohort study_cohort <- Cohort$new( name = "diabetes_study", inclusions = inclusion_phenotypes, description = "Type 2 diabetes patients for outcomes study" ) ``` -------------------------------- ### Check Python Architecture on Apple Silicon Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This bash command checks the architecture of the default Python installation. It is used to diagnose architecture mismatch errors, ensuring Python is running in ARM64 mode on Apple Silicon. ```bash # Check your Python architecture python3 -c "import platform; print(platform.machine())" # Should show 'arm64' on Apple Silicon # If showing 'x86_64', you need ARM64 Python: brew install python@3.12 # This installs ARM64 version on Apple Silicon /opt/homebrew/bin/python3.12 -m venv new_venv ``` -------------------------------- ### Python Global vs. Local Scope Demonstration Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Illustrates the concept of global and local scope in Python using indentation. A global variable 'x' is accessible throughout the script, while a local variable 'y' is only accessible within the 'some_function'. This example clarifies how Python uses indentation to define code blocks and variable scope. ```python # we create a variable called x with global scope (no indentation! not in a code block) x = 10 def some_function(): # create a variable called y with local scope y = 5 print("Inside function, x:", x) # Accessing global variable print("Inside function, y:", y) # Accessing local variable some_function() print("Outside function, x:", x) # Accessing global variable # print("Outside function, y:", y) # This would cause a NameError as y is local to some_function ``` -------------------------------- ### Initialize PhenEx Python Environment (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Demonstrates how to automatically initialize or manually configure the Python virtual environment for PhenEx within an R session. This ensures that the necessary Python backend is accessible for the R package. ```r library(phenexr) # Automatic initialization on package load # Manual initialization if needed: phenex_initialize(virtualenv = "phenex-env") ``` -------------------------------- ### Define and Execute a Simple Python Function Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Shows the definition of a Python function named 'greet' that accepts a name as input and prints a greeting. It then demonstrates how to call this function with a specific argument. ```python def greet(name): print("Hello, " + name) ``` ```python greet("Alice") # Output: Hello, Alice ``` -------------------------------- ### Python Keyword Argument Usage in greet function Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Demonstrates how to use keyword arguments when calling a Python function. This allows explicit assignment of values to function parameters by their names. ```python greet(name='Alice') # use the keyword 'name' when calling greet ``` -------------------------------- ### Python Object Instantiation from Animal Class Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Illustrates how to create an instance (object) of the previously defined 'Animal' class in Python. This demonstrates the process of object instantiation by calling the class name followed by parentheses. ```python animal1 = Animal() ``` -------------------------------- ### Install Jupyter Kernel for PhenEx Source: https://github.com/bayer-group/phenex/blob/main/docs/installation.md Installs a Jupyter kernel specifically for the PhenEx environment, allowing PhenEx to be used within Jupyter notebooks. Requires an activated Python virtual environment. ```python python -m ipykernel install --user --name phenex --display-name "PhenEx" ``` -------------------------------- ### Install R Dependencies for PhenEx Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Installs essential R packages required for the PhenEx R package, including devtools for package installation, reticulate for Python interoperability, R6 for object-oriented programming, and jsonlite for JSON handling. ```r install.packages(c("devtools", "reticulate", "R6", "jsonlite")) ``` -------------------------------- ### R Dependencies Installation Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This R command installs the necessary R dependencies for the PhenEx project, including 'reticulate', 'R6', and 'jsonlite', which are crucial for integrating R with Python and handling data structures. ```r install.packages(c("reticulate", "R6", "jsonlite")) ``` -------------------------------- ### Build Package Website Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Demonstrates how to build a static website for the R package using `pkgdown`. This website includes function references, vignettes, and an overview, generated from the package source and documentation. ```r # Generate pkgdown website pkgdown::build_site("r-package") ``` -------------------------------- ### Configure reticulate for Virtual Environment Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Configures the `reticulate` R package to use a specified Python virtual environment. This step is essential for R to find and utilize the correct Python installation and any installed Python packages, like PhenEx. ```r # Set the path to your python environment python_env <- './.venv' # Adjust this path as needed # Configure reticulate to use your Python environment reticulate::use_virtualenv(python_env, required = TRUE) ``` -------------------------------- ### Retrieve SBP Measurements Below a Threshold (Python) Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/MeasurementPhenotype_Tutorial.ipynb This example shows how to retrieve systolic blood pressure (SBP) measurements recorded within one year prior to an index date, with an additional filter to include only values less than 180 mmHg. It extends the previous example by incorporating a ValueFilter with a LessThan condition. Multiple rows per patient are still returned if they meet the criteria. ```python sbp7 = MeasurementPhenotype( name = 'sbp_mean_baseline', codelist = sbp_codelist, domain = 'MEASUREMENT', relative_time_range = ONEYEAR_PREINDEX, value_filter=ValueFilter( max_value=LessThan(180) ) ) sbp7.execute(mapped_tables) ``` -------------------------------- ### Python Get Type of Object Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Demonstrates how to determine the data type of an object in Python using the 'type()' function. This is useful for verifying that an object has been correctly instantiated from its intended class. ```python type(animal1) ``` -------------------------------- ### Render PhenEx Quarto Tutorial Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Renders a Quarto document that serves as a comprehensive tutorial for PhenEx. The tutorial covers database connection (Snowflake), OMOP data integration, medical codelists, study design, reporting, and interactive dashboards. ```r quarto::quarto_render("r-package/examples/PhenEx_Study_Tutorial.qmd") ``` -------------------------------- ### Create List of Inclusion Phenotypes Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This snippet consolidates the individual inclusion phenotypes into a list. The order of phenotypes in this list can affect the attrition table generated during cohort creation. ```python # Create the final list of includions. These criteria will be executed sequentially when creating the attrition table, so adjust the order as desired for the attrition table. inclusions = [pt_inclusion1, pt_inclusion2] ``` -------------------------------- ### Get OMOP Mapped Tables Dictionary in Python Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Retrieves and prints the keys of the mapped tables dictionary from OMOP domains using the PhenEx library. This is essential for understanding available dataset mappings. ```python from phenex.mappers import OMOPDomains omop_mapped_tables = OMOPDomains.get_mapped_tables(con) print(omop_mapped_tables.keys()) ``` -------------------------------- ### Python Phenex CodelistPhenotype Component Initialization Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Shows how to initialize a Phenex CodelistPhenotype component using keyword arguments. This process parameterizes the component by assigning values to its required arguments like name, domain, codelist, and relative_time_range. ```python phenotype4 = CodelistPhenotype( name = 'atrial fibrillation', # the keyword argument name takes a value of type string; we can define the name of our phenotype! domain = 'CONDITION_OCCURRENCE', # the keyword argument domain takes a value of type string ; this must be one of the keys in our mapped_tables dictionary codelist = Codelist(['c1']), # the keyword argument codelist takes a value of type Codelist; we need to create this! relative_time_range = one_year_pre_index # the keyword argument relative_time_range takes value of type RelativeTimeRangeFilter which we must create ) ``` -------------------------------- ### Instantiate CodelistPhenotype with Domain Key in Python Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Demonstrates how to instantiate a CodelistPhenotype object, specifying the 'domain' parameter. This domain must correspond to a valid key within the mapped_tables dictionary to avoid errors. ```python phenotype3 = CodelistPhenotype( ... domain = 'CONDITION_OCCURRENCE' # this must be one of the keys in our mapped_tables dictionary ) ``` -------------------------------- ### Construct a PhenEx Cohort Definition using Functions in Python Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Illustrates a structured approach to defining a PhenEx cohort by breaking down the process into multiple functions for entry criteria, inclusion criteria, exclusion criteria, and baseline characteristics. The main function orchestrates the creation and execution of the cohort. ```python def create_my_cohort(): # define the entry criterion entry_criterion = CodelistPhenotype(...) # call all functions that further define oru cohort inclusion_criteria = create_inclusion_criteria(entry_criterion) exclusion_criteria = create_exclusion_criteria(entry_criterion) baseline_characteristics = create_baseline_characteristics(entry_criterion) # put the cohort together using all components we have created cohort = Cohort( entry = entry_criterion, inclusion = inclusion_criteria, exclusion = exclusion_criteria, characteristics = baseline_characteristics ) return cohort def create_inclusion_criteria(entry_criterion): # ... create inclusion criteria criteria here return inclusion_criteria def create_exclusion_criteria(entry_criterion): # ... create exclusion criteria here return exclusion_criteria def create_baseline_characteristics(entry_criterion): # ... create baseline characteristics criteria here return baseline_characteristics # call the function that builds the entire cohort cohort = create_my_cohort() cohort.execute() ``` -------------------------------- ### Define ECG CodelistPhenotype (Python) Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/CodelistPhenotype_Tutorial.ipynb Example of defining a CodelistPhenotype for ECG procedures within a relative time range. This snippet shows how to set the domain and the relative time range for the phenotype. ```python from phenex.phenotypes import CodelistPhenotype from phenex.filters import RelativeTimeRangeFilter ecg_codelist = [] # Assuming ecg_codelist is defined elsewhere one_month_after_af_diag = RelativeTimeRangeFilter( # Assuming this filter is defined elsewhere when='after', max_days=30 ) ecg = CodelistPhenotype( name = 'ecg_with_af_inpatient_or_outpatient_primary_one_month_after_af_diag', codelist = ecg_codelist, domain = 'procedure_occurrence', relative_time_range = one_month_after_af_diag ) ``` -------------------------------- ### Create ARM64 Python Environment Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This bash script demonstrates how to create an ARM64 Python virtual environment, essential for resolving architecture mismatches with reticulate on Apple Silicon. It includes steps to remove existing environments and create a new one using Homebrew Python. ```bash # Remove any existing x86_64 Python environment rm -rf .venv # Create ARM64 virtual environment using Homebrew Python (recommended) /opt/homebrew/bin/python3.12 -m venv .venv # Or use system Python if it's ARM64: # python3 -m venv .venv source .venv/bin/activate pip install phenex ``` -------------------------------- ### Construct and Execute PhenEx Cohort Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This code constructs a PhenEx cohort by combining entry criteria, inclusions, exclusions, characteristics, and outcomes. It then executes the cohort, specifying parameters like the number of threads and whether to overwrite existing data. ```python from phenex.phenotypes.cohort import Cohort cohort = Cohort( name = 'study_tutorial_cohort', entry_criterion=pt_entry, inclusions=inclusions, exclusions=exclusions, characteristics=characteristics, outcomes = outcomes, ) cohort.execute(mapped_tables, con = con, n_threads=6, overwrite=True, lazy_execution=True) ``` -------------------------------- ### R-Native Syntax for Phenotype Definition (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Illustrates the R-native syntax used to define and manipulate phenotypes. This includes creating codelists, defining phenotypes based on domains and codelists, combining phenotypes using logical operators, and executing them against data. ```r # Create codelist diabetes_codes <- icd_codelist(c("E11", "E11.9"), "diabetes") # Create phenotype diabetes <- CodelistPhenotype$new( domain = "CONDITION_OCCURRENCE", codelist = diabetes_codes ) # Combine with operators complex_phenotype <- diabetes %OR% age_over_65 %AND% NOT(exclusion_criteria) # Execute and analyze result <- diabetes$execute(tables) summary <- phenotype_summary(result) ``` -------------------------------- ### Initialize Ibis for Interactive Use Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/PhenEx_Study_Tutorial.ipynb This Python code initializes the Ibis library, setting the 'interactive' option to True. This is often used in environments like Jupyter notebooks to enable interactive execution and better output formatting for Ibis expressions. ```python import ibis ibis.options.interactive = True ``` -------------------------------- ### Complex Phenotype Logic with Time-Based Filters (R) Source: https://github.com/bayer-group/phenex/blob/main/r-package/ARCHITECTURE.md Demonstrates how to construct complex phenotypes in PhenEx by combining multiple conditions using logical operators and applying time-based filters, such as relative time ranges, to refine phenotype definitions. ```r # Combine multiple conditions cvd_phenotype <- mi_phenotype %OR% stroke_phenotype %OR% af_phenotype # Time-based filtering one_year_filter <- RelativeTimeRangeFilter$new( min_days = gt(0), max_days = lte(365), anchor_phenotype = index_event ) # Apply filters recent_cvd <- CodelistPhenotype$new( domain = "CONDITION_OCCURRENCE", codelist = cvd_codes, relative_time_range = one_year_filter ) ``` -------------------------------- ### PhenEx R Package Development Workflow Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md Outlines the typical workflow for contributing to the PhenEx R package. It covers editing source files, updating documentation comments, regenerating documentation, testing, and local installation. ```r # 1. Edit R source files in `r-package/R/` # 2. Update roxygen2 comments (`#'`) above functions/classes # 3. Regenerate documentation: `roxygen2::roxygenise("r-package")` # 4. Test package: `devtools::check("r-package")` # 5. Install locally: `devtools::install("r-package")` ``` -------------------------------- ### Roxygen2 Documentation Standard Source: https://github.com/bayer-group/phenex/blob/main/r-package/README.md This snippet illustrates the roxygen2 documentation standard for R functions and classes. It includes essential tags like #' for comments, @description, @param, @return, @export, and @examples, ensuring clear and user-friendly documentation for exported R functions. ```r #' Create a Medical Codelist #' #' @description #' Creates a new codelist for identifying patients with specific medical conditions #' #' @param codes Character vector of medical codes (ICD-10, CPT, etc.) #' @param name Name for the codelist #' @param code_type Type of codes ("ICD10CM", "CPT", etc.) #' @return A Codelist object #' @export #' @examples #' diabetes_codes <- create_codelist(c("E11", "E11.9"), "diabetes", "ICD10CM") ``` -------------------------------- ### Creating and Accessing Python Dictionaries Source: https://github.com/bayer-group/phenex/blob/main/docs/tutorials/Python_For_Phenex_Tutorial.ipynb Illustrates the creation and access of Python dictionaries, which store data as key-value pairs. Dictionaries are useful for representing structured data. Values are accessed using their corresponding keys, not by positional index. ```python person1 = { 'name':'Alice', # create a key which is a string called 'name' that is assigned the string value of alice 'age':40, # create a key which is a string with value 'age' that is assgned the integer value 40 'occupation':'researcher' } ``` ```python # write the name of dictionary you want to access, followed by square brackets containing the key you want to access person1['name'] # we want the value for the key which is a string with value 'name' ``` ```python Result: 'Alice' ```