---
title: "Creating RDML objects"
author: "RDML7 authors"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Creating RDML objects}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = FALSE)
library(RDML7)
```

## Create an object from tables

`buildRDMLFromFData()` is the shortest way to construct RDML data from user
fluorescence.

```r
fdata <- data.frame(
  cyc = 1:5,
  sample1_ACTB = c(10, 11, 15, 30, 80),
  sample1_GAPDH = c(9, 10, 14, 28, 75)
)

description <- data.frame(
  fdataName = c("sample1_ACTB", "sample1_GAPDH"),
  expId = c("exp1", "exp1"),
  runId = c("run1", "run1"),
  reactId = c("A1", "A1"),
  sample = c("sample1", "sample1"),
  sampleType = c("unkn", "unkn"),
  target = c("ACTB", "GAPDH"),
  targetDyeId = c("FAM", "HEX"),
  cq = c(21.3, 22.1)
)

x <- buildRDMLFromFData(
  fdata,
  description,
  fdataType = "adp",
  publisher = "Example laboratory"
)
```

The builder creates the minimum experiment, run, reaction, sample, target, and
dye hierarchy.

```r
summary(x)
asTable(x)
```

## Add melting data

```r
melt <- data.frame(
  tmp = c(70, 71, 72, 73),
  sample1_ACTB = c(100, 130, 90, 60)
)

x <- setFData(
  x,
  melt,
  description[1, ],
  fdataType = "mdp"
)
```

## Result columns

Description tables may carry calculated result fields such as `cq`,
`meltTemp`, or the package extension `meltTemp`.

`meltTemp` preserves multiple measured RDES Tm values. Standard RDML XML can
represent only the primary single `meltTemp`, so conversion to RDML may be
lossy.

## Direct S7 constructors

Advanced code can construct schema objects directly.

```r
sample <- sampleType(
  id = idType("sample1"),
  description = "Example sample"
)

dye <- dyeType(
  id = idType("FAM"),
  description = "FAM"
)

target <- targetType(
  id = idType("ACTB"),
  type = targetTypeType("toi"),
  dyeId = idReferenceType("FAM")
)
```

The exported schema help topics list the main type families:

```r
?rdml-metadata-types
?rdml-sample-target-types
?rdml-thermal-types
?rdml-experimental-types
```

## Value semantics

Always assign the returned object:

```r
x <- setFData(
  x,
  fdata,
  description,
  conflict = "replace"
)
```

## Validate and write

```r
validateRDML(x, action = "error")
writeRDML(x, "created.rdml")
```
