Page 5 of 6

Re: Programming and Computing with Python Right from the Forum

Posted: Wed Apr 07, 2021 6:53 pm
by Eli
Further testing of Keras:

  1. # import the necessary packages
  2. from keras.applications import ResNet50
  3. from keras.preprocessing.image import img_to_array
  4. from keras.applications import imagenet_utils
  5. from PIL import Image
  6. import numpy as np
  7. import flask
  8. import io
  9.  
  10. # Initialize our Flask application and the Keras model
  11. app = flask.Flask("__name__")
  12. model = None
  13. print("Hello World")


Re: Programming and Computing with Python Right from the Forum

Posted: Wed Apr 07, 2021 7:10 pm
by Eli
Test these Dash apps (taken from here)

  1. import dash
  2. import dash_core_components as dcc
  3. import dash_html_components as html
  4.  
  5. app = dash.Dash(' ')
  6. colors = {
  7.     'background': '#111111',
  8.     'text': '#7FDBFF'
  9. }
  10. app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
  11.     html.H1(
  12.         children='Hello Dash',
  13.         style={
  14.             'textAlign': 'center',
  15.             'color': colors['text']
  16.         }
  17.     ),
  18.     html.Div(children='Dash: A web application framework for Python.', style={
  19.         'textAlign': 'center',
  20.         'color': colors['text']
  21.     }),
  22.     dcc.Graph(
  23.         id='Graph1',
  24.         figure={
  25.             'data': [
  26.                 {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
  27.                 {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'MontrĂ©al'},
  28.             ],
  29.             'layout': {
  30.                 'plot_bgcolor': colors['background'],
  31.                 'paper_bgcolor': colors['background'],
  32.                 'font': {
  33.                     'color': colors['text']
  34.                 }
  35.             }
  36.         }
  37.     )
  38. ])
  39.  
  40. if __name__ == '__main__':
  41.     app.run_server(debug=True)
  42.    


  1. import dash
  2. import dash_core_components as dcc
  3. import dash_html_components as html
  4. import pandas as pd
  5. import plotly.graph_objs as go
  6.  
  7. app = dash.Dash(' ')
  8.  
  9. df = pd.read_csv(
  10.     'https://gist.githubusercontent.com/chriddyp/' +
  11.     '5d1ea79569ed194d432e56108a04d188/raw/' +
  12.     'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
  13.     'gdp-life-exp-2007.csv')
  14.  
  15.  
  16. app.layout = html.Div([
  17.     dcc.Graph(
  18.         id='life-exp-vs-gdp',
  19.         figure={
  20.             'data': [
  21.                 go.Scatter(
  22.                     x=df[df['continent'] == i]['gdp per capita'],
  23.                     y=df[df['continent'] == i]['life expectancy'],
  24.                     text=df[df['continent'] == i]['country'],
  25.                     mode='markers',
  26.                     opacity=0.8,
  27.                     marker={
  28.                         'size': 15,
  29.                         'line': {'width': 0.5, 'color': 'white'}
  30.                     },
  31.                     name=i
  32.                 ) for i in df.continent.unique()
  33.             ],
  34.             'layout': go.Layout(
  35.                 xaxis={'type': 'log', 'title': 'GDP Per Capita'},
  36.                 yaxis={'title': 'Life Expectancy'},
  37.                 margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
  38.                 legend={'x': 0, 'y': 1},
  39.                 hovermode='closest'
  40.             )
  41.         }
  42.     )
  43. ])
  44.  
  45. if __name__ == '__main__':
  46.     app.run_server()


Re: Programming and Computing with Python Right from the Forum

Posted: Wed Apr 07, 2021 7:20 pm
by Eli
Generate monkey saddle with SymPy:

  1. from __future__ import division
  2. from sympy import *
  3. x, y = symbols('x y')
  4.  
  5. from sympy.plotting import plot3d
  6. monkey_saddle = x**3 - 3*x*y**2
  7. p = plot3d(monkey_saddle, (x, -2, 2), (y, -2, 2))


Image

Re: Programming and Computing with Python Right from the Forum

Posted: Wed Apr 07, 2021 7:45 pm
by Eli
deSolve: Solvers for Initial Value Problems of Differential Equations ('ODE', 'DAE', 'DDE')

Functions that solve initial value problems of a system of first-order ordinary differential equations ('ODE'), of partial differential equations ('PDE'), of differential algebraic equations ('DAE'), and of delay differential equations. The functions provide an interface to the FORTRAN functions 'lsoda', 'lsodar', 'lsode', 'lsodes' of the 'ODEPACK' collection, to the FORTRAN functions 'dvode', 'zvode' and 'daspk' and a C-implementation of solvers of the 'Runge-Kutta' family with fixed or variable time steps. The package contains routines designed for solving 'ODEs' resulting from 1-D, 2-D and 3-D partial differential equations ('PDE') that have been converted to 'ODEs' by numerical differencing. See more at CRAN

Test deSolve with this code here

  1. library(deSolve)
  2. # Define parameters and initial conditions
  3. a <- -8/3; b <- -10; c <- 28
  4. #Create a three-valued vector of initial conditions using c function
  5. yini <- c(X = 1, Y = 1, Z = 1)
  6. Lorenz <- function(t, y, parms){with (as.list(y), {dX <- a*X + Y*Z; dY <- b*(Y - Z); dZ <- -X*Y + c*Y - Z;
  7. list(c(dX, dY, dZ))})}
  8.  
  9. # We solve the IVP for 100 days producing the output after every 0.01 days
  10. times <- seq(from = 0, to = 100, by = 0.01)
  11. #Integrate
  12. out <- ode(y = yini, times = times, func = Lorenz, parms = NULL)
  13. # We check the output by printing out the first five lines
  14. head(out, n = 5)
  15. plot(out, lwd = 2)
  16. # Plot variables Y versus X to generate the famous butterfly
  17. plot(out[,"X"], out[,"Y"], type = "l", xlab = "X", ylab = "Y", main = "Butterfly")


See more examples here: solving-differential-equations-in-r-189

Re: Programming and Computing with Python Right from the Forum

Posted: Wed Apr 07, 2021 8:41 pm
by Eli
A piece of generative art built by Christophe Cariou with R.

Run this code here

  1. par(mfrow=c(1,1),mar=c(0,0,0,0),oma=c(1,1,1,1))
  2. plot(0,0,type="n", xlim=c(-2,32), ylim=c(3,27),
  3.     xaxs="i", yaxs="i", axes=FALSE, xlab=NA, ylab=NA,
  4.     asp=1)
  5.  
  6. for (j in 0:35) {
  7. for (i in 0:35) {
  8.  
  9.     R <- 8
  10.     alpha <- j*10
  11.     X <- 15+R*cos(alpha/180*pi)
  12.     Y <- 15+R*sin(alpha/180*pi)
  13.  
  14.     r <- 3
  15.     beta <- i*10
  16.     x <- 15+r*cos(beta/180*pi)
  17.     y <- 15+r*sin(beta/180*pi)
  18.  
  19.     d1 <- sqrt((X-x)^2+(Y-y)^2)
  20.     xc <- x
  21.     yc <- y
  22.  
  23.   n <- 180-atan((Y-y)/(X-x))/pi*180
  24.  
  25.     alpha2 <- -(0:n)
  26.     theta <- alpha2/180*pi
  27.  
  28.     b <- d1/(n/180*pi)
  29.     r <- b*theta
  30.  
  31.     x1 <- xc+r*cos(theta)
  32.     y1 <- yc+r*sin(theta)
  33.  
  34.     lines(x1,y1, col="black")
  35.  
  36.     }
  37. }


Re: Programming and Computing with Python Right from the Forum

Posted: Sun Apr 11, 2021 11:36 pm
by Eli
Visaulizing Sigmoid function $S(x) = \sigma(x) = \dfrac{1}{1+ e^{-x}}$ in Python.

  1. def sigmoid(x):
  2.     a = []
  3.     for item in x:
  4.         a.append(1/(1+math.exp(-item)))
  5.     return a
  6.  
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9.  
  10. x = np.arange(-10., 10., 0.2)
  11. sig = sigmoid(x)
  12. plt.plot(x,sig)
  13.  
  14. xcoords = [0.0]
  15. for xc in xcoords:
  16.     plt.axvline(x=xc)
  17.  
  18. plt.ylim(top=1.0)  # adjust the top leaving bottom unchanged
  19. plt.ylim(bottom=0.0)
  20. plt.rc('grid', linestyle="-", color='black')
  21. plt.grid(True)
  22. plt.show()

Image

Re: Programming and Computing with Python Right from the Forum

Posted: Tue Jun 29, 2021 11:21 pm
by Eli
This is a Python implementation of the TDA Mapper algorithm taken from here for visualization of high-dimensional data.

  1. # Import the class
  2. import kmapper as km
  3.  
  4. # Some sample data
  5. from sklearn import datasets
  6. data, labels = datasets.make_circles(n_samples=5000, noise=0.03, factor=0.3)
  7.  
  8. # Initialize
  9. mapper = km.KeplerMapper(verbose=1)
  10.  
  11. # Fit to and transform the data
  12. projected_data = mapper.fit_transform(data, projection=[0,1]) # X-Y axis
  13.  
  14. # Create dictionary called 'graph' with nodes, edges and meta-information
  15. graph = mapper.map(projected_data, data, cover=km.Cover(n_cubes=10))
  16.  
  17. # Visualize it
  18. mapper.visualize(graph, path_html="make_circles_keplermapper_output.html",
  19.                  title="make_circles(n_samples=5000, noise=0.03, factor=0.3)")


Re: Programming and Computing with Python Right from the Forum

Posted: Tue May 03, 2022 5:29 pm
by Eli
Test These codes from Matplotlib website

  1. print("Welcome to TSSFL ODF")
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. N = 5
  5. menMeans = (20, 35, 30, 35, -27)
  6. womenMeans = (25, 32, 34, 20, -25)
  7. menStd = (2, 3, 4, 1, 2)
  8. womenStd = (3, 5, 2, 3, 3)
  9. ind = np.arange(N)    # the x locations for the groups
  10. width = 0.35       # the width of the bars: can also be len(x) sequence
  11.  
  12. fig, ax = plt.subplots()
  13. p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
  14. p2 = ax.bar(ind, womenMeans, width,
  15.             bottom=menMeans, yerr=womenStd, label='Women')
  16.  
  17. ax.axhline(0, color='grey', linewidth=0.8)
  18. ax.set_ylabel('Scores')
  19. ax.set_title('Scores by group and gender')
  20. ax.set_xticks(ind, labels=['G1', 'G2', 'G3', 'G4', 'G5'])
  21. ax.legend()
  22. # Label with label_type 'center' instead of the default 'edge'
  23. ax.bar_label(p1, label_type='center')
  24. ax.bar_label(p2, label_type='center')
  25. ax.bar_label(p2)
  26. plt.show()


Code 2

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. N = 5
  5. menMeans = (20, 35, 30, 35, -27)
  6. womenMeans = (25, 32, 34, 20, -25)
  7. menStd = (2, 3, 4, 1, 2)
  8. womenStd = (3, 5, 2, 3, 3)
  9. ind = np.arange(N)    # the x locations for the groups
  10. width = 0.35       # the width of the bars: can also be len(x) sequence
  11.  
  12. # Fixing random state for reproducibility
  13. np.random.seed(19680801)
  14.  
  15. # Example data
  16. people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
  17. y_pos = np.arange(len(people))
  18. performance = 3 + 10 * np.random.rand(len(people))
  19. error = np.random.rand(len(people))
  20.  
  21. fig, ax = plt.subplots()
  22.  
  23. hbars = ax.barh(y_pos, performance, xerr=error, align='center')
  24. ax.set_yticks(y_pos, labels=people)
  25. ax.invert_yaxis()  # labels read top-to-bottom
  26. ax.set_xlabel('Performance')
  27. ax.set_title('How fast do you want to go today?')
  28.  
  29. # Label with specially formatted floats
  30. ax.bar_label(hbars, fmt='%.2f')
  31. ax.set_xlim(right=15)  # adjust xlim to fit labels
  32.  
  33. plt.show()


Code 3

  1. import matplotlib.pyplot as plt
  2.  
  3. labels = ['G1', 'G2', 'G3', 'G4', 'G5']
  4. men_means = [20, 35, 30, 35, 27]
  5. women_means = [25, 32, 34, 20, 25]
  6. men_std = [2, 3, 4, 1, 2]
  7. women_std = [3, 5, 2, 3, 3]
  8. width = 0.35       # the width of the bars: can also be len(x) sequence
  9.  
  10. fig, ax = plt.subplots()
  11.  
  12. ax.bar(labels, men_means, width, yerr=men_std, label='Men')
  13. ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
  14.        label='Women')
  15.  
  16. ax.set_ylabel('Scores')
  17. ax.set_title('Scores by group and gender')
  18. ax.legend()
  19.  
  20. plt.show()


Code 4

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. labels = ['G1', 'G2', 'G3', 'G4', 'G5']
  5. men_means = [20, 34, 30, 35, 27]
  6. women_means = [25, 32, 34, 20, 25]
  7.  
  8. x = np.arange(len(labels))  # the label locations
  9. width = 0.35  # the width of the bars
  10.  
  11. fig, ax = plt.subplots()
  12. rects1 = ax.bar(x - width/2, men_means, width, label='Men')
  13. rects2 = ax.bar(x + width/2, women_means, width, label='Women')
  14.  
  15. # Add some text for labels, title and custom x-axis tick labels, etc.
  16. ax.set_ylabel('Scores')
  17. ax.set_title('Scores by group and gender')
  18. ax.set_xticks(x, labels)
  19. ax.legend()
  20.  
  21. ax.bar_label(rects1, padding=3)
  22. ax.bar_label(rects2, padding=3)
  23.  
  24. fig.tight_layout()
  25.  
  26. plt.show()


Code 5 from here

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import seaborn as sns
  5.  
  6. df = pd.DataFrame({'Age': ['0-4','5-9','10-14','15-19','20-24','25-29','30-34','35-39','40-44','45-49','50-54','55-59','60-64','65-69','70-74','75-79','80-84','85-89','90-94','95-99','100+'],
  7.                     'Male': [-49228000, -61283000, -64391000, -52437000, -42955000, -44667000, -31570000, -23887000, -22390000, -20971000, -17685000, -15450000, -13932000, -11020000, -7611000, -4653000, -1952000, -625000, -116000, -14000, -1000],
  8.                     'Female': [52367000, 64959000, 67161000, 55388000, 45448000, 47129000, 33436000, 26710000, 25627000, 23612000, 20075000, 16368000, 14220000, 10125000, 5984000, 3131000, 1151000, 312000, 49000, 4000, 0]})
  9.  
  10. AgeClass = ['100+','95-99','90-94','85-89','80-84','75-79','70-74','65-69','60-64','55-59','50-54','45-49','40-44','35-39','30-34','25-29','20-24','15-19','10-14','5-9','0-4']
  11.  
  12. bar_plot = sns.barplot(x='Male', y='Age', data=df, order=AgeClass, lw=0)
  13. bar_plot = sns.barplot(x='Female', y='Age', data=df, order=AgeClass, lw=0)
  14.  
  15. bar_plot.set(xlabel="Population (hundreds of millions)", ylabel="Age-Group", title = "Population Pyramid")
  16.  
  17. plt.show()


Re: Programming and Computing with Python Right from the Forum

Posted: Wed May 25, 2022 5:15 pm
by Eli
Basemap has been replaced by Cartopy, test it with this code and data from here:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import cartopy.crs as ccrs
  4. import cartopy.feature as cfeature
  5.  
  6. kw = dict(color='#FF9900', linestyle='-', linewidth=1.5)
  7. lon, lat = np.loadtxt('https://raw.githubusercontent.com/ocefpaf/2016-Python-course-CBO/master/notebooks/data/challenger_path.csv', delimiter=',', unpack=True)
  8.  
  9. def make_cartopy(projection=ccrs.Robinson(), figsize=(6, 4), resolution='110m'):
  10.     fig, ax = plt.subplots(figsize=figsize, subplot_kw=dict(projection=projection))
  11.     ax.set_global()
  12.     ax.coastlines(resolution=resolution, color='k')
  13.     # Only PlateCarree and Mercator plots are currently supported.
  14.     gl = ax.gridlines(draw_labels=False)
  15.     ax.add_feature(cfeature.LAND, facecolor='0.75')
  16.     return fig, ax
  17.  
  18. fig, ax = make_cartopy(projection=ccrs.Robinson(), resolution='110m')
  19. _ = ax.plot(lon, lat, transform=ccrs.Geodetic(), **kw)
  20. plt.show()


  1. import cartopy.crs as ccrs
  2. import matplotlib.pyplot as plt
  3. ax = plt.axes(projection=ccrs.PlateCarree())
  4. ax.coastlines()
  5. # Save the plot by calling plt.savefig() BEFORE plt.show()
  6. #plt.savefig('coastlines.pdf')
  7. #plt.savefig('coastlines.png')
  8. plt.show()]



Plot the Mollweide projection with the use of stock_img

  1. import cartopy.crs as ccrs
  2. import matplotlib.pyplot as plt
  3. textstr = 'Created at www.tssfl.com'
  4. ax = plt.axes(projection=ccrs.Mollweide())
  5. ax.stock_img()
  6. plt.gcf().text(0.3, 0.80, textstr, fontsize=14, color='green')
  7. plt.show()


Add data to the map

  1. import cartopy.crs as ccrs
  2. import matplotlib.pyplot as plt
  3.  
  4. ax = plt.axes(projection=ccrs.PlateCarree())
  5. ax.stock_img()
  6.  
  7. ny_lon, ny_lat = -75, 43
  8. delhi_lon, delhi_lat = 77.23, 28.61
  9.  
  10. plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
  11.          color='blue', linewidth=2, marker='o',
  12.          transform=ccrs.Geodetic(),
  13.          )
  14.  
  15. plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
  16.          color='gray', linestyle='--',
  17.          transform=ccrs.PlateCarree(),
  18.          )
  19.  
  20. plt.text(ny_lon - 3, ny_lat - 12, 'New York',
  21.          horizontalalignment='right',
  22.          transform=ccrs.Geodetic())
  23.  
  24. plt.text(delhi_lon + 3, delhi_lat - 12, 'Delhi',
  25.          horizontalalignment='left',
  26.          transform=ccrs.Geodetic())
  27.  
  28. plt.show()



Ref: [1], [2]

Re: Programming and Computing with Python Right from the Forum

Posted: Mon Jul 18, 2022 7:47 pm
by Eli
Run this one line code:

  1. load("https://raw.githubusercontent.com/TSSFL/Demos/main/iris.py")