def DrawDigit(A, label=''):
    """ Draw single digit as a greyscale matrix"""
    fig = plt.figure(figsize=(6, 6))
    # Uso la colormap 'gray' per avere la schacchiera in bianco&nero
    img = plt.imshow(A, cmap='gray_r')
    plt.xlabel(label)
    plt.show()
예제 #2
0
def importance_plotting(data, x, y, palette, title):
    """
    Importance plotting of features came from the Kaggle Kernel of Joshua Reed.  
    He used this plot to identify important features. 

    https://www.kaggle.com/josh24990/simple-end-to-end-ml-workflow-top-5-score
    
    Arguments:
        data {[type]} -- [description]
        x {[type]} -- [description]
        y {[type]} -- [description]
        palette {[type]} -- [description]
        title {[type]} -- [description]
    """
    sns.set(style="whitegrid")
    ft = sns.PairGrid(data, y_vars=y, x_vars=x, size=5, aspect=1.5)
    ft.map(sns.stripplot,
           orient='h',
           palette=palette,
           edgecolor="black",
           size=15)

    for ax, title in zip(ft.axes.flat, titles):
        # Set a different title for each axes
        ax.set(title=title)
        # Make the grid horizontal instead of vertical
        ax.xaxis.grid(False)
        ax.yaxis.grid(True)
    plt.show()
예제 #3
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()
예제 #4
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
예제 #5
0
import pandas as pd
import numpy as np
import matplotlib.plt as plt

plt.plot(1, 2, '.')
plt.show()
예제 #6
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
예제 #7
0
def print_trajectory(model):
    plt.imshow(model.return_trajectory_matrix(), cmap='gray')
    plt.title('the trajectory found')
    plt.show()