markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Adding Datasets
b.add_dataset('mesh', compute_times=[0], dataset='mesh01') b.add_dataset('orb', compute_times=np.linspace(0,1,201), dataset='orb01') b.add_dataset('lc', times=np.linspace(0,1,21), dataset='lc01') b.add_dataset('rv', times=np.linspace(0,1,21), dataset='rv01')
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Synthetics To ensure compatibility with computing synthetics in detached and semi-detached systems in Phoebe, the synthetic meshes for our overcontact system are attached to each component separetely, instead of the contact envelope.
print(b['mesh01@model'].components)
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Plotting Meshes
afig, mplfig = b['mesh01@model'].plot(x='ws', show=True)
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Orbits
afig, mplfig = b['orb01@model'].plot(x='ws',show=True)
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Light Curves
afig, mplfig = b['lc01@model'].plot(show=True)
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
RVs
afig, mplfig = b['rv01@model'].plot(show=True)
development/examples/minimal_contact_binary.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
LMFIT package: https://lmfit.github.io/lmfit-py/index.html Example :
import numpy as np import matplotlib.pyplot as plt %matplotlib inline x= np.array([0.,1.,2.,3.]) data = np.array([1.3,1.8,5.,10.7])
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Lets visualize how a quadratic curve fits to it:
plt.scatter(x,data) xarray=np.arange(-1,4,0.1) plt.plot(xarray, xarray**2,'r-') # Not the best fit plt.plot(xarray, xarray**2+1,'g-')
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Lets build a general quadratic model:
def get_residual(vars,x, data): a= vars[0] b=vars[1] model =a* x**2 +b return data-model vars=[1.,0.] print get_residual(vars,x,data) print sum(get_residual(vars,x,data)) vars=[1.,1.] print sum(get_residual(vars,x,data)) vars=[2.,0.] print sum(get_residual(vars,x,data))
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Questions ? leastsq function from scipy:
from scipy.optimize import leastsq vars = [0.,0.] out = leastsq(get_residual, vars, args=(x, data)) print out vars=[1.06734694, 0.96428571] print sum(get_residual(vars,x,data)**2) vars=[1.06734694, 0.96428571] plt.scatter(x,data) xarray=np.arange(-1,4,0.1) plt.plot(xarray, xarray**2,'r-') plt.plot(xarray, xarray**2...
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
LMFIT : Using Parameter objects instead of plain floats as variables. A parameter value: can be varied in the fit have a fixed value have upper and/or lower bounds constrained by an algebraic expression of other Parameter values Ease of changing fitting algorithms. Once a fitting model is set up, one can change the f...
from lmfit import minimize, Parameters params = Parameters() params.add('amp', value=0.) params.add('offset', value=0.) def get_residual(params,x, data): amp= params['amp'].value offset=params['offset'].value model =amp* x**2 +offset return data-model out = minimize(get_residual, params, ar...
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Fit values are the same as before !
out.__dict__ out.params['amp'].__dict__
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Questions ? Manipulating parameters : parameter class gives a lot of flexibility in manipulating the model parameters !
params['amp'].vary = False out = minimize(get_residual, params, args=(x, data)) print out.params print out.chisqr params['amp'].value = 1.0673469387778385 out = minimize(get_residual, params, args=(x, data)) print out.chisqr
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Another way of defining the parameters :
def get_residual(params,x, data): #amp= params['amp'].value #offset=params['offset'].value #xoffset=params['xoffset'].value parvals = params.valuesdict() amp = parvals['amp'] offset = parvals['offset'] model =amp* x**2 +offset return data-model
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Other manipulations :
params = Parameters() params.add('amp', value=0.) #params['amp'] = Parameter(value=..., min=...) params.add('offset', value=0.) params.add('xoffset', value=0.0, vary=False) out = minimize(get_residual, params, args=(x, data)) print out.params Image(filename='output.png', width=500, height=500)
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Challenge : Set parameter bound for 'amp' using "min" and "max"
params['offset'].min = -10. params['offset'].max = 10. out = minimize(get_residual, params, args=(x, data)) print out.params
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
stderr:
print out.params['amp'].stderr
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
correl:
print out.params['amp'].correl
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
report_fit: For a better report :
from lmfit import minimize, Parameters, Parameter, report_fit result = minimize(get_residual, params, args=(x, data)) help(report_fit) # write error report report_fit(result.params)
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Choosing Different Fitting Methods :
Image(filename='fitting.png', width=500, height=500)
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Challenge : Run with two other methods e.g., 'tnc' and 'powell' and compare the results:
result2 = minimize(get_residual, params, args=(x, data), method='tnc') report_fit(result2.params) result3 = minimize(get_residual, params, args=(x, data), method='powell') report_fit(result3.params)
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Complete report :
print(report_fit(result3))
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
Using expressions:
params.add('amp2', expr='(amp-offset)**2') def get_residual(params,x, data): #amp= params['amp'].value #offset=params['offset'].value #xoffset=params['xoffset'].value parvals = params.valuesdict() amp = parvals['amp'] offset = parvals['offset'] amp2 = parvals['amp2'] ...
Other_files/LMFIT_tutorial.ipynb
aliojjati/aliojjati.github.io
mit
if you are in a terminal, you will see something like this:: Processing Data Dictionary Processing Input File Initializing Simulation Reporting Surfaces Beginning Primary Simulation Initializing New Environment Parameters Warming up {1} Warming up {2} Warming up {3} Warming up {4} Warming up {5} Warming up {6} Starting...
help(idf.run)
docs/runningeplus.ipynb
santoshphilip/eppy
mit
Note: idf.run() works for E+ version >= 8.3 Running in parallel processes If you have acomputer with multiple cores, you may want to use all the cores. EnergyPlus allows you to run simulations on multiple cores. Here is an example script of how use eppy to run on multiple cores
"""multiprocessing runs""" import os from eppy.modeleditor import IDF from eppy.runner.run_functions import runIDFs def make_eplaunch_options(idf): """Make options for run, so that it runs like EPLaunch on Windows""" idfversion = idf.idfobjects['version'][0].Version_Identifier.split('.') idfversion.exte...
docs/runningeplus.ipynb
santoshphilip/eppy
mit
Running in parallel processes using Generators Maybe you want to run a 100 or a 1000 simulations. The code above will not let you do that, since it will try to load 1000 files into memory. Now you need to use generators (python's secret sauce. if you don't know this, you need to look into it). Here is a code using ge...
"""multiprocessing runs using generators instead of a list when you are running a 100 files you have to use generators""" import os from eppy.modeleditor import IDF from eppy.runner.run_functions import runIDFs def make_eplaunch_options(idf): """Make options for run, so that it runs like EPLaunch on Windows""" ...
docs/runningeplus.ipynb
santoshphilip/eppy
mit
True Multi-processing What if you want to run your simulations on multiple computers. What if those computers are on other networks (some at home and the other in your office and others in your server room) and some on the cloud. There is an experimental repository where you can do this. Keep an eye on this: https://gi...
"""single run EPLaunch style""" import os from eppy.modeleditor import IDF from eppy.runner.run_functions import runIDFs def make_eplaunch_options(idf): """Make options for run, so that it runs like EPLaunch on Windows""" idfversion = idf.idfobjects['version'][0].Version_Identifier.split('.') idfversion...
docs/runningeplus.ipynb
santoshphilip/eppy
mit
Debugging and reporting problems Debugging issues with IDF.run() used to be difficult, since you needed to go and hunt for the eplusout.err file, and the error message returned was not at all helpful. Now the output from EnergyPlus is returned in the error message, as well as the location and contents of eplusout.err. ...
E eppy.runner.run_functions.EnergyPlusRunError: E Program terminated: EnergyPlus Terminated--Error(s) Detected. E E Contents of EnergyPlus error file at C:\Users\jamiebull1\git\eppy\eppy\tests\test_dir\eplusout.err E Program Version,EnergyPlus, Version 8.9.0-40101eaafd, YMD=2018....
docs/runningeplus.ipynb
santoshphilip/eppy
mit
Define formulae
def peakdens1D(x,k): f1 = (3-k**2)**0.5/(6*math.pi)**0.5*np.exp(-3*x**2/(2*(3-k**2))) f2 = 2*k*x*math.pi**0.5/6**0.5*stats.norm.pdf(x)*stats.norm.cdf(k*x/(3-k**2)**0.5) out = f1+f2 return out def peakdens2D(x,k): f1 = 3**0.5*k**2*(x**2-1)*stats.norm.pdf(x)*stats.norm.cdf(k*x/(2-k**2)**0.5) f2 =...
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Apply formulae to a range of x-values
xs = np.arange(-4,10,0.01).tolist() ys_3d_k01 = [] ys_3d_k05 = [] ys_3d_k1 = [] ys_2d_k01 = [] ys_2d_k05 = [] ys_2d_k1 = [] ys_1d_k01 = [] ys_1d_k05 = [] ys_1d_k1 = [] for x in xs: ys_1d_k01.append(peakdens1D(x,0.1)) ys_1d_k05.append(peakdens1D(x,0.5)) ys_1d_k1.append(peakdens1D(x,1)) ys_2d_k01.append...
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Figure 1 from paper
plt.figure(figsize=(7,5)) plt.plot(xs,ys_1d_k01,color="black",ls=":",lw=2) plt.plot(xs,ys_1d_k05,color="black",ls="--",lw=2) plt.plot(xs,ys_1d_k1,color="black",ls="-",lw=2) plt.plot(xs,ys_2d_k01,color="blue",ls=":",lw=2) plt.plot(xs,ys_2d_k05,color="blue",ls="--",lw=2) plt.plot(xs,ys_2d_k1,color="blue",ls="-",lw=2) plt...
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Apply the distribution to simulated data, extracted peaks with FSL I now simulate random field, extract peaks with FSL and compare these simulated peaks with the theoretical distribution.
os.chdir("/Users/Joke/Documents/Onderzoek/ProjectsOngoing/Power/WORKDIR/") sm=1 smooth_FWHM = 3 smooth_sd = smooth_FWHM/(2*math.sqrt(2*math.log(2))) data = surrogate_3d_dataset(n_subj=1,sk=smooth_sd,shape=(500,500,500),noise_level=1) minimum = data.min() newdata = data - minimum #little trick because fsl.model.Cluster...
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Are the peaks independent? Below, I take a random sample of peaks to compute distances for computational ease. With 10K peaks, it already takes 15 minutes to compute al distances.
ss = 10000 smpl = np.random.choice(len(peaks),ss,replace=False) peaksmpl = peaks.loc[smpl].reset_index()
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Compute distances between peaks and the difference in their height.
dist = [] diff = [] for p in range(ss): for q in range(p+1,ss): xd = peaksmpl.x[q]-peaksmpl.x[p] yd = peaksmpl.y[q]-peaksmpl.y[p] zd = peaksmpl.z[q]-peaksmpl.z[p] if not any(x > 20 or x < -20 for x in [xd,yd,zd]): dist.append(np.sqrt(xd**2+yd**2+zd**2)) diff....
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
Take the mean of heights in bins of 1.
mn = [] ds = np.arange(start=2,stop=100) for d in ds: mn.append(np.mean(np.array(diff)[np.round(np.array(dist))==d])) twocol = cb.qualitative.Paired_12.mpl_colors plt.figure(figsize=(7,5)) plt.plot(dist,diff,"r.",color=twocol[0],linewidth=0,label="combination of 2 points") plt.xlim([2,20]) plt.plot(ds,mn,color=two...
peakdistribution/chengschwartzman_thresholdfree_distribution_simulation.ipynb
jokedurnez/neuropower_extended
mit
RLDS: Examples This colab provides some examples of RLDS usage based on real use cases. If you are looking for an introduction to RLDS, see the RLDS tutorial in Google Colab. <table class="tfo-notebook-buttons" align="left"> <td> <a href="https://colab.research.google.com/github/google-research/rlds/blob/main/rld...
!pip install rlds[tensorflow] !pip install tfds-nightly --upgrade !pip install envlogger !apt-get install libgmp-dev
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Import Modules
import functools import rlds import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Load dataset We can load the human dataset from the Panda Pick Place Can task of the Robosuite collection in TFDS. In these examples, we are assuming that certain fields are present in the steps, so datasets from different tasks will not be compatible.
dataset_config = 'human_dc29b40a' # @param { isTemplate : true} dataset_name = f'robosuite_panda_pick_place_can/{dataset_config}' num_episodes_to_load = 30 # @param { isTemplate: true}
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Learning from Demonstrations or Offline RL We consider the setup where an agent needs to solve a task specified by a reward $r$. We assume a dataset of episodes with the corresponding rewards is available for training. This includes: * The ORL setup [[1], 2] where the agent is trained solely from a dataset of episodes...
K = 5 # @param { isTemplate: true} buffer_size = 30 # @param { isTemplate: true} dataset = tfds.load(dataset_name, split=f'train[:{num_episodes_to_load}]') dataset = dataset.shuffle(buffer_size, seed=42, reshuffle_each_iteration=False) dataset = dataset.take(K) def prepare_observation(step): """Filters the obseravt...
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Absorbing Terminal States in Imitation Learning Imitation learning is the setup where an agent tries to imitate a behavior, as defined by some sample episodes of that behavior. In particular, the reward is not specified. The dataset processing pipeline requires all the different pieces seen in the learning from demonst...
def duplicate_terminal_step(episode): """Duplicates the terminal step if the episode ends in one. Noop otherwise.""" return rlds.transformations.concat_if_terminal( episode, make_extra_steps=tf.data.Dataset.from_tensors) def convert_to_absorbing_state(step): padding = step[rlds.IS_TERMINAL] if step[rlds....
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Offline Analysis One significant use case we envision for RLDS is the offline analysis of collected datasets. There is no standard offline analysis procedure as what is possible is only limited by the imagination of the users. We expose in this section a fictitious use case to illustrate how custom tags stored in a RL ...
def placed_tag_is_set(step): return tf.not_equal(tf.math.count_nonzero(step['tag:placed']),0) def compute_return(steps): """Computes the return of the episode up to the 'placed' tag.""" # Truncate the episode after the placed tag. steps = rlds.transformations.truncate_after_condition( steps, truncate_con...
rlds/examples/rlds_examples.ipynb
google-research/rlds
apache-2.0
Initial set-up Load experiments for unified dataset: - Steady-state activation [Li1997] - Activation time constant [Li1997] - Steady-state inactivation [Li1997] - Inactivation time constant [Sun1997] - Recovery time constant [Li1997]
from experiments.ical_li import (li_act_and_tau, li_inact_1000, li_inact_kin_80, li_recov) modelfile = 'models/courtemanche_ical.mmt'
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Plot steady-state and tau functions
from ionchannelABC.visualization import plot_variables sns.set_context('talk') V = np.arange(-80, 40, 0.01) cou_par_map = {'di': 'ical.d_inf', 'fi': 'ical.f_inf', 'dt': 'ical.tau_d', 'ft': 'ical.tau_f'} f, ax = plot_variables(V, cou_par_map, 'models/courtemanche_ical.mmt', figsha...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Activation gate ($d$) calibration Combine model and experiments to produce: - observations dataframe - model function to run experiments and return traces - summary statistics function to accept traces
observations, model, summary_statistics = setup(modelfile, li_act_and_tau) assert len(observations)==len(summary_statistics(model({}))) g = plot_sim_results(modelfile, li_act_and_tau)
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Set up prior ranges for each parameter in the model. See the modelfile for further information on specific parameters. Prepending `log_' has the effect of setting the parameter in log space.
limits = {'ical.p1': (-100, 100), 'ical.p2': (0, 50), 'log_ical.p3': (-7, 3), 'ical.p4': (-100, 100), 'ical.p5': (0, 50)} prior = Distribution(**{key: RV("uniform", a, b - a) for key, (a,b) in limits.items()}) # Test this works correctly with set-up funct...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Run ABC calibration
db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "courtemanche_ical_dgate_unified.db")) logging.basicConfig() abc_logger = logging.getLogger('ABC') abc_logger.setLevel(logging.DEBUG) eps_logger = logging.getLogger('Epsilon') eps_logger.setLevel(logging.DEBUG) pop_size = theoretical_population_size(2, len...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Analysis of results
df, w = history.get_distribution(m=0) df.describe() sns.set_context('poster') mpl.rcParams['font.size'] = 14 mpl.rcParams['legend.fontsize'] = 14 g = plot_sim_results(modelfile, li_act_and_tau, df=df, w=w) plt.tight_layout() m,_,_ = myokit.load(modelfile) originals = {} ...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Voltage-dependent inactivation gate ($f$) calibration
observations, model, summary_statistics = setup(modelfile, li_inact_1000, li_inact_kin_80, li_recov) assert len(observations)==len(summary_statistics(model({}))) g = plot_sim...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Run ABC calibration
db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "courtemanche_ical_fgate_unified.db")) logging.basicConfig() abc_logger = logging.getLogger('ABC') abc_logger.setLevel(logging.DEBUG) eps_logger = logging.getLogger('Epsilon') eps_logger.setLevel(logging.DEBUG) pop_size = theoretical_population_size(2, len...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Analysis of results
df, w = history.get_distribution() df.describe() sns.set_context('poster') mpl.rcParams['font.size'] = 14 mpl.rcParams['legend.fontsize'] = 14 g = plot_sim_results(modelfile, li_inact_1000, li_inact_kin_80, li_recov, df=df, w=w) pl...
docs/examples/human-atrial/courtemanche_ical_unified.ipynb
c22n/ion-channel-ABC
gpl-3.0
Construct the model m
# Impedance, imp VP RHO imp = np.ones(50) * 2550 * 2650 imp[10:15] = 2700 * 2750 imp[15:27] = 2400 * 2450 imp[27:35] = 2800 * 3000 plt.plot(imp)
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
But I really want to use the reflectivity, so let's compute that:
D = convmtx([-1, 1], imp.size)[:, :-1] D r = D @ imp plt.plot(r[:-1])
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
I don't know how best to control the magnitude of the coefficients or how to combine this matrix with G, so for now we'll stick to the model m being the reflectivity, calculated the normal way.
m = (imp[1:] - imp[:-1]) / (imp[1:] + imp[:-1]) plt.plot(m)
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
Forward operator: convolution with wavelet Now we make the kernel matrix G, which represents convolution.
from scipy.signal import ricker wavelet = ricker(40, 2) plt.plot(wavelet) # Downsampling: set to 1 to use every sample. s = 2 # Make G. G = convmtx(wavelet, m.size)[::s, 20:70] plt.imshow(G, cmap='viridis', interpolation='none') # Or we can use bruges (pip install bruges) # from bruges.filters import ricker # wavel...
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
Forward model the data d Now we can perform the forward problem: computing the data.
d = G @ m
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
Let's visualize these components for fun...
def add_subplot_axes(ax, rect, axisbg='w'): """ Facilitates the addition of a small subplot within another plot. From: http://stackoverflow.com/questions/17458580/ embedding-small-plots-inside-subplots-in-matplotlib License: CC-BY-SA Args: ax (axis): A matplotlib axis. rect (l...
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
Note that G * m gives us exactly the same result as np.convolve(w_, m). This is just another way of implementing convolution that lets us use linear algebra to perform the operation, and its inverse.
plt.plot(np.convolve(wavelet, m, mode='same')[::s], 'blue', lw=3) plt.plot(G @ m, 'red')
NumPy_reflectivity.ipynb
kwinkunks/axb
apache-2.0
Plot something with Matlab:
%%matlab %%%%%%%%%%%% %%% Plot Test to check that Matlab is loaded properly %%%%%%%%%%%% a = linspace(0.01,6*pi,100); plot(sin(a)) grid on hold on plot(cos(a),'r')
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
First Part (Hilbert for a random signal) Hilbert Transform Here we look at how padding affects the phase when taking the Hilbert transform. This code is from Javier for a simple signal.
%%matlab %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Checks if padding a signal makes a difference when taking the %%% Hilbert transform to find the phase. %%% %%% code from Javier (email, 3/07/2014) %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% signal = randn(1000,1); hsig = hilbert(signal); %% padding with t...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Apparently for a complex number z: angle(z) - is equal to theta = atan2(imag(z),real(z)). Quick check below and comparison to unwrapped phase:
%%matlab signal = randn(10,1); hilbert(signal); %phase = atan(signal./imag(hilbert(signal))) phase = atan2(imag(hilbert(signal)), signal); x = imag(hilbert(signal)); hold on % the first 2 below are exactly the same, so they are indeed the same plot(angle(hilbert(signal)), 'g') plot(phase, 'b') plot(unwrap(phase), 'r')...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Second Part (Hilbert for padded/unpadded MEG) Looking at how padding affects the phase of cleaned MEG signals when taking the Hilbert transform:
%%matlab %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Loads cleaned MEG epoch. %%% Padds the signal with 200 columns at the beginning with the first column of the epoch %%% and 200 columns at the end with the last column of the epoch. %%% Computes Hilbert transform of unpadded and padded ...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Third Part (Hilbert for padded/unpadded MEG) Here we take the Hilbert transform of the transposed MEG matrix which yields a time samples x channels matrix. In Matlab, the hilbert() function operates columnwise. I guess this is the correct way to compute the phase. Padding is done by: - appending 200 columns identical t...
%%matlab %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Load MEG signals for epochs specified in the "data" array. %%% Computes Hilbert transform of unpadded and padded version. %%% Plots the previous graphs. %%% %%% OBS: Code takes Hilbert transform of %%% the "time samples (row...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Fourth Part Here we also compare the phases of unpadded and padded signal as in Part Three, with the difference that the padding is done using symmetric extension (also called reflective padding in the past). Padding is done using wextend().
%%matlab %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Load MEG signals for epochs specified in the "data" array. %%% Computes Hilbert transform of unpadded and padded version. %%% Padding is done using symmetric extension. %%% Plots the previous graphs. %%% %%% OBS: Code take...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Fifth Part (Hilbert on padded/unpadded filtered MEG) This section looks at estimating instantaneous phase with FieldTrip. We filter the our data and then apply the Hilbert transform. This can be done in ft_preprocessing() like so:
%%matlab % load header file load('/home/dragos/DTC/MSc/SummerProject/4D_header_adapted.mat'); filterOrder = 750; Fs = 169.54; %% add data folders to path addpath('/home/dragos/DTC/MSc/SummerProject/data/MEG_AD_Thesis/MEG_50863_noECG_10s/07'); addpath('/home/dragos/DTC/MSc/SummerProject/data/MEG_AD_Thesis/MEG_50863_n...
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Looking at how padding affects the phase of RAW MEG signals when taking the Hilbert transform. Have to merge raw data first...
%%matlab %% add RAW data folder to path addpath('/home/dragos/DTC/MSc/SummerProject/data/MEG_AD_Thesis/50863') %unload_ext pymatbridge
sources/notebooks/testing_connectivity.ipynb
dnstanciu/masters-project
gpl-3.0
Fun with the BBBC021 dataset This uses the BBBC021 dataset, a screen of MCF-7 breast cancer cells treated with a library of 113 compounds. A subset (103 wells) have been annotated such that the compounds they were treated have been placed in 12 categories. I ran the feature extraction using Microscopium's object featu...
# first load in the screen metadata bbbc021_metadata = pd.read_csv("./BBBC021_v1_image.csv") # now load in the mechanism of action metadata, these map # compouds to a class of compounds bbbc021_moa = pd.read_csv("./BBBC021_v1_moa.csv") # wrangle the metadata into a form that maps screen-plate-well format IDs # to the...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Supervised learning Now we have our training data. Let's try it with a simple linear SVM using the full set of features. Why SVM? A linear SVM is simple, performs well and the weights can be used to quantify feature importance. First a quick 5-fold cross validation to check it can discriminate between classes.
classifier = svm.SVC(kernel='linear', C=1) scores = cross_validation.cross_val_score(classifier, bbbc021_feature.values, bbbc021_merged["moa"].values, cv=5) sum(scores / 5)
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Hey, that's not bad!! Previous studies have ~90% accuracy but they've done lots more fine-tuning of the features and segmentation pipeline. The features show the data is somewhat linearly seperable. Let's see how object features, texture features and threshold adjacancy statistics perform on their own.
object_cols = [col for col in bbbc021_feature.columns if "pftas" not in col and "haralick" not in col] haralick_cols = [col for col in bbbc021_feature.columns if "haralick" in col] pftas_cols = [col for col in bbbc021_feature.columns if "pftas" in col] scores = cross_validation.cross_val_score(classifier, ...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Wow! Object and PFTAS features do great on their own. What if we tried both?
object_pftas_cols = [col for col in bbbc021_feature.columns if "haralick" not in col] scores = cross_validation.cross_val_score(classifier, bbbc021_feature[object_pftas_cols].values, bbbc021_merged["moa"].values, ...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
85%! That's the best performance yet. Let's look at some feature importance scores using ExtraTrees. We can use this model to get Gini coefficients for each feature.
et_classifier = ExtraTreesClassifier() et_classifier.fit(bbbc021_feature[object_pftas_cols].values, bbbc021_merged["moa"].values) feature_scores = pd.DataFrame(data={"feature": bbbc021_feature[object_pftas_cols].columns, "gini": et_classifier.feature_importances_}) feature_scores =...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Features across all three channels, and a mixture of both object and adjacancy threshold statistics contribute as the most important features. There's no evidence to suggest that one particular feature dominates here. Supervised Learning - Independence of Features How accurate if the classification if we take random s...
n_features = bbbc021_feature[object_pftas_cols].shape[1] sample_size = int(np.round(n_features * 0.65)) all_scores = [] for i in range(10000): random_index = np.random.choice(np.arange(n_features), sample_size) scores = cross_validation.cross_val_score(classifier, bbb...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
The accuracy of the classifier is robust against random subsetting of the data. Maximum classifier is as high as ~90% on some subset(s) of the data. Unsupervised Learning The next task is to cluster the feature vectors into 11 clusters and see how well the original labels are represented. I'll use Agglomerative Cluster...
ag_clustering = AgglomerativeClustering(n_clusters=12, affinity="cosine", linkage="complete") ag_predict = ag_clustering.fit_predict(X=bbbc021_feature[object_pftas_cols].values) metrics.adjusted_rand_score(bbbc021_merged["moa"].values, ag_predict)
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Not great, but they're not completely random either. Dimensionality Reduction Now we look at the PCA and TSNE embeddings. This is the real test, seeing as the PCA and TSNE embeddings of the data drive the Microscopium interface.
rand_seed = 42 bbbc021_pca = PCA(n_components=2).fit_transform(bbbc021_feature[object_pftas_cols].values) bbbc021_pca_50 = PCA(n_components=50).fit_transform(bbbc021_feature[object_pftas_cols].values) bbbc021_tsne = TSNE(n_components=2, learning_rate=100, random_state=42).fit_transform(bbbc021_pca_50) labels = list(s...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
The PCA embedding isn't particularly useful.
bbbc021_tsne_df = pd.DataFrame(dict(x=bbbc021_tsne[:, 0], y=bbbc021_tsne[:, 1], label=bbbc021_merged["moa"].values), index=bbbc021_feature.index) groups = bbbc021_tsne_df.groupby('label') fig, ax = plt.subplots() ...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
TSNE's is much better. We get some tight clusters and individual categories tend to stay close. Can TSNE embeddings classify examples? Finally, we plot together 10 randomly chosen examples along with the annotated examples. The idea here is to find samples that group together. We can then look up the compound and deter...
np.random.seed(13) # get the set difference of indices in the whole dataset, and indices unannot_index = np.setdiff1d(bbbc021_complete.index, bbbc021_feature.index) # get 20 random examples from the data frame unannot_sample = np.random.choice(unannot_index, 10) # combine these samples with the annotated ones, resc...
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
Woo, I've never matplotlibbed that hard before. Of the unannotated samples, I make the following observations: BBBC021-22141-D08 clusters together tightly with the Microtubule stabilizers BBBC021-25701-C07 and BBBC021-25681-C09 group together with Protein synthesis BBBC021-22161-F07 clusters together with the Auroroa ...
selected_indices = ["BBBC021-22141-D08", "BBBC021-25701-C07", "BBBC021-22161-F07", "BBBC021-27821-C05", "BBBC021-25681-C09", "BBBC021-34641-C10"] bbbc021_metadata.ix[selected_indices].drop_duplicates()
bbbc021_analysis.ipynb
microscopium/microscopium-scripts
bsd-3-clause
MinDiff Data Preparation <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/responsible_ai/model_remediation/min_diff/guide/min_diff_data_preparation"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on Te...
!pip install --upgrade tensorflow-model-remediation import tensorflow as tf from tensorflow_model_remediation import min_diff from tensorflow_model_remediation.tools.tutorials_utils import uci as tutorials_utils
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Original Data For demonstration purposes and to reduce runtimes, this guide uses only a sample fraction of the UCI Income dataset. In a real production setting, the full dataset would be utilized.
# Sampled at 0.3 for reduced runtimes. train = tutorials_utils.get_uci_data(split='train', sample=0.3) print(len(train), 'train examples')
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Converting to tf.data.Dataset MinDiffModel requires that the input be a tf.data.Dataset. If you were using a different format of input prior to integrating MinDiff, you will have to convert your input data. Use tf.data.Dataset.from_tensor_slices to convert to tf.data.Dataset. dataset = tf.data.Dataset.from_tensor_slice...
# Function to convert a DataFrame into a tf.data.Dataset. def df_to_dataset(dataframe, shuffle=True): dataframe = dataframe.copy() labels = dataframe.pop('target') ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=5000) # Reasonable but arbitrary buf...
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Note: The training dataset has not been batched yet but it will be later. Creating MinDiff data During training, MinDiff will encourage the model to reduce differences in predictions between two additional datasets (which may include examples from the original dataset). The selection of these two datasets is the key de...
female_pos = train[(train['sex'] == ' Female') & (train['target'] == 1)] male_pos = train[(train['sex'] == ' Male') & (train['target'] == 1)] print(len(female_pos), 'positively labeled female examples') print(len(male_pos), 'positively labeled male examples')
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
It is perfectly acceptable to create MinDiff datasets from subsets of the original dataset. While there aren't 5,000 or more positive "Male" examples as recommended in the requirements guidance, there are over 2,000 and it is reasonable to try with that many before collecting more data.
min_diff_male_ds = df_to_dataset(male_pos)
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Positive "Female" examples, however, are much scarcer at 385. This is probably too small for good performance and so will require pulling in additional examples. Note: Since this guide began by reducing the dataset via sampling, this problem (and the corresponding solution) may seem contrived. However, it serves as a g...
full_uci_train = tutorials_utils.get_uci_data(split='train') augmented_female_pos = full_uci_train[((full_uci_train['sex'] == ' Female') & (full_uci_train['target'] == 1))] print(len(augmented_female_pos), 'positively labeled female examples')
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Using the full dataset has more than tripled the number of examples that can be used for MinDiff. It’s still low but it is enough to try as a first pass.
min_diff_female_ds = df_to_dataset(augmented_female_pos)
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Both the MinDiff datasets are significantly smaller than the recommended 5,000 or more examples. While it is reasonable to attempt to apply MinDiff with the current data, you may need to consider collecting additional data if you observe poor performance or overfitting during training. Using tf.data.Dataset.filter Alte...
# Male def male_predicate(x, y): return tf.equal(x['sex'], b' Male') and tf.equal(y, 0) alternate_min_diff_male_ds = original_train_ds.filter(male_predicate).cache() # Female def female_predicate(x, y): return tf.equal(x['sex'], b' Female') and tf.equal(y, 0) full_uci_train_ds = df_to_dataset(full_uci_train) alt...
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
The resulting alternate_min_diff_male_ds and alternate_min_diff_female_ds will be equivalent in output to min_diff_male_ds and min_diff_female_ds respectively. Constructing your Training Dataset As a final step, the three datasets (the two newly created ones and the original) need to be merged into a single dataset tha...
original_train_ds = original_train_ds.batch(128) # Same as before MinDiff. # The MinDiff datasets can have a different batch_size from original_train_ds min_diff_female_ds = min_diff_female_ds.batch(32, drop_remainder=True) # Ideally we use the same batch size for both MinDiff datasets. min_diff_male_ds = min_diff_ma...
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Packing the Datasets with pack_min_diff_data Once the datasets are prepared, pack them into a single dataset which will then be passed along to the model. A single batch from the resulting dataset will contain one batch from each of the three datasets you prepared previously. You can do this by using the provided utils...
train_with_min_diff_ds = min_diff.keras.utils.pack_min_diff_data( original_dataset=original_train_ds, sensitive_group_dataset=min_diff_female_ds, nonsensitive_group_dataset=min_diff_male_ds)
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
And that's it! You will be able to use other util functions in the package to unpack individual batches if needed.
for inputs, original_labels in train_with_min_diff_ds.take(1): # Unpacking min_diff_data min_diff_data = min_diff.keras.utils.unpack_min_diff_data(inputs) min_diff_examples, min_diff_membership = min_diff_data # Unpacking original data original_inputs = min_diff.keras.utils.unpack_original_inputs(inputs)
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
With your newly formed data, you are now ready to apply MinDiff in your model! To learn how this is done, please take a look at the other guides starting with Integrating MinDiff with MinDiffModel. Using a Custom Packing Format (optional) You may decide to pack the three datasets together in whatever way you choose. Th...
# Reformat input to be a dict. def _reformat_input(inputs, original_labels): unpacked_min_diff_data = min_diff.keras.utils.unpack_min_diff_data(inputs) unpacked_original_inputs = min_diff.keras.utils.unpack_original_inputs(inputs) return { 'min_diff_data': unpacked_min_diff_data, 'original_data': (un...
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Your model will need to know how to read this customized input as detailed in the Customizing MinDiffModel guide.
for batch in customized_train_with_min_diff_ds.take(1): # Customized unpacking of min_diff_data min_diff_data = batch['min_diff_data'] # Customized unpacking of original_data original_data = batch['original_data']
docs/min_diff/guide/min_diff_data_preparation.ipynb
tensorflow/model-remediation
apache-2.0
Загрузка данных Время ремонта телекоммуникаций Verizon — основная региональная телекоммуникационная компания (Incumbent Local Exchange Carrier, ILEC) в западной части США. В связи с этим данная компания обязана предоставлять сервис ремонта телекоммуникационного оборудования не только для своих клиентов, но и для клие...
data = pd.read_csv('verizon.txt', sep='\t') data.shape data.head() data.Group.value_counts() pylab.figure(figsize(12, 5)) pylab.subplot(1,2,1) pylab.hist(data[data.Group == 'ILEC'].Time, bins = 20, color = 'b', range = (0, 100), label = 'ILEC') pylab.legend() pylab.subplot(1,2,2) pylab.hist(data[data.Group == 'CLEC...
course4/week1 - Доверительные интервалы на основе bootstrap - demo.ipynb
astarostin/MachineLearningSpecializationCoursera
apache-2.0
Bootstrap
def get_bootstrap_samples(data, n_samples): indices = np.random.randint(0, len(data), (n_samples, len(data))) samples = data[indices] return samples def stat_intervals(stat, alpha): boundaries = np.percentile(stat, [100 * alpha / 2., 100 * (1 - alpha / 2.)]) return boundaries
course4/week1 - Доверительные интервалы на основе bootstrap - demo.ipynb
astarostin/MachineLearningSpecializationCoursera
apache-2.0
Интервальная оценка медианы
ilec_time = data[data.Group == 'ILEC'].Time.values clec_time = data[data.Group == 'CLEC'].Time.values np.random.seed(0) ilec_median_scores = map(np.median, get_bootstrap_samples(ilec_time, 1000)) clec_median_scores = map(np.median, get_bootstrap_samples(clec_time, 1000)) print "95% confidence interval for the ILEC m...
course4/week1 - Доверительные интервалы на основе bootstrap - demo.ipynb
astarostin/MachineLearningSpecializationCoursera
apache-2.0
Точечная оценка разности медиан
print "difference between medians:", np.median(clec_time) - np.median(ilec_time)
course4/week1 - Доверительные интервалы на основе bootstrap - demo.ipynb
astarostin/MachineLearningSpecializationCoursera
apache-2.0
Интервальная оценка разности медиан
delta_median_scores = map(lambda x: x[1] - x[0], zip(ilec_median_scores, clec_median_scores)) print "95% confidence interval for the difference between medians", stat_intervals(delta_median_scores, 0.05)
course4/week1 - Доверительные интервалы на основе bootstrap - demo.ipynb
astarostin/MachineLearningSpecializationCoursera
apache-2.0
For now, neglect rotational inertia. Interpolation functions
xi, l, rho = symbols('xi, l, rho') # Shape functions S = Matrix(np.zeros((4, 12))) x2 = (1 - xi) S[0, 0 ] = x2 # extension S[0, 6 ] = xi S[1, 1 ] = x2**2 * (3 - 2*x2) # y-deflection S[1, 7 ] = xi**2 * (3 - 2*xi) S[1, 5 ] = -x2**2 * (x2 - 1) * l S[1, 11] = xi**2 * (xi - 1) * l S[2, 2 ] ...
theory/FE element matrices.ipynb
ricklupton/beamfe
mit
Mass matrix Define the density distribution (linear):
rho1, rho2 = symbols('rho_1, rho_2') rho = (1 - xi)*rho1 + xi*rho2 rho
theory/FE element matrices.ipynb
ricklupton/beamfe
mit
Integrate the density distribution with the shape functions.
def sym_me(): m = Matrix(np.diag([rho, rho, rho, 0])) integrand = S.T * m * S me = integrand.applyfunc( lambda xxx: l * sympy.integrate(xxx, (xi, 0, 1)).expand().factor() ) return me me = sym_me() me.shape me[0,:] me[6,:] me[1,:]
theory/FE element matrices.ipynb
ricklupton/beamfe
mit
Special case: rho1 == rho2
me.subs({rho2: rho1})/rho1
theory/FE element matrices.ipynb
ricklupton/beamfe
mit
Shape integrals As well as the actual mass matrix, the shape integrals are needed for the multibody dynamics equations: \begin{align} m &= \int \mathrm{d}m \ \boldsymbol{S} &= \int \boldsymbol{S} \mathrm{d}m \ \boldsymbol{S}_{kl} &= \int \boldsymbol{S}_k^T \boldsymbol{S}_l \mathrm{d}m \end{...
mass = l * sympy.integrate(rho, (xi, 0, 1)).factor() mass
theory/FE element matrices.ipynb
ricklupton/beamfe
mit
First shape integral:
shape_integral_1 = S[:3, :].applyfunc( lambda xxx: l * sympy.integrate(rho * xxx, (xi, 0, 1)).expand().simplify() ) shape_integral_1.T shape_integral_2 = [ [l * (S[i, :].T * S[j, :]).applyfunc( lambda xxx: sympy.integrate(rho * xxx, (xi, 0, 1)).expand().simplify()) for j in range(3)] for i in ...
theory/FE element matrices.ipynb
ricklupton/beamfe
mit