code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def pull_logs(self, project_name, logstore_name, shard_id, cursor, count=None, end_cursor=None, compress=None): headers = {} if compress is None or compress: if lz4: headers['Accept-Encoding'] = 'lz4' else: headers['Accept-Encodin...
batch pull log data from log service Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shard_id: int :param sh...
null
null
null
def pull_log(self, project_name, logstore_name, shard_id, from_time, to_time, batch_size=None, compress=None): begin_cursor = self.get_cursor(project_name, logstore_name, shard_id, from_time).get_cursor() end_cursor = self.get_cursor(project_name, logstore_name, shard_id, to_time).get_cursor...
batch pull log data from log service using time-range Unsuccessful opertaion will cause an LogException. the time parameter means the time when server receives the logs :type project_name: string :param project_name: the Project name :type logstore_name: string :param lo...
null
null
null
def pull_log_dump(self, project_name, logstore_name, from_time, to_time, file_path, batch_size=None, compress=None, encodings=None, shard_list=None, no_escape=None): file_path = file_path.replace("{}", "{0}") if "{0}" not in file_path: file_path += "{0}" ...
dump all logs seperatedly line into file_path, file_path, the time parameters are log received time on server side. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type from_time: str...
null
null
null
def create_logstore(self, project_name, logstore_name, ttl=30, shard_count=2, enable_tracking=False, append_meta=False, auto_split=True, max_split_shard=64, ...
create log store Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type ttl: int :param ttl: the life cycle of log...
null
null
null
def delete_logstore(self, project_name, logstore_name): headers = {} params = {} resource = "/logstores/" + logstore_name (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteLogStoreResponse(header, resp)
delete log store Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: DeleteLogStoreResponse :raise:...
null
null
null
def get_logstore(self, project_name, logstore_name): headers = {} params = {} resource = "/logstores/" + logstore_name (resp, header) = self._send("GET", project_name, None, resource, params, headers) return GetLogStoreResponse(resp, header)
get the logstore meta info Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: GetLogStoreResponse ...
null
null
null
def update_logstore(self, project_name, logstore_name, ttl=None, enable_tracking=None, shard_count=None, append_meta=None, auto_split=None, max_split_shard=None, preserve_storage=None ): ...
update the logstore meta info Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type ttl: int :param ttl: the life ...
null
null
null
def list_logstore(self, project_name, logstore_name_pattern=None, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_logstore, int(offset), int(size), MAX_LIST_PAGING_SIZE, ...
list the logstore in a projectListLogStoreResponse Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name_pattern: string :param logstore_name_pattern: the sub name logstore, used for the se...
null
null
null
def create_external_store(self, project_name, config): params = {} resource = "/externalstores" headers = {"x-log-bodyrawsize": '0', "Content-Type": "application/json"} body_str = six.b(json.dumps(config.to_json())) (resp, header) = self._send("POST", project_n...
create log store Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config : ExternalStoreConfig :param config :external store config :return: CreateExternalStoreResponse ...
null
null
null
def delete_external_store(self, project_name, store_name): headers = {} params = {} resource = "/externalstores/" + store_name (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteExternalStoreResponse(header, resp)
delete log store Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type store_name: string :param store_name: the external store name :return: DeleteExternalStoreResponse :r...
null
null
null
def get_external_store(self, project_name, store_name): headers = {} params = {} resource = "/externalstores/" + store_name (resp, header) = self._send("GET", project_name, None, resource, params, headers) # add storeName if not existing if 'externalSt...
get the logstore meta info Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type store_name: string :param store_name: the logstore name :return: GetLogStoreResponse :raise...
null
null
null
def update_external_store(self, project_name, config): headers = {"x-log-bodyrawsize": '0', "Content-Type": "application/json"} params = {} resource = "/externalstores/" + config.externalStoreName body_str = six.b(json.dumps(config.to_json())) (resp, header) = se...
update the logstore meta info Unsuccessful opertaion will cause an LogException. :type config: ExternalStoreConfig :param config : external store config :return: UpdateExternalStoreResponse :raise: LogException
null
null
null
def list_external_store(self, project_name, external_store_name_pattern=None, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_external_store, int(offset), int(size), MAX_LIST_PAGI...
list the logstore in a projectListLogStoreResponse Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name_pattern: string :param logstore_name_pattern: the sub name logstore, used for the se...
null
null
null
def list_shards(self, project_name, logstore_name): headers = {} params = {} resource = "/logstores/" + logstore_name + "/shards" (resp, header) = self._send("GET", project_name, None, resource, params, headers) return ListShardResponse(resp, header)
list the shard meta of a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: ListShardResponse ...
null
null
null
def split_shard(self, project_name, logstore_name, shardId, split_hash): headers = {} params = {"action": "split", "key": split_hash} resource = "/logstores/" + logstore_name + "/shards/" + str(shardId) (resp, header) = self._send("POST", project_name, None, resource, par...
split a readwrite shard into two shards Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shardId: int ...
null
null
null
def delete_shard(self, project_name, logstore_name, shardId): headers = {} params = {} resource = "/logstores/" + logstore_name + "/shards/" + str(shardId) (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteShardRespon...
delete a readonly shard Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shardId: int :param shardId...
null
null
null
def update_index(self, project_name, logstore_name, index_detail): headers = {} params = {} resource = "/logstores/" + logstore_name + "/index" headers['Content-Type'] = 'application/json' body = six.b(json.dumps(index_detail.to_json())) headers['x-log-b...
update index for a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type index_detail: IndexConfig :param...
null
null
null
def delete_index(self, project_name, logstore_name): headers = {} params = {} resource = "/logstores/" + logstore_name + "/index" (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteIndexResponse(header, resp)
delete index of a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: DeleteIndexResponse ...
null
null
null
def get_index_config(self, project_name, logstore_name): headers = {} params = {} resource = "/logstores/" + logstore_name + "/index" (resp, header) = self._send("GET", project_name, None, resource, params, headers) return GetIndexResponse(resp, header)
get index config detail of a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: GetIndexResponse :...
null
null
null
def create_logtail_config(self, project_name, config_detail): if config_detail.logstore_name: # try to verify if the logstore exists or not. self.get_logstore(project_name, config_detail.logstore_name) headers = {} params = {} resource = "/conf...
create logtail config in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_detail: LogtailConfigGenerator or SeperatorFileConfigDetail or SimpleFileConfigDetail or FullRegFileConfigDetail or...
null
null
null
def update_logtail_config(self, project_name, config_detail): headers = {} params = {} resource = "/configs/" + config_detail.config_name headers['Content-Type'] = 'application/json' body = six.b(json.dumps(config_detail.to_json())) headers['x-log-bodyra...
update logtail config in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_detail: LogtailConfigGenerator or SeperatorFileConfigDetail or SimpleFileConfigDetail or FullRegFileConfigDetail or...
null
null
null
def delete_logtail_config(self, project_name, config_name): headers = {} params = {} resource = "/configs/" + config_name (resp, headers) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteLogtailConfigResponse(headers, resp)
delete logtail config in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name :return: DeleteLogtailConfigResponse ...
null
null
null
def get_logtail_config(self, project_name, config_name): headers = {} params = {} resource = "/configs/" + config_name (resp, headers) = self._send("GET", project_name, None, resource, params, headers) return GetLogtailConfigResponse(resp, headers)
get logtail config in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name :return: GetLogtailConfigResponse ...
null
null
null
def list_logtail_config(self, project_name, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_logtail_config, int(offset), int(size), MAX_LIST_PAGING_SIZE, project_name) he...
list logtail config name in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type offset: int :param offset: the offset of all config names :type size: int :param size: the...
null
null
null
def create_machine_group(self, project_name, group_detail): headers = {} params = {} resource = "/machinegroups" headers['Content-Type'] = 'application/json' body = six.b(json.dumps(group_detail.to_json())) headers['x-log-bodyrawsize'] = str(len(body)) ...
create machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param group_detail: the machine group detail config :return: CreateMa...
null
null
null
def delete_machine_group(self, project_name, group_name): headers = {} params = {} resource = "/machinegroups/" + group_name (resp, headers) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteMachineGroupResponse(headers, resp)
delete machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_name: string :param group_name: the group name :return: DeleteMachineGroupResponse ...
null
null
null
def update_machine_group(self, project_name, group_detail): headers = {} params = {} resource = "/machinegroups/" + group_detail.group_name headers['Content-Type'] = 'application/json' body = six.b(json.dumps(group_detail.to_json())) headers['x-log-bodyr...
update machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param group_detail: the machine group detail config :return: UpdateMa...
null
null
null
def get_machine_group(self, project_name, group_name): headers = {} params = {} resource = "/machinegroups/" + group_name (resp, headers) = self._send("GET", project_name, None, resource, params, headers) return GetMachineGroupResponse(resp, headers)
get machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_name: string :param group_name: the group name to get :return: GetMachineGroupResponse ...
null
null
null
def list_machine_group(self, project_name, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_machine_group, int(offset), int(size), MAX_LIST_PAGING_SIZE, project_name) he...
list machine group names in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type offset: int :param offset: the offset of all group name :type size: int :param size: the m...
null
null
null
def list_machines(self, project_name, group_name, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_machines, int(offset), int(size), MAX_LIST_PAGING_SIZE, project_name, group_name)...
list machines in a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_name: string :param group_name: the group name to list :type offset: int :param o...
null
null
null
def apply_config_to_machine_group(self, project_name, config_name, group_name): headers = {} params = {} resource = "/machinegroups/" + group_name + "/configs/" + config_name (resp, header) = self._send("PUT", project_name, None, resource, params, headers) return A...
apply a logtail config to a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name to apply :type group_na...
null
null
null
def remove_config_to_machine_group(self, project_name, config_name, group_name): headers = {} params = {} resource = "/machinegroups/" + group_name + "/configs/" + config_name (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) retu...
remove a logtail config to a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name to apply :type group_n...
null
null
null
def get_machine_group_applied_configs(self, project_name, group_name): headers = {} params = {} resource = "/machinegroups/" + group_name + "/configs" (resp, header) = self._send("GET", project_name, None, resource, params, headers) return GetMachineGroupAppliedC...
get the logtail config names applied in a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_name: string :param group_name: the group name list :return: GetMachineGrou...
null
null
null
def get_config_applied_machine_groups(self, project_name, config_name): headers = {} params = {} resource = "/configs/" + config_name + "/machinegroups" (resp, header) = self._send("GET", project_name, None, resource, params, headers) return GetConfigAppliedMachi...
get machine group names where the logtail config applies to Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string :param config_name: the logtail config name used to apply ...
null
null
null
def get_shipper_tasks(self, project_name, logstore_name, shipper_name, start_time, end_time, status_type='', offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.ge...
get odps/oss shipper tasks in a certain time range Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shipper_name: str...
null
null
null
def retry_shipper_tasks(self, project_name, logstore_name, shipper_name, task_list): headers = {} params = {} body = six.b(json.dumps(task_list)) headers['Content-Type'] = 'application/json' headers['x-log-bodyrawsize'] = str(len(body)) resource = "/logsto...
retry failed tasks , only the failed task can be retried Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shipper_name...
null
null
null
def create_project(self, project_name, project_des): params = {} body = {"projectName": project_name, "description": project_des} body = six.b(json.dumps(body)) headers = {'Content-Type': 'application/json', 'x-log-bodyrawsize': str(len(body))} resource = "/" ...
Create a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type project_des: string :param project_des: the description of a project :return: CreateProjectResponse :raise: ...
null
null
null
def get_project(self, project_name): headers = {} params = {} resource = "/" (resp, header) = self._send("GET", project_name, None, resource, params, headers) return GetProjectResponse(resp, header)
get project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :return: GetProjectResponse :raise: LogException
null
null
null
def delete_project(self, project_name): headers = {} params = {} resource = "/" (resp, header) = self._send("DELETE", project_name, None, resource, params, headers) return DeleteProjectResponse(header, resp)
delete project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :return: DeleteProjectResponse :raise: LogException
null
null
null
def create_consumer_group(self, project, logstore, consumer_group, timeout, in_order=False): request = CreateConsumerGroupRequest(project, logstore, ConsumerGroupEntity(consumer_group, timeout, in_order)) consumer_group = request.consumer_group body_str = consumer_group.to_request_j...
create consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type timeout: int :param timeout: time-o...
null
null
null
def update_consumer_group(self, project, logstore, consumer_group, timeout=None, in_order=None): if in_order is None and timeout is None: raise ValueError('in_order and timeout can\'t all be None') elif in_order is not None and timeout is not None: body_dict = { ...
Update consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type timeout: int :param timeout: timeou...
null
null
null
def delete_consumer_group(self, project, logstore, consumer_group): headers = {"x-log-bodyrawsize": '0'} params = {} resource = "/logstores/" + logstore + "/consumergroups/" + consumer_group (resp, header) = self._send("DELETE", project, None, resource, params, headers)...
Delete consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :return: None
null
null
null
def list_consumer_group(self, project, logstore): resource = "/logstores/" + logstore + "/consumergroups" params = {} headers = {} (resp, header) = self._send("GET", project, None, resource, params, headers) return ListConsumerGroupResponse(resp, header)
List consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :return: ListConsumerGroupResponse
null
null
null
def update_check_point(self, project, logstore, consumer_group, shard, check_point, consumer='', force_success=True): request = ConsumerGroupUpdateCheckPointRequest(project, logstore, consumer_group, consumer, shard, ...
Update check point :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type shard: int :param shard: shard id ...
null
null
null
def get_check_point(self, project, logstore, consumer_group, shard=-1): request = ConsumerGroupGetCheckPointRequest(project, logstore, consumer_group, shard) params = request.get_params() headers = {} resource = "/logstores/" + logstore + "/consumergroups/" + consumer_group...
Get check point :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type shard: int :param shard: shard id ...
null
null
null
def get_check_point_fixed(self, project, logstore, consumer_group, shard=-1): res = self.get_check_point(project, logstore, consumer_group, shard) res.check_checkpoint(self, project, logstore) return res
Get check point :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type shard: int :param shard: shard id ...
null
null
null
def heart_beat(self, project, logstore, consumer_group, consumer, shards=None): if shards is None: shards = [] request = ConsumerGroupHeartBeatRequest(project, logstore, consumer_group, consumer, shards) body_str = request.get_request_body() params = request.ge...
Heatbeat consumer group :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type consumer_group: string :param consumer_group: consumer group name :type consumer: string :param consumer:...
null
null
null
def copy_project(self, from_project, to_project, to_client=None, copy_machine_group=False): if to_client is None: to_client = self return copy_project(self, to_client, from_project, to_project, copy_machine_group)
copy project, logstore, machine group and logtail config to target project, expecting the target project doesn't contain same named logstores as source project :type from_project: string :param from_project: project name :type to_project: string :param to_project: projec...
null
null
null
def copy_logstore(self, from_project, from_logstore, to_logstore, to_project=None, to_client=None): return copy_logstore(self, from_project, from_logstore, to_logstore, to_project=to_project, to_client=to_client)
copy logstore, index, logtail config to target logstore, machine group are not included yet. the target logstore will be crated if not existing :type from_project: string :param from_project: project name :type from_logstore: string :param from_logstore: logstore name ...
null
null
null
def list_project(self, offset=0, size=100): # need to use extended method to get more if int(size) == -1 or int(size) > MAX_LIST_PAGING_SIZE: return list_more(self.list_project, int(offset), int(size), MAX_LIST_PAGING_SIZE) headers = {} params = {} ...
list the project Unsuccessful opertaion will cause an LogException. :type offset: int :param offset: the offset of all the matched names :type size: int :param size: the max return names count, -1 means return all data :return: ListProjectResponse :...
null
null
null
def es_migration(self, hosts, project_name, indexes=None, query=None, scroll="5m", logstore_index_mappings=None, pool_size=10, time_reference=None, ...
migrate data from elasticsearch to aliyun log service :type hosts: string :param hosts: a comma-separated list of source ES nodes. e.g. "localhost:9200,other_host:9200" :type project_name: string :param project_name: specify the project_name of your log services. e.g. "your_proje...
null
null
null
def copy_data(self, project, logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, batch_size=None, compress=None, new_topic=None, new_source=None): return copy_data(self, project, logstore, from...
copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side. :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type from_time: string/int ...
null
null
null
def arrange_shard(self, project, logstore, count): return arrange_shard(self, project, logstore, count)
arrange shard to the expected read-write count to a larger one. :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type count: int :param count: expected read-write shard count. should be larger than the c...
null
null
null
if v is None: return "" if isinstance(v, (dict, list)): try: v = json.dumps(v) except Exception: pass elif six.PY2 and isinstance(v, six.text_type): v = v.encode('utf8', "ignore") elif six.PY3 and i...
def _n(v)
convert string to utf8 in Py2 or unicode in Py3 :param v: :return:
2.235747
2.156176
1.036904
if not self.option.cursor_end_time: return False all_finish = True for shard, consumer in self.shard_consumers.items(): if consumer.is_shutdown(): continue # has not yet do any successful fetch yet or get some data if con...
def _need_stop(self)
check if need to stop: 1. end_cursor has been hit and there's no more shard assinged (wait for heatbeat_interval * 3) :return:
4.820379
4.365919
1.104093
Thread.start(self) if join: try: while self.is_alive(): self.join(timeout=60) self.logger.info("worker {0} exit unexpected, try to shutdown it".format(self.option.consumer_name)) self.shutdown() except ...
def start(self, join=False)
when calling with join=True, must call it in main thread, or else, the Keyboard Interrupt won't be caputured. :param join: default False, if hold on until the worker is stopped by Ctrl+C or other reasons. :return:
6.308607
6.101137
1.034005
try: check_point = processor.process(log_groups, check_point_tracker) check_point_tracker.flush_check() except Exception as e: return TaskResult(e) return ProcessTaskResult(check_point)
def consumer_process_task(processor, log_groups, check_point_tracker)
return TaskResult if failed, return ProcessTaskResult if succeed :param processor: :param log_groups: :param check_point_tracker: :return:
4.465024
3.417803
1.306402
try: processor.initialize(shard_id) is_cursor_persistent = False check_point = consumer_client.get_check_point(shard_id) if check_point['checkpoint'] and len(check_point['checkpoint']) > 0: is_cursor_persistent = True cursor = check_point['checkpoint'] ...
def consumer_initialize_task(processor, consumer_client, shard_id, cursor_position, cursor_start_time, cursor_end_time=None)
return TaskResult if failed, or else, return InitTaskResult :param processor: :param consumer_client: :param shard_id: :param cursor_position: :param cursor_start_time: :return:
2.06378
1.959791
1.053061
exception = None try: processor.shutdown(check_point_tracker) except Exception as e: print(e) exception = None try: check_point_tracker.get_check_point() except Exception: logger.error('Failed to flush check point', exc_info=True) return TaskResult(...
def consumer_shutdown_task(processor, check_point_tracker)
:param processor: :param check_point_tracker: :return:
3.66753
3.820534
0.959952
if k > n: return 0 if k == 0: return 1 r = 1 for d in range(1, k + 1): r *= n r /= d n -= 1 return r
def nCk(n, k)
http://blog.plover.com/math/choose.html
2.231921
2.140174
1.042869
totalTime = 0.000001 for region in exp.network.regions.values(): timer = region.getComputeTimer() totalTime += timer.getElapsed() # Sort the region names regionNames = list(exp.network.regions.keys()) regionNames.sort() count = 1 profileInfo = [] L2Time = 0.0 L4Time = 0.0 for regionNam...
def getProfileInfo(exp)
Prints profiling information. Parameters: ---------------------------- @param reset (bool) If set to True, the profiling will be reset.
3.010143
3.130715
0.961487
numRpts = 20 df = None args = [] for sampleSizeProximal in sampleSizeProximalList: for sampleSizeDistal in sampleSizeDistalList: for rpt in range(numRpts): l4Params = getL4Params() l2Params = getL2Params() l2Params["sampleSizeProximal"] = sampleSizeProximal l2Params...
def experimentVaryingSynapseSampling(expParams, sampleSizeDistalList, sampleSizeProximalList)
Test multi-column convergence with varying amount of proximal/distal sampling :return:
2.740631
2.732435
1.003
unionSDRTrace = self.mmGetTraceUnionSDR().data columnCount = self.getNumColumns() activityType = "Union SDR Activity" return self.mmGetCellTracePlot(unionSDRTrace, columnCount, activityType, title=title, showReset=showReset, rese...
def mmGetPlotUnionSDRActivity(self, title="Union SDR Activity Raster", showReset=False, resetShading=0.25)
Returns plot of the activity of union SDR bits. @param title an optional title for the figure @param showReset if true, the first set of activities after a reset will have a gray background @param resetShading If showReset is true, this float specifies the intensity of the reset ...
5.624349
5.835982
0.963736
plot = Plot(self, title) connectedCounts = numpy.ndarray(self.getNumColumns(), dtype=uintType) self.getConnectedCounts(connectedCounts) plot.addGraph(sorted(connectedCounts.tolist(), reverse=True), position=211, xlabel="column", ylabel="# connections") plot...
def mmGetPlotConnectionsPerColumn(self, title="Connections per Columns")
Returns plot of # connections per column. @return (Plot) plot
5.182266
5.3462
0.969336
matrix = self.mmGetDataOverlap() resetsTrace = self.mmGetTraceResets() text = "" for i, row in enumerate(matrix): if resetsTrace.data[i]: text += "\n" for j, item in enumerate(row): if resetsTrace.data[j]: text += " " text += "{:4}".format(item) ...
def mmPrettyPrintDataOverlap(self)
Returns pretty-printed string representation of overlap metric data. (See `mmGetDataOverlap`.) @return (string) Pretty-printed data
4.379505
4.516323
0.969706
self._mmComputeSequenceRepresentationData() numbers = self._mmData["stabilityConfusion"] return Metric(self, "stability confusion", numbers)
def mmGetMetricStabilityConfusion(self)
For each iteration that doesn't follow a reset, looks at every other iteration for the same world that doesn't follow a reset, and computes the number of bits that show up in one or the other set of active cells for that iteration, but not both. This metric returns the distribution of those numbers. ...
20.877707
19.03755
1.096659
plot = Plot(self, title) self._mmComputeSequenceRepresentationData() data = self._mmData["stabilityConfusion"] plot.addGraph(sorted(data, reverse=True), position=211, xlabel="Time steps", ylabel="Overlap") plot.addHistogram(data, positio...
def mmGetPlotStability(self, title="Stability", showReset=False, resetShading=0.25)
Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot
7.883505
7.199407
1.095021
self._mmComputeSequenceRepresentationData() numbers = self._mmData["distinctnessConfusion"] return Metric(self, "distinctness confusion", numbers)
def mmGetMetricDistinctnessConfusion(self)
For each iteration that doesn't follow a reset, looks at every other iteration for every other world that doesn't follow a reset, and computes the number of bits that show up in both sets of active cells those that iteration. This metric returns the distribution of those numbers. @return (Metric) Disti...
20.999207
20.621891
1.018297
period = self.getDutyCyclePeriod() unionSDRArray = numpy.zeros(self.getNumColumns()) unionSDRArray[list(self._mmTraces["unionSDR"].data[-1])] = 1 self._mmData["unionSDRDutyCycle"] = \ UnionTemporalPoolerMonitorMixin._mmUpdateDutyCyclesHelper( self._mmData["unionSDRDutyCycle"], union...
def _mmUpdateDutyCycles(self)
Update the duty cycle variables internally tracked by the TM mixin.
6.923239
6.798297
1.018378
if not self._sequenceRepresentationDataStale: return unionSDRTrace = self.mmGetTraceUnionSDR() sequenceLabelsTrace = self.mmGetTraceSequenceLabels() resetsTrace = self.mmGetTraceResets() n = len(unionSDRTrace.data) overlapMatrix = numpy.empty((n, n), dtype=uintType) stabilityCon...
def _mmComputeSequenceRepresentationData(self)
Calculates values for the overlap distance matrix, stability within a sequence, and distinctness between sequences. These values are cached so that they do need to be recomputed for calls to each of several accessor methods that use these values.
2.822822
2.596457
1.087182
global _PY_REGIONS if moduleName is None: # the region is located in the regions/ directory moduleName = "htmresearch.regions." + regionTypeName if regionTypeName not in _PY_REGIONS: # Add new region class to the network. module = __import__(moduleName, {}, {}, regionTypeName) unregistered...
def registerResearchRegion(regionTypeName, moduleName=None)
Register this region so that NuPIC can later find it. @param regionTypeName: (str) type name of the region. E.g LanguageSensor. @param moduleName: (str) location of the region class, only needed if registering a region that is outside the expected "regions/" dir.
6.254983
5.942894
1.052515
try: images = sc.loadmat(path)[name] except KeyError: raise KeyError('Wrong filename for provided images.') self._initializeDimensions(images) return images
def loadMatlabImages(self, path, name)
Loads images from a .mat file. :param path: (string) Path to .mat file :param name: (string) Object name in the .mat file, just before .mat Also stores image dimensions to later the original images. If there are multiple channels, self.numChannels will store the number of channels, ot...
11.573684
12.555509
0.921801
data = np.load(path) if isinstance(data, dict): if key is None: raise ValueError("Images are stored as a dict, a key must be provided!") try: data = data[key] except KeyError: raise KeyError("Wrong key for provided data.") if not isinstance(data, np.ndarray):...
def loadNumpyImages(self, path, key=None)
Loads images using numpy. :param path: (string) Path to data file :param key: (string) Object key in data file if it's a dict Also stores image dimensions to later the original images. If there are multiple channels, self.numChannels will store the number of channels, otherwise it w...
3.911383
3.841622
1.018159
if len(inputData.shape) == 2: self.imageHeight, self.numImages = inputData.shape self.imageWidth, self.numChannels = None, None elif len(inputData.shape) == 3: self.imageHeight, \ self.imageWidth, \ self.numImages = inputData.shape self.numChannels = None elif len(...
def _initializeDimensions(self, inputData)
Stores the training images' dimensions, for convenience.
2.133942
2.005114
1.06425
if not hasattr(self, 'numImages'): self._initializeDimensions(inputData) batch = np.zeros((self.filterDim, self.batchSize)) # choose correct patch size if self.imageHeight is None: patchSize = self.filterDim elif self.numChannels is None or self.numChannels == 0: patchSize =...
def _getDataBatch(self, inputData)
Returns an array of dimensions (filterDim, batchSize), to be used as batch for training data. This implementation uses random sub-patches as training batch. Images are flattened to get a 2-dimensional batch.
2.511764
2.35713
1.065603
plot = Plot(self, title) plot.addGraph(sorted(self._connectedCounts.tolist(), reverse=True), position=211, xlabel="column", ylabel="# connections") plot.addHistogram(self._connectedCounts.tolist(), position=212, bins=len(se...
def mmGetPlotConnectionsPerColumn(self, title=None)
Returns plot of # connections per column. @return (Plot) plot
5.374802
5.041283
1.066157
cellTrace = self._mmTraces["activeCells"].data cellCount = self.getNumColumns() activityType = "Cell Activity" return self.mmGetCellTracePlot(cellTrace, cellCount, activityType, title=title, showReset=showReset, resetShading=rese...
def mmGetCellActivityPlot(self, title=None, showReset=False, resetShading=0.25)
Returns plot of the cell activity. @param title an optional title for the figure @param showReset if true, the first set of cell activities after a reset will have a gray background @param resetShading If showReset is true, this float specifies the intensity of the reset backgrou...
6.05916
6.742393
0.898666
plot = Plot(self, title) data = numpy.zeros((self.getNumColumns(), self.getNumInputs())) for i in xrange(self.getNumColumns()): self.getPermanence(i, data[i]) plot.add2DArray(data, xlabel="Permanences", ylabel="Column") return plot
def mmGetPermanencesPlot(self, title=None)
Returns plot of column permanences. @param title an optional title for the figure @return (Plot) plot
4.523726
4.964752
0.911169
self.startTime = time.time() print(params) seed = params["seed"] + repetition torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) # Get our directories correct self.dataDir = os.path.join(params["datadir"], "speech_commands") self.resultsDir = os.path.join(params["pa...
def reset(self, params, repetition)
Called once at the beginning of each experiment.
2.203895
2.191518
1.005648
print("\nStarting iteration",iteration) print("Learning rate:", self.learningRate if self.lr_scheduler is None else self.lr_scheduler.get_lr()) t1 = time.time() ret = {} # Update dataset epoch when using pre-processed speech dataset if self.use...
def iterate(self, params, repetition, iteration)
Called once for each training iteration (== epoch here).
2.667449
2.645605
1.008257
if params.get("saveNet", True): saveDir = os.path.join(params["path"], params["name"], "model_{}.pt".format(rep)) torch.save(self.model, saveDir)
def finalize(self, params, rep)
Save the full model once we are done.
5.346552
4.400052
1.215111
lr_scheduler = params.get("lr_scheduler", None) if lr_scheduler is None: return None if lr_scheduler == "StepLR": lr_scheduler_params = "{'step_size': 1, 'gamma':" + str(params["learning_rate_factor"]) + "}" else: lr_scheduler_params = params.get("lr_scheduler_params", None) ...
def createLearningRateScheduler(self, params, optimizer)
Creates the learning rate scheduler and attach the optimizer
2.584594
2.596576
0.995385
lr = params["learning_rate"] print("Creating optimizer with learning rate=", lr) if params["optimizer"] == "SGD": optimizer = optim.SGD(model.parameters(), lr=lr, momentum=params["momentum"], weight_decay=params["weight_decay"], ...
def createOptimizer(self, params, model)
Create a new instance of the optimizer
2.489001
2.532098
0.98298
# Check for pre-trained model modelCheckpoint = os.path.join(params["path"], params["name"], "model_{}_{}.pt".format(repetition, epoch)) if os.path.exists(modelCheckpoint): self.model = torch.load(modelCheckpoint, map_location=self.device) return self...
def train(self, params, epoch, repetition)
Train one epoch of this model by iterating through mini batches. An epoch ends after one pass through the training set, or if the number of mini batches exceeds the parameter "batches_in_epoch".
3.512357
3.418933
1.027325
n_mels = 32 # Check if using pre-processed data or raw data self.use_preprocessed_dataset = PreprocessedSpeechDataset.isValid(self.dataDir) if self.use_preprocessed_dataset: trainDataset = PreprocessedSpeechDataset(self.dataDir, subset="train") validationDataset = PreprocessedSpeechDat...
def loadDatasets(self, params)
The GSC dataset specifies specific files to be used as training, test, and validation. We assume the data has already been processed according to those files into separate train, test, and valid directories. For our experiment we use a subset of the data (10 categories out of 30), just like the Kaggle...
2.386748
2.402021
0.993642
if not self.contains(location): return self.EMPTY_FEATURE return self.SPHERICAL_SURFACE
def getFeatureID(self, location)
Returns the feature index associated with the provided location. In the case of a sphere, it is always the same if the location is valid.
16.841331
14.844292
1.134533
return self.almostEqual( sum([coord ** 2 for coord in location]), self.radius ** 2 )
def contains(self, location)
Checks that the provided point is on the sphere.
13.123446
8.173873
1.605536
if feature == "surface": coordinates = [random.gauss(0, 1.) for _ in xrange(self.dimension)] norm = sqrt(sum([coord ** 2 for coord in coordinates])) return [self.radius * coord / norm for coord in coordinates] elif feature == "random": return self.sampleLocation() else: ra...
def sampleLocationFromFeature(self, feature)
Samples a location from the provided specific feature. In the case of a sphere, there is only one feature.
4.424134
3.943132
1.121985
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # generate sphere phi, theta = np.meshgrid( np.linspace(0, pi, numPoints), np.linspace(0, 2 * pi, numPoints) ) x = self.radius * np.sin(phi) * np.cos(theta) y = self.radius * np.sin(phi) * np.sin(theta) z = s...
def plot(self, numPoints=100)
Specific plotting method for cylinders.
1.880229
1.806051
1.041072
if not self.contains(location): return self.EMPTY_FEATURE if self.almostEqual(abs(location[2]), self.height / 2.): if self.almostEqual(location[0] ** 2 + location[1] ** 2, self.radius ** 2): return self.CYLINDER_EDGE else: return self.FLAT el...
def getFeatureID(self, location)
Returns the feature index associated with the provided location. Three possibilities: - top discs - edges - lateral surface
4.36333
4.063637
1.07375
if self.almostEqual(location[0] ** 2 + location[1] ** 2, self.radius ** 2): return abs(location[2]) < self.height / 2. if self.almostEqual(location[2], self.height / 2.): return location[0] ** 2 + location[1] ** 2 < self.radius ** 2 return False
def contains(self, location)
Checks that the provided point is on the cylinder.
2.660715
2.353132
1.130712
areaRatio = self.radius / (self.radius + self.height) if random.random() < areaRatio: return self._sampleLocationOnDisc() else: return self._sampleLocationOnSide()
def sampleLocation(self)
Simple method to sample uniformly from a cylinder.
6.431373
4.671327
1.376776
if feature == "topDisc": return self._sampleLocationOnDisc(top=True) elif feature == "topEdge": return self._sampleLocationOnEdge(top=True) elif feature == "bottomDisc": return self._sampleLocationOnDisc(top=False) elif feature == "bottomEdge": return self._sampleLocationOnE...
def sampleLocationFromFeature(self, feature)
Samples a location from the provided specific features.
2.424144
2.389708
1.01441
if top is None: z = random.choice([-1, 1]) * self.height / 2. else: z = self.height / 2. if top else - self.height / 2. sampledAngle = 2 * random.random() * pi sampledRadius = self.radius * sqrt(random.random()) x, y = sampledRadius * cos(sampledAngle), sampledRadius * sin(sampledAn...
def _sampleLocationOnDisc(self, top=None)
Helper method to sample from the top and bottom discs of a cylinder. If top is set to True, samples only from top disc. If top is set to False, samples only from bottom disc. If not set (defaults to None), samples from both discs.
3.000232
2.959036
1.013922
if top is None: z = random.choice([-1, 1]) * self.height / 2. else: z = self.height / 2. if top else - self.height / 2. sampledAngle = 2 * random.random() * pi x, y = self.radius * cos(sampledAngle), self.radius * sin(sampledAngle) return [x, y, z]
def _sampleLocationOnEdge(self, top=None)
Helper method to sample from the top and bottom edges of a cylinder. If top is set to True, samples only from top edge. If top is set to False, samples only from bottom edge. If not set (defaults to None), samples from both edges.
3.074697
2.974967
1.033523
z = random.uniform(-1, 1) * self.height / 2. sampledAngle = 2 * random.random() * pi x, y = self.radius * cos(sampledAngle), self.radius * sin(sampledAngle) return [x, y, z]
def _sampleLocationOnSide(self)
Helper method to sample from the lateral surface of a cylinder.
4.051314
3.705371
1.093363
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # generate cylinder x = np.linspace(- self.radius, self.radius, numPoints) z = np.linspace(- self.height / 2., self.height / 2., numPoints) Xc, Zc = np.meshgrid(x, z) Yc = np.sqrt(self.radius ** 2 - Xc ** 2) # plot ...
def plot(self, numPoints=100)
Specific plotting method for cylinders.
1.965984
1.861292
1.056247
if not self.contains(location): return self.EMPTY_FEATURE # random feature numFaces = sum( [self.almostEqual(abs(coord), self.dimensions[i] / 2.) \ for i, coord in enumerate(location)] ) if numFaces == 1: return self.FLAT if numFaces == 2: return self.EDGE ...
def getFeatureID(self, location)
There are three possible features for a box: - flat for a face - pointy for a vertex - edge
5.763367
4.547961
1.267242
for i, coord in enumerate(location): if self.almostEqual(abs(coord), self.dimensions[i] / 2.): return True return False
def contains(self, location)
A location is on the box if one of the dimension is "satured").
6.208514
5.531837
1.122324
if feature == "face": return self._sampleFromFaces() elif feature == "edge": return self._sampleFromEdges() elif feature == "vertex": return self._sampleFromVertices() elif feature == "random": return self.sampleLocation() else: raise NameError("No such feature in ...
def sampleLocationFromFeature(self, feature)
Samples a location from one specific feature. This is only supported with three dimensions.
3.29862
3.225763
1.022586