Support
Quality
Security
License
Reuse
kandi has reviewed pendulum and discovered the below as its top functions. This is intended to give you an instant insight into pendulum implemented functionality, and help decide if they suit your requirements.
Python datetimes made easy
Matplotlib plot of ODE solution is not tangential to RHS vector field
# Plotting
fig,ax=plt.subplots(figsize=(8,8))
ax.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,alpha_dt, alpha_dot_dt)
ax.set_aspect('equal')
-----------------------
pylab.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=10)
ModuleNotFoundError: No module named 'airflow.providers.slack' Airflow 2.0 (MWAA)
--constraint "https://raw.githubusercontent.com/apache/airflow/constraints-main/constraints-3.7.txt"
Function that calculates uncertainty
>>> def ucalc(f, x, u):
... f = S(f)
... syms = list(ordered(f.free_symbols))
... assert len(x) == len(u) == len(syms)
... reps = dict(zip(syms, x))
... ui = IndexedBase('u')
... args = []
... for i, xi in enumerate(syms):
... reps[ui[xi]] = u[i]
... args.append((ui[xi]*diff(f, xi))**2)
... return reps, sqrt(Add(*args)).n(subs=reps)
...
>>> ucalc('2*pi*sqrt(L/g)',(9.8,5.4),(.1,.3))
({L: 9.8, g: 5.4, u[L]: 0.1, u[g]: 0.3}, 0.239055276534314)
Airflow wrong execution_date for timezone aware DAGs
{{ execution_date.in_timezone('Europe/Amsterdam') }}
{{ dag_run.logical_date.astimezone(dag.timezone) }}
-----------------------
{{ execution_date.in_timezone('Europe/Amsterdam') }}
{{ dag_run.logical_date.astimezone(dag.timezone) }}
gym package not identifying ten-armed-bandits-v0 env
git clone gym_armed_bandits
cd gym_armed_bandits
pip install -e .
MWAA not finding aws_default connection
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...
print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
default_args = {
'owner': 'aws',
'depends_on_past': False,
'start_date': datetime(2019, 2, 20),
'provide_context': True
}
dag = DAG(
'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)
#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'
podRun = KubernetesPodOperator(
namespace="mwaa",
image="ubuntu:18.04",
cmds=["bash"],
arguments=["-c", "ls"],
labels={"foo": "bar"},
name="mwaa-pod-test",
task_id="pod-task",
get_logs=True,
dag=dag,
is_delete_operator_pod=False,
config_file=kube_config_path,
in_cluster=False,
cluster_context='aws',
execution_timeout=timedelta(seconds=60)
)
-----------------------
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...
print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
default_args = {
'owner': 'aws',
'depends_on_past': False,
'start_date': datetime(2019, 2, 20),
'provide_context': True
}
dag = DAG(
'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)
#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'
podRun = KubernetesPodOperator(
namespace="mwaa",
image="ubuntu:18.04",
cmds=["bash"],
arguments=["-c", "ls"],
labels={"foo": "bar"},
name="mwaa-pod-test",
task_id="pod-task",
get_logs=True,
dag=dag,
is_delete_operator_pod=False,
config_file=kube_config_path,
in_cluster=False,
cluster_context='aws',
execution_timeout=timedelta(seconds=60)
)
-----------------------
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...
print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
default_args = {
'owner': 'aws',
'depends_on_past': False,
'start_date': datetime(2019, 2, 20),
'provide_context': True
}
dag = DAG(
'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)
#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'
podRun = KubernetesPodOperator(
namespace="mwaa",
image="ubuntu:18.04",
cmds=["bash"],
arguments=["-c", "ls"],
labels={"foo": "bar"},
name="mwaa-pod-test",
task_id="pod-task",
get_logs=True,
dag=dag,
is_delete_operator_pod=False,
config_file=kube_config_path,
in_cluster=False,
cluster_context='aws',
execution_timeout=timedelta(seconds=60)
)
Airflow external_task_sensor never stops poking
wait_for_parent_task = ExternalTaskSensor(
task_id='wait_for_parent_task ',
external_dag_id='test_parent',
external_task_id='task_parent_2',
check_existence=True,
# execution_date needs to be exact (scheduled time) and the london timezone
# Remember: The scheduled start is always the one step further in the past -
# For a daily schedule: - datetime.timedelta(days=1)
execution_date_fn=lambda dt: (datetime.datetime(year=dt.year, month=dt.month, day=dt.day, tzinfo=local_tz)
+ datetime.timedelta(hours=6, minutes=0)
- datetime.timedelta(days=1)
).astimezone(local_tz_london),
)
How to use Gekko to solve for optimal control for a reusable reentry vehicle
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
(L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
import math
pi = math.pi
########################
######FRONT MATTER######
########################
m = GEKKO() # initialize GEKKO
nt = 101 # 2501 #simulation time is 2500 seconds
tfin = 0.04
m.time = np.linspace(0,tfin,nt) #time array
#==================#
#PARAMS
#==================#
Re = m.Param(value = 6371203.92) # radius of the earth, m
S = m.Param(value = 249.9091776) # vehicle surface area, m^2
cl0 = m.Param(value = -0.2070) # coeff lift param 1
cl1 = m.Param(value = 1.6756) # coeff lift param 2
cd0 = m.Param(value = 0.0785) # coeff drag param 1
cd1 = m.Param(value = -0.3529) # coeff drag param 2
cd2 = m.Param(value = 2.0400) # coeff drag param 3
H = m.Param(value = 7254.24) # density scale height, m
rho0= m.Param(value = 1.225570827014494) # sea level atmospheric density, kg/m^3
mu = m.Param(value = 3.986031954093051e14) #earth gravitational param, m^3/s^2
mass= m.Param(value = 92079.2525560557) #vehicle mass, kg
#===============================#
#BOUNDARY CONDITIONS
#===============================#
t0 = 0
alt0 = 79248
rad0 = alt0+Re
altf = 24384
radf = altf+Re
lon0 = 0
lat0 = 0
speed0 = +7802.88
speedf = +762
fpa0 = -1*pi/180
fpaf = -5*pi/180
azi0 = +90*pi/180
azif = -90*pi/180
#===============================#
#LIMITS ON VARIABLES
#===============================#
tfMin = 0; tfMax = 3000;
radMin = Re; radMax = rad0;
lonMin = -pi; lonMax = -lonMin;
latMin = -70*pi/180; latMax = -latMin;
speedMin = 10; speedMax = 45000;
fpaMin = -80*pi/180; fpaMax = 80*pi/180;
aziMin = -180*pi/180; aziMax = 180*pi/180;
aoaMin = -90*pi/180; aoaMax = -aoaMin;
bankMin = -90*pi/180; bankMax = 1*pi/180;
#===============================#
#VARIABLES
#===============================#
#state variables and bounds
rad = m.Var(value=rad0, lb=radMin, ub=radMax) # radius, m
lon = m.Var(value=lon0, lb=lonMin, ub=lonMax) # longitude, rad
lat = m.Var(value=lat0, lb=latMin, ub=latMax) # latitude, rad
vel = m.Var(value=speed0, lb=speedMin, ub=speedMax) # velocity, m/sec
fpa = m.Var(value=fpa0, lb=fpaMin, ub=fpaMax) # flight path angle, rad
azi = m.Var(value=azi0, lb=aziMin, ub=aziMax) # azimuth angle, rad
#control variables
aoa = m.MV(value=-20, lb=aoaMin, ub=aoaMax) # angle of attack, rad
aoa.STATUS = 1
bank = m.MV(value=0, lb=bankMin, ub=bankMax) # bank angle, rad
bank.STATUS = 1
#===============================#
#INTERMEDIATE VARIABLES
#===============================#
altitude = rad - Re
CD = cd0+cd1*aoa+cd2*aoa**2
rho = rho0*m.exp(-altitude/H)
CL = cl0+cl1*aoa
q = 0.5*rho*vel**2
D = q*S*CD/mass
L = q*S*CL/mass
gravity = mu/rad**2
#===============================#
#EOMS
#===============================#
p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
(L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
#===============================#
#OPTIMIZATION SOLVER
#===============================#
m.Maximize(lat*final)
m.options.SOLVER = 3
m.options.IMODE = 6
m.solve(disp=True)
plt.subplot(4,2,1)
plt.plot(m.time,rad.value,label='rad')
plt.legend()
plt.subplot(4,2,2)
plt.plot(m.time,lon.value,label='lon')
plt.legend()
plt.subplot(4,2,3)
plt.plot(m.time,lat.value,label='lat')
plt.legend()
plt.subplot(4,2,4)
plt.plot(m.time,vel.value,label='vel')
plt.legend()
plt.subplot(4,2,5)
plt.plot(m.time,fpa.value,label='fpa')
plt.legend()
plt.subplot(4,2,6)
plt.plot(m.time,azi.value,label='azi')
plt.legend()
plt.subplot(4,2,7)
plt.plot(m.time,aoa.value,label='aoa')
plt.xlabel('Time')
plt.legend()
plt.subplot(4,2,8)
plt.plot(m.time,bank.value,label='bank')
plt.xlabel('Time')
plt.legend()
plt.show()
-----------------------
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
(L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
import math
pi = math.pi
########################
######FRONT MATTER######
########################
m = GEKKO() # initialize GEKKO
nt = 101 # 2501 #simulation time is 2500 seconds
tfin = 0.04
m.time = np.linspace(0,tfin,nt) #time array
#==================#
#PARAMS
#==================#
Re = m.Param(value = 6371203.92) # radius of the earth, m
S = m.Param(value = 249.9091776) # vehicle surface area, m^2
cl0 = m.Param(value = -0.2070) # coeff lift param 1
cl1 = m.Param(value = 1.6756) # coeff lift param 2
cd0 = m.Param(value = 0.0785) # coeff drag param 1
cd1 = m.Param(value = -0.3529) # coeff drag param 2
cd2 = m.Param(value = 2.0400) # coeff drag param 3
H = m.Param(value = 7254.24) # density scale height, m
rho0= m.Param(value = 1.225570827014494) # sea level atmospheric density, kg/m^3
mu = m.Param(value = 3.986031954093051e14) #earth gravitational param, m^3/s^2
mass= m.Param(value = 92079.2525560557) #vehicle mass, kg
#===============================#
#BOUNDARY CONDITIONS
#===============================#
t0 = 0
alt0 = 79248
rad0 = alt0+Re
altf = 24384
radf = altf+Re
lon0 = 0
lat0 = 0
speed0 = +7802.88
speedf = +762
fpa0 = -1*pi/180
fpaf = -5*pi/180
azi0 = +90*pi/180
azif = -90*pi/180
#===============================#
#LIMITS ON VARIABLES
#===============================#
tfMin = 0; tfMax = 3000;
radMin = Re; radMax = rad0;
lonMin = -pi; lonMax = -lonMin;
latMin = -70*pi/180; latMax = -latMin;
speedMin = 10; speedMax = 45000;
fpaMin = -80*pi/180; fpaMax = 80*pi/180;
aziMin = -180*pi/180; aziMax = 180*pi/180;
aoaMin = -90*pi/180; aoaMax = -aoaMin;
bankMin = -90*pi/180; bankMax = 1*pi/180;
#===============================#
#VARIABLES
#===============================#
#state variables and bounds
rad = m.Var(value=rad0, lb=radMin, ub=radMax) # radius, m
lon = m.Var(value=lon0, lb=lonMin, ub=lonMax) # longitude, rad
lat = m.Var(value=lat0, lb=latMin, ub=latMax) # latitude, rad
vel = m.Var(value=speed0, lb=speedMin, ub=speedMax) # velocity, m/sec
fpa = m.Var(value=fpa0, lb=fpaMin, ub=fpaMax) # flight path angle, rad
azi = m.Var(value=azi0, lb=aziMin, ub=aziMax) # azimuth angle, rad
#control variables
aoa = m.MV(value=-20, lb=aoaMin, ub=aoaMax) # angle of attack, rad
aoa.STATUS = 1
bank = m.MV(value=0, lb=bankMin, ub=bankMax) # bank angle, rad
bank.STATUS = 1
#===============================#
#INTERMEDIATE VARIABLES
#===============================#
altitude = rad - Re
CD = cd0+cd1*aoa+cd2*aoa**2
rho = rho0*m.exp(-altitude/H)
CL = cl0+cl1*aoa
q = 0.5*rho*vel**2
D = q*S*CD/mass
L = q*S*CL/mass
gravity = mu/rad**2
#===============================#
#EOMS
#===============================#
p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
(L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
#===============================#
#OPTIMIZATION SOLVER
#===============================#
m.Maximize(lat*final)
m.options.SOLVER = 3
m.options.IMODE = 6
m.solve(disp=True)
plt.subplot(4,2,1)
plt.plot(m.time,rad.value,label='rad')
plt.legend()
plt.subplot(4,2,2)
plt.plot(m.time,lon.value,label='lon')
plt.legend()
plt.subplot(4,2,3)
plt.plot(m.time,lat.value,label='lat')
plt.legend()
plt.subplot(4,2,4)
plt.plot(m.time,vel.value,label='vel')
plt.legend()
plt.subplot(4,2,5)
plt.plot(m.time,fpa.value,label='fpa')
plt.legend()
plt.subplot(4,2,6)
plt.plot(m.time,azi.value,label='azi')
plt.legend()
plt.subplot(4,2,7)
plt.plot(m.time,aoa.value,label='aoa')
plt.xlabel('Time')
plt.legend()
plt.subplot(4,2,8)
plt.plot(m.time,bank.value,label='bank')
plt.xlabel('Time')
plt.legend()
plt.show()
Why is it not possible to store DD-MM-YYYY format in date format?
import datetime
df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")
-----------------------
import datetime
df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")
-----------------------
import datetime
df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")
Why is my css svg animation stuttering on Firefox and not on other browsers?
function startPendulum() {
let animEls = document.querySelector('[class*="animate-pendulum"]');
animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}
function startPendulumStar() {
let animEls = document.querySelector('[class*="animate-star"]');
animEls.classList.replace('--animate-star', 'animate-star');
}
function addTransform() {
let animEls = document.querySelector('[class*="pendulum-transform"]');
animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
background-color: rgba(0, 0, 255, 0.517);
display: inline-block;
width: 50%;
}
.transformBox-fill-box {
transform-box: fill-box;
}
.pendulum-star {
fill: #00ff00;
transform-origin: center center;
fill: #00ff00;
fill-opacity: 0.517647;
stroke: #000000;
stroke-width: 4;
stroke-linecap: butt;
stroke-linejoin: miter;
}
.pendulum-rod {
fill: rgba(0, 0, 255, 0.5);
stroke: #000000;
stroke-width: 4
}
.pendulum-group {
transform-origin: center top;
}
.pendulum-transform {
transform: translate(-20%, 5%);
}
.animate-star .pendulum-star {
animation-name: pendulum-anim;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
.animate-pendulum .pendulum-group {
animation-name: pendulum-anim;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
@keyframes pendulum-anim {
0%,
100% {
transform: rotate(45deg);
}
50% {
transform: rotate(-45deg);
}
}
<div class="pendulum-wrp --animate-pendulum --animate-star">
<svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<g id="pendulum-transform" class="--pendulum-transform">
<g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
<rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
<g id="pendulum-star" class="pendulum-star transformBox-fill-box">
<path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
</g>
</g>
</g>
</svg>
</div>
<p>
<button onclick="startPendulum()">Start pendulum animation</button>
<button onclick="startPendulumStar()">Start star animation</button>
<button onclick="addTransform()">shift by transform</button>
</p>
-----------------------
function startPendulum() {
let animEls = document.querySelector('[class*="animate-pendulum"]');
animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}
function startPendulumStar() {
let animEls = document.querySelector('[class*="animate-star"]');
animEls.classList.replace('--animate-star', 'animate-star');
}
function addTransform() {
let animEls = document.querySelector('[class*="pendulum-transform"]');
animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
background-color: rgba(0, 0, 255, 0.517);
display: inline-block;
width: 50%;
}
.transformBox-fill-box {
transform-box: fill-box;
}
.pendulum-star {
fill: #00ff00;
transform-origin: center center;
fill: #00ff00;
fill-opacity: 0.517647;
stroke: #000000;
stroke-width: 4;
stroke-linecap: butt;
stroke-linejoin: miter;
}
.pendulum-rod {
fill: rgba(0, 0, 255, 0.5);
stroke: #000000;
stroke-width: 4
}
.pendulum-group {
transform-origin: center top;
}
.pendulum-transform {
transform: translate(-20%, 5%);
}
.animate-star .pendulum-star {
animation-name: pendulum-anim;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
.animate-pendulum .pendulum-group {
animation-name: pendulum-anim;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
@keyframes pendulum-anim {
0%,
100% {
transform: rotate(45deg);
}
50% {
transform: rotate(-45deg);
}
}
<div class="pendulum-wrp --animate-pendulum --animate-star">
<svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<g id="pendulum-transform" class="--pendulum-transform">
<g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
<rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
<g id="pendulum-star" class="pendulum-star transformBox-fill-box">
<path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
</g>
</g>
</g>
</svg>
</div>
<p>
<button onclick="startPendulum()">Start pendulum animation</button>
<button onclick="startPendulumStar()">Start star animation</button>
<button onclick="addTransform()">shift by transform</button>
</p>
-----------------------
function startPendulum() {
let animEls = document.querySelector('[class*="animate-pendulum"]');
animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}
function startPendulumStar() {
let animEls = document.querySelector('[class*="animate-star"]');
animEls.classList.replace('--animate-star', 'animate-star');
}
function addTransform() {
let animEls = document.querySelector('[class*="pendulum-transform"]');
animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
background-color: rgba(0, 0, 255, 0.517);
display: inline-block;
width: 50%;
}
.transformBox-fill-box {
transform-box: fill-box;
}
.pendulum-star {
fill: #00ff00;
transform-origin: center center;
fill: #00ff00;
fill-opacity: 0.517647;
stroke: #000000;
stroke-width: 4;
stroke-linecap: butt;
stroke-linejoin: miter;
}
.pendulum-rod {
fill: rgba(0, 0, 255, 0.5);
stroke: #000000;
stroke-width: 4
}
.pendulum-group {
transform-origin: center top;
}
.pendulum-transform {
transform: translate(-20%, 5%);
}
.animate-star .pendulum-star {
animation-name: pendulum-anim;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
.animate-pendulum .pendulum-group {
animation-name: pendulum-anim;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
}
@keyframes pendulum-anim {
0%,
100% {
transform: rotate(45deg);
}
50% {
transform: rotate(-45deg);
}
}
<div class="pendulum-wrp --animate-pendulum --animate-star">
<svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<g id="pendulum-transform" class="--pendulum-transform">
<g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
<rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
<g id="pendulum-star" class="pendulum-star transformBox-fill-box">
<path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
</g>
</g>
</g>
</svg>
</div>
<p>
<button onclick="startPendulum()">Start pendulum animation</button>
<button onclick="startPendulumStar()">Start star animation</button>
<button onclick="addTransform()">shift by transform</button>
</p>
QUESTION
Matplotlib plot of ODE solution is not tangential to RHS vector field
Asked 2022-Apr-15 at 17:51I am experimenting with oridnary differential equations and for that I programmed a little code that plots the trajectory of a pendulum in phase space. However, the trajectory isn't really tangential to the vector field given by the right hand side of the ODE as it is supposed to be. Is this a plotting issue? As I use the same function of the ODE for both the numerical integration and plotting of the vector field I dont know how this can happen...
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
# Constants
g = 9.81
l = 1
delta = 0.6
# Initial state vector: [alpha, dalpha_dot]
x0 = np.array([-6, 8])
# Right hand side od pendulum ODE
def pendulum_rhs(t, y):
return np.array([y[1], g/l * np.sin(y[0]) - delta * y[1]])
# Solve ODE using runge kutta method
ode_sol = solve_ivp (pendulum_rhs, [0, 10], x0, dense_output=True, t_eval=np.linspace(0 ,10, 200))
ode_sol_y = ode_sol.y.T
# Get the vector field along the trajectory
draw_arrow_every_nth = 5
vector_field_at_ode_sol_y = np.array([pendulum_rhs(0, curr_y) for curr_y in ode_sol_y[::draw_arrow_every_nth, :]])
# create whole vector field
alpha = np.linspace(-2*np.pi, 2*np.pi, 21)
alpha_dot = np.linspace(-10, 10, 21)
# full coorindate arrays
alpha_2dgrid, alpha_dot_2dgrid = np.meshgrid(alpha, alpha_dot)
alpha_dt = alpha_dot_2dgrid
alpha_dot_dt = g/l * np.sin(alpha_2dgrid) - delta * alpha_dot_2dgrid
# Plotting
plt.figure()
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,
alpha_dt, alpha_dot_dt)
plt.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])
ANSWER
Answered 2022-Apr-15 at 17:25This looks like an aspect
issue. You could add ax.set_aspect('equal')
to get the result you want.
See code below:
# Plotting
fig,ax=plt.subplots(figsize=(8,8))
ax.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,alpha_dt, alpha_dot_dt)
ax.set_aspect('equal')
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit