Repository navigation
Server side as a big data modelling application
The server side of the project is different in nature and function from the client side. Most of its code makes no reference of websites, online servers or User Interfaces, but instead focuses on normative modelling, large scale computation and sharing results.
The function of the PCNportal server side is to (pre)process the input data of a user and return the results to them in the shape of a link to a downloadable .zip file. Most of the server side code is stored in the project drive on the DCCN servers, except for the virtual environment that is stored in the Anaconda directory.
When the client side calls for a computation request, the server side performs the following steps sequentially (each step has its own code):
- First, it preprocesses user data to make it suitable for PCNtoolkit and its models.
- Then, it splits up the user input data into smaller chunks, and submits one modelling job per chunk of data to the cluster (i.e. parallelized computing).
- Per job, it transfers the corresponding normative model to the chunk of data, and computes z-scores and model error measures.
- Lastly, upon successful completion of all parallelized computation tasks, these results per job are combined back to one set of results. They're then shared to a public server, with a download link being sent to the user.
Below, a longer description is provided for each step along with a short walkthrough, but first I'll explain how the connection between client side and server side is made.
Before we can work on the server side, we need to do two things: upload the user data to the server, and kickstart the modelling process.
The Upload button on the website actually uploads the user data to within the walls of the Docker container, but we need it to be stored on the DCCN server itself. Our SSH connection with the server can act as an information highway to upload the data from the container to the DCCN. We use the SCP (SSH-based secure copy protocol?) to accomplish this data transfer. We store the user's data in a unique directory with a session ID (for example: "c4b141f369964ac28e467d14382cebe1". Importantly, all modelling and processing will be done in this unique directory.
Now we need to execute some type of script to run on the data. We use a bash script to load Anaconda, start our virtual environment with PCNtoolkit and run the Python scripts.
When a computation request is sent, the client side will send a command to the server to execute the bash script just like you would run any other bash script:
# A simple SSH command to run a script on the DCCN and feed lots of arguments to the server side.
ssh -o "StrictHostKeyChecking=no" {user} /path/to/execute_remote.sh {projectdir} {model_selection} {data_type} {session_id} {email_address}
We have now everything we need from the client side to begin the server side modelling.
First, we need to process the user data and modeling parameters in the right format for normative modelling. transfer_normative_modelling_online.py was written to preprocess the data for any algorithm and create make the analysis ready for parallel modelling. To understand the global steps of this script, follow Saige's tutorial on normative modelling with BLR and HBR. Our script combines the functionality of these two scripts, among other things, to allow both BLR and HBR modelling through the website.
If you have succesfully completed these tutorials transfer_normative_modelling_online.py should now look somewhat familiar, although it has some added functionalities.
For example, our script does not take in static hard-coded input for data and modelling choices, but gets these from the user. If you remember, the client side has provided this information through the executed bash script. All we have to do is read them in:
root_dir = "/path/to/project_directory/"
model_name= sys.argv[2]
data_type = sys.argv[3]
session_id = sys.argv[4]
email_address = sys.argv[6]
Secondly, this script dynamically loads the appropriate covariates, names of training data collection sites, modelling parameters and IDP names, depending on what model was chosen by the user. That is possible because all model directories are structured in the same way with the same meta data file names. The rest of the script looks pretty similar to the tutorials, except that we want to use parallelization.
We want to start parallelization (the next step) in an automated way, but that brings along some challenges. This means that a process is tracking whether the computation jobs are done or not, and that is necessary for the website to run automatically. First, it sets up the model parameters, adapted from existing transfer procedures from Mosi, and starts the normative_parallel script - the next step. Within the current script, all we have to do is call the right PCNtoolkit script and load in the (many) necessary parameters:
ptk.normative_parallel.execute_nm(session_path, python_path,
'Transfer_' + job_name, cov_file_ad, resp_file_ad, batch_size, memory, duration, func='transfer',
alg=alg, binary=True, trbefile=sitenum_file_ad,
model_type=method, random_intercept=random_intercept,
random_slope=random_slope, random_noise=random_noise,
hetero_noise=hetero_noise, savemodel='True', outputsuffix=outputsuffix,
inputsuffix=inputsuffix,
n_samples='1000', inscaler=inscaler, outscaler=outscaler,
testcovfile_path=cov_file_te, testrespfile_path=resp_file_te,
tsbefile = sitenum_file_te, output_path=output_path,
model_path=model_path, log_path=log_dir,count_jobsdone=count_jobsdone)
However, the script is not done.
The jobs all end at different moments. So, how do we know when all jobs are done, and how do we run a script to collect results based on that? What do we do if some jobs fail, but others succeed? We cannot manually do either of these steps, so this Python script has automated those procedures. First, we need to measure when a job is done. There are many ways to do this, but we ask every modelling job to create a dummy text file after it has saved the results, and this dummy file has the extension '.jobsdone'. Indeed, you'll find that all successfully completed sessions have a /logs/ directory with one such file per job. Then, transfer_normative_modelling_online.py should keep checking whether all jobs are successfully completed yet (when there are enough .jobsdone files). Our waiting loop await_jobs() checks if all batches have a .jobsdone file yet every n seconds. Every now and then it reruns any failed jobs and checks again.
Knowing that, you can see the logic of our waiter loop:
complete = False
while complete == False:
# Check for twenty minutes if all jobs are completed.
await_jobs(session_path, log_dir)
# Collect and combine the results from all separate batches.
# The script returns false if jobs failed.
complete = ptk.normative_parallel.collect_nm(session_path, 'Transfer_' + job_name,
func='transfer', collect=True, binary=True,
batch_size=batch_size, outputsuffix=outputsuffix)
if complete == True:
break
# Else: rerun until completed.
print("Start rerunning...")
ptk.normative_parallel.rerun_nm(session_path, log_dir, memory, duration, binary=True)
At the bottom of the file, you'll see that when all jobs are successfully completed and the above loop ends, a new script is started to send the results to the user.
The next step handles parallelization for us, and is part of PCNtoolkit. Basically, it splits up the user data into a given number of smaller batches and uses the user modelling preferences to create a separate bash script that creates one modelling job. Then, it submits the jobs to the cluster. As a result, each chunk of data is modelled with corresponding models and the same parameters. The bash script is basically a reformatted version of the ptk.normative_parallel.execute_nm function call above, except that it now calls normative.transfer to start the modelling. After this is executed, you can check 'qstat' on the service account to find the jobs have succeeded.
Now, PCNtoolkit normative modelling is used to facilitate transfer learning with the pre-trained model on the user data. From here on out, all computational work is also handled by PCNtoolkit. It's a sophisticated package that does not need to be understood in-depth to use it, and for more documentation and tutorials we refer to the readthedocs. However, pcntoolkit.normative.py has been adapted slightly for our purpose and it is necessary to explain why for future development.
Transfer learning is not strictly possible yet for Bayesian Linear Regression. Instead, a highly naive version is available that only translates the function to the mean of the transfer data. Nevertheless, we wanted the syntax to be consistent with other algorithms, with the aim of implementing BLR transfer in the future. Therefore, normative.transfer now has a condition that starts this naive transfer function when Bayesian Linear Regression has been chosen.
On another note, normative.transfer also creates the aforementioned .jobsdone dummy files when website mode is activated (through a simple boolean value). When a .jobsdone file is created for every file, we can assume the results are ready to be shared. How? Keep reading.
When all normative modelling jobs of a session are done, the results per batch are merged together to a single file again. We want to send these results to the user, but the files can be too large to be an email attachment. Therefore, we need to put them somewhere where users can download them. Donders gives us access to a public server with a large data storage capacity: SURFdrive. The results will be openly available, but these measurements are anonymized and do not carry information interesting to anyone but the user. Now, we need to provide the user instructions to download the results. We use an automated Gmail server to send them an email that contains a link to their SURFdrive results. Here, they can download them in the click of a button.
Both the Gmail and SURFdrive require an account that of course needs authentication. The SURFdrive account is coupled with the university account, and the Gmail with the PCNportal Google account. The scripts provided use safely stored details to login, and their respective APIs to upload and share the results. These scripts can be changed to share different results, use different accounts or change the email text.
The user's session directory contains information for debugging. If the session directory does not contain any user data, the SSH connection was never made and the data was not copied to the server. If the session directory does not contain any batches, then the backend likely failed to preprocess the data or, less likely, to submit the jobs. If there is no results.zip file, then the results were not properly collected and the waiter loop may still be running (check qstat to see if the jobs are running). If there is no email or download link, there are issues with the API (login).
These are the active server side scripts:
/project_cephfs/3022051.01/scripts/server
|-- config.py ---- contains login information for SURFdrive and Gmail.
|-- execute_modelling.sh ---- activates virtual environment and main Python script.
|-- transfer_normative_models_online.py ---- the main Python script to prepare parallelized normative modelling.
|-- list_subdirs.py ---- this script lists available models and data types (called by app.py).
|-- package_and_send_surfdrive.py ---- collects, zips results, uploads to SURFdrive and sends email.
However, we also need to store data, models and meta-data, so the project drive contains more files than just scripts:
|-- __pycache__ ---- some cached files for modelling
|-- docs ---- documents used for testing
| `-- fmri_data
|-- models ---- all available models
| |-- SurfArea ---- this level of subdirectory denotes the data types
| | `-- BLR_lifespan_40K_66sites ---- within each data type are the pre-trained models
| | `-- Models
| |-- ThickAvg
| | |-- BLR_lifespan_57K_82sites
| | | `-- Models
| | `-- HBR_lifespan_36K_79sites
| | `-- Models
| `-- fMRI
| `-- BLR_yeonetworks_22K_45sites
| `-- Models
|-- scripts ---- these are the tested scripts used in deployment (has already been tested)
| |-- client
| `-- server
|-- sessions ---- this is the processing directory and contains the user data and results
| |-- session_{session_ID} ---- example directory structure
| | |-- Models
| | |-- Transfer
| | |-- batch_1 ---- per batch, a model is transferred.
| | | `-- Models
| | |-- batch_2
| | | `-- Models
| | |-- batch_3
| | | `-- Models
| | |-- batch_4
| | | `-- Models
| | `-- log ---- the error files from parallel processing
|-- test_scripts ---- the scripts used for testing the local website
| |-- client
| `-- server
|-- training_hbr_models ---- directory sometimes used for training/testing normative models