text:
import time
import math
import random
import gym
from gym import spaces
import numpy as np
import grpc

# MQTT Topic for RIP
from codes.b_environments.quanser_rotary_inverted_pendulum import quanser_service_pb2_grpc
from codes.b_environments.quanser_rotary_inverted_pendulum import blender_service_pb2_grpc
from codes.e_utils.names import RLAlgorithmName, AgentMode
from common.environments.environment import Environment
from codes.a_config.parameters import PARAMETERS as params
from codes.b_environments.quanser_rotary_inverted_pendulum.quanser_service_pb2 import QuanserRequest
from codes.b_environments.quanser_rotary_inverted_pendulum.blender_service_pb2 import BlenderRequest
from concurrent import futures
STATE_SIZE = 6

balance_motor_power_list = [-60., 0., 60.]
BLOWING_ACTION_RATE = 0.0004

# if params.SERVER_IDX == 3:
#     RIP_SERVER = '10.0.0.4'
# elif params.SERVER_IDX == 2:
#     RIP_SERVER = '10.0.0.5'

def get_quanser_rip_observation_space():
    if params.QUANSER_STATE_INFO == 0:
        low = np.array([0, 0, 0, 0, 0, 0], dtype=np.float32)
        high = np.array([1., 1., 500., 1., 1., 500.], dtype=np.float32)
    elif params.QUANSER_STATE_INFO == 1:
        low = np.array([0, 0, 0], dtype=np.float32)
        high = np.array([1., 1., 500.], dtype=np.float32)
    elif params.QUANSER_STATE_INFO == 2:
        low = np.array([0, 0, 0, 0], dtype=np.float32)
        high = np.array([1., 1., 500., 500.], dtype=np.float32)
    else:
        raise ValueError()

    observation_space = gym.spaces.Box(
        low=low, high=high, dtype=np.float32
    )
    n_states = observation_space.shape[0]
    return observation_space, n_states

def get_quanser_rip_action_info(params):
    if params.RL_ALGORITHM in [RLAlgorithmName.DQN_V0]:
        action_index_to_voltage = list(np.array([
            -1.0, -0.75, -0.5, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0
        ]) * params.ACTION_SCALE)
        action_space = gym.spaces.Discrete(len(action_index_to_voltage))
        num_outputs = 1
        action_n = action_space.n
        action_min = 0
        action_max = action_space.n - 1
    else:
        action_index_to_voltage = None
        action_space = gym.spaces.Box(
            low=-1.0, high=1.0, shape=(1,),
            dtype=np.float32
        )
        num_outputs = action_space.shape[0]
        action_n = None
        action_min = action_space.low
        action_max = action_space.high

    return action_space, num_outputs, action_n, action_min, action_max, action_index_to_voltage

class EnvironmentQuanserRIP(gym.Env):
    def __init__(self, mode=AgentMode.TRAIN):
        super(EnvironmentQuanserRIP, self).__init__()
        self.next_time_step_of_external_blow = int(random.expovariate(BLOWING_ACTION_RATE))

        self.episode = 0

        self.params = params

        self.previous_time = time.perf_counter()
        self.state_space_shape = (STATE_SIZE,)
        self.action_space_shape = (len(balance_motor_power_list),)

        self.env_reset = False

        self.reward = 0

        self.step_idx = 0
        self.state = []
        self.episode_steps = 0

        self.count_continuous_uprights = 0
        self.is_upright = False

        self.motor_radian = 0
        self.motor_velocity = 0
        self.pendulum_radian = 0
        self.pendulum_velocity = 0

        self.is_motor_limit = False

        self.unit_time = self.params.UNIT_TIME
        self.over_unit_time = 0

        if mode == AgentMode.PLAY:
            self.max_episode_step = self.params.MAX_EPISODE_STEP_AT_PLAY
        else:
            self.max_episode_step = self.params.MAX_EPISODE_STEP

        self.initial_motor_radian = 0.0
        #==================observation==========================================================
        self.observation_space, self.n_states = get_quanser_rip_observation_space()
        #=======================================================================================

        #==================action===============================================================
        self.action_space, self.num_outputs, self.action_n, self.action_min, self.action_max, \
        self.action_index_to_voltage                                                                                = get_quanser_rip_action_info(self.params)
        #=======================================================================================

        channel = grpc.insecure_channel('{0}:50051'.format(RIP_SERVER))
        self.server_obj = quanser_service_pb2_grpc.QuanserRIPStub(channel)

        channel_blender = grpc.insecure_channel('{0}:50051'.format('192.168.0.5'))
        self.server_obj_blender = blender_service_pb2_grpc.BlenderRIPStub(channel_blender)

        self.test_mode = False

        print(self.max_episode_step)

    def get_n_states(self):
        if params.QUANSER_STATE_INFO == 0:
            n_states = 6
        elif params.QUANSER_STATE_INFO == 1:
            n_states = 3
        elif params.QUANSER_STATE_INFO == 2:
            n_states = 4
        else:
            raise ValueError()
        return n_states

    def get_state_shape(self):
        state_shape = (2,)
        return state_shape

    def get_action_shape(self):
        action_shape = (3,)
        return action_shape

    @property
    def action_meanings(self):
        action_meanings = ["LEFT", "STOP", "RIGHT"]
        return action_meanings

    @property
    def action_meanings(self):
        action_meanings = ["LEFT", "STOP", "RIGHT"]
        return action_meanings

    # def pendulum_reset(self):
    #     quanser_response = self.server_obj.step(QuanserRequest(value=0.0))
    #     if quanser_response.message != "PENDULUM_RESET":
    #         raise ValueError()

    def reset(self):
        self.episode_steps = 0
        self.reward = 0
        self.is_motor_limit = False

        quanser_response = self.server_obj.reset(QuanserRequest(value=0.0))

        if quanser_response.message != "RESET":
            raise ValueError()

        if self.step_idx == 0:
            print("next_time_step_of_external_blow: {0}".format(
                self.next_time_step_of_external_blow
            ))

        self.motor_radian = quanser_response.motor_radian
        self.motor_velocity = quanser_response.motor_velocity
        self.pendulum_radian = quanser_response.pendulum_radian
        self.pendulum_velocity = quanser_response.pendulum_velocity

        # if self.episode % 5 == 0:
        #     print("** [EPISODE: {0}] RESET PENDULUM RADIAN : {1:6.3f}, "
        #           "math.cos(self.pendulum_radian): {2:6.3f}, math.sin(self.pendulum_radian): {3:6.3f}".format(
        #         self.episode,
        #         self.pendulum_radian,
        #         math.cos(self.pendulum_radian),
        #         math.sin(self.pendulum_radian),
        #     ))

        if self.params.QUANSER_STATE_INFO == 0:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                math.cos(quanser_response.motor_radian),
                math.sin(quanser_response.motor_radian),
                self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        elif self.params.QUANSER_STATE_INFO == 1:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                # math.cos(quanser_response.motor_radian),
                # math.sin(quanser_response.motor_radian),
                # self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        elif self.params.QUANSER_STATE_INFO == 2:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                # math.cos(quanser_response.motor_radian),
                # math.sin(quanser_response.motor_radian),
                self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        else:
            raise ValueError()
        # wait_time = 1 if self.episode == 0 else 15  # if self.episode % 10 == 0 else 3
        # wait_time = 1
        # previousTime = time.perf_counter()
        # time_done = False
        # while not time_done:
        #     currentTime = time.perf_counter()
        #     if currentTime - previousTime >= wait_time:
        #         time_done = True
        #     time.sleep(0.001)

        self.initial_motor_radian = self.motor_radian
        self.is_motor_limit = False
        self.episode += 1

        return np.asarray(self.state)

    def step(self, action):
        # current_time = time.perf_counter()
        # print("current_time - self.previous_time", current_time - self.previous_time)
        while True:
            current_time = time.perf_counter()
            if current_time - self.previous_time >= self.unit_time:
                break
            time.sleep(0.0001)

        current_time = time.perf_counter()
        step_time = current_time - self.previous_time

        if step_time > self.unit_time:
            self.over_unit_time += 1

        # print(self.step_idx, action, step_time)
        self.previous_time = time.perf_counter()

        if self.step_idx % 100000 == 0:
            print("*OVER UNIT TIME STEP NUMBER :", self.over_unit_time)
        #######################################################

        if self.step_idx >= self.next_time_step_of_external_blow:
            if self.params.RL_ALGORITHM in [
                RLAlgorithmName.DQN_V0, RLAlgorithmName.DISCRETE_A2C_V0, RLAlgorithmName.DISCRETE_PPO_V0
            ]:
                action = random.randint(a=0, b=len(self.action_index_to_voltage)-1)
                action = action * self.action_index_to_voltage[action] * 2.0
            elif self.params.RL_ALGORITHM in [
                RLAlgorithmName.DDPG_V0,
                RLAlgorithmName.CONTINUOUS_A2C_V0,
                RLAlgorithmName.CONTINUOUS_PPO_V0,
                RLAlgorithmName.TD3_V0,
                RLAlgorithmName.CONTINUOUS_SAC_V0,
            ]:
                action = random.uniform(a=-1.0, b=1.0)
                action = action * self.params.ACTION_SCALE * 2.0
            else:
                raise ValueError()

            self.next_time_step_of_external_blow = self.step_idx + int(random.expovariate(BLOWING_ACTION_RATE))
            print("[{0:6}/{1}] External Blow: {2:7.5f}, next_time_step_of_external_blow: {3}".format(
                self.step_idx + 1,
                self.params.MAX_GLOBAL_STEP,
                action,
                self.next_time_step_of_external_blow
            ))
        else:
            action = action[0]
            if self.params.RL_ALGORITHM in [RLAlgorithmName.DQN_V0]:
                action = self.action_index_to_voltage[int(action)]
            elif self.params.RL_ALGORITHM in [
                RLAlgorithmName.DDPG_V0,
                RLAlgorithmName.CONTINUOUS_A2C_V0,
                RLAlgorithmName.CONTINUOUS_PPO_V0,
                RLAlgorithmName.TD3_V0,
                RLAlgorithmName.CONTINUOUS_SAC_V0,
            ]:
                action = action * self.params.ACTION_SCALE

        #motor_power = float(action)
        # if self.step_idx % 100 == 0:
        #     print(action)

        #==================== Grpc and use sample time========================================
        # previous_time = time.perf_counter()
        quanser_response = self.server_obj.step(QuanserRequest(value=action))
        # print(motor_power)
        # if quanser_response.message != "STEP":
        #     raise ValueError()
        # while True:
        #     current_time = time.perf_counter()
        #     if current_time - previous_time >= 25 / 1000:
        #         break
        #     time.sleep(0.0001)
        #=====================================================================================

        self.motor_radian = quanser_response.motor_radian
        self.motor_velocity = quanser_response.motor_velocity
        self.pendulum_radian = quanser_response.pendulum_radian
        self.pendulum_velocity = quanser_response.pendulum_velocity
        self.is_motor_limit = quanser_response.is_motor_limit
        # print("motor: ", self.motor_radian)
        # print("===========transfer time : {0:1.6f} action : {1:3.2f}".format(previous_time - time.perf_counter(), action))
        # print("motor radian : {0:1.3f}, motor velocity : {1:1.3f}, pendulum radian : {2:1.3f}, pendulum velocity : {3:1.3f}".format(
        #     math.degrees(self.motor_radian), self.motor_velocity,
        #       self.pendulum_radian, self.pendulum_velocity
        #     ))
        # print("is motor limit", self.is_motor_limit)

        if self.params.QUANSER_STATE_INFO == 0:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                math.cos(quanser_response.motor_radian),
                math.sin(quanser_response.motor_radian),
                self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        elif self.params.QUANSER_STATE_INFO == 1:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                # math.cos(quanser_response.motor_radian),
                # math.sin(quanser_response.motor_radian),
                # self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        elif self.params.QUANSER_STATE_INFO == 2:
            self.state = [
                math.cos(self.pendulum_radian),
                math.sin(self.pendulum_radian),
                self.pendulum_velocity / params.VELOCITY_STATE_DENOMINATOR,
                # math.cos(0.0),
                # math.sin(0.0),
                # math.cos(quanser_response.motor_radian),
                # math.sin(quanser_response.motor_radian),
                self.motor_velocity / params.VELOCITY_STATE_DENOMINATOR
            ]
        else:
            raise ValueError()
        next_state = np.asarray(self.state)

        self.update_current_state()

        done, info = self.__isDone()

        #=======================reward================================================================
        self.reward = self.get_reward(action)
        # print(self.reward, self.pendulum_radian)
        #=============================================================================================
        self.step_idx += 1
        self.episode_steps += 1

        # print("pendulum radian : {0}, motor radian: {1}, reward: {2}, pendulum_velocity : {3} \n\n".format(
        #     self.pendulum_radian, self.motor_radian, self.is_motor_limit, self.pendulum_velocity
        # ))

        #######################################blender grpc###########################################
        # blender_response = self.server_obj_blender.step_blender(BlenderRequest(
        #     idx=IDX, pendulum_1_radian=math.degrees(self.pendulum_radian), motor_radian=math.degrees(self.motor_radian),
        #     pendulum_2_radian=0
        # ))
        # if not blender_response.is_receive:
        #     raise ValueError()
        ###############################################################################################

        return next_state, self.reward, done, info

    def blender(self):
        blender_response = self.server_obj_blender.step_blender(BlenderRequest(
            idx=IDX, pendulum_1_radian=math.degrees(self.pendulum_radian), motor_radian=math.degrees(self.motor_radian),
            pendulum_2_radian=0
        ))
        if not blender_response.is_receive:
            raise ValueError()

    def __isDone(self):
        info = {}

        def insert_to_info(s):
            info["result"] = s

        if self.episode_steps >= self.max_episode_step: # 5000 * 25ms (0.025sec.) = 125 sec.
            insert_to_info("*** Success ***")
            return True, info
        # elif self.is_motor_limit:
        #     print(self.motor_radian, " !!!!!!!")
        #     insert_to_info("*** Limit position ***")
        #     return True, info
        elif self.is_motor_limit:#abs(self.motor_radian) > math.radians(90) or self.is_motor_limit:
            insert_to_info("***motor_radian exceed 90***")
            return True, info
        else:
            insert_to_info("")
            return False, info

    def update_current_state(self):
        if abs(self.pendulum_radian) < math.radians(90):
            self.count_continuous_uprights += 1
        else:
            self.count_continuous_uprights = 0

        if self.count_continuous_uprights >= 1:
            self.is_upright = True
        else:
            self.is_upright = False

    # def get_reward(self):
    #     if abs(self.pendulum_radian) > math.radians(30):
    #         position_reward = 0.0
    #     else:
    #         if self.is_upright:
    #             position_reward = math.pi - abs(self.pendulum_radian)  # math.pi - math.radians(12) ~ math.pi
    #         else:
    #             if self.is_motor_limit:
    #                 position_reward = 0.0
    #             else:
    #                 position_reward = (math.pi - abs(self.pendulum_radian)) / 2
    #
    #     energy_penalty = 2.0 * -1.0 * (abs(self.pendulum_velocity) + abs(self.motor_velocity)) / 100
    #
    #     reward = position_reward + energy_penalty
    #
    #     reward = max(0.0, reward)
    #
    #     return reward

    def get_reward(self, action):
        # print(self.is_upright, self.pendulum_radian, math.radians(90), action)
        if self.is_upright:
            position_reward = math.pi - abs(self.pendulum_radian)# math.pi - math.radians(12) ~ math.pi
        else:
            if self.is_motor_limit:
                position_reward = 0.0
            else:
                position_reward = (math.pi - abs(self.pendulum_radian)) / 2
                # position_reward = 1 + math.cos(self.pendulum_radian)

        energy_penalty = -1.0 * (abs(self.pendulum_velocity) + abs(self.motor_velocity)) / 100

        reward = position_reward + energy_penalty

        reward = max(0.000001, reward / 1)

        # open ai pendulum reward = -(theta^2 + 0.1theta_dt^2 + 0.001action^2)
        # reward = -((self.pendulum_radian**2) + 0.1*((self.pendulum_velocity/100)**2) + 0.001*(((2*action)/params.ACTION_SCALE)**2))

        # print(position_reward, energy_penalty, reward)

        return reward

    def render(self):
        pass


text:
# -*- coding: utf-8 -*-

# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This is the main module that defines what a QComponent is in Qiskit Metal.

To see the docstring of QComponent, use:
    >> ?QComponent

"""

import logging
import inspect
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Iterable, List, Union, Tuple, Dict as Dict_

import pandas as pd
import numpy as np
from ... import draw
from ... import is_design, logger
from ...draw import BaseGeometry
from ...toolbox_python.attr_dict import Dict
from ._parsed_dynamic_attrs import ParsedDynamicAttributes_Component
from ...toolbox_python.display import format_dict_ala_z
from datetime import datetime
from ... import config
if not config.is_building_docs():
    from ...draw import Vector

__all__ = ['QComponent']

if TYPE_CHECKING:
    # For linting typechecking, import modules that can't be loaded here under normal conditions.
    # For example, I can't import QDesign, because it requires QComponent first. We have the
    # chicken and egg issue.
    from ...designs import QDesign
    import matplotlib

class QComponent():
    """
    `QComponent` is the base class for all Metal components and is the
    central construct from which all components in Metal are derived.

    The class defines the user interface for working with components.

    For front-end user:
        * Manipulates the dictionary of options (stored as string-string key-value
          pairs) to change the geometry and properties of the component.
        * The options of the class are stored in an options dictionary. These
          include the geometric sizes, such as width='10um' or height='5mm', etc.
        * The `make` function parses these strings and implements the logic required
          to transform the dictionary of options (stored as strings) into shapes
          with associated properties.

    For creator user:
        * The creator user implements the `make` function (see above)
        * The class define the internal representation of a components
        * The class provides the interfaces for the component (creator user)

    Default Options:
        Nested default options can be overwritten with the update function.
        The following code demonstrates how the update works.

        .. code-block:: python
            :linenos:

            from qiskit_metal import Dict
            default = Dict(
                a=1,
                b=2,
                c=Dict(
                    d=3,
                    e=4,
                    f=Dict(
                        g=6,
                        h=7
                    )
                )
            )
            overwrite = Dict(
                a=10,
                b=20,
                c=Dict(
                    d=30,
                    f=Dict(
                        h=70
                    )
                ),
                z=33
            )
            default.update(overwrite)
            default

        >> {'a': 10, 'b': 20, 'c': {'d': 30, 'e': 4, 'f': {'g': 6, 'h': 70}}, 'z': 33}
    """

    default_options = Dict(
        # Note: If something is added here, _gather_all_children_options(cls) needs to be changed.
        # Intended for future use, for components that do not normally take pins as inputs
        # to be able to have an input pin and be moved/rotated based on said input.
        # pin_inputs = Dict()
    )
    """Default drawing options"""

    component_metadata = Dict()
    """Component metadata"""

    options = {}
    """A dictionary of the component-designer-defined options.
    These options are used in the make function to create the QGeometry and QPins.
    All options should have string keys and preferrable string values.
    """

    # Dummy private attribute used to check if an instanciated object is
    # indeed a QComponent class. The problem is that the `isinstance`
    # built-in method fails when this module is reloaded.
    # Used by `is_component` to check.
    __i_am_component__ = True

    def __init__(self,
                 design: 'QDesign',
                 name: str = None,
                 options: Dict = None,
                 make=True,
                 component_template: Dict = None) -> Union[None, str]:
        """Create a new Metal component and adds it's default_options to the design.

        Arguments:
            design (QDesign): The parent design.
            name (str): Name of the component. Auto-named if possible.
            options (dict): User options that will override the defaults.  Defaults to None.
            make (bool): True if the make function should be called at the end of the init.
                Options be used in the make function to create the geometry.  Defaults to True.
            component_template (dict): User can overwrite the template options for the component
                that will be stored in the design, in design.template,
                and used every time a new component is instantiated.  Defaults to None.

        Raises:
            ValueError: User supplied design isn't a QDesign

        Note:  Information copied from QDesign class.
            self._design.overwrite_enabled (bool):
            When True - If the string name, used for component, already
            exists in the design, the existing component will be
            deleted from design, and new component will be generated
            with the same name and newly generated component_id,
            and then added to design.

            When False - If the string name, used for component, already
            exists in the design, the existing component will be
            kept in the design, and current component will not be generated,
            nor will be added to the design. The variable design.self.status
            will still be NotBuilt, as opposed to Initialization Successful.

            Either True or False - If string name, used for component, is NOT
            being used in the design, a component will be generated and
            added to design using the name.
        """

        # Make the id be None, which means it hasn't been added to design yet.
        self._id = None
        self._made = False

        # Status: used to handle building of a component and checking if it succeeded or failed.
        self.status = 'Not Built'
        if not is_design(design):
            raise ValueError(
                "Error you did not pass in a valid Metal QDesign object as a '\
                'parent of this QComponent.")

        self._design = design  # reference to parent

        if self._delete_evaluation(name) is 'NameInUse':
            return

        self._name = name
        self._class_name = self._get_unique_class_name()  # Full class name

        #: A dictionary of the component-designer-defined options.
        #: These options are used in the make function to create the QGeometry and QPins.
        #: All options should have string keys and preferrable string values.
        self.options = self.get_template_options(
            design=design, component_template=component_template)
        if options:
            self.options.update(options)

        # Parser for options
        self.p = ParsedDynamicAttributes_Component(self)

        # Should put this earlier so could pass in other error messages?
        self._error_message = ''
        if self._check_pin_inputs():
            self.logger.warning(self._error_message)
            return

        # Build and component internals

        #: Dictionary of pins. Populated by component designer in make function using `add_pin`.
        self.pins = Dict()

        #: Metadata allows a designer to store extra information or analysis results.
        self.metadata = Dict()

        # Add the component to the parent design
        self._id = self.design._get_new_qcomponent_id()  # Create the unique id
        self._add_to_design()  # Do this after the pin checking?

        #: Stores the latest status of the component. Values include:
        #: ``Initialization Successful``, ``Build Failed``, etc.
        self.status = 'Initialization Successful'

        # Used for short name, and renderers adding information to tables.
        self.a_metadata = self._gather_all_children_metadata()

        # Auto naming - add id to component based on type
        if name is None:
            prefix = self.a_metadata
            # limit names to 24 characters
            name_trunc = 24
            # if no prefix, use class name
            if "short_name" not in prefix:
                short_name = self.__class__.__name__[:name_trunc]
            else:
                short_name = prefix['short_name'][:name_trunc]
            name_id = self.design._get_new_qcomponent_name_id(short_name)
            # rename loop to make sure that no components manually named by the user conflicts
            while self.design.rename_component(
                    self._id, short_name + "_" + str(name_id)) != 1:
                name_id = self.design._get_new_qcomponent_name_id(short_name)

        # Add keys for each type of table.  add_qgeometry() will update bool if the table is used.
        self.qgeometry_table_usage = Dict()
        self.populate_to_track_table_usage()

        # Make the component geometry
        if make:
            self.rebuild()

    @classmethod
    def _gather_all_children_options(cls) -> dict:
        '''
        From the base class of QComponent, traverse the child classes
        to gather the .default options for each child class.

        Collects the options starting with the basecomponent,
        and stepping through the children.
        Each child adds it's options to the base options.  If the
        key is the same, the option of the youngest child is used.

        Note: if keys are the same for child and grandchild,
        grandchild will overwrite child

        Init method.

        Returns:
            dict: options from all children
        '''

        options_from_children = {}
        parents = inspect.getmro(cls)

        # len-2: base.py is not expected to have default_options dict to add to design class.
        for child in parents[len(parents) - 2::-1]:
            # The template default options are in a class dict attribute `default_options`.
            if hasattr(child, 'default_options'):
                options_from_children = {
                    **options_from_children,
                    **child.default_options
                }

        return options_from_children

    @classmethod
    def _gather_all_children_metadata(cls) -> dict:
        '''
        From the base class of QComponent, traverse the child classes
        to gather the .default options for each child class.

        Note: if keys are the same for child and grandchild, grandchild will overwrite child
        Init method.

        Returns:
            dict: options from all children
        '''

        options_from_children = {}
        parents = inspect.getmro(cls)
        # Base.py is not expected to have default_options dict to add to design class.
        for child in parents[len(parents) - 2::-1]:
            # There is a developer agreement so the defaults will be in dict named default_options.
            if hasattr(child, 'component_metadata'):
                options_from_children = {
                    **options_from_children,
                    **child.component_metadata
                }

        return options_from_children

    @classmethod
    def _get_unique_class_name(cls) -> str:
        """Returns unique class name based on the module

        Returns:
            str: Example: 'qiskit_metal.qlibrary.qubits.transmon_pocket.TransmonPocket'
        """
        return f'{cls.__module__}.{cls.__name__}'

    @classmethod
    def _register_class_with_design(cls, design: 'QDesign', template_key: str,
                                    component_template: Dict):
        """Init function to register a component class with the design when first instantiated.
            Registers the design template options.

            Arguments:
                design (QDesign): The parent design
                template_key (str): Key to use
                component_template (dict): Template of components to copy, with renderer options
        """
        # do not overwrite
        if template_key not in design.template_options:
            # if not component_template:
            #     component_template = cls._gather_all_children_options()
            children_options = cls._gather_all_children_options()
            options_template_renderer = {
                **children_options,
                **component_template
            }
            # design.template_options[template_key] = deepcopy(
            #     component_template)
            design.template_options[template_key] = deepcopy(
                options_template_renderer)

    @property
    def name(self) -> str:
        '''Name of the component.'''
        return self._name

    @name.setter
    def name(self, new_name: str):
        '''Rename the component. Change the design dictionaries as well.
        handle components. Delete and remake.

        Returns:
            bool: True is successful, otherwise failure code
        '''
        return_code = self.design.rename_component(self.id, new_name)
        if return_code != True:
            logger.warning(
                f'In design_base.name, the new_name={new_name} was not set. ')
        return return_code

    @property
    def design(self) -> 'QDesign':
        '''Return a reference to the parent design object.

        Returns:
            QDesign: design
        '''
        return self._design

    @property
    def class_name(self) -> str:
        '''Return the full name of the class: the full module name with the class name.
        e.g., qiskit_metal.qlibrary.qubits.TransmonPocket

        Returns:
            str: Class name
        '''
        return self._class_name

    @property
    def logger(self) -> logging.Logger:
        """The Qiskit Metal Logger.

        Returns:
            logging.Logger: Logger
        """
        return self._design.logger

    @property
    def pin_names(self) -> set:
        '''The names of the pins.

        Returns:
            set: Set of pin names
        '''
        return set(self.pins.keys())

    @property
    def id(self) -> int:
        '''The unique id of component within a design.

        Returns:
            int: Component id
        '''
        return self._id

    def _add_to_design(self):
        ''' Add self to design objects dictionary. Method will obtain an unique id
        for the component within a design, THEN add itself to design.
        '''
        self.design._components[self.id] = self
        self.design.name_to_id[self.name] = self._id

    @classmethod
    def get_template_options(cls,
                             design: 'QDesign',
                             component_template: Dict = None,
                             logger_: logging.Logger = None,
                             template_key: str = None) -> Dict:
        """
        Creates template options for the Metal Component class required for the class
        to function, based on the design template; i.e., be created, made, and rendered.
        Provides the blank option structure required.

        The options can be extended by plugins, such as renderers.

        Arguments:
            design (QDesign): Design class. Should be the class, not the instance.
            component_template (Dict): Template options to overwrite the class ones (default: None)
            logger_ (logging.Logger): A logger for errors.  Defaults to None.
            template_key (str): The template key identifier. If None, then uses
                cls._get_unique_class_name().  Defaults to None.

        Returns:
            Dict: dictionary of default options based on design template.
        """
        # get key for templates
        if template_key is None:
            template_key = cls._get_unique_class_name()

        renderer_key_values = cls._get_table_values_from_renderers(design)

        # Think
        if component_template is not None:
            renderer_and_component_template = {
                **renderer_key_values,
                **component_template
            }
        else:
            renderer_and_component_template = renderer_key_values

        if template_key not in design.template_options:
            cls._register_class_with_design(design, template_key,
                                            renderer_and_component_template)
            # design, template_key, component_template)

        if template_key not in design.template_options:
            logger_ = logger_ or design.logger
            if logger_:
                logger_.error(
                    f'ERROR in the creating component {cls.__name__}!\nThe default '
                    f'options for the component class {cls.__name__} are missing'
                )

        # Specific object template options
        template_options = deepcopy(Dict(design.template_options[template_key]))

        return template_options

    def _delete_evaluation(self, check_name: str = None):
        """When design.overwrite_enabled, the user is allowed to delete an existing component within
        the design if the name is being used.

        Args:
            check_name (str, optional): Name of new component.  Defaults to None.

        Returns:
            string: Return 'NameInUse' if overwrite flag is False and
            check_name is already being used within design.
            Otherwise return None.
        """
        answer = self._is_name_used(check_name)
        if self._design.overwrite_enabled and answer:
            self._design.delete_component(check_name)
        elif answer:
            logger.warning(
                f'The QComponent name `{check_name}` is already in use, '
                f'by a component (with QComponent id={answer}).\n'
                f'QComponent NOT made, nor added to the design. \n'
                'To force overwrite a QComponent with an existing name '
                'use the flag:\n`design.overwrite_enabled = True`.')
            return 'NameInUse'
        return None

    def make(self):
        """
        The make function implements the logic that creates the geometry
        (poly, path, etc.) from the qcomponent.options dictionary of parameters,
        and the adds them to the design, using qcomponent.add_qgeometry(...),
        adding in extra needed information, such as layer, subtract, etc.

        Use the qiskit_metal.draw module to create the geometry.

        **Note:**
            * This method should be overwritten by the children make function.
            * This function only contains the logic, the actual call to make the element is in
              rebuild()

        Raises:
            NotImplementedError: Overwrite this function by subclassing.
        """
        raise NotImplementedError()

    def rebuild(self):
        """Builds the QComponent.
        This is the main action function of a QComponent, call it qc.
        It converts the qc.options into QGeometry with all of the required options, such as
        the geometry points, layer number, materials, etc. needed to render.

        The build clears the existing QGeometry and QPins and then calls the qc.make function,
        which is writen by the component developer to implement the logic (using the metal.
        draw module) to convert the qc.options into the QGeometry.

        *Build status:*
        The function also sets the build status of the component.
        It sets to `failed` when the component is created, and then it sets to `good` when it is
        done with no errors. The user can also set other statuses, which can appear if the code fails
        to reach the final line of the build, where the build status is set to `good`.

        Raises:
            Exception: Component build failure
        """
        self.status = 'failed'
        try:
            if self._made:  # already made, just remaking
                self.design.qgeometry.delete_component_id(self.id)
                self.design._delete_all_pins_for_component(self.id)

            self.make()
            self._made = True
            self.status = 'good'

            self.design.build_logs.add_success(
                f"{str(datetime.now())} -- Component: {self.name} successfully built"
            )

        except Exception as error:
            self.logger.error(
                f'ERROR in building component name={self.name}, error={error}')
            self.design.build_logs.add_error(
                f"{str(datetime.now())} -- Component: {self.name} failed with error\n: {error}"
            )
            raise error

    def delete(self):
        """
        Delete the QComponent.
        Removes QGeometry, QPins, etc. from the design.
        """
        self.design.delete_component(self.name)

    # Maybe still should be fine as any values will be in component options still?
    # Though the data table approach and rendering directly via shapely could lead to problem
    # with variable use
    def parse_value(
        self, value: Union[Any, List, Dict, Iterable]
    ) -> Union[Any, List, Dict, Iterable]:
        """
        Parse a string, mappable (dict, Dict), iterable (list, tuple) to account for
        units conversion, some basic arithmetic, and design variables.
        This is the main parsing function of Qiskit Metal.

        Arguments:
            value (str): String to parse *or*
            variable_dict (dict): dict pointer of variables

        Return:
            str, float, list, tuple, or ast eval: Parse value

        Handled Inputs:
            Strings:
                Strings of numbers, numbers with units; e.g., '1', '1nm', '1 um'
                    Converts to int or float.
                    Some basic arithmetic is possible, see below.

                Strings of variables 'variable1'.
                    Variable interpretation will use string method
                    isidentifier 'variable1'.isidentifier()`

            Dictionaries:
                Returns ordered `Dict` with same key-value mappings, where the values have
                been subjected to parse_value.

            Itterables(list, tuple, ...):
                Returns same kind and calls itself `parse_value` on each element.

            Numbers:
                Returns the number as is. Int to int, etc.

        Arithemetic:
            Some basic arithmetic can be handled as well, such as `'-2 * 1e5 nm'`
            will yield float(-0.2) when the default units are set to `mm`.

        Default units:
            User units can be set in the design. The design will set config.DEFAULT.units

        Examples:
            See the docstring for this module.
                >> ?qiskit_metal.toolbox_metal.parsing
        """
        return self.design.parse_value(value)

    def parse_options(self, options: Dict = None) -> Dict:
        """
        Parse the options, converting string into interpreted values.
        Parses units, variables, strings, lists, and dictionaries.
        Explained by example below.

        Arguments:
            options (dict) : If left None, then self.options is used.  Defaults to None.

        Returns:
            dict: Parsed value

        Calls `self.design.parse_options`.

        See `self.parse_value` for more information.
        """
        return self.design.parse_value(options if options else self.options)

    def _is_name_used(self, check_name: str) -> int:
        """Used to check if name of component already exists.

        Args:
            check_name (str): Name which user requested to apply to current component.

        Returns:
            int: 0 if does not exist, otherwise
            component-id of component which is already using the name.

        Warning: If user has used this text version of the component name already,
        warning will be given to user.

        """

        if check_name in self._design.name_to_id:
            component_id = self._design.name_to_id[check_name]
            # if not self._overwrite_flag:
            #    logger.warning(f"Called _is_name_used, component_id({check_name}, id={component_id})"
            #                   " is already being used in design.")
            return component_id
        else:
            return 0

####################################################################################
# Functions for handling of pins

    def add_pin(
            self,
            name: str,  # Should be static based on component designer's choice
            points: np.ndarray,
            width: float,
            input_as_norm: bool = False,
            chip: str = 'main',
            gap: float = None):  # gap defaults to 0.6 * width
        """
        Adds a pin from two points which are normal/tangent to the intended plane of the pin.
        The normal should 'point' in the direction of intended connection. Adds the
        new pin as a subdictionary to parent component's pins dictionary.

        Arguments:
            * name (str): name of the pin
            * points (numpy.ndarray): [[x1,y1],[x2,y2]] for the normal/tangent line
            * width (float): the width of the intended connection (eg. qubit bus pad arm)
            * input_as_norm (bool): Indicates if the points are tangent or normal to the pin plane.
              Defaults to False.. Make True for normal.
            * parent (Union[int,]): The id of the parent component.
            * chip (str): the name of the chip the pin is located on.  Defaults to 'main'.
            * gap (float): the dielectric gap of the pin for the purpose of representing as a port
              for simulations.  Defaults to None which is converted to 0.6 * width.

        A dictionary containing a collection of information about the pin, necessary for use in Metal:
            * points (numpy.ndarray) - two (x,y) points which represent the edge of the pin for
              another component to attach to (eg. the edge of a CPW TL)
            * middle (numpy.ndarray) - an (x,y) which represents the middle of the points above,
              where the pin is represented.
            * normal (numpy.ndarray) - the normal vector of the pin, pointing in direction of
              intended connection
            * tangent (numpy.ndarray) - 90 degree rotation of normal vector
            * width (float) - the width of the pin
            * chip (str) - the chip the pin is on
            * parent_name - the id of the parent component
            * net_id - net_id of the pin if connected to another pin.  Defaults to 0, indicates
              not connected))

        ::

            * = pin
            . = outline of component

        ---> = the list being passed in as 'points' [[x1,y1],[x2,y2]]

        normal vector

        ::

            ..........
                     .
            --------->*
                     .
            ..........

        tangent vector

        ::

            ..........^
                     .|
                     .*
                     .|
            ..........|

        """
        assert len(points) == 2

        if gap is None:
            gap = width * 0.6

        rounding_val = self.design.template_options['PRECISION']
        points = np.around(
            points, rounding_val)  #Need points to remain as shapely geom?

        if input_as_norm:
            middle_point = points[1]
            vec_normal = points[1] - points[0]
            vec_normal /= np.linalg.norm(vec_normal)

            s_point = np.round(Vector.rotate(
                vec_normal, (np.pi / 2))) * width / 2 + points[1]
            e_point = np.round(Vector.rotate(
                vec_normal, -(np.pi / 2))) * width / 2 + points[1]
            points = [s_point, e_point]
            tangent_vector = Vector.rotate(vec_normal, np.pi / 2)

        else:
            vec_dist, tangent_vector, vec_normal = draw.Vector.two_points_described(
                points)
            middle_point = np.sum(points, axis=0) / 2.
            width = np.linalg.norm(vec_dist)

        pin_dict = Dict(
            points=points,
            middle=np.around(middle_point, rounding_val),
            normal=np.around(vec_normal, rounding_val),
            tangent=np.around(tangent_vector, rounding_val),
            width=np.around(width, rounding_val),
            gap=np.around(gap, rounding_val),
            chip=chip,
            parent_name=self.id,
            net_id=0,
            # Place holder value for potential future property (auto-routing cpw with
            # length limit)
            length=0)

        self.pins[name] = pin_dict

    def get_pin(self, name: str) -> Dict:
        """Interface for components to get pin data.

        Args:
            name (str): Name of the desired pin.

        Returns:
            dict: Returns the data of the pin, see make_pin() for what those values are.
        """

        return self.pins[name]

    def _check_pin_inputs(self):
        """Checks that the pin_inputs are valid, sets an error message indicating what the
        error is if the inputs are not valid.
        Checks regardless of user passing the component name or component id (probably a smoother way
        to do this check).

        3 Error cases:
            - Component does not exist
            - Pin does not exist
            - Pin is already attached to something

        Returns:
            str: Status test, or None
        """
        # Add check for if user inputs nonsense?
        false_component = False
        false_pin = False
        pin_in_use = False
        for pin_check in self.options.pin_inputs.values():
            component = pin_check['component']
            pin = pin_check['pin']
            if isinstance(component, str):
                if component not in self.design.components:
                    false_component = True
                elif pin not in self.design.components[component].pins:
                    false_pin = True
                elif self.design.components[component].pins[pin].net_id:
                    pin_in_use = True
            elif isinstance(component, int):
                if component not in self.design._components:
                    false_component = True
                elif pin not in self.design._components[component].pins:
                    false_pin = True
                elif self.design._components[component].pins[pin].net_id:
                    pin_in_use = True
            # Should modify to allow for multiple error messages to be returned.
            if false_component:
                self._error_message = f'Component {component} does not exist. {self.name} has not been built. Please check your pin_input values.'
                return 'Component Does Not Exist'
            if false_pin:
                self._error_message = f'Pin {pin} does not exist in component {component}. {self.name} has not been built. Please check your pin_input values.'
                return 'Pin Does Not Exist'
            if pin_in_use:
                self._error_message = f'Pin {pin} of component {component} is already in use. {self.name} has not been built. Please check your pin_input values.'
                return 'Pin In Use'
        return None

    # This method does not appear to be being used anywhere.
    def connect_components_already_in_design(self, pin_name_self: str,
                                             comp2_id: int,
                                             pin2_name: str) -> int:
        """WARNING: Do NOT use this method during generation of component instance.
            This method is expecting self to be added to design._components dict.  More importantly,
            the unique id of self component needs to be in design._components dict.

        Args:
            pin_name_self (str): Name of pin within the component.
            comp2_id (int): Component within design, but not self.
            pin2_name (str): The pin of comp2_id that pin_name_self will connect to.

        Returns:
            int: A unique net_id for the connection.
        """

        net_id_rtn = 0

        if self.id not in self.design._components:
            # Component not in design.
            logger.warning(
                f'No connection made. Component_id {self.id} not in design.')
            return net_id_rtn

        if comp2_id not in self.design._components:
            # Component not in design.
            logger.warning(
                f'No connection made. Component_id {comp2_id} not in design.')
            return net_id_rtn

        if self.design._components[self._id].pins[pin_name_self].net_id:
            # Pin already in use.
            logger.warning(
                f'Component_id {self._id} not connected.  The pin {pin_name_self} is already connected to something else.'
            )
            return net_id_rtn

        if self.design._components[comp2_id].pins[pin2_name].net_id:
            # Pin already in use.
            logger.warning(
                f'Component_id {comp2_id} not connected.  The pin {pin2_name} is already connected to something else.'
            )
            return net_id_rtn

        net_id_rtn = self.design.connect_pins(self.id, pin_name_self, comp2_id,
                                              pin2_name)

        return net_id_rtn

########################################################################

    def add_dependency(self, parent: str, child: str):
        """Add a dependency between one component and another.
        Calls parent design.

        Arguments:
            parent (str): The component on which the child depends
            child (str): The child cannot live without the parent.
        """
        self.design.add_dependency(parent, child)

##########################################
# QGeometry

    def add_qgeometry(
            self,
            kind: str,
            geometry: dict,
            subtract: bool = False,
            helper: bool = False,
            layer: Union[int, str] = 1,  # chip will be here
            chip: str = 'main',
            **kwargs):
        r"""Add QGeometry.

        Takes any additional options in options.

        Arguments:
            kind (str): The kind of QGeometry, such as 'path', 'poly', etc.
                        All geometry in the dictionary should have the same kind,
                        such as Polygon or LineString.
            geometry (Dict[BaseGeometry]): Key-value pairs of name of the geometry
                you want to add and the value should be a shapely geometry object, such
                as a Polygon or a LineString.
            subtract (bool): Subtract from the layer.  Defaults to False.
            helper (bool): Is this a helper object. If true, subtract must be false
                           Defaults to False.
            layer (int, str): The layer to which the set of QGeometry will belong
                              Defaults to 1.
            chip (str): Chip name.  Defaults to 'main'.
            kwargs (dict): Parameters dictionary

        Assumptions:
            * Assumes all geometry in the `geometry` argument are homogeneous in kind;
              i.e., all lines or polys etc.
        """
        # assert (subtract and helper) == False, "The object can't be a subtracted helper. Please"\
        #    " choose it to either be a helper or a a subtracted layer, but not both. Thank you."

        if kind in self.qgeometry_table_usage.keys():
            self.qgeometry_table_usage[kind] = True
        else:
            self.logger.warning(
                f'Component with classname={self.class_name} does not know about table name "{kind}". '
            )

        renderer_key_values = self._get_specific_table_values_from_renderers(
            kind)
        for key in renderer_key_values:
            if key in self.options:
                renderer_key_values[key] = deepcopy(self.options[key])

        # # if not already in kwargs, add renderer information to it.
        renderer_and_options = {**renderer_key_values, **kwargs}

        # When self.options is instantiated, the template_options are populated.
        # renderer_and_options = {**self.options, **kwargs}

        self.design.qgeometry.add_qgeometry(kind,
                                            self.id,
                                            geometry,
                                            subtract=subtract,
                                            helper=helper,
                                            layer=layer,
                                            chip=chip,
                                            **renderer_and_options)

    def _get_specific_table_values_from_renderers(self, kind: str) -> Dict:
        """Populate a dict to combine with options for the qcomponent.

        Based on kind, which the table name, the component-developer denotes in the metadata,
        assume those qgeometry.tables are used for the component. The method
        will search a dict populated by all the renderers during their init.

        Args:
            kind (str): Name of table, like juction, path, or poly.

        Returns:
            Dict: key is column names for tables, value is data for the column.
        """
        all_renderers_key_value = dict()

        # design.renderer_defaults_by_table[table_name][renderer_name][column_name]
        if kind in self.design.renderer_defaults_by_table:
            for name_renderer, renderer_data in self.design.renderer_defaults_by_table[
                    kind].items():
                if len(renderer_data) > 0:
                    for col_name, col_value in renderer_data.items():
                        render_col_name = f'{name_renderer}_{col_name}'
                        all_renderers_key_value[render_col_name] = col_value

        return all_renderers_key_value

    @classmethod
    def _get_table_values_from_renderers(cls, design: 'QDesign') -> Dict:
        """Populate a dict to combine with options for the qcomponent.

        Based on tables the component-developer denotes in the metadata,
        assume those qgeometry.tables are used for the component. The method
        will search a dict populated by all the renderers during their init.

        Returns:
            Dict: key is column names for tables, value is data for the column.
        """
        metadata_dict = cls._gather_all_children_metadata()
        tables_list = design.get_list_of_tables_in_metadata(metadata_dict)

        all_renderers_key_value = dict()
        # design.renderer_defaults_by_table[table_name][renderer_name][column_name]
        for table in tables_list:
            if table in design.renderer_defaults_by_table:
                for name_renderer, renderer_data in design.renderer_defaults_by_table[
                        table].items():
                    if len(renderer_data) > 0:
                        for col_name, col_value in renderer_data.items():
                            render_col_name = f'{name_renderer}_{col_name}'
                            all_renderers_key_value[render_col_name] = col_value
        return all_renderers_key_value

######################################

    def __repr__(self, *args):
        b = '\033[95m\033[1m'
        b1 = '\033[94m\033[1m'
        e = '\033[0m'

        # id = {hex(id(self))}
        # options = pprint.pformat(self.options)

        options = format_dict_ala_z(self.options)
        text = f"{b}name:    {b1}{self.name}{e}\n"\
            f"{b}class:   {b1}{self.__class__.__name__:<22s}{e}\n"\
            f"{b}options: {e}\n{options}\n"\
            f"{b}module:  {b1}{self.__class__.__module__}{e}\n"\
            f"{b}id:      {b1}{self.id}{e}\n"
        return text

############################################################################
# Geometry handling of created qgeometry

    @property
    def qgeometry_types(self) -> List[str]:
        """Get a list of the names of the element tables.

        Returns:
            List[str]: Name of element table or type; e.g., 'poly' and 'path'
        """
        return self.design.qgeometry.get_element_types()

    def qgeometry_dict(self, element_type: str) -> Dict_[str, BaseGeometry]:
        """
        Returns a dict of element qgeometry (shapely geometry) of the component
        as a python dict, where the dict keys are the names of the qgeometry
        and the corresponding values are the shapely geometries.

        Arguments:
            element_type (str): Name of element table or type; e.g., 'poly' and 'path'

        Returns:
            List[BaseGeometry]: Geometry diction or None if an error in the name of the element
            type (ie. table)
        """
        if element_type == 'all' or self.design.qgeometry.check_element_type(
                element_type):
            return self.design.qgeometry.get_component_geometry_dict(
                self.name, element_type)

    def qgeometry_list(self, element_type: str = 'all') -> List[BaseGeometry]:
        """
        Returns a list of element qgeometry (shapely geometry) of the component
        as a python list of shapely geometries.

        Arguments:
            element_type (str): Name of element table or type; e.g., 'poly' and 'path'.
                                Can also specify all

        Returns:
            List[BaseGeometry]: Geometry list or None if an error in the name of the element type
            (ie. table)
        """
        if element_type == 'all' or self.design.qgeometry.check_element_type(
                element_type):
            return self.design.qgeometry.get_component_geometry_list(
                self.name, element_type)

    def qgeometry_table(self, element_type: str) -> pd.DataFrame:
        """
        Returns the entire element table for the component.

        Arguments:
            element_type (str): Name of element table or type; e.g., 'poly' and 'path'

        Returns:
            pd.DataFrame: Element table for the component or None if an error in the name of
            the element type (ie. table)
        """
        if element_type == 'all' or self.design.qgeometry.check_element_type(
                element_type):
            return self.design.qgeometry.get_component(self.name, element_type)

    def qgeometry_bounds(self) -> Tuple:
        """
        Fetched the component bound dict_value.

        Returns:
            tuple: containing (minx, miny, maxx, maxy) bound values for the bounds of the
            component as a whole.

        Uses:
            design.qgeometry.get_component_bounds
        """
        bounds = self.design.qgeometry.get_component_bounds(self.name)
        return bounds

    def qgeometry_plot(self,
                       ax: 'matplotlib.axes.Axes' = None,
                       plot_kw: dict = None) -> List:
        """ Draw all the qgeometry of the component (polys and path etc.)

        Arguments:
            ax (matplotlib.axes.Axes): Matplotlib axis to draw on.  Defaults to None -- gets the current axis.
            plot_kw (dict): Parameters dictionary.

        Returns:
            List: The list of qgeometry draw

        Example use:
            Suppose you had a component called q1:

                fig, ax = draw.mpl.figure_spawn()
                q1.qgeometry_plot(ax)
        """
        qgeometry = self.qgeometry_list()
        plot_kw = {}
        draw.mpl.render(qgeometry, ax=ax, kw=plot_kw)
        return qgeometry

    def populate_to_track_table_usage(self) -> None:
        """Use the element_handler to get a list of all the table names used in QGeometry.
        The dict qgeometry_able_usage should get updated by add_qgeometry(). This dict is used
        to get a summary tables used for this component.
        """
        for table_name in self.design.qgeometry.tables.keys():
            self.qgeometry_table_usage[table_name] = False

ext: py

max_stars_repo_name: mtreinish/qiskit-metal

max_issues_repo_name: mtreinish/qiskit-metal

max_forks_repo_name: mtreinish/qiskit-metal

reason: import numpy


text:
# Tom Simpson
# Learning matplotlib
# 25/07/21

# Imoporting Modules
import matplotlib.pyplot as plt
import numpy as np

# Generating line
xpoints = np.array([0, 10])
ypoints = np.array([0, 10])
plt.plot(xpoints, ypoints, marker = '*')

# Plotting a points
xpoints = np.array([10, 0])
ypoints = np.array([0, 10])
plt.plot(xpoints, ypoints, "bo")

# Showing plot
plt.show()

max_stars_repo_name: tomdsimpson/Silver-DofE

max_issues_repo_name: tomdsimpson/Silver-DofE

max_forks_repo_name: tomdsimpson/Silver-DofE


text:
import numpy

from dexp.datasets.synthetic_datasets import generate_fusion_test_data
from dexp.processing.fusion.dct_fusion import fuse_dct_nd
from dexp.utils.backends import Backend, NumpyBackend
from dexp.utils.timeit import timeit

def test_dct_fusion_numpy():
    with NumpyBackend():
        dct_fusion()

def dct_fusion(length_xy=128):
    image_gt, image_lowq, blend_a, blend_b, image1, image2 = generate_fusion_test_data(
        add_noise=False, length_xy=length_xy, length_z_factor=4
    )
    with timeit("dcf fusion + data transfer"):
        image_fused = fuse_dct_nd(image1, image2)
        image_fused = Backend.to_numpy(image_fused)

    image_gt = Backend.to_numpy(image_gt)
    error = numpy.median(numpy.abs(image_gt - image_fused))
    print(f"error={error}")
    assert error < 22

    # from napari import Viewer, gui_qt
    # with gui_qt():
    #     viewer = Viewer()
    #     viewer.add_image(image_gt, name='image_gt')
    #     viewer.add_image(image_lowq, name='image_lowq')
    #     viewer.add_image(blend_a, name='blend_a')
    #     viewer.add_image(blend_b, name='blend_b')
    #     viewer.add_image(image1, name='image1')
    #     viewer.add_image(image2, name='image2')
    #     viewer.add_image(image_fused, name='image_fused')

max_stars_repo_name: haesleinhuepf/dexp

max_issues_repo_name: haesleinhuepf/dexp

max_forks_repo_name: haesleinhuepf/dexp


text:
#!/usr/bin/python

help_msg = 'calculate contact order from PDB structure file'

import os, sys, glob
import imp
from Bio.PDB import NeighborSearch, PDBParser, Atom, Residue, Polypeptide
from Bio import PDB
import numpy as np

CWD = os.getcwd()
UTLTS_DIR = CWD[:CWD.index('proteomevis_scripts')]+'/proteomevis_scripts/utlts'
sys.path.append(UTLTS_DIR)
from parse_user_input import help_message, false_or_true
from read_in_file import read_in
from parse_data import organism
from output import writeout, print_next_step

def contact_order(contact_matrix):
	CO = 0
	for res1, contact_res in enumerate(contact_matrix):
		for res2, contact in enumerate(contact_res):
			if contact:
				CO+= abs(res1-res2)
	return CO / (float(len(contact_matrix)*contact_matrix.sum()))

if __name__ == "__main__":
	help_message(help_msg)
	extra = ''
	method = false_or_true("Calculate contact density like Shakh2006 [default Zhou2008]?")
	if false_or_true("Relax selection criterion 2"):
		extra += 'pre_output'

	contact_defn = ['Bloom', 'Shakh'][method]
	d_input = read_in('pdb', 'oln', filename = extra)
	d_input1 = read_in('pdb', 'uniprot', filename = extra)
	d_output = {}

	module = imp.load_source("run", "../../contact_density/run.py")	#normal import doesnt work
	for pdb, oln in d_input.iteritems():
		protein_contact = module.ProteinContact(pdb, contact_defn)
		CO = contact_order(protein_contact.contact_matrix())
		if organism=='protherm':
			d_output[d_input1[pdb]] = CO
			x_name = 'uniprot'
		else:
			d_output[oln] = CO
			x_name = 'oln'

	filename = 'PDB'
	if method:
		filename+='_shakh'
	writeout([x_name, 'contact_order'], d_output, filename = '{0}{1}'.format(filename, extra))
	print_next_step()


text:
import os

import cv2
import numpy as np

DATADIR = "./data"
CATEGORIES = ["bee","wasp","other"]
IMG_SIZE = 128

data_X = []
data_Y = []

def Create_Training_Data():
    for i,category in enumerate(CATEGORIES):
        path = os.path.join(DATADIR,category)
        class_num = i
        for img in os.listdir(path):
            img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
            img_array = cv2.resize(img_array,(IMG_SIZE,IMG_SIZE))
            data_X.append(img_array)
            y = np.zeros(3)
            y[class_num] = 1
            data_Y.append(y)

Create_Training_Data()

np.savez("data.npz", X=data_X, Y=data_Y)

max_stars_repo_name: Allstreamer/Bees-N-Wasp-CNN

max_issues_repo_name: Allstreamer/Bees-N-Wasp-CNN

max_forks_repo_name: Allstreamer/Bees-N-Wasp-CNN


text:
import itertools as it

import numpy as np
import pylab as pl

from triflow import Model, schemes

model = Model("k * dxxU - c * dxU",
              "U", ["k", "c"])

x, dx = np.linspace(0, 1, 200, retstep=True)
U = np.cos(2 * np.pi * x * 5)
fields = model.fields_template(x=x, U=U)

parameters = dict(c=.03, k=.001, dx=dx, periodic=True)

t = 0
dt = 1E-2
tmax = 5

pl.plot(fields.x, fields.U, label='t: %g' % t)

scheme = schemes.Theta(model, theta=.5)  # Crank-Nicolson scheme

for i in it.count():
    t, fields = scheme(t, fields, dt, parameters)
    if (i + 1) % 100 == 0:
        pl.plot(fields.x, fields.U, label='t: %g' % t)
    if t >= tmax:
        break

pl.xlim(0, 1)
legend = pl.legend(loc='best')

pl.show()

max_stars_repo_name: locie/triflow

max_issues_repo_name: celliern/triflow

max_forks_repo_name: celliern/triflow


text:
import numpy as np
import keras
import tensorflow as tf
from keras.backend.tensorflow_backend import clear_session

def mle_loss(y_true, y_pred):
    # Minimum likelihood estimate loss function
    mean = tf.slice(y_pred, [0, 0], [-1, 1])
    var = tf.slice(y_pred, [0, 1], [-1, 1])
    return 0.5 * tf.log(2*np.pi*var) + tf.square(y_true - mean) / (2*var)

def mape_loss(y_true, y_pred):
    # Minimum absolute percentage error loss function
    lower_bound = 4.5
    fraction = tf.math.divide(tf.subtract(y_pred, lower_bound),
                              tf.subtract(y_true, lower_bound))
    return tf.abs(tf.subtract(fraction, 1))

class PredictorMLP:
    def __init__(self, gpu='0', sess=None):
        self.sess = sess
        if not isinstance(gpu, str):
            gpu = str(gpu)
        self.gpu = gpu

    def clear_gpu(self):
        config = tf.ConfigProto(device_count={'GPU': 1})
        config.gpu_options.allow_growth = True
        config.gpu_options.visible_device_list = str(self.gpu)
        self.sess = tf.Session(config=config)
        clear_session()

    def get_dense_model(self,
                        input_dims,
                        num_layers,
                        layer_width,
                        loss,
                        regularization,
                        dynamic_filter=0,
                        dynamic_kernel=0):
        config = tf.ConfigProto(device_count={'GPU': 1})
        config.gpu_options.allow_growth = True
        config.gpu_options.visible_device_list = str(self.gpu)
        self.sess = tf.Session(config=config)
        keras.backend.set_session(self.sess)

        input_layer = keras.layers.Input(input_dims)
        model = keras.models.Sequential()

        # if dynamic_kernel > 0 and dynamic_filter > 0:
        #     model.add(keras.layers.Conv1D(filters=dynamic_filter, kernel_size=dynamic_kernel))

        # for _ in range(num_layers):
        model.add(keras.layers.Dense(512, activation='relu'))
        model.add(keras.layers.Dense(2048, activation='relu'))
        model.add(keras.layers.Dense(2048, activation='relu'))
        model.add(keras.layers.Dense(512, activation='relu'))

        model = model(input_layer)
        if loss == 'mle':
            mean = keras.layers.Dense(1)(model)
            var = keras.layers.Dense(1)(model)
            var = keras.layers.Activation(tf.math.softplus)(var)
            output = keras.layers.concatenate([mean, var])
        else:
            if regularization == 0:
                output = keras.layers.Dense(1)(model)
            else:
                reg = keras.regularizers.l1(regularization)
                output = keras.layers.Dense(1, kernel_regularizer=reg)(model)

        dense_net = keras.models.Model(inputs=input_layer, outputs=output)
        return dense_net

    def fit(self, xtrain, ytrain,
            num_layers=10,
            layer_width=20,
            loss='mae',
            epochs=200,
            batch_size=32,
            lr=.01,
            verbose=0,
            regularization=0,
            dynamic_filter=0,
            dynamic_kernel=0):

        if loss == 'mle':
            loss_fn = mle_loss
        elif loss == 'mape':
            loss_fn = mape_loss
        else:
            loss_fn = 'mae'

        self.model = self.get_dense_model((xtrain.shape[1],),
                                          loss=loss_fn,
                                          num_layers=num_layers,
                                          layer_width=layer_width,
                                          regularization=regularization,
                                          dynamic_filter=dynamic_filter,
                                          dynamic_kernel=dynamic_kernel)
        optimizer = keras.optimizers.Adam(lr=lr, beta_1=.9, beta_2=.99)
        self.model.compile(optimizer=optimizer, loss=loss_fn)
        self.model.fit(xtrain, ytrain,
                       batch_size=batch_size,
                       epochs=epochs,
                       verbose=verbose)
        train_pred = np.squeeze(self.model.predict(xtrain))
        train_error = np.mean(abs(train_pred-ytrain))
        return train_error

    def predict(self, xtest):
        return self.model.predict(xtest)

max_stars_repo_name: auroua/SSNENAS

max_issues_repo_name: auroua/SSNENAS

max_forks_repo_name: auroua/SSNENAS


text:
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch
import numpy as np
import math
from trilinear_c._ext import trilinear

def weights_init_normal_classifier(m):
    classname = m.__class__.__name__
    if classname.find("Conv") != -1:
        torch.nn.init.xavier_normal_(m.weight.data)

    elif classname.find("BatchNorm2d") != -1 or classname.find("InstanceNorm2d") != -1:
        torch.nn.init.normal_(m.weight.data, 1.0, 0.02)
        torch.nn.init.constant_(m.bias.data, 0.0)

class resnet18_224(nn.Module):

    def __init__(self, out_dim=5, aug_test=False):
        super(resnet18_224, self).__init__()

        self.aug_test = aug_test
        net = models.resnet18(pretrained=True)
        # self.mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).cuda()
        # self.std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).cuda()

        self.upsample = nn.Upsample(size=(224,224),mode='bilinear')
        net.fc = nn.Linear(512, out_dim)
        self.model = net

    def forward(self, x):

        x = self.upsample(x)
        if self.aug_test:
            # x = torch.cat((x, torch.rot90(x, 1, [2, 3]), torch.rot90(x, 3, [2, 3])), 0)
            x = torch.cat((x, torch.flip(x, [3])), 0)
        f = self.model(x)

        return f

##############################
#           DPE
##############################

class UNetDown(nn.Module):
    def __init__(self, in_size, out_size, normalize=True, dropout=0.0):
        super(UNetDown, self).__init__()
        layers = [nn.Conv2d(in_size, out_size, 5, 2, 2)]
        layers.append(nn.SELU(inplace=True))
        if normalize:
            #layers.append(nn.BatchNorm2d(out_size))
            nn.InstanceNorm2d(out_size, affine = True)
        if dropout:
            layers.append(nn.Dropout(dropout))
        self.model = nn.Sequential(*layers)

    def forward(self, x):
        return self.model(x)

class UNetUp(nn.Module):
    def __init__(self, in_size, out_size, normalize=True, dropout=0.0):
        super(UNetUp, self).__init__()
        layers = [
            nn.Upsample(scale_factor=2, mode = 'bilinear', align_corners=True),
            nn.Conv2d(in_size, out_size, 3, padding=1),
            nn.SELU(inplace=True),
        ]

        if normalize:
            #layers.append(nn.BatchNorm2d(out_size))
            nn.InstanceNorm2d(out_size, affine = True)

        if dropout:
            layers.append(nn.Dropout(dropout))

        self.model = nn.Sequential(*layers)

    def forward(self, x, skip_input):
        x = self.model(x)
        x = torch.cat((x, skip_input), 1)

        return x

class GeneratorUNet(nn.Module):
    def __init__(self, in_channels=3, out_channels=3):
        super(GeneratorUNet, self).__init__()

        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.SELU(inplace=True),
            #nn.BatchNorm2d(16),
            nn.InstanceNorm2d(16, affine = True),
            )
        self.down1 = UNetDown(16, 32)
        self.down2 = UNetDown(32, 64)
        self.down3 = UNetDown(64, 128)
        self.down4 = UNetDown(128, 128)
        self.down5 = UNetDown(128, 128)
        self.down6 = UNetDown(128, 128)
        self.down7 = nn.Sequential(
            nn.Conv2d(128, 128, 3, padding=1),
            nn.SELU(inplace=True),
            nn.Conv2d(128, 128, 1, padding=0),
            )

        self.upsample = nn.Upsample(scale_factor=4, mode = 'bilinear')
        self.conv1x1 = nn.Conv2d(256, 128, 1, padding=0)

        self.up1 = UNetUp(128, 128)
        self.up2 = UNetUp(256, 128)
        self.up3 = UNetUp(192, 64)
        self.up4 = UNetUp(96, 32)

        self.final = nn.Sequential(
            nn.Conv2d(48, 16, 3, padding=1),
            nn.SELU(inplace=True),
            #nn.BatchNorm2d(16),
            #nn.InstanceNorm2d(16, affine = True),
            nn.Conv2d(16, out_channels, 3, padding=1),
            #nn.Tanh(),
            )

    def forward(self, x):
        # U-Net generator with skip connections from encoder to decoder

        x1 = self.conv1(x)
        d1 = self.down1(x1)
        d2 = self.down2(d1)
        d3 = self.down3(d2)
        d4 = self.down4(d3)

        d5 = self.down5(d4)
        d6 = self.down6(d5)
        d7 = self.down7(d6)

        d8 = self.upsample(d7)
        d9 = torch.cat((d4, d8), 1)
        d9 = self.conv1x1(d9)

        u1 = self.up1(d9, d3)
        u2 = self.up2(u1, d2)
        u3 = self.up3(u2, d1)
        u4 = self.up4(u3, x1)

        return torch.add(self.final(u4), x)

class Discriminator_UNet(nn.Module):
    def __init__(self, in_channels=3):
        super(Discriminator_UNet, self).__init__()

        self.model = nn.Sequential(
            nn.Conv2d(3, 16, 3, stride=2, padding=1),
            nn.LeakyReLU(0.2),
            nn.InstanceNorm2d(16, affine=True),
            *discriminator_block(16, 32),
            *discriminator_block(32, 64),
            *discriminator_block(64, 128),
            *discriminator_block(128, 128),
            *discriminator_block(128, 128),
            nn.Conv2d(128, 1, 4, padding=0)
        )

    def forward(self, img_input):
        return self.model(img_input)

##############################
#        Discriminator
##############################

def discriminator_block(in_filters, out_filters, normalization=False):
    """Returns downsampling layers of each discriminator block"""
    layers = [nn.Conv2d(in_filters, out_filters, 3, stride=2, padding=1)]
    layers.append(nn.LeakyReLU(0.2))
    if normalization:
        layers.append(nn.InstanceNorm2d(out_filters, affine=True))
        #layers.append(nn.BatchNorm2d(out_filters))

    return layers

class Discriminator(nn.Module):
    def __init__(self, in_channels=3):
        super(Discriminator, self).__init__()

        self.model = nn.Sequential(
            nn.Upsample(size=(256,256),mode='bilinear'),
            nn.Conv2d(3, 16, 3, stride=2, padding=1),
            nn.LeakyReLU(0.2),
            nn.InstanceNorm2d(16, affine=True),
            *discriminator_block(16, 32),
            *discriminator_block(32, 64),
            *discriminator_block(64, 128),
            *discriminator_block(128, 128),
            #*discriminator_block(128, 128),
            nn.Conv2d(128, 1, 8, padding=0)
        )

    def forward(self, img_input):
        return self.model(img_input)

class Classifier(nn.Module):
    def __init__(self, in_channels=3):
        super(Classifier, self).__init__()

        self.model = nn.Sequential(
            nn.Upsample(size=(256,256),mode='bilinear'),
            nn.Conv2d(3, 16, 3, stride=2, padding=1),
            nn.LeakyReLU(0.2),
            nn.InstanceNorm2d(16, affine=True),
            *discriminator_block(16, 32, normalization=True),
            *discriminator_block(32, 64, normalization=True),
            *discriminator_block(64, 128, normalization=True),
            *discriminator_block(128, 128),
            #*discriminator_block(128, 128, normalization=True),
            nn.Dropout(p=0.5),
            nn.Conv2d(128, 3, 8, padding=0),
        )

    def forward(self, img_input):
        return self.model(img_input)

class Classifier_unpaired(nn.Module):
    def __init__(self, in_channels=3):
        super(Classifier_unpaired, self).__init__()

        self.model = nn.Sequential(
            nn.Upsample(size=(256,256),mode='bilinear'),
            nn.Conv2d(3, 16, 3, stride=2, padding=1),
            nn.LeakyReLU(0.2),
            nn.InstanceNorm2d(16, affine=True),
            *discriminator_block(16, 32),
            *discriminator_block(32, 64),
            *discriminator_block(64, 128),
            *discriminator_block(128, 128),
            #*discriminator_block(128, 128),
            nn.Conv2d(128, 3, 8, padding=0),
        )

    def forward(self, img_input):
        return self.model(img_input)

class Generator3DLUT_identity(nn.Module):
    def __init__(self, dim=33):
        super(Generator3DLUT_identity, self).__init__()
        if dim == 33:
            file = open("IdentityLUT33.txt",'r')
        elif dim == 64:
            file = open("IdentityLUT64.txt",'r')
        LUT = file.readlines()
        self.LUT = torch.zeros(3,dim,dim,dim, dtype=torch.float)

        for i in range(0,dim):
            for j in range(0,dim):
                for k in range(0,dim):
                    n = i * dim*dim + j * dim + k
                    x = LUT[n].split()
                    self.LUT[0,i,j,k] = float(x[0])
                    self.LUT[1,i,j,k] = float(x[1])
                    self.LUT[2,i,j,k] = float(x[2])
        self.LUT = nn.Parameter(torch.tensor(self.LUT))
        self.TrilinearInterpolation = TrilinearInterpolation()

    def forward(self, x):

        return self.TrilinearInterpolation(self.LUT, x)

class Generator3DLUT_zero(nn.Module):
    def __init__(self, dim=33):
        super(Generator3DLUT_zero, self).__init__()

        self.LUT = torch.zeros(3,dim,dim,dim, dtype=torch.float)
        self.LUT = nn.Parameter(torch.tensor(self.LUT))
        self.TrilinearInterpolation = TrilinearInterpolation()

    def forward(self, x):

        return self.TrilinearInterpolation(self.LUT, x)

class TrilinearInterpolation(torch.autograd.Function):

    def forward(self, LUT, x):

        x = x.contiguous()
        output = x.new(x.size())
        dim = LUT.size()[-1]
        shift = dim ** 3
        binsize = 1.0001 / (dim-1)
        W = x.size(2)
        H = x.size(3)
        batch = x.size(0)

        self.x = x
        self.LUT = LUT
        self.dim = dim
        self.shift = shift
        self.binsize = binsize
        self.W = W
        self.H = H
        self.batch = batch

        if x.is_cuda:
            if batch == 1:
                trilinear.trilinear_forward_cuda(LUT,x,output,dim,shift,binsize,W,H,batch)
            elif batch > 1:
                output = output.permute(1,0,2,3).contiguous()
                trilinear.trilinear_forward_cuda(LUT,x.permute(1,0,2,3).contiguous(),output,dim,shift,binsize,W,H,batch)
                output = output.permute(1,0,2,3).contiguous()

        else:
            trilinear.trilinear_forward(LUT,x,output,dim,shift,binsize,W,H,batch)

        return output

    def backward(self, grad_x):

        grad_LUT = torch.zeros(3,self.dim,self.dim,self.dim,dtype=torch.float)

        if grad_x.is_cuda:
            grad_LUT = grad_LUT.cuda()
            if self.batch == 1:
                trilinear.trilinear_backward_cuda(self.x,grad_x,grad_LUT,self.dim,self.shift,self.binsize,self.W,self.H,self.batch)
            elif self.batch > 1:
                trilinear.trilinear_backward_cuda(self.x.permute(1,0,2,3).contiguous(),grad_x.permute(1,0,2,3).contiguous(),grad_LUT,self.dim,self.shift,self.binsize,self.W,self.H,self.batch)
        else:
            trilinear.trilinear_backward(self.x,grad_x,grad_LUT,self.dim,self.shift,self.binsize,self.W,self.H,self.batch)

        return grad_LUT, None

class TV_3D(nn.Module):
    def __init__(self, dim=33):
        super(TV_3D,self).__init__()

        self.weight_r = torch.ones(3,dim,dim,dim-1, dtype=torch.float)
        self.weight_r[:,:,:,(0,dim-2)] *= 2.0
        self.weight_g = torch.ones(3,dim,dim-1,dim, dtype=torch.float)
        self.weight_g[:,:,(0,dim-2),:] *= 2.0
        self.weight_b = torch.ones(3,dim-1,dim,dim, dtype=torch.float)
        self.weight_b[:,(0,dim-2),:,:] *= 2.0
        self.relu = torch.nn.ReLU()

    def forward(self, LUT):

        dif_r = LUT.LUT[:,:,:,:-1] - LUT.LUT[:,:,:,1:]
        dif_g = LUT.LUT[:,:,:-1,:] - LUT.LUT[:,:,1:,:]
        dif_b = LUT.LUT[:,:-1,:,:] - LUT.LUT[:,1:,:,:]
        tv = torch.mean(torch.mul((dif_r ** 2),self.weight_r)) + torch.mean(torch.mul((dif_g ** 2),self.weight_g)) + torch.mean(torch.mul((dif_b ** 2),self.weight_b))

        mn = torch.mean(self.relu(dif_r)) + torch.mean(self.relu(dif_g)) + torch.mean(self.relu(dif_b))

        return tv, mn


text:
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
import numpy as np
import scipp as sc

class Binned1d:
    """
    Benchmark different aspects of binned data
    """
    params = (list(10**np.arange(8)), list(10**np.arange(0, 7)))
    param_names = ['nevent', 'nbin']

    def setup(self, nevent, nbin):
        self.da = sc.data.binned_x(nevent, nbin)

    def time_bins_constituents(self, nevent, nbin):
        self.da.bins.constituents

    def time_bins_size(self, nevent, nbin):
        self.da.bins.size()

    def time_bins_sum(self, nevent, nbin):
        self.da.bins.sum()

    def time_bins_mean(self, nevent, nbin):
        self.da.bins.sum()

    def time_bins_concat(self, nevent, nbin):
        self.da.bins.concat('x')

max_stars_repo_name: nvaytet/scipp

max_issues_repo_name: nvaytet/scipp

max_forks_repo_name: nvaytet/scipp