Interract with TVB REST server using the TVBClient API

TVB REST server is part of tvb-framework release. If you want to run this example you will have to start a REST server or you should have access to a public TVB REST server.

In [1]:
import os
import time

from keycloak import KeycloakOpenID
from tvb.adapters.datatypes.db.connectivity import ConnectivityIndex
from tvb.adapters.simulator.simulator_adapter import SimulatorAdapterModel
from tvb.core.entities.model.model_operation import STATUS_ERROR, STATUS_CANCELED, STATUS_FINISHED
from tvb.interfaces.rest.client.tvb_client import TVBClient
In [2]:
tvb_client = TVBClient("http://192.168.123.93:9090")

keycloak_instance = KeycloakOpenID("https://keycloak.codemart.ro/auth/", "TVB", "tvb-tests")

tvb_client._update_token(keycloak_instance.token("tvb_user", "pass"))
In [3]:
def monitor_operation(tvb_client, operation_gid):
    while True:
        status = tvb_client.get_operation_status(operation_gid)
        if status in [STATUS_FINISHED, STATUS_CANCELED, STATUS_ERROR]:
            break
        print("Current operation GID {} => STATUS {}".format(operation_gid, status))
        time.sleep(5)
    print("Operation {} has finished with status: {}".format(operation_gid, status))
In [4]:
# Requesting projects for the logged user
projects_of_user = tvb_client.get_project_list()
default_project = projects_of_user[0]
default_project_gid = default_project.gid
default_project.name
Out[4]:
'Default_Project'
In [5]:
# Requesting datatypes for the default project
data_in_project = tvb_client.get_data_in_project(default_project_gid)
connectivity_gid = None
datatypes_type = []
for datatype in data_in_project:
    datatypes_type.append(datatype.type)
    if datatype.type == ConnectivityIndex().display_type:
        connectivity_gid = datatype.gid

datatypes_type
Out[5]:
['Connectivity',
 'Surface',
 'Surface',
 'Surface',
 'Surface',
 'Surface',
 'Surface',
 'Sensors',
 'Sensors',
 'Sensors',
 'ConnectivityAnnotations',
 'RegionMapping',
 'ProjectionMatrix',
 'ProjectionMatrix',
 'ProjectionMatrix',
 'LocalConnectivity']
In [6]:
# Preparing the simulator
simulator = SimulatorAdapterModel()
simulator.connectivity = connectivity_gid
simulator.simulation_length = 100

# Starting the simulation
operation_gid = tvb_client.fire_simulation(default_project_gid, simulator)

# Monitoring the simulation operation
monitor_operation(tvb_client, operation_gid)
Current operation GID 6b9552dc-7b21-11ea-87ba-1860247fb747 => STATUS 4-PENDING
Current operation GID 6b9552dc-7b21-11ea-87ba-1860247fb747 => STATUS 4-PENDING
Current operation GID 6b9552dc-7b21-11ea-87ba-1860247fb747 => STATUS 3-STARTED
Operation 6b9552dc-7b21-11ea-87ba-1860247fb747 has finished with status: 5-FINISHED
In [7]:
# Requesting the results of the simulation
simulation_results = tvb_client.get_operation_results(operation_gid)
datatype_names = []
for datatype in simulation_results:
    datatype_names.append(datatype.name)
    
datatype_names
Out[7]:
['SimulationHistory', 'TimeSeriesRegion']
In [8]:
# Download the resulted time series file

time_series_gid = simulation_results[1].gid
time_series_path = tvb_client.retrieve_datatype(time_series_gid, os.getcwd())

time_series_path
Out[8]:
'/home/tvb_user/tvb-root/tvb_documentation/demos/TimeSeriesRegion_d13567caa859479ba61597e106c97b30.h5'
In [9]:
from tvb.adapters.datatypes.h5.time_series_h5 import TimeSeriesH5

# Loading a chuck from the time series H5 file, as this can be very large
with TimeSeriesH5(time_series_path) as time_series_h5:
    data_shape = time_series_h5.read_data_shape()
    chunk = time_series_h5.read_data_slice(tuple([slice(20), slice(data_shape[1]), slice(data_shape[2]), slice(data_shape[3])]))

assert chunk.shape[0] == 20
assert chunk.shape[1] == data_shape[1]
assert chunk.shape[2] == data_shape[2]
assert chunk.shape[3] == data_shape[3]
In [10]:
# Requesting algorithms to run on time series
algos = tvb_client.get_operations_for_datatype(time_series_gid)
algos_pp = [(algo.module+'.'+algo.classname) for algo in algos]

algos_pp
Out[10]:
['tvb.adapters.analyzers.cross_correlation_adapter.CrossCorrelateAdapter',
 'tvb.adapters.analyzers.cross_correlation_adapter.PearsonCorrelationCoefficientAdapter',
 'tvb.adapters.analyzers.fcd_adapter.FunctionalConnectivityDynamicsAdapter',
 'tvb.adapters.analyzers.fmri_balloon_adapter.BalloonModelAdapter',
 'tvb.adapters.analyzers.fourier_adapter.FourierAdapter',
 'tvb.adapters.analyzers.ica_adapter.ICAAdapter',
 'tvb.adapters.analyzers.metrics_group_timeseries.TimeseriesMetricsAdapter',
 'tvb.adapters.analyzers.node_coherence_adapter.NodeCoherenceAdapter',
 'tvb.adapters.analyzers.node_complex_coherence_adapter.NodeComplexCoherenceAdapter',
 'tvb.adapters.analyzers.node_covariance_adapter.NodeCovarianceAdapter',
 'tvb.adapters.analyzers.pca_adapter.PCAAdapter',
 'tvb.adapters.analyzers.wavelet_adapter.ContinuousWaveletTransformAdapter',
 'tvb.adapters.visualizers.brain.BrainViewer',
 'tvb.adapters.visualizers.brain.DualBrainViewer',
 'tvb.adapters.visualizers.eeg_monitor.EegMonitor',
 'tvb.adapters.visualizers.time_series.TimeSeriesDisplay']
In [11]:
from tvb.adapters.analyzers.fourier_adapter import FFTAdapterModel, FourierAdapter

# Prepare Fourier model
fourier_model = FFTAdapterModel()
fourier_model.time_series = time_series_gid
fourier_model.window_function = 'hamming'

# Launch Fourier Analyzer
operation_gid = tvb_client.launch_operation(default_project_gid, FourierAdapter, fourier_model)

operation_gid
Out[11]:
'750ec3da-7b21-11ea-a7ec-1860247fb747'
In [12]:
# Download the connectivity file
connectivity_path = tvb_client.retrieve_datatype(connectivity_gid, os.getcwd())
print("Connectivity path: {}".format(connectivity_path))

# Loading an entire Connectivity datatype in memory
connectivity = tvb_client.load_datatype_from_file(connectivity_path)
connectivity.summary_info()
Connectivity path: /home/tvb_user/tvb-root/tvb_documentation/demos/Connectivity_6b28b6c61836452bb52cbd18538a7775.h5
Out[12]:
{'Number of regions': 76,
 'Number of connections': 1560,
 'Undirected': False,
 'areas shape': '(76,)',
 'areas dtype': 'float64',
 'areas [min, median, max]': '[0, 2580.89, 10338.2]',
 'weights shape': '(76, 76)',
 'weights dtype': 'float64',
 'weights [min, median, max]': '[0, 0, 3]',
 'weights-non-zero [min, median, max]': '[0.00462632, 2, 3]',
 'tract_lengths [min, median, max]': '[0, 71.6635, 153.486]',
 'tract_lengths-non-zero [min, median, max]': '[4.93328, 74.0646, 153.486]',
 'tract_lengths (connections) [min, median, max]': '[0, 55.8574, 138.454]'}