On Sat, 2008-10-18 at 09:26 -0400, Don Dailey wrote:
> I have two versions of the reference bot.  A C and a Java version. 

I've ported the Java position.d to D2 and added a basic wrapper around
it.  Here are performance numbers on my laptop
javabot runs in 132 seconds for 1,000,000 simulations
drefbot runs in 146 seconds for 1,000,000 simulations

compilation command with dmd 2.014:
dmd -gc -O -release drefbot.d gtp.d position.d phobosrandom.d
tangoshuffle.d -ofdrefbot
(windows user append .exe to end of line)

Here's a basic description of the files:
position.d - A D2 port of position.java
gtp.d - GTP implementation using some generic programming
        (automatic parameter conversion, uses command registration)
drefbot.d - Basic glue of position.d with gtp.d
tangoshuffle.d - Used as replacement for Collections.shuffle
phobosrandom.d - Patched version of std.random to fix a serious bug

It's possible to eliminate tangoshuffle.d, but I was lazy with my
initial port and didn't bother thinking about how to efficiently shuffle
(and debug whatever I hacked together)
import gtp;
import position;
import std.conv;

int boardSize = 9;
int level = 1000;
Position gme;

void main(string[] args){
	if (args.length > 1)
		level = to!(int)(args[1]);
	gme.init();
	register("boardsize", (int n){boardSize = n; gme.setBoardSize(n);});
	register("clear_board", (){gme.setBoardSize(boardSize);});
	register("final_status_list", (string s){return ""[];});
	register("genmove", (string color){
			string smv = gme.genmove(level);
			gme.make(smv);
			debug gme.display;
			return smv;
		});
	register("komi", (double n){gme.setKomi(n);});
	register("name", (){return "DrefBot"[];});
	register("play", (string color, string vertex){gme.make(vertex);});
	register("ref-nodes", (){return gme.final_search_nodes;});
	register("ref-playouts", (){return level;});
	register("ref-score", (){return gme.final_search_score;});
	register("version", (){return "0.1"[];});
	run();
}
module gtp;
import std.conv;
import std.stdio;
import std.string;
import std.c.stdlib;

alias string delegate(string[]) gtpCommandProcessor_t;
gtpCommandProcessor_t[string] gtpCommands;

void register(R, T...)(string commandName, R delegate(T) f){
	string callback(string[] args){
		T translatedArgs;
		try{
			assert(T.length == args.length, "Incorrect number of arguments");
			foreach(i, type; T)
				translatedArgs[i] = to!(type)(args[i]);
			string r = "";
			static if (is(R==void))
				f(translatedArgs);
			else
				r = to!(string)(f(translatedArgs));
			return "= " ~ r ~ "\n\n";
		}
		catch (Exception e){
			return "? " ~ e.msg ~ "\n\n";
		}
	}
	gtpCommands[commandName] = &callback;
}

R delegate(T) toDelegate(R, T...)(R function(T) f){ return delegate R(T t){return f(t);}; }
void register(R, T...)(string commandName, R function(T) f){
	register(commandName, toDelegate(f));
}

string listCommands(){
	string retval = "";
	foreach(string key, gtpCommandProcessor_t value; gtpCommands){
		if (retval.length == 0)
			retval = key;
		else
			retval ~= "\n" ~ key;
	}
	return retval;
}

void run(){
	register("known_command", 
		delegate bool (string cmd){return (cmd in gtpCommands) !is null; });
	register("list_commands", &listCommands);
	register("protocol_version", (){return 2;});
	register("quit", (){exit(0);});
	foreach(string line; lines(stdin)){
		if (line.length==0 || line[0] == '#')
			continue;
		auto pieces = split(line);
		if (pieces[0] in gtpCommands)
			writef("%s",gtpCommands[pieces[0]](pieces[1..$]));
		else
			writef("? Unknown command %s\n\n", pieces[0]);
	}
}
// Written in the D programming language

/**
Facilities for random number generation. The old-style functions
$(D_PARAM rand_seed) and $(D_PARAM rand) will soon be deprecated as
they rely on global state and as such are subjected to various
thread-related issues.

The new-style generator objects hold their own state so they are
immune of threading issues. The generators feature a number of
well-known and well-documented methods of generating random
numbers. An overall fast and reliable means to generate random numbers
is the $(D_PARAM Mt19937) generator, which derives its name from
"$(WEB math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html, Mersenne
Twister) with a period of 2 to the power of 19937". In
memory-constrained situations, $(WEB
en.wikipedia.org/wiki/Linear_congruential_generator, linear
congruential) generators such as $(D MinstdRand0) and $(D MinstdRand)
might be useful. The standard library provides an alias $(D_PARAM
Random) for whichever generator it finds the most fit for the target
environment.
   
Example:

----
Random gen;
// Generate a uniformly-distributed integer in the range [0, 15]
auto i = uniform!(int)(gen, 0, 15);
// Generate a uniformly-distributed real in the range [0, 100$(RPAREN)
auto r = uniform!(real)(gen, 0.0L, 100.0L);
----

In addition to random number generators, this module features
distributions, which skew a generator's output statistical
distribution in various ways. So far the uniform distribution for
integers and real numbers have been implemented.

Author:

$(WEB erdani.org, Andrei Alexandrescu)

Credits:

The entire random number library architecture is derived from the
excellent $(WEB
open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf, C++0X) random
number facility proposed by Jens Maurer and contributed to by
researchers at the Fermi laboratory.

Macros:

WIKI = Phobos/StdRandom
*/

// random.d
// www.digitalmars.com

//module std.random;
module phobosrandom;

import std.stdio, std.math, std.c.time, std.traits, std.contracts, std.conv,
    std.algorithm, std.process, std.date;

// Segments of the code in this file Copyright (c) 1997 by Rick Booth
// From "Inner Loops" by Rick Booth, Addison-Wesley

// Work derived from:

/* 
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

version (Win32)
{
    extern(Windows) int QueryPerformanceCounter(ulong *count);
}

version (linux)
{
    private import std.c.linux.linux;
}

/**
   Linear Congruential generator.
*/

struct LinearCongruentialEngine(UIntType, UIntType a, UIntType c, UIntType m)
{
/// Alias for the generated type $(D_PARAM UIntType).
    alias UIntType ResultType;
    static invariant
    {
        /// Does this generator have a fixed range? ($(D_PARAM true)).
        bool hasFixedRange = true;
        /// Lowest generated value.
        ResultType min = ( c == 0 ? 1 : 0 );
        /// Highest generated value.
        ResultType max = m - 1;
/**
   The parameters of this distribution. The random number is $(D_PARAM x =
        (x * a + c) % m).
*/
        UIntType
            multiplier = a,
            ///ditto
            increment = c,
            ///ditto
            modulus = m;
    }
    
    static assert(isIntegral!(UIntType));
    static assert(m == 0 || a < m);
    static assert(m == 0 || c < m);
    static assert(m == 0 ||
                  (cast(ulong)a * (m-1) + c) % m == (c < a ? c - a + m : c - a));

/**
     Constructs a $(D_PARAM LinearCongruentialEngine) generator.
*/
    static LinearCongruentialEngine opCall(UIntType x0 = 1)
    {
        LinearCongruentialEngine result;
        result.seed(x0);
        return result;
    }

/**
   (Re)seeds the generator.
*/
    void seed(UIntType x0 = 1)
    {
        static if (c == 0)
        {
            enforce(x0, "Invalid (zero) seed for "
                    ~LinearCongruentialEngine.stringof);
        }
        _x = modulus ? (x0 % modulus) : x0;
    }

/**
   Returns the next number in the random sequence.
*/
    UIntType next()
    {
        static if (m) 
            _x = cast(UIntType) ((cast(ulong) a * _x + c) % m);
        else
            _x = a * _x + c;
        return _x;
    }

/**
   Discards next $(D_PARAM n) samples.
*/
    void discard(ulong n)
    {
        while (n--) next;
    }

/**
   Compares against $(D_PARAM rhs) for equality.
*/
    bool opEquals(LinearCongruentialEngine rhs)
    {
        return _x == rhs._x;
    }
    
    private UIntType _x = 1;
};

/**
   Define $(D_PARAM LinearCongruentialEngine) generators with "good"
   parameters.

   Example:

   ----
   // seed with a constant
   auto rnd0 = MinstdRand0(1);
   auto n = rnd0.next; // same for each run
   // Seed with an unpredictable value
   rnd0.seed(unpredictableSeed);
   n = rnd0.next; // different across runs
   ----
*/
alias LinearCongruentialEngine!(uint, 16807, 0, 2147483647) MinstdRand0;
/// ditto
alias LinearCongruentialEngine!(uint, 48271, 0, 2147483647) MinstdRand;

unittest
{
    // The correct numbers are taken from The Database of Integer Sequences
    // http://www.research.att.com/~njas/sequences/eisBTfry00128.txt
    auto checking0 = [
        16807UL,282475249,1622650073,984943658,1144108930,470211272,
        101027544,1457850878,1458777923,2007237709,823564440,1115438165,
        1784484492,74243042,114807987,1137522503,1441282327,16531729,
        823378840,143542612 ];
    auto rnd0 = MinstdRand0(1);
    foreach (e; checking0)
    {
        assert(rnd0.next == e);
    }
    // Test the 10000th invocation
    // Correct value taken from:
    // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
    rnd0.seed;
    rnd0.discard(9999);
    assert(rnd0.next == 1043618065);

    // Test MinstdRand
    auto checking = [48271UL,182605794,1291394886,1914720637,2078669041,
                     407355683];
    auto rnd = MinstdRand(1);
    foreach (e; checking)
    {
        assert(rnd.next == e);
    }

    // Test the 10000th invocation
    // Correct value taken from:
    // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2461.pdf
    rnd.seed;
    rnd.discard(9999);
    assert(rnd.next == 399268537);
}

/**
   The $(LINK2 http://math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html,
   Mersenne Twister generator).
*/
struct MersenneTwisterEngine(
    UIntType, size_t w, size_t n, size_t m, size_t r,
    UIntType a, size_t u, size_t s,
    UIntType b, size_t t,
    UIntType c, size_t l)
{
/// Result type (an alias for $(D_PARAM UIntType)).
    alias UIntType ResultType;

/**
   Parameter for the generator.
*/
    static invariant
    {
        size_t wordSize = w;
        size_t stateSize = n;
        size_t shiftSize = m;
        size_t maskBits = r;
        UIntType xorMask = a;
        UIntType temperingU = u;
        size_t temperingS = s;
        UIntType temperingB = b;
        size_t temperingT = t;
        UIntType temperingC = c;
        size_t temperingL = l;
    }

    /// Smallest generated value (0).
    static invariant UIntType min = 0;
    /// Largest generated value.
    static invariant UIntType max =
        w == UIntType.sizeof * 8 ? UIntType.max : (1u << w) - 1;
    /// The default seed value.
    static invariant UIntType defaultSeed = 5489u;

    static assert(1 <= m && m <= n);
    static assert(0 <= r && 0 <= u && 0 <= s && 0 <= t && 0 <= l);
    static assert(r <= w && u <= w && s <= w && t <= w && l <= w);
    static assert(0 <= a && 0 <= b && 0 <= c);
    static assert(a <= max && b <= max && c <= max);

/**
   Constructs a MersenneTwisterEngine object
*/
    static MersenneTwisterEngine opCall(ResultType value)
    {
        MersenneTwisterEngine result;
        result.seed(value);
        return result;
    }
    
/**
   Constructs a MersenneTwisterEngine object
*/
    void seed(ResultType value = defaultSeed)
    {
        static if (w == ResultType.sizeof * 8)
        {
            mt[0] = value;
        }
        else
        {
            static assert(max + 1 > 0);
            mt[0] = value % (max + 1);
        }
        for (mti = 1; mti < n; ++mti) {
            mt[mti] = 
                cast(UIntType)
                (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> (w - 2))) + mti); 
            /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
            /* In the previous versions, MSBs of the seed affect   */
            /* only MSBs of the array mt[].                        */
            /* 2002/01/09 modified by Makoto Matsumoto             */
            mt[mti] &= ResultType.max;
            /* for >32 bit machines */
        }
    }

/**
   Returns the next random value.
*/
    uint next()
    {
        static invariant ResultType
            upperMask = ~((cast(ResultType) 1u <<
                           (ResultType.sizeof * 8 - (w - r))) - 1),
            lowerMask = (cast(ResultType) 1u << r) - 1;

        ulong y = void;
        static invariant ResultType mag01[2] = [0x0UL, a];

        if (mti >= n)
        {
            /* generate N words at one time */
            if (mti == n + 1)   /* if init_genrand() has not been called, */
                seed(5489UL); /* a default initial seed is used */
            
            int kk = 0;            
            for (; kk < n - m; ++kk)
            {
                y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
                mt[kk] = cast(UIntType) (mt[kk + m] ^ (y >> 1)
                                         ^ mag01[cast(UIntType) y & 0x1U]);
            }
            for (; kk < n - 1; ++kk)
            {
                y = (mt[kk] & upperMask)|(mt[kk + 1] & lowerMask);
                mt[kk] = cast(UIntType) (mt[kk + (m -n)] ^ (y >> 1)
                                         ^ mag01[cast(UIntType) y & 0x1U]);
            }
            y = (mt[n -1] & upperMask)|(mt[0] & lowerMask);
            mt[n - 1] = cast(UIntType) (mt[m - 1] ^ (y >> 1)
                                        ^ mag01[cast(UIntType) y & 0x1U]);
            
            mti = 0;
        }
        
        y = mt[mti++];
        
        /* Tempering */
        y ^= (y >> temperingU);
        y ^= (y << temperingS) & temperingB;
        y ^= (y << temperingT) & temperingC;
        y ^= (y >> temperingL);
        
        return cast(UIntType) y;
    }

/**
   Discards next $(D_PARAM n) samples.
*/
    void discard(ulong n)
    {
        while (n--) next;
    }

    private ResultType mt[n];
    private size_t mti = n + 1; /* means mt is not initialized */
}

/**
A $(D MersenneTwisterEngine) instantiated with the parameters of the
original engine $(WEB math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html,
MT19937), generating uniformly-distributed 32-bit numbers with a
period of 2 to the power of 19937. Recommended for random number
generation unless memory is severely restricted, in which case a $(D
LinearCongruentialEngine) would be the generator of choice.

Example:

----
// seed with a constant
Mt19937 gen;
auto n = gen.next; // same for each run
// Seed with an unpredictable value
gen.seed(unpredictableSeed);
n = gen.next; // different across runs
----
 */
alias MersenneTwisterEngine!(uint, 32, 624, 397, 31, 0x9908b0df, 11, 7,
                             0x9d2c5680, 15, 0xefc60000, 18)
    Mt19937;

unittest
{
    Mt19937 gen;
    gen.discard(9999);
    assert(gen.next == 4123659995);
}

/**
The "default", "favorite", "suggested" random number generator on the
current platform. It is a typedef for one of the previously-defined
generators. You may want to use it if (1) you need to generate some
nice random numbers, and (2) you don't care for the minutiae of the
method being used.
 */

alias Mt19937 Random;

/**
A "good" seed for initializing random number engines. Initializing
with $(D_PARAM unpredictableSeed) makes engines generate different
random number sequences every run.

Example:

----
auto rnd = Random(unpredictableSeed);
auto n = rnd.next;
...
----   
*/

uint unpredictableSeed()
{
    static uint moseghint = 87324921;
    return cast(uint) (getpid ^ getUTCtime ^ ++moseghint);
}

unittest
{
    // not much to test here
    auto a = unpredictableSeed;
    static assert(is(typeof(a) == uint));
    auto b = unpredictableSeed;
    assert(a != b);
}

/**
Generates uniformly-distributed numbers within a range using an
external generator. The $(D boundaries) parameter controls the shape
of the interval (open vs. closed on either side). Valid values for $(D
boundaries) are "[]", "$(LPAREN)]", "[$(RPAREN)", and "()". The
default interval is [a, b$(RPAREN).

Example:

----
auto a = new double[20];
Random gen;
auto rndIndex = UniformDistribution!(uint)(0, a.length);
auto rndValue = UniformDistribution!(double)(0, 1);
// Get a random index into the array
auto i = rndIndex.next(gen);
// Get a random probability, i.e., a real number in [0, 1$(RPAREN)
auto p = rndValue.next(gen);
// Assign that value to that array element
a[i] = p;
auto digits = UniformDistribution!(char, "[]")('0', '9');
auto percentages = UniformDistribution!(double, "$(LPAREN)]")(0.0, 100.0);
// Get a digit in ['0', '9']
auto digit = digits.next(gen); 
// Get a number in $(LPAREN)0.0, 100.0]
auto p = percentages.next(gen);
----
*/
struct UniformDistribution(NumberType, string boundaries = "[)")
{
    enum char leftLim = boundaries[0], rightLim = boundaries[1];
    static assert((leftLim == '[' || leftLim == '(')
                  && (rightLim == ']' || rightLim == ')'));

    alias NumberType InputType;
    alias NumberType ResultType;
/**
Constructs a $(D UniformDistribution) able to generate numbers between
$(D a) and $(D b). The bounds of the interval are controlled by the
template argument, e.g. $(D UniformDistribution!(double, "[]")(0, 1))
generates numbers in the interval [0.0, 1.0].
*/
    static UniformDistribution opCall(NumberType a, NumberType b)
    {
        UniformDistribution result;
        static if (leftLim == '(')
            result._a = nextLarger(a);
        else
            result._a = a;
        static if (rightLim == ')')
            result._b = nextSmaller(b);
        else
            result._b = b;
        //enforce(result._a <= result._b,
        //        "Invalid distribution range: " ~ leftLim ~ to!(string)(a)
        //        ~ ", " ~ to!(string)(b) ~ rightLim);
        return result;
    }
/**
Returns the left bound of the random value generated.
*/
    ResultType a() { return leftLim == '[' ? _a : nextSmaller(_a); }

/**
Returns the the right bound of the random value generated.
*/ 
    ResultType b() { return rightLim == ']' ? _b : nextLarger(_b); }

/**
Does nothing (provided for conformity with other distributions).
*/
    void reset()
    {
    }

/**
Returns a random number using $(D UniformRandomNumberGenerator) as
back-end.
*/
    ResultType next(UniformRandomNumberGenerator)
        (ref UniformRandomNumberGenerator urng)
    {
        static if (isIntegral!(NumberType))
        {
            auto myRange = _b - _a;
            if (!myRange) return _a;
            assert(urng.max - urng.min >= myRange,
                   "UniformIntGenerator.next not implemented for large ranges");
            unsigned!(typeof((urng.max - urng.min + 1) / (myRange + 1)))
                bucketSize = 1 + (urng.max - urng.min - myRange) / (myRange + 1);
            assert(bucketSize, to!(string)(myRange));
            ResultType r = void;
            do
            {
                r = (urng.next - urng.min) / bucketSize;
            }
            while (r > myRange);
            return _a + r;
        }
        else
        {
            return _a + (_b - _a) * cast(NumberType) (urng.next - urng.min)
                / (urng.max - urng.min);
        }
    }
    
private:    
    NumberType _a = 0, _b = NumberType.max;

    static NumberType nextLarger(NumberType x)
    {
        static if (isIntegral!(NumberType))
            return x + 1;
        else
            return nextafter(x, x.infinity);
    }

    static NumberType nextSmaller(NumberType x)
    {
        static if (isIntegral!(NumberType))
            return x - 1;
        else
            return nextafter(x, -x.infinity);
    }
}

unittest
{
    MinstdRand0 gen;
    auto rnd1 = UniformDistribution!(int)(0, 15);
    foreach (i; 0 .. 20)
    {
        auto x = rnd1.next(gen);
        assert(0 <= x && x <= 15);
        //writeln(x);
    }
}

unittest
{
    MinstdRand0 gen;
    foreach (i; 0 .. 20)
    {
        auto x = uniform!(double)(gen, 0., 15.);
        assert(0 <= x && x <= 15);
        //writeln(x);
    }
}

/**
Convenience function that generates a number in an interval by
forwarding to $(D UniformDistribution!(T, boundaries)(a, b).next).

Example:

----
Random gen(unpredictableSeed);
// Generate an integer in [0, 1024$(RPAREN)
auto a = uniform(gen, 0, 1024);
// Generate a float in [0, 1$(RPAREN)
auto a = uniform(gen, 0.0f, 1.0f);
----
*/

T1 uniform(T1, string boundaries = "[)", UniformRandomNumberGenerator, T2)
    (ref UniformRandomNumberGenerator gen, T1 a, T2 b)
{
    alias typeof(return) Result;
    auto dist = UniformDistribution!(Result, boundaries)(a, b);
    return dist.next(gen);
}

unittest
{
    auto gen = Mt19937(unpredictableSeed);
    auto a = uniform(gen, 0, 1024);
    assert(0 <= a && a <= 1024);
    auto b = uniform(gen, 0.0f, 1.0f);
    assert(0 <= b && b < 1, to!(string)(b));
}

/**
Shuffles elements of $(D array) using $(D r) as a shuffler.
*/

void randomShuffle(T, SomeRandomGen)(T[] array, ref SomeRandomGen r)
{
    foreach (i; 0 .. array.length)
    {
        // generate a random number i .. n
        invariant which = i + uniform!(size_t)(r, 0u, array.length - i);
        swap(array[i], array[which]);
    }
}

unittest
{
    auto a = ([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]).dup;
    auto b = a.dup;
    Mt19937 gen;
    randomShuffle(a, gen);
    //assert(a == expectedA);
    assert(a.sort == b.sort);
}

/**
Throws a dice with relative probabilities stored in $(D
proportions). Returns the index in $(D proportions) that was chosen.

Example:

----
auto x = dice(0.5, 0.5);   // x is 0 or 1 in equal proportions
auto y = dice(50, 50);     // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 30% of the time,
                           // and 2 10% of the time
----
*/

size_t dice(R)(ref R rnd, double[] proportions...) {
    invariant sum = reduce!("(assert(b >= 0), a + b)")(0.0, proportions);
    enforce(sum > 0, "Proportions in a dice cannot sum to zero");
    invariant point = uniform(rnd, 0.0, sum);
    assert(point < sum);
    auto mass = 0.0;
    foreach (i, e; proportions) {
        mass += e;
        if (point < mass) return i;
    }
    // this point should not be reached
    assert(false);
}

unittest {
    auto rnd = Random(unpredictableSeed);
    auto i = dice(rnd, 0, 100);
    assert(i == 1);
    i = dice(rnd, 100, 0);
    assert(i == 0);
}

/* ===================== Random ========================= */

// BUG: not multithreaded

private uint seed;		// starting seed
private uint index;		// ith random number

/**
The random number generator is seeded at program startup with a random
value.  This ensures that each program generates a different sequence
of random numbers. To generate a repeatable sequence, use $(D
rand_seed()) to start the sequence. seed and index start it, and each
successive value increments index.  This means that the $(I n)th
random number of the sequence can be directly generated by passing
index + $(I n) to $(D rand_seed()).

Note: This is more random, but slower, than C's $(D rand()) function.
To use C's $(D rand()) instead, import $(D std.c.stdlib).
 
BUGS: Shares a global single state, not multithreaded.  SCHEDULED FOR
DEPRECATION.

*/

void rand_seed(uint seed, uint index)
{
    .seed = seed;
    .index = index;
}

/**
Get the next random number in sequence.
BUGS: Shares a global single state, not multithreaded.
SCHEDULED FOR DEPRECATION.
*/

uint rand()
{
    static uint xormix1[20] =
    [
                0xbaa96887, 0x1e17d32c, 0x03bcdc3c, 0x0f33d1b2,
                0x76a6491d, 0xc570d85d, 0xe382b1e3, 0x78db4362,
                0x7439a9d4, 0x9cea8ac5, 0x89537c5c, 0x2588f55d,
                0x415b5e1d, 0x216e3d95, 0x85c662e7, 0x5e8ab368,
                0x3ea5cc8c, 0xd26a0f74, 0xf3a9222b, 0x48aad7e4
    ];

    static uint xormix2[20] =
    [
                0x4b0f3b58, 0xe874f0c3, 0x6955c5a6, 0x55a7ca46,
                0x4d9a9d86, 0xfe28a195, 0xb1ca7865, 0x6b235751,
                0x9a997a61, 0xaa6e95c8, 0xaaa98ee1, 0x5af9154c,
                0xfc8e2263, 0x390f5e8c, 0x58ffd802, 0xac0a5eba,
                0xac4874f6, 0xa9df0913, 0x86be4c74, 0xed2c123b
    ];

    uint hiword, loword, hihold, temp, itmpl, itmph, i;

    loword = seed;
    hiword = index++;
    for (i = 0; i < 4; i++)		// loop limit can be 2..20, we choose 4
    {
        hihold  = hiword;                           // save hiword for later
        temp    = hihold ^  xormix1[i];             // mix up bits of hiword
        itmpl   = temp   &  0xffff;                 // decompose to hi & lo
        itmph   = temp   >> 16;                     // 16-bit words
        temp    = itmpl * itmpl + ~(itmph * itmph); // do a multiplicative mix
        temp    = (temp >> 16) | (temp << 16);      // swap hi and lo halves
        hiword  = loword ^ ((temp ^ xormix2[i]) + itmpl * itmph); //loword mix
        loword  = hihold;                           // old hiword is loword
    }
    return hiword;
}

static this()
{
    ulong s;

    version(Win32)
    {
	QueryPerformanceCounter(&s);
    }
    version(linux)
    {
	// time.h
	// sys/time.h

	timeval tv;

	if (gettimeofday(&tv, null))
	{   // Some error happened - try time() instead
	    s = std.c.linux.linux.time(null);
	}
	else
	{
	    s = cast(ulong)((cast(long)tv.tv_sec << 32) + tv.tv_usec);
	}
    }
    rand_seed(cast(uint) s, cast(uint)(s >> 32));
}


unittest
{
    static uint results[10] =
    [
	0x8c0188cb,
	0xb161200c,
	0xfc904ac5,
	0x2702e049,
	0x9705a923,
	0x1c139d89,
	0x346b6d1f,
	0xf8c33e32,
	0xdb9fef76,
	0xa97fcb3f
    ];
    int i;
    uint seedsave = seed;
    uint indexsave = index;

    rand_seed(1234, 5678);
    for (i = 0; i < 10; i++)
    {	uint r = rand();
	//printf("0x%x,\n", rand());
	assert(r == results[i]);
    }

    seed = seedsave;
    index = indexsave;
}
module position;

import std.algorithm;
import std.conv;
import std.stdio;
import std.string :find, toupper;

import phobosrandom; // a patched version of std.random
import tangoshuffle; // ported from D1 Tango library

struct Position {

    /*
      note:  The board is a 1 dimension array of integers which
             can be viewd like this (example uses 3x3 board):

	     4 4 4 4 
	     4 0 0 0
	     4 0 0 0
	     4 0 0 0
	     4 4 4 4 4

	     where 0 -> empty legal point
	           1 -> white stone
		   2 -> black stone
		   4 -> board edge

             One extra element appended so that diagonal eye
	     test for lower right corner does not cause array
	     overflow error.
     */


	public  int    N;
	public  int    NN;
	public  int    N1;
	public  int    N2;
	public  int    NNN; 
	public  int    asz; 
	private int    ctm;
	private int    savctm;
	public  long[] key;   // for PSK testing at root
	public  int[]  mvs;
	private int[]  bd;
	private int[]  savbd;
	public  int[]  dir;       // the 4 direction offsets
	public  int[]  dia;       // the 4 diagonal offsets
	private int[]  valid;     // convenient list of valid points
	private int[]  v;         // used to track valid moves in playouts.
	public  int[]  ulst;
	private double komi = 7.5;
	private double defaultKomi = 7.5;
	private int    defaultBoardSize = 9;
	private int    MAX_PLAYOUT_PLY;
	
	private static int  CAP1 = 1024;
	private static int  CAP2 = 2048;
	private static int  MASK = 1023;         // applied to move
	// private static int  NON_MOVE = 0xFFFE;
	private static int  FLAG = 64;           // used for marking board 
	private int[]  hits;
	private int[]  wins;
	
	public  double  final_search_score;
	public  long    final_search_nodes;
  
	private string fileLetters = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
	
	
	private static Random rng;// = new Random();
	
	
	public void setBoardSize(int size)
	{
		N = size;
		NN = size * size;    // useful to have around
		N1 = size + 1;       // useful to have around
		N2 = size + 2;       
		NNN = (size + 1) * (size + 2) + 1;
		
		
		MAX_PLAYOUT_PLY = NN * 3;
		
		hits = new int[NNN];
		wins = new int[NNN];
		
		bd = new int[NNN];
		savbd = new int[NNN];
		
		v = new int[NN];
		valid = new int[NN];
		mvs = new int[NNN * 4];
		key = new long[NNN * 4];
		
		ulst = new int[NN + 2];
		
		ctm = 0;
		
		for (int i=0; i<NNN; i++) bd[i] = 4;
		
		int ix = 0;
		for (int f=0; f<N; f++)
	    for (int r=0; r<N; r++) {
				bd[ (r+1)*N1+f+1] = 0;
				v[ix] = (r+1)*N1+f+1;
				valid[ix++] = (r+1)*N1+f+1;
	    }
		
		dir = new int[4];
		dir[0] = 1;
		dir[1] = -1;
		dir[2] = N1;
		dir[3] = -N1;
		
		dia = new int[4];
		dia[0] = N;
		dia[1] = -N;
		dia[2] = N2;
		dia[3] = -N2;
	}
	
	//public this()
	public void init()
	{
		setBoardSize(defaultBoardSize);
		setKomi(defaultKomi);
	}
	
	
	public void setKomi( double k )
	{
		komi = k;
	}
	
	
	/* ------------------------
		 Use this for debugging
		 ------------------------ */
	public void display()
	{
		for (int r=0; r<N; r++) {
	    writefln("");
	    for (int f=0; f<N; f++) {
				int c = bd[ (r+1)*N1+f+1];
				switch (c) {
				case 0 : writef(" -"); break;
				case 1 : writef(" O"); break;
				case 2 : writef(" #"); break;
				}
				
	    }
		}
		writefln("\n\n");
	}
	
	
	/* ---------------------------------------------------
		 capture() - For a given target this method removes
		 all stones belonging to target color in same chain
		 and returns the number of stones removed.
		 --------------------------------------------------- */
	public int capture(int target)
	{
		int   cc;
		int   col = bd[target];    // target color
		
		ulst[cc++] = target;
		bd[target] |= FLAG;
		
		for (int j=0; j<cc; j++) {
	    int  t = ulst[j];
			
	    for (int d=0; d<4; d++) {
				int  x = t + dir[d];
				
				if (bd[x] == 0) {
					for (int k=0; k<cc; k++) bd[ ulst[k] ] ^= FLAG;
					return 0;
				}
				
				if (bd[x] == col) {
					ulst[cc++] = x;
					bd[x] |= FLAG;
				}
	    }
		}
		
		for (int j=0; j<cc; j++) bd[ ulst[j] ] = 0;
		return( cc );
	}
	
	
	
	/* -------------------------------------------------
		 gotlibs - returns true or false if target stone
		 group has at least 1 liberty.    Used for testing
		 suicide. 
		 ------------------------------------------------- */
	public bool gotLibs(int target)
	{
		int      cc;
		int      col = bd[target];    // target color
		
		ulst[cc++] = target;
		bd[ target ] |= FLAG;
		
		for (int j=0; j<cc; j++) {
	    int  t = ulst[j];
			
	    for (int d=0; d<4; d++) {
				int  x = t + dir[d];
				
				if (bd[x] == 0) { // no capture
					for (int k=0; k<cc; k++) bd[ ulst[k] ] ^= FLAG;
					return true;
				} else if (bd[x] == col) {
					ulst[cc++] = x;
					bd[x] |= FLAG;
				}
	    }
		}
		
		for (int j=0; j<cc; j++) bd[ ulst[j] ] ^= FLAG;
		return false;
	}
	
	
	
	/* -------------------------------------------------------------
		 eyeMove(mv) - determine if candiate move would be filling a 
		 one point eye - a move forbidden by this program!
		 
		 definition of eye:
		 
		 an empty point whose orthogonal neighbors are all of the
		 same color AND whose diagonal neighbors contain no more
		 than 1 stone of the opposite color unless it's a border
		 in which case no diagonal enemies are allowed.
		 ------------------------------------------------------------- */
	bool eyeMove(int mv)
	{
		int    fstone = 2 - (ctm & 1);   // friendly stone
		int    estone = fstone ^ 3;      // enemy stone
		int    edge;
		int    enemies;
		
		if (mv == 0) return false;
		
		for (int d=0; d<4; d++) {
	    int x = mv + dir[d];
	    if (bd[x] == 4) continue;
	    if (bd[x] != fstone) return false;
		}
		
		for (int d=0; d<4; d++) {
	    int x = mv + dia[d];
	    
	    if (bd[x] == 4)  {
				edge = 1;
	    } else if (bd[x] == estone) {
				enemies++;
	    }
		}
		
		if (enemies + edge < 2) return true;
		return false;
	}
	
  
	bool vetoMove(int mv)
	{
		int[5] s; // default init to all zeros
		
		for (int d=0; d<4; d++) {
	    int x = mv + dir[d];
	    s[ bd[x] ]++;
			
	    x = mv + dia[d];
	    s[ bd[x] ]++;
		}
		
		if ( s[4] > 0 && s[1] == 0 && s[2] == 0 )  return true;
		
		return false;
	}
	
	
	
	/* -------------------------------------------------------
		 playout() - do 1 playout. 
		 
		 returns score from initiating players point of view
		 taking komi into consideration where: 
		 
		 -1  -> initial player loses
	   0  -> initial player draws (must be integer komi)
	   1  -> initial player wins
		 
		 ALSO, tracks results by move in hits[] and wins[]
		 ---------------------------------------------------- */
	int playout()
	{
		int tp;  // total points that are relevant (empty points)
		int cp;  // current pointer into move list
		int pc;  // pass counter
		
		// save current state so we can restore when done
		copy(bd, savbd);
		savctm=ctm;
		
		// we only care about empty points, gather them up
		for (int j=0; j<NN; j++) 
	    if (bd[valid[j]] == 0)
				v[tp++] = valid[j];
		
		do {                      // do {...} while (ctm < MAX_PLAYOUT_PLY);
	    int  i=void;
			
	    // step 1:  find a move to play
	    // -------
	    for (i=cp; i<tp; i++) {
				int r = uniform(rng,i,tp);   // random point in list
				int mv = v[r];
				int err;
				
				// swap random point with current point
				v[r] = v[i];
				v[i] = mv;
				
				if (eyeMove(mv)) continue;   // ignore eye moves
				// if (vetoMove(mv)) continue;   // ignore special kinds of moves
				
				err = make( mv );
				
				if (err >= 0) {
					// if this is a capture, regather empty points
					if (err > 0) {
						tp=0;
						cp=0;
						i = 0;
						for (int j=0; j<NN; j++) 
							if (bd[valid[j]] == 0)
								v[tp++] = valid[j];
						break;
					} else {
						v[i] = v[cp];
						cp++;
						break;
					}
				}
	    }
			
			
	    if (i==tp) {
				make(0);
				pc++;     // this is a pass
				if (pc == 2) break;
	    } else {
				pc = 0;   // not a pass, reset
	    }
			
		} while (ctm < MAX_PLAYOUT_PLY);
		
		/*
	  // I have never seen this happen, but I'm assured it can
		
	  if (ctm >= MAX_PLAYOUT_PLY) {
		writefln( "HEY, maximum playout length reached\n" );
	  }
		
		*/
		
		
		final_search_nodes += ctm - savctm;    // stats on nodes searched
		
		int sc = easyChinese();
		
		if (sc > komi) sc = 1; else if (sc < komi) sc = -1; else sc = 0;
		
		// view score from point of view of initiating player
		if ((savctm & 1)==1) sc = -sc;   
		
		
		// Track win statistics using AMAF - (All Moves As First)
		// ------------------------------------------------------
		for (int i=savctm; i<ctm; i+=2) {
	    bool ok = true;                // ok to use this move?
	    int mv = mvs[i] & MASK;
			
	    // see if either side has used this move before
	    for (int j=savctm; j<i; j++) {
				if ( (mvs[j] & MASK) == mv ) {
					ok = false;
					break;
				}
	    }
			
	    if (ok) {
				wins[ mv ] += sc;
				hits[ mv ] ++;
	    }
		}
		
		
		// unsave starting state
		copy(savbd, bd);
		ctm=savctm;
		
		return sc;
	}
	
	
	/* ------------------------------------------------------
		 genmove(level) - generate a move based on level passed
		 and returns that move in gtp string format.
		 ------------------------------------------------------ */
	public string genmove(int level)
	{
		double bsc = -99.0;
		int    bmv;
		int    tsc;
		
		final_search_score = 0.0;
		final_search_nodes = 0;
		
		
		// clear statistics from previous moves
		// ------------------------------------
		for (int i=0; i<NNN; i++) {
	    wins[i] = 0;
	    hits[i] = 0;
		}
		
		
		for (int i=0; i<level; i++)  { tsc += playout(); }
		
		// writefln( "tsc = %d\n", tsc );
		
		final_search_score = 0.5 + ( tsc / cast(double) level ) * 0.5;
		
		
		bmv = 0;   // default move is pass if nothing else found
		
		// Shuffle the list before picking a move
		int[] mvlist = valid.dup;
		shuffle(mvlist);
		
		for(int i=0;i<mvlist.length; i++) {
			int mv = mvlist[i];
			if (!eyeMove(mv) && legalMove(mv) && hits[mv] > 0) {
				double sc = wins[mv] / cast(double) (hits[mv]);
				if (sc > bsc) {
					bmv = mv;
					bsc = sc;
				}
			}
		}
		
		// writefln("score = %8.4f\n", bsc );
		
		if (bmv==0) return "pass";
		
		int  col = (bmv % N1) - 1;
		int  row = (bmv / N1) - 1;
		
		char c = fileLetters[col];
		int  r = N  - row;
		
		string vertex = to!(string)(c) ~ to!(string)(r);
		return( vertex );
	}
	
	
	
	/* ------------------------------------------------------------------
		 easyChinese() - gets chinese score.  
     
		 NOTE: This function ASSUMES game is played out to bitter end where 
		 there are never more than single point eyes. 
		 ------------------------------------------------------------------- */
	int easyChinese()
	{
		int[4]  sc; // default initialized to zero
		
		for (int i=0; i<NN; i++) {
	    int  mv = valid[i];
	    int   c = bd[ mv ];
	    
	    if (c != 0) {
				sc[c]++;
	    } else {
				int  types=0;
				for (int d=0; d<4; d++) types |= bd[ mv + dir[d] ];
				sc[types & 3]++;
	    }
		}
		
		return( sc[2] - sc[1] );
	}
	
	
	
	
	/* --------------------------------------------------------
		 legalMove - determine if a move is fully legal INCLUDING
		 positional superko.   Expects move in internal format.
		 
		 Does not change the position. 
		 
		 NOTE: only works if hash key list is maintained.
		 -------------------------------------------------------- */
	public bool legalMove( int mv )
	{
		key[ctm] = hash();
		if (mv == 0) return true;
		
		if (mv != 0) {
	    for (int i=0; i<ctm; i++) {
				if (key[i] == key[ctm]) return false;
	    }
		}
		
		// save current state
		copy(bd, savbd);
		savctm=ctm;
		
		int err = make(mv & MASK); 
		
		// unsave current state
		copy(savbd, bd);
		ctm=savctm;
		
		if (err >= 0) return true; else return false;
	}
	
	
	
	/* --------------------------------------------------------
		 legalMove - determine if a move is fully legal INCLUDING
		 positional superko.   Expects move as a string.
		 
		 Does not change the position. 
		 
		 NOTE: only works if hash key list is maintained.
		 -------------------------------------------------------- */
	public bool legalMove( string smv )
	{
		int  mv;
		
		if (smv == "PASS") {
	    mv = 0;
		} else if (smv == "pass") {
	    mv = 0;
		} else if (smv == "resign") {
	    mv = 0;
		} else {
	    // convert vertex
			int col = find(fileLetters, toupper(smv)[0]);
			int row = N - to!(int)(smv[1..$]);	
			
	    mv = (row+1) * N1 + col + 1;
		}
		
		return legalMove(mv);
	}
	
	
	
  
	/* --------------------------------------------------------
		 make() - tries to make a move and returns a status code.  
		 
		 Does not check for positional superko.
		 Does not destroy the position if the move is not legal.
		 
		 returns:
		 negative value if move is illegal:
		 -1 if move is suicide
		 -2 if move is simple ko violation
	   -3 if point is occupied
		 
		 if legal returns:
		 0 - non-capture move
		 n > 0  - number of stones captured
		 -------------------------------------------------------- */
	public int make(int mv)
	{
		int fstone = 2 - (ctm & 1);
		int estone = fstone ^ 3;
		
		
		if ( mv == 0 ) { mvs[ctm] = 0; ctm++; return 0; }
		if ( bd[mv] != 0 ) { return -3; }
		
		bd[mv] = fstone;
		
		// did we capture opponent?
		int cap = 0;
		for (int d=0; d<4; d++) {
	    int x = mv + dir[d];
			
	    if (bd[x] == estone) {
				cap += capture(x);
	    }
		}
		
		if (cap == 0) { // suicide?
	    if (gotLibs(mv) == false) {
				bd[mv] = 0;  // take back
				return -1;
	    }
	    mvs[ctm] = mv;
		} else {
	    if (cap == 1) {   // simple ko?
				int lm = mvs[ctm-1];   // last move
				
				if ( (lm & CAP1) != 0 ) 
					if ( bd[MASK & lm] == 0 ) {
						bd[MASK & lm] = estone;
						bd[mv] = 0;
						return -2;  // simple ko
					}
				mvs[ctm] = mv | CAP1;
	    } else {
				mvs[ctm] = mv | CAP2;
	    }
		}
		
		ctm++;
		return cap;
	}
	
	
	/* -----------------------------------------------------
		 make() - same as make(int mv) except it expects move
		 in standard string format e.g. "e5", "pass", etc.
		 ----------------------------------------------------- */
	public int make( string smv )
	{
		int  mv;
		
		if (smv == "PASS") {
	    mv = 0;
		} else 	if (smv == "pass") {
	    mv = 0;
		} else if (smv == "resign") {
	    mv = 0;
		} else {
	    // convert vertex
			int col = find(fileLetters, toupper(smv)[0]);
			int row = N - to!(int)(smv[1..$]);
			
	    mv = (row+1) * N1 + col + 1;
		}
		return make(mv);
	}
	
	
	/* ------------------------------------------------------------
		 get a hash of current position - calculating from scratch
		 
		 Note: this is DJB hash which was desgiend for 32 bits even
		 though we are using it as a 64 bit hash
     
		 Should be using the superior zobrist hash but I'm lazy, 
		 this is easier, and performance is not an issue the way it's
		 used here.
		 ------------------------------------------------------------ */
	public long hash()
	{
		long k = 5381;
		
		foreach (int i; bd ) {
	    k = ((k << 5) + k) + cast(long)i;
		}
		
		return k;
	}


}
module tangoshuffle;

import phobosrandom;

// This file is covered under the BSD license
// and is copyright Sean Kelly
// It was copied from the Tango libraries

struct RandOper()
{
	static size_t opCall( size_t lim )
	{
		// NOTE: The use of 'max' here is intended to eliminate modulo bias
		//       in this routine.
		size_t max = size_t.max - (size_t.max % lim);
		size_t val;
		
		do
			{
				static if( size_t.sizeof == 4 )
					{
						val = (((cast(size_t)rand()) << 16) & 0xffff0000u) |
							(((cast(size_t)rand()))       & 0x0000ffffu);
					}
				else // assume size_t.sizeof == 8
					{
						val = (((cast(size_t)rand()) << 48) & 0xffff000000000000uL) |
							(((cast(size_t)rand()) << 32) & 0x0000ffff00000000uL) |
							(((cast(size_t)rand()) << 16) & 0x00000000ffff0000uL) |
							(((cast(size_t)rand()))       & 0x000000000000ffffuL);
					}
			} while( val > max );
		return val % lim;
	}
}

template shuffle_( Elem, Oper )
{
	void fn( Elem[] buf, Oper oper )
	{
		// NOTE: Indexes are passed instead of references because DMD does
		//       not inline the reference-based version.
		void exch( size_t p1, size_t p2 )
		{
			Elem t  = buf[p1];
			buf[p1] = buf[p2];
			buf[p2] = t;
		}
		
		for( size_t pos = buf.length - 1; pos > 0; --pos )
			{
				exch( pos, oper( pos + 1 ) );
			}
	}
}

// Slight modificaiton from Tango: Buf changed to T or T[]...
template shuffle( T, Oper = RandOper!() )
{
	void shuffle( T[] buf, Oper oper = Oper.init )
	{
		return shuffle_!(T, Oper).fn( buf, oper );
	}
}
_______________________________________________
computer-go mailing list
[email protected]
http://www.computer-go.org/mailman/listinfo/computer-go/

Reply via email to