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:
# import the necessary packages
from keras.applications import ResNet50
from keras.preprocessing.image import img_to_array
from keras.applications import imagenet_utils
from PIL import Image
import numpy as np
import flask
import io
# Initialize our Flask application and the Keras model
app = flask.Flask("__name__")
model = None
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)
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(' ')
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(
children='Hello Dash',
style={
'textAlign': 'center',
'color': colors['text']
}
),
html.Div(children='Dash: A web application framework for Python.', style={
'textAlign': 'center',
'color': colors['text']
}),
dcc.Graph(
id='Graph1',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background'],
'font': {
'color': colors['text']
}
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
app = dash.Dash(' ')
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
'gdp-life-exp-2007.csv')
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x=df[df['continent'] == i]['gdp per capita'],
y=df[df['continent'] == i]['life expectancy'],
text=df[df['continent'] == i]['country'],
mode='markers',
opacity=0.8,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
if __name__ == '__main__':
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:
from __future__ import division
from sympy import *
x, y = symbols('x y')
from sympy.plotting import plot3d
monkey_saddle = x**3 - 3*x*y**2
p = plot3d(monkey_saddle, (x, -2, 2), (y, -2, 2))

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
library(deSolve)
# Define parameters and initial conditions
a <- -8/3; b <- -10; c <- 28
#Create a three-valued vector of initial conditions using c function
yini <- c(X = 1, Y = 1, Z = 1)
Lorenz <- function(t, y, parms){with (as.list(y), {dX <- a*X + Y*Z; dY <- b*(Y - Z); dZ <- -X*Y + c*Y - Z;
list(c(dX, dY, dZ))})}
# We solve the IVP for 100 days producing the output after every 0.01 days
times <- seq(from = 0, to = 100, by = 0.01)
#Integrate
out <- ode(y = yini, times = times, func = Lorenz, parms = NULL)
# We check the output by printing out the first five lines
head(out, n = 5)
plot(out, lwd = 2)
# Plot variables Y versus X to generate the famous butterfly
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
par(mfrow=c(1,1),mar=c(0,0,0,0),oma=c(1,1,1,1))
plot(0,0,type="n", xlim=c(-2,32), ylim=c(3,27),
xaxs="i", yaxs="i", axes=FALSE, xlab=NA, ylab=NA,
asp=1)
for (j in 0:35) {
for (i in 0:35) {
R <- 8
alpha <- j*10
X <- 15+R*cos(alpha/180*pi)
Y <- 15+R*sin(alpha/180*pi)
r <- 3
beta <- i*10
x <- 15+r*cos(beta/180*pi)
y <- 15+r*sin(beta/180*pi)
d1 <- sqrt((X-x)^2+(Y-y)^2)
xc <- x
yc <- y
n <- 180-atan((Y-y)/(X-x))/pi*180
alpha2 <- -(0:n)
theta <- alpha2/180*pi
b <- d1/(n/180*pi)
r <- b*theta
x1 <- xc+r*cos(theta)
y1 <- yc+r*sin(theta)
lines(x1,y1, col="black")
}
}
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.
def sigmoid(x):
a = []
for item in x:
a.append(1/(1+math.exp(-item)))
return a
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10., 10., 0.2)
sig = sigmoid(x)
plt.plot(x,sig)
xcoords = [0.0]
for xc in xcoords:
plt.axvline(x=xc)
plt.ylim(top=1.0) # adjust the top leaving bottom unchanged
plt.ylim(bottom=0.0)
plt.rc('grid', linestyle="-", color='black')
plt.grid(True)
plt.show()
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.
# Import the class
import kmapper as km
# Some sample data
from sklearn import datasets
data, labels = datasets.make_circles(n_samples=5000, noise=0.03, factor=0.3)
# Initialize
mapper = km.KeplerMapper(verbose=1)
# Fit to and transform the data
projected_data = mapper.fit_transform(data, projection=[0,1]) # X-Y axis
# Create dictionary called 'graph' with nodes, edges and meta-information
graph = mapper.map(projected_data, data, cover=km.Cover(n_cubes=10))
# Visualize it
mapper.visualize(graph, path_html="make_circles_keplermapper_output.html",
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
print("Welcome to TSSFL ODF")
import matplotlib.pyplot as plt
import numpy as np
N = 5
menMeans = (20, 35, 30, 35, -27)
womenMeans = (25, 32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
p2 = ax.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd, label='Women')
ax.axhline(0, color='grey', linewidth=0.8)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, labels=['G1', 'G2', 'G3', 'G4', 'G5'])
ax.legend()
# Label with label_type 'center' instead of the default 'edge'
ax.bar_label(p1, label_type='center')
ax.bar_label(p2, label_type='center')
ax.bar_label(p2)
plt.show()
Code 2
import matplotlib.pyplot as plt
import numpy as np
N = 5
menMeans = (20, 35, 30, 35, -27)
womenMeans = (25, 32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
# Fixing random state for reproducibility
np.random.seed(19680801)
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
fig, ax = plt.subplots()
hbars = ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
# Label with specially formatted floats
ax.bar_label(hbars, fmt='%.2f')
ax.set_xlim(right=15) # adjust xlim to fit labels
plt.show()
Code 3
import matplotlib.pyplot as plt
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
ax.bar(labels, men_means, width, yerr=men_std, label='Men')
ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
Code 4
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x, labels)
ax.legend()
ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
fig.tight_layout()
plt.show()
Code 5 from
here
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
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+'],
'Male': [-49228000, -61283000, -64391000, -52437000, -42955000, -44667000, -31570000, -23887000, -22390000, -20971000, -17685000, -15450000, -13932000, -11020000, -7611000, -4653000, -1952000, -625000, -116000, -14000, -1000],
'Female': [52367000, 64959000, 67161000, 55388000, 45448000, 47129000, 33436000, 26710000, 25627000, 23612000, 20075000, 16368000, 14220000, 10125000, 5984000, 3131000, 1151000, 312000, 49000, 4000, 0]})
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']
bar_plot = sns.barplot(x='Male', y='Age', data=df, order=AgeClass, lw=0)
bar_plot = sns.barplot(x='Female', y='Age', data=df, order=AgeClass, lw=0)
bar_plot.set(xlabel="Population (hundreds of millions)", ylabel="Age-Group", title = "Population Pyramid")
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:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
kw = dict(color='#FF9900', linestyle='-', linewidth=1.5)
lon, lat = np.loadtxt('https://raw.githubusercontent.com/ocefpaf/2016-Python-course-CBO/master/notebooks/data/challenger_path.csv', delimiter=',', unpack=True)
def make_cartopy(projection=ccrs.Robinson(), figsize=(6, 4), resolution='110m'):
fig, ax = plt.subplots(figsize=figsize, subplot_kw=dict(projection=projection))
ax.set_global()
ax.coastlines(resolution=resolution, color='k')
# Only PlateCarree and Mercator plots are currently supported.
gl = ax.gridlines(draw_labels=False)
ax.add_feature(cfeature.LAND, facecolor='0.75')
return fig, ax
fig, ax = make_cartopy(projection=ccrs.Robinson(), resolution='110m')
_ = ax.plot(lon, lat, transform=ccrs.Geodetic(), **kw)
plt.show()
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
# Save the plot by calling plt.savefig() BEFORE plt.show()
#plt.savefig('coastlines.pdf')
#plt.savefig('coastlines.png')
plt.show()]
Plot the Mollweide projection with the use of stock_img
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
textstr = 'Created at www.tssfl.com'
ax = plt.axes(projection=ccrs.Mollweide())
ax.stock_img()
plt.gcf().text(0.3, 0.80, textstr, fontsize=14, color='green')
plt.show()
Add data to the map
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()
ny_lon, ny_lat = -75, 43
delhi_lon, delhi_lat = 77.23, 28.61
plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
color='blue', linewidth=2, marker='o',
transform=ccrs.Geodetic(),
)
plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
color='gray', linestyle='--',
transform=ccrs.PlateCarree(),
)
plt.text(ny_lon - 3, ny_lat - 12, 'New York',
horizontalalignment='right',
transform=ccrs.Geodetic())
plt.text(delhi_lon + 3, delhi_lat - 12, 'Delhi',
horizontalalignment='left',
transform=ccrs.Geodetic())
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:
load("https://raw.githubusercontent.com/TSSFL/Demos/main/iris.py")