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:

#11

Test Astropy with the following codes:

  1. from astropy.io import fits
  2. fits_image_filename = fits.util.get_testdata_filepath('test0.fits')
  3.  
  4. hdul = fits.open(fits_image_filename)
  5.  
  6. hdul.info()
  7. #or
  8. with fits.open(fits_image_filename) as hdul:
  9.     hdul.info()


  1. import matplotlib.pyplot as plt
  2. from astropy.visualization import astropy_mpl_style
  3. plt.style.use(astropy_mpl_style)
  4. #import astropy.coordinates as coord
  5. #import astropy.units as u
  6.  
  7. #Download the example FITS files used by this example:
  8. from astropy.utils.data import get_pkg_data_filename
  9. from astropy.io import fits
  10.  
  11. image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
  12.  
  13. #Use astropy.io.fits.info() to display the structure of the file:
  14. fits.info(image_file)
  15.  
  16. #Get image data
  17. image_data = fits.getdata(image_file, ext=0)
  18.  
  19. #The data is now stored as a 2D numpy array. Print the dimensions using the shape attribute:
  20. print(image_data.shape)
  21.  
  22. #Display the image data:
  23. plt.figure()
  24. plt.imshow(image_data, cmap='gray')
  25. plt.colorbar()
  26. 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:

#12

We can read various datasets in different formats from any public server.

For example, the two code samples below will read some datasets in HDF5 format located at here

  1. import h5py
  2. import urllib.request
  3.  
  4. urllib.request.urlretrieve('https://ndownloader.figshare.com/files/7024271', 'NEONDSImagingSpectrometerData.h5')
  5.  
  6. f = h5py.File('./NEONDSImagingSpectrometerData.h5', 'r')
  7. #Check data keys
  8. keys = f.keys()
  9. r = f['Reflectance']
  10. print(r.shape)


  1. import h5py
  2. import urllib.request
  3.  
  4. urllib.request.urlretrieve('https://ndownloader.figshare.com/files/7024985', 'NEONDSTowerTemperatureData.hdf5')
  5.  
  6. f = h5py.File('./NEONDSTowerTemperatureData.hdf5', 'r')
  7. #Check keys
  8. keys = f.keys()
  9. data1 = f['Domain_03']
  10. print(data1)

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:

#13

We can programmatically extract various zipped, .tar.gz files, etc., and use them the way we want.

Extract zipped files located here in the current working directory:

  1. import zipfile
  2. import urllib.request
  3.  
  4. urllib.request.urlretrieve("https://github.com/harvard-lts/fits/releases/download/1.4.0/fits-latest.zip", "fits-latest.zip")
  5.  
  6. with zipfile.ZipFile('./fits-latest.zip', 'r') as zip_ref:
  7.     zip_ref.extractall() #You can specify the directory inside () to extract to



Extract the entire tar.gz archive to the current working directory:

  1. import tarfile
  2. import urllib.request
  3.  
  4. urllib.request.urlretrieve("https://heasarc.gsfc.nasa.gov/FTP/software/lheasoft/fv/fv5.5.2_Linux.tar.gz", "fv5.5.2_Linux.tar.gz")
  5. #See more approaches at https://docs.python.org/3/library/tarfile.html
  6. tar = tarfile.open("./fv5.5.2_Linux.tar.gz")
  7. tar.extractall()
  8. tar.close()



Extract a subset of a tar archive with TarFile.extractall() using a generator function:

  1. import tarfile
  2. import urllib.request
  3. import os
  4. import tarfile
  5.  
  6. def py_files(members):
  7.     for tarinfo in members:
  8.         if os.path.splitext(tarinfo.name)[1] == ".py":
  9.             yield tarinfo
  10.  
  11. urllib.request.urlretrieve("http://sidekick.epfl.ch/datasets/kickstarter-etter-cosn2013.tar.gz", "kickstarter-etter-cosn2013.tar.gz")
  12. #See more approaches at https://docs.python.org/3/library/tarfile.html
  13. tar = tarfile.open("./kickstarter-etter-cosn2013.tar.gz")            
  14. tar.extractall(members=py_files(tar))
  15. tar.close()

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:

#14

Run any code with Bokeh and Python, try this example take here:

  1. import numpy as np
  2.  
  3. # Bokeh libraries
  4. from bokeh.io import output_notebook
  5. from bokeh.plotting import figure, show, save
  6.  
  7. # My word count data
  8. day_num = np.linspace(1, 10, 10)
  9. daily_words = [450, 628, 488, 210, 287, 791, 508, 639, 397, 943]
  10. cumulative_words = np.cumsum(daily_words)
  11.  
  12. # Output the visualization directly in the notebook
  13. output_notebook()
  14.  
  15. # Create a figure with a datetime type x-axis
  16. fig = figure(title='My Tutorial Progress',
  17.              plot_height=400, plot_width=700,
  18.              x_axis_label='Day Number', y_axis_label='Words Written',
  19.              x_minor_ticks=2, y_range=(0, 6000),
  20.              toolbar_location=None)
  21.  
  22. # The daily words will be represented as vertical bars (columns)
  23. fig.vbar(x=day_num, bottom=0, top=daily_words,
  24.          color='blue', width=0.75,
  25.          legend_label='Daily')
  26.  
  27. # The cumulative sum will be a trend line
  28. fig.line(x=day_num, y=cumulative_words,
  29.          color='gray', line_width=1,
  30.          legend_label='Cumulative')
  31.  
  32. # Put the legend in the upper left corner
  33. fig.legend.location = 'top_left'
  34.  
  35. # Let's check it out
  36. show(fig)

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:

#15

Read and manipulate any image archived in any public domain/server. For example, let's read this PNG image and check a few things about it:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. #Read and manipulate any image posted at TSSFL Open Discussion Forums
  5. img = plt.imread('https://www.tssfl.com/download/file.php?id=1043&t=1/iris_data.png')
  6. print(img.shape)
  7. plt.imshow(img)
  8. 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:

#16

Do further tests with astropy (Checkout here):

  1. from astropy.coordinates import SkyCoord, EarthLocation
  2. from astropy import coordinates as coord
  3. from astropy.coordinates.tests.utils import randomly_sample_sphere
  4. from astropy.time import Time
  5. from astropy import units as u
  6. import numpy as np
  7.  
  8. #1000 random locations on the sky
  9. ra, dec, _ = randomly_sample_sphere(1000)
  10. coos = SkyCoord(ra, dec)
  11. print(coos)


  1. from time import perf_counter
  2.  
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5.  
  6. from astropy.coordinates.erfa_astrom import erfa_astrom, ErfaAstromInterpolator
  7. from astropy.coordinates import SkyCoord, EarthLocation, AltAz
  8. from astropy.time import Time
  9. import astropy.units as u
  10.  
  11. np.random.seed(1337)
  12.  
  13. # 100_000 times randomly distributed over 12 hours
  14. t = Time('2020-01-01T20:00:00') + np.random.uniform(0, 1, 10_000) * u.hour
  15.  
  16. location = location = EarthLocation(
  17.     lon=-17.89 * u.deg, lat=28.76 * u.deg, height=2200 * u.m
  18. )
  19.  
  20. # A celestial object in ICRS
  21. crab = SkyCoord.from_name("Crab Nebula")
  22.  
  23. # target horizontal coordinate frame
  24. altaz = AltAz(obstime=t, location=location)
  25.  
  26.  
  27. # the reference transform using no interpolation
  28. t0 = perf_counter()
  29. no_interp = crab.transform_to(altaz)
  30. reference = perf_counter() - t0
  31. print(f'No Interpolation took {reference:.4f} s')
  32.  
  33.  
  34. # now the interpolating approach for different time resolutions
  35. resolutions = 10.0**np.arange(-1, 5) * u.s
  36. times = []
  37. seps = []
  38.  
  39. for resolution in resolutions:
  40.     with erfa_astrom.set(ErfaAstromInterpolator(resolution)):
  41.         t0 = perf_counter()
  42.         interp = crab.transform_to(altaz)
  43.         duration = perf_counter() - t0
  44.  
  45.     print(
  46.         f'Interpolation with {resolution.value: 9.1f} {str(resolution.unit)}'
  47.         f' resolution took {duration:.4f} s'
  48.         f' ({reference / duration:5.1f}x faster) '
  49.     )
  50.     seps.append(no_interp.separation(interp))
  51.     times.append(duration)
  52.  
  53. seps = u.Quantity(seps)
  54.  
  55. fig = plt.figure()
  56.  
  57. ax1, ax2 = fig.subplots(2, 1, gridspec_kw={'height_ratios': [2, 1]}, sharex=True)
  58.  
  59. ax1.plot(
  60.     resolutions.to_value(u.s),
  61.     seps.mean(axis=1).to_value(u.microarcsecond),
  62.     'o', label='mean',
  63. )
  64.  
  65. for p in [25, 50, 75, 95]:
  66.     ax1.plot(
  67.         resolutions.to_value(u.s),
  68.         np.percentile(seps.to_value(u.microarcsecond), p, axis=1),
  69.         'o', label=f'{p}%', color='C1', alpha=p / 100,
  70.     )
  71.  
  72. ax1.set_title('Transformation of SkyCoord with 100.000 obstimes over 12 hours')
  73.  
  74. ax1.legend()
  75. ax1.set_xscale('log')
  76. ax1.set_yscale('log')
  77. ax1.set_ylabel('Angular distance to no interpolation / µas')
  78.  
  79. ax2.plot(resolutions.to_value(u.s), reference / np.array(times), 's')
  80. ax2.set_yscale('log')
  81. ax2.set_ylabel('Speedup')
  82. ax2.set_xlabel('time resolution / s')
  83.  
  84. ax2.yaxis.grid()
  85. fig.tight_layout()
  86. 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:

#17

Test how to create animations with Python and Plotly with this code (see more here):

  1. import plotly.graph_objects as go
  2. import numpy as np
  3. from plotly.offline import plot
  4.  
  5. import pandas as pd
  6.  
  7. url = "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv"
  8. dataset = pd.read_csv(url)
  9.  
  10. years = ["1952", "1962", "1967", "1972", "1977", "1982", "1987", "1992", "1997", "2002",
  11.          "2007"]
  12.  
  13. # make list of continents
  14. continents = []
  15. for continent in dataset["continent"]:
  16.     if continent not in continents:
  17.         continents.append(continent)
  18. # make figure
  19. fig_dict = {
  20.     "data": [],
  21.     "layout": {},
  22.     "frames": []
  23. }
  24.  
  25. # fill in most of layout
  26. fig_dict["layout"]["xaxis"] = {"range": [30, 85], "title": "Life Expectancy"}
  27. fig_dict["layout"]["yaxis"] = {"title": "GDP per Capita", "type": "log"}
  28. fig_dict["layout"]["hovermode"] = "closest"
  29. fig_dict["layout"]["updatemenus"] = [
  30.     {
  31.         "buttons": [
  32.             {
  33.                 "args": [None, {"frame": {"duration": 500, "redraw": False},
  34.                                 "fromcurrent": True, "transition": {"duration": 300,
  35.                                                                     "easing": "quadratic-in-out"}}],
  36.                 "label": "Play",
  37.                 "method": "animate"
  38.             },
  39.             {
  40.                 "args": [[None], {"frame": {"duration": 0, "redraw": False},
  41.                                   "mode": "immediate",
  42.                                   "transition": {"duration": 0}}],
  43.                 "label": "Pause",
  44.                 "method": "animate"
  45.             }
  46.         ],
  47.         "direction": "left",
  48.         "pad": {"r": 10, "t": 87},
  49.         "showactive": False,
  50.         "type": "buttons",
  51.         "x": 0.1,
  52.         "xanchor": "right",
  53.         "y": 0,
  54.         "yanchor": "top"
  55.     }
  56. ]
  57.  
  58. sliders_dict = {
  59.     "active": 0,
  60.     "yanchor": "top",
  61.     "xanchor": "left",
  62.     "currentvalue": {
  63.         "font": {"size": 20},
  64.         "prefix": "Year:",
  65.         "visible": True,
  66.         "xanchor": "right"
  67.     },
  68.     "transition": {"duration": 300, "easing": "cubic-in-out"},
  69.     "pad": {"b": 10, "t": 50},
  70.     "len": 0.9,
  71.     "x": 0.1,
  72.     "y": 0,
  73.     "steps": []
  74. }
  75.  
  76. # make data
  77. year = 1952
  78. for continent in continents:
  79.     dataset_by_year = dataset[dataset["year"] == year]
  80.     dataset_by_year_and_cont = dataset_by_year[
  81.         dataset_by_year["continent"] == continent]
  82.  
  83.     data_dict = {
  84.         "x": list(dataset_by_year_and_cont["lifeExp"]),
  85.         "y": list(dataset_by_year_and_cont["gdpPercap"]),
  86.         "mode": "markers",
  87.         "text": list(dataset_by_year_and_cont["country"]),
  88.         "marker": {
  89.             "sizemode": "area",
  90.             "sizeref": 200000,
  91.             "size": list(dataset_by_year_and_cont["pop"])
  92.         },
  93.         "name": continent
  94.     }
  95.     fig_dict["data"].append(data_dict)
  96.  
  97. # make frames
  98. for year in years:
  99.     frame = {"data": [], "name": str(year)}
  100.     for continent in continents:
  101.         dataset_by_year = dataset[dataset["year"] == int(year)]
  102.         dataset_by_year_and_cont = dataset_by_year[
  103.             dataset_by_year["continent"] == continent]
  104.  
  105.         data_dict = {
  106.             "x": list(dataset_by_year_and_cont["lifeExp"]),
  107.             "y": list(dataset_by_year_and_cont["gdpPercap"]),
  108.             "mode": "markers",
  109.             "text": list(dataset_by_year_and_cont["country"]),
  110.             "marker": {
  111.                 "sizemode": "area",
  112.                 "sizeref": 200000,
  113.                 "size": list(dataset_by_year_and_cont["pop"])
  114.             },
  115.             "name": continent
  116.         }
  117.         frame["data"].append(data_dict)
  118.  
  119.     fig_dict["frames"].append(frame)
  120.     slider_step = {"args": [
  121.         [year],
  122.         {"frame": {"duration": 300, "redraw": False},
  123.          "mode": "immediate",
  124.          "transition": {"duration": 300}}
  125.     ],
  126.         "label": year,
  127.         "method": "animate"}
  128.     sliders_dict["steps"].append(slider_step)
  129.  
  130.  
  131. fig_dict["layout"]["sliders"] = [sliders_dict]
  132.  
  133. fig = go.Figure(fig_dict)
  134.  
  135. plot(fig)

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:

#18

You can plot and visualize various cosmological skys, such as Haslam 408 MHz all-sky maps right here, test this code

  1. import healpy as hp
  2. import urllib.request
  3. import matplotlib.pyplot as plt
  4.  
  5. urllib.request.urlretrieve('http://www.jb.man.ac.uk/research/cosmos/haslam_map/haslam408_dsds_Remazeilles2014.fits', 'haslam408_dsds_Remazeilles2014_ns2048.fits')
  6.  
  7. Haslam_map = hp.fitsfunc.read_map("./haslam408_dsds_Remazeilles2014_ns2048.fits")
  8. hp.mollview(Haslam_map, coord=['G'], unit='K', norm='hist', cbar=False, min= 11, max=100, xsize=2000, title = "Haslam All-Sky 408 MHz Map", return_projected_map=True, hold=True)
  9.  
  10. fig = plt.gcf()
  11. ax = plt.gca()
  12.  
  13. image = ax.get_images()[0]
  14. cbar = fig.colorbar(image,ticks=[11, 100], orientation='horizontal', shrink=0.80, pad=0.025) #shrink = fraction
  15. cbar.ax.set_ylabel("K",  labelpad=20, rotation=360, y=0.14, x=0)
  16. plt.show()


More informative code:

  1. import healpy as hp
  2. import urllib.request
  3. import matplotlib.pyplot as plt
  4.  
  5. urllib.request.urlretrieve('http://www.jb.man.ac.uk/research/cosmos/haslam_map/haslam408_dsds_Remazeilles2014.fits', 'haslam408_dsds_Remazeilles2014_ns2048.fits')
  6.  
  7. Haslam_map = hp.fitsfunc.read_map("./haslam408_dsds_Remazeilles2014_ns2048.fits")
  8. hp.visufunc.mollview(Haslam_map, coord=['G'], title=r"${\rm Haslam \ All-Sky \ 408 \ MHz \ Map}$", norm='hist',
  9. xsize=2000, flip='astro', min=0, max=200,remove_dip=False, remove_mono=False, gal_cut=0, format='%g',
  10. format2='%g', cbar=None, cmap=None, notext=False, hold=False, margins=None,
  11. sub=None, return_projected_map=False)
  12. fig = plt.gcf()
  13. ax = plt.gca()
  14. image = ax.get_images()[0]
  15. cbar = fig.colorbar(image, ticks=[0,  200], orientation='horizontal', shrink=0.80, pad=0.025) #shrink = fraction
  16. #cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])  #horizontal colorbar
  17. #cbar_txt="K"
  18. #cbar.set_label(cbar_txt, labelpad=0.2)
  19. #ColorbarBase.set_label, The argument of labelpad is given in points (1/72 inch).
  20. #y accepts values in [0, 1], 0.0 is the lower border and 1.0 the upper.
  21. cbar.ax.set_ylabel(r"${\rm K}$",  labelpad=20, rotation=360, y=0.14, x=0)
  22. textstr = 'Created at \nwww.tssfl.com'
  23. #plt.text(0.02, 0.5, textstr, fontsize=14, transform=plt.gcf().transFigure)
  24. plt.gcf().text(0.04, 0.92, textstr, fontsize=14, color='green') # (0,0) is bottom left, (1,1) is top right
  25.  plt.show()


which produce a map similar to:
Attachments
Haslam_408_MHz_all_sky_map.png
(169.76 KiB) Not downloaded yet
Haslam_408_MHz_all_sky_map.png
(169.76 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:

#19

Produce a list of named Python colors with the following code from Matplotlib documenation:

  1. import matplotlib.pyplot as plt
  2. import matplotlib.colors as mcolors
  3.  
  4.  
  5. def plot_colortable(colors, title, sort_colors=True, emptycols=0):
  6.  
  7.     cell_width = 212
  8.     cell_height = 22
  9.     swatch_width = 48
  10.     margin = 12
  11.     topmargin = 40
  12.  
  13.     # Sort colors by hue, saturation, value and name.
  14.     if sort_colors is True:
  15.         by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
  16.                          name)
  17.                         for name, color in colors.items())
  18.         names = [name for hsv, name in by_hsv]
  19.     else:
  20.         names = list(colors)
  21.  
  22.     n = len(names)
  23.     ncols = 4 - emptycols
  24.     nrows = n // ncols + int(n % ncols > 0)
  25.  
  26.     width = cell_width * 4 + 2 * margin
  27.     height = cell_height * nrows + margin + topmargin
  28.     dpi = 72
  29.  
  30.     fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
  31.     fig.subplots_adjust(margin/width, margin/height,
  32.                         (width-margin)/width, (height-topmargin)/height)
  33.     ax.set_xlim(0, cell_width * 4)
  34.     ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
  35.     ax.yaxis.set_visible(False)
  36.     ax.xaxis.set_visible(False)
  37.     ax.set_axis_off()
  38.     ax.set_title(title, fontsize=24, loc="left", pad=10)
  39.  
  40.     for i, name in enumerate(names):
  41.         row = i % nrows
  42.         col = i // nrows
  43.         y = row * cell_height
  44.  
  45.         swatch_start_x = cell_width * col
  46.         swatch_end_x = cell_width * col + swatch_width
  47.         text_pos_x = cell_width * col + swatch_width + 7
  48.  
  49.         ax.text(text_pos_x, y, name, fontsize=14,
  50.                 horizontalalignment='left',
  51.                 verticalalignment='center')
  52.  
  53.         ax.hlines(y, swatch_start_x, swatch_end_x,
  54.                   color=colors[name], linewidth=18)
  55.  
  56.     return fig
  57.  
  58. plot_colortable(mcolors.BASE_COLORS, "Base Colors",
  59.                 sort_colors=False, emptycols=1)
  60. plot_colortable(mcolors.TABLEAU_COLORS, "Tableau Palette",
  61.                 sort_colors=False, emptycols=2)
  62.  
  63. #sphinx_gallery_thumbnail_number = 3
  64. plot_colortable(mcolors.CSS4_COLORS, "CSS Colors")
  65.  
  66. # Optionally plot the XKCD colors (Caution: will produce large figure)
  67. #xkcd_fig = plot_colortable(mcolors.XKCD_COLORS, "XKCD Colors")
  68. #xkcd_fig.savefig("XKCD_Colors.png")
  69.  
  70. plt.show()

Attachments
list_of_python_colors.png
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:

#20

Here is the Python code by Prof. Geoff Boeing to animate the Lorenz Attractor. You can run it here.

  1. import numpy as np, matplotlib.pyplot as plt, glob, os
  2. import IPython.display as IPdisplay, matplotlib.font_manager as fm
  3. from scipy.integrate import odeint
  4. from mpl_toolkits.mplot3d.axes3d import Axes3D
  5. from PIL import Image
  6.  
  7. # define the fonts to use for plots
  8. family = 'Myriad Pro'
  9. title_font = fm.FontProperties(family=family, style='normal', size=20, weight='normal', stretch='normal')
  10.  
  11. save_folder = 'images/lorenz-animate'
  12. if not os.path.exists(save_folder):
  13.     os.makedirs(save_folder)
  14.  
  15. # define the initial system state (aka x, y, z positions in space)
  16. initial_state = [0.1, 0, 0]
  17.  
  18. # define the system parameters sigma, rho, and beta
  19. sigma = 10.
  20. rho   = 28.
  21. beta  = 8./3.
  22.  
  23. # define the time points to solve for, evenly spaced between the start and end times
  24. start_time = 1
  25. end_time = 60
  26. interval = 100
  27. time_points = np.linspace(start_time, end_time, end_time * interval)
  28.  
  29. # define the lorenz system
  30. def lorenz_system(current_state, t):
  31.     x, y, z = current_state
  32.     dx_dt = sigma * (y - x)
  33.     dy_dt = x * (rho - z) - y
  34.     dz_dt = x * y - beta * z
  35.     return [dx_dt, dy_dt, dz_dt]
  36.  
  37. # plot the system in 3 dimensions
  38. def plot_lorenz(xyz, n):
  39.     fig = plt.figure(figsize=(12, 9))
  40.     ax = fig.gca(projection='3d')
  41.     ax.xaxis.set_pane_color((1,1,1,1))
  42.     ax.yaxis.set_pane_color((1,1,1,1))
  43.     ax.zaxis.set_pane_color((1,1,1,1))
  44.     x = xyz[:, 0]
  45.     y = xyz[:, 1]
  46.     z = xyz[:, 2]
  47.     ax.plot(x, y, z, color='g', alpha=0.7, linewidth=0.7)
  48.     ax.set_xlim((-30,30))
  49.     ax.set_ylim((-30,30))
  50.     ax.set_zlim((0,50))
  51.     ax.set_title('Lorenz system attractor', fontproperties=title_font)
  52.    
  53.     plt.savefig('{}/{:03d}.png'.format(save_folder, n), dpi=60, bbox_inches='tight', pad_inches=0.1)
  54.     plt.close()
  55.  
  56. # return a list in iteratively larger chunks
  57. def get_chunks(full_list, size):
  58.     size = max(1, size)
  59.     chunks = [full_list[0:i] for i in range(1, len(full_list) + 1, size)]
  60.     return chunks
  61.  
  62. # get incrementally larger chunks of the time points, to reveal the attractor one frame at a time
  63. chunks = get_chunks(time_points, size=20)
  64.  
  65. # get the points to plot, one chunk of time steps at a time, by integrating the system of equations
  66. points = [odeint(lorenz_system, initial_state, chunk) for chunk in chunks]
  67.  
  68. # plot each set of points, one at a time, saving each plot
  69. for n, point in enumerate(points):
  70.     plot_lorenz(point, n)
  71.  
  72.    
  73. #Animate it
  74. # create a tuple of display durations, one for each frame
  75. first_last = 100 #show the first and last frames for 100 ms
  76. standard_duration = 5 #show all other frames for 5 ms
  77. durations = tuple([first_last] + [standard_duration] * (len(points) - 2) + [first_last])
  78.  
  79. # load all the static images into a list
  80. images = [Image.open(image) for image in glob.glob('{}/*.png'.format(save_folder))]
  81. gif_filepath = 'images/animated-lorenz-attractor.gif'
  82.  
  83. # save as an animated gif
  84. gif = images[0]
  85. gif.info['duration'] = durations #ms per frame
  86. gif.info['loop'] = 0 #how many times to loop (0=infinite)
  87. gif.save(fp=gif_filepath, format='gif', save_all=True, append_images=images[1:])
  88.  
  89. # verify that the number of frames in the gif equals the number of image files and durations
  90. Image.open(gif_filepath).n_frames == len(images) == len(durations)
  91.  
  92. IPdisplay.Image(url=gif_filepath)



Related Lorenz attractor 2D and 3D static images can be produced by the code below:

  1. import numpy as np, matplotlib.pyplot as plt, matplotlib.font_manager as fm, os
  2. from scipy.integrate import odeint
  3. from mpl_toolkits.mplot3d.axes3d import Axes3D
  4.  
  5. font_family = 'Myriad Pro'
  6. title_font = fm.FontProperties(family=font_family, style='normal', size=20, weight='normal', stretch='normal')
  7.  
  8. save_folder = 'images'
  9. if not os.path.exists(save_folder):
  10.     os.makedirs(save_folder)
  11.  
  12. # define the initial system state (aka x, y, z positions in space)
  13. initial_state = [0.1, 0, 0]
  14.  
  15. # define the system parameters sigma, rho, and beta
  16. sigma = 10.
  17. rho   = 28.
  18. beta  = 8./3.
  19.  
  20. # define the time points to solve for, evenly spaced between the start and end times
  21. start_time = 0
  22. end_time = 100
  23. time_points = np.linspace(start_time, end_time, end_time*100)
  24.  
  25. # define the lorenz system
  26. # x, y, and z make up the system state, t is time, and sigma, rho, beta are the system parameters
  27. def lorenz_system(current_state, t):
  28.    
  29.     # positions of x, y, z in space at the current time point
  30.     x, y, z = current_state
  31.    
  32.     # define the 3 ordinary differential equations known as the lorenz equations
  33.     dx_dt = sigma * (y - x)
  34.     dy_dt = x * (rho - z) - y
  35.     dz_dt = x * y - beta * z
  36.    
  37.     # return a list of the equations that describe the system
  38.     return [dx_dt, dy_dt, dz_dt]
  39.  
  40. # use odeint() to solve a system of ordinary differential equations
  41. # the arguments are:
  42. # 1, a function - computes the derivatives
  43. # 2, a vector of initial system conditions (aka x, y, z positions in space)
  44. # 3, a sequence of time points to solve for
  45. # returns an array of x, y, and z value arrays for each time point, with the initial values in the first row
  46. xyz = odeint(lorenz_system, initial_state, time_points)
  47.  
  48. # extract the individual arrays of x, y, and z values from the array of arrays
  49. x = xyz[:, 0]
  50. y = xyz[:, 1]
  51. z = xyz[:, 2]
  52.  
  53. # plot the lorenz attractor in three-dimensional phase space
  54. fig = plt.figure(figsize=(12, 9))
  55. ax = fig.gca(projection='3d')
  56. ax.xaxis.set_pane_color((1,1,1,1))
  57. ax.yaxis.set_pane_color((1,1,1,1))
  58. ax.zaxis.set_pane_color((1,1,1,1))
  59. ax.plot(x, y, z, color='g', alpha=0.7, linewidth=0.6)
  60. ax.set_title('Lorenz attractor phase diagram', fontproperties=title_font)
  61.  
  62. fig.savefig('{}/lorenz-attractor-3d.png'.format(save_folder), dpi=180, bbox_inches='tight')
  63. plt.show()
  64.  
  65. # now plot two-dimensional cuts of the three-dimensional phase space
  66. fig, ax = plt.subplots(1, 3, sharex=False, sharey=False, figsize=(17, 6))
  67.  
  68. # plot the x values vs the y values
  69. ax[0].plot(x, y, color='r', alpha=0.7, linewidth=0.3)
  70. ax[0].set_title('x-y phase plane', fontproperties=title_font)
  71.  
  72. # plot the x values vs the z values
  73. ax[1].plot(x, z, color='m', alpha=0.7, linewidth=0.3)
  74. ax[1].set_title('x-z phase plane', fontproperties=title_font)
  75.  
  76. # plot the y values vs the z values
  77. ax[2].plot(y, z, color='b', alpha=0.7, linewidth=0.3)
  78. ax[2].set_title('y-z phase plane', fontproperties=title_font)
  79.  
  80. fig.savefig('{}/lorenz-attractor-phase-plane.png'.format(save_folder), dpi=180, bbox_inches='tight')
  81. plt.show()


See a different parameterization to visualize the Lorenz system with R at solving-differential-equations-in-r-189
Attachments
animated-lorenz-attractor.gif
animated-lorenz-attractor.gif (3.12 MiB) Viewed 1789 times
animated-lorenz-attractor.gif
animated-lorenz-attractor.gif (3.12 MiB) Viewed 1789 times
Lorenz2D.png
Lorenz3D.png
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 9 guests