Here are a few useful SciPy sample codes showcasing different aspects of the library, including optimization, integration, interpolation, and signal processing.
1. Optimization: Minimizing a Function
This example demonstrates how to minimize a mathematical function using scipy.optimize.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import numpy as np from scipy.optimize import minimize
# Define a function to minimize defobjective_function(x): return x**2 + 10*np.sin(x)
# Initial guess x0 = 2.0
# Perform the minimization result = minimize(objective_function, x0, method='BFGS')
print("Minimum value of the function:", result.fun) print("Value of x that minimizes the function:", result.x)
[Output]
Minimum value of the function: 8.31558557947746
Value of x that minimizes the function: [3.83746713]
2. Integration: Calculating the Area Under a Curve
This example shows how to calculate the definite integral of a function using scipy.integrate.quad.
1 2 3 4 5 6 7 8 9 10
from scipy.integrate import quad
# Define a function to integrate defintegrand(x): return np.exp(-x**2)
# Compute the integral from 0 to infinity result, error = quad(integrand, 0, np.inf)
print("Integral result:", result)
[Output]
Integral result: 0.8862269254527579
3. Interpolation: Interpolating Data Points
This example demonstrates how to interpolate data points using scipy.interpolate.interp1d.
import numpy as np import matplotlib.pyplot as plt from scipy.signal import butter, lfilter
# Generate a noisy signal np.random.seed(0) t = np.linspace(0, 1, 500, endpoint=False) signal = np.sin(2 * np.pi * 7 * t) + 0.5 * np.random.randn(500)
# Design a low-pass filter defbutter_lowpass(cutoff, fs, order=5): nyquist = 0.5 * fs normal_cutoff = cutoff / nyquist b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a
# Apply the filter to the signal deflowpass_filter(data, cutoff, fs, order=5): b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y
# Parameters cutoff = 3.5# Desired cutoff frequency of the filter, Hz fs = 50.0# Sample rate, Hz
# Filter the signal filtered_signal = lowpass_filter(signal, cutoff, fs)
These examples provide a glimpse of the powerful tools available in SciPy for scientific computing, including optimization, integration, interpolation, and signal processing.
PuLP is a Python library used for linear programming (LP) and mixed-integer linear programming (MILP).
It allows you to define and solve optimization problems where you want to minimize or maximize a linear objective function subject to linear constraints.
Installation
First, you need to install PuLP. You can do this using pip:
1
pip install pulp
Basic Usage of PuLP
Here’s a step-by-step guide to solving a simple linear programming problem with PuLP.
Example Problem:
Suppose you are a factory manager and you want to determine the optimal number of products $A$ and $B$ to produce to maximize your profit. Each product requires a certain amount of resources (time, materials) and yields a certain profit.
Objective: Maximize profit.
Constraints:
You have $100$ units of material.
You have $80$ hours of labor.
Product $A$ requires $4$ units of material and $2$ hours of labor.
Product $B$ requires $3$ units of material and $5$ hours of labor.
# Step 1: Define the problem # Create a maximization problem problem = pulp.LpProblem("Maximize_Profit", pulp.LpMaximize)
# Step 2: Define the decision variables # Let x be the number of product A to produce, y be the number of product B to produce x = pulp.LpVariable('x', lowBound=0, cat='Continuous') y = pulp.LpVariable('y', lowBound=0, cat='Continuous')
# Step 3: Define the objective function # Objective function: Maximize 20x + 25y problem += 20*x + 25*y, "Profit"
# Step 6: Display the results print("Status:", pulp.LpStatus[problem.status]) print("Optimal number of product A to produce:", pulp.value(x)) print("Optimal number of product B to produce:", pulp.value(y)) print("Maximum Profit:", pulp.value(problem.objective))
Explanation of the Code:
Define the Problem: We create a linear programming problem with the objective to maximize profit.
Decision Variables: We define the decision variables x and y for the number of products A and B to produce. These variables are continuous and non-negative.
Objective Function: We define the objective function to maximize, which is the total profit: 20*x + 25*y.
Constraints: We add constraints based on the available resources:
Material constraint: 4*x + 3*y <= 100
Labor constraint: 2*x + 5*y <= 80
Solve the Problem: We solve the linear programming problem using PuLP’s solve method.
Display the Results: We print the optimal values of x and y, and the maximum profit.
Interpretation of Output:
Output
1 2 3 4
Status: Optimal Optimal number of product A to produce: 18.571429 Optimal number of product B to produce: 8.5714286 Maximum Profit: 585.714295
Interpretation
The optimal solution is to produce $18.5$ units of product A and $8.57$ units of product B, which yields a maximum profit of $585.71.
This is a basic example of using PuLP in Python.
The library is powerful and can handle more complex constraints, variables, and objectives, including mixed-integer programming.
Here’s a advanced and useful sample code using Altair, which demonstrates how to create a layered chart with interactivity, such as tooltips and selection, along with custom encoding:
import altair as alt from vega_datasets import data
# Load dataset source = data.cars()
# Define a brush selection brush = alt.selection(type='interval')
# Base chart with a scatter plot base = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color=alt.condition(brush, 'Origin:N', alt.value('lightgray')), tooltip=['Name:N', 'Origin:N', 'Horsepower:Q', 'Miles_per_Gallon:Q'] ).properties( width=600, height=400 ).add_selection( brush )
# Layer a bar chart on top that shows the distribution of 'Origin' for selected points bars = alt.Chart(source).mark_bar().encode( x='count():Q', y='Origin:N', color='Origin:N' ).transform_filter( brush )
# Combine the scatter plot and the bar chart chart = base & bars chart
Result
Explanation
Brush Selection: An interactive selection that allows users to drag over the scatter plot to select a region.
Scatter Plot: A basic plot where points are colored by their origin, and the color changes based on the selection.
Bar Chart: Shows the distribution of car origins, updated based on the selection made in the scatter plot.
Interactivity: Tooltips provide detailed information when hovering over the points, and the chart updates dynamically based on the user’s selection.
This example combines interactivity with advanced encoding and layout, making it useful for exploratory data analysis.