<commit_before>"""
Extending the RoadRunner object with additional fields.
"""

from __future__ import print_function, division, absolute_import
import os
import roadrunner
import warnings

# ---------------------------------------------------------------------
# Extended RoadRunner class
# ---------------------------------------------------------------------
class ExtendedRoadRunner(roadrunner.RoadRunner):

    def __init__(self, *args, **kwargs):
        super(ExtendedRoadRunner, self).__init__(*args, **kwargs)

    # ---------------------------------------------------------------------
    # Model access
    # ---------------------------------------------------------------------
    # def getBoundarySpeciesConcentrations(self):
    #     return self.model.getBoundarySpeciesConcentrations()
    # getBoundarySpeciesConcentrations.__doc__ = roadrunner.ExecutableModel.getBoundarySpeciesConcentrations.__doc__

    # These model functions are attached after class creation
    _model_functions = [
        'getBoundarySpeciesConcentrations',
        'getBoundarySpeciesConcentrations',
        'getBoundarySpeciesIds',
        'getNumBoundarySpecies',

        'getFloatingSpeciesConcentrations',
        'getFloatingSpeciesIds',
        'getNumFloatingSpecies',

        'getGlobalParameterIds',
        'getGlobalParameterValues',
        'getNumGlobalParameters',

        'getCompartmentIds',
        'getCompartmentVolumes',
        'getNumCompartments',

        'getConservedMoietyValues',
        'getNumConservedMoieties',
        'getNumDepFloatingSpecies',
        'getNumIndFloatingSpecies',

        'getReactionIds',
        'getReactionRates',
        'getNumReactions',
        'getNumEvents',
        'getNumRateRules'
     ]

    # ---------------------------------------------------------------------
    # Jarnac compatibility layer
    # ---------------------------------------------------------------------
    def fjac(self):
        return self.getFullJacobian()
    fjac.__doc__ = roadrunner.RoadRunner.getFullJacobian.__doc__

    def sm(self):
        return self.getFullStoichiometryMatrix()
    sm.__doc__ = roadrunner.RoadRunner.getFullStoichiometryMatrix.__doc__

    def rs(self):
        return self.model.getReactionIds()
    rs.__doc__ = roadrunner.ExecutableModel.getReactionIds.__doc__

    def fs(self):
        return self.model.getFloatingSpeciesIds()
    fs.__doc__ = roadrunner.ExecutableModel.getFloatingSpeciesIds.__doc__

    def bs(self):
        return self.model.getBoundarySpeciesIds()
    bs.__doc__ = roadrunner.ExecutableModel.getBoundarySpeciesIds.__doc__

    def ps(self):
        return self.model.getGlobalParameterIds()
    ps.__doc__ = roadrunner.ExecutableModel.getGlobalParameterIds.__doc__

    def vs(self):
        return self.model.getCompartmentIds()
    vs.__doc__ = roadrunner.ExecutableModel.getCompartmentIds.__doc__

    def dv(self):
        return self.model.getStateVectorRate()
    dv.__doc__ = roadrunner.ExecutableModel.getStateVector.__doc__

    def rv(self):
        return self.model.getReactionRates()
    rv.__doc__ = roadrunner.ExecutableModel.getReactionRates.__doc__

    def sv(self):
        return self.model.getFloatingSpeciesConcentrations()
    sv.__doc__ = roadrunner.ExecutableModel.getFloatingSpeciesConcentrations.__doc__

    # ---------------------------------------------------------------------
    # Export Utilities
    # ---------------------------------------------------------------------
    def __getSBML(self, current):
        if current is True:
            return self.getCurrentSBML()
        else:
            return self.getSBML()

    def getAntimony(self, current=False):
        """ Antimony string of the original model loaded into roadrunner.

        :param current: return current model state
        :type current: bool
        :return: Antimony
        :rtype: str
        """
        sbml = self.__getSBML(current)
        from .. import sbmlToAntimony
        return sbmlToAntimony(sbml)

    def getCurrentAntimony(self):
        """ Antimony string of the current model state.

        See also: :func:`getAntimony`
        :return: Antimony
        :rtype: str
        """
        return self.getAntimony(current=True)

    def getCellML(self, current=False):
        """ CellML string of the original model loaded into roadrunner.

        :param current: return current model state
        :type current: bool
        :returns: CellML string
        :rtype: str
        """
        sbml = self.__getSBML(current)
        from .. import sbmlToCellML
        return sbmlToCellML(sbml)

    def getCurrentCellML(self):
        """ CellML string of current model state.

        See also: :func:`getCellML`
        :returns: CellML string
        :rtype: str
        """
        return self.getCellML(current=True)

    def getMatlab(self, current=False):
        """ Matlab string of the original model loaded into roadrunner.

        See also: :func:`getCurrentMatlab`
        :returns: Matlab string
        :rtype: str
        """
        try:
            from sbml2matlab import sbml2matlab
            sbml = self.__getSBML(current)
            return sbml2matlab(sbml)
        except ImportError:
            warnings.warn("'sbml2matlab' could not be imported, no support for Matlab code generation",
                          RuntimeWarning, stacklevel=2)
            return ""

    def getCurrentMatlab(self):
        """ Matlab string of current model state.

        :param current: return current model state
        :type current: bool
        :returns: Matlab string
        :rtype: str
        """
        return self.getMatlab(current=True)

    def exportToSBML(self, filePath, current=True):
        """ Save current model as SBML file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of SBML file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.__getSBML(current))

    def exportToAntimony(self, filePath, current=True):
        """ Save current model as Antimony file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of Antimony file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getAntimony(current))

    def exportToCellML(self, filePath, current=True):
        """ Save current model as CellML file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of CellML file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getCellML(current))

    def exportToMatlab(self, filePath, current=True):
        """ Save current model as Matlab file.
        To save the original model loaded into roadrunner use
        current=False.

        :param self: RoadRunner instance
        :type self: RoadRunner.roadrunner
        :param filePath: file path of Matlab file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getMatlab(current))

    # ---------------------------------------------------------------------
    # Reset Methods
    # ---------------------------------------------------------------------
    # FIXME: Remove in next release
    def resetToOrigin(self):
        """ Reset model to state when first loaded.

        This resets the model back to the state when it was FIRST loaded,
        this includes all init() and parameters such as k1 etc.

        identical to:
            r.reset(roadrunner.SelectionRecord.ALL)
        """
        self.reset(roadrunner.SelectionRecord.ALL)

    def resetAll(self):
        """ Reset all model variables to CURRENT init(X) values.

        This resets all variables, S1, S2 etc to the CURRENT init(X) values. It also resets all
        parameters back to the values they had when the model was first loaded.
        """
        self.reset(roadrunner.SelectionRecord.TIME |
                   roadrunner.SelectionRecord.RATE |
                   roadrunner.SelectionRecord.FLOATING |
                   roadrunner.SelectionRecord.GLOBAL_PARAMETER)

    # ---------------------------------------------------------------------
    # Routines flattened from model, aves typing and easier finding of methods
    # ---------------------------------------------------------------------
    def getRatesOfChange(self):
        """ Rate of change of all state variables in the model.

        :returns: rate of change of all state variables (eg species) in the model.
        """
        if self.conservedMoietyAnalysis:
            m1 = self.getLinkMatrix()
            m2 = self.model.getStateVectorRate()
            return m1.dot(m2)
        else:
            return self.model.getStateVectorRate()

    # ---------------------------------------------------------------------
    # Plotting Utilities
    # ---------------------------------------------------------------------
    def draw(self, **kwargs):
        """ Draws an SBMLDiagram of the current model.

        To set the width of the output plot provide the 'width' argument.
        Species are drawn as white circles (boundary species
        shaded in blue), reactions as grey squares.
        Currently only the drawing of medium-size networks is supported.
        """
        import shutil
        # PATH variable may not be present - cannot use os.environ['PATH']
        # but can use shutil.which for Python 3.3+
        if hasattr(shutil, 'which'):
            if shutil.which('dot') is None:
                warnings.warn("Graphviz is not installed in your machine or could not be found. 'draw' command cannot produce a diagram.",
                    Warning, stacklevel=2)
                return
        elif not 'PATH' in os.environ or any([ os.access( os.path.join( p, 'dot' ), os.X_OK ) for p in os.environ['PATH'].split( os.pathsep )]):
            warnings.warn("Graphviz is not installed in your machine or could not be found. 'draw' command cannot produce a diagram.",
                Warning, stacklevel=2)
            return

        from tellurium import SBMLDiagram
        diagram = SBMLDiagram(self.getSBML())
        diagram.draw(**kwargs)

    # FIXME: update the documentation of plot function
    def plot(self, result=None, show=True,
             xtitle=None, ytitle=None, title=None, xlim=None, ylim=None, logx=False, logy=False,
             xscale='linear', yscale='linear', grid=False, ordinates=None, tag=None, labels=None,
             figsize=(6,4), savefig=None, dpi=80, **kwargs):
        """ Plot roadrunner simulation data.

        Plot is called with simulation data to plot as the first argument. If no data is provided the data currently
        held by roadrunner generated in the last simulation is used. The first column is considered the x axis and
        all remaining columns the y axis.
        If the result array has no names, than the current r.selections are used for naming. In this case the
        dimension of the r.selections has to be the same like the number of columns of the result array.

        Curves are plotted in order of selection (columns in result).

        In addition to the listed keywords plot supports all matplotlib.pyplot.plot keyword arguments,
        like color, alpha, linewidth, linestyle, marker, ...
        ::

            sbml = te.getTestModel('feedback.xml')
            r = te.loadSBMLModel(sbml)
            s = r.simulate(0, 100, 201)
            r.plot(s, loc="upper right", linewidth=2.0, lineStyle='-', marker='o', markersize=2.0, alpha=0.8,
                   title="Feedback Oscillation", xlabel="time", ylabel="concentration", xlim=[0,100], ylim=[-1, 4])

        :param result: results data to plot (numpy array)
        :param show: show the plot, use show=False to plot multiple simulations in one plot
        :param xtitle: x-axis label (str)
        :param ytitle: y-axis label (str)
        :param title: plot title (str)
        :param xlim: limits on x-axis (tuple [start, end])
        :param ylim: limits on y-axis
        :param logx: boolean of log scale for x-axis
        :param logy: boolean of log scale for y-axis
        :param xscale: 'linear' or 'log' scale for x-axis
        :param yscale: 'linear' or 'log' scale for y-axis
        :param grid: show grid
        :param ordinates: If supplied, only these selections will be plotted (see RoadRunner selections)
        :param tag: If supplied, all traces with the same tag will be plotted with the same color/style
        :param kwargs: additional matplotlib keywords like marker, lineStyle, color, alpha, ...
        :param labels: 'id' to use species IDs,
        :param figsize: If supplied, customize the size of the figure,
        :param savefig: If supplied, save the figure to specified location,
        :param dpi: Change the dpi of the saved figure,
        :return:
        """
        if result is None:
            result = self.getSimulationData()

        from .. import getPlottingEngine

        if ordinates:
            kwargs['ordinates'] = ordinates
        if title:
            kwargs['title'] = title
        if xtitle:
            kwargs['xtitle'] = xtitle
        if ytitle:
            kwargs['ytitle'] = ytitle
        if xlim:
            kwargs['xlim'] = xlim
        if ylim:
            kwargs['ylim'] = ylim
        if logx:
            kwargs['logx'] = logx
        if logy:
            kwargs['logy'] = logy
        if tag:
            kwargs['tag'] = tag
        if figsize:
            kwargs['figsize'] = figsize
        if savefig:
            kwargs['savefig'] = savefig
        if dpi:
            kwargs['dpi'] = dpi

        # FIXME: provide the additional parameters to the plotting engine

        engine = getPlottingEngine()
        if show:
            # show the plot immediately
            engine.plotTimecourse(result, **kwargs)
        else:
            # otherwise, accumulate the traces
            engine.accumulateTimecourse(result, **kwargs)

    def show(self, reset=True):
        """ Show plot. """
        from .. import getPlottingEngine
        getPlottingEngine().show(reset=reset)

    # ---------------------------------------------------------------------
    # Stochastic Simulation Methods
    # ---------------------------------------------------------------------
    def getSeed(self, integratorName="gillespie"):
        """ Current seed used by the integrator with integratorName.
        Defaults to the seed of the gillespie integrator.

        :param integratorName: name of the integrator for which the seed should be retured
        :type integratorName: str
        :returns: current seed
        :rtype: float
        """
        integrator = self.getIntegratorByName(integratorName)
        return integrator.getValue('seed')

    @property
    def seed(self):
        """ Getter for Gillespie seed. """
        return self.getSeed()

    def setSeed(self, seed, integratorName="gillespie"):
        """ Set seed in integrator with integratorName.
        Defaults to the seed of the gillespie integrator.

        Raises Error if integrator does not have key 'seed'.

        :param seed: seed to set
        :param integratorName: name of the integrator for which the seed should be retured
        :type integratorName: str
        """
        # there are some issues converting big Python (greater than 4,294,967,295) integers
        # to C integers on 64 bit machines. If its converted to float before, works around the issue.
        self.setIntegratorSetting(integratorName=integratorName, settingName="seed", value=float(seed))

    @seed.setter
    def seed(self, value):
        """ Setter for Gillespie seed. """
        return self.setSeed(value)

    def gillespie(self, *args, **kwargs):
        """ Run a Gillespie stochastic simulation.

        Sets the integrator to gillespie and performs simulation.
        ::

            rr = te.loada ('S1 -> S2; k1*S1; k1 = 0.1; S1 = 40')
            # Simulate from time zero to 40 time units
            result = rr.gillespie (0, 40)
            # Simulate on a grid with 10 points from start 0 to end time 40
            rr.reset()
            result = rr.gillespie (0, 40, 10)
            # Simulate from time zero to 40 time units using the given selection list
            # This means that the first column will be time and the second column species S1
            rr.reset()
            result = rr.gillespie (0, 40, selections=['time', 'S1'])
            # Simulate from time zero to 40 time units, on a grid with 20 points
            # using the give selection list
            rr.reset()
            result = rr.gillespie (0, 40, 20, ['time', 'S1'])
            rr.plot(result)

        :param seed: seed for gillespie
        :type seed: int
        :param args: parameters for simulate
        :param kwargs: parameters for simulate
        :returns: simulation results
        """

        integratorName = self.integrator.getName()
        if (integratorName != 'gillespie'):
            self.setIntegrator('gillespie')
            self.integrator.variable_step_size = True
        if (len(args) > 3):
            self.integrator.variable_step_size = False
        if (len(args) == 3):
            if (type(args[2]) != list):
                self.integrator.variable_step_size = False
        elif ('points' in kwargs or 'steps' in kwargs):
            self.integrator.variable_step_size = False

        s = self.simulate(*args, **kwargs)
        self.setIntegrator(integratorName)
        return s
<commit_msg>Update gilespie doc<commit_after>"""
Extending the RoadRunner object with additional fields.
"""

from __future__ import print_function, division, absolute_import
import os
import roadrunner
import warnings

# ---------------------------------------------------------------------
# Extended RoadRunner class
# ---------------------------------------------------------------------
class ExtendedRoadRunner(roadrunner.RoadRunner):

    def __init__(self, *args, **kwargs):
        super(ExtendedRoadRunner, self).__init__(*args, **kwargs)

    # ---------------------------------------------------------------------
    # Model access
    # ---------------------------------------------------------------------
    # def getBoundarySpeciesConcentrations(self):
    #     return self.model.getBoundarySpeciesConcentrations()
    # getBoundarySpeciesConcentrations.__doc__ = roadrunner.ExecutableModel.getBoundarySpeciesConcentrations.__doc__

    # These model functions are attached after class creation
    _model_functions = [
        'getBoundarySpeciesConcentrations',
        'getBoundarySpeciesConcentrations',
        'getBoundarySpeciesIds',
        'getNumBoundarySpecies',

        'getFloatingSpeciesConcentrations',
        'getFloatingSpeciesIds',
        'getNumFloatingSpecies',

        'getGlobalParameterIds',
        'getGlobalParameterValues',
        'getNumGlobalParameters',

        'getCompartmentIds',
        'getCompartmentVolumes',
        'getNumCompartments',

        'getConservedMoietyValues',
        'getNumConservedMoieties',
        'getNumDepFloatingSpecies',
        'getNumIndFloatingSpecies',

        'getReactionIds',
        'getReactionRates',
        'getNumReactions',
        'getNumEvents',
        'getNumRateRules'
     ]

    # ---------------------------------------------------------------------
    # Jarnac compatibility layer
    # ---------------------------------------------------------------------
    def fjac(self):
        return self.getFullJacobian()
    fjac.__doc__ = roadrunner.RoadRunner.getFullJacobian.__doc__

    def sm(self):
        return self.getFullStoichiometryMatrix()
    sm.__doc__ = roadrunner.RoadRunner.getFullStoichiometryMatrix.__doc__

    def rs(self):
        return self.model.getReactionIds()
    rs.__doc__ = roadrunner.ExecutableModel.getReactionIds.__doc__

    def fs(self):
        return self.model.getFloatingSpeciesIds()
    fs.__doc__ = roadrunner.ExecutableModel.getFloatingSpeciesIds.__doc__

    def bs(self):
        return self.model.getBoundarySpeciesIds()
    bs.__doc__ = roadrunner.ExecutableModel.getBoundarySpeciesIds.__doc__

    def ps(self):
        return self.model.getGlobalParameterIds()
    ps.__doc__ = roadrunner.ExecutableModel.getGlobalParameterIds.__doc__

    def vs(self):
        return self.model.getCompartmentIds()
    vs.__doc__ = roadrunner.ExecutableModel.getCompartmentIds.__doc__

    def dv(self):
        return self.model.getStateVectorRate()
    dv.__doc__ = roadrunner.ExecutableModel.getStateVector.__doc__

    def rv(self):
        return self.model.getReactionRates()
    rv.__doc__ = roadrunner.ExecutableModel.getReactionRates.__doc__

    def sv(self):
        return self.model.getFloatingSpeciesConcentrations()
    sv.__doc__ = roadrunner.ExecutableModel.getFloatingSpeciesConcentrations.__doc__

    # ---------------------------------------------------------------------
    # Export Utilities
    # ---------------------------------------------------------------------
    def __getSBML(self, current):
        if current is True:
            return self.getCurrentSBML()
        else:
            return self.getSBML()

    def getAntimony(self, current=False):
        """ Antimony string of the original model loaded into roadrunner.

        :param current: return current model state
        :type current: bool
        :return: Antimony
        :rtype: str
        """
        sbml = self.__getSBML(current)
        from .. import sbmlToAntimony
        return sbmlToAntimony(sbml)

    def getCurrentAntimony(self):
        """ Antimony string of the current model state.

        See also: :func:`getAntimony`
        :return: Antimony
        :rtype: str
        """
        return self.getAntimony(current=True)

    def getCellML(self, current=False):
        """ CellML string of the original model loaded into roadrunner.

        :param current: return current model state
        :type current: bool
        :returns: CellML string
        :rtype: str
        """
        sbml = self.__getSBML(current)
        from .. import sbmlToCellML
        return sbmlToCellML(sbml)

    def getCurrentCellML(self):
        """ CellML string of current model state.

        See also: :func:`getCellML`
        :returns: CellML string
        :rtype: str
        """
        return self.getCellML(current=True)

    def getMatlab(self, current=False):
        """ Matlab string of the original model loaded into roadrunner.

        See also: :func:`getCurrentMatlab`
        :returns: Matlab string
        :rtype: str
        """
        try:
            from sbml2matlab import sbml2matlab
            sbml = self.__getSBML(current)
            return sbml2matlab(sbml)
        except ImportError:
            warnings.warn("'sbml2matlab' could not be imported, no support for Matlab code generation",
                          RuntimeWarning, stacklevel=2)
            return ""

    def getCurrentMatlab(self):
        """ Matlab string of current model state.

        :param current: return current model state
        :type current: bool
        :returns: Matlab string
        :rtype: str
        """
        return self.getMatlab(current=True)

    def exportToSBML(self, filePath, current=True):
        """ Save current model as SBML file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of SBML file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.__getSBML(current))

    def exportToAntimony(self, filePath, current=True):
        """ Save current model as Antimony file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of Antimony file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getAntimony(current))

    def exportToCellML(self, filePath, current=True):
        """ Save current model as CellML file.

        :param current: export current model state
        :type current: bool
        :param filePath: file path of CellML file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getCellML(current))

    def exportToMatlab(self, filePath, current=True):
        """ Save current model as Matlab file.
        To save the original model loaded into roadrunner use
        current=False.

        :param self: RoadRunner instance
        :type self: RoadRunner.roadrunner
        :param filePath: file path of Matlab file
        :type filePath: str
        """
        with open(filePath, 'w') as f:
            f.write(self.getMatlab(current))

    # ---------------------------------------------------------------------
    # Reset Methods
    # ---------------------------------------------------------------------
    # FIXME: Remove in next release
    def resetToOrigin(self):
        """ Reset model to state when first loaded.

        This resets the model back to the state when it was FIRST loaded,
        this includes all init() and parameters such as k1 etc.

        identical to:
            r.reset(roadrunner.SelectionRecord.ALL)
        """
        self.reset(roadrunner.SelectionRecord.ALL)

    def resetAll(self):
        """ Reset all model variables to CURRENT init(X) values.

        This resets all variables, S1, S2 etc to the CURRENT init(X) values. It also resets all
        parameters back to the values they had when the model was first loaded.
        """
        self.reset(roadrunner.SelectionRecord.TIME |
                   roadrunner.SelectionRecord.RATE |
                   roadrunner.SelectionRecord.FLOATING |
                   roadrunner.SelectionRecord.GLOBAL_PARAMETER)

    # ---------------------------------------------------------------------
    # Routines flattened from model, aves typing and easier finding of methods
    # ---------------------------------------------------------------------
    def getRatesOfChange(self):
        """ Rate of change of all state variables in the model.

        :returns: rate of change of all state variables (eg species) in the model.
        """
        if self.conservedMoietyAnalysis:
            m1 = self.getLinkMatrix()
            m2 = self.model.getStateVectorRate()
            return m1.dot(m2)
        else:
            return self.model.getStateVectorRate()

    # ---------------------------------------------------------------------
    # Plotting Utilities
    # ---------------------------------------------------------------------
    def draw(self, **kwargs):
        """ Draws an SBMLDiagram of the current model.

        To set the width of the output plot provide the 'width' argument.
        Species are drawn as white circles (boundary species
        shaded in blue), reactions as grey squares.
        Currently only the drawing of medium-size networks is supported.
        """
        import shutil
        # PATH variable may not be present - cannot use os.environ['PATH']
        # but can use shutil.which for Python 3.3+
        if hasattr(shutil, 'which'):
            if shutil.which('dot') is None:
                warnings.warn("Graphviz is not installed in your machine or could not be found. 'draw' command cannot produce a diagram.",
                    Warning, stacklevel=2)
                return
        elif not 'PATH' in os.environ or any([ os.access( os.path.join( p, 'dot' ), os.X_OK ) for p in os.environ['PATH'].split( os.pathsep )]):
            warnings.warn("Graphviz is not installed in your machine or could not be found. 'draw' command cannot produce a diagram.",
                Warning, stacklevel=2)
            return

        from tellurium import SBMLDiagram
        diagram = SBMLDiagram(self.getSBML())
        diagram.draw(**kwargs)

    # FIXME: update the documentation of plot function
    def plot(self, result=None, show=True,
             xtitle=None, ytitle=None, title=None, xlim=None, ylim=None, logx=False, logy=False,
             xscale='linear', yscale='linear', grid=False, ordinates=None, tag=None, labels=None,
             figsize=(6,4), savefig=None, dpi=80, **kwargs):
        """ Plot roadrunner simulation data.

        Plot is called with simulation data to plot as the first argument. If no data is provided the data currently
        held by roadrunner generated in the last simulation is used. The first column is considered the x axis and
        all remaining columns the y axis.
        If the result array has no names, than the current r.selections are used for naming. In this case the
        dimension of the r.selections has to be the same like the number of columns of the result array.

        Curves are plotted in order of selection (columns in result).

        In addition to the listed keywords plot supports all matplotlib.pyplot.plot keyword arguments,
        like color, alpha, linewidth, linestyle, marker, ...
        ::

            sbml = te.getTestModel('feedback.xml')
            r = te.loadSBMLModel(sbml)
            s = r.simulate(0, 100, 201)
            r.plot(s, loc="upper right", linewidth=2.0, lineStyle='-', marker='o', markersize=2.0, alpha=0.8,
                   title="Feedback Oscillation", xlabel="time", ylabel="concentration", xlim=[0,100], ylim=[-1, 4])

        :param result: results data to plot (numpy array)
        :param show: show the plot, use show=False to plot multiple simulations in one plot
        :param xtitle: x-axis label (str)
        :param ytitle: y-axis label (str)
        :param title: plot title (str)
        :param xlim: limits on x-axis (tuple [start, end])
        :param ylim: limits on y-axis
        :param logx: boolean of log scale for x-axis
        :param logy: boolean of log scale for y-axis
        :param xscale: 'linear' or 'log' scale for x-axis
        :param yscale: 'linear' or 'log' scale for y-axis
        :param grid: show grid
        :param ordinates: If supplied, only these selections will be plotted (see RoadRunner selections)
        :param tag: If supplied, all traces with the same tag will be plotted with the same color/style
        :param kwargs: additional matplotlib keywords like marker, lineStyle, color, alpha, ...
        :param labels: 'id' to use species IDs,
        :param figsize: If supplied, customize the size of the figure,
        :param savefig: If supplied, save the figure to specified location,
        :param dpi: Change the dpi of the saved figure,
        :return:
        """
        if result is None:
            result = self.getSimulationData()

        from .. import getPlottingEngine

        if ordinates:
            kwargs['ordinates'] = ordinates
        if title:
            kwargs['title'] = title
        if xtitle:
            kwargs['xtitle'] = xtitle
        if ytitle:
            kwargs['ytitle'] = ytitle
        if xlim:
            kwargs['xlim'] = xlim
        if ylim:
            kwargs['ylim'] = ylim
        if logx:
            kwargs['logx'] = logx
        if logy:
            kwargs['logy'] = logy
        if tag:
            kwargs['tag'] = tag
        if figsize:
            kwargs['figsize'] = figsize
        if savefig:
            kwargs['savefig'] = savefig
        if dpi:
            kwargs['dpi'] = dpi

        # FIXME: provide the additional parameters to the plotting engine

        engine = getPlottingEngine()
        if show:
            # show the plot immediately
            engine.plotTimecourse(result, **kwargs)
        else:
            # otherwise, accumulate the traces
            engine.accumulateTimecourse(result, **kwargs)

    def show(self, reset=True):
        """ Show plot. """
        from .. import getPlottingEngine
        getPlottingEngine().show(reset=reset)

    # ---------------------------------------------------------------------
    # Stochastic Simulation Methods
    # ---------------------------------------------------------------------
    def getSeed(self, integratorName="gillespie"):
        """ Current seed used by the integrator with integratorName.
        Defaults to the seed of the gillespie integrator.

        :param integratorName: name of the integrator for which the seed should be retured
        :type integratorName: str
        :returns: current seed
        :rtype: float
        """
        integrator = self.getIntegratorByName(integratorName)
        return integrator.getValue('seed')

    @property
    def seed(self):
        """ Getter for Gillespie seed. """
        return self.getSeed()

    def setSeed(self, seed, integratorName="gillespie"):
        """ Set seed in integrator with integratorName.
        Defaults to the seed of the gillespie integrator.

        Raises Error if integrator does not have key 'seed'.

        :param seed: seed to set
        :param integratorName: name of the integrator for which the seed should be retured
        :type integratorName: str
        """
        # there are some issues converting big Python (greater than 4,294,967,295) integers
        # to C integers on 64 bit machines. If its converted to float before, works around the issue.
        self.setIntegratorSetting(integratorName=integratorName, settingName="seed", value=float(seed))

    @seed.setter
    def seed(self, value):
        """ Setter for Gillespie seed. """
        return self.setSeed(value)

    def gillespie(self, *args, **kwargs):
        """ Run a Gillespie stochastic simulation.

        Sets the integrator to gillespie and performs simulation.
        ::

            rr = te.loada ('S1 -> S2; k1*S1; k1 = 0.1; S1 = 40')
            # Simulate from time zero to 40 time units using variable step sizes (classic Gillespie)
            result = rr.gillespie (0, 40)
            # Simulate on a grid with 10 points from start 0 to end time 40
            rr.reset()
            result = rr.gillespie (0, 40, 10)
            # Simulate from time zero to 40 time units using variable step sizes with given selection list
            # This means that the first column will be time and the second column species S1
            rr.reset()
            result = rr.gillespie (0, 40, selections=['time', 'S1'])
            # Simulate on a grid with 20 points from time zero to 40 time units
            # using the given selection list
            rr.reset()
            result = rr.gillespie (0, 40, 20, ['time', 'S1'])
            rr.plot(result)

        :param seed: seed for gillespie
        :type seed: int
        :param args: parameters for simulate
        :param kwargs: parameters for simulate
        :returns: simulation results
        """

        integratorName = self.integrator.getName()
        if (integratorName != 'gillespie'):
            self.setIntegrator('gillespie')
            self.integrator.variable_step_size = True
        if (len(args) > 3):
            self.integrator.variable_step_size = False
        if (len(args) == 3):
            if (type(args[2]) != list):
                self.integrator.variable_step_size = False
        elif ('points' in kwargs or 'steps' in kwargs):
            self.integrator.variable_step_size = False

        s = self.simulate(*args, **kwargs)
        self.setIntegrator(integratorName)
        return s
<|endoftext|>


<commit_before>"""distutils

The main package for the Python Module Distribution Utilities.  Normally
used from a setup script as

   from distutils.core import setup

   setup (...)
"""

# This module should be kept compatible with Python 2.1.

__revision__ = "$Id$"

# Distutils version
#
# Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding
# new features to distutils that would warrant bumping the version number.
#
# In general, major and minor version should loosely follow the Python
# version number the distutils code was shipped with.
#
__version__ = "2.5.0"
<commit_msg>Bump the patch level version of distutils since there were a few bug fixes since the 2.5.0 release.<commit_after>"""distutils

The main package for the Python Module Distribution Utilities.  Normally
used from a setup script as

   from distutils.core import setup

   setup (...)
"""

# This module should be kept compatible with Python 2.1.

__revision__ = "$Id$"

# Distutils version
#
# Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding
# new features to distutils that would warrant bumping the version number.
#
# In general, major and minor version should loosely follow the Python
# version number the distutils code was shipped with.
#
__version__ = "2.5.1"
<|endoftext|>


<commit_before>"""Pens for creating glyphs in FontLab."""

__all__ = ["FLPen", "FLPointPen", "drawFLGlyphOntoPointPen"]

from FL import *

try:
	from fl_cmd import *
except ImportError:
	print "The fl_cmd module is not available here. flPen.py"

from robofab.tools.toolsFL import NewGlyph
from robofab.pens.pointPen import AbstractPointPen
from robofab.pens.adapterPens import SegmentToPointPen

def roundInt(x):
	return int(round(x))

class FLPen(SegmentToPointPen):

	def __init__(self, glyph):
		SegmentToPointPen.__init__(self, FLPointPen(glyph))

class FLPointPen(AbstractPointPen):

	def __init__(self, glyph):
		if hasattr(glyph, "isRobofab"):
			self.glyph = glyph.naked()
		else:
			self.glyph = glyph
		self.currentPath = None

	def beginPath(self):
		self.currentPath = []

	def endPath(self):
		# Love is... abstracting away FL's madness.
		path = self.currentPath
		self.currentPath = None
		glyph = self.glyph
		if len(path) == 1 and path[0][3] is not None:
			# Single point on the contour, it has a name. Make it an anchor.
			x, y = path[0][0]
			name = path[0][3]
			anchor = Anchor(name, roundInt(x), roundInt(y))
			glyph.anchors.append(anchor)
			return
		firstOnCurveIndex = None
		for i in range(len(path)):
			if path[i][1] is not None:
				firstOnCurveIndex = i
				break
		if firstOnCurveIndex is None:
			# TT special case: on-curve-less contour. FL doesn't support that,
			# so we insert an implied point at the end.
			x1, y1 = path[0][0]
			x2, y2 = path[-1][0]
			impliedPoint = 0.5 * (x1 + x2), 0.5 * (y1 + y2)
			path.append((impliedPoint, "qcurve", True, None))
			firstOnCurveIndex = 0
		path = path[firstOnCurveIndex + 1:] + path[:firstOnCurveIndex + 1]
		firstPoint, segmentType, smooth, name = path[-1]
		closed = True
		if segmentType == "move":
			path = path[:-1]
			closed = False
			# XXX The contour is not closed, but I can't figure out how to
			# create an open contour in FL. Creating one by hand shows type"0x8011"
			# for a move node in an open contour, but I'm not able to access
			# that flag.
		elif segmentType == "line":
			# The contour is closed and ends in a lineto, which is redundant
			# as it's implied by closepath.
			path = path[:-1]
		x, y = firstPoint
		node = Node(nMOVE, Point(roundInt(x), roundInt(y)))
		if smooth and closed:
			if segmentType == "line" or path[0][1] == "line":
				node.alignment = nFIXED
			else:
				node.alignment = nSMOOTH
		glyph.Insert(node, len(glyph))
		segment = []
		nPoints = len(path)
		for i in range(nPoints):
			pt, segmentType, smooth, name = path[i]
			segment.append(pt)
			if segmentType is None:
				continue
			if segmentType == "curve":
				if len(segment) < 2:
					segmentType = "line"
				elif len(segment) == 2:
					segmentType = "qcurve"
			if segmentType == "qcurve":
				for x, y in segment[:-1]:
					glyph.Insert(Node(nOFF, Point(roundInt(x), roundInt(y))), len(glyph))
				x, y = segment[-1]
				node = Node(nLINE, Point(roundInt(x), roundInt(y)))
				glyph.Insert(node, len(glyph))
			elif segmentType == "curve":
				if len(segment) == 3:
					cubicSegments = [segment]
				else:
					from fontTools.pens.basePen import decomposeSuperBezierSegment
					cubicSegments = decomposeSuperBezierSegment(segment)
				nSegments = len(cubicSegments)
				for i in range(nSegments):
					pt1, pt2, pt3 = cubicSegments[i]
					x, y = pt3
					node = Node(nCURVE, Point(roundInt(x), roundInt(y)))
					node.points[1].x, node.points[1].y = roundInt(pt1[0]), roundInt(pt1[1])
					node.points[2].x, node.points[2].y = roundInt(pt2[0]), roundInt(pt2[1])
					if i != nSegments - 1:
						node.alignment = nSMOOTH
					glyph.Insert(node, len(self.glyph))
			elif segmentType == "line":
				assert len(segment) == 1, segment
				x, y = segment[0]
				node = Node(nLINE, Point(roundInt(x), roundInt(y)))
				glyph.Insert(node, len(glyph))
			else:
				assert 0, "unsupported curve type (%s)" % segmentType
			if smooth:
				if i + 1 < nPoints or closed:
					# Can't use existing node, as you can't change node attributes
					# AFTER it's been appended to the glyph.
					node = glyph[-1]
					if segmentType == "line" or path[(i+1) % nPoints][1] == "line":
						# tangent
						node.alignment = nFIXED
					else:
						# curve
						node.alignment = nSMOOTH
			segment = []
		if closed:
			# we may have output a node too much
			node = glyph[-1]
			if node.type == nLINE and (node.x, node.y) == (roundInt(firstPoint[0]), roundInt(firstPoint[1])):
				glyph.DeleteNode(len(glyph) - 1)

	def addPoint(self, pt, segmentType=None, smooth=None, name=None, **kwargs):
		self.currentPath.append((pt, segmentType, smooth, name))

	def addComponent(self, baseName, transformation):
		assert self.currentPath is None
		# make base glyph if needed, Component() needs the index
		NewGlyph(self.glyph.parent, baseName)
		baseIndex = self.glyph.parent.FindGlyph(baseName)
		if baseIndex == -1:
			raise KeyError, "couldn't find or make base glyph"
		xx, xy, yx, yy, dx, dy = transformation
		# XXX warn when xy or yx != 0
		new = Component(baseIndex, Point(dx, dy), Point(xx, yy))
		self.glyph.components.append(new)

def drawFLGlyphOntoPointPen(flGlyph, pen):
	"""Draw a FontLab glyph onto a PointPen."""
	for anchor in flGlyph.anchors:
		pen.beginPath()
		pen.addPoint((anchor.x, anchor.y), name=anchor.name)
		pen.endPath()
	for contour in _getContours(flGlyph):
		pen.beginPath()
		for pt, segmentType, smooth in contour:
			pen.addPoint(pt, segmentType=segmentType, smooth=smooth)
		pen.endPath()
	for baseGlyph, tranform in _getComponents(flGlyph):
		pen.addComponent(baseGlyph, tranform)

NODE_TYPES = {nMOVE: "move", nLINE: "line", nCURVE: "curve",
             nOFF: None}

def _getContours(glyph):
	contours = []
	for i in range(len(glyph)):
		node = glyph[i]
		segmentType = NODE_TYPES[node.type]
		if segmentType == "move":
			contours.append([])
		for pt in node.points[1:]:
			contours[-1].append(((pt.x, pt.y), None, False))
		smooth = node.alignment != nSHARP
		contours[-1].append(((node.x, node.y), segmentType, smooth))

	for contour in contours:
		# filter out or change the move
		movePt, segmentType, smooth = contour[0]
		assert segmentType == "move"
		lastSegmentType = contour[-1][1]
		if movePt == contour[-1][0] and lastSegmentType == "curve":
			contour[0] = contour[-1]
			contour.pop()
		elif lastSegmentType is None:
			contour[0] = movePt, "qcurve", smooth
		else:
			assert lastSegmentType in ("line", "curve")
			contour[0] = movePt, "line", smooth

		# change "line" to "qcurve" if appropriate
		previousSegmentType = "ArbitraryValueOtherThanNone"
		for i in range(len(contour)):
			pt, segmentType, smooth = contour[i]
			if segmentType == "line" and previousSegmentType is None:
				contour[i] = pt, "qcurve", smooth
			previousSegmentType = segmentType

	return contours

def _simplifyValues(*values):
	"""Given a set of numbers, convert items to ints if they are
	integer float values, eg. 0.0, 1.0."""
	newValues = []
	for v in values:
		i = int(v)
		if v == i:
			v = i
		newValues.append(v)
	return newValues

def _getComponents(glyph):
	components = []
	for comp in glyph.components:
		baseName = glyph.parent[comp.index].name
		dx, dy = comp.delta.x, comp.delta.y
		sx, sy = comp.scale.x, comp.scale.y
		dx, dy, sx, sy = _simplifyValues(dx, dy, sx, sy)
		components.append((baseName, (sx, 0, 0, sy, dx, dy)))
	return components

def test():
	g = fl.glyph
	g.Clear()

	p = PLPen(g)
	p.moveTo((50, 50))
	p.lineTo((150,50))
	p.lineTo((170, 200), smooth=2)
	p.curveTo((173, 225), (150, 250), (120, 250), smooth=1)
	p.curveTo((85, 250), (50, 200), (50, 200))
	p.closePath()

	p.moveTo((300, 300))
	p.lineTo((400, 300))
	p.curveTo((450, 325), (450, 375), (400, 400))
	p.qCurveTo((400, 500), (350, 550), (300, 500), (300, 400))
	p.closePath()
	p.setWidth(600)
	p.setNote("Hello, this is a note")
	p.addAnchor("top", (250, 600))

	fl.UpdateGlyph(-1)
	fl.UpdateFont(-1)

if __name__ == "__main__":
	test()
<commit_msg>FLPointContourPen as an alternative to FLPointPen. FLPointContourPen ignores the components. In some situations adding a component to a fl glyphs makes FontLab crash. <commit_after>"""Pens for creating glyphs in FontLab."""

__all__ = ["FLPen", "FLPointPen", "drawFLGlyphOntoPointPen"]

from FL import *

try:
	from fl_cmd import *
except ImportError:
	print "The fl_cmd module is not available here. flPen.py"

from robofab.tools.toolsFL import NewGlyph
from robofab.pens.pointPen import AbstractPointPen
from robofab.pens.adapterPens import SegmentToPointPen

def roundInt(x):
	return int(round(x))

class FLPen(SegmentToPointPen):

	def __init__(self, glyph):
		SegmentToPointPen.__init__(self, FLPointPen(glyph))

class FLPointPen(AbstractPointPen):

	def __init__(self, glyph):
		if hasattr(glyph, "isRobofab"):
			self.glyph = glyph.naked()
		else:
			self.glyph = glyph
		self.currentPath = None

	def beginPath(self):
		self.currentPath = []

	def endPath(self):
		# Love is... abstracting away FL's madness.
		path = self.currentPath
		self.currentPath = None
		glyph = self.glyph
		if len(path) == 1 and path[0][3] is not None:
			# Single point on the contour, it has a name. Make it an anchor.
			x, y = path[0][0]
			name = path[0][3]
			anchor = Anchor(name, roundInt(x), roundInt(y))
			glyph.anchors.append(anchor)
			return
		firstOnCurveIndex = None
		for i in range(len(path)):
			if path[i][1] is not None:
				firstOnCurveIndex = i
				break
		if firstOnCurveIndex is None:
			# TT special case: on-curve-less contour. FL doesn't support that,
			# so we insert an implied point at the end.
			x1, y1 = path[0][0]
			x2, y2 = path[-1][0]
			impliedPoint = 0.5 * (x1 + x2), 0.5 * (y1 + y2)
			path.append((impliedPoint, "qcurve", True, None))
			firstOnCurveIndex = 0
		path = path[firstOnCurveIndex + 1:] + path[:firstOnCurveIndex + 1]
		firstPoint, segmentType, smooth, name = path[-1]
		closed = True
		if segmentType == "move":
			path = path[:-1]
			closed = False
			# XXX The contour is not closed, but I can't figure out how to
			# create an open contour in FL. Creating one by hand shows type"0x8011"
			# for a move node in an open contour, but I'm not able to access
			# that flag.
		elif segmentType == "line":
			# The contour is closed and ends in a lineto, which is redundant
			# as it's implied by closepath.
			path = path[:-1]
		x, y = firstPoint
		node = Node(nMOVE, Point(roundInt(x), roundInt(y)))
		if smooth and closed:
			if segmentType == "line" or path[0][1] == "line":
				node.alignment = nFIXED
			else:
				node.alignment = nSMOOTH
		glyph.Insert(node, len(glyph))
		segment = []
		nPoints = len(path)
		for i in range(nPoints):
			pt, segmentType, smooth, name = path[i]
			segment.append(pt)
			if segmentType is None:
				continue
			if segmentType == "curve":
				if len(segment) < 2:
					segmentType = "line"
				elif len(segment) == 2:
					segmentType = "qcurve"
			if segmentType == "qcurve":
				for x, y in segment[:-1]:
					glyph.Insert(Node(nOFF, Point(roundInt(x), roundInt(y))), len(glyph))
				x, y = segment[-1]
				node = Node(nLINE, Point(roundInt(x), roundInt(y)))
				glyph.Insert(node, len(glyph))
			elif segmentType == "curve":
				if len(segment) == 3:
					cubicSegments = [segment]
				else:
					from fontTools.pens.basePen import decomposeSuperBezierSegment
					cubicSegments = decomposeSuperBezierSegment(segment)
				nSegments = len(cubicSegments)
				for i in range(nSegments):
					pt1, pt2, pt3 = cubicSegments[i]
					x, y = pt3
					node = Node(nCURVE, Point(roundInt(x), roundInt(y)))
					node.points[1].x, node.points[1].y = roundInt(pt1[0]), roundInt(pt1[1])
					node.points[2].x, node.points[2].y = roundInt(pt2[0]), roundInt(pt2[1])
					if i != nSegments - 1:
						node.alignment = nSMOOTH
					glyph.Insert(node, len(self.glyph))
			elif segmentType == "line":
				assert len(segment) == 1, segment
				x, y = segment[0]
				node = Node(nLINE, Point(roundInt(x), roundInt(y)))
				glyph.Insert(node, len(glyph))
			else:
				assert 0, "unsupported curve type (%s)" % segmentType
			if smooth:
				if i + 1 < nPoints or closed:
					# Can't use existing node, as you can't change node attributes
					# AFTER it's been appended to the glyph.
					node = glyph[-1]
					if segmentType == "line" or path[(i+1) % nPoints][1] == "line":
						# tangent
						node.alignment = nFIXED
					else:
						# curve
						node.alignment = nSMOOTH
			segment = []
		if closed:
			# we may have output a node too much
			node = glyph[-1]
			if node.type == nLINE and (node.x, node.y) == (roundInt(firstPoint[0]), roundInt(firstPoint[1])):
				glyph.DeleteNode(len(glyph) - 1)

	def addPoint(self, pt, segmentType=None, smooth=None, name=None, **kwargs):
		self.currentPath.append((pt, segmentType, smooth, name))

	def addComponent(self, baseName, transformation):
		assert self.currentPath is None
		# make base glyph if needed, Component() needs the index
		NewGlyph(self.glyph.parent, baseName)
		baseIndex = self.glyph.parent.FindGlyph(baseName)
		if baseIndex == -1:
			raise KeyError, "couldn't find or make base glyph"
		xx, xy, yx, yy, dx, dy = transformation
		# XXX warn when xy or yx != 0
		new = Component(baseIndex, Point(dx, dy), Point(xx, yy))
		self.glyph.components.append(new)

def drawFLGlyphOntoPointPen(flGlyph, pen):
	"""Draw a FontLab glyph onto a PointPen."""
	for anchor in flGlyph.anchors:
		pen.beginPath()
		pen.addPoint((anchor.x, anchor.y), name=anchor.name)
		pen.endPath()
	for contour in _getContours(flGlyph):
		pen.beginPath()
		for pt, segmentType, smooth in contour:
			pen.addPoint(pt, segmentType=segmentType, smooth=smooth)
		pen.endPath()
	for baseGlyph, tranform in _getComponents(flGlyph):
		pen.addComponent(baseGlyph, tranform)

class FLPointContourPen(FLPointPen):
	"""Same as FLPointPen, except that it ignores components."""
	def addComponent(self, baseName, transformation):
		pass

NODE_TYPES = {nMOVE: "move", nLINE: "line", nCURVE: "curve",
             nOFF: None}

def _getContours(glyph):
	contours = []
	for i in range(len(glyph)):
		node = glyph[i]
		segmentType = NODE_TYPES[node.type]
		if segmentType == "move":
			contours.append([])
		for pt in node.points[1:]:
			contours[-1].append(((pt.x, pt.y), None, False))
		smooth = node.alignment != nSHARP
		contours[-1].append(((node.x, node.y), segmentType, smooth))

	for contour in contours:
		# filter out or change the move
		movePt, segmentType, smooth = contour[0]
		assert segmentType == "move"
		lastSegmentType = contour[-1][1]
		if movePt == contour[-1][0] and lastSegmentType == "curve":
			contour[0] = contour[-1]
			contour.pop()
		elif lastSegmentType is None:
			contour[0] = movePt, "qcurve", smooth
		else:
			assert lastSegmentType in ("line", "curve")
			contour[0] = movePt, "line", smooth

		# change "line" to "qcurve" if appropriate
		previousSegmentType = "ArbitraryValueOtherThanNone"
		for i in range(len(contour)):
			pt, segmentType, smooth = contour[i]
			if segmentType == "line" and previousSegmentType is None:
				contour[i] = pt, "qcurve", smooth
			previousSegmentType = segmentType

	return contours

def _simplifyValues(*values):
	"""Given a set of numbers, convert items to ints if they are
	integer float values, eg. 0.0, 1.0."""
	newValues = []
	for v in values:
		i = int(v)
		if v == i:
			v = i
		newValues.append(v)
	return newValues

def _getComponents(glyph):
	components = []
	for comp in glyph.components:
		baseName = glyph.parent[comp.index].name
		dx, dy = comp.delta.x, comp.delta.y
		sx, sy = comp.scale.x, comp.scale.y
		dx, dy, sx, sy = _simplifyValues(dx, dy, sx, sy)
		components.append((baseName, (sx, 0, 0, sy, dx, dy)))
	return components

def test():
	g = fl.glyph
	g.Clear()

	p = PLPen(g)
	p.moveTo((50, 50))
	p.lineTo((150,50))
	p.lineTo((170, 200), smooth=2)
	p.curveTo((173, 225), (150, 250), (120, 250), smooth=1)
	p.curveTo((85, 250), (50, 200), (50, 200))
	p.closePath()

	p.moveTo((300, 300))
	p.lineTo((400, 300))
	p.curveTo((450, 325), (450, 375), (400, 400))
	p.qCurveTo((400, 500), (350, 550), (300, 500), (300, 400))
	p.closePath()
	p.setWidth(600)
	p.setNote("Hello, this is a note")
	p.addAnchor("top", (250, 600))

	fl.UpdateGlyph(-1)
	fl.UpdateFont(-1)

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


<commit_before>from hoomd import *
from hoomd import hpmc

import unittest

import math

# this script needs to be run on two ranks

# initialize with one rank per partitions
context.initialize(args="--nrank=1")

class gibbs_ensemble_test(unittest.TestCase):
    def setUp(self):
        p = comm.get_partition()
        phi=0.2
        a = (1/6*math.pi / phi)**(1/3)

        unitcell=lattice.sc(a=a, type_name='A')
        self.system = init.create_lattice(unitcell=unitcell, n=5)

        self.system.particles.types.add('B')
        self.mc = hpmc.integrate.sphere(seed=123+p,implicit=True)
        self.mc.set_params(d=0.1)

    def tearDown(self):
        del self.mc
        del self.system
        context.initialize()

    def test_spheres(self):
        # within two-phase region of hard spheres phase diagram
        q=0.8
        etap=0.7
        ntrial = 20
        p = comm.get_partition()

        self.mc.set_params(ntrial=ntrial)
        nR = etap/(math.pi/6.0*math.pow(q,3.0))
        self.mc.set_params(nR=nR,depletant_type='B')

        self.mc.shape_param.set('A', diameter=1.0)
        self.mc.shape_param.set('B', diameter=q)

        # needs to be run with 2 partitions
        muvt=hpmc.update.muvt(mc=self.mc,seed=456,ngibbs=2,transfer_types=['A'])

        muvt.set_params(dV=0.01)
        muvt.set_params(move_ratio=.01)

        run(100)

if __name__ == '__main__':
    unittest.main(argv = ['test.py', '-v'])
<commit_msg>Use python3 division semantics<commit_after>from __future__ import division
from hoomd import *
from hoomd import hpmc

import unittest

import math

# this script needs to be run on two ranks

# initialize with one rank per partitions
context.initialize(args="--nrank=1")

class gibbs_ensemble_test(unittest.TestCase):
    def setUp(self):
        p = comm.get_partition()
        phi=0.2
        a = (1/6*math.pi / phi)**(1/3)

        unitcell=lattice.sc(a=a, type_name='A')
        self.system = init.create_lattice(unitcell=unitcell, n=5)

        self.system.particles.types.add('B')
        self.mc = hpmc.integrate.sphere(seed=123+p,implicit=True)
        self.mc.set_params(d=0.1)

    def tearDown(self):
        del self.mc
        del self.system
        context.initialize()

    def test_spheres(self):
        # within two-phase region of hard spheres phase diagram
        q=0.8
        etap=0.7
        ntrial = 20
        p = comm.get_partition()

        self.mc.set_params(ntrial=ntrial)
        nR = etap/(math.pi/6.0*math.pow(q,3.0))
        self.mc.set_params(nR=nR,depletant_type='B')

        self.mc.shape_param.set('A', diameter=1.0)
        self.mc.shape_param.set('B', diameter=q)

        # needs to be run with 2 partitions
        muvt=hpmc.update.muvt(mc=self.mc,seed=456,ngibbs=2,transfer_types=['A'])

        muvt.set_params(dV=0.01)
        muvt.set_params(move_ratio=.01)

        run(100)

if __name__ == '__main__':
    unittest.main(argv = ['test.py', '-v'])
<|endoftext|>


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

from django.conf import settings
from django.db import migrations, models
from django.contrib.auth.models import Group , Permission

def forwards_func(apps, schema_editor):
    group = Group.objects.create(name="tada_admin")
    permissions = Permission.objects.all()
    for permission in permissions:
        group.permissions.add(permission)
    group = Group.objects.create(name="tada_deo")
    group = Group.objects.create(name="tada_dee")

    # We get the model from the versioned app registry;
    # if we directly import it, it'll be the wrong version
    # Country = apps.get_model("myapp", "Country")
    # db_alias = schema_editor.connection.alias
    # Country.objects.using(db_alias).bulk_create([
    #     Country(name="USA", code="us"),
    #     Country(name="France", code="fr"),
    # ])

def reverse_func(apps, schema_editor):
    Group.objects.get(name="tada_admin").delete()
    Group.objects.get(name="tada_deo").delete()
    Group.objects.get(name="tada_dee").delete()
    # forwards_func() creates two Country instances,
    # so reverse_func() should delete them.
    # Country = apps.get_model("myapp", "Country")
    # db_alias = schema_editor.connection.alias
    # Country.objects.using(db_alias).filter(name="USA", code="us").delete()
    # Country.objects.using(db_alias).filter(name="France", code="fr").delete()

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]
<commit_msg>Leaves a comment on the migration file<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
from django.contrib.auth.models import Group , Permission

# Initial migration for populating the db with groups and their permissions.

def forwards_func(apps, schema_editor):
    group = Group.objects.create(name="tada_admin")
    permissions = Permission.objects.all()
    for permission in permissions:
        group.permissions.add(permission)
    group = Group.objects.create(name="tada_deo")
    group = Group.objects.create(name="tada_dee")

    # We get the model from the versioned app registry;
    # if we directly import it, it'll be the wrong version
    # Country = apps.get_model("myapp", "Country")
    # db_alias = schema_editor.connection.alias
    # Country.objects.using(db_alias).bulk_create([
    #     Country(name="USA", code="us"),
    #     Country(name="France", code="fr"),
    # ])

def reverse_func(apps, schema_editor):
    Group.objects.get(name="tada_admin").delete()
    Group.objects.get(name="tada_deo").delete()
    Group.objects.get(name="tada_dee").delete()
    # forwards_func() creates two Country instances,
    # so reverse_func() should delete them.
    # Country = apps.get_model("myapp", "Country")
    # db_alias = schema_editor.connection.alias
    # Country.objects.using(db_alias).filter(name="USA", code="us").delete()
    # Country.objects.using(db_alias).filter(name="France", code="fr").delete()

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]
<|endoftext|>


<commit_before># Ridiculously simple test of the winsound module for Windows.

import unittest
from test import test_support
import winsound, time
import os
import subprocess

class BeepTest(unittest.TestCase):
    # As with PlaySoundTest, incorporate the _have_soundcard() check
    # into our test methods.  If there's no audio device present,
    # winsound.Beep returns 0 and GetLastError() returns 127, which
    # is: ERROR_PROC_NOT_FOUND ("The specified procedure could not
    # be found").  (FWIW, virtual/Hyper-V systems fall under this
    # scenario as they have no sound devices whatsoever  (not even
    # a legacy Beep device).)

    def test_errors(self):
        self.assertRaises(TypeError, winsound.Beep)
        self.assertRaises(ValueError, winsound.Beep, 36, 75)
        self.assertRaises(ValueError, winsound.Beep, 32768, 75)

    def test_extremes(self):
        if _have_soundcard():
            winsound.Beep(37, 75)
            winsound.Beep(32767, 75)
        else:
            self.assertRaises(RuntimeError, winsound.Beep, 37, 75)
            self.assertRaises(RuntimeError, winsound.Beep, 32767, 75)

    def test_increasingfrequency(self):
        if _have_soundcard():
            for i in xrange(100, 2000, 100):
                winsound.Beep(i, 75)

class MessageBeepTest(unittest.TestCase):

    def tearDown(self):
        time.sleep(0.5)

    def test_default(self):
        self.assertRaises(TypeError, winsound.MessageBeep, "bad")
        self.assertRaises(TypeError, winsound.MessageBeep, 42, 42)
        winsound.MessageBeep()

    def test_ok(self):
        winsound.MessageBeep(winsound.MB_OK)

    def test_asterisk(self):
        winsound.MessageBeep(winsound.MB_ICONASTERISK)

    def test_exclamation(self):
        winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)

    def test_hand(self):
        winsound.MessageBeep(winsound.MB_ICONHAND)

    def test_question(self):
        winsound.MessageBeep(winsound.MB_ICONQUESTION)

class PlaySoundTest(unittest.TestCase):

    def test_errors(self):
        self.assertRaises(TypeError, winsound.PlaySound)
        self.assertRaises(TypeError, winsound.PlaySound, "bad", "bad")
        self.assertRaises(
            RuntimeError,
            winsound.PlaySound,
            "none", winsound.SND_ASYNC | winsound.SND_MEMORY
        )

    def test_alias_asterisk(self):
        if _have_soundcard():
            winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemAsterisk', winsound.SND_ALIAS
            )

    def test_alias_exclamation(self):
        if _have_soundcard():
            winsound.PlaySound('SystemExclamation', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemExclamation', winsound.SND_ALIAS
            )

    def test_alias_exit(self):
        if _have_soundcard():
            winsound.PlaySound('SystemExit', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemExit', winsound.SND_ALIAS
            )

    def test_alias_hand(self):
        if _have_soundcard():
            winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemHand', winsound.SND_ALIAS
            )

    def test_alias_question(self):
        if _have_soundcard():
            winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemQuestion', winsound.SND_ALIAS
            )

    def test_alias_fallback(self):
        # This test can't be expected to work on all systems.  The MS
        # PlaySound() docs say:
        #
        #     If it cannot find the specified sound, PlaySound uses the
        #     default system event sound entry instead.  If the function
        #     can find neither the system default entry nor the default
        #     sound, it makes no sound and returns FALSE.
        #
        # It's known to return FALSE on some real systems.

        # winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS)
        return

    def test_alias_nofallback(self):
        if _have_soundcard():
            # Note that this is not the same as asserting RuntimeError
            # will get raised:  you cannot convert this to
            # self.assertRaises(...) form.  The attempt may or may not
            # raise RuntimeError, but it shouldn't raise anything other
            # than RuntimeError, and that's all we're trying to test
            # here.  The MS docs aren't clear about whether the SDK
            # PlaySound() with SND_ALIAS and SND_NODEFAULT will return
            # True or False when the alias is unknown.  On Tim's WinXP
            # box today, it returns True (no exception is raised).  What
            # we'd really like to test is that no sound is played, but
            # that requires first wiring an eardrum class into unittest
            # <wink>.
            try:
                winsound.PlaySound(
                    '!"$%&/(#+*',
                    winsound.SND_ALIAS | winsound.SND_NODEFAULT
                )
            except RuntimeError:
                pass
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                '!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT
            )

    def test_stopasync(self):
        if _have_soundcard():
            winsound.PlaySound(
                'SystemQuestion',
                winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP
            )
            time.sleep(0.5)
            try:
                winsound.PlaySound(
                    'SystemQuestion',
                    winsound.SND_ALIAS | winsound.SND_NOSTOP
                )
            except RuntimeError:
                pass
            else: # the first sound might already be finished
                pass
            winsound.PlaySound(None, winsound.SND_PURGE)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                None, winsound.SND_PURGE
            )

def _get_cscript_path():
    """Return the full path to cscript.exe or None."""
    for dir in os.environ.get("PATH", "").split(os.pathsep):
        cscript_path = os.path.join(dir, "cscript.exe")
        if os.path.exists(cscript_path):
            return cscript_path

__have_soundcard_cache = None
def _have_soundcard():
    """Return True iff this computer has a soundcard."""
    global __have_soundcard_cache
    if __have_soundcard_cache is None:
        cscript_path = _get_cscript_path()
        if cscript_path is None:
            # Could not find cscript.exe to run our VBScript helper. Default
            # to True: most computers these days *do* have a soundcard.
            return True

        check_script = os.path.join(os.path.dirname(__file__),
                                    "check_soundcard.vbs")
        p = subprocess.Popen([cscript_path, check_script],
                             stdout=subprocess.PIPE)
        __have_soundcard_cache = not p.wait()
    return __have_soundcard_cache

def test_main():
    test_support.run_unittest(BeepTest, MessageBeepTest, PlaySoundTest)

if __name__=="__main__":
    test_main()
<commit_msg>The behaviour of winsound.Beep() seems to differ between different versions of Windows when there's either:     a) no sound card entirely     b) legacy beep driver has been disabled     c) the legacy beep driver has been uninstalled Sometimes RuntimeErrors are raised, sometimes they're not.  If _have_soundcard() returns False, don't expect winsound.Beep() to raise a RuntimeError, as this clearly isn't the case, as demonstrated by the various Win32 XP buildbots.<commit_after># Ridiculously simple test of the winsound module for Windows.

import unittest
from test import test_support
import winsound, time
import os
import subprocess

class BeepTest(unittest.TestCase):
    # As with PlaySoundTest, incorporate the _have_soundcard() check
    # into our test methods.  If there's no audio device present,
    # winsound.Beep returns 0 and GetLastError() returns 127, which
    # is: ERROR_PROC_NOT_FOUND ("The specified procedure could not
    # be found").  (FWIW, virtual/Hyper-V systems fall under this
    # scenario as they have no sound devices whatsoever  (not even
    # a legacy Beep device).)

    def test_errors(self):
        self.assertRaises(TypeError, winsound.Beep)
        self.assertRaises(ValueError, winsound.Beep, 36, 75)
        self.assertRaises(ValueError, winsound.Beep, 32768, 75)

    def test_extremes(self):
        if _have_soundcard():
            winsound.Beep(37, 75)
            winsound.Beep(32767, 75)
        else:
            # The behaviour of winsound.Beep() seems to differ between
            # different versions of Windows when there's either a) no
            # sound card entirely, b) legacy beep driver has been disabled,
            # or c) the legacy beep driver has been uninstalled.  Sometimes
            # RuntimeErrors are raised, sometimes they're not.  Meh.
            try:
                winsound.Beep(37, 75)
                winsound.Beep(32767, 75)
            except RuntimeError:
                pass

    def test_increasingfrequency(self):
        if _have_soundcard():
            for i in xrange(100, 2000, 100):
                winsound.Beep(i, 75)

class MessageBeepTest(unittest.TestCase):

    def tearDown(self):
        time.sleep(0.5)

    def test_default(self):
        self.assertRaises(TypeError, winsound.MessageBeep, "bad")
        self.assertRaises(TypeError, winsound.MessageBeep, 42, 42)
        winsound.MessageBeep()

    def test_ok(self):
        winsound.MessageBeep(winsound.MB_OK)

    def test_asterisk(self):
        winsound.MessageBeep(winsound.MB_ICONASTERISK)

    def test_exclamation(self):
        winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)

    def test_hand(self):
        winsound.MessageBeep(winsound.MB_ICONHAND)

    def test_question(self):
        winsound.MessageBeep(winsound.MB_ICONQUESTION)

class PlaySoundTest(unittest.TestCase):

    def test_errors(self):
        self.assertRaises(TypeError, winsound.PlaySound)
        self.assertRaises(TypeError, winsound.PlaySound, "bad", "bad")
        self.assertRaises(
            RuntimeError,
            winsound.PlaySound,
            "none", winsound.SND_ASYNC | winsound.SND_MEMORY
        )

    def test_alias_asterisk(self):
        if _have_soundcard():
            winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemAsterisk', winsound.SND_ALIAS
            )

    def test_alias_exclamation(self):
        if _have_soundcard():
            winsound.PlaySound('SystemExclamation', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemExclamation', winsound.SND_ALIAS
            )

    def test_alias_exit(self):
        if _have_soundcard():
            winsound.PlaySound('SystemExit', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemExit', winsound.SND_ALIAS
            )

    def test_alias_hand(self):
        if _have_soundcard():
            winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemHand', winsound.SND_ALIAS
            )

    def test_alias_question(self):
        if _have_soundcard():
            winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                'SystemQuestion', winsound.SND_ALIAS
            )

    def test_alias_fallback(self):
        # This test can't be expected to work on all systems.  The MS
        # PlaySound() docs say:
        #
        #     If it cannot find the specified sound, PlaySound uses the
        #     default system event sound entry instead.  If the function
        #     can find neither the system default entry nor the default
        #     sound, it makes no sound and returns FALSE.
        #
        # It's known to return FALSE on some real systems.

        # winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS)
        return

    def test_alias_nofallback(self):
        if _have_soundcard():
            # Note that this is not the same as asserting RuntimeError
            # will get raised:  you cannot convert this to
            # self.assertRaises(...) form.  The attempt may or may not
            # raise RuntimeError, but it shouldn't raise anything other
            # than RuntimeError, and that's all we're trying to test
            # here.  The MS docs aren't clear about whether the SDK
            # PlaySound() with SND_ALIAS and SND_NODEFAULT will return
            # True or False when the alias is unknown.  On Tim's WinXP
            # box today, it returns True (no exception is raised).  What
            # we'd really like to test is that no sound is played, but
            # that requires first wiring an eardrum class into unittest
            # <wink>.
            try:
                winsound.PlaySound(
                    '!"$%&/(#+*',
                    winsound.SND_ALIAS | winsound.SND_NODEFAULT
                )
            except RuntimeError:
                pass
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                '!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT
            )

    def test_stopasync(self):
        if _have_soundcard():
            winsound.PlaySound(
                'SystemQuestion',
                winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP
            )
            time.sleep(0.5)
            try:
                winsound.PlaySound(
                    'SystemQuestion',
                    winsound.SND_ALIAS | winsound.SND_NOSTOP
                )
            except RuntimeError:
                pass
            else: # the first sound might already be finished
                pass
            winsound.PlaySound(None, winsound.SND_PURGE)
        else:
            self.assertRaises(
                RuntimeError,
                winsound.PlaySound,
                None, winsound.SND_PURGE
            )

def _get_cscript_path():
    """Return the full path to cscript.exe or None."""
    for dir in os.environ.get("PATH", "").split(os.pathsep):
        cscript_path = os.path.join(dir, "cscript.exe")
        if os.path.exists(cscript_path):
            return cscript_path

__have_soundcard_cache = None
def _have_soundcard():
    """Return True iff this computer has a soundcard."""
    global __have_soundcard_cache
    if __have_soundcard_cache is None:
        cscript_path = _get_cscript_path()
        if cscript_path is None:
            # Could not find cscript.exe to run our VBScript helper. Default
            # to True: most computers these days *do* have a soundcard.
            return True

        check_script = os.path.join(os.path.dirname(__file__),
                                    "check_soundcard.vbs")
        p = subprocess.Popen([cscript_path, check_script],
                             stdout=subprocess.PIPE)
        __have_soundcard_cache = not p.wait()
    return __have_soundcard_cache

def test_main():
    test_support.run_unittest(BeepTest, MessageBeepTest, PlaySoundTest)

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


<commit_before>"""
Copyright 2013 Steven Diamond

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from cvxpy.atoms.cummax import cummax
from cvxpy.atoms.dist_ratio import dist_ratio
from cvxpy.atoms.eye_minus_inv import eye_minus_inv, resolvent
from cvxpy.atoms.geo_mean import geo_mean
from cvxpy.atoms.gen_lambda_max import gen_lambda_max
from cvxpy.atoms.harmonic_mean import harmonic_mean
from cvxpy.atoms.lambda_max import lambda_max
from cvxpy.atoms.lambda_min import lambda_min
from cvxpy.atoms.lambda_sum_largest import lambda_sum_largest
from cvxpy.atoms.lambda_sum_smallest import lambda_sum_smallest
from cvxpy.atoms.length import length
from cvxpy.atoms.log_det import log_det
from cvxpy.atoms.log_sum_exp import log_sum_exp
from cvxpy.atoms.matrix_frac import matrix_frac
from cvxpy.atoms.matrix_frac import MatrixFrac
from cvxpy.atoms.max import max
from cvxpy.atoms.min import min
from cvxpy.atoms.norm import norm, norm2
from cvxpy.atoms.norm1 import norm1
from cvxpy.atoms.norm_inf import norm_inf
from cvxpy.atoms.norm_nuc import normNuc
from cvxpy.atoms.mixed_norm import mixed_norm
from cvxpy.atoms.norm1 import norm1
from cvxpy.atoms.norm_inf import norm_inf
from cvxpy.atoms.one_minus_pos import one_minus_pos
from cvxpy.atoms.one_minus_pos import diff_pos
from cvxpy.atoms.pf_eigenvalue import pf_eigenvalue
from cvxpy.atoms.pnorm import pnorm, Pnorm
from cvxpy.atoms.prod import prod, Prod
from cvxpy.atoms.quad_form import quad_form, QuadForm
from cvxpy.atoms.quad_over_lin import quad_over_lin
from cvxpy.atoms.sigma_max import sigma_max
from cvxpy.atoms.sign import sign
from cvxpy.atoms.sum_largest import sum_largest
from cvxpy.atoms.sum_smallest import sum_smallest
from cvxpy.atoms.sum_squares import sum_squares
from cvxpy.atoms.total_variation import tv

from cvxpy.atoms.affine.bmat import bmat
from cvxpy.atoms.affine.conj import conj
from cvxpy.atoms.affine.conv import conv
from cvxpy.atoms.affine.cumsum import cumsum
from cvxpy.atoms.affine.diag import diag
from cvxpy.atoms.affine.diff import diff
from cvxpy.atoms.affine.hstack import hstack
from cvxpy.atoms.affine.imag import imag
from cvxpy.atoms.affine.kron import kron
from cvxpy.atoms.affine.binary_operators import multiply, matmul, scalar_product
from cvxpy.atoms.affine.promote import promote
from cvxpy.atoms.affine.real import real
from cvxpy.atoms.affine.reshape import reshape, deep_flatten
from cvxpy.atoms.affine.sum import sum
from cvxpy.atoms.affine.trace import trace
from cvxpy.atoms.affine.upper_tri import upper_tri
from cvxpy.atoms.affine.vec import vec
from cvxpy.atoms.affine.vstack import vstack

from cvxpy.atoms.elementwise.abs import abs
from cvxpy.atoms.elementwise.ceil import ceil, floor
from cvxpy.atoms.elementwise.entr import entr
from cvxpy.atoms.elementwise.exp import exp
from cvxpy.atoms.elementwise.huber import huber
from cvxpy.atoms.elementwise.inv_pos import inv_pos
from cvxpy.atoms.elementwise.kl_div import kl_div
from cvxpy.atoms.elementwise.log import log
from cvxpy.atoms.elementwise.log1p import log1p
from cvxpy.atoms.elementwise.logistic import logistic
from cvxpy.atoms.elementwise.maximum import maximum
from cvxpy.atoms.elementwise.minimum import minimum
from cvxpy.atoms.elementwise.neg import neg
from cvxpy.atoms.elementwise.pos import pos
from cvxpy.atoms.elementwise.power import power
from cvxpy.atoms.elementwise.scalene import scalene
from cvxpy.atoms.elementwise.sqrt import sqrt
from cvxpy.atoms.elementwise.square import square

# TODO(akshayka): Perhaps couple this information with the atom classes
# themselves.
SOC_ATOMS = [
    geo_mean,
    pnorm,
    Pnorm,
    QuadForm,
    quad_over_lin,
    power,
]

EXP_ATOMS = [
    log_sum_exp,
    log_det,
    entr,
    exp,
    kl_div,
    log,
    log1p,
    logistic,
]

PSD_ATOMS = [
    lambda_max,
    lambda_sum_largest,
    log_det,
    MatrixFrac,
    normNuc,
    sigma_max,
]

NONPOS_ATOMS = [
    norm1,
    abs
]
<commit_msg>expose transpose<commit_after>"""
Copyright 2013 Steven Diamond

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from cvxpy.atoms.cummax import cummax
from cvxpy.atoms.dist_ratio import dist_ratio
from cvxpy.atoms.eye_minus_inv import eye_minus_inv, resolvent
from cvxpy.atoms.geo_mean import geo_mean
from cvxpy.atoms.gen_lambda_max import gen_lambda_max
from cvxpy.atoms.harmonic_mean import harmonic_mean
from cvxpy.atoms.lambda_max import lambda_max
from cvxpy.atoms.lambda_min import lambda_min
from cvxpy.atoms.lambda_sum_largest import lambda_sum_largest
from cvxpy.atoms.lambda_sum_smallest import lambda_sum_smallest
from cvxpy.atoms.length import length
from cvxpy.atoms.log_det import log_det
from cvxpy.atoms.log_sum_exp import log_sum_exp
from cvxpy.atoms.matrix_frac import matrix_frac
from cvxpy.atoms.matrix_frac import MatrixFrac
from cvxpy.atoms.max import max
from cvxpy.atoms.min import min
from cvxpy.atoms.norm import norm, norm2
from cvxpy.atoms.norm1 import norm1
from cvxpy.atoms.norm_inf import norm_inf
from cvxpy.atoms.norm_nuc import normNuc
from cvxpy.atoms.mixed_norm import mixed_norm
from cvxpy.atoms.norm1 import norm1
from cvxpy.atoms.norm_inf import norm_inf
from cvxpy.atoms.one_minus_pos import one_minus_pos
from cvxpy.atoms.one_minus_pos import diff_pos
from cvxpy.atoms.pf_eigenvalue import pf_eigenvalue
from cvxpy.atoms.pnorm import pnorm, Pnorm
from cvxpy.atoms.prod import prod, Prod
from cvxpy.atoms.quad_form import quad_form, QuadForm
from cvxpy.atoms.quad_over_lin import quad_over_lin
from cvxpy.atoms.sigma_max import sigma_max
from cvxpy.atoms.sign import sign
from cvxpy.atoms.sum_largest import sum_largest
from cvxpy.atoms.sum_smallest import sum_smallest
from cvxpy.atoms.sum_squares import sum_squares
from cvxpy.atoms.total_variation import tv

from cvxpy.atoms.affine.bmat import bmat
from cvxpy.atoms.affine.conj import conj
from cvxpy.atoms.affine.conv import conv
from cvxpy.atoms.affine.cumsum import cumsum
from cvxpy.atoms.affine.diag import diag
from cvxpy.atoms.affine.diff import diff
from cvxpy.atoms.affine.hstack import hstack
from cvxpy.atoms.affine.imag import imag
from cvxpy.atoms.affine.kron import kron
from cvxpy.atoms.affine.binary_operators import multiply, matmul, scalar_product
from cvxpy.atoms.affine.promote import promote
from cvxpy.atoms.affine.real import real
from cvxpy.atoms.affine.reshape import reshape, deep_flatten
from cvxpy.atoms.affine.sum import sum
from cvxpy.atoms.affine.trace import trace
from cvxpy.atoms.affine.transpose import transpose
from cvxpy.atoms.affine.upper_tri import upper_tri
from cvxpy.atoms.affine.vec import vec
from cvxpy.atoms.affine.vstack import vstack

from cvxpy.atoms.elementwise.abs import abs
from cvxpy.atoms.elementwise.ceil import ceil, floor
from cvxpy.atoms.elementwise.entr import entr
from cvxpy.atoms.elementwise.exp import exp
from cvxpy.atoms.elementwise.huber import huber
from cvxpy.atoms.elementwise.inv_pos import inv_pos
from cvxpy.atoms.elementwise.kl_div import kl_div
from cvxpy.atoms.elementwise.log import log
from cvxpy.atoms.elementwise.log1p import log1p
from cvxpy.atoms.elementwise.logistic import logistic
from cvxpy.atoms.elementwise.maximum import maximum
from cvxpy.atoms.elementwise.minimum import minimum
from cvxpy.atoms.elementwise.neg import neg
from cvxpy.atoms.elementwise.pos import pos
from cvxpy.atoms.elementwise.power import power
from cvxpy.atoms.elementwise.scalene import scalene
from cvxpy.atoms.elementwise.sqrt import sqrt
from cvxpy.atoms.elementwise.square import square

# TODO(akshayka): Perhaps couple this information with the atom classes
# themselves.
SOC_ATOMS = [
    geo_mean,
    pnorm,
    Pnorm,
    QuadForm,
    quad_over_lin,
    power,
]

EXP_ATOMS = [
    log_sum_exp,
    log_det,
    entr,
    exp,
    kl_div,
    log,
    log1p,
    logistic,
]

PSD_ATOMS = [
    lambda_max,
    lambda_sum_largest,
    log_det,
    MatrixFrac,
    normNuc,
    sigma_max,
]

NONPOS_ATOMS = [
    norm1,
    abs
]
<|endoftext|>


<commit_before>import deepchem
import numpy as np
import tensorflow as tf
import unittest
from deepchem.models.tensorgraph.models import unet
from deepchem.models.tensorgraph import layers

class TestUNet(unittest.TestCase):

  def test_unet(self):
    unet2D = deepchem.models.tensorgraph.models.unet.UNet(
        learning_rate=0.003, img_rows=32, img_cols=32, model_dir='./unet/')
    # Prepare Training Data
    data = np.ones((5, 32, 32, 3))
    labels = np.ones((5, 32 * 32))
    train = deepchem.data.NumpyDataset(data, labels)
    # Train the model
    unet2D.fit(train, nb_epochs=2)
    unet2D.save()
    # Prepare the Testing data
    test_data = np.ones((2, 32, 32, 3))
    test = deepchem.data.NumpyDataset(test_data)
    # predict
    predictions = unet2D.predict(test)
    # check output shape
    assert predictions.shape == (2, 32, 32, 1)

    # new object of UNet to test if loading the model results in same predictions
    unet2D_new = deepchem.models.tensorgraph.models.unet.UNet(
        learning_rate=0.003, img_rows=32, img_cols=32, model_dir='./unet/')
    unet2D_new.load_from_dir('./unet/')
    unet2D_new.restore()
    predictions_new = unet2D_new.predict(test)

    assert np.all(predictions == predictions_new)
<commit_msg>replacing language level assert statements<commit_after>import deepchem
import numpy as np
import tensorflow as tf
import unittest
from deepchem.models.tensorgraph.models import unet
from deepchem.models.tensorgraph import layers

class TestUNet(unittest.TestCase):

  def test_unet(self):
    unet2D = deepchem.models.tensorgraph.models.unet.UNet(
        learning_rate=0.003, img_rows=32, img_cols=32, model_dir='./unet/')
    # Prepare Training Data
    data = np.ones((5, 32, 32, 3))
    labels = np.ones((5, 32 * 32))
    train = deepchem.data.NumpyDataset(data, labels)
    # Train the model
    unet2D.fit(train, nb_epochs=2)
    unet2D.save()
    # Prepare the Testing data
    test_data = np.ones((2, 32, 32, 3))
    test = deepchem.data.NumpyDataset(test_data)
    # predict
    predictions = unet2D.predict(test)
    # check output shape
    self.assertEqual(predictions.shape, (2, 32, 32, 1))

    # new object of UNet to test if loading the model results in same predictions
    unet2D_new = deepchem.models.tensorgraph.models.unet.UNet(
        learning_rate=0.003, img_rows=32, img_cols=32, model_dir='./unet/')
    unet2D_new.load_from_dir('./unet/')
    unet2D_new.restore()
    predictions_new = unet2D_new.predict(test)

    self.assertTrue(np.all(predictions == predictions_new))
<|endoftext|>


<commit_before>import tensorflow as tf
import numpy as np
import logging as log

COLS_HEADERS = "a8,b8,c8,d8,e8,f8,g8,h8,a7,b7,c7,d7,e7,f7,g7,h7,a6,b6,c6,d6,e6,f6,g6,h6,a5,b5,c5,d5,e5,f5,g5,h5,a4,b4,c4,d4,e4,f4,g4,h4,a3,b3,c3,d3,e3,f3,g3,h3,a2,b2,c2,d2,e2,f2,g2,h2,a1,b1,c1,d1,e1,f1,g1,h1,whos_move,fen,result"
CSV_COLUMNS = COLS_HEADERS.split(',')

TRAINING_DATA = "trainer/data/train-data-10000.csv"
TEST_DATA = "trainer/data/test-data-10000.csv"

def input_fn():
    # Preprocess your data here...

    # ...then return 1) a mapping of feature columns to Tensors with
    # the corresponding feature data, and 2) a Tensor containing labels
    return feature_cols, labels

# Load datasets
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=TRAINING_DATA,
      target_dtype=np.int,
      features_dtype=np.float32)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename=TEST_DATA,
      target_dtype=np.int,
      features_dtype=np.float32)

# Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape[4])]

 # Build 3 layer DNN with 10, 20, 10 units respectively
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
                                          hidden_units=[10, 20, 10],
                                          n_classes=3,
                                          model_dir="output")
# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": np.array(training_set.data)},
      y=np.array(training_set.target),
      num_epochs=None,
      shuffle=True)

# Train model
classifier.train(input_fn=train_input_fn, steps=2000)

# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": np.array(test_set.data)},
      y=np.array(test_set.target),
      num_epochs=1,
      shuffle=False)

# Evaluate accuracy
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
<commit_msg>moving back to old DNNLinearCombinedClassifer<commit_after>import tensorflow as tf
import logging as log
import pandas as pd

CSV_COLUMNS = ['a1','b1','c1','d1','e1','f1','g1','h1','a2','b2','c2','d2','e2','f2','g2','h2','a3','b3','c3','d3','e3','f3','g3','h3'
,'a4','b4','c4','d4','e4','f4','g4','h4','a5','b5','c5','d5','e5','f5','g5','h5','a6','b6','c6','d6','e6','f6','g6','h6','a7',
'b7','c7','d7','e7','f7','g7','h7','a8','b8','c8','d8','e8','f8','g8','h8','whos_move','fen','result']

# ----------------------------------------------------------------------------------------
# Feature Columns:
# initialize the feature_columns to none
# ----------------------------------------------------------------------------------------
feature_columns = [ None for i in range(64) ]
for i, col in enumerate(CSV_COLUMNS):
    if i >= 64:
        break
    # each col value can be one of 13 possibilities. Whatever it is, hash it...
    feature_columns[i] = tf.feature_column.categorical_column_with_hash_bucket(col, hash_bucket_size=13)

# ----------------------------------------------------------------------------------------
# Categorical Columns:
# ----------------------------------------------------------------------------------------
whos_move = tf.feature_column.categorical_column_with_vocabulary_list("whos_move", ["w", "b"])

# !!! LABEL (CLASSIFICATION) !!!
result = tf.feature_column.categorical_column_with_vocabulary_list("result", ["1-0", "0-1", "1/2-1/2"])

# ----------------------------------------------------------------------------------------
# Linear Model (Wide)
# ----------------------------------------------------------------------------------------
base_columns = feature_columns + [whos_move]
crossed_columns = []

# ----------------------------------------------------------------------------------------
# Neural Network (Deep)
# ----------------------------------------------------------------------------------------
deep_columns = [ tf.feature_column.indicator_column(col) for col in feature_columns ] + [tf.feature_column.indicator_column(whos_move)]

# ----------------------------------------------------------------------------------------
# input_fn()
# ----------------------------------------------------------------------------------------
def input_fn(data_file, num_epochs, shuffle):
  """Input builder function."""
  print("Reading input...")
  df_data = pd.read_csv(
      tf.gfile.Open(data_file),
      names=CSV_COLUMNS,
      verbose=True,
      skipinitialspace=True,
      engine="python",
      skiprows=1)
  # remove NaN elements
  df_data = df_data.dropna(how="any", axis=0)
  labels = df_data["result"].apply(lambda x: "1-0" in x).astype(int)
  return tf.estimator.inputs.pandas_input_fn(
      x=df_data,
      y=labels,
      batch_size=100,
      num_epochs=num_epochs,
      shuffle=shuffle,
      num_threads=5)

# ----------------------------------------------------------------------------------------
# Combine the wide and deep models into one
# ----------------------------------------------------------------------------------------
model_dir = "output"
m = tf.estimator.DNNLinearCombinedClassifier(
    model_dir=model_dir,
    linear_feature_columns=crossed_columns,
    dnn_feature_columns=deep_columns,
    dnn_hidden_units=[20,12])

# ----------------------------------------------------------------------------------------
# log the progress to the terminal
# ----------------------------------------------------------------------------------------
import logging
logging.getLogger().setLevel(logging.INFO)

# set num_epochs to None to get infinite stream of data.
m.train(
    input_fn=input_fn("data/train-data-10000.csv", num_epochs=None, shuffle=True),
    steps=100)
# set steps to None to run evaluation until all data consumed.
results = m.evaluate(
    input_fn=input_fn("data/test-data-10000.csv", num_epochs=3, shuffle=False),
    steps=None)

# print("model directory = %s" % model_dir)
# for key in sorted(results):
#     print("%s: %s" % (key, results[key]))
<|endoftext|>