# Peer-review code package

## Polarity-Registered Nuclear Mapping Reveals Discrete Topological Classes of Chromosome Organization

**Package version:** 1.0 (peer-review release)  
**Package purpose:** reproducible demonstration of the homolog-classification and post-classification workflow  
**Language:** R, distributed as Quarto (`.qmd`) source documents  
**Corresponding author:** Paolo A. Netti  
**Contact:** paolo.netti@iit.it  

---

## 1. Overview

This archive contains the two custom R/Quarto scripts used to assign coherent homolog labels to chromosome territories and to generate the post-classification dataset used in downstream analyses.

The package includes a reduced **experimental** demonstration dataset containing only nuclei assigned to the **Top** state. It is included to permit editors and reviewers to run the complete workflow on real, representative input data without requiring the full experimental dataset.

The demonstration workflow is sequential:

```text
00_Demo_Top_Raw_ChromosomeTerritories.RData
                    │
                    ▼
Supplementary Code 1: homolog classification
                    │
                    ▼
01_Demo_Top_EnergyClassification.RData
                    │
                    ▼
Supplementary Code 2: post-classification annotation
                    │
                    ▼
02_Demo_Top_Postclassification.RData
```

The two latter files are supplied as reference intermediate and final outputs. They allow reviewers to verify that their local execution reproduces the expected state after each analysis step.

---

## 2. Recommended archive filenames

The following filenames are recommended for the reviewer archive:

| Order | Recommended filename | Object stored in the `.RData` file | Role |
|---:|---|---|---|
| 00 | `00_Demo_Top_Raw_ChromosomeTerritories.RData` | `DataSet_FlatTop` | Input dataset for Supplementary Code 1 and Supplementary Code 2 |
| 01 | `01_Demo_Top_EnergyClassification.RData` | `analysis_results` | Expected intermediate output from Supplementary Code 1; input for Supplementary Code 2 |
| 02 | `02_Demo_Top_Postclassification.RData` | `dataset` | Expected final output from Supplementary Code 2 |

The current filenames remain functional because both scripts use interactive file-selection dialogs. Renaming is recommended only to make the analysis order unambiguous to reviewers.

The two source-code files should be named:

```text
Supplementary_Code_1_Homolog_Classification.qmd
Supplementary_Code_2_PostClassification.qmd
```

---

## 3. Description of the two scripts

### Supplementary Code 1 — Similarity-based homolog classification

Supplementary Code 1 assigns coherent `Alpha` and `Beta` labels to homologous chromosome territories across nuclei.

For each possible starting nucleus, the script:

1. calculates pairwise Euclidean distances and elastic energies between provisional homolog labels;
2. compares direct and swapped homolog pairings;
3. constructs a greedy minimum-energy path through the nuclei;
4. propagates `Alpha` and `Beta` labels along that path; and
5. calculates cumulative energies.

The script generates one candidate path per starting nucleus. The output object, `analysis_results`, contains:

```r
analysis_results$paths  # chromosome-specific candidate paths
analysis_results$data   # combined data frame across all paths
```

For the supplied Top-state demonstration dataset, the reference result contains **67 candidate paths** and **8,978 rows** in `analysis_results$data`.

### Supplementary Code 2 — Post-classification homolog annotation and density-level assignment

Supplementary Code 2:

1. selects the candidate path with the lowest terminal cumulative energy;
2. transfers the corresponding `Alpha`/`Beta` assignments to the chromosome-territory dataset;
3. assigns within-group two-dimensional kernel-density levels;
4. applies the explicitly coded, display-oriented label calibration when enabled;
5. displays an example kernel-density estimate plot; and
6. saves the annotated output object, `dataset`.

The reference final output contains **268 chromosome-territory observations**, corresponding to 67 Top-state nuclei × 2 chromosome territories × 2 homologs.

---

## 4. Contents of the reviewer archive

```text
README.md
Supplementary_Code_1_Homolog_Classification.qmd
Supplementary_Code_2_PostClassification.qmd

00_Demo_Top_Raw_ChromosomeTerritories.RData
01_Demo_Top_EnergyClassification.RData
02_Demo_Top_Postclassification_Annotated.RData
```

---

## 5. System requirements

### Tested hardware and operating system

The workflow was validated on:

- **Computer:** MacBook Pro (Retina, 15-inch, Mid 2015)
- **Operating system:** macOS Monterey 12.7.1
- **Processor:** 2.8 GHz quad-core Intel Core i7
- **Memory:** 16 GB 1600 MHz DDR3
- **RStudio:** version 2023.12.0+369
- **R:** R version 4.3.1

No GPU acceleration, cloud-computing resource, or non-standard hardware is required.

### R and Quarto Required

- **R:** R version 4.1.0 or later is required because the code uses the native R pipe (`|>`).
- **Quarto:** required to render the `.qmd` documents; the scripts can alternatively be run interactively by executing their R code cells in RStudio.

### Required R packages

Install the following CRAN packages:

```r
install.packages(c(
  "dplyr",
  "tidyr",
  "purrr",
  "rio",
  "beepr",
  "ks",
  "plotrix"
))
```

The interactive file and directory dialogs use `tcltk`, which is included with most standard R installations.  No additional package is required for macOS and standard Windows installations.

---

## 6. Installation guide

1. Install R version 4.1.0 or later.
2. Install Quarto and/or RStudio. RStudio is recommended for interactive execution.
3. Install the R packages listed above.
4. Place both `.qmd` files and the three demonstration `.RData` files in the same directory.
5. Open the two Quarto documents in RStudio.

On a standard internet-connected desktop computer, installation of the required R packages usually takes only a few minutes when binary CRAN packages are available. Compilation from source may take longer.

---

## 7. Demonstration workflow

### 7.1 Demonstration input

The raw demonstration input is:

```text
00_Demo_Top_Raw_ChromosomeTerritories.RData
```

It contains the object `DataSet_FlatTop`, a reduced real-data subset consisting of **67 Top-state nuclei**. The subset contains chromosome territories `Chr06` and `Chr12`, with two provisional homolog labels per chromosome territory.

This reduced dataset is supplied only to demonstrate software execution. It is not intended to reproduce every quantitative result presented in the manuscript.

### 7.2 Run Supplementary Code 1

1. Open `Supplementary_Code_1_Homolog_Classification.qmd`.
2. Execute the R code cells sequentially. The document metadata intentionally disables automatic evaluation during rendering; run the code interactively in RStudio.
3. When prompted, select:

   ```text
   00_Demo_Top_Raw_ChromosomeTerritories.RData
   ```

4. Select a directory in which to save the generated energy-classification output.
5. Retain the default Top-state analysis parameters already specified in the document:

   ```r
   pattern = "F0.M0.0"
   chromosomes = c("Chr06", "Chr12")
   ```

6. The script saves an `.RData` file containing the object `analysis_results`.

The generated `analysis_results` object should correspond to the supplied reference intermediate file:

```text
01_Demo_Top_EnergyClassification.RData
```

### 7.3 Run Supplementary Code 2

1. Open `Supplementary_Code_2_PostClassification.qmd`.
2. Execute the R code cells sequentially.
3. When prompted for the chromosome-territory dataset, select:

   ```text
   00_Demo_Top_Raw_ChromosomeTerritories.RData
   ```

4. When prompted for the energy-classification dataset, select either:
   - the `.RData` output generated in Section 7.2; or
   - the supplied reference intermediate file:

     ```text
     01_Demo_Top_EnergyClassification.RData
     ```

5. Retain the default analysis settings:

   ```r
   analysis_pattern <- "F0.M0.0"
   path_selection_chromosome <- "Chr12"
   energy_variable <- "CumulativeTotalEnergy"
   ```

6. Select an output directory when prompted.

The script displays an example KDE plot and saves an `.RData` file containing the object `dataset`.

The generated `dataset` object should correspond to the supplied reference final-output file:

```text
02_Demo_Top_Postclassification_Annotated.RData
```

### 7.4 Display-oriented Alpha/Beta label calibration

Supplementary Code 2 includes an explicit optional label-swap function. The
currently active line swaps `Alpha` and `Beta` labels for `Chr12` after
density-level assignment. This operation changes only the display labels in
`Omologo_Energetico`; it does not modify coordinates, path selection, matching
energies, cumulative energies, or density estimates.

For reproducibility, retain or modify this line only when the same
display-oriented calibration is intended for the corresponding analysis and
figures.

---

## 8. Expected outputs and reproducibility checks

### Expected intermediate output

After Supplementary Code 1, the expected object is:

```r
analysis_results
```

with:

```r
length(analysis_results$paths)  # expected: 67
nrow(analysis_results$data)     # expected: 8978
```

### Expected final output

After Supplementary Code 2, the expected object is:

```r
dataset
```

with:

```r
nrow(dataset)                   # expected: 268
```

---

## 9. Expected run time

Supplementary Code 1 is the rate-limiting step because it constructs one candidate path for each of the 67 starting nuclei and evaluates the pairwise energy criterion repeatedly during path construction. Supplementary Code 2 is substantially faster.

| Analysis step | Demonstration dataset | Expected elapsed time on a standard desktop |
|---|---:|---|
| Supplementary Code 1 | 67 Top-state nuclei | 3 hours |
| Supplementary Code 2 | 268 chromosome-territory observations | Typically less than 1 minute |

The exact elapsed time depends on R version, installed package versions, processor performance, and whether the code is executed interactively or through document rendering.

---

## 10. Use with new data

To analyse a new experimental subset:

1. Prepare a chromosome-territory table containing the following fields:

   * `IdentificativoCellula`: unique identifier assigned to each cell or nucleus.
   * `Object_Name`: chromosome-territory identifier (for example, `Chr06` or `Chr12`).
   * `Pattern`: experimental-condition identifier used to select the subset of data to be analysed (for example, `F0.M0.0`).
   * `Omologo`: provisional homolog label assigned before energy-based classification, typically `A` or `B`.
   * `Replica`: biological or experimental replicate identifier.
   * `X_circ`: x-coordinate of the chromosome-territory centroid in the affine-normalized nuclear reference frame.
   * `Y_circ`: y-coordinate of the chromosome-territory centroid in the affine-normalized nuclear reference frame.

2. For Supplementary Code 2, the input dataset must additionally contain:

   * `Orientamento`: nuclear orientation or polarity-state label associated with the observation (for example, `Top`).
   * `Z_circ`: z-coordinate of the chromosome-territory centroid in the affine-normalized nuclear reference frame.
   * `Raggio_Circ`: radial distance of the chromosome-territory centroid from the nuclear centroid in the affine-normalized reference frame.
   * `Angolo_Circ`: in-plane polar angle of the chromosome-territory centroid in the affine-normalized reference frame.
   * `X_cart`: x-coordinate of the chromosome-territory centroid in the registered Cartesian nuclear reference frame before affine normalization.
   * `Y_cart`: y-coordinate of the chromosome-territory centroid in the registered Cartesian nuclear reference frame before affine normalization.
   * `Z_cart`: z-coordinate of the chromosome-territory centroid in the registered Cartesian nuclear reference frame before affine normalization.
   * `Raggio`: radial distance of the chromosome-territory centroid from the nuclear centroid in Cartesian coordinates.
   * `Angolo`: in-plane polar angle of the chromosome-territory centroid in Cartesian coordinates.
   * `Dist.Chr2Perim.Norm`: normalized distance between the chromosome-territory centroid and the nuclear perimeter, measured along the radial line from the nuclear centroid in the x–y plane.


3. In Supplementary Code 1, update the selected pattern, chromosome identifiers, and output filename as appropriate.
4. Run Supplementary Code 1 to generate `analysis_results`.
5. In Supplementary Code 2, use the same chromosome-territory input and the corresponding energy-classification output.
6. Confirm that `analysis_pattern`, `path_selection_chromosome`, and `energy_variable` are appropriate for the data being analysed.
7. Record any intentional display-oriented Alpha/Beta label calibration.

Supplementary Code 2 accepts either of the following energy-result conventions:

```r
# Current convention
energy_results$paths
energy_results$data

# Legacy convention
energy_results$lista
energy_results$dataframe
```

The code standardizes these internally before selecting the optimal path; no energy or label assignment is recalculated by this compatibility step.

---

## 11. Display-oriented Alpha/Beta label calibration

Supplementary Code 2 includes an explicit optional label-swap function for display-oriented calibration. In the supplied configuration, the `Alpha` and `Beta` labels are swapped for `Chr12` after density-level assignment.

This operation changes only the displayed values in `Omologo_Energetico`. It does not modify coordinates, path selection, matching energies, cumulative energies, density estimates, or density-level assignments. The same setting is used in the supplied reference post-classification output.

---

## 12. License, repository, and support

The custom code used for homolog classification and post-classification is provided as Supplementary Code 1 and Supplementary Code 2 accompanying this manuscript. The associated demonstration datasets are included to enable reviewers and readers to run the workflow and verify the expected intermediate and final outputs.

For questions concerning the code or data, contact:

```text
Paolo A. Netti
paolo.netti@iit.it
```
