示例#1
0
 def rellenar_cobros(self):
     model = self.wids['tv_cobros'].get_model()
     model.clear()
     if self.objeto.cobros != []:
         utils.combo_set_from_db(self.wids['cbe_cliente'], 
                                 self.objeto.cobros[0].cliente.id)
     for c in self.objeto.cobros:
         if c.facturaVentaID != None:
             importe_factura = c.facturaVenta.importeTotal
             vencimientos = "(%d) " % len(c.facturaVenta.vencimientosCobro)
             vencimientos += "; ".join(
                 ["%s: %s €" % (utils.str_fecha(v.fecha), 
                  utils.float2str(v.importe)) 
                  for v in c.facturaVenta.vencimientosCobro])
         elif c.prefacturaID != None:
             importe_factura = c.prefactura.importeTotal
             vencimientos = "(%d) " % (len(c.prefactura.vencimientosCobro))
             vencimientos += "; ".join(
                 ["%s: %s €" % (utils.str_fecha(v.fecha), 
                                utils.float2str(v.importe)) 
                  for v in c.prefactura.vencimientosCobro])
         model.append((c.numfactura, 
                       "%s €" % (utils.float2str(c.importe)), 
                       utils.str_fecha(c.fecha), 
                       "%s €" % (utils.float2str(importe_factura)),
                       vencimientos,  
                       c.id))
 def rellenar_pies(self, 
                   total, pendiente, cobrado, 
                   total_pagares, pendiente_pagares, cobrado_pagares, 
                   total_otros, pendiente_otros, cobrado_otros, 
                   total_vencimientos, cobrado_strict):
     """
     Rellena los entries del pie del formulario con los totales recibidos.
     CWT: Al pendiente de cobro hay que restarle lo negociado en pagaré, 
     aunque no hayan vencido o estén marcados como pendiente.
     Por tanto, el 
     pendiente = total (facturado) - total_pagares - cobrado_otros
     y (lo mismo pero jugando con las incóginitas) el 
     cobrado = total_pagares + cobrado_otros = total - pendiente
     """
     self.wids['e_total'].set_text("%s €" % utils.float2str(total))
     # self.wids['e_pendiente'].set_text("%s €" % utils.float2str(pendiente))
     self.wids['e_pendiente'].set_text("%s €" % utils.float2str(total_vencimientos - total_pagares - cobrado_otros))
     self.wids['e_cobrado_strict'].set_text("%s €" % utils.float2str(cobrado_strict))
     # self.wids['e_cobrado'].set_text("%s €" % utils.float2str(cobrado))
     self.wids['e_cobrado'].set_text("%s €" % utils.float2str(total_pagares + cobrado_otros))
     self.wids['e_total_pagares'].set_text("%s €" % utils.float2str(total_pagares))
     self.wids['e_pendiente_pagares'].set_text("%s €" % utils.float2str(pendiente_pagares))
     self.wids['e_cobrado_pagares'].set_text("%s €" % utils.float2str(cobrado_pagares))
     self.wids['e_total_otros'].set_text("%s €" % utils.float2str(total_otros))
     self.wids['e_pendiente_otros'].set_text("%s €" % utils.float2str(pendiente_otros))
     self.wids['e_cobrado_otros'].set_text("%s €" % utils.float2str(cobrado_otros))
 def imprimir(self,boton):
     """
     Prepara la vista preliminar para la impresión del informe
     """
     import informes
     datos = []
     total = 0
     self.resultados.sort(self.por_fecha_ldc)
     for ldc in self.resultados:
         subtotal = ldc.cantidad * ldc.precio
         datos.append((ldc.nombre_proveedor,
                       ldc.albaranEntrada.numalbaran,
                       utils.str_fecha(ldc.albaranEntrada.fecha),
                       ldc.descripcion_productoCompra,
                       utils.float2str(ldc.cantidad),
                       utils.float2str(ldc.precio),
                       utils.float2str(subtotal)
                     ))
         total += subtotal
     if len(self.resultados) > 0:
         datos.append(("", "", "", "", "", "", "-"*20))
         datos.append(("", "", "", "", "", "", utils.float2str(total)))
     if (self.inicio) == None:            
         fechaInforme = 'Hasta '+utils.str_fecha(self.fin)
     else:
         fechaInforme = utils.str_fecha(self.inicio)+' - '+utils.str_fecha(self.fin)
     if datos != []:
         informes.abrir_pdf(geninformes.entradasAlmacen(datos,fechaInforme, cols_a_derecha=(4, 5, 6)))
示例#4
0
def valorar_a_precio_valoracion(tv):
    """
    Valora todos los productos de compra con existencias distintas a cero 
    (OJO: Incluye existencias negativas) según el precio de valoración 
    definido (precio por defecto, precio medio ponderado, etc.).
    """
    pcs = pclases.ProductoCompra.select(pclases.AND(
            pclases.ProductoCompra.q.controlExistencias == True, 
            pclases.ProductoCompra.q.existencias != 0))
    model = tv.get_model()
    tv.freeze_child_notify()
    tv.set_model(None)
    model.clear()
    suma = 0.0
    for pc in pcs:
        precio_valoracion = pc.get_precio_valoracion()
        valoracion = precio_valoracion * pc.existencias
        model.append((pc.codigo, 
                      pc.descripcion, 
                      utils.float2str(pc.existencias,precision=2,autodec=True),
                      utils.float2str(precio_valoracion, precision = 2), 
                      utils.float2str(valoracion, precision = 2), 
                      pc.id))
        suma += valoracion
    tv.set_model(model)
    tv.thaw_child_notify()
    return suma
 def rellenar_widgets(self):
     """
     Introduce la información del producto actual
     en los widgets.
     No se chequea que sea != None, así que
     hay que tener cuidado de no llamar a 
     esta función en ese caso.
     """
     producto = self.objeto
     self.wids['i_barcode'].set_from_file(EanBarCode().getImage(producto.codigo))
     self.wids['e_codigo'].set_text(producto.codigo)
     self.wids['e_descripcion'].set_text(producto.descripcion)
     self.wids['e_nombre'].set_text(producto.nombre)
     self.wids['e_precio'].set_text(str(producto.preciopordefecto))
     self.wids['e_minimo'].set_text(str(producto.minimo))
     self.wids['e_arancel'].set_text(str(producto.arancel))
     self.wids['e_prodestandar'].set_text(utils.float2str(producto.prodestandar))
     campos = producto.camposEspecificosEspecial
     self.wids['e_stock'].set_text(utils.float2str(campos.stock))
     self.wids['e_existencias'].set_text(str(campos.existencias))
     try:
         pesobulto = utils.float2str(producto.calcular_razon_bultos())
     except (ValueError, TypeError):
         pesobulto = "N/A"
     self.wids['e_razon'].set_text(pesobulto)
     self.wids['e_unidad'].set_text(campos.unidad)
     self.wids['e_observaciones'].set_text(campos.observaciones)
     # Datos no modificables:
     self.wids['e_idproducto'].set_text(`producto.id`)
     self.mostrar_especificos()
     self.rellenar_tabla_tarifas()
     self.rellenar_existencias_almacen(producto)
     self.objeto.make_swap()
     self.objeto.camposEspecificosEspecial.make_swap()
示例#6
0
 def rellenar_tabla(self, facturas):
     """
     Rellena el model con los items de la consulta
     """        
     model = self.wids['tv_datos'].get_model()
     model.clear()
     self.wids['tv_datos'].freeze_child_notify()
     self.wids['tv_datos'].set_model(None)
     for cliente in facturas:
         padre = model.append(None, (cliente and cliente.nombre 
                                         or "Sin cliente", 
                                     "0.00", 
                                     "", 
                                     "0.00", 
                                     cliente and cliente.get_puid() or ""))
         for factura in facturas[cliente]:
             formapago = factura.get_forma_de_pago()
             importe = factura.calcular_total()
             pdte = factura.calcular_pendiente_de_documento_de_pago()
             model[padre][1] = utils.float2str(utils._float(model[padre][1])
                 + importe)
             model[padre][3] = utils.float2str(utils._float(model[padre][3])
                 + pdte)
             model.append(padre, (factura.numfactura, 
                                  utils.float2str(importe), 
                                  utils.str_fecha(factura.fecha), 
                                  utils.float2str(pdte), 
                                  factura.get_puid()))
     self.wids['tv_datos'].set_model(model)
     self.wids['tv_datos'].thaw_child_notify()
示例#7
0
def build_tabla_contenido(data):
    """
    Construye la tabla del contenido del albaranSalida.
    Los datos deben venir en listas. Cada línea de la tabla, una tupla o lista 
    con el código, descripción, cantidad, precio unitario (con dto. si lo 
    lleva e IVA) y número de pedido.
    El precio y cantidad deben ser flotantes para poder calcular el subtotal.
    """
    estilo_cabecera_tabla = ParagraphStyle("Cabecera tabla", 
                                           parent=estilos["Heading3"])
    estilo_cabecera_tabla.fontName = "Times-Bold"
    estilo_cabecera_tabla.alignment = enums.TA_CENTER
    estilo_numeros_tabla = ParagraphStyle("Números tabla", 
                                           parent=estilos["Normal"])
    estilo_numeros_tabla.alignment = enums.TA_RIGHT
    datos = [(Paragraph(escribe("Código"), estilo_cabecera_tabla), 
              Paragraph(escribe("Descripción"), estilo_cabecera_tabla), 
              Paragraph("Cantidad", estilo_cabecera_tabla), 
              Paragraph("Precio/U", estilo_cabecera_tabla), 
              #Paragraph("Total c/IVA", estilo_cabecera_tabla), 
              # CWT: Prefiere la carta de portes sin IVA.
              Paragraph("Total", estilo_cabecera_tabla), 
              Paragraph(escribe("Nº Pedido"), estilo_cabecera_tabla))
            ]
    for d in data:
        fila = (escribe(d[0]), 
                Paragraph(escribe(d[1]),estilos["Normal"]), 
                Paragraph(escribe(utils.float2str(d[2])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[3])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[2] * d[3])), 
                    estilo_numeros_tabla),
                escribe(d[4])
               )
        datos.append(fila)
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.35, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.11), 
                  repeatRows = 1)
    tabla.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), 
        ("LINEBEFORE", (0, 0), (-1, -1), 0.25, colors.black),
        ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black), 
        ("LINEBELOW", (0, "splitlast"), (-1, "splitlast"), 1.0, colors.black), 
        ("BOX", (0, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), 
        ("VALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("VALIGN", (0, 0), (0, -1), "TOP"), 
        ("ALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("ALIGN", (-3, 1), (-1, -1), "RIGHT"), 
        #("ALIGN", (0, 1), (0, -1), "DECIMAL"), <- No puedo cambiar 
        #                               el pivotChar de "." a ",". No me vale.
        ("ALIGN", (-1, 1), (-1, -1), "CENTER"), 
        ("ALIGN", (0, 1), (0, -1), "CENTER"), 
        #("RIGHTPADDING", (0, 1), (0, -1), 0.75 * cm), 
        ]))
    return tabla
示例#8
0
 def rellenar_tabla(self, tabla):
     """
     Rellena el model con las ldc existentes
     """
     albaran = self.objeto
     if albaran != None:
         lineas = albaran.lineasDeCompra
         try:
             lineas.sort(lambda l1, l2: l1.id - l2.id)
         except:
             pass
         model = self.wids['tv_ldvs'].get_model()
         model.clear()
         for l in lineas:
             model.append((l.productoCompra.codigo,
                           l.productoCompra.descripcion,
                           utils.float2str(l.cantidad, 2),
                           utils.float2str(l.precio, 4, autodec = True),
                           "%s %%" % (utils.float2str(l.iva * 100, 0)),
                           "%s %%" % (utils.float2str(l.descuento * 100, 0)),
                           utils.float2str(l.get_subtotal(iva = True)),
                           #l.silo and l.silo.nombre or "", 
                           l.pedidoCompra 
                             and l.pedidoCompra.numpedido or "", 
                           l.pedidoCompra 
                             and utils.str_fecha(l.pedidoCompra.fecha) 
                             or "", 
                           l.id))
示例#9
0
文件: adapter.py 项目: pacoqueen/upy
def setter_textview(objeto, col, w):
    """
    Muestra el valor del atributo "col" del objeto
    "objeto" en el textview "w".
    """
    valor = getattr(objeto, col.name)
    if isinstance(col, sqlobject.col.SODateCol):
        valor = str_fecha(valor)
    elif isinstance(col, sqlobject.col.SODateTimeCol):
        valor = str_fechahoralarga(valor)
    elif isinstance(col, sqlobject.col.SOTimeCol):
        valor = str_hora(valor)
    elif isinstance(col, sqlobject.col.SOFloatCol):
        # XXX
        # HACK: Workaround. Los valores que son porcentaje (descuentos e IVA) 
        # se deben mostrar con el símbolo "%", pero la única manera de 
        # distinguir esas columnas es mirar el nombre.
        if col.name in NOMBRES_COLUMNAS_PORCENTAJE:
            valor = "%s %%" % float2str(valor * 100, 
                                        precision = 5, 
                                        autodec = True)
        # XXX
        else:
            valor = float2str(valor, autodec = False)
            # Si autodec=True y es número redondo > 1000 escribe 1.000 y el 
            # getter lo interpreta como flotante.
    if not isinstance(valor, str):
        valor = str(valor)
    buf = w.get_buffer()
    buf.set_text(valor)
示例#10
0
    def GET(self, id=None):
        #if id is None, email every active user with his balance
        if id is not None:
            users = [get_object_or_404(User, id=id)]
        else:
            users = User.filter(active=True)

        default_tpl = settings.MAIL_DEFAULT_TEMPLATE
        try:
            f = open(settings.MAIL_FILE_TEMPLATE, 'rb')
            tpl = pickle.load(f)
            f.close()
        except (IOError, pickle.PickleError):
            tpl = default_tpl

        userside = web.input(
            u=0).u != 0  # used to check if the mail is coming from a QR scan
        for u in users:
            utpl = default_tpl
            if u.balance < 0 and not userside:
                utpl = tpl

            body = utpl.format(
                apayer=float2str(-u.balance if u.balance < 0 else 0),
                solde=float2str(u.balance),
                prenom=u.firstname,
                nom=u.lastname)

            web.sendmail(settings.MAIL_ADDRESS, u.email,
                         'Your INGI cafetaria balance', body)

        if userside:
            return render_no_layout.consume('BALANCE', u)

        raise web.seeother('/')
示例#11
0
    def GET(self, id=None):
        #if id is None, email every active user with his balance
        if id is not None:
            users = [get_object_or_404(User, id=id)]
        else:
            users = User.filter(active=True)

        default_tpl = settings.MAIL_DEFAULT_TEMPLATE
        try:
            f = open(settings.MAIL_FILE_TEMPLATE, 'rb')
            tpl = pickle.load(f)
            f.close()
        except (IOError, pickle.PickleError):
            tpl = default_tpl

        userside = web.input(u=0).u != 0 # used to check if the mail is coming from a QR scan
        for u in users:
            utpl = default_tpl
            if u.balance < 0 and not userside:
                utpl = tpl
            
            body = utpl.format(apayer = float2str(-u.balance if u.balance <0 else 0), 
                               solde = float2str(u.balance), 
                               prenom = u.firstname, 
                               nom = u.lastname)

            web.sendmail(settings.MAIL_ADDRESS, u.email, 'Your INGI cafetaria balance', body)

        if userside:
            return render_no_layout.consume('BALANCE', u)

        raise web.seeother('/')
示例#12
0
 def imprimir(self, boton):
     """
     Imprime la tarifa en pantalla.
     """
     import informes
     datos = []
     model = self.wids['tabla_productos'].get_model()
     for iter in model: 
         datos.append((iter[0], 
                       iter[1], 
                       "%s €" % (utils.float2str(iter[2], 3)), 
                       "%s €" % (utils.float2str(iter[3], 3))
                     ))
     def cmp_func(x, y):
         """
         Para ordenar por nombre de producto.
         """
         if x[1] < y[1]:
             return -1
         if x[1] > y[1]:
             return 1
         return 0
     datos.sort(cmp_func)
     if datos != []:
         nombre_tarifa = self.wids['cb_nombre_tarifa'].child.get_text()
         informes.abrir_pdf(geninformes.imprimir_tarifa(datos, nombre_tarifa, utils.str_fecha(mx.DateTime.localtime())))
示例#13
0
文件: iva.py 项目: pacoqueen/upy
 def mostrar_totales(self, devengado, soportado, base_devengado):
     """
     Muestra los totales, la diferencia de ambos y colorea los Entries.
     """
     # Base imponible de las facturas de venta. (Si trabajara con más IVAs debería haber una línea por cada tipo de IVA)
     self.wids['e_base_devengado'].set_text("%s €" % (utils.float2str(base_devengado, 2)))
     # Devengado
     self.wids['e_devengado'].set_text("%s €" % utils.float2str(devengado, 2))
     self.wids['e_devengado'].set_tooltip_text(str(devengado))
     self.wids['e_devengado'].modify_text(gtk.STATE_NORMAL, 
         self.wids['e_devengado'].get_colormap().alloc_color("red"))
     # Soportado
     self.wids['e_soportado'].set_text(
         "%s €" % utils.float2str(soportado, 2))
     self.wids['e_soportado'].set_tooltip_text(str(soportado))
     self.wids['e_soportado'].modify_text(gtk.STATE_NORMAL, 
         self.wids['e_soportado'].get_colormap().alloc_color("blue"))
     # Diferencia
     diferencia = devengado - soportado
     self.wids['e_diferencia'].set_text(
         "%s €" % utils.float2str(diferencia, 2))
     self.wids['e_diferencia'].set_tooltip_text(str(diferencia))
     if diferencia > 0:
         self.wids['e_diferencia'].modify_text(gtk.STATE_NORMAL, 
             self.wids['e_diferencia'].get_colormap().alloc_color("red"))
     else:
         self.wids['e_diferencia'].modify_text(gtk.STATE_NORMAL, 
             self.wids['e_diferencia'].get_colormap().alloc_color("blue"))
示例#14
0
 def imprimir(self,boton):
     """
     Prepara la vista preliminar para la impresión del informe
     """
     import informes
     datos = []
     model = self.wids['tv_datos'].get_model()
     for i in model:
         datos.append((i[0],
                       i[1],
                       i[2]))
     if self.balas != 0:
         datos.append(("", "", ""))
         datos.append(("", "-" * 30 , "-" * 30))
         datos.append(("", "", ""))
         datos.append((" " * 50 + "TOTAL:", "%s m²" % (utils.float2str(self.kilos)), self.balas))
     if self.rollos != 0:
         datos.append(("", "", ""))
         datos.append(("", "-" * 30 , "-" * 30))
         datos.append(("", "", ""))
         datos.append((" " * 50 + "TOTAL:", "%s m²" % (utils.float2str(self.metros)), self.rollos))
     if (self.inicio) == None:            
         fechaInforme = 'Hasta '+utils.str_fecha(time.strptime(self.fin,"%Y/%m/%d"))
     else:
         fechaInforme = utils.str_fecha(time.strptime(self.inicio,"%Y/%m/%d"))+' - '+utils.str_fecha(time.strptime(self.fin,"%Y/%m/%d"))
     if datos != []:
         informes.abrir_pdf(geninformes.producido_produccion(datos, fechaInforme, self.grafico))
 def rellenar_tabla(self, items):
     """
     Rellena el model con los items de la consulta
     """
     vpro = VentanaProgreso(padre = self.wids['ventana'])
     vpro.mostrar()
     vpro.set_valor(0.0, "Contando existencias...")
     act = 0.0
     tot = len(items) * len(self.tvs)
     try:
         fecha = utils.parse_fecha(self.wids['e_fecha'].get_text())
     except (TypeError, ValueError, AttributeError):
         fecha = mx.DateTime.today()
         self.wids['e_fecha'].set_text(utils.str_fecha(fecha))
     # XXX: Optimización (cosas de cómo están hechas las funciones de get_*
     #      por dentro en pclases):
     if fecha >= mx.DateTime.today():
         fecha = None
     for tv, kg, bultos, a in self.tvs:
         model = tv.get_model()
         model.clear()
         totalkgs = 0.0
         totalbultos = 0
         for pv in items:
             vpro.set_valor(act/tot, 
                            "Contando existencias...\t[%s]" % pv.get_puid())
             stock = pv.get_stock(hasta = fecha, almacen = a)
             totalkgs += stock
             existencias = pv.get_existencias(hasta=fecha, almacen = a)
             totalbultos += existencias
             stock_A = pv.get_stock_A(hasta = fecha, almacen = a)
             existencias_A = pv.get_existencias_A(hasta=fecha, almacen = a)
             stock_B = pv.get_stock_B(hasta = fecha, almacen = a)
             existencias_B = pv.get_existencias_B(hasta=fecha, almacen = a)
             stock_C = pv.get_stock_C(hasta = fecha, almacen = a)
             existencias_C = pv.get_existencias_C(hasta=fecha, almacen = a)
             model.append((pv.codigo,
                           pv.descripcion,
                           utils.float2str(stock),
                           utils.float2str(existencias, autodec = True),
                           utils.float2str(stock_A!=None and stock_A or 0),
                           utils.float2str(existencias_A != None and 
                                           existencias_A or 0, 
                                           autodec = True),
                           utils.float2str(stock_B!=None and stock_B or 0),
                           utils.float2str(existencias_B != None and 
                                           existencias_B or 0, 
                                           autodec = True),
                           utils.float2str(stock_C!=None and stock_C or 0),
                           utils.float2str(existencias_C != None and 
                                           existencias_C or 0, 
                                           autodec = True),
                           pv.get_puid()))
             act += 1
         kg.set_text(utils.float2str(totalkgs))
         bultos.set_text(utils.float2str(totalbultos, autodec = True))
     vpro.ocultar()
示例#16
0
 def buscar(self, boton):
     """
     Busca todos los productos e introduce en los TreeViews las existencias 
     de los mismos. En total y por almacén.
     El total no lo calcula, se obtiene del total global (que debería 
     coincidir con el sumatorio de...).
     """
     fechaini = self.wids['e_fechaini'].get_text().strip()
     if fechaini:
         try:
             fechaini = utils.parse_fecha(fechaini)
         except (ValueError, TypeError):
             utils.dialogo_info(titulo = "ERROR EN FECHA INICIAL", 
              texto = "El texto «%s» no es una fecha correcta." % fechaini,
              padre = self.wids['ventana'])
             fechaini = None
     fechafin = self.wids['e_fechafin'].get_text().strip()
     if fechafin:
         try:
             fechafin = utils.parse_fecha(fechafin)
         except (ValueError, TypeError):
             utils.dialogo_info(titulo = "ERROR EN FECHA FINAL", 
              texto = "El texto «%s» no es una fecha correcta." % fechafin,
              padre = self.wids['ventana'])
             fechafin = None
     if fechafin:
         FV = pclases.FacturaVenta
         if fechaini:
             facturas = FV.select(pclases.AND(
                                     FV.q.fecha >= fechaini, 
                                     FV.q.fecha <= fechafin))
         else:
             facturas = FV.select(FV.q.fecha <= fechafin)
         from ventana_progreso import VentanaProgreso
         vpro = VentanaProgreso(padre = self.wids['ventana'])
         vpro.mostrar()
         txtvpro = "Buscando facturas..."
         total = 0.0
         i = 0.0
         vpro.set_valor(i, txtvpro)
         model = self.wids['tv_datos'].get_model()
         model.clear()
         for f in facturas:
             i += 1
             vpro.set_valor(i/facturas.count(), 
                            txtvpro)
             model.append((f.numfactura, 
                         utils.str_fecha(f.fecha), 
                         f.cliente and f.cliente.cif or "¡Sin cliente!", 
                         f.cliente and f.cliente.nombre or "¡Sin cliente!", 
                         utils.float2str(f.calcular_base_imponible()), 
                         utils.float2str(f.calcular_total_iva()), 
                         utils.float2str(f.calcular_importe_total()), 
                         f.get_puid()))
             total += f.calcular_importe_total()
         vpro.ocultar()
         self.wids['e_total'].set_text(utils.float2str(total))
 def rellenar_tabla(self, items):
 	"""
     Rellena el model con los items de la consulta
     """        
 	model = self.wids['tv_datos'].get_model()
 	model.clear()
     total = 0
     vencido = 0
     hoy = datetime.date.today()
     por_fecha = {}
 	for i in items:
         if not i[2]:  # i[2] = False cuando es vencimiento normal de la BD
             total += i[1].importe 
             importe = i[1].importe
             anno = i[1].fecha.year
             mes = i[1].fecha.month
             if i[1].fecha < hoy:
                 vencido += i[1].importe
             fra = i[1].facturaVenta or i[1].prefactura
             model.append((fra.numfactura,
                           utils.str_fecha(i[1].fecha),
                           utils.float2str(importe),
                           i[1].observaciones,
                           fra.cliente.nombre,
                           "V:" + `i[1].id`))
         else:   # i[2] = True. Es un vencimiento rescatado de LogicMovimientos.
             importe = i[1]['importe']
             anno = i[1]['fecha'].year
             mes = i[1]['fecha'].month
             total += i[1]['importe']
             if i[1]['fecha'] < hoy:
                 vencido += i[1]['importe']
             model.append(("LOGIC",      # Esto me va a valer para diferenciar un vto. de la BD de uno de Logic.
                           utils.str_fecha(i[1]['fecha']),
                           utils.float2str(i[1]['importe']),
                           i[1]['comentario'],
                           i[1]['cuenta'],
                           "L:" + i[1]['id']))
         if anno not in por_fecha:
             por_fecha[anno] = {}
         if mes not in por_fecha[anno]:
             por_fecha[anno][mes] = 0.0
         por_fecha[anno][mes] += importe
     self.wids['e_total'].set_text("%s €" % utils.float2str(total))
     self.wids['e_vencido'].set_text("%s €" % utils.float2str(vencido))
     # Relleno el model de totales.
     annos = por_fecha.keys()
     annos.sort()
     model = self.wids['tv_totales'].get_model()
     model.clear()
     for anno in annos:
         total_anno = sum([por_fecha[anno][mes] for mes in por_fecha[anno]])
         anno_padre = model.append(None, (`anno`, 
                                          utils.float2str(total_anno), 
                                          ""))
         meses = por_fecha[anno].keys()
示例#18
0
文件: skel.py 项目: pacoqueen/upy
 def rellenar_tabla_XXX(self):
     model = self.wids['XXXtv_treeview'].get_model()
     model.clear()
     total = 0.0
     for p in self.objeto.XXXunoamuchos:
         total += p.XXXcampoacumulable
         model.append((p.XXXcampo1, 
                       utils.float2str(p.XXXcampoacumulable), 
                       p.id))
     self.wids['XXXe_total_si_lo_hay'].set_text(utils.float2str(total))
示例#19
0
 def rellenar_totales(self, totf, tots, totb):
     """
     Introduce los totales en los "entries".
     """
     self.wids['e_total'].set_text(utils.float2str(totf))
     self.wids['e_siniva'].set_text(utils.float2str(tots))
     try:
         beneficio = totb * 100.0 / tots
     except ZeroDivisionError:
         beneficio = 0
     self.wids['e_beneficio'].set_text("%s (%s %%)" % (utils.float2str(totb), utils.float2str(beneficio, 4, autodec = True)))
示例#20
0
 def rellenar_facturas(self):
 	"""
     Rellena el model con las facturas no bloqueadas.
     """        
 	model = self.wids['tv_facturas'].get_model()
 	model.clear()
     self.wids['tv_facturas'].freeze_child_notify()
     self.wids['tv_facturas'].set_model(None)
     vpro = ventana_progreso.VentanaProgreso(padre = self.wids['ventana'])
     vpro.mostrar()
     i = 0.0
     facturas = pclases.FacturaVenta.select(pclases.FacturaVenta.q.bloqueada == False, orderBy = "id")
     prefacturas = pclases.Prefactura.select(pclases.Prefactura.q.bloqueada == False, orderBy = "id")
     tot = facturas.count() + prefacturas.count()
     for factura in facturas:
         vpro.set_valor(i/tot, 'Recuperando factura %s...' % (factura.numfactura))
         i += 1
         if factura.vencimientosCobro == []:
             motivo = "Sin vencimientos."
         elif factura.cliente.cif == None or factura.cliente.cif.strip() == "":
             motivo = "Cliente sin CIF."
         else:
             motivo = "Factura no bloqueada."
         model.append((factura.numfactura,
                       utils.str_fecha(factura.fecha),
                       factura.cliente and factura.cliente.nombre or "-",
                       "%s €" % (utils.float2str(factura.calcular_total())), 
                       ", ".join([a.numalbaran for a in factura.get_albaranes()]),
                       factura.bloqueada,
                       motivo,
                       factura.id))
     for factura in prefacturas:
         vpro.set_valor(i/tot, 'Recuperando factura %s...' % (factura.numfactura))
         i += 1
         if factura.vencimientosCobro == []:
             motivo = "Sin vencimientos."
         elif factura.cliente.cif == None or factura.cliente.cif.strip() == "":
             motivo = "Cliente sin CIF."
         else:
             motivo = "Factura no bloqueada."
         model.append((factura.numfactura,
                       utils.str_fecha(factura.fecha),
                       factura.cliente and factura.cliente.nombre or "-",
                       "%s €" % (utils.float2str(factura.calcular_total())), 
                       ", ".join([a.numalbaran for a in factura.get_albaranes()]),
                       factura.bloqueada,
                       motivo,
                       factura.id))
     self.wids['tv_facturas'].set_model(model)
     self.wids['tv_facturas'].thaw_child_notify()
     vpro.ocultar()
 def imprimir(self,boton):
     """
     Prepara la vista preliminar para la impresión del informe
     """
     import informes
     datos = []
     for i in self.resultado:
         if not i[2]:    # i[2] = False cuando es vencimiento normal de la BD
             if isinstance(i[1], pclases.FacturaDeAbono):
                 importe = i[1].calcular_importe_total()
                 datos.append((i[1].numfactura,
                               utils.str_fecha(i[1].fecha),
                               utils.float2str(importe),
                               "",
                               i[1].cliente and i[1].cliente.nombre or ""))
             else:
                 fra = i[1].facturaVenta or i[1].prefactura
                 datos.append((fra.numfactura,
                               utils.str_fecha(i[1].fecha),
                               utils.float2str(i[1].importe),
                               i[1].observaciones,
                               fra.cliente.nombre))
         else:   # i[2] = True. Es un vencimiento rescatado de LogicMovimientos.
             datos.append(("LOGIC",      # Esto me va a valer para diferenciar un vto. de la BD de uno de Logic.
                           utils.str_fecha(i[1]['fecha']),
                           utils.float2str(i[1]['importe']),
                           i[1]['comentario'],
                           i[1]['cuenta']))
     if (self.inicio) == None:            
         fechaInforme = 'Hasta %s' % (utils.str_fecha(self.fin))
     else:
         fechaInforme = utils.str_fecha(self.inicio)+' - '+utils.str_fecha(self.fin)
     if datos != []:
         model = self.wids['tv_totales'].get_model()
         datos.append(("---", )*5)
         datos.append(("TOTALES POR MES Y AÑO", ">->", ">->", ">->", ">->"))
         for fila in model:
             datos.append((fila[0], "", fila[1], "", ""))
             iter_filames = model.iter_children(fila.iter)
             while iter_filames:
                 filames = model[iter_filames]
                 datos.append(("", filames[0], filames[1], "", ""))
                 iter_filames = model.iter_next(iter_filames)
         datos.append(("---", )*5)
         datos.append(("", 
                       "Total", 
                       self.wids['e_total'].get_text(), 
                       "Vencido a la fecha", 
                       self.wids['e_vencido'].get_text()))
         informes.abrir_pdf(geninformes.vencimientosCobro(datos,fechaInforme))
示例#22
0
 def rellenar_tabla_transferencias(self):
     model = self.wids['tv_transferencias'].get_model()
     model.clear()
     total = 0.0
     for p in self.objeto.pagos:
         total += p.importe
         model.append((p.proveedor and p.proveedor.nombre, 
                       p.cuentaOrigen and p.cuentaOrigen.nombre, 
                       utils.float2str(p.importe), 
                       utils.str_fecha(p.fecha), 
                       p.observaciones, 
                       p.concepto, 
                       p.id))
     self.wids['e_total'].set_text(utils.float2str(total))
示例#23
0
 def rellenar_tabla(self,lista = []):
 	"""
     Rellena el model con los resultados de la búsqueda almacenados
     en una lista de lotes.
     """        
     model = self.wids['tv_resultado'].get_model()
 	model.clear()
 	for elem in lista:
 		model.append((elem.numlote,
                 elem.codigo,
                 "%s (%s)" % (str(elem.tenacidad), utils.float2str(elem.calcular_tenacidad_media())),
                 "%s (%s)" % (str(elem.elongacion), utils.float2str(elem.calcular_elongacion_media())),
                 "%s (%s)" % (elem.rizo, utils.float2str(elem.calcular_rizo_medio())),
                 "%s (%s)" % (elem.encogimiento, utils.float2str(elem.calcular_encogimiento_medio())),
                 elem.id))
示例#24
0
文件: iva.py 项目: pacoqueen/upy
 def rellenar_tabla(self, fras):
     """
     Introduce las facturas recibidas en el TreeView y 
     calcula el total de IVA para las facturas de compra 
     y de venta por separado.
     """
     tv = self.wids['tv_datos']
     model = tv.get_model()
     tv.freeze_child_notify()
     tv.set_model(None)
     model.clear()
     devengado = 0.0
     soportado = 0.0
     base_devengado = 0.0
     for fra in fras:
         if isinstance(fra, pclases.FacturaVenta):
             iva = fra.calcular_total_iva()
             base_devengado += fra.calcular_base_imponible()
             devengado += iva
             fila = [utils.str_fecha(fra.fecha), 
                     "%s (%s)" % (fra.numfactura, 
                                  fra.cliente and fra.cliente.nombre or ""),
                     "%s €" % utils.float2str(fra.calcular_importe_total()), 
                     "%s €" % utils.float2str(iva), 
                     "", 
                     "", 
                     "", 
                     "FV:%d" % fra.id
                     ]
         elif isinstance(fra, pclases.FacturaCompra):
             iva = fra.calcular_importe_iva()
             soportado += iva
             fila = [utils.str_fecha(fra.fecha), 
                     "", 
                     "",
                     "", 
                     "%s (%s)" % (fra.numfactura, fra.proveedor and fra.proveedor.nombre or ""), 
                     "%s €" % utils.float2str(fra.calcular_importe_total()), 
                     "%s €" % utils.float2str(iva), 
                     "FC:%d" % fra.id
                     ]
         else:
             self.logger.error("iva::rellenar_tabla -> Factura %s no es FacturaVenta ni FacturaCompra." % fra)
             continue
         model.append(fila)
     tv.set_model(model)
     tv.thaw_child_notify()
     self.mostrar_totales(devengado, soportado, base_devengado)
示例#25
0
 def es_diferente(self):
     """
     Devuelve True si algún valor en ventana difiere de 
     los del objeto.
     """
     if self.objeto == None:
         igual = True
     else:
         self.wids['sp_validez'].update()    # Por si ha tecleado en vez 
                         # de usar los botones de incremento y decremento.
         igual = self.objeto != None
         for colname in self.dic_campos:
             col = self.clase._SO_columnDict[colname]
             try:
                 valor_ventana = self.leer_valor(col, self.dic_campos[colname])
             except (ValueError, mx.DateTime.RangeError, TypeError):
                 if colname == "numpresupuesto":
                     valor_ventana = None
                 else:
                     igual = False
             valor_objeto = getattr(self.objeto, col.name)
             if colname == "comercialID" and valor_ventana == -1:
                     valor_ventana = None
             if isinstance(col, pclases.SODateCol):
                 valor_objeto = utils.abs_mxfecha(valor_objeto)
             igual = igual and (valor_ventana == valor_objeto)
             if not igual:
                 break
         igual = (igual 
                   and "%s %%" % utils.float2str(self.objeto.descuento*100, 
                                                 autodec = True) 
                     == self.wids['e_descuento'].get_text())
     return not igual
示例#26
0
 def rellenar_tabla(self, items):
 	"""
     Rellena el model con los items de la consulta (objetos LDC).
     """        
 	model = self.wids['tv_datos'].get_model()
 	model.clear()
     self.wids['tv_datos'].freeze_child_notify()
     self.wids['tv_datos'].set_model(None)
     vpro = ventana_progreso.VentanaProgreso(padre = self.wids['ventana'])
     vpro.mostrar()
     i = 0.0
     try:
         tot = len(items)
     except TypeError:   # len() of unsized object. Es un SelectResults
         tot = items.count()
     total = 0
     # Albarán tienen todas las LDC porque las LDC se han obtenido a partir de albaranes.
 	for ldc in items:
         i+=1
         vpro.set_valor(i/tot, 'Mostrando %d...' % (ldc.id))
         subtotal = ldc.cantidad * ldc.precio
         model.append((ldc.nombre_proveedor,
                       ldc.albaranEntrada.numalbaran,
                       utils.str_fecha(ldc.albaranEntrada.fecha),
                       ldc.descripcion_productoCompra,
                       ldc.cantidad,
                       ldc.precio,
                       subtotal,
                       ldc.id))
         total += subtotal
     self.wids['tv_datos'].set_model(model)
     self.wids['tv_datos'].thaw_child_notify()
     vpro.ocultar()
     self.wids['e_total'].set_text("%s €" % utils.float2str(total))
     self.wids['e_entradas'].set_text("%d" % tot)
    def imprimir(self, boton):
        """
        Prepara la vista preliminar para la impresión del informe
        """
        import informes
        datos = []
        for i in self.resultado:
            datos.append((i.cliente.nombre,
                          utils.str_fecha(i.fecha),
                          i.numpedido,
                          "%s €" % (utils.float2str(i.calcular_importe_total())),
                          i.bloqueado and "Sí" or "No",
                          i.cerrado and "Sí" or "No"))
        datos.append(("", "", "", "---", "", ""))
        datos.append(("%s pedidos listados." % (self.wids['e_total'].get_text()),
                      "",
                      "Importe total:",
                      self.wids['e_importe_total'].get_text(),
                      "",
                      ""))
        if (self.inicio) == None:
            fechaInforme = 'Hasta ' + utils.str_fecha(time.strptime(self.fin, "%Y/%m/%d"))
        else:
            fechaInforme = utils.str_fecha(time.strptime(self.inicio, "%Y/%m/%d")) + ' - ' + utils.str_fecha(time.strptime(self.fin, "%Y/%m/%d"))

        if datos != []:
            informes.abrir_pdf(geninformes.pedidosCliente(datos, self.cliente and self.cliente.nombre or "?", fechaInforme))
示例#28
0
    def cambiar_existencias(self, cell, path, texto):
        # Chequeo permiso de escritura para camibar precios, existencias y demás:
        try:
            ventana = pclases.Ventana.select(pclases.Ventana.q.fichero == "productos.py")[0]
            if self.usuario and (not self.usuario.get_permiso(ventana).escritura or self.usuario.nivel >= 2):
                utils.dialogo_info(titulo = "USUARIO SIN PRIVILEGIOS", 
                                   texto = "Necesita permiso de escritura para modificar las existencias.", 
                                   padre = self.wids['ventana'])
                return
        except IndexError:
            if self.usuario and self.usuario.nivel >= 2:
                utils.dialogo_info(titulo = "USUARIO SIN PRIVILEGIOS", 
                                   texto = "No tiene permisos suficientes para modificar las existencias.", 
                                   padre = self.wids['ventana'])
                return

        model = self.wids['tv_datos'].get_model()
        id = model[path][-1]
        try:
            existencias = utils._float(texto)
        except ValueError:
            utils.dialogo_info(titulo = "ERROR DE FORMATO", 
                               texto = "El texto %s no es correcto." % (texto), 
                               padre = self.wids['ventana'])
        else:
            if "PC" in model[path][0]:
                producto = pclases.ProductoCompra.get(id)
                producto.sync()
                producto.existencias = existencias
                producto.syncUpdate()
                model[path][3] = utils.float2str(producto.existencias)
示例#29
0
 def generator(self, alpha, link):
     alpha_string = float2str(alpha)
     link_file_name = link + ".link"
     with open(self.generator_tempelete,"r") as fin,\
         open(link_file_name,"w") as fout:
         for line in fin:
             fout.write(line.replace(self.sentinel,alpha_string))
示例#30
0
 def generator(self, alpha, link):
     alpha_string = float2str(alpha)
     link_file_name = link + ".link"
     with open(self.generator_tempelete,"r") as fin,\
         open(link_file_name,"w") as fout:
         for line in fin:
             fout.write(line.replace(self.sentinel, alpha_string))
示例#31
0
    def set_valor(self, w, nombrecampo, tipocampo):
#        valor = self.objeto._SO_getValue(nombrecampo)
        get_valor = getattr(self.objeto, '_SO_get_%s' % (nombrecampo))
        valor = get_valor()
        if isinstance(tipocampo, sqlobject.SOStringCol):  # Cadena: el widget es un entry
            if valor != None:
                w.set_text(valor)
            else:
                w.set_text("")
        elif isinstance(tipocampo, sqlobject.SOIntCol):   # Entero: el widget es un entry
            try:
                w.set_text("%d" % valor)
            except TypeError:
                w.set_text("0")
        elif isinstance(tipocampo, sqlobject.SOBoolCol):  # Boolean: el widget es un checkbox
            w.set_active(valor)
        elif isinstance(tipocampo, sqlobject.SOForeignKey):  # Entero-clave ajena: el widget es un comboboxentry
            utils.combo_set_from_db(w, valor)
        elif isinstance(tipocampo, sqlobject.SOCol):      # Clase base, casi seguro Float: el widget es un entry
            if valor != None:
                try:
                    w.set_text(utils.float2str(valor))
                except ValueError:
                    w.set_text('0')
        else:
            txt = "categorias_laborales.py: No se pudo establecer el valor %s para %s." % (valor, w)
            print txt
            self.logger.error(txt)
示例#32
0
 def refinar_resultados_busqueda(self, resultados):
     """
     Muestra en una ventana de resultados todos los
     registros de "resultados".
     Devuelve el id (primera columna de la ventana
     de resultados) de la fila seleccionada o None
     si se canceló.
     """
     filas_res = []
     for r in resultados:
         if r.es_transferencia():
             filas_res.append((r.id, 
                               utils.str_fecha(r.fecha), 
                               r.proveedor and r.proveedor.nombre or "-", 
                               r.cuentaOrigen and r.cuentaOrigen.nombre or "-", 
                               r.cuentaDestino and r.cuentaDestino.nombre or "-", 
                               utils.float2str(r.importe)))
     idcuenta = utils.dialogo_resultado(filas_res,
                                        titulo = 'SELECCIONE TRANSFERENCIA',
                                        cabeceras = ('ID', 'Fecha', 'Proveedor', 'Cuenta', 'Destino', "Importe"), 
                                        padre = self.wids['ventana'])
     if idcuenta < 0:
         return None
     else:
         return idcuenta
示例#33
0
 def _to_link(self):
     linkfile = self.link + '.link'
     with open(linkfile, 'r') as f:
         content = f.readlines()
     with open(linkfile, 'w') as f:
         f.write(
             self.link_header_format.format(float2str(self.alpha), self.mni,
                                            self.ekin, self.mass, self.zone,
                                            self.mpist))
         for i, line in enumerate(content):
             if not line.startswith('c #'):
                 break
             if line.startswith(self.header_end):
                 del content[0:i + 1]
                 break
         for line in content:
             f.write(line)
示例#34
0
def main(args):
    print('=' * 10, 'Starting', '=' * 10, '\n')
    print(device)

    # Set the seed for reproducing the results
    random.seed(args.manual_seed)
    np.random.seed(args.manual_seed)
    torch.manual_seed(args.manual_seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(args.manual_seed)
        cudnn.benchmark = True

    # Set up results folder
    if not os.path.exists(os.path.join(ROOT, RESULT, 'saved_val_images')):
        os.makedirs(os.path.join(ROOT, RESULT, 'saved_val_images'))
    if not os.path.exists(os.path.join(ROOT, RESULT, 'saved_train_images')):
        os.makedirs(os.path.join(ROOT, RESULT, 'saved_train_images'))

    # Setup Dataloader
    data_loader = get_loader(args.dataset)

    input_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])
    target_transform = extended_transforms.MaskToTensor()

    traindata = data_loader('train',
                            n_classes=args.n_classes,
                            transform=input_transform,
                            target_transform=target_transform,
                            do_transform=True,
                            portion=args.data_portion)
    trainloader = data.DataLoader(traindata,
                                  batch_size=args.batch_size,
                                  num_workers=1,
                                  shuffle=True)
    valdata = data_loader('val',
                          n_classes=args.n_classes,
                          transform=input_transform,
                          target_transform=target_transform)
    valloader = data.DataLoader(valdata,
                                batch_size=args.batch_size,
                                num_workers=1,
                                shuffle=False)

    n_classes = traindata.n_classes
    n_trainsamples = len(traindata)
    n_iters_per_epoch = np.ceil(n_trainsamples /
                                float(args.batch_size * args.iter_size))

    print('#Training data = {}'.format(n_trainsamples))

    # Setup Model
    model = get_model(name=args.arch,
                      n_classes=n_classes,
                      ignore_index=traindata.ignore_index,
                      output_stride=args.output_stride,
                      pretrained=args.pretrained,
                      momentum_bn=args.momentum_bn,
                      dprob=args.dprob).to(device)

    epochs_done = 0
    X = []
    Y = []
    Y_test = []
    avg_pixel_acc = 0
    mean_class_acc = 0
    mIoU = 0
    avg_pixel_acc_test = 0
    mean_class_acc_test = 0
    mIoU_test = 0
    best_mIoU = 0
    best_epoch = 0

    if args.model_path:
        model_name = args.model_path.split('.')
        checkpoint_name = model_name[0] + '_optimizer.pkl'
        checkpoint = torch.load(os.path.join(ROOT, RESULT, checkpoint_name))
        optm = checkpoint['optimizer']
        model.load_state_dict(checkpoint['state_dict'])
        split_str = model_name[0].split('_')
        epochs_done = int(split_str[-1])
        saved_loss = pickle.load(
            open(os.path.join(ROOT, RESULT, "saved_loss.p"), "rb"))
        saved_accuracy = pickle.load(
            open(os.path.join(ROOT, RESULT, "saved_accuracy.p"), "rb"))
        X = saved_loss["X"][:epochs_done]
        Y = saved_loss["Y"][:epochs_done]
        Y_test = saved_loss["Y_test"][:epochs_done]
        avg_pixel_acc = saved_accuracy["P"][:epochs_done, :]
        mean_class_acc = saved_accuracy["M"][:epochs_done, :]
        mIoU = saved_accuracy["I"][:epochs_done, :]
        avg_pixel_acc_test = saved_accuracy["P_test"][:epochs_done, :]
        mean_class_acc_test = saved_accuracy["M_test"][:epochs_done, :]
        mIoU_test = saved_accuracy["I_test"][:epochs_done, :]

    if args.best_model_path:
        best_model_name = args.best_model_path.split('_')
        best_mIoU = float(best_model_name[-2])
        best_epoch = int(best_model_name[-3])

    # Learning rates: For new layers (such as final layer), we set lr to be 10x the learning rate of layers already trained
    bias_10x_params = filter(
        lambda x: ('bias' in x[0]) and ('final' in x[0]) and ('conv' in x[0]),
        model.named_parameters())
    bias_10x_params = list(map(lambda x: x[1], bias_10x_params))

    bias_params = filter(lambda x: ('bias' in x[0]) and ('final' not in x[0]),
                         model.named_parameters())
    bias_params = list(map(lambda x: x[1], bias_params))

    nonbias_10x_params = filter(
        lambda x:
        (('bias' not in x[0]) or ('bn' in x[0])) and ('final' in x[0]),
        model.named_parameters())
    nonbias_10x_params = list(map(lambda x: x[1], nonbias_10x_params))

    nonbias_params = filter(
        lambda x: ('bias' not in x[0]) and ('final' not in x[0]),
        model.named_parameters())
    nonbias_params = list(map(lambda x: x[1], nonbias_params))

    optimizer = torch.optim.SGD([
        {
            'params': bias_params,
            'lr': args.lr
        },
        {
            'params': bias_10x_params,
            'lr': 20 * args.lr if args.pretrained else args.lr
        },
        {
            'params': nonbias_10x_params,
            'lr': 10 * args.lr if args.pretrained else args.lr
        },
        {
            'params': nonbias_params,
            'lr': args.lr
        },
    ],
                                lr=args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay,
                                nesterov=(args.optim == 'Nesterov'))
    num_param_groups = 4

    # optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)

    # Setting up scheduler
    if args.model_path and args.restore:
        # Here we restore all states of optimizer
        optimizer.load_state_dict(optm)
        total_iters = n_iters_per_epoch * args.epochs
        lambda1 = lambda step: 0.5 + 0.5 * math.cos(np.pi * step / total_iters)
        scheduler = lr_scheduler.LambdaLR(
            optimizer,
            lr_lambda=[lambda1] * num_param_groups,
            last_epoch=epochs_done * n_iters_per_epoch)
        # scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1, last_epoch=epochs_done)
    else:
        # scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1)
        # Here we simply restart the training
        # if args.T0:
        #     total_iters = args.T0 * n_iters_per_epoch
        # else:
        total_iters = ((args.epochs - epochs_done) * n_iters_per_epoch)
        lambda1 = lambda step: 0.5 + 0.5 * math.cos(np.pi * step / total_iters)
        scheduler = lr_scheduler.LambdaLR(optimizer,
                                          lr_lambda=[lambda1] *
                                          num_param_groups)

    global l_avg, totalclasswise_pixel_acc, totalclasswise_gtpixels, totalclasswise_predpixels
    global l_avg_test, totalclasswise_pixel_acc_test, totalclasswise_gtpixels_test, totalclasswise_predpixels_test
    global steps, steps_test

    scheduler.step()

    criterion = nn.CrossEntropyLoss(size_average=False,
                                    ignore_index=traindata.ignore_index)

    for epoch in range(epochs_done, args.epochs):
        print('=' * 10, 'Epoch %d' % (epoch + 1), '=' * 10)
        l_avg = 0
        totalclasswise_pixel_acc = 0
        totalclasswise_gtpixels = 0
        totalclasswise_predpixels = 0
        l_avg_test = 0
        totalclasswise_pixel_acc_test = 0
        totalclasswise_gtpixels_test = 0
        totalclasswise_predpixels_test = 0
        steps = 0
        steps_test = 0

        # scheduler.step()
        train(model, optimizer, criterion, trainloader, epoch, scheduler,
              traindata)
        val(model, criterion, valloader, epoch, valdata)

        # save the model every 5 epochs
        if (epoch + 1) % 5 == 0 or epoch == args.epochs - 1:
            if (epoch + 1) > 5:
                os.remove(
                    os.path.join(
                        ROOT, RESULT,
                        "{}_{}_{}.pkl".format(args.arch, args.dataset,
                                              epoch - 4)))
                os.remove(
                    os.path.join(
                        ROOT, RESULT, "{}_{}_{}_optimizer.pkl".format(
                            args.arch, args.dataset, epoch - 4)))
            torch.save(
                model,
                os.path.join(
                    ROOT, RESULT,
                    "{}_{}_{}.pkl".format(args.arch, args.dataset, epoch + 1)))
            torch.save(
                {
                    'state_dict': model.state_dict(),
                    'optimizer': optimizer.state_dict()
                },
                os.path.join(
                    ROOT, RESULT,
                    "{}_{}_{}_optimizer.pkl".format(args.arch, args.dataset,
                                                    epoch + 1)))

        # remove old loss & accuracy files
        if os.path.isfile(os.path.join(ROOT, RESULT, "saved_loss.p")):
            os.remove(os.path.join(ROOT, RESULT, "saved_loss.p"))
        if os.path.isfile(os.path.join(ROOT, RESULT, "saved_accuracy.p")):
            os.remove(os.path.join(ROOT, RESULT, "saved_accuracy.p"))

        # save train and validation loss
        X.append(epoch + 1)
        Y.append(l_avg / steps)
        Y_test.append(l_avg_test / steps_test)
        saved_loss = {"X": X, "Y": Y, "Y_test": Y_test}
        pickle.dump(saved_loss,
                    open(os.path.join(ROOT, RESULT, "saved_loss.p"), "wb"))

        # pixel accuracy
        totalclasswise_pixel_acc = totalclasswise_pixel_acc.reshape(
            (-1, n_classes)).astype(np.float32)
        totalclasswise_gtpixels = totalclasswise_gtpixels.reshape(
            (-1, n_classes))
        totalclasswise_predpixels = totalclasswise_predpixels.reshape(
            (-1, n_classes))
        totalclasswise_pixel_acc_test = totalclasswise_pixel_acc_test.reshape(
            (-1, n_classes)).astype(np.float32)
        totalclasswise_gtpixels_test = totalclasswise_gtpixels_test.reshape(
            (-1, n_classes))
        totalclasswise_predpixels_test = totalclasswise_predpixels_test.reshape(
            (-1, n_classes))

        if isinstance(avg_pixel_acc, np.ndarray):
            avg_pixel_acc = np.vstack(
                (avg_pixel_acc, np.sum(totalclasswise_pixel_acc, axis=1) /
                 np.sum(totalclasswise_gtpixels, axis=1)))
            mean_class_acc = np.vstack(
                (mean_class_acc,
                 np.mean(totalclasswise_pixel_acc / totalclasswise_gtpixels,
                         axis=1)))
            mIoU = np.vstack(
                (mIoU,
                 np.mean(totalclasswise_pixel_acc /
                         (totalclasswise_gtpixels + totalclasswise_predpixels -
                          totalclasswise_pixel_acc),
                         axis=1)))

            avg_pixel_acc_test = np.vstack(
                (avg_pixel_acc_test,
                 np.sum(totalclasswise_pixel_acc_test, axis=1) /
                 np.sum(totalclasswise_gtpixels_test, axis=1)))
            mean_class_acc_test = np.vstack(
                (mean_class_acc_test,
                 np.mean(totalclasswise_pixel_acc_test /
                         totalclasswise_gtpixels_test,
                         axis=1)))
            mIoU_test = np.vstack((mIoU_test,
                                   np.mean(totalclasswise_pixel_acc_test /
                                           (totalclasswise_gtpixels_test +
                                            totalclasswise_predpixels_test -
                                            totalclasswise_pixel_acc_test),
                                           axis=1)))
        else:
            avg_pixel_acc = np.sum(totalclasswise_pixel_acc, axis=1) / np.sum(
                totalclasswise_gtpixels, axis=1)
            mean_class_acc = np.mean(totalclasswise_pixel_acc /
                                     totalclasswise_gtpixels,
                                     axis=1)
            mIoU = np.mean(
                totalclasswise_pixel_acc /
                (totalclasswise_gtpixels + totalclasswise_predpixels -
                 totalclasswise_pixel_acc),
                axis=1)

            avg_pixel_acc_test = np.sum(
                totalclasswise_pixel_acc_test, axis=1) / np.sum(
                    totalclasswise_gtpixels_test, axis=1)
            mean_class_acc_test = np.mean(totalclasswise_pixel_acc_test /
                                          totalclasswise_gtpixels_test,
                                          axis=1)
            mIoU_test = np.mean(
                totalclasswise_pixel_acc_test /
                (totalclasswise_gtpixels_test + totalclasswise_predpixels_test
                 - totalclasswise_pixel_acc_test),
                axis=1)

        saved_accuracy = {
            "X": X,
            "P": avg_pixel_acc,
            "M": mean_class_acc,
            "I": mIoU,
            "P_test": avg_pixel_acc_test,
            "M_test": mean_class_acc_test,
            "I_test": mIoU_test
        }
        pickle.dump(saved_accuracy,
                    open(os.path.join(ROOT, RESULT, "saved_accuracy.p"), "wb"))

        # save the best model
        this_mIoU = np.mean(
            totalclasswise_pixel_acc_test /
            (totalclasswise_gtpixels_test + totalclasswise_predpixels_test -
             totalclasswise_pixel_acc_test),
            axis=1)[0]
        if this_mIoU > best_mIoU:
            if best_mIoU > 0:
                os.remove(
                    os.path.join(
                        ROOT, RESULT,
                        "{}_{}_{}_{}_best.pkl".format(args.arch, args.dataset,
                                                      best_epoch,
                                                      float2str(best_mIoU))))
                os.remove(
                    os.path.join(
                        ROOT, RESULT, "{}_{}_{}_{}_optimizer_best.pkl".format(
                            args.arch, args.dataset, best_epoch,
                            float2str(best_mIoU))))
            best_mIoU = this_mIoU
            best_epoch = epoch + 1
            torch.save(
                model,
                os.path.join(
                    ROOT, RESULT,
                    "{}_{}_{}_{}_best.pkl".format(args.arch, args.dataset,
                                                  best_epoch,
                                                  float2str(best_mIoU))))
            torch.save(
                {
                    'state_dict': model.state_dict(),
                    'optimizer': optimizer.state_dict()
                },
                os.path.join(
                    ROOT, RESULT, "{}_{}_{}_{}_optimizer_best.pkl".format(
                        args.arch, args.dataset, best_epoch,
                        float2str(best_mIoU))))

        train_mIoU = np.mean(
            totalclasswise_pixel_acc /
            (totalclasswise_gtpixels + totalclasswise_predpixels -
             totalclasswise_pixel_acc),
            axis=1)[0]
        print('Train mIoU = {}, Val mIoU = {}'.format(train_mIoU, this_mIoU))
示例#35
0
    def __init__(self, config_file='explosion.cfg'):
        """
        Initialize explosion from config file explosion.cfg.

        Actual values need to be in the [explosion] section, the
        [DEFAULT] section is a backup.  It is also hard-coded, so you
        don't need to overwrite it unless it is being changed.  The
        current defaults are in this class in attribute
        'default_config'.

        [DEFAULT]
        program = ../k
        ext = #presn
        dump = ../%(base)s%(ext)s
        template = explosion.link
        logfile = explosion.log
        cmdfile = explosion.cmd
        logall = True
        verbose = True
        alpha = 1.0
        precision = 2
        force = False
        run = True

        [Here is what you *have* to add:]
        link = <link sentinal like "Da">
        ekin_or_mni = <value>
        base = <run name>

        [example]
        link = Da
        alpha = 1.0
        ekin = 1.2e+51
        base = s25

        [explosion]
        link = Pa
        alpha = 1.0
        ekin = 1.2e+51
        base = u25

        ======

        So, with the defaults, the files that you need in the
        explosion directory are just

        explosion.link
        explosion.cmd
        explosion.cfg

        """

        start_time = datetime.datetime.now()

        config = Config(self.default_config)
        #        config.readfp(io.BytesIO(self.default_config))
        config.read(config_file)

        section = 'explosion'
        run = config.getboolean(section, 'run')
        force = config.getboolean(section, 'force')
        kepler = config.get(section, 'program')
        presn_dump_name = config.get(section, 'dump')
        self.base_name = config.get(section, 'base')
        self.generator_tempelete = config.get(section, 'template')
        generator_start = config.get(section, 'link')

        logfile = config.get(section, 'logfile')
        self.exp_cmd_file = config.get(section, 'cmdfile')
        verbose = config.getboolean(section, 'verbose')
        logall = config.getboolean(section, 'logall')

        # set up log output
        # maybe this this be replaced by
        # deriving class from Logged and
        # self.setup_logger(silent = not verbose, logfile=logfile, format='UTC')
        # and at the end: self.close_logger()
        self.logger = logging.getLogger(self.__class__.__name__)
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(logfile, 'w')
        if verbose:
            level = logging.DEBUG
        else:
            level = logging.WARNING
        fh.setLevel(level)
        formatter = utils.UTCFormatter(
            '%(asctime)s%(msecs)03d %(nameb)-12s %(levelname)s: %(message)s',
            datefmt='%Y%m%d%H%M%S')
        fh.setFormatter(formatter)
        root_logger = logging.getLogger('')
        if logall and len(root_logger.handlers) == 0:
            root_logger.addHandler(fh)
            root_logger.setLevel(level)
        else:
            self.logger.addHandler(fh)

        # set up state for explosion
        state = State(config=config)

        link = Link(generator_start)

        self.logger.info("{:s}: first alpha = {:g}".format(link, state.alpha))

        while state.best is None:
            if run:
                finished = True
                dump_file_name = self.base_name + link + "#final"
                if not os.path.exists(dump_file_name):
                    finished = False
                dump_file_name = self.base_name + link + "#envel"
                if not os.path.exists(dump_file_name):
                    finished = False
                # check if run parameters are identical
                if finished and not force:
                    if not state.eq_alpha(self.existing_alpha(link)):
                        self.logger.warning(
                            'Previous run ' + link +
                            ' had different alpha.  RERUNNING.')
                        finished = False
                        force = True
                        os.remove(self.base_name + link + "#final")
                        os.remove(self.base_name + link + "#envel")
                        os.remove(self.base_name + link + "z")
                        os.remove(link + ".link")
                if (not finished) or force:
                    # call_string = "{} {}{} ".format(kepler, self.base_name, link)

                    # # look if a restart (z) dump is present
                    # dump_file_name = self.base_name + link + "z"
                    # if (not os.path.exists(dump_file_name)) or force:
                    #     self.logger.info("RUN")
                    #     self.generator(state.alpha, link)
                    #     self.make_cmd(link);
                    #     call_string += presn_dump_name
                    # else:
                    #     self.logger.info("CONTINUE")
                    #     call_string += "z"
                    # call_string += " k </dev/null >/dev/null"
                    # self.logger.info("CALL: {}".format(call_string))
                    # os.system(call_string)

                    args = [kepler, self.base_name + link]

                    # look if a restart (z) dump is present
                    dump_file_name = self.base_name + link + "z"
                    if (not os.path.exists(dump_file_name)) or force:
                        self.logger.info("RUN")
                        self.generator(state.alpha, link)
                        self.make_cmd(link)
                        args += [presn_dump_name]
                    else:
                        self.logger.info("CONTINUE")
                        args += ['z']
                    args += ['k']
                    self.logger.info("CALL: {}".format(' '.join(args)))
                    with open(os.devnull, 'r') as null_in:
                        with open(os.devnull, 'w') as null_out:
                            subprocess.call(args,
                                            shell=False,
                                            stdin=null_in,
                                            stdout=null_out,
                                            stderr=subprocess.STDOUT)
                else:
                    self.logger.info("FINISHED")

            state.update(link)

            if state.best is None:
                link += 1
                self.logger.info("{}: new alpha = {} ({},{})".format(
                    link, state.alpha, state.lo_val(), state.hi_val()))

        end_time = datetime.datetime.now()
        load_time = end_time - start_time
        self.logger.info('finished in ' +
                         time2human(load_time.total_seconds()))

        self.logger.critical(
            self.out_format.format(state.flag, state.goal,
                                   state.val(state.best),
                                   abs(state.goal - state.val(state.best)),
                                   float2str(state.best.alpha),
                                   state.best.link, state.best.mass,
                                   state.best.zone))

        state.save('explosion.res')

        # clean up
        for filename in glob.iglob("xxx*"):
            os.remove(filename)