Live Programming and Computing with Python, R, Sage, Octave, Maxima, Singular, Gap, GP, HTML & Macaulay2

User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#21

Extract/unzip and analyze the Planck chains/MCMC samples from the Planck Legacy Archive:

  1. import zipfile
  2. import urllib.request
  3.  
  4. 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")
  5.  
  6. with zipfile.ZipFile('./COM_CosmoParams_base-plikHM-TTTEEE-lowl-lowE_R3.00.zip', 'r') as zip_ref:
  7.     zip_ref.extractall() #You can specify the directory inside () to extract to
  8.    

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#22

Test GetDist with this code, see more examples here:

  1. # Show plots inline, and load main getdist plot module and samples class
  2. from __future__ import print_function
  3. import sys, os
  4. sys.path.insert(0,os.path.realpath(os.path.join(os.getcwd(),'..')))
  5. from getdist import plots, MCSamples
  6. import getdist
  7. # use this *after* importing getdist if you want to use interactive plots
  8. # %matplotlib notebook
  9. import matplotlib.pyplot as plt
  10. import IPython
  11. print('GetDist Version: %s, Matplotlib version: %s'%(getdist.__version__, plt.matplotlib.__version__))
  12. # matplotlib 2 may not work very well without usetex on, can uncomment
  13. # plt.rcParams['text.usetex']=True
  14.  
  15. #Let test GetDist by getting some random samples for demonstration and then
  16. #make some random covariance, then independent samples from Gaussian
  17.  
  18. import numpy as np
  19. ndim = 4
  20. nsamp = 10000
  21. np.random.seed(10)
  22. A = np.random.rand(ndim,ndim)
  23. cov = np.dot(A, A.T)
  24. samps = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
  25. A = np.random.rand(ndim,ndim)
  26. cov = np.dot(A, A.T)
  27. samps2 = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
  28.  
  29. # Get the getdist MCSamples objects for the samples, specifying same parameter
  30. # names and labels; if not specified weights are assumed to all be unity
  31. names = ["x%s"%i for i in range(ndim)]
  32. labels =  ["x_%s"%i for i in range(ndim)]
  33. samples1 = MCSamples(samples=samps,names = names, labels = labels)
  34. samples2 = MCSamples(samples=samps2,names = names, labels = labels, label='Second set')
  35.  
  36. # Triangle plot
  37. g = plots.get_subplot_plotter()
  38. g.triangle_plot([samples1, samples2], filled=True)
  39. plt.show()
  40.  
  41. # Get 1D marginalized comparison plot
  42. g = plots.get_single_plotter(width_inch=3)
  43. g.plot_1d([samples1, samples2], 'x1')
  44. plt.show()
  45.  
  46. # Get filled 2D comparison plot with legend
  47. g = plots.get_single_plotter(width_inch=4, ratio=1)
  48. g.plot_2d([samples1, samples2], 'x1', 'x2', filled=True)
  49. g.add_legend(['sim 1', 'sim 2'], colored_text=True);
  50. plt.show()


The outputs are:


Image
Attachments
gdplot1.png
(79.97 KiB) Not downloaded yet
gdplot1.png
(79.97 KiB) Not downloaded yet
gdplot2.png
gdplot2.png (9.62 KiB) Viewed 1774 times
gdplot2.png
gdplot2.png (9.62 KiB) Viewed 1774 times
gdplot3.png
gdplot3.png (17.53 KiB) Viewed 1774 times
gdplot3.png
gdplot3.png (17.53 KiB) Viewed 1774 times
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#23

Test TensorFlow and Keras with Fashion MNIST dataset, take over from the code below:

  1. from __future__ import absolute_import, division, print_function, unicode_literals
  2. # TensorFlow and tf.keras
  3. import tensorflow as tf
  4. from tensorflow import keras
  5.  
  6. # Helper libraries
  7. import numpy as np
  8. import matplotlib.pyplot as plt
  9.  
  10. print(tf.__version__)
  11.  
  12. fashion_mnist = tf.keras.datasets.fashion_mnist
  13.  
  14. (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
  15.  
  16. print(test_labels)
  17.  
  18. class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
  19.                'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
  20.  
  21. print(train_images.shape)
  22. print(len(train_labels))
  23. print(train_labels)
  24. print(test_images.shape)
  25. print(len(test_labels))
  26.  
  27. #Preprocess the data
  28. plt.figure()
  29. plt.imshow(train_images[0])
  30. plt.colorbar()
  31. plt.grid(False)
  32. plt.show()

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#24

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:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. plt.style.use("ggplot")
  5.  
  6. t = np.arange(0.0, 2.0, 0.1)
  7. s = np.sin(2 * np.pi * t)
  8. s2 = np.cos(2 * np.pi * t)
  9. plt.plot(t, s, "o-", lw=4.1)
  10. plt.plot(t, s2, "o-", lw=4.1)
  11. plt.xlabel("time (s)")
  12. plt.ylabel("Voltage (mV)")
  13. #plt.title("Simple plot $\\frac{\\alpha}{2}$")
  14. plt.grid(True)
  15. plt.show()
  16.  
  17. import tikzplotlib
  18.  
  19. tikzplotlib.save("test.tex")


Image
Attachments
tikz_convert.png
(46.74 KiB) Not downloaded yet
tikz_convert.png
(46.74 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#25

Testing NBODYKIT, a massively parallel, large-scale structure toolkit (see this paper):

  1. from nbodykit.lab import *
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. #Below, we create a very simple catalog of uniformly distributed
  5. #particles in a box of side length L=1 h^−1 Mpc
  6. catalog = UniformCatalog(nbar=100, BoxSize=1.0)
  7. BoxSize = 2500.
  8. """Catalogs have a fixed size and a set of columns describing the particle data.
  9. In this case, our catalog has “Position” and “Velocity” columns.
  10. Users can easily manipulate the existing column data or add new columns"""
  11. catalog['Position'] *= BoxSize # re-normalize units of Position
  12. #catalog['Mass'] = 10**(np.random(12, 15, size=len(catalog))) # add some random mass values
  13. mesh = catalog.to_mesh(Nmesh=64, BoxSize=BoxSize)# Interpolate the particles onto a mesh of size 64^3
  14. #We can save our mesh to disk to later re-load using nbodykit
  15. mesh.save('mesh.bigfile')
  16. #or preview a low-resolution, 2D projection of the mesh to make sure everythings looks as expected
  17. plt.imshow(mesh.preview(axes=[0,1], Nmesh=32))
  18. plt.show()
  19. #Use the FFTPower algorithm to compute the power spectrum P(k,μ)
  20. #of the density mesh using a fast Fourier transform via
  21.  
  22. result = FFTPower(mesh,mode="2d", Nmu=5)
  23.  
  24. #with the measured power stored as the power attribute of the result variable.
  25. #The algorithm result and meta-data, input parameters, etc. can then be saved to disk as a JSON file
  26. result.save("power-result.json")

Image
Attachments
nbodykit_catalog.png
(10.59 KiB) Not downloaded yet
nbodykit_catalog.png
(10.59 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Admin
Site Admin
Senior Expert Member
Reactions: 56
Posts: 383
Joined: 10 years ago
Has thanked: 38 times
Been thanked: 32 times
Contact:

#26

NLTK - the Natural Language Toolkit is installed, test it:

  1. import nltk
  2.  
  3. #Simple nltk demo, Tokenize and tag some text
  4.  
  5. sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good."""
  6. print(sentence)
  7. nltk.download('punkt')
  8. tokens = nltk.word_tokenize(sentence)
  9. print(tokens)
  10.  
  11. nltk.download('averaged_perceptron_tagger')
  12. tagged = nltk.pos_tag(tokens)
  13. print(tagged[0:6])
  14.  
  15. #Identify named entities
  16. nltk.download('maxent_ne_chunker')
  17. nltk.download('words')
  18. entities = nltk.chunk.ne_chunk(tagged)
  19. print(entities)
  20.  
  21. #Display a parse tree:
  22.  
  23. from nltk.corpus import treebank
  24. nltk.download('treebank')
  25. t = treebank.parsed_sents('wsj_0001.mrg')[0]
  26. print(t)

0
TSSFL Stack is dedicated to empowering and accelerating teaching and learning, fostering scientific research, and promoting rapid software development and digital technologies
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#27

Test SymPy:

  1. from sympy.plotting import plot
  2. from sympy import *
  3. plot( sin(x),cos(x), (x, -pi, pi))



Image


  1. from sympy.plotting import plot
  2. from sympy import *
  3. x=Symbol('x')
  4. plot(x**2, line_color='red')


Image
Attachments
sympy3.png
(39.53 KiB) Not downloaded yet
sympy3.png
(39.53 KiB) Not downloaded yet
sympy_plot.png
(21.57 KiB) Not downloaded yet
sympy_plot.png
(21.57 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#28

3-D plotting with SymPy:

  1. from sympy import symbols
  2. from sympy.plotting import plot3d
  3.  
  4. x, y = symbols('x y')
  5. #Fig 1
  6. plot3d(x*y, (x, -5, 5), (y, -5, 5))
  7. #Fig 2
  8. plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
  9. #Fig 3
  10. plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x*y, (x, -3, 3), (y, -3, 3)))
  11. #Fig 4
  12. from sympy import symbols, cos, sin
  13. from sympy.plotting import plot3d_parametric_surface
  14. u, v = symbols('u v')
  15. plot3d_parametric_surface(cos(u + v), sin(u - v), u - v, (u, -5, 5), (v, -5, 5))


Image

Image

Image

Image
Attachments
example1.png
(128.56 KiB) Not downloaded yet
example1.png
(128.56 KiB) Not downloaded yet
example2.png
(160.44 KiB) Not downloaded yet
example2.png
(160.44 KiB) Not downloaded yet
example3.png
(149.97 KiB) Not downloaded yet
example3.png
(149.97 KiB) Not downloaded yet
example4.png
(85.53 KiB) Not downloaded yet
example4.png
(85.53 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#29

Further examples with SymPy:


  1. from sympy import plot_implicit, symbols, Eq, And
  2. x, y = symbols('x y')
  3. #Fig 1
  4. plot_implicit(y > x**2)
  5.  
  6. #PlotGrid Class
  7. from sympy import symbols
  8. from sympy.plotting import plot, plot3d, PlotGrid
  9.  
  10. p1 = plot(x, x**2, x**3, (x, -5, 5))
  11. p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
  12. p3 = plot(x**3, (x, -5, 5))
  13. p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))


Image

Image

Image

Image

Image
Attachments
example1.png
(9.06 KiB) Not downloaded yet
example1.png
(9.06 KiB) Not downloaded yet
example2.png
(22.67 KiB) Not downloaded yet
example2.png
(22.67 KiB) Not downloaded yet
example3.png
(24.71 KiB) Not downloaded yet
example3.png
(24.71 KiB) Not downloaded yet
example4.png
(17.47 KiB) Not downloaded yet
example4.png
(17.47 KiB) Not downloaded yet
example5.png
(128.56 KiB) Not downloaded yet
example5.png
(128.56 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#30

Plotting options with SymPy:


  1. from sympy import plot_implicit, symbols, Eq, And
  2. x, y = symbols('x y')
  3.  
  4. #PlotGrid Class
  5. from sympy import symbols
  6. from sympy.plotting import plot, plot3d, PlotGrid
  7.  
  8. p1 = plot(x, x**2, x**3, (x, -5, 5))
  9. p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
  10. p3 = plot(x**3, (x, -5, 5))
  11. p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
  12.  
  13. #Plotting vertically in a single line:
  14. PlotGrid(2, 1 , p1, p2)
  15.  
  16. #Plotting horizontally in a single line:
  17. PlotGrid(1, 3 , p2, p3, p4)
  18.  
  19. #Plotting in a grid form:
  20. PlotGrid(2, 2, p1, p2 ,p3, p4)



Image

Image

Image
Attachments
example1.png
(33.2 KiB) Not downloaded yet
example1.png
(33.2 KiB) Not downloaded yet
example2.png
(66.81 KiB) Not downloaded yet
example2.png
(66.81 KiB) Not downloaded yet
example3.png
(82.69 KiB) Not downloaded yet
example3.png
(82.69 KiB) Not downloaded yet
0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply
  • Similar Topics
    Replies
    Views
    Last post

Return to “Technologies for Teaching, Learning, Research, Problem Solving and Business”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 10 guests