# Stata in JupyterLab

[Stata](https://www.stata.com/) is a powerful statistics package for data science. Stata commands and functionality can be accessed on the DNAnexus Platform via [stata\_kernel](https://kylebarron.dev/stata_kernel/), in Jupyter notebooks.

## Before You Begin

### Project License Requirement

On the DNAnexus Platform, use the [JupyterLab app](https://documentation.dnanexus.com/user/jupyter-notebooks) to create and edit Jupyter notebooks.

{% hint style="info" %}
You can only run this app within a project that's billed to an account with a license that allows the use of both [JupyterLab](https://documentation.dnanexus.com/user/jupyter-notebooks) and [HTTPS apps](https://documentation.dnanexus.com/developer/apps/https-applications). [Contact DNAnexus Sales](mailto:sales@dnanexus.com) if you need to upgrade your license.

JupyterLab is accessible to all users of the UK Biobank Research Analysis Platform and the Our Future Health Trusted Research Environment. A license is required to access JupyterLab on the DNAnexus Platform. [Contact DNAnexus Sales](mailto:sales@dnanexus.com) for more information.
{% endhint %}

### Stata License Requirement

To use Stata on the DNAnexus Platform, you need a valid Stata license. Before launching Stata in a project, you must save your license details according to the instructions below in a plain text file with the extension `.json`, then upload this file to the project's root directory. You only need to do this once per project.

#### Creating a Stata License Details File

Start by creating the file in a text editor, including all the fields shown here, where `<user>` is your DNAnexus username, and`<organization>`is the org of which you're a member:

```json
{
  "license": {
    "serialNumber": "<Serial number from Stata>",
    "code": "<Code from Stata>",
    "authorization": "<Authorization from Stata>",
    "user": "<Registered user line 1>",
    "organization": "<Registered user line 2>"
  }
}
```

Save the file according to the following format, where `<username>` is your DNAnexus username: `.stataSettings.user-<username>.json`

{% hint style="info" %}
Some operating systems may not support the naming of files with a "." as the first character. If this is the case, you can rename the `.json` file after uploading it to your project by hovering over the name of your file and clicking the pencil icon that appears.
{% endhint %}

#### Uploading the Stata License Details File

Open the project in which you want to use Stata. Upload the Stata license details file to the project's root directory by going to your project's **Manage** tab, clicking on the **Add** button on the upper right, and then selecting the **Upload data** option.

#### Secure Indirect Format Option for Shared Projects

When working in a shared project, you can take an additional step to avoid exposing your Stata license details to project collaborators.

Create a private project. Then create and save a Stata license details file in that project's root directory, per the instructions above.

Within the shared project, create and save a Stata license details file in this format, where `project-yyyy` is the name of the private project, and `file-xxxx` is the license details file ID, in that private project:

```json
{
  "licenseFile": {
    "$dnanexus_link": {
      "id": "file-xxxx",
      "project": "project-yyyy"
    }
  }
}
```

{% hint style="info" %}
When working on the Research Analysis Platform, you can only create a private credentials project from the [Research Analysis Platform Projects page](https://ukbiobank.dnanexus.com/panx/projects).
{% endhint %}

## Launching JupyterLab

1. Open the project in which you want to use Stata. From within the project's **Manage** tab, click the **Start Analysis** button.
2. Select the app **JupyterLab with Python, R, Stata, ML, Image Processing**.
3. Click the **Run Selected** button. If you haven't run this app before, you are prompted to install it. Next, you are taken to the **Run Analysis** screen.
4. On the **Run Analysis** screen, open the **Analysis Inputs** tab and click the **Stata settings file** button.
5. Add your Stata settings file as an input. This is the `.json` file you created, containing your Stata license details.
6. In the **Common** section at the bottom of the **Analysis Inputs** pane, open the **Feature** dropdown menu and select **Stata.**
7. Click the **Start Analysis** button at the top right corner of the screen. This launches the JupyterLab app, and takes you to the project's **Monitor** tab, where you can monitor the app's status as it loads.

{% hint style="info" %}
The app can take some time to load and start running.
{% endhint %}

Once the analysis starts, you see the notification "Running" appear under the name of the app.

## Opening JupyterLab

Click the **Monitor** tab heading. This opens a list of running and past jobs. Jobs are shown in reverse chronological order, with the most recently launched at the top. The topmost row should show the job you launched. To open the job and enter the JupyterLab interface, click on the URL shown under **Worker URL**.

![](https://1612471957-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_EsL_ie8XyZlLe_yf9%2Fuploads%2Fgit-blob-a1634d37549b8f67159fd64c29fb658610625f99%2Fjupyterlab_worker_url.png?alt=media)

{% hint style="info" %}
If you do not see the worker URL, click on the name of the job in the Monitor page.
{% endhint %}

## Using Stata Within JupyterLab

Within the JupyterLab interface, open the **DNAnexus** tab shown at the left edge of the screen.

![The location of the DNAnexus tab within the JupyterLab interface.](https://1612471957-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_EsL_ie8XyZlLe_yf9%2Fuploads%2Fgit-blob-3a83ea90e0993d8e0067fd2da0d6a226dbd882d4%2FScreen%20Shot%202021-06-14%20at%206.58.53%20PM.png?alt=media)

Open a new Stata notebook by clicking the **Stata** tile in the **Notebooks** section.

### Working with Project Files

You can download DNAnexus data files to the JupyterLab container from Stata notebook with:

```shell
!dx download project-xxxx:file-yyy
```

Data files in the current project can also be accessed using a `/mnt/project` folder from a Stata notebook as follows: To load a DTA file:

```shell
use /mnt/project/<path>/data_in.dta
```

To load a CSV file:

```shell
import delimited /mnt/project/<path>/data_in.csv
```

To write a DTA file to the JupyterLab container:

```shell
save data_out
```

To write a CSV file to the JupyterLab container:

```shell
export delimited data_out.csv
```

To upload a data file from the JupyterLab container to the project, use the following command in a Stata notebook:

```shell
!dx upload <file> --destination=<destination>
```

Alternatively, open a new Launcher tab, open Terminal, and run:

```shell
dx upload <file> --destination=<destination>
```

The `/mnt/project` directory is read-only, so trying to write to it results in an error.

### Creating a Stata Dataset with Spark

[JupyterLab Spark Cluster app](https://documentation.dnanexus.com/user/jupyter-notebooks/dxjupyterlab-spark-cluster) can be used to query and filter DNAnexus [datasets](https://documentation.dnanexus.com/developer/datasets) returning a PySpark DataFrame. PySpark Dataframe can be converted to a pandas DataFrame with:

```python
pandas_df = spark_df.toPandas()
```

Pandas dataframe can be exported to CSV or Stata DTA files in the JupyterLab container with:

```python
pandas_df.to_stata("data_out.dta")
pandas_df.to_csv("data_out.csv")
```

To upload a data file from the JupyterLab container to the DNAnexus project in the JupyterLab Spark Cluster app, use

```shell
%%bash
dx upload <file>
```

Once saved to the project, data files can be used in a JupyterLab Stata session using the instructions above.
