To create a piecewise linear graph with two segments using two gradients, you can divide the graph into two parts:
- The first part, from
start_time to t80 (determined by the t80 point), uses the gradient gradient.
- The second part, from
t80 to g1s_x (or another endpoint if defined differently), uses a gradient determined by reaching the G1s point.
Here's an approach to implement this:
- Calculate the initial line using the given
gradient until t80.
- Calculate the second line segment to reach
g1s_y from t80.
Let me show you how you can implement this logic:
import numpy as np
import matplotlib.pyplot as plt
# Constants
DMAX = 100 # for example
G1s = 10 # for example
FREQ = 500 # number of points
def stop_approach_phase(start_time, gradient):
# Determine x_values range
length = abs(DMAX) / abs(gradient)
x_values = np.linspace(start_time, start_time + length, FREQ)
# Normalized x for tanh scaling
normalized_x = np.linspace(-1, 0, FREQ)
scaled_atan = np.arctan(3 * normalized_x)
atan_min, atan_max = scaled_atan.min(), scaled_atan.max()
# Calculate y_values using atan scaled between DMAX and 0
y_values = DMAX + (scaled_atan - atan_min) / (atan_max - atan_min) * (-DMAX)
# Determine closest y value to G1s
differences = np.abs(y_values - G1s)
closest_index = np.argmin(differences)
g1s_x = x_values[closest_index]
g1s_y = y_values[closest_index]
# Determine 80% DMAX value
t80_DMAX_value = 0.8 * DMAX
differences_t80_DMAX = np.abs(y_values - t80_DMAX_value)
closest_index_t80_DMAX = np.argmin(differences_t80_DMAX)
t80_x = x_values[closest_index_t80_DMAX]
t80_y = y_values[closest_index_t80_DMAX]
return x_values, y_values, g1s_x, g1s_y, t80_x, t80_y
def plot_phase(start_time, gradient):
x_values, y_values, g1s_x, g1s_y, t80_x, t80_y = stop_approach_phase(start_time, gradient)
# First segment
x1 = np.linspace(start_time, t80_x, FREQ // 2)
y1 = DMAX - gradient * (x1 - start_time)
# Calculate new gradient for the second part
remaining_x = g1s_x - t80_x
new_gradient = (G1s - t80_y) / remaining_x if remaining_x != 0 else 0
# Second segment
x2 = np.linspace(t80_x, g1s_x, FREQ // 2)
y2 = t80_y + new_gradient * (x2 - t80_x)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(x1, y1, label='First Segment')
plt.plot(x2, y2, label='Second Segment')
plt.scatter([t80_x, g1s_x], [t80_y, g1s_y], color='red', zorder=5)
plt.text(t80_x, t80_y, 'T80', fontsize=9, ha='right')
plt.text(g1s_x, g1s_y, 'G1s', fontsize=9, ha='right')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Graph with Two Gradients')
plt.legend()
plt.grid(True)
plt.show()
plot_phase(0, -0.5)
This script defines a function to generate and plot a piecewise linear graph with the specified criteria. Adjust the DMAX, G1s, and FREQ values as necessary for your application. The script uses matplotlib to visualize your function with the specified constraints.