<commit_before>#!/usr/bin/env python
# (Supposedly allows execution without python keyword)

__author__ = "whitehaven"

from sys import stdin
import argparse

BLOCK_SIZE = 8

def binlist(char):  # returns list of 1|0
    result = []
    while char:
        if char & 1 == 1:
            result.append(1)
        else:
            result.append(0)
        char >>= 1
    if len(result) < 8:
        for leftover in range(len(result), 8):
            result.append(0)
    result.reverse()
    return result  # must be size 8

# function to convert chars to TF values to garble chars (8 bit, [0-255] range)
# receives strings
def str2garble(subject):
    results = []  # will be list of lists of 1|0
    for element in subject:
        print(binlist(element))
        results.append(binlist(element))
    return results

# function to convert garble chars to TF values into chars
# receives strings of garble

encryptThis = bytearray("Shiz", 'utf-8')

print(str2garble(encryptThis))

# argparse these options
#	-h help
#	-i inline
# ?	-s? standard input
#	-d decrypt mode

# take -o= for file output
# otherwise, std input

# > > encryption:
# break down to chars
# 	convert to binaryish arrays
#	encrypt
# 	output

# > > decryption:
# read in 8-byte bits
#	decrypt
# 	convert to char
# 	output
<commit_msg>random outputs to correct ranges are output as ints<commit_after>#!/usr/bin/env python
# (Supposedly allows execution without python keyword)

__author__ = "whitehaven"

from sys import stdin
import argparse
from random import randint

BLOCK_SIZE = 8

def garblist(blist):
    garbledlist = []
    for element in blist:
        if element == 1:
            garbledlist.append(randint(ord('n'), ord('z')))
        else:  # if element == 0
            garbledlist.append(randint(ord('a'), ord('m')))
    return garbledlist

# this function is separate because it is useful elsewhere
def binlist(char):  # returns list of 1|0
    result = []
    while char:
        if char & 1 == 1:
            result.append(1)
        else:
            result.append(0)
        char >>= 1
    if len(result) < 8:
        for leftover in range(len(result), 8):
            result.append(0)
    result.reverse()
    return result  # will be size 8

# function to convert chars to TF values to garble chars (8 bit, [0-255] range)
# receives strings
def str2garble(subject):
    results = []  # will be list of lists of 1|0
    garbled = []  # will be list of lists of a-m|n-z
    for element in subject:
        results.append(binlist(element))
    print(results)
    # now, results has list of lists of the string passed in (0 and 1s)
    for element in results:
        garbled.append(garblist(element))

    return garbled

# function to convert garble chars to TF values into chars
# receives strings of garble

encryptThis = bytearray("Shiz", 'utf-8')

print(str2garble(encryptThis))

# argparse these options
#	-h help
#	-i inline
# ?	-s? standard input
#	-d decrypt mode

# take -o= for file output
# otherwise, std input

# > > encryption:
# break down to chars
# 	convert to binaryish arrays
#	encrypt
# 	output

# > > decryption:
# read in 8-byte bits
#	decrypt
# 	convert to char
# 	output
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
############################################################################################
#
#    Zoook e-sale for OpenERP, Open Source Management Solution
#    Copyright (C) 2011 Zikzakmedia S.L. (<http://www.zikzakmedia.com>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
############################################################################################

from django.db import models

from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language
from transmeta import TransMeta

from transurl import catalog_url, product_url

'''OpenERP Models'''
class ProductCategory(models.Model):
    """ProductCategory OpenERP"""
    __metaclass__ = TransMeta

    name = models.CharField(_('Name'), max_length=128)
    description = models.TextField(_('Description'), null=True, blank=True)
    slug = models.SlugField(_('slug'), max_length=128, help_text=_("This is a unique identifier that allows your contents to display its detail view, ex 'how-can-i-contribute'"), unique=True)
    fslug = models.CharField(_('Full Slug'), max_length=256, null=True, blank=True)
    metatitle = models.CharField(_('Title'), max_length=128, null=True, blank=True)
    metakeyword = models.TextField(_('Keyword'), null=True, blank=True)
    metadescription = models.TextField(_('Description'), null=True, blank=True)
    AVAILABLE_SORT_BY_CHOICES = (
        ('default', 'Use Config Settings'),
        ('position', 'Best Value'),
        ('name', 'Name'),
        ('price', 'Price')
    )
    available_sort_by = models.CharField(_('Available Product Listing (Sort By)'), choices=AVAILABLE_SORT_BY_CHOICES, default='default', max_length=40)
    DEFAULT_SORT_BY_CHOICES = (
        ('default', 'Use Config Settings'),
        ('position', 'Best Value'),
        ('name', 'Name'),
        ('price', 'Price')
    )
    default_sort_by = models.CharField(_('Default Product Listing Sort (Sort By)'), choices=DEFAULT_SORT_BY_CHOICES,  default='default', max_length=40)
    status = models.BooleanField(_('Status'), default=False)
    parent = models.ForeignKey('ProductCategory', null=True, blank=True)
    sequence = models.IntegerField(_('Sequence'), null=True, blank=True)

    class Meta:
        db_table = 'product_category'
        verbose_name = _('category')
        verbose_name_plural = _('categories')
        translate = (
            'name',
            'description',
            'slug',
            'fslug',
            'metatitle',
            'metakeyword',
            'metadescription',
            )

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/%s/%s/' % (get_language(), catalog_url[get_language()], self.fslug)

class ProductTemplate(models.Model):
    """ProductTemplate OpenERP"""
    __metaclass__ = TransMeta

    name = models.CharField(_('Name'), max_length=128)
    categ = models.ManyToManyField('ProductCategory', null=True, blank=True, related_name='categ_s')
    shortdescription = models.TextField(_('Short Description'), null=True, blank=True)
    description = models.TextField(_('Sale Description'), null=True, blank=True)
    slug = models.CharField(_('Slug'), max_length=128, null=True, blank=True)
    VISIBILITY_CHOICES = (
        ('all', 'All'),
        ('search', 'Search'),
        ('catalog', 'Catalog'),
        ('none', 'None'),
    )
    visibility = models.CharField(_('Visibility'), choices=VISIBILITY_CHOICES, default='', max_length=40)
    metatitle = models.CharField(_('Meta Title'), max_length=128, null=True, blank=True)
    metadescription = models.TextField(_('Meta Description'), null=True, blank=True)
    metakeyword = models.TextField(_('Meta Keyword'), null=True, blank=True)
    crosssells = models.ManyToManyField('ProductTemplate', blank=True, related_name='crosssells_s')
    related = models.ManyToManyField('ProductTemplate', blank=True, related_name='related_s')
    upsells = models.ManyToManyField('ProductTemplate', blank=True, related_name='upsells_s')
    uom = models.CharField(_('Unit Of Measure'), max_length=128)
    uos = models.CharField(_('Unit of Sale'), max_length=128)
    volume = models.FloatField(_('Volume'), null=True, blank=True)
    warranty = models.FloatField(_('Warranty (months)'),null=True, blank=True)
    weight = models.FloatField(_('Gross weight'),null=True, blank=True)
    weight_net = models.FloatField(_('Net weight'), null=True, blank=True)
    status = models.BooleanField(_('Status'), default=False)

    class Meta:
        db_table = 'product_template'
        verbose_name = _('template')
        verbose_name_plural = _('templates')
        translate = ('name', 'slug', 'shortdescription', 'description', 'metadescription', 'metakeyword', 'metatitle')

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/%s/%s' % (get_language(), product_url[get_language()], self.slug)

class ProductProduct(models.Model):
    """ProductProduct OpenERP"""
    __metaclass__ = TransMeta

    product_tmpl = models.ForeignKey('ProductTemplate')
    active = models.BooleanField(_('Active'), default=False)
    code = models.CharField(_('Code'), max_length=128, null=True, blank=True) #Reference
    ean13 = models.CharField(_('EAN13'), max_length=128, null=True, blank=True)
    price = models.FloatField(_('Pricelist'))
    manufacturer = models.CharField(_('Manufacturer'), max_length=128, null=True, blank=True)

    class Meta:
        db_table = 'product_product'
        verbose_name = _('product')
        verbose_name_plural = _('products')
#        translate = ( )

    def __unicode__(self):
        return self.code

class ProductManufacturerAttribute(models.Model):
    """ProductManufacturerAttribute OpenERP"""

    name = models.CharField(_('Attribute'), max_length=128, null=True, blank=True)
    product = models.ForeignKey('ProductProduct', null=True, blank=True)
    value = models.CharField(_('Value'), max_length=128, null=True, blank=True)

    class Meta:
        db_table = 'product_manufacturer_attribute'
        verbose_name = _('attribute')
        verbose_name_plural = _('attributes')

    def __unicode__(self):
        return self.name

class ProductImages(models.Model):
    """ProductImages OpenERP"""

    name = models.CharField(_('Image Title'), max_length=128, null=True, blank=True)
    product = models.ForeignKey('ProductProduct', null=True, blank=True)
    filename = models.CharField(_('File Location'), max_length=128, null=True, blank=True)
    base_image = models.BooleanField(_('Base Image'), default=False)
    exclude = models.BooleanField(_('Exclude'), default=False)

    class Meta:
        db_table = 'product_images'
        verbose_name = _('image')
        verbose_name_plural = _('images')

    def __unicode__(self):
        return self.name
<commit_msg>[FIX] Catalog get_absolute_url: without / end slug<commit_after># -*- encoding: utf-8 -*-
############################################################################################
#
#    Zoook e-sale for OpenERP, Open Source Management Solution
#    Copyright (C) 2011 Zikzakmedia S.L. (<http://www.zikzakmedia.com>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
############################################################################################

from django.db import models

from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language
from transmeta import TransMeta

from transurl import catalog_url, product_url

'''OpenERP Models'''
class ProductCategory(models.Model):
    """ProductCategory OpenERP"""
    __metaclass__ = TransMeta

    name = models.CharField(_('Name'), max_length=128)
    description = models.TextField(_('Description'), null=True, blank=True)
    slug = models.SlugField(_('slug'), max_length=128, help_text=_("This is a unique identifier that allows your contents to display its detail view, ex 'how-can-i-contribute'"), unique=True)
    fslug = models.CharField(_('Full Slug'), max_length=256, null=True, blank=True)
    metatitle = models.CharField(_('Title'), max_length=128, null=True, blank=True)
    metakeyword = models.TextField(_('Keyword'), null=True, blank=True)
    metadescription = models.TextField(_('Description'), null=True, blank=True)
    AVAILABLE_SORT_BY_CHOICES = (
        ('default', 'Use Config Settings'),
        ('position', 'Best Value'),
        ('name', 'Name'),
        ('price', 'Price')
    )
    available_sort_by = models.CharField(_('Available Product Listing (Sort By)'), choices=AVAILABLE_SORT_BY_CHOICES, default='default', max_length=40)
    DEFAULT_SORT_BY_CHOICES = (
        ('default', 'Use Config Settings'),
        ('position', 'Best Value'),
        ('name', 'Name'),
        ('price', 'Price')
    )
    default_sort_by = models.CharField(_('Default Product Listing Sort (Sort By)'), choices=DEFAULT_SORT_BY_CHOICES,  default='default', max_length=40)
    status = models.BooleanField(_('Status'), default=False)
    parent = models.ForeignKey('ProductCategory', null=True, blank=True)
    sequence = models.IntegerField(_('Sequence'), null=True, blank=True)

    class Meta:
        db_table = 'product_category'
        verbose_name = _('category')
        verbose_name_plural = _('categories')
        translate = (
            'name',
            'description',
            'slug',
            'fslug',
            'metatitle',
            'metakeyword',
            'metadescription',
            )

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/%s/%s' % (get_language(), catalog_url[get_language()], self.fslug)

class ProductTemplate(models.Model):
    """ProductTemplate OpenERP"""
    __metaclass__ = TransMeta

    name = models.CharField(_('Name'), max_length=128)
    categ = models.ManyToManyField('ProductCategory', null=True, blank=True, related_name='categ_s')
    shortdescription = models.TextField(_('Short Description'), null=True, blank=True)
    description = models.TextField(_('Sale Description'), null=True, blank=True)
    slug = models.CharField(_('Slug'), max_length=128, null=True, blank=True)
    VISIBILITY_CHOICES = (
        ('all', 'All'),
        ('search', 'Search'),
        ('catalog', 'Catalog'),
        ('none', 'None'),
    )
    visibility = models.CharField(_('Visibility'), choices=VISIBILITY_CHOICES, default='', max_length=40)
    metatitle = models.CharField(_('Meta Title'), max_length=128, null=True, blank=True)
    metadescription = models.TextField(_('Meta Description'), null=True, blank=True)
    metakeyword = models.TextField(_('Meta Keyword'), null=True, blank=True)
    crosssells = models.ManyToManyField('ProductTemplate', blank=True, related_name='crosssells_s')
    related = models.ManyToManyField('ProductTemplate', blank=True, related_name='related_s')
    upsells = models.ManyToManyField('ProductTemplate', blank=True, related_name='upsells_s')
    uom = models.CharField(_('Unit Of Measure'), max_length=128)
    uos = models.CharField(_('Unit of Sale'), max_length=128)
    volume = models.FloatField(_('Volume'), null=True, blank=True)
    warranty = models.FloatField(_('Warranty (months)'),null=True, blank=True)
    weight = models.FloatField(_('Gross weight'),null=True, blank=True)
    weight_net = models.FloatField(_('Net weight'), null=True, blank=True)
    status = models.BooleanField(_('Status'), default=False)

    class Meta:
        db_table = 'product_template'
        verbose_name = _('template')
        verbose_name_plural = _('templates')
        translate = ('name', 'slug', 'shortdescription', 'description', 'metadescription', 'metakeyword', 'metatitle')

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/%s/%s' % (get_language(), product_url[get_language()], self.slug)

class ProductProduct(models.Model):
    """ProductProduct OpenERP"""
    __metaclass__ = TransMeta

    product_tmpl = models.ForeignKey('ProductTemplate')
    active = models.BooleanField(_('Active'), default=False)
    code = models.CharField(_('Code'), max_length=128, null=True, blank=True) #Reference
    ean13 = models.CharField(_('EAN13'), max_length=128, null=True, blank=True)
    price = models.FloatField(_('Pricelist'))
    manufacturer = models.CharField(_('Manufacturer'), max_length=128, null=True, blank=True)

    class Meta:
        db_table = 'product_product'
        verbose_name = _('product')
        verbose_name_plural = _('products')
#        translate = ( )

    def __unicode__(self):
        return self.code

class ProductManufacturerAttribute(models.Model):
    """ProductManufacturerAttribute OpenERP"""

    name = models.CharField(_('Attribute'), max_length=128, null=True, blank=True)
    product = models.ForeignKey('ProductProduct', null=True, blank=True)
    value = models.CharField(_('Value'), max_length=128, null=True, blank=True)

    class Meta:
        db_table = 'product_manufacturer_attribute'
        verbose_name = _('attribute')
        verbose_name_plural = _('attributes')

    def __unicode__(self):
        return self.name

class ProductImages(models.Model):
    """ProductImages OpenERP"""

    name = models.CharField(_('Image Title'), max_length=128, null=True, blank=True)
    product = models.ForeignKey('ProductProduct', null=True, blank=True)
    filename = models.CharField(_('File Location'), max_length=128, null=True, blank=True)
    base_image = models.BooleanField(_('Base Image'), default=False)
    exclude = models.BooleanField(_('Exclude'), default=False)

    class Meta:
        db_table = 'product_images'
        verbose_name = _('image')
        verbose_name_plural = _('images')

    def __unicode__(self):
        return self.name
<|endoftext|>


<commit_before>#
#  DIALS viewer
#
#  Copyright (C) 2014 Diamond Light Source
#
#  Author: Luis Fuentes-Montero (Luiso)
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package."
#
#
from __future__ import division
import wx
from dials.viewer.viewer_frame import ReflectionFrame

class viewer_App(wx.App):
  def OnInit(self):
    self.frame = ReflectionFrame(None, -1, "DIALS Reflections Viewer"
    , wx.DefaultPosition,(550,200))

    self.SetTopWindow(self.frame)
    self.frame.Show(True)
    return True

  def table_in(self, loc_tabl):
    self.frame.tabl_to_frame(loc_tabl)

def next_gen_viewer_test(table):
  print "table(ptr) =", table
  from dials.viewer.next_gen_viewer.multi_3D_slice_viewer import show_3d
  print "Here Yes"

  table_row = table[8037]
  data_flex = table_row['shoebox'].data
  show_3d(data_flex)

  lst_flex_dat = []
  for nm in range(9):
    lst_flex_dat.append(table[nm]['shoebox'].data)
    lst_flex_dat.append(table[nm]['shoebox'].mask)

  show_3d(lst_flex_dat)

if __name__ == "__main__":

  import cPickle as pickle
  import sys
  from dials.array_family import flex
  table = flex.reflection_table.from_pickle(sys.argv[1])

  app = viewer_App(redirect=False)
  app.table_in(table)
  app.MainLoop()

  next_gen_viewer_test(table)
<commit_msg>making the viewer tester to rely on the proper app<commit_after>#
#  DIALS viewer_tester
#
#  Copyright (C) 2014 Diamond Light Source
#
#  Author: Luis Fuentes-Montero (Luiso)
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package."
#
#
from __future__ import division
import wx
from dials.viewer.viewer_frame import ReflectionFrame

def next_gen_viewer_test(table):
  print "table(ptr) =", table
  from dials.viewer.next_gen_viewer.multi_3D_slice_viewer import show_3d

  table_row = table[8037]
  data_flex = table_row['shoebox'].data
  show_3d(data_flex)

  lst_flex_dat = []
  for nm in range(9):
    lst_flex_dat.append(table[nm]['shoebox'].data)
    lst_flex_dat.append(table[nm]['shoebox'].mask)

  show_3d(lst_flex_dat)

if __name__ == "__main__":

  import cPickle as pickle
  import sys
  from dials.array_family import flex
  from dials.viewer.reflection_view import viewer_App

  table = flex.reflection_table.from_pickle(sys.argv[1])

  app = viewer_App(redirect=False)
  app.table_in(table)
  app.MainLoop()

  next_gen_viewer_test(table)
<|endoftext|>


<commit_before># global host
pkgs = []
grps = []

is_notebook = host in ["archmini", "archnote"]
# drivers
pkgs += ["mesa"]

if host == "archhost":
    pkgs += ["nvidia",
             "lib32-nvidia-utils"  # for steam
             ]
elif host == "archnote":
    pkgs += ["bbswitch",
             # "bumblebee",
             # "nvidia",
             "xf86-video-intel",
             "xf86-input-libinput"]  # touchpad
elif host == "archmini":
    pkgs += ["xf86-video-intel",
             "lib32-mesa",
             "xf86-input-synaptics",  # touchpad
             "broadcom-wl"]  # wi-fi

# monitoring
pkgs += ["iftop",  # network monitor
         "htop",  # process monitor
         "iotop",  # disk monitor
         "hddtemp",  # disk temperature
         "smartmontools"]

if host == "archhost":
    pkgs += ["apcupsd"]  # UPS
elif is_notebook:
    pkgs += ["powertop"]

# font packages
pkgs += ["ttf-ms-fonts",
         "ttf-tahoma",
         # "ttf-vista-fonts",
         "ttf-fixedsys-excelsior-linux",
         "ttf-droid",
         "ttf-dejavu",
         "ttf-ubuntu-font-family",
         "adobe-source-code-pro-fonts"]

# terminal
pkgs += ["urxvt-perls",
         "zsh",
         "oh-my-zsh-git",
         "zsh-syntax-highlighting",
         "fzf"]

# system
pkgs += ["refind-efi",
         "polkit",
         "gnupg",
         "xcursor-ize-vision",
         "pkgfile",  # pkgfile makepkg (get package for makepkg)
         "pkgcacheclean",  # clean the pacman cache
         "perwindowlayoutd",  # daemon to make per window layout (also exists "kbdd-git")
         "libnotify",  # create notifications message
         "autofs",  # automounter (nfs, samba, etc)
         "aurman",  # AUR package manager
         "rsync"]

# WM
pkgs += ["xorg-server",
         "xorg-xinit",
         "awesome",
         "rofi",  # run app menu
         "vicious"]

if is_notebook:
    grps += ["gnome"]

# login manager
pkgs += ["lightdm", "lightdm-gtk-greeter"]

# net tools
pkgs += ["wget",
         "wpa_supplicant",
         "net-tools",
         "dialog",
         "connman",
         "smbclient",
         "nfs-utils",
         "httpie",
         "openssh",
         "openvpn",
         ]

# remote access
# pkgs += ["teamviewer"]

# audio
pkgs += ["pulseaudio",
         "pavucontrol",
         "volumeicon"]

# web
pkgs += ["firefox",
         "firefox-i18n-ru",
         "flashplugin",
         "tor-browser-ru",
         "google-chrome",
         ]

# programming
pkgs += ["protobuf"]

# cpp
pkgs += ["boost", "clang", "gtest", "zeromq", "valgrind", "cmake", "gdb"]

# rust
# pkgs += ["rust", "cargo", "rust-src", "rust-racer"]
# rust-doc-git

# 3D for rust
# pkgs += ["sdl2", "sdl2_image"]

# sql
pkgs += ["sqlite-analyzer"]

# go
pkgs += ["go"]

# python
pkgs += ["python",
         "python2",
         "python-pip",
         "python2-pip",
         "python-nose",
         "python2-nose",
         "python-jedi",
         "python2-jedi",
         "python-pylint",
         "flake8",
         "python-pytest",
         "python-termcolor",
         "python-virtualenv",
         "tk",
         "swig",
         "portaudio",  # for pyaudio and my audio-lib
         ]

# text editors & ide
pkgs += ["emacs", "vim", "sublime-text-dev", "clion", "pycharm-professional"]

# file managers
pkgs += ["doublecmd-gtk2",
         "fsearch-git",
         "transmission-remote-gui-bin",
         "yandex-disk",  # yandex-disk setup/start
         "dropbox"]

# git
pkgs += ["git",
         "icdiff",  # console diff
         "meld"]

# archive program
pkgs += ["p7zip", "unzip", "unrar"]

# media
pkgs += ["byzanz-git",  # create gif from screen
         "viewnior",  # image viewer
         "simplescreenrecorder",  # write video from screen
         "gimp",
         "blender",
         "smplayer",
         "deadbeef"]

# office
pkgs += ["mupdf"  # pdf viewer
         # "llpp-git"  # pdf viewer
         # "libreoffice-fresh"
         ]

# spell checkers
pkgs += ["enchant", "hunspell-en", "hunspell-ru-aot", "languagetool"]

# android
# if host == "archhost":
#     pkgs += ["adb"]
# if host == "archmini":
#     pkgs += ["android-studio"]

# xorg
pkgs += ["xorg-xfontsel",  # font select
         "xorg-xprop",  # window info (xprop | grep WM_CLASS)
         "xorg-xev",  # keypress info
         "xorg-xwininfo",  # select window
         "xrectsel"]  # get select region

if is_notebook:
    pkgs += ["xorg-xbacklight"]  # backlight control application (xbacklight -set 40)

# VM
pkgs += ["jre7-openjdk", "docker", "docker-compose"]

# game
pkgs += ["playonlinux",
        "steam",
        "lib32-libldap",  # for WOT ?
        "minecraft"]

packages = pkgs
groups = grps
ignore_packages = ["yaourt", "ansible"]
ignore_groups = ["base", "base-devel"]
<commit_msg>change gnome to cinnamon<commit_after># global host
pkgs = []
grps = []

is_notebook = host in ["archmini", "archnote"]
# drivers
pkgs += ["mesa"]

if host == "archhost":
    pkgs += ["nvidia",
             "lib32-nvidia-utils"  # for steam
             ]
elif host == "archnote":
    pkgs += ["bbswitch",
             # "bumblebee",
             # "nvidia",
             "xf86-video-intel",
             "xf86-input-libinput"]  # touchpad
elif host == "archmini":
    pkgs += ["xf86-video-intel",
             "lib32-mesa",
             "xf86-input-synaptics",  # touchpad
             "broadcom-wl"]  # wi-fi

# monitoring
pkgs += ["iftop",  # network monitor
         "htop",  # process monitor
         "iotop",  # disk monitor
         "hddtemp",  # disk temperature
         "smartmontools"]

if host == "archhost":
    pkgs += ["apcupsd"]  # UPS
elif is_notebook:
    pkgs += ["powertop"]

# font packages
pkgs += ["ttf-ms-fonts",
         "ttf-tahoma",
         # "ttf-vista-fonts",
         "ttf-fixedsys-excelsior-linux",
         "ttf-droid",
         "ttf-dejavu",
         "ttf-ubuntu-font-family",
         "adobe-source-code-pro-fonts"]

# terminal
pkgs += ["urxvt-perls",
         "zsh",
         "oh-my-zsh-git",
         "zsh-syntax-highlighting",
         "fzf"]

# system
pkgs += ["refind-efi",
         "polkit",
         "gnupg",
         "xcursor-ize-vision",
         "pkgfile",  # pkgfile makepkg (get package for makepkg)
         "pkgcacheclean",  # clean the pacman cache
         "perwindowlayoutd",  # daemon to make per window layout (also exists "kbdd-git")
         "libnotify",  # create notifications message
         "autofs",  # automounter (nfs, samba, etc)
         "aurman",  # AUR package manager
         "rsync"]

# WM
pkgs += ["xorg-server",
         "xorg-xinit",
         "awesome",
         "rofi",  # run app menu
         "vicious"]

if is_notebook:
    grps += ["cinnamon"]

# login manager
pkgs += ["lightdm", "lightdm-gtk-greeter"]

# net tools
pkgs += ["wget",
         "wpa_supplicant",
         "net-tools",
         "dialog",
         "connman",
         "smbclient",
         "nfs-utils",
         "httpie",
         "openssh",
         "openvpn",
         ]

# remote access
# pkgs += ["teamviewer"]

# audio
pkgs += ["pulseaudio",
         "pavucontrol",
         "volumeicon"]

# web
pkgs += ["firefox",
         "firefox-i18n-ru",
         "flashplugin",
         "tor-browser-ru",
         "google-chrome",
         ]

# programming
pkgs += ["protobuf"]

# cpp
pkgs += ["boost", "clang", "gtest", "zeromq", "valgrind", "cmake", "gdb"]

# rust
# pkgs += ["rust", "cargo", "rust-src", "rust-racer"]
# rust-doc-git

# 3D for rust
# pkgs += ["sdl2", "sdl2_image"]

# sql
pkgs += ["sqlite-analyzer"]

# go
pkgs += ["go"]

# python
pkgs += ["python",
         "python2",
         "python-pip",
         "python2-pip",
         "python-nose",
         "python2-nose",
         "python-jedi",
         "python2-jedi",
         "python-pylint",
         "flake8",
         "python-pytest",
         "python-termcolor",
         "python-virtualenv",
         "tk",
         "swig",
         "portaudio",  # for pyaudio and my audio-lib
         ]

# text editors & ide
pkgs += ["emacs", "vim", "sublime-text-dev", "clion"]
if is_notebook:
    grps += ["pycharm-community-edition"]
else:
    grps += ["pycharm-professional"]

# file managers
pkgs += ["doublecmd-gtk2",
         "fsearch-git",
         "transmission-remote-gui-bin",
         "yandex-disk",  # yandex-disk setup/start
         "dropbox"]

# git
pkgs += ["git",
         "icdiff",  # console diff
         "meld"]

# archive program
pkgs += ["p7zip", "unzip", "unrar"]

# media
pkgs += ["byzanz-git",  # create gif from screen
         "viewnior",  # image viewer
         "simplescreenrecorder",  # write video from screen
         "gimp",
         "blender",
         "smplayer",
         "deadbeef"]

# office
pkgs += ["mupdf"  # pdf viewer
         # "llpp-git"  # pdf viewer
         # "libreoffice-fresh"
         ]

# spell checkers
pkgs += ["enchant", "hunspell-en", "hunspell-ru-aot", "languagetool"]

# android
# if host == "archhost":
#     pkgs += ["adb"]
# if host == "archmini":
#     pkgs += ["android-studio"]

# xorg
pkgs += ["xorg-xfontsel",  # font select
         "xorg-xprop",  # window info (xprop | grep WM_CLASS)
         "xorg-xev",  # keypress info
         "xorg-xwininfo",  # select window
         "xrectsel"]  # get select region

if is_notebook:
    pkgs += ["xorg-xbacklight"]  # backlight control application (xbacklight -set 40)

# VM
pkgs += ["jre7-openjdk", "docker", "docker-compose"]

# game
pkgs += ["playonlinux",
        "steam",
        "lib32-libldap",  # for WOT ?
        "minecraft"]

packages = pkgs
groups = grps
ignore_packages = ["yaourt", "ansible"]
ignore_groups = ["base", "base-devel"]
<|endoftext|>


<commit_before># This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from indico.core import signals
from indico.core.db import db
from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs
from indico.core.db.sqlalchemy.util.session import no_autoflush
from indico.modules.events.cloning import EventCloner
from indico.modules.events.features.util import is_feature_enabled
from indico.modules.events.models.events import EventType
from indico.modules.events.registration.models.form_fields import RegistrationFormFieldData
from indico.modules.events.registration.models.forms import RegistrationForm
from indico.modules.events.registration.models.items import RegistrationFormItem, RegistrationFormSection
from indico.modules.events.registration.models.registrations import Registration, RegistrationData
from indico.util.i18n import _

class RegistrationFormCloner(EventCloner):
    name = 'registration_forms'
    friendly_name = _('Registration forms')

    @property
    def is_visible(self):
        return is_feature_enabled(self.old_event, 'registration')

    @property
    def is_available(self):
        return bool(self.old_event.registration_forms)

    @no_autoflush
    def run(self, new_event, cloners, shared_data):
        # if the registration cloner is also enabled, we have to keep
        # all revisions since they are likely to be in use
        clone_all_revisions = 'registrations' in cloners
        attrs = get_simple_column_attrs(RegistrationForm) - {'start_dt', 'end_dt', 'modification_end_dt'}
        self._field_data_map = {}
        self._form_map = {}
        for old_form in self.old_event.registration_forms:
            new_form = RegistrationForm(**{attr: getattr(old_form, attr) for attr in attrs})
            self._clone_form_items(old_form, new_form, clone_all_revisions)
            new_event.registration_forms.append(new_form)
            db.session.flush()
            self._form_map[old_form] = new_form
        return {'form_map': self._form_map,
                'field_data_map': self._field_data_map}

    def _clone_form_items(self, old_form, new_form, clone_all_revisions):
        old_sections = RegistrationFormSection.find(RegistrationFormSection.registration_form_id == old_form.id)
        items_attrs = get_simple_column_attrs(RegistrationFormSection)
        for old_section in old_sections:
            new_section = RegistrationFormSection(**{attr: getattr(old_section, attr) for attr in items_attrs})
            for old_item in old_section.children:
                new_item = RegistrationFormItem(parent=new_section, registration_form=new_form,
                                                **{attr: getattr(old_item, attr) for attr in items_attrs})
                if new_item.is_field:
                    if clone_all_revisions:
                        self._clone_all_field_versions(old_item, new_item)
                    else:
                        field_data = RegistrationFormFieldData(field=new_item,
                                                               versioned_data=old_item.versioned_data)
                        new_item.current_data = field_data
                        self._field_data_map[old_item.current_data] = field_data
                new_section.children.append(new_item)
            new_form.form_items.append(new_section)
            db.session.flush()

    def _clone_all_field_versions(self, old_item, new_item):
        for old_version in old_item.data_versions:
            new_version = RegistrationFormFieldData(versioned_data=old_version.versioned_data, field=new_item)
            if old_version.id == old_item.current_data_id:
                new_item.current_data = new_version
            new_item.data_versions.append(new_version)
            self._field_data_map[old_version] = new_version

class RegistrationCloner(EventCloner):
    name = 'registrations'
    friendly_name = _('Registrations')
    requires = {'registration_forms'}

    @property
    def is_visible(self):
        return is_feature_enabled(self.old_event, 'registration')

    @property
    def is_available(self):
        return (RegistrationForm.query.with_parent(self.old_event)
                .filter(RegistrationForm.registrations.any(Registration.is_active))
                .has_rows())

    @property
    def is_default(self):
        return self.old_event.type_ == EventType.meeting

    def run(self, new_event, cloners, shared_data):
        form_map = shared_data['registration_forms']['form_map']
        field_data_map = shared_data['registration_forms']['field_data_map']
        for old_form, new_form in form_map.iteritems():
            self._clone_registrations(old_form, new_form, field_data_map)
        self._synchronize_registration_friendly_id(new_event)
        db.session.flush()

    def _clone_registrations(self, old_form, new_form, field_data_map):
        registration_attrs = get_simple_column_attrs(Registration) - {'uuid', 'ticket_uuid'}
        for old_registration in old_form.registrations:
            if old_registration.is_deleted:
                continue
            new_registration = Registration(user=old_registration.user, registration_form=new_form,
                                            **{attr: getattr(old_registration, attr) for attr in registration_attrs})
            reg_data_attrs = get_simple_column_attrs(RegistrationData) - {'storage_file_id', 'storage_backend', 'size'}
            for old_registration_data in old_registration.data:
                new_registration_data = RegistrationData(registration=new_registration,
                                                         **{attr: getattr(old_registration_data, attr)
                                                            for attr in reg_data_attrs})
                new_registration_data.field_data = field_data_map[old_registration_data.field_data]
                if old_registration_data.storage_file_id is not None:
                    with old_registration_data.open() as fd:
                        new_registration_data.save(fd)
            db.session.flush()
            signals.event.registration_state_updated.send(new_registration)

    def _synchronize_registration_friendly_id(self, new_event):
        new_event._last_friendly_registration_id = (
            db.session
            .query(db.func.max(Registration.friendly_id))
            .filter(Registration.event_id == new_event.id)
            .scalar() or 0
        )
<commit_msg>Make registration_state_updated signal consistent<commit_after># This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from indico.core import signals
from indico.core.db import db
from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs
from indico.core.db.sqlalchemy.util.session import no_autoflush
from indico.modules.events.cloning import EventCloner
from indico.modules.events.features.util import is_feature_enabled
from indico.modules.events.models.events import EventType
from indico.modules.events.registration.models.form_fields import RegistrationFormFieldData
from indico.modules.events.registration.models.forms import RegistrationForm
from indico.modules.events.registration.models.items import RegistrationFormItem, RegistrationFormSection
from indico.modules.events.registration.models.registrations import Registration, RegistrationData
from indico.util.i18n import _

class RegistrationFormCloner(EventCloner):
    name = 'registration_forms'
    friendly_name = _('Registration forms')

    @property
    def is_visible(self):
        return is_feature_enabled(self.old_event, 'registration')

    @property
    def is_available(self):
        return bool(self.old_event.registration_forms)

    @no_autoflush
    def run(self, new_event, cloners, shared_data):
        # if the registration cloner is also enabled, we have to keep
        # all revisions since they are likely to be in use
        clone_all_revisions = 'registrations' in cloners
        attrs = get_simple_column_attrs(RegistrationForm) - {'start_dt', 'end_dt', 'modification_end_dt'}
        self._field_data_map = {}
        self._form_map = {}
        for old_form in self.old_event.registration_forms:
            new_form = RegistrationForm(**{attr: getattr(old_form, attr) for attr in attrs})
            self._clone_form_items(old_form, new_form, clone_all_revisions)
            new_event.registration_forms.append(new_form)
            db.session.flush()
            self._form_map[old_form] = new_form
        return {'form_map': self._form_map,
                'field_data_map': self._field_data_map}

    def _clone_form_items(self, old_form, new_form, clone_all_revisions):
        old_sections = RegistrationFormSection.find(RegistrationFormSection.registration_form_id == old_form.id)
        items_attrs = get_simple_column_attrs(RegistrationFormSection)
        for old_section in old_sections:
            new_section = RegistrationFormSection(**{attr: getattr(old_section, attr) for attr in items_attrs})
            for old_item in old_section.children:
                new_item = RegistrationFormItem(parent=new_section, registration_form=new_form,
                                                **{attr: getattr(old_item, attr) for attr in items_attrs})
                if new_item.is_field:
                    if clone_all_revisions:
                        self._clone_all_field_versions(old_item, new_item)
                    else:
                        field_data = RegistrationFormFieldData(field=new_item,
                                                               versioned_data=old_item.versioned_data)
                        new_item.current_data = field_data
                        self._field_data_map[old_item.current_data] = field_data
                new_section.children.append(new_item)
            new_form.form_items.append(new_section)
            db.session.flush()

    def _clone_all_field_versions(self, old_item, new_item):
        for old_version in old_item.data_versions:
            new_version = RegistrationFormFieldData(versioned_data=old_version.versioned_data, field=new_item)
            if old_version.id == old_item.current_data_id:
                new_item.current_data = new_version
            new_item.data_versions.append(new_version)
            self._field_data_map[old_version] = new_version

class RegistrationCloner(EventCloner):
    name = 'registrations'
    friendly_name = _('Registrations')
    requires = {'registration_forms'}

    @property
    def is_visible(self):
        return is_feature_enabled(self.old_event, 'registration')

    @property
    def is_available(self):
        return (RegistrationForm.query.with_parent(self.old_event)
                .filter(RegistrationForm.registrations.any(Registration.is_active))
                .has_rows())

    @property
    def is_default(self):
        return self.old_event.type_ == EventType.meeting

    def run(self, new_event, cloners, shared_data):
        form_map = shared_data['registration_forms']['form_map']
        field_data_map = shared_data['registration_forms']['field_data_map']
        for old_form, new_form in form_map.iteritems():
            self._clone_registrations(old_form, new_form, field_data_map)
        self._synchronize_registration_friendly_id(new_event)
        db.session.flush()

    def _clone_registrations(self, old_form, new_form, field_data_map):
        registration_attrs = get_simple_column_attrs(Registration) - {'uuid', 'ticket_uuid'}
        for old_registration in old_form.registrations:
            if old_registration.is_deleted:
                continue
            new_registration = Registration(user=old_registration.user, registration_form=new_form,
                                            **{attr: getattr(old_registration, attr) for attr in registration_attrs})
            reg_data_attrs = get_simple_column_attrs(RegistrationData) - {'storage_file_id', 'storage_backend', 'size'}
            for old_registration_data in old_registration.data:
                new_registration_data = RegistrationData(registration=new_registration,
                                                         **{attr: getattr(old_registration_data, attr)
                                                            for attr in reg_data_attrs})
                new_registration_data.field_data = field_data_map[old_registration_data.field_data]
                if old_registration_data.storage_file_id is not None:
                    with old_registration_data.open() as fd:
                        new_registration_data.save(fd)
            db.session.flush()
            signals.event.registration_state_updated.send(new_registration, previous_state=None)

    def _synchronize_registration_friendly_id(self, new_event):
        new_event._last_friendly_registration_id = (
            db.session
            .query(db.func.max(Registration.friendly_id))
            .filter(Registration.event_id == new_event.id)
            .scalar() or 0
        )
<|endoftext|>


<commit_before>#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Quality settings'''
import xml.etree.ElementTree as xmlMod
from usefullFunctions import *
from Preferences.PresetList.Preset.OSA import *
from Preferences.PresetList.Preset.ValueType.Size import *
import os

class Quality:
	'''class to manage Quality settings'''

	def __init__(self, xml= None):
		'''initialize Quality settings with default value or values extracted from an xml object'''
		if xml is None:
			self.defaultInit()
		else:
			self.fromXml(xml)

	def defaultInit(self):
		'''initialize Quality settings with default value'''
		self.pourcent = 100
		self.size = Size('1920x1080')
		self.samples = 1500
		self.simplify = None
		self.format = 'OPEN_EXR_MULTILAYER'
		self.OSA = OSA()

	def fromXml(self, xml):
		'''initialize Quality settings with values extracted from an xml object'''
		node = xml.find('resolution')
		self.pourcent = int(node.get('pourcent'))
		self.size = Size(xml = node)
		self.samples = int(xml.find('samples').get('value'))
		if xml.find('simplify') is not None:
			self.simplify = int(xml.find('simplify').get('value'))
		else:
			self.simplify = None
		self.format = xml.find('format').get('value')
		self.OSA = OSA(xml.find('OSA'))

	def toXml(self):
		'''export Quality settings into xml syntaxed string'''
		txt = '<quality>\n'
		txt += '  <resolution pourcent="'+str(self.pourcent)+'" '+self.size.toXmlAttr()+' />\n'
		txt += '  <samples value="'+str(self.samples)+'" />\n'

		if self.simplify is not None:
			txt += '  <simplify value="'+str(self.simplify)+'" />\n'

		txt += '  <format value="'+self.format+'" />\n'

		txt += self.OSA.toXml()

		txt += '</quality>\n'
		return txt

	def menu(self, log):
		'''menu to explore and edit Quality settings settings'''
		change = False
		log.menuIn('Quality')

		while True:

			log.print()

			self.print()

			print('''\n\n        Menu :
1- Edit Resolution Size
2- Edit Pourcent Setting
3- Edit Cycles Samples
4- Edit Simplify Setting
5- Edit Format
6- Edit OSA settings (for Blender Render only)
0- Quit

''')

			choice = input('Action?').strip().lower()

			if choice in ['0', 'q', 'quit', 'cancel']:
				log.menuOut()
				return change
			elif choice == '1':
				change = (self.size.edit(log, 'Resolution Size') or change)
			elif choice in ['2', '3']:
				change = (self.edit(log, int(choice)) or change)
			elif choice == '4':
				change = (self.editSimplify(log) or change)
			elif choice == '5':
				change = (self.editFormat(log) or change)
			elif choice == '6':
				change = (self.OSA.menu(log) or change)
			else:
				log.error('Unvalid menu choice', False)

	def print(self):
		'''a method to print preset'''
		print('Resolution :            '+self.size.toStr()+'@'+str(self.pourcent))
		print('Cycles Samples :        '+str(self.samples))
		print('Simplify :              '+self.getSimplify())
		print('Format :                '+self.format)

	def getSimplify(self):
		'''A method to get simplify setting'''
		if self.simplify is None:
			return 'Disabled'
		else:
			return str(self.simplify)+' subdiv'

	def edit(self, log, choice):
		'''A method to edit pourcent setting'''
		if choice == 2:
			log.menuIn('Edit Resolution Pourcent')
		else:
			log.menuIn('Edit Cycles Samples')

		while True:

			log.print()

			# print current setting and get new one
			if choice == 2:
				print('\n\n        Edit Pourcent :\nCurrent Pourcent : '+str(self.pourcent)+'\n')
				new = input('New pourcent setting?').strip().lower()
			else:
				print('\n\n        Edit Cycles Samples :\nCurrent Sammples : '+str(self.samples)+'\n')
				new = input('New Samples setting?').strip().lower()

			# exit menu
			if new in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			#check new setting
			try:
				new = int(new)
			except ValueError:
				log.error('New setting must be an integer.')
				continue

			if new < 0:
				log.error('New setting must be a positive integer.')
				continue

			# apply new setting and exit
			if choice == 2:
				self.pourcent = new
				log.write('Resolution pourcent setting is set to : '\
							+str(self.pourcent)+'%')
			else:
				self.samples = new
				log.write('Cycles samples set to : '+str(self.samples)+'%')
			log.menuOut()
			return True

	def editSimplify(self, log):
		'''A method to Edit Simplify settings'''
		log.menuIn('Edit Simplify settings')

		while True:

			log.print()

			# print current setting and get new one
			print('\n\n        Edit Simplify Settings :\nCurrent settings : '+self.getSimplify()+'\n')
			choice = input('New setting?').strip().lower()

			# exit menu
			if choice in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			#check new setting
			try:
				choice = int(choice)
			except ValueError:
				log.error('New setting must be an integer.')
				continue

			if choice < 0:
				log.error('New setting must be a positive integer.')
				continue

			if choice < 11:
				self.simplify = choice
			else:
				self.simplify = None
			log.write('Simplify set to : '+self.getSimplify())
			log.menuOut()
			return True

	def editFormat(self, log):
		'''A method to edit format settings'''
		formats = [
					'PNG',
					'JPEG',
					'OPEN_EXR',
					'OPEN_EXR_MULTILAYER'
					]
		log.menuIn('Choose Output Format')

		while True:

			log.print()

			print('\n\n        Edit Output Format :\n\nCurrent format : '+self.format)

			indexPrintList(formats)

			choice = input('new format?').strip()

			if choice.lower() in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			try:
				choice = int(choice)
			except ValueError:
				log.error('An integer is expected!')
				continue

			if choice < 0 or choice >= len(formats):
				log.error('Out of choice range!')
				continue

			self.format = formats[choice]
			log.write('Output format is set to : '+self.format)
			log.menuOut()
			return True

	def apply(self, scene):
		'''apply settings to a blender scene object'''
		scene.render.resolution_percentage = self.pourcent
		scene.render.resolution_x = self.size.X
		scene.render.resolution_y = self.size.Y

		scene.cycles.use_square_samples = False
		scene.cycles.samples = self.samples

		if self.simplify is None:
			scene.render.use_simplify = False
		else:
			scene.render.use_simplify = True
			scene.render.simplify_subdivision_render

		scene.render.image_settings.file_format = self.format

	def getExtension(self):
		'''return file extension'''
		if self.format == 'PNG':
			return '.png'
		if self.format == 'JPEG':
			return '.jpg'
		return '.exr'

<commit_msg>print OSA setting when printing Quality settings<commit_after>#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Quality settings'''
import xml.etree.ElementTree as xmlMod
from usefullFunctions import *
from Preferences.PresetList.Preset.OSA import *
from Preferences.PresetList.Preset.ValueType.Size import *
import os

class Quality:
	'''class to manage Quality settings'''

	def __init__(self, xml= None):
		'''initialize Quality settings with default value or values extracted from an xml object'''
		if xml is None:
			self.defaultInit()
		else:
			self.fromXml(xml)

	def defaultInit(self):
		'''initialize Quality settings with default value'''
		self.pourcent = 100
		self.size = Size('1920x1080')
		self.samples = 1500
		self.simplify = None
		self.format = 'OPEN_EXR_MULTILAYER'
		self.OSA = OSA()

	def fromXml(self, xml):
		'''initialize Quality settings with values extracted from an xml object'''
		node = xml.find('resolution')
		self.pourcent = int(node.get('pourcent'))
		self.size = Size(xml = node)
		self.samples = int(xml.find('samples').get('value'))
		if xml.find('simplify') is not None:
			self.simplify = int(xml.find('simplify').get('value'))
		else:
			self.simplify = None
		self.format = xml.find('format').get('value')
		self.OSA = OSA(xml.find('OSA'))

	def toXml(self):
		'''export Quality settings into xml syntaxed string'''
		txt = '<quality>\n'
		txt += '  <resolution pourcent="'+str(self.pourcent)+'" '+self.size.toXmlAttr()+' />\n'
		txt += '  <samples value="'+str(self.samples)+'" />\n'

		if self.simplify is not None:
			txt += '  <simplify value="'+str(self.simplify)+'" />\n'

		txt += '  <format value="'+self.format+'" />\n'

		txt += self.OSA.toXml()

		txt += '</quality>\n'
		return txt

	def menu(self, log):
		'''menu to explore and edit Quality settings settings'''
		change = False
		log.menuIn('Quality')

		while True:

			log.print()

			self.print()

			print('''\n\n        Menu :
1- Edit Resolution Size
2- Edit Pourcent Setting
3- Edit Cycles Samples
4- Edit Simplify Setting
5- Edit Format
6- Edit OSA settings (for Blender Render only)
0- Quit

''')

			choice = input('Action?').strip().lower()

			if choice in ['0', 'q', 'quit', 'cancel']:
				log.menuOut()
				return change
			elif choice == '1':
				change = (self.size.edit(log, 'Resolution Size') or change)
			elif choice in ['2', '3']:
				change = (self.edit(log, int(choice)) or change)
			elif choice == '4':
				change = (self.editSimplify(log) or change)
			elif choice == '5':
				change = (self.editFormat(log) or change)
			elif choice == '6':
				change = (self.OSA.menu(log) or change)
			else:
				log.error('Unvalid menu choice', False)

	def print(self):
		'''a method to print preset'''
		print('Resolution :            '+self.size.toStr()+'@'+str(self.pourcent))
		print('Cycles Samples :        '+str(self.samples))
		print('Simplify :              '+self.getSimplify())
		print('Format :                '+self.format)
		self.OSA.print()

	def getSimplify(self):
		'''A method to get simplify setting'''
		if self.simplify is None:
			return 'Disabled'
		else:
			return str(self.simplify)+' subdiv'

	def edit(self, log, choice):
		'''A method to edit pourcent setting'''
		if choice == 2:
			log.menuIn('Edit Resolution Pourcent')
		else:
			log.menuIn('Edit Cycles Samples')

		while True:

			log.print()

			# print current setting and get new one
			if choice == 2:
				print('\n\n        Edit Pourcent :\nCurrent Pourcent : '+str(self.pourcent)+'\n')
				new = input('New pourcent setting?').strip().lower()
			else:
				print('\n\n        Edit Cycles Samples :\nCurrent Sammples : '+str(self.samples)+'\n')
				new = input('New Samples setting?').strip().lower()

			# exit menu
			if new in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			#check new setting
			try:
				new = int(new)
			except ValueError:
				log.error('New setting must be an integer.')
				continue

			if new < 0:
				log.error('New setting must be a positive integer.')
				continue

			# apply new setting and exit
			if choice == 2:
				self.pourcent = new
				log.write('Resolution pourcent setting is set to : '\
							+str(self.pourcent)+'%')
			else:
				self.samples = new
				log.write('Cycles samples set to : '+str(self.samples)+'%')
			log.menuOut()
			return True

	def editSimplify(self, log):
		'''A method to Edit Simplify settings'''
		log.menuIn('Edit Simplify settings')

		while True:

			log.print()

			# print current setting and get new one
			print('\n\n        Edit Simplify Settings :\nCurrent settings : '+self.getSimplify()+'\n')
			choice = input('New setting?').strip().lower()

			# exit menu
			if choice in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			#check new setting
			try:
				choice = int(choice)
			except ValueError:
				log.error('New setting must be an integer.')
				continue

			if choice < 0:
				log.error('New setting must be a positive integer.')
				continue

			if choice < 11:
				self.simplify = choice
			else:
				self.simplify = None
			log.write('Simplify set to : '+self.getSimplify())
			log.menuOut()
			return True

	def editFormat(self, log):
		'''A method to edit format settings'''
		formats = [
					'PNG',
					'JPEG',
					'OPEN_EXR',
					'OPEN_EXR_MULTILAYER'
					]
		log.menuIn('Choose Output Format')

		while True:

			log.print()

			print('\n\n        Edit Output Format :\n\nCurrent format : '+self.format)

			indexPrintList(formats)

			choice = input('new format?').strip()

			if choice.lower() in ['', 'q', 'quit', 'cancel']:
				log.menuOut()
				return False

			try:
				choice = int(choice)
			except ValueError:
				log.error('An integer is expected!')
				continue

			if choice < 0 or choice >= len(formats):
				log.error('Out of choice range!')
				continue

			self.format = formats[choice]
			log.write('Output format is set to : '+self.format)
			log.menuOut()
			return True

	def apply(self, scene):
		'''apply settings to a blender scene object'''
		scene.render.resolution_percentage = self.pourcent
		scene.render.resolution_x = self.size.X
		scene.render.resolution_y = self.size.Y

		scene.cycles.use_square_samples = False
		scene.cycles.samples = self.samples

		if self.simplify is None:
			scene.render.use_simplify = False
		else:
			scene.render.use_simplify = True
			scene.render.simplify_subdivision_render

		scene.render.image_settings.file_format = self.format

	def getExtension(self):
		'''return file extension'''
		if self.format == 'PNG':
			return '.png'
		if self.format == 'JPEG':
			return '.jpg'
		return '.exr'

<|endoftext|>


<commit_before>import numpy
from numpy import linspace, zeros, atleast_2d

from dolo.algos.steady_state import find_deterministic_equilibrium

def deterministic_solve(model, shocks=None, start_states=None, start_controls=None, start_constraints=None, T=100, ignore_constraints=False, iuse_pandas=True, initial_guess=None, verbose=False):
    '''
    Computes a perfect foresight simulation using a stacked-time algorithm.

    :param model: an "fga" model
    :param shocks: a :math:`n_e\\times N` matrix containing :math:`N` realizations of the shocks. :math:`N` must be smaller than :math:`T`.    The exogenous process is assumed to remain constant and equal to its last value after `N` periods.
    :param T: the horizon for the perfect foresight simulation
    :param use_pandas: if True, returns a pandas dataframe, else the simulation matrix
    :param ignore_constraints: if True, complementarity constraintes are ignored.
    :return: a dataframe with T+1 observations of the model variables along the simulation (states, controls, auxiliaries). The first observation is the steady-state corresponding to the first value of the shocks. The simulation should return
    to a steady-state corresponding to the last value of the exogenous shocks.
    '''

    # TODO:

    if model.model_type == 'fga':
        from dolo.compiler.converter import GModel_fg_from_fga
        model = GModel_fg_from_fga(model)

    # definitions
    n_s = len(model.calibration['states'])
    n_x = len(model.calibration['controls'])

    if shocks == None:
        shocks = numpy.zeros( (len(model.calibration['shocks']),1))

    # until last period, exogenous shock takes its last value
    epsilons = numpy.zeros( (shocks.shape[0], T))
    epsilons[:,:(shocks.shape[1]-1)] = shocks[:,1:]
    epsilons[:,(shocks.shape[1]-1):] = shocks[:,-1:]

    # final initial and final steady-states consistent with exogenous shocks
    if start_states is None:
        start = find_steady_state( model, numpy.atleast_2d(shocks[:,0:1]), constraints=start_constraints)
    else:
        # we look only for optimal initial controls
        start = find_steady_state( model, numpy.atleast_2d(shocks[:,0:1]), constraints=start_constraints, force_states=start_states)

    final = find_steady_state( model, numpy.atleast_2d(shocks[:,-1:]))

    start_s = start[0]
    final_x = final[1]

    final = numpy.concatenate( final )
    start = numpy.concatenate( start )

    if verbose==True:
        print("Initial states : {}".format(start_s))
        print("Final controls : {}".format(final_x))

    p = model.calibration['parameters']

    if initial_guess is None:

        initial_guess = numpy.concatenate( [start*(1-l) + final*l for l in linspace(0.0,1.0,T+1)] )
        initial_guess = initial_guess.reshape( (-1, n_s + n_x)).T

    else:
        from pandas import DataFrame
        if isinstance( initial_guess, DataFrame ):
            initial_guess = array( initial_guess ).T.copy()
        initial_guess = initial_guess[:n_s+n_x,:]
        initial_guess[:n_s,0] = start_s
        initial_guess[n_s:,-1] = final_x

    sh = initial_guess.shape

    if model.x_bounds and not ignore_constraints:
        initial_states = initial_guess[:n_s,:]
        [lb, ub] = [ u( initial_states, p ) for u in model.x_bounds]
        lower_bound = initial_guess*0 - numpy.inf
        lower_bound[n_s:,:] = lb
        upper_bound = initial_guess*0 + numpy.inf
        upper_bound[n_s:,:] = ub
        test1 = max( lb.max(axis=1) - lb.min(axis=1) )
        test2 = max( ub.max(axis=1) - ub.min(axis=1) )
        if test1 >0.00000001 or test2>0.00000001:
            raise Exception("Not implemented: perfect foresight solution requires that controls have constant bounds.")
    else:
        ignore_constraints=True
        lower_bound = None
        upper_bound = None

    nn = sh[0]*sh[1]

    fobj  = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x, epsilons)[0].ravel()

    from dolo.numeric.solver import solver

    if not ignore_constraints:
        dfobj = lambda vec: det_residual( model, vec.reshape(sh), start_s, final_x, epsilons)[1]
        from dolo.numeric.ncpsolve import ncpsolve
        ff  = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x, epsilons)
        sol = ncpsolve(ff, lower_bound.ravel(), upper_bound.ravel(), initial_guess.ravel(), verbose=verbose, maxit=maxit )
        if isinstance(sol, list):
            raise Exception("No convergence after {} iterations.".format(sol[1]))
#        sol = solver(fobj, initial_guess.ravel(), lb=lower_bound.ravel(), ub=upper_bound.ravel(), jac=dfobj, method='ncpsolve' )
        sol = sol.reshape(sh)
        #sol = solver(fobj, initial_guess, jac=dfobj, lb=lower_bound, ub=upper_bound, method='ncpsolve', serial_problem=False, verbose=verbose )
    else:
        from scipy.optimize import fsolve
        dfobj = lambda vec: det_residual( model, vec.reshape(sh), start_s, final_x, epsilons)[1].toarray()
        x0 = initial_guess.ravel()
        sol = fsolve(fobj, x0, fprime=dfobj)
        sol = sol.reshape(sh)

#        sol = solver(fobj, initial_guess, jac=dfobj, method='fsolve', serial_problem=False, verbose=verbose )

    if use_pandas:
        import pandas
        if 'auxiliary' in model.functions:
            colnames = model.symbols['states'] + model.symbols['controls'] + model.symbols['auxiliary']
            # compute auxiliaries
            y = model.functions['auxiliary'](sol[:n_s,:], sol[n_s:,:], p)
            sol = numpy.row_stack([sol,y])
        else:
            colnames = model.symbols['states'] + model.symbols['controls']

        ts = pandas.DataFrame(sol.T, columns=colnames)
        return ts
    else:
        return sol

def det_residual(model, guess, start, final, shocks, diff=True):
    '''
    Computes the residuals, the derivatives of the stacked-time system.
    :param model: an fga model
    :param guess: the guess for the simulated values. An `(n_s.n_x) x N` array, where n_s is the number of states,
    n_x the number of controls, and `N` the length of the simulation.
    :param start: initial boundary condition (initial value of the states)
    :param final: final boundary condition (last value of the controls)
    :param shocks: values for the exogenous shocks
    :param diff: if True, the derivatives are computes
    :return: a list with two elements:
        - an `(n_s.n_x) x N` array with the residuals of the system
        - a `(n_s.n_x) x N x (n_s.n_x) x N` array representing the jacobian of the system
    '''

    # TODO: compute a sparse derivative and ensure the solvers can deal with it

    n_s = len( model.symbols['states'] )
    n_x = len( model.symbols['controls'] )

    n_e = len( model.symbols['shocks'] )
    N = guess.shape[1]

    p = model.calibration['parameters']

    f = model.functions['arbitrage']
    g = model.functions['transition']

    vec = guess[:,:-1]
    vec_f = guess[:,1:]

    s = vec[:n_s,:]
    x = vec[n_s:,:]
    S = vec_f[:n_s,:]
    X = vec_f[n_s:,:]

    if diff:
        SS, SS_s, SS_x, SS_e = g(s,x,shocks,p, derivs=True)
        R, R_s, R_x, R_S, R_X = f(s,x,S,X,p,derivs=True)
    else:
        SS = g(s,x,shocks,p)
        R = f(s,x,S,X,p)

    res_s = SS - S
    res_x = R

    res = numpy.zeros( (n_s+n_x, N) )

    res[:n_s,1:] = res_s
    res[n_s:,:-1] = res_x

    res[:n_s,0] = - (guess[:n_s,0] - start)
    res[n_s:, -1] = - (guess[n_s:, -1] - guess[n_s:, -2] )

    if not diff:
        return res
    else:

        sparse_jac=False
        if not sparse_jac:

            # we compute the derivative matrix

            from dolo.numeric.serial_operations import serial_multiplication as smult
            res_s_s = SS_s
            res_s_x = SS_x

            # next block is probably very inefficient
            jac = numpy.zeros( (n_s+n_x, N, n_s+n_x, N) )
            for i in range(N-1):
                jac[n_s:,i,:n_s,i] = R_s[:,:,i]
                jac[n_s:,i,n_s:,i] = R_x[:,:,i]
                jac[n_s:,i,:n_s,i+1] = R_S[:,:,i]
                jac[n_s:,i,n_s:,i+1] = R_X[:,:,i]
                jac[:n_s,i+1,:n_s,i] = SS_s[:,:,i]
                jac[:n_s,i+1,n_s:,i] = SS_x[:,:,i]
                jac[:n_s,i+1,:n_s,i+1] = -numpy.eye(n_s)
            jac[:n_s,0,:n_s,0] = - numpy.eye(n_s)
            jac[n_s:,-1,n_s:,-1] = - numpy.eye(n_x)
            jac[n_s:,-1,n_s:,-2] = + numpy.eye(n_x)
            nn = jac.shape[0]*jac.shape[1]
            res = res.ravel()
            jac = jac.reshape((nn,nn))

        from scipy.sparse import csc_matrix, csr_matrix

        jac = csr_matrix(jac)

        return [res,jac]

if __name__ == '__main__':

    # this example computes the response of the rbc economy to a series of expected productivity shocks.
    # investment is bounded by an exogenous value 0.2, so that investment is constrained in the first periods

    # TODO: propose a meaningful economic example

    from dolo import *
    from pylab import *

    model = yaml_import('examples/global_models/rbc_pf.yaml')

    e_z = atleast_2d( linspace(0.1, 0.0, 10) )

    start_s = numpy.zeros(2) * numpy.nan
    start_s[0] = 1.5

    import time
    t1 = time.time()
    #sol1 = deterministic_solve(model, shocks=e_z, T=50, use_pandas=True, ignore_constraints=True, start_s=start_s)

    #sol1 = deterministic_solve(model, T=50, use_pandas=True, ignore_constraints=True, start_s=start_s)

    sol2 = deterministic_solve(model, shocks=e_z, T=1000, use_pandas=True, ignore_constraints=False)
    t2 = time.time()

    print("Elapsed : {}".format(t2-t1))

    exit()
    from pylab import *

    subplot(211)
    plot(sol1['k'], label='k')
    plot(sol1['z'], label='z')
    plot(sol1['i'], label='i')

    subplot(212)
    plot(sol2['k'], label='k')
    plot(sol2['z'], label='z')
    plot(sol2['i'], label='i')
    plot(sol2['i']*0 + sol2['i'].max(), linestyle='--', color='black')

    legend()
    show()

<commit_msg>Progress on perfect_foresight/steady_state (2)<commit_after>import numpy
from numpy import linspace, zeros, atleast_2d

from dolo.algos.steady_state import find_deterministic_equilibrium

def deterministic_solve(model, shocks=None, start_states=None, start_constraints=None, T=100, ignore_constraints=False, maxit=100, use_pandas=True, initial_guess=None, verbose=False):
    '''
    Computes a perfect foresight simulation using a stacked-time algorithm.

    :param model: an "fga" model
    :param shocks: a :math:`n_e\\times N` matrix containing :math:`N` realizations of the shocks. :math:`N` must be smaller than :math:`T`.    The exogenous process is assumed to remain constant and equal to its last value after `N` periods.
    :param T: the horizon for the perfect foresight simulation
    :param use_pandas: if True, returns a pandas dataframe, else the simulation matrix
    :param ignore_constraints: if True, complementarity constraintes are ignored.
    :return: a dataframe with T+1 observations of the model variables along the simulation (states, controls, auxiliaries). The first observation is the steady-state corresponding to the first value of the shocks. The simulation should return
    to a steady-state corresponding to the last value of the exogenous shocks.
    '''

    # TODO:

    if model.model_type == 'fga':
        from dolo.compiler.converter import GModel_fg_from_fga
        model = GModel_fg_from_fga(model)

    # definitions
    n_s = len(model.calibration['states'])
    n_x = len(model.calibration['controls'])

    if shocks == None:
        shocks = numpy.zeros( (len(model.calibration['shocks']),1))

    # until last period, exogenous shock takes its last value
    epsilons = numpy.zeros( (shocks.shape[0], T))
    epsilons[:,:(shocks.shape[1]-1)] = shocks[:,1:]
    epsilons[:,(shocks.shape[1]-1):] = shocks[:,-1:]

    final_dict = {model.symbols['shocks'][i]: shocks[i,-1] for i in range(len(model.symbols['shocks']))}
    start_dict = {model.symbols['shocks'][i]: shocks[i,0] for i in range(len(model.symbols['shocks']))}

    if start_constraints:
        start_dict.update(start_constraints)

    final_equilibrium = find_deterministic_equilibrium( model, constraints=final_dict)
    final_s = final_equilibrium['states']
    final_x = final_equilibrium['controls']

    # final initial and final steady-states consistent with exogenous shocks
    if start_states is None:
        start_equilibrium = find_deterministic_equilibrium( model, constraints=start_dict)
        start_s = start_equilibrium['states']
        start_x = start_equilibrium['controls']
    else:
        start_s = start_states
        start_x = final_x

    #TODO: for start_x, it should be possible to use first order guess

    final = numpy.concatenate( [final_s, final_x] )
    start = numpy.concatenate( [start_s, start_x] )

    if verbose==True:
        print("Initial states : {}".format(start_s))
        print("Final controls : {}".format(final_x))

    p = model.calibration['parameters']

    if initial_guess is None:

        initial_guess = numpy.concatenate( [start*(1-l) + final*l for l in linspace(0.0,1.0,T+1)] )
        initial_guess = initial_guess.reshape( (-1, n_s + n_x)).T

    else:
        from pandas import DataFrame
        if isinstance( initial_guess, DataFrame ):
            initial_guess = array( initial_guess ).T.copy()
        initial_guess = initial_guess[:n_s+n_x,:]
        initial_guess[:n_s,0] = start_s
        initial_guess[n_s:,-1] = final_x

    sh = initial_guess.shape

    if model.x_bounds and not ignore_constraints:
        initial_states = initial_guess[:n_s,:]
        [lb, ub] = [ u( initial_states, p ) for u in model.x_bounds]
        lower_bound = initial_guess*0 - numpy.inf
        lower_bound[n_s:,:] = lb
        upper_bound = initial_guess*0 + numpy.inf
        upper_bound[n_s:,:] = ub
        test1 = max( lb.max(axis=1) - lb.min(axis=1) )
        test2 = max( ub.max(axis=1) - ub.min(axis=1) )
        if test1 >0.00000001 or test2>0.00000001:
            raise Exception("Not implemented: perfect foresight solution requires that controls have constant bounds.")
    else:
        ignore_constraints=True
        lower_bound = None
        upper_bound = None

    nn = sh[0]*sh[1]

    fobj  = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x, epsilons)[0].ravel()

    from dolo.numeric.solver import solver

    if not ignore_constraints:
        dfobj = lambda vec: det_residual( model, vec.reshape(sh), start_s, final_x, epsilons)[1]
        from dolo.numeric.ncpsolve import ncpsolve
        ff  = lambda vec: det_residual(model, vec.reshape(sh), start_s, final_x, epsilons)
        sol = ncpsolve(ff, lower_bound.ravel(), upper_bound.ravel(), initial_guess.ravel(), verbose=verbose, maxit=maxit )
        if isinstance(sol, list):
            raise Exception("No convergence after {} iterations.".format(sol[1]))
#        sol = solver(fobj, initial_guess.ravel(), lb=lower_bound.ravel(), ub=upper_bound.ravel(), jac=dfobj, method='ncpsolve' )
        sol = sol.reshape(sh)
        #sol = solver(fobj, initial_guess, jac=dfobj, lb=lower_bound, ub=upper_bound, method='ncpsolve', serial_problem=False, verbose=verbose )
    else:
        from scipy.optimize import fsolve
        dfobj = lambda vec: det_residual( model, vec.reshape(sh), start_s, final_x, epsilons)[1].toarray()
        x0 = initial_guess.ravel()
        sol = fsolve(fobj, x0, fprime=dfobj)
        sol = sol.reshape(sh)

#        sol = solver(fobj, initial_guess, jac=dfobj, method='fsolve', serial_problem=False, verbose=verbose )

    if use_pandas:
        import pandas
        if 'auxiliary' in model.functions:
            colnames = model.symbols['states'] + model.symbols['controls'] + model.symbols['auxiliary']
            # compute auxiliaries
            y = model.functions['auxiliary'](sol[:n_s,:], sol[n_s:,:], p)
            sol = numpy.row_stack([sol,y])
        else:
            colnames = model.symbols['states'] + model.symbols['controls']

        ts = pandas.DataFrame(sol.T, columns=colnames)
        return ts
    else:
        return sol

def det_residual(model, guess, start, final, shocks, diff=True):
    '''
    Computes the residuals, the derivatives of the stacked-time system.
    :param model: an fga model
    :param guess: the guess for the simulated values. An `(n_s.n_x) x N` array, where n_s is the number of states,
    n_x the number of controls, and `N` the length of the simulation.
    :param start: initial boundary condition (initial value of the states)
    :param final: final boundary condition (last value of the controls)
    :param shocks: values for the exogenous shocks
    :param diff: if True, the derivatives are computes
    :return: a list with two elements:
        - an `(n_s.n_x) x N` array with the residuals of the system
        - a `(n_s.n_x) x N x (n_s.n_x) x N` array representing the jacobian of the system
    '''

    # TODO: compute a sparse derivative and ensure the solvers can deal with it

    n_s = len( model.symbols['states'] )
    n_x = len( model.symbols['controls'] )

    n_e = len( model.symbols['shocks'] )
    N = guess.shape[1]

    p = model.calibration['parameters']

    f = model.functions['arbitrage']
    g = model.functions['transition']

    vec = guess[:,:-1]
    vec_f = guess[:,1:]

    s = vec[:n_s,:]
    x = vec[n_s:,:]
    S = vec_f[:n_s,:]
    X = vec_f[n_s:,:]

    if diff:
        SS, SS_s, SS_x, SS_e = g(s,x,shocks,p, derivs=True)
        R, R_s, R_x, R_S, R_X = f(s,x,S,X,p,derivs=True)
    else:
        SS = g(s,x,shocks,p)
        R = f(s,x,S,X,p)

    res_s = SS - S
    res_x = R

    res = numpy.zeros( (n_s+n_x, N) )

    res[:n_s,1:] = res_s
    res[n_s:,:-1] = res_x

    res[:n_s,0] = - (guess[:n_s,0] - start)
    res[n_s:, -1] = - (guess[n_s:, -1] - guess[n_s:, -2] )

    if not diff:
        return res
    else:

        sparse_jac=False
        if not sparse_jac:

            # we compute the derivative matrix

            from dolo.numeric.serial_operations import serial_multiplication as smult
            res_s_s = SS_s
            res_s_x = SS_x

            # next block is probably very inefficient
            jac = numpy.zeros( (n_s+n_x, N, n_s+n_x, N) )
            for i in range(N-1):
                jac[n_s:,i,:n_s,i] = R_s[:,:,i]
                jac[n_s:,i,n_s:,i] = R_x[:,:,i]
                jac[n_s:,i,:n_s,i+1] = R_S[:,:,i]
                jac[n_s:,i,n_s:,i+1] = R_X[:,:,i]
                jac[:n_s,i+1,:n_s,i] = SS_s[:,:,i]
                jac[:n_s,i+1,n_s:,i] = SS_x[:,:,i]
                jac[:n_s,i+1,:n_s,i+1] = -numpy.eye(n_s)
            jac[:n_s,0,:n_s,0] = - numpy.eye(n_s)
            jac[n_s:,-1,n_s:,-1] = - numpy.eye(n_x)
            jac[n_s:,-1,n_s:,-2] = + numpy.eye(n_x)
            nn = jac.shape[0]*jac.shape[1]
            res = res.ravel()
            jac = jac.reshape((nn,nn))

        from scipy.sparse import csc_matrix, csr_matrix

        jac = csr_matrix(jac)

        return [res,jac]

if __name__ == '__main__':

    # this example computes the response of the rbc economy to a series of expected productivity shocks.
    # investment is bounded by an exogenous value 0.2, so that investment is constrained in the first periods

    # TODO: propose a meaningful economic example

    from dolo import *
    from pylab import *

    model = yaml_import('examples/global_models/rbc_pf.yaml')

    e_z = atleast_2d( linspace(0.1, 0.0, 10) )

    start_s = numpy.zeros(2) * numpy.nan
    start_s[0] = 1.5

    import time
    t1 = time.time()
    #sol1 = deterministic_solve(model, shocks=e_z, T=50, use_pandas=True, ignore_constraints=True, start_s=start_s)

    #sol1 = deterministic_solve(model, T=50, use_pandas=True, ignore_constraints=True, start_s=start_s)

    sol2 = deterministic_solve(model, shocks=e_z, T=1000, use_pandas=True, ignore_constraints=False)
    t2 = time.time()

    print("Elapsed : {}".format(t2-t1))

    exit()
    from pylab import *

    subplot(211)
    plot(sol1['k'], label='k')
    plot(sol1['z'], label='z')
    plot(sol1['i'], label='i')

    subplot(212)
    plot(sol2['k'], label='k')
    plot(sol2['z'], label='z')
    plot(sol2['i'], label='i')
    plot(sol2['i']*0 + sol2['i'].max(), linestyle='--', color='black')

    legend()
    show()

<|endoftext|>