##########################################################################
# Programme Python simulant la propagation dans l'espace de deux ondes
# progressives périodiques de caractéristiques différentes
# Possibilité de mettre en pause l'animation en cliquant sur la fenêtre
#
# On peut modifier les grandeurs physiques T2, v2 pour comprendre
# leur influence sur la propagation de l'onde
# ##########################################################################

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# ############################
# 1. FONCTIONS
# ############################
# fonction qui est applelé à chaque image de l'animation (frame)
def Trace_Chaque_Frame(i):
    # calcul de la date pour la frame i en cours:
    t = i * dt
    # calcul de y pour chaque onde avec l'équation d'onde:
    y1 = A1*np.cos(2*np.pi*(x/Lambda1) - 2*np.pi*(t/T1))
    y2 = A2*np.cos(2*np.pi*(x/Lambda2) - 2*np.pi*(t/T2))
    # on ajoute (x,y1) et (x,y2) à chaque liste oonde1 et onde2
    onde1.set_data(x, y1)
    onde2.set_data(x, y2)
    # on ajoute les données x,y pour tracer les deux lignes en pointillés
    # ces lignes sont verticales en x= 0,5  et x=1 (1/2 lgr d'onde et lgr d'onde)
    trait1.set_data([0.5,0.5],[-1.5*A1,1.5*A1])
    trait2.set_data([1,1],[-1.5*A1,1.5*A1])
    # on retourne les 4 listes pour le tracé
    return onde1,onde2,trait1,trait2

# fonction mettant en pause ou non l'animation si on clique sur la fenêtre matplotlib
def Clic(event):
    global animation_en_pause
    if not animation_en_pause:
        Figure_anime.event_source.stop()
        animation_en_pause = True
    else:
        Figure_anime.event_source.start()
        animation_en_pause = False

# ############################
# 2. initialisation des variables
# ############################
# ONDE n° 1 de référence
# période en secondes:
T1=0.5
# célérité en m/s:
v1=2
# amplitude en mètres
A1=2

""" -----------------PARTIE A MODIFIER----------------- """
# ONDE n° 2
# période en secondes:
T2= 0.5
# célérité en m/s:
v2= 2
# amplitude en mètres
A2= 2
""" --------------- FIN PARTIE A MODIFIER -------------- """

# Calcul des longeurs d'onde:
Lambda1=v1*T1
Lambda2=v2*T2
# intervalle de temps entre deux images de l'animation
dt = 0.01
# tableaux numpy des positions sur l'axe des abscisses:
xmin = 0
xmax = 4
nb_valeurs_x = 49
x = np.linspace(xmin, xmax, nb_valeurs_x)

# variable booléenne permettant de savoir si l'animation est en pause ou non
animation_en_pause = False

# ############################
# 3. Préparation de la figure
# ############################
# initialisation de la figure:
Figure = plt.figure("Propagation de 2 ondes périodiques progressives")
# Création d'un évènement "Clic de la souris" sur la fenêtre Matplolib (si clic, appel de la fonction "Clic")
Figure.canvas.mpl_connect('button_press_event', Clic)

# ONDE 1 ############################################
# séparation en 2 sous figures (2 lignes, 1 colonne):
# 1ère ligne sélectionnée pour tracer l'onde 1:
plt.subplot(2,1,1)
# définition du style de l'onde 1:
onde1, = plt.plot([],[],"ro--")
# définition du style des 2 lignes verticales qui permetent de mieux repérer 2 points:
trait1, = plt.plot([],[],"k--")
trait2, = plt.plot([],[],"k--")
# limites des axes pour bien voir la figure. 1.5*A évite que les courbes soient au mxi de la fenêtre:
plt.xlim(xmin, xmax)
plt.ylim(-1.5*A1,1.5*A1)
# textes sur les axes et titre de la figure
plt.xlabel("abscisse x en m")
plt.ylabel("ordonnée y des points en m")
plt.title("Onde n°1 de référence")
# possibilité d'afficher les informations:
#plt.title("T= "+str(T1)+" s   v="+str(v1)+" m/s     "+chr(955)+" = "+str(Lambda1)+" m")

# ONDE 2 ############################################
# séparation en 2 sous figures (2 lignes, 1 colonne):
# 2nde ligne sélectionnée pour tracer l'onde 2
plt.subplot(2,1,2)
# définition du style de l'onde 2
onde2, = plt.plot([],[],"bo--")
# axes etc... pour l'onde 2
plt.xlim(xmin, xmax)
plt.ylim(-1.5*A2,1.5*A2)
plt.xlabel("abscisse x en m")
plt.ylabel("ordonnée y des points en m")
plt.title("Onde n°2")
# possibilité d'afficher les informations:
# plt.title("T= "+str(T2)+" s   v="+str(v2)+" m/s     "+chr(955)+" = "+str(Lambda2)+" m")

# réglage automatiques des marges entre les figures:
plt.tight_layout()

# ############################
# 4. Animation de la figure
# ############################
Figure_anime = animation.FuncAnimation(Figure, Trace_Chaque_Frame, frames=nb_valeurs_x, blit=True, interval=10, repeat=True)

plt.show() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling