SOCR ≫ DSPA ≫ DSPA2 Topics ≫

This DSPA2 appendix illustrates some very simple examples of using the OpenAI API for synthetically generating free text, 2D images, and software code.

This is a \(3^{rd}\) generation SOCR AI Bot for (1) synthetically simulating intelligent text response to human text/voice prompts; (2) simulating realistic 2D brain images; and (3) writing R code for simple verbal descriptions. These are based on OpenAI and Third-generation Generative Pre-trained Transformer (GPT-3) technologies.

1 Context-Specific Synthetic Text Responses

Based on GPT3, use OpenAI to respond to the following prompt, i.e., the text input seeding/guiding the AI verbose response:

Expected health disparities and racial inequality in the US in 2030…

# What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.

# GPT-3 models: https://beta.openai.com/docs/models/gpt-3

# General Health Essay
synthText <- create_completion(model = "text-davinci-003", n=5, best_of=10,
                               max_tokens=300, temperature=0.8, # 
                               prompt = "Write an abstract of a healthcare essay")
                               # prompt = "How many outerspace layers are there?")
synthText$choices$text
## [1] "\n\nThis essay explores the role of health care systems in addressing the growing disparities in health care access and outcomes. It examines the current state of health care systems in the United States, and considers how they can be improved to reduce disparities in health care access and outcomes. The essay discusses how changes to the health care system can be used to improve medical care and reduce health inequities, including expanding access to existing health care services, investing in preventive health care, providing incentives for health care providers to serve underserved populations, and implementing measures to reduce disparities in health insurance coverage. It also discusses how healthcare systems can be improved to best meet the needs of all individuals, regardless of their income or socio-economic status. In conclusion, this essay argues for the importance of creating a more equitable health care system in order to address the growing disparities in health care access and outcomes."
## [2] "\n\nThis essay examines the ethical implications of the use of healthcare resources in the United States. It argues that the current allocation of resources results in disparities between different population groups and is an ethical issue that needs to be addressed. The essay looks at the history of healthcare, the current healthcare landscape and how it affects different populations, and possible solutions to address the ethical implications of the current system. It concludes by arguing that the ethical implications of the current healthcare system must be addressed in order to ensure that all individuals have access to equitable healthcare."                                                                                                                                                                                                                                                                                                                                                                           
## [3] "\n\nThis essay explores the implications of healthcare privatization on public health outcomes. It draws on case studies from the United States, United Kingdom, and Canada to analyze the effects of privatization on access to health care and the quality of care. The essay finds that the privatization of healthcare systems has led to increased costs and reduced access to care, with more limited services being provided to those with lower incomes. The essay also explores the potential benefits of healthcare privatization, including increased efficiency and cost savings. Overall, this essay argues that while healthcare privatization may create some benefits, it can also have a detrimental impact on public health outcomes."                                                                                                                                                                                                                                                                                                
## [4] "\n\nThis essay provides an in-depth discussion of the increasing prevalence of mental health issues in modern society and the various ways in which healthcare professionals are responding to this. Through a review of current literature, the essay examines the various methods being used to improve mental health services, including prevention and early intervention strategies, the use of technology, and the development of more comprehensive care models. The paper also discusses the need for increased investment in mental healthcare and the importance of addressing stigma and discrimination associated with mental illness. Ultimately, the essay argues that the healthcare industry must work together to develop more comprehensive and effective solutions to mental health issues in order to improve overall public health."                                                                                                                                                                                               
## [5] "\n\nThis essay aims to provide an analysis of the current healthcare landscape in the United States. Through an exploration of the key issues facing healthcare providers and patients, as well as an examination of potential strategies to address these challenges, this essay looks to provide insights into ways to improve the healthcare system. By examining the history of healthcare policy, the current landscape of health insurance and public health initiatives, and the potential implications of these policies on both providers and patients, this essay seeks to provide an in-depth analysis of the current healthcare system in the United States. By doing so, it hopes to provide a comprehensive overview of the current healthcare system and offer possible solutions to address the various challenges that exist."
# Health Disparity
synthText <- 
  create_completion(model = "text-davinci-003", n=5, best_of=10,
                    max_tokens=300, temperature=0.8, # 
                    prompt = "Expected health disparities and racial inequality in the US in 2030")
synthText$choices$text
## [1] "\n\n1. Inequities in access to healthcare: By 2030, minority and underserved communities will continue to face disparities in access to medical care, compounded by disparities in the availability of health insurance, leading to significant differences in health outcomes.\n\n2. Social determinants of health: Social determinants of health, including poverty, education, housing, and employment, will continue to drive inequality in health outcomes. Those living in poverty will suffer from poor health due to limited access to preventive healthcare, nutritional food, and safe housing.\n\n3. Mental health: Mental health disparities will continue to be pronounced among minority communities, with a higher prevalence of untreated mental health conditions and less access to mental health services.\n\n4. Access to quality healthcare: There will be a growing disparity in access to quality healthcare between minority and non-minority communities, leading to unequal access to the best treatment options.\n\n5. Cost of healthcare: The cost of healthcare will continue to be a major barrier to healthcare access for many minority and underserved communities, further increasing disparities in health outcomes. \n\n6. Health disparities in rural areas: By 2030, rural communities, many of which are predominantly composed of minority populations, will continue to suffer from health disparities due to limited access to healthcare services and specialists."                                                                                                                             
## [2] "\n\nExpected health disparities and racial inequality in the US in 2030 include an increased lifespan gap between people of color and white Americans. Black Americans are projected to have a life expectancy 5 years shorter than white Americans. The prevalence of chronic diseases such as diabetes, heart disease, and hypertension is expected to increase for people of color, as well as for Native Americans and other minority groups.\n\nRacial disparities in access to health care are expected to remain, with people of color more likely to be uninsured and have poorer access to health care services. Additionally, the disparities in education and employment opportunities for people of color are expected to continue, leading to further health disparities due to lack of resources and income.\n\nThe US is also expected to experience rising levels of environmental injustice as people of color are more likely to live in areas of higher air pollution and water contamination. This will in turn lead to increased rates of asthma, cancer, and other illnesses. Furthermore, inadequate access to nutritious food and safe housing are expected to remain a problem in many communities of color, leading to higher rates of obesity and other health issues."                                                                                                                                                                                                                                                                                                                                         
## [3] "\n\n1. Increased infant mortality rates among people of color: Studies have shown that infant mortality rates among African Americans are 2.4 times higher than for whites, and Native American and African American women have higher rates of infant death than any other racial group in the US. This disparity is likely to continue and increase in the next decade due to increased poverty, lack of access to quality healthcare, and environmental conditions. \n\n2. Persisting disparities in access to healthcare: People of color are more likely to be uninsured and have difficulty navigating the complex healthcare system. As a result, they are less likely to get the care they need, leading to increased levels of preventable diseases and poorer outcomes.\n\n3. Higher rates of chronic illnesses among people of color: People of color are disproportionately affected by chronic illnesses such as diabetes and obesity. This is due to a lack of access to healthy food and exercise opportunities, combined with the heavy burden of social and economic stresses. This trend is likely to continue in the coming decade.\n\n4. Widening gap in the quality of education: People of color are more likely to attend under-resourced schools and have lower levels of educational attainment. This is due to a lack of access to resources and quality teaching. This trend is likely to continue and even worsen, resulting in larger gaps in educational outcomes between racial groups. \n\n5. Increases in racial profiling by law enforcement: People of color are more likely to be stopped and searched"
## [4] "\n\n1. Expected rise in chronic health conditions such as obesity, diabetes and heart disease among lower-income communities of color due to limited access to quality health care and healthy food.\n\n2. A continued rise in mental health issues among people of color due to enduring discrimination, poverty, and lack of job security.\n\n3. Widening economic inequality between white and non-white households, with people of color disproportionately impacted by job losses due to automation and the gig economy.\n\n4. Widening gaps in educational attainment and educational opportunities for people of color due to structural inequalities in the education system.\n\n5. Continued disparities in access to quality health care, with people of color more likely to receive poorer-quality care due to structural racism and discrimination.\n\n6. Increased criminalization of people of color, with policies that disproportionately target racial minorities.\n\n7. A continued rise in police violence against people of color due to inadequate training and accountability measures.\n\n8. Higher rates of poverty among people of color, due to structural racism and lack of access to resources and opportunities."                                                                                                                                                                                                                                                                                                                                                                                           
## [5] "\n\nHealth disparities and racial inequality in the US are expected to continue in 2030 due to entrenched systemic racism and the effects of the COVID-19 pandemic. African Americans and other people of color are more likely to experience health disparities due to the impacts of structural racism, such as unequal access to healthcare and financial resources, discrimination in the job market, and limited access to nutritious food. Additionally, communities of color are more likely to be exposed to air pollution and other environmental toxins, putting them at greater risk of developing chronic illnesses.\n\nThe economic fallout from the COVID-19 pandemic is also expected to have a profound impact on health disparities and racial inequality in the US. As the economic recession deepens, people of color are more likely to experience greater economic insecurity, unemployment, and reduced access to healthcare. This will likely only increase existing disparities in health outcomes and access to health services.\n\nFinally, racial bias and discrimination in the healthcare system can lead to disparate diagnosis, treatment, and outcomes for patients of color. The legacy of racism in the US healthcare system is still very much alive, and it is expected to continue in 2030 unless significant efforts are made to address systemic racism."

2 Realistic 2D Brain Images

Generate 5 2D sagittal MRI brain images of Alzheimer’s disease patients and contrast these to healthy control patients.

2.1 imulated 2D Brain Scans of Asymptomatic Controls (Healthy Participants)

#### Healthy Controls 

library(RCurl)
library(json64)
## Warning: package 'json64' was built under R version 4.2.2
library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# Generate images": maximum text-prompt text length is 1000 characters, 1 <= n <= 10
# https://beta.openai.com/docs/api-reference/images/create

synthImages <- create_image("2D sagittal MRI brain image of Healthy Asymptomatic Controls",
                            n=5, size="1024x1024",
                            response_format="b64_json")  # response_format="url"

# Convert base64 JSON synth images to 2D rasterized images
# single image rendering
# raw1 <- base64Decode(synthImages$data[1]$b64_json[1], mode="raw")
# img1 <- png::readPNG(raw1)
# plot_ly(z=~(255*img1), type="image")
# plot_ly(z=~(255*img1[,,1]), type="heatmap")

convBase64JSON2Img <- function(txt) {
  raw <- base64Decode(txt, mode="raw")
  # Handle PNG format
  if (all(as.raw(c(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) == raw[1:8])) {
    img <- png::readPNG(raw)
  } 
  # Handle JPEG format
  else if (all(as.raw(c(0xff, 0xd8, 0xff, 0xd9)) == raw[c(1:2, length(raw)-(1:0))])) { 
    img <- jpeg::readJPEG(raw)
  } 
  # Currently no other formats are interpreted, but other formats can be added below
  else stop("No Appropriate Image Format Interpreter Available ...")
  return(img)
}
# raw1 <- convBase64JSON2Img(synthImages$data[1]$b64_json[1])
# plot_ly(z=~(255*raw1), type="image")

vars <- c(1:length(synthImages$data[1]$b64_json))
plots <- lapply(vars, function(var) {
  raw = convBase64JSON2Img(synthImages$data[1]$b64_json[var])
  plot_ly(z=~(255*raw), type="image", name=paste0("Synth Healthy Control Img ", var)) %>%
                        layout(title = paste0("Synth AD Img ", var),
                          xaxis = list(title = "", showticklabels = FALSE), 
                          yaxis = list(title = "", showticklabels = FALSE))
})
subplot(plots, nrows = 1, shareY = TRUE) %>% layout(title="Simulated 2D Scans of Healthy Controls")