Exemplo n.º 1
0
    def solve(self, ns=10, return_eigenvectors=True):
        """
        Solves (i.e. find the low energy eigenstates) of a certain spin system
        with a given z component of spin.

        Parameters
        ----------
        ns : int
            number of states
        functional : boolean
            Use functional or matrix representation of the Hamiltonian
        return_eigenvectors: boolean
            Return the eigenvectors along with the ..
        """
        # what are trying to deal with?
        systemsize = (util.choose(self.n, self.nu) *
                      util.choose(self.n, self.nd) * 80)

        # what resources do we have
        svmem = psutil.virtual_memory()
        mcap = np.floor(svmem.free / systemsize)
        cap = 2 * mcap if self.humo.real else mcap

        # construct the best solution to the problem
        functional = False

        if cap < 2:
            print('Error. Not enough free virtual memory for \
                   exact diagonalization of this system')
            sys.exit('Not enough memory')

        if cap < ns:
            # Solve
            util.message('cap<ns', verbal)
            ns = np.max(cap - 2, 1)
            functional = True

        if cap < 40:
            util.message('cap40', verbal)
            functional = True

        self.lita, H = SzState.hamiltonian(self.humo,
                                           self.nu + self.nd,
                                           self.nu,
                                           functional=functional)

        if functional:  # functional definition
            Nu, Nd = self.lita.Ns
            HTu, HTd, HU = H
            H = slinalg.LinearOperator(
                (Nu * Nd, Nu * Nd),
                dtype=HTu.dtype,
                matvec=lambda v: lanczos.Hv(HTu, HTd, HU, v))

        self.w, self.v = diagonalize(H,
                                     k=min(ns,
                                           np.prod(self.lita.Ns) - 1),
                                     return_eigenvectors=return_eigenvectors)

        return self.w, self.v
Exemplo n.º 2
0
def place_actions(state: risk.PlaceState) -> Actions:
    num_territories = sum(1 for _ in state.territories_owned(state.current_player))
    num_reinforcements = state.reinforcements(state.current_player)

    action_space_len = int(
        sum(
            util.choose(num_territories, n) * util.choose(num_reinforcements - 1, n - 1)
            for n in range(1, min(num_territories, num_reinforcements))))

    territories_owned = [t.name for t in state.territories_owned(state.current_player)]
    reinforcements = state.reinforcements(state.current_player)
    max_n = min(len(territories_owned), reinforcements)

    def sample(n):
        actions = []
        while len(actions) < n:
            n = random.randint(1, max_n)
            combo_i = random.randint(0, util.choose(len(territories_owned), n) - 1)
            alloc_i = random.randint(0, util.choose(reinforcements - 1, n - 1) - 1)
            combo = util.kth_n_combination(territories_owned, n, combo_i)
            alloc = util.kth_n_integer_composition(reinforcements, n, alloc_i)
            action = risk.Place(combo, alloc)
            if action not in actions:
                yield action
                actions.append(action)

    def _iter():
        for n in range(1, max_n):
            for terrs in itertools.combinations(territories_owned, n):
                for troops in util.integer_compositions(reinforcements, n):
                    yield risk.Place(terrs, troops)

    return Actions(sample, _iter, action_space_len)
Exemplo n.º 3
0
 def run_config():
     config = {}
     images = EC2MPI.ec2.get_all_images(owners=USER_ID)
     # Choose the architecture
     arch = util.choose(["i386", "x86_64"], "Choose architecture")
     for image in images:
         if image.architecture == arch:
             config["ami"] = image.id
     # Choose architecture
     if arch == "i386":
         config["instance_type"] = util.choose(["m1.small", "c1.medium"], "Choose instance size")
     elif arch == "x86_64":
         config["instance_type"] = util.choose(["m1.large", "m1.xlarge", "c1.xlarge"], "Choose instance size")
     else:
         print "Sorry, bad arch"
         sys.exit()
     # Choose the number of instances
     config["max_count"] = util.choose([2, 4, 8, 16, 32, 64, 128, 256], "Number of instances")
     # If this is a large cluster, set the min at 80% of the requested
     if config["max_count"] > 32:
         config["min_count"] = int(0.8 * config["count"])
     else:
         config["min_count"] = config["max_count"]
     # Choose the SSH key to use
     available_keys = EC2MPI.get_mpi_keys()
     if len(available_keys) == 0:
         print "You don't have any keys, creating one now"
         config["mpi_key"] = EC2MPI.gen_mpi_key()
     else:
         available_keys += ["Create a new key"]
         mpi_key = util.choose(available_keys, "Choose a key to use for MPI communication")
     if mpi_key == "Create a new key":
         config["mpi_key"] = EC2MPI.gen_mpi_key()
     else:
         config["mpi_key"] = mpi_key
     rand_name = EC2MPI.rand_name()
     cluster_name = raw_input("Name this cluster (q to Quit) [%s]: " % rand_name)
     while 1:
         if cluster_name == u"q":
             sys.exit()
         if cluster_name == u"":
             cluster_name = rand_name
         if EC2MPI.domain.get_item(cluster_name):
             print "Name is already taken"
             rand_name = EC2MPI.rand_name()
             cluster_name = raw_input("Name this cluster (q to Quit) [%s]: " % rand_name)
         else:
             config["name"] = cluster_name
             break
     config["status"] = "config"
     config["reservation"] = ""
     config["s3_bucket"] = S3_BUCKET
     config["mpi_bucket"] = md5.new(config["name"]).hexdigest()
     config["placement"] = "us-east-1a"
     return config
Exemplo n.º 4
0
 def sample(n):
     actions = []
     while len(actions) < n:
         n = random.randint(1, max_n)
         combo_i = random.randint(0, util.choose(len(territories_owned), n) - 1)
         alloc_i = random.randint(0, util.choose(reinforcements - 1, n - 1) - 1)
         combo = util.kth_n_combination(territories_owned, n, combo_i)
         alloc = util.kth_n_integer_composition(reinforcements, n, alloc_i)
         action = risk.Place(combo, alloc)
         if action not in actions:
             yield action
             actions.append(action)
Exemplo n.º 5
0
def computeMeanPairwiseHammingDistance(result, clusterIndices, clusterIndexToProfileMap=None):
    '''
    clusterIndices: list of indices for which pairs are created.
    clusterIndexToProfileMap: a map from cluster index to precomputed cluster profiles.
    if there are more clusterIndices than the TERM_PROMISCUITY_LIMIT, return None.
    if there is only one cluster index, return 0.
    otherwise, return the mean of the hamming distances of every pair of clusterIndices.  n choose 2 pairs.
    '''
    numClusters = len(clusterIndices)
    # ignore terms associated with many clusters on the assumption that they are too general to be interesting.
    if numClusters > TERM_PROMISCUITY_LIMIT:
        return None
    numPairs = 0
    totalHammingDistance = 0
    for indexPair in util.choose(clusterIndices, 2):
        numPairs += 1
        # hamming distance is the number of differences in two equal length bit strings.
        if clusterIndexToProfileMap:
            profile0 = clusterIndexToProfileMap[indexPair[0]]
            profile1 = clusterIndexToProfileMap[indexPair[1]]
        else:
            profile0 = getProfileForCluster(result['rows'][indexPair[0]])
            profile1 = getProfileForCluster(result['rows'][indexPair[1]])
        totalHammingDistance += hammingDistanceForProfiles(profile0, profile1)
    if numPairs > 0:
        meanPairwiseHammingDistance = totalHammingDistance / float(numPairs)
    else:
        meanPairwiseHammingDistance = 0
    return meanPairwiseHammingDistance
Exemplo n.º 6
0
def test_choose_with_known_examples():
    examples = {
        (0, 0): 1,
        (0, 1): 0,
        (1, 0): 1,
        (4, 2): 6,
        (2, 4): 0,
        (10, 3): 120
    }
    for ((n, k), expected) in examples.items():
        assert util.choose(n, k) == expected
    def _react(self, action):
        state = util.choose( self.P[ action ][ self.state ] )
        reward = self.R.get( (self.state, state), 0 ) + self.R_bias

        # If there is no way to get out of this state, the episode has ended
        if self.end_set is not None:
            episode_ended = state in self.end_set 
        else:
            episode_ended = len( self.Q[ state ] ) == 0

        if episode_ended:
            state = self._start()
        self.state = state

        return state, reward, episode_ended
def choose_small_world( path_lengths, s, r ):
    # Check distances
    dists = path_lengths[s][1]
    if s in dists: dists.pop( s )
    if not dists: return None

    neighbours, dists = zip( *dists.items() )
    # Create a pr distribution
    dists = np.power( np.array( dists, dtype=float ), -r )
    # Zero out neighbours
    for i in xrange( len( dists ) ):
        if dists[i] == 1: dists[i] = 0

    if not dists.any(): 
        return None

    s_ = util.choose( zip( neighbours, dists ) )
    return s_
Exemplo n.º 9
0
def choose_small_world(path_lengths, s, r):
    # Check distances
    dists = path_lengths[s][1]
    if s in dists: dists.pop(s)
    if not dists: return None

    neighbours, dists = zip(*dists.items())
    # Create a pr distribution
    dists = np.power(np.array(dists, dtype=float), -r)
    # Zero out neighbours
    for i in xrange(len(dists)):
        if dists[i] == 1: dists[i] = 0

    if not dists.any():
        return None

    s_ = util.choose(zip(neighbours, dists))
    return s_
Exemplo n.º 10
0
def makePairsForGenomeParams(genome=None, limit_genomes=None, genomes=None):
        # all genomes
        allGenomes = []
        if genome:
            allGenomes.append(genome)
        if genomes:
            allGenomes.extend(genomes)
        if limit_genomes:
            allGenomes.extend(limit_genomes)
        allGenomes = list(set(allGenomes))
        # all pairs of genomes
        pairs = roundup_common.normalizePairs(util.choose(allGenomes, 2))
        if genome:
            pairs = [pair for pair in pairs if pair[0] == genome or pair[1] == genome]
        if limit_genomes:
            pairs = [pair for pair in pairs if pair[0] in limit_genomes or pair[1] in limit_genomes]
        if genomes:
            pairs = [pair for pair in pairs if pair[0] in genomes and pair[1] in genomes]
        return pairs
Exemplo n.º 11
0
 def get_next_price(self, price, timestep):
     return choose(self.future_prices_and_probabilities(price, timestep))
Exemplo n.º 12
0
 def get_next_state(self, state, action, timestep):
     return choose(
         self.future_states_probabilities(from_state=state, action=action))
Exemplo n.º 13
0
def p15(n=20, m=20):
    print choose(n+n,n)
Exemplo n.º 14
0
import sys

from bitarray import bitarray

from util import choose, encode_ordinal

if __name__ == "__main__":
    rank_count = int(sys.argv[1])

    first_seed = bitarray(endian="little")
    first_seed.frombytes(bytes.fromhex(sys.argv[2]))

    second_seed = bitarray(endian="little")
    second_seed.frombytes(bytes.fromhex(sys.argv[3]))

    errors = first_seed ^ second_seed
    ordinal = encode_ordinal(errors)
    binom = choose(errors.length(), errors.count())

    print("First Seed: ", first_seed.tobytes().hex())
    print("Second Seed:", second_seed.tobytes().hex())
    print("Difference:", errors.tobytes().hex())
    print("Difference Count:", errors.count())
    print("Combination Ordinal:", ordinal)
    print("Total Combinations:", binom)
    print("Rank Responsibility:", (ordinal * rank_count) // binom)
Exemplo n.º 15
0
def p15(n=20, m=20):
    print choose(n + n, n)
Exemplo n.º 16
0
 def act( self, state ):
     action = util.choose( self.pi[ state ] )
     return action