Пример #1
0
	def printGraph(train, test, name):
		sns.set_style("darkgrid")
		epochs = [i+1 for i in range(self.num_epochs)]
		plt.plot(epochs, test, 'r', label = "Test")
		plt.plot(epochs, train, 'b', label = "Train")
		plt.legend(loc = "upper left")	
		plt.title(name+" vs. Epochs")
		plt.xlabel("Epochs")
		plt.ylabel(name)
		plt.savefig("result_graphs/%s_%s_train_vs_test_%i_epochs.png"%(self.run_name, name, self.num_epochs))
		plt.clf()
Пример #2
0
def main():
    border_c = 2.0
    border = PERIOD * border_c

    step = 2 * PERIOD / POINT_NUMBER
    amplitude = 1.0

    s_gauss = GaussSignal(SIGMA, amplitude)
    t_values = [-border + i * step for i in range(int(2 * border / step) + 1)]

    gauss_values = [s_gauss.value(t) for t in t_values]
    gauss_noise_values = random.normal(0, 0.05, len(t_values))
    impulse_noise_values = noise_impulse(len(gauss_values), 7, 0.4)

    values_w_gauss = [
        val1 + val2 for val1, val2 in zip(gauss_values, gauss_noise_values)
    ]
    values_w_impulse = [
        val1 + val2 for val1, val2 in zip(gauss_values, impulse_noise_values)
    ]

    butterworth_f = butterworth_filter(6, 20, 'high')
    gauss_f = gauss_filter(4, 20, 'high')

    plt.subplot(2, 2, 1)
    plt.plot(t_values, gauss_values, 'r', t_values, values_w_gauss, 'y',
             t_values,
             values_w_gauss - signal.filtfilt(gauss_f, 1, values_w_gauss), 'g')
    plt.legend(['Исходный график', 'Гауссовы помехи', 'Фильтр Гаусса'])

    plt.subplot(2, 2, 2)
    plt.plot(
        t_values, gauss_values, 'r', t_values, values_w_gauss, 'y', t_values,
        values_w_gauss - signal.filtfilt(butterworth_f, 1, values_w_gauss),
        'b')
    plt.legend(['Исходный график', 'Гауссовы помехи', 'Фильтр Баттеруорта'])

    plt.subplot(2, 2, 3)
    plt.plot(t_values, gauss_values, 'r', t_values, values_w_impulse, 'y',
             t_values,
             values_w_impulse - signal.filtfilt(gauss_f, 1, values_w_impulse),
             'g')
    plt.legend(['Исходный график', 'Импульсные помехи', 'Фильтр Гаусса'])

    plt.subplot(2, 2, 4)
    plt.plot(
        t_values, gauss_values, 'r', t_values, values_w_impulse, 'y', t_values,
        values_w_impulse - signal.filtfilt(butterworth_f, 1, values_w_impulse),
        'b')
    plt.legend(['Исходный график', 'Импульсные помехи', 'Фильтр Баттеруорта'])
    plt.show()
Пример #3
0
def affichagegraph(slope, intercept, r_value, unit):

    print(slope, "x + ",
          intercept)  # sortie console du R^2 et  Ax + B (optionel)
    print("r-squared =", r_value**2)

    y = [
    ]  # on bricole en creant le y, il est utilisé pour tracer la fitted line
    for i in range(0, len(speed)):
        y.append(intercept + slope * speed[i])

    pyplot.title('y={0}X+{1}  R2={2}'.format(slope, intercept, r_value**2))
    pyplot.suptitle(
        'Frequence en sortie du capteur en fonction de la Vitesse mesurée')
    axes = plt.axes()
    axes.grid()  # dessiner une grille pour une meilleur lisibilité du graphe
    axes.set_xlabel('vitesse({0})'.format(unit))
    axes.set_ylabel('Frequence(Hz)')
    plt.scatter(speed, freq)  # speed et freq sont envoyer en param x et y
    plt.plot(speed, y, 'r', label='fitted line')
    plt.legend()
    plt.show()
    return
Пример #4
0
import pandas as pd
import numpy as np
import matplotlib.plt as plt

plt.plot(1, 2, '.')
plt.show()
Пример #5
0
def ParameterFunction(parameterSet):
    SC = exu.SystemContainer()
    mbs = SC.AddSystem()

    #default values
    mass = 1.6          #mass in kg
    spring = 4000       #stiffness of spring-damper in N/m
    damper = 8          #damping constant in N/(m/s)
    u0=-0.08            #initial displacement
    v0=1                #initial velocity
    f =80               #force applied to mass

    #process parameters
    if 'mass' in parameterSet:
        mass = parameterSet['mass']
        
    if 'spring' in parameterSet:
        spring = parameterSet['spring']

    iCalc = 'Ref' #needed for parallel computation ==> output files are different for every computation
    if 'computationIndex' in parameterSet:
        iCalc = str(parameterSet['computationIndex'])

    #mass-spring-damper system
    L=0.5               #spring length (for drawing)
    
    x0=f/spring         #static displacement
    
    # print('resonance frequency = '+str(np.sqrt(spring/mass)))
    # print('static displacement = '+str(x0))
    
    #node for 3D mass point:
    n1=mbs.AddNode(Point(referenceCoordinates = [L,0,0], 
                         initialCoordinates = [u0,0,0], 
                         initialVelocities= [v0,0,0]))
    
    #ground node
    nGround=mbs.AddNode(NodePointGround(referenceCoordinates = [0,0,0]))
    
    #add mass point (this is a 3D object with 3 coordinates):
    massPoint = mbs.AddObject(MassPoint(physicsMass = mass, nodeNumber = n1))
    
    #marker for ground (=fixed):
    groundMarker=mbs.AddMarker(MarkerNodeCoordinate(nodeNumber= nGround, coordinate = 0))
    #marker for springDamper for first (x-)coordinate:
    nodeMarker  =mbs.AddMarker(MarkerNodeCoordinate(nodeNumber= n1, coordinate = 0))
    
    #spring-damper between two marker coordinates
    nC = mbs.AddObject(CoordinateSpringDamper(markerNumbers = [groundMarker, nodeMarker], 
                                              stiffness = spring, damping = damper)) 
    
    #add load:
    mbs.AddLoad(LoadCoordinate(markerNumber = nodeMarker, 
                                             load = f))
    #add sensor:
    fileName = 'solution/paramVarDisplacement'+iCalc+'.txt'
    mbs.AddSensor(SensorObject(objectNumber=nC, fileName=fileName, 
                               outputVariableType=exu.OutputVariableType.Force))
    
    #print(mbs)
    mbs.Assemble()
    
    steps = 1000  #number of steps to show solution
    tEnd = 1     #end time of simulation
    
    simulationSettings = exu.SimulationSettings()
    #simulationSettings.solutionSettings.solutionWritePeriod = 5e-3  #output interval general
    simulationSettings.solutionSettings.writeSolutionToFile = False
    simulationSettings.solutionSettings.sensorsWritePeriod = 5e-3  #output interval of sensors
    simulationSettings.timeIntegration.numberOfSteps = steps
    simulationSettings.timeIntegration.endTime = tEnd
    
    simulationSettings.timeIntegration.generalizedAlpha.spectralRadius = 1 #no damping
    
    #exu.StartRenderer()              #start graphics visualization
    #mbs.WaitForUserToContinue()    #wait for pressing SPACE bar to continue
    
    #start solver:
    exu.SolveDynamic(mbs, simulationSettings)
    
    #SC.WaitForRenderEngineStopFlag()#wait for pressing 'Q' to quit
    #exu.StopRenderer()               #safely close rendering window!
    
    # #evaluate final (=current) output values
    # u = mbs.GetNodeOutput(n1, exu.OutputVariableType.Position)
    # print('displacement=',u)

    #+++++++++++++++++++++++++++++++++++++++++++++++++++++
    #evaluate difference between reference and optimized solution
    #reference solution:
    dataRef = np.loadtxt('solution/paramVarDisplacementRef.txt', comments='#', delimiter=',')
    data = np.loadtxt(fileName, comments='#', delimiter=',')
    diff = data[:,1]-dataRef[:,1]
    
    errorNorm = np.sqrt(np.dot(diff,diff))/steps*tEnd
    
    #+++++++++++++++++++++++++++++++++++++++++++++++++++++
    #compute exact solution:
    if False:
        from matplotlib import plt
        
        plt.close('all')
        plt.plot(data[:,0], data[:,1], 'b-', label='displacement (m)')
                
        ax=plt.gca() # get current axes
        ax.grid(True, 'major', 'both')
        ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) 
        ax.yaxis.set_major_locator(ticker.MaxNLocator(10)) 
        plt.legend() #show labels as legend
        plt.tight_layout()
        plt.show() 

    import os
    if iCalc != 'Ref':
        os.remove(fileName) #remove files in order to clean up
        
    del mbs
    del SC
    
    return errorNorm
Пример #6
0
import numpy as np
from matplotlib import plt
fs1 = input("enter a number-")
f1 = input("enter a number-")
n = np.arange(0, 2000, 0.1)
a1 = np.sin(2 * 3.14 * f1 * n / fs1)
plt.plot(a1)
plt.show()
fs2 = input("enter a number-")
f2 = input("enter a number-")
n2 = np.arange(0, 2000, 0.1)
a2 = np.sin(2 * 3.14 * f2 * n2 / fs2)
plt.plot(a2)
plt.show()
y = a1 + a2
print("y")
plt.plot(y)
plt.show()
Пример #7
0
fx_1 = 27.0 / (b - a)
#f(25)
fx_2 = 25.0 / (b - a)

#Our answer is then
ans = fx_1 - fx_2

#print
print(
    ' The probability that the taxi ride will last at least 25 minutes is %2.1f%%'
    % (100 * ans))

# Doing this with schipy

# Import the following
from scipy.stats import uniform
import numpy as np
from matplotlib import plt
#Let's set an A and B
A = 0
B = 5

# Set x as 100 linearly spaced points between A and B
x = np.linspace(A, B, 100)

# Use uniform(loc=start point,scale=endpoint)
rv = uniform(loc=A, scale=B)

#Plot the PDF of that uniform distirbution
plt.plot(x, rv.pdf(x))
Пример #8
0
]

# Instantiate a Gaussian Process model
gp = GaussianProcessRegressor(kernel=kernel,
                              alpha=dy**2,
                              n_restarts_optimizer=10)

# Fit to data using Maximum Likelihood Estimation of the parameters
gp.fit(X, y)

# Make the prediction on the meshed x-axis (ask for MSE as well)
y_pred, sigma = gp.predict(x, return_std=True)

# Plot the function, the prediction and the 95% confidence interval based on
# the MSE
plt.figure()
plt.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations')
plt.plot(x, y_pred, 'b-', label=u'Prediction')
plt.fill(np.concatenate([x, x[::-1]]),
         np.concatenate(
             [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),
         alpha=.5,
         fc='b',
         ec='None',
         label='95% confidence interval')
plt.xlabel('$x$')
plt.ylabel('$f(x)$')
plt.ylim(-10, 20)
plt.legend(loc='upper left')

plt.show()