text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta

struct __enum_ZWaveClassType <: ProtoEnum
    COMMAND_CLASS_NO_OPERATION::Int32
    ZWAVE_CMD_CLASS::Int32
    COMMAND_CLASS_ZENSOR_NET::Int32
    COMMAND_CLASS_BASIC::Int32
    COMMAND_CLASS_CONTROLLER_REPLICATION::Int32
    COMMAND_CLASS_APPLICATION_STATUS::Int32
    COMMAND_CLASS_ZIP::Int32
    COMMAND_CLASS_SECURITY_PANEL_MODE::Int32
    COMMAND_CLASS_SWITCH_BINARY::Int32
    COMMAND_CLASS_SWITCH_MULTILEVEL::Int32
    COMMAND_CLASS_SWITCH_ALL::Int32
    COMMAND_CLASS_SWITCH_TOGGLE_BINARY::Int32
    COMMAND_CLASS_SWITCH_TOGGLE_MULTILEVEL::Int32
    COMMAND_CLASS_CHIMNEY_FAN::Int32
    COMMAND_CLASS_SCENE_ACTIVATION::Int32
    COMMAND_CLASS_SCENE_ACTUATOR_CONF::Int32
    COMMAND_CLASS_SCENE_CONTROLLER_CONF::Int32
    COMMAND_CLASS_SECURITY_PANEL_ZONE::Int32
    COMMAND_CLASS_SECURITY_PANEL_ZONE_SENSOR::Int32
    COMMAND_CLASS_SENSOR_BINARY::Int32
    COMMAND_CLASS_SENSOR_MULTILEVEL::Int32
    COMMAND_CLASS_METER::Int32
    COMMAND_CLASS_SWITCH_COLOR::Int32
    COMMAND_CLASS_NETWORK_MANAGEMENT_INCLUSION::Int32
    COMMAND_CLASS_METER_PULSE::Int32
    COMMAND_CLASS_BASIC_TARIFF_INFO::Int32
    COMMAND_CLASS_HRV_STATUS::Int32
    COMMAND_CLASS_THERMOSTAT_HEATING::Int32
    COMMAND_CLASS_HRV_CONTROL::Int32
    COMMAND_CLASS_DCP_CONFIG::Int32
    COMMAND_CLASS_DCP_MONITOR::Int32
    COMMAND_CLASS_METER_TBL_CONFIG::Int32
    COMMAND_CLASS_METER_TBL_MONITOR::Int32
    COMMAND_CLASS_METER_TBL_PUSH::Int32
    COMMAND_CLASS_PREPAYMENT::Int32
    COMMAND_CLASS_THERMOSTAT_MODE::Int32
    COMMAND_CLASS_PREPAYMENT_ENCAPSULATION::Int32
    COMMAND_CLASS_THERMOSTAT_OPERATING_STATE::Int32
    COMMAND_CLASS_THERMOSTAT_SETPOINT::Int32
    COMMAND_CLASS_THERMOSTAT_FAN_MODE::Int32
    COMMAND_CLASS_THERMOSTAT_FAN_STATE::Int32
    COMMAND_CLASS_CLIMATE_CONTROL_SCHEDULE::Int32
    COMMAND_CLASS_THERMOSTAT_SETBACK::Int32
    COMMAND_CLASS_RATE_TBL_CONFIG::Int32
    COMMAND_CLASS_RATE_TBL_MONITOR::Int32
    COMMAND_CLASS_TARIFF_CONFIG::Int32
    COMMAND_CLASS_TARIFF_TBL_MONITOR::Int32
    COMMAND_CLASS_DOOR_LOCK_LOGGING::Int32
    COMMAND_CLASS_NETWORK_MANAGEMENT_BASIC::Int32
    COMMAND_CLASS_SCHEDULE_ENTRY_LOCK::Int32
    COMMAND_CLASS_ZIP_6LOWPAN::Int32
    COMMAND_CLASS_BASIC_WINDOW_COVERING::Int32
    COMMAND_CLASS_MTP_WINDOW_COVERING::Int32
    COMMAND_CLASS_NETWORK_MANAGEMENT_PROXY::Int32
    COMMAND_CLASS_SCHEDULE::Int32
    COMMAND_CLASS_NETWORK_MANAGEMENT_PRIMARY::Int32
    COMMAND_CLASS_TRANSPORT_SERVICE::Int32
    COMMAND_CLASS_CRC_16_ENCAP::Int32
    COMMAND_CLASS_APPLICATION_CAPABILITY::Int32
    COMMAND_CLASS_ZIP_ND::Int32
    COMMAND_CLASS_ASSOCIATION_GRP_INFO::Int32
    COMMAND_CLASS_DEVICE_RESET_LOCALLY::Int32
    COMMAND_CLASS_CENTRAL_SCENE::Int32
    COMMAND_CLASS_IP_ASSOCIATION::Int32
    COMMAND_CLASS_ANTITHEFT::Int32
    COMMAND_CLASS_ZWAVEPLUS_INFO::Int32
    COMMAND_CLASS_ZIP_GATEWAY::Int32
    COMMAND_CLASS_MULTI_CHANNEL::Int32
    COMMAND_CLASS_MULTI_INSTANCE::Int32
    COMMAND_CLASS_ZIP_PORTAL::Int32
    COMMAND_CLASS_DOOR_LOCK::Int32
    COMMAND_CLASS_USER_CODE::Int32
    COMMAND_CLASS_HUMIDITY_CONTROL_SETPOINT::Int32
    COMMAND_CLASS_DMX::Int32
    COMMAND_CLASS_BARRIER_OPERATOR::Int32
    COMMAND_CLASS_NETWORK_MANAGEMENT_INSTALLATION_MAINTENANCE::Int32
    COMMAND_CLASS_ZIP_NAMING::Int32
    COMMAND_CLASS_MAILBOX::Int32
    COMMAND_CLASS_WINDOW_COVERING::Int32
    COMMAND_CLASS_IRRIGATION::Int32
    COMMAND_CLASS_SUPERVISION::Int32
    COMMAND_CLASS_HUMIDITY_CONTROL_MODE::Int32
    COMMAND_CLASS_HUMIDITY_CONTROL_OPERATING_STATE::Int32
    COMMAND_CLASS_ENTRY_CONTROL::Int32
    COMMAND_CLASS_CONFIGURATION::Int32
    COMMAND_CLASS_ALARM::Int32
    COMMAND_CLASS_NOTIFICATION::Int32
    COMMAND_CLASS_MANUFACTURER_SPECIFIC::Int32
    COMMAND_CLASS_POWERLEVEL::Int32
    COMMAND_CLASS_INCLUSION_CONTROLLER::Int32
    COMMAND_CLASS_PROTECTION::Int32
    COMMAND_CLASS_LOCK::Int32
    COMMAND_CLASS_NODE_NAMING::Int32
    COMMAND_CLASS_FIRMWARE_UPDATE_MD::Int32
    COMMAND_CLASS_GROUPING_NAME::Int32
    COMMAND_CLASS_REMOTE_ASSOCIATION_ACTIVATE::Int32
    COMMAND_CLASS_REMOTE_ASSOCIATION::Int32
    COMMAND_CLASS_BATTERY::Int32
    COMMAND_CLASS_CLOCK::Int32
    COMMAND_CLASS_HAIL::Int32
    COMMAND_CLASS_WAKE_UP::Int32
    COMMAND_CLASS_ASSOCIATION::Int32
    COMMAND_CLASS_VERSION::Int32
    COMMAND_CLASS_INDICATOR::Int32
    COMMAND_CLASS_PROPRIETARY::Int32
    COMMAND_CLASS_LANGUAGE::Int32
    COMMAND_CLASS_TIME::Int32
    COMMAND_CLASS_TIME_PARAMETERS::Int32
    COMMAND_CLASS_GEOGRAPHIC_LOCATION::Int32
    COMMAND_CLASS_MULTI_CHANNEL_ASSOCIATION::Int32
    COMMAND_CLASS_MULTI_INSTANCE_ASSOCIATION::Int32
    COMMAND_CLASS_MULTI_CMD::Int32
    COMMAND_CLASS_ENERGY_PRODUCTION::Int32
    COMMAND_CLASS_MANUFACTURER_PROPRIETARY::Int32
    COMMAND_CLASS_SCREEN_MD::Int32
    COMMAND_CLASS_SCREEN_ATTRIBUTES::Int32
    COMMAND_CLASS_SIMPLE_AV_CONTROL::Int32
    COMMAND_CLASS_AV_CONTENT_DIRECTORY_MD::Int32
    COMMAND_CLASS_AV_RENDERER_STATUS::Int32
    COMMAND_CLASS_AV_CONTENT_SEARCH_MD::Int32
    COMMAND_CLASS_SECURITY::Int32
    COMMAND_CLASS_AV_TAGGING_MD::Int32
    COMMAND_CLASS_IP_CONFIGURATION::Int32
    COMMAND_CLASS_ASSOCIATION_COMMAND_CONFIGURATION::Int32
    COMMAND_CLASS_SENSOR_ALARM::Int32
    COMMAND_CLASS_SILENCE_ALARM::Int32
    COMMAND_CLASS_SENSOR_CONFIGURATION::Int32
    COMMAND_CLASS_SECURITY_2::Int32
    COMMAND_CLASS_MARK::Int32
    COMMAND_CLASS_NON_INTEROPERABLE::Int32
    __enum_ZWaveClassType() = new(0,1,2,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,113,114,115,116,117,118,119,122,123,124,125,128,129,130,132,133,134,135,136,137,138,139,140,142,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,239,240)
end #struct __enum_ZWaveClassType
const ZWaveClassType = __enum_ZWaveClassType()

struct __enum_ZWaveCmdType <: ProtoEnum
    CMD_UNDEFINED::Int32
    ACCEPT_LOST::Int32
    ALARM_GET::Int32
    ALARM_REPORT::Int32
    ANTITHEFT_GET::Int32
    ANTITHEFT_REPORT::Int32
    ANTITHEFT_SET::Int32
    APPLICATION_BUSY::Int32
    APPLICATION_REJECTED_REQUEST::Int32
    ASSIGN_ID::Int32
    ASSIGN_RETURN_ROUTE::Int32
    ASSIGN_RETURN_ROUTE_PRIORITY::Int32
    ASSIGN_SUC_RETURN_ROUTE_PRIORITY::Int32
    ASSOCIATION_GET::Int32
    ASSOCIATION_GROUPINGS_GET::Int32
    ASSOCIATION_GROUPINGS_REPORT::Int32
    ASSOCIATION_GROUP_COMMAND_LIST_GET::Int32
    ASSOCIATION_GROUP_COMMAND_LIST_REPORT::Int32
    ASSOCIATION_GROUP_INFO_GET::Int32
    ASSOCIATION_GROUP_INFO_REPORT::Int32
    ASSOCIATION_GROUP_NAME_GET::Int32
    ASSOCIATION_GROUP_NAME_REPORT::Int32
    ASSOCIATION_REMOVE::Int32
    ASSOCIATION_REPORT::Int32
    ASSOCIATION_SET::Int32
    AV_CONTENT_BROWSE_MD_BY_LETTER_GET::Int32
    AV_CONTENT_BROWSE_MD_BY_LETTER_REPORT::Int32
    AV_CONTENT_BROWSE_MD_CHILD_COUNT_GET::Int32
    AV_CONTENT_BROWSE_MD_CHILD_COUNT_REPORT::Int32
    AV_CONTENT_BROWSE_MD_GET::Int32
    AV_CONTENT_BROWSE_MD_REPORT::Int32
    AV_CONTENT_SEARCH_MD_GET::Int32
    AV_CONTENT_SEARCH_MD_REPORT::Int32
    AV_MATCH_ITEM_TO_RENDERER_MD_GET::Int32
    AV_MATCH_ITEM_TO_RENDERER_MD_REPORT::Int32
    AV_RENDERER_STATUS_GET::Int32
    AV_RENDERER_STATUS_REPORT::Int32
    AV_TAGGING_MD_GET::Int32
    AV_TAGGING_MD_REPORT::Int32
    BARRIER_OPERATOR_GET::Int32
    BARRIER_OPERATOR_REPORT::Int32
    BARRIER_OPERATOR_SET::Int32
    BARRIER_OPERATOR_SIGNAL_GET::Int32
    BARRIER_OPERATOR_SIGNAL_REPORT::Int32
    BARRIER_OPERATOR_SIGNAL_SET::Int32
    BARRIER_OPERATOR_SIGNAL_SUPPORTED_GET::Int32
    BARRIER_OPERATOR_SIGNAL_SUPPORTED_REPORT::Int32
    BASIC_GET::Int32
    BASIC_REPORT::Int32
    BASIC_SET::Int32
    BASIC_TARIFF_INFO_GET::Int32
    BASIC_TARIFF_INFO_REPORT::Int32
    BASIC_WINDOW_COVERING_START_LEVEL_CHANGE::Int32
    BASIC_WINDOW_COVERING_STOP_LEVEL_CHANGE::Int32
    BATTERY_GET::Int32
    BATTERY_REPORT::Int32
    BIND_ACCEPT::Int32
    BIND_COMPLETE::Int32
    BIND_REQUEST::Int32
    CENTRAL_SCENE_NOTIFICATION::Int32
    CENTRAL_SCENE_SUPPORTED_GET::Int32
    CENTRAL_SCENE_SUPPORTED_REPORT::Int32
    CHIMNEY_FAN_ALARM_LOG_GET::Int32
    CHIMNEY_FAN_ALARM_LOG_REPORT::Int32
    CHIMNEY_FAN_ALARM_LOG_SET::Int32
    CHIMNEY_FAN_ALARM_STATUS_GET::Int32
    CHIMNEY_FAN_ALARM_STATUS_REPORT::Int32
    CHIMNEY_FAN_ALARM_STATUS_SET::Int32
    CHIMNEY_FAN_ALARM_TEMP_GET::Int32
    CHIMNEY_FAN_ALARM_TEMP_REPORT::Int32
    CHIMNEY_FAN_ALARM_TEMP_SET::Int32
    CHIMNEY_FAN_BOOST_TIME_GET::Int32
    CHIMNEY_FAN_BOOST_TIME_REPORT::Int32
    CHIMNEY_FAN_BOOST_TIME_SET::Int32
    CHIMNEY_FAN_DEFAULT_SET::Int32
    CHIMNEY_FAN_MIN_SPEED_GET::Int32
    CHIMNEY_FAN_MIN_SPEED_REPORT::Int32
    CHIMNEY_FAN_MIN_SPEED_SET::Int32
    CHIMNEY_FAN_MODE_GET::Int32
    CHIMNEY_FAN_MODE_REPORT::Int32
    CHIMNEY_FAN_MODE_SET::Int32
    CHIMNEY_FAN_SETUP_GET::Int32
    CHIMNEY_FAN_SETUP_REPORT::Int32
    CHIMNEY_FAN_SETUP_SET::Int32
    CHIMNEY_FAN_SPEED_GET::Int32
    CHIMNEY_FAN_SPEED_REPORT::Int32
    CHIMNEY_FAN_SPEED_SET::Int32
    CHIMNEY_FAN_START_TEMP_GET::Int32
    CHIMNEY_FAN_START_TEMP_REPORT::Int32
    CHIMNEY_FAN_START_TEMP_SET::Int32
    CHIMNEY_FAN_STATE_GET::Int32
    CHIMNEY_FAN_STATE_REPORT::Int32
    CHIMNEY_FAN_STATE_SET::Int32
    CHIMNEY_FAN_STATUS_GET::Int32
    CHIMNEY_FAN_STATUS_REPORT::Int32
    CHIMNEY_FAN_STOP_TEMP_GET::Int32
    CHIMNEY_FAN_STOP_TEMP_REPORT::Int32
    CHIMNEY_FAN_STOP_TEMP_SET::Int32
    CHIMNEY_FAN_STOP_TIME_GET::Int32
    CHIMNEY_FAN_STOP_TIME_REPORT::Int32
    CHIMNEY_FAN_STOP_TIME_SET::Int32
    CLOCK_GET::Int32
    CLOCK_REPORT::Int32
    CLOCK_SET::Int32
    CMD_ASSIGN_SUC_RETURN_ROUTE::Int32
    CMD_AUTOMATIC_CONTROLLER_UPDATE_START::Int32
    CMD_ENCAPSULATION::Int32
    CMD_NODES_EXIST::Int32
    CMD_NODES_EXIST_REPLY::Int32
    CMD_NOP_POWER::Int32
    CMD_RESERVED_IDS::Int32
    CMD_SET_NWI_MODE::Int32
    CMD_SET_SUC::Int32
    CMD_SET_SUC_ACK::Int32
    CMD_STATIC_ROUTE_REQUEST::Int32
    CMD_SUC_NODE_ID::Int32
    COMMAND_APPLICATION_NODE_INFO_GET::Int32
    COMMAND_APPLICATION_NODE_INFO_REPORT::Int32
    COMMAND_APPLICATION_NODE_INFO_SET::Int32
    COMMAND_CLASS_SECURITY_PANEL_ZONE_SENSOR_INSTALLED_REPORT::Int32
    COMMAND_COMMAND_CLASS_NOT_SUPPORTED::Int32
    COMMAND_COMPLETE::Int32
    COMMAND_CONFIGURATION_GET::Int32
    COMMAND_CONFIGURATION_REPORT::Int32
    COMMAND_CONFIGURATION_SET::Int32
    COMMAND_FIRST_SEGMENT::Int32
    COMMAND_RECORDS_SUPPORTED_GET::Int32
    COMMAND_RECORDS_SUPPORTED_REPORT::Int32
    COMMAND_SCHEDULE_GET::Int32
    COMMAND_SCHEDULE_REPORT::Int32
    COMMAND_SCHEDULE_SET::Int32
    COMMAND_SEGMENT_COMPLETE::Int32
    COMMAND_SEGMENT_REQUEST::Int32
    COMMAND_SEGMENT_WAIT::Int32
    COMMAND_SUBSEQUENT_SEGMENT::Int32
    COMMAND_ZIP_PACKET::Int32
    COMPLETE::Int32
    CONFIGURATION_GET::Int32
    CONFIGURATION_REPORT::Int32
    CONFIGURATION_SET::Int32
    CONTROLLER_CHANGE::Int32
    CONTROLLER_CHANGE_STATUS::Int32
    CRC_16_ENCAP::Int32
    CTRL_REPLICATION_TRANSFER_GROUP::Int32
    CTRL_REPLICATION_TRANSFER_GROUP_NAME::Int32
    CTRL_REPLICATION_TRANSFER_SCENE::Int32
    CTRL_REPLICATION_TRANSFER_SCENE_NAME::Int32
    DATE_GET::Int32
    DATE_REPORT::Int32
    DCP_EVENT_STATUS_GET::Int32
    DCP_EVENT_STATUS_REPORT::Int32
    DCP_LIST_GET::Int32
    DCP_LIST_REMOVE::Int32
    DCP_LIST_REPORT::Int32
    DCP_LIST_SET::Int32
    DCP_LIST_SUPPORTED_GET::Int32
    DCP_LIST_SUPPORTED_REPORT::Int32
    DEFAULT_SET::Int32
    DEFAULT_SET_COMPLETE::Int32
    DEVICE_RESET_LOCALLY_NOTIFICATION::Int32
    DMX_ADDRESS_GET::Int32
    DMX_ADDRESS_REPORT::Int32
    DMX_ADDRESS_SET::Int32
    DMX_CAPABILITY_GET::Int32
    DMX_CAPABILITY_REPORT::Int32
    DMX_DATA::Int32
    DOOR_LOCK_CONFIGURATION_GET::Int32
    DOOR_LOCK_CONFIGURATION_REPORT::Int32
    DOOR_LOCK_CONFIGURATION_SET::Int32
    DOOR_LOCK_LOGGING_RECORDS_SUPPORTED_GET::Int32
    DOOR_LOCK_LOGGING_RECORDS_SUPPORTED_REPORT::Int32
    DOOR_LOCK_OPERATION_GET::Int32
    DOOR_LOCK_OPERATION_REPORT::Int32
    DOOR_LOCK_OPERATION_SET::Int32
    ENERGY_PRODUCTION_GET::Int32
    ENERGY_PRODUCTION_REPORT::Int32
    ENTRY_CONTROL_CONFIGURATION_GET::Int32
    ENTRY_CONTROL_CONFIGURATION_REPORT::Int32
    ENTRY_CONTROL_CONFIGURATION_SET::Int32
    ENTRY_CONTROL_EVENT_SUPPORTED_GET::Int32
    ENTRY_CONTROL_EVENT_SUPPORTED_REPORT::Int32
    ENTRY_CONTROL_KEY_SUPPORTED_GET::Int32
    ENTRY_CONTROL_KEY_SUPPORTED_REPORT::Int32
    ENTRY_CONTROL_NOTIFICATION::Int32
    EVENT_SUPPORTED_GET::Int32
    EVENT_SUPPORTED_REPORT::Int32
    EXCLUDE_REQUEST::Int32
    FAILED_NODE_REMOVE::Int32
    FAILED_NODE_REMOVE_STATUS::Int32
    FAILED_NODE_REPLACE::Int32
    FAILED_NODE_REPLACE_STATUS::Int32
    FIND_NODES_IN_RANGE::Int32
    FIRMWARE_MD_GET::Int32
    FIRMWARE_MD_REPORT::Int32
    FIRMWARE_UPDATE_MD_GET::Int32
    FIRMWARE_UPDATE_MD_REPORT::Int32
    FIRMWARE_UPDATE_MD_REQUEST_GET::Int32
    FIRMWARE_UPDATE_MD_REQUEST_REPORT::Int32
    FIRMWARE_UPDATE_MD_STATUS_REPORT::Int32
    GATEWAY_CONFIGURATION_GET::Int32
    GATEWAY_CONFIGURATION_REPORT::Int32
    GATEWAY_CONFIGURATION_SET::Int32
    GATEWAY_CONFIGURATION_STATUS::Int32
    GATEWAY_LOCK_SET::Int32
    GATEWAY_MODE_GET::Int32
    GATEWAY_MODE_REPORT::Int32
    GATEWAY_MODE_SET::Int32
    GATEWAY_PEER_GET::Int32
    GATEWAY_PEER_REPORT::Int32
    GATEWAY_PEER_SET::Int32
    GEOGRAPHIC_LOCATION_GET::Int32
    GEOGRAPHIC_LOCATION_REPORT::Int32
    GEOGRAPHIC_LOCATION_SET::Int32
    GET_NODES_IN_RANGE::Int32
    GROUPING_NAME_GET::Int32
    GROUPING_NAME_REPORT::Int32
    GROUPING_NAME_SET::Int32
    HAIL::Int32
    HRV_CONTROL_BYPASS_GET::Int32
    HRV_CONTROL_BYPASS_REPORT::Int32
    HRV_CONTROL_BYPASS_SET::Int32
    HRV_CONTROL_MODE_GET::Int32
    HRV_CONTROL_MODE_REPORT::Int32
    HRV_CONTROL_MODE_SET::Int32
    HRV_CONTROL_MODE_SUPPORTED_GET::Int32
    HRV_CONTROL_MODE_SUPPORTED_REPORT::Int32
    HRV_CONTROL_VENTILATION_RATE_GET::Int32
    HRV_CONTROL_VENTILATION_RATE_REPORT::Int32
    HRV_CONTROL_VENTILATION_RATE_SET::Int32
    HRV_STATUS_GET::Int32
    HRV_STATUS_REPORT::Int32
    HRV_STATUS_SUPPORTED_GET::Int32
    HRV_STATUS_SUPPORTED_REPORT::Int32
    HUMIDITY_CONTROL_MODE_GET::Int32
    HUMIDITY_CONTROL_MODE_REPORT::Int32
    HUMIDITY_CONTROL_MODE_SET::Int32
    HUMIDITY_CONTROL_MODE_SUPPORTED_GET::Int32
    HUMIDITY_CONTROL_MODE_SUPPORTED_REPORT::Int32
    HUMIDITY_CONTROL_OPERATING_STATE_GET::Int32
    HUMIDITY_CONTROL_OPERATING_STATE_REPORT::Int32
    HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET::Int32
    HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT::Int32
    HUMIDITY_CONTROL_SETPOINT_GET::Int32
    HUMIDITY_CONTROL_SETPOINT_REPORT::Int32
    HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET::Int32
    HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT::Int32
    HUMIDITY_CONTROL_SETPOINT_SET::Int32
    HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET::Int32
    HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT::Int32
    INDICATOR_GET::Int32
    INDICATOR_REPORT::Int32
    INDICATOR_SET::Int32
    INITIATE::Int32
    IP_ASSOCIATION_GET::Int32
    IP_ASSOCIATION_REMOVE::Int32
    IP_ASSOCIATION_REPORT::Int32
    IP_ASSOCIATION_SET::Int32
    IP_CONFIGURATION_GET::Int32
    IP_CONFIGURATION_RELEASE::Int32
    IP_CONFIGURATION_RENEW::Int32
    IP_CONFIGURATION_REPORT::Int32
    IP_CONFIGURATION_SET::Int32
    IRRIGATION_SYSTEM_CONFIG_GET::Int32
    IRRIGATION_SYSTEM_CONFIG_REPORT::Int32
    IRRIGATION_SYSTEM_CONFIG_SET::Int32
    IRRIGATION_SYSTEM_INFO_GET::Int32
    IRRIGATION_SYSTEM_INFO_REPORT::Int32
    IRRIGATION_SYSTEM_SHUTOFF::Int32
    IRRIGATION_SYSTEM_STATUS_GET::Int32
    IRRIGATION_SYSTEM_STATUS_REPORT::Int32
    IRRIGATION_VALVE_CONFIG_GET::Int32
    IRRIGATION_VALVE_CONFIG_REPORT::Int32
    IRRIGATION_VALVE_CONFIG_SET::Int32
    IRRIGATION_VALVE_INFO_GET::Int32
    IRRIGATION_VALVE_INFO_REPORT::Int32
    IRRIGATION_VALVE_RUN::Int32
    IRRIGATION_VALVE_TABLE_GET::Int32
    IRRIGATION_VALVE_TABLE_REPORT::Int32
    IRRIGATION_VALVE_TABLE_RUN::Int32
    IRRIGATION_VALVE_TABLE_SET::Int32
    KEX_FAIL::Int32
    KEX_GET::Int32
    KEX_REPORT::Int32
    KEX_SET::Int32
    LANGUAGE_GET::Int32
    LANGUAGE_REPORT::Int32
    LANGUAGE_SET::Int32
    LAST_WORKING_ROUTE_GET::Int32
    LAST_WORKING_ROUTE_REPORT::Int32
    LAST_WORKING_ROUTE_SET::Int32
    LEARN_MODE_SET::Int32
    LEARN_MODE_SET_STATUS::Int32
    LOCK_GET::Int32
    LOCK_REPORT::Int32
    LOCK_SET::Int32
    LOST::Int32
    LOWPAN_FIRST_FRAGMENT::Int32
    LOWPAN_SUBSEQUENT_FRAGMENT::Int32
    MAILBOX_CONFIGURATION_GET::Int32
    MAILBOX_CONFIGURATION_REPORT::Int32
    MAILBOX_CONFIGURATION_SET::Int32
    MAILBOX_NODE_FAILING::Int32
    MAILBOX_QUEUE::Int32
    MAILBOX_WAKEUP_NOTIFICATION::Int32
    MANUFACTURER_SPECIFIC_GET::Int32
    MANUFACTURER_SPECIFIC_REPORT::Int32
    METER_GET::Int32
    METER_PULSE_GET::Int32
    METER_PULSE_REPORT::Int32
    METER_REPORT::Int32
    METER_TBL_CURRENT_DATA_GET::Int32
    METER_TBL_CURRENT_DATA_REPORT::Int32
    METER_TBL_HISTORICAL_DATA_GET::Int32
    METER_TBL_HISTORICAL_DATA_REPORT::Int32
    METER_TBL_PUSH_CONFIGURATION_GET::Int32
    METER_TBL_PUSH_CONFIGURATION_REPORT::Int32
    METER_TBL_PUSH_CONFIGURATION_SET::Int32
    METER_TBL_REPORT::Int32
    METER_TBL_STATUS_DATE_GET::Int32
    METER_TBL_STATUS_DEPTH_GET::Int32
    METER_TBL_STATUS_REPORT::Int32
    METER_TBL_STATUS_SUPPORTED_GET::Int32
    METER_TBL_STATUS_SUPPORTED_REPORT::Int32
    METER_TBL_TABLE_CAPABILITY_GET::Int32
    METER_TBL_TABLE_ID_GET::Int32
    METER_TBL_TABLE_ID_REPORT::Int32
    METER_TBL_TABLE_POINT_ADM_NO_GET::Int32
    METER_TBL_TABLE_POINT_ADM_NO_REPORT::Int32
    METER_TBL_TABLE_POINT_ADM_NO_SET::Int32
    MOVE_TO_POSITION_GET::Int32
    MOVE_TO_POSITION_REPORT::Int32
    MOVE_TO_POSITION_SET::Int32
    MULTI_CHANNEL_ASSOCIATION_GET::Int32
    MULTI_CHANNEL_ASSOCIATION_GROUPINGS_GET::Int32
    MULTI_CHANNEL_ASSOCIATION_GROUPINGS_REPORT::Int32
    MULTI_CHANNEL_ASSOCIATION_REMOVE::Int32
    MULTI_CHANNEL_ASSOCIATION_REPORT::Int32
    MULTI_CHANNEL_ASSOCIATION_SET::Int32
    MULTI_CHANNEL_CAPABILITY_GET::Int32
    MULTI_CHANNEL_CAPABILITY_REPORT::Int32
    MULTI_CHANNEL_CMD_ENCAP::Int32
    MULTI_CHANNEL_END_POINT_FIND::Int32
    MULTI_CHANNEL_END_POINT_FIND_REPORT::Int32
    MULTI_CHANNEL_END_POINT_GET::Int32
    MULTI_CHANNEL_END_POINT_REPORT::Int32
    MULTI_CMD_ENCAP::Int32
    MULTI_INSTANCE_ASSOCIATION_GET::Int32
    MULTI_INSTANCE_ASSOCIATION_GROUPINGS_GET::Int32
    MULTI_INSTANCE_ASSOCIATION_GROUPINGS_REPORT::Int32
    MULTI_INSTANCE_ASSOCIATION_REMOVE::Int32
    MULTI_INSTANCE_ASSOCIATION_REPORT::Int32
    MULTI_INSTANCE_ASSOCIATION_SET::Int32
    MULTI_INSTANCE_CMD_ENCAP::Int32
    MULTI_INSTANCE_GET::Int32
    MULTI_INSTANCE_REPORT::Int32
    NETWORK_KEY_SET::Int32
    NETWORK_KEY_VERIFY::Int32
    NETWORK_UPDATE_REQUEST::Int32
    NETWORK_UPDATE_REQUEST_STATUS::Int32
    NEW_NODE_REGISTERED::Int32
    NEW_RANGE_REGISTERED::Int32
    NODE_ADD::Int32
    NODE_ADD_STATUS::Int32
    NODE_INFO::Int32
    NODE_INFORMATION_SEND::Int32
    NODE_INFO_CACHED_GET::Int32
    NODE_INFO_CACHED_REPORT::Int32
    NODE_LIST_GET::Int32
    NODE_LIST_REPORT::Int32
    NODE_NAMING_NODE_LOCATION_GET::Int32
    NODE_NAMING_NODE_LOCATION_REPORT::Int32
    NODE_NAMING_NODE_LOCATION_SET::Int32
    NODE_NAMING_NODE_NAME_GET::Int32
    NODE_NAMING_NODE_NAME_REPORT::Int32
    NODE_NAMING_NODE_NAME_SET::Int32
    NODE_NEIGHBOR_UPDATE_REQUEST::Int32
    NODE_NEIGHBOR_UPDATE_STATUS::Int32
    NODE_RANGE_INFO::Int32
    NODE_REMOVE::Int32
    NODE_REMOVE_STATUS::Int32
    NOTIFICATION_GET::Int32
    NOTIFICATION_REPORT::Int32
    NOTIFICATION_SET::Int32
    NOTIFICATION_SUPPORTED_GET::Int32
    NOTIFICATION_SUPPORTED_REPORT::Int32
    POWERLEVEL_GET::Int32
    POWERLEVEL_REPORT::Int32
    POWERLEVEL_SET::Int32
    POWERLEVEL_TEST_NODE_GET::Int32
    POWERLEVEL_TEST_NODE_REPORT::Int32
    POWERLEVEL_TEST_NODE_SET::Int32
    PREPAYMENT_BALANCE_GET::Int32
    PREPAYMENT_BALANCE_REPORT::Int32
    PREPAYMENT_SUPPORTED_GET::Int32
    PREPAYMENT_SUPPORTED_REPORT::Int32
    PROPRIETARY_GET::Int32
    PROPRIETARY_REPORT::Int32
    PROPRIETARY_SET::Int32
    PROTECTION_GET::Int32
    PROTECTION_REPORT::Int32
    PROTECTION_SET::Int32
    PUBLIC_KEY_REPORT::Int32
    RATE_TBL_ACTIVE_RATE_GET::Int32
    RATE_TBL_ACTIVE_RATE_REPORT::Int32
    RATE_TBL_CURRENT_DATA_GET::Int32
    RATE_TBL_CURRENT_DATA_REPORT::Int32
    RATE_TBL_GET::Int32
    RATE_TBL_HISTORICAL_DATA_GET::Int32
    RATE_TBL_HISTORICAL_DATA_REPORT::Int32
    RATE_TBL_REMOVE::Int32
    RATE_TBL_REPORT::Int32
    RATE_TBL_SET::Int32
    RATE_TBL_SUPPORTED_GET::Int32
    RATE_TBL_SUPPORTED_REPORT::Int32
    RECORD_GET::Int32
    RECORD_REPORT::Int32
    REMOTE_ASSOCIATION_ACTIVATE::Int32
    REMOTE_ASSOCIATION_CONFIGURATION_GET::Int32
    REMOTE_ASSOCIATION_CONFIGURATION_REPORT::Int32
    REMOTE_ASSOCIATION_CONFIGURATION_SET::Int32
    REQUEST_NODE_INFO::Int32
    RETURN_ROUTE_ASSIGN::Int32
    RETURN_ROUTE_ASSIGN_COMPLETE::Int32
    RETURN_ROUTE_DELETE::Int32
    RETURN_ROUTE_DELETE_COMPLETE::Int32
    SCENE_ACTIVATION_SET::Int32
    SCENE_ACTUATOR_CONF_GET::Int32
    SCENE_ACTUATOR_CONF_REPORT::Int32
    SCENE_ACTUATOR_CONF_SET::Int32
    SCENE_CONTROLLER_CONF_GET::Int32
    SCENE_CONTROLLER_CONF_REPORT::Int32
    SCENE_CONTROLLER_CONF_SET::Int32
    SCHEDULE_CHANGED_GET::Int32
    SCHEDULE_CHANGED_REPORT::Int32
    SCHEDULE_ENTRY_LOCK_ENABLE_ALL_SET::Int32
    SCHEDULE_ENTRY_LOCK_ENABLE_SET::Int32
    SCHEDULE_ENTRY_LOCK_WEEK_DAY_GET::Int32
    SCHEDULE_ENTRY_LOCK_WEEK_DAY_REPORT::Int32
    SCHEDULE_ENTRY_LOCK_WEEK_DAY_SET::Int32
    SCHEDULE_ENTRY_LOCK_YEAR_DAY_GET::Int32
    SCHEDULE_ENTRY_LOCK_YEAR_DAY_REPORT::Int32
    SCHEDULE_ENTRY_LOCK_YEAR_DAY_SET::Int32
    SCHEDULE_ENTRY_TYPE_SUPPORTED_GET::Int32
    SCHEDULE_ENTRY_TYPE_SUPPORTED_REPORT::Int32
    SCHEDULE_GET::Int32
    SCHEDULE_OVERRIDE_GET::Int32
    SCHEDULE_OVERRIDE_REPORT::Int32
    SCHEDULE_OVERRIDE_SET::Int32
    SCHEDULE_REMOVE::Int32
    SCHEDULE_REPORT::Int32
    SCHEDULE_SET::Int32
    SCHEDULE_STATE_GET::Int32
    SCHEDULE_STATE_REPORT::Int32
    SCHEDULE_STATE_SET::Int32
    SCHEDULE_SUPPORTED_GET::Int32
    SCHEDULE_SUPPORTED_REPORT::Int32
    SCREEN_ATTRIBUTES_GET::Int32
    SCREEN_ATTRIBUTES_REPORT::Int32
    SCREEN_MD_GET::Int32
    SCREEN_MD_REPORT::Int32
    SECURITY_2_CAPABILITIES_GET::Int32
    SECURITY_2_CAPABILITIES_REPORT::Int32
    SECURITY_2_COMMANDS_SUPPORTED_GET::Int32
    SECURITY_2_COMMANDS_SUPPORTED_REPORT::Int32
    SECURITY_2_MESSAGE_ENCAPSULATION::Int32
    SECURITY_2_NETWORK_KEY_GET::Int32
    SECURITY_2_NETWORK_KEY_REPORT::Int32
    SECURITY_2_NETWORK_KEY_VERIFY::Int32
    SECURITY_2_NONCE_GET::Int32
    SECURITY_2_NONCE_REPORT::Int32
    SECURITY_2_TRANSFER_END::Int32
    SECURITY_COMMANDS_SUPPORTED_GET::Int32
    SECURITY_COMMANDS_SUPPORTED_REPORT::Int32
    SECURITY_MESSAGE_ENCAPSULATION::Int32
    SECURITY_MESSAGE_ENCAPSULATION_NONCE_GET::Int32
    SECURITY_NONCE_GET::Int32
    SECURITY_NONCE_REPORT::Int32
    SECURITY_PANEL_MODE_GET::Int32
    SECURITY_PANEL_MODE_REPORT::Int32
    SECURITY_PANEL_MODE_SET::Int32
    SECURITY_PANEL_MODE_SUPPORTED_GET::Int32
    SECURITY_PANEL_MODE_SUPPORTED_REPORT::Int32
    SECURITY_PANEL_ZONE_NUMBER_SUPPORTED_GET::Int32
    SECURITY_PANEL_ZONE_SENSOR_INSTALLED_GET::Int32
    SECURITY_PANEL_ZONE_SENSOR_STATE_GET::Int32
    SECURITY_PANEL_ZONE_SENSOR_STATE_REPORT::Int32
    SECURITY_PANEL_ZONE_SENSOR_TYPE_GET::Int32
    SECURITY_PANEL_ZONE_SENSOR_TYPE_REPORT::Int32
    SECURITY_PANEL_ZONE_STATE_GET::Int32
    SECURITY_PANEL_ZONE_STATE_REPORT::Int32
    SECURITY_PANEL_ZONE_SUPPORTED_REPORT::Int32
    SECURITY_PANEL_ZONE_TYPE_GET::Int32
    SECURITY_PANEL_ZONE_TYPE_REPORT::Int32
    SECURITY_SCHEME_GET::Int32
    SECURITY_SCHEME_INHERIT::Int32
    SECURITY_SCHEME_REPORT::Int32
    SENSOR_ALARM_GET::Int32
    SENSOR_ALARM_REPORT::Int32
    SENSOR_ALARM_SET::Int32
    SENSOR_ALARM_SUPPORTED_GET::Int32
    SENSOR_ALARM_SUPPORTED_REPORT::Int32
    SENSOR_BINARY_GET::Int32
    SENSOR_BINARY_REPORT::Int32
    SENSOR_MULTILEVEL_GET::Int32
    SENSOR_MULTILEVEL_REPORT::Int32
    SENSOR_TRIGGER_LEVEL_GET::Int32
    SENSOR_TRIGGER_LEVEL_REPORT::Int32
    SENSOR_TRIGGER_LEVEL_SET::Int32
    SIMPLE_AV_CONTROL_GET::Int32
    SIMPLE_AV_CONTROL_REPORT::Int32
    SIMPLE_AV_CONTROL_SET::Int32
    SIMPLE_AV_CONTROL_SUPPORTED_GET::Int32
    SIMPLE_AV_CONTROL_SUPPORTED_REPORT::Int32
    STATISTICS_CLEAR::Int32
    STATISTICS_GET::Int32
    STATISTICS_REPORT::Int32
    SUPERVISION_GET::Int32
    SUPERVISION_REPORT::Int32
    SWITCH_ALL_GET::Int32
    SWITCH_ALL_OFF::Int32
    SWITCH_ALL_ON::Int32
    SWITCH_ALL_REPORT::Int32
    SWITCH_ALL_SET::Int32
    SWITCH_BINARY_GET::Int32
    SWITCH_BINARY_REPORT::Int32
    SWITCH_BINARY_SET::Int32
    SWITCH_COLOR_GET::Int32
    SWITCH_COLOR_REPORT::Int32
    SWITCH_COLOR_SET::Int32
    SWITCH_COLOR_START_LEVEL_CHANGE::Int32
    SWITCH_COLOR_STOP_LEVEL_CHANGE::Int32
    SWITCH_COLOR_SUPPORTED_GET::Int32
    SWITCH_COLOR_SUPPORTED_REPORT::Int32
    SWITCH_MULTILEVEL_GET::Int32
    SWITCH_MULTILEVEL_REPORT::Int32
    SWITCH_MULTILEVEL_SET::Int32
    SWITCH_MULTILEVEL_START_LEVEL_CHANGE::Int32
    SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE::Int32
    SWITCH_TOGGLE_BINARY_GET::Int32
    SWITCH_TOGGLE_BINARY_REPORT::Int32
    SWITCH_TOGGLE_BINARY_SET::Int32
    SWITCH_TOGGLE_MULTILEVEL_GET::Int32
    SWITCH_TOGGLE_MULTILEVEL_REPORT::Int32
    SWITCH_TOGGLE_MULTILEVEL_SET::Int32
    SWITCH_TOGGLE_MULTILEVEL_START_LEVEL_CHANGE::Int32
    SWITCH_TOGGLE_MULTILEVEL_STOP_LEVEL_CHANGE::Int32
    TARIFF_TBL_COST_GET::Int32
    TARIFF_TBL_COST_REPORT::Int32
    TARIFF_TBL_GET::Int32
    TARIFF_TBL_REMOVE::Int32
    TARIFF_TBL_REPORT::Int32
    TARIFF_TBL_SET::Int32
    TARIFF_TBL_SUPPLIER_GET::Int32
    TARIFF_TBL_SUPPLIER_REPORT::Int32
    TARIFF_TBL_SUPPLIER_SET::Int32
    THERMOSTAT_FAN_MODE_GET::Int32
    THERMOSTAT_FAN_MODE_REPORT::Int32
    THERMOSTAT_FAN_MODE_SET::Int32
    THERMOSTAT_FAN_MODE_SUPPORTED_GET::Int32
    THERMOSTAT_FAN_MODE_SUPPORTED_REPORT::Int32
    THERMOSTAT_FAN_STATE_GET::Int32
    THERMOSTAT_FAN_STATE_REPORT::Int32
    THERMOSTAT_HEATING_MODE_GET::Int32
    THERMOSTAT_HEATING_MODE_REPORT::Int32
    THERMOSTAT_HEATING_MODE_SET::Int32
    THERMOSTAT_HEATING_RELAY_STATUS_GET::Int32
    THERMOSTAT_HEATING_RELAY_STATUS_REPORT::Int32
    THERMOSTAT_HEATING_SETPOINT_GET::Int32
    THERMOSTAT_HEATING_SETPOINT_REPORT::Int32
    THERMOSTAT_HEATING_SETPOINT_SET::Int32
    THERMOSTAT_HEATING_STATUS_GET::Int32
    THERMOSTAT_HEATING_STATUS_REPORT::Int32
    THERMOSTAT_HEATING_STATUS_SET::Int32
    THERMOSTAT_HEATING_TIMED_OFF_SET::Int32
    THERMOSTAT_MODE_GET::Int32
    THERMOSTAT_MODE_REPORT::Int32
    THERMOSTAT_MODE_SET::Int32
    THERMOSTAT_MODE_SUPPORTED_GET::Int32
    THERMOSTAT_MODE_SUPPORTED_REPORT::Int32
    THERMOSTAT_OPERATING_STATE_GET::Int32
    THERMOSTAT_OPERATING_STATE_REPORT::Int32
    THERMOSTAT_SETBACK_GET::Int32
    THERMOSTAT_SETBACK_REPORT::Int32
    THERMOSTAT_SETBACK_SET::Int32
    THERMOSTAT_SETPOINT_GET::Int32
    THERMOSTAT_SETPOINT_REPORT::Int32
    THERMOSTAT_SETPOINT_SET::Int32
    THERMOSTAT_SETPOINT_SUPPORTED_GET::Int32
    THERMOSTAT_SETPOINT_SUPPORTED_REPORT::Int32
    TIME_GET::Int32
    TIME_PARAMETERS_GET::Int32
    TIME_PARAMETERS_REPORT::Int32
    TIME_PARAMETERS_SET::Int32
    TIME_REPORT::Int32
    TRANSFER_END::Int32
    TRANSFER_NEW_PRIMARY_COMPLETE::Int32
    TRANSFER_NODE_INFO::Int32
    TRANSFER_PRESENTATION::Int32
    TRANSFER_RANGE_INFO::Int32
    UNSOLICITED_DESTINATION_GET::Int32
    UNSOLICITED_DESTINATION_REPORT::Int32
    UNSOLICITED_DESTINATION_SET::Int32
    USERS_NUMBER_GET::Int32
    USERS_NUMBER_REPORT::Int32
    USER_CODE_GET::Int32
    USER_CODE_REPORT::Int32
    USER_CODE_SET::Int32
    VERSION_COMMAND_CLASS_GET::Int32
    VERSION_COMMAND_CLASS_REPORT::Int32
    VERSION_GET::Int32
    VERSION_REPORT::Int32
    WAKE_UP_INTERVAL_GET::Int32
    WAKE_UP_INTERVAL_REPORT::Int32
    WAKE_UP_INTERVAL_SET::Int32
    WAKE_UP_NOTIFICATION::Int32
    WAKE_UP_NO_MORE_INFORMATION::Int32
    WINDOW_COVERING_GET::Int32
    WINDOW_COVERING_REPORT::Int32
    WINDOW_COVERING_SET::Int32
    WINDOW_COVERING_START_LEVEL_CHANGE::Int32
    WINDOW_COVERING_STOP_LEVEL_CHANGE::Int32
    WINDOW_COVERING_SUPPORTED_GET::Int32
    WINDOW_COVERING_SUPPORTED_REPORT::Int32
    ZIP_INV_NODE_SOLICITATION::Int32
    ZIP_NAMING_LOCATION_GET::Int32
    ZIP_NAMING_LOCATION_REPORT::Int32
    ZIP_NAMING_LOCATION_SET::Int32
    ZIP_NAMING_NAME_GET::Int32
    ZIP_NAMING_NAME_REPORT::Int32
    ZIP_NAMING_NAME_SET::Int32
    ZIP_NODE_ADVERTISEMENT::Int32
    ZIP_NODE_SOLICITATION::Int32
    ZWAVEPLUS_INFO_GET::Int32
    ZWAVEPLUS_INFO_REPORT::Int32
    ZWAVE_CMD_NOP::Int32
    ZWAVE_CMD_RESERVE_NODE_IDS::Int32
    __enum_ZWaveCmdType() = new(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635)
end #struct __enum_ZWaveCmdType
const ZWaveCmdType = __enum_ZWaveCmdType()

export ZWaveClassType, ZWaveCmdType


text:
function update_lam_logpostvec!(i::Int, n::Int, s::State, c::Constants, d::Data)
  logprior0 = log(s.eps[i])
  loglike0 = logdnoisy(i, n, s, c, d)
  logPost0 = logprior0 + loglike0

  logpriorVec = log.(s.W[i,:]) .+ log(1.0 - s.eps[i])
  loglikeVec = zeros(c.K)

  for k in 1:c.K
    for j in 1:d.J
      z = s.Z[j, k]
      loglikeVec[k] += logdmixture(z, i, n, j, s, c, d)
    end
  end

  logPostVec = logpriorVec .+ loglikeVec

  return [logPost0; logPostVec]
end

function update_lam!(i::Int, n::Int, s::State, c::Constants, d::Data)
  logPostVec = update_lam_logpostvec!(i, n, s, c, d)
  k = MCMC.wsample_logprob(logPostVec) - 1
  s.lam[i][n] = k
end

function update_lam!(s::State, c::Constants, d::Data)
  for i in 1:d.I
    for n in 1:d.N[i]
      update_lam!(i, n, s, c, d)
    end
  end
end

ext: jl

max_stars_repo_name: luiarthur/CytofResearch

max_issues_repo_name: luiarthur/CytofResearch

max_forks_repo_name: luiarthur/CytofResearch


text:
using ApproxFunBase, LinearAlgebra, Random, Test
    import ApproxFunBase: Infinity, ∞

@testset "Helper" begin
    @testset "interlace" begin
        @test ApproxFunBase.interlace!([-1.0],0) == [-1.0]
        @test ApproxFunBase.interlace!([1.0,2.0],0) == [2.0,1.0]
        @test ApproxFunBase.interlace!([1,2,3],0) == [2,1,3]
        @test ApproxFunBase.interlace!([1,2,3,4],0) == [3,1,4,2]

        @test ApproxFunBase.interlace!([-1.0],1) == [-1.0]
        @test ApproxFunBase.interlace!([1.0,2.0],1) == [1.0,2.0]
        @test ApproxFunBase.interlace!([1,2,3],1) == [1,3,2]
        @test ApproxFunBase.interlace!([1,2,3,4],1) == [1,3,2,4]

        @test ApproxFunBase.interlace(collect(6:10),collect(1:5)) == ApproxFunBase.interlace!(collect(1:10),0)
        @test ApproxFunBase.interlace(collect(1:5),collect(6:10)) == ApproxFunBase.interlace!(collect(1:10),1)
    end

    @testset "Iterators" begin
        @test cache(ApproxFunBase.BlockInterlacer((1:∞,[2],[2])))[1:6] ==
            [(1,1),(2,1),(2,2),(3,1),(3,2),(1,2)]

        @test collect(ApproxFunBase.BlockInterlacer(([2],[2],[2]))) ==
            [(1,1),(1,2),(2,1),(2,2),(3,1),(3,2)]
    end

    # TODO: Tensorizer tests
end

@testset "Domain" begin
    @test 0.45-0.65im ∉ Segment(-1,1)

    @test ApproxFunBase.AnySegment() == ApproxFunBase.AnySegment()

    @test ApproxFunBase.dimension(Domain{Float64}) == 1
    @test ApproxFunBase.dimension(Segment{Float64}) == 1
    @test ApproxFunBase.dimension(ChebyshevInterval()) == 1
    @test ApproxFunBase.dimension(ChebyshevInterval()^2) == 2
    @test ApproxFunBase.dimension(ChebyshevInterval()^3) == 3

    @test isambiguous(convert(ApproxFunBase.Point,ApproxFunBase.AnyDomain()))
    @test isambiguous(ApproxFunBase.Point(ApproxFunBase.AnyDomain()))

    @test_skip ApproxFunBase.Point(NaN) == ApproxFunBase.Point(NaN)
end

@time include("MatrixTest.jl")
@time include("SpacesTest.jl")

@testset "blockbandwidths for FiniteOperator of pointscompatibleace bug" begin
    S = ApproxFunBase.PointSpace([1.0,2.0])
    @test ApproxFunBase.blockbandwidths(FiniteOperator([1 2; 3 4],S,S)) == (0,0)
end

@testset "DiracDelta sampling" begin
    δ = 0.3DiracDelta(0.1) + 3DiracDelta(2.3)
    Random.seed!(0)
    for _=1:10
        @test sample(δ) ∈ [0.1, 2.3]
    end
    Random.seed!(0)
    r = sample(δ, 10_000)
    @test count(i -> i == 0.1, r)/length(r) ≈ 0.3/(3.3) atol=0.01
end

@time include("ETDRK4Test.jl")


text:
### A Pluto.jl notebook ###
# v0.11.12

using Markdown
using InteractiveUtils

# ╔═╡ 34968600-f1c6-11ea-2d29-d300e57ea2e8
begin
	using Images
	using FileIO
	using Plots
end

# ╔═╡ 5184395e-f1c6-11ea-2587-6f04898233c2
SvpImg = load("../img/SVP_ConvergenceZonePropagation.png")

# ╔═╡ a36d9d70-f1c6-11ea-37d9-b77d507d806d
NumRows, NumCols = size(SvpImg)

# ╔═╡ df563950-f1c6-11ea-25ed-a3210bbc3e71
begin
	zMin = 0.
	zMax = 5e3
	cMin = 1490.
	cMax = 1550.

	# 256
	nRows = 327 : NumRows - 245
	nCols = 1405 : NumCols - 1144
	SvpCrop = SvpImg[nRows, nCols]
end

# ╔═╡ 7c1af8b0-f1d2-11ea-34f3-8522ccac0729
Nrows, Ncols = size(SvpCrop)

# ╔═╡ f03896f0-f1d5-11ea-33f1-37d138cbf3f0
begin
	LinearTransform(Min, Max, N, n) = Min + (Max - Min)*n/N
	n2c(nc) = LinearTransform(cMin, cMax, Ncols, nc)
	n2z(nz) = LinearTransform(zMin, zMax, Nrows, nz)
end

# ╔═╡ 17a4a102-f1d3-11ea-1751-ef912f9d0d42
begin
	Svp₁ = copy(SvpCrop)

	nc₁ = (Ncols ÷ 2) + 12
	Svp₁[:, nc₁] .= RGB(0, 0, 1)

	z₁ = n2z(1)
# 	z₁ = 0.
	c₁ = cMin + (cMax - cMin)*nc₁/Ncols
# 	c₁ = 1520

	Svp₁
end

# ╔═╡ c55b30b0-f1d4-11ea-173a-3f19bf11e577
begin
	Svp₂ = copy(SvpCrop)

	nz₂ = (Nrows ÷ 15) - 8
	Svp₂[nz₂, :] .= RGB(1, 0, 0)

	nc₂ = (Ncols ÷ 4) - 25
	Svp₂[:, nc₂] .= RGB(0, 0, 1)

	z₂ = n2z(nz₂)
	c₂ = n2c(nc₂)

	Svp₂
end

# ╔═╡ 9e2aec90-f1d6-11ea-1f25-5f02cc093c6f
begin
	Svp₃ = copy(SvpCrop)

	nz₃ = (Nrows ÷ 4) - 13
	Svp₃[nz₃, :] .= RGB(1, 0, 0)

	nc₃ = (Ncols ÷ 3) + 33
	Svp₃[:, nc₃] .= RGB(0, 0, 1)

	z₃ = n2z(nz₃)
	c₃ = n2c(nc₃)

	Svp₃
end

# ╔═╡ 0682327e-f1d7-11ea-2a37-af5ebb964d12
begin
	Svp₄ = copy(SvpCrop)

	nz₄ = (Nrows ÷ 3) + 90
	Svp₄[nz₄, :] .= RGB(1, 0, 0)

	nc₄ = (Ncols ÷ 5) - 40
	Svp₄[:, nc₄] .= RGB(0, 0, 1)

	z₄ = n2z(nz₄)
	c₄ = n2c(nc₄)

	Svp₄
end

# ╔═╡ 8a44d190-f1d7-11ea-209d-e3d44ffa8f23
begin
	Svp₅ = copy(SvpCrop)

	nz₅ = Nrows
	Svp₅[nz₅, :] .= RGB(1, 0, 0)

	nc₅ = Ncols - 38
	Svp₅[:, nc₅] .= RGB(0, 0, 1)

	z₅ = n2z(nz₅)
	c₅ = n2c(nc₅)

	Svp₅
end

# ╔═╡ b8b4aa30-f1d4-11ea-12e1-090b74b2ea67
z = [z₁, z₂, z₃, z₄, z₅]

# ╔═╡ fa7166e0-f1d7-11ea-37ee-43fe6df8aa24
c = [c₁, c₂, c₃, c₄, c₅]

# ╔═╡ fe0c40e0-f1d7-11ea-0402-83ae99b738f4
begin
	plot(c, z, yaxis = :flip)
	plot!([1520, 1500, 1515, 1495, 1545.], [0., 300., 1200., 2e3, 5000.])
end

# ╔═╡ Cell order:
# ╠═34968600-f1c6-11ea-2d29-d300e57ea2e8
# ╠═5184395e-f1c6-11ea-2587-6f04898233c2
# ╠═a36d9d70-f1c6-11ea-37d9-b77d507d806d
# ╠═df563950-f1c6-11ea-25ed-a3210bbc3e71
# ╠═7c1af8b0-f1d2-11ea-34f3-8522ccac0729
# ╠═f03896f0-f1d5-11ea-33f1-37d138cbf3f0
# ╠═17a4a102-f1d3-11ea-1751-ef912f9d0d42
# ╠═c55b30b0-f1d4-11ea-173a-3f19bf11e577
# ╠═9e2aec90-f1d6-11ea-1f25-5f02cc093c6f
# ╠═0682327e-f1d7-11ea-2a37-af5ebb964d12
# ╠═8a44d190-f1d7-11ea-209d-e3d44ffa8f23
# ╠═b8b4aa30-f1d4-11ea-12e1-090b74b2ea67
# ╠═fa7166e0-f1d7-11ea-37ee-43fe6df8aa24
# ╠═fe0c40e0-f1d7-11ea-0402-83ae99b738f4


text:
module OilData

using DataFrames
using PlotlyJS
using Dates
using HDF5

#greet() = print("Hello World!")

include("parser.jl")
export add_day,
       find_prt_start_date,
       read_hdf5_times,
       read_rsm,
       find_column_name,
       find_schedule_end_date,
       find_prt_current_date,
       find_prt_current_time,
       read_grdecl_float64!,
       read_grdecl_keyword_data!,
       read_grdecl_string!,
       skip_grdecl_keyword_data!

include("plotly.jl")
export plotly_trace, plotly_layout,
       axis_time,
       axis_bhp,
       axis_oil_rate,
       axis_water_rate

include("utility.jl")
export downsample, find_duplication,
       find_integer_times,
       find_indices,
       find_last_duplication,
       repair_times,
       smooth_production

end # module


text:
module TraceEstimation

include("common.jl")
include("hutchinson.jl")
include("diagapp.jl")
include("slq.jl")
include("chebyhutch.jl")
include("diagonalapprox.jl")

end


text:
using JLD2
using GLMakie

jl_file    = jldopen("fluxernathy_averages.jld2", "r+")
jl_file_nh = jldopen("fluxernathy_nh_averages.jld2", "r+")

s_keys = keys(jl_file["timeseries"])
t_keys = keys(jl_file["timeseries"][s_keys[1]])

s_index = 2
t_index = 30 # 10 year averages, lets look at year 100ish

state_name = s_keys[s_index]
state_name = "u"

field = jl_file["timeseries"][state_name][t_keys[t_index]][1,:,:]
field_nh = jl_file_nh["timeseries"][state_name][t_keys[t_index]][1,:,:]

state_name = "b"

field_b = jl_file["timeseries"][state_name][t_keys[t_index]][1,:,:]
field_nh_b = jl_file_nh["timeseries"][state_name][t_keys[t_index]][1,:,:]

function get_grid(field, jl_file; ghost = 3)
    yC = jl_file["grid"]["yᵃᶜᵃ"][ghost+1:end-ghost]
    zC = jl_file["grid"]["zᵃᵃᶜ"][ghost+1:end-ghost]
    yF = jl_file["grid"]["yᵃᶠᵃ"][ghost+1:end-ghost]
    zF = jl_file["grid"]["zᵃᵃᶠ"][ghost+1:end-ghost]

    y = size(field)[1] == size(yC)[1] ? yC : yF
    z = size(field)[2] == size(zC)[1] ? zC : zF

    return y,z
end

y,z = get_grid(field, jl_file)

colorrange = extrema(field)

fig = Figure(resolution = (1186, 596))
ax_h = fig[1,1] = Axis(fig)
hm = heatmap!(ax_h, y, z, field, colorrange = colorrange, colormap = :balance, interpolate = true)
contour!(ax_h, y, z, field_b, levels = 20, color = :black, linewidth = 3.0,)

ax_nh = fig[1,2] = Axis(fig)
heatmap!(ax_nh, y, z, field_nh, colorrange = colorrange, colormap = :balance, interpolate = true)
contour!(ax_nh, y, z, field_nh_b, levels = 20, color = :black, linewidth = 3.0,)

Colorbar(fig[1,3], hm, label = state_name) # , ticks = contour_levels)

for tmpax in [ax_h, ax_nh]
    tmpax.title = state_name
    tmpax.titlesize = 40
    tmpax.ylabel = "Depth [m]"
    tmpax.xlabel = "South to North [m]"
    tmpax.xlabelsize = 25
    tmpax.ylabelsize = 25
    tmpax.limits = (extrema(y)..., extrema(z)...)
end

# ax1 = fig[jj,ii] = Axis(fig)

display(fig)

#=
ax.xticks = ([-80, -60, -30, 0, 30, 60, 80], ["80S", "60S", "30S", "0", "30N", "60N", "80N"])
pressure_levels = [1000, 850, 700, 550, 400, 250, 100, 10]
ax.yticks = (pressure_levels .* 1e2, string.(pressure_levels))
ax.yreversed = true
=#

max_stars_repo_name: sandreza/Mesoscale

max_issues_repo_name: sandreza/Mesoscale

max_forks_repo_name: sandreza/Mesoscale


text:
#module diagonalize
#export diagonlize
using PyCall
using NPZ
using Printf
using Combinatorics
using LinearAlgebra
using StaticArrays
using Einsum
using TensorOperations
#using fci

np = pyimport("numpy")

mutable struct DeterminantString
    norbs::UInt8
    nelec::UInt8
    config::Vector{Int}
    #config::MVector{N, Int}
    index::UInt
    label::UInt
end

function run_fci(orbs, nalpha, nbeta, m=12)
    #get eigenvalues from lanczos
    int1e = npzread("/Users/nicole/code/fci/src/data/int1e_4.npy")
    int2e = npzread("/Users/nicole/code/fci/src/data/int2e_4.npy")
    H_pyscf = npzread("/Users/nicole/code/fci/src/data/H_full_a.npy")
    ci = npzread("/Users/nicole/code/fci/src/data/cimatrix.npy")
    yalpha, ybeta = make_xy(orbs, nalpha, nbeta)

    #get all configs
    configa = zeros(orbs)
    configb = zeros(orbs)
    configa[1:nalpha] .= 1
    configb[1:nbeta] .= 1

    alpha_configs = get_all_configs(configa, orbs)
    beta_configs = get_all_configs(configb, orbs)
    ndets_a = factorial(orbs)÷(factorial(nalpha)*factorial(orbs-nalpha))
    ndets_b = factorial(orbs)÷(factorial(nbeta)*factorial(orbs-nbeta))

    #make lookup table
    println("\n alpha")
    index_table_a = make_index_table(alpha_configs, ndets_a, yalpha)
    println("\n beta")
    index_table_b = make_index_table(beta_configs, ndets_b, ybeta)
    error("stop")

    Ha_diag = precompute_spin_diag_terms(alpha_configs, ndets_a, orbs, index_table_a, yalpha, int1e, int2e, nalpha)
    Hb_diag = precompute_spin_diag_terms(beta_configs, ndets_b, orbs, index_table_b, ybeta, int1e, int2e, nbeta)

    #get H components
    H_alpha = compute_ss_terms_full(ndets_a, orbs, int1e, int2e, index_table_a, alpha_configs, yalpha)
    H_beta = compute_ss_terms_full(ndets_b, orbs, int1e, int2e, index_table_b, beta_configs, ybeta)
    #H_mixed = compute_ab_terms_full(ndets_a, ndets_b, orbs, int1e, int2e, index_table_a, index_table_b, alpha_configs, beta_configs, yalpha, ybeta)

    H_alpha = Ha_diag + H_alpha
    H_beta = Hb_diag + H_beta

    #H_alpha[abs.(H_alpha) .< 1e-14] .= 0
    #H_beta[abs.(H_beta) .< 1e-14] .= 0
    #H_mixed[abs.(H_mixed) .< 1e-14] .= 0
    #H_pyscf[abs.(H_pyscf) .< 1e-14] .= 0
    #ci[abs.(ci) .< 1e-14] .= 0

    Ia = Matrix{Float64}(I, size(H_alpha))
    Ib = Matrix{Float64}(I, size(H_beta))
    #Ha = kron(H_alpha, Ib)
    #Hb = kron(Ia, H_beta)
    #Ha[abs.(Ha) .< 1e-14] .= 0
    #Hb[abs.(Hb) .< 1e-14] .= 0

    #H = kron(H_alpha, Ib) + kron(Ia, H_beta) + H_mixed
    #Hmat = zeros(ndets_a*ndets_b, ndets_a*ndets_b)
    #Hmat .+= kron(Ib, H_alpha)
    #Hmat .+= kron(H_beta, Ia)
    #Hmat .+= H_mixed

    #H = .5*(Hmat+Hmat')
    #H = Hmat

    #println("\nH_alpha")
    ##display(H_alpha)
    #
    #println("\nH_beta")
    #display(H_beta)

    #println("H mixed")
    #display(H_mixed)
    #
    #println("\nmy H:")
    #display(H)
    #
    #println("my ci:")
    #display(ci)

    #println("\n Diff between my ci and slater ci")
    #diff3 = ci-H
    #diff3[abs.(diff3) .< 1e-14] .= 0
    #display(diff3)
    #println(diag(diff3))
    #
    #println("\nH Pyscf")
    #display(H_pyscf)
    #
    #println("\nDiff Between PYSCF and MY H")
    #diff = H_pyscf - H
    #diff[abs.(diff) .< 1e-14] .= 0
    #display(diff)
    #println("Trace: ", tr(diff))
    #println(diag(diff))

    #e = sort(eigvals(H))
    #e2 = eigvals(ci)
    #e3 = eigvals(H_pyscf)
    #eigvals_pyscf = npzread("/Users/nicole/code/fci/src/data/eigenvals.npy")
    #nuc = npzread("/Users/nicole/code/fci/src/data/nuc.npy")
    #my_energies = e.+nuc
    #ci_energies = e2.+nuc
    #diff_mypyscf = eigvals_pyscf - my_energies
    #diff_cipyscf = eigvals_pyscf - ci_energies
    #diff_mypyscf[abs.(diff_mypyscf) .< 1e-14] .= 0
    #diff_cipyscf[abs.(diff_cipyscf) .< 1e-14] .= 0

    #println("\n Pyscf eigenvals:")
    #display(eigvals_pyscf)
    #println("\n CI eigenvals + nuc:")
    #display(ci_energies)
    #println("\nMy eigenvals + nuc:")
    #display(my_energies)

    #println("\n Diff Mine and Pyscf")
    #display(diff_mypyscf)
    #println("\n Diff CI and pyscf")
    #display(diff_cipyscf)

    dim = ndets_a*ndets_b
    b = zeros(dim)
    b[1] = 1
    #initalize empty matrices for T and V
    T = zeros(Float64, m+1, m)
    V = zeros(Float64, dim, m+1)
    #normalize start vector
    V[:,1] = b/norm(b)
    #next vector
    #w = Hmat*V[:,1]
    w = get_sigma(H_alpha, H_beta, Ia, Ib, V[:,1], [alpha_configs, beta_configs], orbs, [yalpha, ybeta], int2e, index_table_a, index_table_b, dim, ndets_a)
    #orthogonalise
    T[1,1] = dot(w,V[:,1])
    w = w - T[1,1]*V[:,1]
    #normalize next vector
    T[2,1] = norm(w)
    V[:,2] = w/T[2,1]

    for j = 2:m
        #make T symmetric
        T[j-1, j] = T[j, j-1]

        #next vector
        w = get_sigma(H_alpha, H_beta, Ia, Ib, V[:,j], [alpha_configs, beta_configs], orbs, [yalpha, ybeta], int2e, index_table_a, index_table_b, dim, ndets_a)
        #w = Hmat*V[:,j]
        #orthogonalise agaisnt two previous vectors
        T[j,j] = dot(w,V[:, j])
        # below is like this w_3 = w_3 - a_2 |v_2> - b_2 |v_1>
        w = w - dot(w,V[:,j])*V[:,j] - T[j-1, j]*V[:, j-1] #subtract projection on v_j and v_(j-1)

        # note: <v_2 | H | v_0> = 0 so only have to subtract two previous vectors for othogonalization
        # that is what is being checked below
        #if j > 3
        #    value = dot(w, V[:,j-2])
        #    println("\n overlap with diff >1: ", value)
        #end

        #normalize
        T[j+1, j] = norm(w)
        V[:,j+1] = w/T[j+1, j]

        #convergence check
        if T[j+1, j] < 10E-10
            @printf("\n\n --------------- Converged at %i iteration ---------------  \n\n", j)
            Tm = T[1:j, 1:j]
            #println("Tm tridiag matrix")
            #display(Tm)
            #Tm_vals = sort(eigvals(Tm))
            #println("\nTm eigen vals: ")
            #display(Tm_vals)
            #println("\nMy eigenvals - nuc:")
            #x = (my_energies .- nuc)
            #display(x)
            #diff = x[1]-Tm_vals[1]
            #println("\n -------- Diff in eigenvalues ------------")
            #display(diff)
            return Tm, V
            break
        end

        if j == m
            println("\n ----------- HIT MAX ITERATIONS -------------\n ")
        end
    end

    #make T into symmetric matrix of shape (m,m)
    Tm = T[1:m, 1:m]
    #display(T[1:m, 1:m])
    #Tm_vals = sort(eigvals(Tm))
    #println("Tm eigen vals: ")
    #display(Tm_vals)
    #println("\nMy eigenvals - nuc:")
    #x = (my_energies .- nuc)
    #display(x)
    #diff = x[1]-Tm_vals[1]
    #println("\n --------- Diff in eigenvalues ------------")
    #display(diff)
    #println("\n")
    return Tm, V
end

function make_index_table(configs, ndets, y_matrix)
    index_table = zeros(Int, configs[1].norbs, configs[1].norbs, ndets)#={{{=#
    orbs = [1:configs[1].norbs;]
    for I in 1:ndets
        vir = filter!(x->!(x in configs[I].config), [1:configs[I].norbs;])
        for p in configs[I].config
            for q in vir
                new_config, sorted_config, sign_s = excit_config(deepcopy(configs[I].config), [p,q])
                println("config: ", new_config)
                idx = get_index(new_config, y_matrix, configs[I].norbs)
                println("index: ", idx)
                index_table[p,q,configs[I].label]=sign_s*idx
            end
        end
    end#=}}}=#
    return index_table#, sign_table
end

function precompute_spin_diag_terms(configs, ndets, orbs, index_table, y_matrix, int1e, int2e, nelec)
    Hout = zeros(ndets, ndets)#={{{=#
    for K in 1:ndets
        config = configs[K].config
        idx = get_index(config, y_matrix, orbs)
        for i in 1:nelec
            Hout[idx,idx] += int1e[config[i], config[i]]
            for j in i+1:nelec
                Hout[idx,idx] += int2e[config[i], config[i], config[j], config[j]]
                Hout[idx,idx] -= int2e[config[i], config[j], config[i], config[j]]
            end
        end
    end#=}}}=#
    return Hout
end

function compute_ss_terms_full(ndets, norbs, int1e, int2e, index_table, configs, y_matrix)
    Ha = zeros(ndets, ndets)
    nelecs = size(configs[1].config)[1]

    #h1eff = deepcopy(int1e)
    #@tensor begin
    #    h1eff[p,q] -= .5 * int2e[p,j,j,q]
    #end

    for I in configs #Ia or Ib, configs=list of all possible determinants
        I_idx = get_index(I.config, y_matrix, I.norbs)
        F = zeros(ndets)
        orbs = [1:I.norbs;]
        vir = filter!(x->!(x in I.config), orbs)

        #single excitation
        for k in I.config
            for l in vir
                #annihlate electron in orb k
                config_single, sorted_config, sign_s = excit_config(deepcopy(I.config), [k,l])
                config_single_idx = index_table[k,l,I.label]
                F[abs(config_single_idx)] += sign_s*int1e[k,l]
                for m in I.config
                    if m!=k
                        F[abs(config_single_idx)] += sign_s*(int2e[k,l,m,m]-int2e[k,m,l,m])
                    end
                end
            end
        end

        #double excitation
        for k in I.config
            for i in I.config
                if i>k
                    for l in vir
                        for j in vir
                            if j>l
                                single, sorted_s, sign_s = excit_config(deepcopy(I.config), [k,l])
                                double, sorted_d, sign_d = excit_config(deepcopy(sorted_s), [i,j])
                                idx = get_index(double, y_matrix, I.norbs)
                                if sign_d == sign_s
                                    F[abs(idx)] += (int2e[i,j,k,l] - int2e[i,l,j,k]) #one that works for closed

                                else
                                    F[abs(idx)] -= (int2e[i,j,k,l] - int2e[i,l,j,k]) #one that works for closed
                                end
                            end
                        end
                    end
                end
            end
        end

        Ha[:,I_idx] .= F
    end
    return Ha
end

function compute_ab_terms_full(ndets_a, ndets_b, norbs, int1e, int2e, index_table_a, index_table_b, alpha, beta, yalpha, ybeta)
    dim = ndets_a*ndets_b#={{{=#
    Hmat = zeros(dim, dim)

    for Ka in alpha
        Ka_idx = get_index(Ka.config, yalpha, norbs)
        orbsa = [1:norbs;]
        vira = filter!(x->!(x in Ka.config), orbsa)
        for Kb in beta
            Kb_idx = get_index(Kb.config, ybeta, norbs)
            orbsb = [1:norbs;]
            virb = filter!(x->!(x in Kb.config), orbsb)
            K = Ka_idx + (Kb_idx-1)*ndets_a #works for closed shell

            #diagonal part
            for l in Kb.config
                for n in Ka.config
                    Hmat[K, K] += int2e[n,n,l,l]
                end
            end

            #excit alpha only
            for p in Ka.config
                for q in vira
                    a_single, sort_a, sign_a = excit_config(deepcopy(Ka.config), [p,q])
                    idxa = abs(index_table_a[p,q,Ka.label])

                    Kprime = idxa + (Kb_idx-1)*ndets_a
                    #alpha beta <ii|jj>
                    for m in Kb.config
                        Hmat[K,Kprime]+=sign_a*int2e[p,q,m,m]
                    end
                end
            end

            #excit beta only
            for r in Kb.config
                for s in virb
                    b_single, sort_b, sign_b = excit_config(deepcopy(Kb.config), [r,s])
                    idxb = abs(index_table_b[r,s,Kb.label])
                    Lprime = Ka_idx + (idxb-1)*ndets_a

                    #alpha beta <ii|jj>
                    for n in Ka.config
                        Hmat[K,Lprime]+=sign_b*int2e[r,s,n,n]
                    end
                end
            end

            #excit alpha and beta
            for p in Ka.config
                for q in vira
                    a_single, sort_a, sign_a = excit_config(deepcopy(Ka.config), [p,q])
                    idxa = abs(index_table_a[p,q,Ka.label])
                    for r in Kb.config
                        for s in virb
                            b_single, sort_b, sign_b = excit_config(deepcopy(Kb.config), [r,s])
                            idxb = abs(index_table_b[r,s,Kb.label])
                            L = idxa + (idxb-1)*ndets_a
                            Hmat[K,L] += sign_a*sign_b*(int2e[p,q,r,s])
                        end
                    end
                end
            end
        end
    end#=}}}=#
    return Hmat
end

function get_sigma3(configs, norbs, y_matrix, int2e, vector, index_table_a, index_table_b, dim, ndets_a)
    #configs = [alpha_configs, beta_configs]{{{
    #nelec = [n_alpha, n_beta]
    #y_matrix = [y_alpha, y_beta]
    sigma3 = zeros(dim, 1)

    for I in configs[1]  #alpha configs
        orbs = [1:norbs;]
        vir_I = filter!(x->!(x in I.config), orbs)
        I_idx = get_index(I.config, y_matrix[1], norbs)
        for J in configs[2]     #beta configs
            orbs2 = [1:norbs;]
            vir_J = filter!(x->!(x in J.config), orbs2)
            J_idx = get_index(J.config, y_matrix[2], norbs)
            K = I_idx + (J_idx-1)*ndets_a

            for l in J.config
                for n in I.config
                    #Hmat[K,K]
                    sigma3[K] += int2e[n,n,l,l]*vector[K]
                end
            end

            #excit alpha only
            for p in I.config
                for q in vir_I
                    a_single, sorta, sign_a = excit_config(deepcopy(I.config), [p,q])
                    idxa = abs(index_table_a[p,q,I.label])
                    Kprim = idxa + (J_idx-1)*ndets_a
                    for m in J.config
                        #Hmat[K,Kprim]
                        sigma3[K]+=sign_a*int2e[p,q,m,m]*vector[Kprim]
                    end
                end
            end

            #excit beta only
            for r in J.config
                for s in vir_J
                    b_single, sortb, sign_b = excit_config(deepcopy(J.config), [r,s])
                    idxb = abs(index_table_b[r,s,J.label])
                    Lprim = I_idx + (idxb-1)*ndets_a
                    for n in I.config
                        #Hmat[K,Lprim]
                        sigma3[K]+=sign_b*int2e[r,s,n,n]*vector[Lprim]
                    end
                end
            end

            #excit both alpha and beta
            for p in I.config
                for q in vir_I
                    a_single, sorta, sign_a = excit_config(deepcopy(I.config), [p,q])
                    idxa = abs(index_table_a[p,q,I.label])
                    for r in J.config
                        for s in vir_J
                            b_single, sortb, sign_b = excit_config(deepcopy(J.config), [r,s])
                            idxb = abs(index_table_b[r,s,J.label])
                            L = idxa + (idxb-1)*ndets_a
                            #Hmat[K,L]
                            sigma3[K] += sign_a*sign_b*int2e[p,q,r,s]*vector[L]
                        end
                    end
                end
            end
        end
    end#=}}}=#
    return sigma3
end

function get_sigma(Ha, Hb, Ia, Ib, vector, configs, norbs, y_matrix, int2e, index_table_a, index_table_b, dim, ndets_a)
    #b = reshape(vector, (size(Ha)[1], size(Hb)[1]))
    #sigma1 = reshape(Ha*b, (dim, 1))
    #sigma2 = reshape(Hb*transpose(b), (dim, 1))
    sigma1 = kron(Ib, Ha)*vector
    sigma2 = kron(Hb, Ia)*vector
    sigma3 = get_sigma3(configs, norbs, y_matrix, int2e, vector, index_table_a, index_table_b, dim, ndets_a)
    sigma = sigma1 + sigma2 + sigma3
    return sigma
end

function make_xy(norbs, nalpha, nbeta)
    #makes y mazotrices for grms indexing{{{
    n_unocc_a = (norbs-nalpha)+1
    n_unocc_b = (norbs-nbeta)+1

    #make x matricies
    xalpha = zeros(n_unocc_a, nalpha+1)
    xbeta = zeros(n_unocc_b, nbeta+1)
    #fill first row and columns
    xalpha[:,1] .= 1
    xbeta[:,1] .= 1
    xalpha[1,:] .= 1
    xbeta[1,:] .= 1

    for i in 2:nalpha+1
        for j in 2:n_unocc_a
            xalpha[j, i] = xalpha[j-1, i] + xalpha[j, i-1]
        end
    end

    for i in 2:nbeta+1
        for j in 2:n_unocc_b
            xbeta[j, i] = xbeta[j-1, i] + xbeta[j, i-1]
        end
    end

    #make y matrices
    copya = deepcopy(xalpha)
    copyb = deepcopy(xbeta)
    arraya = zeros(size(xalpha)[2])
    arrayb = zeros(size(xbeta)[2])
    yalpha = vcat(transpose(arraya), xalpha[1:size(xalpha)[1]-1, :])
    ybeta = vcat(transpose(arrayb), xbeta[1:size(xbeta)[1]-1, :])#=}}}=#
    return yalpha, ybeta
end

function get_all_configs(config, norbs)
    #get all possible configs from a given start config{{{
    nelecs = UInt8(size(config)[1])
    all_configs = unique(collect(permutations(config, size(config)[1])))
    configs = [] #empty Array
    for i in 1:size(all_configs)[1]
        A = findall(!iszero, all_configs[i])
        push!(configs,DeterminantString(norbs, nelecs, A, 1, UInt(i)))
    end
    #=}}}=#
    return configs
end

function get_index(config, y, norbs)
    #config has to be orbital index form since it will turned into bit string form{{{
    string = zeros(Int8, norbs)
    string[config] .= 1

    #println("config: ", config)
    index = 1
    start = [1,1]

    for value in string
        if value == 0
            #move down but dont add to index
            start[1] = start[1]+1
        end
        if value == 1
            #move right and add value to index
            start[2] = start[2] + 1
            index += y[start[1], start[2]]
        end
    end#=}}}=#
    return UInt8(index)
end

function excit_config(config, positions)
    #apply creation operator to the string{{{
    #get new index of string and store in lookup table
    #config is orbital indexing in ascending order
    #positions [i,a] meaning electron in orb_i went to orb_a

    spot = first(findall(x->x==positions[1], config))
    config[spot] = positions[2]
    config_org = deepcopy(config)
    count, arr = bubble_sort(config)
    if iseven(count)
        sign = 1
    else
        sign = -1
    end#=}}}=#
    return config_org, arr, sign
end

function bubble_sort(arr)
    len = size(arr)[1]#={{{=#
    count = 0
    # Traverse through all array elements
    for i = 1:len-1
        for j = 2:len
        # Last i elements are already in place
        # Swap if the element found is greater
            if arr[j-1] > arr[j]
                count += 1
                tmp = arr[j-1]
                arr[j-1] = arr[j]
                arr[j] = tmp
            end
        end
    end
    return count, arr#=}}}=#
end

max_stars_repo_name: nbraunsc/fci

max_issues_repo_name: nbraunsc/fci

max_forks_repo_name: nbraunsc/fci


text:
# Autogenerated wrapper script for Pango_jll for i686-w64-mingw32
export libpango, libpangocairo, libpangoft

using FriBidi_jll
using FreeType2_jll
using Glib_jll
using Fontconfig_jll
using HarfBuzz_jll
using Cairo_jll
JLLWrappers.@generate_wrapper_header("Pango")
JLLWrappers.@declare_library_product(libpango, "libpango-1.0-0.dll")
JLLWrappers.@declare_library_product(libpangocairo, "libpangocairo-1.0-0.dll")
JLLWrappers.@declare_library_product(libpangoft, "libpangoft2-1.0-0.dll")
function __init__()
    JLLWrappers.@generate_init_header(FriBidi_jll, FreeType2_jll, Glib_jll, Fontconfig_jll, HarfBuzz_jll, Cairo_jll)
    JLLWrappers.@init_library_product(
        libpango,
        "bin\\libpango-1.0-0.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpangocairo,
        "bin\\libpangocairo-1.0-0.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libpangoft,
        "bin\\libpangoft2-1.0-0.dll",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
lattice = load_lattice(joinpath(@__DIR__, "Al8.json"))
atoms   = load_atoms(  joinpath(@__DIR__, "Al8.json"))
atoms   = attach_pseudos(atoms, Al="hgh/pbe/al-q3.hgh")

function load_Al_nodiis_potential(basis)
    guessfile = joinpath(@__DIR__, "Al_nodiis_initV.jld2")
    if !isfile(guessfile)
        ρ0 = guess_density(basis)
        _, ham = DFTK.energy_hamiltonian(basis, nothing, nothing; ρ=ρ0)
        V = DFTK.total_local_potential(ham)
        V .+= 3.0rand(Float64, size(V)...)

        jldopen(guessfile, "w") do file
            file["V"] = V
        end
    end

    jldopen(guessfile, "r") do file
        file["V"]
    end
end

cases = Dict{String, Any}(
    "adaptive" => (damping=DFTK.AdaptiveDamping(), ),  # Parameter-free adaptive damping
)
for α in 1:9
    cases["standard_0$α"] = (damping=DFTK.FixedDamping(α / 10), )
end
cases["standard_10"] = (damping=DFTK.FixedDamping(1.0), )
for i in [1, 3, 4, 5]
    cases["adaptive_0$i"] = (damping=DFTK.AdaptiveDamping(i / 10), )
end

config[@__DIR__] = (
    directory        =  @__DIR__,
    lattice          = lattice,
    atoms            = atoms,
    magnetic_moments = [],
    #
    kwargs_model     = (smearing=Smearing.Gaussian(), temperature=0.001),
    Ecut             = 20,
    kgrid            = kgrid_size_from_minimal_spacing(lattice, 2π * 0.04 / u"Å"),
    supersampling    = 1.5,
    potential        = load_Al_nodiis_potential,
    kwargs_scf       = (acceleration=DFTK.AndersonAcceleration(;m=0), ),
    mixing           = SimpleMixing(),
    cases            = cases,
)

max_stars_repo_name: mfherbst/supporting-adaptive-damping

max_issues_repo_name: mfherbst/supporting-adaptive-damping

max_forks_repo_name: mfherbst/supporting-adaptive-damping


text:
#!/bin/bash
#=
exec julia --color=yes --startup-file=no "${BASH_SOURCE[0]}" "$@"
=#

using Pkg
#Pkg.activate(".")
#include("srg/MockFBA.jl")
import MockFBA

using YAML

function main(ARGS)
    #load the config file
    config=YAML.load_file(ARGS[1])
    #An option to split the calculation in NGC/SGC or use NS for combined
    group=ARGS[2]
    tile_pass=parse(Int32,ARGS[3])
    #how many partition we want this pass to run with
    npartition=parse(Int32,ARGS[4])
    #which partition should I execute now
    mypart=parse(Int32,ARGS[5])

    #load the tiles
    tiles_dic=MockFBA.load_DESI_tiles(config["TILES"]["tile_file"],config["TILES"]["PROGRAM"],
                  tile_pass,group)

    #Number of tiles for the current setting
    ntile=size(tiles_dic["TILEID"],1)

    if(ntile==0)
        println("No tile to assign in pass=$(tile_pass)\n")
        return
    elseif(mypart>=ntile)
	println("Nothing to be done, have only ntile=$(ntile), but this cpu=$(mypart)")
	return
    end

    #The indices of tiles I will execute
    beg_index,end_index= MockFBA.partition_indices(ntile,npartition,mypart)

    #println("my_indices: $(beg_index) $(end_index) , total_tile: $(ntile)")

    this_index=collect(beg_index:end_index)
    #tile_date="2019-09-16T00:00:00"
    tile_date=config["focal_plane"]["date"]
    MockFBA.Run_Many_Tile(config,this_index,tiles_dic;group=group,tile_date=tile_date, plate_scale=nothing,fp_dic=nothing,exc_dic=nothing,verbose=2)
end

#@show ARGS
main(ARGS)

max_stars_repo_name: shadaba/MockFBA

max_issues_repo_name: shadaba/MockFBA

max_forks_repo_name: shadaba/MockFBA


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiNetworkingV1NetworkPolicy <: SwaggerModel
    apiVersion::Any # spec type: Union{ Nothing, String } # spec name: apiVersion
    kind::Any # spec type: Union{ Nothing, String } # spec name: kind
    metadata::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1ObjectMeta } # spec name: metadata
    spec::Any # spec type: Union{ Nothing, IoK8sApiNetworkingV1NetworkPolicySpec } # spec name: spec

    function IoK8sApiNetworkingV1NetworkPolicy(;apiVersion=nothing, kind=nothing, metadata=nothing, spec=nothing)
        o = new()
        validate_property(IoK8sApiNetworkingV1NetworkPolicy, Symbol("apiVersion"), apiVersion)
        setfield!(o, Symbol("apiVersion"), apiVersion)
        validate_property(IoK8sApiNetworkingV1NetworkPolicy, Symbol("kind"), kind)
        setfield!(o, Symbol("kind"), kind)
        validate_property(IoK8sApiNetworkingV1NetworkPolicy, Symbol("metadata"), metadata)
        setfield!(o, Symbol("metadata"), metadata)
        validate_property(IoK8sApiNetworkingV1NetworkPolicy, Symbol("spec"), spec)
        setfield!(o, Symbol("spec"), spec)
        o
    end
end # type IoK8sApiNetworkingV1NetworkPolicy

const _property_map_IoK8sApiNetworkingV1NetworkPolicy = Dict{Symbol,Symbol}(Symbol("apiVersion")=>Symbol("apiVersion"), Symbol("kind")=>Symbol("kind"), Symbol("metadata")=>Symbol("metadata"), Symbol("spec")=>Symbol("spec"))
const _property_types_IoK8sApiNetworkingV1NetworkPolicy = Dict{Symbol,String}(Symbol("apiVersion")=>"String", Symbol("kind")=>"String", Symbol("metadata")=>"IoK8sApimachineryPkgApisMetaV1ObjectMeta", Symbol("spec")=>"IoK8sApiNetworkingV1NetworkPolicySpec")
Base.propertynames(::Type{ IoK8sApiNetworkingV1NetworkPolicy }) = collect(keys(_property_map_IoK8sApiNetworkingV1NetworkPolicy))
Swagger.property_type(::Type{ IoK8sApiNetworkingV1NetworkPolicy }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiNetworkingV1NetworkPolicy[name]))}
Swagger.field_name(::Type{ IoK8sApiNetworkingV1NetworkPolicy }, property_name::Symbol) =  _property_map_IoK8sApiNetworkingV1NetworkPolicy[property_name]

function check_required(o::IoK8sApiNetworkingV1NetworkPolicy)
    true
end

function validate_property(::Type{ IoK8sApiNetworkingV1NetworkPolicy }, name::Symbol, val)
end


text:
# hann.jl

import Sound # hann
import DSP # hanning
using Test: @testset, @test

@testset "hann" begin
   for n in [8, 9]
       @test Sound.hann(n) ≈ DSP.hanning(n+2)[2:end-1]
   end
end


text:
"""
    randSphere(K::Int)

Returns a random K-vector from the unit sphere
"""
randSphere(K::Int) = normalize(randn(K))

"Computes `γ` from `ρ`"
gammasoc(ρ::Float64) = sqrt(1 - ρ^2) / ρ

"Computes `ρ` from `γ`"
rhosoc(γ::Float64)   = 1/ sqrt(1 + γ^2)

"Computes `ϵ` from `μ` and `s^2`"
epssoc(μ::Float64, s2::Float64) = phi(μ/sqrt(1+s2))

"The cumulative function of the Normal distribution"
phi(x::Real) = cdf(Normal(), x)

"The density function of the Normal distribution"
G(x::Real) = pdf(Normal(), x)

"Returns the two modulation functions: Fw and Fϵ"
function modfunc(hσ1γ::Float64, μ1sqs2::Float64)
    phiϵ = phi(μ1sqs2)
    phiw = phi(hσ1γ)
    Z    = phiϵ + phiw - 2*phiϵ*phiw

    Fw = (1 - 2phiϵ) * G(hσ1γ) / Z
    Fϵ = (1 - 2phiw) * G(μ1sqs2) / Z

    return (Fw, Fϵ)
end


text:
using Test

using ArnoldiMethod: collect_eigen!, copy_eigenvalues!
using LinearAlgebra

@testset "Eigenvector upper triangular matrix" begin
    n = 20

    # Exactly upper triangular matrix R
    for T in (Float64, ComplexF64)

        # Upper triangular matrix
        R = triu(rand(T, n, n))

        # Compute exact eigenvectors according to LAPACK
        λs, xs = eigen(R)

        # Allocate a complex-valued eigenvector
        x = zeros(complex(T), n)

        for i = 1:n
            # Compute the `i`th eigenvector
            fill!(x, zero(T))
            collect_eigen!(x, R, i)

            # Test whether it corresponds to the LAPACK result
            @test norm(x) ≈ 1
            @test abs.(x) ≈ abs.(xs[:, i])
        end
    end
end

rot(θ) = [cos(θ) sin(θ); -sin(θ) cos(θ)]

@testset "Eigenvectors quasi-upper triangular matrix" begin
    # Real arithmetic with conjugate eigvals -- quasi-upper triangular R
    n = 20
    R = triu(rand(n, n))
    R[1:2,1:2] .= rot(1.0) + I
    R[10:11,10:11] .= rot(1.2) + 2I

    # Compute exact eigenvectors according to LAPACK
    λs, xs = eigen(R)

    # Allocate a complex-valued eigenvector
    x = zeros(ComplexF64, n)

    for i = 1:n
        fill!(x, 0.0)
        collect_eigen!(x, R, i)

        @test norm(x) ≈ 1
        @test abs.(x) ≈ abs.(xs[:, i])
    end
end

@testset "Extract partial" begin
    n = 20
    R = triu(rand(n, n))
    R[1:2,1:2] .= rot(1.0) + I
    for range = (1:3, 1:4)
        λs = eigvals(R[range, range])
        θs = copy_eigenvalues!(rand(ComplexF64, length(range)), R, range)
        @test sort!(λs, by = reim) ≈ sort!(θs, by = reim)
    end
end


text: Dict{String,Any}("answer" => Dict{String,Any}("value" => "9223372036854775807","type" => "integer"),"neganswer" => Dict{String,Any}("value" => "-9223372036854775808","type" => "integer"))

max_stars_repo_name: vanillajonathan/julia

max_issues_repo_name: vanillajonathan/julia

max_forks_repo_name: vanillajonathan/julia


text:
# =============================================
# Bernstein expansion for univariate monomials
# =============================================

"""
    univariate(m::AbstractMonomialLike, l::Integer, dom::Interval)

Compute the Bernstein coefficients of a univariate monomial over an interval.

### Input

- `m`    -- monomial in one variable
- `l`    -- degree of the Bernstein polynomial
- `dom`  -- interval domain of the Bernstein expansion

### Output

An `l+1`-dimensional vector that corresponds to the Bernstein expansion of order
`l` of the monomial `m`.

### Notes

For experimental purposes, different variations of the algorithm are availble
in the internal function `_univariate!`. By dispatching on any of the following
values, you can choose between:

- `fastmath` : Uses the `@fastmath`. This is the fastest implementation.
- `fastpow`  : Uses `fastpow` from `DiffEqBase.jl`. This is the second fastest
               implementation.
- `base`     : Uses `^` from Julia. This is the slowest implementation, but it's
               accuracy is guaranteed to be within an `<= 1 ulp` for all possible
               input values.

### Algorithm

TODO: add description (ref Smith's PhD thesis).
"""
function univariate(m::AbstractMonomialLike, l::Integer, dom::Interval{N}) where {N}
    nvariables(m) == 1 || throw(ArgumentError("this function only acccepts univariate " *
        "monomials but the given monomial has $(nvariables(m)) variables"))

    k = degree(m)
    coeffs = Vector{N}(undef, l+1) # preallocate output
    _univariate!(coeffs, k, l, inf(dom), sup(dom))
end

# Bernstein coefficients for univariate terms like 4x²; uses linearity property
function univariate(t::AbstractTermLike, l::Integer, dom::Interval{N}) where {N}
    m = monomial(t)
    α = coefficient(t)
    coeffs = univariate(m, l, dom)
    return α .* coeffs
end

# fallback in floating-point
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N) where {N<:AbstractFloat}
    _univariate!(coeffs, k, l, low, high, Val(:fastmath)) # :optimized
end

# use @fastmath macro to allow floating point optimizations
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N, ::Val{:fastmath}) where {N<:AbstractFloat}
    if k < l
        m = l-k
        @fastmath @inbounds begin
             for i in 0:l
                 coeffs[i+1] = zero(N)
                 for j in max(0, i-m):min(k, i)
                     aux = binomial(m, i-j) * binomial(k, j) / binomial(k+m, i)
                     coeffs[i+1] += aux * low^(k-j) * high^j
                 end
            end
        end
    else
        @fastmath @inbounds begin
            for i in 0:l
                coeffs[i+1] = low^(k-i) * high^i
            end
        end
    end
    return coeffs
end

# use @fastmath macro to allow floating point optimizations
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N, ::Val{:optimized}) where {N<:AbstractFloat}
    if k < l
        m = l-k
        @fastmath @inbounds begin
             for i in 0:l
                 coeffs[i+1] = zero(N)
                 for j in max(0, i-m):min(k, i)
                     aux = BINOM_QUOT_TABLE[m, i, j, k]
                     coeffs[i+1] += aux * low^(k-j) * high^j
                 end
            end
        end
    else
        @fastmath @inbounds begin
            for i in 0:l
                coeffs[i+1] = low^(k-i) * high^i
            end
        end
    end
    return coeffs
end

# use fastpow version of ^
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N, ::Val{:fastpow}) where {N<:AbstractFloat}
    if k < l
        m = l-k
        @inbounds begin
             for i in 0:l
                 coeffs[i+1] = zero(N)
                 for j in max(0, i-m):min(k, i)
                     aux = binomial(m, i-j) * binomial(k, j) / binomial(k+m, i)
                     coeffs[i+1] += aux * fastpow(low, k-j) * fastpow(high, j)
                 end
            end
        end
    else
        @fastmath @inbounds begin
            for i in 0:l
                coeffs[i+1] = fastpow(low, k-i) * fastpow(high, i)
            end
        end
    end
    return coeffs
end

# use Julia base version of ^
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N, ::Val{:base}) where {N<:AbstractFloat}
    if k < l
        m = l-k
        @inbounds begin
             for i in 0:l
                 coeffs[i+1] = zero(N)
                 for j in max(0, i-m):min(k, i)
                     aux = binomial(m, i-j) * binomial(k, j) / binomial(k+m, i)
                     coeffs[i+1] += aux * low^(k-j) * high^j
                 end
            end
        end
    else
        @inbounds begin
            for i in 0:l
                coeffs[i+1] = low^(k-i) * high^i
            end
        end
    end
    return coeffs
end

# exact computation using rationals
function _univariate!(coeffs::AbstractVector{N}, k::Integer, l::Integer,
                      low::N, high::N) where {M, N<:Rational{M}}
    if k < l
        m = l-k
        @inbounds for i in 0:l
            coeffs[i+1] = zero(N)
            for j in max(0, i-m):min(k, i)
                aux = binomial(m, i-j) * binomial(k, j) // binomial(k+m, i)
                coeffs[i+1] += aux * low^(k-j) * high^j
            end
        end
    else
        @inbounds @simd for i in 0:l
            coeffs[i+1] = low^(k-i) * high^i
        end
    end
    return coeffs
end

# TODO: handle zeros in i, j, k, m (?)
function _binomial_quotients(; N=Float64, m_max=10, i_max=10, j_max=10, k_max=10)
    M = Array{N, 4}(undef, m_max, i_max, j_max, k_max)
    for k in 1:k_max
        for j in 1:j_max
            for i in 1:i_max
                for m in 1:m_max
                    @inbounds M[m, i, j, k] = binomial(m, i-j) * binomial(k, j) / binomial(k+m, i)
                end
            end
        end
    end
    return M
end

# lookup table for the binomial quotients in the univariate case with k < l
const BINOM_QUOT_TABLE = _binomial_quotients()

# ===============================================
# Bernstein expansion for multivariate monomials
# ===============================================

"""
    multivariate(m::AbstractMonomialLike, l::AbstractVector{Int}, dom::IntervalBox{N}) where {N}

Compute the Bernstein coefficients of a multivariate monomial.

### Input

- `m`    -- monomial in several variables
- `l`    -- vector of degrees of the Bernstein polynomial for each variable
- `dom`  -- multi-dimensional interval domain of the Bernstein expansion

### Output

A vector of vectors holding the Bernstein coefficients implicitly.

### Algorithm

TODO: add description (ref Smith's PhD thesis).
```
"""
function multivariate(m::AbstractMonomialLike, l::AbstractVector{Int}, dom::IntervalBox{D, N}) where {D, N}
    n = nvariables(m)
    (n == length(l) == D) || throw(ArgumentError("the number of " *
        "variables in the monomial `m`, number of degrees `l` and domain size of `dom` " *
        "do no match; they are $n, $(length(l)) and $D respectively"))

    k = exponents(m) # vector of degrees for each variable

    # preallocate outputs
    coeffs = Vector{Vector{N}}(undef, n)
    @inbounds for i in 1:n
        coeffs[i] = Vector{N}(undef, l[i] + 1)
    end

    @inbounds for i in 1:n
        _univariate!(coeffs[i], k[i], l[i], inf(dom[i]), sup(dom[i]))
    end
    return coeffs
end

# Bernstein coefficients for multivariate terms like 4x²y; uses linearity property
function multivariate(t::AbstractTermLike, l::AbstractVector{Int}, dom::IntervalBox)
    m = monomial(t)
    α = coefficient(t)
    coeffs = multivariate(m, l, dom)
    return α .* coeffs
end

max_stars_repo_name: JuliaReach/BernsteinExpansions

max_issues_repo_name: JuliaReach/BernsteinExpansions

max_forks_repo_name: JuliaReach/BernsteinExpansions


text:
import Base: show

"""

# Engine types

Engine for Hamiltonian Monte Carlo

### Types defined
```julia
* Nuts       : No-U-Turn sampler
* Static     : Static integration time
```
"""
abstract type Engine end

"""

# Available sampling algorithms

Currently limited to Hmc().

"""
abstract type SamplingAlgorithm end

"""

# Nuts type and constructor

Settings for engine=Nuts() in Hmc().

### Method
```julia
Nuts(;max_depth=10)
```
### Optional arguments
```julia
* `max_depth::Number`           : Maximum tree depth
```

### Related help
```julia
?Sample                         : Sampling settings
?Engine                         : Engine for Hamiltonian Monte Carlo
```
"""
struct Nuts <: Engine
  max_depth::Int64
end
Nuts(;max_depth::Number=10) = Nuts(max_depth)

"""

# Static type and constructor

Settings for engine=Static() in Hmc().

### Method
```julia
Static(;int_time=2 * pi)
```
### Optional arguments
```julia
* `;int_time::Number`          : Static integration time
```

### Related help
```julia
?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo
```
"""
struct Static <: Engine
  int_time::Float64
end
Static(;int_time::Number=2 * pi) = Static(int_time)

"""

# Metric types

Geometry of base manifold

### Types defined
```julia
* unit_e::Metric      : Euclidean manifold with unit metric
* dense_e::Metric     : Euclidean manifold with dense netric
* diag_e::Metric      : Euclidean manifold with diag netric
```
"""
abstract type Metric end
struct unit_e <: Metric
end
struct dense_e <: Metric
end
struct diag_e <: Metric
end

"""

# Hmc type and constructor

Settings for algorithm=StanSample.Hmc() in Sample().

### Method
```julia
Hmc(;
  engine=StanSample.Nuts(),
  metric=StanSample.diag_e,
  stepsize=1.0,
  stepsize_jitter=1.0
)
```
### Optional arguments
```julia
* `engine::Engine`            : Engine for Hamiltonian Monte Carlo
* `metric::Metric`            : Geometry for base manifold
* `stepsize::Float64`         : Stepsize for discrete evolutions
* `stepsize_jitter::Float64`  : Uniform random jitter of the stepsize [%]
```

### Related help
```julia
?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo
?Nuts                          : Settings for Nuts
?Static                        : Settings for Static
?Metric                        : Base manifold geometries
```
"""
struct Hmc <: SamplingAlgorithm
  engine::Engine
  metric::Metric
  stepsize::Float64
  stepsize_jitter::Float64
end
Hmc(;engine::Engine=Nuts(), metric::DataType=diag_e,
  stepsize::Number=1.0, stepsize_jitter::Number=1.0) =
    Hmc(engine, metric(), stepsize, stepsize_jitter)
Hmc(engine::Engine) = Hmc(engine, diag_e(), 1.0, 1.0)

"""

# Fixed_param type and constructor

Settings for algorithm=CmdStan.Fixed_param() in Sample().

### Method
```julia
Fixed_param()
```

### Related help
```julia
?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo
?Nuts                          : Settings for Nuts
?Static                        : Settings for Static
?Metric                        : Base manifold geometries
```
"""
struct Fixed_param <: SamplingAlgorithm end

"""

# Adapt type and constructor

Settings for adapt=CmdStan.Adapt() in Sample().

### Method
```julia
Adapt(;
  engaged=true,
  gamma=0.05,
  delta=0.8,
  kappa=0.75,
  t0=10.0,
  init_buffer=75,
  term_buffer=50,
  window::25
)
```
### Optional arguments
```julia
* `engaged::Bool`              : Adaptation engaged?
* `gamma::Float64`             : Adaptation regularization scale
* `delta::Float64`             : Adaptation target acceptance statistic
* `kappa::Float64`             : Adaptation relaxation exponent
* `t0::Float64`                : Adaptation iteration offset
* `init_buffer::Int64`         : Width of initial adaptation interval
* `term_buffer::Int64`         : Width of final fast adaptation interval
* `window::Int64`              : Initial width of slow adaptation interval
```

### Related help
```julia
?Sample                        : Sampling settings
```
"""
struct Adapt
  engaged::Bool
  gamma::Float64
  delta::Float64
  kappa::Float64
  t0::Float64
  init_buffer::Int64
  term_buffer::Int64
  window::Int64
end
Adapt(;engaged::Bool=true, gamma::Number=0.05, delta::Number=0.8,
  kappa::Number=0.75, t0::Number=10.0,
  init_buffer::Number=75, term_buffer::Number=50, window::Number=25) =
    Adapt(engaged, gamma, delta, kappa, t0, init_buffer, term_buffer, window)

"""
# Sample type and constructor

Settings for method=Sample() in SampleModel.

### Method
```julia
Sample(;
  num_samples=1000,
  num_warmup=1000,
  save_warmup=false,
  thin=1,
  adapt=StanSample.Adapt(),
  algorithm=SamplingAlgorithm()
)
```
### Optional arguments
```julia
* `num_samples::Int64`          : Number of sampling iterations ( >= 0 )
* `num_warmup::Int64`           : Number of warmup iterations ( >= 0 )
* `save_warmup::Bool`           : Include warmup samples in output
* `thin::Int64`                 : Period between saved samples
* `adapt::Adapt`                : Warmup adaptation settings
* `algorithm::SamplingAlgorithm`: Sampling algorithm

```

"""
struct Sample
  num_samples::Int64
  num_warmup::Int64
  save_warmup::Bool
  thin::Int64
  adapt::Adapt
  algorithm::SamplingAlgorithm
end
Sample(;num_samples::Number=1000, num_warmup::Number=1000,
  save_warmup::Bool=false, thin::Number=1,
  adapt::Adapt=Adapt(), algorithm::SamplingAlgorithm=Hmc()) =
    Sample(num_samples, num_warmup, save_warmup, thin, adapt, algorithm)


text:
#==============================================================================#
# names.jl
#
# AWS Endpoint URLs and Amazon Resource Names.
#
# http://docs.aws.amazon.com/general/latest/gr/rande.html
# http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
#
# Copyright OC Technology Pty Ltd 2014 - All rights reserved
#==============================================================================#

export arn, is_arn,
       arn_service, arn_region, arn_account, arn_resource,
       arn_iam_type, arn_iam_name

"""
    arn([::AWSConfig], service, resource, [region, [account]])

Generate an [Amazon Resource Name](http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) for `service` and `resource`.
"""

function arn(service, resource,
             region=get(default_aws_config(), :region, ""),
             account=aws_account_number(default_aws_config()))

    if service == "s3"
        region = ""
        account = ""
    elseif service == "iam"
        region = ""
    end

    "arn:aws:$service:$region:$account:$resource"
end

function arn(aws::AWSConfig,
             service,
             resource,
             region=get(aws, :region, ""),
             account=aws_account_number(aws))

    arn(service, resource, region, account)
end

"""
    arn_service(arn)

Extract service name from `arn`.
"""

arn_service(arn) = split(arn, ":")[3]

"""
    arn_region(arn)

Extract region name from `arn`.
"""

arn_region(arn) = split(arn, ":")[4]

"""
    arn_account(arn)

Extract account number from `arn`.
"""

arn_account(arn) = split(arn, ":")[5]

"""
    arn_resource(arn)

Extract resource name from `arn`.
"""

arn_resource(arn) = split(arn, ":")[6]

"""
    arn_iam_type

Extract IAM resource type from `arn`.
e.g. \"role\", \"policy\"...
"""
arn_iam_type(arn) = split(arn_resource(arn), "/")[1]

"""
    arn_iam_name

Extract IAM resource name from `arn`.
"""
arn_iam_name(arn) = split(arn_resource(arn), "/")[end]

"""
    is_arn(arn)

Is `arn` in the [correct format]?
(http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
"""

function is_arn(arn)

    v = split(arn, ":")
    p = [is_arn_prefix, is_partition, is_service, is_region, is_account]

    return length(v) >= 6 && all(v[1:5] .|> p)
end

arn_match(s, n, p) = ismatch(p, s) ||
                     (debug_level == 0 || warn("Bad ARN $n: \"$s\""); false)

is_arn_prefix(s) = arn_match(s, "prefix",   r"^arn$")
is_partition(s)  = arn_match(s, "partiton", r"^aws[a-z-]*$")
is_service(s)    = arn_match(s, "service",  r"^[a-zA-Z0-9\-]+$")
is_region(s)     = arn_match(s, "region",   r"^([a-z]{2}-[a-z]+-\d)?$")
is_account(s)    = arn_match(s, "account",  r"^(\d{12})?$")

#==============================================================================#
# End of file.
#==============================================================================#


text:
struct PrintLevel <: MOI.AbstractOptimizerAttribute end

MOI.supports(::Optimizer, ::MOI.RawParameter) = true
MOI.supports(::Optimizer, ::MOI.TimeLimitSec) = true
MOI.supports(::Optimizer, ::MOI.NumberOfThreads) = true

"""
    MOI.set(model::Optimizer, ::MOI.TimeLimitSec, value::Union{Nothing,Float64})
Set the time limit
"""
function MOI.set(model::Optimizer, ::MOI.TimeLimitSec, value::Union{Nothing,Float64})
    set_option!(model, "time_limit", isnothing(value) ? Inf : value)
end
function MOI.get(model::Optimizer, ::MOI.TimeLimitSec)
    tl = get_option(model, "time_limit")
    return isinf(tl) ? nothing : tl
end

"""
    MOI.set(model::Optimizer, p::MOI.RawParameter, value)
Set a RawParameter to `value`
"""
MOI.set(model::Optimizer, p::MOI.RawParameter, value) = set_option!(model, p.name, value)
MOI.get(model::Optimizer, p::MOI.RawParameter) = get_option(model, p.name)

function MOI.set(model::Optimizer, ::MOI.NumberOfThreads, value)
    set_option!(model, "threads", isnothing(value) ? typemax(0) : value)
end
function MOI.get(model::Optimizer, ::MOI.NumberOfThreads)
    nt = get_option(model, "threads")
    return nt == typemax(0) ? nothing : nt
end


text:
"""
    cubic(box::Array{<:Real,2},r::Number)

Make a lattice with cubic structure.

# Arguments

 - **box** (Array) 3D Box to be filled with spheres of radius r. e.g. [[0,1],[1,2],[0,4]]
 - **r** (Number) Radius of the sphere

# Returns
Community with the spheres
"""
function cubic(box::Array{<:Real,2},r::Number)

    d = size(box)
    if d != (3,2)
        error("Incompatible number of dimensions ", d)
    end

    #Make first dimension
    lineX = Array(box[1,1]:2*r:box[1,2])

    #Make second dimension
    lineY = fill(box[2,1]+r,length(lineX))
    nY = ceil(INT,(box[2,2]-box[2,1])/(2*r))
    areaX = zeros(FLOAT,1)
    areaY = zeros(FLOAT,1)
    dx = 2*r
    dy = 2*r
    for i in 0:nY-1
        append!(areaX,lineX)
        append!(areaY,lineY.+dy*i)
    end

    #Make third dimension
    areaZ = fill(box[2,1]+r,length(areaX))
    nZ = ceil(INT,(box[3,2]-box[3,1])/(2*r))
    volumeX = zeros(FLOAT,1)
    volumeY = zeros(FLOAT,1)
    volumeZ = zeros(FLOAT,1)
    dy = 2*r
    dz = 2*r
    for i in 0:nZ-1
        append!(volumeX,areaX)
        append!(volumeY,areaY)
        append!(volumeZ,areaZ.+dz*i)
    end

    #Return
    return [volumeX volumeY volumeZ]

end


text:
struct IDTreeNode
    id::Int
    children::Vector{IDTreeNode}

    IDTreeNode(id::Integer, children::Vector{IDTreeNode}=IDTreeNode[]) = new(id, children)
end

AbstractTrees.children(node::IDTreeNode) = node.children
AbstractTrees.printnode(io::IO, node::IDTreeNode) = print(io, "#", node.id)

"""
Basic tree type used for testing.

Each node has a unique ID, making them easy to reference. Node children are ordered.

Node type only implements `children`, so serves to test default implementations of most functions.
"""
struct IDTree
    nodes::Dict{Int, IDTreeNode}
    root::IDTreeNode
end

_make_idtreenode(id::Integer) = IDTreeNode(id)
_make_idtreenode((id, children)::Pair{<:Integer, <:Any}) = IDTreeNode(id, _make_idtreenode.(children))

"""
Create from nested `id => children` pairs. Leaf nodes may be represented by ID only.
"""
function IDTree(x)
    root = _make_idtreenode(x)
    nodes = Dict{Int, IDTreeNode}()

    for node in PreOrderDFS(root)
        haskey(nodes, node.id) && error("Duplicate node ID $(node.id)")
        nodes[node.id] = node
    end

    return IDTree(nodes, root)
end

@testset "IDTree" begin
    tree = IDTree(1 => [
        2 => [
            3,
            4 => [5],
        ],
        6,
        7 => [
            8 => [
                9,
                10,
                11 => 12:14,
                15,
            ],
        ],
        16,
    ])

    nodes = [tree.nodes[id] for id in 1:16]

    # Node/subtree properties
    #                              1   2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
    @test treesize.(nodes)    == [16, 4, 1, 2, 1, 1, 9, 8, 1, 1, 4, 1, 1, 1, 1, 1]
    @test treebreadth.(nodes) == [10, 2, 1, 1, 1, 1, 6, 6, 1, 1, 3, 1, 1, 1, 1, 1]
    @test treeheight.(nodes)  == [ 4, 2, 0, 1, 0, 0, 3, 2, 0, 0, 1, 0, 0, 0, 0, 0]

    # Child/descendant checking
    @test ischild(nodes[2], nodes[1])
    @test ischild(nodes[3], nodes[2])
    @test !ischild(nodes[3], nodes[1])
    @test !ischild(nodes[1], nodes[2])
    @test !ischild("foo", nodes[1])
    @test !ischild(nodes[1], "foo")

    @test isdescendant(nodes[2], nodes[1])
    @test isdescendant(nodes[9], nodes[1])
    @test isdescendant(nodes[12], nodes[7])
    @test !isdescendant(nodes[1], nodes[2])
    @test !isdescendant(nodes[4], nodes[8])
    @test !isdescendant(nodes[1], nodes[1])
    @test !isdescendant("foo", nodes[1])
    @test !isdescendant(nodes[1], "foo")

    @test intree(nodes[2], nodes[1])
    @test intree(nodes[9], nodes[1])
    @test intree(nodes[12], nodes[7])
    @test !intree(nodes[1], nodes[2])
    @test !intree(nodes[4], nodes[8])
    @test intree(nodes[1], nodes[1])
    @test !intree("foo", nodes[1])
    @test !intree(nodes[1], "foo")

    # Traversal
    @test [n.id for n in PreOrderDFS(tree.root)] == 1:16
    @test [n.id for n in PostOrderDFS(tree.root)] == [3, 5, 4, 2, 6, 9, 10, 12, 13, 14, 11, 15, 8, 7, 16, 1]
    @test [n.id for n in Leaves(tree.root)] == [3, 5, 6, 9, 10, 12, 13, 14, 15, 16]

    # printing
    @test AbstractTrees.repr_tree(tree.root) == """
    #1
    ├─ #2
    │  ├─ #3
    │  └─ #4
    │     └─ #5
    ├─ #6
    ├─ #7
    │  └─ #8
    │     ├─ #9
    │     ├─ #10
    │     ├─ #11
    │     │  ├─ #12
    │     │  ├─ #13
    │     │  └─ #14
    │     └─ #15
    └─ #16
    """
end

"""
    A tree in which every node has 0 or 1 children
"""
struct OneTree
    nodes::Vector{Int}
end
AbstractTrees.treekind(::Type{OneTree}) = AbstractTrees.IndexedTree()
AbstractTrees.siblinglinks(::Type{OneTree}) = AbstractTrees.StoredSiblings()
AbstractTrees.relative_state(t::OneTree, _, __::Int) = 1
Base.getindex(t::OneTree, idx) = t.nodes[idx]
AbstractTrees.childindices(tree::OneTree, node::Int) =
    (ret = (node == 0 || tree[node] == 0) ? () : (tree[node],))
AbstractTrees.children(tree::OneTree) = AbstractTrees.children(tree, tree)
AbstractTrees.rootstate(tree::OneTree) = 1
AbstractTrees.printnode(io::IO, t::OneTree) =
    AbstractTrees.printnode(io::IO, t[AbstractTrees.rootstate(t)])
Base.eltype(::Type{<:TreeIterator{OneTree}}) = Int
Base.IteratorEltype(::Type{<:TreeIterator{OneTree}}) = Base.HasEltype()

@testset "OneTree" begin
    ot = OneTree([2,3,4,0])
    @test repr_tree(ot) == """
        2
        └─ 3
           └─ 4
              └─ 0
        """
    @test @inferred(collect(Leaves(ot))) == [0]
    @test eltype(collect(Leaves(ot))) === Int
    @test collect(PreOrderDFS(ot)) == [2,3,4,0]
    @test collect(PostOrderDFS(ot)) == [0,4,3,2]
end

"""
    Stores an explicit parent for some other kind of tree
"""
struct ParentTree{T}
    tree::T
    parents::Vector{Int}
end
AbstractTrees.treekind(::Type{ParentTree{T}}) where {T} = AbstractTrees.treekind(T)
AbstractTrees.parentlinks(::Type{ParentTree{T}}) where {T} = AbstractTrees.StoredParents()
AbstractTrees.siblinglinks(::Type{ParentTree{T}}) where {T} = AbstractTrees.siblinglinks(T)
AbstractTrees.relative_state(t::ParentTree, x, r::Int) =
    AbstractTrees.relative_state(t.tree, x, r)
Base.getindex(t::ParentTree, idx) = t.tree[idx]
AbstractTrees.childindices(tree::ParentTree, node::Int) = AbstractTrees.childindices(tree.tree, node)
AbstractTrees.children(tree::ParentTree) = AbstractTrees.children(tree, tree)
AbstractTrees.rootstate(tree::ParentTree) = AbstractTrees.rootstate(tree.tree)
AbstractTrees.parentind(tree::ParentTree, node::Int) = tree.parents[node]
AbstractTrees.printnode(io::IO, t::ParentTree) =
    AbstractTrees.printnode(io::IO, t[AbstractTrees.rootstate(t)])

@testset "ParentTree" begin
    ot = OneTree([2,3,4,0])
    pt = ParentTree(ot,[0,1,2,3])

    @test repr_tree(pt) == """
        2
        └─ 3
           └─ 4
              └─ 0
        """
    @test collect(Leaves(pt)) == [0]
    @test collect(PreOrderDFS(pt)) == [2,3,4,0]
    @test collect(PostOrderDFS(pt)) == [0,4,3,2]

    # Test modification while iterating over PreOrderDFS
    a = [1,[2,[3]]]
    b = treemap!(PreOrderDFS(a)) do node
        !isa(node, Vector) && return node
        ret = pushfirst!(copy(node),0)
        # And just for good measure stomp over the old node to make sure nothing
        # is cached.
        empty!(node)
        ret
    end
    @test b == Any[0,1,Any[0,2,[0,3]]]
end

struct IntTree
    num::Int
    children::Vector{IntTree}
end
==(x::IntTree,y::IntTree) = x.num == y.num && x.children == y.children
AbstractTrees.children(itree::IntTree) = itree.children
Base.eltype(::Type{<:TreeIterator{IntTree}}) = IntTree
Base.IteratorEltype(::Type{<:TreeIterator{IntTree}}) = Base.HasEltype()
AbstractTrees.nodetype(::IntTree) = IntTree

@testset "IntTree" begin
    itree = IntTree(1, [IntTree(2, IntTree[])])
    iter = Leaves(itree)
    @test @inferred(first(iter)) == IntTree(2, IntTree[])
    val, state = iterate(iter)
    @test Base.return_types(iterate, Tuple{typeof(iter), typeof(state)}) ==
        [Union{Nothing, Tuple{IntTree,typeof(state)}}]
end

#=
@test treemap(PostOrderDFS(tree)) do ind, x, children
    IntTree(isa(x,Int) ? x : mapreduce(x->x.num,+,0,children),
        isempty(children) ? IntTree[] : children)
end == IntTree(6,[IntTree(1,IntTree[]),IntTree(5,[IntTree(2,IntTree[]),IntTree(3,IntTree[])])])
=#

@test collect(PostOrderDFS([])) == Any[[]]


text: # https://www.codewars.com/kata/5772382d509c65de7e000982/solutions/julia


text:
mutable struct Rigged{N} <: AbstractStreamableRNG
    values::Vector
    index::Int64
    function Rigged(values::Vector)
        @assert(reduce(&, (x -> (0 <x < 1)).(values)))
        index = 1
        N = length(values)
        return new{N}(values, index)
    end
end

function reset_stream!(r::Rigged{N}) where N
    r.index = 1
end

reset_substream!(r::Rigged{N}) where {N} = reset_stream!(r::Rigged{N})

function rand_inbounds(r::Rigged{N}, ::Random.CloseOpen12_64) where N
    if r.index > N
        r.index = 1
    end
    val = r.values[r.index] + 1.0
    r.index += 1
    return val
end

function rand_inbounds(r::Rigged{N}, ::Random.CloseOpen01_64=Random.CloseOpen01()) where N
    if r.index > N
        r.index = 1
    end
    val = r.values[r.index]
    r.index += 1
    return val
end

############################
rand_inbounds(r::Rigged, ::Random.UInt52Raw{T}) where {T<:Random.BitInteger} = reinterpret(UInt64, rand_inbounds(r, Random.CloseOpen12())) % T

function rand(r::Rigged, x::Random.SamplerTrivial{Random.UInt52Raw{UInt64}})
    rand_inbounds(r, x[])
end

function rand(r::Rigged, ::Random.SamplerTrivial{Random.UInt2x52Raw{UInt128}})
    rand_inbounds(r, Random.UInt52Raw(UInt128)) << 64 | rand_inbounds(r, Random.UInt52Raw(UInt128))
end

function rand(r::Rigged, ::Random.SamplerTrivial{Random.UInt104Raw{UInt128}})
    reserve(r, 2)
	xor(rand_inbounds(r, Random.UInt52Raw(UInt128)) << 52, rand_inbounds(r, Random.UInt52Raw(UInt128)))
end

#### floats

rand(r::Rigged, sp::Random.SamplerTrivial{Random.CloseOpen12_64}) = rand_inbounds(r, sp[])


text:
using PointCloudFilters
using Test

@testset "PointCloudFilters.jl" begin
    # Write your own tests here.
end