Пример #1
0
class ScorePoseTask(taskbase.TaskBase):
    weights = traitlets.CUnicode(allow_none=True)
    patch = traitlets.CUnicode(allow_none=True)

    def __init__(self, weights=None, patch=None):
        super().__init__(weights=weights, patch=patch)

    def setup(self):
        self.protocol_lock = threading.Lock()

    @property
    @pyrosetta.distributed.requires_init
    @pyrosetta.distributed.with_lock
    def score_function(self):
        if not self.weights:
            return scoring.get_score_function()
        elif not self.patch:
            sff = scoring.ScoreFunctionFactory()
            return sff.create_score_function(self.weights)
        else:
            sff = scoring.ScoreFunctionFactory()
            return sff.create_score_function(self.weights, self.patch)

    @pyrosetta.distributed.requires_init
    def execute(self, pack_or_pose):
        work_pose = packed_pose.to_packed(pack_or_pose).pose
        with self.protocol_lock:
            self.score_function(work_pose)
        return packed_pose.PackedPose(work_pose)
Пример #2
0
class Bus(t.HasTraits):
    '''Bus Model'''

    name = t.CUnicode(default_value='Bus1', help='Name of Generator (str)')
    bus_type = t.Enum(
        values=['SWING', 'PQ', 'PV'],
        default_value='PQ',
        help='Bus type',
    )
    real_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Active power demand (MW)')
    imag_power_demand = tt.Array(default_value=[0.0],
                                 minlen=1,
                                 help='Reactive power demand (MVAR)')
    shunt_conductance = t.CFloat(default_value=0,
                                 help='Shunt Conductance (TODO: units)')
    shunt_susceptance = t.CFloat(default_value=0,
                                 help='Shunt Susceptance (TODO: units)')
    area = t.CUnicode(default_value='0', help='Area the bus is located in')
    voltage_magnitude = t.CFloat(default_value=1.0,
                                 help='Voltage magnitude (p.u.)')
    voltage_angle = t.CFloat(default_value=0.0, help='Voltage angle (deg)')
    base_voltage = t.CFloat(default_value=230, help='Base voltage (kV)')
    zone = t.CUnicode(default_value='0', help='Zone the bus is located in')
    maximum_voltage = t.CFloat(default_value=1.05, help='Maximum voltage')
    minimum_voltage = t.CFloat(default_value=0.95, help='Minimum voltage')

    def __init__(self, **kwargs):

        v = kwargs.pop('real_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['real_power_demand'] = v

        v = kwargs.pop('imag_power_demand', None)
        v = self._coerce_value_to_list({'value': v})
        kwargs['imag_power_demand'] = v

        super(Bus, self).__init__(**kwargs)

    @t.validate('real_power_demand', 'imag_power_demand')
    def _coerce_value_to_list(self, proposal):
        v = proposal['value']
        if (v is not None and (isinstance(v, int) or isinstance(v, float))):
            v = [
                v,
            ]
        elif v is None:
            v = [
                0.0,
            ]

        return v
Пример #3
0
class IDObject(widgets.Widget):
    """ an object with an id
    
    """
    id = HashableType()
    groups = trait.List(trait=trait.CUnicode(),
                        default_value=("all", ),
                        help='the groups that this object belongs to')
    other_info = trait.CUnicode(
        '', help='other information about the object as HTML').tag(sync=True)

    @trait.default('id')
    def _default_id(self):
        return uuid.uuid4()

    def get_object_trait_names(self):
        """ get trait names which are only associated with the object,
        i.e. not from the ipywidgets base class
        """
        base_ipywidget_traits = set(widgets.Widget().trait_names())
        all_traits = set(self.trait_names())
        return list(all_traits.difference(base_ipywidget_traits))

    def trait_series(self):
        """ create pandas.Series of objects traits
        
        Examples
        --------
        >>> obj = IDObject(id=1,other_info='test')
        >>> obj.trait_series()
        groups        (all,)
        id                 1
        other_info      test
        dtype: object
        
        """
        trait_dict = {}
        for name in self.get_object_trait_names():
            value = getattr(self, name)
            # might break series if cell value is a list
            value = tuple(value) if isinstance(value, list) else value
            trait_dict[name] = value
        return pd.Series(trait_dict)

    # def _repr_latex_(self):
    #     """
    #     """
    #     return self.trait_series().to_latex()

    def __repr__(self):
        """ visualising in jupyter notebook
        """
        return self.trait_series().to_string()
Пример #4
0
class TriclinicSolid(GeometricObject):
    """ a wireframe object

    Examples
    --------
    
    >>> box = TriclinicSolid()
    >>> box.position
    (0.0, 0.0, 0.0)
    >>> box.a
    (1.0, 0.0, 0.0)

    >>> try:
    ...     box.pivot = ''
    ... except Exception as err:
    ...     print(err)
    pivot must be at the centre or corner
        
    """
    a = Vector3(default_value=(1, 0, 0), help='box vector a').tag(sync=True)
    b = Vector3(default_value=(0, 1, 0), help='box vector b').tag(sync=True)
    c = Vector3(default_value=(0, 0, 1), help='box vector c').tag(sync=True)
    pivot = trait.CUnicode('centre',
                           help='pivot about centre or corner').tag(sync=True)

    @trait.validate('pivot')
    def _valid_pivot(self, proposal):
        pivot = proposal['value']
        if pivot not in ['centre', 'corner']:
            raise trait.TraitError('pivot must be at the centre or corner')
        return proposal['value']
Пример #5
0
class BaseRosettaScriptsTask(taskbase.TaskBase):
    @property
    @pyrosetta.distributed.requires_init
    @pyrosetta.distributed.with_lock
    def parser(self):
        if not getattr(self, "_parser", None):
            BaseRosettaScriptsTask._parser = \
                    rosetta_scripts.RosettaScriptsParser()

        return self._parser

    protocol_xml = traitlets.CUnicode()

    def __init__(self, protocol_xml):
        super().__init__(protocol_xml=protocol_xml)

    @pyrosetta.distributed.requires_init
    @pyrosetta.distributed.with_lock
    def setup(self):
        self.default_options = pyrosetta.rosetta.basic.options.process()
        self.tag = self.parser.create_tag_from_xml_string(
            self.protocol_xml, self.default_options)

        # Validate by parsing
        self.parser.parse_protocol_tag(self.tag, self.default_options)
        self.protocol_lock = threading.Lock()

    @property
    @pyrosetta.distributed.requires_init
    @pyrosetta.distributed.with_lock
    def parsed_protocol(self):
        return self.parser.parse_protocol_tag(self.tag, self.default_options)

    def execute(self, pack_or_pose):
        return packed_pose.to_packed(self.apply(pack_or_pose))
Пример #6
0
class VertexAttribute(traitlets.HasTraits):
    name = traitlets.CUnicode("attr")
    id = traitlets.CInt(-1)
    data = traittypes.Array(None, allow_none=True)
    each = traitlets.CInt(-1)
    opengl_type = traitlets.CInt(GL.GL_FLOAT)
    divisor = traitlets.CInt(0)

    @traitlets.default("id")
    def _id_default(self):
        return GL.glGenBuffers(1)

    @contextmanager
    def bind(self, program=None):
        loc = -1
        if program is not None:
            loc = GL.glGetAttribLocation(program.program, self.name)
            if loc >= 0:
                GL.glVertexAttribDivisor(loc, self.divisor)
                _ = GL.glEnableVertexAttribArray(loc)
        _ = GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.id)
        if loc >= 0:
            GL.glVertexAttribPointer(loc, self.each, self.opengl_type, False, 0, None)
        yield
        if loc >= 0:
            GL.glDisableVertexAttribArray(loc)
        GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)

    @traitlets.observe("data")
    def _set_data(self, change):
        arr = change["new"]
        self.each = arr.shape[-1]
        self.opengl_type = np_to_gl[arr.dtype.name]
        with self.bind():
            GL.glBufferData(GL.GL_ARRAY_BUFFER, arr.nbytes, arr, GL.GL_STATIC_DRAW)
Пример #7
0
class VertexArray(traitlets.HasTraits):
    name = traitlets.CUnicode("vertex")
    id = traitlets.CInt(-1)
    indices = traittypes.Array(None, allow_none=True)
    index_id = traitlets.CInt(-1)
    attributes = traitlets.List(trait=traitlets.Instance(VertexAttribute))
    each = traitlets.CInt(-1)

    @traitlets.default("id")
    def _id_default(self):
        return GL.glGenVertexArrays(1)

    @contextmanager
    def bind(self, program=None):
        GL.glBindVertexArray(self.id)
        if self.index_id != -1:
            GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.index_id)
        # We only bind the attributes if we have a program too
        if program is None:
            attrs = []
        else:
            attrs = self.attributes
        with ExitStack() as stack:
            _ = [stack.enter_context(_.bind(program)) for _ in attrs]
            yield
        if self.index_id != -1:
            GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, 0)
        GL.glBindVertexArray(0)

    @traitlets.observe("indices")
    def _set_indices(self, change):
        arr = change["new"]
        self.index_id = GL.glGenBuffers(1)
        GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.index_id)
        GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, arr.nbytes, arr, GL.GL_STATIC_DRAW)
Пример #8
0
class WorkflowWidget(ipywidgets.VBox):
    """
    Widget for displaying a single `Workflow` object, with a table of its versions.

    `version` holds the currently-selected version name as a string, and can be modified.
    `current_vg` is a read-only trait holding the currently-selected `~.VersionedGraft`.
    """

    flow = traitlets.Instance(klass=Workflow, allow_none=True)
    version = traitlets.CUnicode(allow_none=True)

    current_vg = traitlets.Instance(klass=VersionedGraft,
                                    read_only=True,
                                    allow_none=True)

    def __init__(self, **kwargs):
        self._version_selector = ipywidgets.Select(layout=ipywidgets.Layout(
            width="initial"))
        super().__init__(**kwargs)
        ipywidgets.link((self._version_selector, "value"), (self, "version"))

    @traitlets.observe("flow")
    def _update_flow(self, change):
        flow = self.flow
        if flow is None:
            self.children = []
            self.version = None
            return

        info = ipywidgets.HTML(f"""
            <h2>{flow.title}</h2>
            <p><code>{flow.id}</p></code>
            <p>{"<i class='fa fa-unlock'></i> Public" if flow.has_public_reader() else "<i class='fa fa-lock'></i> Private"}</p>  # noqa: E501
            <p><b>Labels:</b> <code>{flow.labels}</code></p>
            <p><b>Tags:</b> <code>{flow.tags}</code></p>
            """)

        latest = flow.versions[-1] if flow.versions else None

        self._version_selector.options = flow.version_names[::-1]
        self._version_selector.value = latest.version if latest else None
        self._version_selector.rows = min(5, len(flow.versions))
        self.set_trait("current_vg",
                       latest)  # in case version name was the same

        desc = ipywidgets.HTML(value=_strong_to_b.sub(
            r"<\1b>", markdowner.convert(flow.description)))

        self.children = [
            info, self._version_selector,
            ipywidgets.HTML("<hr>"), desc
        ]

    @traitlets.observe("version")
    def _update_version(self, change):
        vg = (self.flow[self.version]
              if self.flow is not None and self.version is not None else None)
        self.set_trait("current_vg", vg)
Пример #9
0
class Branch(t.HasTraits):

    "Branch model"

    name = t.CUnicode(default_value='Branch1', help='Name of Branch (str)')
    from_bus = t.CUnicode(default_value='Bus1', help='Name of From Bus')
    to_bus = t.CUnicode(default_value='Bus2', help='Name of To Bus')
    resistance = t.CFloat(default_value=0, help='Branch resistance (p.u.)')
    reactance = t.CFloat(default_value=0, help='Branch reactance (p.u.)')
    susceptance = t.CFloat(default_value=0, help='Branch susceptance (p.u.)')
    rating = t.CFloat(default_value=M, help='Branch Rating')
    status = t.CBool(default_value=1, help='Branch status')
    angle_minimum = t.CFloat(default_value=0.0, help='Branch angle minimum')
    angle_maximum = t.CFloat(default_value=0.0, help='Branch angle maximum')
    tap = t.CFloat(default_value=None, allow_none=True)
    shift = t.CFloat(default_value=None, allow_none=True)
    from_real_power_flow = t.CFloat(default_value=None, allow_none=True, help='From active power flow (MW)')
    from_imag_power_flow = t.CFloat(default_value=None, allow_none=True, help='From reactive power flow (MVAR)')
    to_real_power_flow = t.CFloat(default_value=None, allow_none=True, help='To active power flow (MW)')
    to_imag_power_flow = t.CFloat(default_value=None, allow_none=True, help='To reactive power flow (MVAR)')
Пример #10
0
class Base(WXYZBase):
    """Utility traitlets, primarily based around
    - development convenience
    - ipywidgets conventions
    - integration with wxyz.lab.DockBox, mostly lumino Widget.label attrs
    """

    _model_module = T.Unicode(module_name).tag(sync=True)
    _model_module_version = T.Unicode(module_version).tag(sync=True)
    _view_module = T.Unicode(module_name).tag(sync=True)
    _view_module_version = T.Unicode(module_version).tag(sync=True)

    error = T.CUnicode("").tag(sync=True)  # type: str
    description = T.Unicode("An Undescribed Widget").tag(
        sync=True)  # type: str
    icon_class = T.Unicode("jp-CircleIcon").tag(sync=True)  # type: str
    closable = T.Bool(default_value=True).tag(sync=True)  # type: bool
Пример #11
0
class TextAnnotation(SceneAnnotation):

    name = "text_annotation"
    data = traitlets.Instance(TextCharacters)
    text = traitlets.CUnicode()
    draw_instructions = traitlets.List()
    origin = traitlets.Tuple(traitlets.CFloat(),
                             traitlets.CFloat(),
                             default_value=(-1, -1))
    scale = traitlets.CFloat(1.0)

    @traitlets.observe("text")
    def _observe_text(self, change):
        text = change["new"]
        lines = text.split("\n")
        draw_instructions = []
        y = 0
        for line in reversed(lines):
            x = 0
            dy = 0
            for c in line:
                e = self.data.characters[c]
                draw_instructions.append((x, y, e.texture, e.vbo_offset))
                dy = max(dy, e.vert_advance)
                x += e.hori_advance
            y += dy
        self.draw_instructions = draw_instructions

    def _set_uniforms(self, scene, shader_program):
        pass

    def draw(self, scene, program):
        viewport = np.array(GL.glGetIntegerv(GL.GL_VIEWPORT), dtype="f4")
        program._set_uniform("viewport", viewport)
        each = self.data.vertex_array.each
        for x, y, tex, vbo_offset in self.draw_instructions:
            with tex.bind(0):
                program._set_uniform("x_offset", float(x))
                program._set_uniform("y_offset", float(y))
                program._set_uniform("x_origin", self.origin[0])
                program._set_uniform("y_origin", self.origin[1])
                program._set_uniform("scale", self.scale)
                GL.glDrawArrays(GL.GL_TRIANGLES, vbo_offset * each, each)
Пример #12
0
class ColormapTexture(Texture1D):
    colormap_name = traitlets.CUnicode()

    def __init__(self, *args, **kwargs):
        # Override...
        kwargs["boundary_x"] = "clamp"
        super(ColormapTexture, self).__init__(*args, **kwargs)

    @traitlets.validate("colormap_name")
    def _validate_name(self, proposal):
        try:
            cm.get_cmap(proposal["value"])
        except ValueError:
            raise traitlets.TraitError(
                "Colormap name needs to be known by" "matplotlib"
            )
        return proposal["value"]

    @traitlets.observe("colormap_name")
    def _observe_colormap_name(self, change):
        cmap = cm.get_cmap(change["new"])
        cmap_vals = np.array(cmap(np.linspace(0, 1, 256)), dtype="f4")
        self.data = cmap_vals
Пример #13
0
class GeometricObject(IDObject):
    """ a geometric object
    x,y,z should represent the centre of volume
    
    Examples
    --------
    
    >>> gobject = GeometricObject()
    >>> gobject.position
    (0.0, 0.0, 0.0)
    
    """
    position = Vector3(default_value=(0, 0, 0),
                       help='cartesian coordinate of pivot').tag(sync=True)

    visible = trait.Bool(True).tag(sync=True)
    color = Color('red').tag(sync=True)
    transparency = trait.CFloat(1, min=0.0, max=1.0).tag(sync=True)

    label = trait.CUnicode('-').tag(sync=True).tag(sync=True)
    label_visible = trait.Bool(False).tag(sync=True)
    label_color = Color('red').tag(sync=True)
    label_transparency = trait.CFloat(1, min=0.0, max=1.0).tag(sync=True)
class CText(widgets.Text):
    value = traitlets.CUnicode(help="String value",
                               allow_none=True).tag(sync=True)
Пример #15
0
class Shader(traitlets.HasTraits):
    """
    Creates a shader from source

    Parameters
    ----------

    source : str
        This can either be a string containing a full source of a shader,
        an absolute path to a source file or a filename of a shader
        residing in the ./shaders/ directory.

    """

    _shader = None
    source = traitlets.Any()
    shader_name = traitlets.CUnicode()
    info = traitlets.CUnicode()
    shader_type = traitlets.CaselessStrEnum(("vertex", "fragment", "geometry"))
    blend_func = traitlets.Tuple(GLValue(),
                                 GLValue(),
                                 default_value=("src alpha", "dst alpha"))
    blend_equation = GLValue("func add")
    depth_test = GLValue("always")

    use_separate_blend = traitlets.Bool(False)
    blend_equation_separate = traitlets.Tuple(GLValue(),
                                              GLValue(),
                                              default_value=("none", "none"))
    blend_func_separate = traitlets.Tuple(
        GLValue(),
        GLValue(),
        GLValue(),
        GLValue(),
        default_value=("none", "none", "none", "none"),
    )

    def _get_source(self, source):
        if ";" in source:
            # This is probably safe, right?  Enh, probably.
            return source
        # What this does is concatenate multiple (if available) source files.
        # This gets around GLSL's composition issues, which means we can have
        # functions that get called at each step in a ray tracing process, for
        # instance, that can still share ray tracing code between multiple
        # files.
        if not isinstance(source, (tuple, list)):
            source = (source, )
        source = (
            "header.inc.glsl",
            "known_uniforms.inc.glsl",
        ) + tuple(source)
        full_source = []
        for fn in source:
            if os.path.isfile(fn):
                sh_directory = ""
            else:
                sh_directory = os.path.join(os.path.dirname(__file__),
                                            "shaders")
            fn = os.path.join(sh_directory, fn)
            if not os.path.isfile(fn):
                raise YTInvalidShaderType(fn)
            full_source.append(open(fn, "r").read())
        return "\n\n".join(full_source)

    def _enable_null_shader(self):
        source = _NULL_SOURCES[self.shader_type]
        self.compile(source=source)

    def compile(self, source=None, parameters=None):
        if source is None:
            source = self.source
            if source is None:
                raise RuntimeError
        if parameters is not None:
            raise NotImplementedError
        source = self._get_source(source)
        shader_type_enum = getattr(GL, f"GL_{self.shader_type.upper()}_SHADER")
        shader = GL.glCreateShader(shader_type_enum)
        # We could do templating here if we wanted.
        self.shader_source = source
        GL.glShaderSource(shader, source)
        GL.glCompileShader(shader)
        result = GL.glGetShaderiv(shader, GL.GL_COMPILE_STATUS)
        if not (result):
            raise RuntimeError(GL.glGetShaderInfoLog(shader))
        self._shader = shader

    def setup_blend(self):
        GL.glEnable(GL.GL_BLEND)
        if self.use_separate_blend:
            GL.glBlendEquationSeparate(*self.blend_equation_separate)
            GL.glBlendFuncSeparate(*self.blend_func_separate)
        else:
            GL.glBlendEquation(self.blend_equation)
            GL.glBlendFunc(*self.blend_func)
        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glDepthFunc(self.depth_test)

    @property
    def shader(self):
        if self._shader is None:
            try:
                self.compile()
            except RuntimeError as exc:
                print(exc)
                for line_num, line in enumerate(
                        self.shader_source.split("\n")):
                    print(f"{line_num + 1:05}: {line}")
                self._enable_null_shader()
        return self._shader

    def delete_shader(self):
        if None not in (self._shader, GL.glDeleteShader):
            GL.glDeleteShader(self._shader)
            self._shader = None

    def __del__(self):
        # This is not guaranteed to be called
        self.delete_shader()
Пример #16
0
class Generator(t.HasTraits):
    '''Generator Model'''

    name = t.CUnicode(default_value='GenCo0', help='Name of Generator (str)')
    generator_bus = t.CUnicode(default_value='Bus0',
                               help='Bus of Generator (str)')
    generator_voltage = t.CFloat(
        default_value=1.0, help='Nominal voltage of the generator (p.u.)')
    base_power = t.CFloat(default_value=100.0,
                          help='Base power of the generator (MVA)')
    generation_type = t.Enum(['COAL', 'NATURALGAS', 'WIND'],
                             default_value='COAL')
    minimum_up_time = t.CInt(default_value=0,
                             min=0,
                             help='Minimum up time (hrs)')
    minimum_down_time = t.CInt(default_value=0,
                               min=0,
                               help='Minimum down time (hrs)')
    ramp_up_rate = t.CFloat(default_value=0,
                            min=0,
                            help='Ramp up rate (MW/hr)')
    ramp_down_rate = t.CFloat(default_value=0,
                              min=0,
                              help='Ramp down rate (MW/hr)')
    maximum_real_power = t.CFloat(default_value=0,
                                  min=0,
                                  help='Capacity of Generator (MW)')
    minimum_real_power = t.CFloat(default_value=0,
                                  min=0,
                                  help='Minimum generation (MW)')
    maximum_imag_power = t.CFloat(default_value=0,
                                  help='Maximum reactive generation (MVAR)')
    minimum_imag_power = t.CFloat(default_value=0,
                                  help='Minimum reactive generation (MVAR)')
    initial_real_power = t.CFloat(default_value=0,
                                  min=0,
                                  help='Initial power generation (MW)')
    initial_imag_power = t.CFloat(default_value=0,
                                  min=0,
                                  help='Initial power generation (MVAR)')
    initial_status = t.CBool(default_value=True,
                             min=0,
                             help='Initial status (bool)')
    startup_time = t.CInt(default_value=0, min=0, help='Startup time (hrs)')
    shutdown_time = t.CInt(default_value=0, min=0, help='Shutdown time (hrs)')
    nsegments = t.CInt(default_value=2,
                       min=MINIMUM_COST_CURVE_SEGMENTS,
                       max=MAXIMUM_COST_CURVE_SEGMENTS,
                       help='Number of data points for piecewise linear')
    cost_curve_points = tt.Array(default_value=[0, 0, 0],
                                 minlen=(MINIMUM_COST_CURVE_SEGMENTS + 1),
                                 maxlen=(MAXIMUM_COST_CURVE_SEGMENTS + 1))
    cost_curve_values = tt.Array(default_value=[0, 0, 0],
                                 minlen=(MINIMUM_COST_CURVE_SEGMENTS + 1),
                                 maxlen=(MAXIMUM_COST_CURVE_SEGMENTS + 1))
    noload_cost = t.CFloat(default_value=0,
                           min=0,
                           help='No-Load Cost of a Generator ($/hr)')
    startup_cost = t.CFloat(default_value=0,
                            min=0,
                            help='Startup Cost of a Generator ($/hr)')
    inertia = t.CFloat(allow_none=True,
                       default_value=None,
                       min=0,
                       help='Inertia of generator (NotImplemented)')
    droop = t.CFloat(allow_none=True,
                     default_value=None,
                     min=0,
                     help='Droop of generator (NotImplemented)')

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

    @property
    def _npoints(self):
        return self.nsegments + 1

    @property
    def ramp_rate(self):
        raise AttributeError(
            "'{class_name}' object has no attribute 'ramp_rate'. Try 'ramp_up_rate' or 'ramp_down_rate'."
            .format(class_name=self.__class__.__name__))

    @ramp_rate.setter
    def ramp_rate(self, v):
        self.ramp_up_rate = v
        self.ramp_down_rate = v

    @t.observe('noload_cost')
    def _callback_noload_cost_update_points_values(self, change):

        self.cost_curve_values = [change['new']] * self._npoints

        return change['new']

    @t.observe('minimum_real_power')
    def _callback_minimum_real_power_update_points_values(self, change):

        self.cost_curve_points = np.linspace(change['new'],
                                             self.maximum_real_power,
                                             self._npoints)

        return change['new']

    @t.observe('maximum_real_power')
    def _callback_maximum_real_power_update_points_values(self, change):

        self.cost_curve_points = np.linspace(self.minimum_real_power,
                                             change['new'], self._npoints)

        self.ramp_rate = self.maximum_real_power

        return change['new']

    @t.observe('nsegments')
    def _callback_nsegments_update_points_values(self, change):

        self.cost_curve_points = np.linspace(self.minimum_real_power,
                                             self.maximum_real_power,
                                             change['new'] + 1)
        self.cost_curve_values = [self.noload_cost] * (change['new'] + 1)

        return change['new']

    @t.validate('cost_curve_points', 'cost_curve_values')
    def _validate_max_length(self, proposal):
        if not len(proposal['value']) == self._npoints:
            raise t.TraitError(
                'len({class_name}().{trait_name}) must be equal to {class_name}().nsegments + 1. Proposed {trait_name} is {proposal}'
                .format(class_name=proposal['owner'].__class__.__name__,
                        trait_name=proposal['trait'].name,
                        proposal=proposal['value']))

        return proposal['value']

    @t.validate('ramp_up_rate', 'ramp_down_rate', 'initial_real_power',
                'initial_imag_power')
    def _less_than_maximum_real_power_check(self, proposal):
        if not proposal['value'] <= self.maximum_real_power:
            raise t.TraitError(
                '{class_name}().{trait_name} must be a less than or equal to {class_name}().maximum_real_power.'
                .format(class_name=proposal['owner'].__class__.__name__,
                        trait_name=proposal['trait'].name))
        else:
            return proposal['value']
Пример #17
0
class Watchdog(widgets.Widget):
    path = traitlets.CUnicode(".", sync=True)
    description = traitlets.CUnicode(sync=True)
    value = traitlets.Any(sync=True)
    recursive = traitlets.CBool(False, sync=True)
    watching = traitlets.CBool(False, sync=True)
    poll_interval = traitlets.CInt(1, sync=True)
    last_event = traitlets.Dict(sync=True)
    file = traitlets.CUnicode(sync=True)

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

        self._wd_handlers = widgets.CallbackDispatcher()
        self._wd_observer = None
        self.on_msg(self._handle_wd_msg)

    def __del__(self):
        self.stop()
        super(Watchdog, self).__del__()

    def _handle_wd_msg(self, _, content, buffers):
        """ Be very careful here: inspecting the messages in the
            browser may be the only way to find problems
        """
        self.last_event = content
        event = content.get('event', None)
        if event is None:
            return
        if (not self.file) or fnmatch(content["src_path"], self.file):
            self._wd_handlers(self, content)

    def on_any(self, callback, remove=False):
        self._wd_handlers.register_callback(callback, remove=remove)

    def ls(self):
        return glob.glob(os.path.join(self.path, self.file or "*.*"))

    def touch(self, idx=0):
        os.utime(self.ls()[idx], None)

    def start(self):
        self.stop()

        ip = get_ipython()

        self._wd_observer = subprocess.Popen(map(str, [
            sys.executable, "-m", "ipywatchdogwidget.observe", "--model-id",
            self.model_id, "--path",
            os.path.abspath(self.path), "--poll-interval", self.poll_interval,
            "--port", ip.kernel._recorded_ports["shell"], "--recursive",
            self.recursive, "--session-key",
            ip.kernel.session.key.decode()
        ]),
                                             stderr=subprocess.STDOUT)
        self.watching = True

    def stop(self):
        if self._wd_observer:
            parent = psutil.Process(self._wd_observer.pid)
            [child.kill() for child in parent.children(recursive=True)]
            parent.kill()
            self._wd_observer = None
        self.watching = False
Пример #18
0
def create_jsmesh_view(gobject, mapping=None, jslink=False):
    """create PyThreeJS Mesh for GeometricObjects
    and with one-way synchronisation
    
    Properties
    ----------
    gobject : GeometricObject
    mapping : None or dict
        if None, use default gobject->jsobject mapping
    jslink : bool
        if True, where possible, create client side links
        http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#The-difference-between-linking-in-the-kernel-and-linking-in-the-client 
    
    Examples
    --------
    
    >>> import pandas3js as pjs
    >>> sphere = pjs.models.Sphere()
    >>> mesh = pjs.views.create_jsmesh_view(sphere)
    >>> mesh.position
    [0.0, 0.0, 0.0]
    >>> str(mesh.material.color)
    '#ff0000'
    
    >>> sphere.position = (1,0,0)
    >>> mesh.position
    [1.0, 0.0, 0.0]
    
    >>> sphere.color = (1,1,1)
    >>> str(mesh.material.color)
    '#ffffff'
    
    >>> lmesh = create_jsmesh_view(pjs.models.Box())
    >>> lmesh = create_jsmesh_view(pjs.models.Line())
    >>> bsmesh = create_jsmesh_view(pjs.models.TriclinicSolid())
    >>> bwmesh = create_jsmesh_view(pjs.models.TriclinicWire())
    >>> cmesh = create_jsmesh_view(pjs.models.Circle())
    >>> mesh = create_jsmesh_view(pjs.models.Octahedron())
    >>> mesh = create_jsmesh_view(pjs.models.Icosahedron())
    >>> mesh = create_jsmesh_view(pjs.models.Plane())
    
    """
    if jslink:
        direct_link = widget.jsdlink
    else:
        direct_link = trait.dlink

    class_str = obj_to_str(gobject)
    if hasattr(gobject, '_use_default_viewmap'):
        class_map = copy.deepcopy(gobject_jsmapping['default'])
        class_map['grep'] = 'pythreejs.{}Geometry'.format(
            class_str.split('.')[-1])
        # directly link all traits to geometry object traits
        for trait_name in gobject.class_own_traits():
            class_map['gdmap'][trait_name] = trait_name
        if gobject._use_default_viewmap is not None:
            class_map['show_label'] = True
            class_map['label_height'] = gobject._use_default_viewmap
    elif not class_str in gobject_jsmapping:
        raise ValueError(
            'No pythreejs mapping available for {}'.format(class_str))
    else:
        class_map = gobject_jsmapping[class_str]

    # create geometry
    geometry = str_to_obj(class_map['grep'])()

    for key, val in class_map['gvar'].items():
        geometry.set_trait(key, val)
    for key, val in class_map['gdmap'].items():
        direct_link((gobject, val), (geometry, key))
    for gkey, gdic in class_map['gfmap'].items():
        handle = _create_trait_dlink(gdic, gkey, gobject, geometry)
        gobject.observe(handle, names=gdic['vars'])

    # create material
    material = str_to_obj(class_map['matrep'])()

    for key, val in class_map['matvar'].items():
        material.set_trait(key, val)
    for key, val in class_map['matdmap'].items():
        direct_link((gobject, val), (material, key))
    for mkey, mdic in class_map['matfmap'].items():
        handle = _create_trait_dlink(mdic, mkey, gobject, material)
        gobject.observe(handle, names=mdic['vars'])

    # create mesh
    mesh = str_to_obj(class_map['meshrep'])(geometry=geometry,
                                            material=material)

    for key, val in class_map['meshvar'].items():
        mesh.set_trait(key, val)
    for key, val in class_map['meshdmap'].items():
        direct_link((gobject, val), (mesh, key))
    for skey, sdic in class_map['meshfmap'].items():
        handle = _create_trait_dlink(sdic, skey, gobject, mesh)
        gobject.observe(handle, names=sdic['vars'])

    # add special traits
    mesh.add_traits(gobject_id=HashableType())
    mesh.gobject_id = gobject.id
    mesh.add_traits(other_info=trait.CUnicode().tag(sync=True))
    direct_link((gobject, 'other_info'), (mesh, 'other_info'))

    return mesh
Пример #19
0
def create_jslabelmesh_view(gobject, mapping=None, jslink=False):
    """create PyThreeJS Text Mesh for GeometricObject
    and with one-way synchronisation

    Properties
    ----------
    gobject : GeometricObject
    mapping : None or dict
        if None, use default gobject->jsobject mapping
    jslink : bool
        if True, where possible, create client side links
        http://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#The-difference-between-linking-in-the-kernel-and-linking-in-the-client 

    Examples
    --------
    
    >>> import pandas3js as pjs
    >>> sphere = pjs.models.Sphere()
    >>> lmesh = pjs.views.create_jslabelmesh_view(sphere)
    >>> lmesh.position
    [0.0, 0.0, 0.0]
    >>> str(lmesh.material.map.string)
    '-'
    >>> lmesh.scale
    [1.0, 1.0, 1.0]
    
    >>> sphere.position = (1,0,0)
    >>> lmesh.position
    [1.0, 0.0, 0.0]
    
    >>> sphere.label = 'test'
    >>> str(lmesh.material.map.string)
    'test'
                  
    >>> sphere.radius = 3.0
    >>> lmesh.scale
    [1.0, 3.0, 1.0]
    
    """
    if jslink:
        direct_link = widget.jsdlink
    else:
        direct_link = trait.dlink

    class_str = obj_to_str(gobject)
    if hasattr(gobject, '_use_default_viewmap'):
        class_map = copy.deepcopy(gobject_jsmapping['default'])
        class_map['grep'] = 'pythreejs.' + class_str.split('.')[-1]
        # directly link all traits to geometry object
        for trait_name in gobject.class_own_traits():
            class_map['gdmap'][trait_name] = trait_name
        if gobject._use_default_viewmap is not None:
            class_map['show_label'] = True
            class_map['label_height'] = gobject._use_default_viewmap
    elif not class_str in gobject_jsmapping:
        raise ValueError(
            'No pythreejs mapping available for {}'.format(class_str))
    else:
        class_map = gobject_jsmapping[class_str]

    text_map = js.TextTexture(string=gobject.label,
                              color=colors.to_hex(gobject.label_color),
                              size=100,
                              squareTexture=False)
    material = js.SpriteMaterial(map=text_map,
                                 opacity=gobject.label_transparency,
                                 transparent=False,
                                 depthTest=False,
                                 depthWrite=True)
    height = class_map['label_height']
    height_attr = getattr(gobject, height) if isinstance(
        height, basestring) else height
    mesh = js.Sprite(material=material,
                     position=gobject.position,
                     scaleToTexture=True,
                     scale=[1, height_attr, 1])

    # add special traits
    mesh.add_traits(gobject_id=HashableType())
    mesh.gobject_id = gobject.id
    mesh.add_traits(other_info=trait.CUnicode().tag(sync=True))

    if not class_map['show_label']:
        mesh.visible = False
        return mesh

    # add directional synchronisation
    direct_link((gobject, 'other_info'), (mesh, 'other_info'))
    direct_link((gobject, 'label'), (text_map, 'string'))
    direct_link((gobject, 'position'), (mesh, 'position'))
    direct_link((gobject, 'label_visible'), (mesh, 'visible'))
    direct_link((gobject, 'label_transparency'), (material, 'opacity'))
    trait.dlink((gobject, 'label_color'), (text_map, 'color'), colors.to_hex)
    trait.dlink((gobject, 'label_transparency'), (material, 'transparent'),
                lambda t: True if t <= 0.999 else False)

    if isinstance(height, basestring):

        def change_height(change):
            mesh.scale = [1, change.new, 1]

        gobject.observe(change_height, names=height)

    return mesh
Пример #20
0
import os
import argparse

import traitlets as ts
ts.CUnicode('Ni').tag(sync=True)


def reverse_str(s):
    if not isinstance(s, str):
        return None
    res = ""
    for i in range(len(s)):
        res = res + s[len(s) - i - 1]
    return res


VOWEL_LETTERS = ('a', 'e', 'i', 'o', 'u')


def pig(s):
    if not isinstance(s, str):
        return None
    res = ""
    for i in range(len(s)):
        res = res + s[len(s) - i - 1]
    return res


if __name__ == "__main__":
    s = input("Please input a string: \n")
    print(reverse_str(s))