markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Pandas DataFrame
HTML(table.dframe().head().to_html())
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Dataset dictionary
table.columns()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Creating tabular data from Elements using the .table and .dframe methods If you have data in some other HoloViews element and would like to use the columnar data features, you can easily tabularize any of the core Element types into a Table Element, using the .table() method. Similarly, the .dframe() method will conve...
xs = np.arange(10) curve = hv.Curve(zip(xs, np.exp(xs))) curve * hv.Scatter(zip(xs, curve)) + curve.table()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Similarly, we can get a pandas dataframe of the Curve using curve.dframe(). Here we wrap that call as raw HTML to allow automated testing of this notebook, but just calling curve.dframe() would give the same result visually:
HTML(curve.dframe().to_html())
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Although 2D image-like objects are not inherently well suited to a flat columnar representation, serializing them by converting to tabular data is a good way to reveal the differences between Image and Raster elements. Rasters are a very simple type of element, using array-like integer indexing of rows and columns fro...
%%opts Points (s=200) [size_index=None] extents = (-1.6,-2.7,2.0,3) np.random.seed(42) mat = np.random.rand(3, 3) img = hv.Image(mat, bounds=extents) raster = hv.Raster(mat) img * hv.Points(img) + img.table() + \ raster * hv.Points(raster) + raster.table()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Tabularizing space containers Even deeply nested objects can be deconstructed in this way, serializing them to make it easier to get your raw data out of a collection of specialized Element types. Let's say we want to make multiple observations of a noisy signal. We can collect the data into a HoloMap to visualize it a...
obs_hmap = hv.HoloMap({i: hv.Image(np.random.randn(10, 10), bounds=(0,0,3,3)) for i in range(3)}, key_dimensions=['Observation']) obs_hmap
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Now we can serialize this data just as before, where this time we get a four-column (4D) table. The key dimensions of both the HoloMap and the Images, as well as the z-values of each Image, are all merged into a single table. We can visualize the samples we have collected by converting it to a Scatter3D object.
%%opts Layout [fig_size=150] Scatter3D [color_index=3 size_index=None] (cmap='hot' edgecolor='k' s=50) obs_hmap.table().to.scatter3d() + obs_hmap.table()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Here the z dimension is shown by color, as in the original images, and the other three dimensions determine where the datapoint is shown in 3D. This way of deconstructing will work for any data structure that satisfies the conditions described above, no matter how nested. If we vary the amount of noise while continuing...
from itertools import product extents = (0,0,3,3) error_hmap = hv.HoloMap({(i, j): hv.Image(j*np.random.randn(3, 3), bounds=extents) for i, j in product(range(3), np.linspace(0, 1, 3))}, key_dimensions=['Observation', 'noise']) noise_layout = error_hmap.layout('noise') n...
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Applying operations to the data Sorting by columns Once data is in columnar form, it is simple to apply a variety of operations. For instance, Dataset can be sorted by their dimensions using the .sort() method. By default, this method will sort by the key dimensions, but any other dimension(s) can be supplied to spec...
bars = hv.Bars((['C', 'A', 'B', 'D'], [2, 7, 3, 4])) bars + bars.sort() + bars.sort(['y'])
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Working with categorical or grouped data Data is often grouped in various ways, and the Dataset interface provides various means to easily compare between groups and apply statistical aggregates. We'll start by generating some synthetic data with two groups along the x-axis and 4 groups along the y axis.
n = np.arange(1000) xs = np.repeat(range(2), 500) ys = n%4 zs = np.random.randn(1000) table = hv.Table((xs, ys, zs), kdims=['x', 'y'], vdims=['z']) table
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Since there are repeat observations of the same x- and y-values, we have to reduce the data before we display it or else use a datatype that supports plotting distributions in this way. The BoxWhisker type allows doing exactly that:
%%opts BoxWhisker [aspect=2 fig_size=200 bgcolor='w'] hv.BoxWhisker(table)
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Aggregating/Reducing dimensions Most types require the data to be non-duplicated before being displayed. For this purpose, HoloViews makes it easy to aggregate and reduce the data. These two operations are simple inverses of each other--aggregate computes a statistic for each group in the supplied dimensions, while re...
%%opts Bars [show_legend=False] {+axiswise} hv.Bars(table).aggregate(function=np.mean) + hv.Bars(table).reduce(x=np.mean)
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
(A) aggregates over both the x and y dimension, computing the mean for each x/y group, while (B) reduces the x dimension leaving just the mean for each group along y. Collapsing multiple Dataset Elements When multiple observations are broken out into a HoloMap they can easily be combined using the collapse method. Here...
hmap = hv.HoloMap({i: hv.Curve(np.arange(10)*i) for i in range(10)}) collapsed = hmap.collapse(function=np.mean, spreadfn=np.std) hv.Spread(collapsed) * hv.Curve(collapsed) + collapsed.table()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Working with complex data In the last section we only scratched the surface of what the Dataset interface can do. When it really comes into its own is when working with high-dimensional datasets. As an illustration, we'll load a dataset of some macro-economic indicators for OECD countries from 1964-1990, cached on the...
macro_df = pd.read_csv('http://assets.holoviews.org/macro.csv', '\t') dimensions = {'unem': 'Unemployment', 'capmob': 'Capital Mobility', 'gdp': 'GDP Growth', 'trade': 'Trade', 'year': 'Year', 'country': 'Country'} macro_df = macro_d...
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
We'll also take this opportunity to set default options for all the following plots.
%output dpi=100 options = hv.Store.options() opts = hv.Options('plot', aspect=2, fig_size=250, show_frame=False, show_grid=True, legend_position='right') options.NdOverlay = opts options.Overlay = opts
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Loading the data As we saw above, we can supply a dataframe to any Dataset type. When dealing with so many dimensions it would be cumbersome to supply all the dimensions explicitly, but luckily Dataset can easily infer the dimensions from the dataframe itself. We simply supply the kdims, and it will infer that all othe...
macro = hv.Table(macro_df, kdims=['Year', 'Country'])
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
To get an overview of the data we'll quickly sort it and then view the data for one year.
%%opts Table [aspect=1.5 fig_size=300] macro = macro.sort() macro[1988]
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Most of the examples above focus on converting a Table to simple Element types, but HoloViews also provides powerful container objects to explore high-dimensional data, such as HoloMap, NdOverlay, NdLayout, and GridSpace. HoloMaps work as a useful interchange format from which you can conveniently convert to the other ...
%%opts Curve (color=Palette('Set3')) gdp_curves = macro.to.curve('Year', 'GDP Growth') gdp_curves.overlay('Country')
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Now that we've extracted the gdp_curves, we can apply some operations to them. As in the simpler example above we will collapse the HoloMap of Curves using a number of functions to visualize the distribution of GDP Growth rates over time. First we find the mean curve with np.std as the spreadfn and cast the result to a...
%%opts Overlay [bgcolor='w' legend_position='top_right'] Curve (color='k' linewidth=1) Spread (facecolor='gray' alpha=0.2) hv.Spread(gdp_curves.collapse('Country', np.mean, np.std), label='std') *\ hv.Overlay([gdp_curves.collapse('Country', fn).relabel(name)(style=dict(linestyle=ls)) for name, fn, ls in [('...
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Many HoloViews Element types support multiple kdims, including HeatMap, Points, Scatter, Scatter3D, and Bars. Bars in particular allows you to lay out your data in groups, categories and stacks. By supplying the index of that dimension as a plotting option you can choose to lay out your data as groups of bars, categori...
%opts Bars [bgcolor='w' aspect=3 figure_size=450 show_frame=False] %%opts Bars [category_index=2 stack_index=0 group_index=1 legend_position='top' legend_cols=7 color_by=['stack']] (color=Palette('Dark2')) macro.to.bars(['Country', 'Year'], 'Trade', [])
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
This plot contains a lot of data, and so it's probably a good idea to focus on specific aspects of it, telling a simpler story about them. For instance, using the .select method we can then customize the palettes (e.g. to use consistent colors per country across multiple analyses). Palettes can customized by selecting...
%%opts Bars [padding=0.02 color_by=['group']] (alpha=0.6, color=Palette('Set1', reverse=True)[0.:.2]) countries = {'Belgium', 'Netherlands', 'Sweden', 'Norway'} macro.to.bars(['Country', 'Year'], 'Unemployment').select(Year=(1978, 1985), Country=countries)
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Many HoloViews Elements support multiple key and value dimensions. A HeatMap is indexed by two kdims, so we can visualize each of the economic indicators by year and country in a Layout. Layouts are useful for heterogeneous data you want to lay out next to each other. Before we display the Layout let's apply some styli...
%opts HeatMap [show_values=False xticks=40 xrotation=90 aspect=1.2 invert_yaxis=True colorbar=True] %opts Layout [figure_size=120 aspect_weight=0.5 hspace=0.8 vspace=0] hv.Layout([macro.to.heatmap(['Year', 'Country'], value) for value in macro.data.columns[2:]]).cols(2)
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Another way of combining heterogeneous data dimensions is to map them to a multi-dimensional plot type. Scatter Elements, for example, support multiple vdims, which may be mapped onto the color and size of the drawn points in addition to the y-axis position. As for the Curves above we supply 'Year' as the sole key dim...
%%opts Scatter [scaling_method='width' scaling_factor=2] (color=Palette('Set3') edgecolors='k') gdp_unem_scatter = macro.to.scatter('Year', ['GDP Growth', 'Unemployment']) gdp_unem_scatter.overlay('Country')
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
In this way we can plot any dimension against any other dimension, very easily allowing us to iterate through different ways of revealing relationships in the dataset.
%%opts NdOverlay [legend_cols=2] Scatter [size_index=1] (color=Palette('Blues')) macro.to.scatter('GDP Growth', 'Unemployment', ['Year']).overlay()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
This view, for example, immediately highlights the high unemployment rates of the 1980s. Since all HoloViews Elements are composable, we can generate complex figures just by applying the * operator. We'll simply reuse the GDP curves we generated earlier, combine them with the scatter points (which indicate the unemploy...
%%opts Curve (color='k') Scatter [color_index=2 size_index=2 scaling_factor=1.4] (cmap='Blues' edgecolors='k') macro_overlay = gdp_curves * gdp_unem_scatter annotations = hv.Arrow(1973, 8, 'Oil Crisis', 'v') * hv.Arrow(1975, 6, 'Stagflation', 'v') *\ hv.Arrow(1979, 8, 'Energy Crisis', 'v') * hv.Arrow(1981.9, 5, 'Early...
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Since we didn't map the country to some other container type, we get a widget allowing us to view the plot separately for each country, reducing the forest of curves we encountered before to manageable chunks. While looking at the plots individually like this allows us to study trends for each country, we may want to ...
%opts Overlay [aspect=1] %%opts NdLayout [figure_size=100] Scatter [color_index=2] (cmap='Reds') countries = {'United States', 'Canada', 'United Kingdom'} (gdp_curves * gdp_unem_scatter).select(Country=countries).layout('Country')
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Finally, let's combine some plots for each country into a Layout, giving us a quick overview of each economic indicator for each country:
%%opts Layout [fig_size=100] Scatter [color_index=2] (cmap='Reds') (macro_overlay.relabel('GDP Growth', depth=1) +\ macro.to.curve('Year', 'Unemployment', ['Country'], group='Unemployment',) +\ macro.to.curve('Year', 'Trade', ['Country'], group='Trade') +\ macro.to.scatter('GDP Growth', 'Unemployment', ['Country'])).co...
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Find maximum of Bernoulli distribution Single experiment $$\phi(x) = p ^ {x} * (1 - p) ^ { 1 - x }$$ Series of experiments $$\mathcal{L}(p|x) = \prod_{i=1}^{n} p^{x_{i}}*(p-1)^{1-x_{i}}$$ Hints sympy.diff() sympy.expand() sympy.expand_log() sympy.solve() sympy.symbols() sympy gotchas
import sympy from sympy.abc import x p = sympy.symbols('p', positive=True) phi = p ** x * (1 - p) ** (1 - x) L = np.prod([phi.subs(x, i) for i in xs]) # objective function to maximize log_L = sympy.expand_log(sympy.log(L)) sol = sympy.solve(sympy.diff(log_L, p), p)[0] import matplotlib.pyplot as plt x_space = np.lin...
mle.ipynb
hyzhak/mle
mit
Empirically examine the behavior of the maximum likelihood estimator evalf()
def estimator_gen(niter=10, ns=100): """ generate data to estimate distribution of maximum likelihood estimator' """ x = sympy.symbols('x', real=True) phi = p**x*(1-p)**(1-x) for i in range(niter): xs = sample(ns) # generate some samples from the experiment L = np.prod([phi.subs(...
mle.ipynb
hyzhak/mle
mit
Dynamic of MLE by length sample sequence
def estimator_dynamics(ns_space, num_tries = 20): for ns in ns_space: estimations = list(estimator_gen(num_tries, ns)) yield np.mean(estimations), np.std(estimations) ns_space = list(range(10, 100, 5)) entries = list(estimator_dynamics(ns_space)) entries_mean = list(map(lambda e: e[0], entries)...
mle.ipynb
hyzhak/mle
mit
I'll fit a significantly larger vocabular this time, as the embeddings are basically given for us.
num_words = 5000 max_len = 400 tok = Tokenizer(num_words) tok.fit_on_texts(input_text[:25000]) X_train = tok.texts_to_sequences(input_text[:25000]) X_test = tok.texts_to_sequences(input_text[25000:]) y_train = input_label[:25000] y_test = input_label[25000:] X_train = sequence.pad_sequences(X_train, maxlen=max_len)...
lectures/lec22/.ipynb_checkpoints/notebook22-checkpoint.ipynb
statsmaths/stat665
gpl-2.0
Session 1.4 Collections Sets and dictionaries
# Sets my_set = set([1, 2, 3, 3, 3, 4]) print(my_set) len(my_set) my_set.add(3) # sets are unordered print(my_set) my_set.remove(3) print(my_set) # set operation using union | or intersection & my_first_set = set([1, 2, 4, 6, 8]) my_second_set = set([8, 9, 10]) my_first_set | my_second_set my_first_set & my_second...
live/python_basic_1_4_live.ipynb
pycam/python-basic
unlicense
Exercises 1.4.1 Given the protein sequence "MPISEPTFFEIF", find the unique amino acids in the sequence.
# Dictionnaries are collections of key/value pairs my_dict = {'A': 'Adenine', 'C': 'Cytosine', 'T': 'Thymine', 'G': 'Guanine'} print(my_dict) my_dict['C'] my_dict['N'] ?my_dict.get my_dict.get('N', 'unknown') print(my_dict) len(my_dict) type(my_dict) 'T' in my_dict # Assign new key/value pair my_dict['Y'] = 'Py...
live/python_basic_1_4_live.ipynb
pycam/python-basic
unlicense
To begin, let's make a function which will create $N$ noisy, irregularly-spaced data points containing a periodic signal, and plot one realization of that data:
def create_data(N, period=2.5, err=0.1, rseed=0): rng = np.random.RandomState(rseed) t = np.arange(N, dtype=float) + 0.3 * rng.randn(N) y = np.sin(2 * np.pi * t / period) + err * rng.randn(N) return t, y, err t, y, dy = create_data(100, period=20) plt.errorbar(t, y, dy, fmt='o');
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
From this, our algorithm should be able to identify any periodicity that is present. Choosing the Frequency Grid The Lomb-Scargle Periodogram works by evaluating a power for a set of candidate frequencies $f$. So the first question is, how many candidate frequencies should we choose? It turns out that this question is ...
def freq_grid(t, oversampling=5, nyquist_factor=3): T = t.max() - t.min() N = len(t) df = 1. / (oversampling * T) fmax = 0.5 * nyquist_factor * N / T N = int(fmax // df) return df + df * np.arange(N)
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
Now let's use the gatspy tools to plot the periodogram:
t, y, dy = create_data(100, period=2.5) freq = freq_grid(t) print(len(freq)) from gatspy.periodic import LombScargle model = LombScargle().fit(t, y, dy) period = 1. / freq power = model.periodogram(period) plt.plot(period, power) plt.xlim(0, 5);
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
The algorithm finds a strong signal at a period of 2.5. To demonstrate explicitly that the Nyquist rate doesn't apply in irregularly-sampled data, let's use a period below the averaged sampling rate and show that we can find it:
t, y, dy = create_data(100, period=0.3) period = 1. / freq_grid(t, nyquist_factor=10) model = LombScargle().fit(t, y, dy) power = model.periodogram(period) plt.plot(period, power) plt.xlim(0, 1);
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
With a data sampling rate of approximately $1$ time unit, we easily find a period of $0.3$ time units. The averaged Nyquist limit clearly does not apply for irregularly-spaced data! Nevertheless, short of a full analysis of the temporal window function, it remains a useful milepost in estimating the upper limit of freq...
from gatspy.periodic import LombScargleFast help(LombScargleFast.periodogram_auto) from gatspy.periodic import LombScargleFast t, y, dy = create_data(100) model = LombScargleFast().fit(t, y, dy) period, power = model.periodogram_auto() plt.plot(period, power) plt.xlim(0, 5);
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
Here, to illustrate the different computational scalings, we'll evaluate the computational time for a number of inputs, using LombScargleAstroML (a fast implementation of the $O[N^2]$ algorithm) and LombScargleFast, which is the fast FFT-based implementation:
from time import time from gatspy.periodic import LombScargleAstroML, LombScargleFast def get_time(N, Model): t, y, dy = create_data(N) model = Model().fit(t, y, dy) t0 = time() model.periodogram_auto() t1 = time() result = t1 - t0 # for fast operations, we should...
examples/FastLombScargle.ipynb
nhuntwalker/gatspy
bsd-2-clause
Now, let's apply the theory of rotation matrices to write some code which will rotate a vector by amount $\theta$. The function rotmat(th) returns the rotation matrix.
def rotmat(th): rotator = np.array([[ma.cos(th), -ma.sin(th)],[ma.sin(th), ma.cos(th)]]) return rotator
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
This function rotation(th, vec) takes in a rotation angle and vector input and returns a tuple of numpy arrays which can be animated to create a "smooth transition" of the rotation using Plotly Animate.
def rotation(th, vec): # Parameters t = np.linspace(0,1,50) tt = th*t # Rotation matrix BigR = np.identity(2) for i in range(len(tt)-1): BigR = np.vstack((BigR,rotmat(tt[i+1]))) newvec = np.matmul(BigR,vec) x = newvec[::2] y = newvec[1::2] return (x,y)
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
In the cell below, enter a rotation angle and vector inside the rotation() function which has some inputs inside already and hit shift enter to generate an animation of the rotation! (<b>N.B. Don't worry too much if you're not familiar with the plotly syntax, it's more important you understand what the matrices are doi...
# Enter a 2D vector here... vec = [1,0] # Enter rotation angle here... th = 4 (x0,y0) = rotation(th, vec) x0 = list(x0) y0 = list(y0) # Syntax for plotly, see documentation for more info data = [{"x": [x0[i],0], "y": [y0[i],0], "frame": i} for i in range(len(x0))] figure = {'data': [{'x': data[0]['x'], 'y': data[0]['...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
3. Scaling Matrices Now we are familiar with rotation matrices, we will move onto another type of matrix transformation known as a "scaling" matrix. Scaling matrices have the form: <br> <br> $$ \text{Scale} = \begin{pmatrix} s1 & 0 \ 0 & s2 \end{pmatrix} $$ <br> Now let's look at what this matrix does to an arbitrary v...
# Input vector, scale 1, scale 2 as arguments def scale(vec, *args): assert len(vec)==2, "Please provide a 2D vector for the first argument" assert len(args)==1 or len(args)==2, "Please provide 1 or 2 scale arguments" t = np.linspace(1,args[0],50) # If only one scale argument given then scale in both di...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
Now try it for yourself by running the function with your own inputs, by default 2 scale arguments have been inputted but you can try 1 if you like as well.
# Again input vector here vec = [1,1] # Arguments here s1 = 2 s2 = 3 (x1,y1) = scale(vec, s1, s2) x1 = list(x1) y1 = list(y1) # Plotly syntax again data = [{"x": [x1[i],0], "y": [y1[i],0], "frame": i} for i in range(len(x1))] figure = {'data': [{'x': data[0]['x'], 'y': data[0]['y']}], 'layout': {'xaxis': {'...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
4. Custom Matrix Now we have explained some basic matrix transformations, feel free to use the following code to create your own 2x2 matrix transformations.
# Custom 2D transformation def custom(vec): print("Enter values for 2x2 matrix [[a,b],[c,d]] ") a = input("Enter a value for a: ") b = input("Enter a value for b: ") c = input("Enter a value for c: ") d = input("Enter a value for d: ") try: a = float(a) except ValueError: pri...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
5. Skew Matrices For the next matrix we will use a slightly different approach to visualize what this transformation does. Instead of taking one vector and following what the matrix does to it, we will take 3 vectors ((1, 0), (1, 1) and (0, 1)) and look at what the matrix does to the entire area captured between these ...
def skew(axis, vec): t = np.linspace(0,1,50) # Skew in x-direction if axis == 0: A = [[1,1],[0,1]] w = np.matmul(A,vec)-vec x = [vec[0]+tt*w[0] for tt in t] y = [vec[1]+tt*w[1] for tt in t] return(x, y) # Skew in y-direction elif axis == 1: A = [[1,0],...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
Now we write a function which will take 6 arrays in total (2 for (1, 0), 2 for (0, 1) and 2 for (1, 1)) and shows an animation of how the 3 vectors are transformed. Remember that we can forget about the origin as it is always mapped to itself (this is a standard property of linear transformations).
# Function that returns data in a format to be used by plotly and then plots it def sqtransformation(x0,x1,x2,y0,y1,y2): data = [{"x": [0,x0[i],x1[i],x2[i],0], "y": [0,y0[i],y1[i],y2[i],0], "frame": i} for i in range(len(x0))] figure = {'data': [{'x': data[0]['x'], 'y': data[0]['y'], 'fill':'tonexty'}], ...
visuals_maths/2D_Transformations/notebook/2D_transformations.ipynb
cydcowley/Imperial-Visualizations
mit
1. Single Day Analysis
ref_date = '2020-01-02' engine = SqlEngine(os.environ['DB_URI']) universe = Universe('hs300') codes = engine.fetch_codes(ref_date, universe) total_data = engine.fetch_data(ref_date, 'EMA5D', codes, 300, industry='sw', risk_model='short') all_styles = risk_styles + industry_styles + ['COUNTRY'] risk_cov = total_data['...
notebooks/Example 6 - Target Volatility Builder.ipynb
wegamekinglc/alpha-mind
mit
Portfolio Construction using EPS factor as alpha factor; short selling is forbiden; target of volatility for the activate weight is setting at 2.5% annually level.
er = factor['EMA5D'].fillna(factor["EMA5D"].median()).values bm = factor['weight'].values lbound = np.zeros(len(er)) ubound = bm + 0.01 cons_mat = np.ones((len(er), 1)) risk_targets = (bm.sum(), bm.sum()) target_vol = 0.025 risk_model = dict(cov=None, factor_cov=risk_cov/10000, factor_loading=risk_exposure, idsync=spec...
notebooks/Example 6 - Target Volatility Builder.ipynb
wegamekinglc/alpha-mind
mit
2. Porfolio Construction: 2016 ~ 2018
""" Back test parameter settings """ start_date = '2020-01-01' end_date = '2020-02-21' freq = '10b' neutralized_risk = industry_styles industry_name = 'sw' industry_level = 1 risk_model = 'short' batch = 0 horizon = map_freq(freq) universe = Universe('hs300') data_source = os.environ['DB_URI'] benchmark_code = 300 ta...
notebooks/Example 6 - Target Volatility Builder.ipynb
wegamekinglc/alpha-mind
mit
We're going to load the data in using h5py from an hdf5 file. HDF5 is a file format that allows for very simple storage of numerical data; in this particular case, we'll be loading in a 3D array, and then examining it.
f = h5py.File("/srv/nbgrader/data/koala.hdf5", "r") print(list(f.keys()))
week05/examples_week05.ipynb
UIUC-iSchool-DataViz/spring2017
mit
Here, we load in the data by reading from the key koala that we just found.
koala = f["/koala"][:] print(koala.shape)
week05/examples_week05.ipynb
UIUC-iSchool-DataViz/spring2017
mit
We'll use subplots to show the maximum value along each of the three axes, along with a histogram of all the values. The .max() function here accepts and axis argument, which means "max along a given axis."
for i in range(3): plt.subplot(2,2,i+1) plt.imshow(koala.max(axis=i), interpolation='nearest', origin='lower', cmap='viridis') plt.subplot(2,2,4) plt.hist(koala.ravel(), bins = 32, log = True)
week05/examples_week05.ipynb
UIUC-iSchool-DataViz/spring2017
mit
We'll make a slicer, too -- this one is along the x value. Note how we take a floating point value and turn that into an index to make the image.
def xslicer(coord = 0.5): # We're accepting a float here, so we convert that into the right index we want ind = int(coord * koala.shape[0]) plt.imshow(koala[ind,:,:], interpolation = 'nearest', origin='lower') ipywidgets.interact(xslicer, coord = (0.0, 1.0, 0.01))
week05/examples_week05.ipynb
UIUC-iSchool-DataViz/spring2017
mit
Download the dataset from its repository at github https://github.com/jeanpat/DeepFISH/tree/master/dataset
!wget https://github.com/jeanpat/DeepFISH/blob/master/dataset/LowRes_13434_overlapping_pairs.h5 filename = './LowRes_13434_overlapping_pairs.h5' h5f = h5py.File(filename,'r') pairs = h5f['dataset_1'][:] h5f.close() print('dataset is a numpy array of shape:', pairs.shape) N = 11508 grey = pairs[N,:,:,0] g_truth = pa...
notebooks/Clean Dataset from their spurious pixels.ipynb
jeanpat/DeepFISH
gpl-3.0
Let's compare the groundtruth image befor and after cleaning
plt.figure(figsize=(20,10)) plt.subplot(251,xticks=[],yticks=[]) plt.imshow(grey, cmap=plt.cm.gray) plt.subplot(252,xticks=[],yticks=[]) plt.imshow(g_truth, cmap=plt.cm.flag_r) plt.subplot(253,xticks=[],yticks=[]) plt.imshow(g_truth == 1, cmap=plt.cm.flag_r) plt.subplot(254,xticks=[],yticks=[]) plt.imshow(g_truth == 2...
notebooks/Clean Dataset from their spurious pixels.ipynb
jeanpat/DeepFISH
gpl-3.0
Clean the whole dataset
new_data = np.zeros((1,94,93,2), dtype = int) N = pairs.shape[0]#10 for idx in range(N): g_truth = pairs[idx,:,:,1] grey = pairs[idx,:,:,0] _, _, _, seg = clean_ground_truth(g_truth, size = 1) paired = np.dstack((grey, seg)) # #https://stackoverflow.com/questions/7372316/how-to-make-a-2d-numpy-a...
notebooks/Clean Dataset from their spurious pixels.ipynb
jeanpat/DeepFISH
gpl-3.0
Save the dataset using hdf5 format
filename = './Cleaned_LowRes_13434_overlapping_pairs.h5' hf = h5py.File(filename,'w') hf.create_dataset('13434_overlapping_chrom_pairs_LowRes', data=new_data, compression='gzip', compression_opts=9) hf.close()
notebooks/Clean Dataset from their spurious pixels.ipynb
jeanpat/DeepFISH
gpl-3.0
K-means Clustering non-distributed implementation
X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0) # Save simulated data to be used in MapReduce code np.savetxt("kmeans_simulated_data.txt", X, fmt='%.18e', delimiter=' ') plt.scatter(X[:, 0], X[:, 1], s=50); # Write modules for the simulation of local K-Meanss d...
codes/driver_kmeans.ipynb
r2rahul/numericalanalysis
gpl-2.0
Simulating MapReduce K-Means Algorithm Mapper Script Assumes mapper data input in tidy format and all varibales are properly encoded
%%writefile mapper_kmeans.py import sys import csv import math import numpy as np #Read the centroids iteratively and its co-ordinates with open('kmeans_cache.txt', 'r') as f: fp = csv.reader(f, delimiter = " ") m = np.array([[float(i) for i in j] for j in fp]) # input comes from STDIN (stan...
codes/driver_kmeans.ipynb
r2rahul/numericalanalysis
gpl-2.0
Reducer Script
%%writefile reducer_kmeans.py from operator import itemgetter import sys import numpy as np current_cluster = None current_val = 0 # input comes from STDIN for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() cluster, value = line.split('\t', 1) #Convert value to float ...
codes/driver_kmeans.ipynb
r2rahul/numericalanalysis
gpl-2.0
Simulate Job Chaining with Shell Script for loop iterates over each reducer output . Inside for loop Centroid co-ordinates are updated in kmeans_cache.txt at each iteration . Final output is stored in kmeans_cache.txt
%%sh #Initialize the initial clusters for i in `seq 1 20`; do echo 'Iteration Number = '$i cat kmeans_simulated_data.txt | python mapper_kmeans.py | sort | python reducer_kmeans.py > kmeans_temp.txt mv kmeans_temp.txt kmeans_cache.txt done
codes/driver_kmeans.ipynb
r2rahul/numericalanalysis
gpl-2.0
Test MapReduce Implementation
#Check if the centroid calculated in the non-distributed and distributed method are in same range def check_mapreduce(centroid_non, centroid_dist): #Check if new and old centroid have changed or not error = np.all(np.array(centroid_non) == np.array(centroid_dist)) #error calculation second way: Relative Err...
codes/driver_kmeans.ipynb
r2rahul/numericalanalysis
gpl-2.0
Value in relationship If we assume that a relationsip holds some sort of value, how is that value divided? Think about it...what kinds of value could a relationship hold? If we think about power in terms of an imbalance in social exchange, how is the value of a relationship distributed based on the power of the ind...
g.add_edges_from([("B", "C"), ("B", "D"), ("D", "E")]) nx.draw_networkx(g)
class19.ipynb
davebshow/DH3501
mit
Dependence - if relationships confer value, nodes A and C are completely dependent on node B for value. Exclusion - node B can easily exclude node A or C from the value conferred by the network. Satiation - at a certain point, nodes like B begin to see diminishing returns and only maintains relations from which the...
g = nx.Graph([("A", "B")]) nx.draw_networkx(g) plt.title("2-Node Path") g = nx.Graph([("A", "B"), ("B", "C")]) nx.draw_networkx(g) plt.title("3-Node Path") g = nx.Graph([("A", "B"), ("B", "C"), ("C", "D")]) nx.draw_networkx(g) plt.title("4-Node Path") g = nx.Graph([("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")]) nx...
class19.ipynb
davebshow/DH3501
mit
How about power in a network that looks like this?
g = nx.Graph([("A", "B"), ("B", "C"), ("B", "D"), ("C", "D")]) nx.draw_networkx(g) plt.title("Triangle with outlier")
class19.ipynb
davebshow/DH3501
mit
Or this?
g = nx.Graph([("A", "B"), ("B", "C"), ("C", "A")]) nx.draw_networkx(g) plt.title("Triangle")
class19.ipynb
davebshow/DH3501
mit
Locations
HOME_DIR = os.path.expanduser('~').replace('\\', '/') BASE_DIR = '{}/Documents/DANS/projects/has/dacs'.format(HOME_DIR) FM_DIR = '{}/fm'.format(BASE_DIR) FMNS = '{http://www.filemaker.com/fmpxmlresult}' CONFIG_DIR = '.'
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Config All configuration in a big yaml file
with open('{}/config.yaml')
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Data description Main source tables and fields to skip
CONFIG = yaml.load(''' mainTables: - contrib - country ''') mainTables = ('contrib', 'country') SKIP_FIELDS = dict( contrib=set(''' dateandtime_ciozero ikid ikid_base find_country_id find_type gnewpassword gnewpassword2 goldpassword help_description help_text message message_allert teller total_costs_total whois ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to merge
MERGE_FIELDS = dict( contrib=dict( academic_entity_url=['academic_entity_url_2'], contribution_url=['contribution_url_2'], contact_person_mail=['contact_person_mail_2'], type_of_inkind=['other_type_of_inkind'], vcc11_name=[ 'vcc12_name', 'vcc21_name', ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to rename
MAP_FIELDS = dict( contrib=dict( approved='approved', academic_entity_url='urlAcademic', contribution_url='urlContribution', contact_person_mail='contactPersonEmail', contact_person_name='contactPersonName', costs_description='costDescription', costs_total='co...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to split into multiple values
generic = re.compile('[ \t]*[\n+][ \t\n]*') # split on newlines (with surrounding white space) genericComma = re.compile('[ \t]*[\n+,;][ \t\n]*') # split on newlines or commas (with surrounding white space) SPLIT_FIELDS=dict( contrib=dict( discipline=generic, keyword=genericComma, ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to hack
STRIP_NUM = re.compile('^[0-9]\s*\.?\s+') def stripNum(v): return STRIP_NUM.sub('', v) HACK_FIELDS=dict( contrib=dict( tadirahActivity=stripNum, ), country=dict(), )
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to decompose into several fields
DECOMPOSE_FIELDS=dict( contrib=dict( typeContribution='typeContributionOther', ), country=dict(), )
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Custom field types
FIELD_TYPE = dict( contrib=dict( costTotal='valuta', dateCreated='datetime', dateModified='datetime', dateApproved='datetime', dateApprovedCIO='datetime', contactPersonEmail='email', submitted='bool', approved='bool', reviewerDecision='bool', ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Default values
DEFAULT_VALUES=dict( contrib=dict( dateCreated=datetime(2000,1,1,0,0,0), creator="admin", type_of_inkind="General", ), country=dict(), )
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to move to other tables
MOVE_FIELDS=dict( contrib=dict( assessment=set(''' approved dateApproved dateApprovedCIO submitted reviewerName reviewerDecision vccDecision vccApproval vccDisApproval '''.strip().split()), ), country=dict(), )
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Fields to value lists
MAKE_VALUE_LISTS = dict( contrib=set(''' keyword year '''.strip().split()), ) VALUE_LISTS = dict( contrib=set(''' discipline keyword tadirahActivity tadirahObject tadirahTechnique typeContribution typeContributionOther:typeContribution vcc year '''.strip().split()), ) MOVE_MISSING = dict( contrib='descript...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Field values Patterns for value types
# Source field types, including types assigned by type overriding (see FIELD_TYPE_OVERRIDE above). # These will be translated into appropriate SQL field types TYPES = {'bool', 'number', 'decimal', 'text', 'valuta', 'email', 'date', 'datetime'} # dates are already in ISO (date2_pattern). # If we encounter other dates,...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Date and Time values
def date_repl(match): [d,m,y] = list(match.groups()) return '{}-{}-{}'.format(y,m,d) def date2_repl(match): [y,m,d] = list(match.groups()) return '{}-{}-{}'.format(y,m,d) def datetime_repl(match): [d,m,y,hr,mn,sc] = list(match.groups()) return '{}-{}-{}T{}:{}:{}'.format(y,m,d,hr,mn,sc ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Boolean, numeric and string values
def bools(v_raw, i, t, fname): if v_raw in BOOL_VALUES[True]: return True if v_raw in BOOL_VALUES[False]: return False warning( 'table `{}` field `{}` record {}: not a boolean value: "{}"'.format( t, fname, i, v_raw )) return v_raw def num(v_raw, i, t, fname): if type(v_raw)...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Money values
def money(v_raw, i, t, fname): note = ',' in v_raw or '.' in v_raw v = v_raw.strip().lower().replace(' ','').replace('€', '').replace('euro', '').replace('\u00a0', '') for p in range(2,4): # interpret . or , as decimal point if less than 3 digits follow it if len(v) >= p and v[-p] in '.,': ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Clean up field values
def sanitize(t, i, fname, value): if fname == '_id': return value (ftype, fmult) = allFields[t][fname] newValue = [] for v_raw in value: if v_raw == None or v_raw in NULL_VALUES: continue elif ftype == 'text': v = v_raw elif ftype == 'bool': v = bools(v_raw, i, t, fname) ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Show information
def info(x): sys.stdout.write('{}\n'.format(x)) def warning(x): sys.stderr.write('{}\n'.format(x)) def showFields(): for (mt, defs) in sorted(allFields.items()): info(mt) for (fname, fdef) in sorted(defs.items()): info('{:>25}: {:<10} ({})'.format(fname, *fdef)) def showdata(rows): ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Read FM fields
def readFmFields(): for mt in mainTables: infile = '{}/{}.xml'.format(FM_DIR, mt) root = etree.parse(infile, parser).getroot() fieldroots = [x for x in root.iter(FMNS+'METADATA')] fieldroot = fieldroots[0] fields = [] fieldDefs = {} for x in fieldroot.iter(FMN...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Read FM data
def readFmData(): for mt in mainTables: infile = '{}/{}.xml'.format(FM_DIR, mt) root = etree.parse(infile, parser).getroot() dataroots = [x for x in root.iter(FMNS+'RESULTSET')] dataroot = dataroots[0] rows = [] rowsRaw = [] fields = rawFields[mt] for ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Split tables into several tables by column groups
def moveFields(): for mt in mainTables: for (omt, mfs) in MOVE_FIELDS[mt].items(): for mf in mfs: allFields.setdefault(omt, dict())[mf] = allFields[mt][mf] del allFields[mt][mf] allFields.setdefault(omt, dict)['{}_id'.format(mt)] = ('id', 1) f...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Value Lists
def readLists(): valueLists = dict() for path in glob('{}/*.txt'.format(FM_DIR)): tname = basename(splitext(path)[0]) data = [] with open(path) as fh: for line in fh: data.append(line.rstrip().split('\t')) valueLists[tname] = data for (vList, data...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Country table
def countryTable(): extraInfo = valueDict['countryExtra'] idMapping = dict() for row in allData['country']: for f in row: if type(row[f]) is list: row[f] = row[f][0] iso = row['iso'] row['_id'] = ObjectId() idMapping[iso] = row['_id'] (name, lat, long) = ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
User table
def userTable(): idMapping = dict() existingUsers = [] testUsers = [ dict(eppn='suzan', email='suzan1@test.eu', mayLogin=True, authority='local', firstName='Suzan', lastName='Karelse'), dict(eppn='marie', email='suzan2@test.eu', mayLogin=True, authority='local', fir...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Related tables
def relTables(): def norm(x): return x.strip().lower() relIndex = dict() for mt in sorted(VALUE_LISTS): rows = allData[mt] for f in sorted(VALUE_LISTS[mt]): comps = f.split(':') if len(comps) == 2: (f, fAs) = comps else: ...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Test tweaks Tweaks for testing purposes.
def testTweaks(): mt = 'contrib' myContribs = {'3DHOP', 'AAI'} my = uidMapping['dirk'] for row in allData[mt]: title = row.get('title', [None]) if len(title) == 0: title = [None] if title[0] in myContribs: row['creator'] = [dict(_id=my)]
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Insert into MongoDB
def importMongo(): client = MongoClient() client.drop_database('dariah') db = client.dariah for (mt, rows) in allData.items(): info(mt) db[mt].insert_many(rows)
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
The whole pipeline
money_warnings = {} money_notes = {} valueDict = dict() rawFields = dict() allFields = dict() rawData = dict() allData = dict() uidMapping = dict() parser = etree.XMLParser(remove_blank_text=True, ns_clean=True) readFmFields() readFmData() readLists() moveFields() countryTable() userTable() relTables() testTweaks() im...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
To import the bson dump in another mongodb installation, use the commandline to dump the dariah database here mongodump -d dariah -o dariah and to import it elsewhere. mongorestore --drop -d dariah dariah
valueDict.keys() valueDict['keywords']
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Exploration The process has finished, but here is space to explore the data, in order to find patterns, regularities, and, more importantly, irregularities. First step: create csv files of the data and combine them into an excel sheet.
import xlsxwriter EXPORT_DIR = os.path.expanduser('~/Downloads') EXPORT_ORIG = '{}/contribFromFileMaker.xlsx'.format(EXPORT_DIR) EXPORT_MONGO = '{}/contribInMongoDB.xlsx'.format(EXPORT_DIR) workbook = xlsxwriter.Workbook(EXPORT_ORIG, {'strings_to_urls': False}) for mt in rawData: worksheet = workbook.add_workshee...
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Here is a query to get all 'type_of_inkind' values for contributions.
for c in dbm.contrib.distinct('typeContribution', {}): print(c)
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Here are the users:
for c in dbm.users.find({}): print(c)
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit
Here are the countries:
for c in dbm.country.find({'isMember': True}): print(c) for c in dbm.contrib.distinct('country', {}): print(c)
static/tools/.ipynb_checkpoints/from_filemaker-checkpoint.ipynb
Dans-labs/dariah
mit