예제 #1
0
    def graficar(self, archivo, filtro, f_infty):
        if filtro == 'Circuito_Pasa_Bajas'.lower():
            titulo = 'Circuito pasa bajas con frecuencia de cero dB en '
        else:
            titulo = 'Circuito pasa altas con frecuencia de cero dB en '

        l = ltspice.Ltspice(os.getcwd() + '/' + archivo)
        # Make sure that the .raw file is located in the correct path
        l.parse()
        f = l.get_frequency()
        V_in = abs(l.get_data('V(in)'))
        V_out = abs((l.get_data('V(out)')))
        H = 20 * np.log10(V_out) - 20 * np.log10(V_in)
        f = np.multiply(f, 1e-6)

        #plt.figure()
        plt.semilogx(f, H, f,
                     np.ones(len(H)) * -3, f,
                     np.ones(len(H)) * -10.3, f,
                     np.ones(len(H)) * -30)
        plt.legend(['H', '-3dB', '-10,3 dB', '-30dB'])
        plt.ylabel('Magnitud [dB]')
        plt.xlabel('frecuencia [MHz]')
        #plt.title(titulo+str(f_infty)+' Hz')
        #plt.xlim([60,100])
        #plt.ylim([-2,2])
        plt.grid(True)
        plt.xticks(
            np.concatenate(
                (np.arange(10, 100, step=10), np.arange(100, 300, step=100))))
        plt.savefig(os.getcwd() + '/' + filtro + '_' + str(f_infty) + '_Hz' +
                    '.png')
예제 #2
0
    def graficar(self,archivo,tipoFiltro,orden):
        '''
        Esta función permite graficar los resultados

        - Archivo: Documento .raw que se genera por el simulador
        - tipoFiltro: Tipo de filtro
        - orden: Orden del filtro
        '''
        l = ltspice.Ltspice(os.getcwd()+'/'+archivo) 
        # Make sure that the .raw file is located in the correct path
        l.parse()
        f= l.get_frequency()*1e-6
        V_in =abs(l.get_data('V(in)'))
        V_out =abs(l.get_data('V(out)'))
        H=20*np.log10(V_out)-20*np.log10(V_in)
        
        plt.figure()
        plt.semilogx(f,H ,f,np.ones(len(H))*-6,f,np.ones(len(H))*-30,f,np.ones(len(H))*-73.87)
        plt.ylabel('Magnitud [dB]')
        plt.xlabel('frecuencia [MHz]')
        
        plt.axvline(x=200, ymin=-3, ymax=3,c='m')
        plt.legend(['H','-6dB','-30dB','-73.87dB','200 MHz'])
        plt.grid(True)
        plt.title(tipoFiltro+' con orden '+str(orden))
        plt.xticks(np.concatenate((np.arange(10,100,step=10),np.arange(100,400,step=100))))
        plt.savefig(os.getcwd()+'/'+tipoFiltro.replace(' ','_').lower()+'_Orden_'+str(orden)+'.png')
        plt.show()
예제 #3
0
 def getData(sim_raw, variables):
     l = ltspice.Ltspice(os.path.dirname(__file__) + sim_raw)
     # Make sure that the .raw file is located in the correct path
     #l = ltspice.Ltspice('C:/Users/user/Desktop/python_spice/root_con/practice_optpy.raw' )
     tryParse(l)
     v_sim = l.getData(variables[0])
     i_sim = l.getData(variables[1])
     simulation = ModelPv(v_sim, i_sim)
     os.system('ltspice_end.bat')
     return simulation
def getData(dir):

    l = ltspice.Ltspice(dir)
    # Make sure that the .raw file is located in the correct path
    l.parse()

    time = l.getTime()
    V_source = l.getData('V(source)')
    V = l.getData('V(cap)')
    I = l.getData('I(R1)')

    return time, V, I
예제 #5
0
    for run in runList_:
        queue.put((LTSpicePath, run))
    queue.join()
    end = time()
    elapsed = end - start
    print('elapsed: ', elapsed)
    return (runList_,indexlist)

(runs, indexlist) = execRuns(16)

import ltspice
import struct

outdata = [None] * len(runs)
for r in range(len(runs)):
    outdata[r] = ltspice.Ltspice('{}.raw'.format(runs[r]))
    outdata[r].parse()

totalpoints = 0
for dat in outdata:
    totalpoints += dat._point_num

##totalpoints = outdata[0]._point_num
# TODO: this only works for TRANS...
out = open('outdata.raw','w', encoding='UTF16', newline='')
out.write('Title: * {}\n'.format('i forgot what the input file was'))
out.write('Date: {}\n'.format(outdata[0].date.strip()))
out.write('Plotname: {}\n'.format(outdata[0].plot_name.strip())) # TODO: copying this name might not always work
out.write('Flags: {}\n'.format(outdata[0].flags.strip())) # TODO: copying this name might not always work
out.write('No. Variables: {}\n'.format(outdata[0]._variable_num))
out.write('No. Points: {}\n'.format(totalpoints))
예제 #6
0
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os

file_path = 'inv_example.raw'
l = ltspice.Ltspice(file_path)
l.parse()

time = l.get_time()
V0 = l.get_data('V(N003)')
V1 = l.get_data('V(N004)')

plt.plot(time, V0)
plt.plot(time, V1)
plt.show()


    'R2 N002 N003 ' + r_2 + ' \n'
    'V1 N002 N004 SINE(0 177 60 0 0 90) \n'
    '.model D D \n'
    '.lib C:\\Users\\user\\Documents\\LTspiceXVII\\lib\\cmp\\standard.dio \n'
    '.options maxstep=1.25-5 \n'
    '.tran 0 512e-4 0 0.417e-6 \n'
    '.backanno \n'
    '.end \n')

#%% Create new netlist

newNetCall(netlist, code)
#%%Get info

#l = ltspice.Ltspice('C:/Users/user/Desktop/python_spice/root_con/practice_optpy.raw' )
l = ltspice.Ltspice(os.path.dirname(__file__) + sim_raw)
# Make sure that the .raw file is located in the correct path
l.parse()

time = l.getTime()
#v_1 = l.getData('V(V1)')
v_na = l.getData('V(n002)')
v_nb = l.getData('V(n004)')
i_in = l.getData('I(R2)')
simulation = Modelo(time, v_na - v_nb, i_in)
#%% Plotting signals

#plt.plot(time, v_1)
plt.plot(simulation.t, simulation.v)
plt.plot(time, simulation.i * 1000)
#plt.xlim((0, 1e-3))
예제 #8
0
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os

l = ltspice.Ltspice(os.path.dirname(__file__) + '/rectifier.raw')
l.parse()

time = l.get_time()
V_source = l.get_data('V(source)')
V_cap_max = []

plt.plot(time, V_source)
for i in range(l.case_count):  # Iteration in simulation cases
    time = l.get_time(i)
    # Case count starts from zero
    # Each case has different time point numbers
    V_cap = l.get_data('V(cap,pgnd)', i)
    V_cap_max.append(max(V_cap))
    plt.plot(time, V_cap)

print(V_cap_max)

plt.xlim((0, 1e-3))
plt.ylim((-15, 15))
plt.grid()
plt.savefig('rectifier.png')
plt.show()
예제 #9
0
파일: analyze.py 프로젝트: swharden/memtest
import os
import ltspice
import matplotlib.pyplot as plt
import numpy as np

filePath = os.path.join(os.path.dirname(__file__), "voltage-clamp-simple.raw")
print("loading", filePath)
assert os.path.isfile(filePath)

l = ltspice.Ltspice(filePath)
l.parse()
print("NAMES:", ", ".join(l.getVariableNames()))

times = l.getTime() * 1e3  # ms
Vcell = l.getData('V(n003)') * 1e3  # mV
Vcommand = l.getData('V(vcmd)') * 1e3  # mV
Iclamp = l.getData('I(Rf)') * 1e12  # pA

ax1 = plt.subplot(211)
plt.grid(ls='--', alpha=.5)
plt.plot(times, Iclamp, 'r-')
plt.ylabel("Current (pA)")

plt.subplot(212, sharex=ax1)
plt.grid(ls='--', alpha=.5)
plt.plot(times, Vcell, label="Cell")
plt.plot(times, Vcommand, label="Clamp")
plt.ylabel("Potential (mV)")
plt.xlabel("Time (milliseconds)")
plt.legend()
예제 #10
0

# %%
lts "circuito sencillo.net"

# %% [markdown]
# Al ejecutar esta simulación, se genera un fichero `.raw` con los resultados. Es muy parecido al `outfile` que hemos empleado antes con Ahkab. Para leer este fichero, tenemos que usar el paquete [ltspice de Python](https://github.com/DongHoonPark/ltspice_pytool), el cual podéis instalar directamente desde Jupyter:

# %%
get_ipython().system('pip install ltspice')

# %% [markdown]
# Ahora ya podemos leer este fichero `.raw` y pintar una recta de voltaje muy parecida a la que obtuvimos anteriormente con Ahkab:

# %%
l = ltspice.Ltspice("circuito sencillo.raw")
l.parse()
tiempo = l.get_time()
voltaje = l.get_data('V(1)')
corriente = l.get_data('I(V1)')
# Podemos pintar la corrente en función del tiempo
# plt.plot(tiempo, corriente)
# O el voltaje
plt.plot(tiempo, voltaje)

# %% [markdown]
# ** En resumen: ** hemos usado dos *compiladores* Spice distintos para hacer el mismo ejercicio. De igual manera podríamos haber usado [Ngspice](http://ngspice.sourceforge.net) u otro. De hecho, podíamos haber usado Ahkab en modo comando. Si tenemos correctamente instalado este framework, en princpio podemos invocarlo [directamente desde línea de comandos](https://ahkab.readthedocs.io/en/latest/help/Command-Line-Help.html):

# %%
get_ipython().system('ahkab "circuito sencillo.sp"')
예제 #11
0
import os
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate
np.set_printoptions(suppress=True)

l = ltspice.Ltspice(os.path.dirname(__file__) + "/voltage-clamp-simple.raw")
l.parse()

times = l.getTime() * 1e3  # ms
Iclamp = l.getData('I(Rf)') * 1e12  # pA

plt.figure(figsize=(6, 3))
plt.title("Irregularly Spaced Data")
plt.plot(times, Iclamp, '.-')
plt.savefig(os.path.dirname(__file__) + "/voltage-clamp-simple-fig3.png")
plt.show()

# interpolate data for 20 kHz sample rate
f = scipy.interpolate.interp1d(times, Iclamp)
pointCount = int((times[-1] - times[0]) * 20) + 1
times = np.linspace(times[0], times[-1], pointCount)
Iclamp = f(times)

plt.figure(figsize=(6, 3))
plt.grid(ls='--', alpha=.5)
plt.title("Interpolated 20kHz Signal")
plt.plot(times, Iclamp)
plt.savefig(os.path.dirname(__file__) + "/voltage-clamp-simple-fig4.png")
예제 #12
0
파일: test.py 프로젝트: swharden/memtest
import os
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate
np.set_printoptions(suppress=True)

# read data from LTSpice simulation file
l = ltspice.Ltspice(
    os.path.dirname(__file__) +
    f"/../models/single-electrode-advanced/voltage-clamp.raw")
l.parse()
times = l.getTime() * 1e3  # ms
Iclamp = l.getData('I(Rf)') * 1e12  # pA

# interpolate data for 20 kHz sample rate
f = scipy.interpolate.interp1d(times, Iclamp)
pointCount = int((times[-1] - times[0]) * 20) + 1
times = np.linspace(times[0], times[-1], pointCount)
Iclamp = f(times)

plt.figure(figsize=(6, 3))
plt.grid(ls='--', alpha=.5)
plt.title("Interpolated 20kHz Signal")
plt.plot(times, Iclamp)
plt.savefig(os.path.dirname(__file__) + "/mt1.png")
plt.show()
예제 #13
0
#%% Create new netlist

f_id = open(netlist, 'w')
f_id.write(code)
f_id.close()

#%%Simulation

os.system('ltspice_call.bat')
time.sleep(5)
os.system('ltspice_end.bat')
#%%Get info

#l = ltspice.Ltspice('C:/Users/user/Desktop/python_spice/root_con/practice_optpy.raw' )
l = ltspice.Ltspice(os.path.dirname(__file__) + '/practice_optpy.raw')
# Make sure that the .raw file is located in the correct path
l.parse()

time = l.getTime()
V_source = l.getData('V(source)')
V_cap = l.getData('V(cap)')
I_ser = l.getData('I(R1)')

#%% Plotting signals

plt.plot(time, V_source)
plt.plot(time, V_cap)
plt.plot(time, I_ser)
#plt.xlim((0, 1e-3))
#plt.ylim((-10, 10))
예제 #14
0
    parser.add_argument('graph_file',
                        metavar='graph_path',
                        type=str,
                        help="Graph file to be plot to")
    parser.add_argument('values',
                        metavar='exprs',
                        type=str,
                        nargs='+',
                        help="Expresions to be ploted")

    args = parser.parse_args()

    if (not os.path.exists(args.raw_file)):
        print('invalid raw file: file not find!', file=sys.stderr)

    raw = ltspice.Ltspice(args.raw_file)
    raw.parse()

    print(len(raw.variables), 'variable found')

    time = raw.get_time()

    graph_datas = []

    for need_exps in args.values:
        if (not need_exps in raw.variables):
            print('"%s" did not contains "%s"' % (args.raw_file, need_exps))

        graph_datas.append({
            "name":
            need_exps,
예제 #15
0
## Writing the netlist to a file
print('Writing the .net file for LTspice XVII...')
file = NETLIST_PATH
with open(file, mode='w') as f:
    f.write(netlist)

## Executing LTspice XVII in batch mode
## (Possibly, handling of error is needed.)
print('Running LTspice XVII...')
subprocess.call([LTSPICE_PATH, '-b', file])
print('LTspice XVII simulation successfully completed!')

## Loading the simulation results
print('Loading the resulting .raw file...')
l = ltspice.Ltspice(file.replace('.net', '.raw'))
l.parse()
time = l.getTime()

## Node and branch settings
node = range(N_STAGES + 1)
xt = [n / N_STAGES * LENGTH for n in node]
branch = range(N_STAGES)
xb = [(n + 0.5) / N_STAGES * LENGTH for n in branch]

## Obtaining waveform: Signal source
v_source = l.getData('V(1)')

## Obtaining waveform: Node voltages
vn, vn_interp = [], []
for i in node:
예제 #16
0
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os

l = ltspice.Ltspice(os.path.dirname(__file__) + '/01_RC_circuit.raw')
# Make sure that the .raw file is located in the correct path
l.parse()

time = l.getTime()
V_source = l.getData('V(source)')
V_cap = l.getData('V(cap)')

plt.plot(time, V_source)
plt.plot(time, V_cap)
plt.xlim((0, 1e-3))
plt.ylim((-10, 10))
plt.grid()
plt.show()
예제 #17
0
    def graficar(self,archivo,Rs,RL):
        # Obtenención de datos
        l = ltspice.Ltspice(os.getcwd()+'/'+archivo) 
        l.parse()
        
        unidadesFrecuencia='MHz'
        unidadesFrecuenciaFactor=1e-6

        f= l.get_frequency()*unidadesFrecuenciaFactor
        v_in =l.get_data('V(in)')
        i_vin=l.get_data('i(vin)')
        v_out =l.get_data('V(out)')

         # Operaciones
        H=20*np.log10(abs(v_out/v_in))
        H_angle=(np.angle(v_out/v_in))*180/math.pi
    
        dB_corte=20*np.log10(1/(2**0.5))

        nMax=self.posicionMagnitudMaxima(H)
        f_resonancia=f[nMax]

        nOmegaLow=self.posicionPrimerCoicidenciaSentidoPositivo(H,H[nMax]+dB_corte)
        f_low=f[nOmegaLow]

        nOmegaHigh=self.posicionPrimerCoicidenciaSentidoNegativo(H,H[nMax]+dB_corte)
        f_high=f[nOmegaHigh]

        Q=f_resonancia/(f_high-f_low)

        print('f_o: ',f_resonancia,unidadesFrecuencia)
        print(f'Q={Q} {unidadesFrecuencia}/{unidadesFrecuencia}')  

        # Configuración de texto

        conf_left = {'fontsize':12,'horizontalalignment':'left','verticalalignment':'top'}
        conf_right= {'fontsize':12,'horizontalalignment':'right','verticalalignment':'top'}
        conf_center= {'fontsize':12,'horizontalalignment':'center','verticalalignment':'baseline'}


        ## Factor de calidad

        fig, axs = plt.subplots(2, 1)
        axs[0].semilogx(f,H,f,np.ones(len(H))*(H[nMax]+dB_corte))
        axs[1].semilogx(f,H_angle)
        
        axs[0].set_xticks((np.arange(70,110,step=10)))
        axs[1].set_xticks((np.arange(70,110,step=10)))
        
        axs[0].text(f[nMax],H[nMax]\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{H[nMax].round(3)}[dB])',conf_center)
        
        #H_c_low=H[nOmegaLow]+(H[0]-H[nOmegaLow])/8
        axs[0].text(f[nOmegaLow],H[nOmegaLow]\
            ,f'({f[nOmegaLow].round(3)} [{unidadesFrecuencia}],{H[nOmegaLow].round(3)}[dB])',conf_right)
        #H_c_high=H[nOmegaHigh]+(H[0]-H[nOmegaHigh])/8
        axs[0].text(f[nOmegaHigh],H[nOmegaHigh]\
            ,f'({f[nOmegaHigh].round(3)} [{unidadesFrecuencia}],{H[nOmegaHigh].round(3)}[dB])',conf_left)
        H_m=H[nMax]+(H[0]-H[nMax])/2
        axs[0].text(f[nMax],H_m\
            ,f'Q={Q.round(3)}',conf_center)
        
        
        axs[1].text(f[nMax],H_angle[nMax]*0.97\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{H_angle[nMax].round(3)}[$^0 $])',conf_left)
        
        axs[0].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        axs[1].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        
        axs[0].set_ylabel('Magnitud [dB]')
        axs[1].set_ylabel('Arg(H) [$^0 $]')

        axs[0].legend(['H','-3 [dB]'],loc="lower right")

        axs[0].grid(True)
        axs[1].grid(True)
        plt.show()

        
        
        ## Impedancia de entrada del amplificador

        Z_in_amplificador=abs(v_in/i_vin)-Rs
        Z_in_amplificador_fase=np.angle(v_in/i_vin)*180/math.pi


        fig, axs = plt.subplots(2, 1)
        axs[0].semilogx(f, Z_in_amplificador)
        axs[1].semilogx(f, Z_in_amplificador_fase)
        
        axs[0].set_xticks((np.arange(70,110,step=10)))
        axs[1].set_xticks((np.arange(70,110,step=10)))
        
        axs[0].text(f[nMax],Z_in_amplificador[nMax]*0.97\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{Z_in_amplificador[nMax].round(3)}[$\Omega $])',conf_left)
        axs[1].text(f[nMax],Z_in_amplificador_fase[nMax]*0.97\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{Z_in_amplificador_fase[nMax].round(3)}[$^0 $])',conf_left)
        
        axs[0].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        axs[1].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        
        axs[0].set_ylabel('|Z|')
        axs[1].set_ylabel('Arg(Z) [$^0 $]')

        axs[0].grid(True)
        axs[1].grid(True)
        plt.show()

        ## Potencia
        S_fuente=v_in*np.conj(i_vin) #[VA] Potencia aparente
        S_carga=v_out*np.conj(v_out/RL) #[VA] Potencia aparente

        P_fuente=np.real(S_fuente) #[W] Potencia real
        P_carga=np.real(S_carga) #[[W]] Potencia real
        
        Q_fuente=np.imag(S_fuente) #[W] Potencia real
        Q_carga=np.imag(S_carga) #[[W]] Potencia real

        H_P=P_carga/P_fuente
        H_Q=Q_carga/Q_fuente
        
        fig, axs = plt.subplots(2, 1)
        axs[0].semilogx(f, H_P)
        axs[1].semilogx(f, H_Q)
        
        axs[0].set_xticks((np.arange(70,110,step=10)))
        axs[1].set_xticks((np.arange(70,110,step=10)))
        
        axs[0].text(f[nMax],H_P[nMax]\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{H_P[nMax].round(3)} [W/W])',conf_left)
        axs[1].text(f[nMax],H_Q[nMax]\
            ,f'({f[nMax].round(3)} [{unidadesFrecuencia}],{H_Q[nMax].round(3)} [VAR/VAR])',conf_left)
        
        axs[0].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        axs[1].set_xlabel(f'frecuencia [{unidadesFrecuencia}]')
        
        axs[0].set_ylabel('Pout/Pin [W/W]')
        axs[1].set_ylabel('Pout/Pin [VAR/VAR]')

        axs[0].grid(True)
        axs[1].grid(True)
        plt.show()
예제 #18
0
import os
import ltspice
import matplotlib.pyplot as plt
import numpy as np

base = os.path.dirname(__file__)
fp = f"{base}\\fft.fft"

lt = ltspice.Ltspice(fp)

lt.parse()
vars = lt.getVariableNames()
print(f"FFT Variables: {vars}")

f = lt.getFrequencies()
fig, ax = plt.subplots()


for var in ('V(ip)', 'V(op)'):
    res = 20 * np.log10(lt.getData(var))
    ax.semilogx(f, res, label=var)

fig.legend()
plt.show()
예제 #19
0
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os

l = ltspice.Ltspice(os.path.dirname(__file__) + '/rc.raw')
l.parse()

time = l.get_time()
V_source = l.get_data('V(source)')
V_cap = l.get_data('V(cap)')

plt.plot(time, V_source)
plt.plot(time, V_cap)
plt.xlim((0, 1e-3))
plt.ylim((-10, 10))
plt.grid()
plt.savefig("rc.png")
plt.show()
예제 #20
0
파일: analyze.py 프로젝트: swharden/memtest
# read data from the LTSpice .raw file
import ltspice
l = ltspice.Ltspice("voltage-clamp.raw")
l.parse()

# obtain data by its identifier and scale it as desired
times = l.getTime() * 1e3  # ms
Vcell = l.getData('V(n007)') * 1e3  # mV
Vcommand = l.getData('V(n006)') * 1e3  # mV
Iclamp = l.getData('I(Rf)') * 1e12  # pA

# plot scaled simulation data
import matplotlib.pyplot as plt

ax1 = plt.subplot(211)
plt.grid(ls='--', alpha=.5)
plt.plot(times, Iclamp, 'r-')
plt.ylabel("Current (pA)")

plt.subplot(212, sharex=ax1)
plt.grid(ls='--', alpha=.5)
plt.plot(times, Vcell, label="Cell")
plt.plot(times, Vcommand, label="Clamp")
plt.ylabel("Potential (mV)")
plt.xlabel("Time (milliseconds)")
plt.legend()

plt.margins(0, .1)
plt.tight_layout()
plt.savefig("voltage-clamp-simple-fig1.png")
#plt.show()
예제 #21
0
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os

l = ltspice.Ltspice(os.path.dirname(__file__)+'/energy_calc.raw') 
l.parse() 

energy_R1 = []

for i in range(l.case_count): # Iteration in simulation cases
    time = l.get_time(i)
    I_R1 = l.get_data('I(R1)',i)
    R1 = 1
    power_R1 = R1 * I_R1 * I_R1 # Calc dissipated power from R1 from 0 to 5ms
    a = ltspice.integrate(time, power_R1, [0, 5e-3])
    energy_R1.append(a)
    
cond = np.linspace(1e-3, 10e-3, 10) #Simulation condition written in .asc file

plt.xlabel("RL circuit inductance (H)")
plt.ylabel("Energy (J)")
plt.grid()
plt.plot(cond, energy_R1)
plt.savefig('energy_calc.png')
plt.show()
예제 #22
0
    def readRaw(self):
        if Config.simulator == "LTSPICE":
            raw = ltspice.Ltspice(Config.TEMP_DIR + self.filename + ".raw")
            raw.parse()

            data = dict()
            for var in raw.getVariableNames():
                if var == "time":
                    data["time"] = raw.getTime()
                else:
                    data[var] = raw.getData(var)
            del raw
            return data

        elif Config.simulator == "NGSPICE_WRDATA":
            read = pd.read_csv(Config.TEMP_DIR + "output.m", delimiter="\s+")

            d = dict()
            for col in read.columns:
                d[col] = np.array(read[col], dtype=np.float64)

            return d

        elif Config.simulator == "NGSPICE":
            # shameless rip from
            # https://gist.github.com/snmishra/27dcc624b639c2626137

            BSIZE_SP = 512
            MDATA_LIST = [
                b'title', b'date', b'plotname', b'flags', b'no. variables',
                b'no. points', b'dimensions', b'command', b'option'
            ]

            try:
                fp = open(Config.TEMP_DIR + self.filename + ".raw", 'rb')
            except:
                print("NO RAW FILE")
                return {"None": [None]}

            plot = {}
            count = 0
            arrs = []
            plots = []

            while (True):
                try:
                    mdata = fp.readline(BSIZE_SP).split(b':', maxsplit=1)
                except:
                    raise
                if len(mdata) == 2:
                    if mdata[0].lower() in MDATA_LIST:
                        plot[mdata[0].lower()] = mdata[1].strip()
                    if mdata[0].lower() == b'variables':
                        nvars = int(plot[b'no. variables'])
                        npoints = int(plot[b'no. points'])
                        plot['varnames'] = []
                        plot['varunits'] = []
                        for varn in range(nvars):
                            varspec = (fp.readline(BSIZE_SP).strip().decode(
                                'ascii').split())
                            assert (varn == int(varspec[0]))
                            plot['varnames'].append(varspec[1])
                            plot['varunits'].append(varspec[2])
                    if mdata[0].lower() == b'binary':
                        dtype = [
                            np.complex_
                            if b'complex' in plot.get(b'flags') else np.float_
                        ] * nvars

                        rowdtype = np.dtype({
                            "names": plot["varnames"],
                            "formats": dtype
                        })
                        # We should have all the metadata by now
                        arrs.append(
                            np.fromfile(fp, dtype=rowdtype, count=npoints))
                        plots.append(plot)
                        fp.readline()  # Read to the end of line
                else:
                    break

            d = dict()
            for i, var in enumerate(plots[0]["varnames"]):
                name = var
                # capitalize V or I
                if "v(" in var:
                    name = "V" + var[1:]
                if "i(" in var:
                    name = "I" + var[1:]

                d[name] = list()
                for data in arrs[0]:
                    d[name].append(data[i].real)
                d[name] = np.array(d[name])

            return d