<commit_before>from __future__ import print_function, division, absolute_import

from functools import partial
import itertools
from itertools import chain, product, starmap
import sys

import numpy as np

from numba import unittest_support as unittest
from numba import jit, typeof, utils, TypingError
from .support import TestCase, MemoryLeakMixin

def slice_passing(sl):
    return sl.start, sl.stop, sl.step

def slice_constructor(*args):
    sl = slice(*args)
    return sl.start, sl.stop, sl.step

def slice_construct_and_use(args, l):
    sl = slice(*args)
    return l[sl]

def slice_indices(s, *indargs):
    return s.indices(*indargs)

class TestSlices(MemoryLeakMixin, TestCase):

    def test_slice_passing(self):
        """
        Check passing a slice object to a Numba function.
        """
        # NOTE this also checks slice attributes
        def check(a, b, c, d, e, f):
            sl = slice(a, b, c)
            got = cfunc(sl)
            self.assertPreciseEqual(got, (d, e, f))

        maxposint = sys.maxsize
        maxnegint = -maxposint - 1
        cfunc = jit(nopython=True)(slice_passing)

        # Positive steps
        start_cases = [(None, 0), (42, 42), (-1, -1)]
        stop_cases = [(None, maxposint), (9, 9), (-11, -11)]
        step_cases = [(None, 1), (12, 12)]
        for (a, d), (b, e), (c, f) in itertools.product(start_cases,
                                                        stop_cases,
                                                        step_cases):
            check(a, b, c, d, e, f)

        # Negative steps
        start_cases = [(None, maxposint), (42, 42), (-1, -1)]
        stop_cases = [(None, maxnegint), (9, 9), (-11, -11)]
        step_cases = [(-1, -1), (-12, -12)]
        for (a, d), (b, e), (c, f) in itertools.product(start_cases,
                                                        stop_cases,
                                                        step_cases):
            check(a, b, c, d, e, f)

        # Some member is neither integer nor None
        with self.assertRaises(TypeError):
            cfunc(slice(1.5, 1, 1))

    def test_slice_constructor(self):
        """
        Test the 'happy path' for slice() constructor in nopython mode.
        """
        maxposint = sys.maxsize
        maxnegint = -maxposint - 1
        a = np.arange(10)
        cfunc = jit(nopython=True)(slice_constructor)
        cfunc_use = jit(nopython=True)(slice_construct_and_use)
        for args, expected in [
            ((None,), (0, maxposint, 1)),
            ((5,), (0, 5, 1)),
            ((None, None), (0, maxposint, 1)),
            ((1, None), (1, maxposint, 1)),
            ((None, 2), (0, 2, 1)),
            ((1, 2), (1, 2, 1)),
            ((None, None, 3), (0, maxposint, 3)),
            ((None, 2, 3), (0, 2, 3)),
            ((1, None, 3), (1, maxposint, 3)),
            ((1, 2, 3), (1, 2, 3)),
            ((None, None, -1), (maxposint, maxnegint, -1)),
            ((10, None, -1), (10, maxnegint, -1)),
            ((None, 5, -1), (maxposint, 5, -1)),
            ((10, 5, -1), (10, 5, -1)),
        ]:
            got = cfunc(*args)
            self.assertPreciseEqual(got, expected)
            usage = slice_construct_and_use(args, a)
            cusage = cfunc_use(args, a)
            self.assertPreciseEqual(usage, cusage)

    def test_slice_constructor_cases(self):
        """
        Test that slice constructor behaves same in python and compiled code.
        """
        options = (None, -1, 0, 1)
        arg_cases = chain.from_iterable(
            product(options, repeat=n) for n in range(5)
        )
        array = np.arange(10)

        cfunc = jit(nopython=True)(slice_construct_and_use)

        self.disable_leak_check()
        for args in arg_cases:
            try:
                expected = slice_construct_and_use(args, array)
            except TypeError as py_type_e:
                # Catch cases of 0, or more than 3 arguments.
                # This becomes a typing error in numba
                n_args = len(args)
                self.assertRegexpMatches(
                    str(py_type_e),
                    r"slice expected at (most|least) (3|1) arguments, got {}"
                    .format(n_args)
                )
                with self.assertRaises(TypingError) as numba_e:
                    cfunc(args, array)
            except Exception as py_e:
                with self.assertRaises(type(py_e)) as numba_e:
                    cfunc(args, array)
                self.assertIn(
                    str(py_e),
                    str(numba_e.exception)
                )
            else:
                self.assertPreciseEqual(expected, cfunc(args, array))

    def test_slice_indices(self):
        """Test that a numba slice returns same result for .indices as a python one."""
        slices = starmap(
            slice,
            product(
                chain(range(-5, 5), (None,)),
                chain(range(-5, 5), (None,)),
                chain(range(-5, 5), (None,))
            )
        )
        lengths = range(-2, 3)

        cfunc = jit(nopython=True)(slice_indices)

        for s, l in product(slices, lengths):
            if l < 0 and not utils.IS_PY3:
                # Passing a negative length to slice.indices in python2 is
                # undefined. See https://bugs.python.org/issue14794#msg174678
                continue
            try:
                expected = slice_indices(s, l)
            except Exception as py_e:
                with self.assertRaises(type(py_e)) as numba_e:
                    cfunc(s, l)
                self.assertIn(
                    str(py_e),
                    str(numba_e.exception)
                )
            else:
                self.assertPreciseEqual(expected, cfunc(s, l))

    def test_slice_indices_examples(self):
        """Tests for specific error cases."""
        cslice_indices = jit(nopython=True)(slice_indices)

        with self.assertRaises(TypingError) as e:
            cslice_indices(slice(None), 1, 2, 3)
        self.assertIn(
             "indices() takes exactly one argument (3 given)",
             str(e.exception)
        )

        with self.assertRaises(TypingError) as e:
            cslice_indices(slice(None, None, 0), 1.2)
        self.assertIn(
            "'%s' object cannot be interpreted as an integer" % typeof(1.2),
            str(e.exception)
        )

if __name__ == '__main__':
    unittest.main()
<commit_msg>Test contents of slice constructor error<commit_after>from __future__ import print_function, division, absolute_import

from functools import partial
import itertools
from itertools import chain, product, starmap
import sys

import numpy as np

from numba import unittest_support as unittest
from numba import jit, typeof, utils, TypingError
from .support import TestCase, MemoryLeakMixin

def slice_passing(sl):
    return sl.start, sl.stop, sl.step

def slice_constructor(*args):
    sl = slice(*args)
    return sl.start, sl.stop, sl.step

def slice_construct_and_use(args, l):
    sl = slice(*args)
    return l[sl]

def slice_indices(s, *indargs):
    return s.indices(*indargs)

class TestSlices(MemoryLeakMixin, TestCase):

    def test_slice_passing(self):
        """
        Check passing a slice object to a Numba function.
        """
        # NOTE this also checks slice attributes
        def check(a, b, c, d, e, f):
            sl = slice(a, b, c)
            got = cfunc(sl)
            self.assertPreciseEqual(got, (d, e, f))

        maxposint = sys.maxsize
        maxnegint = -maxposint - 1
        cfunc = jit(nopython=True)(slice_passing)

        # Positive steps
        start_cases = [(None, 0), (42, 42), (-1, -1)]
        stop_cases = [(None, maxposint), (9, 9), (-11, -11)]
        step_cases = [(None, 1), (12, 12)]
        for (a, d), (b, e), (c, f) in itertools.product(start_cases,
                                                        stop_cases,
                                                        step_cases):
            check(a, b, c, d, e, f)

        # Negative steps
        start_cases = [(None, maxposint), (42, 42), (-1, -1)]
        stop_cases = [(None, maxnegint), (9, 9), (-11, -11)]
        step_cases = [(-1, -1), (-12, -12)]
        for (a, d), (b, e), (c, f) in itertools.product(start_cases,
                                                        stop_cases,
                                                        step_cases):
            check(a, b, c, d, e, f)

        # Some member is neither integer nor None
        with self.assertRaises(TypeError):
            cfunc(slice(1.5, 1, 1))

    def test_slice_constructor(self):
        """
        Test the 'happy path' for slice() constructor in nopython mode.
        """
        maxposint = sys.maxsize
        maxnegint = -maxposint - 1
        a = np.arange(10)
        cfunc = jit(nopython=True)(slice_constructor)
        cfunc_use = jit(nopython=True)(slice_construct_and_use)
        for args, expected in [
            ((None,), (0, maxposint, 1)),
            ((5,), (0, 5, 1)),
            ((None, None), (0, maxposint, 1)),
            ((1, None), (1, maxposint, 1)),
            ((None, 2), (0, 2, 1)),
            ((1, 2), (1, 2, 1)),
            ((None, None, 3), (0, maxposint, 3)),
            ((None, 2, 3), (0, 2, 3)),
            ((1, None, 3), (1, maxposint, 3)),
            ((1, 2, 3), (1, 2, 3)),
            ((None, None, -1), (maxposint, maxnegint, -1)),
            ((10, None, -1), (10, maxnegint, -1)),
            ((None, 5, -1), (maxposint, 5, -1)),
            ((10, 5, -1), (10, 5, -1)),
        ]:
            got = cfunc(*args)
            self.assertPreciseEqual(got, expected)
            usage = slice_construct_and_use(args, a)
            cusage = cfunc_use(args, a)
            self.assertPreciseEqual(usage, cusage)

    def test_slice_constructor_cases(self):
        """
        Test that slice constructor behaves same in python and compiled code.
        """
        options = (None, -1, 0, 1)
        arg_cases = chain.from_iterable(
            product(options, repeat=n) for n in range(5)
        )
        array = np.arange(10)

        cfunc = jit(nopython=True)(slice_construct_and_use)

        self.disable_leak_check()
        for args in arg_cases:
            try:
                expected = slice_construct_and_use(args, array)
            except TypeError as py_type_e:
                # Catch cases of 0, or more than 3 arguments.
                # This becomes a typing error in numba
                n_args = len(args)
                self.assertRegexpMatches(
                    str(py_type_e),
                    r"slice expected at (most|least) (3|1) arguments, got {}"
                    .format(n_args)
                )
                with self.assertRaises(TypingError) as numba_e:
                    cfunc(args, array)
                self.assertIn(
                    "Invalid use of Function",
                    str(numba_e.exception)
                )
                self.assertIn(
                    ", ".join(str(typeof(arg)) for arg in args),
                    str(numba_e.exception)
                )
            except Exception as py_e:
                with self.assertRaises(type(py_e)) as numba_e:
                    cfunc(args, array)
                self.assertIn(
                    str(py_e),
                    str(numba_e.exception)
                )
            else:
                self.assertPreciseEqual(expected, cfunc(args, array))

    def test_slice_indices(self):
        """Test that a numba slice returns same result for .indices as a python one."""
        slices = starmap(
            slice,
            product(
                chain(range(-5, 5), (None,)),
                chain(range(-5, 5), (None,)),
                chain(range(-5, 5), (None,))
            )
        )
        lengths = range(-2, 3)

        cfunc = jit(nopython=True)(slice_indices)

        for s, l in product(slices, lengths):
            if l < 0 and not utils.IS_PY3:
                # Passing a negative length to slice.indices in python2 is
                # undefined. See https://bugs.python.org/issue14794#msg174678
                continue
            try:
                expected = slice_indices(s, l)
            except Exception as py_e:
                with self.assertRaises(type(py_e)) as numba_e:
                    cfunc(s, l)
                self.assertIn(
                    str(py_e),
                    str(numba_e.exception)
                )
            else:
                self.assertPreciseEqual(expected, cfunc(s, l))

    def test_slice_indices_examples(self):
        """Tests for specific error cases."""
        cslice_indices = jit(nopython=True)(slice_indices)

        with self.assertRaises(TypingError) as e:
            cslice_indices(slice(None), 1, 2, 3)
        self.assertIn(
             "indices() takes exactly one argument (3 given)",
             str(e.exception)
        )

        with self.assertRaises(TypingError) as e:
            cslice_indices(slice(None, None, 0), 1.2)
        self.assertIn(
            "'%s' object cannot be interpreted as an integer" % typeof(1.2),
            str(e.exception)
        )

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Support for CFFI. Allows checking whether objects are CFFI functions and
obtaining the pointer and numba signature.
"""
from __future__ import print_function, division, absolute_import

from types import BuiltinFunctionType
import ctypes

from numba import types
from . import templates

try:
    import cffi
    ffi = cffi.FFI()
except ImportError:
    ffi = None

SUPPORTED = ffi is not None
_ool_func_types = {}
_ool_func_ptr = {}
_ffi_modules = set()

ffi_module = types.Module(cffi.FFI)

def is_ffi_module(obj):
    # Compiled FFI modules have a member, ffi, which is an instance of
    # CompiledFFI, which behaves similarly to an instance of cffi.FFI. In
    # order to simplify handling a CompiledFFI object, we treat them as
    # if they're cffi.FFI instances for typing and lowering purposes.
    return obj in _ffi_modules or isinstance(obj, cffi.FFI)

def is_cffi_func(obj):
    """Check whether the obj is a CFFI function"""
    try:
        return ffi.typeof(obj).kind == 'function'
    except TypeError:
        try:
            return obj in _ool_func_types
        except:
            return False

def get_pointer(cffi_func):
    """
    Get a pointer to the underlying function for a CFFI function as an
    integer.
    """
    if cffi_func in _ool_func_ptr:
        return _ool_func_ptr[cffi_func]
    return int(ffi.cast("uintptr_t", cffi_func))

_cached_type_map = None

def _type_map():
    """
    Lazily compute type map, as calling ffi.typeof() involves costly
    parsing of C code...
    """
    global _cached_type_map
    if _cached_type_map is None:
        _cached_type_map = {
            ffi.typeof('char') :                types.int8,
            ffi.typeof('short') :               types.short,
            ffi.typeof('int') :                 types.intc,
            ffi.typeof('long') :                types.long_,
            ffi.typeof('long long') :           types.longlong,
            ffi.typeof('unsigned char') :       types.uchar,
            ffi.typeof('unsigned short') :      types.ushort,
            ffi.typeof('unsigned int') :        types.uintc,
            ffi.typeof('unsigned long') :       types.ulong,
            ffi.typeof('unsigned long long') :  types.ulonglong,
            ffi.typeof('int8_t') :              types.char,
            ffi.typeof('uint8_t') :             types.uchar,
            ffi.typeof('int16_t') :             types.short,
            ffi.typeof('uint16_t') :            types.ushort,
            ffi.typeof('int32_t') :             types.intc,
            ffi.typeof('uint32_t') :            types.uintc,
            ffi.typeof('int64_t') :             types.longlong,
            ffi.typeof('uint64_t') :            types.ulonglong,
            ffi.typeof('float') :               types.float_,
            ffi.typeof('double') :              types.double,
            ffi.typeof('char *') :              types.voidptr,
            ffi.typeof('void *') :              types.voidptr,
            ffi.typeof('uint8_t *') :           types.CPointer(types.uint8),
            ffi.typeof('float *') :             types.CPointer(types.float32),
            ffi.typeof('double *') :            types.CPointer(types.float64),
            ffi.typeof('ssize_t') :             types.intp,
            ffi.typeof('size_t') :              types.uintp,
            ffi.typeof('void') :                types.void,
        }
    return _cached_type_map

def map_type(cffi_type):
    """
    Map CFFI type to numba type.
    """
    kind = getattr(cffi_type, 'kind', '')
    if kind in ('struct', 'union'):
        raise TypeError("No support for struct or union")
    elif kind == 'function':
        if cffi_type.ellipsis:
            raise TypeError("vararg function is not supported")
        restype = map_type(cffi_type.result)
        argtypes = [map_type(arg) for arg in cffi_type.args]
        return templates.signature(restype, *argtypes)
    else:
        result = _type_map().get(cffi_type)

    if result is None:
        raise TypeError(cffi_type)

    return result

def make_function_type(cffi_func):
    """
    Return a Numba type for the given CFFI function pointer.
    """
    cffi_type = _ool_func_types.get(cffi_func) or ffi.typeof(cffi_func)
    sig = map_type(cffi_type)
    return types.ExternalFunctionPointer(sig, get_pointer=get_pointer)

class ExternCFunction(types.ExternalFunction):
    # XXX unused?

    def __init__(self, symbol, cstring):
        """Parse C function declaration/signature"""
        parser = cffi.cparser.Parser()
        rft = parser.parse_type(cstring) # "RawFunctionType"
        type_map = _type_map()
        self.restype = type_map[rft.result.build_backend_type(ffi, None)]
        self.argtypes = [type_map[arg.build_backend_type(ffi, None)] for arg in rft.args]
        signature = templates.signature(self.restype, *self.argtypes)
        super(ExternCFunction, self).__init__(symbol, signature)

registry = templates.Registry()

@registry.register
class FFI_from_buffer(templates.AbstractTemplate):
    key = cffi.FFI.from_buffer

    def generic(self, args, kws):
        if kws or (len(args) != 1):
            return
        [ary] = args
        if not (isinstance(ary, types.Array) or ary.layout in ('C', 'F')):
            return
        ptr = types.CPointer(ary.dtype)
        return templates.signature(ptr, ary)

@registry.register_attr
class FFIAttribute(templates.AttributeTemplate):
    key = ffi_module

    def resolve_from_buffer(self, ffi):
        return types.Function(FFI_from_buffer)

def register_module(mod):
    """
    Add typing for all functions in an out-of-line CFFI module to the typemap
    """
    for f in dir(mod.lib):
        f = getattr(mod.lib, f)
        if isinstance(f, BuiltinFunctionType):
            _ool_func_types[f] = mod.ffi.typeof(f)
            addr = mod.ffi.addressof(mod.lib, f.__name__)
            _ool_func_ptr[f] = int(mod.ffi.cast("uintptr_t", addr))
        _ffi_modules.add(mod.ffi)
<commit_msg>Fix is_ffi_module<commit_after># -*- coding: utf-8 -*-
"""
Support for CFFI. Allows checking whether objects are CFFI functions and
obtaining the pointer and numba signature.
"""
from __future__ import print_function, division, absolute_import

from types import BuiltinFunctionType
import ctypes

from numba import types
from . import templates

try:
    import cffi
    ffi = cffi.FFI()
except ImportError:
    ffi = None

SUPPORTED = ffi is not None
_ool_func_types = {}
_ool_func_ptr = {}
_ffi_modules = set()

ffi_module = types.Module(cffi.FFI)

def is_ffi_module(obj):
    # Compiled FFI modules have a member, ffi, which is an instance of
    # CompiledFFI, which behaves similarly to an instance of cffi.FFI. In
    # order to simplify handling a CompiledFFI object, we treat them as
    # if they're cffi.FFI instances for typing and lowering purposes.
    try:
        return obj in _ffi_modules or isinstance(obj, cffi.FFI)
    except TypeError: # Unhashable type possible
        return False

def is_cffi_func(obj):
    """Check whether the obj is a CFFI function"""
    try:
        return ffi.typeof(obj).kind == 'function'
    except TypeError:
        try:
            return obj in _ool_func_types
        except:
            return False

def get_pointer(cffi_func):
    """
    Get a pointer to the underlying function for a CFFI function as an
    integer.
    """
    if cffi_func in _ool_func_ptr:
        return _ool_func_ptr[cffi_func]
    return int(ffi.cast("uintptr_t", cffi_func))

_cached_type_map = None

def _type_map():
    """
    Lazily compute type map, as calling ffi.typeof() involves costly
    parsing of C code...
    """
    global _cached_type_map
    if _cached_type_map is None:
        _cached_type_map = {
            ffi.typeof('char') :                types.int8,
            ffi.typeof('short') :               types.short,
            ffi.typeof('int') :                 types.intc,
            ffi.typeof('long') :                types.long_,
            ffi.typeof('long long') :           types.longlong,
            ffi.typeof('unsigned char') :       types.uchar,
            ffi.typeof('unsigned short') :      types.ushort,
            ffi.typeof('unsigned int') :        types.uintc,
            ffi.typeof('unsigned long') :       types.ulong,
            ffi.typeof('unsigned long long') :  types.ulonglong,
            ffi.typeof('int8_t') :              types.char,
            ffi.typeof('uint8_t') :             types.uchar,
            ffi.typeof('int16_t') :             types.short,
            ffi.typeof('uint16_t') :            types.ushort,
            ffi.typeof('int32_t') :             types.intc,
            ffi.typeof('uint32_t') :            types.uintc,
            ffi.typeof('int64_t') :             types.longlong,
            ffi.typeof('uint64_t') :            types.ulonglong,
            ffi.typeof('float') :               types.float_,
            ffi.typeof('double') :              types.double,
            ffi.typeof('char *') :              types.voidptr,
            ffi.typeof('void *') :              types.voidptr,
            ffi.typeof('uint8_t *') :           types.CPointer(types.uint8),
            ffi.typeof('float *') :             types.CPointer(types.float32),
            ffi.typeof('double *') :            types.CPointer(types.float64),
            ffi.typeof('ssize_t') :             types.intp,
            ffi.typeof('size_t') :              types.uintp,
            ffi.typeof('void') :                types.void,
        }
    return _cached_type_map

def map_type(cffi_type):
    """
    Map CFFI type to numba type.
    """
    kind = getattr(cffi_type, 'kind', '')
    if kind in ('struct', 'union'):
        raise TypeError("No support for struct or union")
    elif kind == 'function':
        if cffi_type.ellipsis:
            raise TypeError("vararg function is not supported")
        restype = map_type(cffi_type.result)
        argtypes = [map_type(arg) for arg in cffi_type.args]
        return templates.signature(restype, *argtypes)
    else:
        result = _type_map().get(cffi_type)

    if result is None:
        raise TypeError(cffi_type)

    return result

def make_function_type(cffi_func):
    """
    Return a Numba type for the given CFFI function pointer.
    """
    cffi_type = _ool_func_types.get(cffi_func) or ffi.typeof(cffi_func)
    sig = map_type(cffi_type)
    return types.ExternalFunctionPointer(sig, get_pointer=get_pointer)

class ExternCFunction(types.ExternalFunction):
    # XXX unused?

    def __init__(self, symbol, cstring):
        """Parse C function declaration/signature"""
        parser = cffi.cparser.Parser()
        rft = parser.parse_type(cstring) # "RawFunctionType"
        type_map = _type_map()
        self.restype = type_map[rft.result.build_backend_type(ffi, None)]
        self.argtypes = [type_map[arg.build_backend_type(ffi, None)] for arg in rft.args]
        signature = templates.signature(self.restype, *self.argtypes)
        super(ExternCFunction, self).__init__(symbol, signature)

registry = templates.Registry()

@registry.register
class FFI_from_buffer(templates.AbstractTemplate):
    key = cffi.FFI.from_buffer

    def generic(self, args, kws):
        if kws or (len(args) != 1):
            return
        [ary] = args
        if not (isinstance(ary, types.Array) or ary.layout in ('C', 'F')):
            return
        ptr = types.CPointer(ary.dtype)
        return templates.signature(ptr, ary)

@registry.register_attr
class FFIAttribute(templates.AttributeTemplate):
    key = ffi_module

    def resolve_from_buffer(self, ffi):
        return types.Function(FFI_from_buffer)

def register_module(mod):
    """
    Add typing for all functions in an out-of-line CFFI module to the typemap
    """
    for f in dir(mod.lib):
        f = getattr(mod.lib, f)
        if isinstance(f, BuiltinFunctionType):
            _ool_func_types[f] = mod.ffi.typeof(f)
            addr = mod.ffi.addressof(mod.lib, f.__name__)
            _ool_func_ptr[f] = int(mod.ffi.cast("uintptr_t", addr))
        _ffi_modules.add(mod.ffi)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
use 2nd order friedmann equations + the continuity equation
numerically integrate the cosmological equations for standard cosmology where
omega = 1 for matter universe
also
omega = 1 30% matter, 70% dark energy
luminosity distance plots
https://arxiv.org/pdf/astro-ph/9905116.pdf
pl.plot(sampler.flatchain[:,0])
pl.plot(sampler.flatchain[:,1])
pl.plot(sampler.flatchain[:,0],sampler.flatchain[:,1],'.')
interaction term next
>>ODE solver (ODE int)
integrate both scale factor and continuity equation at the same time
change units
use time = 1/h0 and distance c/h0
AND
integrate backwards from today so from 0 ti -t
ok to ask Luke
later : movify to include co-moving distance (Ryden?)
+ Luminosity distance
find out how old a universe with only matter and at
critical density would be today
integrate over time, t0 will be now, where a crosses 0 is the beginning
so find time in years
then tell how a changes with time and the age of the universe in universe with
critical
density today, single fluid an with equation of state w=-1/3
Dodn't always ask what to do
event catcher - stop integration once a reaches 0
put in more than one fluid in the universe
maybe http://www.ni.gsu.edu/~rclewley/PyDSTool/FrontPage.html
m + DE universe (age)
Create plot of omega lambda vs omaga matter across age of universe
0.3 and 0.7 today, what were they in the past
Krysztoff, Luke
[try a_dot as equation and not just a_dot, i.e. ditch a_dotdot, but that is if
the equations are correct. if solver doens't have a problem when feeding data
in at each calculation then a_dot as a_dot and not equation shouldn't matter] -
worked out in the end

what interaction terms could there be?

git test

NOT AN ASSIGNMENT
"""

from scipy.integrate import odeint
import numpy as np
from pylab import figure, plot, xlabel, grid, legend, title
from matplotlib.font_manager import FontProperties

def vectorfield(v, t, w):
    a, a_dot, e_dash_m, e_dash_de, omega0m, omega0de = v
    w_m, w_de = w
    lamb_m = -2e-2 #10
    lamb_de = 2e-2
    # Create f = [a_dot, a_dotdot, e'_dotm, e'_dotde, omegam_dot, omegade_dot]:
    f = [a_dot,
         (-a/2)*(e_dash_m*(1+3*w_m)+e_dash_de*(1+3*w_de)),
         -3*(a_dot/a)*(e_dash_m*(1+w_m+lamb_m/3*a/a_dot)),
         -3*(a_dot/a)*(e_dash_de*(1+w_de+lamb_de/3*a/a_dot)),
         (H0**2)*e_dash_m*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
                           e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
                           (-3*a_dot/a*e_dash_m*(1+w_m)),
         (H0**2)*e_dash_de*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
                            e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
                            (-3*a_dot/a*e_dash_de*(1+w_de))]

    return f

# a past which to discard values, value chosen by looking at the plot
# set arbitrarily - sometimes jumps over the result(?)
a_d = 10e-3

# time in 1/H0 to integrate until, if this time isn't long enough to reach a_d
# then "time" will be added to integration time until a_d is reached
# 0.665 matter only, 0.96 m+de, -0.49
time = 0.6

# Parameters
H0 = 1       # Hubble parameter at t=now
#Dh = c/H0   # Hubble distance
tH = 1.0/H0  # Hubble time
# G = 1
# c = 1

# Eq of state parameter
w_m = 0.0     # matter
w_de = -1.0   # cosmological constant (dark energy)
w_r = 1/3     # radiation

# Initial conditions
# a0 = scale factor, a_dot = speed, e_dash0 = e0/ec0
a0 = 1.0
a_dot0 = 1.0
e_dash0m = 0.3
e_dash0de = 0.7
omega0m = 0.3
omega0de = 0.7

# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
numpoints = 250

stoptime = -time

# Plot the solution
figure()
xlabel('t in 1/H0')
grid(True)
lw = 1

while True:
#    print('stoptime is:',str(stoptime),'1/H0')
    # Create the time samples for the output of the ODE solver.
    t = [stoptime*tH * float(i) / (numpoints - 1) for i in range(numpoints)]

    # Pack up the parameters and initial conditions:
    v0 = [a0, a_dot0, e_dash0m, e_dash0de, omega0m, omega0de]

    w = [w_m, w_de]

    # Call the ODE solver.
    vsol = odeint(vectorfield, v0, t, args=(w,), atol=abserr, rtol=relerr)

    # Remove unwanted results from the plot
    # Separate results into their own arrays
    a = vsol[:,0]
    a_dot = vsol[:,1]
    e_dashm = vsol[:,2]
    e_dashde = vsol[:,3]
    omegam = vsol[:,4]
    omegade = vsol[:,5]

    # Find where results start to get strange
    blowups = np.where(a < a_d)    # tuple with indecies of a
                                   # so small it blows up a_dot
    blowups = np.asarray(blowups)  # converting to np array

    if blowups.any():
        blowup = blowups[0,0]      # first instance of a being too small
    else:
        stoptime -= time
        continue

    # Remove the values after the index when a is too small
    t_cut = np.asarray(t)
    t_cut = t_cut[:blowup]
    a = a[:blowup]
    a_dot = a_dot[:blowup]
    e_dashm = e_dashm[:blowup]
    e_dashde = e_dashde[:blowup]
    omegam = omegam[:blowup]
    omegade = omegade[:blowup]

    # Age
    age = t_cut[np.argmin(t_cut)]
    age = round(age, 2)

    # plotting selected resutls
    # a and a_dot
    xlabel('t in 1/H0')
    lw = 1
    plot(t_cut, a, 'r', linewidth=lw)
    plot(t_cut, a_dot, 'b', linewidth=lw)
    legend((r'$a$', r'$\.a$'), prop=FontProperties(size=16))
    title('Cut results for $\omega$ = %s, age = %s 1/H0'%(w,age))

    while False:
        # e_dashm
        figure()
        xlabel('t in 1/H0')
        lw = 1
        plot(t_cut, e_dashm, 'g', linewidth=lw)
        title('Cut $\epsilon_m \'$ for $\omega$ = %s'%(w))

        # e_dashde
        figure()
        xlabel('t in 1/H0')
        lw = 1
        plot(t_cut, e_dashde, 'm', linewidth=lw)
        title('Cut $\epsilon_{DE} \'$ for $\omega$ = %s'%(w))

        break

    # omegam and omegade
    figure()
    plot(t_cut, omegam, 'c', linewidth=lw)
    plot(t_cut, omegade, 'k', linewidth=lw)
    legend((r'$\Omega_m$', r'$\Omega_{DE}$'), prop=FontProperties(size=16))
    title('Cut results for $\omega$ = %s, age = %s 1/H0'%(w,age))

    break

while False:
    figure()
    xlabel('t in 1/H0')
    grid(True)
    lw = 1

    # plotting all results
    plot(t, vsol[:,0], 'r', linewidth=lw)
    plot(t, vsol[:,1], 'b', linewidth=lw)

    legend((r'$a$', r'$\.a$', r'$\'\epsilon$'), prop=FontProperties(size=16))
    title('Complete results for $\omega$ = %s'%(w))

    break<commit_msg>new lambda options<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
use 2nd order friedmann equations + the continuity equation
numerically integrate the cosmological equations for standard cosmology where
omega = 1 for matter universe
also
omega = 1 30% matter, 70% dark energy
luminosity distance plots
https://arxiv.org/pdf/astro-ph/9905116.pdf
pl.plot(sampler.flatchain[:,0])
pl.plot(sampler.flatchain[:,1])
pl.plot(sampler.flatchain[:,0],sampler.flatchain[:,1],'.')
interaction term next
>>ODE solver (ODE int)
integrate both scale factor and continuity equation at the same time
change units
use time = 1/h0 and distance c/h0
AND
integrate backwards from today so from 0 ti -t
ok to ask Luke
later : movify to include co-moving distance (Ryden?)
+ Luminosity distance
find out how old a universe with only matter and at
critical density would be today
integrate over time, t0 will be now, where a crosses 0 is the beginning
so find time in years
then tell how a changes with time and the age of the universe in universe with
critical
density today, single fluid an with equation of state w=-1/3
Dodn't always ask what to do
event catcher - stop integration once a reaches 0
put in more than one fluid in the universe
maybe http://www.ni.gsu.edu/~rclewley/PyDSTool/FrontPage.html
m + DE universe (age)
Create plot of omega lambda vs omaga matter across age of universe
0.3 and 0.7 today, what were they in the past
Krysztoff, Luke
[try a_dot as equation and not just a_dot, i.e. ditch a_dotdot, but that is if
the equations are correct. if solver doens't have a problem when feeding data
in at each calculation then a_dot as a_dot and not equation shouldn't matter] -
worked out in the end
git test

what interaction terms could there be?

NOT AN ASSIGNMENT
"""

from scipy.integrate import odeint
import numpy as np
from pylab import figure, plot, xlabel, grid, legend, title
from matplotlib.font_manager import FontProperties

#def vectorfield(v, t, w):
#    a, a_dot, e_dash_m, e_dash_de, omega0m, omega0de = v
#    w_m, w_de = w
#    lamb_m = -2e-2 #10
#    lamb_de = 2e-2
#    # Create f = [a_dot, a_dotdot, e'_dotm, e'_dotde, omegam_dot, omegade_dot]:
#    f = [a_dot,
#         (-a/2)*(e_dash_m*(1+3*w_m)+e_dash_de*(1+3*w_de)),
#         -3*(a_dot/a)*(e_dash_m*(1+w_m+lamb_m/3*a/a_dot)),
#         -3*(a_dot/a)*(e_dash_de*(1+w_de+lamb_de/3*a/a_dot)),
#         (H0**2)*e_dash_m*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
#                           e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
#                           (-3*a_dot/a*e_dash_m*(1+w_m)),
#         (H0**2)*e_dash_de*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
#                            e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
#                            (-3*a_dot/a*e_dash_de*(1+w_de))]
#
#    return f

def vectorfield(v, t, w):
    a, a_dot, e_dash_m, e_dash_de, omega0m, omega0de = v
    w_m, w_de = w
    lamb = 2e-1 #10
    # Create f = [a_dot, a_dotdot, e'_dotm, e'_dotde, omegam_dot, omegade_dot]:
    f = [a_dot,
         (-a/2)*(e_dash_m*(1+3*w_m)+e_dash_de*(1+3*w_de)),
         -3*(a_dot/a)*(e_dash_m*(1+w_m-lamb/3*a/a_dot)),
         -3*(a_dot/a)*(e_dash_de*(1+w_de+lamb/3*a/a_dot)),
         (H0**2)*e_dash_m*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
                           e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
                           (-3*a_dot/a*e_dash_m*(1+w_m)),
         (H0**2)*e_dash_de*(2*a/a_dot)*(1-a*(-a/2)*(e_dash_m*(1+3*w_m)+
                            e_dash_de*(1+3*w_de))/a_dot**2)+(a/a_dot)**2*
                            (-3*a_dot/a*e_dash_de*(1+w_de))]

    return f

# a past which to discard values, value chosen by looking at the plot
# set arbitrarily - sometimes jumps over the result(?)
a_d = 10e-6

# time in 1/H0 to integrate until, if this time isn't long enough to reach a_d
# then "time" will be added to integration time until a_d is reached
# 0.665 matter only, 0.96 m+de, -0.49
time = 0.6

# Parameters
H0 = 1       # Hubble parameter at t=now
#Dh = c/H0   # Hubble distance
tH = 1.0/H0  # Hubble time
# G = 1
# c = 1

# Eq of state parameter
w_m = 0.0     # matter
w_de = -1.0   # cosmological constant (dark energy)
w_r = 1/3     # radiation

# Initial conditions
# a0 = scale factor, a_dot = speed, e_dash0 = e0/ec0
a0 = 1.0
a_dot0 = 1.0
e_dash0m = 0.3
e_dash0de = 0.7
omega0m = 0.3
omega0de = 0.7

# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6
numpoints = 250

stoptime = -time

# Plot the solution
figure()
xlabel('t in 1/H0')
grid(True)
lw = 1

while True:
#    print('stoptime is:',str(stoptime),'1/H0')
    # Create the time samples for the output of the ODE solver.
    t = [stoptime*tH * float(i) / (numpoints - 1) for i in range(numpoints)]

    # Pack up the parameters and initial conditions:
    v0 = [a0, a_dot0, e_dash0m, e_dash0de, omega0m, omega0de]

    w = [w_m, w_de]

    # Call the ODE solver.
    vsol = odeint(vectorfield, v0, t, args=(w,), atol=abserr, rtol=relerr)

    # Remove unwanted results from the plot
    # Separate results into their own arrays
    a = vsol[:,0]
    a_dot = vsol[:,1]
    e_dashm = vsol[:,2]
    e_dashde = vsol[:,3]
    omegam = vsol[:,4]
    omegade = vsol[:,5]

    # Find where results start to get strange
    blowups = np.where(a < a_d)    # tuple with indecies of a
                                   # so small it blows up a_dot
    blowups = np.asarray(blowups)  # converting to np array

    if blowups.any():
        blowup = blowups[0,0]      # first instance of a being too small
    else:
        stoptime -= time
        continue

    # Remove the values after the index when a is too small
    t_cut = np.asarray(t)
    t_cut = t_cut[:blowup]
    a = a[:blowup]
    a_dot = a_dot[:blowup]
    e_dashm = e_dashm[:blowup]
    e_dashde = e_dashde[:blowup]
    omegam = omegam[:blowup]
    omegade = omegade[:blowup]

    # Age
    age = t_cut[np.argmin(t_cut)]
    age = round(age, 2)

    # plotting selected resutls
    # a and a_dot
    xlabel('t in 1/H0')
    lw = 1
    plot(t_cut, a, 'r', linewidth=lw)
    plot(t_cut, a_dot, 'b', linewidth=lw)
    legend((r'$a$', r'$\.a$'), prop=FontProperties(size=16))
    title('Cut results for $\omega$ = %s, age = %s 1/H0'%(w,age))

    while False:
        # e_dashm
        figure()
        xlabel('t in 1/H0')
        lw = 1
        plot(t_cut, e_dashm, 'g', linewidth=lw)
        title('Cut $\epsilon_m \'$ for $\omega$ = %s'%(w))

        # e_dashde
        figure()
        xlabel('t in 1/H0')
        lw = 1
        plot(t_cut, e_dashde, 'm', linewidth=lw)
        title('Cut $\epsilon_{DE} \'$ for $\omega$ = %s'%(w))

        break

    # omegam and omegade
    figure()
    plot(t_cut, omegam, 'c', linewidth=lw)
    plot(t_cut, omegade, 'k', linewidth=lw)
    legend((r'$\Omega_m$', r'$\Omega_{DE}$'), prop=FontProperties(size=16))
    title('Cut results for $\omega$ = %s, age = %s 1/H0'%(w,age))

    break

while False:
    figure()
    xlabel('t in 1/H0')
    grid(True)
    lw = 1

    # plotting all results
    plot(t, vsol[:,0], 'r', linewidth=lw)
    plot(t, vsol[:,1], 'b', linewidth=lw)

    legend((r'$a$', r'$\.a$', r'$\'\epsilon$'), prop=FontProperties(size=16))
    title('Complete results for $\omega$ = %s'%(w))

    break<|endoftext|>


<commit_before>from numerictypes import string_, unicode_, integer, object_
from numeric import ndarray, broadcast, empty, compare_chararrays
from numeric import array as narray
import sys

__all__ = ['chararray']

_globalvar = 0
_unicode = unicode

# special sub-class for character arrays (string_ and unicode_)
# This adds + and * operations and methods of str and unicode types
#  which operate on an element-by-element basis

# It also strips white-space on element retrieval and on
#   comparisons

class chararray(ndarray):
    def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
                offset=0, strides=None, order='C'):
        global _globalvar

        if unicode:
            dtype = unicode_
        else:
            dtype = string_

        _globalvar = 1
        if buffer is None:
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
                                   order=order)
        else:
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
                                   buffer=buffer,
                                   offset=offset, strides=strides,
                                   order=order)
        _globalvar = 0
        return self

    def __array_finalize__(self, obj):
        # The b is a special case because it is used for reconstructing.
        if not _globalvar and self.dtype.char not in 'SUb':
            raise ValueError, "Can only create a chararray from string data."

    def __getitem__(self, obj):
        val = ndarray.__getitem__(self, obj)
        if isinstance(val, (string_, unicode_)):
            temp = val.rstrip()
            if len(temp) == 0:
                val = ''
            else:
                val = temp
        return val

    def __eq__(self, other):
        return compare_chararrays(self, other, '==', True)

    def __ne__(self, other):
        return compare_chararrays(self, other, '!=', True)

    def __ge__(self, other):
        return compare_chararrays(self, other, '>=', True)

    def __le__(self, other):
        return compare_chararrays(self, other, '<=', True)

    def __gt__(self, other):
        return compare_chararrays(self, other, '>', True)

    def __lt__(self, other):
        return compare_chararrays(self, other, '<', True)

    def __add__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        outitem = self.itemsize + arr.itemsize
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = (val[0] + val[1])
        return result

    def __radd__(self, other):
        b = broadcast(other, self)
        outitem = b.iters[0].base.itemsize + \
                  b.iters[1].base.itemsize
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = (val[0] + val[1])
        return result

    def __mul__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        if not issubclass(arr.dtype.type, integer):
            raise ValueError, "Can only multiply by integers"
        outitem = b.iters[0].base.itemsize * arr.max()
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = val[0]*val[1]
        return result

    def __rmul__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        if not issubclass(arr.dtype.type, integer):
            raise ValueError, "Can only multiply by integers"
        outitem = b.iters[0].base.itemsize * arr.max()
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = val[0]*val[1]
        return result

    def __mod__(self, other):
        b = broadcast(self, other)
        res = [None]*b.size
        maxsize = -1
        for k,val in enumerate(b):
            newval = val[0] % val[1]
            maxsize = max(len(newval), maxsize)
            res[k] = newval
        newarr = chararray(b.shape, maxsize, self.dtype is unicode_)
        newarr[:] = res
        return newarr

    def __rmod__(self, other):
        return NotImplemented

    def _generalmethod(self, name, myiter):
        res = [None]*myiter.size
        maxsize = -1
        for k, val in enumerate(myiter):
            newval = []
            for chk in val[1:]:
                if not chk or (chk.dtype is object_ and chk.item() is None):
                    break
                newval.append(chk)
            newitem = getattr(val[0],name)(*newval)
            maxsize = max(len(newitem), maxsize)
            res[k] = newitem
        newarr = chararray(myiter.shape, maxsize, self.dtype is unicode_)
        newarr[:] = res
        return newarr

    def _typedmethod(self, name, myiter, dtype):
        result = empty(myiter.shape, dtype=dtype)
        res = result.flat
        for k, val in enumerate(myiter):
            newval = []
            for chk in val[1:]:
                if not chk or (chk.dtype is object_ and chk.item() is None):
                    break
                newval.append(chk)
            this_str = val[0].rstrip('\x00')
            newitem = getattr(this_str,name)(*newval)
            res[k] = newitem
        return result

    def _samemethod(self, name):
        result = self.copy()
        res = result.flat
        for k, val in enumerate(self.flat):
            res[k] = getattr(val, name)()
        return result

    def capitalize(self):
        return self._samemethod('capitalize')

    if sys.version[:3] >= '2.4':
        def center(self, width, fillchar=' '):
            return self._generalmethod('center',
                                       broadcast(self, width, fillchar))
        def ljust(self, width, fillchar=' '):
            return self._generalmethod('ljust',
                                       broadcast(self, width, fillchar))
        def rjust(self, width, fillchar=' '):
            return self._generalmethod('rjust',
                                       broadcast(self, width, fillchar))
        def rsplit(self, sep=None, maxsplit=None):
            return self._typedmethod('rsplit', broadcast(self, sep, maxsplit),
                                     object)
    else:
        def ljust(self, width):
            return self._generalmethod('ljust', broadcast(self, width))
        def rjust(self, width):
            return self._generalmethod('rjust', broadcast(self, width))
        def center(self, width):
            return self._generalmethod('center', broadcast(self, width))

    def count(self, sub, start=None, end=None):
        return self._typedmethod('count', broadcast(self, sub, start, end), int)

    def decode(self,encoding=None,errors=None):
        return self._generalmethod('decode', broadcast(self, encoding, errors))

    def encode(self,encoding=None,errors=None):
        return self._generalmethod('encode', broadcast(self, encoding, errors))

    def endswith(self, suffix, start=None, end=None):
        return self._typedmethod('endswith', broadcast(self, suffix, start, end), bool)

    def expandtabs(self, tabsize=None):
        return self._generalmethod('endswith', broadcast(self, tabsize))

    def find(self, sub, start=None, end=None):
        return self._typedmethod('find', broadcast(self, sub, start, end), int)

    def index(self, sub, start=None, end=None):
        return self._typedmethod('index', broadcast(self, sub, start, end), int)

    def _ismethod(self, name):
        result = empty(self.shape, dtype=bool)
        res = result.flat
        for k, val in enumerate(self.flat):
            item = val.rstrip('\x00')
            res[k] = getattr(item, name)()
        return result

    def isalnum(self):
        return self._ismethod('isalnum')

    def isalpha(self):
        return self._ismethod('isalpha')

    def isdigit(self):
        return self._ismethod('isdigit')

    def islower(self):
        return self._ismethod('islower')

    def isspace(self):
        return self._ismethod('isspace')

    def istitle(self):
        return self._ismethod('istitle')

    def isupper(self):
        return self._ismethod('isupper')

    def join(self, seq):
        return self._generalmethod('join', broadcast(self, seq))

    def lower(self):
        return self._samemethod('lower')

    def lstrip(self, chars):
        return self._generalmethod('lstrip', broadcast(self, chars))

    def replace(self, old, new, count=None):
        return self._generalmethod('replace', broadcast(self, old, new, count))

    def rfind(self, sub, start=None, end=None):
        return self._typedmethod('rfind', broadcast(self, sub, start, end), int)

    def rindex(self, sub, start=None, end=None):
        return self._typedmethod('rindex', broadcast(self, sub, start, end), int)

    def rstrip(self, chars=None):
        return self._generalmethod('rstrip', broadcast(self, chars))

    def split(self, sep=None, maxsplit=None):
        return self._typedmethod('split', broadcast(self, sep, maxsplit), object)

    def splitlines(self, keepends=None):
        return self._typedmethod('splitlines', broadcast(self, keepends), object)

    def startswith(self, prefix, start=None, end=None):
        return self._typedmethod('startswith', broadcast(self, prefix, start, end), bool)

    def strip(self, chars=None):
        return self._generalmethod('strip', broadcast(self, chars))

    def swapcase(self):
        return self._samemethod('swapcase')

    def title(self):
        return self._samemethod('title')

    def translate(self, table, deletechars=None):
        if self.dtype is unicode_:
            return self._generalmethod('translate', broadcast(self, table))
        else:
            return self._generalmethod('translate', broadcast(self, table, deletechars))

    def upper(self):
        return self._samemethod('upper')

    def zfill(self, width):
        return self._generalmethod('zfill', broadcast(self, width))

def array(obj, itemsize=None, copy=True, unicode=False, order=None):

    if isinstance(obj, chararray):
        if itemsize is None:
            itemsize = obj.itemsize
        if copy or (itemsize != obj.itemsize) \
           or (not unicode and obj.dtype == unicode_) \
           or (unicode and obj.dtype == string_):
            return obj.astype("%s%d" % (obj.dtype.char, itemsize))
        else:
            return obj

    if isinstance(obj, ndarray) and (obj.dtype in [unicode_, string_]):
        new = obj.view(chararray)
        if unicode and obj.dtype == string_:
            return new.astype((unicode_, obj.itemsize))
        elif obj.dtype == unicode_:
            return new.astype((string_, obj.itemsize))

        if copy: return new.copy()
        else: return new

    if unicode: dtype = "U"
    else: dtype = "S"

    if itemsize is not None:
        dtype += str(itemsize)

    if isinstance(obj, (str, _unicode)):
        if itemsize is None:
            itemsize = len(obj)
        shape = len(obj) / itemsize
        return chararray(shape, itemsize=itemsize, unicode=unicode,
                         buffer=obj)

    # default
    val = narray(obj, dtype=dtype, order=order, subok=1)

    return val.view(chararray)

def asarray(obj, itemsize=None, unicode=False, order=None):
    return array(obj, itemsize, copy=False,
                 unicode=unicode, order=order)
<commit_msg>Fix ticket #408 --- chararray problem with argsort<commit_after>from numerictypes import string_, unicode_, integer, object_
from numeric import ndarray, broadcast, empty, compare_chararrays
from numeric import array as narray
import sys

__all__ = ['chararray']

_globalvar = 0
_unicode = unicode

# special sub-class for character arrays (string_ and unicode_)
# This adds + and * operations and methods of str and unicode types
#  which operate on an element-by-element basis

# It also strips white-space on element retrieval and on
#   comparisons

class chararray(ndarray):
    def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
                offset=0, strides=None, order='C'):
        global _globalvar

        if unicode:
            dtype = unicode_
        else:
            dtype = string_

        _globalvar = 1
        if buffer is None:
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
                                   order=order)
        else:
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
                                   buffer=buffer,
                                   offset=offset, strides=strides,
                                   order=order)
        _globalvar = 0
        return self

    def __array_finalize__(self, obj):
        # The b is a special case because it is used for reconstructing.
        if not _globalvar and self.dtype.char not in 'SUb':
            raise ValueError, "Can only create a chararray from string data."

    def __getitem__(self, obj):
        val = ndarray.__getitem__(self, obj)
        if isinstance(val, (string_, unicode_)):
            temp = val.rstrip()
            if len(temp) == 0:
                val = ''
            else:
                val = temp
        return val

    def __eq__(self, other):
        return compare_chararrays(self, other, '==', True)

    def __ne__(self, other):
        return compare_chararrays(self, other, '!=', True)

    def __ge__(self, other):
        return compare_chararrays(self, other, '>=', True)

    def __le__(self, other):
        return compare_chararrays(self, other, '<=', True)

    def __gt__(self, other):
        return compare_chararrays(self, other, '>', True)

    def __lt__(self, other):
        return compare_chararrays(self, other, '<', True)

    def __add__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        outitem = self.itemsize + arr.itemsize
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = (val[0] + val[1])
        return result

    def __radd__(self, other):
        b = broadcast(other, self)
        outitem = b.iters[0].base.itemsize + \
                  b.iters[1].base.itemsize
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = (val[0] + val[1])
        return result

    def __mul__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        if not issubclass(arr.dtype.type, integer):
            raise ValueError, "Can only multiply by integers"
        outitem = b.iters[0].base.itemsize * arr.max()
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = val[0]*val[1]
        return result

    def __rmul__(self, other):
        b = broadcast(self, other)
        arr = b.iters[1].base
        if not issubclass(arr.dtype.type, integer):
            raise ValueError, "Can only multiply by integers"
        outitem = b.iters[0].base.itemsize * arr.max()
        result = chararray(b.shape, outitem, self.dtype is unicode_)
        res = result.flat
        for k, val in enumerate(b):
            res[k] = val[0]*val[1]
        return result

    def __mod__(self, other):
        b = broadcast(self, other)
        res = [None]*b.size
        maxsize = -1
        for k,val in enumerate(b):
            newval = val[0] % val[1]
            maxsize = max(len(newval), maxsize)
            res[k] = newval
        newarr = chararray(b.shape, maxsize, self.dtype is unicode_)
        newarr[:] = res
        return newarr

    def __rmod__(self, other):
        return NotImplemented

    def argsort(self, axis=-1, kind='quicksort', order=None):
        return self.__array__().argsort(axis, kind, order)

    def _generalmethod(self, name, myiter):
        res = [None]*myiter.size
        maxsize = -1
        for k, val in enumerate(myiter):
            newval = []
            for chk in val[1:]:
                if not chk or (chk.dtype is object_ and chk.item() is None):
                    break
                newval.append(chk)
            newitem = getattr(val[0],name)(*newval)
            maxsize = max(len(newitem), maxsize)
            res[k] = newitem
        newarr = chararray(myiter.shape, maxsize, self.dtype is unicode_)
        newarr[:] = res
        return newarr

    def _typedmethod(self, name, myiter, dtype):
        result = empty(myiter.shape, dtype=dtype)
        res = result.flat
        for k, val in enumerate(myiter):
            newval = []
            for chk in val[1:]:
                if not chk or (chk.dtype is object_ and chk.item() is None):
                    break
                newval.append(chk)
            this_str = val[0].rstrip('\x00')
            newitem = getattr(this_str,name)(*newval)
            res[k] = newitem
        return result

    def _samemethod(self, name):
        result = self.copy()
        res = result.flat
        for k, val in enumerate(self.flat):
            res[k] = getattr(val, name)()
        return result

    def capitalize(self):
        return self._samemethod('capitalize')

    if sys.version[:3] >= '2.4':
        def center(self, width, fillchar=' '):
            return self._generalmethod('center',
                                       broadcast(self, width, fillchar))
        def ljust(self, width, fillchar=' '):
            return self._generalmethod('ljust',
                                       broadcast(self, width, fillchar))
        def rjust(self, width, fillchar=' '):
            return self._generalmethod('rjust',
                                       broadcast(self, width, fillchar))
        def rsplit(self, sep=None, maxsplit=None):
            return self._typedmethod('rsplit', broadcast(self, sep, maxsplit),
                                     object)
    else:
        def ljust(self, width):
            return self._generalmethod('ljust', broadcast(self, width))
        def rjust(self, width):
            return self._generalmethod('rjust', broadcast(self, width))
        def center(self, width):
            return self._generalmethod('center', broadcast(self, width))

    def count(self, sub, start=None, end=None):
        return self._typedmethod('count', broadcast(self, sub, start, end), int)

    def decode(self,encoding=None,errors=None):
        return self._generalmethod('decode', broadcast(self, encoding, errors))

    def encode(self,encoding=None,errors=None):
        return self._generalmethod('encode', broadcast(self, encoding, errors))

    def endswith(self, suffix, start=None, end=None):
        return self._typedmethod('endswith', broadcast(self, suffix, start, end), bool)

    def expandtabs(self, tabsize=None):
        return self._generalmethod('endswith', broadcast(self, tabsize))

    def find(self, sub, start=None, end=None):
        return self._typedmethod('find', broadcast(self, sub, start, end), int)

    def index(self, sub, start=None, end=None):
        return self._typedmethod('index', broadcast(self, sub, start, end), int)

    def _ismethod(self, name):
        result = empty(self.shape, dtype=bool)
        res = result.flat
        for k, val in enumerate(self.flat):
            item = val.rstrip('\x00')
            res[k] = getattr(item, name)()
        return result

    def isalnum(self):
        return self._ismethod('isalnum')

    def isalpha(self):
        return self._ismethod('isalpha')

    def isdigit(self):
        return self._ismethod('isdigit')

    def islower(self):
        return self._ismethod('islower')

    def isspace(self):
        return self._ismethod('isspace')

    def istitle(self):
        return self._ismethod('istitle')

    def isupper(self):
        return self._ismethod('isupper')

    def join(self, seq):
        return self._generalmethod('join', broadcast(self, seq))

    def lower(self):
        return self._samemethod('lower')

    def lstrip(self, chars):
        return self._generalmethod('lstrip', broadcast(self, chars))

    def replace(self, old, new, count=None):
        return self._generalmethod('replace', broadcast(self, old, new, count))

    def rfind(self, sub, start=None, end=None):
        return self._typedmethod('rfind', broadcast(self, sub, start, end), int)

    def rindex(self, sub, start=None, end=None):
        return self._typedmethod('rindex', broadcast(self, sub, start, end), int)

    def rstrip(self, chars=None):
        return self._generalmethod('rstrip', broadcast(self, chars))

    def split(self, sep=None, maxsplit=None):
        return self._typedmethod('split', broadcast(self, sep, maxsplit), object)

    def splitlines(self, keepends=None):
        return self._typedmethod('splitlines', broadcast(self, keepends), object)

    def startswith(self, prefix, start=None, end=None):
        return self._typedmethod('startswith', broadcast(self, prefix, start, end), bool)

    def strip(self, chars=None):
        return self._generalmethod('strip', broadcast(self, chars))

    def swapcase(self):
        return self._samemethod('swapcase')

    def title(self):
        return self._samemethod('title')

    def translate(self, table, deletechars=None):
        if self.dtype is unicode_:
            return self._generalmethod('translate', broadcast(self, table))
        else:
            return self._generalmethod('translate', broadcast(self, table, deletechars))

    def upper(self):
        return self._samemethod('upper')

    def zfill(self, width):
        return self._generalmethod('zfill', broadcast(self, width))

def array(obj, itemsize=None, copy=True, unicode=False, order=None):

    if isinstance(obj, chararray):
        if itemsize is None:
            itemsize = obj.itemsize
        if copy or (itemsize != obj.itemsize) \
           or (not unicode and obj.dtype == unicode_) \
           or (unicode and obj.dtype == string_):
            return obj.astype("%s%d" % (obj.dtype.char, itemsize))
        else:
            return obj

    if isinstance(obj, ndarray) and (obj.dtype in [unicode_, string_]):
        new = obj.view(chararray)
        if unicode and obj.dtype == string_:
            return new.astype((unicode_, obj.itemsize))
        elif obj.dtype == unicode_:
            return new.astype((string_, obj.itemsize))

        if copy: return new.copy()
        else: return new

    if unicode: dtype = "U"
    else: dtype = "S"

    if itemsize is not None:
        dtype += str(itemsize)

    if isinstance(obj, (str, _unicode)):
        if itemsize is None:
            itemsize = len(obj)
        shape = len(obj) / itemsize
        return chararray(shape, itemsize=itemsize, unicode=unicode,
                         buffer=obj)

    # default
    val = narray(obj, dtype=dtype, order=order, subok=1)

    return val.view(chararray)

def asarray(obj, itemsize=None, unicode=False, order=None):
    return array(obj, itemsize, copy=False,
                 unicode=unicode, order=order)
<|endoftext|>


<commit_before>from .separation_model import SeparationModel<commit_msg>fail gracefully without torch<commit_after>from .. import torch_imported, ImportErrorClass
if torch_imported:
    from .separation_model import SeparationModel
else:
    class SeparationModel(ImportErrorClass):
        def __init__(self):
            super(SeparationModel, self).__init__('pytorch')<|endoftext|>


<commit_before>'''
Created on 21 mrt. 2013

@author: j.h. kwakkel
'''
import jpype
import os
import sys

from expWorkbench import debug, info, warning
from expWorkbench.ema_exceptions import EMAError

__all__ = ['NetLogoException',
           'NetLogoLink']

if sys.platform=='win32':
    NETLOGO_HOME = r'C:\Program Files (x86)\NetLogo 5.1.0'
    jar_separator = ";" # jars are separated by a ; on Windows
elif sys.platform=='darwin':
    jar_separator = ":" # jars are separated by a : on MacOS
    NETLOGO_HOME = r'/Applications/NetLogo 5.1.0'
else:
    # TODO should raise and exception which is subsequently cached and
    # transformed into a a warning just like excel and vensim
    warning('netlogo support not available')

PYNETLOGO_HOME = os.path.dirname(os.path.abspath(__file__))

class NetLogoException(Exception):
    pass

class NetLogoLink():

    def __init__(self, gui=False, thd=False):
        '''

        Create a link with netlogo. Underneath, the netlogo jvm is started
        throuhg jpype.

        :param gui: boolean, if true run netlogo with gui, otherwise run in
                    headless mode. Defaults to false.
        :param thd: boolean, if thrue start netlogo in 3d mode. Defaults to
                    false

        '''
        if not jpype.isJVMStarted():
            # netlogo jars
            jars = [NETLOGO_HOME + r'/lib/scala-library.jar',
                    NETLOGO_HOME + r'/lib/asm-all-3.3.1.jar',
                    NETLOGO_HOME + r'/lib/picocontainer-2.13.6.jar',
                    NETLOGO_HOME + r'/lib/log4j-1.2.16.jar',
                    NETLOGO_HOME + r'/lib/jmf-2.1.1e.jar',
                    NETLOGO_HOME + r'/lib/pegdown-1.1.0.jar',
                    NETLOGO_HOME + r'/lib/parboiled-core-1.0.2.jar',
                    NETLOGO_HOME + r'/lib/parboiled-java-1.0.2.jar',
                    NETLOGO_HOME + r'/lib/mrjadapter-1.2.jar',
                    NETLOGO_HOME + r'/lib/jhotdraw-6.0b1.jar',
                    NETLOGO_HOME + r'/lib/quaqua-7.3.4.jar',
                    NETLOGO_HOME + r'/lib/swing-layout-7.3.4.jar',
                    NETLOGO_HOME + r'/lib/jogl-1.1.1.jar',
                    NETLOGO_HOME + r'/lib/gluegen-rt-1.1.1.jar',
                    NETLOGO_HOME + r'/NetLogo.jar',
                    PYNETLOGO_HOME + r'/external_files/netlogoLink.jar']

            # format jars in right format for starting java virtual machine
            # TODO the use of the jre here is only relevant under windows
            # apparently
            # might be solvable by setting netlogo home user.dir

            joined_jars = jar_separator.join(jars)
            jarpath = '-Djava.class.path={}'.format(joined_jars)

            jvm_handle = jpype.getDefaultJVMPath()
            jpype.startJVM(jvm_handle, jarpath, "-Xms128M","-Xmx1024m")
            jpype.java.lang.System.setProperty('user.dir', NETLOGO_HOME)

            if sys.platform=='darwin':
                jpype.java.lang.System.setProperty("java.awt.headless", "true");

            debug("jvm started")

        link = jpype.JClass('netlogoLink.NetLogoLink')
        debug('NetLogoLink class found')

        if sys.platform == 'darwin' and gui:
            info('on mac only headless mode is supported')
            gui=False

        self.link = link(gui, thd)
        debug('NetLogoLink class instantiated')

    def load_model(self, path):
        '''

        load a netlogo model.

        :param path: the absolute path to the netlogo model
        :raise: IOError in case the  model is not found
        :raise: NetLogoException wrapped arround netlogo exceptions.

        '''
        if not os.path.isfile(path):
            raise EMAError('{} is not a file'.format(path))

        try:
            self.link.loadModel(path)
        except jpype.JException(jpype.java.io.IOException)as ex:
            raise IOError(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.lang.InterruptedException) as ex:
            raise NetLogoException(ex.message())

    def kill_workspace(self):
        '''

        close netlogo and shut down the jvm

        '''

        self.link.killWorkspace()

    def command(self, netlogo_command):
        '''

        Execute the supplied command in netlogo

        :param netlogo_command: a string with a valid netlogo command
        :raises: NetLogoException in case of either a LogoException or
                CompilerException being raised by netlogo.

        '''

        try:
            self.link.command(netlogo_command)
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.nvm.EngineException) as ex:
            raise NetLogoException(ex.message())

    def report(self, netlogo_reporter):
        '''

        Every reporter (commands which return a value) that can be called in
        the NetLogo Command Center can be called with this method.

        :param netlogo_reporter: a valid netlogo reporter
        :raises: NetlogoException

        '''

        try:
            result = self.link.report(netlogo_reporter)
            return self._cast_results(result)
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.lang.Exception) as ex:
            raise NetLogoException(ex.message())

    def _cast_results(self, results):
        '''

        Convert the results to the proper python data type. The NLResults
        object knows its datatype and has converter methods for each.

        :param results; the results from report
        :returns: a correct python version of the results

        '''

        java_dtype = results.type

        if java_dtype == "Boolean":
            results = results.getResultAsBoolean()
            if results == 1:
                return True
            else:
                return False
        elif java_dtype == "String":
            return results.getResultAsString()
        elif java_dtype == "Integer":
            return results.getResultAsInteger()
        elif java_dtype == "Double":
            return results.getResultAsDouble()
        elif java_dtype == "BoolList":
            results = results.getResultAsBooleanArray()

            tr = []
            for entry in results:
                if entry == 1:
                    tr.append(True)
                else:
                    tr.append(False)
            return tr
        elif java_dtype == "StringList":
            return results.getResultAsStringArray()
        elif java_dtype == "IntegerList":
            return results.getResultAsIntegerArray()
        elif java_dtype == "DoubleList":
            return results.getResultAsDoubleArray()
        else:
            raise NetLogoException("unknown datatype")<commit_msg>attempt at resolving jpype import error<commit_after>'''
Created on 21 mrt. 2013

@author: j.h. kwakkel
'''
try:
    import jpype
except ImportError:
    jpype = None
import os
import sys

from expWorkbench import debug, info, warning
from expWorkbench.ema_exceptions import EMAError

__all__ = ['NetLogoException',
           'NetLogoLink']

if sys.platform=='win32':
    NETLOGO_HOME = r'C:\Program Files (x86)\NetLogo 5.1.0'
    jar_separator = ";" # jars are separated by a ; on Windows
elif sys.platform=='darwin':
    jar_separator = ":" # jars are separated by a : on MacOS
    NETLOGO_HOME = r'/Applications/NetLogo 5.1.0'
else:
    # TODO should raise and exception which is subsequently cached and
    # transformed into a a warning just like excel and vensim
    warning('netlogo support not available')

PYNETLOGO_HOME = os.path.dirname(os.path.abspath(__file__))

class NetLogoException(Exception):
    pass

class NetLogoLink():

    def __init__(self, gui=False, thd=False):
        '''

        Create a link with netlogo. Underneath, the netlogo jvm is started
        throuhg jpype.

        :param gui: boolean, if true run netlogo with gui, otherwise run in
                    headless mode. Defaults to false.
        :param thd: boolean, if thrue start netlogo in 3d mode. Defaults to
                    false

        '''
        if not jpype.isJVMStarted():
            # netlogo jars
            jars = [NETLOGO_HOME + r'/lib/scala-library.jar',
                    NETLOGO_HOME + r'/lib/asm-all-3.3.1.jar',
                    NETLOGO_HOME + r'/lib/picocontainer-2.13.6.jar',
                    NETLOGO_HOME + r'/lib/log4j-1.2.16.jar',
                    NETLOGO_HOME + r'/lib/jmf-2.1.1e.jar',
                    NETLOGO_HOME + r'/lib/pegdown-1.1.0.jar',
                    NETLOGO_HOME + r'/lib/parboiled-core-1.0.2.jar',
                    NETLOGO_HOME + r'/lib/parboiled-java-1.0.2.jar',
                    NETLOGO_HOME + r'/lib/mrjadapter-1.2.jar',
                    NETLOGO_HOME + r'/lib/jhotdraw-6.0b1.jar',
                    NETLOGO_HOME + r'/lib/quaqua-7.3.4.jar',
                    NETLOGO_HOME + r'/lib/swing-layout-7.3.4.jar',
                    NETLOGO_HOME + r'/lib/jogl-1.1.1.jar',
                    NETLOGO_HOME + r'/lib/gluegen-rt-1.1.1.jar',
                    NETLOGO_HOME + r'/NetLogo.jar',
                    PYNETLOGO_HOME + r'/external_files/netlogoLink.jar']

            # format jars in right format for starting java virtual machine
            # TODO the use of the jre here is only relevant under windows
            # apparently
            # might be solvable by setting netlogo home user.dir

            joined_jars = jar_separator.join(jars)
            jarpath = '-Djava.class.path={}'.format(joined_jars)

            jvm_handle = jpype.getDefaultJVMPath()
            jpype.startJVM(jvm_handle, jarpath, "-Xms128M","-Xmx1024m")
            jpype.java.lang.System.setProperty('user.dir', NETLOGO_HOME)

            if sys.platform=='darwin':
                jpype.java.lang.System.setProperty("java.awt.headless", "true");

            debug("jvm started")

        link = jpype.JClass('netlogoLink.NetLogoLink')
        debug('NetLogoLink class found')

        if sys.platform == 'darwin' and gui:
            info('on mac only headless mode is supported')
            gui=False

        self.link = link(gui, thd)
        debug('NetLogoLink class instantiated')

    def load_model(self, path):
        '''

        load a netlogo model.

        :param path: the absolute path to the netlogo model
        :raise: IOError in case the  model is not found
        :raise: NetLogoException wrapped arround netlogo exceptions.

        '''
        if not os.path.isfile(path):
            raise EMAError('{} is not a file'.format(path))

        try:
            self.link.loadModel(path)
        except jpype.JException(jpype.java.io.IOException)as ex:
            raise IOError(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.lang.InterruptedException) as ex:
            raise NetLogoException(ex.message())

    def kill_workspace(self):
        '''

        close netlogo and shut down the jvm

        '''

        self.link.killWorkspace()

    def command(self, netlogo_command):
        '''

        Execute the supplied command in netlogo

        :param netlogo_command: a string with a valid netlogo command
        :raises: NetLogoException in case of either a LogoException or
                CompilerException being raised by netlogo.

        '''

        try:
            self.link.command(netlogo_command)
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.nvm.EngineException) as ex:
            raise NetLogoException(ex.message())

    def report(self, netlogo_reporter):
        '''

        Every reporter (commands which return a value) that can be called in
        the NetLogo Command Center can be called with this method.

        :param netlogo_reporter: a valid netlogo reporter
        :raises: NetlogoException

        '''

        try:
            result = self.link.report(netlogo_reporter)
            return self._cast_results(result)
        except jpype.JException(jpype.java.org.nlogo.api.LogoException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.org.nlogo.api.CompilerException) as ex:
            raise NetLogoException(ex.message())
        except jpype.JException(jpype.java.lang.Exception) as ex:
            raise NetLogoException(ex.message())

    def _cast_results(self, results):
        '''

        Convert the results to the proper python data type. The NLResults
        object knows its datatype and has converter methods for each.

        :param results; the results from report
        :returns: a correct python version of the results

        '''

        java_dtype = results.type

        if java_dtype == "Boolean":
            results = results.getResultAsBoolean()
            if results == 1:
                return True
            else:
                return False
        elif java_dtype == "String":
            return results.getResultAsString()
        elif java_dtype == "Integer":
            return results.getResultAsInteger()
        elif java_dtype == "Double":
            return results.getResultAsDouble()
        elif java_dtype == "BoolList":
            results = results.getResultAsBooleanArray()

            tr = []
            for entry in results:
                if entry == 1:
                    tr.append(True)
                else:
                    tr.append(False)
            return tr
        elif java_dtype == "StringList":
            return results.getResultAsStringArray()
        elif java_dtype == "IntegerList":
            return results.getResultAsIntegerArray()
        elif java_dtype == "DoubleList":
            return results.getResultAsDoubleArray()
        else:
            raise NetLogoException("unknown datatype")<|endoftext|>


<commit_before>import os
import pip
import tempfile
import subprocess
import yank.version

BUCKET_NAME = 'openpathsampling'
if not yank.version.release:
    PREFIX = 'latest'
else:
    PREFIX = yank.version.short_version

PREFIX = ''

if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()):
    raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd')
# The secret key is available as a secure environment variable
# on travis-ci to push the build documentation to Amazon S3.
with tempfile.NamedTemporaryFile('w') as f:
    f.write('''[default]
access_key = {AWS_ACCESS_KEY_ID}
secret_key = {AWS_SECRET_ACCESS_KEY}
'''.format(**os.environ))
    f.flush()

    template = ('s3cmd --config {config} '
                'sync docs/_build/ s3://{bucket}/')
    cmd = template.format(
            config=f.name,
            bucket=BUCKET_NAME
    )
    return_val = subprocess.call(cmd.split())<commit_msg>fix version<commit_after>import os
import pip
import tempfile
import subprocess
import opentis.version

BUCKET_NAME = 'openpathsampling'
if not yank.version.release:
    PREFIX = 'latest'
else:
    PREFIX = yank.version.short_version

PREFIX = ''

if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()):
    raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd')
# The secret key is available as a secure environment variable
# on travis-ci to push the build documentation to Amazon S3.
with tempfile.NamedTemporaryFile('w') as f:
    f.write('''[default]
access_key = {AWS_ACCESS_KEY_ID}
secret_key = {AWS_SECRET_ACCESS_KEY}
'''.format(**os.environ))
    f.flush()

    template = ('s3cmd --config {config} '
                'sync docs/_build/ s3://{bucket}/')
    cmd = template.format(
            config=f.name,
            bucket=BUCKET_NAME
    )
    return_val = subprocess.call(cmd.split())<|endoftext|>


<commit_before># INSERT LICENSE HEADER HERE

import gtk
import gtk.glade
import config
import gobject
import pango

widgets = None

def addCategory(store, category):
	""" add parent item to store and return the treeiter """
	iter = store.append(None, (category,"",""))

	return iter

def fillConfigView():
	"""
	fill config treeview with categories,
	options/values and defaults
	"""
	configView = widgets.get_widget("configView")
	configStore = configView.get_model()

	for category in ("tekka","colors","chatting"):
		cDict = config.get(category, default=None)

		if not cDict:
			continue

		iter = addCategory(configStore, category)

		if not iter:
			continue

		for (key, value) in cDict.items():
			default = str(config.getDefault(category, key))
			configStore.append(iter, row=(key, value, default))

def renderOption(column, renderer, model, iter):
	if not model.iter_parent(iter):
		# category row, markup bold
		renderer.set_property("weight", pango.WEIGHT_BOLD)
	else:
		renderer.set_property("weight", pango.WEIGHT_NORMAL)

def renderValue(column, renderer, model, iter):
	if not model.iter_parent(iter):
		renderer.set_property("editable", False)
	else:
		renderer.set_property("editable", True)

def renderDefaultValue(column, renderer, model, iter):
	pass

def configValueEdited(renderer, path, newText):
	model = widgets.get_widget("configView").get_model()
	treeIter = model.get_iter(path)

	catIter = model.iter_parent(treeIter)

	if not catIter:
		return

	model.set(treeIter, 1, newText)

	category = model.get(catIter, 0)[0]
	option = model[path][0]
	value = model[path][1]

	config.set(category, option, value)

def setup():
	""" called initially """
	global widgets
	gladePath = config.get("gladefiles", "dialogs") + "advancedPreferences.glade"
	widgets = gtk.glade.XML(gladePath)

	configView = widgets.get_widget("configView")

	c = 0
	for name in ("Option", "Value", "Default Value"):
		renderer = gtk.CellRendererText()

		if name == "Value":
			# value column is editable
			renderer.set_property("editable", True)
			renderer.connect("edited", configValueEdited)

		column = gtk.TreeViewColumn(name, renderer, text=c)

		# set custom rendering function (render<key>)
		column.set_cell_data_func(renderer,
				eval("render%s" % name.replace(" ","")))

		configView.append_column(column)
		c+=1

	store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
			gobject.TYPE_STRING)

	configView.set_model(store)

def run():
	dialog = widgets.get_widget("advancedPreferences")

	fillConfigView()

	dialog.run()
	dialog.destroy()
<commit_msg>Fixed advanced settings dialog<commit_after># INSERT LICENSE HEADER HERE

import gtk
import gtk.glade
import config
import gobject
import pango

widgets = None

def addCategory(store, category):
	""" add parent item to store and return the treeiter """
	iter = store.append(None, (category,"",""))

	return iter

def fillConfigView():
	"""
	fill config treeview with categories,
	options/values and defaults
	"""
	configView = widgets.get_widget("configView")
	configStore = configView.get_model()

	for category in ("tekka","colors","chatting"):
		cDict = config.get(category, default=None)

		if not cDict:
			continue

		iter = addCategory(configStore, category)

		if not iter:
			continue

		for (key, value) in cDict.items():
			default = str(config.get_default(category, key))
			configStore.append(iter, row=(key, value, default))

def renderOption(column, renderer, model, iter):
	if not model.iter_parent(iter):
		# category row, markup bold
		renderer.set_property("weight", pango.WEIGHT_BOLD)
	else:
		renderer.set_property("weight", pango.WEIGHT_NORMAL)

def renderValue(column, renderer, model, iter):
	if not model.iter_parent(iter):
		renderer.set_property("editable", False)
	else:
		renderer.set_property("editable", True)

def renderDefaultValue(column, renderer, model, iter):
	pass

def configValueEdited(renderer, path, newText):
	model = widgets.get_widget("configView").get_model()
	treeIter = model.get_iter(path)

	catIter = model.iter_parent(treeIter)

	if not catIter:
		return

	model.set(treeIter, 1, newText)

	category = model.get(catIter, 0)[0]
	option = model[path][0]
	value = model[path][1]

	config.set(category, option, value)

def setup():
	""" called initially """
	global widgets
	gladePath = config.get("gladefiles", "dialogs") + "advancedPreferences.glade"
	widgets = gtk.glade.XML(gladePath)

	configView = widgets.get_widget("configView")

	c = 0
	for name in ("Option", "Value", "Default Value"):
		renderer = gtk.CellRendererText()

		if name == "Value":
			# value column is editable
			renderer.set_property("editable", True)
			renderer.connect("edited", configValueEdited)

		column = gtk.TreeViewColumn(name, renderer, text=c)

		# set custom rendering function (render<key>)
		column.set_cell_data_func(renderer,
				eval("render%s" % name.replace(" ","")))

		configView.append_column(column)
		c+=1

	store = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
			gobject.TYPE_STRING)

	configView.set_model(store)

def run():
	dialog = widgets.get_widget("advancedPreferences")

	fillConfigView()

	dialog.run()
	dialog.destroy()
<|endoftext|>