Skip to content

Commit

Permalink
Merge pull request #1 from jkosciessa/dev-kosciessa
Browse files Browse the repository at this point in the history
Minor updates to the doc pages
  • Loading branch information
InesGP authored Jun 21, 2024
2 parents 750ed01 + cb90618 commit 714db40
Show file tree
Hide file tree
Showing 13 changed files with 974 additions and 56 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ share/python-wheels/
.installed.cfg
*.egg
MANIFEST
*.DS_STORE

# PyInstaller
# Usually these files are written by a python script from a template
Expand Down Expand Up @@ -119,6 +120,9 @@ venv.bak/

# mkdocs documentation
/site
/doc/_build/*
/doc/auto_examples/*
/doc/generated/*

# mypy
.mypy_cache/
Expand All @@ -127,3 +131,6 @@ dmypy.json

# Pyre type checker
.pyre/

# examples
/examples/*_data/*
4 changes: 2 additions & 2 deletions doc/API/datatypes.rst
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
Data Types
===================================

.. autoclass:: whobpyt.datatypes.Recording
.. autoclass:: whobpyt.datatypes.Timeseries
:members:
:undoc-members:
:special-members: __init__

.. autoclass:: whobpyt.datatypes.par
.. autoclass:: whobpyt.datatypes.Parameter
:members:
:undoc-members:
:special-members: __init__
Expand Down
23 changes: 4 additions & 19 deletions doc/API/models.rst
Original file line number Diff line number Diff line change
@@ -1,27 +1,12 @@
Models
===================================

.. autoclass:: whobpyt.models.JansenRit.RNNJANSEN
:members: info, createIC, createDelayIC, setModelParameters, forward
.. autoclass:: whobpyt.models.jansen_rit.JansenRitParams
:members: info, createIC, createDelayIC, setModelSCParameters, forward
:undoc-members:
:special-members: __init__

.. autoclass:: whobpyt.models.RWW.RNNRWW
:members: info, createIC, setModelParameters, forward
:undoc-members:
:special-members: __init__

.. autoclass:: whobpyt.models.RWWEI2.RWWEI2
:members: info, createIC, setModelParameters, forward
:undoc-members:
:special-members: __init__

.. autoclass:: whobpyt.models.BOLD.BOLD_Layer
:members: info, createIC, setModelParameters, forward
:undoc-members:
:special-members: __init__

.. autoclass:: whobpyt.models.EEG.EEG_Layer
:members: info, createIC, setModelParameters, forward
.. autoclass:: whobpyt.models.wong_wang.ReducedWongWangModel
:members: info, createIC, createDelayIC, setModelSCParameters, forward
:undoc-members:
:special-members: __init__
2 changes: 0 additions & 2 deletions doc/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
#SPHINXPROJ = fooof
SPHINXPROJ = whobpyt
SOURCEDIR = .
BUILDDIR = _build
Expand Down Expand Up @@ -50,7 +49,6 @@ install:
# --no-checkout just fetches the root folder without content
# --depth 1 is a speed optimization since we don't need the history prior to the last commit
# -b gh-pages fetches only the branch for the gh-pages
#git clone -b gh-pages --single-branch --no-checkout --depth 1 https://github.com/fooof-tools/fooof _build/gh_pages
git clone -b gh-pages --single-branch --no-checkout --depth 1 [email protected]:griffithslab/whobpyt _build/gh_pages
# A .nojekyll file tells Github pages to bypass Jekyll processing
touch _build/gh_pages/.nojekyll
Expand Down
6 changes: 0 additions & 6 deletions doc/usage.rst

This file was deleted.

177 changes: 177 additions & 0 deletions examples/eg__RWW_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""
==================================
Fitting Wong_Wang model (HCP data)
==================================
"""

# sphinx_gallery_thumbnail_number = 1

# %%
# Importage
# ---------
#

# os stuff
import os
import sys
sys.path.append('..')

# whobpyt stuff
import whobpyt
from whobpyt.datatypes import Parameter, Timeseries
from whobpyt.models.wong_wang import ReducedWongWangModel, ReducedWongWangParams
from whobpyt.optimization.custom_cost_RWW import CostsRWW
from whobpyt.run import ModelFitting
from whobpyt.datasets import fetch_hcpl2k8

# array and pd stuff
import numpy as np
import pandas as pd

# viz stuff
import matplotlib.pyplot as plt

# gdown
import gdown

# %%
# define destination path and download the data


"""
des_dir = '../'
if not os.path.exists(des_dir):
os.makedirs(des_dir) # create folder if it does not exist
url = "https://drive.google.com/drive/folders/18smy3ElTd4VksoL4Z15dhwT5l3yjk6xS"
os.chdir(des_dir)
gdown.download_folder(url, remaining_ok = True)
"""

# Go to examples folder
#os.chdir('examples')


# Download the data for this example to default location ~/.whobpyt/data
data_dir = fetch_hcpl2k8()

base_dir = os.path.join(data_dir, 'HCP')

# %%
#get subject list
#base_dir = '../HCP/'

#subs =sorted([sc_file[-10:-4] for sc_file in os.listdir(base_dir) if sc_file[:8] == 'weights_'])

sub = '100307'

# %%
# define options for wong-wang model
node_size = 83
mask = np.tril_indices(node_size, -1)
num_epochs = 5
TPperWindow = 20
step_size = 0.05
input_size = 2
tr = 0.75
repeat_size = 5

# %%
# load raw data and get SC empirical BOLD and FC
sc_file = os.path.join(base_dir, 'weights_' + sub + '.txt')
ts_file = os.path.join(base_dir, sub + '_rfMRI_REST1_LR_hpc200_clean__l2k8_sc33_ts.pkl') # out_dir+'sub_'+sub+'simBOLD_idt.txt'

sc = np.loadtxt(sc_file)
SC = (sc + sc.T) * 0.5
sc = np.log1p(SC) / np.linalg.norm(np.log1p(SC))

ts_pd = pd.read_pickle(ts_file)
ts = ts_pd.values
ts = ts / np.max(ts)
fc_emp = np.corrcoef(ts.T)

# %%
# prepare data structure for model
print(ts.T.shape)
fMRIstep = tr
data_mean = Timeseries(ts.T, fMRIstep)

# %%
# get model parameters structure and define the fitted parameters by setting non-zero variance for the model
params = ReducedWongWangParams(g=Parameter(400, 400, 1/np.sqrt(10), True), g_EE=Parameter(1.5, 1.5, 1/np.sqrt(50), True), \
g_EI =Parameter(0.8, 0.8, 1/np.sqrt(50), True), \
g_IE=Parameter(0.6, 0.6, 1/np.sqrt(50), True), I_0 =Parameter(0.2), \
std_in=Parameter(np.log(0.1), np.log(0.1), 0.1, True, True, lb =0.02))

# %%
# call model want to fit
model = ReducedWongWangModel(params, node_size =node_size, TRs_per_window =TPperWindow, step_size=step_size, tr=tr, sc=sc, use_fit_gains=True)

# %%
# create objective function
ObjFun = CostsRWW(model)

# %%
# call model fit
F = ModelFitting(model, ObjFun)


# %%
# Model Training
# ---------------------------------------------------
#
F.train(u = 0, empRecs = [data_mean], num_epochs = num_epochs, TPperWindow = TPperWindow, learningrate = 0.05)

# %%
# Plots of loss over Training
plt.plot(np.arange(1,len(F.trainingStats.loss)+1), F.trainingStats.loss)
plt.title("Total Loss over Training Epochs")

# %%
# Plots of parameters values over Training
plt.plot(F.trainingStats.fit_params['g_EE'], label = "g_EE")
plt.plot(F.trainingStats.fit_params['g_EI'], label = "g_EI")
plt.plot(F.trainingStats.fit_params['g_IE'], label = "g_IE")
plt.legend()
plt.title("Local Coupling Variables Changing Over Training Epochs")

# %%
# Model Evaluation (with 20 window for warmup)
# ---------------------------------------------------
#
F.evaluate(u = 0, empRec = data_mean, TPperWindow = TPperWindow, base_window_num = 20)

# %%
# Plot SC and fitted SC

fig, ax = plt.subplots(1, 2, figsize=(5, 4))
im0 = ax[0].imshow(sc, cmap='bwr', vmin = 0.0, vmax = 0.05)
ax[0].set_title('The empirical SC')
fig.colorbar(im0, ax=ax[0], fraction=0.046, pad=0.04)
im1 = ax[1].imshow(F.model.sc_fitted.detach().numpy(), cmap='bwr', vmin = 0.0, vmax = 0.05)
ax[1].set_title('The fitted SC')
fig.colorbar(im1, ax=ax[1], fraction=0.046, pad=0.04)
plt.show()

# %%
# Plot E I and simulated BOLD
fig, ax = plt.subplots(1, 3, figsize=(12, 8))
ax[0].plot(F.lastRec['E'].npTS().T)
ax[0].set_title('Test: E')
ax[1].plot(F.lastRec['I'].npTS().T)
ax[1].set_title('Test: I')
ax[2].plot(F.lastRec['bold'].npTS().T)
ax[2].set_title('Test: BOLD')
plt.show()

# %%
# Plot the FC and the test FC
fig, ax = plt.subplots(1, 2, figsize=(5, 4))
im0 = ax[0].imshow(fc_emp, cmap='bwr')
ax[0].set_title('The empirical FC')
fig.colorbar(im0, ax=ax[0], fraction=0.046, pad=0.04)
im1 = ax[1].imshow(np.corrcoef(F.lastRec['bold'].npTS()), cmap='bwr')
ax[1].set_title('The simulated FC')
fig.colorbar(im1, ax=ax[1], fraction=0.046, pad=0.04)
plt.show()
38 changes: 19 additions & 19 deletions examples/eg__replicate_Momi2023.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
output_size = eeg_data.shape[0]
batch_size = 20
step_size = 0.0001
num_epochs = 20 #2 # num_epochs = 20
num_epochs = 2 # num_epochs = 20
tr = 0.001
state_size = 6
base_batch_num = 20
Expand All @@ -131,35 +131,35 @@
# get model parameters structure and define the fitted parameters by setting non-zero variance for the model
lm = np.zeros((output_size,200))
lm_v = np.zeros((output_size,200))
params = JansenRitParams(A = par(3.25),
a= par(100,100, 2, True),
B = par(22),
params = JansenRitParams(A=par(3.25),
a=par(100,100, 2, True),
B=par(22),
b = par(50, 50, 1, True),
g=par(500,500,2, True),
g_f=par(10,10,1, True),
g_b=par(10,10,1, True),
g = par(500,500,2, True),
g_f = par(10,10,1, True),
g_b = par(10,10,1, True),
c1 = par(135, 135, 1, True),
c2 = par(135*0.8, 135*0.8, 1, True),
c3 = par(135*0.25, 135*0.25, 1, True),
c4 = par(135*0.25, 135*0.25, 1, True),
std_in= par(np.log(10), np.log(10), .1, True, True),
vmax= par(5),
v0=par(6),
r=par(0.56),
y0=par(-2, -2, 1/4, True),
std_in = par(np.log(10), np.log(10), .1, True, True),
vmax = par(5),
v0 = par(6),
r = par(0.56),
y0 = par(-2, -2, 1/4, True),
mu = par(np.log(1.5),
np.log(1.5), .1, True, True, lb=0.1),
k =par(5., 5., 0.2, True, lb=1),
k0=par(0),
k = par(5., 5., 0.2, True, lb=1),
k0 = par(0),
cy0 = par(50, 50, 1, True),
ki=par(ki0),
lm=par(lm, lm, 1 * np.ones((output_size, node_size))+lm_v, True)
ki = par(ki0),
lm = par(lm, lm, 1 * np.ones((output_size, node_size))+lm_v, True)
)


# %%
# call model want to fit
model = JansenRitModel(params,
model = JansenRitModel(params,
node_size=node_size,
TRs_per_window=batch_size,
step_size=step_size,
Expand All @@ -169,7 +169,7 @@
lm=lm,
dist=dist,
use_fit_gains=True,
use_fit_lfm = False)
use_fit_lfm=False)



Expand All @@ -195,7 +195,7 @@
# %%
# load in a previously completed model fitting results object
full_run_fname = os.path.join(data_dir, 'Subject_1_low_voltage_fittingresults_stim_exp.pkl')
F = pickle.load(open(full_run_fname, 'rb'))
#F = pickle.load(open(full_run_fname, 'rb'))
F.evaluate(u = u, empRec = data_mean, TPperWindow = batch_size, base_window_num = 20)


Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ mne
# Docs requirements
sphinx
#sphinx==3.1.1
sphinx-gallery==0.8.1
sphinx_gallery==0.8.1
sphinx_rtd_theme #==0.5.0
sphinx-tabs==1.3.0
sphinx-copybutton==0.3.1
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.9',
python_requires='>=3.8',
)

4 changes: 2 additions & 2 deletions whobpyt/models/jansen_rit/jansen_rit.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class JansenRitModel(AbstractNeuralModel):
createDelayIC(self, ver):
Creates the initial conditions for the delays.
setModelParameters(self):
setModelSCParameters(self):
Sets the parameters of the model.
forward(input, noise_out, hx)
Expand Down Expand Up @@ -244,7 +244,7 @@ def __init__(self,
self.params = params
self.output_size = lm.shape[0] # number of EEG channels

self.setModelParameters()
self.setModelParameters() # defined in datatypes/abstract_neural_model.py
self.setModelSCParameters()


Expand Down
1 change: 1 addition & 0 deletions whobpyt/models/wong_wang/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .wong_wang import ReducedWongWangModel, ReducedWongWangParams
Loading

0 comments on commit 714db40

Please sign in to comment.