<commit_before>#!/usr/bin/env python3

#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Franck Jullien <franck.jullien@collshade.fr>
# SPDX-License-Identifier: BSD-2-Clause

import argparse

from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer

from litex_boards.platforms import efinix_titanium_ti60_f225_dev_kit

from litex.build.generic_platform import *

from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex.soc.integration.soc import SoCRegion

from litehyperbus.core.hyperbus import HyperRAM

# CRG ----------------------------------------------------------------------------------------------

class _CRG(Module):
    def __init__(self, platform, sys_clk_freq):
        self.clock_domains.cd_sys = ClockDomain()

        # # #

        clk25 = platform.request("clk25")
        rst_n = platform.request("user_btn", 0)

        # PLL
        self.submodules.pll = pll = TITANIUMPLL(platform)
        self.comb += pll.reset.eq(~rst_n)
        pll.register_clkin(clk25, 25e6)
        # You can use CLKOUT0 only for clocks with a maximum frequency of 4x
        # (integer) of the reference clock. If all your system clocks do not fall within
        # this range, you should dedicate one unused clock for CLKOUT0.
        pll.create_clkout(None, 25e6)

        pll.create_clkout(self.cd_sys, sys_clk_freq, with_reset=True)

# BaseSoC ------------------------------------------------------------------------------------------

class BaseSoC(SoCCore):
    def __init__(self, sys_clk_freq=int(200e6), with_spi_flash=False, with_hyperram=False, **kwargs):
        platform = efinix_titanium_ti60_f225_dev_kit.Platform()

        # SoCCore ----------------------------------------------------------------------------------
        SoCCore.__init__(self, platform, sys_clk_freq,
            ident         = "LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit",
            ident_version = True,
            **kwargs
        )

        # CRG --------------------------------------------------------------------------------------
        self.submodules.crg = _CRG(platform, sys_clk_freq)

        # SPI Flash --------------------------------------------------------------------------------
        if with_spi_flash:
            from litespi.modules import W25Q64JW
            from litespi.opcodes import SpiNorFlashOpCodes as Codes
            self.add_spi_flash(mode="1x", module=W25Q64JW(Codes.READ_1_1_1), with_master=True)

        if with_hyperram:
            self.submodules.hyperram = HyperRAM(platform.request("hyperram"), latency=7)
            self.bus.add_slave("main_ram", slave=self.hyperram.bus, region=SoCRegion(origin=0x40000000, size=32*1024*1024))

# Build --------------------------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(description="LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit")
    parser.add_argument("--build",          action="store_true", help="Build bitstream")
    parser.add_argument("--load",           action="store_true", help="Load bitstream")
    parser.add_argument("--flash",          action="store_true", help="Flash bitstream")
    parser.add_argument("--sys-clk-freq",   default=200e6,       help="System clock frequency (default: 200MHz)")
    parser.add_argument("--with-spi-flash", action="store_true", help="Enable SPI Flash (MMAPed)")
    parser.add_argument("--with-hyperram",  action="store_true", help="Enable HyperRAM")
    builder_args(parser)
    soc_core_args(parser)
    args = parser.parse_args()

    soc = BaseSoC(
        sys_clk_freq   = int(float(args.sys_clk_freq)),
        with_spi_flash = args.with_spi_flash,
        with_hyperram  = args.with_hyperram,
         **soc_core_argdict(args))
    builder = Builder(soc, **builder_argdict(args))
    builder.build(run=args.build)

    if args.load:
        prog = soc.platform.create_programmer()
        prog.load_bitstream(os.path.join(builder.gateware_dir, f"{soc.build_name}.bit"))

    if args.flash:
        from litex.build.openfpgaloader import OpenFPGALoader
        prog = OpenFPGALoader("titanium_ti60_f225")
        prog.flash(0, os.path.join(builder.gateware_dir, f"{soc.build_name}.hex"))

if __name__ == "__main__":
    main()
<commit_msg>titanium_ti60_f225_dev_kit: Add HyperRAM separator.<commit_after>#!/usr/bin/env python3

#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Franck Jullien <franck.jullien@collshade.fr>
# SPDX-License-Identifier: BSD-2-Clause

import argparse

from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer

from litex_boards.platforms import efinix_titanium_ti60_f225_dev_kit

from litex.build.generic_platform import *

from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex.soc.integration.soc import SoCRegion

from litehyperbus.core.hyperbus import HyperRAM

# CRG ----------------------------------------------------------------------------------------------

class _CRG(Module):
    def __init__(self, platform, sys_clk_freq):
        self.clock_domains.cd_sys = ClockDomain()

        # # #

        clk25 = platform.request("clk25")
        rst_n = platform.request("user_btn", 0)

        # PLL
        self.submodules.pll = pll = TITANIUMPLL(platform)
        self.comb += pll.reset.eq(~rst_n)
        pll.register_clkin(clk25, 25e6)
        # You can use CLKOUT0 only for clocks with a maximum frequency of 4x
        # (integer) of the reference clock. If all your system clocks do not fall within
        # this range, you should dedicate one unused clock for CLKOUT0.
        pll.create_clkout(None, 25e6)

        pll.create_clkout(self.cd_sys, sys_clk_freq, with_reset=True)

# BaseSoC ------------------------------------------------------------------------------------------

class BaseSoC(SoCCore):
    def __init__(self, sys_clk_freq=int(200e6), with_spi_flash=False, with_hyperram=False, **kwargs):
        platform = efinix_titanium_ti60_f225_dev_kit.Platform()

        # SoCCore ----------------------------------------------------------------------------------
        SoCCore.__init__(self, platform, sys_clk_freq,
            ident         = "LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit",
            ident_version = True,
            **kwargs
        )

        # CRG --------------------------------------------------------------------------------------
        self.submodules.crg = _CRG(platform, sys_clk_freq)

        # SPI Flash --------------------------------------------------------------------------------
        if with_spi_flash:
            from litespi.modules import W25Q64JW
            from litespi.opcodes import SpiNorFlashOpCodes as Codes
            self.add_spi_flash(mode="1x", module=W25Q64JW(Codes.READ_1_1_1), with_master=True)

        # HyperRAM ---------------------------------------------------------------------------------
        if with_hyperram:
            self.submodules.hyperram = HyperRAM(platform.request("hyperram"), latency=7)
            self.bus.add_slave("main_ram", slave=self.hyperram.bus, region=SoCRegion(origin=0x40000000, size=32*1024*1024))

# Build --------------------------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(description="LiteX SoC on Efinix Titanium Ti60 F225 Dev Kit")
    parser.add_argument("--build",          action="store_true", help="Build bitstream")
    parser.add_argument("--load",           action="store_true", help="Load bitstream")
    parser.add_argument("--flash",          action="store_true", help="Flash bitstream")
    parser.add_argument("--sys-clk-freq",   default=200e6,       help="System clock frequency (default: 200MHz)")
    parser.add_argument("--with-spi-flash", action="store_true", help="Enable SPI Flash (MMAPed)")
    parser.add_argument("--with-hyperram",  action="store_true", help="Enable HyperRAM")
    builder_args(parser)
    soc_core_args(parser)
    args = parser.parse_args()

    soc = BaseSoC(
        sys_clk_freq   = int(float(args.sys_clk_freq)),
        with_spi_flash = args.with_spi_flash,
        with_hyperram  = args.with_hyperram,
         **soc_core_argdict(args))
    builder = Builder(soc, **builder_argdict(args))
    builder.build(run=args.build)

    if args.load:
        prog = soc.platform.create_programmer()
        prog.load_bitstream(os.path.join(builder.gateware_dir, f"{soc.build_name}.bit"))

    if args.flash:
        from litex.build.openfpgaloader import OpenFPGALoader
        prog = OpenFPGALoader("titanium_ti60_f225")
        prog.flash(0, os.path.join(builder.gateware_dir, f"{soc.build_name}.hex"))

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  oneweather.py
#
#  Copyright 2015 pocmon <pocmon@sina.com> MIT License
#

import json
import urllib.request
import urllib.parse
import gzip
import sys
import unicodedata

# 默认城市
city = '深圳'
# 判断汉字条件
chz = True
phz = True

def winfo(city):  # 显示天气信息

    print("\n城市：" + city + "\n")

    # 网址中汉字处理，城市名称
    city = urllib.parse.quote(city)

    # 获取JSON
    url = "http://wthrcdn.etouch.cn/weather_mini?city=%s" % (city)
    mys = urllib.request.urlopen(url).read()
    # 解压JSON，并转码
    myw = gzip.decompress(mys).decode('utf-8')

    myj = json.loads(myw)

    if myj["desc"] == "OK":
        city = myj["data"]["city"]
        wendu = myj["data"]["wendu"]
        weather = myj["data"]["ganmao"]

        print("实时天气：")
        print("\t" + (wendu + "℃ ").ljust(5) + weather + "\n")

        print("今日天气：")
        high = myj["data"]["forecast"][0]["high"]  # 最高温度
        fengxiang = myj["data"]["forecast"][0]["fengxiang"]  # 风向
        fengli = myj["data"]["forecast"][0]["fengli"]  # 风力
        type = myj["data"]["forecast"][0]["type"]  # 天气类型
        low = myj["data"]["forecast"][0]["low"]  # 最低温度
        date = myj["data"]["forecast"][0]["date"]  # 日期
        print("\t" + date.ljust(10) + type.ljust(10) + high.ljust(10) + low.ljust(10) + fengli.ljust(8) + fengxiang)

        print("\n未来四天预报：")
        for wday in range(1, 5):
            high = myj["data"]["forecast"][wday]["high"]  # 最高温度
            fengxiang = myj["data"]["forecast"][wday]["fengxiang"]  # 风向
            fengli = myj["data"]["forecast"][wday]["fengli"]  # 风力
            type = myj["data"]["forecast"][wday]["type"]  # 天气类型
            low = myj["data"]["forecast"][wday]["low"]  # 最低温度
            date = myj["data"]["forecast"][wday]["date"]  # 日期
            print("\t" + date.ljust(10) + type.ljust(10) + high.ljust(10) + low.ljust(10) + fengli.ljust(8) + fengxiang)

        print("\n昨日天气：")
        high = myj["data"]["yesterday"]["high"]  # 最高温度
        fengxiang = myj["data"]["yesterday"]["fx"]  # 风向
        fengli = myj["data"]["yesterday"]["fl"]  # 风力
        type = myj["data"]["yesterday"]["type"]  # 天气类型
        low = myj["data"]["yesterday"]["low"]  # 最低温度
        date = myj["data"]["yesterday"]["date"]  # 日期
        print("\t" + date.ljust(10) + type.ljust(10) + high.ljust(10) + low.ljust(10) + fengli.ljust(8) + fengxiang)

    else:
        print("要查询的城市未找到，请检查城市名称是否正确！本程序只支持中国城市名称！")

if len(sys.argv) > 2:
    print("\n请输入正确的命令：oneweather.py [中国城市名称]，目前本程序只支持一个城市的天气询查！")
    print("如：oneweather.py 北京 , 不带城市名称，默认城市：" + city)
else:
    if len(sys.argv) == 1:

        print("\n可输入城市名参数：oneweather.py [中国城市名称/默认" + city + "],如：oneweather.py 北京")
        winfo(city)

    elif len(sys.argv) == 2:

        # 判断参数是否为汉字，只支持汉字
        for cs in range(0, len(sys.argv[1])):

            if unicodedata.east_asian_width(sys.argv[1][cs]) != 'Na':
                chz = True
            else:
                chz = False

            phz = (chz and phz)

        if not phz:
            print("\n请检查城市名称是否正确，本程序只支持中国中文城市名称！")
        else:
            city = sys.argv[1]
            winfo(city)
<commit_msg>v0.03<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  oneweather.py
#
#  Copyright 2015 pocmon <pocmon@sina.com> MIT License
#

import json
import urllib.request
import urllib.parse
import gzip
import sys
import unicodedata

# 默认城市
city = '深圳'
# 判断汉字条件
chz = True
phz = True

def winfo(city):  # 显示天气信息

    print("\n城市：" + city + "\n")

    # 网址中汉字处理，城市名称
    city = urllib.parse.quote(city)

    # 获取JSON
    url = "http://wthrcdn.etouch.cn/weather_mini?city=%s" % (city)
    mys = urllib.request.urlopen(url).read()
    # 解压JSON，并转码
    myw = gzip.decompress(mys).decode('utf-8')

    myj = json.loads(myw)

    if myj["desc"] == "OK":
        city = myj["data"]["city"]
        wendu = myj["data"]["wendu"]
        weather = myj["data"]["ganmao"]

        print("实时天气：")
        print("\t" + (wendu + "℃ ").ljust(5) + weather + "\n")

        print("今日天气：")
        high = myj["data"]["forecast"][0]["high"]  # 最高温度
        fengxiang = myj["data"]["forecast"][0]["fengxiang"]  # 风向
        fengli = myj["data"]["forecast"][0]["fengli"]  # 风力
        type = myj["data"]["forecast"][0]["type"]  # 天气类型
        low = myj["data"]["forecast"][0]["low"]  # 最低温度
        date = myj["data"]["forecast"][0]["date"]  # 日期
        print("\t" + date + "\t" + type + "\t" + high.ljust(10) + low.ljust(10) + fengli + "\t" + fengxiang)

        print("\n未来四天预报：")
        for wday in range(1, 5):
            high = myj["data"]["forecast"][wday]["high"]  # 最高温度
            fengxiang = myj["data"]["forecast"][wday]["fengxiang"]  # 风向
            fengli = myj["data"]["forecast"][wday]["fengli"]  # 风力
            type = myj["data"]["forecast"][wday]["type"]  # 天气类型
            low = myj["data"]["forecast"][wday]["low"]  # 最低温度
            date = myj["data"]["forecast"][wday]["date"]  # 日期
            print("\t" + date + "\t" + type + "\t" + high.ljust(10) + low.ljust(10) + fengli + "\t" + fengxiang)

        print("\n昨日天气：")
        high = myj["data"]["yesterday"]["high"]  # 最高温度
        fengxiang = myj["data"]["yesterday"]["fx"]  # 风向
        fengli = myj["data"]["yesterday"]["fl"]  # 风力
        type = myj["data"]["yesterday"]["type"]  # 天气类型
        low = myj["data"]["yesterday"]["low"]  # 最低温度
        date = myj["data"]["yesterday"]["date"]  # 日期
        print("\t" + date + "\t" + type + "\t" + high.ljust(10) + low.ljust(10) + fengli + "\t" + fengxiang)

    else:
        print("要查询的城市未找到，请检查城市名称是否正确！本程序只支持中国城市名称！")

if len(sys.argv) > 2:
    print("\n请输入正确的命令：oneweather.py [中国城市名称]，目前本程序只支持一个城市的天气询查！")
    print("如：oneweather.py 北京 , 不带城市名称，默认城市：" + city)
else:
    if len(sys.argv) == 1:

        print("\n可输入城市名参数：oneweather.py [中国城市名称/默认" + city + "],如：oneweather.py 北京")
        winfo(city)

    elif len(sys.argv) == 2:

        # 判断参数是否为汉字，只支持汉字
        for cs in range(0, len(sys.argv[1])):

            if unicodedata.east_asian_width(sys.argv[1][cs]) != 'Na':
                chz = True
            else:
                chz = False

            phz = (chz and phz)

        if not phz:
            print("\n请检查城市名称是否正确，本程序只支持中国中文城市名称！")
        else:
            city = sys.argv[1]
            winfo(city)
<|endoftext|>


<commit_before>"""IPython terminal interface using prompt_toolkit in place of readline"""
from __future__ import print_function

from IPython.core.interactiveshell import InteractiveShell
from IPython.utils.py3compat import PY3
from traitlets import Bool, Unicode, Dict

from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, HasSelection
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.styles import PygmentsStyle

from pygments.styles import get_style_by_name
from pygments.lexers import Python3Lexer, PythonLexer
from pygments.token import Token

from .pt_inputhooks import get_inputhook_func

class IPythonPTCompleter(Completer):
    """Adaptor to provide IPython completions to prompt_toolkit"""
    def __init__(self, ipy_completer):
        self.ipy_completer = ipy_completer

    def get_completions(self, document, complete_event):
        if not document.current_line.strip():
            return

        used, matches = self.ipy_completer.complete(
                            line_buffer=document.current_line,
                            cursor_pos=document.cursor_position_col
        )
        start_pos = -len(used)
        for m in matches:
            yield Completion(m, start_position=start_pos)

class PTInteractiveShell(InteractiveShell):
    colors_force = True

    pt_cli = None

    vi_mode = Bool(False, config=True,
        help="Use vi style keybindings at the prompt",
    )

    highlighting_style = Unicode('', config=True,
        help="The name of a Pygments style to use for syntax highlighting"
    )

    highlighting_style_overrides = Dict(config=True,
        help="Override highlighting format for specific tokens"
    )

    def get_prompt_tokens(self, cli):
        return [
            (Token.Prompt, 'In ['),
            (Token.PromptNum, str(self.execution_count)),
            (Token.Prompt, ']: '),
        ]

    def get_continuation_tokens(self, cli, width):
        return [
            (Token.Prompt, (' ' * (width - 2)) + ': '),
        ]

    def init_prompt_toolkit_cli(self):
        kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
        insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
        # Ctrl+J == Enter, seemingly
        @kbmanager.registry.add_binding(Keys.ControlJ,
                            filter=(HasFocus(DEFAULT_BUFFER)
                                    & ~HasSelection()
                                    & insert_mode
                                   ))
        def _(event):
            b = event.current_buffer
            if not b.document.on_last_line:
                b.newline()
                return

            status, indent = self.input_splitter.check_complete(b.document.text)

            if (status != 'incomplete') and b.accept_action.is_returnable:
                b.accept_action.validate_and_handle(event.cli, b)
            else:
                b.insert_text('\n' + (' ' * (indent or 0)))

        @kbmanager.registry.add_binding(Keys.ControlC)
        def _(event):
            event.current_buffer.reset()

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        app = create_prompt_application(multiline=True,
                            lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
                            get_prompt_tokens=self.get_prompt_tokens,
                            get_continuation_tokens=self.get_continuation_tokens,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(self.Completer),
                            enable_history_search=True,
                            style=style,
        )

        self.pt_cli = CommandLineInterface(app,
                           eventloop=create_eventloop(self.inputhook))

    def __init__(self, *args, **kwargs):
        super(PTInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.keep_running = True

    def ask_exit(self):
        self.keep_running = False

    def interact(self):
        while self.keep_running:
            print(self.separate_in, end='')
            try:
                document = self.pt_cli.run()
            except EOFError:
                if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
                    self.ask_exit()

            else:
                if document:
                    self.run_cell(document.text, store_history=True)

    _inputhook = None
    def inputhook(self, context):
        if self._inputhook is not None:
            self._inputhook(context)

    def enable_gui(self, gui=None):
        if gui:
            self._inputhook = get_inputhook_func(gui)
        else:
            self._inputhook = None

if __name__ == '__main__':
    PTInteractiveShell.instance().interact()
<commit_msg>Implement pre-filling prompt from set_next_input()<commit_after>"""IPython terminal interface using prompt_toolkit in place of readline"""
from __future__ import print_function

from IPython.core.interactiveshell import InteractiveShell
from IPython.utils.py3compat import PY3
from traitlets import Bool, Unicode, Dict

from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasFocus, HasSelection
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.styles import PygmentsStyle

from pygments.styles import get_style_by_name
from pygments.lexers import Python3Lexer, PythonLexer
from pygments.token import Token

from .pt_inputhooks import get_inputhook_func

class IPythonPTCompleter(Completer):
    """Adaptor to provide IPython completions to prompt_toolkit"""
    def __init__(self, ipy_completer):
        self.ipy_completer = ipy_completer

    def get_completions(self, document, complete_event):
        if not document.current_line.strip():
            return

        used, matches = self.ipy_completer.complete(
                            line_buffer=document.current_line,
                            cursor_pos=document.cursor_position_col
        )
        start_pos = -len(used)
        for m in matches:
            yield Completion(m, start_position=start_pos)

class PTInteractiveShell(InteractiveShell):
    colors_force = True

    pt_cli = None

    vi_mode = Bool(False, config=True,
        help="Use vi style keybindings at the prompt",
    )

    highlighting_style = Unicode('', config=True,
        help="The name of a Pygments style to use for syntax highlighting"
    )

    highlighting_style_overrides = Dict(config=True,
        help="Override highlighting format for specific tokens"
    )

    def get_prompt_tokens(self, cli):
        return [
            (Token.Prompt, 'In ['),
            (Token.PromptNum, str(self.execution_count)),
            (Token.Prompt, ']: '),
        ]

    def get_continuation_tokens(self, cli, width):
        return [
            (Token.Prompt, (' ' * (width - 2)) + ': '),
        ]

    def init_prompt_toolkit_cli(self):
        kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
        insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
        # Ctrl+J == Enter, seemingly
        @kbmanager.registry.add_binding(Keys.ControlJ,
                            filter=(HasFocus(DEFAULT_BUFFER)
                                    & ~HasSelection()
                                    & insert_mode
                                   ))
        def _(event):
            b = event.current_buffer
            if not b.document.on_last_line:
                b.newline()
                return

            status, indent = self.input_splitter.check_complete(b.document.text)

            if (status != 'incomplete') and b.accept_action.is_returnable:
                b.accept_action.validate_and_handle(event.cli, b)
            else:
                b.insert_text('\n' + (' ' * (indent or 0)))

        @kbmanager.registry.add_binding(Keys.ControlC)
        def _(event):
            event.current_buffer.reset()

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        app = create_prompt_application(multiline=True,
                            lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
                            get_prompt_tokens=self.get_prompt_tokens,
                            get_continuation_tokens=self.get_continuation_tokens,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(self.Completer),
                            enable_history_search=True,
                            style=style,
        )

        self.pt_cli = CommandLineInterface(app,
                           eventloop=create_eventloop(self.inputhook))

    def __init__(self, *args, **kwargs):
        super(PTInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.keep_running = True

    def ask_exit(self):
        self.keep_running = False

    rl_next_input = None

    def pre_prompt(self):
        if self.rl_next_input:
            self.pt_cli.application.buffer.text = self.rl_next_input
            self.rl_next_input = None

    def interact(self):
        while self.keep_running:
            print(self.separate_in, end='')

            try:
                document = self.pt_cli.run(pre_run=self.pre_prompt)
            except EOFError:
                if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
                    self.ask_exit()

            else:
                if document:
                    self.run_cell(document.text, store_history=True)

    _inputhook = None
    def inputhook(self, context):
        if self._inputhook is not None:
            self._inputhook(context)

    def enable_gui(self, gui=None):
        if gui:
            self._inputhook = get_inputhook_func(gui)
        else:
            self._inputhook = None

if __name__ == '__main__':
    PTInteractiveShell.instance().interact()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from crispy_forms import layout
from django import forms
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy
from django_cradmin.viewhelpers import multiselect2
from django_cradmin.viewhelpers import multiselect2view

from devilry.apps.core import models as core_models
from devilry.devilry_cradmin import devilry_listbuilder
from devilry.devilry_cradmin import devilry_listfilter
from devilry.utils import datetimeutils
from devilry.devilry_deadlinemanagement.views import viewutils

class SelectedAssignmentGroupForm(forms.Form):
    qualification_modelclass = core_models.AssignmentGroup
    invalid_qualification_item_message = ugettext_lazy(
        'Something went wrong. This may happen if someone else performed a similar operation '
        'while you where selecting. Refresh the page and try again')

    #: The items selected as ModelMultipleChoiceField.
    #: If some or all items should be selected by default, override this.
    selected_items = forms.ModelMultipleChoiceField(

        # No items are selectable by default.
        queryset=None,

        # Used if the object to select for some reason does
        # not exist(has been deleted or altered in some way)
        error_messages={
            'invalid_choice': invalid_qualification_item_message,
        }
    )

    def __init__(self, *args, **kwargs):
        selectable_qualification_items_queryset = kwargs.pop('selectable_items_queryset')
        self.assignment = kwargs.pop('assignment')
        super(SelectedAssignmentGroupForm, self).__init__(*args, **kwargs)
        self.fields['selected_items'].queryset = selectable_qualification_items_queryset

class AssignmentGroupTargetRenderer(multiselect2.target_renderer.Target):

    #: The selected item as it is shown when selected.
    #: By default this is :class:`.SelectedQualificationItem`.
    selected_target_renderer = devilry_listbuilder.assignmentgroup.ExaminerMultiselectItemValue

    #: A descriptive name for the items selected.
    descriptive_item_name = ugettext_lazy('assignment group')

    def get_move_deadline_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer move_dealine_text',
            'Move deadline for selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_submit_button_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer submit_button_text',
            'New attempt for selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_with_items_title(self):
        return pgettext_lazy(
            'assignment_group_target_renderer with_items_title',
            'Selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_without_items_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer without_items_text',
            'No %(what)s selected'
        ) % {'what': self.descriptive_item_name}

    def get_hidden_fields(self):
        return [
            layout.Hidden(name='post_type_received_data', value='')
        ]

class AssignmentGroupMultiSelectListFilterView(viewutils.DeadlineManagementMixin, multiselect2view.ListbuilderFilterView):
    """
    Abstract class that implements ``ListbuilderFilterView``.

    Adds anonymization and activity filters for the ``AssignmentGroup``s.
    Fetches the ``AssignmentGroups`` through :meth:`~.get_unfiltered_queryset_for_role` and joins
    necessary tables used for anonymzation and annotations used by viewfilters.
    """
    model = core_models.AssignmentGroup
    value_renderer_class = devilry_listbuilder.assignmentgroup.ExaminerMultiselectItemValue
    template_name = 'devilry_deadlinemanagement/deadline-bulk-multiselect-filterlistview.django.html'
    handle_deadline_type = None

    def get_pagetitle(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view pagetitle',
                             'Select groups')

    def get_pageheading(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view pageheading',
                             'Select groups')

    def get_page_subheading(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view page_subheading',
                             'Select the groups you want to manage the deadline for.')

    def get_default_paginate_by(self, queryset):
        return 5

    def __add_filterlist_items_anonymous_uses_custom_candidate_ids(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchAnonymousUsesCustomCandidateIds())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByAnonymousUsesCustomCandidateIds())

    def __add_filterlist_items_anonymous(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchAnonymous())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByAnonymous(include_points=False))

    def __add_filterlist_items_not_anonymous(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchNotAnonymous())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByNotAnonymous(include_points=False))

    def __add_anonymization_filters_for_items(self, filterlist):
        """
        Adds filters based on the :attr:`~.devilry.apps.core.models.anonymizationmode` of the
        ``Assignment``.
        """
        if self.assignment.uses_custom_candidate_ids:
            self.__add_filterlist_items_anonymous_uses_custom_candidate_ids(filterlist=filterlist)
        else:
            self.__add_filterlist_items_anonymous(filterlist=filterlist)

    def add_filterlist_items(self, filterlist):
        super(AssignmentGroupMultiSelectListFilterView, self).add_filterlist_items(filterlist)
        if self.assignment.is_anonymous:
            self.__add_anonymization_filters_for_items(filterlist=filterlist)
        else:
            self.__add_filterlist_items_not_anonymous(filterlist=filterlist)
        filterlist.append(devilry_listfilter.assignmentgroup.ActivityFilter())
        filterlist.append(devilry_listfilter.assignmentgroup.IsPassingGradeFilter())
        filterlist.append(devilry_listfilter.assignmentgroup.PointsFilter())

    def get_unfiltered_queryset_for_role(self, role):
        return self.get_queryset_for_role_on_handle_deadline_type(role=role)

    def get_target_renderer_class(self):
        return AssignmentGroupTargetRenderer

    def get_form_class(self):
        return SelectedAssignmentGroupForm

    def get_value_and_frame_renderer_kwargs(self):
        return {
            'assignment': self.assignment
        }

    def get_form_kwargs(self):
        kwargs = super(AssignmentGroupMultiSelectListFilterView, self).get_form_kwargs()
        kwargs['selectable_items_queryset'] = self.get_unfiltered_queryset_for_role(self.assignment)
        kwargs['assignment'] = self.assignment
        return kwargs

    def get_target_renderer_kwargs(self):
        kwargs = super(AssignmentGroupMultiSelectListFilterView, self).get_target_renderer_kwargs()
        kwargs['form_action'] = self.request.cradmin_app.reverse_appurl(
            viewname='manage-deadline-post',
            kwargs={
                'deadline': datetimeutils.datetime_to_url_string(self.deadline),
                'handle_deadline': self.handle_deadline_type
            })
        return kwargs

    def get_selected_groupids(self, posted_form):
        return [item.id for item in posted_form.cleaned_data['selected_items']]

    def get_group_anonymous_displaynames(self, form):
        """
        Build a list of anonymized displaynames for the groups that where corrected.

        Args:
            form: posted form

        Returns:
            (list): list of anonymized displaynames for the groups
        """
        groups = form.cleaned_data['selected_items']
        anonymous_display_names = [
            unicode(group.get_anonymous_displayname(assignment=self.assignment))
            for group in groups]
        return anonymous_display_names

    def get_success_url(self):
        """
        Defaults to the apps indexview.
        """
        return self.request.cradmin_app.reverse_appindexurl()

    def get_filterlist_url(self, filters_string):
        return self.request.cradmin_app.reverse_appurl(
            'select-groups-manually-filter', kwargs={
                'deadline': datetimeutils.datetime_to_url_string(self.deadline),
                'handle_deadline': self.handle_deadline_type,
                'filters_string': filters_string
            })
<commit_msg>#993: More generic text on multiselect button<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from crispy_forms import layout
from django import forms
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy
from django_cradmin.viewhelpers import multiselect2
from django_cradmin.viewhelpers import multiselect2view

from devilry.apps.core import models as core_models
from devilry.devilry_cradmin import devilry_listbuilder
from devilry.devilry_cradmin import devilry_listfilter
from devilry.utils import datetimeutils
from devilry.devilry_deadlinemanagement.views import viewutils

class SelectedAssignmentGroupForm(forms.Form):
    qualification_modelclass = core_models.AssignmentGroup
    invalid_qualification_item_message = ugettext_lazy(
        'Something went wrong. This may happen if someone else performed a similar operation '
        'while you where selecting. Refresh the page and try again')

    #: The items selected as ModelMultipleChoiceField.
    #: If some or all items should be selected by default, override this.
    selected_items = forms.ModelMultipleChoiceField(

        # No items are selectable by default.
        queryset=None,

        # Used if the object to select for some reason does
        # not exist(has been deleted or altered in some way)
        error_messages={
            'invalid_choice': invalid_qualification_item_message,
        }
    )

    def __init__(self, *args, **kwargs):
        selectable_qualification_items_queryset = kwargs.pop('selectable_items_queryset')
        self.assignment = kwargs.pop('assignment')
        super(SelectedAssignmentGroupForm, self).__init__(*args, **kwargs)
        self.fields['selected_items'].queryset = selectable_qualification_items_queryset

class AssignmentGroupTargetRenderer(multiselect2.target_renderer.Target):

    #: The selected item as it is shown when selected.
    #: By default this is :class:`.SelectedQualificationItem`.
    selected_target_renderer = devilry_listbuilder.assignmentgroup.ExaminerMultiselectItemValue

    #: A descriptive name for the items selected.
    descriptive_item_name = ugettext_lazy('groups')

    def get_move_deadline_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer move_dealine_text',
            'Move deadline for selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_submit_button_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer submit_button_text',
            'Continue with selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_with_items_title(self):
        return pgettext_lazy(
            'assignment_group_target_renderer with_items_title',
            'Selected %(what)s'
        ) % {'what': self.descriptive_item_name}

    def get_without_items_text(self):
        return pgettext_lazy(
            'assignment_group_target_renderer without_items_text',
            'No %(what)s selected'
        ) % {'what': self.descriptive_item_name}

    def get_hidden_fields(self):
        return [
            layout.Hidden(name='post_type_received_data', value='')
        ]

class AssignmentGroupMultiSelectListFilterView(viewutils.DeadlineManagementMixin, multiselect2view.ListbuilderFilterView):
    """
    Abstract class that implements ``ListbuilderFilterView``.

    Adds anonymization and activity filters for the ``AssignmentGroup``s.
    Fetches the ``AssignmentGroups`` through :meth:`~.get_unfiltered_queryset_for_role` and joins
    necessary tables used for anonymzation and annotations used by viewfilters.
    """
    model = core_models.AssignmentGroup
    value_renderer_class = devilry_listbuilder.assignmentgroup.ExaminerMultiselectItemValue
    template_name = 'devilry_deadlinemanagement/deadline-bulk-multiselect-filterlistview.django.html'
    handle_deadline_type = None

    def get_pagetitle(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view pagetitle',
                             'Select groups')

    def get_pageheading(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view pageheading',
                             'Select groups')

    def get_page_subheading(self):
        return pgettext_lazy('assignment_group_multiselect_list_filter_view page_subheading',
                             'Select the groups you want to manage the deadline for.')

    def get_default_paginate_by(self, queryset):
        return 5

    def __add_filterlist_items_anonymous_uses_custom_candidate_ids(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchAnonymousUsesCustomCandidateIds())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByAnonymousUsesCustomCandidateIds())

    def __add_filterlist_items_anonymous(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchAnonymous())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByAnonymous(include_points=False))

    def __add_filterlist_items_not_anonymous(self, filterlist):
        filterlist.append(devilry_listfilter.assignmentgroup.SearchNotAnonymous())
        filterlist.append(devilry_listfilter.assignmentgroup.OrderByNotAnonymous(include_points=False))

    def __add_anonymization_filters_for_items(self, filterlist):
        """
        Adds filters based on the :attr:`~.devilry.apps.core.models.anonymizationmode` of the
        ``Assignment``.
        """
        if self.assignment.uses_custom_candidate_ids:
            self.__add_filterlist_items_anonymous_uses_custom_candidate_ids(filterlist=filterlist)
        else:
            self.__add_filterlist_items_anonymous(filterlist=filterlist)

    def add_filterlist_items(self, filterlist):
        super(AssignmentGroupMultiSelectListFilterView, self).add_filterlist_items(filterlist)
        if self.assignment.is_anonymous:
            self.__add_anonymization_filters_for_items(filterlist=filterlist)
        else:
            self.__add_filterlist_items_not_anonymous(filterlist=filterlist)
        filterlist.append(devilry_listfilter.assignmentgroup.ActivityFilter())
        filterlist.append(devilry_listfilter.assignmentgroup.IsPassingGradeFilter())
        filterlist.append(devilry_listfilter.assignmentgroup.PointsFilter())

    def get_unfiltered_queryset_for_role(self, role):
        return self.get_queryset_for_role_on_handle_deadline_type(role=role)

    def get_target_renderer_class(self):
        return AssignmentGroupTargetRenderer

    def get_form_class(self):
        return SelectedAssignmentGroupForm

    def get_value_and_frame_renderer_kwargs(self):
        return {
            'assignment': self.assignment
        }

    def get_form_kwargs(self):
        kwargs = super(AssignmentGroupMultiSelectListFilterView, self).get_form_kwargs()
        kwargs['selectable_items_queryset'] = self.get_unfiltered_queryset_for_role(self.assignment)
        kwargs['assignment'] = self.assignment
        return kwargs

    def get_target_renderer_kwargs(self):
        kwargs = super(AssignmentGroupMultiSelectListFilterView, self).get_target_renderer_kwargs()
        kwargs['form_action'] = self.request.cradmin_app.reverse_appurl(
            viewname='manage-deadline-post',
            kwargs={
                'deadline': datetimeutils.datetime_to_url_string(self.deadline),
                'handle_deadline': self.handle_deadline_type
            })
        return kwargs

    def get_selected_groupids(self, posted_form):
        return [item.id for item in posted_form.cleaned_data['selected_items']]

    def get_group_anonymous_displaynames(self, form):
        """
        Build a list of anonymized displaynames for the groups that where corrected.

        Args:
            form: posted form

        Returns:
            (list): list of anonymized displaynames for the groups
        """
        groups = form.cleaned_data['selected_items']
        anonymous_display_names = [
            unicode(group.get_anonymous_displayname(assignment=self.assignment))
            for group in groups]
        return anonymous_display_names

    def get_success_url(self):
        """
        Defaults to the apps indexview.
        """
        return self.request.cradmin_app.reverse_appindexurl()

    def get_filterlist_url(self, filters_string):
        return self.request.cradmin_app.reverse_appurl(
            'select-groups-manually-filter', kwargs={
                'deadline': datetimeutils.datetime_to_url_string(self.deadline),
                'handle_deadline': self.handle_deadline_type,
                'filters_string': filters_string
            })
<|endoftext|>


<commit_before># -*- coding: ISO-8859-15 -*-
''' GML support'''
# =================================================================
#
# $Id$
#
# Authors: Tom Kralidis <tomkralidis@hotmail.com>
#
# Copyright (c) 2010 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import util
from owslib import crs

TYPES = ['gml:Point', 'gml:LineString', 'gml:Polygon', 'gml:Envelope']

DEFAULT_SRS = crs.Crs('urn:x-ogc:def:crs:EPSG:6.11:4326')

class Geometry(object):
    ''' base geometry class '''

    def __init__(self, element):
        ''' initialize geometry parser  '''

        self.type = None
        self.wkt = None
        self.crs = None
        self._exml = element

        ''' return OGC WKT for GML geometry '''

        operand = element.xpath(
        '|'.join(TYPES), namespaces={'gml':'http://www.opengis.net/gml'})[0]

        if operand.attrib.has_key('srsName'):
            self.crs = crs.Crs(operand.attrib['srsName'])

        self.type = util.xmltag_split(operand.tag)

        if util.xmltag_split(operand.tag) == 'Point':
            self._get_point()
        elif util.xmltag_split(operand.tag) == 'LineString':
            self._get_linestring()
        elif util.xmltag_split(operand.tag) == 'Polygon':
            self._get_polygon()
        elif util.xmltag_split(operand.tag) == 'Envelope':
            self._get_envelope()

        # reproject data if needed
        if self.crs and self.crs.code != 4326:
            self.wkt = self.transform(self.crs.code, DEFAULT_SRS.code)
        else:  # no reprojection
            self.crs = DEFAULT_SRS

    def _get_point(self):
        ''' Parse gml:Point '''

        tmp = self._exml.find(util.nspath_eval('gml:Point/gml:pos'))

        if tmp is None:
            raise RuntimeError, ('Invalid gml:Point geometry.  Missing gml:pos')
        else:
            xypoint = tmp.text.split()
            self.wkt = 'POINT(%s %s)' % (xypoint[0], xypoint[1])

    def _get_linestring(self):
        ''' Parse gml:LineString'''

        tmp = self._exml.find(util.nspath_eval('gml:LineString/gml:posList'))

        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:LineString geometry.  Missing gml:posList')
        else:
            self.wkt = 'LINESTRING(%s)' % _poslist2wkt(tmp.text)

    def _get_polygon(self):
        ''' Parse gml:Polygon'''

        tmp = self._exml.find('.//%s' % util.nspath_eval('gml:posList'))

        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:LineString geometry.  Missing gml:posList')
        else:
            self.wkt = 'POLYGON((%s))' % _poslist2wkt(tmp.text)

    def _get_envelope(self):
        ''' Parse gml:Envelope '''

        tmp = self._exml.find(util.nspath_eval('gml:Envelope/gml:lowerCorner'))
        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:Envelope geometry.  Missing gml:lowerCorner')
        else:
            lower_left = tmp.text

        tmp = self._exml.find(util.nspath_eval('gml:Envelope/gml:upperCorner'))
        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:Envelope geometry.  Missing gml:upperCorner')
        else:
            upper_right = tmp.text

        xymin = lower_left.split()
        xymax = upper_right.split()

        if len(xymin) != 2 or len(xymax) != 2:
            raise RuntimeError, \
           ('Invalid gml:Envelope geometry. \
           gml:lowerCorner and gml:upperCorner must hold both lat and long.')

        self.wkt = util.bbox2wktpolygon('%s,%s,%s,%s' %
        (xymin[1], xymin[0], xymax[1], xymax[0]))

    def _poslist2wkt(poslist):
        ''' Repurpose gml:posList into WKT aware list '''

        tmp = poslist.split()
        poslist2 = []

        xlist = tmp[1::2]
        ylist = tmp[::2]

        for i, j in zip(xlist, ylist):
            poslist2.append('%s %s' % (i, j))

        return ', '.join(poslist2)

    def transform(self, src, dest):
        ''' transform coordinates from one CRS to another '''

        import pyproj
        from shapely.geometry import Point, LineString, Polygon
        from shapely.wkt import loads

        proj_src = pyproj.Proj(init='epsg:%s' % src)
        proj_dst = pyproj.Proj(init='epsg:%s' % dest)

        geom = loads(self.wkt)

        if geom.type == 'Point':
            newgeom = Point(pyproj.transform(proj_src, proj_dst, geom.x, geom.y))
            wkt2 = newgeom.wkt

        elif geom.type == 'LineString':
            vertices = []
            for vertice in list(geom.coords):
                newgeom = pyproj.transform(proj_src, proj_dst, vertice[0], vertice[1])
                vertices.append(newgeom)

            linestring = LineString(vertices)

            wkt2 = linestring.wkt

        elif geom.type == 'Polygon':
            vertices = []
            for vertice in list(geom.exterior.coords):
                newgeom = pyproj.transform(proj_src, proj_dst, vertice[0], vertice[1])
                vertices.append(newgeom)

            polygon = Polygon(vertices)

            wkt2 = polygon.wkt

        return wkt2
<commit_msg>fix axis order headaches for incoming request geometry (#35)<commit_after># -*- coding: ISO-8859-15 -*-
''' GML support'''
# =================================================================
#
# $Id$
#
# Authors: Tom Kralidis <tomkralidis@hotmail.com>
#
# Copyright (c) 2010 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import util
from owslib import crs

TYPES = ['gml:Point', 'gml:LineString', 'gml:Polygon', 'gml:Envelope']

DEFAULT_SRS = crs.Crs('urn:x-ogc:def:crs:EPSG:6.11:4326')

class Geometry(object):
    ''' base geometry class '''

    def __init__(self, element):
        ''' initialize geometry parser  '''

        self.type = None
        self.wkt = None
        self.crs = None
        self._exml = element

        ''' return OGC WKT for GML geometry '''

        operand = element.xpath(
        '|'.join(TYPES), namespaces={'gml':'http://www.opengis.net/gml'})[0]

        if operand.attrib.has_key('srsName'):
            self.crs = crs.Crs(operand.attrib['srsName'])
        else:
            self.crs = DEFAULT_SRS

        self.type = util.xmltag_split(operand.tag)

        if util.xmltag_split(operand.tag) == 'Point':
            self._get_point()
        elif util.xmltag_split(operand.tag) == 'LineString':
            self._get_linestring()
        elif util.xmltag_split(operand.tag) == 'Polygon':
            self._get_polygon()
        elif util.xmltag_split(operand.tag) == 'Envelope':
            self._get_envelope()

        # reproject data if needed
        if self.crs is not None and self.crs.code != 4326:
            self.wkt = self.transform(self.crs.code, DEFAULT_SRS.code)

    def _get_point(self):
        ''' Parse gml:Point '''

        tmp = self._exml.find(util.nspath_eval('gml:Point/gml:pos'))

        if tmp is None:
            raise RuntimeError, ('Invalid gml:Point geometry.  Missing gml:pos')
        else:
            xypoint = tmp.text.split()
            if self.crs.axisorder == 'yx':
                self.wkt = 'POINT(%s %s)' % (xypoint[1], xypoint[0])
            else:
                self.wkt = 'POINT(%s %s)' % (xypoint[0], xypoint[1])

    def _get_linestring(self):
        ''' Parse gml:LineString'''

        tmp = self._exml.find(util.nspath_eval('gml:LineString/gml:posList'))

        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:LineString geometry.  Missing gml:posList')
        else:
            self.wkt = 'LINESTRING(%s)' % _poslist2wkt(tmp.text, axisorder)

    def _get_polygon(self):
        ''' Parse gml:Polygon'''

        tmp = self._exml.find('.//%s' % util.nspath_eval('gml:posList'))

        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:LineString geometry.  Missing gml:posList')
        else:
            self.wkt = 'POLYGON((%s))' % _poslist2wkt(tmp.text, axisorder)

    def _get_envelope(self):
        ''' Parse gml:Envelope '''

        tmp = self._exml.find(util.nspath_eval('gml:Envelope/gml:lowerCorner'))
        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:Envelope geometry.  Missing gml:lowerCorner')
        else:
            lower_left = tmp.text

        tmp = self._exml.find(util.nspath_eval('gml:Envelope/gml:upperCorner'))
        if tmp is None:
            raise RuntimeError, \
            ('Invalid gml:Envelope geometry.  Missing gml:upperCorner')
        else:
            upper_right = tmp.text

        llmin = lower_left.split()
        urmax = upper_right.split()

        if len(llmin) < 2 or len(urmax) < 2:
            raise RuntimeError, ('Invalid gml:Envelope geometry. \
            gml:lowerCorner and gml:upperCorner must hold at least x and y')

        if self.crs.axisorder == 'yx':
            self.wkt = util.bbox2wktpolygon('%s,%s,%s,%s' %
            (llmin[1], llmin[0], urmax[1], urmax[0]))
        else:
            self.wkt = util.bbox2wktpolygon('%s,%s,%s,%s' %
            (llmin[0], llmin[1], urmax[0], urmax[1]))

    def _poslist2wkt(poslist, axisorder):
        ''' Repurpose gml:posList into WKT aware list '''

        tmp = poslist.split()
        poslist2 = []

        xlist = tmp[1::2]
        ylist = tmp[::2]

        if axisorder == 'yx':
            for i, j in zip(ylist, xlist):
                poslist2.append('%s %s' % (i, j))
        else:
            for i, j in zip(xlist, ylist):
                poslist2.append('%s %s' % (i, j))

        return ', '.join(poslist2)

    def transform(self, src, dest):
        ''' transform coordinates from one CRS to another '''

        import pyproj
        from shapely.geometry import Point, LineString, Polygon
        from shapely.wkt import loads

        proj_src = pyproj.Proj(init='epsg:%s' % src)
        proj_dst = pyproj.Proj(init='epsg:%s' % dest)

        geom = loads(self.wkt)

        if geom.type == 'Point':
            newgeom = Point(pyproj.transform(proj_src, proj_dst, geom.x, geom.y))
            wkt2 = newgeom.wkt

        elif geom.type == 'LineString':
            vertices = []
            for vertice in list(geom.coords):
                newgeom = pyproj.transform(proj_src, proj_dst, vertice[0], vertice[1])
                vertices.append(newgeom)

            linestring = LineString(vertices)

            wkt2 = linestring.wkt

        elif geom.type == 'Polygon':
            vertices = []
            for vertice in list(geom.exterior.coords):
                newgeom = pyproj.transform(proj_src, proj_dst, vertice[0], vertice[1])
                vertices.append(newgeom)

            polygon = Polygon(vertices)

            wkt2 = polygon.wkt

        return wkt2
<|endoftext|>


<commit_before>from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core import validators
from django.db import backend, connection
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.manager import Manager
from django.db.models.base import Model, AdminOptions
from django.db.models.fields import *
from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel, TABULAR, STACKED
from django.db.models.fields.generic import GenericRelation, GenericRel, GenericForeignKey
from django.db.models import signals
from django.utils.functional import curry
from django.utils.text import capfirst

# Admin stages.
ADD, CHANGE, BOTH = 1, 2, 3

# Decorator. Takes a function that returns a tuple in this format:
#     (viewname, viewargs, viewkwargs)
# Returns a function that calls urlresolvers.reverse() on that data, to return
# the URL for those parameters.
def permalink(func):
    from django.core.urlresolvers import reverse
    def inner(*args, **kwargs):
        bits = func(*args, **kwargs)
        viewname = bits[0]
        return reverse(bits[0], None, *bits[1:3])
    return inner

class LazyDate(object):
    """
    Use in limit_choices_to to compare the field to dates calculated at run time
    instead of when the model is loaded.  For example::

        ... limit_choices_to = {'date__gt' : models.LazyDate(days=-3)} ...

    which will limit the choices to dates greater than three days ago.
    """
    def __init__(self, **kwargs):
        self.delta = datetime.timedelta(**kwargs)

    def __str__(self):
        return str(self.__get_value__())

    def __repr__(self):
        return "<LazyDate: %s>" % self.delta

    def __get_value__(self):
        return (datetime.datetime.now() + self.delta).date()

    def __getattr__(self, attr):
        if attr == 'delta':
            # To fix ticket #3377. Note that normal access to LazyDate.delta
            # (after construction) will still work, because they don't go
            # through __getattr__). This is mainly needed for unpickling.
            raise AttributeError
        return getattr(self.__get_value__(), attr)
<commit_msg>Updated [4497] to use something closer to the English language in the comment.<commit_after>from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core import validators
from django.db import backend, connection
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.manager import Manager
from django.db.models.base import Model, AdminOptions
from django.db.models.fields import *
from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel, TABULAR, STACKED
from django.db.models.fields.generic import GenericRelation, GenericRel, GenericForeignKey
from django.db.models import signals
from django.utils.functional import curry
from django.utils.text import capfirst

# Admin stages.
ADD, CHANGE, BOTH = 1, 2, 3

# Decorator. Takes a function that returns a tuple in this format:
#     (viewname, viewargs, viewkwargs)
# Returns a function that calls urlresolvers.reverse() on that data, to return
# the URL for those parameters.
def permalink(func):
    from django.core.urlresolvers import reverse
    def inner(*args, **kwargs):
        bits = func(*args, **kwargs)
        viewname = bits[0]
        return reverse(bits[0], None, *bits[1:3])
    return inner

class LazyDate(object):
    """
    Use in limit_choices_to to compare the field to dates calculated at run time
    instead of when the model is loaded.  For example::

        ... limit_choices_to = {'date__gt' : models.LazyDate(days=-3)} ...

    which will limit the choices to dates greater than three days ago.
    """
    def __init__(self, **kwargs):
        self.delta = datetime.timedelta(**kwargs)

    def __str__(self):
        return str(self.__get_value__())

    def __repr__(self):
        return "<LazyDate: %s>" % self.delta

    def __get_value__(self):
        return (datetime.datetime.now() + self.delta).date()

    def __getattr__(self, attr):
        if attr == 'delta':
            # To fix ticket #3377. Note that normal accesses to LazyDate.delta
            # (after construction) will still work, because they don't go
            # through __getattr__). This is mainly needed for unpickling.
            raise AttributeError
        return getattr(self.__get_value__(), attr)
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# - Neither the name of Carnegie Mellon University nor the names of its
#   contributors may be used to endorse or promote products derived from this
#   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import logging, numpy, openravepy, os, tempfile
from ..util import CopyTrajectory
from base import BasePlanner, PlanningError, PlanningMethod
from openravepy import PlannerStatus

class OpenRAVERetimer(BasePlanner):
    def __init__(self, algorithm):
        super(OpenRAVERetimer, self).__init__()
        self.algorithm = algorithm

    @PlanningMethod
    def RetimeTrajectory(self, robot, path):
        RetimeTrajectory = openravepy.planningutils.RetimeTrajectory

        output_traj = CopyTrajectory(path, env=self.env)
        status = RetimeTrajectory(output_traj, False, 1., 1., self.algorithm)

        if status not in [ PlannerStatus.HasSolution,
                           PlannerStatus.InterruptedWithSolution ]:
            raise PlanningError('Retimer returned with status {0:s}.'.format(
                                str(status)))

        return output_traj

class ParabolicRetimer(OpenRAVERetimer):
    def __init__(self):
        super(ParabolicRetimer, self).__init__('ParabolicTrajectoryRetimer')
<commit_msg>Call SimplifyTrajectory before an OpenRAVE retimer.<commit_after>#!/usr/bin/env python

# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# - Neither the name of Carnegie Mellon University nor the names of its
#   contributors may be used to endorse or promote products derived from this
#   software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import logging, numpy, openravepy, os, tempfile
from ..util import CopyTrajectory, SimplifyTrajectory
from base import BasePlanner, PlanningError, PlanningMethod
from openravepy import PlannerStatus

class OpenRAVERetimer(BasePlanner):
    def __init__(self, algorithm):
        super(OpenRAVERetimer, self).__init__()
        self.algorithm = algorithm

    @PlanningMethod
    def RetimeTrajectory(self, robot, path):
        RetimeTrajectory = openravepy.planningutils.RetimeTrajectory

        cspec = path.GetConfigurationSpecification()
        group = cspec.GetGroupFromName('joint_values')
        if group.interpolation != 'linear':
            raise PlanningError(
                'Path has interpolation of type "{:s}"; only "linear"'
                ' interpolation is supported.'.format(
                    group.interpolation
                )
            )

        # Copy the input trajectory into the planning environment. This is
        # necessary for two reasons: (1) the input trajectory may be in another
        # environment and/or (2) the retimer modifies the trajectory in-place.
        input_path = CopyTrajectory(path, env=self.env)

        # Remove co-linear waypoints. Some of the default OpenRAVE retimers do
        # not perform this check internally (e.g. ParabolicTrajectoryRetimer).
        output_traj = SimplifyTrajectory(input_path, robot)

        # Compute the timing. This happens in-place.
        status = RetimeTrajectory(output_traj, False, 1., 1., self.algorithm)

        if status not in [ PlannerStatus.HasSolution,
                           PlannerStatus.InterruptedWithSolution ]:
            raise PlanningError('Retimer returned with status {0:s}.'.format(
                                str(status)))

        return output_traj

class ParabolicRetimer(OpenRAVERetimer):
    def __init__(self):
        super(ParabolicRetimer, self).__init__('ParabolicTrajectoryRetimer')

class ParabolicSmoother(OpenRAVERetimer):
    def __init__(self):
        super(ParabolicRetimer, self).__init__('ParabolicSmoother')
<|endoftext|>


<commit_before>"""
The sequence execution part of

  Prefrontal neural correlates of memory for sequences.
  B. B. Averbeck & D. Lee, JNS 2007.

  http://www.jneurosci.org/content/27/9/2204.abstract

"""
from __future__ import division

import numpy as np

from pycog import tasktools

#-----------------------------------------------------------------------------------------
# Sequence-related definitions
#-----------------------------------------------------------------------------------------

# Sequence definitions
sequences = {
    1: [4] + [5, 1, 0],
    2: [4] + [3, 1, 2],
    3: [4] + [3, 7, 8],
    4: [4] + [5, 7, 6],
    5: [4] + [5, 1, 2],
    6: [4] + [3, 1, 0],
    7: [4] + [3, 7, 6],
    8: [4] + [5, 7, 8]
}
nseq = len(sequences)

# Possible targets from each position
#
#   0 1 2
#   3 4 5
#   6 7 8
#
options = {
    1: [0, 2],
    3: [1, 7],
    4: [3, 5],
    5: [1, 7],
    7: [6, 8]
}

#-----------------------------------------------------------------------------------------
# Network structure
#-----------------------------------------------------------------------------------------

Nin  = 9 + nseq
N    = 200
Nout = 2

# For addressing inputs
DOTS     = range(9)
SEQUENCE = range(9, 9+nseq)

# E/I
ei, EXC, INH = tasktools.generate_ei(N)
Nexc = len(EXC)
Ninh = len(INH)

# Inputs
EXC_SENSORY = EXC[:Nexc//2]
INH_SENSORY = INH[:Ninh//2]
EXC_MOTOR   = EXC[Nexc//2:]
INH_MOTOR   = INH[Ninh//2:]

# Time constant
tau = 50

#-----------------------------------------------------------------------------------------
# Noise
#-----------------------------------------------------------------------------------------

var_rec = 0.01**2

#-----------------------------------------------------------------------------------------
# Input connectivity
#-----------------------------------------------------------------------------------------

Cin = np.zeros((N, Nin))
Cin[EXC_SENSORY + INH_SENSORY,:] = 1

#-----------------------------------------------------------------------------------------
# Recurrent connectivity
#-----------------------------------------------------------------------------------------

rng = np.random.RandomState(1)

Crec = np.zeros((N, N))
for i in EXC_SENSORY:
    Crec[i,EXC_SENSORY] = 1*(rng.uniform(size=len(EXC_SENSORY)) < 0.8)
    Crec[i,i]           = 0
    Crec[i,EXC_MOTOR]   = 1*(rng.uniform(size=len(EXC_MOTOR)) < 0.2)
    Crec[i,INH_SENSORY] = np.sum(Crec[i,EXC])/len(INH_SENSORY)
for i in EXC_MOTOR:
    Crec[i,EXC]       = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,i]         = 0
    Crec[i,INH_MOTOR] = np.sum(Crec[i,EXC])/len(INH_MOTOR)
for i in INH_SENSORY:
    Crec[i,EXC]         = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,INH_SENSORY] = np.sum(Crec[i,EXC])/(len(INH_SENSORY) - 1)
    Crec[i,i]           = 0
for i in INH_MOTOR:
    Crec[i,EXC]       = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,INH_MOTOR] = np.sum(Crec[i,EXC])/(len(INH_MOTOR) - 1)
    Crec[i,i]         = 0

#-----------------------------------------------------------------------------------------
# Output connectivity
#-----------------------------------------------------------------------------------------

Cout = np.zeros((Nout, N))
Cout[:,EXC_MOTOR + INH_MOTOR] = 1

#-----------------------------------------------------------------------------------------
# Task structure
#-----------------------------------------------------------------------------------------

# Screen coordinates
x0, y0 = -0.5, -0.5
dx, dy = +0.5, +0.5

# Convert dots to screen coordinates
def target_position(k):
    j = 2 - k//3
    i = k % 3

    return x0+i*dx, y0+j*dy

def generate_trial(rng, dt, params):
    #---------------------------------------------------------------------------------
    # Select task condition
    #---------------------------------------------------------------------------------

    if params['name'] in ['gradient', 'test']:
        seq = params.get('seq', rng.choice(sequences.keys()))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % nseq
        if b == 0:
            generate_trial.seqs = rng.permutation(nseq)

        seq = generate_trial.seqs[b] + 1
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    iti      = 1000
    fixation = 1000
    M1       = 500
    M2       = 500
    M3       = 500
    T        = iti + fixation + M1 + M2 + M3

    epochs = {
        'iti':      (0, iti),
        'fixation': (iti, iti + fixation),
        'M1':       (iti + fixation, iti + fixation + M1),
        'M2':       (iti + fixation + M1, iti + fixation + M1 + M2),
        'M3':       (iti + fixation + M1 + M2, iti + fixation + M1 + M2 + M3),
        }
    epochs['T'] = T

    #---------------------------------------------------------------------------------
    # Trial info
    #---------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    trial['info'] = {'seq': seq}

    #---------------------------------------------------------------------------------
    # Inputs
    #---------------------------------------------------------------------------------

    # Input matrix
    X = np.zeros((len(t), Nin))

    # Which sequence?
    X[:,SEQUENCE[seq-1]] = 1

    # Sequence
    sequence = sequences[seq]

    # Options
    X[e['fixation'],sequence[0]] = 1
    for I, J in zip([e['M1'], e['M2'], e['M3']],
                    [[sequence[0]] + options[sequence[0]],
                     [sequence[1]] + options[sequence[1]],
                     [sequence[2]] + options[sequence[2]]]):
        for j in J:
            X[I,j] = 1

    # Inputs
    trial['inputs'] = X

    #---------------------------------------------------------------------------------
    # Target output
    #---------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix
        M = np.zeros((len(t), Nout)) # Mask matrix

        # Hold gaze
        Y[e['fixation'],:] = target_position(sequence[0])
        Y[e['M1'],:]       = target_position(sequence[1])
        Y[e['M2'],:]       = target_position(sequence[2])
        Y[e['M3'],:]       = target_position(sequence[3])

        # We don't constrain the intertrial interval
        M[e['fixation']+e['M1']+e['M2']+e['M3'],:] = 1

        # Output and mask
        trial['outputs'] = Y
        trial['mask']    = M

    #---------------------------------------------------------------------------------

    return trial

min_error = 0.05

mode         = 'continuous'
n_validation = 100*nseq
<commit_msg>Initial commit<commit_after>"""
The sequence execution part of

  Prefrontal neural correlates of memory for sequences.
  B. B. Averbeck & D. Lee, JNS 2007.

  http://www.jneurosci.org/content/27/9/2204.abstract

"""
from __future__ import division

import numpy as np

from pycog import tasktools

#-----------------------------------------------------------------------------------------
# Sequence-related definitions
#-----------------------------------------------------------------------------------------

# Sequence definitions
sequences = {
    1: [4] + [5, 1, 0],
    2: [4] + [3, 1, 2],
    3: [4] + [3, 7, 8],
    4: [4] + [5, 7, 6],
    5: [4] + [5, 1, 2],
    6: [4] + [3, 1, 0],
    7: [4] + [3, 7, 6],
    8: [4] + [5, 7, 8]
}
nseq = len(sequences)

# Possible targets from each position
#
#   0 1 2
#   3 4 5
#   6 7 8
#
options = {
    1: [0, 2],
    3: [1, 7],
    4: [3, 5],
    5: [1, 7],
    7: [6, 8]
}
#
#-----------------------------------------------------------------------------------------
# Network structure
#-----------------------------------------------------------------------------------------

Nin  = 9 + nseq
N    = 200
Nout = 2

# For addressing inputs
DOTS     = range(9)
SEQUENCE = range(9, 9+nseq)

# E/I
ei, EXC, INH = tasktools.generate_ei(N)
Nexc = len(EXC)
Ninh = len(INH)

# Inputs
EXC_SENSORY = EXC[:Nexc//2]
INH_SENSORY = INH[:Ninh//2]
EXC_MOTOR   = EXC[Nexc//2:]
INH_MOTOR   = INH[Ninh//2:]

# Time constant
tau = 50

#-----------------------------------------------------------------------------------------
# Noise
#-----------------------------------------------------------------------------------------

var_rec = 0.01**2

#-----------------------------------------------------------------------------------------
# Input connectivity
#-----------------------------------------------------------------------------------------

Cin = np.zeros((N, Nin))
Cin[EXC_SENSORY + INH_SENSORY,:] = 1

#-----------------------------------------------------------------------------------------
# Recurrent connectivity
#-----------------------------------------------------------------------------------------

rng = np.random.RandomState(1)

Crec = np.zeros((N, N))
for i in EXC_SENSORY:
    Crec[i,EXC_SENSORY] = 1*(rng.uniform(size=len(EXC_SENSORY)) < 0.8)
    Crec[i,i]           = 0
    Crec[i,EXC_MOTOR]   = 1*(rng.uniform(size=len(EXC_MOTOR)) < 0.2)
    Crec[i,INH_SENSORY] = np.sum(Crec[i,EXC])/len(INH_SENSORY)
for i in EXC_MOTOR:
    Crec[i,EXC]       = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,i]         = 0
    Crec[i,INH_MOTOR] = np.sum(Crec[i,EXC])/len(INH_MOTOR)
for i in INH_SENSORY:
    Crec[i,EXC]         = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,INH_SENSORY] = np.sum(Crec[i,EXC])/(len(INH_SENSORY) - 1)
    Crec[i,i]           = 0
for i in INH_MOTOR:
    Crec[i,EXC]       = 1*(rng.uniform(size=len(EXC)) < 0.8)
    Crec[i,INH_MOTOR] = np.sum(Crec[i,EXC])/(len(INH_MOTOR) - 1)
    Crec[i,i]         = 0

#-----------------------------------------------------------------------------------------
# Output connectivity
#-----------------------------------------------------------------------------------------

Cout = np.zeros((Nout, N))
Cout[:,EXC_MOTOR + INH_MOTOR] = 1

#-----------------------------------------------------------------------------------------
# Task structure
#-----------------------------------------------------------------------------------------

# Screen coordinates
x0, y0 = -0.5, -0.5
dx, dy = +0.5, +0.5

# Convert dots to screen coordinates
def target_position(k):
    j = 2 - k//3
    i = k % 3

    return x0+i*dx, y0+j*dy

def generate_trial(rng, dt, params):
    #---------------------------------------------------------------------------------
    # Select task condition
    #---------------------------------------------------------------------------------

    if params['name'] in ['gradient', 'test']:
        seq = params.get('seq', rng.choice(sequences.keys()))
    elif params['name'] == 'validation':
        b = params['minibatch_index'] % nseq
        if b == 0:
            generate_trial.seqs = rng.permutation(nseq)

        seq = generate_trial.seqs[b] + 1
    else:
        raise ValueError("Unknown trial type.")

    #-------------------------------------------------------------------------------------
    # Epochs
    #-------------------------------------------------------------------------------------

    iti      = 1000
    fixation = 1000
    M1       = 500
    M2       = 500
    M3       = 500
    T        = iti + fixation + M1 + M2 + M3

    epochs = {
        'iti':      (0, iti),
        'fixation': (iti, iti + fixation),
        'M1':       (iti + fixation, iti + fixation + M1),
        'M2':       (iti + fixation + M1, iti + fixation + M1 + M2),
        'M3':       (iti + fixation + M1 + M2, iti + fixation + M1 + M2 + M3),
        }
    epochs['T'] = T

    #---------------------------------------------------------------------------------
    # Trial info
    #---------------------------------------------------------------------------------

    t, e  = tasktools.get_epochs_idx(dt, epochs) # Time, task epochs in discrete time
    trial = {'t': t, 'epochs': epochs}           # Trial

    trial['info'] = {'seq': seq}

    #---------------------------------------------------------------------------------
    # Inputs
    #---------------------------------------------------------------------------------

    # Input matrix
    X = np.zeros((len(t), Nin))

    # Which sequence?
    X[:,SEQUENCE[seq-1]] = 1

    # Sequence
    sequence = sequences[seq]

    # Options
    X[e['fixation'],sequence[0]] = 1
    for I, J in zip([e['M1'], e['M2'], e['M3']],
                    [[sequence[0]] + options[sequence[0]],
                     [sequence[1]] + options[sequence[1]],
                     [sequence[2]] + options[sequence[2]]]):
        for j in J:
            X[I,j] = 1

    # Inputs
    trial['inputs'] = X

    #---------------------------------------------------------------------------------
    # Target output
    #---------------------------------------------------------------------------------

    if params.get('target_output', False):
        Y = np.zeros((len(t), Nout)) # Output matrix
        M = np.zeros((len(t), Nout)) # Mask matrix

        # Hold gaze
        Y[e['fixation'],:] = target_position(sequence[0])
        Y[e['M1'],:]       = target_position(sequence[1])
        Y[e['M2'],:]       = target_position(sequence[2])
        Y[e['M3'],:]       = target_position(sequence[3])

        # We don't constrain the intertrial interval
        M[e['fixation']+e['M1']+e['M2']+e['M3'],:] = 1

        # Output and mask
        trial['outputs'] = Y
        trial['mask']    = M

    #---------------------------------------------------------------------------------

    return trial

min_error = 0.05

mode         = 'continuous'
n_validation = 100*nseq
<|endoftext|>


<commit_before>from simplecoin import currencies
from simplecoin.exceptions import InvalidAddressException
from simplecoin.tests import UnitTest

class TestConfig(UnitTest):
    def test_config_eq(self):
        self.assertNotEqual(currencies['TCO'], currencies['DOGE'])
        self.assertEqual(currencies['TCO'], currencies['TCO'])
        assert currencies['TCO'] > currencies['DOGE']
        assert currencies['DOGE'] < currencies['TCO']
        assert None not in currencies.values()

    def test_lookup_payable(self):
        currencies.lookup_payable_addr("185cYTmEaTtKmBZc8aSGCr9v2VCDLqQHgR")
        currencies.lookup_payable_addr("DAbhwsnEq5TjtBP5j76TinhUqqLTktDAnD")
        self.assertRaises(
            InvalidAddressException,
            lambda: currencies.lookup_payable_addr(
                "VkbHY8ua2TjxdL7gY2uMfCz3TxMzMPgmRR"))
        self.assertRaises(
            InvalidAddressException,
            lambda: currencies.lookup_payable_addr(
                "test"))
<commit_msg>Closes #99<commit_after>from simplecoin import currencies, chains
from simplecoin.exceptions import InvalidAddressException
from simplecoin.tests import UnitTest

class TestConfig(UnitTest):
    def test_config_eq(self):
        self.assertNotEqual(currencies['TCO'], currencies['DOGE'])
        self.assertEqual(currencies['TCO'], currencies['TCO'])
        assert currencies['TCO'] > currencies['DOGE']
        assert currencies['DOGE'] < currencies['TCO']
        assert None not in currencies.values()

    def test_lookup_payable(self):
        currencies.lookup_payable_addr("185cYTmEaTtKmBZc8aSGCr9v2VCDLqQHgR")
        currencies.lookup_payable_addr("DAbhwsnEq5TjtBP5j76TinhUqqLTktDAnD")
        self.assertRaises(
            InvalidAddressException,
            lambda: currencies.lookup_payable_addr(
                "VkbHY8ua2TjxdL7gY2uMfCz3TxMzMPgmRR"))
        self.assertRaises(
            InvalidAddressException,
            lambda: currencies.lookup_payable_addr(
                "test"))

    def test_chain_repr(self):
        repr(chains.values()[0])
<|endoftext|>