Page 3 of 6
Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 03, 2021 6:49 pm
by Eli
Extract/unzip and analyze the Planck chains/MCMC samples from the
Planck Legacy Archive:
import zipfile
import urllib.request
urllib.request.urlretrieve("http://pla.esac.esa.int/pla/aio/product-action?COSMOLOGY.FILE_ID=COM_CosmoParams_base-plikHM-TTTEEE-lowl-lowE_R3.00.zip", "COM_CosmoParams_base-plikHM-TTTEEE-lowl-lowE_R3.00.zip")
with zipfile.ZipFile('./COM_CosmoParams_base-plikHM-TTTEEE-lowl-lowE_R3.00.zip', 'r') as zip_ref:
zip_ref.extractall() #You can specify the directory inside () to extract to
Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 03, 2021 7:08 pm
by Eli
Test GetDist with this code, see more examples
here:
# Show plots inline, and load main getdist plot module and samples class
from __future__ import print_function
import sys, os
sys.path.insert(0,os.path.realpath(os.path.join(os.getcwd(),'..')))
from getdist import plots, MCSamples
import getdist
# use this *after* importing getdist if you want to use interactive plots
# %matplotlib notebook
import matplotlib.pyplot as plt
import IPython
print('GetDist Version: %s, Matplotlib version: %s'%(getdist.__version__, plt.matplotlib.__version__))
# matplotlib 2 may not work very well without usetex on, can uncomment
# plt.rcParams['text.usetex']=True
#Let test GetDist by getting some random samples for demonstration and then
#make some random covariance, then independent samples from Gaussian
import numpy as np
ndim = 4
nsamp = 10000
np.random.seed(10)
A = np.random.rand(ndim,ndim)
cov = np.dot(A, A.T)
samps = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
A = np.random.rand(ndim,ndim)
cov = np.dot(A, A.T)
samps2 = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
# Get the getdist MCSamples objects for the samples, specifying same parameter
# names and labels; if not specified weights are assumed to all be unity
names = ["x%s"%i for i in range(ndim)]
labels = ["x_%s"%i for i in range(ndim)]
samples1 = MCSamples(samples=samps,names = names, labels = labels)
samples2 = MCSamples(samples=samps2,names = names, labels = labels, label='Second set')
# Triangle plot
g = plots.get_subplot_plotter()
g.triangle_plot([samples1, samples2], filled=True)
plt.show()
# Get 1D marginalized comparison plot
g = plots.get_single_plotter(width_inch=3)
g.plot_1d([samples1, samples2], 'x1')
plt.show()
# Get filled 2D comparison plot with legend
g = plots.get_single_plotter(width_inch=4, ratio=1)
g.plot_2d([samples1, samples2], 'x1', 'x2', filled=True)
g.add_legend(['sim 1', 'sim 2'], colored_text=True);
plt.show()
The outputs are:

Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 03, 2021 7:55 pm
by Eli
Test TensorFlow and Keras with
Fashion MNIST dataset, take over from the code below:
from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
print(test_labels)
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
print(train_images.shape)
print(len(train_labels))
print(train_labels)
print(test_images.shape)
print(len(test_labels))
#Preprocess the data
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 03, 2021 9:16 pm
by Eli
Use
tikzplotlib to convert matplotlib figures into TikZ/PGF Plots for native inclusion into LaTeX or ConTeXt documents.
The output of tikzplotlib is in PGFPlots, a TeX library that sits on top of PGF/TikZ and describes graphs in terms of axes, data and so on:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("ggplot")
t = np.arange(0.0, 2.0, 0.1)
s = np.sin(2 * np.pi * t)
s2 = np.cos(2 * np.pi * t)
plt.plot(t, s, "o-", lw=4.1)
plt.plot(t, s2, "o-", lw=4.1)
plt.xlabel("time (s)")
plt.ylabel("Voltage (mV)")
#plt.title("Simple plot $\\frac{\\alpha}{2}$")
plt.grid(True)
plt.show()
import tikzplotlib
tikzplotlib.save("test.tex")

Re: Programming and Computing with Python Right from the Forum
Posted: Mon Jan 11, 2021 9:43 am
by Eli
Testing
NBODYKIT, a massively parallel, large-scale structure toolkit (see
this paper):
from nbodykit.lab import *
import numpy as np
import matplotlib.pyplot as plt
#Below, we create a very simple catalog of uniformly distributed
#particles in a box of side length L=1 h^−1 Mpc
catalog = UniformCatalog(nbar=100, BoxSize=1.0)
BoxSize = 2500.
"""Catalogs have a fixed size and a set of columns describing the particle data.
In this case, our catalog has “Position” and “Velocity” columns.
Users can easily manipulate the existing column data or add new columns"""
catalog['Position'] *= BoxSize # re-normalize units of Position
#catalog['Mass'] = 10**(np.random(12, 15, size=len(catalog))) # add some random mass values
mesh = catalog.to_mesh(Nmesh=64, BoxSize=BoxSize)# Interpolate the particles onto a mesh of size 64^3
#We can save our mesh to disk to later re-load using nbodykit
mesh.save('mesh.bigfile')
#or preview a low-resolution, 2D projection of the mesh to make sure everythings looks as expected
plt.imshow(mesh.preview(axes=[0,1], Nmesh=32))
plt.show()
#Use the FFTPower algorithm to compute the power spectrum P(k,μ)
#of the density mesh using a fast Fourier transform via
result = FFTPower(mesh,mode="2d", Nmu=5)
#with the measured power stored as the power attribute of the result variable.
#The algorithm result and meta-data, input parameters, etc. can then be saved to disk as a JSON file
result.save("power-result.json")

Re: Programming and Computing with Python Right from the Forum
Posted: Tue Jan 12, 2021 11:59 am
by Admin
NLTK - the Natural Language Toolkit is installed, test it:
import nltk
#Simple nltk demo, Tokenize and tag some text
sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good."""
print(sentence)
nltk.download('punkt')
tokens = nltk.word_tokenize(sentence)
print(tokens)
nltk.download('averaged_perceptron_tagger')
tagged = nltk.pos_tag(tokens)
print(tagged[0:6])
#Identify named entities
nltk.download('maxent_ne_chunker')
nltk.download('words')
entities = nltk.chunk.ne_chunk(tagged)
print(entities)
#Display a parse tree:
from nltk.corpus import treebank
nltk.download('treebank')
t = treebank.parsed_sents('wsj_0001.mrg')[0]
print(t)
Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 17, 2021 12:27 am
by Eli
Test SymPy:
from sympy.plotting import plot
from sympy import *
plot( sin(x),cos(x), (x, -pi, pi))
from sympy.plotting import plot
from sympy import *
x=Symbol('x')
plot(x**2, line_color='red')

Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 17, 2021 6:23 pm
by Eli
3-D plotting with SymPy:
from sympy import symbols
from sympy.plotting import plot3d
x, y = symbols('x y')
#Fig 1
plot3d(x*y, (x, -5, 5), (y, -5, 5))
#Fig 2
plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
#Fig 3
plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x*y, (x, -3, 3), (y, -3, 3)))
#Fig 4
from sympy import symbols, cos, sin
from sympy.plotting import plot3d_parametric_surface
u, v = symbols('u v')
plot3d_parametric_surface(cos(u + v), sin(u - v), u - v, (u, -5, 5), (v, -5, 5))

Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 17, 2021 6:38 pm
by Eli
Further examples with SymPy:
from sympy import plot_implicit, symbols, Eq, And
x, y = symbols('x y')
#Fig 1
plot_implicit(y > x**2)
#PlotGrid Class
from sympy import symbols
from sympy.plotting import plot, plot3d, PlotGrid
p1 = plot(x, x**2, x**3, (x, -5, 5))
p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
p3 = plot(x**3, (x, -5, 5))
p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))

Re: Programming and Computing with Python Right from the Forum
Posted: Sun Jan 17, 2021 6:55 pm
by Eli
Plotting options with SymPy:
from sympy import plot_implicit, symbols, Eq, And
x, y = symbols('x y')
#PlotGrid Class
from sympy import symbols
from sympy.plotting import plot, plot3d, PlotGrid
p1 = plot(x, x**2, x**3, (x, -5, 5))
p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
p3 = plot(x**3, (x, -5, 5))
p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
#Plotting vertically in a single line:
PlotGrid(2, 1 , p1, p2)
#Plotting horizontally in a single line:
PlotGrid(1, 3 , p2, p3, p4)
#Plotting in a grid form:
PlotGrid(2, 2, p1, p2 ,p3, p4)
