markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
For interactive use, formulas can be entered as text strings and passed to the spot.formula constructor. | f = spot.formula('p1 U p2 R (p3 & !p4)')
f
g = spot.formula('{a;b*;c[+]}<>->GFb'); g | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
By default the parser recognizes an infix syntax, but when this fails, it tries to read the formula with the LBT syntax: | h = spot.formula('& | a b c'); h | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
By default, a formula object is presented using mathjax as above.
When a formula is converted to string you get Spot's syntax by default: | str(f) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
If you prefer to print the string in another syntax, you may use the to_str() method, with an argument that indicates the output format to use. The latex format assumes that you will the define macros such as \U, \R to render all operators as you wish. On the otherhand, the sclatex (with sc for self-contained) format... | for i in ['spot', 'spin', 'lbt', 'wring', 'utf8', 'latex', 'sclatex']:
print("%-10s%s" % (i, f.to_str(i))) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
Formulas output via format() can also use some convenient shorthand to select the syntax: | print("""\
Spin: {0:s}
Spin+parentheses: {0:sp}
Spot (default): {0}
Spot+shell quotes: {0:q}
LBT, right aligned: {0:l:~>40}
LBT, no M/W/R: {0:[MWR]l}""".format(f)) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
The specifiers that can be used with format are documented as follows: | help(spot.formula.__format__) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
A spot.formula object has a number of built-in predicates whose value have been computed when the formula was constructed. For instance you can check whether a formula is in negative normal form using is_in_nenoform(), and you can make sure it is an LTL formula (i.e. not a PSL formula) using is_ltl_formula(): | f.is_in_nenoform() and f.is_ltl_formula()
g.is_ltl_formula() | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
Similarly, is_syntactic_stutter_invariant() tells wether the structure of the formula guarranties it to be stutter invariant. For LTL formula, this means the X operator should not be used. For PSL formula, this function capture all formulas built using the siPSL grammar. | f.is_syntactic_stutter_invariant()
spot.formula('{a[*];b}<>->c').is_syntactic_stutter_invariant()
spot.formula('{a[+];b[*]}<>->d').is_syntactic_stutter_invariant() | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
spot.relabel renames the atomic propositions that occur in a formula, using either letters, or numbered propositions: | gf = spot.formula('(GF_foo_) && "a > b" && "proc[2]@init"'); gf
spot.relabel(gf, spot.Abc)
spot.relabel(gf, spot.Pnn) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
The AST of any formula can be displayed with show_ast(). Despite the name, this is not a tree but a DAG, because identical subtrees are merged. Binary operators have their left and right operands denoted with L and R, while non-commutative n-ary operators have their operands numbered. | print(g); g.show_ast() | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
Any formula can also be classified in the temporal hierarchy of Manna & Pnueli | g.show_mp_hierarchy()
spot.mp_class(g, 'v')
f = spot.formula('F(a & X(!a & b))'); f | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
Etessami's rule for removing X (valid only in stutter-invariant formulas) | spot.remove_x(f) | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
Removing abbreviated operators | f = spot.formula("G(a xor b) -> F(a <-> b)")
spot.unabbreviate(f, "GF^")
spot.unabbreviate(f, "GF^ei") | tests/python/formulas.ipynb | hich28/mytesttxx | gpl-3.0 |
What We Expect Our Simulation Data Will Look Like:
The above code should generate a 100x100x100 volume and populate it with various, non-intersectting pointsets (representing foreground synpases). When the foreground is generated, the volume will then be introduced to random background noise which will fill the rest of... | #displaying the random clusters
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
z, y, x = foreground.nonzero()
ax.scatter(x, y, z, zdir='z', c='r')
plt.title('Random Foreground')
plt.show()
#displaying the noise
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
z, y, x = combinedIm.nonzero()
... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Why Our Simulation is Correct: Real microscopic images of synapses usually contain a majority of background noise and relatively few synapse clusters. As shown above, the generated test volume follows this expectation.
Difficult Simulation
We will now simulate data where our algorithm will not perform well on. We will... | def generateDifficultTestVolume():
#create a test volume
volume = np.zeros((100, 100, 100))
myPointSet = set()
for _ in range(rand(500, 800)):
potentialPointSet = generatePointSet()
#be sure there is no overlap
while len(myPointSet.intersection(potentialPointSet)) > 0:
... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Simulation Analysis
Pseudocode
Inputs: 3D image array that has been processed through plosLib pipeline, raw image file that hasn't been through plosLib
Outputs: List of synapse clusters | ####Pseudocode: Will not run!####
#Step 1 Otsu's Binarization to threshold out background noise intensity to 0.
for(each 2D image slice in 3D plos_image):
threshold_otsu on slice #uses Otsu's Binarization to threshold background noise to 0.
return thresholded_image
#Step 2 Cluster for... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Algorithm Code | from skimage.filters import threshold_otsu
from skimage.measure import label
from cluster import Cluster
import numpy as np
import cv2
import plosLib as pLib
### Step 1: Threshold the image using Otsu Binarization
def otsuVox(argVox):
probVox = np.nan_to_num(argVox)
bianVox = np.zeros_like(probVox)
for zI... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Easy Simulation Analysis
What We Expect
As previously mentioned, we believe the pipeline will work very well on the easy simulation (See Simulation Data: Easy Simulation for explanation).
Generate Easy Simulation Data: See Simulation Data Above.
Pipeline Run on Easy Data | completeClusterMemberList = completePipeline(combinedIm) | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Easy Simulation Results | ### Get Cluster Volumes
def getClusterVolumes(clusterList):
completeClusterVolumes = []
for cluster in clusterList:
completeClusterVolumes.append(cluster.getVolume())
return completeClusterVolumes
import mouseVis as mv
#plotting results
completeClusterVolumes = getClusterVolumes(completeClusterMem... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Performance Metrics:
We will be judging our algorithm's performance through two metrics: average cluster volume and cluster density per volume. This is based off of the 2 parameters we used to generate the test volume (see Simulation Data: Easy Simulation).
If our algorithm was successful, the average volume of detecte... | #test stats
# get actual cluster volumes from foreground (for 'Expected' values)
def getForegroundClusterVols(foreground):
foregroundClusterList = connectedComponents(foreground)
del foregroundClusterList[0] #background cluster
foregroundClusterVols = []
for cluster in foregroundClusterList:
fo... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Quantify Performance for Easy Simulation | foregroundClusterVols = getForegroundClusterVols(foreground)
getAverageMetric(completeClusterVolumes, foregroundClusterVols)
getDensityMetric(completeClusterVolumes, foregroundClusterVols) | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
As shown above, our connectLib pipeline worked extremely well on the easy simulation. The small difference between the actual and expected values come from the generated synapse point sets. Foreground synapses can potentially be adjacent to each other in the test volume. Connected Components will label the multiple, co... | completeClusterMemberListHard = completePipeline(combinedImHard)
print len(completeClusterMemberListHard) | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Difficult Simulation Results: | #Plos Pipeline Results
plosOut = pLib.pipeline(combinedImHard)
#Otsu's Binarization Thresholding
bianOut = otsuVox(plosOut)
#Connected Components
connectList = connectedComponents(bianOut)
#get total volume for hard simulation clusters
totalClusterHard = []
for cluster in connectList:
totalClusterHard.append(cluste... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Performance Metrics
See Easy Simulation Analysis: Performance Metrics.
Quantify Performance for Difficult Simulation | foregroundClusterVolsHard = getForegroundClusterVols(foregroundHard)
getAverageMetric(completeClusterVolumesHard, foregroundClusterVolsHard)
getDensityMetric(completeClusterVolumesHard, foregroundClusterVolsHard) | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
As predicted, the foreground and background was combined into one cluster through the connectLib Pipeline (see Results). This large cluster does not coregister with any of the original foreground clusters. Clearly, our pipeline performed very poorly on the difficult simulation as zero clusters were actually detected. T... | easySimulationVolumes = []
hardSimulationVolumes = []
for i in range(10):
#Easy Simulation
randIm = generateTestVolume()
foreground = randIm[0]
combinedIm = randIm[1]
completeClusterMemberList = completePipeline(combinedIm)
completeClusterVolumes = getClusterVolumes(completeClusterMemberList)
... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Plotting Expected and Average Cluster Volumes for each easy simulation.
Red = Expected Average Volume
Blue = Observed Average Volume | #separate expected and actual values into separate indices
esv = [list(t) for t in zip(*easySimulationVolumes)]
#outlier
del esv[0][6]
del esv [1][6]
fig = plt.figure()
plt.title('Easy Simulation: Average and Expected Cluster Volumes (10 Trials)')
plt.xlabel('Simulation #')
plt.ylabel('Volume (voxels)')
x = np.arange(... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Plotting Expected and Average Cluster Volumes for each difficult simulation. | hsv = [list(t) for t in zip(*hardSimulationVolumes)]
fig = plt.figure()
plt.title('Difficult Simulation: Average and Expected Cluster Volumes (10 Trials)')
plt.xlabel('Simulation #')
plt.ylabel('Volume (voxels)')
x = np.arange(10)
plt.scatter(x, hsv[0], c='r')
plt.scatter(x, hsv[1], c='b')
plt.show() | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Summary of Simulation Analysis
Our difficult and easy simulation data demonstrates how our connectLib pipeline is dependent on how different the background and foreground voxel intensity values are. When the background and foreground are not distinguishable, the connectLib cannot threshold and filter out the background... | import pickle
realData = pickle.load(open('../data/realDataRaw_t0.synth'))
realDataSection = realData[5: 10]
plosDataSection = pLib.pipeline(realDataSection)
mv.generateHist(plosDataSection, bins = 50, title = "Voxel Intensity Distribution after PLOS", xaxis = 'Relative Voxel Intensity', yaxis = 'Frequency') | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Predicting Performance:
Mouse brains have a lot more activity than be portrayed in our simulated data. There are different captured cell types and a wide variation of background/foreground noise. Our Naive Fencing method and Otsu's Binarization could potentially not be enough to produce clean synapse clusters. Because ... | print 'Running'
realClusterList = completePipeline(plosDataSection)
realClusterVols = getClusterVolumes(realClusterList) | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Results | mv.generateHist(realClusterVols, title = 'Cluster Volumes for Easy Simulation', bins = 50, xaxis = 'Volumes', yaxis = 'Relative Frequency')
print realClusterVols
del realClusterVols[0]
mv.generateHist(realClusterVols, title = 'Cluster Volumes for Easy Simulation', axisStart = 0, axisEnd = 200, bins = 25, xaxis = 'Vo... | pipeline_1/background/connectLib_revised.md.ipynb | NeuroDataDesign/pan-synapse | apache-2.0 |
Get acq stats data and clean | # Make a map of AGASC_ID to AGACS 1.7 MAG_ACA. The acq_stats.h5 file has whatever MAG_ACA
# was in place at the time of planning the loads.
# Define new term `red_mag_err` which is used here in place of the
# traditional COLOR1 == 1.5 test.
with tables.open_file(str(SKA / 'data' / 'agasc' / 'miniagasc_1p7.h5'), 'r') ... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Get ASVT data and make it look more like acq stats data | peas = Table.read('pea_analysis_results_2018_299_CCD_temp_performance.csv', format='ascii.csv')
peas = asvt_utils.flatten_pea_test_data(peas)
peas = peas[peas['ccd_temp'] > -10.5]
# Version of ASVT PEA data that is more flight-like
fpeas = Table([peas['star_mag'], peas['ccd_temp'], peas['search_box_hw']],
... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Combine flight acqs and ASVT data | data_all = vstack([acqs[acq_ok]['year', 'fail', 'mag_aca', 't_ccd', 'halfwidth', 'quarter',
'color', 'asvt', 'red_mag_err', 'mag_obs'],
fpeas])
data_all.sort('year') | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Compute box probit delta term based on box size | # Adjust probability (in probit space) for box size.
data_all['box_delta'] = get_box_delta(data_all['halfwidth'])
# Put in an ad-hoc penalty on ASVT data that introduces up to a -0.3 shift
# on probit probability. It goes from 0.0 for mag < 10.1 up to 0.3 at mag=10.4.
ok = data_all['asvt']
box_delta_tweak = (data_al... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Model definition | def t_ccd_normed(t_ccd):
return (t_ccd + 8.0) / 8.0
def p_fail(pars,
t_ccd, tc2=None,
box_delta=0, rescale=True, probit=False):
"""
Acquisition probability model
:param pars: p0, p1, p2 (quadratic in t_ccd) and floor (min p_fail)
:param t_ccd: t_ccd (degC) or scaled t_ccd if... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Model fitting functions | def calc_binom_stat(data, model, staterror=None, syserror=None, weight=None, bkg=None):
"""
Calculate log-likelihood for a binomial probability distribution
for a single trial at each point.
Defining p = model, then probability of seeing data == 1 is p and
probability of seeing data == 0 is (1 ... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Plotting and validation | def plot_fails_mag_aca_vs_t_ccd(mag_bins, data_all, year0=2015.0):
ok = (data_all['year'] > year0) & ~data_all['fail'].astype(bool)
da = data_all[ok]
fuzzx = np.random.uniform(-0.3, 0.3, len(da))
fuzzy = np.random.uniform(-0.125, 0.125, len(da))
plt.plot(da['t_ccd'] + fuzzx, da['mag_aca'] + fuzzy, '... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Define magnitude bins for fitting and show data | mag_centers = np.array([6.3, 8.1, 9.1, 9.55, 9.75, 10.0, 10.25, 10.55, 10.75, 11.0])
mag_bins = (mag_centers[1:] + mag_centers[:-1]) / 2
mag_means = np.array([8.0, 9.0, 9.5, 9.75, 10.0, 10.25, 10.5, 10.75])
for m0, m1, mm in zip(mag_bins[:-1], mag_bins[1:], mag_means):
ok = (data_all['asvt'] == False) & (data_all[... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Color != 1.5 fit (this is MOST acq stars) | # fit = fit_sota_model(data_all['color'] == 1.5, ms_disabled=True)
mask_no_1p5 = ((data_all['red_mag_err'] == False) &
(data_all['t_ccd'] > -18) &
(data_all['t_ccd'] < -0.5))
mag0s, mag1s = mag_bins[:-1], mag_bins[1:]
fits = {}
masks = []
for m0, m1 in zip(mag0s, mag1s):
print(m0, m1... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Define model for color=1.5 stars
Post AGASC 1.7, there is inadequate data to independently perform the binned
fitting.
Instead assume a magnitude error distribution which is informed by examining
the observed distribution of dmag = mag_obs - mag_aca (observed - catalog). This
turns out to be well-represented by... | def plot_mag_errs(acqs, red_mag_err):
ok = ((acqs['red_mag_err'] == red_mag_err) &
(acqs['mag_obs'] > 0) &
(acqs['img_func'] == 'star'))
dok = acqs[ok]
dmag = dok['mag_obs'] - dok['mag_aca']
plt.figure(figsize=(14, 4.5))
plt.subplot(1, 3, 1)
plt.plot(dok['mag_aca'], dmag, '... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Define an analytical approximation for distribution with ad-hoc positive tail | # Define parameters / metadata for floor model
FLOOR = {'fit_parvals': fit_parvals,
'mag_bin_centers': mag_bin_centers}
def calc_1p5_mag_err_weights():
x = np.linspace(-2.8, 4, 18)
ly = 3.8 * (1 - np.abs(x) / np.where(x > 0, 4.0, 2.8))
y = 10 ** ly
return x, y / y.sum()
FLOOR['mag_errs_1p... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Global model for arbitrary mag, t_ccd, color, and halfwidth | def floor_model_acq_prob(mag, t_ccd, color=0.6, halfwidth=120, probit=False):
"""
Acquisition probability model
:param mag: Star magnitude(s)
:param t_ccd: CCD temperature(s)
:param color: Star color (compared to 1.5 to decide which p_fail model to use)
:param halfwidth: Search box size (arcsec... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Compare to flight data for halfwidth=120
Selecting only data with halfwidth=120 is a clean, model-independent way to
compare the model to raw flight statistics.
Setup functions to get appropriate data | # NOTE this is in chandra_aca.star_probs as of version 4.27
from scipy.stats import binom
def binom_ppf(k, n, conf, n_sample=1000):
"""
Compute percent point function (inverse of CDF) for binomial, where
the percentage is with respect to the "p" (binomial probability) parameter
not the "k" parameter.
... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Compare model to flight for color != 1.5 stars | def plot_floor_and_flight(color, halfwidth=120):
# This computes probabilities for 120 arcsec boxes, corresponding to raw data
t_ccds = np.linspace(-16, -6, 20)
mag_acas = np.array([9.5, 10.0, 10.25, 10.5, 10.75])
for ii, mag_aca in enumerate(reversed(mag_acas)):
flight_probs = 1 - acq_success... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Compare model to flight for color = 1.5 stars | plt.figure(figsize=(13, 4))
plt.subplot(1, 2, 1)
for m0, m1, color in [(9, 9.5, 'C0'), (9.5, 10, 'C1'), (10, 10.3, 'C2'), (10.3, 10.7, 'C3')]:
ok = data_all['red_mag_err'] & mag_filter(m0, m1) & t_ccd_filter(-16, -10)
data = data_all[ok]
data['model'] = floor_model_acq_prob(data['mag_aca'], data['t_ccd'], c... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Write model as a 3-d grid to a gzipped FITS file | def write_model_as_fits(model_name,
comment=None,
mag0=5, mag1=12, n_mag=141, # 0.05 mag spacing
t_ccd0=-16, t_ccd1=-1, n_t_ccd=31, # 0.5 degC spacing
halfw0=60, halfw1=180, n_halfw=7, # 20 arcsec spacing
... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Generate regression data for chandra_aca
The real testing is done here with a copy of the functions from chandra_aca, but
now generate some regression test data as a smoke test that things are working
on all platforms. | mags = [9, 9.5, 10.5]
t_ccds = [-10, -5]
halfws = [60, 120, 160]
mag, t_ccd, halfw = np.meshgrid(mags, t_ccds, halfws, indexing='ij')
probs = floor_model_acq_prob(mag, t_ccd, halfwidth=halfw, probit=True, color=1.0)
print(repr(probs.round(3).flatten()))
probs = floor_model_acq_prob(mag, t_ccd, halfwidth=halfw, probit... | fit_acq_model-2019-08-binned-poly-binom-floor.ipynb | sot/aca_stats | bsd-3-clause |
Scatter Chart
Scatter Chart Selections
Click a point on the Scatter plot to select it. Now, run the cell below to check the selection. After you've done this, try holding the ctrl (or command key on Mac) and clicking another point. Clicking the background will reset the selection. | x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(20)
y_data = np.random.randn(20)
scatter_chart = Scatter(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc}, colors=['dodgerblue'],
interactions={'click': 'select'},
selected_style={'opacity': 1.0, 'fill': 'Dar... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Alternately, the selected attribute can be directly set on the Python side (try running the cell below): | scatter_chart.selected = [1, 2, 3] | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Scatter Chart Interactions and Tooltips | x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(20)
y_data = np.random.randn(20)
dd = Dropdown(options=['First', 'Second', 'Third', 'Fourth'])
scatter_chart = Scatter(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc}, colors=['dodgerblue'],
names=np.arange(100, 200), names_unique=... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Image
For images, on_element_click returns the location of the mouse click. | i = ImageIpy.from_file(os.path.abspath('../data_files/trees.jpg'))
bqi = Image(image=i, scales={'x': x_sc, 'y': y_sc}, x=(0, 10), y=(-1, 1))
fig_image = Figure(marks=[bqi], axes=[ax_x, ax_y])
fig_image
bqi.on_element_click(print_event) | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Line Chart | # Adding default tooltip to Line Chart
x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(100)
y_data = np.random.randn(3, 100)
def_tt = Tooltip(fields=['name', 'index'], formats=['', '.2f'], labels=['id', 'line_num'])
line_chart = Lines(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc},
... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Bar Chart | # Adding interaction to select bar on click for Bar Chart
x_sc = OrdinalScale()
y_sc = LinearScale()
x_data = np.arange(10)
y_data = np.random.randn(2, 10)
bar_chart = Bars(x=x_data, y=[y_data[0, :].tolist(), y_data[1, :].tolist()], scales= {'x': x_sc, 'y': y_sc},
interactions={'click': 'select'},
... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Histogram | # Adding tooltip for Histogram
x_sc = LinearScale()
y_sc = LinearScale()
sample_data = np.random.randn(100)
def_tt = Tooltip(formats=['', '.2f'], fields=['count', 'midpoint'])
hist = Hist(sample=sample_data, scales= {'sample': x_sc, 'count': y_sc},
tooltip=def_tt, display_legend=True, labels=['... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Pie Chart
Set up a pie chart with click to show the tooltip. | pie_data = np.abs(np.random.randn(10))
sc = ColorScale(scheme='Reds')
tooltip_widget = Tooltip(fields=['size', 'index', 'color'], formats=['0.2f', '', '0.2f'])
pie = Pie(sizes=pie_data, scales={'color': sc}, color=np.random.randn(10),
tooltip=tooltip_widget, interactions = {'click': 'tooltip'}, selected_sty... | examples/Interactions/Mark Interactions.ipynb | SylvainCorlay/bqplot | apache-2.0 |
Select clean 83mKr events
KR83m cuts similar to Adam's note:
https://github.com/XENON1T/FirstResults/blob/master/PositionReconstructionSignalCorrections/S2map/s2-correction-xy-kr83m-fit-in-bins.ipynb
Valid second interaction
Time between S1s in [0.6, 2] $\mu s$
z in [-90, -5] cm | # Get SR1 krypton datasets
dsets = hax.runs.datasets
dsets = dsets[dsets['source__type'] == 'Kr83m']
dsets = dsets[dsets['trigger__events_built'] > 10000] # Want a lot of Kr, not diffusion mode
dsets = hax.runs.tags_selection(dsets, include='sciencerun0')
# Sample ten datasets randomly (with fixed seed, so the anal... | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
Get S1s from these events | from hax.treemakers.peak_treemakers import PeakExtractor
dt = 10 * units.ns
wv_length = pax_config['BasicProperties.SumWaveformProperties']['peak_waveform_length']
waveform_ts = np.arange(-wv_length/2, wv_length/2 + 0.1, dt)
class GetS1s(PeakExtractor):
__version__ = '0.0.1'
uses_arrays = True
# (don't ac... | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
Save to disk
Pandas object array is very memory-ineficient. Takes about 25 MB/dataset to store it in this format (even compressed). If we'd want to extract more than O(10) datasets we'd get into trouble already at the extraction stage.
Least we can do is convert to sensible format (waveform matrix, ordinary dataframe) ... | waveforms = np.vstack(s1s['sum_waveform'].values)
del s1s['sum_waveform']
s1s = pd.DataFrame(s1s.to_records()) | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
Merge with the per-event data (which is useful e.g. for making position-dependent selections) | merged_data = hax.minitrees._merge_minitrees(s1s, data)
del merged_data['index']
np.savez_compressed('sr0_kr_s1s.npz', waveforms=waveforms)
merged_data.to_hdf('sr0_kr_s1s.hdf5', 'data') | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
Quick look | len(s1s)
from pax import units
plt.hist(s1s.left * 10 * units.ns / units.ms, bins=np.linspace(0, 2.5, 100));
plt.yscale('log') | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
S1 is usually at trigger. | plt.hist(s1s.area, bins=np.logspace(0, 3, 100));
plt.axvline(35, color='r')
plt.yscale('log')
plt.xscale('log')
np.sum(s1s['area'] > 35)/len(s1s) | notebooks/extraction/extract_s1s.ipynb | JelleAalbers/xeshape | mit |
How to build a GeoDataFrame
We firstly explore how to do this by using the GeoJSON schema.
See https://gist.github.com/sgillies/2217756 for the "__geo_interface__".
But this basically copies GeoJSON, for which see https://tools.ietf.org/html/rfc7946
It's then as simple as this... | point_features = [{"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": {
"prop0": "value0", "prop1": "value1"
}
}]
point_data = gpd.GeoDataFrame.from_features(point_features)
point_data
point_data.ix[0].geome... | notebooks/Geopandas.ipynb | MatthewDaws/OSMDigest | mit |
Notes
Some things that jumped out at me as I read the GeoJSON spec:
Coordinates are always in the order: longitude, latitude.
A "Polygon" is allowed to contain holes. The "outer" edge should be ordered counter-clockwise, and each "inner" edge (i.e. a "hole") should be clockwise.
If a polygon contains more than one ar... | type(point_data.geometry[0]), type(line_data.geometry[0]), type(data.geometry[0])
import shapely.geometry
pts = shapely.geometry.LineString([shapely.geometry.Point(0,0), shapely.geometry.Point(1,0), shapely.geometry.Point(1,1)])
df = gpd.GeoDataFrame({"geometry": [pts], "key1":["value1"], "key2":["value2"]})
df
df.i... | notebooks/Geopandas.ipynb | MatthewDaws/OSMDigest | mit |
Support in the library | import osmdigest.geometry as geometry
import osmdigest.sqlite as sq
import os
filename = os.path.join("..", "..", "..", "Data", "california-latest.db")
db = sq.OSM_SQLite(filename)
way = db.complete_way(33088737)
series = geometry.geoseries_from_way(way)
series
gpd.GeoDataFrame(series).T.plot()
way = db.complete_wa... | notebooks/Geopandas.ipynb | MatthewDaws/OSMDigest | mit |
For relations
We can build a geo data frame with the raw data from a relation. | relation = db.complete_relation(2866485)
geometry.geodataframe_from_relation(relation)
geometry.geodataframe_from_relation( db.complete_relation(63222) ) | notebooks/Geopandas.ipynb | MatthewDaws/OSMDigest | mit |
Looking at relations
These are harder to compute automatically, because the exact interpretation of the sub-elements depends upon context. However, most relations which have "interesting" geometry (as opposed to giving contextual information on other elements) are of "multi-polygon" type, and can be recognised by the ... | gen = db.relations()
for _ in range(15):
next(gen)
relation = next(gen)
print(relation)
series = geometry.geoseries_from_relation(db.complete_relation(relation))
series
gpd.GeoDataFrame(series).T.plot() | notebooks/Geopandas.ipynb | MatthewDaws/OSMDigest | mit |
3. Enter BigQuery Query To Table Recipe Parameters
Specify a single query and choose legacy or standard mode.
For PLX use user authentication and: SELECT * FROM [plx.google:FULL_TABLE_NAME.all] WHERE...
Every time the query runs it will overwrite the table.
Modify the values below for your use case, can be done multip... | FIELDS = {
'auth_write':'service', # Credentials used for writing data.
'query':'', # SQL with newlines and all.
'dataset':'', # Existing BigQuery dataset.
'table':'', # Table to create from this query.
'legacy':True, # Query type must match source tables.
}
print("Parameters Set To: %s" % FIELDS)
| colabs/bigquery_query.ipynb | google/starthinker | apache-2.0 |
4. Execute BigQuery Query To Table
This does NOT need to be modified unless you are changing the recipe, click play. | from starthinker.util.configuration import execute
from starthinker.util.recipe import json_set_fields
TASKS = [
{
'bigquery':{
'auth':{'field':{'name':'auth_write','kind':'authentication','order':1,'default':'service','description':'Credentials used for writing data.'}},
'from':{
'query':{'f... | colabs/bigquery_query.ipynb | google/starthinker | apache-2.0 |
Then as a list of lines... (just one line) | with open('tmdb_5000_movies.csv','r') as f:
lines = [line for line in f]
lines[0] | three_agd.ipynb | Fifth-Cohort-Awesome/NightThree | mit |
Then as a data frame... (just Avatar) | import pandas as pd
df = pd.read_csv("tmdb_5000_movies.csv")
df.query('id == 19995') | three_agd.ipynb | Fifth-Cohort-Awesome/NightThree | mit |
Goal Two
Right now, the file is in a 'narrow' format. In other words, several interesting bits are collapsed into a single field. Let's attempt to make the data frame a 'wide' format. All the collapsed items expanded horizontally.
References:
https://www.kaggle.com/fabiendaniel/film-recommendation-engine
http://www.jea... | import json
import pandas as pd
import numpy as np
df = pd.read_csv("tmdb_5000_movies.csv")
#convert to json
json_columns = ['genres', 'keywords', 'production_countries',
'production_companies', 'spoken_languages']
for column in json_columns:
df[column] = df[column].apply(json.loads)
def get... | three_agd.ipynb | Fifth-Cohort-Awesome/NightThree | mit |
Goal Three | genres_long_df = pd.melt(genres_arranged_df, id_vars=df.columns, value_vars=get_unique_inner_json("genres"), var_name="genre", value_name="genre_val")
genres_long_df = genres_long_df[genres_long_df['genre_val'] == 1]
genres_long_df.query('title == "Avatar"')
| three_agd.ipynb | Fifth-Cohort-Awesome/NightThree | mit |
2 数据预处理
通过特征提取,我们能得到未经处理的特征,这时的特征可能有以下问题:
不属于同一量纲:即特征的规格不一样,不能够放在一起比较。无量纲化可以解决这一问题。
信息冗余:对于某些定量特征,其包含的有效信息为区间划分,例如学习成绩,假若只关心“及格”或不“及格”,那么需要将定量的考分,转换成“1”和“0”表示及格和未及格。二值化可以解决这一问题。
定性特征不能直接使用:某些机器学习算法和模型只能接受定量特征的输入,那么需要将定性特征转换为定量特征。最简单的方式是为每一种定性值指定一个定量值,但是这种方式过于灵活,增加了调参的工作。通常使用哑编码的方式将定性特征转换为定量特征:假设有N种定性值,则将这一个特征扩展为N种特征... | from sklearn.preprocessing import StandardScaler
# 标准化,返回值为标准化后的数据
StandardScaler().fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.1.2 区间缩放法
区间缩放法的思路有多种,常见的一种为利用两个最值进行缩放,公式表达为:
x' = (x - min) / (max - min)
使用preproccessing库的MinMaxScaler类对数据进行区间缩放的代码如下: | from sklearn.preprocessing import MinMaxScaler
# 区间缩放,返回值为缩放到[0, 1]区间的数据
MinMaxScaler().fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.1.3 标准化与归一化的区别
简单来说,标准化是依照特征矩阵的列处理数据,其通过求z-score的方法,将样本的特征值转换到同一量纲下。归一化是依照特征矩阵的行处理数据,其目的在于样本向量在点乘运算或其他核函数计算相似性时,拥有统一的标准,也就是说都转化为“单位向量”。规则为l2的归一化公式如下:
x' = x / ((sum(x[j] ^ 2)) ^ 0.5)
使用preproccessing库的Normalizer类对数据进行归一化的代码如下: | from sklearn.preprocessing import Normalizer
# 归一化,返回值为归一化后的数据
Normalizer().fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.2 对定量特征二值化
定量特征二值化的核心在于设定一个阈值,大于阈值的赋值为1,小于等于阈值的赋值为0,公式表达如下:
x = 1 if x > threshold else 0
使用preproccessing库的Binarizer类对数据进行二值化的代码如下: | from sklearn.preprocessing import Binarizer
# 二值化,阈值设置为3,返回值 为二值化后的数据
Binarizer(threshold=3).fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.3 对定性特征哑编码
由于IRIS数据集的特征皆为定量特征,故使用其目标值进行哑编码(实际上是不需要的)。使用preproccessing库的OneHotEncoder类对数据进行哑编码的代码如下: | from sklearn.preprocessing import OneHotEncoder
# 哑编码,对数据的目标值,返回值为哑编码后的数据
OneHotEncoder().fit_transform(iris.target.reshape((-1,1))) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.4 缺失值计算
由于IRIS数据集没有缺失值,故对数据集新增一个样本,4个特征均赋值为NaN,表示数据缺失。使用preproccessing库的Imputer类对数据进行缺失值计算的代码如下: | import numpy as np
from sklearn.preprocessing import Imputer
# 缺失值计算,返回值为计算缺失值后的数据
# 参数missing_value为缺失值的表示形式,默认为NaN
# 参数strategy为缺失值的填充方式,默认为mean(均值)
Imputer().fit_transform(\
np.vstack((np.array([np.nan, np.nan, np.nan, np.nan]),iris.data))) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.5 数据变换
常见的数据变换有基于多项式的、基于指数函数的、基于对数函数的。4个特征,度为2的多项式转换公式如下:
(x1',x2',x3',...,xn')
=(1, x1, x2, ..., xn, x1^2, x1*x2, x1*x2*x3, ..., )
使用preproccessing库的PolynomialFeatures类对数据进行多项式转换的代码如下: | from sklearn.preprocessing import PolynomialFeatures
# 多项式转换
# 参数degree为度,默认值为2
PolynomialFeatures().fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
基于单变元函数的数据变换可以使用一个统一的方式完成,使用preproccessing库的FunctionTransformer对数据进行对数函数转换的代码如下: | from sklearn.preprocessing import FunctionTransformer
#自定义转换函数为对数函数的数据变换
#第一个参数是单变元函数
FunctionTransformer(np.log1p).fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
2.6 回顾
类 功能 说明
StandardScaler 无量纲化 标准化,基于特征矩阵的列,将特征值转换至服从标准正态分布
MinMaxScaler 无量纲化 区间缩放,基于最大最小值,将特征值转换到[0, 1]区间上
Normalizer 归一化 基于特征矩阵的行,将样本向量转换为“单位向量”
Binarizer 二值化 基于给定阈值,将定量特征按阈值划分
OneHotEncoder 哑编码 将定性数据编码为定量数据
Imputer 缺失值计算 计算缺失值,缺失值可填充为均值等
PolynomialFeatures 多项式数据转换 多项式数据转换
FunctionTransformer... | from sklearn.feature_selection import VarianceThreshold
# 方差选择法,返回值为特征选择后的数据
# 参数threshold为方差的阈值
VarianceThreshold(threshold=3).fit_transform(iris.data) | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
3.1.2 相关系数法
使用相关系数法,先要计算各个特征对目标值的相关系数以及相关系数的P值。用feature_selection库的SelectKBest类结合相关系数来选择特征的代码如下: | from sklearn.feature_selection import SelectKBest
from scipy.stats import pearsonr
# 选择K个最好的特征,返回选择特征后的数据
# 第一个参数为计算评估特征是否好的函数,该函数输入特征矩阵和目标向量,
# 输出二元组(评分,P值)的数组,数组第i项为第i个特征的评分和P值。
# 在此定义为计算相关系数
# 参数k为选择的特征个数
SelectKBest(lambda X, Y: tuple(map(tuple,np.array(list(map(lambda x:pearsonr(x, Y), X.T))).T)), k=2).fit_transf... | dev/pyml/2001_使用sklearn做单机特征工程.ipynb | karst87/ml | mit |
The reveals that we have the function
$$ expi = \intop_{-\infty}^u \frac {e^y} y dy $$
By just changing the sign of y to -y we obtain
$$ W(u) = \intop_u^\infty \frac {e^{-y}} y dy = - \intop_{y = -\infty}^{y = u} \frac {e^{y}} y dy $$
Replace $y$ by $-\xi$ the $W(u)$ becomes
$$ W(u) = - \intop_{\xi = \infty}^{\xi = -u}... | u = 4 * 10** -np.arange(11.) # generates values 4, 4e-1, 4e-2 .. 4e-10
print("{:>10s} {:>10s}".format('u ', 'wu '))
for u, wu in zip(u, -expi(-u)): # makes a list of value pairs [u, W(u)]
print("{0:10.1e} {1:10.4e}".format(u, wu)) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
which is equal to the values in the table.
It''s now convenient to use the familiar form W(u) instead of -expi(-u)
We can define a function for W either as an anonymous function or a regular function. Anonymous functions are called lambdda functions or lambda expressions in Python. In this case: | from scipy.special import expi
W = lambda u : -expi(-u) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Or, alternatively as a regular one-line function: | def W(u): return -expi(-u) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
or in full, so that we don't need the import above and we directly see where the function comes from: | import scipy
W = lambda u: -scipy.special.expi( -u ) # Theis well function | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Now we can put this well function immediately to use for answering practical questions. For example: what is the drawdown after $t=1\,d$ at distance $r=350 \, m$ by a well extracting $Q = 2400\, m^3/d$ in an confined aquifer with transmissivity $kD = 2400\, m^2/d$ and storage coefficient $S=0.001$ [-] ? | r = 350; t = 1.; kD=2400; S=0.001; Q=2400
u = r**2 * S / (4 * kD * t)
s = Q/(4 * np.pi * kD) * W(u) # applying the theis well function according to the book
print(" r = {} m\n\
t = {} d\n\
kD = {} m2/d\n\
S = {} [-]\n\
Q = {} m3/d\n\
u = {:.5g} [-]\n\
W(u) = {:.5g} [-]\n\
s(r, t) = {:.... | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Above we computed $u$ separately to prevent cluttering the expression. Of course, you can define a lambda or regular function to compute like so | u = lambda r, t: r**2 * S / (4 * kD * t) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
The lambda function $u$ now takes two parameters like $u(r,t)$ and uses the other parameters $S$ and $kD$ that it finds in the workspace at the moment when the lambda function is created. So don't change $S$ and $kD$ afterwards without redefining $u(r,t)$.
Try this out: | u(r,t) # yields u as a function of r and t
W(u(r,t)) # given W(u) as a function of r and t
Q/(4 * np.pi * kD) * W(u(r,t)) # gives the drawdown that we had before | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
It's now straight forward to compute the drawdown for many times like so: | t = np.logspace(-3, 2, 51) # gives 51 times on log scale between 10^(-3) = 0.001 and 10^(2) = 100 | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
This given the following times: | for it, tt in enumerate(t):
if it % 10 == 0: print()
print("%8.3g" % tt, end=" ") | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
With these times we can compute the drawdown for all these times in a single strike without changing anything to our formula: | s = Q / (4 * np.pi * kD) * W(u(r,t)) # computes s(r,t)
s # shows s(r,t) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
For a nicer print print t and s next to each other | print("{:>10s} {:>10s}".format('time', 'drawdown'))
for tt, ss in zip(t, s):
print("{0:10.3g} {1:10.3g}".format(tt,ss)) | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
And of course we can make a plot of these results: | import matplotlib.pyplot as plt # imports plot functions (matlab style)
fig = plt.figure()
# Drawdown versus log(t)
ax1 = fig.add_subplot(121)
ax1.set(xlabel='time [d]', ylabel='drawdown [m]', xscale='log', title='Drawdown versus log(t)')
ax1.invert_yaxis()
ax1.grid(True)
plt.plot(t, s)
# Drawdown versus t
ax2 = f... | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Exercises
Show the drawdown as a function of r instead of x, for t=2 d and r between 0.1 and 1000 m
For the 5 wells of which the lcoations and extractions are given below, show the combined drawdown for time between 0.01 and 10 days at x= 0 and y = 0. | well_names = ['School', 'Lazaret', 'Square', 'Mosque', 'Water_company']
Q = [400., 1200., 1150., 600., 1900]
x = [-300., -250., 100., 55., 125.]
y =[-450., +230., 50., -300., 250.]
Nwells = len(well_names)
x0 = 0.
y0 = 0.
t = np.logspace(-2, 2, 41)
s = np.zeros((Nwells, len(t)))
for iw, Q0, xw, yw in zip(range(Nwells... | exercises_notebooks/TransientFlowToAWell.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Minimal example
Generate a .csv file that is accepted as input to SmartVA-Analyze 1.1 | # SmartVA-Analyze 1.1 accepts a csv file as input
# and expects a column for every field name in the "Guide for data entry.xlsx" spreadsheet
df = pd.DataFrame(index=[0], columns=cb.index.unique())
# SmartVA-Analyze 1.1 also requires a handful of columns that are not in the Guide
df['child_3_10'] = np.nan
df['agedays'... | 01_example_mapping_in_python.ipynb | aflaxman/SmartVA-Analyze-Mapping-Example | gpl-3.0 |
Example of simple, hypothetical mapping
If we have data on a set of verbal autopsies (VAs) that did not use the PHMRC Shortened Questionnaire, we must map them to the expected format. This is a simple, hypothetical example for a set of VAs that asked only about injuries, hypertension, chest pain: | hypothetical_data = pd.DataFrame(index=range(5))
hypothetical_data['sex'] = ['M', 'M', 'F', 'M', 'F']
hypothetical_data['age'] = [35, 45, 75, 67, 91]
hypothetical_data['injury'] = ['rti', 'fall', '', '', '']
hypothetical_data['heart_disease'] = ['N', 'N', 'Y', 'Y', 'Y']
hypothetical_data['chest_pain'] = ['N', 'N', 'Y... | 01_example_mapping_in_python.ipynb | aflaxman/SmartVA-Analyze-Mapping-Example | gpl-3.0 |
Analysis of evoked response using ICA and PCA reduction techniques
This example computes PCA and ICA of evoked or epochs data. Then the
PCA / ICA components, a.k.a. spatial filters, are used to transform
the channel data to new sources / virtual channels. The output is
visualized on the average of all the epochs. | # Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Asish Panda <asishrocks95@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.decoding import UnsupervisedSpatialFilter
from sklearn.decomposition import PCA, FastI... | 0.17/_downloads/8b68ef11c9dcc68ed3cd0ccec9a41a34/plot_decoding_unsupervised_spatial_filter.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Transform data with PCA computed on the average ie evoked response | pca = UnsupervisedSpatialFilter(PCA(30), average=False)
pca_data = pca.fit_transform(X)
ev = mne.EvokedArray(np.mean(pca_data, axis=0),
mne.create_info(30, epochs.info['sfreq'],
ch_types='eeg'), tmin=tmin)
ev.plot(show=False, window_title="PCA", time_unit='s') | 0.17/_downloads/8b68ef11c9dcc68ed3cd0ccec9a41a34/plot_decoding_unsupervised_spatial_filter.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Transform data with ICA computed on the raw epochs (no averaging) | ica = UnsupervisedSpatialFilter(FastICA(30), average=False)
ica_data = ica.fit_transform(X)
ev1 = mne.EvokedArray(np.mean(ica_data, axis=0),
mne.create_info(30, epochs.info['sfreq'],
ch_types='eeg'), tmin=tmin)
ev1.plot(show=False, window_title='ICA', time_uni... | 0.17/_downloads/8b68ef11c9dcc68ed3cd0ccec9a41a34/plot_decoding_unsupervised_spatial_filter.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.