Exemplo n.º 1
0
 def regla4y5(self, pila, operacion, indice):
     if type(operacion.Condicion.Op1) == C3D.Valor and type(
             operacion.Condicion.Op2) == C3D.Valor:
         #Significa que ambos elementos a comparar son constantes. por lo que se cumple parte de la regla 4
         if self.ejecutarComparacion(operacion.Condicion.Op1.Valor,
                                     operacion.Condicion.Operador,
                                     operacion.Condicion.Op2.Valor):
             print('regla 4')
             self.ElementosIgnorar.append(indice)
             if len(pila) > indice + 1 and type(
                     pila[indice + 1]) == C3D.Goto:
                 self.ElementosIgnorar.append(indice + 1)
             nuevaOrden = C3D.Goto(
                 C3D.Identificador(operacion.EtiquetaTrue.Id))
             self.ListaOptimizada.append(nuevaOrden)
             return
         else:
             print('regla 5')
             self.ElementosIgnorar.append(indice)
             if len(pila) > indice + 1 and type(
                     pila[indice + 1]) == C3D.Goto:
                 self.ElementosIgnorar.append(indice + 1)
                 nuevaOrden = C3D.Goto(
                     C3D.Identificador(pila[indice + 1].Etiqueta.Id))
                 self.ListaOptimizada.append(nuevaOrden)
Exemplo n.º 2
0
    def regla16(self, operacion, indice):
        if type(operacion.Valor) == C3D.Operacion:
            asignado = self.verificaValor(operacion.Tx)
            op1 = self.verificaValor(operacion.Valor.Op1)
            op2 = self.verificaValor(operacion.Valor.Op2)
            operador = operacion.Valor.Operador
            if (operador
                    == C3D.OP_ARITMETICO.MULTIPLICACION) and (op2 == '2'
                                                              or op1 == '2'):
                #Agregamos los datos ya optimizados
                nuevaOperacion = C3D.Asignacion(
                    C3D.Identificador(asignado),
                    C3D.Operacion(operacion.Tx, operacion.Tx,
                                  C3D.OP_ARITMETICO.SUMA))
                #Generamos los datos para realizar el reporte de optimizacion
                termino = ""
                optimizado = ""
                if op1 == '2':
                    termino = asignado + " = " + op1 + " * " + op2
                    optimizado = asignado + " = " + op2 + " + " + op2
                elif op2 == '2':
                    termino = asignado + " = " + op1 + " * " + op2
                    optimizado = asignado + " = " + op1 + " + " + op1

                self.reporteOptimizado.append(
                    ["Regla 16", termino, optimizado,
                     str(indice + 1)])
                return nuevaOperacion
            else:
                return False
        else:
            return False
Exemplo n.º 3
0
def main():
    t1 = 5 < 9
    if t1: goto.L1
    goto.L2

    label.L1
    C3D.eje_if = "Verdadero"
    C3D.pila = 0
    C3D.ejecutar()  #Crear Base de datos

    goto.L3

    label.L2
    C3D.eje_if = "Else"
    C3D.pila = 0
    C3D.ejecutar()  #Crear Base de datos

    label.L3
Exemplo n.º 4
0
def main():
t1 = 5 > 9
if t1 : goto .L1
goto .L2

label .L1
C3D.pila = 0
C3D.eje_if = "Verdadero"
C3D.ejecutar() #Crear Base de datos
#print("si jala")

goto .L3

label .L2
C3D.pila = 0
C3D.eje_if = "Else"
C3D.ejecutar() #Crear Base de datos

label .L3
main()
Exemplo n.º 5
0
 def regla4y5(self, pila, operacion, indice):
     if type(operacion.Condicion.Op1) == C3D.Valor and type(
             operacion.Condicion.Op2) == C3D.Valor:
         #Significa que ambos elementos a comparar son constantes. por lo que se cumple parte de la regla 4
         if self.ejecutarComparacion(operacion.Condicion.Op1.Valor,
                                     operacion.Condicion.Operador,
                                     operacion.Condicion.Op2.Valor):
             #print('regla 4')
             termino = 'if ' + self.ImprimirCondicional(
                 operacion.Condicion) + ' goto ' + operacion.EtiquetaTrue.Id
             self.ElementosIgnorar.append(indice)
             if len(pila) > indice + 1 and type(
                     pila[indice + 1]) == C3D.Goto:
                 termino = termino + 'goto ' + pila[indice + 1].Etiqueta.Id
                 self.ElementosIgnorar.append(indice + 1)
             nuevaOrden = C3D.Goto(
                 C3D.Identificador(operacion.EtiquetaTrue.Id))
             optimizado = 'goto ' + nuevaOrden.Etiqueta.Id
             self.reporteOptimizado.append(
                 ["Regla 4", termino, optimizado,
                  str(indice + 1)])
             self.ListaOptimizada.append(nuevaOrden)
             return
         else:
             #print('regla 5')
             self.ElementosIgnorar.append(indice)
             if len(pila) > indice + 1 and type(
                     pila[indice + 1]) == C3D.Goto:
                 termino = 'if ' + self.ImprimirCondicional(
                     operacion.Condicion
                 ) + ' goto ' + operacion.EtiquetaTrue.Id
                 termino = termino + 'goto ' + pila[indice + 1].Etiqueta.Id
                 self.ElementosIgnorar.append(indice + 1)
                 nuevaOrden = C3D.Goto(
                     C3D.Identificador(pila[indice + 1].Etiqueta.Id))
                 self.ListaOptimizada.append(nuevaOrden)
                 optimizado = 'goto ' + nuevaOrden.Etiqueta.Id
                 self.reporteOptimizado.append(
                     ["Regla 5", termino, optimizado,
                      str(indice + 1)])
Exemplo n.º 6
0
 def CambiarComparador(self, condicion):
     if condicion.Operador == C3D.OP_RELACIONAL.MAYOR_QUE:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.MENOR_IGUAL_QUE)
     if condicion.Operador == C3D.OP_RELACIONAL.MAYOR_IGUAL_QUE:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.MENOR_QUE)
     if condicion.Operador == C3D.OP_RELACIONAL.MENOR_QUE:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.MAYOR_IGUAL_QUE)
     if condicion.Operador == C3D.OP_RELACIONAL.MENOR_IGUAL_QUE:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.MAYOR_QUE)
     if condicion.Operador == C3D.OP_RELACIONAL.IGUAL:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.DIFERENTE)
     if condicion.Operador == C3D.OP_RELACIONAL.DIFERENTE:
         return C3D.Condicion(condicion.Op1, condicion.Op2, C3D.OP_RELACIONAL.IGUAL)
Exemplo n.º 7
0
 def regla12_13(self, operacion, indice):
     if type(operacion.Valor) == C3D.Operacion:
         asignado = self.verificaValor(operacion.Tx)
         op1 = self.verificaValor(operacion.Valor.Op1)
         op2 = self.verificaValor(operacion.Valor.Op2)
         operador = operacion.Valor.Operador
         if (asignado != op1) and (operador
                                   == C3D.OP_ARITMETICO.SUMA) and (op2
                                                                   == '0'):
             #Agregamos los datos ya optimizados
             nuevaOperacion = C3D.Asignacion(C3D.Identificador(asignado),
                                             operacion.Valor.Op1)
             #Generamos los datos para realizar el reporte de optimizacion
             termino = asignado + " = " + op1 + " + " + op2
             optimizado = asignado + " = " + op1
             self.reporteOptimizado.append(
                 ["Regla 12", termino, optimizado,
                  str(indice + 1)])
             return nuevaOperacion
         elif (asignado != op2) and (
                 operador == C3D.OP_ARITMETICO.SUMA) and (op1 == '0'):
             #Agregamos los datos ya optimizados
             nuevaOperacion = C3D.Asignacion(C3D.Identificador(asignado),
                                             operacion.Valor.Op2)
             #Generamos los datos para realizar el reporte de optimizacion
             termino = asignado + " = " + op1 + " + " + op2
             optimizado = asignado + " = " + op2
             self.reporteOptimizado.append(
                 ["Regla 12", termino, optimizado,
                  str(indice + 1)])
             return nuevaOperacion
         elif (asignado != op1) and (
                 operador == C3D.OP_ARITMETICO.RESTA) and (op2 == '0'):
             #Agregamos los datos ya optimizados
             nuevaOperacion = C3D.Asignacion(C3D.Identificador(asignado),
                                             operacion.Valor.Op1)
             #Generamos los datos para realizar el reporte de optimizacion
             termino = asignado + " = " + op1 + " - " + op2
             optimizado = asignado + " = " + op1
             self.reporteOptimizado.append(
                 ["Regla 13", termino, optimizado,
                  str(indice + 1)])
             return nuevaOperacion
         else:
             return False
     else:
         return False
parser.add_argument('--model', default='/home/yangwang/env/models/C3D@UCF101_s1/MatFile/params.mat', help='model to test')
parser.add_argument('--saveDir', default='c3d_feat_dense/', help='file to save results')
# misc

def mkdir_p(path):
    if not os.path.isdir(path):
        os.makedirs(path)

print('==> parsing options')
global opts
opts = parser.parse_args()
print(opts)
mkdir_p(opts.saveDir)

print('==> create model')
model = C3D(nClass=opts.nClass, dropRatio=opts.dropRatio, leak=opts.leak)
model.cuda().eval()

print('==> initialize model with [%s]'%(opts.model))
if opts.model[-4:]=='.mat':
    model._init_from_mat(opts.model, lastLayer=False)
elif os.path.isfile(opts.model):
    L = torch.load(opts.model)
    model.load_state_dict(L['state_dict'])
else:
    print('[%s] not found'%(opts.model))
    quit()

print('==> register forward hook functions')
Buffer = {}
def _relu6_hook(self, input, output):
Exemplo n.º 9
0
    from GCore import Calibrate
    import MovieReader
    import C3D

    global ted_geom, ted_geom2, ted_shape, tony_geom, tony_shape, tony_geom2, tony_obj, ted_obj, diff_geom, c3d_frames
    global tony_shape_vector, tony_shape_mat, ted_lo_rest, ted_lo_mat, c3d_points
    global md, movies

    ted_dir = os.path.join(os.environ['GRIP_DATA'], 'ted')

    wavFilename = os.path.join(ted_dir, '32T01.WAV')
    md = MovieReader.open_file(wavFilename)

    c3d_filename = os.path.join(
        ted_dir, '201401211653-4Pico-32_Quad_Dialogue_01_Col_wip_02.c3d')
    c3d_dict = C3D.read(c3d_filename)
    c3d_frames, c3d_fps, c3d_labels = c3d_dict['frames'], c3d_dict[
        'fps'], c3d_dict['labels']
    if False:  # only for cleaned-up data
        c3d_subject = 'TedFace'
        which = np.where([s.startswith(c3d_subject) for s in c3d_labels])[0]
        c3d_frames = c3d_frames[:, which, :]
        c3d_labels = [c3d_labels[i] for i in which]
        print c3d_labels
    if False:  # this is for the cleaned-up data (don't apply the other offset...)
        offset = Calibrate.composeRT(Calibrate.composeR((0.0, 0.0, 0)),
                                     (0, 0, -8), 0)  # 0.902
        c3d_frames[:, :, :3] = np.dot(c3d_frames[:, :, :3] - offset[:3, 3],
                                      offset[:3, :3])[:, :, :3]
    offset = Calibrate.composeRT(Calibrate.composeR((3.9, -38.7, 0)),
                                 (-159.6, 188.8, 123 - 12), 0)  # 0.902
Exemplo n.º 10
0
names = 'spiking_model'
data_path = './raw/'  # todo: input your data path
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_dataset = torchvision.datasets.MNIST(root=data_path, train=True, download=True, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)

test_set = torchvision.datasets.MNIST(root=data_path, train=False, download=True, transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)

best_acc = 0  # best test accuracy
start_epoch = 0  # start from epoch 0 or last checkpoint epoch
acc_record = list([])
loss_train_record = list([])
loss_test_record = list([])

snn = C3D(20)
snn.to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(snn.parameters(), lr=learning_rate)

for epoch in range(num_epochs):
    # ============= Train =====================
    running_loss = 0
    start_time = time.time()
    for i, (images, labels) in enumerate(train_loader):
        # --- create zoom-in and zoom-out version of each image
        images2 = torch.empty((images.shape[0] * 2, 10, images.shape[2], images.shape[3]))
        labels2 = torch.empty((images.shape[0] * 2), dtype=torch.int64)
        for j in range(images.shape[0]):
            img0 = images[j, 0, :, :].numpy()
            rows, cols = img0.shape
Exemplo n.º 11
0
test_set = torchvision.datasets.MNIST(root=data_path,
                                      train=False,
                                      download=True,
                                      transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(test_set,
                                          batch_size=batch_size,
                                          shuffle=False,
                                          num_workers=0)

best_acc = 0  # best test accuracy
start_epoch = 0  # start from epoch 0 or last checkpoint epoch
acc_record = list([])
loss_train_record = list([])
loss_test_record = list([])

snn = C3D(10)
snn.to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(snn.parameters(), lr=learning_rate)

for epoch in range(num_epochs):
    # ============= Train =====================
    running_loss = 0
    start_time = time.time()
    for i, (images, labels) in enumerate(train_loader):
        # --- create zoom-in and zoom-out version of each image
        images2 = torch.empty(
            (images.shape[0] * 2, 10, images.shape[2], images.shape[3]))
        labels2 = torch.empty((images.shape[0] * 2), dtype=torch.int64)
        for j in range(images.shape[0]):
            img0 = images[j, 0, :, :].numpy()