<commit_before>import unittest
import numpy as np
from . import rge
from . import matrixelements
from . import wilsoncoefficients
from . import matrixelements
from .. import eft, ckm
from ..running import running
from math import log
from flavio.physics.eft import WilsonCoefficients
from flavio.physics.bdecays.wilsoncoefficients import wctot_dict

s = 1.519267515435317e+24

par = {
    'm_e': 0.510998928e-3,
    'm_mu': 105.6583715e-3,
    'm_tau': 1.77686,
    'm_B+': 5.27929,
    'm_B0': 5.27961,
    'm_Bs': 5.36679,
    'm_K*0': 0.89166,
    'tau_B+': 1638.e-15*s,
    'tau_B0': 152.e-14*s,
    'alpha_e': 1/127.940,
    'alpha_s': 0.1185,
    'm_Z': 91.1876,
    'm_b': 4.17,
    'm_s': 0.1,
    'm_t': 173.1,
    'm_c': 1.275,
    'GF': 1.1663787e-5,
    'Vus': 0.22,
    'Vub': 3.7e-3,
    'Vcb': 4.1e-2,
    'gamma': 1.22,
}

class TestBMatrixElements(unittest.TestCase):
    def test_functions(self):
        # check if the limit q2->0 is implemented correctly
        self.assertAlmostEqual(matrixelements.F_87(0.1, 0.),
                               matrixelements.F_87(0.1, 1e-8),
                               places=6)
        self.assertAlmostEqual(matrixelements.SeidelA(0, 4, 5),
                               matrixelements.SeidelA(1e-8, 4, 5),
                               places=6)
        # for F_89, just see if this raises an exception
        matrixelements.F_89(0.4, 0.5)
        wc_obj = WilsonCoefficients()
        wc = wctot_dict(wc_obj, 'bsmumu', 4.2, par)
        matrixelements.delta_C7(par, wc, q2=3.5, scale=4.2, qiqj='bs')
        matrixelements.delta_C9(par, wc, q2=3.5, scale=4.2, qiqj='bs')
        # comparing to the values from the data file
        x =  [1.3, 0.13, 0.18]
        self.assertEqual(matrixelements.F_17(*x), -0.795182 -0.0449909j)
        self.assertEqual(matrixelements.F_19(*x),-16.3032 +0.281462j)
        self.assertEqual(matrixelements.F_27(*x), 4.77109 +0.269943j)
        self.assertEqual(matrixelements.F_29(*x), 6.75552 -1.6887j)
        # it should be that F17+F27/6=0
        self.assertAlmostEqual(matrixelements.F_17(*x),-matrixelements.F_27(*x)/6,places=5)
        # check the limiting cases of the quark loop function
        self.assertAlmostEqual(matrixelements.h(3.5, 1e-8, 4.2), matrixelements.h(3.5, 0., 4.2), places=6)
        self.assertAlmostEqual(matrixelements.h(1e-8, 1.2, 4.2), matrixelements.h(0., 1.2, 4.2), places=6)
        # comparing roughly to the plots in hep-ph/0403185v2 (but with opposite sign!)
        x = [2.5, 4.75, 4.75]
        np.testing.assert_almost_equal(-matrixelements.Fu_17(*x), 1.045 + 0.62j, decimal=1)
        np.testing.assert_almost_equal(-matrixelements.Fu_19(*x), -0.57 + 8.3j, decimal=1)
        np.testing.assert_almost_equal(-matrixelements.Fu_29(*x), -13.9 + -32.5j, decimal=0)
<commit_msg>Fix 1 test<commit_after>import unittest
import numpy as np
from . import rge
from . import matrixelements
from . import wilsoncoefficients
from . import matrixelements
from .. import eft, ckm
from ..running import running
from math import log
from flavio.physics.eft import WilsonCoefficients
from flavio.physics.bdecays.wilsoncoefficients import wctot_dict

s = 1.519267515435317e+24

par = {
    'm_e': 0.510998928e-3,
    'm_mu': 105.6583715e-3,
    'm_tau': 1.77686,
    'm_B+': 5.27929,
    'm_B0': 5.27961,
    'm_Bs': 5.36679,
    'm_K*0': 0.89166,
    'tau_B+': 1638.e-15*s,
    'tau_B0': 152.e-14*s,
    'alpha_e': 1/127.940,
    'alpha_s': 0.1185,
    'm_Z': 91.1876,
    'm_b': 4.17,
    'm_s': 0.1,
    'm_t': 173.1,
    'm_c': 1.275,
    'm_c BVgamma': 1.5,
    'GF': 1.1663787e-5,
    'Vus': 0.22,
    'Vub': 3.7e-3,
    'Vcb': 4.1e-2,
    'gamma': 1.22,
}

class TestBMatrixElements(unittest.TestCase):
    def test_functions(self):
        # check if the limit q2->0 is implemented correctly
        self.assertAlmostEqual(matrixelements.F_87(0.1, 0.),
                               matrixelements.F_87(0.1, 1e-8),
                               places=6)
        self.assertAlmostEqual(matrixelements.SeidelA(0, 4, 5),
                               matrixelements.SeidelA(1e-8, 4, 5),
                               places=6)
        # for F_89, just see if this raises an exception
        matrixelements.F_89(0.4, 0.5)
        wc_obj = WilsonCoefficients()
        wc = wctot_dict(wc_obj, 'bsmumu', 4.2, par)
        matrixelements.delta_C7(par, wc, q2=3.5, scale=4.2, qiqj='bs')
        matrixelements.delta_C9(par, wc, q2=3.5, scale=4.2, qiqj='bs')
        # comparing to the values from the data file
        x =  [1.3, 0.13, 0.18]
        self.assertEqual(matrixelements.F_17(*x), -0.795182 -0.0449909j)
        self.assertEqual(matrixelements.F_19(*x),-16.3032 +0.281462j)
        self.assertEqual(matrixelements.F_27(*x), 4.77109 +0.269943j)
        self.assertEqual(matrixelements.F_29(*x), 6.75552 -1.6887j)
        # it should be that F17+F27/6=0
        self.assertAlmostEqual(matrixelements.F_17(*x),-matrixelements.F_27(*x)/6,places=5)
        # check the limiting cases of the quark loop function
        self.assertAlmostEqual(matrixelements.h(3.5, 1e-8, 4.2), matrixelements.h(3.5, 0., 4.2), places=6)
        self.assertAlmostEqual(matrixelements.h(1e-8, 1.2, 4.2), matrixelements.h(0., 1.2, 4.2), places=6)
        # comparing roughly to the plots in hep-ph/0403185v2 (but with opposite sign!)
        x = [2.5, 4.75, 4.75]
        np.testing.assert_almost_equal(-matrixelements.Fu_17(*x), 1.045 + 0.62j, decimal=1)
        np.testing.assert_almost_equal(-matrixelements.Fu_19(*x), -0.57 + 8.3j, decimal=1)
        np.testing.assert_almost_equal(-matrixelements.Fu_29(*x), -13.9 + -32.5j, decimal=0)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from ironicclient.common import utils
from ironicclient.openstack.common import cliutils
from ironicclient.v1 import resource_fields as res_fields

def _print_port_show(port):
    fields = ['address', 'created_at', 'extra', 'node_uuid', 'updated_at',
              'uuid']
    data = dict([(f, getattr(port, f, '')) for f in fields])
    cliutils.print_dict(data, wrap=72)

@cliutils.arg('port', metavar='<port id>', help="UUID of port")
@cliutils.arg(
    '--address',
    dest='address',
    action='store_true',
    default=False,
    help='Get the port by it\'s MAC address instead of UUID.')
def do_port_show(cc, args):
    """Show a port."""
    if args.address:
        port = cc.port.get_by_address(args.port)
    else:
        port = cc.port.get(args.port)
    _print_port_show(port)

@cliutils.arg(
    '--detail',
    dest='detail',
    action='store_true',
    default=False,
    help="Show detailed information about ports.")
@cliutils.arg(
    '--address',
    metavar='<macaddress>',
    help='MAC address of port, to get the port'
         'which has this address')
@cliutils.arg(
    '--limit',
    metavar='<limit>',
    type=int,
    help='Maximum number of ports to return per request, '
         '0 for no limit. Default is the maximum number used '
         'by the Ironic API Service.')
@cliutils.arg(
    '--marker',
    metavar='<marker>',
    help='Port UUID (e.g of the last port in the list from '
         'a previous request). Returns the list of ports '
         'after this UUID.')
@cliutils.arg(
    '--sort-key',
    metavar='<sort_key>',
    help='Port field that will be used for sorting.')
@cliutils.arg(
    '--sort-dir',
    metavar='<sort_dir>',
    choices=['asc', 'desc'],
    help='Sort direction: one of "asc" (the default) or "desc".')
def do_port_list(cc, args):
    """List ports."""
    params = {}

    if args.address is not None:
        params['address'] = args.address
    if args.detail:
        fields = res_fields.PORT_FIELDS
        field_labels = res_fields.PORT_FIELD_LABELS
    else:
        fields = res_fields.PORT_LIST_FIELDS
        field_labels = res_fields.PORT_LIST_FIELD_LABELS

    params.update(utils.common_params_for_list(args,
                                               fields,
                                               field_labels))

    port = cc.port.list(**params)
    cliutils.print_list(port, fields,
                        field_labels=field_labels,
                        sortby_index=None)

@cliutils.arg(
    '-a', '--address',
    metavar='<address>',
    required=True,
    help='MAC Address for this port')
@cliutils.arg(
    '-n', '--node_uuid',
    metavar='<node uuid>',
    required=True,
    help='UUID of the node that this port belongs to')
@cliutils.arg(
    '-e', '--extra',
    metavar="<key=value>",
    action='append',
    help="Record arbitrary key/value metadata. "
         "Can be specified multiple times")
def do_port_create(cc, args):
    """Create a new port."""
    field_list = ['address', 'extra', 'node_uuid']
    fields = dict((k, v) for (k, v) in vars(args).items()
                  if k in field_list and not (v is None))
    fields = utils.args_array_to_dict(fields, 'extra')
    port = cc.port.create(**fields)

    field_list.append('uuid')
    data = dict([(f, getattr(port, f, '')) for f in field_list])
    cliutils.print_dict(data, wrap=72)

@cliutils.arg('port', metavar='<port id>', nargs='+', help="UUID of port")
def do_port_delete(cc, args):
    """Delete a port."""
    for p in args.port:
        cc.port.delete(p)
        print ('Deleted port %s' % p)

@cliutils.arg('port', metavar='<port id>', help="UUID of port")
@cliutils.arg(
    'op',
    metavar='<op>',
    choices=['add', 'replace', 'remove'],
    help="Operations: 'add', 'replace' or 'remove'")
@cliutils.arg(
    'attributes',
    metavar='<path=value>',
    nargs='+',
    action='append',
    default=[],
    help="Attributes to add/replace or remove "
         "(only PATH is necessary on remove)")
def do_port_update(cc, args):
    """Update a port."""
    patch = utils.args_array_to_patch(args.op, args.attributes[0])
    port = cc.port.update(args.port, patch)
    _print_port_show(port)
<commit_msg>Fix help string for port-list<commit_after># -*- coding: utf-8 -*-
#
# Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from ironicclient.common import utils
from ironicclient.openstack.common import cliutils
from ironicclient.v1 import resource_fields as res_fields

def _print_port_show(port):
    fields = ['address', 'created_at', 'extra', 'node_uuid', 'updated_at',
              'uuid']
    data = dict([(f, getattr(port, f, '')) for f in fields])
    cliutils.print_dict(data, wrap=72)

@cliutils.arg('port', metavar='<port id>', help="UUID of port")
@cliutils.arg(
    '--address',
    dest='address',
    action='store_true',
    default=False,
    help='Get the port by it\'s MAC address instead of UUID.')
def do_port_show(cc, args):
    """Show a port."""
    if args.address:
        port = cc.port.get_by_address(args.port)
    else:
        port = cc.port.get(args.port)
    _print_port_show(port)

@cliutils.arg(
    '--detail',
    dest='detail',
    action='store_true',
    default=False,
    help="Show detailed information about ports.")
@cliutils.arg(
    '--address',
    metavar='<macaddress>',
    help='MAC address of port, to get the port '
         'which has this address.')
@cliutils.arg(
    '--limit',
    metavar='<limit>',
    type=int,
    help='Maximum number of ports to return per request, '
         '0 for no limit. Default is the maximum number used '
         'by the Ironic API Service.')
@cliutils.arg(
    '--marker',
    metavar='<marker>',
    help='Port UUID (e.g of the last port in the list from '
         'a previous request). Returns the list of ports '
         'after this UUID.')
@cliutils.arg(
    '--sort-key',
    metavar='<sort_key>',
    help='Port field that will be used for sorting.')
@cliutils.arg(
    '--sort-dir',
    metavar='<sort_dir>',
    choices=['asc', 'desc'],
    help='Sort direction: one of "asc" (the default) or "desc".')
def do_port_list(cc, args):
    """List ports."""
    params = {}

    if args.address is not None:
        params['address'] = args.address
    if args.detail:
        fields = res_fields.PORT_FIELDS
        field_labels = res_fields.PORT_FIELD_LABELS
    else:
        fields = res_fields.PORT_LIST_FIELDS
        field_labels = res_fields.PORT_LIST_FIELD_LABELS

    params.update(utils.common_params_for_list(args,
                                               fields,
                                               field_labels))

    port = cc.port.list(**params)
    cliutils.print_list(port, fields,
                        field_labels=field_labels,
                        sortby_index=None)

@cliutils.arg(
    '-a', '--address',
    metavar='<address>',
    required=True,
    help='MAC Address for this port')
@cliutils.arg(
    '-n', '--node_uuid',
    metavar='<node uuid>',
    required=True,
    help='UUID of the node that this port belongs to')
@cliutils.arg(
    '-e', '--extra',
    metavar="<key=value>",
    action='append',
    help="Record arbitrary key/value metadata. "
         "Can be specified multiple times")
def do_port_create(cc, args):
    """Create a new port."""
    field_list = ['address', 'extra', 'node_uuid']
    fields = dict((k, v) for (k, v) in vars(args).items()
                  if k in field_list and not (v is None))
    fields = utils.args_array_to_dict(fields, 'extra')
    port = cc.port.create(**fields)

    field_list.append('uuid')
    data = dict([(f, getattr(port, f, '')) for f in field_list])
    cliutils.print_dict(data, wrap=72)

@cliutils.arg('port', metavar='<port id>', nargs='+', help="UUID of port")
def do_port_delete(cc, args):
    """Delete a port."""
    for p in args.port:
        cc.port.delete(p)
        print ('Deleted port %s' % p)

@cliutils.arg('port', metavar='<port id>', help="UUID of port")
@cliutils.arg(
    'op',
    metavar='<op>',
    choices=['add', 'replace', 'remove'],
    help="Operations: 'add', 'replace' or 'remove'")
@cliutils.arg(
    'attributes',
    metavar='<path=value>',
    nargs='+',
    action='append',
    default=[],
    help="Attributes to add/replace or remove "
         "(only PATH is necessary on remove)")
def do_port_update(cc, args):
    """Update a port."""
    patch = utils.args_array_to_patch(args.op, args.attributes[0])
    port = cc.port.update(args.port, patch)
    _print_port_show(port)
<|endoftext|>


<commit_before>from __future__ import absolute_import

import datetime
from itertools import product

import iris
from iris.util import guess_coord_axis

import numpy as np

from .interface import Interface
from .grid import GridInterface
from ..ndmapping import (NdMapping, item_check, sorted_context)
from ..spaces import HoloMap, DynamicMap
from .. import util

from holoviews.core.dimension import Dimension

def get_date_format(coord):
    def date_formatter(val, pos=None):
        date = coord.units.num2date(val)
        date_format = Dimension.type_formatters.get(datetime.datetime, None)
        if date_format:
            return date.strftime(date_format)
        else:
            return date

    return date_formatter

def coord_to_dimension(coord):
    """
    Converts an iris coordinate to a HoloViews dimension.
    """
    kwargs = {}
    if coord.units.is_time_reference():
        kwargs['value_format'] = get_date_format(coord)
    else:
        kwargs['unit'] = str(coord.units)
    return Dimension(coord.name(), **kwargs)

def sort_coords(coord):
    """
    Sorts a list of DimCoords trying to ensure that
    dates and pressure levels appear first and the
    longitude and latitude appear last in the correct
    order.
    """
    order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
    axis = guess_coord_axis(coord)
    return (order.get(axis, 0), coord and coord.name())

class CubeInterface(GridInterface):
    """
    The CubeInterface provides allows HoloViews to interact with iris
    Cube data. When passing an iris Cube to a HoloViews Element the
    init method will infer the dimensions of the Cube from its
    coordinates. Currently the interface only provides the basic
    methods required for HoloViews to work with an object.
    """

    types = (iris.cube.Cube,)

    datatype = 'cube'

    @classmethod
    def init(cls, eltype, data, kdims, vdims):
        if kdims:
            kdim_names = [kd.name if isinstance(kd, Dimension) else kd for kd in kdims]
        else:
            kdim_names = [kd.name for kd in eltype.kdims]

        if not isinstance(data, iris.cube.Cube):
            ndims = len(kdim_names)
            kdims = [kd if isinstance(kd, Dimension) else Dimension(kd)
                     for kd in kdims]
            vdim = vdims[0].name if isinstance(vdims[0], Dimension) else vdims[0]
            if isinstance(data, tuple):
                value_array = data[-1]
                data = {d: vals for d, vals in zip(kdim_names + [vdim], data)}
            elif isinstance(data, dict):
                value_array = data[vdim]
            coords = [(iris.coords.DimCoord(data[kd.name], long_name=kd.name,
                                            units=kd.unit), ndims-n-1)
                      for n, kd in enumerate(kdims)]
            try:
                data = iris.cube.Cube(value_array, long_name=vdim,
                                      dim_coords_and_dims=coords)
            except:
                pass
            if not isinstance(data, iris.cube.Cube):
                raise TypeError('Data must be be an iris dataset type.')

        if kdims:
            coords = []
            for kd in kdims:
                coord = data.coords(kd.name if isinstance(kd, Dimension) else kd)
                if len(coord) == 0:
                    raise ValueError('Key dimension %s not found in '
                                     'Iris cube.' % kd)
                coords.append(coord[0])
        else:
            coords = data.dim_coords
            coords = sorted(coords, key=sort_coords)
        kdims = [coord_to_dimension(crd) for crd in coords]
        if vdims is None:
            vdims = [Dimension(data.name(), unit=str(data.units))]

        return data, {'kdims':kdims, 'vdims':vdims}, {'group':data.name()}

    @classmethod
    def validate(cls, dataset):
        pass

    @classmethod
    def values(cls, dataset, dim, expanded=True, flat=True):
        """
        Returns an array of the values along the supplied dimension.
        """
        dim = dataset.get_dimension(dim)
        if dim in dataset.vdims:
            data = dataset.data.copy().data
            coord_names = [c.name() for c in dataset.data.dim_coords
                           if c.name() in dataset.kdims]
            if flat:
                dim_inds = [coord_names.index(d.name) for d in dataset.kdims]
                dim_inds += [i for i in range(len(dataset.data.dim_coords))
                             if i not in dim_inds]
                data = data.transpose(dim_inds)
        elif expanded:
            idx = dataset.get_dimension_index(dim)
            data = util.cartesian_product([dataset.data.coords(d.name)[0].points
                                           for d in dataset.kdims])[idx]
        else:
            data = dataset.data.coords(dim.name)[0].points
        return data.flatten() if flat else data

    @classmethod
    def reindex(cls, dataset, kdims=None, vdims=None):
        """
        Since cubes are never indexed directly the data itself
        does not need to be reindexed, the Element can simply
        reorder its key dimensions.
        """
        dropped = {d.name: cls.values(dataset, d, False)[0]
                   for d in dataset.kdims if d not in kdims
                   and len(cls.values(dataset, d, False)) == 1}
        if dropped:
            constraints = iris.Constraint(**dropped)
            return dataset.data.extract(constraints)
        else:
            return dataset.data

    @classmethod
    def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
        """
        Groups the data by one or more dimensions returning a container
        indexed by the grouped dimensions containing slices of the
        cube wrapped in the group_type. This makes it very easy to
        break up a high-dimensional dataset into smaller viewable chunks.
        """
        if not isinstance(dims, list): dims = [dims]
        dynamic = kwargs.pop('dynamic', False)
        dims = [dataset.get_dimension(d) for d in dims]
        constraints = [d.name for d in dims]
        slice_dims = [d for d in dataset.kdims if d not in dims]

        if dynamic:
            def load_subset(*args):
                constraint = iris.Constraint(**dict(zip(constraints, args)))
                return dataset.clone(dataset.data.extract(constraint),
                                      new_type=group_type,
                                      **dict(kwargs, kdims=slice_dims))
            dynamic_dims = [d(values=list(cls.values(dataset, d, False))) for d in dims]
            return DynamicMap(load_subset, kdims=dynamic_dims)

        unique_coords = product(*[cls.values(dataset, d, expanded=False)
                                  for d in dims])
        data = []
        for key in unique_coords:
            constraint = iris.Constraint(**dict(zip(constraints, key)))
            cube = dataset.clone(dataset.data.extract(constraint),
                                  new_type=group_type,
                                  **dict(kwargs, kdims=slice_dims))
            data.append((key, cube))
        if issubclass(container_type, NdMapping):
            with item_check(False), sorted_context(False):
                return container_type(data, kdims=dims)
        else:
            return container_type(data)

    @classmethod
    def range(cls, dataset, dimension):
        """
        Computes the range along a particular dimension.
        """
        dim = dataset.get_dimension(dimension)
        values = dataset.dimension_values(dim, False)
        return (np.nanmin(values), np.nanmax(values))

    @classmethod
    def redim(cls, dataset, dimensions):
        """
        Rename coords on the Cube.
        """
        new_dataset = dataset.data.copy()
        for name, new_dim in dimensions.items():
            if name == new_dataset.name():
                new_dataset.rename(new_dim.name)
            for coord in new_dataset.dim_coords:
                if name == coord.name():
                    coord.rename(new_dim.name)
        return new_dataset

    @classmethod
    def length(cls, dataset):
        """
        Returns the total number of samples in the dataset.
        """
        return np.product([len(d.points) for d in dataset.data.coords()])

    @classmethod
    def sort(cls, columns, by=[]):
        """
        Cubes are assumed to be sorted by default.
        """
        return columns

    @classmethod
    def aggregate(cls, columns, kdims, function, **kwargs):
        """
        Aggregation currently not implemented.
        """
        raise NotImplementedError

    @classmethod
    def sample(cls, dataset, samples=[]):
        """
        Sampling currently not implemented.
        """
        raise NotImplementedError

    @classmethod
    def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
        """
        Adding value dimensions not currently supported by iris interface.
        Adding key dimensions not possible on dense interfaces.
        """
        if not vdim:
            raise Exception("Cannot add key dimension to a dense representation.")
        raise NotImplementedError

    @classmethod
    def select_to_constraint(cls, selection):
        """
        Transform a selection dictionary to an iris Constraint.
        """
        constraint_kwargs = {}
        for dim, constraint in selection.items():
            if isinstance(constraint, slice):
                constraint = (constraint.start, constraint.stop)
            if isinstance(constraint, tuple):
                constraint = iris.util.between(*constraint, rh_inclusive=False)
            constraint_kwargs[dim] = constraint
        return iris.Constraint(**constraint_kwargs)

    @classmethod
    def select(cls, dataset, selection_mask=None, **selection):
        """
        Apply a selection to the data.
        """
        constraint = cls.select_to_constraint(selection)
        pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
        indexed = cls.indexed(dataset, selection)
        extracted = dataset.data.extract(constraint)
        if indexed and not extracted.dim_coords:
            return extracted.data.item()
        post_dim_coords = [c.name() for c in extracted.dim_coords]
        dropped = [c for c in pre_dim_coords if c not in post_dim_coords]
        for d in dropped:
            extracted = iris.util.new_axis(extracted, d)
        return extracted

Interface.register(CubeInterface)
<commit_msg>Removed superfluous dynamic groupby in iris<commit_after>from __future__ import absolute_import

import datetime
from itertools import product

import iris
from iris.util import guess_coord_axis

import numpy as np

from .interface import Interface
from .grid import GridInterface
from ..ndmapping import (NdMapping, item_check, sorted_context)
from ..spaces import HoloMap, DynamicMap
from .. import util

from holoviews.core.dimension import Dimension

def get_date_format(coord):
    def date_formatter(val, pos=None):
        date = coord.units.num2date(val)
        date_format = Dimension.type_formatters.get(datetime.datetime, None)
        if date_format:
            return date.strftime(date_format)
        else:
            return date

    return date_formatter

def coord_to_dimension(coord):
    """
    Converts an iris coordinate to a HoloViews dimension.
    """
    kwargs = {}
    if coord.units.is_time_reference():
        kwargs['value_format'] = get_date_format(coord)
    else:
        kwargs['unit'] = str(coord.units)
    return Dimension(coord.name(), **kwargs)

def sort_coords(coord):
    """
    Sorts a list of DimCoords trying to ensure that
    dates and pressure levels appear first and the
    longitude and latitude appear last in the correct
    order.
    """
    order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
    axis = guess_coord_axis(coord)
    return (order.get(axis, 0), coord and coord.name())

class CubeInterface(GridInterface):
    """
    The CubeInterface provides allows HoloViews to interact with iris
    Cube data. When passing an iris Cube to a HoloViews Element the
    init method will infer the dimensions of the Cube from its
    coordinates. Currently the interface only provides the basic
    methods required for HoloViews to work with an object.
    """

    types = (iris.cube.Cube,)

    datatype = 'cube'

    @classmethod
    def init(cls, eltype, data, kdims, vdims):
        if kdims:
            kdim_names = [kd.name if isinstance(kd, Dimension) else kd for kd in kdims]
        else:
            kdim_names = [kd.name for kd in eltype.kdims]

        if not isinstance(data, iris.cube.Cube):
            ndims = len(kdim_names)
            kdims = [kd if isinstance(kd, Dimension) else Dimension(kd)
                     for kd in kdims]
            vdim = vdims[0].name if isinstance(vdims[0], Dimension) else vdims[0]
            if isinstance(data, tuple):
                value_array = data[-1]
                data = {d: vals for d, vals in zip(kdim_names + [vdim], data)}
            elif isinstance(data, dict):
                value_array = data[vdim]
            coords = [(iris.coords.DimCoord(data[kd.name], long_name=kd.name,
                                            units=kd.unit), ndims-n-1)
                      for n, kd in enumerate(kdims)]
            try:
                data = iris.cube.Cube(value_array, long_name=vdim,
                                      dim_coords_and_dims=coords)
            except:
                pass
            if not isinstance(data, iris.cube.Cube):
                raise TypeError('Data must be be an iris dataset type.')

        if kdims:
            coords = []
            for kd in kdims:
                coord = data.coords(kd.name if isinstance(kd, Dimension) else kd)
                if len(coord) == 0:
                    raise ValueError('Key dimension %s not found in '
                                     'Iris cube.' % kd)
                coords.append(coord[0])
        else:
            coords = data.dim_coords
            coords = sorted(coords, key=sort_coords)
        kdims = [coord_to_dimension(crd) for crd in coords]
        if vdims is None:
            vdims = [Dimension(data.name(), unit=str(data.units))]

        return data, {'kdims':kdims, 'vdims':vdims}, {'group':data.name()}

    @classmethod
    def validate(cls, dataset):
        pass

    @classmethod
    def values(cls, dataset, dim, expanded=True, flat=True):
        """
        Returns an array of the values along the supplied dimension.
        """
        dim = dataset.get_dimension(dim)
        if dim in dataset.vdims:
            data = dataset.data.copy().data
            coord_names = [c.name() for c in dataset.data.dim_coords
                           if c.name() in dataset.kdims]
            if flat:
                dim_inds = [coord_names.index(d.name) for d in dataset.kdims]
                dim_inds += [i for i in range(len(dataset.data.dim_coords))
                             if i not in dim_inds]
                data = data.transpose(dim_inds)
        elif expanded:
            idx = dataset.get_dimension_index(dim)
            data = util.cartesian_product([dataset.data.coords(d.name)[0].points
                                           for d in dataset.kdims])[idx]
        else:
            data = dataset.data.coords(dim.name)[0].points
        return data.flatten() if flat else data

    @classmethod
    def reindex(cls, dataset, kdims=None, vdims=None):
        """
        Since cubes are never indexed directly the data itself
        does not need to be reindexed, the Element can simply
        reorder its key dimensions.
        """
        dropped = {d.name: cls.values(dataset, d, False)[0]
                   for d in dataset.kdims if d not in kdims
                   and len(cls.values(dataset, d, False)) == 1}
        if dropped:
            constraints = iris.Constraint(**dropped)
            return dataset.data.extract(constraints)
        else:
            return dataset.data

    @classmethod
    def groupby(cls, dataset, dims, container_type=HoloMap, group_type=None, **kwargs):
        """
        Groups the data by one or more dimensions returning a container
        indexed by the grouped dimensions containing slices of the
        cube wrapped in the group_type. This makes it very easy to
        break up a high-dimensional dataset into smaller viewable chunks.
        """
        if not isinstance(dims, list): dims = [dims]
        dynamic = kwargs.pop('dynamic', False)
        dims = [dataset.get_dimension(d) for d in dims]
        constraints = [d.name for d in dims]
        slice_dims = [d for d in dataset.kdims if d not in dims]

        unique_coords = product(*[cls.values(dataset, d, expanded=False)
                                  for d in dims])
        data = []
        for key in unique_coords:
            constraint = iris.Constraint(**dict(zip(constraints, key)))
            cube = dataset.clone(dataset.data.extract(constraint),
                                  new_type=group_type,
                                  **dict(kwargs, kdims=slice_dims))
            data.append((key, cube))
        if issubclass(container_type, NdMapping):
            with item_check(False), sorted_context(False):
                return container_type(data, kdims=dims)
        else:
            return container_type(data)

    @classmethod
    def range(cls, dataset, dimension):
        """
        Computes the range along a particular dimension.
        """
        dim = dataset.get_dimension(dimension)
        values = dataset.dimension_values(dim, False)
        return (np.nanmin(values), np.nanmax(values))

    @classmethod
    def redim(cls, dataset, dimensions):
        """
        Rename coords on the Cube.
        """
        new_dataset = dataset.data.copy()
        for name, new_dim in dimensions.items():
            if name == new_dataset.name():
                new_dataset.rename(new_dim.name)
            for coord in new_dataset.dim_coords:
                if name == coord.name():
                    coord.rename(new_dim.name)
        return new_dataset

    @classmethod
    def length(cls, dataset):
        """
        Returns the total number of samples in the dataset.
        """
        return np.product([len(d.points) for d in dataset.data.coords()])

    @classmethod
    def sort(cls, columns, by=[]):
        """
        Cubes are assumed to be sorted by default.
        """
        return columns

    @classmethod
    def aggregate(cls, columns, kdims, function, **kwargs):
        """
        Aggregation currently not implemented.
        """
        raise NotImplementedError

    @classmethod
    def sample(cls, dataset, samples=[]):
        """
        Sampling currently not implemented.
        """
        raise NotImplementedError

    @classmethod
    def add_dimension(cls, columns, dimension, dim_pos, values, vdim):
        """
        Adding value dimensions not currently supported by iris interface.
        Adding key dimensions not possible on dense interfaces.
        """
        if not vdim:
            raise Exception("Cannot add key dimension to a dense representation.")
        raise NotImplementedError

    @classmethod
    def select_to_constraint(cls, selection):
        """
        Transform a selection dictionary to an iris Constraint.
        """
        constraint_kwargs = {}
        for dim, constraint in selection.items():
            if isinstance(constraint, slice):
                constraint = (constraint.start, constraint.stop)
            if isinstance(constraint, tuple):
                constraint = iris.util.between(*constraint, rh_inclusive=False)
            constraint_kwargs[dim] = constraint
        return iris.Constraint(**constraint_kwargs)

    @classmethod
    def select(cls, dataset, selection_mask=None, **selection):
        """
        Apply a selection to the data.
        """
        constraint = cls.select_to_constraint(selection)
        pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
        indexed = cls.indexed(dataset, selection)
        extracted = dataset.data.extract(constraint)
        if indexed and not extracted.dim_coords:
            return extracted.data.item()
        post_dim_coords = [c.name() for c in extracted.dim_coords]
        dropped = [c for c in pre_dim_coords if c not in post_dim_coords]
        for d in dropped:
            extracted = iris.util.new_axis(extracted, d)
        return extracted

Interface.register(CubeInterface)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 17:33:27 2018

@author: dan
"""

import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
from matplotlib.colors import LightSource

class Texture(object):
    "simple texture filter"

    def __init__(self, style='noise', **kwargs):
        self.style = style
        self.block = kwargs.get('block', 1)
        self.light = kwargs.get('light', False)
        if self.light:
            prob = kwargs.get('prob', .15)
            dark = kwargs.get('dark', .15)
            self.fraction = kwargs.get('fraction', 0.2)
            self.vert = kwargs.get('vert_exag', 2.)
            self.blend = kwargs.get('blend_mode', 'soft')
            self.fraction = kwargs.get('fraction', .5)
            self.light_source = LightSource()
        else:
            prob = kwargs.get('prob', .2)
            dark = kwargs.get('dark', .02)
        if style == 'hash':
            prob /= 4.
            self.choice = [1. - dark, 1.]
            self.p = [prob, 1. - prob]
        elif style == 'hash2':
            # hash2 spreads out points somewhat evenly, but random within
            # 3x3 blocks. Up to 2 points are chosen per block.
            # Set up arrays and their probabilities
            self.p = 9 * [1./11] + [2./11]  # 2 chances to get blank
            self.choice = list(range(9)) + [-1]
            blank = np.ones((3,3))
            self.template = {-1: blank.copy()}
            blank[0, 0] = 1. - dark
            for i in range(9):
                    self.template[i] = blank
                    blank = np.roll(blank, 1)
        else:
            self.choice = list(1. - np.array([1,2,3]) * dark) + [1.]
            self.p = 3 * [prob] + [1. - 3 * prob]
        self.kwargs = kwargs

    def __call__(self, im, dpi=100):
        if self.style == 'noise': return self._noise(im), 0, 0
        if self.style == 'hash': return self._hash(im), 0, 0
        if self.style == 'hash2': return self._hash2(im), 0, 0
        return im, 0, 0  # Do nothing if style not found

    def _expand(self, small, large):
        """Expand small 2D array into large 2D array. Clipping not supported.
            small : 2D np.array
            large : 2D np.array must be n-times larger than small
            Note: Make sure to only supply 2D arrays, not 3D, ie
            self._expand(small, large[:, :, 0]) if necessary.
        """
        n = self.block
        if n == 1:
            large[...] = small
            return
        nx, ny = large.shape
        dx = nx % n
        dy = ny % n
        for a in range(n):
            for b in range(n):
                large[a:nx-dx:n, b:ny-dy:n] = small

    def _combine(self, rgb, clip):  # return new array with rgb and clip
        nx, ny = clip.shape
        tgt = np.empty((nx, ny, 4))
        tgt[..., :3] = rgb
        tgt[..., 3] = clip
        return tgt

    def _light(self, rgb, elevation):
        """Shade the supplied rgb array with the 2D elevation array.
            Note: elevation must be 2D, ie use noise[:, :, 0] if necessary.
        """
        rgb2 = self.light_source.shade_rgb(rgb, elevation,
                                           blend_mode=self.blend,
                                           fraction=self.fraction,
                                           vert_exag=self.vert)
        return rgb2

    def _noise(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        half = rnd.choice(self.choice, shape, p=self.p)  # (nx, ny)
        noise = np.ones((nx, ny, 1))  # (nx, ny, 1)
        self._expand(half, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

    def _hash(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        noise = np.ones((nx, ny, 1))
        buffer = np.ones(shape)
        for axis in [0, 1]:
            for dtn in [-1, 1]:
                small = rnd.choice(self.choice, shape, p=self.p)
                buffer *= small
                s2 = small * small
                buffer *= np.roll(s2, dtn, axis)
                buffer *= np.roll(s2 * small, 2 * dtn, axis)
        np.clip(buffer, self.choice[0]**3, 1, buffer)
        self._expand(buffer, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

    def _hash2(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        small = {}
        for dtn in [-1, 1]:
            for axis in [0, 1]:
                small[(dtn, axis)] = np.ones(shape)
        keys = list(small.keys())
        self.keys = keys #test
        self.small = small #test
        for x in range(nx//n-3):
            for y in range(ny//n-3):
                # Pick two each of direction buffers and templates
                # can't choose tuples directly, so use index to keys list
                k = rnd.choice(len(keys), 2, replace=False)
                t = rnd.choice(self.choice, 2, replace=False, p=self.p)
                self.k = k #test
                self.t = t #test
                for i in range(2):
                    b = small[keys[k[i]]]
                    b[x:x+3, y:y+3] *= self.template[t[i]]
        buffer = np.ones(shape)
        for dtn in [-1, 1]:
            for axis in [0, 1]:
                s = small[(dtn, axis)]
                s2 = s * s
                buffer *= s
                buffer *= np.roll(s2, dtn, axis)
                buffer *= np.roll(s2 * s, 2 * dtn, axis)
        noise = np.ones((nx, ny, 1))
        self._expand(buffer, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

def test(style, **kwargs):
    global filt
    filt = Texture(style=style, **kwargs)
    im = np.ones((20,20,4))
    res, a, b = filt.__call__(im)

def texture_pie(ax):
    tf = []
    tf.append(Texture(style='noise', block=2))
    tf.append(Texture(style='noise', block=8))
    tf.append(Texture(style='noise', light=True, block=2))
    tf.append(Texture(style='noise', light=True, block=6))
    tf.append(Texture(style='hash2', light=False, block=3))
    tf.append(Texture(style='hash2', light=True, block=6))
    labels = []
    labels.append('Fine Noise')
    labels.append('Coarse Noise')
    labels.append('Shaded Noise')
    labels.append('Shaded\nCoarse Noise')
    labels.append('Fine Hash')
    labels.append('Shaded\nCoarse Hash')

    fracs = len(tf) * [10]
    explode = tuple([0.05] + (len(tf) - 1) * [0])
    pies = ax.pie(fracs, explode=explode, labels=labels, labeldistance=0.7)

    for pie, texture_filter in zip(pies[0], tf):
        pie.set_agg_filter(texture_filter)
        pie.set_rasterized(True)  # to support mixed-mode renderers
        pie.set(ec="none", lw=2)

if __name__=='__main__':
    test('hash2')
#    fig = plt.figure(figsize=(8,8))
#    fig.clear()
#    plt.subplots_adjust(left=0.05, right=0.95)
#
#    ax = fig.add_subplot(111)
#    ax.set_aspect(1)
#    texture_pie(ax)
#    ax.set_frame_on(True)
#
#    plt.show()<commit_msg>Tested version of _hash2<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 13 17:33:27 2018

@author: dan
"""

import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
from matplotlib.colors import LightSource

class Texture(object):
    "simple texture filter"

    def __init__(self, style='noise', **kwargs):
        self.style = style
        self.block = kwargs.get('block', 1)
        self.light = kwargs.get('light', False)
        if self.light:
            prob = kwargs.get('prob', .15)
            dark = kwargs.get('dark', .15)
            self.fraction = kwargs.get('fraction', 0.2)
            self.vert = kwargs.get('vert_exag', 2.)
            self.blend = kwargs.get('blend_mode', 'soft')
            self.fraction = kwargs.get('fraction', .5)
            self.light_source = LightSource()
        else:
            prob = kwargs.get('prob', .2)
            dark = kwargs.get('dark', .02)
        if style == 'hash':
            prob /= 4.
            self.choice = [1. - dark, 1.]
            self.p = [prob, 1. - prob]
        elif style == 'hash2':
            # hash2 spreads out points somewhat evenly, but random within
            # 3x3 blocks. Up to 2 points are chosen per block.
            # Set up arrays and their probabilities
            self.p = 9 * [1./11] + [2./11]  # 2 chances to get blank
            self.choice = list(range(9)) + [-1]
            self.clip = (1. - dark)**3  # clip limit (max darkness)
            blank = np.ones((3,3))
            self.template = {-1: blank.copy()}
            blank[0, 0] = 1. - dark
            for i in range(9):
                    self.template[i] = blank
                    blank = np.roll(blank, 1)
        else:
            self.choice = list(1. - np.array([1,2,3]) * dark) + [1.]
            self.p = 3 * [prob] + [1. - 3 * prob]
        self.kwargs = kwargs

    def __call__(self, im, dpi=100):
        if self.style == 'noise': return self._noise(im), 0, 0
        if self.style == 'hash': return self._hash(im), 0, 0
        if self.style == 'hash2': return self._hash2(im), 0, 0
        return im, 0, 0  # Do nothing if style not found

    def _expand(self, small, large):
        """Expand small 2D array into large 2D array. Clipping not supported.
            small : 2D np.array
            large : 2D np.array must be n-times larger than small
            Note: Make sure to only supply 2D arrays, not 3D, ie
            self._expand(small, large[:, :, 0]) if necessary.
        """
        n = self.block
        if n == 1:
            large[...] = small
            return
        nx, ny = large.shape
        dx = nx % n
        dy = ny % n
        for a in range(n):
            for b in range(n):
                large[a:nx-dx:n, b:ny-dy:n] = small

    def _combine(self, rgb, clip):  # return new array with rgb and clip
        nx, ny = clip.shape
        tgt = np.empty((nx, ny, 4))
        tgt[..., :3] = rgb
        tgt[..., 3] = clip
        return tgt

    def _light(self, rgb, elevation):
        """Shade the supplied rgb array with the 2D elevation array.
            Note: elevation must be 2D, ie use noise[:, :, 0] if necessary.
        """
        rgb2 = self.light_source.shade_rgb(rgb, elevation,
                                           blend_mode=self.blend,
                                           fraction=self.fraction,
                                           vert_exag=self.vert)
        return rgb2

    def _noise(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        half = rnd.choice(self.choice, shape, p=self.p)  # (nx, ny)
        noise = np.ones((nx, ny, 1))  # (nx, ny, 1)
        self._expand(half, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

    def _hash(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        noise = np.ones((nx, ny, 1))
        buffer = np.ones(shape)
        for axis in [0, 1]:
            for dtn in [-1, 1]:
                small = rnd.choice(self.choice, shape, p=self.p)
                buffer *= small
                s2 = small * small
                buffer *= np.roll(s2, dtn, axis)
                buffer *= np.roll(s2 * small, 2 * dtn, axis)
        np.clip(buffer, self.clip, 1, buffer)
        self._expand(buffer, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

    def _hash2(self, im):
        n = self.block
        rgb = im[...,:3]  # (nx, ny, 3)
        clip = im[...,3]   # (nx, ny)
        nx, ny = clip.shape
        shape = (nx//n, ny//n)
        small = {}
        for dtn in [-1, 1]:
            for axis in [0, 1]:
                small[(dtn, axis)] = np.ones(shape)
        keys = list(small.keys())
        self.keys = keys #test
        self.small = small #test
        for x in range(nx//n-3):
            for y in range(ny//n-3):
                # Pick two each of direction buffers and templates
                # can't choose tuples directly, so use index to keys list
                k = rnd.choice(len(keys), 2, replace=False)
                t = rnd.choice(self.choice, 2, replace=False, p=self.p)
                self.k = k #test
                self.t = t #test
                for i in range(2):
                    b = small[keys[k[i]]]
                    b[x:x+3, y:y+3] *= self.template[t[i]]
        buffer = np.ones(shape)
        for dtn in [-1, 1]:
            for axis in [0, 1]:
                s = small[(dtn, axis)]
                s2 = s * s
                buffer *= s
                buffer *= np.roll(s2, dtn, axis)
                buffer *= np.roll(s2 * s, 2 * dtn, axis)
        np.clip(buffer, self.choice[0]**3, 1, buffer)
        noise = np.ones((nx, ny, 1))
        self._expand(buffer, noise[..., 0])
        if self.light:
            rgb = self._light(rgb, noise[..., 0])
        else:
            rgb *= noise  # (nx, ny, 3) = (nx, ny, 3) * (nx, ny, 1)
        return self._combine(rgb, clip)

def test(style, **kwargs):
    global filt
    filt = Texture(style=style, **kwargs)
    im = np.ones((20,20,4))
    res, a, b = filt.__call__(im)

def texture_pie(ax):
    tf = []
    tf.append(Texture(style='noise', block=2))
    tf.append(Texture(style='noise', block=8))
    tf.append(Texture(style='noise', light=True, block=2))
    tf.append(Texture(style='noise', light=True, block=6))
    tf.append(Texture(style='hash2', light=False, block=3))
    tf.append(Texture(style='hash2', light=True, block=6))
    labels = []
    labels.append('Fine Noise')
    labels.append('Coarse Noise')
    labels.append('Shaded Noise')
    labels.append('Shaded\nCoarse Noise')
    labels.append('Fine Hash')
    labels.append('Shaded\nCoarse Hash')

    fracs = len(tf) * [10]
    explode = tuple([0.05] + (len(tf) - 1) * [0])
    pies = ax.pie(fracs, explode=explode, labels=labels, labeldistance=0.7)

    for pie, texture_filter in zip(pies[0], tf):
        pie.set_agg_filter(texture_filter)
        pie.set_rasterized(True)  # to support mixed-mode renderers
        pie.set(ec="none", lw=2)

if __name__=='__main__':
#    test('hash2')
    fig = plt.figure(figsize=(8,8))
    fig.clear()
    plt.subplots_adjust(left=0.05, right=0.95)

    ax = fig.add_subplot(111)
    ax.set_aspect(1)
    texture_pie(ax)
    ax.set_frame_on(True)

    plt.show()<|endoftext|>


<commit_before>#Copyright (C) 2017  Oscar Triano 'dotoscat' <dotoscat (at) gmail (dot) com>

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero 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 Affero General Public License for more details.

#You should have received a copy of the GNU Affero General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

from .constant import SIZE

basic = [
    "............____................",
    "................................",
    ".....................____.......",
    "................................",
    ".....____.......................",
    "................................",
    "..________________________......",
    "................................",
    "................................",
]

def load_level(level, pool):
    x = 0.
    y = 0.
    #  pool.free_all()
    for line in reversed(level):
        x = 0.
        for tile in line:
            print(tile, end='')
            if tile == '_':
                platform = pool.get()
                collision_attrs = {
                    "x": x,
                    "y": y,
                    "width": SIZE,
                    "height": SIZE/4.
                }
                print(collision_attrs)
                platform.set("body", x=x, y=y)
                platform.set("collision", **collision_attrs)
                platform.set("platform", **collision_attrs)
            x += SIZE
        print()
        y += SIZE
<commit_msg>Elevar un poco la plataforma<commit_after>#Copyright (C) 2017  Oscar Triano 'dotoscat' <dotoscat (at) gmail (dot) com>

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero 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 Affero General Public License for more details.

#You should have received a copy of the GNU Affero General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

from .constant import SIZE

basic = [
    "............____................",
    "................................",
    ".....................____.......",
    "................................",
    ".....____.......................",
    "................................",
    "..________________________......",
    "................................",
    "................................",
    "................................",
]

def load_level(level, pool):
    x = 0.
    y = 0.
    #  pool.free_all()
    for line in reversed(level):
        x = 0.
        for tile in line:
            print(tile, end='')
            if tile == '_':
                platform = pool.get()
                collision_attrs = {
                    "x": x,
                    "y": y,
                    "width": SIZE,
                    "height": SIZE/4.
                }
                print(collision_attrs)
                platform.set("body", x=x, y=y)
                platform.set("collision", **collision_attrs)
                platform.set("platform", **collision_attrs)
            x += SIZE
        print()
        y += SIZE
<|endoftext|>


<commit_before>__author__ = 'holzi'
from MCP23017 import MCP23017

Chip2 = MCP23017(0x21)

Chip2.initDevice()
status = Chip2.set_io_direction_port_a(0x00)   #PortA is completeley Output
print(status)
#Do a write check
status = Chip2.write_byte_port_a(0x0A)
print(status)

if Chip2.read_byte_port_a() == 0x0A:
    print("PASS")
else:
    print("FAIL")
<commit_msg>0 = true in python<commit_after>__author__ = 'holzi'
from MCP23017 import MCP23017

Chip2 = MCP23017(0x21)

Chip2.initDevice()
status = Chip2.set_io_direction_port_a(0x00)   #PortA is completeley Output
print(status)
#Do a write check
status = Chip2.write_byte_port_a(0x0A)
print(status)

if Chip2.read_byte_port_a() == 0x0A:
    print("PASS")
else:
    print("FAIL ")
<|endoftext|>


<commit_before>import json
import leveldb
import cPickle as pickle

from configdb import exceptions
from configdb.db import schema
from configdb.db.interface import base
from configdb.db.interface import inmemory_interface

class LevelDbSession(object):
    """This 'session' does not provide transaction support, only
    request batching."""

    def __init__(self, db):
        self._db = db
        self._batch = leveldb.WriteBatch()

    def _key_for_obj(self, obj):
        return self._db._key(obj._entity_name, obj.name)

    def add(self, obj):
        self._batch.Put(self._key_for_obj(obj),
                        self._db._serialize(obj))

    def delete(self, obj):
        self._batch.Delete(self._key_for_obj(obj))

    def commit(self):
        self._db.db.Write(self._batch, sync=True)

    def rollback(self):
        if hasattr(self, '_batch'):
            del self._batch

class LevelDbInterface(base.DbInterface):
    """Interface to a local LevelDB database.

    The interface is pretty simple at the moment, but it's a good
    example of how to implement a database backend for configdb.

    We store lightweight InMemoryObject instances in the database,
    representing relations with sets of names.  Object serialization
    is done using the 'pickle' module.
    """

    def __init__(self, path, schema, **kwargs):
        self.db = leveldb.LevelDB(path, **kwargs)
        self.schema = schema

    def _key(self, entity_name, object_name):
        return '%s:%s' % (entity_name, object_name)

    def _serialize(self, obj):
        return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)

    def _deserialize(self, data):
        return pickle.loads(data)

    def session(self):
        return base.session_context_manager(LevelDbSession(self))

    def get_by_name(self, entity_name, object_name, session):
        try:
            return self._deserialize(
                self.db.Get(self._key(entity_name, object_name)))
        except KeyError:
            return None

    def _find_all(self, entity_name):
        cursor = self.db.RangeIter(u'%s:' % entity_name,
                                   u'%s:\xff' % entity_name)
        for key, serialized_data in cursor:
            yield self._deserialize(serialized_data)

    def find(self, entity_name, query, session):
        entity = self.schema.get_entity(entity_name)
        return self._run_query(entity, query,
                               self._find_all(entity_name))

    def create(self, entity_name, attrs, session):
        entity = self.schema.get_entity(entity_name)
        obj = inmemory_interface.InMemoryObject(entity, attrs)
        session.add(obj)
        return obj

    def delete(self, entity_name, object_name, session):
        session.delete(self.get_by_name(entity_name, object_name, session))
<commit_msg>Final fix for issue12<commit_after>import json
import leveldb
import cPickle as pickle

from configdb import exceptions
from configdb.db import schema
from configdb.db.interface import base
from configdb.db.interface import inmemory_interface

class LevelDbSession(object):
    """This 'session' does not provide transaction support, only
    request batching."""

    def __init__(self, db):
        self._db = db
        self._batch = leveldb.WriteBatch()

    def _key_for_obj(self, obj):
        return self._db._key(obj._entity_name, obj.name)

    def add(self, obj):
        self._batch.Put(self._key_for_obj(obj),
                        self._db._serialize(obj))

    def delete(self, obj):
        self._batch.Delete(self._key_for_obj(obj))

    def commit(self):
        self._db.db.Write(self._batch, sync=True)

    def rollback(self):
        if hasattr(self, '_batch'):
            del self._batch

class LevelDbInterface(base.DbInterface):
    """Interface to a local LevelDB database.

    The interface is pretty simple at the moment, but it's a good
    example of how to implement a database backend for configdb.

    We store lightweight InMemoryObject instances in the database,
    representing relations with sets of names.  Object serialization
    is done using the 'pickle' module.
    """

    def __init__(self, path, schema, **kwargs):
        self.db = leveldb.LevelDB(path, **kwargs)
        self.schema = schema

    def _key(self, entity_name, object_name):
        return '%s:%s' % (entity_name, object_name)

    def _serialize(self, obj):
        return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)

    def _deserialize(self, data):
        return pickle.loads(data)

    def session(self):
        return base.session_context_manager(LevelDbSession(self))

    def get_by_name(self, entity_name, object_name, session):
        try:
            return self._deserialize(
                self.db.Get(self._key(entity_name, object_name)))
        except KeyError:
            return None

    def _find_all(self, entity_name):
        final = entity_name.encode('utf-8') + '\xff'
        cursor = self.db.RangeIter(u'%s:' % entity_name, final)
        for key, serialized_data in cursor:
            yield self._deserialize(serialized_data)

    def find(self, entity_name, query, session):
        entity = self.schema.get_entity(entity_name)
        return self._run_query(entity, query,
                               self._find_all(entity_name))

    def create(self, entity_name, attrs, session):
        entity = self.schema.get_entity(entity_name)
        obj = inmemory_interface.InMemoryObject(entity, attrs)
        session.add(obj)
        return obj

    def delete(self, entity_name, object_name, session):
        session.delete(self.get_by_name(entity_name, object_name, session))
<|endoftext|>


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

import string
import os
import sys
import json
import fontforge
import psMat

PUA_START = 0xE000
PUA_END = 0xF8FF
FONT_EM = 1024
POWERLINE_START = 0xE0A0
POWERLINE_END = 0xE0D5

def read_map_names(filename):
    array = []
    with open(filename) as file_map:
        lines = file_map.readlines()
        lines = [x.strip() for x in lines]
        for line in lines:
            if len(line) == 0:
                continue
            tab = line.split()
            if tab[0][0] == '@':
                array.append((tab[0][1:], ord(tab[1][0])))
            else:
                array.append((tab[0], int(tab[1], 16)))
    return array

def lookup_map_name(map_names, codepoint, fallback_name):
    for name, code in map_names:
        if code == codepoint:
            return name
    return fallback_name

# Insert the powerline glyphs at the same place that all the patched powerline fonts to make
# our font compatible with most of plugins/modules that insert those glyphs
def insert_powerline_extra(dest):
    codepoint = POWERLINE_START
    font = fontforge.open("./fonts/PowerlineExtraSymbols.otf")
    font.em = FONT_EM
    map_names = read_map_names("./fonts/PowerlineExtraSymbols-map")
    excludes = [ 0xE0A4, 0xE0A5, 0xE0A6, 0xE0A7, 0xE0A8, 0xE0A9, 0xE0AA, 0xE0AB,
                 0xE0AC, 0xE0AD, 0xE0AE, 0xE0AF, 0xE0C9, 0xE0CB, 0xE0D3 ]
    inserted = []

    while codepoint < POWERLINE_END:
        if codepoint in excludes:
            codepoint += 1
            continue
        font.selection.select(codepoint)
        font.copy()
        dest.selection.select(codepoint)
        dest.paste()
        inserted.append(codepoint)
        codepoint += 1
    print("#powerline-extras:" + str(len(inserted)))
    for x in inserted:
        number = hex(x).replace("0x", "")
        name = lookup_map_name(map_names, x, number)
        print("powerline_" + name + ":" + number, end=';')
    print("")

# Return true if the format of the name is something like 'uniXXXX' where X are
# hexadecimals
def is_default_name(name):
    if (len(name) != 7 or
        not name.startswith("uni") or
        not all(c in string.hexdigits for c in name[-4:])):
        return False
    return True

# Name the glyph according to the font name
def make_name(name, name_font):
    name = name.lower()
    if is_default_name(name):
        return name_font + "_" + name[-4:]
    return name_font + "_" + name.replace("-", "_")

if len(sys.argv) < 2:
    print("Give me a config file", file=sys.stderr)
    sys.exit(1)

with open(sys.argv[1]) as config_file:
    config_data = json.load(config_file)

    dest = fontforge.font()
    dest.em = FONT_EM
#    dest.encoding = "UnicodeFull"
    dest.encoding = "ISO10646"

    insert_powerline_extra(dest)

    codepoint = PUA_START

    for json_file in config_data:

        font = fontforge.open(json_file["path"])
        font.em = FONT_EM

        excludes = []
        if "excludes" in json_file:
            excludes = list(map(lambda x : int(x, 16), json_file["excludes"]))

        start_from = 0
        if "start-from" in json_file:
            start_from = int(json_file["start-from"], 16)

        until = -1
        if "until" in json_file:
            until = int(json_file["until"], 16)

        move_vertically = 0
        if "move-vertically" in json_file:
            move_vertically = int(json_file["move-vertically"])

        name_font = json_file["name"]
        if "short-name" in json_file:
            name_font = json_file["short-name"]
        name_font = name_font.replace("-", "_")

        map_names = []
        if "map-names" in json_file:
            map_names = read_map_names(json_file["map-names"])

        start = codepoint
        inserted = []

        for symbol in font.glyphs("encoding"):
            if codepoint == POWERLINE_START:
                codepoint = POWERLINE_END
            if (symbol.encoding in excludes or
                symbol.encoding < start_from or
                (until > 0 and symbol.encoding >= until)):
                continue
            if symbol.width > 0 and symbol.unicode > 0:
                encoding = symbol.encoding
                name = symbol.glyphname
                font.selection.select(encoding)
                font.copy()
                dest.selection.select(codepoint)
                dest.paste()
                dest.transform(psMat.translate(0, move_vertically))
                if len(map_names) > 0:
                    name = lookup_map_name(map_names, encoding, name)
                new_name = make_name(name, name_font)
                dest.createMappedChar(codepoint).glyphname = new_name
                inserted.append((new_name ,codepoint))
                codepoint += 1

        print("#" + json_file["name"] + ":" + str(len(inserted)))
        for (name, x) in inserted:
            print(name + ":" + str(hex(x)).replace("0x", ""), end=';')
        print("")

    dest.em = FONT_EM
    dest.fontname = "icons-in-terminal"
    dest.familyname = "icons-in-terminal"
    dest.fullname = "icons-in-terminal"
    dest.appendSFNTName('English (US)', 'Preferred Family', dest.familyname)
    dest.appendSFNTName('English (US)', 'Compatible Full', dest.fullname)
    dest.fontname= "icons-in-terminal"
    dest.generate("icons-in-terminal.ttf")
    sys.exit(0)

sys.exit(1)
<commit_msg>Remove interlines<commit_after>#!/usr/bin/env python3

import string
import os
import sys
import json
import fontforge
import psMat

PUA_START = 0xE000
PUA_END = 0xF8FF
FONT_EM = 1024
POWERLINE_START = 0xE0A0
POWERLINE_END = 0xE0D5

def read_map_names(filename):
    array = []
    with open(filename) as file_map:
        lines = file_map.readlines()
        lines = [x.strip() for x in lines]
        for line in lines:
            if len(line) == 0:
                continue
            tab = line.split()
            if tab[0][0] == '@':
                array.append((tab[0][1:], ord(tab[1][0])))
            else:
                array.append((tab[0], int(tab[1], 16)))
    return array

def lookup_map_name(map_names, codepoint, fallback_name):
    for name, code in map_names:
        if code == codepoint:
            return name
    return fallback_name

# Insert the powerline glyphs at the same place that all the patched powerline fonts to make
# our font compatible with most of plugins/modules that insert those glyphs
def insert_powerline_extra(dest):
    codepoint = POWERLINE_START
    font = fontforge.open("./fonts/PowerlineExtraSymbols.otf")
    font.em = FONT_EM
    map_names = read_map_names("./fonts/PowerlineExtraSymbols-map")
    excludes = [ 0xE0A4, 0xE0A5, 0xE0A6, 0xE0A7, 0xE0A8, 0xE0A9, 0xE0AA, 0xE0AB,
                 0xE0AC, 0xE0AD, 0xE0AE, 0xE0AF, 0xE0C9, 0xE0CB, 0xE0D3 ]
    inserted = []

    while codepoint < POWERLINE_END:
        if codepoint in excludes:
            codepoint += 1
            continue
        font.selection.select(codepoint)
        font.copy()
        dest.selection.select(codepoint)
        dest.paste()
        inserted.append(codepoint)
        codepoint += 1
    print("#powerline-extras:" + str(len(inserted)))
    for x in inserted:
        number = hex(x).replace("0x", "")
        name = lookup_map_name(map_names, x, number)
        print("powerline_" + name + ":" + number, end=';')
    print("")

# Return true if the format of the name is something like 'uniXXXX' where X are
# hexadecimals
def is_default_name(name):
    if (len(name) != 7 or
        not name.startswith("uni") or
        not all(c in string.hexdigits for c in name[-4:])):
        return False
    return True

# Name the glyph according to the font name
def make_name(name, name_font):
    name = name.lower()
    if is_default_name(name):
        return name_font + "_" + name[-4:]
    return name_font + "_" + name.replace("-", "_")

if len(sys.argv) < 2:
    print("Give me a config file", file=sys.stderr)
    sys.exit(1)

with open(sys.argv[1]) as config_file:
    config_data = json.load(config_file)

    dest = fontforge.font()
    dest.em = FONT_EM
#    dest.encoding = "UnicodeFull"
    dest.encoding = "ISO10646"

    insert_powerline_extra(dest)

    codepoint = PUA_START

    for json_file in config_data:

        font = fontforge.open(json_file["path"])
        font.em = FONT_EM

        excludes = []
        if "excludes" in json_file:
            excludes = list(map(lambda x : int(x, 16), json_file["excludes"]))

        start_from = 0
        if "start-from" in json_file:
            start_from = int(json_file["start-from"], 16)

        until = -1
        if "until" in json_file:
            until = int(json_file["until"], 16)

        move_vertically = 0
        if "move-vertically" in json_file:
            move_vertically = int(json_file["move-vertically"])

        name_font = json_file["name"]
        if "short-name" in json_file:
            name_font = json_file["short-name"]
        name_font = name_font.replace("-", "_")

        map_names = []
        if "map-names" in json_file:
            map_names = read_map_names(json_file["map-names"])

        start = codepoint
        inserted = []

        for symbol in font.glyphs("encoding"):
            if codepoint == POWERLINE_START:
                codepoint = POWERLINE_END
            if (symbol.encoding in excludes or
                symbol.encoding < start_from or
                (until > 0 and symbol.encoding >= until)):
                continue
            if symbol.width > 0 and symbol.unicode > 0:
                encoding = symbol.encoding
                name = symbol.glyphname
                font.selection.select(encoding)
                font.copy()
                if encoding == 0x20:
                    dest.selection.select(0x20)
                    dest.paste()
                    continue
                dest.selection.select(codepoint)
                dest.paste()
                dest.transform(psMat.translate(0, move_vertically))
                if len(map_names) > 0:
                    name = lookup_map_name(map_names, encoding, name)
                new_name = make_name(name, name_font)
                dest.createMappedChar(codepoint).glyphname = new_name
                inserted.append((new_name ,codepoint))
                codepoint += 1

        print("#" + json_file["name"] + ":" + str(len(inserted)))
        for (name, x) in inserted:
            print(name + ":" + str(hex(x)).replace("0x", ""), end=';')
        print("")

    ascent = dest.ascent
    descent = dest.descent

    dest.os2_winascent_add = 0
    dest.os2_windescent_add = 0
    dest.os2_typoascent_add = 0
    dest.os2_typodescent_add = 0
    dest.hhea_ascent_add = 0
    dest.hhea_descent_add = 0

    # print ("ASCENT: " + str(ascent))
    # print ("DESCENT: " + str(descent))

    dest.os2_winascent = ascent
    dest.os2_windescent = descent
    dest.os2_typoascent = ascent
    dest.os2_typodescent = -descent
    dest.hhea_ascent = ascent
    dest.hhea_descent = -descent

    dest.em = FONT_EM
    dest.fontname = "icons-in-terminal"
    dest.familyname = "icons-in-terminal"
    dest.fullname = "icons-in-terminal"
    dest.appendSFNTName('English (US)', 'Preferred Family', dest.familyname)
    dest.appendSFNTName('English (US)', 'Compatible Full', dest.fullname)
    dest.fontname= "icons-in-terminal"
    dest.generate("icons-in-terminal.ttf")
    sys.exit(0)

sys.exit(1)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Ultros documentation build configuration file, created by
# sphinx-quickstart on Sat Jul  2 11:34:37 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

print("===")
print("Path: {}".format(os.getcwd()))
print("===")
sys.path.insert(0, os.path.abspath('../../src/'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx_autodoc_typehints',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.viewcode',
    'sphinxcontrib.asyncio',
]

# Boolean indicating whether to scan all found documents for autosummary
# directives, and to generate stub pages for each.
autosummary_generate = True

autoclass_content = 'both'  # include both class docstring and __init__
autodoc_default_flags = [
    # Make sure that any autodoc declarations show the right members
    'members',
    'private-members',
    'special-members',
    'show-inheritance',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'Ultros (Core)'
copyright = '2016, Gareth Coles & Sean Gordon'
author = 'Gareth Coles & Sean Gordon'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.0.0'
# The full version, including alpha/beta/rc tags.
release = version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_templates']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'colorful'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'Ultros v2.0.0'

# A shorter title for the navigation bar.  Default is the same as html_title.
#
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = "logo.png"

# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or
# 32x32 pixels large.
#
html_favicon = "favicon.ico"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}

# If false, no module index is generated.
#
# html_domain_indices = True

# If false, no index is generated.
#
# html_use_index = True

# If true, the index is split into individual pages for each letter.
#
# html_split_index = False

# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True

# If set, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'Ultrosdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
     # The paper size ('letterpaper' or 'a4paper').
     #
     # 'papersize': 'letterpaper',

     # The font size ('10pt', '11pt' or '12pt').
     #
     # 'pointsize': '10pt',

     # Additional stuff for the LaTeX preamble.
     #
     # 'preamble': '',

     # Latex figure (float) alignment
     #
     # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'Ultros.tex', 'Ultros (Core) Documentation',
     'Gareth Coles & Sean Gordon', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False

# If true, show page references after internal links.
#
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
#
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
#
# latex_appendices = []

# If false, no module index is generated.
#
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'ultros', 'Ultros (Core) Documentation',
     [author], 1)
]

# If true, show URL addresses after external links.
#
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Ultros', 'Ultros (Core) Documentation',
     author, 'Ultros', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []

# If false, no module index is generated.
#
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright

# The basename for the epub file. It defaults to the project name.
# epub_basename = project

# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#
# epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#
# epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
#
# epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#
# epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_pre_files = []

# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
#
# epub_tocdepth = 3

# Allow duplicate toc entries.
#
# epub_tocdup = True

# Choose between 'default' and 'includehidden'.
#
# epub_tocscope = 'default'

# Fix unsupported image types using the Pillow.
#
# epub_fix_images = False

# Scale large images.
#
# epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# epub_show_urls = 'inline'

# If false, no index is generated.
#
# epub_use_index = True
<commit_msg>Document undocumented members as well<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Ultros documentation build configuration file, created by
# sphinx-quickstart on Sat Jul  2 11:34:37 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

print("===")
print("Path: {}".format(os.getcwd()))
print("===")
sys.path.insert(0, os.path.abspath('../../src/'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx_autodoc_typehints',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.viewcode',
    'sphinxcontrib.asyncio',
]

# Boolean indicating whether to scan all found documents for autosummary
# directives, and to generate stub pages for each.
autosummary_generate = True

autoclass_content = 'both'  # include both class docstring and __init__
autodoc_default_flags = [
    # Make sure that any autodoc declarations show the right members
    'members',
    'undoc-members',
    'private-members',
    'special-members',
    'show-inheritance',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'Ultros (Core)'
copyright = '2016, Gareth Coles & Sean Gordon'
author = 'Gareth Coles & Sean Gordon'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.0.0'
# The full version, including alpha/beta/rc tags.
release = version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_templates']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'colorful'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = 'Ultros v2.0.0'

# A shorter title for the navigation bar.  Default is the same as html_title.
#
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = "logo.png"

# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or
# 32x32 pixels large.
#
html_favicon = "favicon.ico"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}

# If false, no module index is generated.
#
# html_domain_indices = True

# If false, no index is generated.
#
# html_use_index = True

# If true, the index is split into individual pages for each letter.
#
# html_split_index = False

# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True

# If set, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#
html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'Ultrosdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
     # The paper size ('letterpaper' or 'a4paper').
     #
     # 'papersize': 'letterpaper',

     # The font size ('10pt', '11pt' or '12pt').
     #
     # 'pointsize': '10pt',

     # Additional stuff for the LaTeX preamble.
     #
     # 'preamble': '',

     # Latex figure (float) alignment
     #
     # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'Ultros.tex', 'Ultros (Core) Documentation',
     'Gareth Coles & Sean Gordon', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False

# If true, show page references after internal links.
#
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
#
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
#
# latex_appendices = []

# If false, no module index is generated.
#
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'ultros', 'Ultros (Core) Documentation',
     [author], 1)
]

# If true, show URL addresses after external links.
#
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'Ultros', 'Ultros (Core) Documentation',
     author, 'Ultros', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []

# If false, no module index is generated.
#
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False

# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright

# The basename for the epub file. It defaults to the project name.
# epub_basename = project

# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#
# epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#
# epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
#
# epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#
# epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_pre_files = []

# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#
# epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
#
# epub_tocdepth = 3

# Allow duplicate toc entries.
#
# epub_tocdup = True

# Choose between 'default' and 'includehidden'.
#
# epub_tocscope = 'default'

# Fix unsupported image types using the Pillow.
#
# epub_fix_images = False

# Scale large images.
#
# epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# epub_show_urls = 'inline'

# If false, no index is generated.
#
# epub_use_index = True
<|endoftext|>


<commit_before><commit_msg>Arch: Fixed orientation of CTH profile<commit_after><|endoftext|>