Exemple #1
0
    def _readRow(self, hfen, rfather, xmove):
        sql = "SELECT ROWID, W, B, D, O, RFATHER, XMOVE FROM STATS WHERE HASHFEN = ?"
        cursor = self._conexion.cursor()
        cursor.execute(sql, (hfen, ))
        liRows = cursor.fetchall()
        if liRows:
            for row in liRows:
                RFATHER = row[5]
                if rfather == RFATHER:
                    alm = Util.Almacen()
                    alm.ROWID = row[0]
                    alm.W = row[1]
                    alm.B = row[2]
                    alm.D = row[3]
                    alm.O = row[4]
                    alm.RFATHER = RFATHER
                    alm.XMOVE = row[6]
                    return alm

        alm = Util.Almacen()
        alm.ROWID = None
        alm.W = 0
        alm.B = 0
        alm.D = 0
        alm.O = 0
        alm.RFATHER = rfather
        alm.XMOVE = xmove
        return alm
Exemple #2
0
    def _readRowExt(self, rfather, hashFen, fen):
        sql = "SELECT ROWID, W, B, D, O, RFATHER, XMOVE FROM STATS WHERE HASHFEN = ?"
        cursor = self._conexion.cursor()
        cursor.execute(sql, (hashFen, ))
        liRows = cursor.fetchall()
        basefenM2 = fen2fenM2(fen)

        def history(xmove, rfather):
            li = [
                xmove,
            ]
            sql = "SELECT RFATHER, XMOVE FROM STATS WHERE ROWID = ?"
            while rfather != self.riniFen:
                cursor.execute(sql, (rfather, ))
                resp = cursor.fetchone()
                if resp is None:
                    break
                rfather, xmove = resp
                li.insert(0, xmove)
            li = [num2move(x) for x in li]
            pv = " ".join(li)
            setFen(self.iniFen)
            makePV(pv)
            fenM2 = fen2fenM2(getFen())
            return pv, fenM2

        liAlms = []
        alm_base = None
        tW = tB = tD = tO = 0
        if liRows:
            li = []
            for row in liRows:
                alm = Util.Almacen()
                alm.ROWID, alm.W, alm.B, alm.D, alm.O, alm.RFATHER, alm.XMOVE = row
                alm.PV, alm.FENM2 = history(alm.XMOVE, alm.RFATHER)
                if alm.RFATHER == rfather:
                    alm_base = alm
                li.append(alm)
            for alm in li:
                if alm.FENM2 == basefenM2:
                    liAlms.append(alm)
                    tW += alm.W
                    tB += alm.B
                    tD += alm.D
                    tO += alm.O
        alm = Util.Almacen()
        alm.W = tW
        alm.B = tB
        alm.D = tD
        alm.O = tO
        alm.BASE = alm_base
        alm.LIALMS = liAlms
        cursor.close()
        return alm
Exemple #3
0
 def read_work(self, work):
     tm = '%d"' % work.seconds if work.seconds else ''
     dp = "%d^" % work.depth if work.depth else ''
     r = Util.Almacen()
     r.title = "%s %s%s" % (work.ref, tm, dp)
     r.labels = []
     for ng in range(len(self.sts.groups)):
         rl = Util.Almacen()
         rl.points = self.sts.xdonePoints(work, ng)
         rl.label = self.sts.donePoints(work, ng)
         rl.is_max = False
         r.labels.append(rl)
     return r
Exemple #4
0
def leeDicParametros(configuracion):
    fichero = configuracion.ficheroAnalisis
    dic = Util.recuperaVar(fichero)
    if not dic:
        dic = {}
    alm = Util.Almacen()
    alm.motor = dic.get("MOTOR", configuracion.tutor.clave)
    alm.tiempo = dic.get("TIEMPO", configuracion.tiempoTutor)
    alm.depth = dic.get("DEPTH", 0)
    alm.timedepth = dic.get("TIMEDEPTH", False)
    alm.kblunders = dic.get("KBLUNDERS", 50)
    alm.ptbrilliancies = dic.get("PTBRILLIANCIES", 100)
    alm.dpbrilliancies = dic.get("DPBRILLIANCIES", 7)
    alm.desdeelfinal = dic.get("DESDEELFINAL", False)
    alm.multiPV = dic.get("MULTIPV", "PD")
    alm.priority = dic.get("PRIORITY", EngineThread.PRIORITY_NORMAL)

    alm.libro = dic.get("LIBRO", None)

    alm.masvariantes = dic.get("MASVARIANTES", True)
    alm.limitemasvariantes = dic.get("LIMITEMASVARIANTES", 0)
    alm.mejorvariante = dic.get("MEJORVARIANTE", False)
    alm.infovariante = dic.get("INFOVARIANTE", True)
    alm.unmovevariante = dic.get("UNMOVEVARIANTE", False)
    alm.siBorrarPrevio = dic.get("SIBORRARPREVIO", True)
    alm.siPDT = dic.get("SIPDT", False)

    alm.showGraphs = dic.get("SHOWGRAPHS", True)

    alm.stability = dic.get("STABILITY", False)
    alm.st_centipawns = dic.get("ST_CENTIPAWNS", 5)
    alm.st_depths = dic.get("ST_DEPTHS", 3)
    alm.st_timelimit = dic.get("ST_TIMELIMIT", 5)

    return alm
    def calculaSolucion(self):
        fenMB = self.cp.fen()
        fenOB = fenMB.replace(" w ", " b ") if "w" in fenMB else fenMB.replace(
            " b ", " w ")
        stAttacKing = set()
        stAttacKed = set()
        for fen in (fenMB, fenOB):
            LCEngine.setFen(fen)
            liMV = LCEngine.getExMoves()
            for mv in liMV:
                if mv.captura():
                    stAttacKing.add(mv.desde())
                    stAttacKed.add(mv.hasta())

        liSolucion = []
        for posicion, pieza in self.cp.casillas.iteritems():
            if pieza:
                reg = Util.Almacen()
                reg.pieza = pieza
                reg.posicion = posicion

                lt = posicion[0]
                nm = int(posicion[1])
                iswhite = nm % 2 == 0
                if lt in "bdfh":
                    iswhite = not iswhite
                reg.color = iswhite

                reg.atacante = posicion in stAttacKing
                reg.atacada = posicion in stAttacKed
                reg.comprobada = False
                liSolucion.append(reg)
        return liSolucion
    def nuevo(self):
        wav = None
        nombre = ""
        while True:
            w = WEdicionSonido(self,
                               _("New"),
                               wav=wav,
                               maxTime=600000,
                               nombre=nombre)
            resp = w.exec_()
            if resp:
                centesimas = w.centesimas
                if not centesimas:
                    return
                nombre = w.nombre().strip()
                if not nombre:
                    QTUtil2.mensError(self, _("Name missing"))
                    continue

                reg = Util.Almacen()
                reg.nombre = nombre
                reg.centesimas = centesimas
                reg.id = Util.nuevoID()
                reg.wav = w.wav
                reg.ordenVista = (self.liSonidos[-1].ordenVista +
                                  1) if self.liSonidos else 1
                self.db[reg.id] = reg
                self.liSonidos.append(reg)
                self.grid.refresh()
                return
Exemple #7
0
    def almListaJugadas(self, fen):
        li = self.book.lista(self.path, fen)
        posicion = ControlPosicion.ControlPosicion()
        posicion.leeFen(fen)

        total = 0
        maxim = 0
        for entry in li:
            w = entry.weight
            total += w
            if w > maxim:
                maxim = w

        listaJugadas = []
        for entry in li:
            alm = Util.Almacen()
            pv = entry.pv()
            w = entry.weight
            alm.desde, alm.hasta, alm.coronacion = pv[:2], pv[2:4], pv[4:]
            alm.pgn = posicion.pgnSP(alm.desde, alm.hasta, alm.coronacion)
            alm.fen = fen
            alm.porc = "%0.02f%%" % (w * 100.0 / total, ) if total else ""
            alm.weight = w
            listaJugadas.append(alm)

        return listaJugadas
    def calculaSolucion(self):
        mi = MotorInterno.MotorInterno()
        mi.ponFen(self.cp.fen())
        mi.calculaEstado()
        stAttacKing = set()
        stAttacKed = set()
        for bando in (True, False):
            for mv in mi.listaCapturas(bando):
                stAttacKing.add(mv.a1())
                stAttacKed.add(mv.h8())

        liSolucion = []
        for posicion, pieza in self.cp.casillas.iteritems():
            if pieza:
                reg = Util.Almacen()
                reg.pieza = pieza
                reg.posicion = posicion

                lt = posicion[0]
                nm = int(posicion[1])
                iswhite = nm % 2 == 0
                if lt in "bdfh":
                    iswhite = not iswhite
                reg.color = iswhite

                reg.atacante = posicion in stAttacKing
                reg.atacada = posicion in stAttacKed
                reg.comprobada = False
                liSolucion.append(reg)
        return liSolucion
 def aceptar(self):
     self.selected = alm = Util.Almacen()
     alm.tourney = self.cbtourney.valor()
     alm.tolerance_min = self.sbtolerance_min.valor()
     alm.tolerance_max = self.sbtolerance_max.valor()
     alm.tries_min = self.sbtries_min.valor()
     alm.tries_max = self.sbtries_max.valor()
     alm.color = self.cbcolor.valor()
     self.accept()
Exemple #10
0
 def guarda(self):
     reg = Util.Almacen()
     for atr in dir(self):
         if atr.startswith("_") and not atr.startswith("__"):
             if atr == "_itemSC":
                 reg._bloqueDatos = self._itemSC.bloqueDatos
             else:
                 valor = getattr(self, atr)
                 setattr(reg, atr, valor)
     return reg
Exemple #11
0
 def guarda(self):
     reg = Util.Almacen()
     for atr in dir(self):
         if atr.startswith("_") and not atr.startswith("__"):
             if atr == "_jg":
                 reg._jg = self._jg.guardaEnTexto()
             else:
                 valor = getattr(self, atr)
                 setattr(reg, atr, valor)
     return reg
Exemple #12
0
    def importarPolyglot(self, ventana, partida, bookW, bookB, titulo, depth, siWhite, onlyone, minMoves):
        bp = QTUtil2.BarraProgreso1(ventana, titulo, formato1="%m")
        bp.ponTotal(0)
        bp.ponRotulo(_X(_("Reading %1"), "..."))
        bp.mostrar()

        cp = partida.ultPosicion

        setFen = LCEngine.setFen
        makeMove = LCEngine.makeMove
        getFen = LCEngine.getFen

        def hazFEN(fen, lipv_ant, control):
            if bp.siCancelado():
                return
            siWhite1 = " w " in fen
            book = bookW if siWhite1 else bookB
            liPV = book.miraListaPV(fen, siWhite1 == siWhite, onlyone=onlyone)
            if liPV and len(lipv_ant) < depth:
                for pv in liPV:
                    setFen(fen)
                    makeMove(pv)
                    fenN = getFen()
                    lipv_nue = lipv_ant[:]
                    lipv_nue.append(pv)
                    hazFEN(fenN, lipv_nue, control)
            else:
                p = Partida.Partida()
                p.leerLIPV(lipv_ant)
                control.liPartidas.append(p)
                control.num_partidas += 1
                bp.ponTotal(control.num_partidas)
                bp.pon(control.num_partidas)
                if control.num_partidas and control.num_partidas % 1000 == 0:
                    self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history)
                    control.liPartidas = []
                    control.with_history = False

        control = Util.Almacen()
        control.liPartidas = []
        control.num_partidas = 0
        control.with_history = True
        control.rotulo = "%s,%s,%s" % (_("Polyglot book"), bookW.nombre, bookB.nombre)

        hazFEN(cp.fen(), partida.lipv(), control)

        bp.ponRotulo(_("Writing..."))

        if control.liPartidas:
            self.guardaPartidas(control.rotulo, control.liPartidas, minMoves, with_history=control.with_history)
        bp.cerrar()

        return True
    def hazListaRM(self):
        li = []
        posOP = 0
        nombrePlayer = _("You")
        posReal = 0
        ultPts = -99999999
        for pos, rm in enumerate(self.mrm.liMultiPV):
            pv1 = rm.pv.split(" ")[0]
            desde = pv1[:2]
            hasta = pv1[2:4]
            coronacion = pv1[4] if len(pv1) == 5 else None

            pgn = self.posicion.pgnSP(desde, hasta, coronacion)
            a = Util.Almacen()
            a.rm = rm
            a.texto = "%s (%s)" % (pgn, rm.abrTextoBase())
            p = a.puntosABS = rm.puntosABS()
            if p != ultPts:
                ultPts = p
                posReal += 1

            txt = ""
            siOP = rm.pv == self.rmOP.pv
            siUsu = rm.pv == self.rmUsu.pv
            if siOP and siUsu:
                txt = _("Both")
                posOP = pos
            elif siOP:
                txt = self.nombreOP
                posOP = pos
            elif siUsu:
                txt = nombrePlayer
            else:
                txt = ""
            a.player = txt

            a.siElegido = siOP or siUsu
            if a.siElegido or not self.siCompetitivo:
                if siOP:
                    posOP = len(li)
                a.posReal = posReal
                li.append(a)

        return li, posOP
Exemple #14
0
    def yieldData(self, liFields, filtro):
        select = ",".join(liFields)
        sql = "SELECT %s FROM %s"%(select, self.tabla)
        if self.filter:
            sql += " WHERE %s"%self.filter
            if filtro:
                sql += " AND %s" % filtro
        else:
            if filtro:
                sql += " WHERE %s"% filtro

        self._cursor.execute(sql)
        while True:
            raw = self._cursor.fetchone()
            if raw:
                alm = Util.Almacen()
                for campo in liFields:
                    setattr(alm, campo, raw[campo])
                yield alm
            else:
                return
Exemple #15
0
    def new(self, reg_base):
        def distribution(num):
            lipesos = []
            t = 1
            for x in range(12):
                t += x + 3 // (x + 1)
                lipesos.append(t)

            pt = num
            li_resp = []
            for n, peso in enumerate(lipesos[:-1]):
                elem = int(peso * pt * 100.0 / sum(lipesos[n:]))
                v = elem // 100
                if elem % 100:
                    v += 1

                li_resp.append(v)
                pt -= v
            li_resp.append(pt)
            return li_resp[::-1]

        games = reg_base.tourney["GAMES"]
        reg = Util.Almacen()
        reg.DATE_INIT = Util.dtosext(Util.hoy())
        reg.DATE_END = ""
        reg.NAME = reg_base.tourney["TOURNEY"]
        reg.TIMES = str([
            [0, 0],
        ] * 12)
        reg.NUM_GAMES = ngames = len(games)
        reg.NEXT_GAME = 0
        reg.TRIES_USED = 0
        reg.DISTRIBUTION = str(distribution(ngames))
        reg.TOLERANCE = "%d,%d" % (reg_base.tolerance_min,
                                   reg_base.tolerance_max)
        reg.TRIES = "%d,%d" % (reg_base.tries_min, reg_base.tries_max)
        reg.COLOR = reg_base.color
        reg.GAMES = Util.var2blob(games)

        self.dbf.insertarReg(reg, True)
Exemple #16
0
    def gmCrear(self):
        if self.torneo.numEngines() < 2:
            QTUtil2.mensError(self, _("You must create at least two engines"))
            return

        dicValores = self.configuracion.leeVariables("crear_torneo")

        get = dicValores.get

        liGen = [(None, None)]

        config = FormLayout.Spinbox(_("Rounds"), 1, 999, 50)
        liGen.append((config, get("ROUNDS", 1)))

        liGen.append((None, None))

        config = FormLayout.Spinbox(_("Total minutes"), 1, 999, 50)
        liGen.append((config, get("MINUTES", 10)))

        config = FormLayout.Spinbox(_("Seconds added per move"), 0, 999, 50)
        liGen.append((config, get("SECONDS", 0)))

        liGen.append((None, _("Engines")))

        liEngines = self.torneo.liEngines()
        for pos, en in enumerate(liEngines):
            liGen.append((en.alias, get(en.huella(), True)))

        liGen.append((None, None))
        liGen.append((_("Select all"), False))

        reg = Util.Almacen()
        reg.form = None

        def dispatch(valor):
            if reg.form is None:
                reg.form = valor
                reg.liEngines = []
                leng = len(liEngines)
                for x in range(leng):
                    reg.liEngines.append(valor.getWidget(x + 3))
                reg.selectall = valor.getWidget(leng + 3)
                reg.valorall = False

            else:
                QTUtil.refreshGUI()
                select = reg.selectall.isChecked()
                if select != reg.valorall:
                    for uno in reg.liEngines:
                        uno.setChecked(select)
                    reg.valorall = select
                QTUtil.refreshGUI()

        resultado = FormLayout.fedit(liGen,
                                     title=_("Games"),
                                     parent=self,
                                     icon=Iconos.Torneos(),
                                     dispatch=dispatch)
        if resultado is None:
            return

        accion, liResp = resultado
        dicValores["ROUNDS"] = rounds = liResp[0]
        dicValores["MINUTES"] = minutos = liResp[1]
        dicValores["SECONDS"] = segundos = liResp[2]

        liSel = []
        for num in range(self.torneo.numEngines()):
            en = liEngines[num]
            dicValores[en.huella()] = si = liResp[3 + num]
            if si:
                liSel.append(en.huella())

        self.configuracion.escVariables("crear_torneo", dicValores)

        nSel = len(liSel)
        if nSel < 2:
            QTUtil2.mensError(self, _("You must create at least two engines"))
            return

        for r in range(rounds):
            for x in range(0, nSel - 1):
                for y in range(x + 1, nSel):
                    self.torneo.nuevoGame(liSel[x], liSel[y], minutos,
                                          segundos)
                    self.torneo.nuevoGame(liSel[y], liSel[x], minutos,
                                          segundos)

        self.gridGames.refresh()
        self.gridGames.gobottom()
        self.borraResult()
Exemple #17
0
def genHistograms(partida, sicentipawns):
    siPawns = not sicentipawns
    hgame = HSerie(siPawns)
    hwhite = HSerie(siPawns)
    hblack = HSerie(siPawns)

    lijg = []
    lijgW = []
    lijgB = []

    porcT = 0
    porcW = 0
    porcB = 0
    with open("IntFiles/Formulas/eloperfomance.formula") as f:
        eloformula = f.read().strip()

    for num, jg in enumerate(partida.liJugadas):
        if jg.analisis:
            mrm, pos = jg.analisis
            siBlancas = jg.siBlancas()
            pts = mrm.liMultiPV[pos].puntosABS_5()
            pts0 = mrm.liMultiPV[0].puntosABS_5()
            lostp_abs = pts0 - pts

            elo_base = int(eval(eloformula.replace("xlost", str(lostp_abs))))
            jg.elo_real = max(elo_base, 0)
            elo = max(elo_base, 1000)
            jg.elo = elo

            li = list({rm.puntosABS_5() for rm in mrm.liMultiPV})
            li.sort(reverse=True)
            jg.elo_factor = len(li)

            porc = jg.porcentaje = 100 - lostp_abs if lostp_abs < 100 else 0
            porcT += porc

            lijg.append(jg)
            if siBlancas:
                lijgW.append(jg)
                porcW += porc
            else:
                pts = -pts
                pts0 = -pts0
                lijgB.append(jg)
                porcB += porc

            if siPawns:
                pts /= 100.0
                pts0 /= 100.0
            lostp = abs(pts0 - pts)

            nj = num / 2.0 + 1.0
            rotulo = "%d." % int(nj)
            if not siBlancas:
                rotulo += ".."
            jg.xnum = rotulo
            rotulo += jg.pgnSP()

            jg.xsiW = siBlancas

            tooltip = rotulo + " " + ("%+0.02f" if siPawns else "%+d") % pts
            if lostp:
                tooltip += " ?" + ("%0.02f" if siPawns else "%d") % lostp
            else:
                tooltip += "!"
            tooltip += " (%d)" % elo
            hp = HPoint(nj, pts, lostp, lostp_abs, tooltip, elo)
            hgame.addPoint(hp)
            if siBlancas:
                hwhite.addPoint(hp.clone())
            else:
                hblack.addPoint(hp.clone())

    alm = Util.Almacen()
    alm.hgame = hgame
    alm.hwhite = hwhite
    alm.hblack = hblack

    alm.lijg = lijg
    alm.lijgW = lijgW
    alm.lijgB = lijgB

    alm.porcT = porcT * 1.0 / len(lijg) if len(lijg) else 0
    alm.porcW = porcW * 1.0 / len(lijgW) if len(lijgW) else 0
    alm.porcB = porcB * 1.0 / len(lijgB) if len(lijgB) else 0

    return alm
 def linea_bloque(self, pos):
     alm = Util.Almacen()
     alm.fen, alm.bm, alm.sol, alm.pgn, alm.dif = self.li_bloque[pos].split(
         "|")
     alm.max_time = (int(alm.dif)**2) * 5 + 120
     return alm
Exemple #19
0
 def leeRegAllRecno(self, recno):
     raw = self.leeAllRecno(recno)
     alm = Util.Almacen()
     for campo in self.liCamposAll:
         setattr(alm, campo, raw[campo])
     return alm, raw
Exemple #20
0
def genSVG(partida):
    siPawns = not VarGen.configuracion.centipawns
    game = []
    gameDif = []
    white = []
    black = []
    whiteDif = []
    blackDif = []

    axis_x = []
    axis_xW = []
    axis_xB = []

    lijg = []
    lijgW = []
    lijgB = []

    # complexity = {True:[], False:[], None:[]}
    # winprobability = {True:[], False:[], None:[]}
    # narrowness = {True:[], False:[], None:[]}
    # efficientmobility = {True:[], False:[], None:[]}
    # piecesactivity = {True:[], False:[], None:[]}
    # exchangetendency = {True:[], False:[], None:[]}

    for num, jg in enumerate(partida.liJugadas):
        if jg.analisis:
            mrm, pos = jg.analisis
            siBlancas = jg.siBlancas()
            pts = mrm.liMultiPV[pos].puntosABS_5()
            pts0 = mrm.liMultiPV[0].puntosABS_5()
            if not siBlancas:
                pts = -pts
                pts0 = -pts0
            if siPawns:
                pts = pts / 100.0
                pts0 = pts0 / 100.0

            nj = num / 2.0 + 1.0

            rotulo = "%d." % int(nj)
            if not siBlancas:
                rotulo += ".."
            jg.xnum = rotulo
            jg.xsiW = siBlancas
            rotulo += jg.pgnSP()
            axis_x.append(rotulo)
            lijg.append(jg)

            game.append(pts)
            gameDif.append(pts0 - pts)

            if siBlancas:
                axis_xW.append(rotulo)
                white.append(pts)
                whiteDif.append(pts0 - pts)
                lijgW.append(jg)
            else:
                axis_xB.append(rotulo)
                black.append(-pts)
                blackDif.append(-pts0 + pts)
                lijgB.append(jg)

                # if not hasattr(jg,"complexity"):
                # cp = jg.posicionBase
                # jg.complexity = Analisis.calc_complexity(cp, mrm)
                # jg.winprobability = Analisis.calc_winprobability(cp, mrm)
                # jg.narrowness = Analisis.calc_narrowness(cp, mrm)
                # jg.efficientmobility = Analisis.calc_efficientmobility(cp, mrm)
                # jg.piecesactivity = Analisis.calc_piecesactivity(cp, mrm)
                # jg.exchangetendency = Analisis.calc_exchangetendency(cp, mrm)

                # complexity[siBlancas].append(jg.complexity)
                # winprobability[siBlancas].append(jg.winprobability)
                # narrowness[siBlancas].append(jg.narrowness)
                # efficientmobility[siBlancas].append(jg.efficientmobility)
                # piecesactivity[siBlancas].append(jg.piecesactivity)
                # exchangetendency[siBlancas].append(jg.exchangetendency)
                # complexity[None].append(jg.complexity)
                # winprobability[None].append(jg.winprobability)
                # narrowness[None].append(jg.narrowness)
                # efficientmobility[None].append(jg.efficientmobility)
                # piecesactivity[None].append(jg.piecesactivity)
                # exchangetendency[None].append(jg.exchangetendency)

    alm = Util.Almacen()

    alm.lijg = lijg
    alm.lijgW = lijgW
    alm.lijgB = lijgB
    alm.axis_x = axis_x

    alm.game = wHistogram(6, False, axis_x, game)
    alm.gameDif = wHistogram(7, True, axis_x, gameDif)

    alm.white = wHistogram(2, False, axis_xW, white)
    alm.whiteDif = wHistogram(3, True, axis_xW, whiteDif)

    alm.black = wHistogram(4, False, axis_xB, black)
    alm.blackDif = wHistogram(5, True, axis_xB, blackDif)

    # alm.complexity = {}
    # alm.winprobability = {}
    # alm.narrowness = {}
    # alm.efficientmobility = {}
    # alm.piecesactivity = {}
    # alm.exchangetendency = {}

    # axis = { True:axis_xW, False:axis_xB, None:axis_x}
    # for quien in (True,False,None):
    # ax = axis[quien]
    # alm.complexity[quien] = wHistogram( 0, True, ax, complexity[quien] )
    # alm.winprobability[quien] = wHistogram( 1, True, ax, winprobability[quien] )
    # alm.narrowness[quien] = wHistogram( 2, True, ax, narrowness[quien] )
    # alm.efficientmobility[quien] = wHistogram( 3, True, ax, efficientmobility[quien] )
    # alm.piecesactivity[quien] = wHistogram( 4, True, ax, piecesactivity[quien] )
    # alm.exchangetendency[quien] = wHistogram( 5, True, ax, exchangetendency[quien] )

    return alm
Exemple #21
0
def genHistograms(partida, sicentipawns):
    siPawns = not sicentipawns
    hgame = HSerie(siPawns)
    hwhite = HSerie(siPawns)
    hblack = HSerie(siPawns)

    lijg = []
    lijgW = []
    lijgB = []

    for num, jg in enumerate(partida.liJugadas):
        if jg.analisis:
            mrm, pos = jg.analisis
            siBlancas = jg.siBlancas()
            pts = mrm.liMultiPV[pos].puntosABS_5()
            pts0 = mrm.liMultiPV[0].puntosABS_5()
            lostp_abs = pts0 - pts
            lijg.append(jg)
            if siBlancas:
                lijgW.append(jg)
            else:
                pts = -pts
                pts0 = -pts0
                lijgB.append(jg)

            if siPawns:
                pts /= 100.0
                pts0 /= 100.0
            lostp = abs(pts0 - pts)

            nj = num / 2.0 + 1.0
            rotulo = "%d." % int(nj)
            if not siBlancas:
                rotulo += ".."
            jg.xnum = rotulo
            rotulo += jg.pgnSP()

            jg.xsiW = siBlancas

            tooltip = rotulo + " " + ("%+0.02f" if siPawns else "%+d") % pts
            if lostp:
                tooltip += " ?" + ("%0.02f" if siPawns else "%d") % lostp
            else:
                tooltip += "!"
            hp = HPoint(nj, pts, lostp, lostp_abs, tooltip)
            hgame.addPoint(hp)
            if siBlancas:
                hwhite.addPoint(hp.clone())
            else:
                hblack.addPoint(hp.clone())

    alm = Util.Almacen()
    alm.hgame = hgame
    alm.hwhite = hwhite
    alm.hblack = hblack

    alm.lijg = lijg
    alm.lijgW = lijgW
    alm.lijgB = lijgB

    return alm
Exemple #22
0
def paramAnalisisMasivo(parent, configuracion, siVariosSeleccionados):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

    # # Tutor
    li = configuracion.ayudaCambioTutor()
    li[0] = alm.motor
    liGen.append((_("Engine") + ":", li))

    liGen.append(SEPARADOR)

    # # Time
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    liGen.append((config, alm.tiempo / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 31):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liGen.append((config, alm.depth))

    # Time+Depth
    liGen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    liGen.append(SEPARADOR)
    li = [(_("Default"), "PD"), (_("Maximum"), "MX")]
    for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200):
        li.append((str(x), str(x)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    liGen.append((config, alm.multiPV))
    liGen.append(SEPARADOR)

    liJ = [(_("White"), "BLANCAS"), (_("Black"), "NEGRAS"),
           (_("White & Black"), "AMBOS")]
    config = FormLayout.Combobox(_("Analyze only color"), liJ)
    liGen.append((config, "AMBOS"))

    liGen.append(
        ("<div align=\"right\">" + _("Only player moves") + ":<br>%s</div>" %
         _("(You can add multiple aliases separated by ; and wildcard * )"),
         ""))

    fvar = configuracion.ficheroBooks
    listaLibros = Books.ListaLibros()
    listaLibros.recuperaVar(fvar)
    # Comprobamos que todos esten accesibles
    listaLibros.comprueba()
    defecto = listaLibros.lista[0]
    li = [("--", None)]
    for libro in listaLibros.lista:
        if libro.nombre == alm.libro:
            defecto = libro
        li.append((libro.nombre, libro))
    config = FormLayout.Combobox(
        _("Do not scan the opening moves based on book"), li)
    liGen.append((config, defecto))

    liGen.append((_("Start from the end of the game") + ":", alm.desdeelfinal))

    liGen.append(SEPARADOR)
    liGen.append((_("Only selected games") + ":", siVariosSeleccionados))

    liBlunders, liBrilliancies = formBlundersBrilliancies(alm, configuracion)

    lista = []
    lista.append((liGen, _("General options"), ""))
    lista.append((liBlunders, _("Wrong moves"), ""))
    lista.append((liBrilliancies, _("Brilliancies"), ""))

    reg = Util.Almacen()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refreshGUI()

    resultado = FormLayout.fedit(lista,
                                 title=_("Mass analysis"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        liGen, liBlunders, liBrilliancies = liResp

        alm.motor = liGen[0]
        alm.tiempo = int(liGen[1] * 1000)
        alm.depth = liGen[2]
        alm.timedepth = liGen[3]
        alm.multiPV = liGen[4]

        color = liGen[5]
        alm.blancas = color != "NEGRAS"
        alm.negras = color != "BLANCAS"

        cjug = liGen[6].strip()
        alm.liJugadores = cjug.upper().split(";") if cjug else None

        alm.libroAperturas = liGen[7]
        alm.libro = alm.libroAperturas.nombre

        alm.desdeelfinal = liGen[8]

        alm.siVariosSeleccionados = liGen[9]

        alm.kblunders = liBlunders[0]
        alm.tacticblunders = liBlunders[1]
        alm.pgnblunders = liBlunders[2]
        alm.oriblunders = liBlunders[3]
        alm.bmtblunders = liBlunders[4]

        alm.dpbrilliancies = liBrilliancies[0]
        alm.ptbrilliancies = liBrilliancies[1]
        alm.fnsbrilliancies = liBrilliancies[2]
        alm.pgnbrilliancies = liBrilliancies[3]
        alm.oribrilliancies = liBrilliancies[4]
        alm.bmtbrilliancies = liBrilliancies[5]

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x.upper()] = getattr(alm, x)
        Util.guardaVar(configuracion.ficheroAnalisis, dic)

        if not (alm.tacticblunders or alm.pgnblunders or alm.bmtblunders
                or alm.fnsbrilliancies or alm.pgnbrilliancies
                or alm.bmtbrilliancies):
            QTUtil2.mensError(parent,
                              _("No file was specified where to save results"))
            return

        return alm
    else:
        return None
Exemple #23
0
def paramAnalisis(parent, configuracion, siModoAmpliado, siTodosMotores=False):
    alm = leeDicParametros(configuracion)

    # Datos
    liGen = [SEPARADOR]

    # # Tutor
    if siTodosMotores:
        li = configuracion.ayudaCambioCompleto(alm.motor)
    else:
        li = configuracion.ayudaCambioTutor()
        li[0] = alm.motor
    liGen.append((_("Engine") + ":", li))

    # # Time
    liGen.append(SEPARADOR)
    config = FormLayout.Editbox(_("Duration of engine analysis (secs)"),
                                40,
                                tipo=float)
    liGen.append((config, alm.tiempo / 1000.0))

    # Depth
    liDepths = [("--", 0)]
    for x in range(1, 51):
        liDepths.append((str(x), x))
    config = FormLayout.Combobox(_("Depth"), liDepths)
    liGen.append((config, alm.depth))

    # Time+Depth
    liGen.append(("%s+%s:" % (_("Time"), _("Depth")), alm.timedepth))

    # MultiPV
    liGen.append(SEPARADOR)
    li = [(_("Default"), "PD"), (_("Maximum"), "MX")]
    for x in (1, 3, 5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200):
        li.append((str(x), str(x)))
    config = FormLayout.Combobox(
        _("Number of moves evaluated by engine(MultiPV)"), li)
    liGen.append((config, alm.multiPV))

    # Priority
    liGen.append(SEPARADOR)
    li = [(_("Normal"), EngineThread.PRIORITY_NORMAL),
          (_("Low"), EngineThread.PRIORITY_LOW),
          (_("Very low"), EngineThread.PRIORITY_VERYLOW),
          (_("High"), EngineThread.PRIORITY_HIGH),
          (_("Very high"), EngineThread.PRIORITY_VERYHIGH)]
    config = FormLayout.Combobox(_("Process priority"), li)
    liGen.append((config, alm.priority))

    # Completo
    if siModoAmpliado:
        liGen.append(SEPARADOR)

        liJ = [(_("White"), "BLANCAS"), (_("Black"), "NEGRAS"),
               (_("White & Black"), "AMBOS")]
        config = FormLayout.Combobox(_("Analyze only color"), liJ)
        liGen.append((config, "AMBOS"))

        config = FormLayout.Editbox("<div align=\"right\">" + _("Moves") +
                                    "<br>" + _("By example:") +
                                    " -5,8-12,14,19-",
                                    rx="[0-9,\-,\,]*")
        liGen.append((config, ""))

        fvar = configuracion.ficheroBooks
        listaLibros = Books.ListaLibros()
        listaLibros.recuperaVar(fvar)
        # Comprobamos que todos esten accesibles
        listaLibros.comprueba()
        li = [("--", None)]
        defecto = listaLibros.lista[0] if alm.libro else None
        for libro in listaLibros.lista:
            if alm.libro == libro.nombre:
                defecto = libro
            li.append((libro.nombre, libro))
        config = FormLayout.Combobox(
            _("Do not scan the opening moves based on book"), li)
        liGen.append((config, defecto))
        liGen.append(SEPARADOR)

        liGen.append(
            (_("To redo any existing prior analyses (if they exist)") + ":",
             alm.siBorrarPrevio))

        liGen.append(
            (_("Start from the end of the game") + ":", alm.desdeelfinal))

        liGen.append(SEPARADOR)

        liGen.append((_("Show graphics") + ":", alm.showGraphs))

        liVar = [SEPARADOR]
        liVar.append((_("Add analysis to variants") + ":", alm.masvariantes))
        liVar.append(SEPARADOR)

        liVar.append((FormLayout.Spinbox(_("Minimum points lost"), 0, 1000,
                                         60), alm.limitemasvariantes))
        liVar.append(SEPARADOR)

        liVar.append((_("Only add better variant") + ":", alm.mejorvariante))
        liVar.append(SEPARADOR)

        liVar.append((_("Include info about engine") + ":", alm.infovariante))
        liVar.append(SEPARADOR)

        liVar.append(
            ("%s %s/%s/%s:" %
             (_("Format"), _("Points"), _("Depth"), _("Time")), alm.siPDT))
        liVar.append(SEPARADOR)

        liVar.append(
            (_("Only one move of each variant") + ":", alm.unmovevariante))

        liBlunders, liBrilliancies = formBlundersBrilliancies(
            alm, configuracion)

        liST = [SEPARADOR]
        liST.append((_("Activate") + ":", alm.stability))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Last depths to control same best move"), 2,
                                10, 40), alm.st_depths))
        liST.append(SEPARADOR)
        liST.append(
            (FormLayout.Spinbox(_("Maximum difference among last evaluations"),
                                0, 99999, 60), alm.st_centipawns))
        liST.append(SEPARADOR)
        liST.append((FormLayout.Spinbox(_("Additional time limit"), 0, 99999,
                                        60), alm.st_timelimit))

        lista = []
        lista.append((liGen, _("General options"), ""))
        lista.append((liVar, _("Variants"), ""))
        lista.append((liBlunders, _("Wrong moves"), ""))
        lista.append((liBrilliancies, _("Brilliancies"), ""))
        lista.append((liST, _("Stability control"), ""))

    else:
        lista = liGen

    reg = Util.Almacen()
    reg.form = None

    def dispatchR(valor):
        if reg.form is None:
            if isinstance(valor, FormLayout.FormTabWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(0, 1)
                reg.wdepth = valor.getWidget(0, 2)
                reg.wdt = valor.getWidget(0, 3)
            elif isinstance(valor, FormLayout.FormWidget):
                reg.form = valor
                reg.wtime = valor.getWidget(1)
                reg.wdepth = valor.getWidget(2)
                reg.wdt = valor.getWidget(3)
        else:
            sender = reg.form.sender()
            if not reg.wdt.isChecked():
                if sender == reg.wtime:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                elif sender == reg.wdepth:
                    if reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)
                elif sender == reg.wdt:
                    if reg.wtime.textoFloat() > 0:
                        reg.wdepth.setCurrentIndex(0)
                    elif reg.wdepth.currentIndex() > 0:
                        reg.wtime.ponFloat(0.0)

                QTUtil.refreshGUI()

    resultado = FormLayout.fedit(lista,
                                 title=_("Analysis Configuration"),
                                 parent=parent,
                                 anchoMinimo=460,
                                 icon=Iconos.Opciones(),
                                 dispatch=dispatchR)

    if resultado:
        accion, liResp = resultado

        if siModoAmpliado:
            liGen, liVar, liBlunders, liBrilliancies, liST = liResp
        else:
            liGen = liResp

        alm.motor = liGen[0]
        alm.tiempo = int(liGen[1] * 1000)
        alm.depth = liGen[2]
        alm.timedepth = liGen[3]
        alm.multiPV = liGen[4]
        alm.priority = liGen[5]

        if siModoAmpliado:
            color = liGen[6]
            alm.blancas = color != "NEGRAS"
            alm.negras = color != "BLANCAS"
            alm.jugadas = liGen[7]
            alm.libroAperturas = liGen[8]
            alm.libro = alm.libroAperturas.nombre if alm.libroAperturas else None
            alm.siBorrarPrevio = liGen[9]
            alm.desdeelfinal = liGen[10]
            alm.showGraphs = liGen[11]

            (alm.masvariantes, alm.limitemasvariantes, alm.mejorvariante,
             alm.infovariante, alm.siPDT, alm.unmovevariante) = liVar

            (alm.kblunders, alm.tacticblunders, alm.pgnblunders,
             alm.oriblunders, alm.bmtblunders) = liBlunders

            (alm.dpbrilliancies, alm.ptbrilliancies, alm.fnsbrilliancies,
             alm.pgnbrilliancies, alm.oribrilliancies,
             alm.bmtbrilliancies) = liBrilliancies

            (alm.stability, alm.st_depths, alm.st_centipawns,
             alm.st_timelimit) = liST

        dic = {}
        for x in dir(alm):
            if not x.startswith("__"):
                dic[x.upper()] = getattr(alm, x)
        Util.guardaVar(configuracion.ficheroAnalisis, dic)

        return alm
    else:
        return None
Exemple #24
0
def genHistograms(partida, sicentipawns):
    siPawns = not sicentipawns
    hgame = HSerie(siPawns)
    hwhite = HSerie(siPawns)
    hblack = HSerie(siPawns)

    lijg = []
    lijgW = []
    lijgB = []

    porcT = 0
    porcW = 0
    porcB = 0

    for num, jg in enumerate(partida.liJugadas):
        if jg.analisis:
            mrm, pos = jg.analisis
            siBlancas = jg.siBlancas()
            pts = mrm.liMultiPV[pos].puntosABS()
            pts0 = mrm.liMultiPV[0].puntosABS()
            jg.lostp_abs = lostp_abs = pts0 - pts

            porc = jg.porcentaje = 100 - lostp_abs if lostp_abs < 100 else 0
            porcT += porc

            lijg.append(jg)
            if siBlancas:
                lijgW.append(jg)
                porcW += porc
            else:
                pts = -pts
                pts0 = -pts0
                lijgB.append(jg)
                porcB += porc

            if siPawns:
                pts /= 100.0
                pts0 /= 100.0
            lostp = abs(pts0 - pts)

            nj = num / 2.0 + 1.0
            rotulo = "%d." % int(nj)
            if not siBlancas:
                rotulo += ".."
            jg.xnum = rotulo
            rotulo += jg.pgnSP()

            jg.xsiW = siBlancas

            tooltip = rotulo + " " + ("%+0.02f" if siPawns else "%+d") % pts
            if lostp:
                tooltip += " ?" + ("%0.02f" if siPawns else "%d") % lostp
            else:
                tooltip += "!"
            tooltip += " (%d)" % jg.elo
            hp = HPoint(nj, pts, lostp, lostp_abs, tooltip, jg.elo)
            hgame.addPoint(hp)
            if siBlancas:
                hwhite.addPoint(hp.clone())
            else:
                hblack.addPoint(hp.clone())

    alm = Util.Almacen()
    alm.hgame = hgame
    alm.hwhite = hwhite
    alm.hblack = hblack

    alm.lijg = lijg
    alm.lijgW = lijgW
    alm.lijgB = lijgB

    alm.porcT = porcT * 1.0 / len(lijg) if len(lijg) else 0
    alm.porcW = porcW * 1.0 / len(lijgW) if len(lijgW) else 0
    alm.porcB = porcB * 1.0 / len(lijgB) if len(lijgB) else 0

    return alm
Exemple #25
0
 def save_next(self, recno, next_game, tries_used, times):
     reg = Util.Almacen()
     reg.NEXT_GAME = next_game
     reg.TRIES_USED = tries_used
     reg.TIMES = str(times)
     self.dbf.modificarReg(recno, reg)