<commit_before># -*- coding: utf-8 -*-

#
# Copyright (c) 2011-2015 Genestack Limited
# All Rights Reserved
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF GENESTACK LIMITED
# The copyright notice above does not evidence any
# actual or intended publication of such source code.
#

from Connection import Application

CALCULATE_CHECKSUMS = 'markKeyForCountChecksum'

class CLApplication(Application):
    """
    Base class to interact with CommandLine Applications.
    Application_ID is required you can pass it as init argument or overwrite it in children.
    Source files and params depends on application.

    """
    APPLICATION_ID = None

    def __repr__(self):
        return self.APPLICATION_ID

    def create_file(self, source_files, name=None, params=None, calculate_checksums=False, expected_checksums=None,
                    initialize=False):
        """
        Creates application native file and returns its accession.
        If source file is not found or is not of source file type, the corresponding exceptions are thrown.

        :param source_files: list of source file accessions
        :type source_files: list
        :param name: if name is specified created file will be renamed
        :type name: str
        :param params: is command arguments to be set, if None then arguments stay default.
        :param params: list
        :param calculate_checksums: flag that used in initialization script to count checsums of created files
        :type calculate_checksums: bool
        :param expected_checksums: List of expected checksums in any order
        :type expected_checksums: list
        :param initialize: flag if initialization should be started immediately
        :return: accession of created file
        :rtype: str
        """
        app_file = self.__create_file(source_files, params)

        if name:
            self.rename_file(app_file, name)

        if calculate_checksums:
            self.mark_for_tests(app_file)

        if expected_checksums:
            self.add_checksums(app_file, expected_checksums)

        if initialize:
            self.start(app_file)
        return app_file

    def mark_for_tests(self, app_file):
        """
        Mark file for test via add corresponding key to the metainfo.
        Test file will calculate md5 checksums for processed files stored in the storage during initialization.

        :param app_file: accession of file
        :return: None
        """
        self.connection.application('genestack/bio-test-cla').invoke(
            '%s' % CALCULATE_CHECKSUMS, app_file
        )

    def add_checksums(self, app_file, expected_checksums_set):
        """
        Add expected md5 checksum to the metainfo.
        Expected checksums calculated in the next way:
          - number of checksums is same as number of entries in the storage.
          - order of the checksums does not matter.
          For example Reference Genome have 2 entries (annotation and fasta files).

          If there are multiple files in one entry it will concatenate them in order as they were PUT to storage
          by the initialization script.
          If file marked for test then after initialization metainfo will have both expected and actual checksums.

        :param app_file: accession of application file
        :param expected_checksums_set: collection of md5 checksums
        :return: None
        """
        self.connection.application('genestack/bio-test-cla').invoke(
            'addCheckSums', app_file, expected_checksums_set
        )

    def __create_file(self, source_files, params=None):
        source_file_list = source_files if isinstance(source_files, list) else [source_files]
        result_file = self.invoke('createFile', source_file_list)
        if params is not None:
            self.change_command_line_arguments(result_file, params)
        return result_file

    def change_command_line_arguments(self, accession, params):
        """
        Changes command arguments in file metainfo.
        params is list of commindlines, each commnaline is string with commands separated with spaces.

        If file is not found or is not of file type
        or is already initialized,
        the corresponding exceptions are thrown.

        :param accession: file accession
        :type accession: str
        :param params: list of commandlines to be set
        :type params: list
        :rtype: None
        """
        self.invoke('changeCommandLineArguments', accession, params if isinstance(params, list) else [params])

    def start(self, accession):
        """
        Starts file initialization.
        If native file is not found or is not of native file type, the corresponding exceptions are thrown.

        :param accession: file accession
        :type accession: str
        :rtype: None
        """
        self.invoke('start', accession)

    # TODO move to filesUtils, why we return name?
    def rename_file(self, accession, name):
        """
        Renames file and returns its new name.

        :param accession: file accession
        :type accession: str
        :param name: name
        :type name: str
        :return: new name
        :rtype: str
        """
        # TODO java return name because javascript require it for callback, should we support same interface in python?
        return self.invoke('renameFile', accession, name)

    def replace_file_reference(self, accession, key, accession_to_remove, accession_to_add):
        """
        Replaces file reference for the file.

        If file is not found or is not of native file type,
        the corresponding exceptions are thrown.
        If accession_to_remove or accession_to_add is not found,
        the corresponding exceptions are thrown.

        :param accession: accession of file
        :param key: key for source files
        :param accession_to_remove: accession to remove
        :param accession_to_add: accession to add
        :rtype: None
        """
        self.invoke('replaceFileReference', accession, key, accession_to_remove, accession_to_add)

class TestCLApplication(CLApplication):
    APPLICATION_ID = 'genestack/testcla'

class BsmapApplication(CLApplication):
    APPLICATION_ID = 'genestack/bsmap'

class UnalignedReadsQC(CLApplication):
    APPLICATION_ID = 'genestack/unalignedreads-qc'

class FastQCApplicaton(CLApplication):
    APPLICATION_ID = 'genestack/fastqc-report'

class AlignedReadsQC(CLApplication):
    APPLICATION_ID = 'genestack/alignedreads-qc'

class MethratioApplication(CLApplication):
    APPLICATION_ID = 'genestack/methratio'

class HTSeqCountsApplication(CLApplication):
    APPLICATION_ID = 'genestack/htseqCount'

class NormalizationApplication(CLApplication):
    APPLICATION_ID = 'genestack/normalization'

class TophatApplication(CLApplication):
    APPLICATION_ID = 'genestack/tophat'

class VariationCallerApplication(CLApplication):
    APPLICATION_ID = 'genestack/variationCaller'

# Preprocess
# preprocess raw reads

# TODO remove this class, this old name leaved here for compatibility
class TrimAdaptorsAndContiminations(CLApplication):
    APPLICATION_ID = 'genestack/fastq-mcf'

class TrimAdaptorsAndContaminants(CLApplication):
    APPLICATION_ID = 'genestack/fastq-mcf'

class FilterByQuality(CLApplication):
    APPLICATION_ID = 'genestack/qualityFilter'

class TrimToFixedLength(CLApplication):
    APPLICATION_ID = 'genestack/fastx-trimmer'

class SubsampleReads(CLApplication):
    APPLICATION_ID = 'genestack/subsampling'

class FilterDuplicatedReads(CLApplication):
    APPLICATION_ID = 'genestack/filter-duplicated-reads'

class TrimLowQualityBases(CLApplication):
    APPLICATION_ID = 'genestack/trim-low-quality-bases'

# preprocess mapped reads
class MarkDuplicated(CLApplication):
    APPLICATION_ID = 'genestack/markDuplicates'

class RemoveDuplicates(CLApplication):
    APPLICATION_ID = 'genestack/removeDuplicates'

# analize
class VariationCaller2Application(CLApplication):
    APPLICATION_ID = 'genestack/variationCaller-v2'

# Unsorted
class BowtieApplication(CLApplication):
    APPLICATION_ID = 'genestack/bowtie'

class BsmapApplicationWG(CLApplication):
    APPLICATION_ID = 'genestack/bsmapWG'

class BWAApplication(CLApplication):
    APPLICATION_ID = 'genestack/bwaMapper'

class RemoveDuplicated(CLApplication):
    APPLICATION_ID = 'genestack/removeDuplicates'

class ConcatenateVariantsApplication(CLApplication):
    APPLICATION_ID = 'genestack/concatenate-variants'

class VariationMergerApplication(CLApplication):
    APPLICATION_ID = 'genestack/merge-vcf'

class CuffquantApplication(CLApplication):
    APPLICATION_ID = 'genestack/cuffquant'

class MergeMappedReadsApplication(CLApplication):
    APPLICATION_ID = 'genestack/samtools-merge'

class VariantsAssociationAnalysisApplication(CLApplication):
    APPLICATION_ID = 'genestack/variantsAssociationAnalysis'

<commit_msg>Fix docstring, change `rtype: None` to `return: None`<commit_after># -*- coding: utf-8 -*-

#
# Copyright (c) 2011-2015 Genestack Limited
# All Rights Reserved
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF GENESTACK LIMITED
# The copyright notice above does not evidence any
# actual or intended publication of such source code.
#

from Connection import Application

CALCULATE_CHECKSUMS = 'markKeyForCountChecksum'

class CLApplication(Application):
    """
    Base class to interact with CommandLine Applications.
    Application_ID is required you can pass it as init argument or overwrite it in children.
    Source files and params depends on application.

    """
    APPLICATION_ID = None

    def __repr__(self):
        return self.APPLICATION_ID

    def create_file(self, source_files, name=None, params=None, calculate_checksums=False, expected_checksums=None,
                    initialize=False):
        """
        Creates application native file and returns its accession.
        If source file is not found or is not of source file type, the corresponding exceptions are thrown.

        :param source_files: list of source file accessions
        :type source_files: list
        :param name: if name is specified created file will be renamed
        :type name: str
        :param params: is command arguments to be set, if None then arguments stay default.
        :param params: list
        :param calculate_checksums: flag that used in initialization script to count checsums of created files
        :type calculate_checksums: bool
        :param expected_checksums: List of expected checksums in any order
        :type expected_checksums: list
        :param initialize: flag if initialization should be started immediately
        :return: accession of created file
        :rtype: str
        """
        app_file = self.__create_file(source_files, params)

        if name:
            self.rename_file(app_file, name)

        if calculate_checksums:
            self.mark_for_tests(app_file)

        if expected_checksums:
            self.add_checksums(app_file, expected_checksums)

        if initialize:
            self.start(app_file)
        return app_file

    def mark_for_tests(self, app_file):
        """
        Mark file for test via add corresponding key to the metainfo.
        Test file will calculate md5 checksums for processed files stored in the storage during initialization.

        :param app_file: accession of file
        :return: None
        """
        self.connection.application('genestack/bio-test-cla').invoke(
            '%s' % CALCULATE_CHECKSUMS, app_file
        )

    def add_checksums(self, app_file, expected_checksums_set):
        """
        Add expected md5 checksum to the metainfo.
        Expected checksums calculated in the next way:
          - number of checksums is same as number of entries in the storage.
          - order of the checksums does not matter.
          For example Reference Genome have 2 entries (annotation and fasta files).

          If there are multiple files in one entry it will concatenate them in order as they were PUT to storage
          by the initialization script.
          If file marked for test then after initialization metainfo will have both expected and actual checksums.

        :param app_file: accession of application file
        :param expected_checksums_set: collection of md5 checksums
        :return: None
        """
        self.connection.application('genestack/bio-test-cla').invoke(
            'addCheckSums', app_file, expected_checksums_set
        )

    def __create_file(self, source_files, params=None):
        source_file_list = source_files if isinstance(source_files, list) else [source_files]
        result_file = self.invoke('createFile', source_file_list)
        if params is not None:
            self.change_command_line_arguments(result_file, params)
        return result_file

    def change_command_line_arguments(self, accession, params):
        """
        Changes command arguments in file metainfo.
        params is list of commindlines, each commnaline is string with commands separated with spaces.

        If file is not found or is not of file type
        or is already initialized,
        the corresponding exceptions are thrown.

        :param accession: file accession
        :type accession: str
        :param params: list of commandlines to be set
        :type params: list
        :return: None
        """
        self.invoke('changeCommandLineArguments', accession, params if isinstance(params, list) else [params])

    def start(self, accession):
        """
        Starts file initialization.
        If native file is not found or is not of native file type, the corresponding exceptions are thrown.

        :param accession: file accession
        :type accession: str
        :return: None
        """
        self.invoke('start', accession)

    # TODO move to filesUtils, why we return name?
    def rename_file(self, accession, name):
        """
        Renames file and returns its new name.

        :param accession: file accession
        :type accession: str
        :param name: name
        :type name: str
        :return: new name
        :rtype: str
        """
        # TODO java return name because javascript require it for callback, should we support same interface in python?
        return self.invoke('renameFile', accession, name)

    def replace_file_reference(self, accession, key, accession_to_remove, accession_to_add):
        """
        Replaces file reference for the file.

        If file is not found or is not of native file type,
        the corresponding exceptions are thrown.
        If accession_to_remove or accession_to_add is not found,
        the corresponding exceptions are thrown.

        :param accession: accession of file
        :param key: key for source files
        :param accession_to_remove: accession to remove
        :param accession_to_add: accession to add
        :return: None
        """
        self.invoke('replaceFileReference', accession, key, accession_to_remove, accession_to_add)

class TestCLApplication(CLApplication):
    APPLICATION_ID = 'genestack/testcla'

class BsmapApplication(CLApplication):
    APPLICATION_ID = 'genestack/bsmap'

class UnalignedReadsQC(CLApplication):
    APPLICATION_ID = 'genestack/unalignedreads-qc'

class FastQCApplicaton(CLApplication):
    APPLICATION_ID = 'genestack/fastqc-report'

class AlignedReadsQC(CLApplication):
    APPLICATION_ID = 'genestack/alignedreads-qc'

class MethratioApplication(CLApplication):
    APPLICATION_ID = 'genestack/methratio'

class HTSeqCountsApplication(CLApplication):
    APPLICATION_ID = 'genestack/htseqCount'

class NormalizationApplication(CLApplication):
    APPLICATION_ID = 'genestack/normalization'

class TophatApplication(CLApplication):
    APPLICATION_ID = 'genestack/tophat'

class VariationCallerApplication(CLApplication):
    APPLICATION_ID = 'genestack/variationCaller'

# Preprocess
# preprocess raw reads

# TODO remove this class, this old name leaved here for compatibility
class TrimAdaptorsAndContiminations(CLApplication):
    APPLICATION_ID = 'genestack/fastq-mcf'

class TrimAdaptorsAndContaminants(CLApplication):
    APPLICATION_ID = 'genestack/fastq-mcf'

class FilterByQuality(CLApplication):
    APPLICATION_ID = 'genestack/qualityFilter'

class TrimToFixedLength(CLApplication):
    APPLICATION_ID = 'genestack/fastx-trimmer'

class SubsampleReads(CLApplication):
    APPLICATION_ID = 'genestack/subsampling'

class FilterDuplicatedReads(CLApplication):
    APPLICATION_ID = 'genestack/filter-duplicated-reads'

class TrimLowQualityBases(CLApplication):
    APPLICATION_ID = 'genestack/trim-low-quality-bases'

# preprocess mapped reads
class MarkDuplicated(CLApplication):
    APPLICATION_ID = 'genestack/markDuplicates'

class RemoveDuplicates(CLApplication):
    APPLICATION_ID = 'genestack/removeDuplicates'

# analize
class VariationCaller2Application(CLApplication):
    APPLICATION_ID = 'genestack/variationCaller-v2'

# Unsorted
class BowtieApplication(CLApplication):
    APPLICATION_ID = 'genestack/bowtie'

class BsmapApplicationWG(CLApplication):
    APPLICATION_ID = 'genestack/bsmapWG'

class BWAApplication(CLApplication):
    APPLICATION_ID = 'genestack/bwaMapper'

class RemoveDuplicated(CLApplication):
    APPLICATION_ID = 'genestack/removeDuplicates'

class ConcatenateVariantsApplication(CLApplication):
    APPLICATION_ID = 'genestack/concatenate-variants'

class VariationMergerApplication(CLApplication):
    APPLICATION_ID = 'genestack/merge-vcf'

class CuffquantApplication(CLApplication):
    APPLICATION_ID = 'genestack/cuffquant'

class MergeMappedReadsApplication(CLApplication):
    APPLICATION_ID = 'genestack/samtools-merge'

class VariantsAssociationAnalysisApplication(CLApplication):
    APPLICATION_ID = 'genestack/variantsAssociationAnalysis'

<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- mode: Python; coding: utf-8 -*-

import sys
from xml.sax.saxutils import escape
from xml.sax.saxutils import unescape

def out_entries(entries,simpara):
  buff = []
  buff.append('<row>')
  for entry in entries:
    buff.append('<entry align="left" valign="top">')
    if simpara:
      buff.append('<simpara><literal>')
    buff.append(entry.strip())
    if simpara:
      buff.append('</literal></simpara>')
    buff.append('</entry>')
  buff.append('</row>')
  return buff

def split_line(line):
  line = unescape(line)
  if not hasattr(split_line, 'positions'):
    split_line.positions = []
    left = 2
    right = -1
    for part in line[1:-2].split('|'):
      right += len(part) + 1
      split_line.positions.append( {'left':left, 'right':right} )
      left = right + 3
  strings = []
  for position in split_line.positions:
    strings.append(escape(line[position['left']:position['right']]))
  return strings

def table_header(title, headings, info_line):
  column_count = len(headings)
  if len(headings[0]) == 0:
    sys.exit("The first table heading is empty.")
  buff = []
  if title:
    buff.append('
')
    buff.append('<title>' + title + '</title>')
  else:
    buff.append('<informaltable tabstyle="queryresult table" frame="all" rowsep="1" colsep="1">')
  buff.append('<tgroup cols="')
  buff.append(str(column_count))
  buff.append('">')
  for i in range(1, column_count + 1):
    buff.append('<colspec colname="col')
    buff.append(str(i))
    buff.append('"/>')
  buff.append('
')
  buff.extend(out_entries(headings, 0))
  buff.append('

<row><entry align="left" valign="top" namest="col1" nameend="col')
  buff.append(str(column_count))
  buff.append('">')
  buff.append(info_line)
  buff.append('</entry></row>
')
  return buff

data = sys.stdin.readlines()
data.pop(0)
first_line = split_line(data.pop(0))
data.pop(0)
query_title = False
if len(sys.argv) > 1:
  query_title = sys.argv[1]
body = []
body.append('
')
for line in data:
  if line[0] == '|':
    body.extend(out_entries(split_line(line), 1))
body.append('
')

sys.stdout.write(''.join(table_header(query_title, first_line, line)))
sys.stdout.write(''.join(body))
sys.stdout.write('</tgroup>')
if query_title:
  sys.stdout.write('
')
else:
  sys.stdout.write('</informaltable>')

<commit_msg>Quick fix to handle empty results from Cypher,<commit_after>#!/usr/bin/env python
# -*- mode: Python; coding: utf-8 -*-

import sys
from xml.sax.saxutils import escape
from xml.sax.saxutils import unescape

def out_entries(entries,simpara):
  buff = []
  buff.append('<row>')
  for entry in entries:
    buff.append('<entry align="left" valign="top">')
    if simpara:
      buff.append('<simpara><literal>')
    buff.append(entry.strip())
    if simpara:
      buff.append('</literal></simpara>')
    buff.append('</entry>')
  buff.append('</row>')
  return buff

def split_line(line):
  line = unescape(line)
  if not hasattr(split_line, 'positions'):
    split_line.positions = []
    left = 2
    right = -1
    for part in line[1:-2].split('|'):
      right += len(part) + 1
      split_line.positions.append( {'left':left, 'right':right} )
      left = right + 3
  strings = []
  for position in split_line.positions:
    strings.append(escape(line[position['left']:position['right']]))
  return strings

def table_header(title, headings, info_line):
  column_count = len(headings)
  if len(headings[0]) == 0:
    sys.exit("The first table heading is empty.")
  buff = []
  if title:
    buff.append('
')
    buff.append('<title>' + title + '</title>')
  else:
    buff.append('<informaltable tabstyle="queryresult table" frame="all" rowsep="1" colsep="1">')
  buff.append('<tgroup cols="')
  buff.append(str(column_count))
  buff.append('">')
  for i in range(1, column_count + 1):
    buff.append('<colspec colname="col')
    buff.append(str(i))
    buff.append('"/>')
  buff.append('
')
  buff.extend(out_entries(headings, 0))
  buff.append('

<row><entry align="left" valign="top" namest="col1" nameend="col')
  buff.append(str(column_count))
  buff.append('">')
  buff.append(info_line)
  buff.append('</entry></row>
')
  return buff

data = sys.stdin.readlines()
data.pop(0)
first_line = split_line(data.pop(0))
column_count = len(first_line)
data.pop(0)
query_title = False
if len(sys.argv) > 1:
  query_title = sys.argv[1]
body = []
body.append('
')
if len(data) == 2:
  body.append('<row><entry align="left" valign="top" namest="col1" nameend="col')
  body.append(str(column_count))
  body.append('">')
  body.append('(empty result)')
  body.append('</entry></row>')
  line = data[1]
else:
  for line in data:
    if line[0] == '|':
      body.extend(out_entries(split_line(line), 1))
body.append('
')

sys.stdout.write(''.join(table_header(query_title, first_line, line)))
sys.stdout.write(''.join(body))
sys.stdout.write('</tgroup>')
if query_title:
  sys.stdout.write('
')
else:
  sys.stdout.write('</informaltable>')

<|endoftext|>


<commit_before>from neuroimaging import traits
import numpy as N
import pylab as P
from matplotlib.axes import Subplot
from matplotlib.figure import Figure

from neuroimaging.core.image.image import Image
from neuroimaging.modalities.fmri import fMRIImage
from neuroimaging.ui.visualization.viewer import BoxViewer
from neuroimaging.utils.tests.data import repository

#matplotlib.use('WXAgg')
###########
# to run plot window without halting execution
# should add check to make sure wxPython is available,
# if not maybe import corresponding classes from gtk backends?

## import gtk
## from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
## from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar

from wxPython.wx import *

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg, \
     NavigationToolbar2WxAgg, FigureManager

###########

class TSDiagnostics(traits.HasTraits):

    mean = traits.true
    sd = traits.true
    mse = traits.true
    mask = traits.Any

    def __init__(self, fmri_image, **keywords):
        traits.HasTraits.__init__(self, **keywords)
        self.fmri_image = fmri_image

    def compute(self):
        ntime = self.fmri_image.grid.shape[0]
        nslice = self.fmri_image.grid.shape[1]

        self.MSEtime = N.zeros((ntime-1,), N.float64)
        self.MSEslice = N.zeros((ntime-1, nslice), N.float64)
        self.mean_signal = N.zeros((ntime,), N.float64)
        self.maxMSEslice = N.zeros((nslice,), N.float64)
        self.minMSEslice = N.zeros((nslice,), N.float64)
        self.meanMSEslice = N.zeros((nslice,), N.float64)

        if self.mean or self.sd or self.mse:
            grid = self.fmri_image.grid.subgrid(0)
            allslice = [slice(0,i,1) for i in self.fmri_image.grid.shape[1:]]
            if self.mean:
                self.mean_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)
            if self.sd:
                self.sd_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)
            if self.mse:
                self.mse_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)

        npixel = {}
        if self.mask is not None:
            nvoxel = self.mask.readall().sum()
        else:
            nvoxel = N.product(self.fmri_image.grid.shape[1:])

        for i in range(ntime-1):
            tmp1 = N.squeeze(self.fmri_image[slice(i,i+1)])
            tmp = (tmp1 -
                   N.squeeze(self.fmri_image[slice(i+1,i+2)]))

            if self.mask is not None:
                tmp *= self.mask.readall()
                tmp1 *= self.mask.readall()

            tmp3 = N.power(tmp, 2)
            tmp2 = self.mse_image.readall()
            self.mse_image[allslice] = tmp2 + tmp3

            self.MSEtime[i] = tmp3.sum() / nvoxel
            self.mean_signal[i] = tmp1.sum() / nvoxel

            for j in range(nslice):
                if self.mask is not None:
                    if not npixel.has_key(j):
                        npixel[j] = self.mask.getslice(slice(j,j+1)).sum()
                else:
                    if not npixel.has_key(j):
                        npixel[j] = N.product(self.fmri_image.grid.shape[2:])
                self.MSEslice[i,j] = N.power(tmp[j], 2).sum() / npixel[j]

        if self.mean:
            self.mean_image[allslice] = N.sum(self.fmri_image.readall(), axis=0) / nvoxel
        if self.sd:
            if self.mask is not None:
                mask = self.mask.readall()
                self.sd_image[allslice] = N.std(mask * self.fmri_image.readall(), axis=0)
            else:
                self.sd_image[allslice] =  N.std(self.fmri_image.readall(), axis=0)

        tmp = self.fmri_image[slice(i+1,i+2)]
        if self.mask is not None:
            tmp *= self.mask.readall()
        self.mean_signal[i+1] = tmp.sum() / nvoxel

        self.maxMSEslice = N.maximum.reduce(self.MSEslice, axis=0)
        self.minMSEslice = N.minimum.reduce(self.MSEslice, axis=0)
        self.meanMSEslice = N.mean(self.MSEslice, axis=0)

        self.mse_image[allslice] = N.sqrt(self.mse_image.readall()/ (ntime-1))
        v = BoxViewer(self.mse_image)
        v.draw(); P.show()

    def plotData(self):
        win = wxFrame(None, -1, "")
        fig = Figure((8,8), 75)
        canvas = FigureCanvasWxAgg(win, -1, fig)
        toolbar = NavigationToolbar2WxAgg(canvas)
        toolbar.Realize()
        #figmgr = FigureManager(canvas, 1, win)
        sizer = wxBoxSizer(wxVERTICAL)
        sizer.Add(canvas, 1, wxLEFT|wxTOP|wxGROW)
        sizer.Add(toolbar, 0, wxLEFT|wxGROW)
        win.SetSizer(sizer)
        win.Fit()

        colors = ['b','g','r','c','m','y','k']
        ax = fig.add_subplot(411)
        ax.plot(self.MSEtime)
        ax = fig.add_subplot(412)
        for j in range(self.MSEslice.shape[1]):
            ax.plot(self.MSEslice[:,j], colors[j%7]+'.-')
        ax = fig.add_subplot(413)
        ax.plot(self.mean_signal)
        ax = fig.add_subplot(414)
        ax.plot(self.maxMSEslice)
        ax.plot(self.minMSEslice)
        ax.plot(self.meanMSEslice)
        win.Show()

if __name__ == '__main__':
    app = wxPySimpleApp(0)
    sample = fMRIImage("test_fmri.hdr", datasource=repository)
    #sample = fMRIImage('http://kff.stanford.edu/FIAC/fiac0/fonc1/fsl/fiac0_fonc1.img')

    tsdiag = TSDiagnostics(sample)
    tsdiag.compute()
    tsdiag.plotData()
    app.MainLoop()
    tsdiag.sd_image.tofile('diag_sd.img', clobber=True)
    tsdiag.mean_image.tofile('diag_mean.img', clobber=True)
    tsdiag.mse_image.tofile('diag_mse.img', clobber=True)

<commit_msg>it works again, small cleanup<commit_after>import numpy as N
import pylab as P

from wxPython.wx import *
from matplotlib.axes import Subplot
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg, \
     NavigationToolbar2WxAgg, FigureManager

from neuroimaging import traits

from neuroimaging.core.image.image import Image
from neuroimaging.modalities.fmri import fMRIImage
from neuroimaging.ui.visualization.viewer import BoxViewer
from neuroimaging.utils.tests.data import repository

class TSDiagnostics(traits.HasTraits):

    mean = traits.true
    sd = traits.true
    mse = traits.true
    mask = traits.Any

    def __init__(self, fmri_image, **keywords):
        traits.HasTraits.__init__(self, **keywords)
        self.fmri_image = fmri_image

    def compute(self):
        ntime = self.fmri_image.grid.shape[0]
        nslice = self.fmri_image.grid.shape[1]

        self.MSEtime = N.zeros((ntime-1,), N.float64)
        self.MSEslice = N.zeros((ntime-1, nslice), N.float64)
        self.mean_signal = N.zeros((ntime,), N.float64)
        self.maxMSEslice = N.zeros((nslice,), N.float64)
        self.minMSEslice = N.zeros((nslice,), N.float64)
        self.meanMSEslice = N.zeros((nslice,), N.float64)

        if self.mean or self.sd or self.mse:
            grid = self.fmri_image.grid.subgrid(0)
            allslice = [slice(0,i,1) for i in self.fmri_image.grid.shape[1:]]
            if self.mean:
                self.mean_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)
            if self.sd:
                self.sd_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)
            if self.mse:
                self.mse_image = Image(N.zeros(self.fmri_image.shape[1:]), grid=grid)

        npixel = {}
        if self.mask is not None:
            nvoxel = self.mask.readall().sum()
        else:
            nvoxel = N.product(self.fmri_image.grid.shape[1:])

        for i in range(ntime-1):
            tmp1 = N.squeeze(self.fmri_image[slice(i,i+1)])
            tmp = (tmp1 -
                   N.squeeze(self.fmri_image[slice(i+1,i+2)]))

            if self.mask is not None:
                tmp *= self.mask.readall()
                tmp1 *= self.mask.readall()

            tmp3 = N.power(tmp, 2)
            tmp2 = self.mse_image.readall()
            self.mse_image[allslice] = tmp2 + tmp3

            self.MSEtime[i] = tmp3.sum() / nvoxel
            self.mean_signal[i] = tmp1.sum() / nvoxel

            for j in range(nslice):
                if self.mask is not None:
                    if not npixel.has_key(j):
                        npixel[j] = self.mask.getslice(slice(j,j+1)).sum()
                else:
                    if not npixel.has_key(j):
                        npixel[j] = N.product(self.fmri_image.grid.shape[2:])
                self.MSEslice[i,j] = N.power(tmp[j], 2).sum() / npixel[j]

        if self.mean:
            self.mean_image[allslice] = N.sum(self.fmri_image.readall(), axis=0) / nvoxel
        if self.sd:
            if self.mask is not None:
                mask = self.mask.readall()
                self.sd_image[allslice] = N.std(mask * self.fmri_image.readall(), axis=0)
            else:
                self.sd_image[allslice] =  N.std(self.fmri_image.readall(), axis=0)

        tmp = self.fmri_image[slice(i+1,i+2)]
        if self.mask is not None:
            tmp *= self.mask.readall()
        self.mean_signal[i+1] = tmp.sum() / nvoxel

        self.maxMSEslice = N.maximum.reduce(self.MSEslice, axis=0)
        self.minMSEslice = N.minimum.reduce(self.MSEslice, axis=0)
        self.meanMSEslice = N.mean(self.MSEslice, axis=0)

        self.mse_image[allslice] = N.sqrt(self.mse_image.readall()/ (ntime-1))
        v = BoxViewer(self.mse_image)
        v.draw(); P.show()

    def plotData(self):
        win = wxFrame(None, -1, "")
        fig = Figure((8,8), 75)
        canvas = FigureCanvasWxAgg(win, -1, fig)
        toolbar = NavigationToolbar2WxAgg(canvas)
        toolbar.Realize()
        #figmgr = FigureManager(canvas, 1, win)
        sizer = wxBoxSizer(wxVERTICAL)
        sizer.Add(canvas, 1, wxLEFT|wxTOP|wxGROW)
        sizer.Add(toolbar, 0, wxLEFT|wxGROW)
        win.SetSizer(sizer)
        win.Fit()

        colors = ['b','g','r','c','m','y','k']
        ax = fig.add_subplot(411)
        ax.plot(self.MSEtime)
        ax = fig.add_subplot(412)
        for j in range(self.MSEslice.shape[1]):
            ax.plot(self.MSEslice[:,j], colors[j%7]+'.-')
        ax = fig.add_subplot(413)
        ax.plot(self.mean_signal)
        ax = fig.add_subplot(414)
        ax.plot(self.maxMSEslice)
        ax.plot(self.minMSEslice)
        ax.plot(self.meanMSEslice)
        win.Show()

if __name__ == '__main__':
    app = wxPySimpleApp(0)
    sample = fMRIImage("test_fmri.hdr", datasource=repository)
    #sample = fMRIImage('http://kff.stanford.edu/FIAC/fiac0/fonc1/fsl/fiac0_fonc1.img')
    tsdiag = TSDiagnostics(sample)
    tsdiag.compute()
    tsdiag.plotData()
    app.MainLoop()
    tsdiag.sd_image.tofile('diag_sd.img', clobber=True)
    tsdiag.mean_image.tofile('diag_mean.img', clobber=True)
    tsdiag.mse_image.tofile('diag_mse.img', clobber=True)

<|endoftext|>


<commit_before># Copyright (C) 2006-2013  Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/

import sys, csv
from essentia import *
from essentia.standard import *
from pylab import *
from numpy import *

try:
    filename = sys.argv[1]
except:
    print "usage:", sys.argv[0], "<input-audiofile>"
    sys.exit()

# In this example we will extract predominant melody given an audio file by
# running a chain of algorithms.

# First, create our algorithms:
hopSize = 128
frameSize = 2048
sampleRate = 44100
guessUnvoiced = True

run_windowing = Windowing(type='hann', zeroPadding=3*frameSize) # Hann window with x4 zero padding
run_spectrum = Spectrum(size=frameSize * 4)
run_spectral_peaks = SpectralPeaks(minFrequency=1,
                                   maxFrequency=20000,
                                   maxPeaks=100,
                                   sampleRate=sampleRate,
                                   magnitudeThreshold=0,
                                   orderBy="magnitude")
run_pitch_salience_function = PitchSalienceFunction()
run_pitch_salience_function_peaks = PitchSalienceFunctionPeaks()
run_pitch_contours = PitchContours(hopSize=hopSize)
run_pitch_contours_melody = PitchContoursMelody(guessUnvoiced=guessUnvoiced,
                                                frameSize=frameSize,
                                                hopSize=hopSize)

# ... and create a Pool
pool = Pool();

# Now we are ready to start processing.
# 1. Load audio and pass it through the equal-loudness filter
audio = MonoLoader(filename = filename)()
audio = EqualLoudness()(audio)

# 2. Cut audio into frames and compute for each frame:
#    spectrum -> spectral peaks -> pitch salience function -> pitch salience function peaks
for frame in FrameGenerator(audio, frameSize=frameSize, hopSize=hopSize):
    frame = run_windowing(frame)
    spectrum = run_spectrum(frame)
    peak_frequencies, peak_magnitudes = run_spectral_peaks(spectrum)

    salience = run_pitch_salience_function(peak_frequencies, peak_magnitudes)
    salience_peaks_bins, salience_peaks_saliences = run_pitch_salience_function_peaks(salience)

    pool.add('allframes_salience_peaks_bins', salience_peaks_bins)
    pool.add('allframes_salience_peaks_saliences', salience_peaks_saliences)

# 3. Now, as we have gathered the required per-frame data, we can feed it to the contour
#    tracking and melody detection algorithms:
contours_bins, contours_saliences, contours_start_times, duration = run_pitch_contours(
        pool['allframes_salience_peaks_bins'],
        pool['allframes_salience_peaks_saliences'])
pitch, confidence = run_pitch_contours_melody(contours_bins,
                                              contours_saliences,
                                              contours_start_times,
                                              duration)

# NOTE that we can avoid the majority of intermediate steps by using a composite algorithm
#      PredominantMelody (see extractor_predominant_melody.py). This script will be usefull
#      if you want to get access to pitch salience function and pitch contours.

n_frames = len(pitch)
print "number of frames:", n_frames

# visualize output pitch
fig = plt.figure()
plot(range(n_frames), pitch, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Pitch (Hz)')
suptitle("Predominant melody pitch")

# visualize output pitch confidence
fig = plt.figure()
plot(range(n_frames), confidence, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Confidence')
suptitle("Predominant melody pitch confidence")

show()
<commit_msg>fixed a python example (incorrect arguments to PredominantMelody algo)<commit_after># Copyright (C) 2006-2013  Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/

import sys, csv
from essentia import *
from essentia.standard import *
from pylab import *
from numpy import *

try:
    filename = sys.argv[1]
except:
    print "usage:", sys.argv[0], "<input-audiofile>"
    sys.exit()

# In this example we will extract predominant melody given an audio file by
# running a chain of algorithms.

# First, create our algorithms:
hopSize = 128
frameSize = 2048
sampleRate = 44100
guessUnvoiced = True

run_windowing = Windowing(type='hann', zeroPadding=3*frameSize) # Hann window with x4 zero padding
run_spectrum = Spectrum(size=frameSize * 4)
run_spectral_peaks = SpectralPeaks(minFrequency=1,
                                   maxFrequency=20000,
                                   maxPeaks=100,
                                   sampleRate=sampleRate,
                                   magnitudeThreshold=0,
                                   orderBy="magnitude")
run_pitch_salience_function = PitchSalienceFunction()
run_pitch_salience_function_peaks = PitchSalienceFunctionPeaks()
run_pitch_contours = PitchContours(hopSize=hopSize)
run_pitch_contours_melody = PitchContoursMelody(guessUnvoiced=guessUnvoiced,
                                                hopSize=hopSize)

# ... and create a Pool
pool = Pool();

# Now we are ready to start processing.
# 1. Load audio and pass it through the equal-loudness filter
audio = MonoLoader(filename = filename)()
audio = EqualLoudness()(audio)

# 2. Cut audio into frames and compute for each frame:
#    spectrum -> spectral peaks -> pitch salience function -> pitch salience function peaks
for frame in FrameGenerator(audio, frameSize=frameSize, hopSize=hopSize):
    frame = run_windowing(frame)
    spectrum = run_spectrum(frame)
    peak_frequencies, peak_magnitudes = run_spectral_peaks(spectrum)

    salience = run_pitch_salience_function(peak_frequencies, peak_magnitudes)
    salience_peaks_bins, salience_peaks_saliences = run_pitch_salience_function_peaks(salience)

    pool.add('allframes_salience_peaks_bins', salience_peaks_bins)
    pool.add('allframes_salience_peaks_saliences', salience_peaks_saliences)

# 3. Now, as we have gathered the required per-frame data, we can feed it to the contour
#    tracking and melody detection algorithms:
contours_bins, contours_saliences, contours_start_times, duration = run_pitch_contours(
        pool['allframes_salience_peaks_bins'],
        pool['allframes_salience_peaks_saliences'])
pitch, confidence = run_pitch_contours_melody(contours_bins,
                                              contours_saliences,
                                              contours_start_times,
                                              duration)

# NOTE that we can avoid the majority of intermediate steps by using a composite algorithm
#      PredominantMelody (see extractor_predominant_melody.py). This script will be usefull
#      if you want to get access to pitch salience function and pitch contours.

n_frames = len(pitch)
print "number of frames:", n_frames

# visualize output pitch
fig = plt.figure()
plot(range(n_frames), pitch, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Pitch (Hz)')
suptitle("Predominant melody pitch")

# visualize output pitch confidence
fig = plt.figure()
plot(range(n_frames), confidence, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Confidence')
suptitle("Predominant melody pitch confidence")

show()
<|endoftext|>


<commit_before>from helpers import *
import org.bukkit.inventory.ItemStack as ItemStack
import org.bukkit.Material as Material
from math import ceil
from basecommands import simplecommand, Validate, CommandException

""" Suggestion by Armadillo28, see thread: http://redstoner.com/forums/threads/2213?page=1#reply-14507 """

disallowed_item_types = (
    Material.getMaterial(0),
    Material.getMaterial(175),
    Material.getMaterial(383),
)

default_args = open_json_file("signalstrengthdefaults", {})

def save_defaults():
    save_json_file("signalstrengthdefaults", default_args)

def item_name(item_type, remove_underscores = True):
    typ = str(item_type).lower()
    return typ.replace("_", "") if remove_underscores else typ

def item_type_allowed(item_type):
    return not item_type in disallowed_item_types

def required_item_count(strength, stack_size, slot_count):
    if strength == 0:
        item_count = 0
    elif strength == 1:
        item_count = 1
    else:
        item_count = int(ceil(slot_count * stack_size / 14.0 * (strength - 1)))

    resulting_strength = 0 if item_count == 0 else int(1 + 14.0 * item_count / stack_size / slot_count)
    #Clarification on these formulas at http://minecraft.gamepedia.com/Redstone_Comparator#Containers

    return item_count if resulting_strength == strength else None

def get_data(player, args):
    uuid = uid(player)
    if uuid in default_args:
        strength, item_type, item_data = default_args[uuid]
        item_type = Material.getMaterial(item_type)
    else:
        strength  = 1
        item_type = Material.REDSTONE
        item_data = 0

    if len(args) > 0:
        Validate.isTrue(args[0].isdigit() and 0 <= int(args[0]) <= 15, "&cThe signal strength has to be a value from 0 to 15")
        strength = int(args[0])

    if len(args) > 1:
        if args[1].isdigit():
            item_type = Material.getMaterial(int(args[1]))
        else:
            item_type = Material.matchMaterial(args[1])
        Validate.notNone(item_type, "&cThat item type could not be found")
        Validate.isTrue(item_type not in disallowed_item_types, "&cThat item type may not be used")

    if len(args) > 2:
        Validate.isTrue(args[2].isdigit() and 0 <= int(args[2]) <= 15, "&cThe data has to be a value from 0 to 15")
        item_data = int(args[2])

    return (strength, item_type, item_data)

def get_inventory(block):
    try:
        return block.getState().getInventory()
    except AttributeError:
        return None

def get_entire_container(container):
    container_blocks = [container]
    container_type = container.getType()
    if container_type in (Material.CHEST, Material.TRAPPED_CHEST):
        loc = container.getLocation()
        x = loc.getBlockX()
        y = loc.getBlockY()
        z = loc.getBlockZ()
        world = loc.getWorld()

        container_blocks += [
            block for block in (
                world.getBlockAt(x + 1, y, z),
                world.getBlockAt(x - 1, y, z),
                world.getBlockAt(x, y, z + 1),
                world.getBlockAt(x, y, z - 1),
            ) if block.getType() == container_type
        ]

    return container_blocks

@simplecommand("signalstrength",
        usage = "(default) [signalstrength] [item] [data]",
        aliases = ["ss", "level"],
        description = "Fills the targeted container with the correct amount of items to achieve the desired signal strength.",
        amin = 0,
        amax = 4,
        helpSubcmd = True,
        senderLimit = 0)
def on_signalstrength_command(sender, command, label, args):
    if not sender.hasPermission("utils.ss"):
        noperm(sender)
        return None
    if len(args) > 0 and args[0].lower() in ("default", "defaults", "setdefaults"):
        strength, item_type, item_data = get_data(sender, args[1:])

        uuid = uid(sender)
        if strength == 1 and item_type == Material.REDSTONE and item_data == 0:
            if uuid in default_args:
                del default_args[uuid]
                save_defaults()
        else:
            default_args[uuid] = (strength, str(item_type), item_data)
            save_defaults()

        return "&aSet your signal strength defaults to (%s, %s, %s)" % (strength, item_name(item_type, False), item_data)

    Validate.isTrue(len(args) <= 3, "&cExpected at most 3 arguments")

    target_block = sender.getTargetBlock(None, 5)
    Validate.notNone(target_block, "&cThat command can only be used when a container is targeted")

    inventory = get_inventory(target_block)
    Validate.notNone(inventory, "&cThat command can only be used if a container is targeted")

    strength, item_type, item_data = get_data(sender, args)

    #--------Get the stack size and required amount of items to achieve the desired signal strength---------
    stack_size = item_type.getMaxStackSize()
    slot_count = inventory.getSize()

    item_count = required_item_count(strength, stack_size, slot_count)
    Validate.notNone(item_count, "&cThe desired signal strength could not be achieved with the requested item type")

    #--------Add the other side of the chest if target is a double chest and check if player can build---------
    container_blocks = get_entire_container(target_block)
    for block in container_blocks:
        Validate.isTrue(can_build(sender, block), "&cYou do not have permission to do that here")

    #----------------Insert items-------------
    full_stack_count, remaining = divmod(item_count, stack_size)
    for block in container_blocks:
        inv = block.getState().getInventory()
        inv.clear()
        for i in range(full_stack_count):
            inv.setItem(i, ItemStack(item_type, stack_size, item_data))
        if remaining > 0:
            inv.setItem(full_stack_count, ItemStack(item_type, remaining, item_data))

    return "&aComparators attached to that %s will now put out a signal strength of %s" % (item_name(target_block.getType()), strength)
<commit_msg>Removed secondary permission, sorry my derp<commit_after>from helpers import *
import org.bukkit.inventory.ItemStack as ItemStack
import org.bukkit.Material as Material
from math import ceil
from basecommands import simplecommand, Validate, CommandException

""" Suggestion by Armadillo28, see thread: http://redstoner.com/forums/threads/2213?page=1#reply-14507 """

disallowed_item_types = (
    Material.getMaterial(0),
    Material.getMaterial(175),
    Material.getMaterial(383),
)

default_args = open_json_file("signalstrengthdefaults", {})

def save_defaults():
    save_json_file("signalstrengthdefaults", default_args)

def item_name(item_type, remove_underscores = True):
    typ = str(item_type).lower()
    return typ.replace("_", "") if remove_underscores else typ

def item_type_allowed(item_type):
    return not item_type in disallowed_item_types

def required_item_count(strength, stack_size, slot_count):
    if strength == 0:
        item_count = 0
    elif strength == 1:
        item_count = 1
    else:
        item_count = int(ceil(slot_count * stack_size / 14.0 * (strength - 1)))

    resulting_strength = 0 if item_count == 0 else int(1 + 14.0 * item_count / stack_size / slot_count)
    #Clarification on these formulas at http://minecraft.gamepedia.com/Redstone_Comparator#Containers

    return item_count if resulting_strength == strength else None

def get_data(player, args):
    uuid = uid(player)
    if uuid in default_args:
        strength, item_type, item_data = default_args[uuid]
        item_type = Material.getMaterial(item_type)
    else:
        strength  = 1
        item_type = Material.REDSTONE
        item_data = 0

    if len(args) > 0:
        Validate.isTrue(args[0].isdigit() and 0 <= int(args[0]) <= 15, "&cThe signal strength has to be a value from 0 to 15")
        strength = int(args[0])

    if len(args) > 1:
        if args[1].isdigit():
            item_type = Material.getMaterial(int(args[1]))
        else:
            item_type = Material.matchMaterial(args[1])
        Validate.notNone(item_type, "&cThat item type could not be found")
        Validate.isTrue(item_type not in disallowed_item_types, "&cThat item type may not be used")

    if len(args) > 2:
        Validate.isTrue(args[2].isdigit() and 0 <= int(args[2]) <= 15, "&cThe data has to be a value from 0 to 15")
        item_data = int(args[2])

    return (strength, item_type, item_data)

def get_inventory(block):
    try:
        return block.getState().getInventory()
    except AttributeError:
        return None

def get_entire_container(container):
    container_blocks = [container]
    container_type = container.getType()
    if container_type in (Material.CHEST, Material.TRAPPED_CHEST):
        loc = container.getLocation()
        x = loc.getBlockX()
        y = loc.getBlockY()
        z = loc.getBlockZ()
        world = loc.getWorld()

        container_blocks += [
            block for block in (
                world.getBlockAt(x + 1, y, z),
                world.getBlockAt(x - 1, y, z),
                world.getBlockAt(x, y, z + 1),
                world.getBlockAt(x, y, z - 1),
            ) if block.getType() == container_type
        ]

    return container_blocks

@simplecommand("signalstrength",
        usage = "(default) [signalstrength] [item] [data]",
        aliases = ["ss", "level"],
        description = "Fills the targeted container with the correct amount of items to achieve the desired signal strength.",
        amin = 0,
        amax = 4,
        helpSubcmd = True,
        senderLimit = 0)
def on_signalstrength_command(sender, command, label, args):
    if len(args) > 0 and args[0].lower() in ("default", "defaults", "setdefaults"):
        strength, item_type, item_data = get_data(sender, args[1:])

        uuid = uid(sender)
        if strength == 1 and item_type == Material.REDSTONE and item_data == 0:
            if uuid in default_args:
                del default_args[uuid]
                save_defaults()
        else:
            default_args[uuid] = (strength, str(item_type), item_data)
            save_defaults()

        return "&aSet your signal strength defaults to (%s, %s, %s)" % (strength, item_name(item_type, False), item_data)

    Validate.isTrue(len(args) <= 3, "&cExpected at most 3 arguments")

    target_block = sender.getTargetBlock(None, 5)
    Validate.notNone(target_block, "&cThat command can only be used when a container is targeted")

    inventory = get_inventory(target_block)
    Validate.notNone(inventory, "&cThat command can only be used if a container is targeted")

    strength, item_type, item_data = get_data(sender, args)

    #--------Get the stack size and required amount of items to achieve the desired signal strength---------
    stack_size = item_type.getMaxStackSize()
    slot_count = inventory.getSize()

    item_count = required_item_count(strength, stack_size, slot_count)
    Validate.notNone(item_count, "&cThe desired signal strength could not be achieved with the requested item type")

    #--------Add the other side of the chest if target is a double chest and check if player can build---------
    container_blocks = get_entire_container(target_block)
    for block in container_blocks:
        Validate.isTrue(can_build(sender, block), "&cYou do not have permission to do that here")

    #----------------Insert items-------------
    full_stack_count, remaining = divmod(item_count, stack_size)
    for block in container_blocks:
        inv = block.getState().getInventory()
        inv.clear()
        for i in range(full_stack_count):
            inv.setItem(i, ItemStack(item_type, stack_size, item_data))
        if remaining > 0:
            inv.setItem(full_stack_count, ItemStack(item_type, remaining, item_data))

    return "&aComparators attached to that %s will now put out a signal strength of %s" % (item_name(target_block.getType()), strength)
<|endoftext|>


<commit_before>import mpd
import os
import random
import ConfigParser

class MpdServer():

    def __init__(self, serverName, serverAddress, serverPort=6600):
        self._serverName = serverName
        self._serverAddress = serverAddress
        self._serverPort = serverPort
        self._connect()

    def _connect(self):
        try:
            self._mpdServer = mpd.MPDClient()
            self._mpdServer.connect(self._serverAddress, self._serverPort)
            self._mpdServer.ping()
            return True
        except:
            print "Error connecting MPD"
            return False

    def getPlaylists(self, startsWith = None):
        l = []
        for pl in self._mpdServer.listplaylists():
            if startsWith == None:
                l.append(pl['playlist'])
            elif str(pl['playlist']).startswith(startsWith):
                l.append(pl['playlist'])
        return sorted(l)

    def getServerVersion(self):
        return self._mpdServer.mpd_version

    def getVolume(self):
        return self._mpdServer.status()['volume']

    def volume(self, volume):
        self._mpdServer.setvol(volume)

    def stop(self):
        self._mpdServer.stop()

    def play(self):
        self._mpdServer.play()

    def emptyPlaylist(self):
        self._mpdServer.clear()

    def loadPlaylist(self, name):
        self._mpdServer.load(name)

    def randomize(self, val):
        self._mpdServer.random(val)

class Mpd():

    def _readConfig(self):
        update = False

        if not os.path.isdir(self._homeDir):
            print "Creating homeDir"
            os.makedirs(self._homeDir)

        if os.path.isfile(self._configFileName):
            self._config.read(self._configFileName)
        else:
            print "Config file not found"
            update = True

        if not self._config.has_section('MPD'):
            print "Adding MPD part"
            update = True
            self._config.add_section("MPD")

        if not self._config.has_option("MPD", "ServerNames"):
            print "No Server Names"
            update = True
            self._config.set("MPD", "ServerNames", "NAME1,NAME2")

        if not self._config.has_option("MPD", "ServerAddresses"):
            print "No Server Addresses"
            update = True
            self._config.set("MPD", "ServerAddresses", "server1,server2")

        if not self._config.has_option("MPD", "ServerPorts"):
            print "No Server Ports"
            update = True
            self._config.set("MPD", "ServerPorts", "6600,6600")

        namesString     = self._config.get("MPD", "ServerNames")
        addressesString = self._config.get("MPD", "ServerAddresses")
        portsString     = self._config.get("MPD", "ServerPorts")

        if namesString == None or addressesString == None or portsString == None:
            print "Error in MPD config Settings"
        else:
            names     = namesString.split(",")
            addresses = addressesString.split(",")
            ports     = portsString.split(",")
            if len(names) != len(addresses) or len(addresses) != len(ports):
                print "Number of MPD configs do not match"
            else:
                for i in range(len(names)):
                    m = MpdServer(names[i].strip(), addresses[i].strip(), ports[i].strip())
                    self._mpdServers[names[i].strip()] = m

        if update:
            with open(self._configFileName, 'w') as f:
                self._config.write(f)

    def __init__(self):
        self._mpdServers     = {}
        self._homeDir        = os.path.expanduser("~/.sensomatic")
        self._configFileName = self._homeDir + '/config.ini'
        self._config         = ConfigParser.ConfigParser()
        self._readConfig()

    def getServerNames(self):
        return self._mpdServers.keys()

    def getServerbyName(self, name):
        if self._mpdServers.has_key(name):
            return self._mpdServers[name]
        else:
            return None

if __name__ == "__main__":
    print "MPD"

    single = MpdServer("Bath", "bathserver")
    single2 = MpdServer("Bath", "bathserver", 6600)

    m = Mpd()
    print m.getServerNames()

    s = m.getServerbyName('AnsiRoom')
    print s.getPlaylists()
    print s.getPlaylists('Drei ???|Die drei ??? \xe2\x80\x93')
    print s.getServerVersion()
    print s.getVolume()
    s.volume(20)
    s.emptyPlaylist()
    random.seed
    s.loadPlaylist(random.choice(s.getPlaylists('Drei ???|Die drei ??? \xe2\x80\x93')))
    s.play()
<commit_msg>Adding add to mpc<commit_after>import os
import mpd
import random
import spotipy
import ConfigParser
import spotipy.util as util

class MpdServer():

    def __init__(self, serverName, serverAddress, serverPort=6600):
        self._serverName = serverName
        self._serverAddress = serverAddress
        self._serverPort = serverPort
        self._connect()

    def _connect(self):
        try:
            self._mpdServer = mpd.MPDClient()
            self._mpdServer.connect(self._serverAddress, self._serverPort)
            self._mpdServer.ping()
            return True
        except:
            print "Error connecting MPD"
            return False

    def getPlaylists(self, startsWith = None):
        l = []
        for pl in self._mpdServer.listplaylists():
            if startsWith == None:
                l.append(pl['playlist'])
            elif str(pl['playlist']).startswith(startsWith):
                l.append(pl['playlist'])
        return sorted(l)

    def getServerVersion(self):
        return self._mpdServer.mpd_version

    def getVolume(self):
        return self._mpdServer.status()['volume']

    def volume(self, volume):
        self._mpdServer.setvol(volume)

    def stop(self):
        self._mpdServer.stop()

    def play(self):
        self._mpdServer.play()

    def emptyPlaylist(self):
        self._mpdServer.clear()

    def loadPlaylist(self, name):
        self._mpdServer.load(name)

    def randomize(self, val):
        self._mpdServer.random(val)

    def add(self, uri):
        self._mpdServer.add(uri)

class Spotify():

    #7C4sUpWGlTy7IANjruj02I Peter Gabriel
    #http://spotipy.readthedocs.io/en/latest/
    def __init__(self):
        self.sp = spotipy.Spotify()

class Mpd():

    def _readConfig(self):
        update = False

        if not os.path.isdir(self._homeDir):
            print "Creating homeDir"
            os.makedirs(self._homeDir)

        if os.path.isfile(self._configFileName):
            self._config.read(self._configFileName)
        else:
            print "Config file not found"
            update = True

        if not self._config.has_section('MPD'):
            print "Adding MPD part"
            update = True
            self._config.add_section("MPD")

        if not self._config.has_option("MPD", "ServerNames"):
            print "No Server Names"
            update = True
            self._config.set("MPD", "ServerNames", "NAME1,NAME2")

        if not self._config.has_option("MPD", "ServerAddresses"):
            print "No Server Addresses"
            update = True
            self._config.set("MPD", "ServerAddresses", "server1,server2")

        if not self._config.has_option("MPD", "ServerPorts"):
            print "No Server Ports"
            update = True
            self._config.set("MPD", "ServerPorts", "6600,6600")

        namesString     = self._config.get("MPD", "ServerNames")
        addressesString = self._config.get("MPD", "ServerAddresses")
        portsString     = self._config.get("MPD", "ServerPorts")

        if namesString == None or addressesString == None or portsString == None:
            print "Error in MPD config Settings"
        else:
            names     = namesString.split(",")
            addresses = addressesString.split(",")
            ports     = portsString.split(",")
            if len(names) != len(addresses) or len(addresses) != len(ports):
                print "Number of MPD configs do not match"
            else:
                for i in range(len(names)):
                    m = MpdServer(names[i].strip(), addresses[i].strip(), ports[i].strip())
                    self._mpdServers[names[i].strip()] = m

        if update:
            with open(self._configFileName, 'w') as f:
                self._config.write(f)

    def __init__(self):
        self._mpdServers     = {}
        self._homeDir        = os.path.expanduser("~/.sensomatic")
        self._configFileName = self._homeDir + '/config.ini'
        self._config         = ConfigParser.ConfigParser()
        self._readConfig()

    def getServerNames(self):
        return self._mpdServers.keys()

    def getServerbyName(self, name):
        if self._mpdServers.has_key(name):
            return self._mpdServers[name]
        else:
            return None

if __name__ == "__main__":
    print "MPD"

    single = MpdServer("Bath", "bathserver")
    single2 = MpdServer("Bath", "bathserver", 6600)

    m = Mpd()
    print m.getServerNames()

    s = m.getServerbyName('AnsiRoom')
    print len(s.getPlaylists())
    print s.getPlaylists('Drei ???|Die drei ??? \xe2\x80\x93')
    print s.getServerVersion()
    print s.getVolume()
    s.volume(20)
    s.emptyPlaylist()
    s.add("http://inforadio.de/livemp3")
    #random.seed
    #s.loadPlaylist(random.choice(s.getPlaylists('Drei ???|Die drei ??? \xe2\x80\x93')))
    s.play()
<|endoftext|>


<commit_before>"""Serializers for REST framework"""
from rest_framework import serializers

from geomat.stein.models import CrystalSystem, Handpiece, MineralType, Photograph, Classification

class StdImageField(serializers.ImageField):
    """
    Get all the variations of the StdImageField
    """

    def to_native(self, obj):
        return self.get_variations_urls(obj)

    def to_representation(self, obj):
        return self.get_variations_urls(obj)

    def get_variations_urls(self, obj):
        """
        Get all the logo urls.
        """

        # Initiate return object
        return_object = {}

        # Get the field of the object
        field = obj.field

        # A lot of ifs going araound, first check if it has the field variations
        if hasattr(field, 'variations'):
            # Get the variations
            variations = field.variations
            # Go through the variations dict
            for key in variations.keys():
                # Just to be sure if the stdimage object has it stored in the obj
                if hasattr(obj, key):
                    # get the by stdimage properties
                    field_obj = getattr(obj, key, None)
                    if field_obj and hasattr(field_obj, 'url'):
                        # store it, with the name of the variation type into our return object
                        return_object[key] = super(
                            StdImageField, self).to_representation(field_obj)

        # Also include the original (if possible)
        if hasattr(obj, 'url'):
            return_object['original'] = super(StdImageField,
                                              self).to_representation(obj)

        return return_object

class ClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        fields = ('classification_name', 'mineral_type')

class NameClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        fields = ('classification_name',)

class MineralTypeSerializer(serializers.ModelSerializer):
    classification = NameClassificationSerializer()
    systematics = serializers.SerializerMethodField()
    fracture = serializers.SerializerMethodField()
    cleavage = serializers.SerializerMethodField()
    lustre = serializers.SerializerMethodField()
    chemical_formula = serializers.SerializerMethodField()
    class Meta:
        model = MineralType
        fields = '__all__'
        depth = 1
    def get_systematics(self, obj):
	return obj.get_systematics_display()
    def get_fracture(self, obj):
	lst =[]
	choice_dict = dict(obj.FRACTURE_CHOICES)
    if obj.lustre:
        for choice in obj.fracture:
            lst.append(choice_dict.get(choice))
	return lst
    def get_cleavage(self, obj):
	lst =[]
	choice_dict = dict(obj.CLEAVAGE_CHOICES)
    if obj.cleavage:
        for choice in obj.cleavage:
            lst.append(choice_dict.get(choice))
	return lst
    def get_lustre(self, obj):
	lst =[]
	choice_dict = dict(obj.LUSTRE_CHOICES)
    if obj.lustre:
        for choice in obj.lustre:
            lst.append(choice_dict.get(choice))
	return lst
    def get_chemical_formula(self, obj):
	return "`" + obj.chemical_formula + "`"

class CrystalSystemSerializer(serializers.ModelSerializer):
    mineral_type = MineralTypeSerializer()

    class Meta:
        model = CrystalSystem
        fields = ('id', 'mineral_type', 'crystal_system', 'temperature',
                  'pressure')

class HandpieceSerializer(serializers.ModelSerializer):
    mineral_type = MineralTypeSerializer(many=True)

    class Meta:
        model = Handpiece
        fields = ('id', 'name', 'mineral_type', 'finding_place',
                  'current_location', 'old_inventory_number', 'created_at',
                  'last_modified')

class PhotographSerializer(serializers.ModelSerializer):
    image_file = StdImageField()
    handpiece = HandpieceSerializer()
    online_status = serializers.BooleanField()

    class Meta:
        model = Photograph
        fields = ('id', 'image_file', 'handpiece', 'orientation', 'shot_type',
                  'online_status', 'created_at', 'last_modified')
<commit_msg>small indet fix<commit_after>"""Serializers for REST framework"""
from rest_framework import serializers

from geomat.stein.models import CrystalSystem, Handpiece, MineralType, Photograph, Classification

class StdImageField(serializers.ImageField):
    """
    Get all the variations of the StdImageField
    """

    def to_native(self, obj):
        return self.get_variations_urls(obj)

    def to_representation(self, obj):
        return self.get_variations_urls(obj)

    def get_variations_urls(self, obj):
        """
        Get all the logo urls.
        """

        # Initiate return object
        return_object = {}

        # Get the field of the object
        field = obj.field

        # A lot of ifs going araound, first check if it has the field variations
        if hasattr(field, 'variations'):
            # Get the variations
            variations = field.variations
            # Go through the variations dict
            for key in variations.keys():
                # Just to be sure if the stdimage object has it stored in the obj
                if hasattr(obj, key):
                    # get the by stdimage properties
                    field_obj = getattr(obj, key, None)
                    if field_obj and hasattr(field_obj, 'url'):
                        # store it, with the name of the variation type into our return object
                        return_object[key] = super(
                            StdImageField, self).to_representation(field_obj)

        # Also include the original (if possible)
        if hasattr(obj, 'url'):
            return_object['original'] = super(StdImageField,
                                              self).to_representation(obj)

        return return_object

class ClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        fields = ('classification_name', 'mineral_type')

class NameClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        fields = ('classification_name',)

class MineralTypeSerializer(serializers.ModelSerializer):
    classification = NameClassificationSerializer()
    systematics = serializers.SerializerMethodField()
    fracture = serializers.SerializerMethodField()
    cleavage = serializers.SerializerMethodField()
    lustre = serializers.SerializerMethodField()
    chemical_formula = serializers.SerializerMethodField()
    class Meta:
        model = MineralType
        fields = '__all__'
        depth = 1
    def get_systematics(self, obj):
	return obj.get_systematics_display()
    def get_fracture(self, obj):
	lst =[]
	choice_dict = dict(obj.FRACTURE_CHOICES)
        if obj.lustre:
            for choice in obj.fracture:
                lst.append(choice_dict.get(choice))
	return lst
    def get_cleavage(self, obj):
	lst =[]
	choice_dict = dict(obj.CLEAVAGE_CHOICES)
        if obj.cleavage:
            for choice in obj.cleavage:
                lst.append(choice_dict.get(choice))
	return lst
    def get_lustre(self, obj):
	lst =[]
	choice_dict = dict(obj.LUSTRE_CHOICES)
        if obj.lustre:
            for choice in obj.lustre:
                lst.append(choice_dict.get(choice))
	return lst
    def get_chemical_formula(self, obj):
	return "`" + obj.chemical_formula + "`"

class CrystalSystemSerializer(serializers.ModelSerializer):
    mineral_type = MineralTypeSerializer()

    class Meta:
        model = CrystalSystem
        fields = ('id', 'mineral_type', 'crystal_system', 'temperature',
                  'pressure')

class HandpieceSerializer(serializers.ModelSerializer):
    mineral_type = MineralTypeSerializer(many=True)

    class Meta:
        model = Handpiece
        fields = ('id', 'name', 'mineral_type', 'finding_place',
                  'current_location', 'old_inventory_number', 'created_at',
                  'last_modified')

class PhotographSerializer(serializers.ModelSerializer):
    image_file = StdImageField()
    handpiece = HandpieceSerializer()
    online_status = serializers.BooleanField()

    class Meta:
        model = Photograph
        fields = ('id', 'image_file', 'handpiece', 'orientation', 'shot_type',
                  'online_status', 'created_at', 'last_modified')
<|endoftext|>


<commit_before>'''
------------------------------------------------------------------------
Firm functions for firms in the steady state and along the transition
path

This Python module imports the following module(s): None

This Python module defines the following functions:
    get_Y()
    get_r()
    get_w()
    get_KLrat_from_r()
    get_w_from_r()
    get_K()
------------------------------------------------------------------------
'''

'''
------------------------------------------------------------------------
    Functions
------------------------------------------------------------------------
'''

def get_Y(K, L, p, method):
    '''
    --------------------------------------------------------------------
    Generates aggregate output (GDP) from aggregate capital stock,
    aggregate labor, and CES production function parameters
    --------------------------------------------------------------------
    INPUTS:
    K = scalar or D dimensional array, aggregate capital stock
    L = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    epsilon = scalar >= 0, elasticity of substitution between capital
              and labor
    Z       = scalar > 0, total factor productivity
    gamma   = scalar in [0, 1], CES production function share parameter
    Y       = scalar or D dimensional array, aggregate output (GDP)

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: Y
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    if p.epsilon == 1:
        # Unit elasticity, Cobb-Douglas
        Y = Z * (K ** p.gamma) * (L ** (1 - p.gamma))
    else:
        # General case
        Y = (Z * (((p.gamma ** (1 / p.epsilon)) *
                   (K ** ((p.epsilon - 1) / p.epsilon))) +
                  (((1 - p.gamma) ** (1 / p.epsilon)) *
                   (L ** ((p.epsilon - 1) / p.epsilon)))) **
             (p.epsilon / (p.epsilon - 1)))

    return Y

def get_r(Y, K, p, method):
    '''
    --------------------------------------------------------------------
    This function computes the interest rate as a function of Y, K, and
    parameters using the firm's first order condition for capital demand
    --------------------------------------------------------------------
    INPUTS:
    Y = scalar or (T+S,) vector, aggregate output
    K = scalar or (T+S,) vector, aggregate capital
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    tau_b     = scalar in [0, 1], corporate income tax rate
    Z         = scalar > 0, total factor productivity
    epsilon   = scalar > 0, elasticity of substitution between capital
                and labor
    gamma     = scalar in [0, 1], share parameter in CES production
                function (capital share of income in Cobb-Douglas case)
    delta     = scalar in [0, 1], per-period capital depreciation rate
    delta_tau = scalar >= 0, percent of capital depreciation rate
                refunded at the corporate income tax rate
    r         = scalar or (T+S,) vector, interest rate on (rental rate
                of) capital

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: r
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
        delta_tau = p.delta_tau[-1]
        tau_b = p.tau_b[-1]
    else:
        Z = p.Z[:p.T]
        delta_tau = p.delta_tau[:p.T]
        tau_b = p.tau_b[:p.T]
    r = ((1 - tau_b) * (Z ** ((p.epsilon - 1) / p.epsilon)) *
         (((p.gamma * Y) / K) ** (1 / p.epsilon)) -
         p.delta + tau_b * delta_tau)

    return r

def get_w(Y, L, p, method):
    '''
    --------------------------------------------------------------------
    This function computes the wage as a function of Y, L, and
    parameters using the firm's first order condition for labor demand
    --------------------------------------------------------------------
    INPUTS:
    Y = scalar or (T+S,) vector, aggregate output
    L = scalar or (T+S,) vector, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    Z       = scalar > 0, total factor productivity
    epsilon = scalar > 0, elasticity of substitution between capital and
              labor
    gamma   = scalar in [0, 1], share parameter in CES production
              function (capital share of income in Cobb-Douglas case)
    w       = scalar or (T+S,) vector, wage

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: w
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    w = ((Z ** ((p.epsilon - 1) / p.epsilon)) *
         ((((1 - p.gamma) * Y) / L) ** (1 / p.epsilon)))

    return w

def get_KLratio_from_r(r, p, method):
    '''
    --------------------------------------------------------------------
    This function solves for the capital-labor ratio given the interest
    rate r and parameters
    --------------------------------------------------------------------
    INPUTS:
    r = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    tau_b     = scalar in [0, 1], corporate income tax rate
    Z         = scalar > 0, total factor productivity
    epsilon   = scalar > 0, elasticity of substitution between capital
                and labor
    gamma     = scalar in [0, 1], share parameter in CES production
                function (capital share of income in Cobb-Douglas case)
    delta     = scalar in [0, 1], per-period capital depreciation rate
    delta_tau = scalar >= 0, percent of capital depreciation rate
                refunded at the corporate income tax rate
    bracket   = scalar or D dimensional array, value in bracket in
                equation for capital-labor ratio

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: KLratio
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
        delta_tau = p.delta_tau[-1]
        tau_b = p.tau_b[-1]
    else:
        Z = p.Z[:p.T]
        delta_tau = p.delta_tau[:p.T]
        tau_b = p.tau_b[:p.T]
    if p.epsilon == 1:
        # Cobb-Douglas case
        bracket = (((1 - tau_b) * p.gamma * Z) /
                   (r + p.delta - tau_b * delta_tau))
        KLratio = bracket ** (1 / (1 - p.gamma))
    else:
        # General CES case
        bracket = ((r + p.delta - (delta_tau * tau_b)) /
                   ((1 - tau_b) * Z * (p.gamma ** (1 / p.epsilon))))
        KLratio = \
            ((((1 - p.gamma) ** (1 / p.epsilon)) /
              ((bracket ** (p.epsilon - 1)) -
               (p.gamma ** (1 / p.epsilon)))) ** (p.epsilon /
                                                  (p.epsilon - 1)))
    return KLratio

def get_w_from_r(r, p, method):
    '''
    --------------------------------------------------------------------
    Solve for steady-state wage w or time path of wages w_t given
    interest rate
    --------------------------------------------------------------------
    INPUTS:
    r = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION:
        get_KLrat_from_r()

    OBJECTS CREATED WITHIN FUNCTION:
    KLratio = scalar or D dimensional array, capital-labor ratio
              computed from interest rate and parameters
    epsilon = scalar > 0, elasticity of substitution between capital and
              labor
    eps     = scalar > 0, epsilon
    gamma   = scalar in [0, 1], share parameter in CES production
              function (capital share of income in Cobb-Douglas case)
    Z       = scalar > 0, total factor productivity
    w       = scalar or D dimensional array, wage

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: w
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    KLratio = get_KLratio_from_r(r, p, method)
    if p.epsilon == 1:
        # Cobb-Douglas case
        w = (1 - p.gamma) * Z * (KLratio ** p.gamma)
    else:
        # General CES case
        w = (((1 - p.gamma) ** (1 / p.epsilon)) * Z *
             (((p.gamma ** (1 / p.epsilon)) *
               (KLratio ** ((p.epsilon - 1) / p.epsilon)) +
               ((1 - p.gamma) ** (1 / p.epsilon))) **
              (1 / (p.epsilon - 1))))
    return w

def get_K(L, r, p, method):
    '''
    --------------------------------------------------------------------
    Generates vector of aggregate capital. Use with small open economy
    option.
    --------------------------------------------------------------------
    Inputs:
        L      = [T+S,] vector, aggregate labor
        r      = [T+S,] vector, exogenous rental rate of the firm
        params = length 3 tuple, (alpha, delta, z)
        alpha  = scalar, capital's share of output
        delta  = scalar, rate of depreciation of capital
        Z      = scalar, total factor productivity

    Functions called: None

    Objects in function:
        K = [T+S,] vector, aggregate capital

    Returns: r
    --------------------------------------------------------------------
    '''
    KLratio = get_KLratio_from_r(r, p, method)
    K = KLratio * L

    print('USING firm.getK()')

    return K
<commit_msg>function to solve for K from Y<commit_after>'''
------------------------------------------------------------------------
Firm functions for firms in the steady state and along the transition
path

This Python module imports the following module(s): None

This Python module defines the following functions:
    get_Y()
    get_r()
    get_w()
    get_KLrat_from_r()
    get_w_from_r()
    get_K()
------------------------------------------------------------------------
'''

'''
------------------------------------------------------------------------
    Functions
------------------------------------------------------------------------
'''

def get_Y(K, L, p, method):
    '''
    --------------------------------------------------------------------
    Generates aggregate output (GDP) from aggregate capital stock,
    aggregate labor, and CES production function parameters
    --------------------------------------------------------------------
    INPUTS:
    K = scalar or D dimensional array, aggregate capital stock
    L = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    epsilon = scalar >= 0, elasticity of substitution between capital
              and labor
    Z       = scalar > 0, total factor productivity
    gamma   = scalar in [0, 1], CES production function share parameter
    Y       = scalar or D dimensional array, aggregate output (GDP)

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: Y
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    if p.epsilon == 1:
        # Unit elasticity, Cobb-Douglas
        Y = Z * (K ** p.gamma) * (L ** (1 - p.gamma))
    else:
        # General case
        Y = (Z * (((p.gamma ** (1 / p.epsilon)) *
                   (K ** ((p.epsilon - 1) / p.epsilon))) +
                  (((1 - p.gamma) ** (1 / p.epsilon)) *
                   (L ** ((p.epsilon - 1) / p.epsilon)))) **
             (p.epsilon / (p.epsilon - 1)))

    return Y

def get_r(Y, K, p, method):
    '''
    --------------------------------------------------------------------
    This function computes the interest rate as a function of Y, K, and
    parameters using the firm's first order condition for capital demand
    --------------------------------------------------------------------
    INPUTS:
    Y = scalar or (T+S,) vector, aggregate output
    K = scalar or (T+S,) vector, aggregate capital
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    tau_b     = scalar in [0, 1], corporate income tax rate
    Z         = scalar > 0, total factor productivity
    epsilon   = scalar > 0, elasticity of substitution between capital
                and labor
    gamma     = scalar in [0, 1], share parameter in CES production
                function (capital share of income in Cobb-Douglas case)
    delta     = scalar in [0, 1], per-period capital depreciation rate
    delta_tau = scalar >= 0, percent of capital depreciation rate
                refunded at the corporate income tax rate
    r         = scalar or (T+S,) vector, interest rate on (rental rate
                of) capital

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: r
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
        delta_tau = p.delta_tau[-1]
        tau_b = p.tau_b[-1]
    else:
        Z = p.Z[:p.T]
        delta_tau = p.delta_tau[:p.T]
        tau_b = p.tau_b[:p.T]
    r = ((1 - tau_b) * (Z ** ((p.epsilon - 1) / p.epsilon)) *
         (((p.gamma * Y) / K) ** (1 / p.epsilon)) -
         p.delta + tau_b * delta_tau)

    return r

def get_w(Y, L, p, method):
    '''
    --------------------------------------------------------------------
    This function computes the wage as a function of Y, L, and
    parameters using the firm's first order condition for labor demand
    --------------------------------------------------------------------
    INPUTS:
    Y = scalar or (T+S,) vector, aggregate output
    L = scalar or (T+S,) vector, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    Z       = scalar > 0, total factor productivity
    epsilon = scalar > 0, elasticity of substitution between capital and
              labor
    gamma   = scalar in [0, 1], share parameter in CES production
              function (capital share of income in Cobb-Douglas case)
    w       = scalar or (T+S,) vector, wage

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: w
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    w = ((Z ** ((p.epsilon - 1) / p.epsilon)) *
         ((((1 - p.gamma) * Y) / L) ** (1 / p.epsilon)))

    return w

def get_KLratio_from_r(r, p, method):
    '''
    --------------------------------------------------------------------
    This function solves for the capital-labor ratio given the interest
    rate r and parameters
    --------------------------------------------------------------------
    INPUTS:
    r = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    tau_b     = scalar in [0, 1], corporate income tax rate
    Z         = scalar > 0, total factor productivity
    epsilon   = scalar > 0, elasticity of substitution between capital
                and labor
    gamma     = scalar in [0, 1], share parameter in CES production
                function (capital share of income in Cobb-Douglas case)
    delta     = scalar in [0, 1], per-period capital depreciation rate
    delta_tau = scalar >= 0, percent of capital depreciation rate
                refunded at the corporate income tax rate
    bracket   = scalar or D dimensional array, value in bracket in
                equation for capital-labor ratio

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: KLratio
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
        delta_tau = p.delta_tau[-1]
        tau_b = p.tau_b[-1]
    else:
        Z = p.Z[:p.T]
        delta_tau = p.delta_tau[:p.T]
        tau_b = p.tau_b[:p.T]
    if p.epsilon == 1:
        # Cobb-Douglas case
        bracket = (((1 - tau_b) * p.gamma * Z) /
                   (r + p.delta - tau_b * delta_tau))
        KLratio = bracket ** (1 / (1 - p.gamma))
    else:
        # General CES case
        bracket = ((r + p.delta - (delta_tau * tau_b)) /
                   ((1 - tau_b) * Z * (p.gamma ** (1 / p.epsilon))))
        KLratio = \
            ((((1 - p.gamma) ** (1 / p.epsilon)) /
              ((bracket ** (p.epsilon - 1)) -
               (p.gamma ** (1 / p.epsilon)))) ** (p.epsilon /
                                                  (p.epsilon - 1)))
    return KLratio

def get_w_from_r(r, p, method):
    '''
    --------------------------------------------------------------------
    Solve for steady-state wage w or time path of wages w_t given
    interest rate
    --------------------------------------------------------------------
    INPUTS:
    r = scalar or D dimensional array, aggregate labor
    p = model parameters object

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION:
        get_KLrat_from_r()

    OBJECTS CREATED WITHIN FUNCTION:
    KLratio = scalar or D dimensional array, capital-labor ratio
              computed from interest rate and parameters
    epsilon = scalar > 0, elasticity of substitution between capital and
              labor
    eps     = scalar > 0, epsilon
    gamma   = scalar in [0, 1], share parameter in CES production
              function (capital share of income in Cobb-Douglas case)
    Z       = scalar > 0, total factor productivity
    w       = scalar or D dimensional array, wage

    FILES CREATED BY THIS FUNCTION: None

    RETURNS: w
    --------------------------------------------------------------------
    '''
    if method == 'SS':
        Z = p.Z[-1]
    else:
        Z = p.Z[:p.T]
    KLratio = get_KLratio_from_r(r, p, method)
    if p.epsilon == 1:
        # Cobb-Douglas case
        w = (1 - p.gamma) * Z * (KLratio ** p.gamma)
    else:
        # General CES case
        w = (((1 - p.gamma) ** (1 / p.epsilon)) * Z *
             (((p.gamma ** (1 / p.epsilon)) *
               (KLratio ** ((p.epsilon - 1) / p.epsilon)) +
               ((1 - p.gamma) ** (1 / p.epsilon))) **
              (1 / (p.epsilon - 1))))
    return w

def get_K(L, r, p, method):
    '''
    --------------------------------------------------------------------
    Generates vector of aggregate capital. Use with small open economy
    option.
    --------------------------------------------------------------------
    Inputs:
        L      = [T+S,] vector, aggregate labor
        r      = [T+S,] vector, exogenous rental rate of the firm
        params = length 3 tuple, (alpha, delta, z)
        alpha  = scalar, capital's share of output
        delta  = scalar, rate of depreciation of capital
        Z      = scalar, total factor productivity

    Functions called: None

    Objects in function:
        K = [T+S,] vector, aggregate capital

    Returns: r
    --------------------------------------------------------------------
    '''
    KLratio = get_KLratio_from_r(r, p, method)
    K = KLratio * L

    print('USING firm.getK()')

    return K

def get_K_from_Y(Y, r, p, method):
    '''
    --------------------------------------------------------------------
    Generates vector of aggregate capital. Use with small open economy
    option.
    --------------------------------------------------------------------
    Inputs:
        L      = [T+S,] vector, aggregate labor
        r      = [T+S,] vector, exogenous rental rate of the firm
        params = length 3 tuple, (alpha, delta, z)
        alpha  = scalar, capital's share of output
        delta  = scalar, rate of depreciation of capital
        Z      = scalar, total factor productivity

    Functions called: None

    Objects in function:
        K = [T+S,] vector, aggregate capital

    Returns: r
    --------------------------------------------------------------------
    '''
    KLratio = get_KLratio_from_r(r, p, method)
    LKratio = KLratio ** -1
    YKratio = get_Y(1, LKratio, p, method)
    K = Y / YKratio

    return K
<|endoftext|>