markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Concatenating :class:Raw <mne.io.Raw> objects :class:Raw <mne.io.Raw> objects can be concatenated in time by using the :func:append <mne.io.Raw.append> function. For this to work, they must have the same number of channels and their :class:Info <mne.Info> structures should be compatible.
# Create multiple :class:`Raw <mne.io.RawFIF>` objects raw1 = raw.copy().crop(0, 10) raw2 = raw.copy().crop(10, 20) raw3 = raw.copy().crop(20, 40) # Concatenate in time (also works without preloading) raw1.append([raw2, raw3]) print('Time extends from', raw1.times.min(), 's to', raw1.times.max(), 's')
0.14/_downloads/plot_object_raw.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
And we'll add a single light curve dataset so that we can see how passband luminosities affect the resulting synthetic light curve model.
b.add_dataset('lc', times=phoebe.linspace(0,1,101), dataset='lc01')
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Lastly, just to make things a bit easier and faster, we'll turn off irradiation (reflection), use blackbody atmospheres, and disable limb-darkening (so that we can play with weird temperatures without having to worry about falling of the grids).
b.set_value('irrad_method', 'none') b.set_value_all('ld_mode', 'manual') b.set_value_all('ld_func', 'linear') b.set_value_all('ld_coeffs', [0.]) b.set_value_all('ld_mode_bol', 'manual') b.set_value_all('ld_func_bol', 'linear') b.set_value_all('ld_coeffs_bol', [0.]) b.set_value_all('atm', 'blackbody')
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Relevant Parameters & Methods A pblum_mode parameter exists for each LC dataset in the bundle. This parameter defines how passband luminosities are handled. The subsections below describe the use and parameters exposed depening on the value of this parameter.
print(b.get_parameter(qualifier='pblum_mode', dataset='lc01'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
For any of these modes, you can expose the intrinsic (excluding extrinsic effects such as spots and irradiation) and extrinsic computed luminosities of each star (in each dataset) by calling b.compute_pblums. Note that as its an aspect-dependent effect, boosting is ignored in all of these output values.
print(b.compute_pblums())
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
For more details, see the section below on "Accessing Model Luminosities" as well as the b.compute_pblums API docs The table below provides a brief summary of all available pblum_mode options. Details are given in the remainder of the tutorial. | pblum_mode | intent | |-------------------|--------| | component-c...
print(b.filter(qualifier='pblum')) print(b.get_parameter(qualifier='pblum_component')) b.set_value('pblum_component', 'secondary') print(b.filter(qualifier='pblum'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Note that in general (for the case of a spherical star), a pblum of 4pi will result in an out-of-eclipse flux of ~1. Now let's just reset to the default case where the primary star has a provided (default) pblum of 4pi.
b.set_value('pblum_component', 'primary') print(b.get_parameter(qualifier='pblum', component='primary'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
NOTE: other parameters also affect flux-levels, including limb darkening, third light, boosting, irradiation, and distance If we call b.compute_pblums, we'll see that the computed intrinsic luminosity of the primary star (pblum@primary@lc01) matches the value of the parameter above.
print(b.compute_pblums())
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Let's see how changing the value of pblum affects the computed light curve. By default, pblum is set to be 4 pi, giving a total flux for the primary star of ~1. Since the secondary star in the default binary is identical to the primary star, we'd expect an out-of-eclipse flux of the binary to be ~2.
b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
If we now set pblum to be only 2 pi, we should expect the luminosities as well as entire light curve to be scaled in half.
b.set_value('pblum', component='primary', value=2*np.pi) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
And if we halve the temperature of the secondary star - the resulting light curve changes to the new sum of fluxes, where the primary star dominates since the secondary star flux is reduced by a factor of 16, so we expect a total out-of-eclipse flux of ~0.5 + ~0.5/16 = ~0.53.
b.set_value('teff', component='secondary', value=0.5 * b.get_value('teff', component='primary')) print(b.filter(qualifier='teff')) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Let us undo our changes before we look at decoupled luminosities.
b.set_value_all('teff', 6000) b.set_value_all('pblum', 4*np.pi)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
pblum_mode = 'decoupled' The luminosities are decoupled when pblums are provided for the individual components. To accomplish this, set pblum_mode to 'decoupled'.
b.set_value('pblum_mode', 'decoupled')
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Now we see that both pblum parameters are available and can have different values.
print(b.filter(qualifier='pblum'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
If we set these to 4pi, then we'd expect each star to contribute 1.0 in flux units, meaning the baseline of the light curve should be at approximately 2.0
b.set_value_all('pblum', 4*np.pi) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Now let's make a significant temperature-ratio by making a very cool secondary star. Since the luminosities are decoupled - this temperature change won't affect the resulting light curve very much (compare this to the case above with coupled luminosities). What is happening here is that even though the secondary star...
print(b.filter(qualifier='teff')) b.set_value('teff', component='secondary', value=3000) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
In most cases you will not want decoupled luminosities as they can easily break the self-consistency of your model. Now we'll just undo our changes before we look at accessing model luminosities.
b.set_value_all('teff', 6000) b.set_value_all('pblum', 4*np.pi)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
pblum_mode = 'absolute' By setting pblum_mode to 'absolute', luminosities and fluxes will be returned in absolute units and not rescaled. Note that third light and distance will still affect the resulting flux levels.
b.set_value('pblum_mode', 'absolute')
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
As we no longer provide pblum values to scale, those parameters are not visible when filtering.
print(b.filter(qualifier='pblum')) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
(note the exponent on the y-axis of the above figure) pblum_mode = 'dataset-scaled' Setting pblum_mode to 'dataset-scaled' is only allowed if fluxes are attached to the dataset itself. Let's use our existing model to generate "fake" data and then populate the dataset.
fluxes = b.get_value('fluxes', context='model') * 0.8 + (np.random.random(101) * 0.1) b.set_value('fluxes', context='dataset', value=fluxes) afig, mplfig = b.plot(context='dataset', show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Now if we set pblum_mode to 'dataset-scaled', the resulting model will be scaled to best fit the data. Note that in this mode we cannot access computed luminosities via b.compute_pblums (without providing model - we'll get back to that in a minute), nor can we access scaled intensities from the mesh.
b.set_value('pblum_mode', 'dataset-scaled') print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
The model stores the scaling factor used between the absolute fluxes and the relative fluxes that best fit to the observational data.
print(b.get_parameter(qualifier='flux_scale', context='model'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
We can then access the scaled luminosities by passing the model tag to b.compute_pblums. Keep in mind this only scales the absolute luminosities by flux_scale so assumes a fixed distance@system. This is useful though if we wanted to use 'dataset-scaled' to get an estimate for pblum before changing to 'component-coupl...
print(b.compute_pblums(model='latest'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Before moving on, let's remove our fake data (and reset pblum_mode or else PHOEBE will complain about the lack of data).
b.set_value('pblum_mode', 'component-coupled') b.set_value('fluxes', context='dataset', value=[])
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
pblum_mode = 'dataset-coupled' Setting pblum_mode to 'dataset-coupled' allows for the same scaling factor to be applied to two different datasets. In order to see this in action, we'll add another LC dataset in a different passband.
b.add_dataset('lc', times=phoebe.linspace(0,1,101), ld_mode='manual', ld_func='linear', ld_coeffs=[0], passband='Johnson:B', dataset='lc02') b.set_value('pblum_mode', dataset='lc02', value='dataset-coupled')
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Here we see the pblum_mode@lc01 is set to 'component-coupled' meaning it will follow the rules described earlier where pblum is provided for the primary component and the secondary is coupled to that. pblum_mode@lc02 is set to 'dataset-coupled' with pblum_dataset@lc01 pointing to 'lc01'.
print(b.filter('pblum*')) print(b.compute_pblums()) b.run_compute() afig, mplfig = b.plot(show=True, legend=True)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Accessing Model Luminosities Passband luminosities at t0@system per-star (including following all coupling logic) can be computed and exposed on the fly by calling compute_pblums.
print(b.compute_pblums())
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
By default this exposes 'pblum' and 'pblum_ext' for all component-dataset pairs in the form of a dictionary. Alternatively, you can pass a label or list of labels to component and/or dataset.
print(b.compute_pblums(dataset='lc01', component='primary'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
For more options, see the b.compute_pblums API docs. Note that this same logic is applied (at t0) to initialize all passband luminosities within the backend, so there is no need to call compute_pblums before run_compute. In order to access passband luminosities at times other than t0, you can add a mesh dataset and req...
b.add_dataset('mesh', times=np.linspace(0,1,5), dataset='mesh01', columns=['areas', 'pblum_ext@lc01', 'ldint@lc01', 'ptfarea@lc01', 'abs_normal_intensities@lc01', 'normal_intensities@lc01']) b.run_compute()
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Since the luminosities are passband-dependent, they are stored with the same dataset as the light curve (or RV), but with the mesh method, and are available at each of the times at which a mesh was stored.
print(b.filter(qualifier='pblum_ext', context='model').twigs)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Now let's compare the value of the synthetic luminosities to those of the input pblum
t0 = b.get_value('t0@system') print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model')) print(b.get_value('pblum@primary@dataset')) print(b.compute_pblums(component='primary', dataset='lc01'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
In this case, since our two stars are identical, the synthetic luminosity of the secondary star should be the same as the primary (and the same as pblum@primary).
print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model')) print(b.get_value(qualifier='pblum_ext', time=t0, component='secondary', kind='mesh', context='model'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
However, if we change the temperature of the secondary star again, since the pblums are coupled, we'd expect the synthetic luminosity of the primary to remain fixed but the secondary to decrease.
b['teff@secondary@component'] = 3000 print(b.compute_pblums(dataset='lc01')) b.run_compute() print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model')) print(b.get_value(qualifier='pblum_ext', time=t0, component='secondary', kind='mesh', context='model'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
And lastly, if we re-enable irradiation, we'll see that the extrinsic luminosities do not match the prescribed value of pblum (an intrinsic luminosity).
print(b['ld_mode']) print(b['atm']) b.run_compute(irrad_method='horvat') print(b.get_value(qualifier='pblum_ext', time=t0, component='primary', kind='mesh', context='model')) print(b.get_value('pblum@primary@dataset')) print(b.compute_pblums(dataset='lc01', irrad_method='horvat'))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Now, we'll just undo our changes before continuing
b.set_value_all('teff@component', 6000)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Role of Pblum Let's now look at the intensities in the mesh to see how they're being scaled under-the-hood. First we'll recompute our model with the equal temperatures and irradiation disabled (to ignore the difference between pblum and pblum_ext).
b.run_compute() areas = b.get_value(qualifier='areas', dataset='mesh01', time=t0, component='primary', unit='m^2') ldint = b.get_value(qualifier='ldint', component='primary', time=t0) ptfarea = b.get_value(qualifier='ptfarea', component='primary', time=t0) abs_normal_intensities = b.get_value(qualifier='abs_normal_in...
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
'abs_normal_intensities' are the intensities per triangle in absolute units, i.e. W/m^3.
print(np.median(abs_normal_intensities))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
The values of 'normal_intensities', however, are significantly samller (in this case). These are the intensities in relative units which will eventually be integrated to give us flux for a light curve.
print(np.median(normal_intensities))
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
'normal_intensities' are scaled from 'abs_normal_intensities' so that the computed luminosity matches the prescribed luminosity (pblum). Here we compute the luminosity by summing over each triangle's intensity in the normal direction, and multiply it by pi to account for blackbody intensity emitted in all directions in...
pblum = b.get_value(qualifier='pblum', component='primary', context='dataset') print(np.sum(normal_intensities * ldint * np.pi * areas) * ptfarea, pblum)
2.3/tutorials/pblum.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Seems that Linear regression model performed very poorly. Most likely it is because model finds a lot of collinearity in the data due to the categorical columns. Test lasso, which is more robust against multi collinearity.
lasso = Lasso(random_state=1, max_iter=10000) lasso.fit(X_train_std, y_train) rmse(y_test, lasso.predict(X_test_std))
Scikit - 21 Kaggle House price prediction (regression).ipynb
abulbasar/machine-learning
apache-2.0
This rmse score seems reasonable. Find cross validation scores.
scores = cross_val_score(cv=10, estimator = lasso, scoring="neg_mean_squared_error", X=X_train_std, y = y_train) scores = np.sqrt(-scores) scores from sklearn import linear_model from sklearn import metrics from sklearn import tree from sklearn import ensemble from sklearn import neighbors import xgboost as xgb rs =...
Scikit - 21 Kaggle House price prediction (regression).ipynb
abulbasar/machine-learning
apache-2.0
Repeated measures ANOVA on source data with spatio-temporal clustering This example illustrates how to make use of the clustering functions for arbitrary, self-defined contrasts beyond standard t-tests. In this case we will tests if the differences in evoked responses between stimulation modality (visual VS auditory) d...
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Denis Engemannn <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn import matplotlib.pyplot as plt import mne from mne.stat...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Set parameters
data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' subjects_dir = data_path + '/subjects' src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif' tmin = -0.2 tmax = 0.3 # Use a low...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Read epochs for all channels, removing a bad one
raw.info['bads'] += ['MEG 2443'] picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads') # we'll load all four conditions that make up the 'two ways' of our ANOVA event_id = dict(l_aud=1, r_aud=2, l_vis=3, r_vis=4) reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6) epochs = mne.Epochs(raw, events, eve...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Transform to source space
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE, sLORETA, or eLORETA) inverse_operator = read_inverse_operator(fname_inv) # we'll only use one hemisphere to speed up this example # instead of a second ver...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Transform to common cortical space Normally you would read in estimates across several subjects and morph them to the same cortical space (e.g. fsaverage). For example purposes, we will simulate this by just having each "subject" have the same response (just noisy in source space) here. We'll only consider the left hem...
n_vertices_sample, n_times = conditions[0].lh_data.shape n_subjects = 7 print('Simulating data for %d subjects.' % n_subjects) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X = randn(n_vertices_sample, n_times, n_subjects, 4) * 10 for ii, condition in enumerate(conditions): X[:, :,...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
It's a good idea to spatially smooth the data, and for visualization purposes, let's morph these to fsaverage, which is a grade 5 ICO source space with vertices 0:10242 for each hemisphere. Usually you'd have to morph each subject's data separately, but here since all estimates are on 'sample' we can use one morph matr...
# Read the source space we are morphing to (just left hemisphere) src = mne.read_source_spaces(src_fname) fsave_vertices = [src[0]['vertno'], []] morph_mat = mne.compute_source_morph( src=inverse_operator['src'], subject_to='fsaverage', spacing=fsave_vertices, subjects_dir=subjects_dir, smooth=20).morph_mat mor...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Now we need to prepare the group matrix for the ANOVA statistic. To make the clustering function work correctly with the ANOVA function X needs to be a list of multi-dimensional arrays (one per condition) of shape: samples (subjects) x time x space. First we permute dimensions, then split the array into a list of condi...
X = np.transpose(X, [2, 1, 0, 3]) # X = [np.squeeze(x) for x in np.split(X, 4, axis=-1)]
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Prepare function for arbitrary contrast As our ANOVA function is a multi-purpose tool we need to apply a few modifications to integrate it with the clustering function. This includes reshaping data, setting default arguments and processing the return values. For this reason we'll write a tiny dummy function. We will te...
factor_levels = [2, 2]
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Finally we will pick the interaction effect by passing 'A:B'. (this notation is borrowed from the R formula language). As an aside, note that in this particular example, we cannot use the A*B notation which return both the main and the interaction effect. The reason is that the clustering function expects stat_fun to r...
effects = 'A:B' # Tell the ANOVA not to compute p-values which we don't need for clustering return_pvals = False # a few more convenient bindings n_times = X[0].shape[1] n_conditions = 4
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
A stat_fun must deal with a variable number of input arguments. Inside the clustering function each condition will be passed as flattened array, necessitated by the clustering procedure. The ANOVA however expects an input array of dimensions: subjects X conditions X observations (optional). The following function catch...
def stat_fun(*args): # get f-values only. return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels, effects=effects, return_pvals=return_pvals)[0]
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute clustering statistic To use an algorithm optimized for spatio-temporal clustering, we just pass the spatial connectivity matrix (instead of spatio-temporal).
# as we only have one hemisphere we need only need half the connectivity print('Computing connectivity.') connectivity = mne.spatial_src_connectivity(src[:1]) # Now let's actually do the clustering. Please relax, on a small # notebook and one single thread only this will take a couple of minutes ... pthresh = 0....
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Visualize the clusters
print('Visualizing clusters.') # Now let's build a convenient representation of each cluster, where each # cluster becomes a "time point" in the SourceEstimate stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep, vertices=fsave_vertices, ...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Finally, let's investigate interaction effect by reconstructing the time courses:
inds_t, inds_v = [(clusters[cluster_ind]) for ii, cluster_ind in enumerate(good_cluster_inds)][0] # first cluster times = np.arange(X[0].shape[1]) * tstep * 1e3 plt.figure() colors = ['y', 'b', 'g', 'purple'] event_ids = ['l_aud', 'r_aud', 'l_vis', 'r_vis'] for ii, (condition, color, eve_id) in en...
0.20/_downloads/da7833d7ecb983c452e4eef48095435a/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Empecemos echando un ojo a la función del rotor, para ver qué vamos a necesitar y con qué parámetros vamos a trabajar.
help(calcular_rotor)
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Podemos trazar unas cuantas curvas para observar qué pinta va a tener lo que saquemos. Por ejemplo, cómo cambian las características de la hélice dependiendo de la velocidad de vuelo, para una hélice de ejemplo que gira a uyna velocidad dada.
vel = np.linspace(0, 30, 100) efic = np.zeros_like(vel) T = np.zeros_like(vel) P = np.zeros_like(vel) mach = np.zeros_like(vel) for i in range(len(vel)): T[i], P[i], efic[i], mach[i] = calcular_rotor(130, vel[i], 0.5, 3) plt.plot(vel, T) plt.title('Tracción de la hélice') plt.plot(vel, P) plt.title('Potencia cons...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Definiendo el genoma Definamos un individuo genérico: Cada individuo será un posible diseño del rotor, con unas características determinadas.
class Individual (object): def __init__(self, genome): self.genome = genome self.traits = {} self.performances = {} self.fitness = 0
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Nuestro rotor depende de varios parámetros, pero en general, buscaremos optimizar el valor de unos, mateniendo un valor controlado de otros. Por ejemplo, la velocidad de avance y la altitud normalmente las impondremos, ya que querremos optimizar para una velocidad y altura de vuelos dadas. En nuestro algoritmo, usaremo...
15 * np.pi / 180
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
A continuación crearemos un diccionario de genes. En él iremos almacenando los nombres de los parámetros y la cantidad de bits que usaremos para definirlos. Cuantos más bits, más resolución Ej: 1 bit : 2 valores, 2 bit : 4 valores, 10 bit : 1024 valores
#Completa este diccionario con las variables que hayas elegido y los bits que usarás dict_genes = { 'omega' : 10, 'R': 10, 'b': 2 }
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ahora, crearemos una función que rellene estos genomas con datos aleatorios:
def generate_genome (dict_genes): #Calculamos el número total de bits con un bucle que recorra el diccionario n_bits = ? #Generamos un array aletorio de 1 y 0 de esa longitud con numpy genome = np.random.randint(0, 2, nbits) #Transformamos el array en una lista antes de devolverl...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Trabajando con el individuo Ahora necesitamos una función que transforme esos genes a valores con sentido. Cada gen es un número binario cuyo valor estará entre 0 y 2 ^ n, siendo n el número de bits que hayamos escogido. Estas variables traducidas las guardaremos en otro diccionario, ya con su valor. Estos genes no est...
def calculate_traits (individual, dict_genes): genome = individual.genome integer_temporal_list = [] for gen in dict_genes: #Recorremos el diccionario de genes para ir traduciendo del binario ??? #Buscamos los bits que se corresponden al bit en cuestión ...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
El siguiente paso es usar estos traits(parámetros) para calcular las performances (características o desempeños) del motor. Aquí es donde entra el modelo del motor propiamente dicho.
def calculate_performances (individual): dict_traits = individual.traits #Nuestras circunstancias las podemos imponer aquí, o irlas pasando como argumento a la función h = 2000 #Altitud de vuelo en metros vz = 70 #velocidad de avance en m/s, unos 250 km/h #Extraemos los traits del diccion...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Comprobemos si todo funciona!
individuo = Individual(generate_genome(dict_genes)) calculate_traits(individuo, dict_genes) calculate_performances(individuo) print(individuo.traits) print(individuo.performances)
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
El último paso que tenemos que realizar sobre el individuo es uno de los más críticos: Transformar las performances en un valor único (fitness) que con exprese cómo de bueno es con respecto al objetivo de optimización. La función de fitness puede ser función de parámetros(traits) y performances, dependiendo de qué quer...
def calculate_fitness (individual): dict_traits = individuo.traits dict_performances = individuo.performances fitness = ????? #Be Creative! individual.fitness = fitness
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ya tenemos terminado todo lo que necesitamos a nivel de individuo! Que comiencen los Juegos! Es hora de trabajar a nivel de algoritmo, y para ello, lo primero es crear una sociedad compuesta de individuos aleatorios. Definamos una función para ello.
def immigration (society, target_population, dict_genes): while len(society) < target_population: new_individual = Individual (generate_genome (dict_genes)) # Generamos un individuo aleatorio calculate_traits (new_individual, dict_genes) # Calculamos sus traits calculate_perfor...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ahora podemos crear nuestra sociedad:
society = [] immigration (society, 12, dict_genes) #12 por ejemplo, pueden ser los que sean #Veamos qué pinta tienen los genes de la población plt.matshow([individual.genome for individual in society], cmap=plt.cm.gray)
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ya tenemos nuestra pequeña sociedad, aumentémosla un poco más mezclando entre sí a los ciudadanos con mejores fitness! Vamos a extender nuestra población mezclando los genomas de otros individuos. Los individuos con mejor fitness es más probable que se reproduzcan. Además, en los nuevos individuos produciremos ligeras ...
#This function was taken from Eli Bendersky's website #It returns an index of a list called "weights", #where the content of each element in "weights" is the probability of this index to be returned. #For this function to be as fast as possible we need to pass it a list of weights in descending order. def weighted_cho...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ahora que tenemos una sociedad extensa, es el momento de que actúe la selección "natural": Eliminaremos de la sociedad a los individuos con peor fitness hasta llegar a una población objetivo.
def tournament(society, target_population): while len(society) > target_population: fitness_list = [individual.fitness for individual in society] society.pop(fitness_list.index(min(fitness_list)))
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
Ya tenemos nuestro algoritmo prácticamente terminado!
society = [] fitness_max = [] for generation in range(30): immigration (society, 100, dict_genes) #Añade individuos aleatorios a la sociedad hasta tener 100 fitness_max += [max([individual.fitness for individual in society])] tournament (society, 15) #Los hace competir hasta que quedan 15 cro...
Ejercicios/Optimizacion de rotor/Optimizacion con algoritmo genetico.ipynb
AeroPython/Taller-PyConEs-2015
mit
2. One argument functions.... The syntax: {function name} ({argument}) "len" is a Python built-in function. Let's call it on a few strings and see if you can figure out what it does.
print ( len("a") ) print ( len("aa") ) print ( len("aaa") )
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
'len' is short for length. When you call it returns how big the object is, in the case of strings, that’s how many characters the string contains. Thus len(“12345”) returns 5. 3. Functions with Multiple Arguments Functions that take multiple arguments can be further defined into those that require exactly n arguments ...
# defining the function... def multiply(a, b): return a * b # remember '*' is multiplication! multiply(10, 25) # <-- calling the function with two arguments, 10 and 25
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
What happens when you give such a function too few/too many arguments? Well, you get an error:
multiply(2,3,4) multiply(1)
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
Take care to note that the error messages you get are actually rather insightful, Python is telling you what the problem is! Functions that take an aribitary number of arguments Now, the syntax for a function that takes an arbitrary number of arguments is the same as the above, you just separate the values by a comma a...
print("hello") # calling print with one arguement print("hello", "world") # two arguments print() # calling print with zero arguments returns an empty line. print("a", "b", "c", "d", "e", "f", "g") # seven arguments
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
4. Functions with optional arguments... If a particular function argument is optional is will have two parts, a 'keyword' and a 'default value'. The syntax: {keyword} = {value} The 'default value' is what happens when we don't change anything, and obviously that is the bit we may want to change. If you do give a func...
print("a", "b", "c", "d", "e", "f", "g") # Notice 'sep' is not defined here. Thus the default value " " is used. print("a", "b", "c", "d", "e", "f", "g", sep="") # no spaces 'abc' print("a", "b", "c", "d", "e", "f", "g", sep="__") # double underscore, 'a__b__c' print("a", "b", "c", "d", "e", "f", "g", ...
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
In later lectures I'll show you how to build your own functions (and why you would want to), but the purpose of this lecture was to simply get you used to seeing function calls. Trust me when I say understanding this stuff is a really useful skill to have moving forward. Homework In the cell below there is a function c...
def call_me(a, f, d, b="", c="cheese", e=False): if e == True: return "{} and {} went to the {}{} {}".format(a, b, c, d, f) else: return "YOU SHALL NOT PASS" # Your Code goes here... call_me(?, ?, ?, ?, ?)
A Beginners Guide to Python/08. Calling Functions.ipynb
fluffy-hamster/A-Beginners-Guide-to-Python
mit
0. Perform a straight forward query using the STOQS data model. Collect all the sea_water_temperature and sea_water_salinity data into dictionaries keyed by platform name. This is to examine the landscape of data we are querying.
# To make sure we collect temperatures and salinities that are properly associated # we will first find all the Platforms that have T & S and then from each Measurement # from the Platform collect the temperatures and salinities into lists for plotting. # Assume that Platforms that have sea_water_salinity also have sea...
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
Approach 1. Use the same kind of self-join query used for selecting data for Parameter-Parameter plots. A sample SQL statement was copied from the STOQS UI and then modified to select sea_water_temperature and sea_water_salinity from all platforms.
sql_multp = '''SELECT DISTINCT stoqs_platform.name, stoqs_instantpoint.timevalue, stoqs_measurement.depth, mp_salt.datavalue AS salt, mp_temp.datavalue AS temp FROM stoqs_measuredparameter INNER JOIN stoqs_measurement ON (stoqs_measuredpar...
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
This approach could be used in a general way to extract all Parameters for each Platform by dynamically generating the SQL (with dozens more self joins) and executing it. We do need more scalable methods than .read_sql_query() and .to_parquet(), which need to read and write all the data in to and out of allocated rando...
# It takes about 5 minutes to read in 0.17 million dorado CSV rows and convert using trimSTOQS ##! time wget https://stoqs.mbari.org/stoqs_canon_october2020/api/measuredparameter.csv?measurement__instantpoint__activity__platform__name=dorado \ ## -q -O - | /srv/stoqs/contrib/trimSTOQS/trimSTOQS parameter__name --sep...
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
The advantage of this approach is that all parameters get transformed into the columns we want. The disadvantage is that it takes a long time to extract the data in CSV format. Approach 1 reads at a rate of about 30,000 rows/sec, approach 2 reads at a rate of 1000 rows/sec - orders of magnitude slower. 3. Do a direct ...
# Base query that's similar to the one behind the api/measuredparameter.csv request sql_base = '''SELECT stoqs_platform.name as platform, stoqs_activity.name as activity__name, stoqs_instantpoint.timevalue, stoqs_measurement.depth, ST_X(stoqs_measurement.geom) as longitude, ST_Y(stoqs_measurement.geom) a...
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
The syntax of crosstab() is arcane and it will take some work to figure out a way to preserve datetime objects as they are read into a DataFrame. It's likely that performing a pivot on the data closer to the database will be more performant than say doing it after reading records into a DataFrame. Approach 4. Use Pand...
# Identify the columns used as the index for the pivot context = ['platform', 'timevalue', 'depth', 'latitude', 'longitude'] %time df4 = df3a.pivot_table(index=context, columns='name', values='datavalue') print(df4.shape) df4.head()
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
This approach looks promising. Some advantages: The SQL query is a simple inner join of the tables - similar to that used for MeasuredParameter Data Access No complicated self joins are needed It will work for any Parameter names from any platforms Missing values are preserved as None or NaN Pandas pivot_table() metho...
if do_plots: # See: https://datashader.org/getting_started/Pipeline.html import holoviews as hv from holoviews.operation.datashader import datashade hv.extension("bokeh") pts1 = hv.Points(df1, kdims=['salt', 'temp']) pts2 = hv.Points(df2, kdims=['PSAL (0.001)', 'TEMP (Celsius)']) pts4a = hv....
stoqs/contrib/notebooks/select_data_in_columns_for_data_science.ipynb
MBARIMike/stoqs
gpl-3.0
http://networkx.github.io/documentation/latest/install.html pip install networkx to install networkx into your python modules pip install networkx --upgrade to upgrade you previously installed version You may have to restart your ipython engine to pick up the new module Test your installation by running the new box l...
import networkx as nx G1 = nx.Graph() G1.add_nodes_from(['A','B','C','D','E','F','G']) G1.nodes() G1.add_edges_from([('A','B'),('A','C')]) G1.add_edges_from([('B','C'),('B','D')]) G1.add_edges_from([('D','E'),('D','F'),('D','G')]) G1.add_edges_from([('E','F')]) G1.add_edges_from([('F','G')]) G1.number_of_edges() ...
Lectures/Lecture 10 - Graph Algorithms/Python Graphs - networkx intro .ipynb
pschragger/big-data-python-class
mit
Let's play with some algorithms in class: https://networkx.github.io/documentation/latest/reference/algorithms.html Social Graph analysis algorithms Betweenness: https://networkx.github.io/documentation/latest/reference/algorithms.centrality.html#betweenness EigenVector centrality https://networkx.github.io/documentati...
#Enumeration of all cliques list(nx.enumerate_all_cliques(G1)) list(nx.cliques_containing_node(G1,'A')) list(nx.cliques_containing_node(G1,'D'))
Lectures/Lecture 10 - Graph Algorithms/Python Graphs - networkx intro .ipynb
pschragger/big-data-python-class
mit
Run Provide the run information: * run id * run metalink containing the 3 by 3 kernel extractions * participant
run_id = '0000000-150625115710650-oozie-oozi-W' run_meta = 'http://sb-10-16-10-55.dev.terradue.int:50075/streamFile/ciop/run/participant-a/0000000-150625115710650-oozie-oozi-W/results.metalink?' participant = 'participant-a'
evaluation-participant-a.ipynb
ocean-color-ac-challenge/evaluate-pearson
apache-2.0
Define all imports in a single cell
import glob import pandas as pd from scipy.stats.stats import pearsonr import numpy import math
evaluation-participant-a.ipynb
ocean-color-ac-challenge/evaluate-pearson
apache-2.0
Manage run results Download the results and aggregate them in a single Pandas dataframe
!curl $run_meta | aria2c -d $participant -M - path = participant # use your path allFiles = glob.glob(path + "/*.txt") frame = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) list_.append(df) frame = pd.concat(list_) len(frame.index)
evaluation-participant-a.ipynb
ocean-color-ac-challenge/evaluate-pearson
apache-2.0
Number of points extracted from MERIS level 2 products Calculate Pearson For all three sites, AAOT, BOUSSOLE and MOBY, calculate the Pearson factor for each band. Note AAOT does not have measurements for band @510 AAOT site
insitu_path = './insitu/AAOT.csv' insitu = pd.read_csv(insitu_path) frame_full = pd.DataFrame.merge(frame.query('Name == "AAOT"'), insitu, how='inner', on = ['Date', 'ORBIT']) frame_xxx= frame_full[['reflec_1_mean', 'rho_wn_IS_412']].dropna() r_aaot_412 = pearsonr(frame_xxx.ix[:,0], frame_xxx.ix[:,1])[0] print(str(l...
evaluation-participant-a.ipynb
ocean-color-ac-challenge/evaluate-pearson
apache-2.0
Compare Spectral Clustering against kMeans using Similarity As there is no ground truth, the criteria used to evaluate clusters produced using Spectral and kmeans is the silhouette coefficient. From the results obtained, it can be appreaciated that Spectral Clustering requires 6 clusters to have the silhouette score si...
#Compare from a silhouette_score perspective kmeans against Spectral Clustering range_n_clusters = np.arange(10)+2 for n_clusters in range_n_clusters: # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clusters # Initi...
Challenge+Boston+marathon.ipynb
borja876/Thinkful-DataScience-Borja
mit
the optimal number of kmeans will be determined using the elbow method. Once the kmeans number of clusters is set, the number of clusters using spectral clustering will be used so that it equals the silhouette score obtained in the first case. K-Means
#Use the elbow method to determine the number of clusters # k-means determine k distortions = [] K = range(1,10) for k in K: kmeanModel = KMeans(n_clusters=k).fit(X_tr) kmeanModel.fit(X_tr) distortions.append(sum(np.min(cdist(X_tr, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X_tr.shape[0]) # Plo...
Challenge+Boston+marathon.ipynb
borja876/Thinkful-DataScience-Borja
mit
The elbow method shows that the optimal number of clusters to be used in the kmeans method is 3, considering the euclidean distance between cluster centers. From an analytical perspective, the inertia functions shows the same results: 3 clusters were the difference between the results obtained by the inertia function a...
#Evaluate the best number of clusters for i in range(1,10): km = KMeans(n_clusters=i, init='k-means++', n_init=10).fit(X_tr_std) print (i, km.inertia_) #Cluster the data kmeans = KMeans(n_clusters=3, init='k-means++', n_init=10).fit(X_tr_std) labels = kmeans.labels_ #Glue back to original data X_tr['clusters'] = la...
Challenge+Boston+marathon.ipynb
borja876/Thinkful-DataScience-Borja
mit
Spectral Clustering
# We know we're looking for 6 clusters from the comparison with the kmeans. n_clusters=6 # Declare and fit the model. sc = SpectralClustering(n_clusters=n_clusters).fit(X_tr_std) # Extract cluster assignments for each data point. labels = sc.labels_ #Glue back to original data X_tr['clusters'] = labels X_tr['Gender'...
Challenge+Boston+marathon.ipynb
borja876/Thinkful-DataScience-Borja
mit
Mean Shift
# Here we set the bandwidth. This function automatically derives a bandwidth # number based on an inspection of the distances among points in the data. bandwidth = estimate_bandwidth(X_tr_std, quantile=0.9) # Declare and fit the model. ms = MeanShift(bandwidth=bandwidth, bin_seeding=True).fit(X_tr_std) # Extract clus...
Challenge+Boston+marathon.ipynb
borja876/Thinkful-DataScience-Borja
mit
In any software development, one of the most important tools are revision control software (RCS). They are used in virtually all software development and in all environments, by everyone and everywhere (no kidding!) RCS can used on almost any digital content, so it is not only restricted to software development, and is...
# create a new git repository called gitdemo: !git init gitdemo
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
If we want to fork or clone an existing repository, we can use the command git clone repository:
!git clone https://github.com/qutip/qutip
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
Git clone can take a URL to a public repository, like above, or a path to a local directory:
!git clone gitdemo gitdemo2
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
We can also clone private repositories over secure protocols such as SSH: $ git clone ssh://myserver.com/myrepository Status Using the command git status we get a summary of the current status of the working directory. It shows if we have modified, added or removed files.
!git status
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
In this case, only the current ipython notebook has been added. It is listed as an untracked file, and is therefore not in the repository yet. Adding files and committing changes To add a new file to the repository, we first create the file and then use the git add filename command:
%%file README A file with information about the gitdemo repository. !git status
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
After having added the file README, the command git status list it as an untracked file.
!git add README !git status
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
Now that it has been added, it is listed as a new file that has not yet been commited to the repository.
!git commit -m "Added a README file" README !git add Lecture-7-Revision-Control-Software.ipynb !git commit -m "added notebook file" Lecture-7-Revision-Control-Software.ipynb !git status
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0
After committing the change to the repository from the local working directory, git status again reports that working directory is clean. Commiting changes When files that is tracked by GIT are changed, they are listed as modified by git status:
%%file README A file with information about the gitdemo repository. A new line. !git status
material/sub/jrjohansson/Lecture-7-Revision-Control-Software.ipynb
geography-munich/sciprog
apache-2.0