input
stringlengths
2.65k
237k
output
stringclasses
1 value
method for S3AddPersonWidget2 """ site_id = r.id if not site_id: output = current.xml.json_message(False, 400, "No id provided!") raise HTTP(400, body=output) db = current.db s3db = current.s3db ltable = s3db.hrm_human_resource_site htable = db.hrm_human_resource query = (ltable.site_id == site_id) & \ (ltable.site_contact == True) & \ (ltable.human_resource_id == htable.id) person = db(query).select(htable.person_id, limitby=(0, 1)).first() if person: fake = Storage(id = person.person_id, tablename = "org_site", ) return s3db.pr_person_lookup(fake, **attr) else: current.response.headers["Content-Type"] = "application/json" output = json.dumps(None, separators=SEPARATORS) return output # ------------------------------------------------------------------------- @staticmethod def site_search_ac(r, **attr): """ JSON search method for S3SiteAutocompleteWidget @param r: the S3Request @param attr: request attributes """ response = current.response resource = r.resource settings = current.deployment_settings # Query comes in pre-filtered to accessible & deletion_status # Respect response.s3.filter resource.add_filter(response.s3.filter) _vars = current.request.get_vars # JQueryUI Autocomplete uses "term" instead of "value" # (old JQuery Autocomplete uses "q" instead of "value") value = _vars.term or _vars.value or _vars.q or None # We want to do case-insensitive searches # (default anyway on MySQL/SQLite, but not PostgreSQL) value = s3_unicode(value).lower().strip() if not value: output = current.xml.json_message(False, 400, "Missing option! Require value") raise HTTP(400, body=output) # Construct query query = (FS("name").lower().like(value + "%")) # Add template specific search criteria extra_fields = settings.get_org_site_autocomplete_fields() for field in extra_fields: if "addr_street" in field: # Need to be able to get through the street number query |= (FS(field).lower().like("%" + value + "%")) else: query |= (FS(field).lower().like(value + "%")) resource.add_filter(query) MAX_SEARCH_RESULTS = settings.get_search_max_results() limit = int(_vars.limit or MAX_SEARCH_RESULTS) if (not limit or limit > MAX_SEARCH_RESULTS) and resource.count() > MAX_SEARCH_RESULTS: output = [ dict(label=str(current.T("There are more than %(max)s results, please input more characters.") % \ dict(max=MAX_SEARCH_RESULTS))) ] else: from s3.s3widgets import set_match_strings s3db = current.s3db # default fields to return fields = ["name", "site_id", ] # Add template specific fields to return fields += extra_fields rows = resource.select(fields, start=0, limit=limit, orderby="name", as_rows=True) output = [] append = output.append for row in rows: # Populate record _row = row.get("org_site", row) record = {"id": _row.site_id, "name": _row.name, } # Populate fields only if present org = row.get("org_organisation.name", None) if org: record["org"] = org L1 = row.get("gis_location.L1", None) if L1: record["L1"] = L1 L2 = row.get("gis_location.L2", None) if L2: record["L2"] = L2 L3 = row.get("gis_location.L3", None) if L3: record["L3"] = L3 L4 = row.get("gis_location.L4", None) if L4: record["L4"] = L4 addr_street = row.get("gis_location.addr_street", None) if addr_street: record["addr"] = addr_street # Populate match information (if applicable) set_match_strings(record, value) append(record) response.headers["Content-Type"] = "application/json" return json.dumps(output, separators=SEPARATORS) # ============================================================================= class S3SiteDetailsModel(S3Model): """ Extra optional details for Sites """ names = ("org_site_status", "org_site_org_group", ) def model(self): T = current.T define_table = self.define_table super_link = self.super_link settings = current.deployment_settings last_contacted = settings.get_org_site_last_contacted() messages = current.messages NONE = messages["NONE"] UNKNOWN_OPT = messages.UNKNOWN_OPT facility_status_opts = { 1: T("Normal"), 2: T("Compromised"), 3: T("Evacuating"), 4: T("Closed"), 99: T("No Response"), } power_supply_type_opts = { 1: T("Grid"), 2: T("Generator"), 98: T("Other"), 99: T("None"), } # --------------------------------------------------------------------- # Site Status # tablename = "org_site_status" define_table(tablename, # Component not instance super_link("site_id", "org_site"), Field("facility_status", "integer", requires = IS_EMPTY_OR( IS_IN_SET(facility_status_opts)), label = T("Facility Status"), represent = lambda opt: \ NONE if opt is None else \ facility_status_opts.get(opt, UNKNOWN_OPT)), s3_date("date_reopening", label = T("Estimated Reopening Date"), readable = False, writable = False, ), Field("power_supply_type", "integer", label = T("Power Supply Type"), requires = IS_EMPTY_OR( IS_IN_SET(power_supply_type_opts, zero=None)), represent = lambda opt: \ NONE if opt is None else \ power_supply_type_opts.get(opt, UNKNOWN_OPT)), s3_date("last_contacted", label = T("Last Contacted"), readable = last_contacted, writable = last_contacted, ), *s3_meta_fields()) # CRUD Strings site_label = settings.get_org_site_label() current.response.s3.crud_strings[tablename] = Storage( label_create = T("Add %(site_label)s Status") % dict(site_label=site_label), title_display = T("%(site_label)s Status") % dict(site_label=site_label), title_list = T("%(site_label)s Status") % dict(site_label=site_label), title_update = T("Edit %(site_label)s Status") % dict(site_label=site_label), label_list_button = T("List %(site_label)s Status") % dict(site_label=site_label), msg_record_created = T("%(site_label)s Status added") % dict(site_label=site_label), msg_record_modified = T("%(site_label)s Status updated") % dict(site_label=site_label), msg_record_deleted = T("%(site_label)s Status deleted") % dict(site_label=site_label), msg_list_empty = T("There is no status for this %(site_label)s yet. Add %(site_label)s Status.") % dict(site_label=site_label), ) # --------------------------------------------------------------------- # Sites <> Coalitions link table # tablename = "org_site_org_group" define_table(tablename, # Component not instance super_link("site_id", "org_site"), self.org_group_id(empty = False, ondelete = "CASCADE", ), *s3_meta_fields()) # Pass names back to global scope (s3.*) return {} # ============================================================================= class S3SiteNameModel(S3Model): """ Site Names model - local names/acronyms for Sites/Facilities """ names = ("org_site_name", ) def model(self): T = current.T LANGUAGE_CODE = IS_ISO639_2_LANGUAGE_CODE # --------------------------------------------------------------------- # Local Names # tablename = "org_site_name" self.define_table(tablename, # Component not instance self.super_link("site_id", "org_site"), Field("language", label = T("Language"), represent = LANGUAGE_CODE.represent, requires = LANGUAGE_CODE(), ), Field("name_l10n", label = T("Local Name"), ), s3_comments(), *s3_meta_fields()) self.configure(tablename, deduplicate = S3Duplicate(primary = ("language", "site_id", ), ), ) # Pass names back to global scope (s3.*) return {} # ============================================================================= class S3SiteTagModel(S3Model): """ Site Tags """ names = ("org_site_tag",) def model(self): T = current.T # --------------------------------------------------------------------- # Site Tags # - Key-Value extensions # - can be used to provide conversions to external systems, such as: # * HXL # - can be a Triple Store for Semantic Web support # tablename = "org_site_tag" self.define_table(tablename, # Component not instance self.super_link("site_id", "org_site"), # key is a reserved word in MySQL Field("tag", label = T("Key"), ), Field("value", label = T("Value"), ), s3_comments(), *s3_meta_fields()) self.configure(tablename, deduplicate = S3Duplicate(primary=("site_id", "tag", ), ), ) # Pass names back to global scope (s3.*) return {} # ============================================================================= class S3SiteLocationModel(S3Model): """ Site Location Model - Locations served by a Site/Facility """ names = ("org_site_location",) def model(self): T = current.T auth = current.auth # --------------------------------------------------------------------- # Sites <> Locations Link Table # tablename = "org_site_location" self.define_table(tablename, # Component not instance self.super_link("site_id", "org_site", label = current.deployment_settings.get_org_site_label(), instance_types = auth.org_site_types, orderby = "org_site.name", realms = auth.permission.permitted_realms("org_site", method="create"), not_filterby = "obsolete", not_filter_opts = (True,), readable = True, writable = True, represent = self.org_site_represent, ), self.gis_location_id( #represent = self.gis_LocationRepresent(sep=", "), represent = S3Represent(lookup="gis_location"), requires = IS_LOCATION(), widget = S3LocationAutocompleteWidget() ), *s3_meta_fields() ) # CRUD Strings site_label = current.deployment_settings.get_org_site_label() current.response.s3.crud_strings[tablename] = Storage( label_create = T("New Location"), title_display = T("Location"), title_list = T("Locations"), title_update = T("Edit Location"), title_upload = T("Import Location data"), label_list_button = T("List Locations"), msg_record_created = T("Location added to %(site_label)s") % dict(site_label=site_label), msg_record_modified = T("Location updated"), msg_record_deleted = T("Location removed from %(site_label)s") % dict(site_label=site_label), msg_list_empty = T("No Locations found for this %(site_label)s") % dict(site_label=site_label)) self.configure(tablename, deduplicate = S3Duplicate(primary = ("site_id", "location_id", ), ), ) # Pass names back to global scope (s3.*) return {} # ============================================================================= class S3FacilityModel(S3Model): """ Generic Site """ names = ("org_facility_type", "org_facility", "org_site_facility_type", "org_facility_type_id", # Passed to global for s3translate "org_facility_geojson", ) def model(self): T = current.T db = current.db s3 = current.response.s3 settings = current.deployment_settings configure = self.configure crud_strings = s3.crud_strings define_table = self.define_table super_link = self.super_link NONE = current.messages["NONE"] hierarchical_facility_types = settings.get_org_facility_types_hierarchical() # --------------------------------------------------------------------- # Facility Types (generic) # tablename = "org_facility_type" define_table(tablename, Field("name", label = T("Name"), requires = IS_NOT_EMPTY(), ), Field("parent", "reference org_facility_type", # This form of hierarchy may not work on all Databases label = T("SubType of"), ondelete = "RESTRICT", readable = hierarchical_facility_types, writable = hierarchical_facility_types, ), s3_comments(), *s3_meta_fields() ) type_represent = S3Represent(lookup = tablename, # Questionable UX: #hierarchy = hierarchical_facility_types, translate = True, ) if hierarchical_facility_types: hierarchy = "parent" # Can't be defined in-line as otherwise get a circular reference table = db[tablename] table.parent.represent = type_represent table.parent.requires = IS_EMPTY_OR( IS_ONE_OF(db, "org_facility_type.id", type_represent, # If limiting to just 1 level of parent #filterby="parent", #filter_opts=(None,), orderby="org_facility_type.name")) list_fields = [(T("Type"), "parent"), #(T("SubType"), "name"), "name", "comments", ] else: hierarchy = None list_fields = ["name", "comments", ] # CRUD strings # @ToDo: Flexible Labelling: 'Facility, 'Place', 'Site' ADD_FAC = T("Create Facility Type") crud_strings[tablename] = Storage( label_create = ADD_FAC, title_display = T("Facility Type Details"), title_list = T("Facility Types"), title_update = T("Edit Facility Type"), title_upload = T("Import Facility Types"), label_list_button = T("List Facility Types"), label_delete_button = T("Delete Facility Type"), msg_record_created = T("Facility Type added"), msg_record_modified = T("Facility Type updated"), msg_record_deleted = T("Facility Type deleted"), msg_list_empty = T("No Facility Types currently registered")) facility_type_id = S3ReusableField("facility_type_id", "reference %s" % tablename, label =
is completed. Useful for nested loops. """ if text_prompts not in [[], None] and not isinstance(text_prompts, str): raise ValueError('text_prompts must be a string') if image_prompts not in [[], None] and not isinstance(image_prompts, str): raise ValueError('image_prompts must be a string') if noise_prompts not in [[], None] and not isinstance(noise_prompts, str): raise ValueError('noise_prompts must be a string') if text_prompts in [[], None] and image_prompts in [[], None] and noise_prompts in [[], None]: raise ValueError('No valid prompts were provided') if not isinstance(video_frames,list) or not os.path.isfile(f'{video_frames[0]}'): raise ValueError(f'video_frames must be a list of paths to files.') eng_config.init_weight = current_source_frame_image_weight # by default, run the first frame for the same number of iterations as the rest of the frames. It can be useful to use more though. if not iterations_for_first_frame: iterations_for_first_frame = iterations_per_frame output_size_X, output_size_Y = VF.filesize_matching_aspect_ratio(video_frames[0], eng_config.output_image_size[0], eng_config.output_image_size[1]) eng_config.output_image_size = [output_size_X, output_size_Y] # Let's generate a single image to initialize the video. Otherwise it takes a few frames for the new video to stabilize on the generated imagery. init_image = 'init_image.jpg' eng_config_init_img = eng_config #eng_config_init_img.init_image_method = 'mse' image(output_filename=init_image, eng_config=eng_config_init_img, text_prompts=text_prompts, image_prompts = image_prompts, noise_prompts = noise_prompts, init_image = video_frames[0], init_weight=current_source_frame_image_weight, iterations = iterations_for_first_frame, save_every = None, verbose = False, leave_progress_bar = False) parsed_text_prompts, parsed_image_prompts, parsed_noise_prompts = VF.parse_all_prompts(text_prompts, image_prompts, noise_prompts) # lock in a seed to use for each frame if not eng_config.seed: # note, retreiving torch.seed() also sets the torch seed eng_config.seed = torch.seed() # if the location for the generated video frames doesn't exist, create it if not os.path.exists(generated_video_frames_path): os.mkdir(generated_video_frames_path) else: VF.delete_files(generated_video_frames_path) output_size_X, output_size_Y = VF.filesize_matching_aspect_ratio(video_frames[0], eng_config.output_image_size[0], eng_config.output_image_size[1]) eng_config.output_image_size = [output_size_X, output_size_Y] # alternate_img_target is required for restyling video. alternate_img_target_decay is experimental. #if eng_config.init_image_method not in ['alternate_img_target_decay', 'alternate_img_target']: # eng_config.init_image_method = 'alternate_img_target' # suppress stdout to keep the progress bar clear with open(os.devnull, 'w') as devnull: with contextlib.redirect_stdout(devnull): eng = Engine(eng_config) eng.initialize_VQGAN_CLIP() eng.alternate_image = True if z_smoother: # Populate the z smoother with the initial image init_image_pil = Image.open(init_image).convert('RGB').resize([output_size_X,output_size_Y], resample=Image.LANCZOS) # init_img_z = eng.pil_image_to_latent_vector(init_image_pil) smoothed_z = Z_Smoother(buffer_len=z_smoother_buffer_len, alpha=z_smoother_alpha) # generate images video_frame_num = 1 current_prompt_number = 0 try: # To generate the first frame of video, either use the init_image argument, or the first frame of source video. pil_image_previous_generated_frame = Image.open(init_image).convert('RGB').resize([output_size_X,output_size_Y], resample=Image.LANCZOS) eng.convert_image_to_init_image(pil_image_previous_generated_frame) eng.configure_optimizer() video_frames_loop = tqdm(video_frames,unit='image',desc='style transfer',leave=leave_progress_bar) for video_frame in video_frames_loop: filename_to_save = os.path.basename(os.path.splitext(video_frame)[0]) + '.' + output_extension filepath_to_save = os.path.join(generated_video_frames_path,filename_to_save) # INIT IMAGE # Alternate aglorithm - init image is unchanged from the previous output. We are not resetting the tensor gradient. # alternate_image_target is the new source frame of video. Apply a loss in Engine using conf.init_image_method == 'alternate_img_target' # The previous output will be trained to change toward the new source frame. pil_image_new_frame = Image.open(video_frame).convert('RGB').resize([output_size_X,output_size_Y], resample=Image.LANCZOS) eng.set_alternate_image_target(pil_image_new_frame) # Optionally use the current source video frame, and the previous generate frames, as input prompts eng.clear_all_prompts() if change_prompts_on_frame is not None: if video_frame_num in change_prompts_on_frame: # change prompts if the current frame number is in the list of change frames current_prompt_number += 1 eng.encode_and_append_prompts(current_prompt_number, parsed_text_prompts, parsed_image_prompts, parsed_noise_prompts) if current_source_frame_prompt_weight: eng.encode_and_append_pil_image(pil_image_new_frame, weight=current_source_frame_prompt_weight) # Generate a new image for iteration_num in tqdm(range(1,iterations_per_frame+1),unit='iteration',desc='generating frame',leave=False): #perform iterations of train() lossAll = eng.train(iteration_num) if verbose: # display some statistics about how the GAN training is going whever we save an image losses_str = ', '.join(f'{loss.item():7.3f}' for loss in lossAll) tqdm.write(f'iteration:{iteration_num:6d}\tvideo frame: {video_frame_num:6d}\tloss sum: {sum(lossAll).item():7.3f}\tloss for each prompt:{losses_str}') # save a frame of video # metadata to save to PNG file as data chunks img_info = [('text_prompts',text_prompts), ('image_prompts',image_prompts), ('noise_prompts',noise_prompts), ('iterations_per_frame',iterations_per_frame), ('iterations_for_first_frame',iterations_for_first_frame), ('cut_method',eng_config.cut_method), ('init_image',video_frame), ('seed',eng.conf.seed), ('z_smoother',z_smoother), ('z_smoother_buffer_len',z_smoother_buffer_len), ('z_smoother_alpha',z_smoother_alpha), ('current_source_frame_prompt_weight',f'{current_source_frame_prompt_weight:2.2f}'), ('current_source_frame_image_weight',f'{",".join(str(current_source_frame_image_weight))}')] if z_smoother: smoothed_z.append(eng._z.clone()) output_tensor = eng.synth(smoothed_z._mid_ewma()) Engine.save_tensor_as_image(output_tensor,filepath_to_save,img_info) else: eng.save_current_output(filepath_to_save,img_info) last_video_frame_generated = filepath_to_save video_frame_num += 1 except KeyboardInterrupt: pass config_info=f'iterations_per_frame: {iterations_per_frame}, '\ f'image_prompts: {image_prompts}, '\ f'noise_prompts: {noise_prompts}, '\ f'init_weight_method: {",".join(eng_config.init_image_method)}, '\ f'init_weight {",".join(str(eng_config.init_weight))}, '\ f'current_source_frame_prompt_weight {current_source_frame_prompt_weight:2.2f}, '\ f'current_source_frame_image_weight {",".join(str(current_source_frame_image_weight))}, '\ f'cut_method {eng_config.cut_method}, '\ f'z_smoother {z_smoother:2.2f}, '\ f'z_smoother_buffer_len {z_smoother_buffer_len:2.2f}, '\ f'z_smoother_alpha {z_smoother_alpha:2.2f}, '\ f'seed {eng.conf.seed}' return config_info def style_transfer_per_frame(video_frames, eng_config=VQGAN_CLIP_Config(), text_prompts = 'Covered in spiders | Surreal:0.5', image_prompts = [], noise_prompts = [], iterations_per_frame = 15, current_source_frame_image_weight = 2.0, generated_video_frames_path='./video_frames', current_source_frame_prompt_weight=0.0, verbose=False, leave_progress_bar = True, output_extension='jpg'): """Apply a style to existing video frames using VQGAN+CLIP. Set values of iteration_per_frame to determine how much the style transfer effect will be. Set values of source_frame_weight to determine how closely the result will match the source image. Balance iteration_per_frame and source_frame_weight to influence output. Set z_smoother to True to apply some latent-vector-based motion smoothing that will increase frame-to-frame consistency further at the cost of adding some motion blur. Set current_source_frame_prompt_weight >0 to have the generated content CLIP-match the source image. Args: * video_frames (list of str) : List of paths to the video frames that will be restyled. * eng_config (VQGAN_CLIP_Config, optional): An instance of VQGAN_CLIP_Config with attributes customized for your use. See the documentation for VQGAN_CLIP_Config(). * text_prompts (str, optional) : Text that will be turned into a prompt via CLIP. Default = [] * image_prompts (str, optional) : Path to image that will be turned into a prompt via CLIP. Default = [] * noise_prompts (str, optional) : Random number seeds can be used as prompts using the same format as a text prompt. E.g. \'123:0.1|234:0.2|345:0.3\' Stories (^) are supported. Default = [] * change_prompts_on_frame (list(int)) : All prompts (separated by "^" will be cycled forward on the video frames provided here. Defaults to None. * iterations_per_frame (int, optional) : Number of iterations of train() to perform for each frame of video. Default = 15 * iterations_for_first_frame (int, optional) : Number of additional iterations of train() to perform on the first frame so that the image is not a gray/random field. Default = 30 * generated_video_frames_path (str, optional) : Path where still images should be saved as they are generated before being combined into a video. Defaults to './video_frames'. * current_source_frame_image_weight (float) : Assigns a loss weight to make the output image look like the source image itself. Default = 0.0 * current_source_frame_prompt_weight (float) : Assigns a loss weight to make the output image look like the CLIP representation of the source image. Default = 0.0 * z_smoother (boolean, optional) : If true, smooth the latent vectors (z) used for image generation by combining multiple z vectors through an exponentially weighted moving average (EWMA). Defaults to False. * z_smoother_buffer_len (int, optional) : How many images' latent vectors should be combined in the smoothing algorithm. Bigger numbers will be smoother, and have more blurred motion. Must be an odd number. Defaults to 3. * z_smoother_alpha (float, optional) : When combining multiple latent vectors for smoothing, this sets how important the "keyframe" z is. As frames move further from the keyframe, their weight drops by (1-z_smoother_alpha) each frame. Bigger numbers apply more smoothing. Defaults to 0.6. * leave_progress_bar (boolean, optional) : When False, the tqdm progress bar will disappear when the work is completed. Useful for nested loops. """ if text_prompts not in [[], None] and not isinstance(text_prompts, str): raise ValueError('text_prompts must be a string') if image_prompts not in [[], None] and not isinstance(image_prompts, str): raise ValueError('image_prompts must be a string') if noise_prompts not in [[], None] and not isinstance(noise_prompts, str): raise ValueError('noise_prompts must be a string') if text_prompts in [[], None] and image_prompts in [[], None] and noise_prompts in [[], None]: raise ValueError('No valid prompts were provided') if not isinstance(video_frames,list) or not os.path.isfile(f'{video_frames[0]}'): raise ValueError(f'video_frames must be a list of paths to files.') eng_config.init_weight = current_source_frame_image_weight output_size_X, output_size_Y = VF.filesize_matching_aspect_ratio(video_frames[0], eng_config.output_image_size[0], eng_config.output_image_size[1]) eng_config.output_image_size = [output_size_X, output_size_Y] # lock in a seed to use for each frame if not eng_config.seed: # note, retreiving torch.seed() also sets the torch seed eng_config.seed = torch.seed() # if the location for the generated video frames doesn't exist, create it if not os.path.exists(generated_video_frames_path): os.mkdir(generated_video_frames_path) else: VF.delete_files(generated_video_frames_path) output_size_X, output_size_Y = VF.filesize_matching_aspect_ratio(video_frames[0], eng_config.output_image_size[0], eng_config.output_image_size[1]) eng_config.output_image_size = [output_size_X, output_size_Y] # suppress stdout to keep the progress bar clear
842], ["Ruyi", "如意", "pleasant", 838], ["Shusong", "疏松", "loose", 837], ["Fanchang", "反常", "unusual", 837], ["Zhenqie", "真切", "clear", 836], ["Keke", "苛刻", "harsh", 833], ["Kuangre", "狂热", "frantic", 829], ["Paiwai", "排外", "antiforeign", 828], ["Chimi", "痴迷", "infatuated", 827], ["Xiaozhang", "嚣张", "rampant", 824], ["Yongdu", "拥堵", "crowd", 823], ["Zaoshu", "早熟", "precocious", 822], ["Youya", "优雅", "graceful", 819], ["Diwa", "低洼", "low-lying", 816], ["Chidao", "迟到", "late", 810], ["Danxiang", "单向", "unidirectional", 808], ["Nianmai", "年迈", "old", 806], ["Kexin", "可信", "credible", 806], ["Guoqi", "过期", "expired", 805], ["Junyun", "均匀", "even", 804], ["Qipai", "气派", "lordly", 802], ["Haoke", "好客", "hospitable", 802], ["Changyou", "常有", "common", 798], ["Xinbian", "新编", "newly-organized", 797], ["Zhuanglie", "壮烈", "heroical", 796], ["Xiangyang", "象样", "nice", 795], ["Neixiang", "内向", "introverted", 795], ["Jili", "吉利", "auspicious", 793], ["Qingbai", "清白", "pure", 792], ["Xingsheng", "兴盛", "prosperous", 790], ["Qinei", "气馁", "discouraged", 789], ["Rechen", "热忱", "zealous", 787], ["Sumu", "肃穆", "solemn and respectful", 783], ["Lingmin", "灵敏", "keen", 781], ["Pingban", "平板", "dull", 779], ["Canren", "残忍", "cruel", 778], ["Qiangyan", "抢眼", "outstanding", 778], ["Duicheng", "对称", "symmetrical", 778], ["Weimiao", "微妙", "subtle", 777], ["Juewang", "绝望", "desperate", 776], ["Chenmen", "沉闷", "sad", 776], ["Chaoqun", "超群", "outstanding", 775], ["Shimao", "时髦", "fashionable", 775], ["Lengdan", "冷淡", "desolate", 775], ["Yiran", "易燃", "flammable", 774], ["Gaoming", "高明", "wise", 770], ["Baorong", "包容", "inclusive", 770], ["Chihuan", "迟缓", "slow", 768], ["Xiane", "险恶", "dangerous", 765], ["Huali", "华丽", "magnificent", 765], ["Yaohai", "要害", "critical", 764], ["Xinqi", "新奇", "novel", 763], ["Feiwo", "肥沃", "fertile", 762], ["Youyu", "犹豫", "hesitant", 762], ["Gaonan", "高难", "highly difficult", 761], ["Minjie", "敏捷", "agile", 753], ["Lingli", "凌厉", "swift and fierce", 753], ["Dianbo", "颠簸", "bumpy", 752], ["Jiang", "激昂", "spirited", 752], ["Kuanyu", "宽馀", "ample", 752], ["Dakuai", "大块", "bulk", 748], ["Jianrong", "兼容", "compatible", 748], ["Qiangshou", "抢手", "marketable", 747], ["Yumei", "愚昧", "ignorant", 746], ["Dilie", "低劣", "inferior", 746], ["Jusang", "沮丧", "depressed", 745], ["Rongyao", "荣耀", "glorious", 744], ["Chunjie", "纯洁", "chaste", 744], ["Pinji", "贫脊", "barren", 739], ["Rehuo", "热火", "friendly", 739], ["Cantong", "惨痛", "deeply grieved", 739], ["Xinchao", "新潮", "new", 734], ["Jiqie", "急切", "anxious", 733], ["Choumi", "稠密", "dense", 729], ["Qingche", "清澈", "limpid", 729], ["Wanqu", "弯曲", "curving", 729], ["Zhongdie", "重叠", "overlapped", 724], ["Qianxu", "谦虚", "modest", 724], ["Chouxiang", "抽象", "abstract", 724], ["Wangwo", "忘我", "absorbed", 724], ["Maomi", "茂密", "dense", 723], ["Zhuanzhu", "专注", "dedicated", 723], ["Beishang", "悲伤", "sad", 719], ["Posui", "破碎", "stave", 718], ["Xinke", "新科", "new", 717], ["Haodang", "浩荡", "enormous and powerful", 716], ["Mingmei", "明媚", "beautiful", 716], ["Ruanruo", "软弱", "weak", 715], ["Kunao", "苦恼", "worried", 714], ["Shoufu", "手扶", "hand-held", 713], ["Shiliang", "适量", "right amount of", 712], ["Guangtou", "光头", "bald", 712], ["Dingsheng", "鼎盛", "prosperous", 710], ["Shunshou", "顺手", "convenient", 710], ["Pinfa", "贫乏", "deficient", 710], ["Fangzheng", "方正", "upright", 709], ["Jinsi", "近似", "approximate", 705], ["Xuruo", "虚弱", "weak", 703], ["Qinjian", "勤俭", "diligent and thrifty", 703], ["Yingming", "英明", "wise", 702], ["Qingdu", "轻度", "mild", 701], ["Qimiao", "奇妙", "marvelous", 700], ["Liangshuang", "凉爽", "cool", 697], ["Menre", "闷热", "sultry", 695], ["Xiangdeng", "相等", "equal", 695], ["Weifeng", "威风", "imposing", 693], ["Kuazhang", "夸张", "exaggerating", 693], ["Yingshou", "应收", "receivable", 690], ["Xuxin", "虚心", "modest", 688], ["Dudao", "独到", "original", 688], ["Qinglang", "晴朗", "sunny", 686], ["Taotao", "滔滔", "torrential", 671], ["Wudi", "无敌", "invincible", 671], ["Ganxin", "甘心", "willing", 670], ["Jianpu", "简朴", "simple", 669], ["Xiwei", "细微", "slight", 666], ["Qinjin", "亲近", "intimate", 665], ["Jingqiao", "精巧", "exquisite", 661], ["Guoren", "过人", "excellent", 660], ["Fangan", "反感", "repugnant", 659], ["Huangliang", "荒凉", "bleak", 657], ["Cangcu", "仓猝", "hasty", 656], ["Xianhong", "鲜红", "bright red", 655], ["Xianhe", "显赫", "prominent", 655], ["Tongling", "同龄", "same age", 654], ["Jiuyuan", "久远", "remote", 654], ["Jincou", "紧凑", "compact", 653], ["Angyang", "昂扬", "spirited", 653], ["Kekou", "可口", "delicious", 653], ["Kure", "酷热", "extremely hot", 652], ["Fansuo", "繁琐", "tedious", 652], ["Jingpi", "精辟", "penetrating", 651], ["Jianying", "坚硬", "hard", 651], ["Nongzhong", "浓重", "strong", 650], ["Binfen", "缤纷", "riotous", 648], ["Shuchang", "舒畅", "happy", 647], ["Houzhong", "厚重", "sincere", 647], ["Weibao", "微薄", "meager", 645], ["Biaozhi", "标致", "beautiful", 643], ["Liaoliang", "嘹亮", "resonant", 643], ["Culve", "粗略", "sketchy", 642], ["Chongdong", "冲动", "impulsive", 641], ["Lingsan", "零散", "scattered", 638], ["Jieshi", "结实", "solid", 638], ["Fengsheng", "丰盛", "sumptuous", 637], ["Tiansheng", "天生", "inborn", 636], ["Jinyao", "紧要", "critical", 635], ["Fulan", "腐烂", "rotten", 634], ["Jinqiao", "紧俏", "scarce", 633], ["Changsheng", "昌盛", "prosperous", 633], ["Weidu", "惟独", "only", 633], ["Tianzhen", "天真", "naive", 633], ["Yaojin", "要紧", "important", 630], ["Zhuanxin", "专心", "wholly-absorbed", 630], ["Andan", "暗淡", "gloomy", 629], ["Ningzhong", "凝重", "dignified", 629], ["Jinzhi", "金质", "gold", 627], ["Haoda", "浩大", "vast", 627], ["Beizhuang", "悲壮", "solemn and stirring", 624], ["Zhishang", "至上", "supreme", 622], ["Qiangzhuang", "强壮", "strong", 622], ["Diluo", "低落", "low", 621], ["Nashou", "拿手", "adept", 620], ["Huangmiu", "荒谬", "absurd", 619], ["Mingkuai", "明快", "sprightly", 613], ["Chaoren", "超人", "supreme", 612], ["Jieju", "拮据", "uptight", 612], ["Boda", "博大", "great", 612], ["Diji", "低级", "preliminary", 608], ["Mianmian", "绵绵", "continuous", 607], ["Xianzu", "险阻", "difficult", 603], ["Shizhong", "适中", "moderate", 603], ["Chaogao", "超高", "ultra-high", 601], ["Lianmian", "连绵", "continuous", 600], ["Youhou", "优厚", "favorable", 600], ["Kunku", "困苦", "poverty-stricken", 599], ["Exin", "恶心", "disgusting", 598], ["Huansan", "涣散", "lax", 597], ["Diai", "低矮", "low", 592], ["Huanxi", "欢喜", "delighted", 591], ["Dongting", "动听", "interesting to listen to", 589], ["Zhipu", "质朴", "plain", 588], ["Haochi", "好吃", "delicious", 587], ["Yanku", "严酷", "severe", 587], ["Haomai", "豪迈", "heroic", 586], ["Daojia", "到家", "proficient", 586], ["Judu", "剧毒", "violently poisonous", 584], ["Yongmeng", "勇猛", "fierce", 577], ["Haohan", "浩瀚", "vast", 569], ["Zijue", "自决", "self determined", 568], ["Jingshen", "精深", "profound", 568], ["Nonglie", "浓烈", "strong", 568], ["Xiuzhen", "袖珍", "pocket-sized", 564], ["Jianxian", "艰险", "hard and dangerous", 564], ["Zhinen", "稚嫩", "immature", 563], ["Zhongyi", "中意", "pleasing", 563], ["Beiai", "悲哀", "sorrowful", 562], ["Moda", "莫大", "greatest", 560], ["Xixi", "细细", "careful", 560], ["Cuguang", "粗犷", "rough", 555], ["Cukuang", "粗旷", "rough", 555], ["Jinlin", "紧邻", "neighbor", 554], ["Yinglang", "硬朗", "hale and hearty", 552], ["Yanran", "俨然", "solemn", 552], ["Jiongyi", "迥异", "different", 550], ["Zouhong", "走红", "popular", 550], ["Kongxian", "空闲", "idle", 547], ["Huaji", "滑稽", "funny", 547], ["Chili", "吃力", "strenuous", 545], ["Huangwu", "荒芜", "desolated", 544], ["Laoshi", "老实", "honest", 543], ["Chunpu", "淳朴", "simple and honorable", 542], ["Naihuo", "耐火", "fireproof", 541], ["Tuanji", "湍急", "rapid", 541], ["Gaosheng", "高盛", "excellent", 540], ["Xixiao", "细小", "tiny", 540], ["Lingqiao", "灵巧", "clever", 540], ["Tanran", "坦然", "confident", 540], ["Chunchun", "淳淳", "pure", 539], ["Jixiao", "极小", "minimum", 539], ["Yayi", "压抑", "depressing", 539], ["Feishi", "费时", "time-consuming", 536], ["Xiansan", "闲散", "at ease", 535], ["Qiqu", "崎岖", "rugged", 535], ["Fuzu", "富足", "abundant", 534], ["Fengliu", "风流", "loose", 533], ["Qiancheng", "虔诚", "reverent", 533], ["Zhengzong", "正宗", "authentic", 533], ["Kailang", "开朗", "open", 533], ["Zhenmi", "缜密", "meticulous", 532], ["Gouyong", "够用", "sufficient", 526], ["Bingcan", "病残", "sick and disabled", 524], ["Pinhan", "贫寒", "poor", 523], ["Luoxuan", "螺旋", "spiral", 523], ["Qingdan", "清淡", "light", 522], ["Bajian", "拔尖", "best", 522], ["Nuoda", "诺大", "big", 521], ["Weiqu", "委屈", "suffering", 521], ["Ruoda", "偌大", "big", 521], ["Xionghun", "雄浑", "vigorous", 519], ["Zuiyou", "最优", "optimal", 519], ["Douqiao", "陡峭", "steep", 518], ["Diwei", "低位", "low", 518], ["Qique", "奇缺", "scarce", 517], ["Shasha", "傻傻", "silly", 515], ["Dizhu", "砥柱", "unyielding", 513], ["Qingcui", "清脆", "clear", 513], ["Dandan", "淡淡", "light", 513], ["Polan", "破烂", "tattered", 512], ["Yibao", "易爆", "explosive", 512], ["Dingli", "鼎立", "$$$", 509], ["Kanyou", "堪忧", "worrying", 509], ["Danjiang", "单桨", "single oar", 509], ["Jijing", "寂静", "silent", 508], ["Youshan", "友善", "friendly", 508], ["Duoduo", "多多", "many", 507], ["Bingwei", "病危", "critically ill", 505], ["Fanza", "繁杂", "numerous and diverse", 504], ["Kuzao", "枯躁", "arid", 504], ["Benfang", "奔放", "bold", 503], ["Timian", "体面", "dignified", 502], ["Pofeng", "颇丰", "many", 500], ["Shuxin", "舒心", "enjoyable", 497], ["Hanhu", "含胡", "ambiguous", 497], ["Shenchen", "深沉", "deep", 496], ["Jundeng", "均等", "equal", 496], ["Nankan", "难看", "ugly", 494], ["Dengzhi", "等值", "equivalent", 494], ["Xianjun", "险峻", "precipitous", 491], ["Ruoxiao", "弱小", "small and weak", 491], ["Kekong", "可控", "controllable", 490], ["Juehao", "绝好", "excellent", 489], ["Yongzhong", "臃肿", "extremely fat", 488], ["Pinghuan", "平缓", "gentle", 488], ["Guohuo", "过火", "overdone", 487], ["Chonglang", "冲浪", "surf", 485], ["Chaosheng", "超声", "supersonic", 484], ["Tongkuai", "痛快", "happy", 484], ["Jujin", "拘谨", "cautious", 484], ["Huohong", "火红", "fiery red", 483], ["Zhizhang", "智障", "mental handicap", 483], ["Biren", "逼人", "threatening", 482], ["Feili", "费力", "strenuous", 482], ["Lian", "离岸", "offshore", 480], ["Rouruan", "柔软", "soft", 480], ["Piaoyi", "飘逸", "elegant", 478], ["Taotian", "滔天", "dreadful", 478], ["Youwei", "有为", "promising", 478], ["Shuoda", "硕大", "gigantic", 474], ["Qibei", "齐备", "prepared", 473], ["Huangtang", "荒唐", "absurd", 472], ["Xili", "犀利", "sharp", 471], ["Niming", "匿名", "anonymous", 471], ["Qinglian", "清廉", "incorruptible", 470], ["Mingle", "明了", "transparent", 468], ["Tiaoti", "挑剔", "nitpicking", 467], ["Jianren", "坚韧", "tenacious", 464], ["Zhuangmei", "壮美", "sublime", 463], ["Weinan", "为难", "awkward", 463], ["Nianlao", "年老", "old", 462], ["Rumen", "入门", "basic", 461], ["Guoji", "过激", "extreme", 460], ["Zhiqian", "值钱", "valuable", 460], ["Anxu", "按需", "on demand", 459], ["Haihao", "还好", "good", 457], ["Tianmi", "甜蜜", "happy", 457], ["Chire", "炽热", "blazing", 457], ["Maosheng", "茂盛", "luxuriant", 456], ["Weie", "巍峨", "palatial", 456], ["Qingliang", "清凉", "cool", 453], ["Zhangyang", "张扬",
<gh_stars>0 # coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long # pylint: disable=unused-import from knack.help_files import helps helps['servicebus'] = """ type: group short-summary: Manage Azure Service Bus namespaces, queues, topics, subscriptions, rules and geo-disaster recovery configuration alias """ helps['servicebus namespace'] = """ type: group short-summary: Manage Azure Service Bus Namespace """ helps['servicebus namespace authorization-rule'] = """ type: group short-summary: Manage Azure Service Bus Namespace Authorization Rule """ helps['servicebus namespace authorization-rule keys'] = """ type: group short-summary: Manage Azure Authorization Rule connection strings for Namespace """ helps['servicebus queue'] = """ type: group short-summary: Manage Azure Service Bus Queue and Authorization Rule """ helps['servicebus queue authorization-rule'] = """ type: group short-summary: Manage Azure Service Bus Queue Authorization Rule """ helps['servicebus queue authorization-rule keys'] = """ type: group short-summary: Manage Azure Authorization Rule keys for Service Bus Queue """ helps['servicebus topic'] = """ type: group short-summary: Manage Azure Service Bus Topic and Authorization Rule """ helps['servicebus topic authorization-rule'] = """ type: group short-summary: Manage Azure Service Bus Topic Authorization Rule """ helps['servicebus topic authorization-rule keys'] = """ type: group short-summary: Manage Azure Authorization Rule keys for Service Bus Topic """ helps['servicebus topic subscription'] = """ type: group short-summary: Manage Azure Service Bus Subscription """ helps['servicebus topic subscription rule'] = """ type: group short-summary: Manage Azure Service Bus Rule """ helps['servicebus georecovery-alias'] = """ type: group short-summary: Manage Azure Service Bus Geo-Disaster Recovery Configuration Alias """ helps['servicebus georecovery-alias authorization-rule'] = """ type: group short-summary: Manage Azure Service Bus Authorization Rule for Namespace with Geo-Disaster Recovery Configuration Alias """ helps['servicebus georecovery-alias authorization-rule keys'] = """ type: group short-summary: Manage Azure Authorization Rule keys for Service Bus Namespace """ helps['servicebus migration'] = """ type: group short-summary: Manage Azure Service Bus Migration of Standard to Premium """ helps['servicebus namespace exists'] = """ type: command short-summary: check for the availability of the given name for the Namespace examples: - name: check for the availability of mynamespace for the Namespace text: az servicebus namespace exists --name mynamespace """ helps['servicebus namespace create'] = """ type: command short-summary: Create a Service Bus Namespace examples: - name: Create a Service Bus Namespace. text: az servicebus namespace create --resource-group myresourcegroup --name mynamespace --location westus --tags tag1=value1 tag2=value2 --sku Standard """ helps['servicebus namespace update'] = """ type: command short-summary: Updates a Service Bus Namespace examples: - name: Updates a Service Bus Namespace. text: az servicebus namespace update --resource-group myresourcegroup --name mynamespace --tags tag=value """ helps['servicebus namespace show'] = """ type: command short-summary: Shows the Service Bus Namespace details examples: - name: shows the Namespace details. text: az servicebus namespace show --resource-group myresourcegroup --name mynamespace """ helps['servicebus namespace list'] = """ type: command short-summary: List the Service Bus Namespaces examples: - name: Get the Service Bus Namespaces by resource group text: az servicebus namespace list --resource-group myresourcegroup - name: Get the Service Bus Namespaces by Subscription. text: az servicebus namespace list """ helps['servicebus namespace delete'] = """ type: command short-summary: Deletes the Service Bus Namespace examples: - name: Deletes the Service Bus Namespace text: az servicebus namespace delete --resource-group myresourcegroup --name mynamespace """ helps['servicebus namespace authorization-rule create'] = """ type: command short-summary: Create Authorization Rule for the given Service Bus Namespace examples: - name: Create Authorization Rule 'myauthorule' for the given Service Bus Namespace 'mynamepsace' in resourcegroup text: az servicebus namespace authorization-rule create --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule --rights Send Listen """ helps['servicebus namespace authorization-rule update'] = """ type: command short-summary: Updates Authorization Rule for the given Service Bus Namespace examples: - name: Updates Authorization Rule 'myauthorule' for the given Service Bus Namespace 'mynamepsace' in resourcegroup text: az servicebus namespace authorization-rule update --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule --rights Send """ helps['servicebus namespace authorization-rule show'] = """ type: command short-summary: Shows the details of Service Bus Namespace Authorization Rule examples: - name: Shows the details of Service Bus Namespace Authorization Rule text: az servicebus namespace authorization-rule show --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule """ helps['servicebus namespace authorization-rule list'] = """ type: command short-summary: Shows the list of Authorization Rule by Service Bus Namespace examples: - name: Shows the list of Authorization Rule by Service Bus Namespace text: az servicebus namespace authorization-rule list --resource-group myresourcegroup --namespace-name mynamespace """ helps['servicebus namespace authorization-rule keys list'] = """ type: command short-summary: List the keys and connection strings of Authorization Rule for Service Bus Namespace examples: - name: List the keys and connection strings of Authorization Rule for Service Bus Namespace text: az servicebus namespace authorization-rule keys list --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule """ helps['servicebus namespace authorization-rule keys renew'] = """ type: command short-summary: Regenerate keys of Authorization Rule for the Service Bus Namespace. examples: - name: Regenerate keys of Authorization Rule for the Service Bus Namespace. text: az servicebus namespace authorization-rule keys renew --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule --key PrimaryKey """ helps['servicebus namespace authorization-rule delete'] = """ type: command short-summary: Deletes the Authorization Rule of the Service Bus Namespace. examples: - name: Deletes the Authorization Rule of the Service Bus Namespace. text: az servicebus namespace authorization-rule delete --resource-group myresourcegroup --namespace-name mynamespace --name myauthorule """ helps['servicebus queue create'] = """ type: command short-summary: Create the Service Bus Queue examples: - name: Create Service Bus Queue. text: az servicebus queue create --resource-group myresourcegroup --namespace-name mynamespace --name myqueue """ helps['servicebus queue update'] = """ type: command short-summary: Updates existing Service Bus Queue examples: - name: Updates Service Bus Queue. text: az servicebus queue update --resource-group myresourcegroup --namespace-name mynamespace --name myqueue --auto-delete-on-idle PT3M """ helps['servicebus queue show'] = """ type: command short-summary: shows the Service Bus Queue Details examples: - name: Shows the Service Bus Queue Details text: az servicebus queue show --resource-group myresourcegroup --namespace-name mynamespace --name myqueue """ helps['servicebus queue list'] = """ type: command short-summary: List the Queue by Service Bus Namepsace examples: - name: Get the Queues by Service Bus Namespace. text: az servicebus queue list --resource-group myresourcegroup --namespace-name mynamespace """ helps['servicebus queue delete'] = """ type: command short-summary: Deletes the Service Bus Queue examples: - name: Deletes the queue text: az servicebus queue delete --resource-group myresourcegroup --namespace-name mynamespace --name myqueue """ helps['servicebus queue authorization-rule create'] = """ type: command short-summary: Create Authorization Rule for the given Service Bus Queue. examples: - name: Create Authorization Rule for Queue text: az servicebus queue authorization-rule create --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule --rights Listen """ helps['servicebus queue authorization-rule update'] = """ type: command short-summary: Update Authorization Rule for the given Service Bus Queue. examples: - name: Update Authorization Rule for Queue text: az servicebus queue authorization-rule update --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule --rights Send """ helps['servicebus queue authorization-rule show'] = """ type: command short-summary: show properties of Authorization Rule for the given Service Bus Queue. examples: - name: show properties of Authorization Rule text: az servicebus queue authorization-rule show --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule """ helps['servicebus queue authorization-rule list'] = """ type: command short-summary: List of Authorization Rule by Service Bus Queue. examples: - name: List of Authorization Rule by Queue text: az servicebus queue authorization-rule list --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue """ helps['servicebus queue authorization-rule keys list'] = """ type: command short-summary: List the keys and connection strings of Authorization Rule for the given Service Bus Queue examples: - name: List the keys and connection strings of Authorization Rule for the given Service Bus Queue text: az servicebus queue authorization-rule keys list --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule """ helps['servicebus queue authorization-rule keys renew'] = """ type: command short-summary: Regenerate keys of Authorization Rule for Service Bus Queue examples: - name: Regenerate keys of Authorization Rule for Service Bus Queue text: az servicebus queue authorization-rule keys renew --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule --key PrimaryKey """ helps['servicebus queue authorization-rule delete'] = """ type: command short-summary: Delete the Authorization Rule of Service Bus Queue examples: - name: Delete the Authorization Rule of Service Bus Queue text: az servicebus queue authorization-rule delete --resource-group myresourcegroup --namespace-name mynamespace --queue-name myqueue --name myauthorule """ helps['servicebus topic create'] = """ type: command short-summary: Create the Service Bus Topic examples: - name: Create a new Service Bus Topic text: az
#!/usr/bin/env python3 import argparse import hashlib import io import logging import os import subprocess import sys DRY_RUN=True DEBUG_LEVEL=30 class FileSystemEntry: source = "" target = "" mtype = "" options = "" freq = "" passno = "" def __str__(self): return self.source + " " + self.target + " " + self.mtype + " " + self.options class Mount(object): def __init__(self, proc_mounts_file='/proc/mounts'): self.entries = self.load(proc_mounts_file) def read_file_into_array(self,filename): file = open(filename, 'r') array = file.readlines() file.close() return array def parse(self,array): entries = [] for line in array: cols = line.split() fse = FileSystemEntry() fse.source = cols[0] fse.target = cols[1] fse.mtype = cols[2] fse.options = cols[3] fse.freq = cols[4] fse.passno = cols[5] entries.append(fse) return entries def load(self, proc_mounts_file): array = self.read_file_into_array(proc_mounts_file) entries = self.parse(array) return entries # Filters all virtual filesystems out (they do not start with '/') def filter_by_path(self,entries): result = [] for o in self.entries: if o.source.startswith(os.sep): result.append(o) return result def longest_match(self, path, entries): max_len = 0 result = None for o in entries: l = len(o.target) if path.startswith(o.target) and l > max_len: result = o max_len = l return result def get_subvol(self, entry): options = entry.options.split(",") for option in options: if option.startswith("subvol="): return option[len("subvol="):] return None def find_root(self, source, entries): for o in entries: if o.source == source and self.get_subvol(o) == os.sep: return o return None def resolve(self, path, entries): entry = self.longest_match(path,entries) if entry is None: return path if entry.target == os.sep: return path subvol = self.get_subvol(entry) if subvol is None: return path if subvol != os.sep: postfix = path[len(entry.target):] _path = subvol + postfix if _path != entry.target: path = self.resolve(_path,entries) root = self.find_root(entry.source,entries) if root is None: return path if path == root.target or path.startswith(root.target + os.sep): return path return (root.target + path) def resolve_bind(self, path): result = self.filter_by_path(self.entries) result = self.resolve(path,result) return result class MountRecorder(Mount): def load(self, proc_mounts_file): array = self.read_file_into_array(proc_mounts_file) content = "".join(array) text_file = open("rec_mounts", "w") text_file.write(content) text_file.close() entries = self.parse(array) return entries class ShellCmd(object): def subprocess(self, args): proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc def read_stdout(self, stream): array=[] for line in stream: item=line.rstrip("\n") array.append(item) return array # The exit_code can be access from external then def execute(self, args): proc = self.subprocess(args) # Python2 vs Python3 if sys.version_info >= (3,0): input_stream = io.TextIOWrapper(proc.stdout, encoding='utf-8') else: input_stream = proc.stdout array = self.read_stdout(input_stream) exit_code = proc.wait() return ( exit_code, array ) class ShellCmdRecorder(ShellCmd): def execute(self, args): exit_code, array = super(ShellCmdRecorder,self).execute(args) cmdline = " ".join(args) filename_sha1 = hashlib.sha1(cmdline.encode("utf-8")).hexdigest() content = "\n".join(array) text_file = open("rec_"+filename_sha1, "w") text_file.write(cmdline + "\n") text_file.write(str(exit_code) + "\n") text_file.write(content + "\n") text_file.close() return (exit_code,array) class BTRFS(object): def __init__(self, shellCmd, mount): self.cmd = shellCmd self.mount = mount def show(self, btrfs_dir, verbose=False): args = ['btrfs','subvolume','show', btrfs_dir] logger.debug(" ".join(args)) return self.cmd.execute(args) def find_btrfs(self, btrfs_dir): while True: exit_code,array = self.show(btrfs_dir) if btrfs_dir == os.sep: break if exit_code != 1: break # Move one level up btrfs_dir = os.path.dirname(btrfs_dir) if exit_code != 0: return (None,None) if len(array) == 1: btrfs_name = "" else: btrfs_name = array[1].split()[1] return (btrfs_dir, btrfs_name) def subvolume_list_raw(self,btrfs_dir): args = ['btrfs','subvolume', 'list', '-o', btrfs_dir ] logger.debug(" ".join(args)) return self.cmd.execute(args) def subvolume_list_extract_dirs(self, array): result = [] for line in array: columns = line.split() last_column = len(columns) - 1 dir_path = columns[last_column] result.append(dir_path) return result def subvolume_list_filter(self,target_dir,btrfs_dir,btrfs_name, source2, array): array = self.subvolume_list_extract_dirs(array) if btrfs_name == "<FS_TREE>": filter1 = source2[1:] else: filter1 = btrfs_name + os.sep length = len(filter1) array2 = [] for item in array: # filter for the btrfs_name prefix name if item.startswith(filter1): item2 = item[length:] if btrfs_name == "<FS_TREE>": item3 = btrfs_dir + os.sep + filter1 + item2 else: item3 = btrfs_dir + item2 if target_dir == item3 or item3.startswith(target_dir + os.sep): array2.append(item3) return array2 def subvolume_list(self,btrfs_dir, btrfs_name, source2, target_dir): exit_code, array= self.subvolume_list_raw(btrfs_dir) if exit_code != 0: return [] subvolumes = self.subvolume_list_filter(target_dir,btrfs_dir,btrfs_name,source2,array) return subvolumes def delete(self,dirname): args = ['btrfs','subvolume', 'delete', dirname] logger.info(" ".join(args)) if DRY_RUN == True: return self.cmd.execute(args) logger.debug("delete finished") # FIXME return code? def findmnt(self): # findmnt # -c Canonicalize all printed paths # -n No Headings # -D Imitate the output of df args = ['findmnt','-c','-n','-D'] logger.debug(" ".join(args)) return self.cmd.execute(args) def parse_btrfs_mount(self,source): pos = source.find("[") if pos == -1: return [ source, '' ] pos_end = source.find("]", pos) if pos_end == -1: return [ source, '' ] source1 = source[0:pos] source2 = source[pos+1:pos_end] return [ source1, source2 ] def filter_findmnt_target(self,lines): result = [] for line in lines: columns = line.split() last_column = len(columns) - 1 source = columns[0] target = columns[last_column] # source can only be device path starting with a '/', everthing else is shm, tmpfs, etc. if not source.startswith(os.sep): continue source1,source2 = self.parse_btrfs_mount(source) result.append([source1,source2,target]) return result # In the end this method wants to match the closed "mountpoint" coming from a bottom up to the tree # So if the pathname is longer than any target mount points, we remove components of the dirname, to find # a final "exact" match. This means we have then a (partial) match of the dirname path, which goes to the # level where the mountpoint is # Test case 1: dirname is shorter --> match root '/' # Test case 2: dirname is longer --> match mount point which matches first when coming from bottom (longest path) # so there is someimes an exact match, somethings not def match_exact(self,name,lines): i = 0 for line in lines: source1,source2,target = line if target == name: return i i=i+1 return -1 def match_dirname(self,dirname,lines): components = dirname.split(os.sep) length = len(components) for i in reversed(range (0,length)): if i == 0: name = os.sep else: name = os.sep.join(components[0:i+1]) pos = self.match_exact(name,lines) if pos > -1: result = lines[pos] break # There has to be always a match, otherwise this dirname was no absolute path return result def find_longest_entry(self,source1,filtered_lines): result = "" for line in filtered_lines: _source1,_source2,_target = line if _source1 == source1 and _source2 == '': return _target return "" def find_match(self,dirname): exit_code, lines = self.findmnt() if not exit_code == 0: return [] filtered_lines = self.filter_findmnt_target(lines) result = self.match_dirname(dirname,filtered_lines) source1,source2,target = result return [ source1, source2, target, dirname ] def rm_recursive(self,dirname): args = [ 'rm', '-rf', dirname] logger.info(" ".join(args)) if DRY_RUN == True: return proc = subprocess.Popen(args,stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in proc.stdout: print(line.strip()) exit_code = proc.wait() def get_path(self): try: path_var = os.environ['PATH'] path_array = path_var.split(os.pathsep) return path_array except KeyError: return [] def find_program(self,name,path_array): for path in path_array: if not os.path.isdir(path): continue filepath = os.path.join(path,name) if os.path.isfile(filepath): return True return False def find_programs(self,required_programs,path_array): not_found_list = [] for name in required_programs: found = self.find_program(name,path_array) if not found: not_found_list.append(name) return not_found_list def self_check(self,required_programs,path_array): not_found_list = self.find_programs(required_programs,path_array) if len(not_found_list) > 0 : msg = "Necessary program not found in PATH: " + ",".join(not_found_list) logger.critical(msg) return False return True # Only Dirs as input (no files, no links etc.) def get_subvolumes(self, dirname): source1,source2,target,dirname = self.find_match(dirname) btrfs_dir, btrfs_name = self.find_btrfs(target) if btrfs_dir is None: return [] logger.debug("btrfs_dir: "+btrfs_dir) logger.debug("btrfs_name: "+btrfs_name) logger.debug("target: "+target) subvolumes = self.subvolume_list(btrfs_dir, btrfs_name, source2, dirname) logger.debug("Subdirs") logger.debug("\n".join(subvolumes)) return subvolumes # FIXME Only Dirs as input (no files, no links etc.) def process_dir(self, dirname): subvolumes = self.get_subvolumes(dirname) for subvolume in subvolumes: self.delete(subvolume) self.rm_recursive(dirname) def run(self,path_list): path_array = self.get_path() required_programs = [ 'rm', 'btrfs', 'findmnt' ] if not self.self_check(required_programs,path_array): exit(1) for path in path_list: if os.path.isdir(path): abspath = os.path.abspath(path) bind_path = self.mount.resolve_bind(abspath) self.process_dir(bind_path) else: self.rm_recursive(path) def save_cmdline(args): content = "\n".join(args) text_file = open("rec_cmdline", "w") text_file.write(content+"\n") text_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser("btrfs-rm") parser.add_argument('directories', metavar='directory', nargs='+', help='directory which contains btrfs snapshots ') parser.add_argument('-t', '--test', dest='dry_run', action='store_true', default=False, help='dry-run without actually deleting stuff') parser.add_argument('-d', '--debug', metavar='level', dest='debug_level', type=int, default=logging.WARN, help='set debug level') parser.add_argument('-r', '--record', dest='record', action='store_true', default=False, help='record shell cmd results for analysis') args = parser.parse_args() DEBUG_LEVEL=args.debug_level DRY_RUN=args.dry_run if DRY_RUN and DEBUG_LEVEL > 20: DEBUG_LEVEL=20 # after arg parse, so that somebody could at least use the -h option if os.geteuid() != 0: exit("You need to have root privileges to run this
from __future__ import print_function, division, absolute_import import subprocess import numpy as np import pandas as pd import hashlib import argparse import sys from classification import metadata import six remapping = { # 'seismic_vessel' : 'research' } def read_ids(gcs_path): id_text = subprocess.check_output(['gsutil', 'cat', gcs_path]) return set([six.ensure_text(x).strip() for x in id_text.strip().split()]) def fishing_range_vessel_id(fishdbname, dataset): return ''' ( select vessel_id, min(start_time) as first_timestamp, max(end_time) as last_timestamp, sum(is_fishing) = 0 as transit_only from `{fishdbname}` a join `{dataset}.segment_info` b on (a.mmsi = cast(ssvid as int64)) group by vessel_id ) '''.format(fishdbname=fishdbname, dataset=dataset) def fishing_range_mmsi(fishdbname, dataset): return ''' ( select cast(mmsi as string) as mmsi, min(start_time) as first_timestamp, max(end_time) as last_timestamp, sum(is_fishing) = 0 as transit_only from `{fishdbname}` group by mmsi ) '''.format(fishdbname=fishdbname, dataset=dataset) def read_vessel_database_for_char_vessel_id(dbname, dataset): query = ''' with core as ( select vessel_id as id, feature.length_m as length, feature.tonnage_gt as tonnage, feature.engine_power_kw as engine_power, feature.geartype as label, feature.crew as crew_size, array_to_string(feature.geartype, '|') as lbl, pos_count from (select * from {dbname} cross join unnest (activity)) a join `{dataset}.vessel_info` b on (a.identity.ssvid = b.ssvid) where (not ((a.last_timestamp is not null and a.last_timestamp < b.first_timestamp) or (a.first_timestamp is not null and a.first_timestamp > b.last_timestamp))) and (feature.length_m is not null or feature.tonnage_gt is not null or feature.engine_power_kw is not null or feature.geartype is not null --or feature.crew is not null ) ), counted as ( select * except(pos_count, label, lbl), lbl as label, sum(pos_count) as count from core group by id, length, tonnage, engine_power, label, crew_size ), ordered as ( select *, row_number() over (partition by id order by count desc, label, length, tonnage, engine_power, crew_size) as rk from counted ) select * except(rk, count) from ordered where rk = 1 '''.format(**locals()) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise def read_vessel_database_for_char_mmsi(dbname, dataset): query = ''' with multi_id as ( select identity.ssvid as id from {dbname} group by id having count(identity.ssvid) > 1 ) select identity.ssvid as id, feature.length_m as length, feature.tonnage_gt as tonnage, feature.engine_power_kw as engine_power, feature.crew as crew_size, array_to_string(feature.geartype, '|') as label from {dbname} a where (feature.length_m is not null or feature.tonnage_gt is not null or feature.engine_power_kw is not null or feature.crew is not null or (feature.geartype is not null and array_length(feature.geartype) > 0)) and identity.ssvid not in (select * from multi_id) order by id '''.format(**locals()) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise def read_vessel_database_for_detect_vessel_id(dbname, fishdbname, dataset): fishing_range_query=fishing_range_vessel_id(fishdbname, dataset) query = ''' with fishing_range_vessel_id as {fishing_range_query}, core as ( select vessel_id as id, feature.length_m as length, feature.tonnage_gt as tonnage, feature.engine_power_kw as engine_power, array_to_string(feature.geartype, '|') as label, feature.crew as crew_size, pos_count, transit_only from (select * from {dbname} cross join unnest (activity)) a join `{dataset}.segment_info` b on (cast(a.identity.ssvid as string) = ssvid) join `fishing_range_vessel_id` c using (vessel_id) where -- valid times overlap with segments (not ((a.last_timestamp is not null and a.last_timestamp < b.first_timestamp) or (a.first_timestamp is not null and a.first_timestamp > b.last_timestamp))) and -- valid times overlaps with fishing ranges (not ((a.last_timestamp is not null and a.last_timestamp < c.first_timestamp) or (a.first_timestamp is not null and a.first_timestamp > c.last_timestamp))) ), counted as ( select * except(pos_count, transit_only, length, tonnage, engine_power, label, crew_size), sum(pos_count) as count, min(transit_only) as transit_only, avg(length) as length, avg(tonnage) as tonnage, avg(engine_power) as engine_power, any_value(label) as label, avg(crew_size) as crew_size from core group by id ), ordered as ( select *, row_number() over (partition by id order by count desc, label, length, tonnage, engine_power, crew_size) as rk from counted ) select * except(rk, count) from ordered '''.format(**locals()) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise def read_vessel_database_for_detect_mmsi(dbname, fishdbname, dataset): fishing_range_query=fishing_range_mmsi(fishdbname, dataset) query = ''' with fishing_range_mmsi as {fishing_range_query}, core as ( select identity.ssvid as id, length_m as length, tonnage_gt as tonnage, engine_power_kw as engine_power, geartype as label, crew as crew_size, confidence, -- 1==low, 2==typical, 3==high (select sum(messages) from unnest(activity)) as pos_count, transit_only from {dbname} a cross join unnest (registry) join `fishing_range_mmsi` c on (cast(mmsi as string) = identity.ssvid) where -- valid times overlaps with fishing ranges -- TODO: should do each activity period separately here. (not (((select min(last_timestamp) from unnest(activity)) < c.first_timestamp) or ((select min(first_timestamp) from unnest(activity)) > c.last_timestamp))) ), counted as ( select * except(pos_count, confidence, transit_only, length, tonnage, engine_power, label, crew_size), sum(pos_count) as count, avg(confidence) as confidence, min(transit_only) as transit_only, avg(length) as length, avg(tonnage) as tonnage, avg(engine_power) as engine_power, any_value(label) as label, avg(crew_size) as crew_size from core group by id ), ordered as ( select *, row_number() over (partition by id order by count desc, label, length, tonnage, engine_power, crew_size, confidence) as rk from counted ) select * except(rk, count) from ordered '''.format(**locals()) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise def read_fishing_ranges_vessel_id(fishdbname, dataset): query = ''' with fishing_ranges as {fishing_ranges}, core as ( select mmsi as ssvid, vessel_id as id, start_time, end_time, is_fishing, pos_count from `{fishdbname}` a join `{dataset}.vessel_info` b on (a.mmsi = cast(ssvid as int64)) join `fishing_ranges` c using (vessel_id) where (not (b.last_timestamp < c.first_timestamp or b.first_timestamp > c.last_timestamp)) ), counted as ( select id, start_time, end_time, is_fishing, sum(pos_count) as count from core group by id, start_time, end_time, is_fishing ), ordered as ( select *, row_number() over (partition by id, start_time, end_time order by count desc) as rk from counted ) select * except(rk, count) from ordered where rk = 1 '''.format(fishdbname=fishdbname, dataset=dataset, fishing_ranges=fishing_range_vessel_id(fishdbname, dataset)) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise def read_fishing_ranges_mmsi(fishdbname, dataset): query = ''' with fishing_ranges as {fishing_ranges}, core as ( select c.mmsi as id, start_time, end_time, is_fishing from `{fishdbname}` a join `fishing_ranges` c on c.mmsi = cast(a.mmsi as string) ) select * from core '''.format(fishdbname=fishdbname, dataset=dataset, fishing_ranges=fishing_range_mmsi(fishdbname, dataset)) try: return pd.read_gbq(query, dialect='standard', project_id='world-fishing-827') except: print(query) raise category_map = {k: v for (k, v) in metadata.VESSEL_CATEGORIES} def disintegrate(label): parts = set() for sub in label.split('|'): for atomic in category_map[sub]: parts.add(atomic) return parts def apply_remapping(df, map): new_labels = [] for lbl in df.label: if lbl and lbl not in ["unknown", "fishing", "non_fishing"]: atoms = disintegrate(lbl) new_atoms = set([remapping.get(x, x) for x in atoms]) if new_atoms == atoms: # If no remapping occurred, keep old label as it's likely more compact. new_labels.append(lbl) else: new_labels.append('|'.join(sorted(new_atoms))) else: new_labels.append(lbl) df['label'] = new_labels def assign_split(df, max_examples, seed=888, check_fishing=False): rnd = np.random.RandomState(seed) if check_fishing: # If we are looking at fishing any vessel can be # be fishing, but stratify by all listed types labels = sorted(set(df.label)) else: # Otherwise, only allow atomic classes into test labels = metadata.VESSEL_CLASS_DETAILED_NAMES all_args = np.arange(len(df)) split = ['Training'] * len(df) if check_fishing: split_a, split_b = '0', '1' else: # Characterization doesn's support splits yet split_a, split_b = 'Test', 'Training' # Half for train half for test total_max_examples = 2 * max_examples for lbl in labels: lbl = six.ensure_text(lbl) base_mask = np.array([six.ensure_text(x) == lbl for x in df.label.values], dtype=bool) mask = base_mask.copy() if check_fishing: mask &= (df.transit_only.values == 0) elif mask.sum() > total_max_examples: trues = np.random.choice(np.nonzero(mask)[0], size=[total_max_examples], replace=False) mask.fill(False) mask[trues] = True for i in all_args[base_mask]: split[i] = None candidates = sorted(all_args[mask], key=lambda x: hashlib.sha256(six.ensure_binary(df.id.iloc[x])).hexdigest()) for i in candidates[:len(candidates)//2]: split[i] = split_a for i in candidates[len(candidates)//2:]: split[i] = split_b df['split'] = split if __name__ == '__main__': # assert sys.version_info[0] == 2, 'must generate with Python 2 until feature sharding is updated' parser = argparse.ArgumentParser('Create Training Info') parser.add_argument( '--vessel-database', required=True, help='The BQ table holding the vessel database') parser.add_argument( '--fishing-table', required=True, help='The BQ table holding fishing ranges') parser.add_argument( '--id-type', choices=['vessel-id', 'mmsi'], required=True ) parser.add_argument( '--id-list', help="GCS location of ids present in features" ) parser.add_argument( '--dataset', help="Name of the dataset to draw vessel_id mapping from" ) parser.add_argument( '--charinfo-file', ) parser.add_argument( '--detinfo-file', ) parser.add_argument( '--detranges-file', ) parser.add_argument( '--charinfo-table', ) parser.add_argument( '--detinfo-table', ) parser.add_argument( '--detranges-table', ) parser.add_argument(
<reponame>jabozzo/delta_sigma_pipe_lascas_2020<filename>calib/calib/gen.py #! /usr/bin/env python import abc import copy from itertools import islice import numpy as np import calib.gen as gen import calib.data as data from calib.misc import default, push_random_state def pipe_map(n_caps, n_refs, differential=False): """ Creates the code->reference map for pipeline operation. Each column in this map contains the reference index to be used for the feedfoward capacitors. :param n_caps: Number of feedfoward capacitors with references, usually the number of stage capacitors -1. :type n_caps: :class:`int` :param n_refs: Number of references per capacitor. :type n_refs: :class:`int` :param differential: Generate a differential or single-ended map. :type differential: :class:`bool` :returns: The map with shape :code:`(n_caps, n_codes, n_diff)` :rtype: :class:`numpy.ndarray` """ res = np.array([0]*n_caps + [1]*(n_caps-1), dtype=int) res = np.array(list(res[ii:ii+n_caps] for ii in range(n_caps))) res = res[::-1, :] res = (tuple(res + ii for ii in range(n_refs-1)) + (np.reshape([n_refs-1]*n_caps, (n_caps, 1,)),) ) res = np.concatenate(res, axis=1) if differential: res = np.stack((res, res[:, ::-1],), axis=2) else: res = np.reshape(res, np.shape(res) + (1,)) return res def adjust_map(map_, n_codes): """ Expands a pipeline map to work with an sub-ADC with the same or more codes than the original sub-ADC. :param map_: The pipeline map. :type map_: :class:`numpy.ndarray` :param n_codes: The number of codes the sub-ADC support. :type n_codes: :class:`int` :returns: The expanded pipeline map. :rtype: :class:`numpy.ndarray` :raises AssertionError: If the map is bigger than the target number of codes. .. seealso :: :func:`pipe_map` """ assert np.size(map_, 1) <= n_codes, "Map does not fit in number of codes" margin = n_codes - np.size(map_, 1) left = margin // 2 right = margin - left return np.concatenate((map_[:, 0:1, :],)*left + (map_,) + (map_[:,-1:, :],)*right, axis=1) def ds_map(n_caps, n_refs, n_codes, differential=False): """ Creates the code->reference map for delta-sigma operation. Each column in this map contains the reference index to be used for the feedfoward capacitors. :param n_caps: Number of feedfoward capacitors with references, usually. :type n_caps: :class:`int` :param n_refs: Number of references per capacitor. :type n_refs: :class:`int` :param n_codes: Number of codes from the loop sub-ADC. :type n_codes: :class:`int` :param differential: Generate a differential or single-ended map. :type differential: :class:`bool` :returns: The map with shape :code:`(n_caps, n_codes, n_diff)` :rtype: :class:`numpy.ndarray` """ p_map = pipe_map(n_caps, n_refs, differential) return adjust_map(p_map, n_codes) def parse_bits(n_bits, half_bit=None): """ Recieves either string, float or integer representations of a number of bits and returns the int + bool respresentation. :param n_bits: Number of bits :type n_bits: :class:`str`, :class:`float`, :class:`int` :param half_bit: If the representation is half bit or not. :type half_bit: :class:`bool` :returns: The int + bool representation of n_bits :rtype: (:class:`int`, :class:`bool`,) :raises ValueError: If the type of n_bits is not suported or n_bits and half_bit conflict with each other (eg: "2.5" and False) """ if isinstance(n_bits, str): try: n_bits = int(n_bits) except ValueError: n_bits = float(n_bits) if isinstance(n_bits, float): int_bits = int(n_bits) c_half_bit = n_bits != int_bits elif isinstance(n_bits, int): int_bits = n_bits c_half_bit = default(half_bit, False) half_bit = c_half_bit else: raise ValueError("n_bits cannot be of type {}".format(type(n_bits))) half_bit = default(half_bit, c_half_bit) if half_bit != c_half_bit: raise ValueError(("Inconsistent parameters " "(n_bits: {}, half_bit: {})").format(n_bits, half_bit)) return int_bits, half_bit def format_bits(n_bits, half_bit=None): """ Converts from int + bool representation to str representation :param n_bits: Number of bits :type n_bits: :class:`str`, :class:`float`, :class:`int` :param half_bit: If the representation is half bit or not. :type half_bit: :class:`bool` :returns: The str representation of n_bits :rtype: :class:`str` .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ n_bits, half_bit = parse_bits(n_bits, half_bit) return "{}.5".format(n_bits) if half_bit else n_bits def compute_n_codes(n_bits, half_bit=None): """ Computes the number of codes a pipeline stage can process. :param n_bits: Number of bits of the stage :type n_bits: :class:`str`, :class:`float`, :class:`int` :param half_bit: If the number of bits is half-bit or not :type half_bit: :class:`bool` :returns: The number of codes the pipeline stage can handle :rtype: :class:`int` .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ n_bits, half_bit = parse_bits(n_bits, half_bit) if half_bit: return 2**(n_bits + 1) - 1 else: return 2**n_bits def compute_n_caps(n_bits, n_refs, half_bit=None): """ Computes the number of capacitors a stage needs to achieve the desired resolution. :param n_bits: Number of bits of the stage :type n_bits: :class:`str`, :class:`float`, :class:`int` :param n_refs: Number of references each feedfoward capacitor can use. :type half_bit: :class:`int` :param half_bit: If the number of bits is half-bit or not :type half_bit: :class:`bool` :returns: The number of capacitors the stage needs. :rtype: :class:`int` :raises AssertionError: If the number of references is invalid for the number of bits. .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ n_bits, half_bit = parse_bits(n_bits, half_bit) n_codes = compute_n_codes(n_bits, half_bit) assert n_refs >= 2, "Need at least 2 references." assert (n_codes - 1) % (n_refs - 1) == 0, ("Cannot match {} " "refs with {} codes.".format(n_refs, n_codes)) return ((n_codes - 1) // (n_refs - 1)) + 1 def compute_lsb(n_bits, fsr_min, fsr_max, half_bit=None): """ Computes the least significant bit (LSB) magnitude in the stage MDAC and sub-ADC to achieve a desired full scale range (FSR). The input FSR and output FSR are assumed to be the same so only one value is returned. :param n_bits: Number of bits of the stage :type n_bits: :class:`str`, :class:`float`, :class:`int` :param fsr_min: Minimum value of the full voltage scale :type fsr_min: :class:`float` :param fsr_min: Maximum value of the full voltage scale :type fsr_min: :class:`float` :param half_bit: If the number of bits is half-bit or not :type half_bit: :class:`bool` :returns: The voltage value of the LSB. :rtype: :class:`float` .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ n_bits, half_bit = parse_bits(n_bits, half_bit) n_codes = compute_n_codes(n_bits, half_bit) diff = fsr_max - fsr_min if half_bit: lsb = diff/(n_codes + 1) else: lsb = diff/n_codes return lsb def infer_thres_bits(thres): d_bits = 2 n_thres = np.size(thres) n_codes = compute_n_codes(d_bits // 2, half_bit=bool(d_bits % 2)) while n_codes < n_thres + 1: d_bits += 1 n_codes = compute_n_codes(d_bits // 2, half_bit=bool(d_bits % 2)) assert n_codes == n_thres + 1, "No match found" return d_bits // 2, bool(d_bits % 2) def infer_stage_lsb(stage): n_bits, half_bit = infer_thres_bits(stage.thres) # HACK: tail fsr asumes stage fsr return compute_lsb(n_bits, *stage.meta.fsr, half_bit=half_bit) def infer_thres_lsb(thres, fsr): n_bits, half_bit = infer_thres_bits(thres) # HACK: tail fsr asumes stage fsr return compute_lsb(n_bits, *fsr, half_bit=half_bit) def compute_ref(fsr_min, fsr_max, n_refs): """ Computes the capacitor references votage for a pipeline stage. :param n_bits: Number of bits of the stage :type n_bits: :class:`str`, :class:`float`, :class:`int` :param fsr_min: Minimum value of the full voltage scale :type fsr_min: :class:`float` :param fsr_min: Maximum value of the full voltage scale :type fsr_min: :class:`float` :param n_refs: Number of references each feedfoward capacitor can use. :type n_refs: :class:`int` :param half_bit: If the number of bits is half-bit or not :type half_bit: :class:`bool` :returns: The values of the feedfoward capacitor references. :rtype: :class:`numpy.ndarray` .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ return np.linspace(fsr_min, fsr_max, n_refs) def compute_thres(n_bits, fsr_min, fsr_max, half_bit=None): """ Computes the threshold voltages for a flash sub-ADC of a pipeline stage. :param n_bits: Number of bits of the stage :type n_bits: :class:`str`, :class:`float`, :class:`int` :param fsr_min: Minimum value of the full voltage scale :type fsr_min: :class:`float` :param fsr_min: Maximum value of the full voltage scale :type fsr_min: :class:`float` :param half_bit: If the number of bits is half-bit or not :type half_bit: :class:`bool` :returns: The values of the theshold voltages. :rtype: :class:`numpy.ndarray` .. seealso :: :func:`parse_bits`, for n_bits and half_bit specification. """ n_bits, half_bit = parse_bits(n_bits, half_bit) lsb = compute_lsb(n_bits, fsr_min, fsr_max, half_bit) n_codes = compute_n_codes(n_bits, half_bit) range_2 = (lsb * (n_codes - 2))/2 avg = (fsr_max + fsr_min) / 2 if n_codes > 2: return np.linspace(-range_2, range_2, n_codes-1) + avg else: return np.reshape(avg, (1,)) def eff_random(eff_mean, tau_std): """ Generates random number following a lognormal distribution, appropiate for the charge efficiency transfer parameter (eff). The lognormal distribution has mean in the mean parameter, but the standard deviation is computed by proyecting the mean in logspace, generating a normal distribution with that standard deviation and then exponeating again. This emulates the linear settling
<reponame>groboclown/petronia # This prevents the self-referential KeyComboTree from causing Any errors. # mypy: allow-any-expr """ Hotkey processing. The system should allow for only one type of chain to be used at a time. """ from typing import Dict, List, Tuple, Sequence, Iterable, Union, Optional from .....base.util import T # The platform-specific integer representation of the key press. It's up to # the platform to understand whether this is a low-level "scan code" (the key # position on the keyboard) or a "virtual key code" (a keyboard layout # translated to a common set of characters). # The sequence of numbers is for the situation where a user's requested key # can be one of a multiple of keys (e.g. left vs. right shift key) ModifierKeyCode = Union[int, Sequence[int]] StandardKeyCode = int KeyCode = Union[ModifierKeyCode, StandardKeyCode] # Up or down state + the key # Internally, this is (keycode << 1) | (key_down ? 1 : 0) StatefulKeyCode = int # A universal collection of key interpretations for matching a hotkey # definition. KeyCombo = Sequence[StatefulKeyCode] class KeyComboTree: """An internal representation of the list of possible keys. This forms a tree of possible results. Using a tree represented by dictionaries is a bit less memory efficient, but prevents the system from having to construct new objects on key press.""" __slots__ = ('children',) children: Dict[StatefulKeyCode, Union[str, 'KeyComboTree']] def __init__(self) -> None: self.children = {} def get(self, key: StatefulKeyCode) -> Union[str, 'KeyComboTree', None]: return self.children.get(key, None) def leaves(self, store: Optional[List[str]] = None) -> Sequence[str]: """All the leaf node values from this point, which are the strings.""" ret: List[str] if store is None: ret = [] else: ret = store for child in self.children.values(): if isinstance(child, str): ret.append(child) else: child.leaves(ret) return ret def add_child(self, keys: KeyCombo, name: str, override: bool = False) -> bool: """ return `True` if the key was added without anything else present, or `False` if something else already registered the key combo. If `override` is set, then the new child is added regardless of the return value. """ if keys: key0: StatefulKeyCode = keys[0] key1: Sequence[StatefulKeyCode] = keys[1:] if key1: if key0 not in self.children: self.children[key0] = KeyComboTree() child = self.children[key0] if isinstance(child, str): # something else already registered it if override: tree = KeyComboTree() tree.add_child(key1, name, override) self.children[key0] = tree return False return child.add_child(key1, name, override) # End of the key chain. if key0 in self.children: if override: self.children[key0] = name return False self.children[key0] = name return True return False def __repr__(self) -> str: kids = [] for key, val in self.children.items(): nk = "{0:02x}:{1}".format( (key >> 1) & 0xff, key & 1 == 0 and 'up' or 'dn' ) kids.append(repr(nk) + '=' + repr(val)) return "KeyComboTree({0})".format(', '.join(kids)) ACTION_PENDING = 1 ACTION_CANCELLED = 2 ACTION_COMPLETE = 3 IGNORED = 0 def create_stateful_key_code(standard_key_code: StandardKeyCode, is_down: bool) -> StatefulKeyCode: assert 0 <= standard_key_code <= 0xffff down_i = 1 if is_down else 0 return (standard_key_code << 1) | down_i def create_primary_chain( modifiers: Sequence[ModifierKeyCode], key_sequence: Sequence[StandardKeyCode] ) -> Sequence[KeyCombo]: """ Primary chain type: the primary modifiers must remain down for the chain to work. Releasing the primary causes the chain to stop. Each key in the key_sequence must be pressed and released before the next one is handled. The chain returned is a collection of all possible chains that match this request. """ # Key down for each of the modifiers, in any order, followed by the key sequence # down-then-up. This is combinations. The sequence does not require releasing # the modifiers to trigger it. if not modifiers: raise ValueError('modifiers list cannot be empty') if not key_sequence: raise ValueError('key sequence cannot be empty') ret: List[List[StatefulKeyCode]] = [] for combo in modifier_key_combinations(modifiers): # These must be pressed to start. key_list = [create_stateful_key_code(key, True) for key in combo] for key in key_sequence[:-1]: # Press then release. key_list.append(create_stateful_key_code(key, True)) key_list.append(create_stateful_key_code(key, False)) # The last key just needs to be pressed once. key_list.append(create_stateful_key_code(key_sequence[-1], True)) ret.append(key_list) return ret def create_modal_chain( initial_modifiers: Sequence[ModifierKeyCode], initial_keys: Sequence[StandardKeyCode], modal_keys: Sequence[StandardKeyCode] ) -> Sequence[KeyCombo]: """ Modal, like screen or tmux. Pressing the initial key sequence causes the rest to be checked. Those initial keys must all be down together, then released in any order, The chain returned is a collection of all possible chains that match this request. """ # initial = create_primary_chain(initial_modifiers, initial_keys) # Can't just reuse the previous one. Some combination of the modifiers # may include an optional set (e.g. "shift" to represent left or right shift), # and just arbitrarily releasing any of those isn't right; instead, it must be # the one associated with the mapping. # All the modifiers must be pressed first in any order, then the initial keys pressed in any order. # Additionally, the key release must be done in any order for any of the initial keys. if not initial_modifiers: raise ValueError('modifiers list cannot be empty') if not modal_keys: raise ValueError('modal key list cannot be empty') # List of the initial modifier + keys, and a list of the modifiers that must be released ret: List[List[StandardKeyCode]] = [] for combo in combinations(initial_modifiers): for modifier_key_list in modifier_key_permutations(combo): for init_key_list in combinations(initial_keys): release_combos = combinations(list(modifier_key_list) + list(init_key_list)) for rcombo in release_combos: rlist: List[StatefulKeyCode] = [] # All the modifiers must be pressed down for key in modifier_key_list: rlist.append(create_stateful_key_code(key, True)) # Then all the initial keys must be pressed down for key in init_key_list: rlist.append(create_stateful_key_code(key, True)) # Then they must all be released for key in rcombo: rlist.append(create_stateful_key_code(key, False)) ret.append(rlist) for key in modal_keys[:-1]: for key_list in ret: key_list.append(create_stateful_key_code(key, True)) key_list.append(create_stateful_key_code(key, False)) # THe last key does not need to be released for key_list in ret: key_list.append(create_stateful_key_code(modal_keys[-1], True)) return ret class HotKeyChain: """ Keeps track of the current hotkey press progress. This doesn't maintain any kind of key up / key down state. Hotkeys used by this *must* follow the convention of press modifier then associated keys. It won't work if they user performs one hotkey combo then tries another without releasing the modifier keys. """ __slots__ = ('_root_combos', '_active_combos',) _active_combos: Optional[KeyComboTree] def __init__( self, chain_commands: Optional[List[Tuple[Sequence[KeyCombo], str]]] = None ) -> None: self._root_combos = KeyComboTree() self._active_combos = None if chain_commands is not None: self.set_key_chains(chain_commands) def set_key_chains(self, chain_commands: List[Tuple[Sequence[KeyCombo], str]]) -> None: """Set all the hotkey combinations.""" combos = KeyComboTree() for key_list, name in chain_commands: for keys in key_list: combos.add_child(keys, name, True) # print("Set key chain to " + repr(combos)) # Change the variable in a single command. self._root_combos = combos self.reset() def reset(self) -> None: """Reset any active hotkey check.""" self._active_combos = None def key_action(self, key_code: StandardKeyCode, is_down: bool) -> Tuple[int, Optional[Iterable[str]]]: """ Handle the key action. Note that this MUST be done in-thread when the event happens, due to the ordering nature of key press, and how Petronia events are not guaranteed to be well-ordered. :param is_down: :param key_code: :return: IGNORED if the key should be passed through, ACTION_PENDING if the key should be blocked from passing to another application, but does not complete an action, ACTION_CANCELLED if the key doesn't continue the current hotkey chain, or the action name to run. """ # Construct the stateful key code key = create_stateful_key_code(key_code, is_down) if self._active_combos: # In the middle of handling a hotkey. next_part = self._active_combos.get(key) if isinstance(next_part, str): self._active_combos = None return ACTION_COMPLETE, (next_part,), if isinstance(next_part, KeyComboTree): self._active_combos = next_part return ACTION_PENDING, set(next_part.leaves()), # Not a known key combo. self._active_combos = None return ACTION_CANCELLED, None, next_part = self._root_combos.get(key) if isinstance(next_part, str): # A one-key hotkey. Shouldn't be allowed, but it is for now. return ACTION_COMPLETE, (next_part,), if isinstance(next_part, KeyComboTree): # Start a combo. # print("Starting hotkey combo " + repr(next_part)) self._active_combos = next_part return ACTION_PENDING, set(next_part.leaves()), # It wasn't a known combo. return IGNORED, None, def modifier_key_combinations( modifiers: Sequence[ModifierKeyCode] ) -> Sequence[List[StandardKeyCode]]: """ Find all the combinations of the modifier keys, and expand out the alternates of modifier keys. """ ret: List[List[StandardKeyCode]] = [] for combo in combinations(modifiers): for perm in modifier_key_permutations(combo): ret.append(perm) return ret def modifier_key_permutations( modifiers: Sequence[ModifierKeyCode] )
<filename>nio/responses.py # -*- coding: utf-8 -*- # Copyright © 2018 <NAME> <<EMAIL>> # Copyright © 2020-2021 Famedly GmbH # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import unicode_literals from builtins import str from dataclasses import dataclass, field from datetime import datetime from functools import wraps from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union from jsonschema.exceptions import SchemaError, ValidationError from logbook import Logger from .event_builders import ToDeviceMessage from .events import (AccountDataEvent, BadEventType, Event, InviteEvent, ToDeviceEvent, EphemeralEvent) from .events.presence import PresenceEvent from .http import TransportResponse from .log import logger_group from .schemas import Schemas, validate_json logger = Logger("nio.responses") logger_group.add_logger(logger) __all__ = [ "ContentRepositoryConfigResponse", "ContentRepositoryConfigError", "FileResponse", "DeleteDevicesAuthResponse", "DeleteDevicesResponse", "DeleteDevicesError", "DeletePushRuleError", "DeletePushRuleResponse", "Device", "DeviceList", "DevicesResponse", "DevicesError", "DeviceOneTimeKeyCount", "DiscoveryInfoError", "DiscoveryInfoResponse", "DownloadResponse", "DownloadError", "EnablePushRuleResponse", "EnablePushRuleError", "ErrorResponse", "InviteInfo", "JoinResponse", "JoinError", "JoinedMembersResponse", "JoinedMembersError", "JoinedRoomsResponse", "JoinedRoomsError", "KeysClaimResponse", "KeysClaimError", "KeysQueryResponse", "KeysQueryError", "KeysUploadResponse", "KeysUploadError", "RegisterResponse", "LoginResponse", "LoginError", "LoginInfoResponse", "LoginInfoError", "LogoutResponse", "LogoutError", "Response", "RoomBanResponse", "RoomBanError", "RoomCreateResponse", "RoomCreateError", "RoomDeleteAliasError", "RoomDeleteAliasResponse", "RoomInfo", "RoomInviteResponse", "RoomInviteError", "RoomKickResponse", "RoomKickError", "RoomLeaveResponse", "RoomLeaveError", "RoomForgetResponse", "RoomForgetError", "RoomMember", "RoomMessagesResponse", "RoomMessagesError", "RoomGetStateResponse", "RoomGetStateError", "RoomGetStateEventResponse", "RoomGetStateEventError", "RoomGetEventResponse", "RoomGetEventError", "RoomGetVisibilityResponse", "RoomPutAliasResponse", "RoomPutStateResponse", "RoomPutStateError", "RoomRedactResponse", "RoomRedactError", "RoomResolveAliasResponse", "RoomResolveAliasError", "RoomSendResponse", "RoomSendError", "RoomSummary", "RoomUnbanResponse", "RoomUnbanError", "Rooms", "SetPushRuleError", "SetPushRuleResponse", "SetPushRuleActionsError", "SetPushRuleActionsResponse", "ShareGroupSessionResponse", "ShareGroupSessionError", "SyncResponse", "SyncError", "Timeline", "UpdateDeviceResponse", "UpdateDeviceError", "RoomTypingResponse", "RoomTypingError", "RoomReadMarkersResponse", "RoomReadMarkersError", "UploadResponse", "UploadError", "ProfileGetResponse", "ProfileGetError", "ProfileGetDisplayNameResponse", "ProfileGetDisplayNameError", "ProfileSetDisplayNameResponse", "ProfileSetDisplayNameError", "ProfileGetAvatarResponse", "ProfileGetAvatarError", "ProfileSetAvatarResponse", "ProfileSetAvatarError", "PresenceGetResponse", "PresenceGetError", "PresenceSetResponse", "PresenceSetError", "RoomKeyRequestResponse", "RoomKeyRequestError", "ThumbnailResponse", "ThumbnailError", "ToDeviceResponse", "ToDeviceError", "RoomContextResponse", "RoomContextError", "UploadFilterError", "UploadFilterResponse", "UpdateReceiptMarkerError", "UpdateReceiptMarkerResponse", ] def verify(schema, error_class, pass_arguments=True): def decorator(f): @wraps(f) def wrapper(cls, parsed_dict, *args, **kwargs): try: logger.info("Validating response schema") validate_json(parsed_dict, schema) except (SchemaError, ValidationError) as e: logger.warn("Error validating response: " + str(e.message)) if pass_arguments: return error_class.from_dict(parsed_dict, *args, **kwargs) else: return error_class.from_dict(parsed_dict) return f(cls, parsed_dict, *args, **kwargs) return wrapper return decorator @dataclass class Rooms: invite: Dict[str, "InviteInfo"] = field() join: Dict[str, "RoomInfo"] = field() leave: Dict[str, "RoomInfo"] = field() @dataclass class DeviceOneTimeKeyCount: curve25519: Optional[int] = field() signed_curve25519: Optional[int] = field() @dataclass class DeviceList: changed: List[str] = field() left: List[str] = field() @dataclass class Timeline: events: List = field() limited: bool = field() prev_batch: str = field() @dataclass class InviteInfo: invite_state: List = field() @dataclass class RoomSummary: invited_member_count: Optional[int] = None joined_member_count: Optional[int] = None heroes: Optional[List[str]] = None @dataclass class UnreadNotifications: notification_count: Optional[int] = None highlight_count: Optional[int] = None @dataclass class RoomInfo: timeline: Timeline = field() state: List = field() ephemeral: List = field() account_data: List = field() summary: Optional[RoomSummary] = None unread_notifications: Optional[UnreadNotifications] = None @staticmethod def parse_account_data(event_dict): """Parse the account data dictionary and produce a list of events.""" events = [] for event in event_dict: events.append(AccountDataEvent.parse_event(event)) return events @dataclass class RoomMember: user_id: str = field() display_name: str = field() avatar_url: str = field() @dataclass class Device: id: str = field() display_name: str = field() last_seen_ip: str = field() last_seen_date: datetime = field() @classmethod def from_dict(cls, parsed_dict): date = None if parsed_dict["last_seen_ts"] is not None: date = datetime.fromtimestamp(parsed_dict["last_seen_ts"] / 1000) return cls( parsed_dict["device_id"], parsed_dict["display_name"], parsed_dict["last_seen_ip"], date ) @dataclass class Response: uuid: str = field(default="", init=False) start_time: Optional[float] = field(default=None, init=False) end_time: Optional[float] = field(default=None, init=False) timeout: int = field(default=0, init=False) transport_response: Optional[TransportResponse] = field( init=False, default=None, ) @property def elapsed(self): if not self.start_time or not self.end_time: return 0 elapsed = self.end_time - self.start_time return max(0, elapsed - (self.timeout / 1000)) @dataclass class FileResponse(Response): """A response representing a successful file content request. Attributes: body (bytes): The file's content in bytes. content_type (str): The content MIME type of the file, e.g. "image/png". filename (str, optional): The file's name returned by the server. """ body: bytes = field() content_type: str = field() filename: Optional[str] = field() def __str__(self): return "{} bytes, content type: {}, filename: {}".format( len(self.body), self.content_type, self.filename ) @classmethod def from_data(cls, data, content_type, filename=None): """Create a FileResponse from file content returned by the server. Args: data (bytes): The file's content in bytes. content_type (str): The content MIME type of the file, e.g. "image/png". """ raise NotImplementedError() @dataclass class ErrorResponse(Response): message: str = field() status_code: Optional[str] = None retry_after_ms: Optional[int] = None soft_logout: bool = False def __str__(self) -> str: if self.status_code and self.message: e = "{} {}".format(self.status_code, self.message) elif self.message: e = self.message elif self.status_code: e = "{} unknown error".format(self.status_code) else: e = "unknown error" if self.retry_after_ms: e = "{} - retry after {}ms".format(e, self.retry_after_ms) return "{}: {}".format(self.__class__.__name__, e) @classmethod def from_dict(cls, parsed_dict: Dict[Any, Any]): # type: (...) -> ErrorResponse try: validate_json(parsed_dict, Schemas.error) except (SchemaError, ValidationError): return cls("unknown error") return cls( parsed_dict["error"], parsed_dict["errcode"], parsed_dict.get("retry_after_ms"), parsed_dict.get("soft_logout", False), ) @dataclass class _ErrorWithRoomId(ErrorResponse): room_id: str = "" @classmethod def from_dict(cls, parsed_dict, room_id): try: validate_json(parsed_dict, Schemas.error) except (SchemaError, ValidationError): return cls("unknown error") return cls( parsed_dict["error"], parsed_dict["errcode"], parsed_dict.get("retry_after_ms"), parsed_dict.get("soft_logout", False), room_id ) class LoginError(ErrorResponse): pass class LogoutError(ErrorResponse): pass class SyncError(ErrorResponse): pass class RoomSendError(_ErrorWithRoomId): pass class RoomGetStateError(_ErrorWithRoomId): """A response representing an unsuccessful room state query.""" pass class RoomGetStateEventError(_ErrorWithRoomId): """A response representing an unsuccessful room state query.""" pass class RoomGetEventError(ErrorResponse): """A response representing an unsuccessful room get event request.""" pass class RoomPutStateError(_ErrorWithRoomId): """A response representing an unsuccessful room state sending request.""" pass class RoomRedactError(_ErrorWithRoomId): pass class RoomResolveAliasError(ErrorResponse): """A response representing an unsuccessful room alias query.""" pass class RoomDeleteAliasError(ErrorResponse): """A response representing an unsuccessful room alias delete request.""" pass class RoomPutAliasError(ErrorResponse): """A response representing an unsuccessful room alias put request.""" pass class RoomGetVisibilityError(ErrorResponse): """A response representing an unsuccessful room get visibility request.""" pass class RoomTypingError(_ErrorWithRoomId): """A response representing a unsuccessful room typing request.""" pass class UpdateReceiptMarkerError(ErrorResponse): pass class RoomReadMarkersError(_ErrorWithRoomId): """A response representing a unsuccessful room read markers request.""" pass class RoomKickError(ErrorResponse): pass class RoomBanError(ErrorResponse): pass class RoomUnbanError(ErrorResponse): pass class RoomInviteError(ErrorResponse): pass class RoomCreateError(ErrorResponse): """A response representing a unsuccessful create room request.""" pass class JoinError(ErrorResponse): pass class RoomLeaveError(ErrorResponse): pass class RoomForgetError(_ErrorWithRoomId): pass class RoomMessagesError(_ErrorWithRoomId): pass class KeysUploadError(ErrorResponse): pass class KeysQueryError(ErrorResponse): pass class KeysClaimError(_ErrorWithRoomId): pass class ContentRepositoryConfigError(ErrorResponse): """A response for a unsuccessful content repository config request.""" class UploadError(ErrorResponse): """A response representing a unsuccessful upload request.""" class DownloadError(ErrorResponse): """A response representing a unsuccessful download request.""" class ThumbnailError(ErrorResponse): """A response representing a unsuccessful thumbnail request.""" @dataclass class ShareGroupSessionError(_ErrorWithRoomId): """Response representing unsuccessful group sessions sharing request.""" users_shared_with: Set[Tuple[str, str]] = field(default_factory=set) @classmethod def from_dict(cls, parsed_dict, room_id, users_shared_with): try: validate_json(parsed_dict, Schemas.error) except (SchemaError, ValidationError): return cls("unknown error") return cls(parsed_dict["error"], parsed_dict["errcode"], room_id, users_shared_with) class DevicesError(ErrorResponse): pass class DeleteDevicesError(ErrorResponse): pass class UpdateDeviceError(ErrorResponse): pass class JoinedMembersError(_ErrorWithRoomId): pass class JoinedRoomsError(ErrorResponse): """A response representing an unsuccessful joined rooms query.""" pass class ProfileGetError(ErrorResponse): pass class ProfileGetDisplayNameError(ErrorResponse): pass class ProfileSetDisplayNameError(ErrorResponse): pass class ProfileGetAvatarError(ErrorResponse): pass class PresenceGetError(ErrorResponse): """Response representing a unsuccessful get presence request.""" pass class PresenceSetError(ErrorResponse): """Response representing a unsuccessful set presence request.""" pass class ProfileSetAvatarError(ErrorResponse): pass @dataclass class DiscoveryInfoError(ErrorResponse): pass @dataclass class DiscoveryInfoResponse(Response): """A response for a successful discovery info request. Attributes: homeserver_url (str): The base URL of the homeserver corresponding to the requested domain. identity_server_url (str, optional): The base URL of the identity server corresponding to the requested domain, if any. """ homeserver_url: str = field() identity_server_url: Optional[str] = None @classmethod @verify(Schemas.discovery_info, DiscoveryInfoError) def from_dict( cls, parsed_dict: Dict[str, Any], ) -> Union["DiscoveryInfoResponse", DiscoveryInfoError]: homeserver_url = parsed_dict["m.homeserver"]["base_url"].rstrip("/") identity_server_url = parsed_dict.get( "m.identity_server", {}, ).get("base_url", "").rstrip("/") or None return cls(homeserver_url, identity_server_url) @dataclass class RegisterErrorResponse(ErrorResponse): pass @dataclass class RegisterResponse(Response): user_id: str = field() device_id: str = field() access_token: str = field() def __str__(self) -> str: return "Registered {}, device id {}.".format( self.user_id, self.device_id, ) @classmethod @verify(Schemas.register, RegisterErrorResponse) def from_dict(cls, parsed_dict): return cls( parsed_dict["user_id"], parsed_dict["device_id"], parsed_dict["access_token"], ) @dataclass class LoginInfoError(ErrorResponse): pass @dataclass class LoginInfoResponse(Response): flows: List[str] = field() @classmethod @verify(Schemas.login_info, LoginInfoError) def from_dict(cls, parsed_dict: Dict[Any, Any]): # type: (...) -> Union[LoginInfoResponse, ErrorResponse] flow_types = [flow["type"] for flow in parsed_dict["flows"]] return cls(flow_types) @dataclass class LoginResponse(Response): user_id: str = field() device_id: str = field() access_token: str = field() def __str__(self) -> str: return "Logged in as {}, device id: {}.".format( self.user_id, self.device_id ) @classmethod @verify(Schemas.login, LoginError) def from_dict(cls, parsed_dict: Dict[Any, Any]): # type: (...) -> Union[LoginResponse, ErrorResponse] return cls( parsed_dict["user_id"], parsed_dict["device_id"], parsed_dict["access_token"], ) @dataclass class LogoutResponse(Response): def __str__(self) -> str: return "Logged out" @classmethod @verify(Schemas.empty, LogoutError) def from_dict(cls, parsed_dict: Dict[Any, Any]): #
<gh_stars>0 """ Flyter Tool for transferring files on the same network using raw sockets. Doesn't use encryption. """ __version__ = (0, 0, 0) __author__ = "CryptoNyxz" __license__ = """ MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from argparse import ArgumentParser from base64 import b64encode from datetime import timedelta from math import log from os import altsep, sep, \ mkdir, stat, unlink from os.path import dirname, exists, join from random import randint from secrets import token_bytes from shutil import get_terminal_size from socket import \ socket, error, timeout, \ ntohs, ntohl, htons, htonl, \ gethostname, \ AF_INET, SOCK_STREAM from threading import Thread from time import time from warnings import warn from sys import argv, exit, version_info if version_info < (3, 6): warn('[!] Some features are not be compatible with the version of your ' 'python interpreter') FROMTERMINAL = False # Utility Functions def random_port(host): """Return a random available TCP port.""" while True: port = randint(10_000, 65536) with socket(AF_INET, SOCK_STREAM) as sock: try: sock.bind((host, port)) except error: continue else: return port def printerror(errormsg): """Print an error message.""" global FROMTERMINAL if FROMTERMINAL: print(f'\n[x] {errormsg}') exit(-1) exit(-1) exit(-1) exit(-1) else: warn(errormsg) def printalert(alert): """Print an alert message.""" global FROMTERMINAL print(f'[!] {alert}') def int_to_bytes_s(integer): """Convert 16 - bit integer to bytes for packing.""" res = ntohs(integer) res = hex(res)[2:] res = '0'*(len(res) % 2) + res return bytes.fromhex(res) def bytes_to_int_s(byteseq): """Convert byte sequence to 16 - but integer for unpacking.""" res = bytes.hex(byteseq) res = int(res, 16) return htons(res) def int_to_bytes_l(integer): """Convert 32 - but integer to bytes for packing.""" res = ntohl(integer) res = hex(res)[2:] res = '0'*(len(res) % 2) + res return bytes.fromhex(res) def bytes_to_int_l(byteseq): """Convert byte sequence to 32 - but integer for unpacking.""" res = bytes.hex(byteseq) res = int(res, 16) return htonl(res) def pack_str(string): """Pack a string into a byte sequence.""" return string.encode() def unpack_str(byteseq): """Unpack a byte sequence into a string.""" return byteseq.decode() # Utility Classes class ProgressBar: """ For displaying progress bars. Parameters ---------- max_value : int, float The upper limit of the progress bar. length : :obj:`int`, optional The length of the progress bar. """ @staticmethod def byte_rescale(data, precision=1): scale = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] p = int(log(data, 2)/10) if data else 0 r_bytes = round(data/pow(2, 10*p), precision) return f"{r_bytes}{scale[p]}" def __init__(self, max_value, length=50): self.max_value = max_value self.current_val = 0 self.length = length self.rate = None self.start_time = None self.start_value = None self.stopped = False @property def done(self): """Return if already finished.""" return self.current_val >= self.max_value or self.stopped def start(self): """Start the progress bar.""" self.stopped = False self.start_time = time() self.start_value = self.current_val def stop(self): """Stop the progress bar.""" self.stopped = True def add_progress(self, value): """ Count new progress. Parameter --------- value : int, float Added progress value. """ if self.stopped: return self.current_val += value def display(self): """Display the current progress.""" if self.stopped: return d_value = self.current_val - self.start_value d_max_value = self.max_value - self.start_value d_time = time() - self.start_time per = d_value/d_max_value prog = int(self.length*per) extra = self.length*round(per) > prog prog_bar = '█'*prog + '▌'*extra spaces = ' '*(self.length - (prog + extra)) rate = d_value/d_time if d_time else float('inf') eta_s = round((d_max_value - d_value)/rate) if rate else \ None eta = timedelta(seconds=eta_s) if eta_s is not None else '?' clear_line = " "*(get_terminal_size().columns - 1) print(f"{clear_line}\r" "Progress: " f"|{prog_bar}{spaces}| " f"{100*per:.1f}% " f"({ProgressBar.byte_rescale(d_value)}) " f"[{ProgressBar.byte_rescale(rate)}/s] " f"ETA: {eta}", end="\r") # Flyter Classes class FlyterSender: """ Handles Flyter file sending processes. Note: Sends to FlyterReceiver instances. Parameterss ---------- recver_ip : str The IP address of the receiver. main_port : int The main TCP port of the receiver. """ DEFAULT_PACKET_SIZE = 1024 def __init__(self, recver_ip, main_port): self.recver_ip = recver_ip self.main_port = main_port self.token = <PASSWORD>_<PASSWORD>(6) self._recver_hostname = None self._recver_token = None self._transfer_type = None self._worker_ports = None self._packet_size = FlyterSender.DEFAULT_PACKET_SIZE self._sending_file = False self._workers_active = 0 self._progress_bar = None try: self.socket = socket(AF_INET, SOCK_STREAM) self.socket.settimeout(60) except: printerror('Error initializing sockets') self.param_set = False def __del__(self): if isinstance(self.socket, socket): self.socket.close() def _send_s(self, filepath, file_size): """ Send a file with a single worker. Parameters ---------- filepath : str The filepath to the file to be sent. """ if not self.param_set: return printerror("Not yet set with receiver's parameters") if not exists(filepath): return printerror("File doesn't exist") self._sending_file = True try: fs = file_size with open(filepath, 'br') as f: while self._sending_file and fs: packet = f.read(self._packet_size) if not packet: break self.socket.send(packet) assert self.socket.recv(1) == b'\x06' # ACK self._progress_bar.add_progress(len(packet)) fs -= len(packet) except AssertionError: self._progress_bar.stop() return printerror("Receiver rejected packet") except FileNotFoundError: self._progress_bar.stop() return printerror("Couldn't access file") except PermissionError: self._progress_bar.stop() return printerror("Couldn't access file due to permission error") except timeout: self._progress_bar.stop() return printerror("Operation timed out") except: self._progress_bar.stop() return printerror(f"Error while sending file") else: self._sending_file = False return True def _send_m(self, filepath, file_sizes): """ Send a file with multiple workers. Speeds up transmission rate by using multiple workers. Parameters ---------- filepath : str The filepath to the file to be sent. file_sizes : list(int) The sizes of the split-up file to be sent. """ if not self.param_set: return printerror("Not yet set with receiver's parameters") if not exists(filepath): printerror("File doesn't exist") def threadfunc(worker_num, fpath, start, end): self._workers_active += 1 try: with socket(AF_INET, SOCK_STREAM) as sock: sock.connect( (self.recver_ip, self._worker_ports[worker_num]) ) sock.send(self.token) assert sock.recv(1) == b'\x06' # ACK fs = end - start with open(fpath, 'br') as f: f.seek(start) while self._sending_file and fs: end_size = f.tell() + self._packet_size size = (self._packet_size - max(0, end_size - end)) packet = f.read(size) if not packet: break sock.send(packet) assert sock.recv(1) == b'\x06' # ACK self._progress_bar.add_progress(len(packet)) fs -= len(packet) except KeyboardInterrupt: self._progress_bar.stop() self._sending_file = False return printerror("User aborted operation") except AssertionError: self._progress_bar.stop() self._sending_file = False return printerror(f"Receiver rejected packet") except FileNotFoundError: self._progress_bar.stop() self._sending_file = False return printerror("Couldn't access file") except PermissionError: self._progress_bar.stop() self._sending_file = False return printerror("Couldn't access file due to permission " "error") except timeout: self._progress_bar.stop() self._sending_file = False return printerror("Operation timed out") except: self._progress_bar.stop() self._sending_file = False return printerror(f"Error while sending file") finally: self._workers_active -= 1 num_workers = len(self._worker_ports) self._sending_file = True try: size = 0 for w in range(num_workers): Thread( target=threadfunc, args=( w, filepath, size, size + file_sizes[w] ), ).start() size += file_sizes[w] except FileNotFoundError: return printerror("Couldn't access file") except PermissionError: return printerror("Couldn't access file due to permission error") except: return printerror("Error while starting to send file") while self._workers_active: try: pass except KeyboardInterrupt: self._progress_bar.stop() self._sending_file = False return printerror("User aborted operation") self._sending_file = False return True def send_file(self, filepath): """ Send a file. Parameters ---------- filepath : str The filepath of the file to be sent. """ if not self.param_set: return printerror("Not yet set with receiver's parameters") if not exists(filepath): return printerror("File doesn't exist") # Headers try: tok = self.token num_w = max(1, len(self._worker_ports)) fpath = filepath.replace(altsep, sep) fname = fpath.split(sep)[-1] fsize = stat(fpath).st_size fsizes = [fsize//num_w for w in range(num_w)] fsizes[-1] += fsize - sum(fsizes) fn = pack_str(fname) len_fn = int_to_bytes_s(len(fn)) fs = [int_to_bytes_l(s) for s in fsizes] fs = b''.join(fs) len_fs = int_to_bytes_s(num_w) headers = b''.join([tok, len_fn, fn, len_fs, fs]) except: return printerror("Error while preparing headers") try: b64_tok = b64encode(self._recver_token).decode() printalert(f"Sending to {self._recver_hostname}-{b64_tok}:" f" [ {fname} ]") self.socket.send(headers) print("Waiting for receiver to accept file") assert self.socket.recv(1) == b'\x06' # ACK except KeyboardInterrupt: return printerror("User
close\r\nX-Storage-Token: ' 't\r\nContent-Length: 0\r\nContent-Type: foo/bar' '\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = 'HTTP/1.1 201' self.assertEquals(headers[:len(exp)], exp) # Ensure getting the copied file gets original content-type sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile() fd.write('GET /v1/a/c/obj3 HTTP/1.1\r\nHost: ' 'localhost\r\nConnection: close\r\nX-Auth-Token: ' 't\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = 'HTTP/1.1 200' self.assertEquals(headers[:len(exp)], exp) self.assert_('Content-Type: foo/bar' in headers.split('\r\n'), repr(headers.split('\r\n'))) # Check set content type with charset sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile() fd.write('PUT /v1/a/c/obj4 HTTP/1.1\r\nHost: ' 'localhost\r\nConnection: close\r\nX-Storage-Token: ' 't\r\nContent-Length: 0\r\nContent-Type: foo/bar' '; charset=UTF-8\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = 'HTTP/1.1 201' self.assertEquals(headers[:len(exp)], exp) # Ensure getting the copied file gets original content-type sock = connect_tcp(('localhost', prolis.getsockname()[1])) fd = sock.makefile() fd.write('GET /v1/a/c/obj4 HTTP/1.1\r\nHost: ' 'localhost\r\nConnection: close\r\nX-Auth-Token: ' 't\r\n\r\n') fd.flush() headers = readuntil2crlfs(fd) exp = 'HTTP/1.1 200' self.assertEquals(headers[:len(exp)], exp) self.assert_('Content-Type: foo/bar; charset=UTF-8' in headers.split('\r\n'), repr(headers.split('\r\n'))) def test_mismatched_etags(self): with save_globals(): # no etag supplied, object servers return success w/ diff values controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'Content-Length': '0'}) self.app.update_request(req) proxy_server.http_connect = fake_http_connect(200, 201, 201, 201, etags=[None, '68b329da9893e34099c7d8ad5cb9c940', '68b329da9893e34099c7d8ad5cb9c940', '68b329da9893e34099c7d8ad5cb9c941']) resp = controller.PUT(req) self.assertEquals(resp.status_int // 100, 5) # server error # req supplies etag, object servers return 422 - mismatch req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'Content-Length': '0', 'ETag': '68b329da9893e34099c7d8ad5cb9c940', }) self.app.update_request(req) proxy_server.http_connect = fake_http_connect(200, 422, 422, 503, etags=['68b329da9893e34099c7d8ad5cb9c940', '68b329da9893e34099c7d8ad5cb9c941', None, None]) resp = controller.PUT(req) self.assertEquals(resp.status_int // 100, 4) # client error def test_request_bytes_transferred_attr(self): with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'Content-Length': '10'}, body='1234567890') self.app.update_request(req) res = controller.PUT(req) self.assert_(hasattr(req, 'bytes_transferred')) self.assertEquals(req.bytes_transferred, 10) def test_copy_zero_bytes_transferred_attr(self): with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 201, 201, 201, body='1234567890') controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Copy-From': 'c/o2', 'Content-Length': '0'}) self.app.update_request(req) res = controller.PUT(req) self.assert_(hasattr(req, 'bytes_transferred')) self.assertEquals(req.bytes_transferred, 0) def test_response_bytes_transferred_attr(self): with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, body='1234567890') controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o') self.app.update_request(req) res = controller.GET(req) res.body self.assert_(hasattr(res, 'bytes_transferred')) self.assertEquals(res.bytes_transferred, 10) def test_request_client_disconnect_attr(self): with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'Content-Length': '10'}, body='12345') self.app.update_request(req) res = controller.PUT(req) self.assertEquals(req.bytes_transferred, 5) self.assert_(hasattr(req, 'client_disconnect')) self.assert_(req.client_disconnect) def test_response_client_disconnect_attr(self): with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, body='1234567890') controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o') self.app.update_request(req) orig_object_chunk_size = self.app.object_chunk_size try: self.app.object_chunk_size = 5 res = controller.GET(req) ix = 0 for v in res.app_iter: ix += 1 if ix > 1: break res.app_iter.close() self.assertEquals(res.bytes_transferred, 5) self.assert_(hasattr(res, 'client_disconnect')) self.assert_(res.client_disconnect) finally: self.app.object_chunk_size = orig_object_chunk_size def test_response_get_accept_ranges_header(self): with save_globals(): req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'GET'}) self.app.update_request(req) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = fake_http_connect(200, 200, 200) resp = controller.GET(req) self.assert_('accept-ranges' in resp.headers) self.assertEquals(resp.headers['accept-ranges'], 'bytes') def test_response_head_accept_ranges_header(self): with save_globals(): req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) self.app.update_request(req) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = fake_http_connect(200, 200, 200) resp = controller.HEAD(req) self.assert_('accept-ranges' in resp.headers) self.assertEquals(resp.headers['accept-ranges'], 'bytes') def test_GET_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o') req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.GET(req) self.assert_(called[0]) def test_HEAD_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', {'REQUEST_METHOD': 'HEAD'}) req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.HEAD(req) self.assert_(called[0]) def test_POST_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): self.app.object_post_as_copy = False proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'Content-Length': '5'}, body='12345') req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.POST(req) self.assert_(called[0]) def test_POST_as_copy_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'Content-Length': '5'}, body='12345') req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.POST(req) self.assert_(called[0]) def test_PUT_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'Content-Length': '5'}, body='12345') req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.PUT(req) self.assert_(called[0]) def test_COPY_calls_authorize(self): called = [False] def authorize(req): called[0] = True return HTTPUnauthorized(request=req) with save_globals(): proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 201, 201, 201) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'COPY'}, headers={'Destination': 'c/o'}) req.environ['swift.authorize'] = authorize self.app.update_request(req) res = controller.COPY(req) self.assert_(called[0]) def test_POST_converts_delete_after_to_delete_at(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 202, 202, 202) self.app.memcache.store = {} orig_time = proxy_server.time.time try: t = time() proxy_server.time.time = lambda: t req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-After': '60'}) self.app.update_request(req) res = controller.POST(req) self.assertEquals(res.status, '202 Fake') self.assertEquals(req.headers.get('x-delete-at'), str(int(t + 60))) self.app.object_post_as_copy = False controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 202, 202, 202) self.app.memcache.store = {} req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-After': '60'}) self.app.update_request(req) res = controller.POST(req) self.assertEquals(res.status, '202 Fake') self.assertEquals(req.headers.get('x-delete-at'), str(int(t + 60))) finally: proxy_server.time.time = orig_time def test_POST_non_int_delete_after(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 202, 202, 202) self.app.memcache.store = {} req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-After': '60.1'}) self.app.update_request(req) res = controller.POST(req) self.assertEquals(res.status, '400 Bad Request') self.assertTrue('Non-integer X-Delete-After' in res.body) def test_POST_negative_delete_after(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 200, 200, 200, 202, 202, 202) self.app.memcache.store = {} req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-After': '-60'}) self.app.update_request(req) res = controller.POST(req) self.assertEquals(res.status, '400 Bad Request') self.assertTrue('X-Delete-At in past' in res.body) def test_POST_delete_at(self): with save_globals(): given_headers = {} def fake_make_requests(req, ring, part, method, path, headers, query_string=''): given_headers.update(headers[0]) self.app.object_post_as_copy = False controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') controller.make_requests = fake_make_requests proxy_server.http_connect = fake_http_connect(200, 200) self.app.memcache.store = {} t = str(int(time() + 100)) req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) controller.POST(req) self.assertEquals(given_headers.get('X-Delete-At'), t) self.assertTrue('X-Delete-At-Host' in given_headers) self.assertTrue('X-Delete-At-Device' in given_headers) self.assertTrue('X-Delete-At-Partition' in given_headers) t = str(int(time() + 100)) + '.1' req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) resp = controller.POST(req) self.assertEquals(resp.status_int, 400) self.assertTrue('Non-integer X-Delete-At' in resp.body) t = str(int(time() - 100)) req = Request.blank('/a/c/o', {}, headers={'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) resp = controller.POST(req) self.assertEquals(resp.status_int, 400) self.assertTrue('X-Delete-At in past' in resp.body) def test_PUT_converts_delete_after_to_delete_at(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) self.app.memcache.store = {} orig_time = proxy_server.time.time try: t = time() proxy_server.time.time = lambda: t req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-After': '60'}) self.app.update_request(req) res = controller.PUT(req) self.assertEquals(res.status, '201 Fake') self.assertEquals(req.headers.get('x-delete-at'), str(int(t + 60))) finally: proxy_server.time.time = orig_time def test_PUT_non_int_delete_after(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) self.app.memcache.store = {} req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-After': '60.1'}) self.app.update_request(req) res = controller.PUT(req) self.assertEquals(res.status, '400 Bad Request') self.assertTrue('Non-integer X-Delete-After' in res.body) def test_PUT_negative_delete_after(self): with save_globals(): controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') proxy_server.http_connect = \ fake_http_connect(200, 200, 201, 201, 201) self.app.memcache.store = {} req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-After': '-60'}) self.app.update_request(req) res = controller.PUT(req) self.assertEquals(res.status, '400 Bad Request') self.assertTrue('X-Delete-At in past' in res.body) def test_PUT_delete_at(self): with save_globals(): given_headers = {} def fake_connect_put_node(nodes, part, path, headers): given_headers.update(headers) controller = proxy_server.ObjectController(self.app, 'account', 'container', 'object') controller._connect_put_node = fake_connect_put_node proxy_server.http_connect = fake_http_connect(200, 200) self.app.memcache.store = {} t = str(int(time() + 100)) req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) controller.PUT(req) self.assertEquals(given_headers.get('X-Delete-At'), t) self.assertTrue('X-Delete-At-Host' in given_headers) self.assertTrue('X-Delete-At-Device' in given_headers) self.assertTrue('X-Delete-At-Partition' in given_headers) t = str(int(time() + 100)) + '.1' req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) resp = controller.PUT(req) self.assertEquals(resp.status_int, 400) self.assertTrue('Non-integer X-Delete-At' in resp.body) t = str(int(time() - 100)) req = Request.blank('/a/c/o', {}, headers={'Content-Length': '0', 'Content-Type': 'foo/bar', 'X-Delete-At': t}) self.app.update_request(req) resp = controller.PUT(req) self.assertEquals(resp.status_int, 400) self.assertTrue('X-Delete-At
be used is "svm_qa_dataframe". The default location that the output file will be written to is the current working directory crpt: bool, optional Uses extended dataframe index name to differentiate from normal svm data, by default 0 (False) save_csv: bool, optional store h5 data into a CSV file, by default False h5_file: str, optional load from a saved hdf5 file on local disk, by default None data : Pandas DataFrame Pandas DataFrame """ def __init__( self, search_path=os.getcwd(), search_patterns=["*_total_*_svm_*.json"], file_basename="svm_data", crpt=0, save_csv=False, store_h5=True, h5_file=None, output_path=None, ): self.search_path = search_path self.search_patterns = search_patterns self.file_basename = file_basename self.crpt = crpt self.save_csv = save_csv self.store_h5 = store_h5 self.h5_file = h5_file self.output_path = output_path self.__name__ = "diagnostic_json_harvester" self.msg_datefmt = "%Y%j%H%M%S" self.splunk_msg_fmt = "%(asctime)s %(levelname)s src=%(name)s- %(message)s" self.log_level = logutil.logging.INFO self.keyword_shortlist = [ "TARGNAME", "DEC_TARG", "RA_TARG", "NUMEXP", "imgname", "Number of GAIA sources.Number of GAIA sources", "number_of_sources.point", "number_of_sources.segment", ] self.log = None self.json_dict = None self.data = None # self.json_harvester() self.h5_file = None # self.h5store() def start_logging(self): """Initializes a logging object which logs process info to sys.stdout Returns ------- logutil.log object logs process info to sys.stdout """ self.log = logutil.create_logger( self.__name__, level=self.log_level, stream=sys.stdout, format=self.splunk_msg_fmt, datefmt=self.msg_datefmt, ) return self.log def flatten_dict(self, dd, separator=".", prefix=""): """Recursive subroutine to flatten nested dictionaries down into a single-layer dictionary. Borrowed from Drizzlepac, which borrowed it from: https://www.geeksforgeeks.org/python-convert-nested-dictionary-into-flattened-dictionary/ Parameters ---------- dd : dict dictionary to flatten separator : str, optional separator character used in constructing flattened dictionary key names from multiple recursive elements. Default value is '.' prefix : str, optional flattened dictionary key prefix. Default value is an empty string (''). Returns ------- dictionary a version of input dictionary *dd* that has been flattened by one layer """ return ( { prefix + separator + k if prefix else k: v for kk, vv in dd.items() for k, v in self.flatten_dict(vv, separator, kk).items() } if isinstance(dd, dict) else {prefix: dd} ) def read_json_file(self, json_filename): """extracts header and data sections from specified json file and returns the header and data (in it's original pre-json format) as a nested ordered dictionary Supported output data types: - all basic single-value python data types (float, int, string, Boolean, etc.) - lists - simple key-value dictionaries and ordered dictionaries - multi-layer nested dictionaries and ordered dictionaries - tuples - numpy arrays - astropy tables Parameters ---------- json_filename : str Name of the json file to extract data from Returns ------- dictionary out_dict structured similarly to self.out_dict with separate 'header' and 'data' keys. The information stored in the 'data' section will be in the same format that it was in before it was serialized and stored as a json file. """ if os.path.exists(json_filename): out_dict = collections.OrderedDict() with open(json_filename) as f: json_data = json.load(f) out_dict["header"] = json_data[ "header" ] # copy over the 'header' section directly. out_dict["general information"] = json_data["general information"] out_dict["data"] = collections.OrderedDict() # set up blank data section for datakey in json_data["data"].keys(): if ( json_data["data"][datakey]["original format"] == "<class 'numpy.ndarray'>" ): # Extract numpy array self.log.info( "Converting dataset '{}' back to format '{}', dtype = {}".format( datakey, json_data["data"][datakey]["original format"], json_data["data"][datakey]["dtype"], ) ) out_dict["data"][datakey] = np.asarray( json_data["data"][datakey]["data"], dtype=json_data["data"][datakey]["dtype"], ) elif ( json_data["data"][datakey]["original format"] == "<class 'tuple'>" ): # Extract tuples out_dict["data"][datakey] = tuple( json_data["data"][datakey]["data"] ) else: # Catchall for everything else out_dict["data"][datakey] = json_data["data"][datakey]["data"] else: errmsg = "json file {} not found!".format(json_filename) self.log.error(errmsg) raise Exception(errmsg) return out_dict def get_json_files(self): """Uses glob to create a list of json files to harvest. This function looks for all the json files containing qa test results generated by `runastrodriz` and `runsinglehap`. The search starts in the directory specified in the `search_path` parameter, but will look in immediate sub-directories as well if no json files are located in the directory specified by `search_path`. Returns ------- ordered dictionary out_json_dict containing lists of all identified json files, grouped by and keyed by Pandas DataFrame index value. """ # set up search string and use glob to get list of files json_list = [] for search_pattern in self.search_patterns: search_string = os.path.join(self.search_path, search_pattern) search_results = glob.glob(search_string) if len(search_results) == 0: search_string = os.path.join(self.search_path, "*", search_pattern) search_results = glob.glob(search_string) self.log.info( "{} files found: {}".format(search_pattern, len(search_results)) ) if len(search_results) > 0: json_list += search_results # store json filenames in a dictionary keyed by Pandas DataFrame index value if json_list: self.json_dict = collections.OrderedDict() for json_filename in sorted(json_list): json_data = self.read_json_file(json_filename) dataframe_idx = json_data["general information"]["dataframe_index"] """***ADAPTED FOR MACHINE LEARNING ARTIFICIAL CORRUPTION FILES***""" if self.crpt == 1: mm = "_".join(os.path.dirname(json_filename).split("_")[1:]) idx = f"{dataframe_idx}_{mm}" else: idx = dataframe_idx if idx in self.json_dict.keys(): self.json_dict[idx].append(json_filename) else: self.json_dict[idx] = [json_filename] del json_data # Housekeeping! # Fail gracefully if no .json files were found else: err_msg = "No .json files were found!" self.log.error(err_msg) raise Exception(err_msg) return self.json_dict def h5store(self, **kwargs): """Store pandas Dataframe to an HDF5 file on local disk. Returns ------- string path to stored h5 file """ if self.output_path is None: self.output_path = os.getcwd() fname = self.file_basename.split(".")[0] + ".h5" self.h5_file = os.path.join(self.output_path, fname) if os.path.exists(self.h5_file): os.remove(self.h5_file) if self.data is not None: store = pd.HDFStore(self.h5_file) store.put("mydata", self.data) store.get_storer("mydata").attrs.metadata = kwargs store.close() self.log.info( "Wrote dataframe and metadata to HDF5 file {}".format(self.h5_file) ) else: print("Data unavailable - run `json_scraper` to collect json data.") return self.h5_file def load_h5_file(self): """Loads dataframe from an H5 on local disk Returns ------- dataframe data loaded from an H5 file and stored in a dataframe object attribute. Raises ------ Exception Requested file not found """ if self.h5_file is None: if self.output_path is None: self.output_path = os.getcwd() self.h5_file = os.path.join(self.output_path, self.file_basename + ".h5") elif not self.h5_file.endswith(".h5"): self.h5_file += ".h5" if os.path.exists(self.h5_file): with pd.HDFStore(self.h5_file) as store: self.data = store["mydata"] print(f"Dataframe created: {self.data.shape}") else: errmsg = "HDF5 file {} not found!".format(self.h5_file) print(errmsg) raise Exception(errmsg) return self.data def json_harvester(self): """Main calling function to harvest json files matching the search pattern and store in dictionaries which are then combined into a single dataframe. Returns ------- dataframe dataset created by scraping data from json files on local disk. """ self.log = self.start_logging() self.log.setLevel(self.log_level) # Get sorted list of json files self.data = None # extract all information from all json files related to a specific Pandas DataFrame index value into a # single line in the master dataframe self.json_dict = self.get_json_files() num_json = len(self.json_dict) for n, idx in enumerate(self.json_dict.keys()): if ((n / num_json) % 0.1) == 0: self.log.info(f"Harvested {num_json} of the JSON files") ingest_dict = self.make_dataframe_line(self.json_dict[idx]) if ingest_dict: if self.data is not None: self.log.debug("APPENDED DATAFRAME") self.data = self.data.append( pd.DataFrame(ingest_dict["data"], index=[idx]) ) else: self.log.debug("CREATED DATAFRAME") self.data = pd.DataFrame(ingest_dict["data"], index=[idx]) if self.save_csv: self.write_to_csv() return self.data def write_to_csv(self): """optionally write dataframe out to .csv file.""" output_csv_filename = self.h5_filename.replace(".h5", ".csv") if os.path.exists(output_csv_filename): os.remove(output_csv_filename) self.data.to_csv(output_csv_filename) self.log.info("Wrote dataframe to csv file {}".format(output_csv_filename)) def make_dataframe_line(self, json_filename_list): """Extracts information from the json files specified by the input list *json_filename_list*. Main difference between this and the original Drizzlepac source code is a much more limited collection of data: descriptions and units are not collected; only a handful of specific keyword values are scraped from general information and header extensions. Parameters ---------- json_filename_list : list list of json files to process Returns ------- ingest_dict : collections.OrderedDict ordered dictionary containing all information extracted from json files specified by the input list *json_filename_list*. """ self.log.setLevel(self.log_level) header_ingested = False gen_info_ingested = False ingest_dict = collections.OrderedDict() ingest_dict["data"] = collections.OrderedDict() for json_filename in json_filename_list: # This is to differentiate point catalog compare_sourcelists columns from segment catalog # compare_sourcelists columns in the dataframe if json_filename.endswith("_point-cat_svm_compare_sourcelists.json"): title_suffix = "hap_vs_hla_point_" elif json_filename.endswith("_segment-cat_svm_compare_sourcelists.json"): title_suffix = "hap_vs_hla_segment_" else: title_suffix = "" json_data = self.read_json_file(json_filename) # add information from "header" section to ingest_dict just once keyword_shortlist = ["TARGNAME", "DEC_TARG", "RA_TARG", "NUMEXP", "imgname"] if not header_ingested: # filter out ALL header keywords not included in 'keyword_shortlist' for header_item in json_data["header"].keys(): if header_item in keyword_shortlist: # if header_item in header_keywords_to_keep: ingest_dict["data"]["header." + header_item] = json_data[ "header" ][header_item] header_ingested = True # add information from
""" 请求查询投资者持仓响应 :param pInvestorPosition: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return self.logger.info('持仓:%s', pInvestorPosition) if pInvestorPosition is None: return instrument_id_str = bytes_2_str(pInvestorPosition.InstrumentID) data_dic = ApiBase.struct_2_dic(pInvestorPosition) # 增加仓位最近刷新时间 data_dic["RefreshDateTime"] = datetime.now() position_date = PositionDateType.create_by_position_date(pInvestorPosition.PositionDate) self._instrument_investor_position_tmp_dic.setdefault(instrument_id_str, {})[position_date] = data_dic self.datetime_last_update_position_dic[instrument_id_str] = datetime.now() if status > 0: self._instrument_investor_position_dic = self._instrument_investor_position_tmp_dic self.logger.info('查询持仓完成') self.datetime_last_update_position = datetime.now() def ReqQryInvestorPositionDetail(self, instrument_id=b""): """ 请求查询投资者持仓明细 :param instrument_id: :return: """ p_struct = ApiStruct.QryInvestorPositionDetail(self.broker_id, self.investor_id, instrument_id) return self._send_request_2_queue(super().ReqQryInvestorPositionDetail, p_struct) def OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast): """请求查询投资者持仓明细响应""" status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return self.logger.info('持仓明细:%s', pInvestorPositionDetail) if status > 0: self.logger.info('查询持仓明细完成') def OnRspError(self, info, RequestId, IsLast): """ 错误应答 :param info: :param RequestId: :param IsLast: :return: """ if IsLast: self.logger.info('错误应答(%d):%s', RequestId, info) self.logger.info('接收错误应答完成') else: self.logger.info('错误应答(%d):%s', RequestId, info) def ReqQryOrder(self, instrument_id=b""): self._instrument_order_tmp_dic = {} p_struct = ApiStruct.QryOrder(self.broker_id, self.investor_id, InstrumentID=instrument_id) if instrument_id != b"": instrument_id_str = bytes_2_str(instrument_id) if instrument_id_str in self._instrument_order_tmp_dic: self._instrument_order_tmp_dic = self._instrument_order_dic.copy() del self._instrument_order_tmp_dic[instrument_id_str] else: self._instrument_order_tmp_dic = self._instrument_order_dic else: self._instrument_order_tmp_dic = {} return self._send_request_2_queue(super().ReqQryOrder, p_struct, request_timeout=0) def OnRspQryOrder(self, pOrder, pRspInfo, nRequestID, bIsLast): """ 请求查询报单响应 :param pOrder: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return self.logger.info('报单:%s', pOrder) data_dic = ApiBase.struct_2_dic(pOrder) instrument_id_str = bytes_2_str(pOrder.InstrumentID) self._instrument_order_tmp_dic.setdefault(instrument_id_str, {})[pOrder.SequenceNo] = data_dic if status > 0: # 为了避免出现加载查询结果过程中,其他现场查询订单引发的信息错误,利用 self._order_tmp_dic 进行临时信息存储 self._instrument_order_dic = self._instrument_order_tmp_dic self.logger.info('查询报单完成。 %s', {key: len(val) for key, val in self._instrument_order_dic.items()}) def OnRspQryTrade(self, pTrade, pRspInfo, nRequestID, bIsLast): """ 请求查询成交响应 :param pTrade: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return self.logger.info('成交:%s', pTrade) if status > 0: self.logger.info('查询成交完成') # 供TradeAgent交易接口使用 def get_position(self, instrument_id) -> dict: """ 供 TradeAgent get_position 使用""" if instrument_id in self._instrument_investor_position_dic: position_date_inv_pos_dic = self._instrument_investor_position_dic[instrument_id] else: position_date_inv_pos_dic = None return position_date_inv_pos_dic def get_order(self, instrument_id) -> dict: """ 供 TradeAgent get_order 使用""" if instrument_id in self._instrument_order_dic: orders_dic = self._instrument_order_dic[instrument_id] else: orders_dic = None return orders_dic def cancel_order(self, instrument_id): """供 TradeAgent cancel_order 使用""" if instrument_id in self._instrument_order_dic: orders_dic = self._instrument_order_dic[instrument_id] for seq_no, order_dic in orders_dic.items(): # if order_dic['VolumeTotal'] > 0: self.ReqOrderAction(order_dic) # 交易操作 def insert_struct_2_db(self, p_struct): """ 将 struct 插入 mongodb,返回key 以及 dic对象 key:(front_id 、session_id 、order_ref_int) OrderRef 是 CTP 后台提供给客户端标识一笔报单的字段,客户端可以通过关键 字组(FrontID 、SessionID 、OrderRef)唯一确定一笔报单,客户端在报单发出时未填 写 OrderRef 字段,CTP 后台会自动为该报单的 OrderRef 字段赋值并返回给客户端。 :param p_struct: :return: """ order_ref_int = int(bytes_2_str(p_struct.OrderRef)) key = (self.front_id, self.session_id, order_ref_int) # dic = ApiBase.insert_one_2_db(p_struct, collection_name=None, **key) dic = {} return key, dic def _request_action_order_insert(self, p_struct): """ 公共Request方法,传入方面,及相关struct数据 函数自动生成新的request_id及进行log记录 2017-11-26 统一改为异步方式执行 :param func: :param p_struct: :return: """ if not self.is_settlement_info_confirmed: self.logger.warning('当前交易日期%s,最新结算信息尚未确认,发出交易请求可能失败', self.trading_day) func = super().ReqOrderInsert # request_id = self.inc_request_id() # order_ref = self.inc_order_ref() # p_struct.OrderRef = order_ref # p_struct.RequestID = request_id return self._send_request_2_queue(func, p_struct, add_request_id=True, add_order_ref=True, request_timeout=2) # self.logger.debug('-> %s(%d):\n%s', func.__name__, request_id, p_struct) # req_ret = func(p_struct, request_id) # self.log_req_if_error(req_ret, stack_num=2) # if req_ret >= 0: # order_ref_int = int(order_ref) # key = (self.front_id, self.session_id, order_ref_int) # stg_order = StrategyOrder( # self.strategy_id, self.front_id, self.session_id, order_ref, p_struct) # self.order_ref_strategy_order_dic[key] = stg_order # self.logger.debug('%s(%d) order_ref_strategy_order_dic[%s]=\n%r', # func.__name__, request_id, key, stg_order) # return req_ret, order_ref def open_long(self, instrument_id, price, vol): """ 开多 :param instrument_id: :param price: :param vol: :return: """ p_struct = ApiStruct.InputOrder(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=str_2_bytes(instrument_id), UserID=self.user_id, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=ApiStruct.D_Buy, CombOffsetFlag=ApiStruct.OF_Open, CombHedgeFlag=ApiStruct.HF_Speculation, LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=ApiStruct.TC_GFD ) return self._request_action_order_insert(p_struct) def close_long(self, instrument_id, price, vol, offset_flag=ApiStruct.OF_Close): """ 平多 上期所的持仓分今仓(当日开仓)和昨仓(历史持仓),平仓时需要指定是平今仓还是昨仓。 上述字段中, 若对上期所的持仓直接使用THOST_FTDC_OF_Close , 则效果同使用 THOST_FTDC_OF_CloseYesterday 。若对其他交易所的持仓使用 :param instrument_id: :param price: :param vol: :return: """ p_struct = ApiStruct.InputOrder(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=str_2_bytes(instrument_id), UserID=self.user_id, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=ApiStruct.D_Sell, CombOffsetFlag=offset_flag, CombHedgeFlag=ApiStruct.HF_Speculation, LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=ApiStruct.TC_GFD ) return self._request_action_order_insert(p_struct) def open_short(self, instrument_id, price, vol): """ 开空 :param instrument_id: :param price: :param vol: :return: """ p_struct = ApiStruct.InputOrder(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=str_2_bytes(instrument_id), UserID=self.user_id, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=ApiStruct.D_Sell, CombOffsetFlag=ApiStruct.OF_Open, CombHedgeFlag=ApiStruct.HF_Speculation, LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=ApiStruct.TC_GFD ) return self._request_action_order_insert(p_struct) def close_short(self, instrument_id, price, vol, offset_flag=ApiStruct.OF_Close): """ 开空 上期所的持仓分今仓(当日开仓)和昨仓(历史持仓),平仓时需要指定是平今仓还是昨仓。 上述字段中, 若对上期所的持仓直接使用THOST_FTDC_OF_Close , 则效果同使用 THOST_FTDC_OF_CloseYesterday 。若对其他交易所的持仓使用 :param instrument_id: :param price: :param vol: :param offset_flag: 平仓标示 OF_Close, OF_ForceClose, OF_CloseToday, OF_CloseYesterday :return: """ p_struct = ApiStruct.InputOrder(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=str_2_bytes(instrument_id), UserID=self.user_id, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=ApiStruct.D_Buy, CombOffsetFlag=offset_flag, CombHedgeFlag=ApiStruct.HF_Speculation, LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=ApiStruct.TC_GFD ) return self._request_action_order_insert(p_struct) def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast): """ 报单录入请求 :param pInputOrder: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return key, _ = self.insert_struct_2_db(pInputOrder) self.logger.info('报单回报%s:\n%s', key, pInputOrder) if status > 0: self.order_ref_strategy_order_dic[key].input_order = pInputOrder self.logger.info('提交报单完成') instrument_id_str = bytes_2_str(pInputOrder.InstrumentID) self.datetime_last_send_order_dic[instrument_id_str] = datetime.now() else: if key in self.order_ref_strategy_order_dic: del self.order_ref_strategy_order_dic[key] self.logger.error('提交报单失败') def OnErrRtnOrderInsert(self, pInputOrder, pRspInfo): """ 交易所报单录入错误回报 :param pInputOrder: :param pRspInfo: :return: """ if not self.is_rsp_success(pRspInfo): return key, _ = self.insert_struct_2_db(pInputOrder) self.logger.error('报单错误回报%s:\n%s', key, pInputOrder) self.ReqQryOrder(pInputOrder.InstrumentID) def OnRtnOrder(self, pOrder): """ 报单通知 报盘将通过交易核心检査的报单发送到交易所前置, 交易所会再次校验该报单. 如果交易所认为该报单不合 法,交易所会将该报单撤销,将错误値息返回給报盘.并返回更新后的该报单的状态,当客户端接收到该错 误信息后, 就会调用 OnErrRtnOrderlnsert 函数, 而更新后的报单状态会通过调用函数 OnRtnOrder发送到 户端. 如果交易所认为该报单合法,则只、返回该报単状态(此时的状态应为: “尚未触发”)。 :param pOrder: :return: """ self.logger.info('报单通知:%s', pOrder) self._get_response(pOrder.RequestID) # 报单状态 order_status = pOrder.OrderStatus order_status_str = "" if order_status == ApiStruct.OST_AllTraded: order_status_str = '全部成交' elif order_status == ApiStruct.OST_PartTradedQueueing: order_status_str = '部分成交还在队列中' elif order_status == ApiStruct.OST_PartTradedNotQueueing: order_status_str = '部分成交不在队列中' elif order_status == ApiStruct.OST_NoTradeQueueing: order_status_str = '未成交还在队列中' elif order_status == ApiStruct.OST_NoTradeNotQueueing: order_status_str = '未成交不在队列中' elif order_status == ApiStruct.OST_Canceled: order_status_str = '撤单' elif order_status == ApiStruct.OST_Unknown: order_status_str = '未知' elif order_status == ApiStruct.OST_NotTouched: order_status_str = '尚未触发' elif order_status == ApiStruct.OST_Touched: order_status_str = '已触发' # 报单提交状态 order_submit_status = pOrder.OrderSubmitStatus order_submit_status_str = "" if order_submit_status == ApiStruct.OSS_InsertRejected: order_submit_status_str = '已经提交' elif order_submit_status == ApiStruct.OSS_CancelSubmitted: order_submit_status_str = '撤单已经提交' elif order_submit_status == ApiStruct.OSS_ModifySubmitted: order_submit_status_str = '修改已经提交' elif order_submit_status == ApiStruct.OSS_Accepted: order_submit_status_str = '已经接受' elif order_submit_status == ApiStruct.OSS_InsertRejected: order_submit_status_str = '报单已经被拒绝' elif order_submit_status == ApiStruct.OSS_CancelRejected: order_submit_status_str = '撤单已经被拒绝' elif order_submit_status == ApiStruct.OSS_ModifyRejected: order_submit_status_str = '改单已经被拒绝' # 记录状态 key, _ = self.insert_struct_2_db(pOrder) if order_status in (ApiStruct.OST_Canceled, ApiStruct.OST_Unknown) or \ order_submit_status in ( ApiStruct.OSS_InsertRejected, ApiStruct.OSS_CancelRejected, ApiStruct.OSS_ModifyRejected): self.logger.warning('报单提交状态:%s 报单状态:%s %s', order_submit_status_str, order_status_str, bytes_2_str(pOrder.StatusMsg)) else: self.logger.debug('报单提交状态:%s 报单状态:%s', order_submit_status_str, order_status_str) self.ReqQryOrder(pOrder.InstrumentID) def OnRtnTrade(self, pTrade): """ 成交通知 如果该报単由交易所进行了最合成交.交易所再次返国该报単的状态(已成交) ,并通过此函数返回该笔成交。 报单成交之后, 一个报单回报(0nRtnorder)和一个成交回报(0nRtnTrade)会被发送到客户瑞,报单回报 中报单的状态为“已成交”.但是仍然建议客户端将成交回报作为报单成交的标志,因为CTP的交易核心在 收到 OnRtnTrade之后才会更新该报単的状态. 如.果客户端通过报单回报来判断报単成交与否并立即平仓,有 极小的概率会出现在平仓指令到达cTP交易核心时该报单的状态仍未更新,就会导致无法平仓. :param pTrade: :return: """ key, _ = self.insert_struct_2_db(pTrade) self.logger.info('成交通知 %s:%s', key, pTrade) order_ref = key[2] if key in self.order_ref_strategy_order_dic: self.order_ref_strategy_order_dic[key].trade_list = pTrade else: self.logger.debug('order_ref_strategy_order_dic.keys:%s', self.order_ref_strategy_order_dic.keys()) self.logger.warning('order_ref: %s 在当前策略报单列表中未找到\n%s', order_ref, pTrade) instrument_id_str = bytes_2_str(pTrade.InstrumentID) self.datetime_last_rtn_trade_dic[instrument_id_str] = datetime.now() # 更新股票持仓信息 if self.update_position_after_rtn_trade: self.ReqQryInvestorPosition(pTrade.InstrumentID) if self.update_order_after_rtn_trade: self.ReqQryOrder(pTrade.InstrumentID) def ReqOrderAction(self, order_dic): """ 2017-11-26 改为使用 order_dic 作为输入参数 根据《API特别说明》文档介绍需要增加 5 个关键参数,因此,需要从 order 信息中进行提取 报单操作请求:撤单指令 FrontID 、SessionID、OrderRef、ExchangID、OrderSysID :param order_dic: :return: """ if order_dic['OrderStatus'] == OST_Canceled_STR or order_dic['VolumeTotalOriginal'] == order_dic['VolumeTraded']: # TODO: 1 返回值没有特别意义,只是用于区分正常返回值,以后再进行规范化处理 return 1 front_id = int(order_dic['FrontID']) session_id = int(order_dic['SessionID']) order_ref = str_2_bytes(order_dic['OrderRef']) exchang_id = str_2_bytes(order_dic['ExchangeID']) order_sys_id = str_2_bytes(order_dic['OrderSysID']) self.logger.debug('请求撤销报单:\n%s', order_dic) order_action_ref = self.inc_order_action_ref() p_struct = ApiStruct.InputOrderAction(self.broker_id, self.investor_id, order_action_ref, OrderRef=order_ref, FrontID=front_id, SessionID=session_id, ExchangeID=exchang_id, OrderSysID=order_sys_id) return self._send_request_2_queue(super().ReqOrderAction, p_struct, add_request_id=True, request_timeout=0) def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast): """ 报单操作请求响应 :param pInputOrderAction: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ status = self.resp_common(pRspInfo, nRequestID, bIsLast) if status < 0: return key, _ = self.insert_struct_2_db(pInputOrderAction) self.logger.info('撤单回报%s:\n%s', key, pInputOrderAction) self.ReqQryOrder(pInputOrderAction.InstrumentID) def OnErrRtnOrderAction(self, pOrderAction, pRspInfo): """ 交易所撤单操作错误回报 正常情况不应该出现 :param pOrderAction: :param pRspInfo: :return: """ if not self.is_rsp_success(pRspInfo): return key, _ = self.insert_struct_2_db(pOrderAction) self.logger.info('撤单错误回报%s:\n%s', key, pOrderAction) def test_md_api(): """ 对mdapi 进行创建、登录、订阅等操作 :return: """ # 行情接口的初始化 # 1. 创建继承自 SPI,并创建出实例,以及 API 实例 # 2. 向 API 实例注册 SPI 实例。 # md_api = MyMdApi(Config.subscribe_instrument_list) # [b'rb1710', b'rb1712'] md_api = MyMdApi([b'au1712', b'rb1712', b'pb1801']) # [b'rb1710', b'rb1712'] # 3. 向 API 实例注册前置地址。交易接口需要注册交易前置地址,行情接口需要注册行情前置地址。 md_api.RegisterFront() md_api.Init() time.sleep(5) try: max_count = 20 # for n in range(max_count): while md_api.has_login: time.sleep(1) # if n == 1: # md_api.UnSubscribeMarketData([b'rb1712']) except KeyboardInterrupt: pass finally: md_api.ReqUserLogout() md_api.Release() def run_trader_api(): """ 初始化的步骤和代码基本上与行情接口(3.2 节)的初始化一致。 不同之处 1. 创建 API 实例时不能指定数据的传输协议。即第二行中的函数 CreateFtdcTraderApi 中只接受一个参数(即流文件目录)。 2. 需要订阅公有流和私有流。 公有流:交易所向所有连接着的客户端发布的信息。比如说:合约场上交易状态。 私有流:交易所向特定客户端发送的信息。如报单回报,成交回报。 订阅模式  Restart:接收所有交易所当日曾发送过的以及之后可能会发送的所有该类消息。  Resume:接收客户端上次断开连接后交易所曾发送过的以及之后可能会发送的所有该类消息。  Quick:接收客户端登录之后交易所可能会发送的所有该类消息。 3. 注册的前置地址是交易前置机的地址。 :return: """ trader_api = MyTraderApi() trader_api.RegisterFront() trader_api.SubscribePrivateTopic(ApiStruct.TERT_QUICK) trader_api.SubscribePublicTopic(ApiStruct.TERT_QUICK) trader_api.Init() try: max_count = 60 # while 1: wait_count = 0 is_settlement_info_confirmed = False order_dic = None for n in range(max_count): if trader_api.has_login: wait_count += 1 # if not
index is None or isinstance(index, int), "i must be an int" self._index = index def __str__(self): return "OP2 IterationIndex: %s" % self._index def __repr__(self): return "IterationIndex(%r)" % self._index @property def index(self): """Return the integer value of this index.""" return self._index def __getitem__(self, idx): return IterationIndex(idx) # This is necessary so that we can convert an IterationIndex to a # tuple. Because, __getitem__ returns a new IterationIndex # we have to explicitly provide an iterable interface def __iter__(self): """Yield self when iterated over.""" yield self i = IterationIndex() """Shorthand for constructing :class:`IterationIndex` objects. ``i[idx]`` builds an :class:`IterationIndex` object for which the `index` property is `idx`. """ class _MapArg(object): def __init__(self, map, idx): r""" Temporary :class:`Arg`-like object for :class:`Map`\s. :arg map: The :class:`Map`. :arg idx: The index into the map. """ self.map = map self.idx = idx class Map(object): """OP2 map, a relation between two :class:`Set` objects. Each entry in the ``iterset`` maps to ``arity`` entries in the ``toset``. When a map is used in a :func:`pyop2.op2.par_loop`, it is possible to use Python index notation to select an individual entry on the right hand side of this map. There are three possibilities: * No index. All ``arity`` :class:`Dat` entries will be passed to the kernel. * An integer: ``some_map[n]``. The ``n`` th entry of the map result will be passed to the kernel. * An :class:`IterationIndex`, ``some_map[pyop2.i[n]]``. ``n`` will take each value from ``0`` to ``e-1`` where ``e`` is the ``n`` th extent passed to the iteration space for this :func:`pyop2.op2.par_loop`. See also :data:`i`. For extruded problems (where ``iterset`` is an :class:`ExtrudedSet`) with boundary conditions applied at the top and bottom of the domain, ``bt_masks`` should be a :class:`dict` mapping boundary condition types to a 2-tuple of masks that should be applied to switch off respectively the "bottom" and "top" nodes of a cell. """ _globalcount = 0 @validate_type(('iterset', Set, SetTypeError), ('toset', Set, SetTypeError), ('arity', numbers.Integral, ArityTypeError), ('name', str, NameTypeError)) def __init__(self, iterset, toset, arity, values=None, name=None, offset=None, parent=None, boundary_masks=None): self._iterset = iterset self._toset = toset self.comm = toset.comm self._arity = arity self._values = verify_reshape(values, IntType, (iterset.total_size, arity), allow_none=True) self._name = name or "map_%d" % Map._globalcount if offset is None or len(offset) == 0: self._offset = None else: self._offset = verify_reshape(offset, IntType, (arity, )) # This is intended to be used for modified maps, for example # where a boundary condition is imposed by setting some map # entries negative. self._parent = parent # A cache for objects built on top of this map self._cache = {} # Which indices in the extruded map should be masked out for # the application of strong boundary conditions self.boundary_masks = boundary_masks Map._globalcount += 1 class MapMask(namedtuple("_MapMask_", ["section", "indices", "facet_points"])): _argtype = ctypes.POINTER(_MapMask) @cached_property def handle(self): struct = _MapMask() struct.section = self.section.handle struct.indices = self.indices.ctypes.data return ctypes.pointer(struct) @validate_type(('index', (int, IterationIndex), IndexTypeError)) def __getitem__(self, index): if configuration["type_check"]: if isinstance(index, int) and not (0 <= index < self.arity): raise IndexValueError("Index must be in interval [0,%d]" % (self._arity - 1)) if isinstance(index, IterationIndex) and index.index not in [0, 1]: raise IndexValueError("IterationIndex must be in interval [0,1]") return _MapArg(self, index) # This is necessary so that we can convert a Map to a tuple # (needed in as_tuple). Because, __getitem__ no longer returns a # Map we have to explicitly provide an iterable interface def __iter__(self): """Yield self when iterated over.""" yield self def __len__(self): """This is not a mixed type and therefore of length 1.""" return 1 @cached_property def _argtype(self): """Ctypes argtype for this :class:`Map`""" return ctypes.c_voidp @cached_property def split(self): return (self,) @cached_property def iteration_region(self): """Return the iteration region for the current map. For a normal map it will always be ALL. For a :class:`DecoratedMap` it will specify over which mesh region the iteration will take place.""" return frozenset([ALL]) @cached_property def implicit_bcs(self): r"""Return any implicit (extruded "top" or "bottom") bcs to apply to this :class:`Map`. Normally empty except in the case of some :class:`DecoratedMap`\s.""" return () @cached_property def vector_index(self): return None @cached_property def iterset(self): """:class:`Set` mapped from.""" return self._iterset @cached_property def toset(self): """:class:`Set` mapped to.""" return self._toset @cached_property def arity(self): """Arity of the mapping: number of toset elements mapped to per iterset element.""" return self._arity @cached_property def arities(self): """Arity of the mapping: number of toset elements mapped to per iterset element. :rtype: tuple""" return (self._arity,) @cached_property def arange(self): """Tuple of arity offsets for each constituent :class:`Map`.""" return (0, self._arity) @cached_property def values(self): """Mapping array. This only returns the map values for local points, to see the halo points too, use :meth:`values_with_halo`.""" return self._values[:self.iterset.size] @cached_property def values_with_halo(self): """Mapping array. This returns all map values (including halo points), see :meth:`values` if you only need to look at the local points.""" return self._values @cached_property def name(self): """User-defined label""" return self._name @cached_property def offset(self): """The vertical offset.""" return self._offset def _constant_layer_masks(self, which): if self.offset is None: return {} idx = {"bottom": -2, "top": -1}[which] masks = {} for method, (section, indices, facet_indices) in self.boundary_masks.items(): facet = facet_indices[idx] off = section.getOffset(facet) dof = section.getDof(facet) section.getDof(facet) indices = indices[off:off+dof] mask = np.zeros(len(self.offset), dtype=IntType) mask[indices] = -1 masks[method] = mask return masks @cached_property def top_mask(self): """The top layer mask to be applied on a mesh cell.""" return self._constant_layer_masks("top") @cached_property def bottom_mask(self): """The bottom layer mask to be applied on a mesh cell.""" return self._constant_layer_masks("bottom") def __str__(self): return "OP2 Map: %s from (%s) to (%s) with arity %s" \ % (self._name, self._iterset, self._toset, self._arity) def __repr__(self): return "Map(%r, %r, %r, None, %r)" \ % (self._iterset, self._toset, self._arity, self._name) def __le__(self, o): """self<=o if o equals self or self._parent <= o.""" if isinstance(o, DecoratedMap): # The iteration region of self must be a subset of the # iteration region of the sparsitymap. return len(self.iteration_region - o.iteration_region) == 0 and self <= o._map return self == o or (isinstance(self._parent, Map) and self._parent <= o) @classmethod def fromhdf5(cls, iterset, toset, f, name): """Construct a :class:`Map` from set named ``name`` in HDF5 data ``f``""" slot = f[name] values = slot.value arity = slot.shape[1:] if len(arity) != 1: raise ArityTypeError("Unrecognised arity value %s" % arity) return cls(iterset, toset, arity[0], values, name) class DecoratedMap(Map, ObjectCached): r"""Augmented type for a map used for attaching extra information used to inform code generation and/or sparsity building about the implicit structure of the extruded :class:`Map`. :param map: The original class:`Map`. :kwarg iteration_region: The class:`IterationRegion` of the mesh over which the parallel loop will iterate. :kwarg implicit_bcs: Any "top" or "bottom" boundary conditions to apply when assembling :class:`Mat`\s. The :data:`map` parameter may be an existing :class:`DecoratedMap` in which case, if either the :data:`iteration_region` or :data:`implicit_bcs` arguments are :data:`None`, they will be copied over from the supplied :data:`map`.""" def __new__(cls, map, iteration_region=None, implicit_bcs=None, vector_index=None): if map is None: return None if isinstance(map, DecoratedMap): # Need to add information, rather than replace if we # already have a decorated map (but overwrite if we're # told to) if iteration_region is None: iteration_region = [x for x in map.iteration_region] if implicit_bcs is None: implicit_bcs = [x for x in map.implicit_bcs] if vector_index is None: vector_index = map.vector_index return DecoratedMap(map.map, iteration_region=iteration_region, implicit_bcs=implicit_bcs, vector_index=vector_index) if isinstance(map, MixedMap): return MixedMap([DecoratedMap(m, iteration_region=iteration_region, implicit_bcs=implicit_bcs, vector_index=vector_index) for m in map]) return super(DecoratedMap, cls).__new__(cls, map, iteration_region=iteration_region, implicit_bcs=implicit_bcs, vector_index=vector_index) def __init__(self, map, iteration_region=None, implicit_bcs=None, vector_index=None): if self._initialized: return self._map = map if iteration_region is None: iteration_region = [ALL] iteration_region = as_tuple(iteration_region, IterationRegion) self._iteration_region = frozenset(iteration_region) if implicit_bcs is None: implicit_bcs = [] implicit_bcs = as_tuple(implicit_bcs) self.implicit_bcs = tuple(sorted(implicit_bcs)) self.vector_index = vector_index self._initialized = True @classmethod def _process_args(cls, m, **kwargs): return (m, ) + (m, ), kwargs @classmethod def _cache_key(cls, map, iteration_region=None, implicit_bcs=None, vector_index=None): ir = as_tuple(iteration_region, IterationRegion) if iteration_region else () bcs = as_tuple(implicit_bcs) if implicit_bcs else () return (map, ir, bcs, vector_index) def __repr__(self): return "DecoratedMap(%r, %r, %r, %r)" % (self._map, self._iteration_region, self.implicit_bcs, self.vector_index) def __str__(self): return "OP2 DecoratedMap on %s with region %s, implicit
<filename>statsmodels/stats/tests/test_diagnostic.py # -*- coding: utf-8 -*- """Tests for Regression Diagnostics and Specification Tests Created on Thu Feb 09 13:19:47 2012 Author: <NAME> License: BSD-3 currently all tests are against R """ import json import os import numpy as np import pandas as pd import pytest from numpy.testing import (assert_, assert_almost_equal, assert_equal, assert_allclose, assert_array_equal) from pandas.testing import assert_frame_equal import statsmodels.stats.diagnostic as smsdia import statsmodels.stats.outliers_influence as oi import statsmodels.stats.sandwich_covariance as sw from statsmodels.datasets import macrodata from statsmodels.datasets import sunspots from statsmodels.regression.linear_model import OLS from statsmodels.tools.tools import Bunch from statsmodels.tools.tools import add_constant from statsmodels.tsa.ar_model import AutoReg cur_dir = os.path.abspath(os.path.dirname(__file__)) @pytest.fixture(scope="module") def diagnostic_data(): rs = np.random.RandomState(93674328) e = rs.standard_normal(500) x = rs.standard_normal((500, 3)) y = x.sum(1) + e c = np.ones_like(y) data = pd.DataFrame(np.c_[y, c, x], columns=["y", "c", "x1", "x2", "x3"]) return data def compare_to_reference(sp, sp_dict, decimal=(14, 14)): assert_allclose(sp[0], sp_dict['statistic'], atol=10 ** -decimal[0], rtol=10 ** -decimal[0]) assert_allclose(sp[1], sp_dict['pvalue'], atol=10 ** -decimal[1], rtol=10 ** -decimal[0]) def test_gq(): d = macrodata.load(as_pandas=False).data realinv = d['realinv'] realgdp = d['realgdp'] realint = d['realint'] endog = realinv exog = add_constant(np.c_[realgdp, realint]) # goldfeld-quandt het_gq_greater = dict(statistic=13.20512768685082, df1=99, df2=98, pvalue=1.246141976112324e-30, distr='f') gq = smsdia.het_goldfeldquandt(endog, exog, split=0.5) compare_to_reference(gq, het_gq_greater, decimal=(13, 14)) assert_equal(gq[-1], 'increasing') class TestDiagnosticG(object): @classmethod def setup_class(cls): d = macrodata.load_pandas().data # growth rates gs_l_realinv = 400 * np.diff(np.log(d['realinv'].values)) gs_l_realgdp = 400 * np.diff(np.log(d['realgdp'].values)) lint = d['realint'][:-1].values tbilrate = d['tbilrate'][:-1].values endogg = gs_l_realinv exogg = add_constant(np.c_[gs_l_realgdp, lint]) exogg2 = add_constant(np.c_[gs_l_realgdp, tbilrate]) exogg3 = add_constant(np.c_[gs_l_realgdp]) res_ols = OLS(endogg, exogg).fit() res_ols2 = OLS(endogg, exogg2).fit() res_ols3 = OLS(endogg, exogg3).fit() cls.res = res_ols cls.res2 = res_ols2 cls.res3 = res_ols3 cls.endog = cls.res.model.endog cls.exog = cls.res.model.exog def test_basic(self): # mainly to check I got the right regression # > mkarray(fm$coefficients, "params") params = np.array([-9.48167277465485, 4.3742216647032, -0.613996969478989]) assert_almost_equal(self.res.params, params, decimal=12) def test_hac(self): res = self.res # > nw = NeweyWest(fm, lag = 4, prewhite = FALSE, verbose=TRUE) # > nw2 = NeweyWest(fm, lag=10, prewhite = FALSE, verbose=TRUE) # > mkarray(nw, "cov_hac_4") cov_hac_4 = np.array([1.385551290884014, -0.3133096102522685, -0.0597207976835705, -0.3133096102522685, 0.1081011690351306, 0.000389440793564336, -0.0597207976835705, 0.000389440793564339, 0.0862118527405036]).reshape((3, 3), order='F') # > mkarray(nw2, "cov_hac_10") cov_hac_10 = np.array([1.257386180080192, -0.2871560199899846, -0.03958300024627573, -0.2871560199899845, 0.1049107028987101, 0.0003896205316866944, -0.03958300024627578, 0.0003896205316866961, 0.0985539340694839]).reshape((3, 3), order='F') cov = sw.cov_hac_simple(res, nlags=4, use_correction=False) bse_hac = sw.se_cov(cov) assert_almost_equal(cov, cov_hac_4, decimal=14) assert_almost_equal(bse_hac, np.sqrt(np.diag(cov)), decimal=14) cov = sw.cov_hac_simple(res, nlags=10, use_correction=False) bse_hac = sw.se_cov(cov) assert_almost_equal(cov, cov_hac_10, decimal=14) assert_almost_equal(bse_hac, np.sqrt(np.diag(cov)), decimal=14) def test_het_goldfeldquandt(self): # TODO: test options missing # > gq = gqtest(fm, alternative='greater') # > mkhtest_f(gq, 'het_gq_greater', 'f') het_gq_greater = dict(statistic=0.5313259064778423, pvalue=0.9990217851193723, parameters=(98, 98), distr='f') # > gq = gqtest(fm, alternative='less') # > mkhtest_f(gq, 'het_gq_less', 'f') het_gq_less = dict(statistic=0.5313259064778423, pvalue=0.000978214880627621, parameters=(98, 98), distr='f') # > gq = gqtest(fm, alternative='two.sided') # > mkhtest_f(gq, 'het_gq_two_sided', 'f') het_gq_two_sided = dict(statistic=0.5313259064778423, pvalue=0.001956429761255241, parameters=(98, 98), distr='f') # > gq = gqtest(fm, fraction=0.1, alternative='two.sided') # > mkhtest_f(gq, 'het_gq_two_sided_01', 'f') het_gq_two_sided_01 = dict(statistic=0.5006976835928314, pvalue=0.001387126702579789, parameters=(88, 87), distr='f') endogg, exogg = self.endog, self.exog # tests gq = smsdia.het_goldfeldquandt(endogg, exogg, split=0.5) compare_to_reference(gq, het_gq_greater, decimal=(14, 14)) assert_equal(gq[-1], 'increasing') gq = smsdia.het_goldfeldquandt(endogg, exogg, split=0.5, alternative='decreasing') compare_to_reference(gq, het_gq_less, decimal=(14, 14)) assert_equal(gq[-1], 'decreasing') gq = smsdia.het_goldfeldquandt(endogg, exogg, split=0.5, alternative='two-sided') compare_to_reference(gq, het_gq_two_sided, decimal=(14, 14)) assert_equal(gq[-1], 'two-sided') # TODO: forcing the same split as R 202-90-90-1=21 gq = smsdia.het_goldfeldquandt(endogg, exogg, split=90, drop=21, alternative='two-sided') compare_to_reference(gq, het_gq_two_sided_01, decimal=(14, 14)) assert_equal(gq[-1], 'two-sided') # TODO other options ??? def test_het_breusch_pagan(self): res = self.res bptest = dict(statistic=0.709924388395087, pvalue=0.701199952134347, parameters=(2,), distr='f') bp = smsdia.het_breuschpagan(res.resid, res.model.exog) compare_to_reference(bp, bptest, decimal=(12, 12)) def test_het_breusch_pagan_nonrobust(self): res = self.res bptest = dict(statistic=1.302014063483341, pvalue=0.5215203247110649, parameters=(2,), distr='f') bp = smsdia.het_breuschpagan(res.resid, res.model.exog, robust=False) compare_to_reference(bp, bptest, decimal=(12, 12)) def test_het_white(self): res = self.res # TODO: regressiontest, compare with Greene or Gretl or Stata hw = smsdia.het_white(res.resid, res.model.exog) hw_values = (33.503722896538441, 2.9887960597830259e-06, 7.7945101228430946, 1.0354575277704231e-06) assert_almost_equal(hw, hw_values) def test_het_white_error(self): res = self.res with pytest.raises(ValueError, match="White's heteroskedasticity"): smsdia.het_white(res.resid, res.model.exog[:, :1]) def test_het_arch(self): # test het_arch and indirectly het_lm against R # > library(FinTS) # > at = ArchTest(residuals(fm), lags=4) # > mkhtest(at, 'archtest_4', 'chi2') archtest_4 = dict(statistic=3.43473400836259, pvalue=0.487871315392619, parameters=(4,), distr='chi2') # > at = ArchTest(residuals(fm), lags=12) # > mkhtest(at, 'archtest_12', 'chi2') archtest_12 = dict(statistic=8.648320999014171, pvalue=0.732638635007718, parameters=(12,), distr='chi2') at4 = smsdia.het_arch(self.res.resid, nlags=4) at12 = smsdia.het_arch(self.res.resid, nlags=12) compare_to_reference(at4[:2], archtest_4, decimal=(12, 13)) compare_to_reference(at12[:2], archtest_12, decimal=(12, 13)) def test_het_arch2(self): # test autolag options, this also test het_lm # unfortunately optimal lag=1 for this data resid = self.res.resid res1 = smsdia.het_arch(resid, nlags=1, autolag=None, store=True) rs1 = res1[-1] with pytest.warns(FutureWarning, match="autolag is deprecated and"): res2 = smsdia.het_arch(resid, nlags=5, autolag='aic', store=True) rs2 = res2[-1] assert_almost_equal(rs2.resols.params, rs1.resols.params, decimal=13) assert_almost_equal(res2[:4], res1[:4], decimal=13) # test that smallest lag, nlags=1 works with pytest.warns(FutureWarning, match="autolag is deprecated and"): res3 = smsdia.het_arch(resid, nlags=1, autolag='aic') assert_almost_equal(res3[:4], res1[:4], decimal=13) def test_acorr_breusch_godfrey(self): res = self.res # bgf = bgtest(fm, order = 4, type="F") breuschgodfrey_f = dict(statistic=1.179280833676792, pvalue=0.321197487261203, parameters=(4, 195,), distr='f') # > bgc = bgtest(fm, order = 4, type="Chisq") # > mkhtest(bgc, "breuschpagan_c", "chi2") breuschgodfrey_c = dict(statistic=4.771042651230007, pvalue=0.3116067133066697, parameters=(4,), distr='chi2') bg = smsdia.acorr_breusch_godfrey(res, nlags=4) bg_r = [breuschgodfrey_c['statistic'], breuschgodfrey_c['pvalue'], breuschgodfrey_f['statistic'], breuschgodfrey_f['pvalue']] assert_almost_equal(bg, bg_r, decimal=13) # check that lag choice works with pytest.warns(FutureWarning, match="The default value of nlags"): bg2 = smsdia.acorr_breusch_godfrey(res, nlags=None) bg3 = smsdia.acorr_breusch_godfrey(res, nlags=14) assert_almost_equal(bg2, bg3, decimal=13) def test_acorr_breusch_godfrey_multidim(self): res = Bunch(resid=np.empty((100, 2))) with pytest.raises(ValueError, match='Model resid must be a 1d array'): smsdia.acorr_breusch_godfrey(res) def test_acorr_ljung_box(self): # unit-test which may be useful later # ddof correction for fitted parameters in ARMA(p,q) fitdf=p+q # bt = Box.test(residuals(fm), lag=4, type = "Ljung-Box", fitdf=2) # mkhtest(bt, "ljung_box_4df2", "chi2") # ljung_box_4df2 = dict(statistic=5.23587172795227, # pvalue=0.0729532930400377, # parameters=(2,), distr='chi2') # bt = Box.test(residuals(fm), lag=4, type = "Box-Pierce", fitdf=2) # mkhtest(bt, "ljung_box_bp_4df2", "chi2") # ljung_box_bp_4df2 = dict(statistic=5.12462932741681, # pvalue=0.0771260128929921, # parameters=(2,), distr='chi2') res = self.res # general test # bt = Box.test(residuals(fm), lag=4, type = "Ljung-Box") # mkhtest(bt, "ljung_box_4", "chi2") ljung_box_4 = dict(statistic=5.23587172795227, pvalue=0.263940335284713, parameters=(4,), distr='chi2') # bt = Box.test(residuals(fm), lag=4, type = "Box-Pierce") # mkhtest(bt, "ljung_box_bp_4", "chi2") ljung_box_bp_4 = dict(statistic=5.12462932741681, pvalue=0.2747471266820692, parameters=(4,), distr='chi2') lb, lbpval, bp, bppval = smsdia.acorr_ljungbox(res.resid, 4, boxpierce=True, return_df=False) compare_to_reference([lb[-1], lbpval[-1]], ljung_box_4, decimal=(13, 13)) compare_to_reference([bp[-1], bppval[-1]], ljung_box_bp_4, decimal=(13, 13)) def test_acorr_ljung_box_big_default(self): res = self.res # R test with big dataset and default lag # bt = Box.test(residuals(fm), type = "Ljung-Box") # mkhtest(bt, "ljung_box_none", "chi2") ljung_box_none = dict(statistic=51.03724531797195, pvalue=0.11334744923390, distr='chi2') # bt = Box.test(residuals(fm), type = "Box-Pierce") # mkhtest(bt, "ljung_box_bp_none", "chi2") ljung_box_bp_none = dict(statistic=45.12238537034000, pvalue=0.26638168491464, distr='chi2') lags = min(40, res.resid.shape[0] // 2 - 2) lb, lbpval, bp, bppval = smsdia.acorr_ljungbox(res.resid, boxpierce=True, lags=lags, return_df=False) compare_to_reference([lb[-1], lbpval[-1]], ljung_box_none, decimal=(13, 13)) compare_to_reference([bp[-1], bppval[-1]], ljung_box_bp_none, decimal=(13, 13)) def test_acorr_ljung_box_small_default(self): res = self.res # R test with small dataset and default lag # bt = Box.test(residuals(fm), type = "Ljung-Box") # mkhtest(bt, "ljung_box_small", "chi2") ljung_box_small = dict(statistic=9.61503968281915, pvalue=0.72507000996945, parameters=(0,), distr='chi2') # bt = Box.test(residuals(fm), type = "Box-Pierce") # mkhtest(bt, "ljung_box_bp_small", "chi2") ljung_box_bp_small = dict(statistic=7.41692150864936, pvalue=0.87940785887006, parameters=(0,), distr='chi2') lb, lbpval, bp, bppval = smsdia.acorr_ljungbox(res.resid[:30], boxpierce=True, lags=13, return_df=False) compare_to_reference([lb[-1], lbpval[-1]], ljung_box_small, decimal=(13, 13)) compare_to_reference([bp[-1], bppval[-1]], ljung_box_bp_small, decimal=(13, 13)) def test_acorr_ljung_box_against_r(self, reset_randomstate): rs = np.random.RandomState(9876543) y1 = rs.standard_normal(100) e = rs.standard_normal(201) y2 = np.zeros_like(e) y2[0] = e[0] for i in range(1, 201): y2[i] = 0.5 * y2[i - 1] - 0.4 * e[i - 1] + e[i] y2 = y2[-100:] r_results_y1_lb = [[0.15685, 1, 0.6921], [5.4737, 5, 0.3608], [10.508, 10, 0.3971]] r_results_y2_lb = [[2.8764, 1, 0.08989], [3.8104, 5, 0.577], [8.4779, 10, 0.5823]] res_y1 = smsdia.acorr_ljungbox(y1, 10, return_df=True) res_y2 = smsdia.acorr_ljungbox(y2, 10, return_df=True) for i, loc in enumerate((1, 5, 10)): row = res_y1.loc[loc] assert_allclose(r_results_y1_lb[i][0], row.loc["lb_stat"], rtol=1e-3) assert_allclose(r_results_y1_lb[i][2], row.loc["lb_pvalue"], rtol=1e-3) row = res_y2.loc[loc] assert_allclose(r_results_y2_lb[i][0], row.loc["lb_stat"], rtol=1e-3) assert_allclose(r_results_y2_lb[i][2], row.loc["lb_pvalue"], rtol=1e-3) res = smsdia.acorr_ljungbox(y2, 10, boxpierce=True, return_df=True) assert_allclose(res.loc[10, "bp_stat"], 7.8935, rtol=1e-3) assert_allclose(res.loc[10, "bp_pvalue"], 0.639, rtol=1e-3) res = smsdia.acorr_ljungbox(y2, 10, boxpierce=True, return_df=True, model_df=1) assert_allclose(res.loc[10, "bp_pvalue"], 0.5449, rtol=1e-3) def test_harvey_collier(self): # > hc = harvtest(fm, order.by = NULL, data = list()) # > mkhtest_f(hc, 'harvey_collier', 't') harvey_collier = dict(statistic=0.494432160939874, pvalue=0.6215491310408242, parameters=198, distr='t') hc = smsdia.linear_harvey_collier(self.res) compare_to_reference(hc, harvey_collier, decimal=(12, 12)) hc_skip = smsdia.linear_harvey_collier(self.res, skip=20) assert not np.allclose(hc[0], hc_skip[0]) def test_rainbow(self): # rainbow test # > rt = raintest(fm) # > mkhtest_f(rt, 'raintest', 'f') raintest = dict(statistic=0.6809600116739604, pvalue=0.971832843583418, parameters=(101, 98), distr='f') # > rt = raintest(fm, fraction=0.4) # > mkhtest_f(rt, 'raintest_fraction_04', 'f') raintest_fraction_04 = dict(statistic=0.565551237772662, pvalue=0.997592305968473, parameters=(122, 77), distr='f') rb = smsdia.linear_rainbow(self.res) compare_to_reference(rb, raintest, decimal=(13, 14)) rb = smsdia.linear_rainbow(self.res, frac=0.4) compare_to_reference(rb, raintest_fraction_04, decimal=(13, 14)) def test_compare_lr(self): res =
if not isinstance(entity, entities.PlayerDroid): entity.getTeam().actors.append(entity) return entity def serverUpdate(self, aiWorld, entityGroup, packetUpdate): p = ObjectController.serverUpdate( self, aiWorld, entityGroup, packetUpdate) self.componentsNeedUpdate = False for component in self.entity.components: p2 = component.serverUpdate(aiWorld, entityGroup, packetUpdate) if packetUpdate: needUpdate = component.needsToSendUpdate() self.newPositionData = self.newPositionData or needUpdate if needUpdate: self.componentsNeedUpdate = True p.add(p2) p.add(net.Uint8(255)) # End of component packets p.add(net.Boolean(self.onFire)) if self.entity.health < self.entity.maxHealth and ( engine.clock.time - self.lastDamage > 4.0 or ( self.entity.getTeam().dock is not None and ( self.entity.getTeam().dock.getPosition() - self.entity.getPosition()).length() < self.entity.getTeam().dock.radius)): self.healthAddition += 60 * engine.clock.timeStep self.entity.health += int(self.healthAddition) self.lastHealthAddition = self.healthAddition self.healthAddition = 0 p.add(net.Int16(self.entity.health)) if self.entity.health <= 0: self.entity.kill(aiWorld, entityGroup, True) return p def actorDamaged(self, entity, damage, ranged): self.healthAddition -= int(damage) def clientUpdate(self, aiWorld, entityGroup, data=None): ObjectController.clientUpdate(self, aiWorld, entityGroup, data) if data is not None: id = net.Uint8.getFrom(data) updatedComponents = [] while id != 255: self.entity.components[id].clientUpdate( aiWorld, entityGroup, data) updatedComponents.append(id) id = net.Uint8.getFrom(data) for id in (x for x in range(len(self.entity.components)) if x not in updatedComponents): self.entity.components[id].clientUpdate(aiWorld, entityGroup) self.onFire = net.Boolean.getFrom(data) self.entity.health = net.Int16.getFrom(data) else: for component in self.entity.components: component.clientUpdate(aiWorld, entityGroup) def delete(self, killed=False): ObjectController.delete(self, killed) class DroidController(ActorController): def __init__(self): ActorController.__init__(self) self.activeWeapon = 0 self.lastActiveWeapon = -1 self.targetPos = Vec3(0, 0, 0) self.torque = 300 self.maxSpeed = 1 self.lastDamage = 0 self.alarmSound = audio.SoundPlayer("alarm") self.lastSentTargetPos = Vec3() self.targetedEnemy = None self.lastTargetedEnemy = None self.lastPosition = None self.onFire = False self.fireTimer = -1 self.lastFireDamage = -1 self.fireEntity = None self.fireParticles = None self.clipCheckCount = 0 def buildSpawnPacket(self): p = ActorController.buildSpawnPacket(self) p.add(net.Uint8(len(self.entity.weaponIds))) for id in self.entity.weaponIds: if id is None: # 255 = None p.add(net.Uint8(255)) else: p.add(net.Uint8(id)) p.add(net.Uint8(255 if self.entity.specialId == None else self.entity.specialId)) p.add(net.Uint8(self.activeWeapon)) return p @staticmethod def readSpawnPacket(aiWorld, entityGroup, iterator, entity=None): entity = ActorController.readSpawnPacket( aiWorld, entityGroup, iterator, entity) numWeapons = net.Uint8.getFrom(iterator) weapons = [] for _ in range(numWeapons): id = net.Uint8.getFrom(iterator) if id == 255: # 255 = None id = None weapons.append(id) entity.setWeapons(weapons) specialId = net.Uint8.getFrom(iterator) if specialId == 255: specialId = None entity.setSpecial(specialId) entity.controller.activeWeapon = net.Uint8.getFrom(iterator) entity.components[entity.controller.activeWeapon].show() return entity def reload(self): weapon = self.entity.components[self.activeWeapon] if isinstance(weapon, components.Gun): weapon.reload() def isReloading(self): weapon = self.entity.components[self.activeWeapon] return isinstance(weapon, components.Gun) and weapon.reloadActive def enableSpecial(self): self.entity.special.enable() def setOnFire(self, entity): self.onFire = True self.fireTimer = engine.clock.time self.fireEntity = entity def setEntity(self, entity): assert isinstance(entity, entities.BasicDroid) ActorController.setEntity(self, entity) def needsToSendUpdate(self): if (self.targetPos - self.lastSentTargetPos).length( ) > 0.2 or ActorController.needsToSendUpdate(self): self.lastSentTargetPos = Vec3(self.targetPos) return True else: return False def serverUpdate(self, aiWorld, entityGroup, packetUpdate): if self.entity.pinned: if engine.clock.time - self.entity.pinTime > 5.0: self.entity.pinned = False self.entity.pinPosition = None self.entity.pinRotation = None else: self.entity.setPosition(self.entity.pinPosition) self.entity.setRotation(self.entity.pinRotation) self.entity.setLinearVelocity(Vec3(0, 0, 0)) if self.entity.special is not None: specialPacket = self.entity.special.serverUpdate( aiWorld, entityGroup, packetUpdate) pos = self.entity.getPosition() if self.lastPosition is None: self.lastPosition = pos else: clipped = False if self.clipCheckCount < 10: # Check to make sure we didn't go through a wall vector = self.entity.getPosition() - self.lastPosition distance = vector.length() if distance > self.entity.radius * 0.9: vector.normalize() queue = aiWorld.getCollisionQueue( self.lastPosition, vector, engine.renderEnvironment) for i in range(queue.getNumEntries()): entry = queue.getEntry(i) collision = entry.getSurfacePoint(render) v = collision - self.lastPosition if v.length() < distance: clipped = True self.entity.setPosition( collision - (vector * self.entity.radius)) self.entity.commitChanges() break if clipped: self.clipCheckCount += 1 else: # We didn't clip this time, so reset the count. self.clipCheckCount = 0 self.lastPosition = self.entity.getPosition() if self.onFire: if engine.clock.time - self.fireTimer > 2.0: self.onFire = False self.fireEntity = None self.fireTimer = -1 elif engine.clock.time - self.lastFireDamage > 0.5: self.lastFireDamage = engine.clock.time self.entity.damage(self.fireEntity, 8, ranged=False) p = ActorController.serverUpdate( self, aiWorld, entityGroup, packetUpdate) p.add(net.Boolean(self.onFire)) if self.activeWeapon != self.lastActiveWeapon: p.add(net.Boolean(True)) p.add(net.Uint8(self.activeWeapon)) self.addCriticalPacket(p, packetUpdate) else: p.add(net.Boolean(False)) p.add(net2.LowResVec3(self.targetPos)) if self.entity.special is not None: p.add(specialPacket) return p def actorDamaged(self, entity, damage, ranged): ActorController.actorDamaged(self, entity, damage, ranged) self.lastDamage = engine.clock.time if self.entity.pinned: self.lastPosition = self.entity.getPosition() def clientUpdate(self, aiWorld, entityGroup, iterator=None): ActorController.clientUpdate(self, aiWorld, entityGroup, iterator) if iterator is not None: self.onFire = net.Boolean.getFrom(iterator) # We're on fire if net.Boolean.getFrom(iterator): if self.lastActiveWeapon != -1: self.entity.components[self.lastActiveWeapon].hide() self.activeWeapon = net.Uint8.getFrom(iterator) self.entity.components[self.activeWeapon].show() self.lastActiveWeapon = self.activeWeapon self.targetPos = net2.LowResVec3.getFrom(iterator) if self.entity.health <= self.entity.maxHealth * 0.15: if not self.alarmSound.isPlaying(): self.alarmSound.play(entity=self.entity) else: self.alarmSound.stop() if self.onFire: if self.fireParticles is None: self.fireParticles = particles.FireParticleGroup( self.entity.getPosition()) particles.add(self.fireParticles) self.fireParticles.setPosition(self.entity.getPosition()) if self.entity.components[self.activeWeapon].reloadActive: self.entity.crosshairNode.show() self.entity.crosshairNode.setR(engine.clock.time * 30) else: self.entity.crosshairNode.hide() if engine.clock.time - self.entity.spawnTime < 4.0: self.entity.setShielded(True) self.entity.initialSpawnShieldEnabled = True elif self.entity.initialSpawnShieldEnabled: self.entity.setShielded(False) self.entity.initialSpawnShieldEnabled = False if self.entity.special is not None: self.entity.special.clientUpdateStart( aiWorld, entityGroup, iterator) def delete(self, killed=False): ActorController.delete(self, killed) self.alarmSound.delete() if self.fireParticles is not None: self.fireParticles.delete() if self.entity.special is not None: self.entity.special.delete() class PlayerController(DroidController): """The PlayerController handles all user input when active. Don't have more than one of these at a time.""" def __init__(self): DroidController.__init__(self) self.keyMap = { "left": False, "right": False, "forward": False, "down": False, "jump": False, "switch-weapon": False, "fire": False, "alternate-action": False, "melee": False, "reload": False, "sprint": False} self.activeWeapon = 1 self.angleX = 0 self.angleY = math.radians(-90) self.inputEnabled = True self.targetPos = Vec3(0, 0, 0) self.lastJump = 0 self.lastCommandTimes = [0, 0] self.commands = [] self.isPlatformMode = False self.zoomed = False self.defaultFov = engine.defaultFov self.fov = self.defaultFov self.desiredFov = self.defaultFov self.currentFov = self.defaultFov self.defaultCameraOffset = Vec3(-1.5, -8, 2.25) self.cameraOffset = Vec3(self.defaultCameraOffset) self.desiredCameraOffset = Vec3(self.defaultCameraOffset) self.currentCameraOffset = Vec3(self.defaultCameraOffset) self.defaultMouseSpeed = 1.0 self.zoomTime = -1 self.totalZoomTime = 0.12 self.currentCrosshair = -1 # Used by GameUI to display the correct cursor self.sprinting = False self.lastSentSprinting = False self.targetDistance = 0 self.lastTargetCheck = 0 def needsToSendUpdate(self): if DroidController.needsToSendUpdate( self) or self.lastSentSprinting != self.sprinting: self.lastSentSprinting = self.sprinting return True else: return False def buildSpawnPacket(self): p = DroidController.buildSpawnPacket(self) p.add(net.String(self.entity.username)) engine.log.debug("Building spawn packet for local player " + self.entity.username + " - ID: " + str(self.entity.getId())) return p @staticmethod def readSpawnPacket(aiWorld, entityGroup, iterator, entity=None): entity = entities.PlayerDroid( aiWorld.world, aiWorld.space, PlayerController(), local=False) entity = DroidController.readSpawnPacket( aiWorld, entityGroup, iterator, entity) entity.getTeam().setPlayer(entity) entity.setUsername(net.String.getFrom(iterator)) engine.log.debug("Spawning remote player " + entity.username + " - ID: " + str(entity.getId())) return entity def setEntity(self, entity): assert isinstance(entity, entities.PlayerDroid) DroidController.setEntity(self, entity) if entity.isLocal: self.mouse = engine.Mouse() self.pickRayNode = CollisionNode("pickRayNode") self.pickRayNP = camera.attachNewNode(self.pickRayNode) self.pickRay = CollisionRay() self.pickRayNode.setIntoCollideMask(BitMask32(0)) self.pickRayNode.setFromCollideMask(BitMask32(1)) self.pickRayNode.addSolid(self.pickRay) self.accept("a", self.setKey, ["left", True]) self.accept("d", self.setKey, ["right", True]) self.accept("w", self.setKey, ["forward", True]) self.accept("s", self.setKey, ["down", True]) self.accept("a-up", self.setKey, ["left", False]) self.accept("d-up", self.setKey, ["right", False]) self.accept("w-up", self.setKey, ["forward", False]) self.accept("s-up", self.setKey, ["down", False]) self.accept("space", self.setKey, ["jump", True]) self.accept("space-up", self.setKey, ["jump", False]) self.accept("tab", self.setKey, ["switch-weapon", True]) self.accept("tab-up", self.setKey, ["switch-weapon", False]) self.accept("mouse1", self.setKey, ["fire", True]) self.accept("mouse1-up", self.setKey, ["fire", False]) self.accept("mouse2", self.setKey, ["alternate-action", True]) self.accept("mouse2-up", self.setKey, ["alternate-action", False]) self.accept("mouse3", self.toggleZoom) self.accept("shift", self.sprint) self.accept("shift-up", self.setKey, ["sprint", False]) self.accept("f", self.setKey, ["melee", True]) self.accept("f-up", self.setKey, ["melee", False]) self.accept("r", self.setKey, ["reload", True]) self.accept("r-up", self.setKey, ["reload", False]) self.accept("q", self.issueCommand, [0]) self.accept("e", self.issueCommand, [1]) self.commandSound = audio.FlatSound("sounds/command.ogg", 0.5) self.sprintSound = audio.FlatSound("sounds/sprint.ogg", 0.5) def sprint(self): if engine.inputEnabled: self.setKey("sprint", True) self.sprintSound.play() def toggleZoom(self): if self.zoomTime == -1 and not self.isPlatformMode: if self.zoomed: self.zoomTime = engine.clock.time self.currentCameraOffset = self.cameraOffset self.currentFov = self.fov self.desiredFov = self.defaultFov self.desiredCameraOffset = self.defaultCameraOffset self.mouse.setSpeed(self.defaultMouseSpeed) self.currentCrosshair = self.entity.components[self.activeWeapon].defaultCrosshair self.zoomed = not self.zoomed elif not self.entity.components[self.activeWeapon].reloadActive: self.zoomTime = engine.clock.time self.currentCameraOffset = self.defaultCameraOffset self.currentFov = self.defaultFov self.desiredFov = self.entity.components[self.activeWeapon].zoomedFov self.desiredCameraOffset = self.entity.components[self.activeWeapon].zoomedCameraOffset self.mouse.setSpeed( self.entity.components[self.activeWeapon].zoomedMouseSpeed) self.currentCrosshair = self.entity.components[self.activeWeapon].zoomedCrosshair self.zoomed = not self.zoomed def setPlatformMode(self, mode): self.isPlatformMode = mode def issueCommand(self, id): if engine.inputEnabled: actors = [x for x in self.entity.getTeam( ).actors if x.teamIndex == id] if len(actors) > 0: actor = actors[0] if engine.clock.time - self.lastCommandTimes[id] < 0.4: # Player double-tapped the key. Special attack. # -1 means special attack self.commands.append((actor.getId(), -1)) elif self.targetedEnemy is not None and self.targetedEnemy.active: # Set the bot's target entity self.commands.append( (actor.getId(), self.targetedEnemy.getId())) else: # No target. Return to the player. self.commands.append((actor.getId(), self.entity.getId())) self.commandSound.play() self.lastCommandTimes[id] = engine.clock.time def setKey(self, key, value): self.keyMap[key] = value and engine.inputEnabled def melee(self): self.entity.components[0].show() self.entity.components[0].fire() def serverUpdate(self, aiWorld, entityGroup, packetUpdate): if self.keyMap["melee"]: if self.zoomed: self.toggleZoom() self.melee() self.keyMap["melee"] = False if self.keyMap["reload"]: if self.zoomed: self.toggleZoom() self.reload() self.keyMap["reload"] = False if self.keyMap["jump"]: if engine.clock.time - self.lastJump > 0.25 and aiWorld.testCollisions( self.entity.collisionNodePath).getNumEntries() > 0: self.lastJump = engine.clock.time self.entity.setLinearVelocity( self.entity.getLinearVelocity() + Vec3(0, 0, 16)) if self.keyMap["switch-weapon"]: self.keyMap["switch-weapon"] = False if self.activeWeapon == 1: self.activeWeapon = 2 else: self.activeWeapon = 1 self.activeWeapon = min( self.activeWeapon, len(self.entity.components) - 1)
that depend on # them for access control if link.left.state not in ('found', link.state): raise MQLInternalError( query, 'Found link in state %(state)s with left in state %(leftstate)s', state=link.state, leftstate=link.left.state) # if we're changing the permission it's legal to talk about has_permission. # but we need to be extraordinarily careful in that case... if link.typeguid == self.lookup_boot_guid('/boot/has_permission', varenv): self.check_change_permission(query, varenv) if link.unique and link.unique in ('left', 'both'): # reverse uniqueness requires the co-operation of the right guid if link.right in (None, Missing): raise MQLInternalError( query, 'Found reverse unique link with empty right') if link.right.state not in ('found', link.state): raise MQLInternalError( query, 'Found link in state %(state)s with right in state %(rightstate)s', state=link.state, leftstate=link.right.state) if not link.right.access_control_ok: # ***************************************************************************************************************** raise MQLAccessError( query, 'User %(user)s does not have permission to connect here', user=varenv.get_user_id()) # ***************************************************************************************************************** # fall through to the usual checks... if link.left.access_control_ok: # this is a bit of a hack since we're in lojson which presumably doesn't know anything about the # schema, but this whole thing needs a rewrite anyway... if hasattr(link.query, 'high_query' ) and link.query.high_query.property.property_permission: perm = link.query.high_query.property.property_permission if scope.check_permission(self, varenv, permissionguid=perm): link.scope = varenv.attribution_guid link.access_control_ok = True else: # ***************************************************************************************************************** raise MQLAccessError( query, 'User %(user)s does not have permission to connect property %(prop)s', user=varenv.get_user_id(), prop=link.query.high_query.property.id) # ***************************************************************************************************************** else: link.scope = varenv.attribution_guid link.access_control_ok = True else: # ***************************************************************************************************************** raise MQLAccessError( query, 'User %(user)s does not have permission to connect here', user=varenv.get_user_id()) # ***************************************************************************************************************** elif link.state in ('found', 'notpresent'): pass else: raise MQLInternalError( query, 'Found link with state %(state)s in check_write_access()', state=link.state) # it's possible to fail on a node if we have versioning. # but we don't have versioning at the moment. if ordered is not Missing: # if we passed on the link, we pass on the ordering if ordered.state in ('create', 'modify'): if ordered.left != link: raise MQLInternalError( query, "Found ordered which does not point to link -- AccessControl can't handle that!" ) if ordered.state in ('create', 'modify') and ordered.guid: raise MQLInternalError( query, 'Found ordered with guid which we are trying to create', guid=ordered.guid) elif ordered.state == 'remove' and not ordered.guid: raise MQLInternalError( query, 'Found ordered without guid which we are trying to remove') # make sure this isn't a side door into has_permission to cause trouble later. if ordered.typeguid == self.lookup_boot_guid('/boot/has_permission', varenv): raise MQLInternalError( query, "Can't reference has_permission during a write regardless of how hard you try" ) # check we would be OK with the link # (we may not have checked the link if it is pre-existing) if ordered.left.left.access_control_ok: ordered.scope = varenv.attribution_guid ordered.access_control_ok = True else: # ***************************************************************************************************************** raise MQLAccessError( query, 'User %(user)s does not have permission to index here', user=varenv.get_user_id()) # ***************************************************************************************************************** elif ordered.state in ('found', 'notpresent'): pass else: # XXX we should handle 'remove' on ordered at some point. raise MQLInternalError( query, 'Found order with state %(state)s in check_write_access()', state=ordered.state) def check_change_permission(self, query, varenv): if not query.link.update: raise MQLInternalError( query, 'You can only update permissions, not insert or delete them') # let's dance around this spot for a little bit - we're currently sitting on the permission. if not query.parent_clause: raise MQLInternalError( query, "Can't change permissions at the root of the query") if query.link.typeguid != self.lookup_boot_guid('/boot/has_permission', varenv): raise MQLInternalError( query, "Can't call check_change_permission except on has_permission") old_permission_guid = query.parent_clause['+has_permission'].node.guid new_permission_guid = query.node.guid if not scope.check_change_permission_by_user( self, varenv, old_permission_guid=old_permission_guid, new_permission_guid=new_permission_guid): # ***************************************************************************************************************** raise MQLAccessError( query, 'User %(user)s cannot change the permission here', user=varenv.get_user_id()) # ***************************************************************************************************************** def check_circularity(self, head_query, varenv): circ_dict = {} for query in elements(head_query, dict): query.node.check_circularity(circ_dict) dumplog('CIRCULARITY_CHECK', circ_dict) def generate_check_responses(self, head_query, varenv): """ Return a list of write queries necessary to make this entire query work. At this point the query is decorated with .prepare objects which contain the things found. """ # for all nodes in the query # if they do not have a .prepare result # start generating a write # if we locate a prepare, stop the write (with an explicit left= or right=) # and recurse from that prepare looking for other writes has_written = False for query in dict_recurse(head_query): write_primitive = None if query.link is not Missing and query.link.state in ('create', 'remove', 'modify'): write_primitive = query.link elif query.node is not Missing and query.node.state in ('create', 'remove'): # if we do not write the (non Missing) link, we never have to write the node write_primitive = query.node elif query.ordered is not Missing and query.ordered.state in ('create', 'modify'): # we may need to write just the order information to the (existing) link write_primitive = query.ordered # did we find something to do? if write_primitive: write_primitive.fake_check_result() def generate_write_queries(self, head_query, varenv): """ Return a list of write queries necessary to make this entire query work. At this point the query is decorated with .prepare objects which contain the things found. """ # for all nodes in the query # if they do not have a .prepare result # start generating a write # if we locate a prepare, stop the write (with an explicit left= or right=) # and recurse from that prepare looking for other writes has_written = False for query in dict_recurse(head_query): write_primitive = None if query.link is not Missing and query.link.state in ('create', 'remove', 'modify'): write_primitive = query.link elif query.node is not Missing and query.node.state in ('create', 'remove'): # if we do not write the (non Missing) link, we never have to write the node write_primitive = query.node elif query.ordered is not Missing and query.ordered.state in ('create', 'modify'): # we may need to write just the order information to the (existing) link write_primitive = query.ordered # did we find something to do? if write_primitive: writeq = write_primitive.generate_write_query() dumplog('WRITE_QUERY', writeq) try: gresult = self.gc.write_varenv(writeq, varenv) has_written = True except MQLGraphError, e: subclass = e.get_kwd('subclass') if subclass == 'EXISTS' and write_primitive.unique == 'key': # must have gotten here due to a race condition in creating a # key in a namespace -- but that's ok, so silently succeed write_primitive.change_state('written') continue elif subclass in ['EXISTS', 'OUTDATED']: # we hit a uniqueness failure! Ick if not has_written: # thankfully this is the first such error; the write can be safely abandoned raise MQLResultError( query, 'Uniqueness check failed (probably this write has already been done)', subclass=subclass) else: # oh dear... LOG.fatal( 'mql.write.unique.fatal.error', 'Write uniqueness failure in half-written request', query=head_query, graph_query=writeq, subclass=e.get_kwd('subclass')) raise MQLResultError( query, 'Write partially complete (locking failure) -- please report this to <EMAIL>', subclass=subclass) else: raise dumplog('WRITE_GRAPH_RESULT', gresult) write_primitive.attach_write_results(gresult) def generate_write_result(self, query, varenv): # make the result look like the query. # uses the % query annotations in create_query_result # note that the result is already structurally isomorphic to the query; this just # converts guids and removes extra fields. if isinstance(query, list): write_result = [] for elem in query: write_result.append(self.generate_write_result(elem, varenv)) elif isinstance(query, dict): write_result = {} for key in query.original_query: if valid_relname(key): write_result[key] = self.generate_write_result(query[key], varenv) elif key[0] in '@:?': asked = query.original_query[key] if key[0] == ':': qp = query.link elif key[0] == '@': qp = query.node elif key[0] == '?': qp = query.ordered if key[1:] == 'update': write_result[key] = (qp.previous is not None) elif key[1:] in QueryPrimitive.writeinsns: # for each write instruction, we output whatever was actually done. write_result[key] = (qp.state == 'written') elif key[1:] == 'id': # handles asked == None correctly write_result[key] = asked if asked is None: varenv.lookup_manager.guid_list.append(qp.guid) elif key[1:] in QueryPrimitive.directives | QueryPrimitive.special: # should we output these? write_result[key] = asked elif key[1:] == 'guid': # handles asked == None correctly write_result[key] = qp.guid elif key[1:] == 'index': write_result[key] = qp.index elif key[1:] == 'value': write_result[key] = self.sanitize_value( getattr(qp, key[1:], None), getattr(qp, 'datatype', None), varenv) elif key[1:] in QueryPrimitive.values: # this better be what you said!!! write_result[key] = getattr(qp, key[1:], None) elif key[1:] in QueryPrimitive.pointers: # might be direct sub-query or constraint, or query if asked is None or isinstance(asked, str): #
display(self, **attr): return self.realWidget().display(**attr) # ------------------------------------------------------------------------- def onaccept(self, value): """ Method to format the value that has just been put on the database """ type = self.get("Type") return self.realWidget().onaccept(value) # ------------------------------------------------------------------------- def getParentType(self): self._store_metadata() return self.get("Type") # ------------------------------------------------------------------------- def getParentQstnID(self): parent = self.get("Parent") query = (self.qtable.code == parent) row = current.db(query).select(limitby=(0, 1)).first() return row.id # ------------------------------------------------------------------------- def fullName(self): return self.question.name # ------------------------------------------------------------------------- def db_type(self): """ Return the real database table type for this question This assumes that the value is valid """ return self.realWidget().db_type() ###################################################################### # Functions not fully implemented or used ###################################################################### def validate(self, valueList, qstn_id): """ This will validate the data passed in to the widget """ result = S3QuestionTypeAbstractWidget.validate(self, valueList) type = self.get("Type") realWidget = survey_question_type[type]() return realWidget.validate(valueList, qstn_id) # ============================================================================= class S3QuestionTypeGridWidget(S3QuestionTypeAbstractWidget): """ Grid widget: Question Type widget provides a widget for the survey module that hold a grid of related questions. Available metadata for this class: Help message: A message to help with completing the question Subtitle: The text for the 1st column and 1st row of the grid QuestionNo: The number of the first question, used for the question code col-cnt: The number of data columns in the grid row-cnt: The number of data rows in the grid columns: An array of headings for each data column rows: An array of headings for each data row data: A matrix of widgets for each data cell """ def __init__(self, question_id = None ): S3QuestionTypeAbstractWidget.__init__(self, question_id) self.metalist.append("Subtitle") self.metalist.append("QuestionNo") self.metalist.append("col-cnt") self.metalist.append("row-cnt") self.metalist.append("columns") self.metalist.append("rows") self.metalist.append("data") self.typeDescription = current.T("Grid") # ------------------------------------------------------------------------- def getMetaData(self, qstn_id=None): self._store_metadata(qstn_id=qstn_id, update=True) self.subtitle = self.get("Subtitle") self.qstnNo = int(self.get("QuestionNo", 1)) self.colCnt = self.get("col-cnt") self.rowCnt = self.get("row-cnt") self.columns = json.loads(self.get("columns")) self.rows = json.loads(self.get("rows")) self.data = json.loads(self.get("data")) # ------------------------------------------------------------------------- def getHeading(self, number): self.getMetaData() col = (number - self.qstnNo) % int(self.colCnt) return self.columns[col] # ------------------------------------------------------------------------- def display(self, **attr): S3QuestionTypeAbstractWidget.display(self, **attr) complete_id = None if "complete_id" in self.question: complete_id = self.question.complete_id self.getMetaData() table = TABLE() if self.data != None: tr = TR(_class="survey_question") if self.subtitle == None: tr.append("") else: tr.append(TH(self.subtitle)) for col in self.columns: if col == None: tr.append("") else: tr.append(TH(col)) table.append(tr) posn = 0 codeNum = self.qstnNo for row in self.data: tr = TR(_class="survey_question") tr.append(TH(self.rows[posn])) for cell in row: if cell == "Blank": tr.append("") else: code = "%s%s" % (self.question["code"], codeNum) codeNum += 1 childWidget = self.getChildWidget(code) if complete_id != None: childWidget.loadAnswer(complete_id, childWidget.id) tr.append(childWidget.subDisplay()) table.append(tr) posn += 1 return TABLE(table, _border=3) # ------------------------------------------------------------------------- def getMatrixSize(self, maxWidth = 20): self._store_metadata() self.getMetaData() width = 0 height = 0 # Add space for the sub heading height = 1 codeNum = self.qstnNo labelWidth = maxWidth/2 for line in range(int(self.rowCnt)): label = survey_T(self.rows[line],self.langDict) (lwidth, lheight) = (labelWidth, len(label)/(4 * labelWidth / 3) + 1) for cell in range(int(self.colCnt)): code = "%s%s" % (self.question["code"], codeNum) codeNum += 1 childWidget = self.getChildWidget(code) type = childWidget.get("Type") realWidget = survey_question_type[type](childWidget.id) (cwidth, cheight) = realWidget.getWidgetSize(maxWidth) lwidth += cwidth if cheight > lheight: lheight = cheight height += lheight if lwidth > width: width = lwidth _debug("%s (%s,%s)" % (self.question["code"], height, width)) self.xlsWidgetSize = (width,height) return (height, width) # ------------------------------------------------------------------------- def writeToMatrix(self, matrix, row, col, langDict=dict(), answerMatrix=None, ): """ Function to write out basic details to the matrix object """ self._store_metadata() self.getMetaData() startrow = row startcol = col endrow = row endcol = col maxWidth = 20 labelWidth = maxWidth / 2 codeNum = self.qstnNo row += 1 needHeading = True # Merge the top left cells subtitle = survey_T(self.subtitle,self.langDict) cell = MatrixElement(startrow, startcol, subtitle, style="styleSubHeader" ) cell.merge(labelWidth - 1,0) matrix.addElement(cell) for line in range(int(self.rowCnt)): # Add the label label = survey_T(self.rows[line],self.langDict) (lwidth, lheight) = (labelWidth, len(label)/(4 * labelWidth / 3) + 1) cell = MatrixElement(row, col, label, style="styleSubHeader" ) cell.merge(lwidth - 1,lheight - 1) matrix.addElement(cell) maxrow = row + lheight endcol = col + lwidth for cell in range(int(self.colCnt)): code = "%s%s" % (self.question["code"], codeNum) codeNum += 1 childWidget = self.getChildWidget(code) type = childWidget.get("Type") realWidget = survey_question_type[type](childWidget.id) realWidget.label = False #realWidget.xlsMargin = (0,0) col = endcol realWidget.startPosn = (col, row) (endrow, endcol) = realWidget.writeToMatrix(matrix, row, col, langDict, answerMatrix ) if endrow > maxrow: maxrow = endrow if needHeading: # Now add the heading for this column label = survey_T(self.columns[cell],self.langDict) cell = MatrixElement(startrow, col, label, style="styleSubHeader" ) cell.merge(endcol - col -1 ,0) matrix.addElement(cell) row = maxrow col = startcol needHeading = False # Add widget padding self.addPaddingToCell(matrix, startrow, startcol, row, endcol) row += self.xlsMargin[1] endcol += self.xlsMargin[0] return (row, endcol) # ------------------------------------------------------------------------- def writeToRTF(self, ss, langDict): """ Function to write the basic question details to a rtf document. This will just display the grid name, following this will be the grid child objects. """ from PyRTF import Paragraph, Cell, B, BorderPS, FramePS thin_edge = BorderPS( width=20, style=BorderPS.SINGLE ) thin_frame = FramePS( thin_edge, thin_edge, thin_edge, thin_edge ) line = [] p = Paragraph(ss.ParagraphStyles.NormalCentre) p.append(B(self.question.name)) line.append(Cell(p, thin_frame, span=2)) return line # ------------------------------------------------------------------------- def insertChildren(self, record, metadata): self.id = record.id self.question = record self.qstn_metadata = metadata self.getMetaData() if self.data != None: posn = 0 qstnNo = self.qstnNo parent_id = self.id parent_code = self.question["code"] for row in self.data: name = self.rows[posn] posn += 1 for cell in row: if cell == "Blank": continue else: type = cell code = "%s%s" % (parent_code, qstnNo) qstnNo += 1 childMetadata = self.get(code) if childMetadata == None: childMetadata = {} else: childMetadata = json.loads(childMetadata) childMetadata["Type"] = type # web2py stomps all over a list so convert back to a string # before inserting it on the database metadata = json.dumps(childMetadata) try: id = self.qtable.insert(name = name, code = code, type = "GridChild", metadata = metadata, ) except: record = self.qtable(code = code) id = record.id record.update_record(name = name, code = code, type = "GridChild", metadata = metadata, ) record = self.qtable(id) current.s3db.survey_updateMetaData(record, "GridChild", childMetadata) # ------------------------------------------------------------------------- def insertChildrenToList(self, question_id, template_id, section_id, qstn_posn): self.getMetaData(question_id) if self.data != None: posn = 0 qstnNo = self.qstnNo qstnPosn = 1 parent_id = self.id parent_code = self.question["code"] for row in self.data: name = self.rows[posn] posn += 1 for cell in row: if cell == "Blank": continue else: code = "%s%s" % (parent_code, qstnNo) qstnNo += 1 record = self.qtable(code = code) id = record.id try: self.qltable.insert(question_id = id, template_id = template_id, section_id = section_id, posn = qstn_posn+qstnPosn, ) qstnPosn += 1 except: pass # already on the database no change required # ------------------------------------------------------------------------- def getChildWidget (self, code): # Get the question from the database query = (self.qtable.code == code) question = current.db(query).select(limitby=(0, 1)).first() if question == None: raise Exception("no question with code %s in database" % code) cellWidget = survey_question_type["GridChild"](question.id) return cellWidget # ============================================================================= class S3QuestionTypeGridChildWidget(S3QuestionTypeAbstractWidget): """ GridChild widget: Question Type widget provides a widget for the survey module that is held by a grid question type an provides a link to the true question type. Available metadata for this class: Type: The type of question it really is (another question type) """ def __init__(self, question_id = None ): T = current.T S3QuestionTypeAbstractWidget.__init__(self, question_id) if self.question != None and "code" in self.question: # Expect the parent code to be the same as the child with the number # removed. This means that the parent code must end with a hyphen. end = self.question.code.rfind("-")+1 parentCode = self.question.code[0:end] parentNumber = self.question.code[end:] self.question.parentCode = parentCode self.question.parentNumber = int(parentNumber) self.metalist.append("Type") self.typeDescription = self.qstn_metadata["Type"] self.xlsWidgetSize = (0, 0) # ------------------------------------------------------------------------- def display(self, **attr): return None # ------------------------------------------------------------------------- def realWidget(self): type = self.get("Type") realWidget = survey_question_type[type]() realWidget.question = self.question realWidget.qstn_metadata = self.qstn_metadata return realWidget # ------------------------------------------------------------------------- def subDisplay(self, **attr): S3QuestionTypeAbstractWidget.display(self, **attr) return self.realWidget().display(question_id=self.id, display = "Control Only") # ------------------------------------------------------------------------- def getParentType(self): self._store_metadata() return self.get("Type") # ------------------------------------------------------------------------- def db_type(self): """ Return the real database table type for this question This assumes that the value is valid """ return self.realWidget().db_type() # ------------------------------------------------------------------------- def writeToMatrix(self, matrix, row, col, langDict=dict(), answerMatrix=None, style={} ): """ Dummy function that doesn't write anything to the matrix, because
self.chaindb.get_canonical_block_header_by_number(block.number, self.wallet_address) if existing_block_header.hash == block.header.hash: self.logger.debug("tried to import a block that has a hash that matches the local block. no import required.") return block else: if not journal_enabled: self.enable_journal_db() journal_record = self.record_journal() journal_enabled = True self.purge_block_and_all_children_and_set_parent_as_chain_head(existing_block_header, save_block_head_hash_timestamp = save_block_head_hash_timestamp) #check to see if this block is chronologically inconsistent - usually due to reward block that used proof from this chain block_hashes_leading_to_inconsistency = self.check_block_chronological_consistency(block) if len(block_hashes_leading_to_inconsistency) > 0: if not allow_replacement: raise ReplacingBlocksNotAllowed("Attempted to import chronologically inconsistent block. Block hashes leading to inconsistency = {}.".format([encode_hex(x) for x in block_hashes_leading_to_inconsistency])) else: # revert all of the blocks leading to the inconsistency. if not journal_enabled: self.enable_journal_db() journal_record = self.record_journal() journal_enabled = True for block_hash in block_hashes_leading_to_inconsistency: self.logger.debug("Purging block {} to preserve chronological consistency".format(encode_hex(block_hash))) block_header = self.chaindb.get_block_header_by_hash(block_hash) # This should be impossible, but lets double check that none of these blocks are on the same chain as this block if block_header.chain_address == block.header.chain_address: raise Exception("Tried to revert chronologically inconsistent block on this same chain. This should never happen...") self.purge_block_and_all_children_and_set_parent_as_chain_head(block_header, save_block_head_hash_timestamp = save_block_head_hash_timestamp) try: return_block = self._import_block(block = block, perform_validation = perform_validation, save_block_head_hash_timestamp = save_block_head_hash_timestamp, allow_unprocessed = allow_unprocessed, ensure_block_unchanged= ensure_block_unchanged, microblock_origin = microblock_origin) # handle importing unprocessed blocks here because doing it recursively results in maximum recursion depth exceeded error if not self.chaindb.is_block_unprocessed(return_block.hash): self.logger.debug("Checking to see if block has unprocessed children") self.import_all_unprocessed_descendants(return_block.hash, perform_validation= True, save_block_head_hash_timestamp = save_block_head_hash_timestamp, allow_unprocessed = True) except Exception as e: if journal_enabled: self.logger.debug('discarding journal') self.discard_journal(journal_record) self.disable_journal_db() raise e if journal_enabled: self.logger.debug('commiting journal') self.commit_journal(journal_record) self.persist_journal() self.disable_journal_db() return return_block def _import_block(self, block: BaseBlock, perform_validation: bool=True, save_block_head_hash_timestamp = True, allow_unprocessed = True, ensure_block_unchanged: bool = True, microblock_origin: bool = False) -> BaseBlock: """ Imports a complete block. """ self.logger.debug("importing block {} with number {}".format(block.__repr__(), block.number)) self.validate_time_from_genesis_block(block) if isinstance(block, self.get_vm(timestamp = block.header.timestamp).get_queue_block_class()): # If it was a queueblock, then the header will have changed after importing perform_validation = False ensure_block_unchanged = False queue_block = True else: queue_block = False if not self.chaindb.is_block_unprocessed(block.header.parent_hash): #this part checks to make sure the parent exists try: vm = self.get_vm(timestamp = block.header.timestamp) self.logger.debug("importing block with vm {}".format(vm.__repr__())) if queue_block: imported_block = vm.import_block(block, private_key = self.private_key) else: imported_block = vm.import_block(block) # Validate the imported block. if ensure_block_unchanged: if microblock_origin: # this started out as a microblock. So we only ensure the microblock fields are unchanged. self.logger.debug('ensuring block unchanged. microblock correction') corrected_micro_block = block.copy(header = block.header.copy( receipt_root = imported_block.header.receipt_root, bloom = imported_block.header.bloom, gas_limit = imported_block.header.gas_limit, gas_used = imported_block.header.gas_used, account_hash = imported_block.header.account_hash, account_balance = imported_block.header.account_balance, )) ensure_imported_block_unchanged(imported_block, corrected_micro_block) else: self.logger.debug('ensuring block unchanged') ensure_imported_block_unchanged(imported_block, block) else: self.logger.debug('Not checking block for changes.') if perform_validation: self.validate_block(imported_block) #self.chain_head_db.set_chain_head_hash(self.wallet_address, imported_block.header.hash) if save_block_head_hash_timestamp: self.chain_head_db.add_block_hash_to_chronological_window(imported_block.header.hash, imported_block.header.timestamp) self.save_chain_head_hash_to_trie_for_time_period(imported_block.header) self.chain_head_db.set_chain_head_hash(imported_block.header.chain_address, imported_block.header.hash) self.chain_head_db.persist(True) self.chaindb.persist_block(imported_block) vm.state.account_db.persist(save_account_hash = True, wallet_address = self.wallet_address) #here we must delete the unprocessed lookup before importing children #because the children cannot be imported if their chain parent is unprocessed. #but we cannot delete the lookup for unprocessed children yet. self.chaindb.remove_block_from_unprocessed(imported_block) # Add chronological consistency lookups self.save_block_chronological_consistency_lookups(imported_block) try: self.header = self.create_header_from_parent(self.get_canonical_head()) except CanonicalHeadNotFound: self.header = self.get_vm_class_for_block_timestamp().create_genesis_block(self.wallet_address).header self.queue_block = None self.logger.debug( 'IMPORTED_BLOCK: number %s | hash %s', imported_block.number, encode_hex(imported_block.hash), ) # Make sure our wallet address hasn't magically changed if self.wallet_address != imported_block.header.chain_address: raise ValidationError("Attempted to import a block onto the wrong chain.") return_block = imported_block except ReceivableTransactionNotFound as e: if not allow_unprocessed: raise UnprocessedBlockNotAllowed() self.logger.debug("Saving block as unprocessed because of ReceivableTransactionNotFound error: {}".format(e)) return_block = self.save_block_as_unprocessed(block) if self.raise_errors: raise e except RewardProofSenderBlockMissing as e: if not allow_unprocessed: raise UnprocessedBlockNotAllowed() self.logger.debug("Saving block as unprocessed because of RewardProofSenderBlockMissing error: {}".format(e)) return_block = self.save_block_as_unprocessed(block) else: if not allow_unprocessed: raise UnprocessedBlockNotAllowed() self.logger.debug("Saving block as unprocessed because parent on this chain is unprocessed") return_block = self.save_block_as_unprocessed(block) return return_block def import_all_unprocessed_descendants(self, block_hash, *args, **kwargs): # 1) get unprocessed children # 2) loop through and import # 3) if child imports, add their unprocessed children to list, and delete that block from unprocessed # 4) if list of unprocessed children has 0 length, break # need to step one level at a time. We use a queue to achieve this effect. It won't get to the next level # until it finishes all of the blocks on this level. So it goes one level at a time. if self.chaindb.has_unprocessed_children(block_hash): self.logger.debug("HAS UNPROCESSED BLOCKS") # try to import all children children_block_hashes = self.chaindb.get_block_children(block_hash) if children_block_hashes != None: block_hashes_to_import = deque(children_block_hashes) # iterate over children while True: # remove from right side current_block_hash_to_import = block_hashes_to_import.pop() if self.chaindb.is_block_unprocessed(current_block_hash_to_import): self.logger.debug("importing child block") try: child_block = self.get_block_by_hash(current_block_hash_to_import) if child_block.header.chain_address != self.wallet_address: #self.logger.debug("Changing to chain with wallet address {}".format(encode_hex(child_block.header.chain_address))) self.set_new_wallet_address(wallet_address=child_block.header.chain_address) self._import_block(child_block, *args, **kwargs) #if the block imported, add its children the the deque if not self.chaindb.is_block_unprocessed(current_block_hash_to_import): # it imported successfully if self.chaindb.has_unprocessed_children(current_block_hash_to_import): children_block_hashes = self.chaindb.get_block_children(current_block_hash_to_import) if children_block_hashes != None: block_hashes_to_import.extendleft(children_block_hashes) # we have queued up its children to be imported. Assuming exceptions don't occur, we can remove this block from the unprocessed children lookup. self.chaindb.delete_unprocessed_children_blocks_lookup(current_block_hash_to_import) except Exception as e: self.logger.error("Tried to import an unprocessed child block and got this error {}".format(e)) if len(block_hashes_to_import) == 0: return self.chaindb.delete_unprocessed_children_blocks_lookup(block_hash) def save_block_chronological_consistency_lookups(self, block: BaseBlock) -> None: ''' We need to require that the proof sender chain doesn't add a block after their claimed chain_head_hash, and the timestamp of this block being imported. :param block: :return: ''' block_header = block.header reward_bundle = self.chaindb.get_reward_bundle(block_header.reward_hash, block.reward_bundle_class) chronological_consistency_key = [block_header.timestamp, block_header.hash] for proof in reward_bundle.reward_type_2.proof: # timestamp, block hash of block responsible sender_chain_header = self.chaindb.get_block_header_by_hash(proof.head_hash_of_sender_chain) # The chronological consistency restrictions are placed on the block on top of the one giving the proof. block_number_with_restrictions = sender_chain_header.block_number + 1 self.logger.debug("saving chronological consistency lookup for chain {}, block {}, timestamp {}".format(encode_hex(sender_chain_header.chain_address), block_number_with_restrictions, block_header.timestamp)) self.chaindb.add_block_consistency_key(sender_chain_header.chain_address, block_number_with_restrictions, chronological_consistency_key) def save_block_as_unprocessed(self, block): #if it is already saved as unprocesessed, do nothing if self.chaindb.is_block_unprocessed(block.hash): return block #before adding to unprocessed blocks, make sure the receive transactions are valid # for receive_transaction in block.receive_transactions: # #there must be at least 1 to get this far # receive_transaction.validate() #now we add it to unprocessed blocks self.chaindb.save_block_as_unprocessed(block) #save the transactions to db vm = self.get_vm(timestamp = block.header.timestamp) vm.save_items_to_db_as_trie(block.transactions, block.header.transaction_root) vm.save_items_to_db_as_trie(block.receive_transactions, block.header.receive_transaction_root) #we don't want to persist because that will add it to the canonical chain. #We just want to save it to the database so we can process it later if needbe. self.chaindb.persist_non_canonical_block(block) #self.chaindb.persist_block(block) try: self.header = self.create_header_from_parent(self.get_canonical_head()) except CanonicalHeadNotFound: self.header = self.get_vm_class_for_block_timestamp().create_genesis_block(self.wallet_address).header self.queue_block = None self.logger.debug( 'SAVED_BLOCK_AS_UNPROCESSED: number %s | hash %s', block.number, encode_hex(block.hash), ) return block def import_current_queue_block(self) -> BaseBlock: return self.import_block(self.queue_block) def import_current_queue_block_with_reward(self, node_staking_score_list: List[NodeStakingScore]) -> BaseBlock: reward_bundle = self.get_consensus_db().create_reward_bundle_for_block(self.wallet_address, node_staking_score_list, at_timestamp=Timestamp(int(time.time()))) # #testing # reward_bundle = reward_bundle.copy(reward_type_2 = reward_bundle.reward_type_2.copy(amount=0)) self.queue_block = self.queue_block.copy(reward_bundle = reward_bundle) return self.import_current_queue_block() def get_all_chronological_blocks_for_window(self, window_timestamp:Timestamp) -> List[BaseBlock]: validate_uint256(window_timestamp, title='timestamp') chronological_blocks = self.chain_head_db.load_chronological_block_window(window_timestamp) if chronological_blocks is None: return None else: list_of_blocks = [] for chronological_block in chronological_blocks: block_hash = chronological_block[1] new_block = self.get_block_by_hash(block_hash) list_of_blocks.append(new_block) return list_of_blocks # # Chronologically consistent blockchain db API # def check_block_chronological_consistency(self, block: BaseBlock) -> List[Hash32]: ''' Checks to see if the block breaks any chronological consistency. If it does, it will return a list of blocks that need to be reverted for this block to be imported returns list of block hashes that have to be reverted :param block: :return: ''' consistency_keys = self.chaindb.get_block_chronological_consistency_keys(block.header.chain_address, block.header.block_number) block_hashes_to_revert = list() for consistency_key in consistency_keys: if consistency_key[0] > block.header.timestamp: block_hashes_to_revert.append(consistency_key[1]) return block_hashes_to_revert # # Validation API # def get_allowed_time_of_next_block(self, chain_address: Address = None) -> Timestamp: if chain_address is None: chain_address = self.wallet_address try: canonical_head = self.chaindb.get_canonical_head(chain_address=chain_address) except CanonicalHeadNotFound: return Timestamp(0) vm = self.get_vm(timestamp=Timestamp(int(time.time()))) min_allowed_time_between_blocks = vm.min_time_between_blocks return Timestamp(canonical_head.timestamp + min_allowed_time_between_blocks) def validate_block(self, block: BaseBlock) -> None: """ Performs validation on a block that is either being mined or imported. Since block validation (specifically the uncle validation must have access to the ancestor blocks, this validation must occur at the Chain level. """ self.validate_gaslimit(block.header) def validate_gaslimit(self, header: BlockHeader) -> None: """ Validate the gas limit on the given header. """ #parent_header =
<filename>EF-SAI-main/codes/Networks/submodules.py import math import torch import torch.nn as nn from torch.nn import init import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ import functools # Channel Attention from CBAM class ChannelAttentionv2(nn.Module): def __init__(self, in_planes, in_planes2, ratio=16, kernel_size=3): super(ChannelAttentionv2, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.conv1 = nn.Sequential(nn.Conv2d(in_planes2*2, 1, kernel_size, padding=kernel_size//2, bias=False), nn.ReLU()) self.conv2 = nn.Sequential(nn.Conv2d(in_planes2, 1, kernel_size, padding=kernel_size//2, bias=False), nn.ReLU()) self.conv3 = nn.Sequential(nn.Conv2d(in_planes2, 1, kernel_size, padding=kernel_size//2, bias=False), nn.ReLU()) #self.conv4 = nn.Sequential(nn.Conv2d(in_planes+1, 1, kernel_size, padding=kernel_size//2, bias=False), nn.ReLU()) #self.conv5 = nn.Sequential(nn.Conv2d(in_planes+1, 1, kernel_size, padding=kernel_size // 2, bias=False),nn.ReLU()) #self.conv6 = nn.Sequential(nn.Conv2d(in_planes+1, 1, kernel_size, padding=kernel_size // 2, bias=False),nn.ReLU()) in_planes3 = in_planes*3+3 self.fc = nn.Sequential(nn.Conv2d(in_planes3, in_planes3 // ratio, 1, bias=False), nn.ReLU(), nn.Conv2d(in_planes3 // ratio, 3, 1, bias=False)) self.sigmoid = nn.Sigmoid() def forward(self, x1, x2, y1, y2, z1, z2): x = self.conv1(x2) x = torch.cat([x1, x], dim=1) # x = self.conv4(x) y = self.conv2(y2) y = torch.cat([y1, y], dim=1) # y = self.conv5(y) z = self.conv3(z2) z = torch.cat([z1, z], dim=1) # z = self.conv6(z) x = torch.cat([x, y, z], dim=1) avg_out = self.fc(self.avg_pool(x)) max_out = self.fc(self.max_pool(x)) out = avg_out + max_out return self.sigmoid(out) #Generator class Identity(nn.Module): def forward(self, x): return x def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == 'batch': momentum = 0.01 norm_layer = functools.partial(nn.BatchNorm2d,momentum = momentum, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'none': def norm_layer(x): return Identity() else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer class ResnetGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from <NAME>'s neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'): """Construct a Resnet-based generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers n_blocks (int) -- the number of ResNet blocks padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero """ assert(n_blocks >= 0) super(ResnetGenerator, self).__init__() if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] n_downsampling = 2 for i in range(n_downsampling): # add downsampling layers mult = 2 ** i model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2 ** n_downsampling for i in range(n_blocks): # add ResNet blocks model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)] for i in range(n_downsampling): # add upsampling layers mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model += [nn.ReflectionPad2d(3)] model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] model += [nn.Tanh()] self.model = nn.Sequential(*model) def forward(self, input): """Standard forward""" return self.model(input) class ResnetBlock(nn.Module): """Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Initialize the Resnet block A resnet block is a conv block with skip connections We construct a conv block with build_conv_block function, and implement skip connections in <forward> function. Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf """ super(ResnetBlock, self).__init__() self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias) def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Construct a convolutional block. Parameters: dim (int) -- the number of channels in the conv layer. padding_type (str) -- the name of padding layer: reflect | replicate | zero norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. use_bias (bool) -- if the conv layer uses bias or not Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU)) """ conv_block = [] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] if use_dropout: conv_block += [nn.Dropout(0.5)] p = 0 if padding_type == 'reflect': conv_block += [nn.ReflectionPad2d(1)] elif padding_type == 'replicate': conv_block += [nn.ReplicationPad2d(1)] elif padding_type == 'zero': p = 1 else: raise NotImplementedError('padding [%s] is not implemented' % padding_type) conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] return nn.Sequential(*conv_block) def forward(self, x): """Forward function (with skip connections)""" out = x + self.conv_block(x) # add skip connections return out class UnetGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer We construct the U-Net from the innermost layer to the outermost layer. It is a recursive process. """ super(UnetGenerator, self).__init__() # construct unet structure unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) # gradually reduce the number of filters from ngf * 8 to ngf unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer def forward(self, input): """Standard forward""" return self.model(input) class UnetSkipConnectionBlock(nn.Module): """Defines the Unet submodule with skip connection. X -------------------identity---------------------- |-- downsampling -- |submodule| -- upsampling --| """ def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet submodule with skip connections. Parameters: outer_nc (int) -- the number of filters in the outer conv layer inner_nc (int) -- the number of filters in the inner conv layer input_nc (int) -- the number of channels in input images/features submodule (UnetSkipConnectionBlock) -- previously defined submodules outermost (bool) -- if this module is the outermost module innermost (bool) -- if this module is the innermost module norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers. """ super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1) down = [downconv] up = [uprelu, upconv, nn.Tanh()] model = down + [submodule] + up elif innermost: upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upconv, upnorm] model = down + up else: upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: # add skip connections return torch.cat([x, self.model(x)], 1) def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name
from __future__ import division, print_function from os.path import join import os import sys import helpers import textwrap import load_data2 as ld2 import match_chips2 as mc2 import report_results2 as rr2 import draw_func2 as df2 import vizualizations as viz import params import itertools import numpy as np import db_info def reload_module(): import imp import sys print('[exp] reloading '+__name__) imp.reload(sys.modules[__name__]) def rrr(): reload_module() def gen_timsubsets(input_set, M, seed=123456): '''generate randomish M-subsets of elements, "far apart" Writen by the <NAME>''' import random from random import sample random.seed(seed) elements = sorted(list(input_set)) allix = set(range(len(elements))) takefrom = allix.copy() def destructive_sample(n): # Remove a random n-subset from takefrom, & return it. s = set(sample(takefrom, n)) takefrom.difference_update(s) return s while True: if len(takefrom) >= M: # Get everything from takefrom. ix = destructive_sample(M) else: # We need to take all of takefrom, and more. ix = takefrom takefrom = allix - ix ix |= destructive_sample(M - len(ix)) assert len(ix) == M yield tuple(sorted([elements[i] for i in ix])) def gen_test_train(input_set, M): 'Generates randomish unique M-subsets, "far apart"' input_set_ = set(input_set) seen_subsets = set([]) timgen = gen_timsubsets(input_set_, M) failsafe = 0 while True: # Generate subset test = timgen.next() # Check if seen before if test in seen_subsets: failsafe += 1 if failsafe > 100000: raise StopIteration('Generator is meant for M << len(input_set)') else: # Mark as seen seen_subsets.add(test) failsafe = 0 train = tuple(sorted(input_set_ - set(test))) yield (test, train) def run_experiment(hs=None, free_mem=False, pprefix='[run_expt]', **kwargs): 'Runs experiment and dumps results. Returns locals={qcx2_res, hs}' ''' import experiments as expt from experiments import * ''' print('** Changing print function with pprefix=%r' % (pprefix,)) def prefix_print(msg): helpers.println(helpers.indent(str(msg), pprefix)) ld2.print = prefix_print df2.print = prefix_print mc2.print = prefix_print rr2.print = prefix_print viz.print = prefix_print # Load a HotSpotter object with just tables if not 'hs' in vars() or hs is None: hs = ld2.HotSpotter() hs.load_tables(ld2.DEFAULT) # because we probably plan to at least draw something hs.load_chips() hs.load_features(load_desc=False) hs.set_samples() # default samples print('======================') print('[expt] Running Experiment on hs:\n'+str(hs.db_name())) #print('[expt] Params: \n'+ helpers.indent(params.param_string())) print('======================') # First load cached results qcx2_res, dirty_samp = mc2.load_cached_matches(hs) if len(dirty_samp) > 0: # Run matching of cached results arent working if hs.matcher is None: print('[expt] !! %d dirty queries force the loading of data.' % len(dirty_samp) ) hs.load_chips() hs.load_features(load_desc=True) hs.load_matcher() # HACK: I need to do this because matcher changes the match_uid # This is really bad and needs to be fixed. No changing the damn # match_uid!!! qcx2_res, dirty_samp = mc2.load_cached_matches(hs) qcx2_res = mc2.run_matching(hs, qcx2_res, dirty_samp) #if free_mem: # Try to free memory before reporting results #hs.free_some_memory() allres = rr2.report_all(hs, qcx2_res, **kwargs) return locals() def oxford_philbin07(hs=None): # philbin params params.__MATCH_TYPE__ = 'bagofwords' params.__BOW_NUM_WORDS__ = [1e4, 2e4, 5e4, 1e6, 1.25e6][3] params.__NUM_RERANK__ = [100, 200, 400, 800, 1000][4] params.__CHIP_SQRT_AREA__ = None params.__XY_THRESH__ = 0.01 #unsure about checks params.BOW_AKMEANS_FLANN_PARAMS = dict(algorithm='kdtree', trees=8, checks=64) if not 'hs' in vars() or hs is None: hs = ld2.HotSpotter() hs.load_tables(ld2.OXFORD) hs.load_chips() hs.load_features(load_desc=False) hs.set_sample_split_pos(55) # Use the 55 cannonical test cases expt_locals = run_experiment(hs, pprefix='[philbin]', oxford=True) return expt_locals def oxford_bow(): params.__MATCH_TYPE__ = 'bagofwords' params.__CHIP_SQRT_AREA__ = None params.__BOW_NUM_WORDS__ = [1e4, 2e4, 5e4, 1e6, 1.25e6][3] db_dir = ld2.OXFORD if not 'hs' in vars() or hs is None: hs = ld2.HotSpotter() hs.load_tables(ld2.OXFORD) hs.load_chips() hs.load_features(load_desc=False) hs.set_sample_range(55, None) # Use only database images assert min(hs.test_sample_cx) == 55 and max(hs.test_sample_cx) == 5117 expt_locals = run_experiment(hs, pprefix='[ox-bow]', free_mem=True, oxford=False, stem=False, matrix=False) return expt_locals def oxford_vsmany(): params.__MATCH_TYPE__ = 'vsmany' params.__CHIP_SQRT_AREA__ = None db_dir = ld2.OXFORD if not 'hs' in vars() or hs is None: hs = ld2.HotSpotter() hs.load_tables(ld2.OXFORD) hs.load_chips() hs.load_features(load_desc=False) hs.set_sample_range(55, None) # Use only database images hs = ld2.HotSpotter(db_dir, samples_range=(55,None)) expt_locals = run_experiment(hs, pprefix='[ox-vsmany]', free_mem=True, oxford=False, stem=False, matrix=False) return locals() def far_appart_splits(input_set, M, K): split_list = [] gen = gen_test_train(input_set, M) for kx in xrange(K): (test, train) = gen.next() split_list.append((test,train)) return split_list def split_nx2_cxs(test_cxs_list, csplit_size): for ix in xrange(len(test_cxs_list)): cxs = test_cxs_list[ix] num_csplits = len(cxs)//csplit_size cxs_splits = far_appart_splits(cxs, csplit_size, num_csplits) test_cx_splits.append(cxs_splits) max_num_csplits = max(map(len, test_cx_splits)) # Put them into experiment sets jx2_test_cxs = [[] for _ in xrange(max_num_csplits)] jx2_index_cxs = [[] for _ in xrange(max_num_csplits)] for ix in xrange(len(test_cx_splits)): cxs_splits = test_cx_splits[ix] for jx in xrange(max_num_csplits): if jx >= len(cxs_splits): break #ix_test_cxs, ix_index_cxs = cxs_splits[jx] ix_index_cxs, ix_test_cxs = cxs_splits[jx] jx2_test_cxs[jx].append(ix_test_cxs) jx2_index_cxs[jx].append(ix_index_cxs) return jx2_test_cxs, jx2_index_cxs def leave_out(expt_func=None, split_test=False, **kwargs): ''' do with TF-IDF on the zebra data set. Let M be the total number of *animals* (not images and not chips) in an experimental data set. Do a series of leave-M-out (M >= 1) experiments on the TF-IDF scoring, where the "left out" M are M different zebras, so that there are no images of these zebras in the images used to form the vocabulary. The vocabulary is formed from the remaining N-M animals. Test how well TF-IDF recognition does with these M animals. Repeat for different subsets of M animals. import experiments as expt from experiments import * ''' # --- # Testing should have animals I have seen and animals I haven't seen. # Make sure num descriptors -per- word is about the same as Oxford # --- # Notes from Monday: # 1) Larger training set (see how animals in training do vs animals out of training) # 2) More detailed analysis of failures # 3) Aggregate scores across different pictures of the same animal if not 'expt_func' in vars() or expt_func is None: expt_func = run_experiment # Load tables hs = ld2.HotSpotter(ld2.DEFAULT, load_basic=True) # Grab names db_names_info = db_info.get_db_names_info(hs) nx2_cxs = db_names_info['nx2_cxs'] valid_nxs = db_names_info['valid_nxs'] multiton_nxs = db_names_info['multiton_nxs'] # How to generate samples/splits for names num_nsplits = 5 nsplit_size = (db_names_info['num_names_with_gt']//num_nsplits) # How to generate samples/splits for chips csplit_size = 1 # number of indexed chips per Jth experiment # Generate name splits kx2_name_split = far_appart_splits(multiton_nxs, nsplit_size, num_nsplits) result_map = {} kx = 0 # run K experiments all_cxs = np.hstack(nx2_cxs[list(valid_nxs)]) for kx in xrange(num_nsplits): print('***************') print('[expt] Leave M=%r names out iteration: %r/%r' % (nsplit_size, kx+1, num_nsplits)) print('***************') # Get name splits (test_nxs, train_nxs) = kx2_name_split[kx] # Lock in TRAIN sample train_cxs_list = nx2_cxs[list(train_nxs)] train_samp = np.hstack(train_cxs_list) # Generate chip splits test_cxs_list = nx2_cxs[list(test_nxs)] test_nChip = map(len, test_cxs_list) print('[expt] testnames #cxs stats: %r' % helpers.printable_mystats(test_nChip)) test_cx_splits = [] if not split_test: # Chucks version of the test (much simplier and better) indx_samp = all_cxs train_samp = train_samp test_samp = all_cxs hs.set_samples(test_samp, train_samp, indx_samp) m_label = '[LNO: %r/%r]' % (kx+1, num_nsplits) expt_locals = expt_func(hs, pprefix=m_label, **kwargs) #result_map[kx] = expt_locals['allres'] return locals() ''' elif split_test: jx = 0 jx2_test_cxs, jx2_index_cxs = split_nx2_cxs(test_cxs_list, csplit_size) for jx in xrange(max_num_csplits): # run K*J experiments # Lock in TEST and INDEX set # INDEX the TRAIN set and a subset of the NOT-TRAIN set # TEST chips which have a groundtruth in the INDEX set indx_samp = np.hstack(jx2_index_cxs[jx]+[train_samp]) test_samp = hs.get_valid_cxs_with_name_in_samp(indx_samp) hs.set_samples(test_samp, train_samp, indx_samp) mj_label = '[LNO:%r/%r;%r/%r]' % (kx+1, num_nsplits, jx+1, max_num_csplits) print('[expt] =================') print('[expt] M=%r, J=%r' % (nsplit_size,csplit_size)) expt_locals = expt_func(hs, pprefix=mj_label, **kwargs) #result_map[kx] = expt_locals['allres'] ''' def tweak_params(expt_func=None): if not 'expt_func' in vars() or expt_func is None: expt_func = run_experiment xy_thresh_tweaks = [.05, .01, .005, .001] scale_low_tweaks = [.75, .5, .25] scale_high_tweaks = [1.5, 2, 8] gen_ = itertools.product(xy_thresh_tweaks, scale_high_tweaks, scale_low_tweaks) parameter_list = [tup for tup in gen_] total_tests = len(parameter_list) result_map = {} hs = None for count, tup in enumerate(parameter_list): print('**********************************************************') print('**********************************************************') print('========================') print('[expt] tweak_params(%d/%d)> param tweak %r ' % (count, total_tests, tup,)) print('========================') rss = helpers.RedirectStdout() rss.start() xy_thresh, scale_thresh_high, scale_thresh_low = tup params.__XY_THRESH__ = xy_thresh params.__SCALE_THRESH_LOW__ = scale_thresh_low params.__SCALE_THRESH_HIGH__ = scale_thresh_high expt_locals = expt_func(hs) if 'hs' in expt_locals: hs = expt_locals['hs'] result_map[tup] = expt_locals['allres'] rss.stop() return locals() def tweak_params_philbin(): return tweak_params(oxford_philbin07) if __name__ == '__main__': from multiprocessing import freeze_support freeze_support() print('\n\n\n[expt] __main__ = experiments.py') print('[expt] sys.argv = %r' % sys.argv) # Default to run_experiment expt_func = run_experiment arg_map = { 'philbin' : oxford_philbin07, 'oxford-bow' : oxford_bow, 'oxford-vsmany' : oxford_vsmany, 'default' : run_experiment, 'tweak' : tweak_params, 'tweak-philbin' : tweak_params_philbin, 'leave-out' : leave_out} print
从设备范围和地图范围构造""" _gskernel.GsDisplayTransformation_swiginit(self, _gskernel.new_GsDisplayTransformation(mapExtent, deviceExtent)) __swig_destroy__ = _gskernel.delete_GsDisplayTransformation def SpatialReference(self, *args) -> "void": r""" *Overload 1:* 当前空间参考 | *Overload 2:* 设置当前空间参考 """ return _gskernel.GsDisplayTransformation_SpatialReference(self, *args) def MapExtent(self, *args) -> "void": r""" *Overload 1:* 地图范围 | *Overload 2:* 设置地图范围 """ return _gskernel.GsDisplayTransformation_MapExtent(self, *args) def DPI(self, *args) -> "void": r""" *Overload 1:* 设备分辨率 | *Overload 2:* 设置设备分辨率 """ return _gskernel.GsDisplayTransformation_DPI(self, *args) def Resolution(self, *args) -> "void": r""" *Overload 1:* 地图分辨率 | *Overload 2:* 设置地图分辨率 """ return _gskernel.GsDisplayTransformation_Resolution(self, *args) def DeviceExtent(self, *args) -> "void": r""" *Overload 1:* 设备范围 | *Overload 2:* 设置范围 """ return _gskernel.GsDisplayTransformation_DeviceExtent(self, *args) def ToMap(self, *args) -> "void": r""" *Overload 1:* 转换设备坐标到地图坐标 | *Overload 2:* 转换设备坐标到地图坐标 | *Overload 3:* 转换设备坐标到地图坐标 | *Overload 4:* 转换设备坐标到地图坐标 """ return _gskernel.GsDisplayTransformation_ToMap(self, *args) def FromMap(self, *args) -> "void": r""" *Overload 1:* 转换地图坐标到设备坐标 | *Overload 2:* 转换地图坐标到设备坐标 | *Overload 3:* 转换地图坐标到设备坐标 | *Overload 4:* 转换地图坐标到设备坐标 """ return _gskernel.GsDisplayTransformation_FromMap(self, *args) def FromPageMeasure(self, u: 'GsUnits', dblLen: 'double') -> "double": r""" 从纸面单位长度转换为像素单位长度""" return _gskernel.GsDisplayTransformation_FromPageMeasure(self, u, dblLen) def Scale(self, *args) -> "void": r""" *Overload 1:* 获取比例尺分母的值 | *Overload 2:* 设置比例尺的值 """ return _gskernel.GsDisplayTransformation_Scale(self, *args) def ReferenceScale(self, *args) -> "void": r""" *Overload 1:* 获取参考比例尺 | *Overload 2:* 设置参考比例尺 """ return _gskernel.GsDisplayTransformation_ReferenceScale(self, *args) def Matrix(self) -> "GsMatrixT< float >": r""" 地图到屏幕的转换矩阵 屏幕到地图的转换矩阵可以通过矩阵Invert获得。""" return _gskernel.GsDisplayTransformation_Matrix(self) # Register GsDisplayTransformation in _gskernel: _gskernel.GsDisplayTransformation_swigregister(GsDisplayTransformation) eUnknownFormat = _gskernel.eUnknownFormat r""" 未知的空间参考定义格式""" eWktFormat = _gskernel.eWktFormat r""" 标准WKT格式""" eXMLFormat = _gskernel.eXMLFormat r""" XML格式""" eProj4Format = _gskernel.eProj4Format r""" proj.4格式""" eESRIWktFormat = _gskernel.eESRIWktFormat r""" ESRI的Wkt格式""" eGeoStar5Format = _gskernel.eGeoStar5Format r""" GeoStar5以逗号分隔的空间参考描述格式。""" eWGS84 = _gskernel.eWGS84 r""" WGS84空间参考""" eCGCS2000 = _gskernel.eCGCS2000 r""" CGCS2000空间参考""" eWebMercator = _gskernel.eWebMercator r""" web墨卡托空间参考""" eUnknownUnit = _gskernel.eUnknownUnit r""" 未知单位""" eMeter = _gskernel.eMeter r""" 米""" eFoot = _gskernel.eFoot r""" foot 1 ft = 0.3048 m""" eUSSurveyFoot = _gskernel.eUSSurveyFoot r"""US survey foot 1 USft = 0.30480060960122 m""" eClarkeFoot = _gskernel.eClarkeFoot r""" Clarke's foot 其与米之前的转换关系 1 Clarke's foot = 0.3047972654 m""" eGermanMetre = _gskernel.eGermanMetre r""" German legal metre,1 German legal metre= 1.0000135965 m""" eIndianFoot = _gskernel.eIndianFoot r""" Indian foot,Indian Foot = 0.99999566 British feet (A.R.Clarke 1865). British yard (= 3 British feet) taken to be J.S.Clark's 1865 value of 0.9144025 metres.""" eSexagesimalDMS = _gskernel.eSexagesimalDMS r""" sexagesimal DMS""" eDegree = _gskernel.eDegree r""" 度""" eUnity = _gskernel.eUnity r""" Unity""" eMM = _gskernel.eMM r""" 毫米""" eInch = _gskernel.eInch r""" 英寸""" eCM = _gskernel.eCM r""" 厘米""" eKM = _gskernel.eKM r""" 千米""" eMile = _gskernel.eMile r""" 英里""" eNatuicalMile = _gskernel.eNatuicalMile ePoint = _gskernel.ePoint eOther = _gskernel.eOther r""" 不确定方向""" eNorth = _gskernel.eNorth r""" 朝北""" eSouth = _gskernel.eSouth r""" 朝南""" eEast = _gskernel.eEast r""" 朝东""" eWest = _gskernel.eWest r""" 朝西""" eUp = _gskernel.eUp r""" 朝上""" eDown = _gskernel.eDown r""" 朝下""" eUnknown = _gskernel.eUnknown r""" 不确定""" eLat = _gskernel.eLat r""" 纬度""" eLong = _gskernel.eLong r""" 经度""" eX = _gskernel.eX r""" X""" eY = _gskernel.eY r""" Y""" eE = _gskernel.eE r""" E""" eN = _gskernel.eN r""" N""" class GsCoordinateSystem(object): r""" 坐标系信息""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr ID = property(_gskernel.GsCoordinateSystem_ID_get, _gskernel.GsCoordinateSystem_ID_set, doc=r""" 坐标系的编号""") Name = property(_gskernel.GsCoordinateSystem_Name_get, _gskernel.GsCoordinateSystem_Name_set, doc=r""" 坐标系的名称""") Type = property(_gskernel.GsCoordinateSystem_Type_get, _gskernel.GsCoordinateSystem_Type_set, doc=r""" 坐标系的类型""") Dim = property(_gskernel.GsCoordinateSystem_Dim_get, _gskernel.GsCoordinateSystem_Dim_set, doc=r""" 坐标系的维度""") InformationSource = property(_gskernel.GsCoordinateSystem_InformationSource_get, _gskernel.GsCoordinateSystem_InformationSource_set, doc=r""" 坐标系的信息来源""") DataSource = property(_gskernel.GsCoordinateSystem_DataSource_get, _gskernel.GsCoordinateSystem_DataSource_set, doc=r""" 坐标系的数据来源""") def __init__(self): _gskernel.GsCoordinateSystem_swiginit(self, _gskernel.new_GsCoordinateSystem()) __swig_destroy__ = _gskernel.delete_GsCoordinateSystem # Register GsCoordinateSystem in _gskernel: _gskernel.GsCoordinateSystem_swigregister(GsCoordinateSystem) class GsCoordinateAxis(object): r""" 坐标轴信息""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr CoordinateSystemID = property(_gskernel.GsCoordinateAxis_CoordinateSystemID_get, _gskernel.GsCoordinateAxis_CoordinateSystemID_set, doc=r""" 坐标系的编号""") ID = property(_gskernel.GsCoordinateAxis_ID_get, _gskernel.GsCoordinateAxis_ID_set, doc=r""" 坐标轴的编号""") Orientation = property(_gskernel.GsCoordinateAxis_Orientation_get, _gskernel.GsCoordinateAxis_Orientation_set, doc=r""" 坐标轴的方向""") Name = property(_gskernel.GsCoordinateAxis_Name_get, _gskernel.GsCoordinateAxis_Name_set, doc=r""" 坐标轴的名称""") Abbreviation = property(_gskernel.GsCoordinateAxis_Abbreviation_get, _gskernel.GsCoordinateAxis_Abbreviation_set, doc=r""" 坐标轴名称的缩写""") UnitID = property(_gskernel.GsCoordinateAxis_UnitID_get, _gskernel.GsCoordinateAxis_UnitID_set, doc=r""" 坐标轴单位的编号""") Order = property(_gskernel.GsCoordinateAxis_Order_get, _gskernel.GsCoordinateAxis_Order_set, doc=r""" 坐标轴的顺序""") def __init__(self): _gskernel.GsCoordinateAxis_swiginit(self, _gskernel.new_GsCoordinateAxis()) __swig_destroy__ = _gskernel.delete_GsCoordinateAxis # Register GsCoordinateAxis in _gskernel: _gskernel.GsCoordinateAxis_swigregister(GsCoordinateAxis) class GsEllipsoid(object): r""" 椭球信息""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr ID = property(_gskernel.GsEllipsoid_ID_get, _gskernel.GsEllipsoid_ID_set, doc=r""" 椭球的编号""") Name = property(_gskernel.GsEllipsoid_Name_get, _gskernel.GsEllipsoid_Name_set, doc=r""" 椭球的名称""") EquatorialRadiusA = property(_gskernel.GsEllipsoid_EquatorialRadiusA_get, _gskernel.GsEllipsoid_EquatorialRadiusA_set, doc=r""" 椭球的长半轴""") PolarRadiusB = property(_gskernel.GsEllipsoid_PolarRadiusB_get, _gskernel.GsEllipsoid_PolarRadiusB_set, doc=r""" 椭球的短半轴""") FlattenInverseF = property(_gskernel.GsEllipsoid_FlattenInverseF_get, _gskernel.GsEllipsoid_FlattenInverseF_set, doc=r""" 椭球的扁率的倒数 扁率 = (长半轴-短半轴)/长半轴""") UnitID = property(_gskernel.GsEllipsoid_UnitID_get, _gskernel.GsEllipsoid_UnitID_set, doc=r""" 椭球的单位编号,此处指长半轴、短半轴的单位""") InformationSource = property(_gskernel.GsEllipsoid_InformationSource_get, _gskernel.GsEllipsoid_InformationSource_set, doc=r""" 椭球的信息来源""") DataSource = property(_gskernel.GsEllipsoid_DataSource_get, _gskernel.GsEllipsoid_DataSource_set, doc=r""" 椭球的数据来源""") def __init__(self): _gskernel.GsEllipsoid_swiginit(self, _gskernel.new_GsEllipsoid()) __swig_destroy__ = _gskernel.delete_GsEllipsoid # Register GsEllipsoid in _gskernel: _gskernel.GsEllipsoid_swigregister(GsEllipsoid) class GsDatum(object): r""" 基准面""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr ID = property(_gskernel.GsDatum_ID_get, _gskernel.GsDatum_ID_set, doc=r""" 基准面编号""") EllipsoidID = property(_gskernel.GsDatum_EllipsoidID_get, _gskernel.GsDatum_EllipsoidID_set, doc=r""" 基准面对应的椭球编号""") Name = property(_gskernel.GsDatum_Name_get, _gskernel.GsDatum_Name_set, doc=r""" 基准面名称""") Type = property(_gskernel.GsDatum_Type_get, _gskernel.GsDatum_Type_set, doc=r""" 基准面类型""") PrimaryMeridianID = property(_gskernel.GsDatum_PrimaryMeridianID_get, _gskernel.GsDatum_PrimaryMeridianID_set, doc=r""" 基准面主午线ID""") InformationSource = property(_gskernel.GsDatum_InformationSource_get, _gskernel.GsDatum_InformationSource_set, doc=r""" 基准面信息来源""") DataSource = property(_gskernel.GsDatum_DataSource_get, _gskernel.GsDatum_DataSource_set, doc=r""" 基准面数据来源""") Exist7parameters = property(_gskernel.GsDatum_Exist7parameters_get, _gskernel.GsDatum_Exist7parameters_set, doc=r""" 基准面是否存在7参数""") ShiftX = property(_gskernel.GsDatum_ShiftX_get, _gskernel.GsDatum_ShiftX_set, doc=r""" 基准面7参数:在x轴上,将椭球中心相对于WGS 84椭球中心相对移动的米数""") ShiftY = property(_gskernel.GsDatum_ShiftY_get, _gskernel.GsDatum_ShiftY_set, doc=r""" 基准面7参数:在Y轴上,将椭球中心相对于WGS 84椭球中心相对移动的米数""") ShiftZ = property(_gskernel.GsDatum_ShiftZ_get, _gskernel.GsDatum_ShiftZ_set, doc=r""" 基准面7参数:在z轴上,将椭球中心相对于WGS 84椭球中心相对移动的米数""") RotateX = property(_gskernel.GsDatum_RotateX_get, _gskernel.GsDatum_RotateX_set, doc=r""" 基准面7参数:绕x轴旋转的弧秒数。""") RotateY = property(_gskernel.GsDatum_RotateY_get, _gskernel.GsDatum_RotateY_set, doc=r""" 基准面7参数:绕Y轴旋转的弧秒数。""") RotateZ = property(_gskernel.GsDatum_RotateZ_get, _gskernel.GsDatum_RotateZ_set, doc=r""" 基准面7参数:绕Z轴旋转的弧秒数。""") ScaleAdjust = property(_gskernel.GsDatum_ScaleAdjust_get, _gskernel.GsDatum_ScaleAdjust_set, doc=r""" 基准面7参数:调整参数。""") def __init__(self): _gskernel.GsDatum_swiginit(self, _gskernel.new_GsDatum()) __swig_destroy__ = _gskernel.delete_GsDatum # Register GsDatum in _gskernel: _gskernel.GsDatum_swigregister(GsDatum) class GsCoordinateReferenceSystem(object): r""" 坐标参考系统信息""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr ID = property(_gskernel.GsCoordinateReferenceSystem_ID_get, _gskernel.GsCoordinateReferenceSystem_ID_set, doc=r""" 坐标参考系统编号""") Name = property(_gskernel.GsCoordinateReferenceSystem_Name_get, _gskernel.GsCoordinateReferenceSystem_Name_set, doc=r""" 坐标参考系统名称""") Type = property(_gskernel.GsCoordinateReferenceSystem_Type_get, _gskernel.GsCoordinateReferenceSystem_Type_set, doc=r""" 坐标参考系统类型""") CoordinateSystemID = property(_gskernel.GsCoordinateReferenceSystem_CoordinateSystemID_get, _gskernel.GsCoordinateReferenceSystem_CoordinateSystemID_set, doc=r""" 坐标系编号""") DatumID = property(_gskernel.GsCoordinateReferenceSystem_DatumID_get, _gskernel.GsCoordinateReferenceSystem_DatumID_set, doc=r""" 椭球编号""") GeographicDatumID = property(_gskernel.GsCoordinateReferenceSystem_GeographicDatumID_get, _gskernel.GsCoordinateReferenceSystem_GeographicDatumID_set, doc=r""" 基础地理坐标系的椭球编号""") InformationSource = property(_gskernel.GsCoordinateReferenceSystem_InformationSource_get, _gskernel.GsCoordinateReferenceSystem_InformationSource_set, doc=r""" 坐标参考系统信息来源""") DataSource = property(_gskernel.GsCoordinateReferenceSystem_DataSource_get, _gskernel.GsCoordinateReferenceSystem_DataSource_set, doc=r""" 坐标参考系统数据来源""") def __init__(self): _gskernel.GsCoordinateReferenceSystem_swiginit(self, _gskernel.new_GsCoordinateReferenceSystem()) __swig_destroy__ = _gskernel.delete_GsCoordinateReferenceSystem # Register GsCoordinateReferenceSystem in _gskernel: _gskernel.GsCoordinateReferenceSystem_swigregister(GsCoordinateReferenceSystem) class GsCoordinateConversionsRule(object): r""" 坐标转换规则""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr Name = property(_gskernel.GsCoordinateConversionsRule_Name_get, _gskernel.GsCoordinateConversionsRule_Name_set, doc=r""" 坐标转换规则名称""") Type = property(_gskernel.GsCoordinateConversionsRule_Type_get, _gskernel.GsCoordinateConversionsRule_Type_set, doc=r""" 坐标转换规则类型""") ID = property(_gskernel.GsCoordinateConversionsRule_ID_get, _gskernel.GsCoordinateConversionsRule_ID_set, doc=r""" 坐标转换规则编号""") def __init__(self): _gskernel.GsCoordinateConversionsRule_swiginit(self, _gskernel.new_GsCoordinateConversionsRule()) __swig_destroy__ = _gskernel.delete_GsCoordinateConversionsRule # Register GsCoordinateConversionsRule in _gskernel: _gskernel.GsCoordinateConversionsRule_swigregister(GsCoordinateConversionsRule) class GsCoordinateConversionsParameter(object): r""" 坐标转换参数信息""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr Name = property(_gskernel.GsCoordinateConversionsParameter_Name_get, _gskernel.GsCoordinateConversionsParameter_Name_set, doc=r""" 坐标转换参数名称""") CoordinateConversionsRuleID = property(_gskernel.GsCoordinateConversionsParameter_CoordinateConversionsRuleID_get, _gskernel.GsCoordinateConversionsParameter_CoordinateConversionsRuleID_set, doc=r""" 坐标转换规则编号""") ID = property(_gskernel.GsCoordinateConversionsParameter_ID_get, _gskernel.GsCoordinateConversionsParameter_ID_set, doc=r""" 坐标转换参数编号""") Value = property(_gskernel.GsCoordinateConversionsParameter_Value_get, _gskernel.GsCoordinateConversionsParameter_Value_set, doc=r""" 坐标转换参数值""") UnitID = property(_gskernel.GsCoordinateConversionsParameter_UnitID_get, _gskernel.GsCoordinateConversionsParameter_UnitID_set, doc=r""" 坐标转换参数单位编号""") def __init__(self): _gskernel.GsCoordinateConversionsParameter_swiginit(self, _gskernel.new_GsCoordinateConversionsParameter()) __swig_destroy__ = _gskernel.delete_GsCoordinateConversionsParameter # Register GsCoordinateConversionsParameter in _gskernel: _gskernel.GsCoordinateConversionsParameter_swigregister(GsCoordinateConversionsParameter) class GsSpatialReference(GsRefObject): r""" 空间参考""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr __swig_destroy__ = _gskernel.delete_GsSpatialReference def __init__(self, *args): r""" *Overload 1:* 从已知的空间参考类型构造 | *Overload 2:* 从字符串和指定类型进行构造 | *Overload 3:* 从字符串和指定类型进行构造 | *Overload 4:* 从EPSG编号构造 """ _gskernel.GsSpatialReference_swiginit(self, _gskernel.new_GsSpatialReference(*args)) def Name(self, *args) -> "void": r""" *Overload 1:* 空间参考的名称 | *Overload 2:* 空间参考的名称 """ return _gskernel.GsSpatialReference_Name(self, *args) def Units(self) -> "GsUnits": r""" 坐标单位""" return _gskernel.GsSpatialReference_Units(self) def ExportToWKT(self, bPretty: 'bool'=False) -> "GsString": r""" 坐标单位""" return _gskernel.GsSpatialReference_ExportToWKT(self, bPretty) def ExportToXml(self) -> "GsString": r""" 以XML的格式输出""" return _gskernel.GsSpatialReference_ExportToXml(self) def ExportToProj4(self) -> "GsString": r""" 以Proj4的格式输出""" return _gskernel.GsSpatialReference_ExportToProj4(self) def IsNull(self) -> "bool": r""" 是否为空""" return _gskernel.GsSpatialReference_IsNull(self) def IsSame(self, sr: 'GsSpatialReference') -> "bool": r""" 是否是相同的坐标系""" return _gskernel.GsSpatialReference_IsSame(self, sr) def IsSameProjCS(self, sr: 'GsSpatialReference') -> "bool": r""" 是否是相同的投影坐标系""" return _gskernel.GsSpatialReference_IsSameProjCS(self, sr) def IsSameGeogCS(self, sr: 'GsSpatialReference') -> "bool": r""" 是否是相同的地理坐标系""" return _gskernel.GsSpatialReference_IsSameGeogCS(self, sr) def IsSameParameter(self, sr: 'GsSpatialReference') -> "bool": r""" 是否是相同的空间参数,可以作为空间参考是否相同的依据,但不绝对""" return _gskernel.GsSpatialReference_IsSameParameter(self, sr) def IsLocalCS(self) -> "bool": r""" 是否是本地坐标系""" return _gskernel.GsSpatialReference_IsLocalCS(self) def IsGeographic(self) -> "bool": r""" 是否是地理坐标系""" return _gskernel.GsSpatialReference_IsGeographic(self) def IsProjected(self) -> "bool": r""" 是否是投影坐标系""" return _gskernel.GsSpatialReference_IsProjected(self) def Geographic(self) -> "GsSmarterPtr< GsSpatialReference >": return _gskernel.GsSpatialReference_Geographic(self) def EquatorialRadiusA(self) -> "double": r""" 椭球长半轴(公里 km)""" return _gskernel.GsSpatialReference_EquatorialRadiusA(self) def PolarRadiusB(self) -> "double": r""" 椭球短半轴(公里 km)""" return _gskernel.GsSpatialReference_PolarRadiusB(self) def FlattenInverseF(self) -> "double": r""" 椭球扁率的倒数""" return _gskernel.GsSpatialReference_FlattenInverseF(self) def MeanRadius(self) -> "double": r""" 椭球平均半径(公里 km)""" return _gskernel.GsSpatialReference_MeanRadius(self) def EPSG(self) -> "int": r""" EPSG""" return _gskernel.GsSpatialReference_EPSG(self) def Ellipsoid(self) -> "GsString": r""" 椭球名称""" return _gskernel.GsSpatialReference_Ellipsoid(self) def Projection(self) -> "GsString": r""" 投影名称""" return _gskernel.GsSpatialReference_Projection(self) def Axis(self, i: 'int', peOrientation: 'GsAxisOrientation *') -> "GsString": r""" 获取坐标轴的方向信息 :type i: int :param i: 坐标轴的顺序(0或者1) :type peOrientation: int :param peOrientation: 输出坐标轴的方向 :rtype: :py:class:`GsString` :return: 返回坐标轴的名称,无效则为空字符串 """ return _gskernel.GsSpatialReference_Axis(self, i, peOrientation) def CoordinateSystem(self) -> "GsCoordinateSystem": r""" 获取坐标系信息""" return _gskernel.GsSpatialReference_CoordinateSystem(self) def CoordinateAxis(self, i: 'int') -> "GsCoordinateAxis": r""" 获取坐标轴信息 :type i: int :param i: 坐标轴的顺序(0或者1) """ return _gskernel.GsSpatialReference_CoordinateAxis(self, i) def EllipsoidInfo(self) -> "GsEllipsoid": r""" 获取椭球信息""" return _gskernel.GsSpatialReference_EllipsoidInfo(self) def Datum(self) -> "GsDatum": r""" 获取基准面信息""" return _gskernel.GsSpatialReference_Datum(self) def GeographicCoordinateReferenceSystem(self) -> "GsCoordinateReferenceSystem": r""" 获取基础地理坐标系统信息""" return _gskernel.GsSpatialReference_GeographicCoordinateReferenceSystem(self) def CoordinateConversionsRule(self) -> "GsCoordinateConversionsRule": r""" 获取坐标转换规则信息""" return _gskernel.GsSpatialReference_CoordinateConversionsRule(self) def CoordinateConversionsParameter(self, nIndex: 'int') -> "GsCoordinateConversionsParameter": r""" 获取坐标转换参数信息 :type nIndex: int :param nIndex: 坐标转换参数的序号(从0开始) """ return _gskernel.GsSpatialReference_CoordinateConversionsParameter(self, nIndex) def CoordinateConversionsParameterCount(self) -> "int": r""" 获取坐标转换参数数量""" return _gskernel.GsSpatialReference_CoordinateConversionsParameterCount(self) # Register GsSpatialReference in _gskernel: _gskernel.GsSpatialReference_swigregister(GsSpatialReference) class GsSpatialReferenceManager(object): r""" 空间参考管理对象。 枚举现有的空间参考,增加新空间参考等等能力。""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr eStandardEPSG = _gskernel.GsSpatialReferenceManager_eStandardEPSG r""" 标准EPSG分类""" eAliasOfEPSG = _gskernel.GsSpatialReferenceManager_eAliasOfEPSG r"""
""" The equilibrium module defines routines for interacting with calculated phase equilibria. """ import warnings import pycalphad.variables as v from pycalphad.core.utils import unpack_components, unpack_condition, unpack_phases, filter_phases, instantiate_models, get_state_variables from pycalphad import calculate from pycalphad.core.errors import EquilibriumError, ConditionError from pycalphad.core.starting_point import starting_point from pycalphad.codegen.callables import build_phase_records from pycalphad.core.constants import MIN_SITE_FRACTION from pycalphad.core.eqsolver import _solve_eq_at_conditions from pycalphad.core.solver import InteriorPointSolver from pycalphad.core.light_dataset import LightDataset import numpy as np from collections import OrderedDict from datetime import datetime def _adjust_conditions(conds): "Adjust conditions values to be within the numerical limit of the solver." new_conds = OrderedDict() for key, value in sorted(conds.items(), key=str): if key == str(key): key = getattr(v, key, key) if isinstance(key, v.MoleFraction): new_conds[key] = [max(val, MIN_SITE_FRACTION*1000) for val in unpack_condition(value)] else: new_conds[key] = unpack_condition(value) return new_conds def _eqcalculate(dbf, comps, phases, conditions, output, data=None, per_phase=False, callables=None, model=None, parameters=None, **kwargs): """ WARNING: API/calling convention not finalized. Compute the *equilibrium value* of a property. This function differs from `calculate` in that it computes thermodynamic equilibrium instead of randomly sampling the internal degrees of freedom of a phase. Because of that, it's slower than `calculate`. This plugs in the equilibrium phase and site fractions to compute a thermodynamic property defined in a Model. Parameters ---------- dbf : Database Thermodynamic database containing the relevant parameters. comps : list Names of components to consider in the calculation. phases : list or dict Names of phases to consider in the calculation. conditions : dict or (list of dict) StateVariables and their corresponding value. output : str Equilibrium model property (e.g., CPM, HM, etc.) to compute. This must be defined as an attribute in the Model class of each phase. data : Dataset Previous result of call to `equilibrium`. Should contain the equilibrium configurations at the conditions of interest. If the databases are not the same as in the original calculation, the results may be meaningless. per_phase : bool, optional If True, compute and return the property for each phase present. If False, return the total system value, weighted by the phase fractions. callables : dict Callable functions to compute 'output' for each phase. model : a dict of phase names to Model Model class to use for each phase. parameters : dict, optional Maps SymPy Symbol to numbers, for overriding the values of parameters in the Database. kwargs Passed to `calculate`. Returns ------- Dataset of property as a function of equilibrium conditions """ if data is None: raise ValueError('Required kwarg "data" is not specified') if model is None: raise ValueError('Required kwarg "model" is not specified') active_phases = unpack_phases(phases) conds = _adjust_conditions(conditions) indep_vars = ['N', 'P', 'T'] # TODO: Rewrite this to use the coord dict from 'data' str_conds = OrderedDict((str(key), value) for key, value in conds.items()) indep_vals = list([float(x) for x in np.atleast_1d(val)] for key, val in str_conds.items() if key in indep_vars) coord_dict = str_conds.copy() components = [x for x in sorted(comps)] desired_active_pure_elements = [list(x.constituents.keys()) for x in components] desired_active_pure_elements = [el.upper() for constituents in desired_active_pure_elements for el in constituents] pure_elements = sorted(set([x for x in desired_active_pure_elements if x != 'VA'])) coord_dict['vertex'] = np.arange(len(pure_elements) + 1) # +1 is to accommodate the degenerate degree of freedom at the invariant reactions grid_shape = np.meshgrid(*coord_dict.values(), indexing='ij', sparse=False)[0].shape prop_shape = grid_shape prop_dims = list(str_conds.keys()) + ['vertex'] result = LightDataset({output: (prop_dims, np.full(prop_shape, np.nan))}, coords=coord_dict) # For each phase select all conditions where that phase exists # Perform the appropriate calculation and then write the result back for phase in active_phases: dof = len(model[phase].site_fractions) current_phase_indices = (data.Phase == phase) if ~np.any(current_phase_indices): continue points = data.Y[np.nonzero(current_phase_indices)][..., :dof] statevar_indices = np.nonzero(current_phase_indices)[:len(indep_vals)] statevars = {key: np.take(np.asarray(vals), idx) for key, vals, idx in zip(indep_vars, indep_vals, statevar_indices)} statevars.update(kwargs) if statevars.get('mode', None) is None: statevars['mode'] = 'numpy' calcres = calculate(dbf, comps, [phase], output=output, points=points, broadcast=False, callables=callables, parameters=parameters, model=model, **statevars) result[output][np.nonzero(current_phase_indices)] = calcres[output].values if not per_phase: out = np.nansum(result[output] * data['NP'], axis=-1) dv_output = result.data_vars[output] result.remove(output) # remove the vertex coordinate because we summed over it result.add_variable(output, dv_output[0][:-1], out) else: dv_phase = data.data_vars['Phase'] dv_np = data.data_vars['NP'] result.add_variable('Phase', dv_phase[0], dv_phase[1]) result.add_variable('NP', dv_np[0], dv_np[1]) return result def equilibrium(dbf, comps, phases, conditions, output=None, model=None, verbose=False, broadcast=True, calc_opts=None, to_xarray=True, scheduler='sync', parameters=None, solver=None, callables=None, **kwargs): """ Calculate the equilibrium state of a system containing the specified components and phases, under the specified conditions. Parameters ---------- dbf : Database Thermodynamic database containing the relevant parameters. comps : list Names of components to consider in the calculation. phases : list or dict Names of phases to consider in the calculation. conditions : dict or (list of dict) StateVariables and their corresponding value. output : str or list of str, optional Additional equilibrium model properties (e.g., CPM, HM, etc.) to compute. These must be defined as attributes in the Model class of each phase. model : Model, a dict of phase names to Model, or a seq of both, optional Model class to use for each phase. verbose : bool, optional Print details of calculations. Useful for debugging. broadcast : bool If True, broadcast conditions against each other. This will compute all combinations. If False, each condition should be an equal-length list (or single-valued). Disabling broadcasting is useful for calculating equilibrium at selected conditions, when those conditions don't comprise a grid. calc_opts : dict, optional Keyword arguments to pass to `calculate`, the energy/property calculation routine. to_xarray : bool Whether to return an xarray Dataset (True, default) or an EquilibriumResult. scheduler : Dask scheduler, optional Job scheduler for performing the computation. If None, return a Dask graph of the computation instead of actually doing it. parameters : dict, optional Maps SymPy Symbol to numbers, for overriding the values of parameters in the Database. solver : pycalphad.core.solver.SolverBase Instance of a solver that is used to calculate local equilibria. Defaults to a pycalphad.core.solver.InteriorPointSolver. callables : dict, optional Pre-computed callable functions for equilibrium calculation. Returns ------- Structured equilibrium calculation, or Dask graph if scheduler=None. Examples -------- None yet. """ if not broadcast: raise NotImplementedError('Broadcasting cannot yet be disabled') comps = sorted(unpack_components(dbf, comps)) phases = unpack_phases(phases) or sorted(dbf.phases.keys()) list_of_possible_phases = filter_phases(dbf, comps) if len(list_of_possible_phases) == 0: raise ConditionError('There are no phases in the Database that can be active with components {0}'.format(comps)) active_phases = {name: dbf.phases[name] for name in filter_phases(dbf, comps, phases)} if len(active_phases) == 0: raise ConditionError('None of the passed phases ({0}) are active. List of possible phases: {1}.'.format(phases, list_of_possible_phases)) if isinstance(comps, (str, v.Species)): comps = [comps] if len(set(comps) - set(dbf.species)) > 0: raise EquilibriumError('Components not found in database: {}' .format(','.join([c.name for c in (set(comps) - set(dbf.species))]))) calc_opts = calc_opts if calc_opts is not None else dict() solver = solver if solver is not None else InteriorPointSolver(verbose=verbose) parameters = parameters if parameters is not None else dict() if isinstance(parameters, dict): parameters = OrderedDict(sorted(parameters.items(), key=str)) models = instantiate_models(dbf, comps, active_phases, model=model, parameters=parameters) # Temporary solution until constraint system improves if conditions.get(v.N) is None: conditions[v.N] = 1 if np.any(np.array(conditions[v.N]) != 1): raise ConditionError('N!=1 is not yet supported, got N={}'.format(conditions[v.N])) # Modify conditions values to be within numerical limits, e.g., X(AL)=0 # Also wrap single-valued conditions with lists conds = _adjust_conditions(conditions) for cond in conds.keys(): if isinstance(cond, (v.MoleFraction, v.ChemicalPotential)) and cond.species not in comps: raise ConditionError('{} refers to non-existent component'.format(cond)) state_variables = sorted(get_state_variables(models=models, conds=conds), key=str) str_conds = OrderedDict((str(key), value) for key, value in conds.items()) components = [x for x in sorted(comps)] desired_active_pure_elements = [list(x.constituents.keys()) for x in components] desired_active_pure_elements = [el.upper() for constituents in desired_active_pure_elements for el in constituents] pure_elements = sorted(set([x for x in desired_active_pure_elements if x != 'VA'])) if verbose: print('Components:', ' '.join([str(x) for x in comps])) print('Phases:', end=' ') output = output if output is not None else 'GM' output = output if isinstance(output, (list, tuple, set)) else [output] output = set(output) output |= {'GM'} output = sorted(output) phase_records = build_phase_records(dbf, comps, active_phases, conds, models, output='GM', callables=callables, parameters=parameters, verbose=verbose, build_gradients=True, build_hessians=True) if verbose: print('[done]', end='\n') # 'calculate' accepts conditions through its keyword arguments grid_opts = calc_opts.copy() statevar_strings = [str(x) for x in state_variables] grid_opts.update({key: value for
DOMAIN + Common.ACTIONS_ADD ACTIONS_EDIT = DOMAIN + Common.ACTIONS_EDIT ACTIONS_DELETE = DOMAIN + Common.ACTIONS_DELETE BUCKETLIST_READ = DOMAIN + Common.BUCKETLIST_READ BUCKETLIST_EDIT = DOMAIN + Common.BUCKETLIST_EDIT CAMPAIGNS_READ = DOMAIN + Common.CAMPAIGNS_READ CAMPAIGNS_ADD = DOMAIN + Common.CAMPAIGNS_ADD CAMPAIGNS_EDIT = DOMAIN + Common.CAMPAIGNS_EDIT CAMPAIGNS_DELETE = DOMAIN + Common.CAMPAIGNS_DELETE COMMENTS_READ = DOMAIN + Common.COMMENTS_READ COMMENTS_ADD = DOMAIN + Common.COMMENTS_ADD COMMENTS_EDIT = DOMAIN + Common.COMMENTS_EDIT COMMENTS_DELETE = DOMAIN + Common.COMMENTS_DELETE LOCATIONS_READ = DOMAIN + Common.LOCATIONS_READ LOCATIONS_ADD = DOMAIN + Common.LOCATIONS_ADD LOCATIONS_EDIT = DOMAIN + Common.LOCATIONS_EDIT LOCATIONS_DELETE = DOMAIN + Common.LOCATIONS_DELETE OBJECTS_READ = DOMAIN + Common.OBJECTS_READ OBJECTS_ADD = DOMAIN + Common.OBJECTS_ADD OBJECTS_EDIT = DOMAIN + Common.OBJECTS_EDIT OBJECTS_DELETE = DOMAIN + Common.OBJECTS_DELETE RELATIONSHIPS_READ = DOMAIN + Common.RELATIONSHIPS_READ RELATIONSHIPS_ADD = DOMAIN + Common.RELATIONSHIPS_ADD RELATIONSHIPS_EDIT = DOMAIN + Common.RELATIONSHIPS_EDIT RELATIONSHIPS_DELETE = DOMAIN + Common.RELATIONSHIPS_DELETE RELEASABILITY_READ = DOMAIN + Common.RELEASABILITY_READ RELEASABILITY_ADD = DOMAIN + Common.RELEASABILITY_ADD RELEASABILITY_DELETE = DOMAIN + Common.RELEASABILITY_DELETE SCREENSHOTS_READ = DOMAIN + Common.SCREENSHOTS_READ SCREENSHOTS_ADD = DOMAIN + Common.SCREENSHOTS_ADD SCREENSHOTS_DELETE = DOMAIN + Common.SCREENSHOTS_DELETE SECTORS_READ = DOMAIN + Common.SECTORS_READ SECTORS_EDIT = DOMAIN + Common.SECTORS_EDIT SERVICES_READ = DOMAIN + Common.SERVICES_READ SERVICES_EXECUTE = DOMAIN + Common.SERVICES_EXECUTE SOURCES_READ = DOMAIN + Common.SOURCES_READ SOURCES_ADD = DOMAIN + Common.SOURCES_ADD SOURCES_EDIT = DOMAIN + Common.SOURCES_EDIT SOURCES_DELETE = DOMAIN + Common.SOURCES_DELETE STATUS_READ = DOMAIN + Common.STATUS_READ STATUS_EDIT = DOMAIN + Common.STATUS_EDIT TICKETS_READ = DOMAIN + Common.TICKETS_READ TICKETS_ADD = DOMAIN + Common.TICKETS_ADD TICKETS_EDIT = DOMAIN + Common.TICKETS_EDIT TICKETS_DELETE = DOMAIN + Common.TICKETS_DELETE class EmailACL(vocab): """ Vocabulary for Email ACLs """ EMAIL = "Email." ADD_ATTACHMENT = EMAIL + "add_attachment" CAMPAIGN_READ = Common.CAMPAIGN_READ READ = EMAIL + Common.READ WRITE = EMAIL + Common.WRITE DELETE = EMAIL + Common.DELETE DOWNLOAD = EMAIL + Common.DOWNLOAD DESCRIPTION_READ = EMAIL + Common.DESCRIPTION_READ DESCRIPTION_EDIT = EMAIL + Common.DESCRIPTION_EDIT ACTIONS_READ = EMAIL + Common.ACTIONS_READ ACTIONS_ADD = EMAIL + Common.ACTIONS_ADD ACTIONS_EDIT = EMAIL + Common.ACTIONS_EDIT ACTIONS_DELETE = EMAIL + Common.ACTIONS_DELETE BUCKETLIST_READ = EMAIL + Common.BUCKETLIST_READ BUCKETLIST_EDIT = EMAIL + Common.BUCKETLIST_EDIT CAMPAIGNS_READ = EMAIL + Common.CAMPAIGNS_READ CAMPAIGNS_ADD = EMAIL + Common.CAMPAIGNS_ADD CAMPAIGNS_EDIT = EMAIL + Common.CAMPAIGNS_EDIT CAMPAIGNS_DELETE = EMAIL + Common.CAMPAIGNS_DELETE COMMENTS_READ = EMAIL + Common.COMMENTS_READ COMMENTS_ADD = EMAIL + Common.COMMENTS_ADD COMMENTS_EDIT = EMAIL + Common.COMMENTS_EDIT COMMENTS_DELETE = EMAIL + Common.COMMENTS_DELETE LOCATIONS_READ = EMAIL + Common.LOCATIONS_READ LOCATIONS_ADD = EMAIL + Common.LOCATIONS_ADD LOCATIONS_EDIT = EMAIL + Common.LOCATIONS_EDIT LOCATIONS_DELETE = EMAIL + Common.LOCATIONS_DELETE OBJECTS_READ = EMAIL + Common.OBJECTS_READ OBJECTS_ADD = EMAIL + Common.OBJECTS_ADD OBJECTS_EDIT = EMAIL + Common.OBJECTS_EDIT OBJECTS_DELETE = EMAIL + Common.OBJECTS_DELETE RELATIONSHIPS_READ = EMAIL + Common.RELATIONSHIPS_READ RELATIONSHIPS_ADD = EMAIL + Common.RELATIONSHIPS_ADD RELATIONSHIPS_EDIT = EMAIL + Common.RELATIONSHIPS_EDIT RELATIONSHIPS_DELETE = EMAIL + Common.RELATIONSHIPS_DELETE RELEASABILITY_READ = EMAIL + Common.RELEASABILITY_READ RELEASABILITY_ADD = EMAIL + Common.RELEASABILITY_ADD RELEASABILITY_DELETE = EMAIL + Common.RELEASABILITY_DELETE SCREENSHOTS_READ = EMAIL + Common.SCREENSHOTS_READ SCREENSHOTS_ADD = EMAIL + Common.SCREENSHOTS_ADD SCREENSHOTS_DELETE = EMAIL + Common.SCREENSHOTS_DELETE SECTORS_READ = EMAIL + Common.SECTORS_READ SECTORS_EDIT = EMAIL + Common.SECTORS_EDIT SERVICES_READ = EMAIL + Common.SERVICES_READ SERVICES_EXECUTE = EMAIL + Common.SERVICES_EXECUTE SOURCES_READ = EMAIL + Common.SOURCES_READ SOURCES_ADD = EMAIL + Common.SOURCES_ADD SOURCES_EDIT = EMAIL + Common.SOURCES_EDIT SOURCES_DELETE = EMAIL + Common.SOURCES_DELETE STATUS_READ = EMAIL + Common.STATUS_READ STATUS_EDIT = EMAIL + Common.STATUS_EDIT TICKETS_READ = EMAIL + Common.TICKETS_READ TICKETS_ADD = EMAIL + Common.TICKETS_ADD TICKETS_EDIT = EMAIL + Common.TICKETS_EDIT TICKETS_DELETE = EMAIL + Common.TICKETS_DELETE class EventACL(vocab): """ Vocabulary for Event ACLs """ EVENT = "Event." ADD_SAMPLE = EVENT + "add_sample" TITLE_EDIT = EVENT + "title_edit" TYPE_EDIT = EVENT + "type_edit" CAMPAIGN_READ = Common.CAMPAIGN_READ READ = EVENT + Common.READ WRITE = EVENT + Common.WRITE DELETE = EVENT + Common.DELETE DOWNLOAD = EVENT + Common.DOWNLOAD DESCRIPTION_READ = EVENT + Common.DESCRIPTION_READ DESCRIPTION_EDIT = EVENT + Common.DESCRIPTION_EDIT ACTIONS_READ = EVENT + Common.ACTIONS_READ ACTIONS_ADD = EVENT + Common.ACTIONS_ADD ACTIONS_EDIT = EVENT + Common.ACTIONS_EDIT ACTIONS_DELETE = EVENT + Common.ACTIONS_DELETE BUCKETLIST_READ = EVENT + Common.BUCKETLIST_READ BUCKETLIST_EDIT = EVENT + Common.BUCKETLIST_EDIT CAMPAIGNS_READ = EVENT + Common.CAMPAIGNS_READ CAMPAIGNS_ADD = EVENT + Common.CAMPAIGNS_ADD CAMPAIGNS_EDIT = EVENT + Common.CAMPAIGNS_EDIT CAMPAIGNS_DELETE = EVENT + Common.CAMPAIGNS_DELETE COMMENTS_READ = EVENT + Common.COMMENTS_READ COMMENTS_ADD = EVENT + Common.COMMENTS_ADD COMMENTS_EDIT = EVENT + Common.COMMENTS_EDIT COMMENTS_DELETE = EVENT + Common.COMMENTS_DELETE LOCATIONS_READ = EVENT + Common.LOCATIONS_READ LOCATIONS_ADD = EVENT + Common.LOCATIONS_ADD LOCATIONS_EDIT = EVENT + Common.LOCATIONS_EDIT LOCATIONS_DELETE = EVENT + Common.LOCATIONS_DELETE OBJECTS_READ = EVENT + Common.OBJECTS_READ OBJECTS_ADD = EVENT + Common.OBJECTS_ADD OBJECTS_EDIT = EVENT + Common.OBJECTS_EDIT OBJECTS_DELETE = EVENT + Common.OBJECTS_DELETE RELATIONSHIPS_READ = EVENT + Common.RELATIONSHIPS_READ RELATIONSHIPS_ADD = EVENT + Common.RELATIONSHIPS_ADD RELATIONSHIPS_EDIT = EVENT + Common.RELATIONSHIPS_EDIT RELATIONSHIPS_DELETE = EVENT + Common.RELATIONSHIPS_DELETE RELEASABILITY_READ = EVENT + Common.RELEASABILITY_READ RELEASABILITY_ADD = EVENT + Common.RELEASABILITY_ADD RELEASABILITY_DELETE = EVENT + Common.RELEASABILITY_DELETE SCREENSHOTS_READ = EVENT + Common.SCREENSHOTS_READ SCREENSHOTS_ADD = EVENT + Common.SCREENSHOTS_ADD SCREENSHOTS_DELETE = EVENT + Common.SCREENSHOTS_DELETE SECTORS_READ = EVENT + Common.SECTORS_READ SECTORS_EDIT = EVENT + Common.SECTORS_EDIT SERVICES_READ = EVENT + Common.SERVICES_READ SERVICES_EXECUTE = EVENT + Common.SERVICES_EXECUTE SOURCES_READ = EVENT + Common.SOURCES_READ SOURCES_ADD = EVENT + Common.SOURCES_ADD SOURCES_EDIT = EVENT + Common.SOURCES_EDIT SOURCES_DELETE = EVENT + Common.SOURCES_DELETE STATUS_READ = EVENT + Common.STATUS_READ STATUS_EDIT = EVENT + Common.STATUS_EDIT TICKETS_READ = EVENT + Common.TICKETS_READ TICKETS_ADD = EVENT + Common.TICKETS_ADD TICKETS_EDIT = EVENT + Common.TICKETS_EDIT TICKETS_DELETE = EVENT + Common.TICKETS_DELETE class ExploitACL(vocab): """ Vocabulary for Exploit ACLs """ EXPLOIT = "Exploit." CAMPAIGN_READ = Common.CAMPAIGN_READ READ = EXPLOIT + Common.READ WRITE = EXPLOIT + Common.WRITE DELETE = EXPLOIT + Common.DELETE DOWNLOAD = EXPLOIT + Common.DOWNLOAD DESCRIPTION_READ = EXPLOIT + Common.DESCRIPTION_READ DESCRIPTION_EDIT = EXPLOIT + Common.DESCRIPTION_EDIT ACTIONS_READ = EXPLOIT + Common.ACTIONS_READ ACTIONS_ADD = EXPLOIT + Common.ACTIONS_ADD ACTIONS_EDIT = EXPLOIT + Common.ACTIONS_EDIT ACTIONS_DELETE = EXPLOIT + Common.ACTIONS_DELETE BUCKETLIST_READ = EXPLOIT + Common.BUCKETLIST_READ BUCKETLIST_EDIT = EXPLOIT + Common.BUCKETLIST_EDIT CAMPAIGNS_READ = EXPLOIT + Common.CAMPAIGNS_READ CAMPAIGNS_ADD = EXPLOIT + Common.CAMPAIGNS_ADD CAMPAIGNS_EDIT = EXPLOIT + Common.CAMPAIGNS_EDIT CAMPAIGNS_DELETE = EXPLOIT + Common.CAMPAIGNS_DELETE COMMENTS_READ = EXPLOIT + Common.COMMENTS_READ COMMENTS_ADD = EXPLOIT + Common.COMMENTS_ADD COMMENTS_EDIT = EXPLOIT + Common.COMMENTS_EDIT COMMENTS_DELETE = EXPLOIT + Common.COMMENTS_DELETE LOCATIONS_READ = EXPLOIT + Common.LOCATIONS_READ LOCATIONS_ADD = EXPLOIT + Common.LOCATIONS_ADD LOCATIONS_EDIT = EXPLOIT + Common.LOCATIONS_EDIT LOCATIONS_DELETE = EXPLOIT + Common.LOCATIONS_DELETE OBJECTS_READ = EXPLOIT + Common.OBJECTS_READ OBJECTS_ADD = EXPLOIT + Common.OBJECTS_ADD OBJECTS_EDIT = EXPLOIT + Common.OBJECTS_EDIT OBJECTS_DELETE = EXPLOIT + Common.OBJECTS_DELETE RELATIONSHIPS_READ = EXPLOIT + Common.RELATIONSHIPS_READ RELATIONSHIPS_ADD = EXPLOIT + Common.RELATIONSHIPS_ADD RELATIONSHIPS_EDIT = EXPLOIT + Common.RELATIONSHIPS_EDIT RELATIONSHIPS_DELETE = EXPLOIT + Common.RELATIONSHIPS_DELETE RELEASABILITY_READ = EXPLOIT + Common.RELEASABILITY_READ RELEASABILITY_ADD = EXPLOIT + Common.RELEASABILITY_ADD RELEASABILITY_DELETE = EXPLOIT + Common.RELEASABILITY_DELETE SCREENSHOTS_READ = EXPLOIT + Common.SCREENSHOTS_READ SCREENSHOTS_ADD = EXPLOIT + Common.SCREENSHOTS_ADD SCREENSHOTS_DELETE = EXPLOIT + Common.SCREENSHOTS_DELETE SECTORS_READ = EXPLOIT + Common.SECTORS_READ SECTORS_EDIT = EXPLOIT + Common.SECTORS_EDIT SERVICES_READ = EXPLOIT + Common.SERVICES_READ SERVICES_EXECUTE = EXPLOIT + Common.SERVICES_EXECUTE SOURCES_READ = EXPLOIT + Common.SOURCES_READ SOURCES_ADD = EXPLOIT + Common.SOURCES_ADD SOURCES_EDIT = EXPLOIT + Common.SOURCES_EDIT SOURCES_DELETE = EXPLOIT + Common.SOURCES_DELETE STATUS_READ = EXPLOIT + Common.STATUS_READ STATUS_EDIT = EXPLOIT + Common.STATUS_EDIT TICKETS_READ = EXPLOIT + Common.TICKETS_READ TICKETS_ADD = EXPLOIT + Common.TICKETS_ADD TICKETS_EDIT = EXPLOIT + Common.TICKETS_EDIT TICKETS_DELETE = EXPLOIT + Common.TICKETS_DELETE class IndicatorACL(vocab): """ Vocabulary for Indicator ACLs """ INDICATOR = "Indicator." CAMPAIGN_READ = Common.CAMPAIGN_READ TYPE_EDIT = INDICATOR + "type_edit" THREAT_TYPE_EDIT = INDICATOR + "threat_type_edit" ATTACK_TYPE_EDIT = INDICATOR + "attack_type_edit" CONFIDENCE_EDIT = INDICATOR + "confidence_edit" IMPACT_EDIT = INDICATOR + "impact_edit" ACTIONS_READ = INDICATOR + "actions_read" ACTIONS_ADD = INDICATOR + "actions_add" ACTIONS_EDIT = INDICATOR + "actions_edit" ACTIONS_DELETE = INDICATOR + "actions_delete" ACTIVITY_READ = INDICATOR + "activity_read" ACTIVITY_ADD = INDICATOR + "activity_add" ACTIVITY_EDIT = INDICATOR + "activity_edit" ACTIVITY_DELETE = INDICATOR + "activity_delete" READ = INDICATOR + Common.READ WRITE = INDICATOR + Common.WRITE DELETE = INDICATOR + Common.DELETE DOWNLOAD = INDICATOR + Common.DOWNLOAD DESCRIPTION_READ = INDICATOR + Common.DESCRIPTION_READ DESCRIPTION_EDIT = INDICATOR + Common.DESCRIPTION_EDIT ACTIONS_READ = INDICATOR + Common.ACTIONS_READ ACTIONS_ADD = INDICATOR + Common.ACTIONS_ADD ACTIONS_EDIT = INDICATOR + Common.ACTIONS_EDIT ACTIONS_DELETE = INDICATOR + Common.ACTIONS_DELETE BUCKETLIST_READ = INDICATOR + Common.BUCKETLIST_READ BUCKETLIST_EDIT = INDICATOR + Common.BUCKETLIST_EDIT CAMPAIGNS_READ = INDICATOR + Common.CAMPAIGNS_READ CAMPAIGNS_ADD = INDICATOR + Common.CAMPAIGNS_ADD CAMPAIGNS_EDIT = INDICATOR + Common.CAMPAIGNS_EDIT CAMPAIGNS_DELETE = INDICATOR + Common.CAMPAIGNS_DELETE COMMENTS_READ = INDICATOR + Common.COMMENTS_READ COMMENTS_ADD = INDICATOR + Common.COMMENTS_ADD COMMENTS_EDIT = INDICATOR + Common.COMMENTS_EDIT COMMENTS_DELETE = INDICATOR + Common.COMMENTS_DELETE LOCATIONS_READ = INDICATOR + Common.LOCATIONS_READ LOCATIONS_ADD = INDICATOR + Common.LOCATIONS_ADD LOCATIONS_EDIT = INDICATOR + Common.LOCATIONS_EDIT LOCATIONS_DELETE = INDICATOR + Common.LOCATIONS_DELETE OBJECTS_READ = INDICATOR + Common.OBJECTS_READ OBJECTS_ADD = INDICATOR + Common.OBJECTS_ADD OBJECTS_EDIT = INDICATOR + Common.OBJECTS_EDIT OBJECTS_DELETE = INDICATOR + Common.OBJECTS_DELETE
256 bins for each channel, a choice # between 32-96 bins are normally used, but this tends # to be application dependent print("flattened feature vector size: %d" % (np.array(features).flatten().shape)) plt.show() print('dominant color:'+str(dom_color)) return dom_color def test_dominant_colors(): images = ['white.jpg','black.jpg','pink.jpg','red.jpg','orange.jpg','yellow.jpg','green.jpg','blue.jpg','lightblue.jpg','purple.jpg', 'orange.jpg','grey.jpg','turqoise.jpg'] for im in images: path = os.path.join('/home/jeremy/projects/core/images',im) img_arr = cv2.imread(path) col = dominant_colors(img_arr,n_components=2) print('file:{} color {}'.format(path,col)) def browse_images(dir,filter='.jpeg'): files = [os.path.join(dir,f) for f in os.listdir(dir) if filter in f] for f in files: img_arr = cv2.imread(f) cv2.imshow('img',img_arr) cv2.waitKey(0) def one_person_per_image(image,save_dir='multiple_people',visual_output=False): if isinstance(image,basestring): # imgname = image.replace('https://','').replace('http://','').replace('/','_') #conver url to name imgname = image else: imgname = 'test.jpg' img_arr = Utils.get_cv2_img_array(image) faces = background_removal.find_face_dlib_with_scores(img_arr) print(faces) if 'scores' in faces and 'faces' in faces: for score,bbox in zip(faces['scores'],faces['faces']): print('score {} bbox {}'.format(score,bbox)) cv2.rectangle(img_arr,(bbox[0],bbox[1]),(bbox[0]+bbox[2],bbox[1]+bbox[3]),color=(255,255,0),thickness=2) if len(faces['scores'])>1: multiples_dir = os.path.join(os.path.dirname(image),save_dir) Utils.ensure_dir(multiples_dir) savename = os.path.join(multiples_dir,os.path.basename(imgname)) print('more than one face found, moving {} to {}'.format(image,savename)) mvcmd = 'mv '+imgname+' '+savename subprocess.call(mvcmd,shell=True) if visual_output: cv2.imshow('image',img_arr) cv2.waitKey(100) def x1y1x2y2_to_xywh(bb): assert bb[2]>bb[0],'bb not in format x1y1x2y2 {}'.format(bb) assert bb[3]>bb[1],'bb not in format x1y1x2y2 {}'.format(bb) return [bb[0],bb[1],bb[2]-bb[0],bb[3]-bb[1]] def xywh_to_x1y1x2y2(bb): return [bb[0],bb[1],bb[2]+bb[0],bb[3]+bb[1]] def xywh_to_yolo(bb_xywh,dims_hxw,correct_out_of_bounds=True): ''' output : for yolo - https://pjreddie.com/darknet/yolo/ Darknet wants a .txt file for each image with a line for each ground truth object in the image that looks like: <object-class> <x> <y> <width> <height> where those are percentages and x,y are CENTER OF BB (also in percent) :param bb_xywh: :param image_dims size of image for this bb (needed since yolo wants bb's as percentages) :return: ''' if correct_out_of_bounds: if bb_xywh[0] > dims_hxw[1]: bb_xywh[0] = dims_hxw[1] logging.warning('corrected y out of bounds') if bb_xywh[1] > dims_hxw[0]: bb_xywh[1] = dims_hxw[0] logging.warning('corrected x out of bounds!') if bb_xywh[0]+bb_xywh[2] > dims_hxw[1]: bb_xywh[2] = dims_hxw[1]-bb_xywh[0] logging.warning('corrected x+w > image width!!') if bb_xywh[1]+bb_xywh[3] > dims_hxw[0]: bb_xywh[3] = dims_hxw[0]-bb_xywh[1] logging.warning('corrected y+h > image height!!') x_center = bb_xywh[0]+(bb_xywh[2]/2.0) #x1+w/2 y_center = bb_xywh[1]+(bb_xywh[3]/2.0) #y1+h/2 x_p = float(x_center)/dims_hxw[1] #center x as % y_p = float(y_center)/dims_hxw[0] #center y as % w_p = float(bb_xywh[2])/dims_hxw[1] #width as % h_p = float(bb_xywh[3])/dims_hxw[0] #height as % try: assert x_p<=1,'x > image width!!' except: logging.warning('x_p>1 bb {} out of bounds hw {}'.format(bb_xywh,dims_hxw)) try: assert y_p<=1,'y > image height!!' except: logging.warning('y_p > 1 bb {} out of bounds hw {}'.format(bb_xywh,dims_hxw)) try: assert bb_xywh[0]+bb_xywh[2]<=dims_hxw[1],'x+w > image width!!' except: logging.warning('x+width bb {} out of bounds hw {}'.format(bb_xywh,dims_hxw)) try: assert bb_xywh[1]+bb_xywh[3]<=dims_hxw[0],'y+h > image height!!' except: logging.warning('y+height bb {} out of bounds hw {}'.format(bb_xywh,dims_hxw)) return([x_p,y_p,w_p,h_p]) def x1x2y1y2_to_yolo(size, box): dw = 1./(size[0]) dh = 1./(size[1]) x = (box[0] + box[1])/2.0 - 1 y = (box[2] + box[3])/2.0 - 1 w = box[1] - box[0] h = box[3] - box[2] x = x*dw w = w*dw y = y*dh h = h*dh return (x,y,w,h) def yolo_to_xywh(bb_yolo,image_dims_HxW): #should change this to HxW and all callers, what was i thiinking ''' output : for yolo - https://pjreddie.com/darknet/yolo/ Darknet wants a .txt file for each image with a line for each ground truth object in the image that looks like: :param bb_yolo: x_center, y_center, w, h all as percentages of image width or height :param image_dims size of image for this bb (needed since yolo wants bb's as percentages) :return: ''' x_center = float(bb_yolo[0])*image_dims_HxW[1] #center x in pixels y_center = float(bb_yolo[1])*image_dims_HxW[0] #center y pixels w = float(bb_yolo[2])*image_dims_HxW[1] #width pixels h = float(bb_yolo[3])*image_dims_HxW[0] #height pixels x=x_center-w/2 y=y_center-h/2 logging.debug('in {} dims {} out(xywh) {} {} {} {}'.format(bb_yolo,image_dims_HxW,x,y,w,h)) return([int(x),int(y),int(w),int(h)]) def bb_with_text(img_arr,bb_xywh,text,boxcolor = [50,255,50],text_bgnd_color=[255,255,80],box_thickness=1): text_color=[0,50,255] cv2.rectangle(img_arr,(bb_xywh[0],bb_xywh[1]),(bb_xywh[0]+bb_xywh[2],bb_xywh[1]+bb_xywh[3]),color=boxcolor,thickness=box_thickness) img_arr[bb_xywh[1]:bb_xywh[1]+20,bb_xywh[0]:bb_xywh[0]+bb_xywh[2]]=(img_arr[bb_xywh[1]:bb_xywh[1]+20,bb_xywh[0]:bb_xywh[0]+bb_xywh[2]]/2)+np.array(text_bgnd_color)/2 cv2.putText(img_arr,text,(bb_xywh[0]+5,bb_xywh[1]+20),cv2.FONT_HERSHEY_PLAIN, 1, text_color) return img_arr def count_values(mask,labels=None): image_size = mask.shape[0]*mask.shape[1] uniques = np.unique(mask) pixelcounts = {} for unique in uniques: pixelcount = len(mask[mask==unique]) ratio = float(pixelcount)/image_size if labels is not None: print('class {} {} count {} ratio {}'.format(unique,labels[unique],pixelcount,ratio)) else: print('class {} count {} ratio {}'.format(unique,pixelcount,ratio)) pixelcounts[unique]=pixelcount return pixelcounts def get_median_image(img_arr_list,visual_output=True): '''' given list of image arrs, produce median image useful for bg subtraction ''' np_images = np.array(img_arr_list) print('np size:'+str(np_images.shape)) median_image = np.median(np_images,axis=0) #get median pixel across images print('type:'+str(type(median_image))) median_image = np.array(median_image,dtype=np.uint8) print('median size:'+str(median_image.shape)) if visual_output: cv2.imshow('median',median_image) k=cv2.waitKey(0) return median_image def test_median_image(): dir = '/home/jeremy/PycharmProjects/snooker/' files = [file for file in os.listdir(dir) if '.jpg' in file] files = sorted(files) # build image array img_arr_list =[] # for file in files: # path = os.path.join(dir,file) # img_arr = cv2.imread(path) # img_arr_list.append(img_arr) # # med_img = get_median_image(img_arr_list) # cv2.imwrite(os.path.join(dir,'median.bmp'),med_img) med_img = cv2.imread(os.path.join(dir, 'median2.bmp')) med_eq = clahe_rgb(med_img) cv2.imshow('hi',med_img) cv2.imshow('eq',med_eq) cv2.waitKey(0) height, width, channels = med_img.shape outfile = os.path.join(dir, 'out.mp4') # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case out = cv2.VideoWriter(outfile, fourcc, 20.0, (width, height)) import time start = time.time() for file in files: path = os.path.join(dir, file) img_arr = cv2.imread(path) img_eq = clahe_rgb(img_arr) diff = cv2.subtract(img_eq, med_eq) cv2.imshow('diff',diff) cv2.waitKey(10) print('ok1') out.write(diff) # Write out frame to video print('ok2') elapsed = time.time() - start print( 'elapsed {} n {} tpi {} ipt {} '.format(elapsed, len(files), elapsed / len(files), float(len(files)) / elapsed)) def clahe_rgb(img_arr): #-----Converting image to LAB Color model----------------------------------- lab= cv2.cvtColor(img_arr, cv2.COLOR_BGR2LAB) # cv2.imshow("lab",lab) #-----Splitting the LAB image to different channels------------------------- l, a, b = cv2.split(lab) # cv2.imshow('l_channel', l) # cv2.imshow('a_channel', a) # cv2.imshow('b_channel', b) # #-----Applying CLAHE to L-channel------------------------------------------- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)) cl = clahe.apply(l) # cv2.imshow('CLAHE output', cl) #-----Merge the CLAHE enhanced L-channel with the a and b channel----------- limg = cv2.merge((cl,a,b)) # cv2.imshow('limg', limg) #-----Converting image from LAB Color model to RGB model-------------------- final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) # cv2.imshow('final', final) return final if __name__ == "__main__": test_median_image() img=cv2.imread('../images/female1.jpg') resize_by_adding_border(img,output_size=(900,1000),visual_output=True) # test_or_training_textfile('/home/jr/python-packages/trendi/classifier_stuff/caffe_nns/only_train',test_or_train='test') # test_or_training_textfile('/home/jr/python-packages/trendi/classifier_stuff/caffe_nns/only_train',test_or_train='train') # Utils.remove_duplicate_files('/media/jr/Transcend/my_stuff/tg/tg_ultimate_image_db/ours/pd_output_brain1/') # resize_and_crop_image_using_bb('../images/female1.jpg',bb=[240,122,170,170],output_w=50,output_h=50) # resize_and_crop_image_using_bb('../images/female1.jpg',bb=[240,122,170,400],output_w=50,output_h=50) # resize_and_crop_image_using_bb('../images/female1.jpg',bb=[240,122,170,400],output_w=150,output_h=50) # resize_and_crop_image_using_bb('../images/female1.jpg',bb=[240,122,170,400],output_w=50,output_h=150) #resize_and_crop_image_using_bb('../images/female1.jpg',bb=[240,122,170,170],output_w=1000,output_h=100) # avg_h,avg_w,avg_d,avg_B,avg_G,avg_R,totfiles = image_stats_from_dir_of_dirs(dir_of_dirs,filter='test') # print('avg h {} avg w {} avgB {} avgG {} avgR {} nfiles {} in dir_of_dirs {}',avg_h,avg_w,avg_d,avg_B,avg_G,avg_R,totfiles,dir_of_dirs) # dir_of_dirs = '/home/jr/core/classifier_stuff/caffe_nns/dataset' # raw_input('enter to continue') # image_chooser_dir_of_dirs(dir_of_dirs,output_dir) # image_chooser(dir_of_dirs,output_dir) # crop_files_in_dir_of_dirs(dir_of_dirs,bb=None,output_w =150,output_h =200,use_visual_output=True) # dir = '/home/jeremy/projects/core/images' # resize_and_crop_maintain_bb_on_dir(dir, output_width = 448, output_height = 448,use_visual_output=True) if(0): #test mask to bbs # url = 'http://s-media-cache-ak0.pinimg.com/736x/fe/5d/f7/fe5df7e80093f674ecc79a9f30069a8a.jpg' # start=time.time() # retval = neurodoll_falcon_client.nd(url,get_combined_results=True) # # elapsed = time.time()-start # print('elapsed time in nd:'+str(elapsed)) # if retval['success']: # print('got nd') # cv2.imwrite('/home/jeremy/projects/core/images/dress_mask_u21.png',retval['mask']) # mask_to_rects(retval['mask']) # else: # print('did not get good mask from ndfc') mask = cv2.imread('/home/jeremy/projects/core/images/dress_mask_u21.png') bbs = mask_to_rects(mask,visual_output=True) print('bbs:{}'.format(bbs)) if(0) : #test dominant colors dir = '/home/jeremy/Dropbox/tg/color_snatches' files = [os.path.join(dir,f) for f in os.listdir(dir)] for file in files: print('file '+file) im1=cv2.imread(file) cv2.imshow('im1',im1) cv2.waitKey(0) dominant_colors(im1) # dir = '/home/jeremy/tg/pd_output' # dir = '/root' # indir = '/home/jeremy/image_dbs/fashionista-v0.2.1' # outdir = '/home/jeremy/image_dbs/fashionista-v0.2.1/reduced_cats' # # indir = '/home/jeremy/image_dbs/colorful_fashion_parsing_data/labels_200x150' # outdir = '/home/jeremy/image_dbs/colorful_fashion_parsing_data/labels_200x150/reduced_cats' # # defenestrate_directory(indir,outdir,filter='.png',keep_these_cats=[1,55,56,57],labels=constants.fashionista_categories_augmented) # # if host == 'jr-ThinkPad-X1-Carbon' or host == 'jr': # dir_of_dirs = '/home/jeremy/tg/train_pairs_dresses' # output_dir = '/home/jeremy/tg/curated_train_pairs_dresses' # sourcedir = '/home/jeremy/projects/core/d1' # targetdir = '/home/jeremy/projects/core/d2' # infile = '/home/jeremy/projects/core/images/female1.jpg' # else: # dir_of_dirs = '/home/jeremy/core/classifier_stuff/caffe_nns/dataset/cropped' # output_dir = '/home/jeremy/core/classifier_stuff/caffe_nns/curated_dataset' # # # kill_the_missing(sourcedir, targetdir) # # image_chooser('/data/jeremy/image_dbs/tg/google/pijamas - Google Search_files') # # output_file = 'resized.jpg' # img_arr = cv2.imread(infile) # orig_h,orig_w = img_arr.shape[0:2] # # resize_keep_aspect(infile, output_file=output_file, output_size = (600,400),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # # resize_keep_aspect(infile, output_file=output_file, output_size = (600,401),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # # resize_keep_aspect(infile, output_file=output_file, output_size = (600,399),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # # resize_keep_aspect(infile, output_file=output_file, output_size = (400,600),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # # resize_keep_aspect(infile, output_file=output_file, output_size = (400,601),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # # resize_keep_aspect(infile, output_file=output_file, output_size = (400,599),use_visual_output=True) # undo_resize_keep_aspect(output_file, output_file=None, output_size = (orig_h,orig_w),use_visual_output=True,careful_with_the_labels=True) # #nonlinear xforms , stolen from: #https://www.kaggle.com/bguberfain/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation/comments ''' import numpy as np import pandas as pd import cv2 from scipy.ndimage.interpolation import map_coordinates from scipy.ndimage.filters import gaussian_filter import matplotlib.pyplot as plt # Function to distort image def elastic_transform(image, alpha, sigma, alpha_affine, random_state=None): """Elastic deformation of images as described in [Simard2003]_ (with modifications). .. [Simard2003] <NAME>, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5 """ if random_state is None: random_state = np.random.RandomState(None) shape = image.shape shape_size = shape[:2] # Random affine center_square = np.float32(shape_size) // 2 square_size = min(shape_size) // 3 pts1 = np.float32([center_square + square_size, [center_square[0]+square_size, center_square[1]-square_size], center_square - square_size]) pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32) M = cv2.getAffineTransform(pts1, pts2) image = cv2.warpAffine(image, M, shape_size[::-1], borderMode=cv2.BORDER_REFLECT_101) dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma) * alpha dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma) * alpha dz = np.zeros_like(dx) x, y, z = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]), np.arange(shape[2])) indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1)), np.reshape(z, (-1,
except: world.send_message(-1001351496983, '[' + x['pionername'] + '](tg://user?id=' + str(id) + ')' + random.choice(worldtexts) + text, parse_mode='markdown') worldtexts = [ ', чтобы знать, что происходит в лагере (в том числе и с вами), советую отписаться мне в личку. Можете считать меня своим внутренним голосом, потому что забивать себе голову тем, кто я на самом деле, не имеет смысла... Но а теперь к делу.\n\n', ', отпишись, пожалуйста, мне в личку. Ведь правильнее будет, если твоя личная информация будет оставаться при тебе, а не оглашаться на весь лагерь. Ладно, ближе к делу...\n\n'] def relax(id): users.update_one({'id': id}, {'$set': {'relaxing': 0}}) def createuser(id, name, username): return {'id': id, 'name': name, 'username': username, 'pionername': None, 'gender': None, 'popularity': 1, 'strenght': 3, 'agility': 3, 'intelligence': 3, 'prepareto': None, 'setname': 1, 'setgender': 1, 'waitforwork': 0, 'respect': 50, 'working': 0, 'relaxing': 0, 'answering': 0, 'busy': [], 'OlgaDmitrievna_respect': 50, 'Slavya_respect': 50, 'Uliana_respect': 50, 'Alisa_respect': 50, 'Lena_respect': 50, 'Electronic_respect': 50, 'Miku_respect': 50, 'Zhenya_respect': 50, 'helping': 0 } def gettime(t): x = time.ctime() x = x.split(" ") for ids in x: for idss in ids: if idss == ':': tru = ids x = tru x = x.split(":") minute = int(x[1]) hour = int(x[0]) + 3 if t == 'h': return hour elif t == 'm': return minute def checktime(): t = threading.Timer(60, checktime) t.start() hour = gettime('h') minute = gettime('m') if hour == 17 and minute == 0: x = findindex('concertready') works[x]['value'] = 0 if hour == 21 and minute == 30: x = findindex('checkpionerssleeping') works[x]['value'] = 0 if (hour == 8 and minute == 10) or (hour == 13 and minute == 0) or (hour == 20 and minute == 30): x = findindex('helpinkitchen') works[x]['value'] = 0 if (hour == 19 and minute == 0): cardplayers = [] eveninggames() if (hour == 7 and minute == 0): odstats['waitforlineyka'] = 1 bot.send_chat_action(-1001351496983, 'typing') time.sleep(3) bot.send_message(-1001351496983, 'Доброе утро, пионеры! В 7:30 жду всех на линейке!') if (hour == 7 and minute == 30): odstats['waitforlineyka'] = 0 bot.send_chat_action(-1001351496983, 'typing') time.sleep(3) bot.send_message(-1001351496983, 'Здраствуйте, пионеры! Сейчас проведём перекличку...') bot.send_chat_action(-1001351496983, 'typing') time.sleep(4) text = '' for ids in odstats['lineyka']: text += ids + '\n' bot.send_message(-1001351496983, text + '\nВот все, кто сегодня пришёл. Молодцы, пионеры! Так держать!' + \ 'Сейчас расскажу о планах на день.', parse_mode='markdown') global nowrp if nowrp: if (hour==9 and minute==0): for ids in rpchats: try: world.send_message(ids, '*Сигнал, оповещающий о начале завтрака*', parse_mode='markdown') except: pass if (hour==14 and minute==0): for ids in rpchats: try: world.send_message(ids, '*Сигнал, оповещающий о начале обеда*', parse_mode='markdown') except: pass if (hour==21 and minute==0): for ids in rpchats: try: world.send_message(ids, '*Сигнал, оповещающий о начале ужина*', parse_mode='markdown') except: pass zavtrak = '9:00' obed = '14:00' uzhin = '21:00' def eveninggames(): global rds if rds == True: egames = ['cards'] # ,'ropepulling'] x = random.choice(egames) if x == 'cards': electronicstats['waitingplayers'] = 1 leader = 'electronic' bot.send_chat_action(-1001351496983, 'typing') t = threading.Timer(3.5, sendmes, args=[bot, 'Уже 7 вечера, а это значит, что пора начинать наши вечерние игры! На сегодня ' + \ 'у нас по плану придуманная Электроником карточная игра. [Электроник](https://t.me/ES_ElectronicBot), ' + \ 'дальше расскажешь ты.', 'markdown']) t.start() time.sleep(4.5) electronic.send_chat_action(-1001351496983, 'typing') t = threading.Timer(2, sendmes, args=[electronic, 'Есть, <NAME>!', None]) t.start() t = threading.Timer(2.1, sendstick, args=[electronic, 'CAADAgAD1QADgi0zDyFh2eUTYDzzAg']) t.start() time.sleep(4) electronic.send_chat_action(-1001351496983, 'typing') t = threading.Timer(10, sendmes, args=[electronic, 'Итак. Правила игры просты: надо выиграть, собрав на руке более сильную ' + \ 'комбинацию, чем у соперника. Процесс игры заключается в том, что соперники поочереди ' + \ 'забирают друг у друга карты. Делается это так: в свой ход вы выбираете одну из карт соперника, ' + \ 'а он после этого может поменять любые 2 карты в своей руке местами. Вы эту перестановку ' + \ 'видите, и после его действия можете изменить свой выбор. А можете не менять. ' + \ 'Так повторяется 3 раза, и вы забираете последнюю карту, которую выберите. Затем ' + \ 'такой же ход повторяется со стороны соперника. Всего каждый участник делает 3 хода, ' + \ 'и после этого оба игрока вскрываются...', None]) t.start() time.sleep(4) electronic.send_chat_action(-1001351496983, 'typing') time.sleep(4) electronic.send_chat_action(-1001351496983, 'typing') time.sleep(4) electronic.send_chat_action(-1001351496983, 'typing') t = threading.Timer(5, sendmes, args=[electronic, 'Что смешного? Ладно, неважно. Все поняли правила? Отлично! Для ' + \ 'регистрации в турнире нужно подойти ко мне, и сказать: "`Хочу принять участие в турнире!`". ' + \ 'Регистрация заканчивается через 20 минут!', 'markdown']) t.start() t = threading.Timer(300, starttournier, args=['cards']) t.start() elif x == 'football': leader = 'uliana' bot.send_chat_action(-1001351496983, 'typing') t = threading.Timer(3.5, sendmes, args=[bot, 'Уже 7 вечера, а это значит, что пора начинать наши вечерние игры! На сегодня ' + \ 'у нас по плану футбол! [Ульяна](https://t.me/ES_UlianaBot), ' + \ 'расскажет вам про правила проведения турнира.', 'markdown']) t.start() time.sleep(4.5) uliana.send_chat_action(-1001351496983, 'typing') t = threading.Timer(2, sendmes, args=[uliana, 'Так точно, <NAME>!', None]) t.start() t = threading.Timer(2.1, sendstick, args=[uliana, 'CAADAgADKQADgi0zD_inNy0pZyh0Ag']) t.start() time.sleep(4) uliana.send_chat_action(-1001351496983, 'typing') t = threading.Timer(5, sendmes, args=[uliana, 'Правила просты - не жульничать! Для записи на турнир ' + \ 'подойдите ко мне и скажите "`Хочу участвовать!`". Вроде бы всё... Жду всех!', 'markdown']) t.start() elif x == 'ropepulling': leader = 'alisa' setka = [] def starttournier(game): try: if game == 'cards': global cardplayers global setka newplayers = ['miku', 'slavya', 'zhenya', 'alisa', 'lena', 'uliana'] specialrules = 0 i = 0 for ids in cardplayers: i += 1 if i % 2 == 0: if i >= 10: prm = 16 elif i > 0: prm = 8 else: prm = 0 else: if i == 1: prm = 4 elif i == 3 or i == 5 or i == 7: prm = 8 elif i == 9: prm = 12 specialrules = 1 g = 0 if prm > 0: while g < (prm - i): randomplayer = random.choice(newplayers) cardplayers.append(randomplayer) newplayers.remove(randomplayer) g += 1 text = '' i = 0 h = len(cardplayers) while i < (h / 2): player1 = random.choice(cardplayers) cardplayers.remove(player1) player2 = random.choice(cardplayers) cardplayers.remove(player2) setka.append([player1, player2]) i += 1 for ids in setka: text += '\n\n' vs = ' VS ' for idss in ids: try: int(idss) x = users.find_one({'id': idss}) text += '[' + x['pionername'] + '](tg://user?id=' + str(x['id']) + ')' + vs except: text += nametopioner(idss) + vs vs = '' electronic.send_chat_action(-1001351496983, 'typing') time.sleep(5) electronic.send_message(-1001351496983, 'Ну что, все в сборе? Тогда вот вам турнирная сетка на первый этап:\n' + text, parse_mode='markdown') time.sleep(1.5) electronic.send_chat_action(-1001351496983, 'typing') time.sleep(3) electronic.send_message(-1001351496983, 'А теперь прошу к столам! Каждый садится со своим соперником. Через 2 минуты начинается ' + 'первый этап!') electronicstats['cardsturn'] = 1 t = threading.Timer(120, cards_nextturn) t.start() for ids in setka: i = 0 for idss in ids: try: int(idss) i += 1 except: if i == 0: index = 1 elif i == 1: index = 0 try: int(ids[index]) talkwithplayer(ids[index], idss) except: pass else: electronic.send_message(-1001351496983, 'К сожалению, игроков для турнира сегодня не набралось. Ну ничего, в следующий раз попробуем!') except: setka = [] cardplayers = [] electronicstats['waitingplayers'] = 0 electronicstats['playingcards'] = 0 electronicstats['cardsturn'] = 0 electronic.send_message(-1001351496983, 'Непредвиденные обстоятельства! Турнир придётся отменить!') def cards_nextturn(): try: global setka global cardplayers for ab in setka: cardplayers.append(ab[0]) cardplayers.append(ab[1]) if len(cardplayers) > 0: print(setka) print(cardplayers) for ids in setka: i = -1 print(ids) for idss in ids: print(idss) i += 1 if i < 2: try: print('try1') int(ids[0]) if i == 0: index = 1 else: index = 0 try: print('try2') int(ids[index]) player1 = users.find_one({'id': ids[0]}) player2 = users.find_one({'id': ids[1]}) r = player1['intelligence'] - player2['intelligence'] r = r / 2 x = random.randint(1, 100) if x <= (50 + r): cardplayers.remove(player2['id']) else: cardplayers.remove(player1['id']) i = 10 print('try2complete') except: coef = 0 user = users.find_one({'id': ids[1]}) if user != None: coef += user['intelligence'] if ids[index] == 'miku': intelligence = mikustats['intelligence'] if ids[index] == 'alisa': intelligence = alisastats['intelligence'] if ids[index] == 'lena': intelligence = lenastats['intelligence'] if ids[index] == 'slavya': intelligence = slavyastats['intelligence'] if ids[index] == 'zhenya': intelligence = zhenyastats['intelligence'] if ids[index] == 'uliana': intelligence = ulianastats['intelligence'] if intelligence == 1: x = 80 + coef if intelligence == 2: x
'type': 'str'}, 'sql_server_license_type': {'key': 'sqlServerLicenseType', 'type': 'str'}, 'data_mover_run_as_account_id': {'key': 'dataMoverRunAsAccountId', 'type': 'str'}, 'snapshot_run_as_account_id': {'key': 'snapshotRunAsAccountId', 'type': 'str'}, 'target_vm_name': {'key': 'targetVmName', 'type': 'str'}, 'target_vm_size': {'key': 'targetVmSize', 'type': 'str'}, 'target_location': {'key': 'targetLocation', 'type': 'str'}, 'target_resource_group_id': {'key': 'targetResourceGroupId', 'type': 'str'}, 'target_availability_set_id': {'key': 'targetAvailabilitySetId', 'type': 'str'}, 'target_availability_zone': {'key': 'targetAvailabilityZone', 'type': 'str'}, 'target_proximity_placement_group_id': {'key': 'targetProximityPlacementGroupId', 'type': 'str'}, 'target_boot_diagnostics_storage_account_id': {'key': 'targetBootDiagnosticsStorageAccountId', 'type': 'str'}, 'target_vm_tags': {'key': 'targetVmTags', 'type': '{str}'}, 'protected_disks': {'key': 'protectedDisks', 'type': '[VMwareCbtProtectedDiskDetails]'}, 'target_network_id': {'key': 'targetNetworkId', 'type': 'str'}, 'vm_nics': {'key': 'vmNics', 'type': '[VMwareCbtNicDetails]'}, 'target_nic_tags': {'key': 'targetNicTags', 'type': '{str}'}, 'migration_recovery_point_id': {'key': 'migrationRecoveryPointId', 'type': 'str'}, 'last_recovery_point_received': {'key': 'lastRecoveryPointReceived', 'type': 'iso-8601'}, 'last_recovery_point_id': {'key': 'lastRecoveryPointId', 'type': 'str'}, 'initial_seeding_progress_percentage': {'key': 'initialSeedingProgressPercentage', 'type': 'int'}, 'migration_progress_percentage': {'key': 'migrationProgressPercentage', 'type': 'int'}, 'resync_progress_percentage': {'key': 'resyncProgressPercentage', 'type': 'int'}, 'initial_seeding_retry_count': {'key': 'initialSeedingRetryCount', 'type': 'long'}, 'resync_retry_count': {'key': 'resyncRetryCount', 'type': 'long'}, 'resync_required': {'key': 'resyncRequired', 'type': 'str'}, 'resync_state': {'key': 'resyncState', 'type': 'str'}, 'perform_auto_resync': {'key': 'performAutoResync', 'type': 'str'}, 'seed_disk_tags': {'key': 'seedDiskTags', 'type': '{str}'}, 'target_disk_tags': {'key': 'targetDiskTags', 'type': '{str}'}, } def __init__( self, *, license_type: Optional[str] = None, sql_server_license_type: Optional[str] = None, target_vm_name: Optional[str] = None, target_vm_size: Optional[str] = None, target_resource_group_id: Optional[str] = None, target_availability_set_id: Optional[str] = None, target_availability_zone: Optional[str] = None, target_proximity_placement_group_id: Optional[str] = None, target_boot_diagnostics_storage_account_id: Optional[str] = None, target_vm_tags: Optional[Dict[str, str]] = None, protected_disks: Optional[List["VMwareCbtProtectedDiskDetails"]] = None, target_network_id: Optional[str] = None, vm_nics: Optional[List["VMwareCbtNicDetails"]] = None, target_nic_tags: Optional[Dict[str, str]] = None, perform_auto_resync: Optional[str] = None, seed_disk_tags: Optional[Dict[str, str]] = None, target_disk_tags: Optional[Dict[str, str]] = None, **kwargs ): super(VMwareCbtMigrationDetails, self).__init__(**kwargs) self.instance_type = 'VMwareCbt' # type: str self.vmware_machine_id = None self.os_type = None self.firmware_type = None self.target_generation = None self.license_type = license_type self.sql_server_license_type = sql_server_license_type self.data_mover_run_as_account_id = None self.snapshot_run_as_account_id = None self.target_vm_name = target_vm_name self.target_vm_size = target_vm_size self.target_location = None self.target_resource_group_id = target_resource_group_id self.target_availability_set_id = target_availability_set_id self.target_availability_zone = target_availability_zone self.target_proximity_placement_group_id = target_proximity_placement_group_id self.target_boot_diagnostics_storage_account_id = target_boot_diagnostics_storage_account_id self.target_vm_tags = target_vm_tags self.protected_disks = protected_disks self.target_network_id = target_network_id self.vm_nics = vm_nics self.target_nic_tags = target_nic_tags self.migration_recovery_point_id = None self.last_recovery_point_received = None self.last_recovery_point_id = None self.initial_seeding_progress_percentage = None self.migration_progress_percentage = None self.resync_progress_percentage = None self.initial_seeding_retry_count = None self.resync_retry_count = None self.resync_required = None self.resync_state = None self.perform_auto_resync = perform_auto_resync self.seed_disk_tags = seed_disk_tags self.target_disk_tags = target_disk_tags class VMwareCbtNicDetails(msrest.serialization.Model): """VMwareCbt NIC details. Variables are only populated by the server, and will be ignored when sending a request. :ivar nic_id: The NIC Id. :vartype nic_id: str :param is_primary_nic: A value indicating whether this is the primary NIC. :type is_primary_nic: str :ivar source_ip_address: The source IP address. :vartype source_ip_address: str :ivar source_ip_address_type: The source IP address type. Possible values include: "Dynamic", "Static". :vartype source_ip_address_type: str or ~azure.mgmt.recoveryservicessiterecovery.models.EthernetAddressType :ivar source_network_id: Source network Id. :vartype source_network_id: str :param target_ip_address: The target IP address. :type target_ip_address: str :param target_ip_address_type: The target IP address type. Possible values include: "Dynamic", "Static". :type target_ip_address_type: str or ~azure.mgmt.recoveryservicessiterecovery.models.EthernetAddressType :param target_subnet_name: Target subnet name. :type target_subnet_name: str :param target_nic_name: Target NIC name. :type target_nic_name: str :param is_selected_for_migration: A value indicating whether this NIC is selected for migration. :type is_selected_for_migration: str """ _validation = { 'nic_id': {'readonly': True}, 'source_ip_address': {'readonly': True}, 'source_ip_address_type': {'readonly': True}, 'source_network_id': {'readonly': True}, } _attribute_map = { 'nic_id': {'key': 'nicId', 'type': 'str'}, 'is_primary_nic': {'key': 'isPrimaryNic', 'type': 'str'}, 'source_ip_address': {'key': 'sourceIPAddress', 'type': 'str'}, 'source_ip_address_type': {'key': 'sourceIPAddressType', 'type': 'str'}, 'source_network_id': {'key': 'sourceNetworkId', 'type': 'str'}, 'target_ip_address': {'key': 'targetIPAddress', 'type': 'str'}, 'target_ip_address_type': {'key': 'targetIPAddressType', 'type': 'str'}, 'target_subnet_name': {'key': 'targetSubnetName', 'type': 'str'}, 'target_nic_name': {'key': 'targetNicName', 'type': 'str'}, 'is_selected_for_migration': {'key': 'isSelectedForMigration', 'type': 'str'}, } def __init__( self, *, is_primary_nic: Optional[str] = None, target_ip_address: Optional[str] = None, target_ip_address_type: Optional[Union[str, "EthernetAddressType"]] = None, target_subnet_name: Optional[str] = None, target_nic_name: Optional[str] = None, is_selected_for_migration: Optional[str] = None, **kwargs ): super(VMwareCbtNicDetails, self).__init__(**kwargs) self.nic_id = None self.is_primary_nic = is_primary_nic self.source_ip_address = None self.source_ip_address_type = None self.source_network_id = None self.target_ip_address = target_ip_address self.target_ip_address_type = target_ip_address_type self.target_subnet_name = target_subnet_name self.target_nic_name = target_nic_name self.is_selected_for_migration = is_selected_for_migration class VMwareCbtNicInput(msrest.serialization.Model): """VMwareCbt NIC input. All required parameters must be populated in order to send to Azure. :param nic_id: Required. The NIC Id. :type nic_id: str :param is_primary_nic: Required. A value indicating whether this is the primary NIC. :type is_primary_nic: str :param target_subnet_name: Target subnet name. :type target_subnet_name: str :param target_static_ip_address: The static IP address. :type target_static_ip_address: str :param is_selected_for_migration: A value indicating whether this NIC is selected for migration. :type is_selected_for_migration: str :param target_nic_name: Target NIC name. :type target_nic_name: str """ _validation = { 'nic_id': {'required': True}, 'is_primary_nic': {'required': True}, } _attribute_map = { 'nic_id': {'key': 'nicId', 'type': 'str'}, 'is_primary_nic': {'key': 'isPrimaryNic', 'type': 'str'}, 'target_subnet_name': {'key': 'targetSubnetName', 'type': 'str'}, 'target_static_ip_address': {'key': 'targetStaticIPAddress', 'type': 'str'}, 'is_selected_for_migration': {'key': 'isSelectedForMigration', 'type': 'str'}, 'target_nic_name': {'key': 'targetNicName', 'type': 'str'}, } def __init__( self, *, nic_id: str, is_primary_nic: str, target_subnet_name: Optional[str] = None, target_static_ip_address: Optional[str] = None, is_selected_for_migration: Optional[str] = None, target_nic_name: Optional[str] = None, **kwargs ): super(VMwareCbtNicInput, self).__init__(**kwargs) self.nic_id = nic_id self.is_primary_nic = is_primary_nic self.target_subnet_name = target_subnet_name self.target_static_ip_address = target_static_ip_address self.is_selected_for_migration = is_selected_for_migration self.target_nic_name = target_nic_name class VMwareCbtPolicyCreationInput(PolicyProviderSpecificInput): """VMware Cbt policy creation input. All required parameters must be populated in order to send to Azure. :param instance_type: Required. The class type.Constant filled by server. :type instance_type: str :param recovery_point_history_in_minutes: The duration in minutes until which the recovery points need to be stored. :type recovery_point_history_in_minutes: int :param crash_consistent_frequency_in_minutes: The crash consistent snapshot frequency (in minutes). :type crash_consistent_frequency_in_minutes: int :param app_consistent_frequency_in_minutes: The app consistent snapshot frequency (in minutes). :type app_consistent_frequency_in_minutes: int """ _validation = { 'instance_type': {'required': True}, } _attribute_map = { 'instance_type': {'key': 'instanceType', 'type': 'str'}, 'recovery_point_history_in_minutes': {'key': 'recoveryPointHistoryInMinutes', 'type': 'int'}, 'crash_consistent_frequency_in_minutes': {'key': 'crashConsistentFrequencyInMinutes', 'type': 'int'}, 'app_consistent_frequency_in_minutes': {'key': 'appConsistentFrequencyInMinutes', 'type': 'int'}, } def __init__( self, *, recovery_point_history_in_minutes: Optional[int] = None, crash_consistent_frequency_in_minutes: Optional[int] = None, app_consistent_frequency_in_minutes: Optional[int] = None, **kwargs ): super(VMwareCbtPolicyCreationInput, self).__init__(**kwargs) self.instance_type = 'VMwareCbt' # type: str self.recovery_point_history_in_minutes = recovery_point_history_in_minutes self.crash_consistent_frequency_in_minutes = crash_consistent_frequency_in_minutes self.app_consistent_frequency_in_minutes = app_consistent_frequency_in_minutes class VmwareCbtPolicyDetails(PolicyProviderSpecificDetails): """VMware Cbt specific policy details. All required parameters must be populated in order to send to Azure. :param instance_type: Required. Gets the class type. Overridden in derived classes.Constant filled by server. :type instance_type: str :param recovery_point_history_in_minutes: The duration in minutes until which the recovery points need to be stored. :type recovery_point_history_in_minutes: int :param app_consistent_frequency_in_minutes: The app consistent snapshot frequency in minutes. :type app_consistent_frequency_in_minutes: int :param crash_consistent_frequency_in_minutes: The crash consistent snapshot frequency in minutes. :type crash_consistent_frequency_in_minutes: int """ _validation = { 'instance_type': {'required': True}, } _attribute_map = { 'instance_type': {'key': 'instanceType', 'type': 'str'}, 'recovery_point_history_in_minutes': {'key': 'recoveryPointHistoryInMinutes', 'type': 'int'}, 'app_consistent_frequency_in_minutes': {'key': 'appConsistentFrequencyInMinutes', 'type': 'int'}, 'crash_consistent_frequency_in_minutes': {'key': 'crashConsistentFrequencyInMinutes', 'type': 'int'}, } def __init__( self, *, recovery_point_history_in_minutes: Optional[int] = None, app_consistent_frequency_in_minutes: Optional[int] = None, crash_consistent_frequency_in_minutes: Optional[int] = None, **kwargs ): super(VmwareCbtPolicyDetails, self).__init__(**kwargs) self.instance_type = 'VMwareCbt' # type: str self.recovery_point_history_in_minutes = recovery_point_history_in_minutes self.app_consistent_frequency_in_minutes = app_consistent_frequency_in_minutes self.crash_consistent_frequency_in_minutes = crash_consistent_frequency_in_minutes class VMwareCbtProtectedDiskDetails(msrest.serialization.Model): """VMwareCbt protected disk details. Variables are only populated by the server, and will be ignored when sending a request. :ivar disk_id: The disk id. :vartype disk_id: str :ivar disk_name: The disk name. :vartype disk_name: str :param disk_type: The disk type. Possible values include: "Standard_LRS", "Premium_LRS", "StandardSSD_LRS". :type disk_type: str or ~azure.mgmt.recoveryservicessiterecovery.models.DiskAccountType :ivar disk_path: The disk path. :vartype disk_path: str :ivar is_os_disk: A value indicating whether the disk is the OS disk. :vartype is_os_disk: str :ivar capacity_in_bytes: The disk capacity in bytes. :vartype capacity_in_bytes: long :ivar log_storage_account_id: The log storage account ARM Id. :vartype log_storage_account_id: str :ivar log_storage_account_sas_secret_name: The key vault secret name of the log storage account. :vartype log_storage_account_sas_secret_name: str :ivar disk_encryption_set_id: The DiskEncryptionSet ARM Id. :vartype disk_encryption_set_id: str :ivar seed_managed_disk_id: The ARM Id of the seed managed disk. :vartype seed_managed_disk_id: str :ivar target_managed_disk_id: The ARM Id of the target managed disk. :vartype target_managed_disk_id: str :param target_disk_name: The name for the target managed disk. :type target_disk_name: str """ _validation = { 'disk_id': {'readonly': True}, 'disk_name': {'readonly': True}, 'disk_path': {'readonly': True}, 'is_os_disk': {'readonly': True}, 'capacity_in_bytes': {'readonly': True}, 'log_storage_account_id': {'readonly': True}, 'log_storage_account_sas_secret_name': {'readonly': True}, 'disk_encryption_set_id': {'readonly': True}, 'seed_managed_disk_id': {'readonly': True}, 'target_managed_disk_id': {'readonly': True}, } _attribute_map = { 'disk_id': {'key': 'diskId', 'type': 'str'}, 'disk_name': {'key': 'diskName', 'type': 'str'}, 'disk_type': {'key': 'diskType', 'type': 'str'}, 'disk_path': {'key': 'diskPath', 'type': 'str'}, 'is_os_disk': {'key': 'isOSDisk', 'type': 'str'}, 'capacity_in_bytes': {'key': 'capacityInBytes',
# -*- coding: utf-8 -*- """ Created on 2020/8/11 @project: SPAIC @filename: Node @author: <NAME> @contact: <EMAIL> @description: 定义神经网络的输入输出接口 """ from ..Network.Assembly import Assembly import torch import numpy as np class Node(Assembly): '''Base class for input encoder and output decoders. ''' _class_label = '<nod>' _is_terminal = True def __init__(self, shape=None, num=None, dec_target=None, dt=None, coding_method=('poisson', 'spike_counts', '...'), coding_var_name='O', node_type=('excitatory', 'inhibitory', 'pyramidal', '...'), **kwargs): super(Node, self).__init__() self._dt = dt self._time = None self.coding_var_name = coding_var_name position = kwargs.get('position', None) if position == None: self.position = [] else: position = np.array(position) assert position.shape[0] == num, " Neuron_position not equal to neuron number" self.position = position if coding_method == ('poisson', 'spike_counts', '...'): raise ValueError('Please specify the coding method such as poisson or spike_counts') else: self.coding_method = coding_method.lower() # The name of coding method self.coding_var_name = coding_var_name if coding_method == 'null': self.is_encoded = True else: self.is_encoded = kwargs.get('is_encoded', False) # 单神经元多脉冲的语音数据集的shape包含脉冲时间以及发放神经元标签,所以不能通过np.prod(shape)获取num,最好还是外部输入num if num is None: raise ValueError('Please set the number of node') else: self.num = num if shape is None: if self.is_encoded: self.shape = (1, 1, num) else: self.shape = (1, num) else: self.shape = tuple([1] + list(shape)) if node_type == ('excitatory', 'inhibitory', 'pyramidal', '...'): self.type = None else: self.type = node_type # Coding parameters self.coding_param = kwargs self.dec_target = dec_target self.source = np.random.rand(*self.shape) #TODO:现在 Encoder, Decoder, Generator功能拆开了,是不是应该把这段放到Decoder类里了, 上边的coding_method也是同理 if self.dec_target is not None: # The size of predict, reward and action is equal to batch_size self.predict = np.zeros((1,)) self.reward = np.zeros((1,)) self.action = np.zeros((1,)) # Parameters of initial operation self.index = 0 self.records = [] self._var_names = list() @property def dt(self): return self._dt @dt.setter def dt(self, dt): self._dt = dt @property def time(self): self._time = self._backend.runtime return self._time @property def time_step(self): return int(self._backend.runtime / self._dt) @time.setter def time(self, time): self._time = time def get_var_names(self): return self._var_names @staticmethod def register(name, coding_class): ''' Register a coding class. Registered encoding or decoding classes can be referred to # via their name. Parameters ---------- name : str A short name for the state updater (e.g. 'poisson', 'spike_counts') coding_class : The subclass of coding object, e.g. an 'PoissonEncoding', 'Spike_Counts'. ''' raise NotImplementedError def torch_coding(self, source, target, device): ''' Args: source (): It is input spike trains for encoding class and output spike trains for decoding class. target (): It is None for encodoing class and labels for decoding class. device (): CPU or CUDA, this parameter is taken from backend Returns: ''' raise NotImplementedError def numpy_coding(self, source, target, device): raise NotImplementedError def tensorflow_coding(self, source, target, device): raise NotImplementedError def build(self, backend): self._backend = backend raise NotImplementedError def __call__(self, data=None): if isinstance(self, Encoder) or isinstance(self, Generator) or isinstance(self, Reward): if isinstance(data, np.ndarray): self.source = data batch_size = data.shape[0] elif isinstance(data, torch.Tensor): self.source = data batch_size = data.shape[0] elif hasattr(data, '__iter__'): self.source = np.array(data) batch_size = self.source.shape[0] else: self.source = np.array([data]) batch_size = 1 if self._backend is None: self.batch_size = batch_size else: self._backend.set_batch_size(batch_size) self.batch_size = None self.new_input = True elif isinstance(self, Decoder): return self.predict # ====================================================================================================================== # Encoders # ====================================================================================================================== class Encoder(Node): ''' Five encoding method are provided, as shown below (key: class): 1. 'sstb': SigleSpikeToBinary, 2. 'mstb': MultipleSpikeToBinary 3. 'poisson': PoissonEncoding 4. 'latency': Latency 5. 'relative_latency': Relative_Latency ''' _coding_subclasses = dict() def __init__(self, shape=None, num=None, dec_target=None, dt=None, coding_method=('poisson', 'spike_counts', '...'), coding_var_name='O', node_type=('excitatory', 'inhibitory', 'pyramidal', '...'), **kwargs): super(Encoder, self).__init__(shape, num, dec_target, dt, coding_method, coding_var_name, node_type, **kwargs) self.batch_size = None self.new_input = True coding_method = coding_method.lower() if coding_method == 'null': self.is_encoded = True else: self.is_encoded = kwargs.get('is_encoded', False) def __new__(cls, shape=None, num=None, dec_target=None, dt=None, coding_method=('poisson', 'spike_counts', '...'), coding_var_name='O', node_type=('excitatory', 'inhibitory', 'pyramidal', '...'), **kwargs): coding_method = coding_method.lower() if cls is not Encoder: return super().__new__(cls) elif coding_method in Encoder._coding_subclasses: return super().__new__(Encoder._coding_subclasses[coding_method]) else: raise ValueError("No coding method: %s in Encoding classes" % coding_method) @staticmethod def register(name, coding_class): ''' Register a coding class. Registered encoding or decoding classes can be referred to # via their name. Parameters ---------- name : str A short name for the state updater (e.g. 'poisson', 'spike_counts') coding_class : The subclass of coding object, e.g. an 'PoissonEncoding', 'Spike_Counts'. ''' # only deal with lower case names name = name.lower() if name in Encoder._coding_subclasses: raise ValueError(('A coding class with the name "%s" has already been registered') % name) if not issubclass(coding_class, Encoder): raise ValueError( ('Given class of type %s does not seem to be a valid encoding class.' % str(type(coding_class)))) Encoder._coding_subclasses[name] = coding_class def init_state(self): self.index = 0 # initial operation: encoding input features into spike patterns def get_input(self): self.index = 0 if self.sim_name == 'pytorch': spikes = self.torch_coding(self.source, self.device) else: spikes = self.numpy_coding(self.source, self.device) self.all_spikes = spikes return self.all_spikes # stand alone operation: get spike pattern in every time step def next_stage(self): # For hardware applications, call next_stage at each time step to get spike data of the current time step. if self.new_input: self.get_input() self.new_input = False self.index += 1 return self.all_spikes[self.index-1] def reset(self): # Called at the start of each epoch self.init_state() def build(self, backend): self._backend = backend self.sim_name = backend.backend_name self.device = backend.device if self.dt is None: self.dt = backend.dt if self.batch_size is not None: self._backend.set_batch_size(self.batch_size) if self.sim_name == 'pytorch': spikes = self.torch_coding(self.source, self.device) # (time_step, batch_size, neuron_shape) else: spikes = self.numpy_coding(self.source, self.device) self.all_spikes = spikes # self.shape = spikes[0].shape key = self.id + ':' + '{'+self.coding_var_name+'}' self._var_names.append(key) backend.add_variable(key, self.shape, value=0) backend.register_initial(None, self.init_state, []) backend.register_standalone(key, self.next_stage, []) # ====================================================================================================================== # Decoders # ====================================================================================================================== class Decoder(Node): ''' Five decoding method are provided, as shown below (key: class): 1. 'spike_counts': Spike_Counts 2. 'first_spike': First_Spike 3. 'time_spike_counts': TimeSpike_Counts 4. 'time_softmax': Time_Softmax 5. 'final_step_voltage': Final_Step_Voltage ''' _coding_subclasses = dict() def __init__(self, num=None, dec_target=None, dt=None, coding_method=('poisson', 'spike_counts', '...'), coding_var_name='O', node_type=('excitatory', 'inhibitory', 'pyramidal', '...'), **kwargs): super(Decoder, self).__init__(None, num, dec_target, dt, coding_method, coding_var_name, node_type, **kwargs) assert num == dec_target.num, ('The num of Decoder is not consistent with neuron_number of NeuronGroup') def __new__(cls, num=None, dec_target=None, dt=None, coding_method=('poisson', 'spike_counts', '...'), coding_var_name='O', node_type=('excitatory', 'inhibitory', 'pyramidal', '...'), **kwargs): coding_method = coding_method.lower() if cls is not Decoder: return super().__new__(cls) elif coding_method in Decoder._coding_subclasses: return super().__new__(Decoder._coding_subclasses[coding_method]) else: raise ValueError("No coding method: %s in Decoding classes" % coding_method) @staticmethod def register(name, coding_class): ''' Register a coding class. Registered encoding or decoding classes can be referred to # via their name. Parameters ---------- name : str A short name for the state updater (e.g. 'poisson', 'spike_counts') coding_class : The subclass of coding object, e.g. an 'PoissonEncoding', 'Spike_Counts'. ''' # only deal with lower case names name = name.lower() if name in Decoder._coding_subclasses: raise ValueError(('A coding class with the name "%s" has already been registered') % name) if not issubclass(coding_class, Decoder): raise ValueError( ('Given class of type %s does not seem to be a valid decoding class.' % str(type(coding_class)))) Decoder._coding_subclasses[name] = coding_class def init_state(self): self.index = 0 # stand alone operation: decoding spike patterns. Predict can be predict labels or RL action def get_output(self, output): if (self.index % self.time_step) == 0: shape = list(output.shape) dec_shape = [self.time_step] + shape if type(output).__name__ == 'Tensor': self.records = torch.zeros(dec_shape, device=self.device) else: self.records = np.zeros(dec_shape) self.index = 0 self.records[self.index % self.time_step, :] = output self.index += 1 if self.index >= self.time_step: if self.sim_name == 'pytorch': self.predict = self.torch_coding(self.records, self.source, self.device) else: self.predict = self.numpy_coding(self.records, self.source, self.device) return 0 def decode_step(self, output): # For hardware applications, call decode_step at each time step to store the output spike data. self.records[self.index, :] = output self.index += 1 # When terminating an epoch, numpy_coding can be called if you want to get the predict matrix # self.predict = self.numpy_coding(self.records, self.source, self.device) def reset(self, decode_shape): # decode_shape is [self.time_step] + output.shape self.init_state() dec_shape = decode_shape self.records = np.zeros(dec_shape) def build(self, backend): self._backend = backend self.sim_name = backend.backend_name self.device = backend.device if self.dt is None: self.dt = backend.dt output_name = self.dec_target.id + ':' + '{'+self.coding_var_name+'}' backend.register_initial(None, self.init_state, []) backend.register_standalone(None, self.get_output, [output_name]) # ====================================================================================================================== # Rewards # ====================================================================================================================== class Reward(Node): ''' Three reward method are provided, as shown below (key: class): 1. 'global_reward', Global_Reward 2. 'xor_reward': XOR_Reward 3. 'da_reward': DA_Reward 4. 'environment_reward': Environment_Reward ''' _coding_subclasses = dict() def __init__(self, shape=None, num=None, dec_target=None,
# CPLEX model for the choice-based facility location # and pricing problem with discrete prices (compact formulation) # Alternatives are duplicated to account for different possible price levels. # General import time import numpy as np # CPLEX import cplex from cplex.exceptions import CplexSolverError # Project import functions # Data #import data_N80_I14 as data_file import data_N08_I10 as data_file def getModel(data): # Initialize the model t_in = time.time() model = cplex.Cplex() # Set number of threads #model.parameters.threads.set(model.get_num_cores()) model.parameters.threads.set(1) print('\n############\nTHREADS = ', end='') print(model.parameters.threads.get()) print('############\n') ########################################## ##### ----- OBJECTIVE FUNCTION ----- ##### ########################################## model.objective.set_sense(model.objective.sense.maximize) ########################################## ##### ----- DECISION VARIABLES ----- ##### ########################################## # Customer choice variables objVar = [] typeVar = [] nameVar = [] lbVar = [] ubVar = [] for i in range(data['I_tot_exp']): for n in range(data['N']): for r in range(data['R']): if data['operator'][data['alt'][i]] == 1: objVar.append((data['p'][i] - data['customer_cost'][data['alt'][i]]) * data['popN'][n]/data['R']) else: objVar.append(0.0) typeVar.append(model.variables.type.binary) nameVar.append('x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']') lbVar.append(0.0) ubVar.append(1.0) model.variables.add(obj = [objVar[i] for i in range(len(objVar))], types = [typeVar[i] for i in range(len(typeVar))], lb = [lbVar[i] for i in range(len(typeVar))], ub = [ubVar[i] for i in range(len(typeVar))], names = [nameVar[i] for i in range(len(nameVar))]) # Facility location variables objVar = [] typeVar = [] nameVar = [] for i in range(data['I_tot_exp']): if data['operator'][data['alt'][i]] == 1: objVar.append(-data['fixed_cost'][data['alt'][i]]) else: objVar.append(0.0) typeVar.append(model.variables.type.binary) nameVar.append('y[' + str(i) + ']') model.variables.add(obj = [objVar[i] for i in range(len(objVar))], types = [typeVar[i] for i in range(len(typeVar))], names = [nameVar[i] for i in range(len(nameVar))]) # Auxiliary demand variables typeVar = [] nameVar = [] lbVar = [] ubVar = [] for i in range(data['I_tot_exp']): typeVar.append(model.variables.type.continuous) nameVar.append('d[' + str(i) + ']') lbVar.append(0.0) ubVar.append(data['Pop']) model.variables.add(types = [typeVar[i] for i in range(len(typeVar))], lb = [lbVar[i] for i in range(len(typeVar))], ub = [ubVar[i] for i in range(len(typeVar))], names = [nameVar[i] for i in range(len(nameVar))]) print('\nCPLEX model: all decision variables added. N variables: %r. Time: %r'\ %(model.variables.get_num(), round(time.time()-t_in,2))) # Creating a dictionary that maps variable names to indices, to speed up constraints creation nameToIndex = { n : j for j, n in enumerate(model.variables.get_names()) } ######################################### ##### -------- CONSTRAINTS -------- ##### ######################################### indicesConstr = [] coefsConstr = [] sensesConstr = [] rhsConstr = [] ################################################### ### ------ Instance-specific constraints ------ ### ################################################### ### --- Instance-specific constraints on the binary variables --- ### for i in range(data['I_out_exp']): indicesConstr.append([nameToIndex['y[' + str(i) + ']']]) coefsConstr.append([1.0]) sensesConstr.append('E') rhsConstr.append(1.0) ### --- Choose at most one price level per alternative --- ### for alt in range(data['I_opt_out'], data['I_tot']): ind = [] co = [] for i in range(data['I_out_exp'], data['I_tot_exp']): if data['alt'][i] == alt: ind.append(nameToIndex['y[' + str(i) + ']']) co.append(1.0) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('L') rhsConstr.append(1.0) ################################################### ### ------------ Choice constraints ----------- ### ################################################### # Each customer chooses one alternative for n in range(data['N']): for r in range(data['R']): ind = [] co = [] for i in range(data['I_tot_exp']): ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']']) co.append(1.0) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('E') rhsConstr.append(1.0) # A customer cannot choose an alternative that is not offered for i in range(data['I_tot_exp']): for n in range(data['N']): for r in range(data['R']): indicesConstr.append([nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'], nameToIndex['y[' + str(i) + ']']]) coefsConstr.append([1.0, -1.0]) sensesConstr.append('L') rhsConstr.append(0.0) # A customer chooses the alternative with the highest utility for i in range(data['I_tot_exp']): for n in range(data['N']): for r in range(data['R']): ind = [] co = [] for j in range(data['I_tot_exp']): ind.append(nameToIndex['x[' + str(j) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']']) co.append(data['U'][j,n,r]) ind.append(nameToIndex['y[' + str(i) + ']']) co.append(-data['U'][i,n,r]) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('G') rhsConstr.append(0.0) ####################################### #### ---- Auxiliary constraints --- ### ####################################### ### Calculating demands (not part of the model) for i in range(data['I_tot_exp']): ind = [] co = [] for n in range(data['N']): for r in range(data['R']): ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']']) co.append(-data['popN'][n]/data['R']) ind.append(nameToIndex['d[' + str(i) + ']']) co.append(1.0) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('E') rhsConstr.append(0.0) model.linear_constraints.add(lin_expr = [[indicesConstr[i], coefsConstr[i]] for i in range(len(indicesConstr))], senses = [sensesConstr[i] for i in range(len(sensesConstr))], rhs = [rhsConstr[i] for i in range(len(rhsConstr))]) print('CPLEX model: all constraints added. N constraints: %r. Time: %r\n'\ %(model.linear_constraints.get_num(), round(time.time()-t_in,2))) return model def solveModel(data, model): try: #model.set_results_stream(None) #model.set_warning_stream(None) model.solve() ### PRINT OBJ FUNCTION print('Objective function value (maximum profit): {:10.4f}'.format(model.solution.get_objective_value())) ### INITIALIZE DICTIONARY OF RESULTS AND SAVE RESULTS results = {} results['facilities'] = np.empty(data['I_tot_exp']) results['demand'] = np.empty(data['I_tot_exp']) for i in range(data['I_tot_exp']): results['facilities'][i] = model.solution.get_values('y[' + str(i) + ']') results['demand'][i] = model.solution.get_values('d[' + str(i) + ']') ### PRINT PRICES, DEMANDS, PROFITS print('\nAlt Name Supplier Facility Price Demand Market share') for i in range(data['I_tot_exp']): print('{:3d} {:6s} {:2d} {:4.0f} {:6.4f} {:8.3f} {:7.4f}' .format(i, data['name_mapping'][data['alt'][i]], data['operator'][data['alt'][i]], results['facilities'][i], data['p'][i], results['demand'][i], results['demand'][i] / data['Pop'])) return results except CplexSolverError: raise Exception('Exception raised during solve') def modelOneScenario(data, r): print('SCENARIO {:4d} '.format(r), end='') model = cplex.Cplex() ########################################## ##### ----- OBJECTIVE FUNCTION ----- ##### ########################################## model.objective.set_sense(model.objective.sense.maximize) ########################################## ##### ----- DECISION VARIABLES ----- ##### ########################################## # Customer choice variables objVar = [] typeVar = [] nameVar = [] lbVar = [] ubVar = [] for i in range(data['I_tot_exp']): for n in range(data['N']): if data['operator'][data['alt'][i]] == 1: objVar.append((data['p'][i] - data['customer_cost'][data['alt'][i]]) * data['popN'][n]) else: objVar.append(0.0) typeVar.append(model.variables.type.binary) nameVar.append('x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']') lbVar.append(0.0) ubVar.append(1.0) model.variables.add(obj = [objVar[i] for i in range(len(objVar))], types = [typeVar[i] for i in range(len(typeVar))], lb = [lbVar[i] for i in range(len(typeVar))], ub = [ubVar[i] for i in range(len(typeVar))], names = [nameVar[i] for i in range(len(nameVar))]) # Facility location variables objVar = [] typeVar = [] nameVar = [] for i in range(data['I_tot_exp']): if data['operator'][data['alt'][i]] == 1: objVar.append(-data['fixed_cost'][data['alt'][i]]) else: objVar.append(0.0) typeVar.append(model.variables.type.binary) nameVar.append('y[' + str(i) + ']') model.variables.add(obj = [objVar[i] for i in range(len(objVar))], types = [typeVar[i] for i in range(len(typeVar))], names = [nameVar[i] for i in range(len(nameVar))]) # Creating a dictionary that maps variable names to indices, to speed up constraints creation nameToIndex = { n : j for j, n in enumerate(model.variables.get_names()) } ######################################### ##### -------- CONSTRAINTS -------- ##### ######################################### indicesConstr = [] coefsConstr = [] sensesConstr = [] rhsConstr = [] ### --- Instance-specific constraints on the binary variables --- ### for i in range(data['I_out_exp']): indicesConstr.append([nameToIndex['y[' + str(i) + ']']]) coefsConstr.append([1.0]) sensesConstr.append('E') rhsConstr.append(1.0) for i in range(data['I_out_exp'], data['I_tot_exp']): if data['list_open'][i] == 1: indicesConstr.append([nameToIndex['y[' + str(i) + ']']]) coefsConstr.append([1.0]) sensesConstr.append('E') rhsConstr.append(1.0) ### --- Choose at most one price level per alternative --- ### for alt in range(data['I_opt_out'], data['I_tot']): ind = [] co = [] for i in range(data['I_out_exp'], data['I_tot_exp']): if data['alt'][i] == alt: ind.append(nameToIndex['y[' + str(i) + ']']) co.append(1.0) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('L') rhsConstr.append(1.0) # Each customer chooses one alternative for n in range(data['N']): ind = [] co = [] for i in range(data['I_tot_exp']): ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']']) co.append(1.0) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('E') rhsConstr.append(1.0) # A customer cannot choose an alternative that is not offered for i in range(data['I_tot_exp']): for n in range(data['N']): indicesConstr.append([nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'], nameToIndex['y[' + str(i) + ']']]) coefsConstr.append([1.0, -1.0]) sensesConstr.append('L') rhsConstr.append(0.0) # A customer chooses the alternative with the highest utility for i in range(data['I_tot_exp']): for n in range(data['N']): ind = [] co = [] for j in range(data['I_tot_exp']): ind.append(nameToIndex['x[' + str(j) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']']) co.append(data['U'][j,n,r]) ind.append(nameToIndex['y[' + str(i) + ']']) co.append(-data['U'][i,n,r]) indicesConstr.append(ind) coefsConstr.append(co) sensesConstr.append('G') rhsConstr.append(0.0) model.linear_constraints.add(lin_expr = [[indicesConstr[i], coefsConstr[i]] for i in range(len(indicesConstr))], senses = [sensesConstr[i] for i in range(len(sensesConstr))], rhs = [rhsConstr[i] for i in range(len(rhsConstr))]) ######################################### ##### ----------- SOLVE ----------- ##### ######################################### try: model.set_results_stream(None) #model.set_warning_stream(None) model.parameters.timelimit.set(172000.0) model.solve() OF = model.solution.get_objective_value() y = np.empty(data['I_tot_exp']) for i in range(data['I_tot_exp']): y[i] =
# File: pan_connector.py # # Copyright (c) 2014-2022 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. # # import json import re import time import phantom.app as phantom import requests import xmltodict from phantom.action_result import ActionResult from phantom.base_connector import BaseConnector from pan_consts import * class PanConnector(BaseConnector): # The actions supported by this connector ACTION_ID_BLOCK_URL = "block_url" ACTION_ID_UNBLOCK_URL = "unblock_url" ACTION_ID_BLOCK_APPLICATION = "block_application" ACTION_ID_UNBLOCK_APPLICATION = "unblock_application" ACTION_ID_BLOCK_IP = "block_ip" ACTION_ID_UNBLOCK_IP = "unblock_ip" ACTION_ID_LIST_APPS = "list_apps" def __init__(self): # Call the BaseConnectors init first super(PanConnector, self).__init__() self._base_url = None self._key = None self._param = None self._device_version = None def initialize(self): config = self.get_config() # Base URL self._base_url = 'https://' + config[phantom.APP_JSON_DEVICE] + '/api/' return phantom.APP_SUCCESS def _parse_response_msg(self, response, action_result): msg = response.get('msg') if msg is None: return # parse it as a dictionary if isinstance(msg, dict): line = msg.get('line') if line is None: return if isinstance(line, list): action_result.append_to_message("message: '{}'".format(', '.join(line))) else: action_result.append_to_message("message: '{}'".format(line)) return # Covert msg from bytes to str type if type(msg) == bytes: msg = msg.decode('utf-8') # parse it as a string if type(msg) == str: action_result.append_to_message("message: '{}'".format(msg)) return def _parse_response(self, response_dict, action_result): # multiple keys could be present even if the response is a failure self.debug_print('response_dict', response_dict) response = response_dict.get('response') if response is None: return action_result.set_status(phantom.APP_ERROR, PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response')) status = response.get('@status') if status is None: return action_result.set_status(phantom.APP_ERROR, PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response/status')) if status != 'success': action_result.set_status(phantom.APP_ERROR, PAN_ERR_REPLY_NOT_SUCCESS.format(status=status)) else: action_result.set_status(phantom.APP_SUCCESS, PAN_SUCC_REST_CALL_SUCCEEDED) code = response.get('@code') if code is not None: action_result.append_to_message("code: '{}'".format(code)) self._parse_response_msg(response, action_result) result = response.get('result') if result is not None: action_result.add_data(result) return action_result.get_status() def _get_key(self): if self._key is not None: # key already created for this call return phantom.APP_SUCCESS config = self.get_config() # Connectivity self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, config[phantom.APP_JSON_DEVICE]) username = config[phantom.APP_JSON_USERNAME] password = config[phantom.APP_JSON_PASSWORD] data = {'type': 'keygen', 'user': username, 'password': password} try: response = requests.post(self._base_url, data=data, verify=config[phantom.APP_JSON_VERIFY], timeout=PAN_DEFAULT_TIMEOUT) except Exception as e: self.debug_print(PAN_ERR_DEVICE_CONNECTIVITY, e) return self.set_status(phantom.APP_ERROR, PAN_ERR_DEVICE_CONNECTIVITY, e) xml = response.text # self.save_progress(PAN_PROG_GOT_REPLY) try: response_dict = xmltodict.parse(xml) except Exception as e: return self.set_status(phantom.APP_ERROR, PAN_ERR_UNABLE_TO_PARSE_REPLY, e) response = response_dict.get('response') if response is None: message = PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response') return self.set_status(phantom.APP_ERROR, message) status = response.get('@status') if status is None: message = PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response/status') return self.set_status(phantom.APP_ERROR, message) if status != 'success': message = PAN_ERR_REPLY_NOT_SUCCESS.format(status=status) json_resp = json.dumps(response).replace('{', ':') json_resp = json_resp.replace('}', '') message += ". Response from server: {0}".format(json_resp) return self.set_status(phantom.APP_ERROR, message) result = response.get('result') if result is None: message = PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response/result') return self.set_status(phantom.APP_ERROR, message) key = result.get('key') if key is None: message = PAN_ERR_REPLY_FORMAT_KEY_MISSING.format(key='response/result/key') return self.set_status(phantom.APP_ERROR, message) self._key = key ver_ar = ActionResult() ret_val = self._validate_version(ver_ar) if phantom.is_fail(ret_val): self.set_status(ret_val, ver_ar.get_message()) self.append_to_message(PAN_ERR_TEST_CONNECTIVITY_FAILED) return self.get_status() return phantom.APP_SUCCESS def _test_connectivity(self, param): # Progress self.save_progress(PAN_PROG_USING_BASE_URL, base_url=self._base_url) status = self._get_key() if phantom.is_fail(status): self.append_to_message(PAN_ERR_TEST_CONNECTIVITY_FAILED) return self.get_status() self.set_status_save_progress(phantom.APP_SUCCESS, PAN_SUCC_TEST_CONNECTIVITY_PASSED) return self.get_status() def _make_rest_call(self, data, action_result): self.debug_print("Making rest call") self.debug_print("_make_rest_call::data", data) config = self.get_config() try: response = requests.post(self._base_url, data=data, verify=config[phantom.APP_JSON_VERIFY], timeout=PAN_DEFAULT_TIMEOUT) except Exception as e: self.debug_print(PAN_ERR_DEVICE_CONNECTIVITY, e) return action_result.set_status(phantom.APP_ERROR, PAN_ERR_DEVICE_CONNECTIVITY, e) xml = response.text action_result.add_debug_data(xml) # self.debug_print("REST Response", str(xml)) try: response_dict = xmltodict.parse(xml) except Exception as e: self.save_progress(PAN_ERR_UNABLE_TO_PARSE_REPLY) return action_result.set_status(phantom.APP_ERROR, PAN_ERR_UNABLE_TO_PARSE_REPLY, e) status = self._parse_response(response_dict, action_result) if phantom.is_fail(status): return action_result.get_status() return action_result.get_status() def _get_first_allow_policy(self, action_result): ret_name = None result_data = action_result.get_data() if len(result_data) == 0: return (action_result.set_status(phantom.APP_ERROR, PAN_ERR_PARSE_POLICY_DATA), ret_name) result_data = result_data[0] rules = result_data['rules'] entries = rules.get('entry') if entries is None: # Just means no rules have been configured return (action_result.set_status(phantom.APP_ERROR, PAN_ERR_NO_POLICY_ENTRIES_FOUND), ret_name) # Convert entries into array, if it's a dict (this will happen if there is only one rule) if isinstance(entries, dict): entry_list = [] entry_list.append(entries) entries = entry_list for entry in entries: action = entry['action'] if action is None: continue if isinstance(action, dict): action = action['#text'] if action == 'allow': ret_name = entry['@name'] break if ret_name is None: return (action_result.set_status(phantom.APP_ERROR, PAN_ERR_NO_ALLOW_POLICY_ENTRIES_FOUND), ret_name) return (action_result.set_status(phantom.APP_SUCCESS), ret_name) def _add_url_security_policy(self, vsys, action_result, type, name=None): element = SEC_POL_DEF_ELEMS sec_policy_name = SEC_POL_NAME.format(type=type) allow_rule_name = self._param.get(PAN_JSON_SEC_POLICY) self.debug_print("Creating Security Policy", sec_policy_name) if type != SEC_POL_URL_TYPE: return action_result.set_status(phantom.APP_ERROR, PAN_ERR_CREATE_UNKNOWN_TYPE_SEC_POL) # The URL policy is actually an 'allow' policy, which uses a URL Profile with block lists. # That's the way to block urls in PAN. # So the policy needs to be placed just before the topmost 'allow' policy for things to work properly. # So get the list of all the security policies, we need to parse through them to get the first 'allow' # However if the user has already supplied a policy name, then use that. if allow_rule_name is None: data = {'type': 'config', 'action': 'get', 'key': self._key, 'xpath': SEC_POL_RULES_XPATH.format(vsys=vsys)} policy_list_act_res = ActionResult() status = self._make_rest_call(data, policy_list_act_res) if phantom.is_fail(status): return action_result.set_status(policy_list_act_res.get_status(), policy_list_act_res.get_message()) self.debug_print("Get Policies Action Result", policy_list_act_res) status, allow_rule_name = self._get_first_allow_policy(policy_list_act_res) if phantom.is_fail(status): return action_result.set_status(status, policy_list_act_res.get_message()) self.debug_print("allow_rule_name", allow_rule_name) element += ACTION_NODE_ALLOW element += URL_PROF_SEC_POL_ELEM.format(url_prof_name=BLOCK_URL_PROF_NAME) element += APP_GRP_SEC_POL_ELEM.format(app_group_name="any") element += IP_GRP_SEC_POL_ELEM.format(ip_group_name="any") xpath = SEC_POL_XPATH.format(vsys=vsys, sec_policy_name=sec_policy_name) data = {'type': 'config', 'action': 'set', 'key': self._key, 'xpath': xpath, 'element': element} self.debug_print("_add_url_security_policy::data", data) status = self._make_rest_call(data, action_result) if phantom.is_fail(status): return action_result.get_status() if allow_rule_name == sec_policy_name: # We are the first allow rule, so no need to move return action_result.get_status() # move it to the top of the first policy with an allow action data = {'type': 'config', 'action': 'move', 'key': self._key, 'xpath': xpath, 'where': 'before', 'dst': allow_rule_name} self.debug_print("_add_url_security_policy::move data", data) move_action_result = ActionResult() status = self._make_rest_call(data, move_action_result) if phantom.is_fail(status): # check if we also treat this error as an error msg = move_action_result.get_message() if msg.find('already at the top') == -1: # looks like an error that we should report action_result.set_status(move_action_result.get_status(), move_action_result.get_message()) return action_result.get_status() return action_result.get_status() def _add_security_policy(self, vsys, action_result, type, name=None, use_source=False, block_ip_grp=None): if use_source: sec_policy_name = SEC_POL_NAME_SRC.format(type=type) element = SEC_POL_DEF_ELEMS_SRC else: sec_policy_name = SEC_POL_NAME.format(type=type) element = SEC_POL_DEF_ELEMS self.debug_print("Creating Security Policy", sec_policy_name) if type == SEC_POL_URL_TYPE: # URL needs to be handled differently return self._add_url_security_policy(vsys, action_result, type, name) elif type == SEC_POL_IP_TYPE: element += ACTION_NODE_DENY element += APP_GRP_SEC_POL_ELEM.format(app_group_name="any") if use_source: element += IP_GRP_SEC_POL_ELEM_SRC.format(ip_group_name=block_ip_grp) else: element += IP_GRP_SEC_POL_ELEM.format(ip_group_name=BLOCK_IP_GROUP_NAME) elif type == SEC_POL_APP_TYPE: element += ACTION_NODE_DENY element += APP_GRP_SEC_POL_ELEM.format(app_group_name=name) element += IP_GRP_SEC_POL_ELEM.format(ip_group_name="any") else: return action_result.set_status(phantom.APP_ERROR, PAN_ERR_CREATE_UNKNOWN_TYPE_SEC_POL) xpath = SEC_POL_XPATH.format(vsys=vsys, sec_policy_name=sec_policy_name) data = {'type': 'config', 'action': 'set', 'key': self._key, 'xpath': xpath, 'element': element} self.debug_print("_add_security_policy::data", data) status = self._make_rest_call(data, action_result) if phantom.is_fail(status): return action_result.get_status() # move it to the top data = {'type': 'config', 'action': 'move', 'key': self._key, 'xpath': xpath, 'where': 'top'} self.debug_print("_add_security_policy::move data", data) move_action_result = ActionResult() status = self._make_rest_call(data, move_action_result) if phantom.is_fail(status): # check if we also treat this error as an error msg = move_action_result.get_message() if msg.find('already at the top') == -1: # looks like an error that we should report action_result.set_status(move_action_result.get_status(), move_action_result.get_message()) return action_result.get_status() return action_result.get_status() def _commit_config(self, action_result): self.debug_print("Commiting the config") data = {'type': 'commit', 'cmd': '<commit></commit>', 'key': self._key} status = self._make_rest_call(data, action_result) if phantom.is_fail(status): return action_result.get_status() # Get the job id of the commit call from the result_data, also pop it since we don't need it # to be in the action result result_data = action_result.get_data() if len(result_data) == 0: return action_result.get_status() result_data = result_data.pop(0) job_id = result_data['job'] self.debug_print("commit job id: ", job_id) while True: data = {'type': 'op', 'key': self._key, 'cmd': '<show><jobs><id>{job}</id></jobs></show>'.format(job=job_id)} status_action_result = ActionResult() status = self._make_rest_call(data, status_action_result) if phantom.is_fail(status): action_result.set_status(phantom.APP_SUCCESS, status_action_result.get_message()) return action_result.get_status() self.debug_print("status", status_action_result) # get the result_data and the job status result_data = status_action_result.get_data() job = result_data[0]['job'] if job['status'] == 'FIN': break # send the % progress self.send_progress(PAN_PROG_COMMIT_PROGRESS, progress=job['progress']) time.sleep(2) return action_result.get_status() def _unblock_url(self, param): status = self._get_key() if phantom.is_fail(status): return self.get_status() action_result = self.add_action_result(ActionResult(dict(param))) vsys = param.get(PAN_JSON_VSYS, 'vsys1') self.debug_print("Removing the Blocked URL") # Add the block url, will create the url profile if not present block_url = param[PAN_JSON_URL] xpath = "{0}{1}".format(URL_PROF_XPATH.format(vsys=vsys, url_profile_name=BLOCK_URL_PROF_NAME), DEL_URL_XPATH.format(url=block_url)) data = {'type':
), ), # COMMETHOD( [], HRESULT, 'CreateComputeShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11ComputeShader)), 'ppComputeShader' ), ), # COMMETHOD( [], HRESULT, 'CreateClassLinkage', ( ['out'], POINTER(POINTER(ID3D11ClassLinkage)), 'ppLinkage' ), ), # COMMETHOD( [], HRESULT, 'CreateBlendState', ( ['in'], POINTER(D3D11_BLEND_DESC), 'pBlendStateDesc' ), ( ['out'], POINTER(POINTER(ID3D11BlendState)), 'ppBlendState' ), ), # COMMETHOD( [], HRESULT, 'CreateDepthStencilState', ( ['in'], POINTER(D3D11_DEPTH_STENCIL_DESC), 'pDepthStencilDesc' ), ( ['out'], POINTER(POINTER(ID3D11DepthStencilState)), 'ppDepthStencilState' ), ), # COMMETHOD( [], HRESULT, 'CreateRasterizerState', ( ['in'], POINTER(D3D11_RASTERIZER_DESC), 'pRasterizerDesc' ), ( ['out'], POINTER(POINTER(ID3D11RasterizerState)), 'ppRasterizerState' ), ), # COMMETHOD( [], HRESULT, 'CreateSamplerState', ( ['in'], POINTER(D3D11_SAMPLER_DESC), 'pSamplerDesc' ), ( ['out'], POINTER(POINTER(ID3D11SamplerState)), 'ppSamplerState' ), ), # COMMETHOD( [], HRESULT, 'CreateQuery', ( ['in'], POINTER(D3D11_QUERY_DESC), 'pQueryDesc' ), ( ['out'], POINTER(POINTER(ID3D11Query)), 'ppQuery' ), ), # COMMETHOD( [], HRESULT, 'CreatePredicate', ( ['in'], POINTER(D3D11_QUERY_DESC), 'pPredicateDesc' ), ( ['out'], POINTER(POINTER(ID3D11Predicate)), 'ppPredicate' ), ), # COMMETHOD( [], HRESULT, 'CreateCounter', ( ['in'], POINTER(D3D11_COUNTER_DESC), 'pCounterDesc' ), ( ['out'], POINTER(POINTER(ID3D11Counter)), 'ppCounter' ), ), # Reserved parameter; must be 0 COMMETHOD( [], HRESULT, 'CreateDeferredContext', (['in'], UINT, 'ContextFlags'), ( ['out'], POINTER(POINTER(ID3D11DeviceContext)), 'ppDeferredContext' ), ), # COMMETHOD( [], HRESULT, 'OpenSharedResource', (['in'], HANDLE, 'hResource'), (['in'], REFIID, 'ReturnedInterface'), ( ['out'], POINTER(POINTER(VOID)), 'ppResource' ), ), # Check* # COMMETHOD( [], HRESULT, 'CheckFormatSupport', (['in'], DXGI_FORMAT, 'Format'), ( ['out'], POINTER(UINT), 'pFormatSupport' ), ), # COMMETHOD( [], HRESULT, 'CheckMultisampleQualityLevels', (['in'], DXGI_FORMAT, 'Format'), (['in'], UINT, 'SampleCount'), ( ['out'], POINTER(UINT), 'pNumQualityLevels' ), ), COMMETHOD( [], VOID, 'CheckCounterInfo', ( ['out'], POINTER(D3D11_COUNTER_INFO), 'pCounterInfo' ), ), # COMMETHOD( [], HRESULT, 'CheckCounter', ( ['in'], POINTER(D3D11_COUNTER_DESC), 'pDesc' ), ( ['out'], POINTER(D3D11_COUNTER_TYPE), 'pType' ), (['in'], POINTER(UINT), 'pActiveCounters'), ( ['out'], LPSTR, 'szName' ), ( ['out', 'in'], POINTER(UINT), 'pNameLength' ), ( ['out'], LPSTR, 'szUnits' ), (['in'], POINTER(UINT), 'pUnitsLength'), ( ['out'], LPSTR, 'szDescription' ), (['in'], POINTER(UINT), 'pDescriptionLength'), ), # COMMETHOD( [], HRESULT, 'CheckFeatureSupport', (['in'], D3D11_FEATURE, 'Feature'), ( ['out'], POINTER(VOID), 'pFeatureSupportData' ), (['in'], UINT, 'FeatureSupportDataSize'), ), # COMMETHOD( [], HRESULT, 'GetPrivateData', (['in'], REFGUID, 'guid'), ( ['out', 'in'], POINTER(UINT), 'pDataSize' ), ( ['out'], POINTER(VOID), 'pData' ), ), # COMMETHOD( [], HRESULT, 'SetPrivateData', (['in'], REFGUID, 'guid'), (['in'], UINT, 'DataSize'), ( ['in'], POINTER(VOID), 'pData' ), ), # COMMETHOD( [], HRESULT, 'SetPrivateDataInterface', (['in'], REFGUID, 'guid'), ( ['in'], POINTER(comtypes.IUnknown), 'pData' ), ), COMMETHOD( [], D3D_FEATURE_LEVEL, 'GetFeatureLevel', ), COMMETHOD( [], UINT, 'GetCreationFlags', ), COMMETHOD( [], HRESULT, 'GetDeviceRemovedReason', ), COMMETHOD( [], VOID, 'GetImmediateContext', ( ['out'], POINTER(POINTER(ID3D11DeviceContext)), 'ppImmediateContext' ), ), COMMETHOD( [], HRESULT, 'SetExceptionMode', (['in'], UINT, 'RaiseFlags'), ), COMMETHOD( [], UINT, 'GetExceptionMode', ), ] class ID3D11VideoDecoder(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoProcessorEnumerator(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoProcessor(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11AuthenticatedChannel(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11CryptoSession(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoDecoderOutputView(ID3D11View): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoProcessorInputView(ID3D11View): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoProcessorOutputView(ID3D11View): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoContext(ID3D11DeviceChild): _case_insensitive_ = True _iid_ = None _idlflags_ = [] class ID3D11VideoDevice(comtypes.IUnknown): _case_insensitive_ = True _iid_ = None _idlflags_ = [] ID3D11Device._methods_ = [ # Create* # COMMETHOD( [], HRESULT, 'CreateBuffer', ( ['in'], POINTER(D3D11_BUFFER_DESC), 'pDesc' ), ( ['in'], POINTER(D3D11_SUBRESOURCE_DATA), 'pInitialData' ), ( ['out'], POINTER(POINTER(ID3D11Buffer)), 'ppBuffer' ), ), # COMMETHOD( [], HRESULT, 'CreateTexture1D', ( ['in'], POINTER(D3D11_TEXTURE1D_DESC), 'pDesc' ), ( ['in'], POINTER(D3D11_SUBRESOURCE_DATA), 'pInitialData' ), ( ['out'], POINTER(POINTER(ID3D11Texture1D)), 'ppTexture1D' ), ), # COMMETHOD( [], HRESULT, 'CreateTexture2D', ( ['in'], POINTER(D3D11_TEXTURE2D_DESC), 'pDesc' ), ( ['in'], POINTER(D3D11_SUBRESOURCE_DATA), 'pInitialData' ), ( ['out'], POINTER(POINTER(ID3D11Texture2D)), 'ppTexture2D' ), ), # COMMETHOD( [], HRESULT, 'CreateTexture3D', ( ['in'], POINTER(D3D11_TEXTURE3D_DESC), 'pDesc' ), ( ['in'], POINTER(D3D11_SUBRESOURCE_DATA), 'pInitialData' ), ( ['out'], POINTER(POINTER(ID3D11Texture3D)), 'ppTexture3D' ), ), # COMMETHOD( [], HRESULT, 'CreateShaderResourceView', ( ['in'], POINTER(ID3D11Resource), 'pResource' ), ( ['in'], POINTER(D3D11_SHADER_RESOURCE_VIEW_DESC), 'pDesc' ), ( ['out'], POINTER(POINTER(ID3D11ShaderResourceView)), 'ppSRView' ), ), # COMMETHOD( [], HRESULT, 'CreateUnorderedAccessView', ( ['in'], POINTER(ID3D11Resource), 'pResource' ), ( ['in'], POINTER(D3D11_UNORDERED_ACCESS_VIEW_DESC), 'pDesc' ), ( ['out'], POINTER(POINTER(ID3D11UnorderedAccessView)), 'ppUAView' ), ), # COMMETHOD( [], HRESULT, 'CreateRenderTargetView', ( ['in'], POINTER(ID3D11Resource), 'pResource' ), ( ['in'], POINTER(D3D11_RENDER_TARGET_VIEW_DESC), 'pDesc' ), ( ['out'], POINTER(POINTER(ID3D11RenderTargetView)), 'ppRTView' ), ), # COMMETHOD( [], HRESULT, 'CreateDepthStencilView', ( ['in'], POINTER(ID3D11Resource), 'pResource' ), ( ['in'], POINTER(D3D11_DEPTH_STENCIL_VIEW_DESC), 'pDesc' ), ( ['out'], POINTER(POINTER(ID3D11DepthStencilView)), 'ppDepthStencilView' ), ), # COMMETHOD( [], HRESULT, 'CreateInputLayout', ( ['in'], POINTER(D3D11_INPUT_ELEMENT_DESC), 'pInputElementDescs' ), ( ['in'], UINT, 'NumElements' ), ( ['in'], POINTER(VOID), 'pShaderBytecodeWithInputSignature' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['out'], POINTER(POINTER(ID3D11InputLayout)), 'ppInputLayout' ), ), # COMMETHOD( [], HRESULT, 'CreateVertexShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11VertexShader)), 'ppVertexShader' ), ), # COMMETHOD( [], HRESULT, 'CreateGeometryShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11GeometryShader)), 'ppGeometryShader' ), ), # COMMETHOD( [], HRESULT, 'CreateGeometryShaderWithStreamOutput', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(D3D11_SO_DECLARATION_ENTRY), 'pSODeclaration' ), ( ['in'], UINT, 'NumEntries' ), ( ['in'], POINTER(UINT), 'pBufferStrides' ), ( ['in'], UINT, 'NumStrides' ), (['in'], UINT, 'RasterizedStream'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11GeometryShader)), 'ppGeometryShader' ), ), # COMMETHOD( [], HRESULT, 'CreatePixelShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11PixelShader)), 'ppPixelShader' ), ), # COMMETHOD( [], HRESULT, 'CreateHullShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11HullShader)), 'ppHullShader' ), ), # COMMETHOD( [], HRESULT, 'CreateDomainShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11DomainShader)), 'ppDomainShader' ), ), # COMMETHOD( [], HRESULT, 'CreateComputeShader', ( ['in'], POINTER(VOID), 'pShaderBytecode' ), (['in'], SIZE_T, 'BytecodeLength'), ( ['in'], POINTER(ID3D11ClassLinkage), 'pClassLinkage' ), ( ['out'], POINTER(POINTER(ID3D11ComputeShader)), 'ppComputeShader' ), ), # COMMETHOD( [], HRESULT, 'CreateClassLinkage', ( ['out'], POINTER(POINTER(ID3D11ClassLinkage)), 'ppLinkage' ), ), # COMMETHOD( [], HRESULT, 'CreateBlendState', ( ['in'], POINTER(D3D11_BLEND_DESC), 'pBlendStateDesc' ), ( ['out'], POINTER(POINTER(ID3D11BlendState)), 'ppBlendState' ), ), # COMMETHOD( [], HRESULT, 'CreateDepthStencilState', ( ['in'], POINTER(D3D11_DEPTH_STENCIL_DESC), 'pDepthStencilDesc' ), ( ['out'], POINTER(POINTER(ID3D11DepthStencilState)), 'ppDepthStencilState' ), ), # COMMETHOD( [], HRESULT, 'CreateRasterizerState', ( ['in'], POINTER(D3D11_RASTERIZER_DESC), 'pRasterizerDesc' ), ( ['out'], POINTER(POINTER(ID3D11RasterizerState)), 'ppRasterizerState' ), ), # COMMETHOD( [], HRESULT, 'CreateSamplerState', ( ['in'], POINTER(D3D11_SAMPLER_DESC), 'pSamplerDesc' ), ( ['out'], POINTER(POINTER(ID3D11SamplerState)), 'ppSamplerState' ), ), # COMMETHOD( [], HRESULT, 'CreateQuery', ( ['in'], POINTER(D3D11_QUERY_DESC), 'pQueryDesc' ), ( ['out'], POINTER(POINTER(ID3D11Query)), 'ppQuery' ), ), # COMMETHOD( [], HRESULT, 'CreatePredicate', ( ['in'], POINTER(D3D11_QUERY_DESC), 'pPredicateDesc' ), ( ['out'], POINTER(POINTER(ID3D11Predicate)), 'ppPredicate' ), ), # COMMETHOD( [], HRESULT, 'CreateCounter', ( ['in'], POINTER(D3D11_COUNTER_DESC), 'pCounterDesc' ), ( ['out'], POINTER(POINTER(ID3D11Counter)), 'ppCounter' ), ), # Reserved parameter; must be 0 COMMETHOD( [], HRESULT, 'CreateDeferredContext', (['in'], UINT, 'ContextFlags'), ( ['out'], POINTER(POINTER(ID3D11DeviceContext)), 'ppDeferredContext' ), ), # COMMETHOD( [], HRESULT, 'OpenSharedResource', (['in'], HANDLE, 'hResource'), (['in'], REFIID, 'ReturnedInterface'), ( ['out'], POINTER(POINTER(VOID)), 'ppResource' ), ), # Check* # COMMETHOD( [], HRESULT, 'CheckFormatSupport', (['in'], DXGI_FORMAT, 'Format'), ( ['out'], POINTER(UINT), 'pFormatSupport' ), ), # COMMETHOD( [], HRESULT, 'CheckMultisampleQualityLevels', (['in'], DXGI_FORMAT, 'Format'), (['in'], UINT, 'SampleCount'), ( ['out'], POINTER(UINT), 'pNumQualityLevels' ), ), COMMETHOD( [], VOID, 'CheckCounterInfo', ( ['out'], POINTER(D3D11_COUNTER_INFO), 'pCounterInfo' ), ), # COMMETHOD( [], HRESULT, 'CheckCounter', ( ['in'], POINTER(D3D11_COUNTER_DESC), 'pDesc' ), ( ['out'], POINTER(D3D11_COUNTER_TYPE), 'pType' ), (['in'], POINTER(UINT), 'pActiveCounters'), ( ['out'], LPSTR, 'szName' ), ( ['out', 'in'], POINTER(UINT), 'pNameLength' ), ( ['out'], LPSTR, 'szUnits' ), (['in'], POINTER(UINT), 'pUnitsLength'), ( ['out'], LPSTR, 'szDescription' ), (['in'], POINTER(UINT), 'pDescriptionLength'), ), # COMMETHOD( [], HRESULT, 'CheckFeatureSupport', (['in'], D3D11_FEATURE, 'Feature'), ( ['out'], POINTER(VOID), 'pFeatureSupportData' ), (['in'], UINT, 'FeatureSupportDataSize'), ), # COMMETHOD( [], HRESULT, 'GetPrivateData', (['in'], REFGUID, 'guid'), ( ['out', 'in'], POINTER(UINT), 'pDataSize' ), ( ['out'], POINTER(VOID), 'pData' ), ), # COMMETHOD( [], HRESULT, 'SetPrivateData', (['in'], REFGUID, 'guid'), (['in'], UINT, 'DataSize'), ( ['in'], POINTER(VOID), 'pData' ), ), # COMMETHOD( [], HRESULT, 'SetPrivateDataInterface', (['in'], REFGUID, 'guid'), ( ['in'], POINTER(comtypes.IUnknown), 'pData' ), ), COMMETHOD( [], D3D_FEATURE_LEVEL, 'GetFeatureLevel', ), COMMETHOD( [], UINT, 'GetCreationFlags', ), COMMETHOD( [], HRESULT, 'GetDeviceRemovedReason', ), COMMETHOD( [], VOID, 'GetImmediateContext', ( ['out'], POINTER(POINTER(ID3D11DeviceContext)), 'ppImmediateContext' ), ), COMMETHOD( [], HRESULT, 'SetExceptionMode', (['in'], UINT, 'RaiseFlags'), ), COMMETHOD( [], UINT, 'GetExceptionMode', ), ] from .dxgi_h import *
) + '&$select=name,selfLink&$filter=partition eq ' + \ folder pr_res = self.bigip.icr_session.get( type_link, timeout=const.CONNECTION_TIMEOUT) if pr_res.status_code < 400: pr_res_obj = json.loads(pr_res.text) if 'items' in pr_res_obj: for profile in pr_res_obj['items']: if profile['name'].find(match) > -1: profile['selfLink'] = \ profile['selfLink'].split('?')[0] del_resp = self.bigip.icr_session.delete( self.bigip.icr_link( profile['selfLink']), timeout=const.CONNECTION_TIMEOUT) if del_resp.status_code > 399 and \ del_resp.status_code != 404: Log.error('persistence', del_resp.text) exps = exceptions exp = exps.VirtualServerDeleteException raise exp(del_resp.text) else: self.folder_persistence_profiles = {} self.common_persistence_profiles = {} else: Log.error('persistence', pr_res.text) raise exceptions.VirtualServerQueryException( pr_res.text) elif response.status_code == 404: True else: raise exceptions.VirtualServerQueryException(response.text) return True @icontrol_rest_folder @log def get_profile_link(self, name=None, folder='Common'): """ Get profile link """ folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/profile/' response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) for refs in response_obj['items']: link = self.bigip.icr_link(refs['reference']['link']) link += '&$select=name,fullPath,selfLink' profile_resp = self.bigip.icr_session.get( link, timeout=const.CONNECTION_TIMEOUT) if profile_resp.status_code < 400: profile_obj = json.loads(profile_resp.text) if 'items' in profile_obj: for profile in profile_obj['items']: if profile['name'] == name: return self.bigip.icr_link( profile['selfLink']) elif response.status_code == 404: return None else: raise exceptions.VirtualServerQueryException(response.text) @icontrol_rest_folder @log def get_persistence_link(self, name=None): """ Get persistence link """ if name: request_url = self.bigip.icr_url + '/ltm/persistence/' response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) for refs in response_obj['items']: link = self.bigip.icr_link(refs['reference']['link']) link += '&$select=name,partition,fullPath,selfLink' profile_resp = self.bigip.icr_session.get( link, timeout=const.CONNECTION_TIMEOUT) if profile_resp.status_code < 400: profile_obj = json.loads(profile_resp.text) if 'items' in profile_obj: for profile in profile_obj['items']: if profile['name'] == name: return self.bigip.icr_link( profile['selfLink']) elif response.status_code == 404: return None else: raise exceptions.VirtualServerQueryException(response.text) @icontrol_rest_folder @log def virtual_server_has_rule(self, name=None, rule_name=None, folder='Common'): """ Does vip have rule? """ if name and rule_name: folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name request_url += '?$select=rules' response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) if 'rules' in response_obj: rule = '/' + folder + '/' + rule_name if rule in response_obj['rules']: return True else: return False elif response.status_code == 404: return False else: raise exceptions.VirtualServerQueryException(response.text) return False @icontrol_rest_folder @log def add_rule(self, name=None, rule_name=None, priority=500, folder='Common'): """ Add rule to vip """ if name and rule_name: folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name request_url += '?$select=rules' response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) if 'rules' in response_obj: rule = '/' + folder + '/' + rule_name if rule not in response_obj['rules']: rules_list = response_obj['rules'] rules_list.append(rule) rules = {'rules': rules_list} request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name Log.debug('virtual-server', 'add rule body: %s' % response_obj) response = self.bigip.icr_session.patch( request_url, data=json.dumps(rules), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException( response.text) else: # rule was already assigned to this virtual server return True else: # no rules.. add this one rules = {'rules': ['/' + folder + '/' + rule_name]} request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, data=json.dumps(rules), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException( response.text) elif response.status_code == 404: return False else: Log.error('virtual', response.text) raise exceptions.VirtualServerQueryException(response.text) return False @icontrol_rest_folder @log def remove_rule(self, name=None, rule_name=None, priority=500, folder='Common'): """ Remove rule from vip """ if name and rule_name: folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name request_url += '?$select=rules' response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) if 'rules' in response_obj: rule = '/' + folder + '/' + rule_name if rule in response_obj['rules']: rules_list = response_obj['rules'] rules_list.remove(rule) rules = {'rules': rules_list} request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.put( request_url, data=json.dumps(rules), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException( response.text) else: # rule not assigned return True else: # no assigned rules return True elif response.status_code == 404: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerQueryException(response.text) return False @icontrol_rest_folder @log def set_persist_profile(self, name=None, profile_name=None, folder='Common'): """ Set persist profile on vip """ if name and profile_name: folder = str(folder).replace('/', '') found_profile = self._which_persistence_profile(profile_name, folder) if found_profile: profile_name = found_profile payload = dict() payload['persist'] = [{'name': profile_name}] request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, json.dumps(payload), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException(response.text) return False @icontrol_rest_folder @log def set_fallback_persist_profile(self, name=None, profile_name=None, folder='Common'): """ Set fallback persist profile on vip """ if name and profile_name: folder = str(folder).replace('/', '') found_profile = self._which_persistence_profile(profile_name, folder) if found_profile: profile_name = found_profile payload = dict() payload['fallbackPersistence'] = \ strip_folder_and_prefix(profile_name) request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, json.dumps(payload), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException(response.text) return False @icontrol_rest_folder @log def remove_all_persist_profiles(self, name=None, folder='Common'): """ Remove persist profiles from vip """ if name: folder = str(folder).replace('/', '') payload = dict() payload['fallbackPersistence'] = '' payload['persist'] = [] request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, json.dumps(payload), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException(response.text) return False @icontrol_rest_folder @log def remove_and_delete_persist_profile(self, name=None, profile_name=None, folder='Common'): """ Remove and delete persist profiles """ if name and profile_name: folder = str(folder).replace('/', '') self.remove_all_persist_profiles(name, folder) return self.delete_persist_profile(profile_name, folder) return False @icontrol_rest_folder @log def enable_virtual_server(self, name=None, folder='Common'): """ Enable vip """ if name: folder = str(folder).replace('/', '') payload = dict() payload['enabled'] = True request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, json.dumps(payload), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException(response.text) return False @icontrol_rest_folder @log def disable_virtual_server(self, name=None, folder='Common'): """ Disable vip """ if name: folder = str(folder).replace('/', '') payload = dict() payload['disabled'] = True request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.patch( request_url, json.dumps(payload), timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerUpdateException(response.text) return False @icontrol_rest_folder @log def delete(self, name=None, folder='Common'): """ Delete vip """ if name: folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '~' + folder + '~' + name response = self.bigip.icr_session.delete( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: return True elif response.status_code == 404: return True else: Log.error('virtual', response.text) raise exceptions.VirtualServerDeleteException(response.text) return False @icontrol_rest_folder @log def get_virtual_servers(self, folder='Common'): """ Get vips """ folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual' request_url += '?$select=name' request_url += '&$filter=partition eq ' + folder response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) vs_names = [] if response.status_code < 400: return_obj = json.loads(response.text) if 'items' in return_obj: for vs in return_obj['items']: vs_names.append(strip_folder_and_prefix(vs['name'])) elif response.status_code != 404: Log.error('virtual', response.text) raise exceptions.VirtualServerQueryException(response.text) return vs_names @icontrol_rest_folder @log def get_virtual_servers_by_pool_name(self, pool_name=None, folder='Common'): """ Get vips by pool name """ folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual' request_url += '?$select=name,pool' request_url += '&$filter=partition eq ' + folder response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) vs_names = [] if response.status_code < 400: return_obj = json.loads(response.text) if 'items' in return_obj: for vs in return_obj['items']: if 'pool' in vs and \ os.path.basename(vs['pool']) == pool_name: vs_names.append(strip_folder_and_prefix(vs['name'])) elif response.status_code != 404: Log.error('virtual', response.text) raise exceptions.VirtualServerQueryException(response.text) return vs_names @icontrol_rest_folder @log def delete_all(self, folder='Common'): """ Delete vips """ folder = str(folder).replace('/', '') request_url = self.bigip.icr_url + '/ltm/virtual/' request_url += '?$select=name,selfLink' request_filter = 'partition eq ' + folder request_url += '&$filter=' + request_filter response = self.bigip.icr_session.get( request_url, timeout=const.CONNECTION_TIMEOUT) if response.status_code < 400: response_obj = json.loads(response.text) if 'items' in response_obj: for item in response_obj['items']: if item['name'].startswith(self.OBJ_PREFIX): item['selfLink'] = item['selfLink'].split('?')[0] response = self.bigip.icr_session.delete( self.bigip.icr_link(item['selfLink']), timeout=const.CONNECTION_TIMEOUT) if response.status_code > 400 and \ response.status_code != 404: Log.error('virtual', response.text) raise exceptions.VirtualServerDeleteException( response.text) return True elif response.status_code != 404: Log.error('rule', response.text) raise exceptions.VirtualServerQueryException(response.text) return False @icontrol_rest_folder @log def get_pool(self, name=None, folder='Common'): """ Get pool """ if name:
""" Functions that pertain to creating and writing output for the model results.""" # External Libraries import numpy as np import netCDF4 as nc from time import strftime import matplotlib.pyplot as plt # Local Libraries import pygem_input as input def netcdfcreate(filename, main_glac_rgi, main_glac_hyps, dates_table, output_filepath=input.output_filepath, nsims=1): """ Create a netcdf file to store the desired output Parameters ---------- filename : str netcdf filename that is being created main_glac_rgi : pandas dataframe dataframe containing relevant rgi glacier information main_glac_hyps : numpy array glacier hypsometry of every glacier included in model run dates_table : pandas dataframe table of the dates, months, days in month, etc. output_filepath : str output filepath of where to store netcdf file nsims : int number of simulations included Returns ------- creates a netcdf file with the proper structure to be fill in by the model results """ # Annual columns annual_columns = np.unique(dates_table['wateryear'].values)[0:int(dates_table.shape[0]/12)] # Netcdf file path and name fullfilename = output_filepath + filename # Create netcdf file ('w' will overwrite existing files, 'r+' will open existing file to write) netcdf_output = nc.Dataset(fullfilename, 'w', format='NETCDF4') # ===== Global attributes ===== netcdf_output.description = 'Results from glacier evolution model' netcdf_output.history = 'Created ' + str(strftime("%Y-%m-%d %H:%M:%S")) netcdf_output.source = 'Python Glacier Evolution Model' # ===== Dimensions ===== glac_idx = netcdf_output.createDimension('glac_idx', None) if input.timestep == 'monthly': time = netcdf_output.createDimension('time', dates_table.shape[0] - input.spinupyears * 12) year = netcdf_output.createDimension('year', annual_columns.shape[0] - input.spinupyears) year_plus1 = netcdf_output.createDimension('year_plus1', annual_columns.shape[0] - input.spinupyears + 1) glac_table = netcdf_output.createDimension('glac_table', main_glac_rgi.shape[1]) elevbin = netcdf_output.createDimension('elevbin', main_glac_hyps.shape[1]) sim = netcdf_output.createDimension('sim', nsims) # Variables associated with dimensions sims = netcdf_output.createVariable('sim', np.int32, ('sim',)) sims.long_name = 'simulation number' sims[:] = range(0, nsims) glaciers = netcdf_output.createVariable('glac_idx', np.int32, ('glac_idx',)) glaciers.long_name = "glacier index" glaciers.standard_name = input.indexname glaciers.comment = "Glacier index value that refers to the glacier table" glaciers[:] = main_glac_rgi.index.values times = netcdf_output.createVariable('time', np.float64, ('time',)) times.long_name = "date" times.units = "days since 1900-01-01 00:00:00" times.calendar = "gregorian" if input.timestep == 'monthly': times[:] = (nc.date2num(dates_table.loc[input.spinupyears*12:dates_table.shape[0]+1,'date'].tolist(), units = times.units, calendar = times.calendar)) years = netcdf_output.createVariable('year', np.int32, ('year',)) years.long_name = "year" if input.option_wateryear == 1: years.units = 'water year' elif input.option_wateryear == 2: years.units = 'calendar year' elif input.option_wateryear == 3: years.units = 'custom year' years[:] = annual_columns[input.spinupyears:annual_columns.shape[0]] # years_plus1 adds an additional year such that the change in glacier dimensions (area, etc.) is recorded years_plus1 = netcdf_output.createVariable('year_plus1', np.int32, ('year_plus1',)) years_plus1.long_name = "year with additional year to record glacier dimension changes" if input.option_wateryear == 1: years_plus1.units = 'water year' elif input.option_wateryear == 2: years_plus1.units = 'calendar year' elif input.option_wateryear == 3: years_plus1.units = 'custom year' years_plus1[:] = np.concatenate((annual_columns[input.spinupyears:annual_columns.shape[0]], np.array([annual_columns[annual_columns.shape[0]-1]+1]))) glacier_table_header = netcdf_output.createVariable('glacier_table_header',str,('glac_table',)) glacier_table_header.long_name = "glacier table header" glacier_table_header[:] = main_glac_rgi.columns.values glacier_table_header.comment = "Column names of RGI table and any added columns. See 'glac_table' for values." glacier_table = netcdf_output.createVariable('glacier_table',np.float64,('glac_idx','glac_table',)) glacier_table.long_name = "glacier table values" glacier_table[:] = main_glac_rgi.values glacier_table.comment = "Values of RGI table and any added columns. See 'glac_table_header' for column names" elevbins = netcdf_output.createVariable('elevbin', np.int32, ('elevbin',)) elevbins.long_name = "center of elevation bin" elevbins.units = "m a.s.l." elevbins[:] = main_glac_hyps.columns.values # ===== Output Variables ===== if input.output_package == 1: # Package 1 "Raw Package" output [units: m w.e. unless otherwise specified]: # monthly variables for each bin (temp, prec, acc, refreeze, snowpack, melt, frontalablation, massbal_clim) # annual variables for each bin (area, icethickness, width, surfacetype) temp_bin_monthly = netcdf_output.createVariable('temp_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) temp_bin_monthly.long_name = "air temperature" temp_bin_monthly.units = "degC" prec_bin_monthly = netcdf_output.createVariable('prec_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) prec_bin_monthly.long_name = "liquid precipitation" prec_bin_monthly.units = "m" acc_bin_monthly = netcdf_output.createVariable('acc_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) acc_bin_monthly.long_name = "accumulation" acc_bin_monthly.units = "m w.e." refreeze_bin_monthly = netcdf_output.createVariable('refreeze_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) refreeze_bin_monthly.long_name = "refreezing" refreeze_bin_monthly.units = "m w.e." snowpack_bin_monthly = netcdf_output.createVariable('snowpack_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) snowpack_bin_monthly.long_name = "snowpack on the glacier surface" snowpack_bin_monthly.units = "m w.e." snowpack_bin_monthly.comment = ("snowpack represents the snow depth when units are m w.e.") melt_bin_monthly = netcdf_output.createVariable('melt_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) melt_bin_monthly.long_name = 'surface melt' melt_bin_monthly.units = "m w.e." melt_bin_monthly.comment = ("surface melt is the sum of melt from snow, refreeze, and the underlying glacier") frontalablation_bin_monthly = netcdf_output.createVariable('frontalablation_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) frontalablation_bin_monthly.long_name = "frontal ablation" frontalablation_bin_monthly.units = "m w.e." frontalablation_bin_monthly.comment = ("mass losses from calving, subaerial frontal melting, sublimation above " + "the waterline and subaqueous frontal melting below the waterline") massbalclim_bin_monthly = netcdf_output.createVariable('massbalclim_bin_monthly', np.float64, ('glac_idx', 'elevbin', 'time')) massbalclim_bin_monthly.long_name = "climatic mass balance" massbalclim_bin_monthly.units = "m w.e." massbalclim_bin_monthly.comment = ("climatic mass balance is the sum of the surface mass balance and the " + "internal mass balance and accounts for the climatic mass loss over the " + "area of the entire bin") area_bin_annual = netcdf_output.createVariable('area_bin_annual', np.float64, ('glac_idx', 'elevbin', 'year_plus1')) area_bin_annual.long_name = "glacier area" area_bin_annual.unit = "km**2" area_bin_annual.comment = "the area that was used for the duration of the year" icethickness_bin_annual = netcdf_output.createVariable('icethickness_bin_annual', np.float64, ('glac_idx', 'elevbin', 'year_plus1')) icethickness_bin_annual.long_name = "ice thickness" icethickness_bin_annual.unit = "m ice" icethickness_bin_annual.comment = "the ice thickness that was used for the duration of the year" width_bin_annual = netcdf_output.createVariable('width_bin_annual', np.float64, ('glac_idx', 'elevbin', 'year_plus1')) width_bin_annual.long_name = "glacier width" width_bin_annual.unit = "km" width_bin_annual.comment = "the width that was used for the duration of the year" surfacetype_bin_annual = netcdf_output.createVariable('surfacetype_bin_annual', np.float64, ('glac_idx', 'elevbin', 'year')) surfacetype_bin_annual.long_name = "surface type" surfacetype_bin_annual.comment = "surface types: 0 = off-glacier, 1 = ice, 2 = snow, 3 = firn, 4 = debris" elif input.output_package == 2: # Package 2 "Glaciologist Package" output [units: m w.e. unless otherwise specified]: # monthly glacier-wide variables (prec, acc, refreeze, melt, frontalablation, massbal_total, runoff, snowline) # annual glacier-wide variables (area, volume, ELA) temp_glac_monthly = netcdf_output.createVariable('temp_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) temp_glac_monthly.long_name = "glacier-wide mean air temperature" temp_glac_monthly.units = "deg C" temp_glac_monthly.comment = ("each elevation bin is weighted equally to compute the mean temperature, and bins " + "where the glacier no longer exists due to retreat have been removed") prec_glac_monthly = netcdf_output.createVariable('prec_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) prec_glac_monthly.long_name = "glacier-wide precipitation (liquid)" prec_glac_monthly.units = "m" acc_glac_monthly = netcdf_output.createVariable('acc_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) acc_glac_monthly.long_name = "glacier-wide accumulation" acc_glac_monthly.units = "m w.e." refreeze_glac_monthly = netcdf_output.createVariable('refreeze_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) refreeze_glac_monthly.long_name = "glacier-wide refreeze" refreeze_glac_monthly.units = "m w.e." melt_glac_monthly = netcdf_output.createVariable('melt_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) melt_glac_monthly.long_name = "glacier-wide melt" melt_glac_monthly.units = "m w.e." frontalablation_glac_monthly = netcdf_output.createVariable('frontalablation_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) frontalablation_glac_monthly.long_name = "glacier-wide frontal ablation" frontalablation_glac_monthly.units = "m w.e." frontalablation_glac_monthly.comment = ("mass losses from calving, subaerial frontal melting, sublimation above" + " the waterline and subaqueous frontal melting below the waterline") massbaltotal_glac_monthly = netcdf_output.createVariable('massbaltotal_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) massbaltotal_glac_monthly.long_name = "glacier-wide total mass balance" massbaltotal_glac_monthly.units = "m w.e." massbaltotal_glac_monthly.comment = ("total mass balance is the sum of the climatic mass balance and frontal " + "ablation.") runoff_glac_monthly = netcdf_output.createVariable('runoff_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) runoff_glac_monthly.long_name = "glacier runoff" runoff_glac_monthly.units = "m**3" runoff_glac_monthly.comment = "runoff from the glacier terminus, which moves over time" snowline_glac_monthly = netcdf_output.createVariable('snowline_glac_monthly', np.float64, ('glac_idx', 'time', 'sim')) snowline_glac_monthly.long_name = "transient snowline" snowline_glac_monthly.units = "m a.s.l." snowline_glac_monthly.comment = "transient snowline is the line separating the snow from ice/firn" area_glac_annual = netcdf_output.createVariable('area_glac_annual', np.float64, ('glac_idx', 'year_plus1', 'sim')) if input.option_wateryear == 1: area_glac_annual.long_name = "glacier area by hydrological year" elif input.option_wateryear == 2: area_glac_annual.long_name = "glacier area by calendar year" elif input.option_wateryear == 3: area_glac_annual.long_name = "glacier area by custom year" else: area_glac_annual.long_name = "glacier area" area_glac_annual.units = "km**2" area_glac_annual.comment = "the area that was used for the duration of the defined start/end of year" volume_glac_annual = netcdf_output.createVariable('volume_glac_annual', np.float64, ('glac_idx', 'year_plus1', 'sim')) if input.option_wateryear == 1: volume_glac_annual.long_name = "glacier volume by hydrological year" elif input.option_wateryear == 2: volume_glac_annual.long_name = "glacier volume by calendar year" elif input.option_wateryear == 3: volume_glac_annual.long_name = "glacier volume by custom year" else: volume_glac_annual.long_name = "glacier volume" volume_glac_annual.units = "km**3 ice" volume_glac_annual.comment = "the volume based on area and ice thickness used for that year" ELA_glac_annual = netcdf_output.createVariable('ELA_glac_annual', np.float64, ('glac_idx', 'year', 'sim')) ELA_glac_annual.long_name = "annual equilibrium line altitude" ELA_glac_annual.units = "m a.s.l." ELA_glac_annual.comment = "equilibrium
_svalue += '-' total_seconds *= -1 else: _svalue += '+' hours = total_seconds // 3600 minutes = (total_seconds - (hours * 3600)) // 60 _svalue += '{0:02d}:{1:02d}'.format( hours, minutes) except AttributeError: pass return _svalue @classmethod def gds_parse_date(cls, input_data): tz = None if input_data[-1] == 'Z': tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') input_data = input_data[:-1] else: results = GeneratedsSuper.tzoff_pattern.search(input_data) if results is not None: tzoff_parts = results.group(2).split(':') tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) if results.group(1) == '-': tzoff *= -1 tz = GeneratedsSuper._FixedOffsetTZ( tzoff, results.group(0)) input_data = input_data[:-6] dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d') dt = dt.replace(tzinfo=tz) return dt.date() def gds_validate_time(self, input_data, node=None, input_name=''): return input_data def gds_format_time(self, input_data, input_name=''): if input_data.microsecond == 0: _svalue = '%02d:%02d:%02d' % ( input_data.hour, input_data.minute, input_data.second, ) else: _svalue = '%02d:%02d:%02d.%s' % ( input_data.hour, input_data.minute, input_data.second, ('%f' % (float(input_data.microsecond) / 1000000))[2:], ) if input_data.tzinfo is not None: tzoff = input_data.tzinfo.utcoffset(input_data) if tzoff is not None: total_seconds = tzoff.seconds + (86400 * tzoff.days) if total_seconds == 0: _svalue += 'Z' else: if total_seconds < 0: _svalue += '-' total_seconds *= -1 else: _svalue += '+' hours = total_seconds // 3600 minutes = (total_seconds - (hours * 3600)) // 60 _svalue += '{0:02d}:{1:02d}'.format(hours, minutes) return _svalue def gds_validate_simple_patterns(self, patterns, target): # pat is a list of lists of strings/patterns. # The target value must match at least one of the patterns # in order for the test to succeed. found1 = True for patterns1 in patterns: found2 = False for patterns2 in patterns1: mo = re_.search(patterns2, target) if mo is not None and len(mo.group(0)) == len(target): found2 = True break if not found2: found1 = False break return found1 @classmethod def gds_parse_time(cls, input_data): tz = None if input_data[-1] == 'Z': tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC') input_data = input_data[:-1] else: results = GeneratedsSuper.tzoff_pattern.search(input_data) if results is not None: tzoff_parts = results.group(2).split(':') tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1]) if results.group(1) == '-': tzoff *= -1 tz = GeneratedsSuper._FixedOffsetTZ( tzoff, results.group(0)) input_data = input_data[:-6] if len(input_data.split('.')) > 1: dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f') else: dt = datetime_.datetime.strptime(input_data, '%H:%M:%S') dt = dt.replace(tzinfo=tz) return dt.time() def gds_check_cardinality_( self, value, input_name, min_occurs=0, max_occurs=1, required=None): if value is None: length = 0 elif isinstance(value, list): length = len(value) else: length = 1 if required is not None : if required and length < 1: self.gds_collector_.add_message( "Required value {}{} is missing".format( input_name, self.gds_get_node_lineno_())) if length < min_occurs: self.gds_collector_.add_message( "Number of values for {}{} is below " "the minimum allowed, " "expected at least {}, found {}".format( input_name, self.gds_get_node_lineno_(), min_occurs, length)) elif length > max_occurs: self.gds_collector_.add_message( "Number of values for {}{} is above " "the maximum allowed, " "expected at most {}, found {}".format( input_name, self.gds_get_node_lineno_(), max_occurs, length)) def gds_validate_builtin_ST_( self, validator, value, input_name, min_occurs=None, max_occurs=None, required=None): if value is not None: try: validator(value, input_name=input_name) except GDSParseError as parse_error: self.gds_collector_.add_message(str(parse_error)) def gds_validate_defined_ST_( self, validator, value, input_name, min_occurs=None, max_occurs=None, required=None): if value is not None: try: validator(value) except GDSParseError as parse_error: self.gds_collector_.add_message(str(parse_error)) def gds_str_lower(self, instring): return instring.lower() def get_path_(self, node): path_list = [] self.get_path_list_(node, path_list) path_list.reverse() path = '/'.join(path_list) return path Tag_strip_pattern_ = re_.compile(r'\{.*\}') def get_path_list_(self, node, path_list): if node is None: return tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) if tag: path_list.append(tag) self.get_path_list_(node.getparent(), path_list) def get_class_obj_(self, node, default_class=None): class_obj1 = default_class if 'xsi' in node.nsmap: classname = node.get('{%s}type' % node.nsmap['xsi']) if classname is not None: names = classname.split(':') if len(names) == 2: classname = names[1] class_obj2 = globals().get(classname) if class_obj2 is not None: class_obj1 = class_obj2 return class_obj1 def gds_build_any(self, node, type_name=None): # provide default value in case option --disable-xml is used. content = "" content = etree_.tostring(node, encoding="unicode") return content @classmethod def gds_reverse_node_mapping(cls, mapping): return dict(((v, k) for k, v in mapping.items())) @staticmethod def gds_encode(instring): if sys.version_info.major == 2: if ExternalEncoding: encoding = ExternalEncoding else: encoding = 'utf-8' return instring.encode(encoding) else: return instring @staticmethod def convert_unicode(instring): if isinstance(instring, str): result = quote_xml(instring) elif sys.version_info.major == 2 and isinstance(instring, unicode): result = quote_xml(instring).encode('utf8') else: result = GeneratedsSuper.gds_encode(str(instring)) return result def __eq__(self, other): def excl_select_objs_(obj): return (obj[0] != 'parent_object_' and obj[0] != 'gds_collector_') if type(self) != type(other): return False return all(x == y for x, y in zip_longest( filter(excl_select_objs_, self.__dict__.items()), filter(excl_select_objs_, other.__dict__.items()))) def __ne__(self, other): return not self.__eq__(other) # Django ETL transform hooks. def gds_djo_etl_transform(self): pass def gds_djo_etl_transform_db_obj(self, dbobj): pass # SQLAlchemy ETL transform hooks. def gds_sqa_etl_transform(self): return 0, None def gds_sqa_etl_transform_db_obj(self, dbobj): pass def gds_get_node_lineno_(self): if (hasattr(self, "gds_elementtree_node_") and self.gds_elementtree_node_ is not None): return ' near line {}'.format( self.gds_elementtree_node_.sourceline) else: return "" def getSubclassFromModule_(module, class_): '''Get the subclass of a class from a specific module.''' name = class_.__name__ + 'Sub' if hasattr(module, name): return getattr(module, name) else: return None # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' ## ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', ## exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Globals # ExternalEncoding = '' # Set this to false in order to deactivate during export, the use of # name space prefixes captured from the input document. UseCapturedNS_ = True CapturedNsmap_ = {} Tag_pattern_ = re_.compile(r'({.*})?(.*)') String_cleanup_pat_ = re_.compile(r"[\n\r\s]+") Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)') CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL) # Change this to redirect the generated superclass module to use a # specific subclass module. CurrentSubclassModule_ = None # # Support/utility functions. # def showIndent(outfile, level, pretty_print=True): if pretty_print: for idx in range(level): outfile.write(' ') def quote_xml(inStr): "Escape markup chars, but do not modify CDATA sections." if not inStr: return '' s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) s2 = '' pos = 0 matchobjects = CDATA_pattern_.finditer(s1) for mo in matchobjects: s3 = s1[pos:mo.start()] s2 += quote_xml_aux(s3) s2 += s1[mo.start():mo.end()] pos = mo.end() s3 = s1[pos:] s2 += quote_xml_aux(s3) return s2 def quote_xml_aux(inStr): s1 = inStr.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') return s1 def quote_attrib(inStr): s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') if '"' in s1: if "'" in s1: s1 = '"%s"' % s1.replace('"', "&quot;") else: s1 = "'%s'" % s1 else: s1 = '"%s"' % s1 return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 def get_all_text_(node): if node.text is not None: text = node.text else: text = '' for child in node: if child.tail is not None: text += child.tail return text def find_attr_value_(attr_name, node): attrs = node.attrib attr_parts = attr_name.split(':') value = None if len(attr_parts) == 1: value = attrs.get(attr_name) elif len(attr_parts) == 2: prefix, name = attr_parts namespace = node.nsmap.get(prefix) if namespace is not None: value = attrs.get('{%s}%s' % (namespace, name, )) return value def encode_str_2_3(instr): return instr class GDSParseError(Exception): pass def raise_parse_error(node, msg): if node is not None: msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) raise GDSParseError(msg) class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 TypeBase64 = 8 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name, namespace, pretty_print=True): if self.category == MixedContainer.CategoryText: # Prevent exporting empty content as empty lines. if self.value.strip(): outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export( outfile, level, namespace, name_=name, pretty_print=pretty_print) def exportSimple(self, outfile, level, name): if self.content_type ==
<reponame>Nullius-2020/SSL-Competitioin-Top-10-solution # coding: utf8 # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os import os.path as osp import sys import argparse from PIL import Image from tqdm import tqdm import imghdr import logging import pickle import cv2 #import gdal def parse_args(): parser = argparse.ArgumentParser( description='Data analyse and data check before training.') parser.add_argument( '--data_dir', dest='data_dir', help='Dataset directory', default=None, type=str) parser.add_argument( '--num_classes', dest='num_classes', help='Number of classes', default=None, type=int) parser.add_argument( '--separator', dest='separator', help='file list separator', default="\t", type=str) parser.add_argument( '--ignore_index', dest='ignore_index', help='Ignored class index', default=255, type=int) if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() def read_img(img_path): img_format = imghdr.what(img_path) name, ext = osp.splitext(img_path) if ext == '.png' or ext == '.jpg': #dataset = Image.open(img_path) #print(img_path,dataset) dataset=cv2_imread(img_path, cv2.IMREAD_UNCHANGED) if dataset == None: raise Exception('Can not open', img_path) #im_data = dataset.ReadAsArray() im_data=np.asarray(dataset) #return im_data return im_data.transpose((1, 2, 0)) elif ext == '.npy': return np.load(img_path) else: raise Exception('Not support {} image format!'.format(ext)) def img_pixel_statistics(img, img_value_num, img_min_value, img_max_value): img.transpose((1, 2, 0)) channel = img.shape[2] means = np.zeros(channel) stds = np.zeros(channel) for k in range(channel): img_k = img[:, :, k] # count mean, std means[k] = np.mean(img_k) stds[k] = np.std(img_k) # count min, max min_value = np.min(img_k) max_value = np.max(img_k) if img_max_value[k] < max_value: img_max_value[k] = max_value if img_min_value[k] > min_value: img_min_value[k] = min_value # count the distribution of image value, value number unique, counts = np.unique(img_k, return_counts=True) add_num = [] max_unique = np.max(unique) add_len = max_unique - len(img_value_num[k]) + 1 if add_len > 0: img_value_num[k] += ([0] * add_len) for i in range(len(unique)): value = unique[i] img_value_num[k][value] += counts[i] img_value_num[k] += add_num return means, stds, img_min_value, img_max_value, img_value_num def data_distribution_statistics(data_dir, img_value_num, logger): """count the distribution of image value, value number """ logger.info( "\n-----------------------------\nThe whole dataset statistics...") if not img_value_num: return logger.info("\nImage pixel statistics:") total_ratio = [] [total_ratio.append([]) for i in range(len(img_value_num))] for k in range(len(img_value_num)): total_num = sum(img_value_num[k]) total_ratio[k] = [i / total_num for i in img_value_num[k]] total_ratio[k] = np.around(total_ratio[k], decimals=4) with open(os.path.join(data_dir, 'img_pixel_statistics.pkl'), 'wb') as f: pickle.dump([total_ratio, img_value_num], f) def data_range_statistics(img_min_value, img_max_value, logger): """print min value, max value """ logger.info("value range: \nimg_min_value = {} \nimg_max_value = {}".format( img_min_value, img_max_value)) def cal_normalize_coefficient(total_means, total_stds, total_img_num, logger): """count mean, std """ total_means = total_means / total_img_num total_stds = total_stds / total_img_num logger.info("\nCount the channel-by-channel mean and std of the image:\n" "mean = {}\nstd = {}".format(total_means, total_stds)) def error_print(str): return "".join(["\nNOT PASS ", str]) def correct_print(str): return "".join(["\nPASS ", str]) def cv2_imread(file_path, flag=cv2.IMREAD_COLOR): """ 解决 cv2.imread 在window平台打开中文路径的问题. """ return cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), flag) def pil_imread(file_path): """read pseudo-color label""" im = Image.open(file_path).convert('L') return np.asarray(im) def get_img_shape_range(img, max_width, max_height, min_width, min_height): """获取图片最大和最小宽高""" img_shape = img.shape height, width = img_shape[0], img_shape[1] max_height = max(height, max_height) max_width = max(width, max_width) min_height = min(height, min_height) min_width = min(width, min_width) return max_width, max_height, min_width, min_height def get_img_channel_num(img, img_channels): """获取图像的通道数""" img_shape = img.shape if img_shape[-1] not in img_channels: img_channels.append(img_shape[-1]) return img_channels def is_label_single_channel(label): """判断标签是否为灰度图""" label_shape = label.shape if len(label_shape) == 2: return True else: return False def image_label_shape_check(img, label): """ 验证图像和标注的大小是否匹配 """ flag = True img_height = img.shape[0] img_width = img.shape[1] label_height = label.shape[0] label_width = label.shape[1] if img_height != label_height or img_width != label_width: flag = False return flag def ground_truth_check(label, label_path): """ 验证标注图像的格式 统计标注图类别和像素数 params: label: 标注图 label_path: 标注图路径 return: png_format: 返回是否是png格式图片 unique: 返回标注类别 counts: 返回标注的像素数 """ if imghdr.what(label_path) == "png": png_format = True else: png_format = False unique, counts = np.unique(label, return_counts=True) return png_format, unique, counts def sum_label_check(label_classes, num_of_each_class, ignore_index, num_classes, total_label_classes, total_num_of_each_class): """ 统计所有标注图上的类别和每个类别的像素数 params: label_classes: 标注类别 num_of_each_class: 各个类别的像素数目 """ is_label_correct = True if ignore_index in label_classes: label_classes2 = np.delete(label_classes, np.where(label_classes == ignore_index)) else: label_classes2 = label_classes if min(label_classes2) < 0 or max(label_classes2) > num_classes - 1: is_label_correct = False add_class = [] add_num = [] for i in range(len(label_classes)): gi = label_classes[i] if gi in total_label_classes: j = total_label_classes.index(gi) total_num_of_each_class[j] += num_of_each_class[i] else: add_class.append(gi) add_num.append(num_of_each_class[i]) total_num_of_each_class += add_num total_label_classes += add_class #print(total_num_of_each_class,total_label_classes) if len(total_label_classes)>0 and len(total_num_of_each_class)>0: return is_label_correct, total_num_of_each_class, total_label_classes else: return is_label_correct,[0.0001],[0.0001] def label_class_check(num_classes, total_label_classes, total_num_of_each_class, wrong_labels, logger): """ 检查实际标注类别是否和配置参数`num_classes`,`ignore_index`匹配。 **NOTE:** 标注图像类别数值必须在[0~(`num_classes`-1)]范围内或者为`ignore_index`。 标注类别最好从0开始,否则可能影响精度。 """ total_ratio = total_num_of_each_class / sum(total_num_of_each_class) total_ratio = np.around(total_ratio, decimals=4) total_nc = sorted( zip(total_label_classes, total_ratio, total_num_of_each_class)) if len(wrong_labels) == 0 and not total_nc[0][0]: logger.info(correct_print("label class check!")) else: logger.info(error_print("label class check!")) if total_nc[0][0]: logger.info("Warning: label classes should start from 0") if len(wrong_labels) > 0: logger.info( "fatal error: label class is out of range [0, {}]".format( num_classes - 1)) for i in wrong_labels: logger.debug(i) return total_nc def label_class_statistics(total_nc, logger): """ 对标注图像进行校验,输出校验结果 """ logger.info( "\nLabel class statistics:\n" "(label class, percentage, total pixel number) = {} ".format(total_nc)) def shape_check(shape_unequal_image, logger): """输出shape校验结果""" if len(shape_unequal_image) == 0: logger.info(correct_print("shape check")) logger.info("All images are the same shape as the labels") else: logger.info(error_print("shape check")) logger.info( "Some images are not the same shape as the labels as follow: ") for i in shape_unequal_image: logger.debug(i) def separator_check(wrong_lines, file_list, separator, logger): """检查分割符是否复合要求""" if len(wrong_lines) == 0: logger.info( correct_print( file_list.split(os.sep)[-1] + " DATASET.separator check")) else: logger.info( error_print( file_list.split(os.sep)[-1] + " DATASET.separator check")) logger.info( "The following list is not separated by {}".format(separator)) for i in wrong_lines: logger.debug(i) def imread_check(imread_failed, logger): if len(imread_failed) == 0: logger.info(correct_print("dataset reading check")) logger.info("All images can be read successfully") else: logger.info(error_print("dataset reading check")) logger.info("Failed to read {} images".format(len(imread_failed))) for i in imread_failed: logger.debug(i) def single_channel_label_check(label_not_single_channel, logger): if len(label_not_single_channel) == 0: logger.info(correct_print("label single_channel check")) logger.info("All label images are single_channel") else: logger.info(error_print("label single_channel check")) logger.info( "{} label images are not single_channel\nLabel pixel statistics may be insignificant" .format(len(label_not_single_channel))) for i in label_not_single_channel: logger.debug(i) def img_shape_range_statistics(max_width, min_width, max_height, min_height, logger): logger.info("\nImage size statistics:") logger.info( "max width = {} min width = {} max height = {} min height = {}". format(max_width, min_width, max_height, min_height)) def img_channels_statistics(img_channels, logger): logger.info("\nImage channels statistics\nImage channels = {}".format( np.unique(img_channels))) def data_analyse_and_check(data_dir, num_classes, separator, ignore_index, logger): train_file_list = osp.join(data_dir, 'train.txt') val_file_list = osp.join(data_dir, 'val.txt') test_file_list = osp.join(data_dir, 'test.txt') total_img_num = 0 has_label = False for file_list in [train_file_list, val_file_list, test_file_list]: # initialization imread_failed = [] max_width = 0 max_height = 0 min_width = sys.float_info.max min_height = sys.float_info.max label_not_single_channel = [] shape_unequal_image = [] wrong_labels = [] wrong_lines = [] total_label_classes = [] total_num_of_each_class = [] img_channels = [] with open(file_list, 'r') as fid: logger.info("\n-----------------------------\nCheck {}...".format( file_list)) lines = fid.readlines() if not lines: logger.info("File list is empty!") continue for line in tqdm(lines): line = line.strip() parts = line.split(separator) if len(parts) == 1: has_label = False if file_list == train_file_list or file_list == val_file_list: logger.info("Train or val list must have labels!") break img_name = parts img_path =img_name[0] try: img = cv2_imread(img_path) except Exception as e: imread_failed.append((line, str(e))) continue elif len(parts) == 2: has_label = True img_name, label_name = parts[0], parts[1] #print( img_name, label_name) img_path =img_name label_path =label_name try: img = cv2_imread(img_path) label = pil_imread(label_path) except Exception as e: imread_failed.append((line, str(e))) continue is_single_channel = is_label_single_channel(label) if not is_single_channel: label_not_single_channel.append(line) continue is_equal_img_label_shape = image_label_shape_check( img, label) if not is_equal_img_label_shape: shape_unequal_image.append(line) png_format, label_classes, num_of_each_class = ground_truth_check( label, label_path) is_label_correct, total_num_of_each_class, total_label_classes = sum_label_check( label_classes, num_of_each_class, ignore_index, num_classes, total_label_classes, total_num_of_each_class) if not is_label_correct: wrong_labels.append(line) else: wrong_lines.append(lines) continue if total_img_num == 0: channel = img.shape[2] total_means = np.zeros(channel) total_stds = np.zeros(channel) img_min_value = [sys.float_info.max] * channel img_max_value = [0] * channel img_value_num = [] [img_value_num.append([]) for i in range(channel)] means, stds, img_min_value, img_max_value, img_value_num = img_pixel_statistics( img, img_value_num, img_min_value, img_max_value) total_means += means total_stds += stds max_width, max_height, min_width, min_height = get_img_shape_range( img, max_width, max_height, min_width, min_height) img_channels = get_img_channel_num(img, img_channels) total_img_num += 1 # data check separator_check(wrong_lines, file_list, separator, logger) imread_check(imread_failed, logger) if has_label: single_channel_label_check(label_not_single_channel, logger) shape_check(shape_unequal_image, logger) total_nc = label_class_check(num_classes, total_label_classes, total_num_of_each_class, wrong_labels, logger) # data analyse on train, validation, test
""" Time stepping solvers. """ import numpy as nm from sfepy.base.base import output, Struct, IndexedStruct, basestr from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver from sfepy.discrete.mass_operator import MassOperator from sfepy.solvers.ts import TimeStepper, VariableTimeStepper class StationarySolver(TimeSteppingSolver): """ Solver for stationary problems without time stepping. This class is provided to have a unified interface of the time stepping solvers also for stationary problems. """ name = 'ts.stationary' def __init__(self, conf, **kwargs): TimeSteppingSolver.__init__(self, conf, ts=None, **kwargs) def __call__(self, state0=None, save_results=True, step_hook=None, post_process_hook=None, nls_status=None): problem = self.problem problem.time_update() state = problem.solve(state0=state0, nls_status=nls_status) if step_hook is not None: step_hook(problem, None, state) if save_results: problem.save_state(problem.get_output_name(), state, post_process_hook=post_process_hook, file_per_var=None) return state def replace_virtuals(deps, pairs): out = {} for key, val in deps.iteritems(): out[pairs[key]] = val return out class EquationSequenceSolver(TimeSteppingSolver): """ Solver for stationary problems with an equation sequence. """ name = 'ts.equation_sequence' def __init__(self, conf, **kwargs): TimeSteppingSolver.__init__(self, conf, ts=None, **kwargs) def __call__(self, state0=None, save_results=True, step_hook=None, post_process_hook=None, nls_status=None): from sfepy.base.base import invert_dict, get_subdict from sfepy.base.resolve_deps import resolve problem = self.problem if state0 is None: state0 = problem.create_state() variables = problem.get_variables() vtos = variables.get_dual_names() vdeps = problem.equations.get_variable_dependencies() sdeps = replace_virtuals(vdeps, vtos) sorder = resolve(sdeps) stov = invert_dict(vtos) vorder = [[stov[ii] for ii in block] for block in sorder] parts0 = state0.get_parts() state = state0.copy() solved = [] for ib, block in enumerate(vorder): output('solving for %s...' % sorder[ib]) subpb = problem.create_subproblem(block, solved) subpb.equations.print_terms() subpb.time_update() substate0 = subpb.create_state() vals = get_subdict(parts0, block) substate0.set_parts(vals) substate = subpb.solve(state0=substate0, nls_status=nls_status) state.set_parts(substate.get_parts()) solved.extend(sorder[ib]) output('...done') if step_hook is not None: step_hook(problem, None, state) if save_results: problem.save_state(problem.get_output_name(), state, post_process_hook=post_process_hook, file_per_var=None) return state def get_initial_state(problem): """ Create a zero state vector and apply initial conditions. """ state = problem.create_state() problem.setup_ic() state.apply_ic() return state def prepare_save_data(ts, conf): """ Given a time stepper configuration, return a list of time steps when the state should be saved. """ try: save_steps = conf.options.save_steps except: save_steps = -1 if save_steps == -1: save_steps = ts.n_step is_save = nm.linspace(0, ts.n_step - 1, save_steps).astype(nm.int32) is_save = nm.unique(is_save) return ts.suffix, is_save def prepare_matrix(problem, state): """ Pre-assemble tangent system matrix. """ problem.update_materials() ev = problem.get_evaluator() try: mtx = ev.eval_tangent_matrix(state(), is_full=True) except ValueError: output('matrix evaluation failed, giving up...') raise return mtx def make_implicit_step(ts, state0, problem, nls_status=None): """ Make a step of an implicit time stepping solver. """ problem.time_update(ts) if ts.step == 0: state0.apply_ebc() state = state0.copy(deep=True) if not ts.is_quasistatic: problem.init_time(ts) ev = problem.get_evaluator() try: vec_r = ev.eval_residual(state(), is_full=True) except ValueError: output('initial residual evaluation failed, giving up...') raise else: err = nm.linalg.norm(vec_r) output('initial residual: %e' % err) if problem.is_linear(): mtx = prepare_matrix(problem, state) else: mtx = None # Initialize solvers (and possibly presolve the matrix). presolve = mtx is not None problem.init_solvers(nls_status=nls_status, mtx=mtx, presolve=presolve) # Initialize variables with history. state0.init_history() if ts.is_quasistatic: # Ordinary solve. state = problem.solve(state0=state0, nls_status=nls_status) else: if (ts.step == 1) and ts.is_quasistatic and problem.is_linear(): mtx = prepare_matrix(problem, state0) problem.init_solvers(nls_status=nls_status, mtx=mtx) state = problem.solve(state0=state0, nls_status=nls_status) return state def make_explicit_step(ts, state0, problem, mass, nls_status=None): """ Make a step of an explicit time stepping solver. """ problem.time_update(ts) if ts.step == 0: state0.apply_ebc() state = state0.copy(deep=True) problem.init_time(ts) # Initialize variables with history. state0.init_history() ev = problem.get_evaluator() try: vec_r = ev.eval_residual(state0(), is_full=True) except ValueError: output('residual evaluation failed, giving up...') raise else: err = nm.linalg.norm(vec_r) output('residual: %e' % err) if ts.step > 0: variables = problem.get_variables() vec_rf = variables.make_full_vec(vec_r, force_value=0.0) rhs = -ts.dt * vec_rf + mass.action(state0()) vec = mass.inverse_action(rhs) state = state0.copy(preserve_caches=True) state.set_full(vec) state.apply_ebc() return state def get_min_dt(adt): red = adt.red while red >= adt.red_max: red *= adt.red_factor dt = adt.dt0 * red return dt def adapt_time_step(ts, status, adt, problem=None): """ Adapt the time step of `ts` according to the exit status of the nonlinear solver. The time step dt is reduced, if the nonlinear solver did not converge. If it converged in less then a specified number of iterations for several time steps, the time step is increased. This is governed by the following parameters: - red_factor : time step reduction factor - red_max : maximum time step reduction factor - inc_factor : time step increase factor - inc_on_iter : increase time step if the nonlinear solver converged in less than this amount of iterations... - inc_wait : ...for this number of consecutive time steps Parameters ---------- ts : VariableTimeStepper instance The time stepper. status : IndexedStruct instance The nonlinear solver exit status. adt : Struct instance The adaptivity parameters of the time solver: problem : Problem instance, optional This canbe used in user-defined adaptivity functions. Not used here. Returns ------- is_break : bool If True, the adaptivity loop should stop. """ is_break = False if status.condition == 0: if status.n_iter <= adt.inc_on_iter: adt.wait += 1 if adt.wait > adt.inc_wait: if adt.red < 1.0: adt.red = adt.red * adt.inc_factor ts.set_time_step(adt.dt0 * adt.red) output('+++++ new time step: %e +++++' % ts.dt) adt.wait = 0 else: adt.wait = 0 is_break = True else: adt.red = adt.red * adt.red_factor if adt.red < adt.red_max: is_break = True else: ts.set_time_step(adt.dt0 * adt.red, update_time=True) output('----- new time step: %e -----' % ts.dt) adt.wait = 0 return is_break class SimpleTimeSteppingSolver(TimeSteppingSolver): """ Implicit time stepping solver with a fixed time step. """ name = 'ts.simple' @staticmethod def process_conf(conf, kwargs): """ Process configuration options. """ get = make_get_conf(conf, kwargs) common = TimeSteppingSolver.process_conf(conf) return Struct(t0=get('t0', 0.0), t1=get('t1', 1.0), dt=get('dt', None), n_step=get('n_step', 10), quasistatic=get('quasistatic', False)) + common def __init__(self, conf, **kwargs): TimeSteppingSolver.__init__(self, conf, **kwargs) self.ts = TimeStepper.from_conf(self.conf) nd = self.ts.n_digit format = '====== time %%e (step %%%dd of %%%dd) =====' % (nd, nd) self.format = format def __call__(self, state0=None, save_results=True, step_hook=None, post_process_hook=None, nls_status=None): """ Solve the time-dependent problem. """ problem = self.problem ts = self.ts suffix, is_save = prepare_save_data(ts, problem.conf) if state0 is None: state0 = get_initial_state(problem) ii = 0 for step, time in ts: output(self.format % (time, step + 1, ts.n_step)) state = self.solve_step(ts, state0, nls_status=nls_status) state0 = state.copy(deep=True) if step_hook is not None: step_hook(problem, ts, state) if save_results and (is_save[ii] == ts.step): filename = problem.get_output_name(suffix=suffix % ts.step) problem.save_state(filename, state, post_process_hook=post_process_hook, file_per_var=None, ts=ts) ii += 1 problem.advance(ts) return state def solve_step(self, ts, state0, nls_status=None): """ Solve a single time step. """ state = make_implicit_step(ts, state0, self.problem, nls_status=nls_status) return state class ExplicitTimeSteppingSolver(SimpleTimeSteppingSolver): """ Explicit time stepping solver with a fixed time step. """ name = 'ts.explicit' @staticmethod def process_conf(conf, kwargs): """ Process configuration options. """ get = make_get_conf(conf, kwargs) common = SimpleTimeSteppingSolver.process_conf(conf, kwargs) return Struct(mass=get('mass', None, 'missing "mass" in options!'), lumped=get('lumped', False)) + common def __init__(self, conf, **kwargs): SimpleTimeSteppingSolver.__init__(self, conf, **kwargs) self.mass = MassOperator(self.problem, self.conf) def solve_step(self, ts, state0, nls_status=None): """ Solve a single time step. """ state = make_explicit_step(ts, state0, self.problem, self.mass, nls_status=nls_status) return state class AdaptiveTimeSteppingSolver(SimpleTimeSteppingSolver): """ Implicit time stepping solver with an adaptive time step. Either the built-in or user supplied function can be used to adapt the time step. """ name = 'ts.adaptive' @staticmethod def process_conf(conf, kwargs): """ Process configuration options. """ get = make_get_conf(conf, kwargs) common = SimpleTimeSteppingSolver.process_conf(conf, kwargs) adt = Struct(red_factor=get('dt_red_factor', 0.2), red_max=get('dt_red_max', 1e-3), inc_factor=get('dt_inc_factor', 1.25), inc_on_iter=get('dt_inc_on_iter', 4), inc_wait=get('dt_inc_wait', 5), red=1.0, wait=0, dt0=0.0) return Struct(adapt_fun=get('adapt_fun', adapt_time_step), adt=adt) + common def __init__(self, conf, **kwargs): TimeSteppingSolver.__init__(self, conf, **kwargs) self.ts = VariableTimeStepper.from_conf(self.conf) self.adt = adt = self.conf.adt adt.dt0 = self.ts.get_default_time_step() self.ts.set_n_digit_from_min_dt(get_min_dt(adt)) self.format = '====== time %e (dt %e, wait %d, step %d of %d) =====' if isinstance(self.conf.adapt_fun, basestr): self.adapt_time_step = self.problem.functions[self.conf.adapt_fun] else: self.adapt_time_step = self.conf.adapt_fun def __call__(self, state0=None, save_results=True, step_hook=None, post_process_hook=None, nls_status=None): """ Solve the time-dependent problem. """ problem = self.problem ts = self.ts if state0 is None: state0 = get_initial_state(problem) ii = 0 for step, time in ts: output(self.format % (time, ts.dt, self.adt.wait, step + 1, ts.n_step)) state = self.solve_step(ts, state0, nls_status=nls_status) state0 = state.copy(deep=True) if step_hook is not None: step_hook(problem, ts, state) if save_results: filename = problem.get_output_name(suffix=ts.suffix % ts.step) problem.save_state(filename, state, post_process_hook=post_process_hook, file_per_var=None, ts=ts) ii += 1 problem.advance(ts) return state def solve_step(self, ts, state0, nls_status=None): """ Solve a single time step. """ status = IndexedStruct(n_iter=0, condition=0) while 1: state = make_implicit_step(ts, state0, self.problem, nls_status=status) is_break = self.adapt_time_step(ts, status, self.adt, self.problem) if is_break: break if nls_status is not None:
0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_get_an_hourly_report_properly_II_less_than_23_hours(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] date = "2021-02-19" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [108, 60, 38, 74, 54, 78, 88, 50, 102, 62, 94, 78, 32, 52, 134, 58, 72, 34, 62, 64, 38, 76, 68, 100], 'no_infringement': [26, 10, 4, 36, 10, 22, 20, 12, 28, 12, 34, 36, 8, 16, 34, 22, 6, 12, 14, 8, 12, 20, 22, 36], 'low_infringement': [20, 28, 8, 38, 22, 30, 14, 14, 22, 4, 2, 6, 20, 20, 38, 14, 30, 10, 10, 32, 8, 24, 26, 34], 'high_infringement': [32, 4, 6, 0, 16, 2, 32, 22, 24, 12, 30, 0, 0, 2, 28, 14, 20, 4, 2, 18, 16, 26, 0, 30], 'critical_infringement': [30, 18, 20, 0, 6, 24, 22, 2, 28, 34, 28, 36, 4, 14, 34, 8, 16, 8, 36, 6, 2, 6, 20, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]} ), ("face-mask-detections", { 'no_face': [6, 6, 18, 4, 16, 4, 18, 16, 16, 0, 2, 4, 8, 12, 12, 4, 10, 4, 0, 0, 16, 6, 2, 4], 'face_with_mask': [10, 8, 12, 18, 4, 6, 18, 14, 14, 6, 16, 6, 12, 14, 8, 4, 0, 2, 8, 2, 18, 10, 2, 8], 'face_without_mask': [4, 12, 0, 16, 14, 14, 18, 2, 18, 16, 12, 8, 10, 14, 2, 0, 14, 10, 6, 6, 6, 16, 12, 10], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_get_hourly_report_two_dates(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = camera["id"] date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id},{camera_id_2}&date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_hourly_report_non_existent_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = 'BAD_ID' date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 404 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_hourly_report_bad_date_format(self, config_rollback_cameras, metric): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera['id'] date = "WRONG_DATE" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_try_get_hourly_report_non_existent_date(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera['id'] date = "2003-05-24" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 200 # Since no files with the specified date were found, no objects were added to the report. assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_hourly_report_two_dates_one_of_them_bad_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = 'BAD_ID' date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id},{camera_id_2}&date={date}") assert response.status_code == 404 assert response.json() == expected # pytest -v api/tests/app/test_camera_metrics.py::TestsGetCameraDistancingDailyReport class TestsGetCameraDistancingDailyReport: """ Get Camera Distancing Daily Report , GET /metrics/cameras/social-distancing/daily""" """ Returns a daily report (for the date range specified) with information about the social distancing infractions detected in the cameras. """ @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 148, 179], 'no_infringement': [0, 0, 136, 139], 'low_infringement': [0, 0, 0, 19], 'high_infringement': [0, 0, 5, 17], 'critical_infringement': [0, 0, 7, 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }), ("face-mask-detections", { 'no_face': [0, 0, 18, 18], 'face_with_mask': [0, 0, 106, 135], 'face_without_mask': [0, 0, 26, 30], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']}) ] ) def test_get_a_daily_report_properly(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] to_date = "2020-09-23" from_date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0], 'no_infringement': [0], 'low_infringement': [0], 'high_infringement': [0], 'critical_infringement': [0], 'dates': ['2020-09-20'] }), ("face-mask-detections", { 'no_face': [0], 'face_with_mask': [0], 'face_without_mask': [0], 'dates': ['2020-09-20']}) ] ) def test_get_a_daily_report_properly_one_day(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={date}&to_date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [104, 120, 161, 301], 'no_infringement': [5, 35, 143, 183], 'low_infringement': [57, 42, 2, 87], 'high_infringement': [42, 43, 9, 27], 'critical_infringement': [0, 0, 7, 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }), ("face-mask-detections", { 'no_face': [85, 77, 114, 41], 'face_with_mask': [36, 76, 188, 170], 'face_without_mask': [23, 33, 39, 128], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }) ] ) def test_get_a_daily_report_properly_two_cameras(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = camera_2["id"] to_date = "2020-09-23" from_date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id},{camera_id_2}&from_date={from_date}&to_date={to_date}" ) assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_a_daily_report_bad_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = 'BAD_ID' response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date=2020-09-20&to_date=2020-09-23") assert response.status_code == 404 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_daily_report_bad_dates(self, config_rollback_cameras, metric): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "BAD_DATE" to_date = "BAD_DATE" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': ['2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22', '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27', '2003-05-28'] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': ['2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22',
#add new infected to queue self.infected_queue.append(len(self.people)) #add person to tracked people self.people[len(self.people)] = Person(parent_key, inf_time, detect_time,recovery_time, category) def simulate(self, end_time,sim,seed): """ Simulate forward until end_time """ from collections import deque from math import ceil import gc np.random.seed(seed) self.num_of_sim = sim self.read_in_Reff() #generate storage for cases self.cases = np.zeros(shape=(end_time, 3),dtype=float) self.observed_cases = np.zeros_like(self.cases) self.observed_cases[0,:] = self.initial_state.copy() #Initalise undetected cases and add them to current self.initialise_sim() #number of cases after end time self.cases_after = 0 #gets incremented in generate new cases #Record day 0 cases self.cases[0,:] = self.current.copy() # Generate imported cases new_imports = [] unobs_imports =[] for day in range(end_time): # Values for a and b are initialised in import_cases_model() which is called by read_in_cases() during setup. a = self.a_dict[day] b = self.b_dict[day] # Dij = number of observed imported infectious individuals Dij = nbinom.rvs(a, 1-1/(b+1)) # Uij = number of *unobserved* imported infectious individuals unobserved_a = 1 if Dij == 0 else Dij Uij = nbinom.rvs(unobserved_a, p=self.qi) unobs_imports.append(Uij) new_imports.append(Dij + Uij) for day, imports in enumerate(new_imports): self.cases[day,0] = imports for n in range(imports): #Generate people if n - unobs_imports[day]>=0: #number of observed people new_person = Person(0,day,day +next(self.get_detect_time),0,'I') self.people[len(self.people)] = new_person if new_person.detection_time <= end_time: self.observed_cases[max(0,ceil(new_person.detection_time)-1),0] +=1 else: #unobserved people new_person = Person(0,day,0,0,'I') self.people[len(self.people)] = new_person if day <= end_time: self.cases[max(0,day-1), 0] +=1 ##### #Create queue for infected people self.infected_queue = deque() #Assign people to infected queue for key, person in self.people.items(): #add to the queue self.infected_queue.append(key) #Record their times if person.infection_time> end_time: #initial undetected cases have slim chance to be infected #after end_time if person.category!='I': #imports shouldn't count for extinction counts self.cases_after +=1 print("cases after at initialisation") #Cases already recorded at initialise_sim() by addding to # self.current #Record initial inferred obs including importations. self.inferred_initial_obs = self.observed_cases[0,:].copy() #print(self.inferred_initial_obs, self.current) # General simulation through time by proceeding through queue # of infecteds n_resim = 0 self.bad_sim = False reinitialising_window = 3 self.daycount= 0 while len(self.infected_queue)>0: day_end = self.people[self.infected_queue[0]].detection_time if day_end < self.forecast_date: if self.inf_backcast_counter > self.max_backcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str(self.max_backcast_cases)+" cases in backcast. Ending") self.num_too_many+=1 self.bad_sim = True break elif self.inf_nowcast_counter > self.max_nowcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str( self.max_nowcast_cases )+" cases in nowcast. Ending") self.num_too_many+=1 self.bad_sim = True break else: #check max cases for after forecast date if self.inf_forecast_counter>self.max_cases: #hold value forever if day_end < self.cases.shape[0]-1: self.cases[ceil(day_end):,2] = self.cases[ceil(day_end)-2,2] self.observed_cases[ceil(day_end):,2] = self.observed_cases[ceil(day_end)-2,2] else: self.cases_after +=1 print("Sim "+str(self.num_of_sim )+" in "+self.state+" has >"+str(self.max_cases)+" cases in forecast period.") self.num_too_many+=1 break ## stop if parent infection time greater than end time if self.people[self.infected_queue[0]].infection_time >end_time: self.infected_queue.popleft() print("queue had someone exceed end_time!!") else: #take approproate Reff based on parent's infection time curr_time = self.people[self.infected_queue[0]].infection_time if type(self.Reff)==int: Reff = 1 print("using flat Reff") elif type(self.Reff)==dict: while True: #sometimes initial cases infection time is pre #Reff data, so take the earliest one try: Reff = self.Reff[ceil(curr_time)-1] except KeyError: if curr_time>0: print("Unable to find Reff for this parent at time: %.2f" % curr_time) raise KeyError curr_time +=1 continue break #generate new cases with times parent_key = self.infected_queue.popleft() #recorded within generate new cases self.generate_new_cases(parent_key,Reff=Reff,k = self.k) #self.people.clear() if self.bad_sim ==False: #Check simulation for discrepancies for day in range(7,end_time): #each day runs through self.infected_queue missed_outbreak = self.data_check(day) #True or False if missed_outbreak: self.daycount +=1 if self.daycount >= reinitialising_window: n_resim +=1 #print("Local outbreak in "+self.state+" not simulated on day %i" % day) #cases to add #treat current like empty list self.current[2] = max(0,self.actual[day] - sum(self.observed_cases[day,1:])) self.current[2] += max(0,self.actual[day-1] - sum(self.observed_cases[day-1,1:])) self.current[2] += max(0,self.actual[day-2] - sum(self.observed_cases[day-2,1:])) #how many cases are symp to asymp prob_symp_given_detect = self.symptomatic_detection_prob*self.ps/( self.symptomatic_detection_prob*self.ps + self.asymptomatic_detection_prob*(1-self.ps) ) num_symp = binom.rvs(n=int(self.current[2]), p=prob_symp_given_detect) #distribute observed cases over 3 days #Triangularly self.observed_cases[max(0,day),2] += num_symp//2 self.cases[max(0,day),2] += num_symp//2 self.observed_cases[max(0,day-1),2] += num_symp//3 self.cases[max(0,day-1),2] += num_symp//3 self.observed_cases[max(0,day-2),2] += num_symp//6 self.cases[max(0,day-2),2] +=num_symp//6 #add asymptomatic num_asymp = self.current[2] - num_symp self.observed_cases[max(0,day),2] += num_asymp//2 self.cases[max(0,day),2] += num_asymp//2 self.observed_cases[max(0,day-1),2] += num_asymp//3 self.cases[max(0,day-1),2] += num_asymp//3 self.observed_cases[max(0,day-2),2] += num_asymp//6 self.cases[max(0,day-2),2] +=num_asymp//6 self.initialise_sim(curr_time=day) #print("Reinitialising with %i new cases " % self.current[2] ) #reset days to zero self.daycount = 0 if n_resim> 10: print("This sim reinitilaised %i times" % n_resim) self.bad_sim = True n_resim = 0 break #Each check of day needs to simulate the cases before moving # to next check, otherwise will be doubling up on undetecteds while len(self.infected_queue)>0: day_end = self.people[self.infected_queue[0]].detection_time #check for exceeding max_cases if day_end <self.forecast_date: if self.inf_backcast_counter > self.max_backcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str(self.max_backcast_cases)+" cases in backcast. Ending") self.num_too_many+=1 self.bad_sim = True break elif self.inf_nowcast_counter > self.max_nowcast_cases: print("Sim "+str(self.num_of_sim )+" in "+self.state+" has > "+str( self.max_nowcast_cases )+" cases in nowcast. Ending") self.num_too_many+=1 self.bad_sim = True break else: if self.inf_forecast_counter> self.max_cases: day_inf = self.people[self.infected_queue[0]].infection_time self.cases[ceil(day_inf):,2] = self.cases[ceil(day_inf)-2,2] self.observed_cases[ceil(day_inf):,2] = self.observed_cases[ceil(day_inf)-2,2] print("Sim "+str(self.num_of_sim )+" in "+self.state+" has >"+str(self.max_cases)+" cases in forecast period.") self.num_too_many+=1 break ## stop if parent infection time greater than end time if self.people[self.infected_queue[0]].infection_time >end_time: personkey =self.infected_queue.popleft() print("queue had someone exceed end_time!!") else: #take approproate Reff based on parent's infection time curr_time = self.people[self.infected_queue[0]].infection_time if type(self.Reff)==int: Reff = 2 elif type(self.Reff)==dict: while True: #sometimes initial cases infection time is pre #Reff data, so take the earliest one try: Reff = self.Reff[ceil(curr_time)-1] except KeyError: if curr_time>0: print("Unable to find Reff for this parent at time: %.2f" % curr_time) raise KeyError curr_time +=1 continue break #generate new cases with times parent_key = self.infected_queue.popleft() self.generate_new_cases(parent_key,Reff=Reff,k=self.k) #missed_outbreak = max(1,missed_outbreak*0.9) else: #pass in here if while queue loop completes continue #only reach here if while loop breaks, so break the data check break self.people.clear() gc.collect() if self.bad_sim: #return NaN arrays for all bad_sims self.cumulative_cases = np.empty_like(self.cases) self.cumulative_cases[:] = np.nan return (self.cumulative_cases,self.cumulative_cases, { 'qs':self.symptomatic_detection_prob, 'metric':np.nan, 'qa':self.asymptomatic_detection_prob, 'qi':self.qi, 'alpha_a':self.alpha_a, 'alpha_s':self.alpha_s, #'accept':self.accept, 'ps':self.ps, 'bad_sim':self.bad_sim, 'cases_after':self.cases_after, 'num_of_sim':self.num_of_sim, } ) else: #good sim ## Perform metric for ABC # self.get_metric(end_time) return ( self.cases.copy(), self.observed_cases.copy(), { 'qs':self.symptomatic_detection_prob, 'metric':np.nan, 'qa':self.asymptomatic_detection_prob, 'qi':self.qi, 'alpha_a':self.alpha_a, 'alpha_s':self.alpha_s, #'accept':self.metric>=0.8, 'ps':self.ps, 'bad_sim':self.bad_sim, 'cases_after':self.cases_after, 'num_of_sim':self.num_of_sim, } ) def to_df(self,results): """ Put results from the simulation into a pandas dataframe and record as h5 format. This is called externally by the run_state.py script. """ import pandas as pd df_results = pd.DataFrame() n_sims = results['symp_inci'].shape[1] days = results['symp_inci'].shape[0] sim_vars=['bad_sim','metrics','qs','qa','qi', 'accept','cases_after','alpha_a','alpha_s','ps'] for key, item in results.items(): if key not in sim_vars: df_results = df_results.append( pd.DataFrame( item.T,index=pd.MultiIndex.from_product([ [key], range(n_sims)], names=['Category', 'sim'] ) ) ) df_results.columns = pd.date_range(start = self.start_date, periods=days #num of days ) df_results.columns = [col.strftime('%Y-%m-%d') for col in df_results.columns] #Record simulation variables for var in sim_vars: df_results[var] = [results[var][sim] for cat,sim in df_results.index] print('VoC_flag is', self.VoC_flag) print("Saving results for state "+self.state) df_results.to_parquet( "./results/"+self.state+self.start_date.strftime( format='%Y-%m-%d')+"sim_R_L"+str(n_sims)+"days_"+str(days)+self.VoC_flag+self.scenario+".parquet", ) return df_results def data_check(self,day): """ A metric to calculate how far the simulation is from the actual data """ try: actual_3_day_total = 0 for i in range(3): actual_3_day_total += self.actual[max(0,day-i)] threshold = case_insertion_threshold*max(1,sum( self.observed_cases[ max(0,day-2):day+1,2] + self.observed_cases[ max(0,day-2):day+1,1] ) ) if actual_3_day_total > threshold: return min(3,actual_3_day_total/threshold) else: #long absence, then a case, reintroduce week_in_sim = sum(self.observed_cases[ max(0,day-7):day+1,2] + self.observed_cases[ max(0,day-7):day+1,1]) if week_in_sim == 0: if actual_3_day_total >0: return actual_3_day_total #no outbreak missed return False except KeyError: #print("No cases on day %i" % day) return False # Deprecated as no long using ABC # def get_metric(self,end_time,omega=0.2): # """ # Calculate the value of the metric of the current sim compared to NNDSS data. # """ # self.actual_array = np.array([self.actual[day] # #if day not in missed_dates else 0 # for day in range(end_time) ]) # #calculate case differences # #moving windows # sim_cases =self.observed_cases[ # :len(self.actual_array),2] + \ # self.observed_cases[: # len(self.actual_array),1] #include asymp cases. # #convolution with 1s should do cum sum # window = 7 # sim_cases = np.convolve(sim_cases, # [1]*window,mode='valid') # actual_cum = np.convolve(self.actual_array, # [1]*window,mode='valid') # cases_diff = abs(sim_cases - actual_cum) # #if sum(cases_diff) <= omega * sum(self.actual_array): # #cumulative diff passes, calculate metric # #sum over days number of times within omega of actual # self.metric = sum( # np.square(cases_diff)#,np.maximum(omega* actual_cum,7) # ) # self.metric = self.metric/(end_time-window) #max is end_time
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*- # Do not modify previous lines. See PEP 8, PEP 263. """ Copyright (c) 2020-2021, kounch All rights reserved. SPDX-License-Identifier: BSD-2-Clause This is a tool that analyzes, extracts and injects data in SPI flash image files for ZX-Uno, ZXDOS and similar devices. These are the main features: - List the contents of a ZX-Uno, etc. SPI flash image, showing, if possible, the version of BIOS, esxdos, main Spectrum core and optional cores, Spectrum ROMs and several BIOS settings - Extract BIOS, esxdos ROM, Spectrum core and/or other cores, Spectrum ROMs to individual files - Create a copy of the flash image and, optionally, and/or truncate some (or all) of the optional cores - Change some BIOS default options (video mode, keyboard layout, default core, default ROM, etc.) - Add or replace FPGA cores and/or Spectrum ROM images (from individual ROM files or RomPack files) - Wipe with 0s all Cores and ZX Spectrum ROMs data - List, add or extract ROM files from a ZX1 ROMPack v2 file - If supplied a different kind of file (like a core or BIOS installation file) it will also try to identify its contents Requires a zx123_hash.json file with block structure for a kind of SPI flash file (e.g.: ZXD) and, optionally, hashes to identify the blocks inside. """ from __future__ import print_function import logging import sys import argparse import os import json import hashlib from binascii import unhexlify import struct if sys.version_info.major == 3: import urllib.request import ssl from zipfile import ZipFile, is_zipfile import tempfile import shutil import ctypes if os.name == 'nt': import msvcrt __MY_VERSION__ = '3.0.2' MAIN_URL = 'https://raw.githubusercontent.com/kounch/zx123_tool/main' MY_DIRPATH = os.path.dirname(sys.argv[0]) MY_DIRPATH = os.path.abspath(MY_DIRPATH) STR_OUTDIR = '' IS_COL_TERM = False LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) LOG_FORMAT = logging.Formatter( '%(asctime)s [%(levelname)-5.5s] - %(name)s: %(message)s') LOG_STREAM = logging.StreamHandler(sys.stdout) LOG_STREAM.setFormatter(LOG_FORMAT) LOGGER.addHandler(LOG_STREAM) if not sys.version_info.major == 3: LOGGER.error('This software requires Python version 3') sys.exit(1) ssl._create_default_https_context = ssl._create_unverified_context def main(): """Main routine""" global STR_OUTDIR enable_term_col() LOGGER.debug('Starting up...') arg_data = parse_args() str_file = arg_data['input_file'] STR_OUTDIR = arg_data['output_dir'] output_file = arg_data['output_file'] # Hash Database str_json = os.path.join(MY_DIRPATH, 'zx123_hash.json') # Update JSON if arg_data['update'] != '': if arg_data['update'] == 'json' or (not str_file and not STR_OUTDIR and not output_file): if os.path.isfile(str_json): os.remove(str_json) if not os.path.isfile(str_json): dl_url = MAIN_URL + '/zx123_hash.json' print('\nDownloading JSON database...', end='') urllib.request.urlretrieve(dl_url, str_json) print('OK') sys.exit(0) if not os.path.isfile(str_json): LOGGER.error('Hash database not found: {0}'.format(str_json)) sys.exit(2) with open(str_json, 'r') as jsonHandle: LOGGER.debug('Loading dictionary with hashes...') fulldict_hash = json.load(jsonHandle) # Analyze/initialize input file and output dir location and extension b_new_img = False if not str_file: if arg_data['output_file']: str_file = unzip_image(MY_DIRPATH, arg_data['output_file'], fulldict_hash) b_new_img = True arg_data['force'] = True if not str_file: sys.exit(3) else: LOGGER.error("There's no input file") sys.exit(3) else: if not STR_OUTDIR: STR_OUTDIR = os.path.dirname(str_file) str_extension = os.path.splitext(str_file)[1] str_extension = str_extension[1:].upper() # Check that file extension is available in Hash Database dict_hash = {} if str_extension in fulldict_hash: dict_hash = fulldict_hash[str_extension] else: for str_kind in fulldict_hash: if "extensions" in fulldict_hash[str_kind]: for str_tmp in fulldict_hash[str_kind]['extensions']: if str_tmp == str_extension: str_extension = str_kind dict_hash = fulldict_hash[str_extension] break if not dict_hash: LOGGER.error('Unknown file extension: .{0}'.format(str_extension)) sys.exit(4) # Is the file header known? if validate_file(str_file, dict_hash['parts']['header'][3]): # List main ROMs, Cores and BIOS settings if arg_data['list']: list_zxdata(str_file, dict_hash, arg_data['show_hashes'], arg_data['check_updated'], arg_data['1core'], arg_data['2mb']) # List ZX Spectrum ROMs if arg_data['roms']: list_romsdata(str_file, fulldict_hash, str_extension, arg_data['show_hashes']) # Extract Cores and/or ROMs for x_item in arg_data['extract']: extractfrom_zxdata(str_file, x_item, fulldict_hash, STR_OUTDIR, str_extension, arg_data['force'], not arg_data['roms']) # Expand image file if needed if arg_data['expand_flash']: if not output_file: output_file = str_file img_len = 33554432 if expand_image(str_file, output_file, img_len, arg_data['force']): arg_data['force'] = True str_file = output_file # Try to update contents from internet if arg_data['update'] != '': if str_extension in ['ZX1', 'ZX2', 'ZXD']: print('\nStarting update...') if not output_file: output_file = str_file arr_upd = [] if arg_data['update'].lower() in ['all', 'bios']: prep_update_zxdata(arr_upd, str_file, fulldict_hash, str_extension, ['BIOS']) if arg_data['update'].lower() in ['all', 'spectrum']: prep_update_zxdata(arr_upd, str_file, fulldict_hash, str_extension, ['Spectrum'], get_1core=arg_data['1core'], get_2mb=arg_data['2mb']) if arg_data['update'].lower() in ['all', 'special']: prep_update_zxdata(arr_upd, str_file, fulldict_hash, str_extension, ['Special']) if arg_data['update'].lower() in ['all', 'cores']: prep_update_cores(arr_upd, str_file, fulldict_hash, str_extension, b_new_img, get_1core=arg_data['1core'], get_2mb=arg_data['2mb']) if b_new_img or arg_data['update'].lower() == 'roms': prep_update_roms(arr_upd, fulldict_hash, str_extension, b_new_img) if arg_data['update'].lower() == 'arcade': prep_update_zxdata(arr_upd, str_file, fulldict_hash, str_extension, ['BIOS']) prep_update_cores(arr_upd, str_file, fulldict_hash, str_extension, b_new_img, 'arcade') prep_update_roms(arr_upd, fulldict_hash, str_extension, b_new_img, True) if arg_data['update'].lower() == 'varcade': prep_update_zxdata(arr_upd, str_file, fulldict_hash, str_extension, ['BIOS'], True) prep_update_cores(arr_upd, str_file, fulldict_hash, str_extension, b_new_img, 'varcade') prep_update_roms(arr_upd, fulldict_hash, str_extension, b_new_img, True) if arr_upd: if inject_zxfiles(str_file, arr_upd, output_file, fulldict_hash, str_extension, b_force=arg_data['force']): arg_data['force'] = True str_file = output_file else: print('Nothing to update') # Wipe Secondary Cores and all ZX Spectrum ROMs if arg_data['wipe_flash']: if str_extension in ['ZX1', 'ZX2', 'ZXD']: if not output_file: output_file = str_file wipe_zxdata(str_file, output_file, dict_hash, arg_data['video_mode'], arg_data['keyboard_layout'], arg_data['boot_timer'], arg_data['force']) # Inject Cores and/or ROMs if arg_data['inject']: if str_extension in ['ZX1', 'ZX2', 'ZXD']: b_force = arg_data['force'] if arg_data['wipe_flash']: b_force = True str_file = output_file else: if not output_file: output_file = str_file inject_zxfiles( str_file, arg_data['inject'], output_file, fulldict_hash, str_extension, arg_data['video_mode'], arg_data['keyboard_layout'], arg_data['boot_timer'], arg_data['default_core'], arg_data['default_rom'], b_force) else: LOGGER.error( 'Not a valid filetype: .{0}'.format(str_extension)) # Truncate image elif arg_data['output_file'] and not arg_data['wipe_flash']: savefrom_zxdata(str_file, dict_hash, arg_data['output_file'], arg_data['n_cores'], arg_data['video_mode'], arg_data['keyboard_layout'], arg_data['boot_timer'], arg_data['default_core'], arg_data['default_rom'], arg_data['force']) else: # Check if it's ROMPack v2 rpk_header = fulldict_hash['RPv2']['parts']['header'] f_size = os.stat(str_file).st_size if validate_file(str_file, rpk_header[3]) and int( rpk_header[1]) == f_size: if str_extension == 'ZX1': # List ZX Spectrum ROMs if not arg_data['extract'] and not arg_data['inject']: list_romsdata(str_file, fulldict_hash, 'RPv2', arg_data['show_hashes'], True) # Extract ROMs for x_item in arg_data['extract']: extractfrom_zxdata(str_file, x_item, fulldict_hash, STR_OUTDIR, 'RPv2', arg_data['force'], False) # Inject ROMs if arg_data['inject']: if not output_file: output_file = str_file inject_zxfiles(str_file, arg_data['inject'], output_file, fulldict_hash, 'RPv2', -1, -1, -1, -1, arg_data['default_rom'], arg_data['force']) else: # Convert between Standard and Spectrum Core? if arg_data['convert_core']: if output_file: print('Trying to convert {0}...'.format(str_file)) convert_core(str_file, dict_hash, output_file, arg_data['force']) else: LOGGER.error('Output file not defined!') else: # File header unknown, try to guess only from hash and size find_zxfile(str_file, fulldict_hash, str_extension, arg_data['show_hashes']) print('') LOGGER.debug("Finished.") def enable_term_col(): """ Enable TERM colours (Windows 10) https://stackoverflow.com/questions/53574442/how-to-reliably-test-color-capability-of-an-output-terminal-in-python3 """ global IS_COL_TERM if os.name == 'nt': ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) hstdout = msvcrt.get_osfhandle(sys.stdout.fileno()) mode = ctypes.c_ulong() IS_COL_TERM = kernel32.GetConsoleMode( hstdout, ctypes.byref(mode)) and ( mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) if not IS_COL_TERM: IS_COL_TERM = kernel32.SetConsoleMode( hstdout, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING) > 0 else: IS_COL_TERM = True # https://ozzmaker.com/add-colour-to-text-in-python/ class colours: RED = '\033[1;31m' GREEN = '\033[1;32m' YELLOW = '\033[1;33m' BLUE = '\033[1;34m' PURPLE = '\033[1;35m' CYAN = '\033[1;36m' ENDC = '\033[m' def printcol(str_col, str_txt, end=''): """Print with TERM colour""" if IS_COL_TERM: print('{0}{1}{2}'.format(str_col, str_txt, colours.ENDC), end=end) else: print(str_txt, end=end) def parse_args(): """ Parses command line :return: Dictionary with different options """ global LOGGER global IS_COL_TERM values = {} values['input_file'] = '' values['output_dir'] = '' values['output_file'] = '' values['force'] = False values['list'] = False values['roms'] = False values['show_hashes'] = False values['extract'] = [] values['n_cores'] = -1 values['inject'] = [] values['wipe_flash'] = False values['expand_flash'] = False values['convert_core'] = False values['1core'] = False values['2mb'] = False values['update'] = '' values['check_updated'] = False values['video_mode'] = -1 values['keyboard_layout'] = -1 values['default_core'] = -1 values['default_rom'] = -1 values['boot_timer'] = -1 parser = argparse.ArgumentParser( description='ZX123 Tool', epilog='Analyze and extract data from ZXDOS, etc. files') parser.add_argument('-v', '--version', action='version', version='%(prog)s {0}'.format(__MY_VERSION__)) parser.add_argument('-i', '--input_file', required=False, action='store', dest='input_file', help='ZX-Uno, ZXDOS, etc. File') parser.add_argument('-d', '--output_dir', required=False, action='store', dest='output_dir', help='Output directory for extracted files') parser.add_argument('-o', '--output_file', required=False, action='store', dest='output_file', help='Output file to copy') parser.add_argument('-f', '--force', required=False, action='store_true', dest='force', help='Force overwrite of existing files') parser.add_argument('-l', '--list_contents', required=False, action='store_true', dest='list_contents', help='List file contents') parser.add_argument('-r', '--roms', required=False, action='store_true', dest='parse_roms', help='Parse Spectrum ROMs data') parser.add_argument('-s', '--show_hashes', required=False, action='store_true', dest='show_hashes', help='Show computed hashes') parser.add_argument('-x', '--extract', required=False, action='store', dest='extract', help='Item(s) to extract') parser.add_argument('-n', '--number_of_cores', required=False, type=int, action='store', dest='n_cores', help='Number of cores to store on output file') parser.add_argument('-a', '--add', required=False, action='append', dest='inject', help='Item to inject') parser.add_argument('-w', '--wipe', required=False, action='store_true', dest='wipe_flash', help='Wipe all secondary cores and ROM data') parser.add_argument('-e', '--32', required=False, action='store_true', dest='expand_flash', help='Expand, if needed, flash file to 32MiB') parser.add_argument('-t', '--convert', required=False, action='store_true', dest='convert_core', help='Convert between Spectrum and standard core') parser.add_argument('-1', '--1core', required=False, action='store_true', dest='use_1core', help='Use, if available, ZXUnCore cores for ZX-Uno') parser.add_argument('-2', '--2mb', required=False, action='store_true', dest='use_2mb', help='Use, if available, 2MB cores for ZX-Uno') parser.add_argument('-u', '--update', required=False, nargs='?', choices=[ 'all', 'bios', 'spectrum', 'special', 'cores', 'arcade', 'varcade', 'json', 'roms' ], const='all', default='', dest='update', help='Update JSON
import boto3 import datetime import json import os import pytest import tempfile import sys import zipfile from unittest.mock import MagicMock, patch SOURCES_BUCKET = "gdh-sources" try: import common_lib except ImportError: sys.path.append( os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, 'common')) import common_lib s3_client = boto3.client("s3", endpoint_url=os.environ.get("AWS_ENDPOINT", "http://localstack:4566"), aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID", "test"), aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY", "test"), region_name=os.environ.get("AWS_REGION", "eu-central-1") ) _SOURCE_API_URL = "http://foo.bar" date_filter = {"numDaysBeforeToday": 2, "op": "EQ"} origin_url = "http://bar.baz/" upload_id = "012345678901234567890123" example_source = { "format": "JSON", "origin": {"url": origin_url, "license": "MIT"}, "automation": {"parser": {"awsLambdaArn": "example.example"}}, "dateFilter": date_filter } example_source_stable_ids = { **example_source, "hasStableIdentifiers": True } def create_upload_url(source_id): return f"{_SOURCE_API_URL}/sources/{source_id}/uploads" @pytest.fixture() def mock_source_api_url_fixture(): """ Supplies a predetermined endpoint for G.h HTTP requests. Because the retrieval library is imported locally, this fixture can't be set to autouse. """ import common_lib # pylint: disable=import-error with patch('common_lib.get_source_api_url') as mock: mock.return_value = _SOURCE_API_URL yield common_lib @pytest.fixture() def setup_e2e(mock_source_api_url_fixture, valid_event, requests_mock): source_id = valid_event['sourceId'] # Mock the request to create the upload. requests_mock.post( create_upload_url(source_id), json={"_id": upload_id}, status_code=201) # Mock the request to retrieve source content. requests_mock.get(origin_url, json={"data": "yes"}) # Mock/stub retrieving credentials, invoking the parser, and S3. common_lib = mock_source_api_url_fixture common_lib.obtain_api_credentials = MagicMock( name="obtain_api_credentials", return_value={}) # Set up mock request values used in multiple requests. # TODO: Complete removal of URL env var. os.environ["EPID_INGESTION_ENV"] = valid_event['env'] os.environ["EPID_INGESTION_SOURCE_ID"] = valid_event['sourceId'] os.environ["EPID_INGESTION_PARSING_DATE_RANGE"] = ( valid_event['parsingDateRange']['start'] + "," + valid_event['parsingDateRange']['end'] ) os.environ["SOURCE_API_URL"] = _SOURCE_API_URL yield requests_mock, common_lib @pytest.fixture() def valid_event(): """Loads valid CloudWatch ScheduledEvent from file.""" current_dir = os.path.dirname(__file__) file_path = os.path.join(current_dir, "valid_scheduled_event.json") with open(file_path) as event_file: return json.load(event_file) def test_format_url_leaves_unchanged_if_no_format_params(): from retrieval import retrieval # Import locally to avoid superseding mock url = "http://foo.bar" assert retrieval.format_source_url(url) == url @patch('retrieval.retrieval.get_today') def test_format_url(mock_today): from retrieval import retrieval # Import locally to avoid superseding mock mock_today.return_value = datetime.datetime(2020, 6, 8) url = "http://foo.bar/$FULLYEAR-$FULLMONTH-$FULLDAY/$MONTH/$DAY.json" assert retrieval.format_source_url( url) == "http://foo.bar/2020-06-08/6/8.json" @patch('retrieval.retrieval.get_today') def test_format_url_daysbefore(mock_today): from retrieval import retrieval # Import locally to avoid superseding mock mock_today.return_value = datetime.datetime(2020, 6, 8) url = "http://foo.bar/$FULLYEAR-$FULLMONTH-$FULLDAY/$MONTH/$DAY.json::daysbefore=3" assert retrieval.format_source_url( url) == "http://foo.bar/2020-06-05/6/5.json" @pytest.mark.skipif(not os.environ.get("DOCKERIZED", False), reason="Running integration tests outside of mock environment disabled") @pytest.mark.parametrize("source", [example_source_stable_ids, example_source]) def test_e2e(source, valid_event, mock_source_api_url_fixture, setup_e2e, tempdir="/tmp"): from retrieval import retrieval requests_mock, common_lib = setup_e2e print(valid_event) source_id = valid_event['sourceId'] retrieval.invoke_parser = MagicMock(name="invoke_parser") # Mock the request to retrieval source details (e.g. format). full_source_url = f"{_SOURCE_API_URL}/sources/{source_id}" requests_mock.get(full_source_url, json=source) has_stable_ids = source.get("hasStableIdentifiers", False) response = retrieval.run_retrieval(tempdir=tempdir) common_lib.obtain_api_credentials.assert_called_once() retrieval.invoke_parser.assert_called_once_with( valid_event["env"], "parsing.example.example", source_id, upload_id, {}, None, response["key"], origin_url, date_filter if has_stable_ids else {}, valid_event["parsingDateRange"] if has_stable_ids else {}) assert requests_mock.request_history[0].url == create_upload_url(source_id) assert requests_mock.request_history[1].url == full_source_url assert requests_mock.request_history[2].url == origin_url assert response["bucket"] == retrieval.OUTPUT_BUCKET assert source_id in response["key"] assert response["upload_id"] == upload_id def test_extract_event_fields_returns_env_source_id_and_date_range(valid_event): from retrieval import retrieval env, source_id, date_range, _ = retrieval.extract_event_fields(valid_event) assert env == valid_event["env"] assert source_id == valid_event["sourceId"] assert date_range == valid_event["parsingDateRange"] def test_extract_event_fields_raises_error_if_event_lacks_env(): from retrieval import retrieval # Import locally to avoid superseding mock with pytest.raises(ValueError, match=retrieval.ENV_FIELD): retrieval.extract_event_fields({"sourceId": "sourceId"}) def test_extract_event_fields_raises_error_if_event_lacks_source_id(): from retrieval import retrieval # Import locally to avoid superseding mock with pytest.raises(ValueError, match=retrieval.SOURCE_ID_FIELD): retrieval.extract_event_fields({"env": "env"}) def test_get_source_details_returns_url_format_stable_identifiers( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = "http://bar.baz" requests_mock.get(f"{_SOURCE_API_URL}/sources/{source_id}", json={"format": "CSV", "origin": {"url": content_url, "license": "MIT"}, "hasStableIdentifiers": True }) result = retrieval.get_source_details( "env", source_id, "upload_id", {}, {}) assert result[0] == content_url assert result[1] == "CSV" assert result[2] == "" assert result[3] == {} assert result[4] is True def test_get_source_details_returns_parser_arn_if_present( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = "http://bar.baz" job_def_arn = "testArn" requests_mock.get( f"{_SOURCE_API_URL}/sources/{source_id}", json={"origin": {"url": content_url, "license": "MIT"}, "format": "JSON", "automation": {"parser": {"awsLambdaArn": job_def_arn}}}) result = retrieval.get_source_details( "env", source_id, "upload_id", {}, {}) assert result[2] == job_def_arn def test_get_source_details_raises_error_if_source_not_found( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock # TODO: Complete removal of URL env var. os.environ["SOURCE_API_URL"] = _SOURCE_API_URL source_id = "id" get_source_url = f"{_SOURCE_API_URL}/sources/{source_id}" requests_mock.get(get_source_url, status_code=404) upload_id = "upload_id" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) try: retrieval.get_source_details("env", source_id, upload_id, {}, {}) except Exception: assert requests_mock.request_history[0].url == get_source_url assert requests_mock.request_history[1].url == update_upload_url assert requests_mock.request_history[-1].json( ) == {"status": "ERROR", "summary": {"error": common_lib.UploadError.SOURCE_CONFIGURATION_NOT_FOUND.name}} return # We got the wrong exception or no exception, fail the test. assert not "Should have raised an exception." def test_get_source_details_raises_error_if_other_errors_getting_source( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock # TODO: Complete removal of URL env var. os.environ["SOURCE_API_URL"] = _SOURCE_API_URL source_id = "sourceId" get_source_url = f"{_SOURCE_API_URL}/sources/{source_id}" requests_mock.get(get_source_url, status_code=500) upload_id = "upload_id" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) try: retrieval.get_source_details("env", source_id, upload_id, {}, {}) except Exception: assert requests_mock.request_history[0].url == get_source_url assert requests_mock.request_history[1].url == update_upload_url assert requests_mock.request_history[-1].json( ) == {"status": "ERROR", "summary": {"error": common_lib.UploadError.INTERNAL_ERROR.name}} return # We got the wrong exception or no exception, fail the test. assert not "Should have raised an exception." def test_retrieve_content_persists_downloaded_json_locally(requests_mock): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = "http://foo.bar/" format = "JSON" requests_mock.get(content_url, json={"data": "yes"}) files_s3_keys = retrieval.retrieve_content( "env", source_id, "upload_id", content_url, format, {}, {}, tempdir="/tmp") assert requests_mock.request_history[0].url == content_url assert "GHDSI" in requests_mock.request_history[0].headers["user-agent"] with open(files_s3_keys[0][0], "r") as f: assert json.load(f)["data"] == "yes" @pytest.mark.skipif(not os.environ.get("DOCKERIZED", False), reason="Running integration tests outside of mock environment disabled") def test_retrieve_content_from_s3(): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = f"s3://{SOURCES_BUCKET}/bar" format = "JSON" s3_client.put_object(Bucket=SOURCES_BUCKET, Key='bar', Body=b'{"data": "yes"}') files_s3_keys = retrieval.retrieve_content( "env", source_id, "upload_id", content_url, format, {}, {}, tempdir="/tmp") with open(files_s3_keys[0][0], "r") as f: assert json.load(f)["data"] == "yes" def test_retrieve_content_persists_downloaded_csv_locally(requests_mock): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = "http://foo.bar/" format = "CSV" requests_mock.get(content_url, content=b"foo,bar\nbaz,quux\n") files_s3_keys = retrieval.retrieve_content( "env", source_id, "upload_id", content_url, format, {}, {}, tempdir="/tmp") assert requests_mock.request_history[0].url == content_url assert "GHDSI" in requests_mock.request_history[0].headers["user-agent"] with open(files_s3_keys[0][0], "r") as f: assert f.read().strip() == "foo,bar\nbaz,quux" def test_retrieve_content_returns_local_and_s3_object_names(requests_mock): from retrieval import retrieval # Import locally to avoid superseding mock source_id = "id" content_url = "http://foo.bar/" requests_mock.get(content_url, json={"data": "yes"}) results = retrieval.retrieve_content( "env", source_id, "upload_id", content_url, "JSON", {}, {}, tempdir="/tmp") assert all("/tmp/" in fn for fn, s3key in results) assert all(source_id in s3key for fn, s3key in results) def test_retrieve_content_raises_error_for_non_supported_format( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock content_url = "http://foo.bar/" source_id = "source_id" upload_id = "123456789012345678901234" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) bad_format = "PDF" try: retrieval.retrieve_content( "env", source_id, upload_id, content_url, bad_format, {}, {}, tempdir="/tmp") except ValueError: assert requests_mock.request_history[0].url == update_upload_url assert requests_mock.request_history[-1].json( ) == {"status": "ERROR", "summary": {"error": common_lib.UploadError.SOURCE_CONFIGURATION_ERROR.name}} return # We got the wrong exception or no exception, fail the test. assert not "Should have raised an exception." def test_retrieve_content_raises_error_for_source_content_not_found( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock content_url = "http://foo.bar/" requests_mock.get(content_url, status_code=404) source_id = "source_id" upload_id = "123456789012345678901234" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) try: retrieval.retrieve_content( "env", source_id, upload_id, content_url, "JSON", {}, {}, tempdir="/tmp") except Exception: assert requests_mock.request_history[0].url == content_url assert requests_mock.request_history[1].url == update_upload_url assert requests_mock.request_history[-1].json( ) == {"status": "ERROR", "summary": {"error": common_lib.UploadError.SOURCE_CONTENT_NOT_FOUND.name}} return # We got the wrong exception or no exception, fail the test. assert not "Should have raised an exception." def test_retrieve_content_raises_error_if_other_errors_getting_source_content( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock content_url = "http://bar.baz/" requests_mock.get(content_url, status_code=500) source_id = "source_id" upload_id = "123456789012345678901234" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) try: retrieval.retrieve_content( "env", source_id, upload_id, content_url, "JSON", {}, {}, tempdir="/tmp") except Exception: assert requests_mock.request_history[0].url == content_url assert requests_mock.request_history[1].url == update_upload_url assert requests_mock.request_history[-1].json( ) == {"status": "ERROR", "summary": {"error": common_lib.UploadError.SOURCE_CONTENT_DOWNLOAD_ERROR.name}} return # We got the wrong exception or no exception, fail the test. assert not "Should have raised an exception." @pytest.mark.skipif(not os.environ.get("DOCKERIZED", False), reason="Running integration tests outside of mock environment disabled") def test_upload_to_s3_writes_indicated_file_to_key(): from retrieval import retrieval # Import locally to avoid superseding mock local_file = "/tmp/data.txt" expected_data = "This is data." with open(local_file, "w") as f: f.write(expected_data) expected_s3_bucket = retrieval.OUTPUT_BUCKET expected_s3_key = "objectkey" retrieval.upload_to_s3(local_file, expected_s3_key, "", "", "", {}, {}) # api creds actual_object = s3_client.get_object( Bucket=expected_s3_bucket, Key=expected_s3_key) s3_data = actual_object['Body'].read().decode("utf-8") assert s3_data == expected_data @pytest.mark.skipif(not os.environ.get("DOCKERIZED", False), reason="Running integration tests outside of mock environment disabled") def test_upload_to_s3_raises_error_on_s3_error( requests_mock, mock_source_api_url_fixture): from retrieval import retrieval # Import locally to avoid superseding mock upload_id = "123456789012345678901234" source_id = "source_id" update_upload_url = f"{_SOURCE_API_URL}/sources/{source_id}/uploads/{upload_id}" requests_mock.put(update_upload_url, json={}) try: retrieval.upload_to_s3("not a file name", "not an s3 key", "env", source_id, upload_id, {}, {}) # api creds except Exception: assert requests_mock.request_history[0].url ==
n_space: return self.__space = n_space self.update() @property def pixmap(self) -> QPixmap: return self.__pixmap @pixmap.setter def pixmap(self, n_pixmap: QPixmap) -> None: self.__pixmap = n_pixmap self.update() @property def name(self) -> str: return self.__name @name.setter def name(self, n_name: str) -> None: if self.__name == n_name: return self.__name = n_name self.update() @property def belong(self) -> str: return self.__belong @belong.setter def belong(self, n_belong: str) -> None: if self.__belong == n_belong: return self.__belong = n_belong self.update() @property def tel(self) -> str: return self.__tel @tel.setter def tel(self, n_tel: str) -> None: if self.__tel == n_tel: return self.__tel = n_tel self.update() @property def bgColor(self) -> QColor: return self.__bgColor @bgColor.setter def bgColor(self, bg_color: QColor) -> None: if self.__bgColor == bg_color: return self.__bgColor = bg_color self.update() @property def nameColor(self) -> QColor: return self.__nameColor @nameColor.setter def nameColor(self, name_color: QColor) -> None: if self.__nameColor == name_color: return self.__nameColor = name_color self.update() @property def belongColor(self) -> QColor: return self.__belongColor @belongColor.setter def belongColor(self, belong_color: QColor) -> None: if self.__belongColor == belong_color: return self.__belongColor = belong_color self.update() def sizeHint(self) -> QSize: return QSize(60, 40) def minimumSizeHint(self) -> QSize: return QSize(50, 40) # 自定义滚动条类 class ScrollBar(QScrollBar): def __init__(self, parent: QScrollBar = None): super(ScrollBar, self).__init__(parent) def getSliderHeight(self) -> int: opt: QStyleOptionSlider = QStyleOptionSlider() self.initStyleOption(opt) rect: QRect = self.style().subControlRect(QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarSlider, self) return rect.height() # 通讯录面板类 class TelPanel(QWidget): positionChanged = Signal(int) # value def __init__(self, parent: QWidget = None): super(TelPanel, self).__init__(parent) self.__step: int = 1200 # 移动的步长 self.__margin: int = 0 # 边距 self.__space: int = 0 # 设备之间的间隔 self.__autoWidth: bool = False # 宽度自动拉伸 self.__autoHeight: bool = False # 高度自动拉伸 self.__normalColor: QColor = QColor(0, 0, 0, 35) # 滚动条正常颜色 self.__highColor: QColor = QColor(0, 0, 0, 75) # 滚动条高亮颜色 self.__columnCount: int = 1 # 面板列数 self.__items: List[QWidget] = [] # 元素窗体集合 self.__indexs: List[int] = [] # 分割窗体位置索引 self.__banners: List[QWidget] = [] # 分割窗体集合 self.__scrollArea: QScrollArea = QScrollArea(self) # 滚动区域 self.__animation: QPropertyAnimation = QPropertyAnimation(self.__scrollArea.verticalScrollBar(), b"value") # 动画滑动 self.__scrollBar: QScrollBar = QScrollBar(Qt.Vertical, self) # 滚动条 self.__widget: QWidget = QWidget(self.__scrollArea) # 滚动区域载体,自动变宽变高 self.__gridLayout: QGridLayout = QGridLayout(self.__widget) # 表格布局 self.__movetop: bool = False # 是否上滑 self.__pressed: bool = False # 鼠标按下 self.__pressedY: int = 0 # 鼠标按下处Y轴坐标 self.__pressedPos: QPoint = QPoint(0, 0) # 鼠标按下处坐标 self.__pressedTime: QDateTime = QDateTime() # 鼠标按下时间 self.__timer: QTimer = QTimer(self) # 定时器控制滚动条隐藏 self.initControl() self.initForm() self.initBar() def eventFilter(self, watched: QObject, event: QEvent) -> bool: if watched == self.__widget: if event.type() == QEvent.Resize: self.initBar() return super(TelPanel, self).eventFilter(watched, event) def resizeEvent(self, event: QResizeEvent) -> None: self.__scrollArea.resize(self.size()) # 根据宽度比例调整滚动条占的区域 width: int = self.width() height: int = self.height() scrollWidth: int = 10 offset: int = 3 self.__scrollBar.setGeometry(width - scrollWidth - offset, offset, scrollWidth, height - offset * 2) def enterEvent(self, event: QEvent) -> None: pass def leaveEvent(self, event: QEvent) -> None: pass def mousePressEvent(self, event: QMouseEvent) -> None: self.__pressed = True self.__pressedPos = event.pos() self.__pressedY = event.pos().y() self.__pressedTime = QDateTime.currentDateTime() self.__scrollBar.show() self.__animation.stop() def mouseReleaseEvent(self, event: QMouseEvent) -> None: self.__pressed = False # 说明是单击按钮 if self.__pressedPos == event.pos(): return # 判断当前时间和鼠标按下事件比较,时间短则说明是滑动 now: QDateTime = QDateTime.currentDateTime() if self.__pressedTime.time().msecsTo(now.time()) > 600: return # 可以改变下面的值来调整幅度 offset: int = self.__step if self.__movetop else -self.__step value: int = self.__scrollArea.verticalScrollBar().value() self.__animation.setStartValue(value) self.__animation.setEndValue(value + offset) self.__animation.start() self.__timer.start(800) def mouseMoveEvent(self, event: QMouseEvent) -> None: currentY: int = event.pos().y() offset: int = self.__pressedY - currentY scal: int = offset * 2 self.__movetop = offset > 0 # 如果滚动条已经在顶部且当前下滑或者在底部且当前上滑则无需滚动 value: int = self.__scrollArea.verticalScrollBar().value() height: int = self.__scrollArea.verticalScrollBar().height() if (value == 0 and not self.__movetop) or ((value + height) == self.__widget.height() and self.__movetop): return if self.__pressedY != currentY: # 设置滚轮位置 self.position += scal self.__pressedY = currentY def initControl(self) -> None: """ 初始化控件 """ # 滚动条区域 self.__scrollArea.setObjectName("TelPanel_ScrollArea") self.__scrollArea.setWidgetResizable(True) self.__scrollArea.setStyleSheet("QScrollArea#TelPanel_ScrollArea{border:none;background:transparent;}") # 替换垂直滚动条,以便获取滚动条手柄的高度 bar: ScrollBar = ScrollBar() self.__scrollArea.setVerticalScrollBar(bar) # 设置滚动条不显示,用自定义的滚动条 self.__scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 滚动条 self.__scrollBar.setVisible(False) self.__scrollArea.verticalScrollBar().valueChanged.connect(self.__scrollBar.setValue) self.__scrollBar.valueChanged.connect(self.__scrollArea.verticalScrollBar().setValue) self.__scrollArea.verticalScrollBar().rangeChanged.connect(self.setRange) self.__scrollBar.valueChanged.connect(self.positionChanged) # 元素载体窗体 self.__widget.installEventFilter(self) self.__widget.setObjectName("TelPanel_Widget") self.__widget.setGeometry(QRect(0, 0, 100, 100)) self.__widget.setStyleSheet("QWidget#TelPanel_Widget{background:transparent;}") self.__scrollArea.setWidget(self.__widget) # 表格布局 self.__gridLayout.setSpacing(0) self.__gridLayout.setContentsMargins(0, 0, 0, 0) def initForm(self) -> None: """ 初始化窗体 """ # 定义动画产生平滑数值 self.__animation.setEasingCurve(QEasingCurve.OutCirc) self.__animation.setDuration(500) # 启动定时器隐藏滚动条 self.__timer.timeout.connect(self.checkBar) def initBar(self) -> None: """ 初始化滚动条 """ # 获取到原有滚动条手柄的高度,重新设置新的滚动条的手柄高度 bar: ScrollBar = self.__scrollArea.verticalScrollBar() # 原有高度可能太小,在此基础上加点 sliderHeight: int = bar.getSliderHeight() + 50 sliderHeight = self.height() if sliderHeight > self.height() else sliderHeight # 滚动条样式 lists: List[str] = [ "QScrollBar:vertical{background:transparent;padding:0px;}", "QScrollBar::handle:vertical{min-height:%dpx;}" % sliderHeight, "QScrollBar::handle:vertical{background:rgba(%d,%d,%d,%d);border-radius:5px;}" % ( self.__normalColor.red(), self.__normalColor.green(), self.__normalColor.blue(), self.__normalColor.alpha()), "QScrollBar::handle:vertical:hover,QScrollBar::handle:vertical:pressed{background:rgba(%d,%d,%d,%d);}" % ( self.__highColor.red(), self.__highColor.green(), self.__highColor.blue(), self.__highColor.alpha()), "QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical{background:none;}", "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{background:none;}" ] self.__scrollBar.setStyleSheet(''.join(lists)) def checkBar(self) -> None: """ 处理滚动条隐藏 """ # 如果当前为按下则不需要隐藏 if self.__pressed: return self.__scrollBar.hide() self.__timer.stop() def setRange(self, n_min: int, n_max: int) -> None: """ 设置滚动条范围值 """ self.__scrollBar.setRange(n_min, n_max) @property def step(self) -> int: return self.__step @property def margin(self) -> int: return self.__margin @property def space(self) -> int: return self.__space @property def autoWidth(self) -> bool: return self.__autoWidth @property def autoHeight(self) -> bool: return self.__autoHeight @property def normalColor(self) -> QColor: return self.__normalColor @property def highColor(self) -> QColor: return self.__highColor @property def position(self) -> int: return self.__scrollBar.value() @property def columnCount(self) -> int: return self.__columnCount @property def items(self) -> List[QWidget]: return self.__items @property def indexs(self) -> List[int]: return self.__indexs @property def banners(self) -> List[QWidget]: return self.__banners def sizeHint(self) -> QSize: return QSize(300, 200) def minimumSizeHint(self) -> QSize: return QSize(20, 20) @step.setter def step(self, n_step: int) -> None: """ 设置每次滚动条移动的步长 """ if self.__step != n_step: self.__step = n_step @margin.setter def margin(self, n_margin: int) -> None: """ 设置四个方位边距 """ self.__margin = n_margin def setMargin(self, left: int, top: int, right: int, bottom: int) -> None: """ 设置四个方位边距 """ self.__gridLayout.setContentsMargins(left, top, right, bottom) @space.setter def space(self, n_space: int) -> None: """ 设置元素间距 """ if self.__space != n_space: self.__gridLayout.setSpacing(n_space) @autoWidth.setter def autoWidth(self, auto_width: bool) -> None: """ 设置是否自动宽度 """ if self.__autoWidth != auto_width: self.__autoWidth = auto_width @autoHeight.setter def autoHeight(self, auto_height: bool) -> None: """ 设置是否自动高度 """ if self.__autoHeight != auto_height: self.__autoHeight = auto_height @position.setter def position(self, value: int): """ 设置滚动条位置 """ self.__scrollBar.setValue(value) @normalColor.setter def normalColor(self, normal_color: QColor) -> None: """ 设置滚动条正常颜色 """ if self.__normalColor != normal_color: self.__normalColor = normal_color self.initBar() @highColor.setter def highColor(self, high_color: QColor) -> None: """ 设置滚动条高亮颜色 """ if self.__highColor != high_color: self.__highColor = high_color self.initBar() @indexs.setter def indexs(self, n_indexs: List[int]) -> None: """ 设置分割窗体 """ if self.__indexs != n_indexs: self.__indexs = n_indexs @banners.setter def banners(self, n_banners: List[QWidget]) -> None: """ 设置索引位置 """ self.__banners = n_banners @columnCount.setter def columnCount(self, column_count: int) -> None: """ 设置窗体元素列数 """ if self.__columnCount != column_count: self.__columnCount = column_count @items.setter def items(self, n_items: List[QWidget]) -> None: """ 设置窗体元素集合 """ self.__items = n_items.copy() row: int = 0 column: int = 0 count: int = 0 temp: int = 0 # 单独添加第一行标识符 if self.__indexs.__len__() > 0 and self.__indexs[0] == 0: self.__gridLayout.addWidget(self.__banners[0], row, column, 1, self.__columnCount) row += 1 for item in n_items: # 逐行添加元素到表格布局 self.__gridLayout.addWidget(item, row, column) column += 1 count += 1 temp += 1 # 强制插入分割控件,另起一行 index: int = self.__indexs.index(count) if count in self.__indexs else -1 if index >= 0: row += 1 column = 0 self.__gridLayout.addWidget(self.__banners[index], row, column, 1, self.__columnCount) # 奇数偶数增加的数量不一样 if temp % self.__columnCount == 0: temp += self.__columnCount else: temp += 1 row += 1 # 如果到了列数则换行 if temp % self.__columnCount == 0: row += 1 column = 0 row += 1 # 设置右边弹簧 if not self.__autoWidth: hSpacer: QSpacerItem = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum) self.__gridLayout.addItem(hSpacer, 0, self.__gridLayout.columnCount()) # 设置底边弹簧 if not self.__autoHeight: vSpacer: QSpacerItem = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding) self.__gridLayout.addItem(vSpacer, row, 0) # 通讯录控件 class TelWidget(QWidget): """ 通讯录控件 作者:feiyangqingyun(QQ:517216493) 2018-9-30 译者:sunchuquin(QQ:1715216365) 2021-06-21 1. 可设置信息集合(图标+姓名+类型+电话)以及添加单个联系人 2. 可设置背景图片+背景颜色 3. 可设置右侧导航字母的列表+默认颜色+高亮颜色 4. 可设置联系人按钮姓名颜色+姓名字体 5. 可设置联系人按钮类型颜色+姓名字体 6. 可设置联系人按钮选中背景颜色 7. 可设置字母导航的风格(背景颜色+线条) 8. 可设置字母导航的颜色+字体大小 9. 可设置各种边距+联系人列数+元素间隔等 10. 支持悬浮滚动条,可设置悬停时间 11. 可设置悬浮滚动条的正常颜色+高亮颜色 12. 支持滑动,可设置滑动的步长速度 13. 支持单击右侧字母导航定位+文本突出显示 14. 单击发出当前联系人的姓名+类型+电话等信息 15. 根据汉字字母排序从小到大排列联系人,自带汉字转拼音功能 """ telClicked = Signal(str, str, str) # name, type, tel class TelInfo: """ 联系人结构体 """ def __init__(self): self.letter: str = '' self.name: str = '' self.n_type: str = '' self.tel: str = '' self.pixmap: QPixmap = QPixmap() def __lt__(self, other): return self.letter < other.letter def __le__(self, other): return self.letter > other.letter def __init__(self, parent: QWidget = None): super(TelWidget, self).__init__(parent) self.zhtopy = ZhToPY() self.__names: List[AnyStr] = [] # 姓名集合 self.__types: List[AnyStr] = [] # 类型集合 self.__tels: List[AnyStr] = [] # 电话集合 self.__bgImage: QPixmap = QPixmap()
[x for x in os.listdir(rsid_path) if os.path.isfile(os.path.join(rsid_path,x)) and x.endswith('.bed')] # if conversion files found, perform conversion if len(files) > 0: rsid_path = os.path.join(rsid_path,files[0]) script = """join {} {} -1 1 -2 4 -o 2.1 -o 2.2 -o 2.3 -o 2.4 -o 2.5 -o 2.6 | sed 's/\ /\t/g' > {}.temp""".format(out_f,rsid_path,out_f) out = subprocess.Popen([script],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() tmp_er = out.stderr.read() if tmp_er != "": logger.error(tmp_er) raise Exception(tmp_er) # we remove the original out_f FOI file and replace with the out_f.temp created with the join command above os.remove(out_f) out = subprocess.Popen(['cp {} {}'.format(out_f+'.temp',out_f)],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() os.remove(out_f+'.temp') else: logger.error('rsID conversion not available for this organism. Analysis terminated.') return [] # sort the FOI and bgzip grsnp_util.sort_convert_to_bgzip(out_f,out_f+".gz") script = "tabix -f " + out_f+".gz" out = subprocess.Popen([script],shell=True,stdout=subprocess.PIPE) out.wait() # check if processed FOI file is empty if os.stat(out_f+".gz")[6]!=0: processed_fois.append(out_f + ".gz") else: logger.error("{} is empty. Removing.") else: processed_fois.append(f) # print "{} is part of the database".format(f) except Exception, e: logger.error("Error while processing the FOIs") logger.error(traceback.format_exc()) raise Exception(e) return processed_fois def preprocess_gf_files(file_paths,root_data_dir,organism): ''' Used to preprocess the GF files and the background file. Returns gzipped file paths ''' processed_files = [] data_dirs = [os.path.join(root_data_dir,'grsnp_db',organism), os.path.join(root_data_dir,'custom_data')] try: for out_f in file_paths: # if the file is not uploaded by the user, do not preprocess if len([x for x in data_dirs if x in out_f]) == 0: # unzip the file unzipped_f = out_f if out_f.endswith('.gz'): out = subprocess.Popen(["gunzip {}".format(out_f)],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() # filepath without the .gz extension unzipped_f = ".".join(unzipped_f.split(".")[:-1]) out_fname = os.path.split(unzipped_f)[1] if not out_fname.endswith('.bed'): out_fname = base_name(out_fname)+".bed" # replace the ".txt" extension with ".bed" output_dir = os.path.split(unzipped_f)[0] out_bed_f = os.path.join(output_dir,out_fname) # the processed file grsnp_util.remove_headers(unzipped_f) # perform rsid conversion if validate_rsids(unzipped_f): # check if a file exists in the database for rsID conversion and construct the path to it rsid_path = os.path.join(root_data_dir,'custom_data','rsid_conversion',organism) if not os.path.exists(rsid_path): logger.error('rsID conversion not available for this organism. Feature set {} removed'.format(unzipped_f)) continue files = [x for x in os.listdir(rsid_path) if os.path.isfile(os.path.join(rsid_path,x)) and x.endswith('.bed')] # if conversion files found, perform conversion if len(files) > 0: rsid_path = os.path.join(rsid_path,files[0]) # sort the RSID script = """sort -k1,1 -o {} {}""".format(unzipped_f,unzipped_f) out = subprocess.Popen([script],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() # join the RSID with the SNP data in custom_data script = """join {} {} -1 1 -2 4 -o 2.1 -o 2.2 -o 2.3 -o 2.4 -o 2.5 -o 2.6 | sed 's/\ /\t/g' > {}.temp""".format(unzipped_f,rsid_path,unzipped_f) out = subprocess.Popen([script],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() tmp_er = out.stderr.read() if tmp_er != "": logger.error(tmp_er) raise Exception(tmp_er) # we remove the original unzipped_f FOI file and replace with the unzipped_f.temp created with the join command above out = subprocess.Popen(['cp {} {}'.format(unzipped_f+'.temp',out_bed_f)],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out.wait() os.remove(unzipped_f+'.temp') else: logger.error('rsID conversion not available for this organism. Analysis terminated.') return [] # sort the FOI grsnp_util.sort_convert_to_bgzip(out_bed_f,out_bed_f+".gz") # check if processed FOI file is empty if os.stat(out_bed_f+".gz")[6]!=0: # add the processed file (the ".bed" file) to the list. processed_files.append(out_bed_f + ".gz") else: logger.error("{} is empty. Removing.") else: processed_files.append(out_f) # print "{} is part of the database".format(out_f) except Exception, e: logger.error("Error while processing the GF/background files") logger.error(traceback.format_exc()) raise Exception(e) return processed_files def run_hypergeom(fois, gfs, bg_path,outdir,job_name="",zip_run_files=False,bkg_overlaps_path="",root_data_dir = "" ,run_annotation=True,run_randomization_test=False,pct_score="",organism = "",stat_test=None): global formatter global run_files_dir valid_stat_tests = ["chisquare","binomial"] if not os.path.exists(os.path.normpath(outdir)): os.mkdir(os.path.normpath(outdir)) fh = logging.FileHandler(os.path.join(outdir,'gr_log.txt')) fh.setFormatter(formatter) logger.addHandler(fh) logger.setLevel(logging.INFO) run_files_dir = outdir logger.propagate = False try: track_descriptions = [] logger.info("Enrichment analysis started") decriptions_path = os.path.join(root_data_dir,"grsnp_db",organism,"gf_descriptions.txt") if os.path.exists(decriptions_path): track_descriptions = [x.split("\t") for x in open(decriptions_path).read().split("\n") if x != ""] # set output settings detailed_outpath = os.path.join(outdir, "detailed.txt") matrix_outpath = os.path.join(outdir,"matrix_PVAL.txt") matrix_sor_outpath = os.path.join(outdir,"matrix_OR.txt") progress_outpath = os.path.join(outdir,".prog") curr_prog = Progress(progress_outpath,0,1) # stores the current progress _write_progress("Starting analysis.", curr_prog) f = open(matrix_outpath,'wb') f.close() f = open(matrix_sor_outpath,'wb') f.close() f = open(detailed_outpath,'wb') f.close() # Read in the paths fois = [line for line in read_lines(fois) if not line.endswith(".tbi")] gfs = [line for line in read_lines(gfs) if not line.endswith(".tbi")] # check if there are spaces in invalid parts of the file name invalid_names = validate_filenames(fois + gfs + [bg_path]) if len(invalid_names) != 0: logger.error("The following file(s) have invalid file names:\n" + "\n".join(invalid_names)) _write_progress("ERROR: Files have invalid filenames. See log file. Terminating run. See Analysis Log.", curr_prog) print "ERROR: Files have invalid filenames. See log file. Terminating run. See Analysis Log." return if bg_path.endswith(".tbi"): logger.error("Background has invalid extension (.tbi). Terminating run.") _write_progress("ERROR: Background has invalid extension (.tbi). Terminating run. See Analysis Log.", curr_prog) print "ERROR: Background has invalid extension (.tbi). Terminating run. See Analysis Log." return if stat_test not in valid_stat_tests and not stat_test.startswith("montecarlo_"): logger.error("Valid p-value test not selected. Terminating run.") _write_progress("ERROR: Valid p-value test not selected. Terminating run. See Analysis Log.", curr_prog) print "ERROR: Valid p-value test not selected. Terminating run. See Analysis Log." return # pre-process the FOIs fois = preprocess_fois(fois,run_files_dir,root_data_dir,organism) if len(fois) == 0: logger.error('No valid FOIs to supplied') _write_progress("ERROR: No valid FOI files supplied. Terminating run. See Analysis Log.", curr_prog) return # pre-process the GFs and the background bg_path = preprocess_gf_files([bg_path],root_data_dir,organism)[0] gfs = preprocess_gf_files(gfs,root_data_dir,organism) # Validate FOIs against background. Also get the size of the background (n_bgs) foi_bg,good_fois = check_background_foi_overlap(bg_path,fois, progress = curr_prog) write_output("\t".join(map(base_name,good_fois))+"\n", matrix_outpath) write_output("\t".join(map(base_name,good_fois))+"\n", matrix_sor_outpath) write_output("\t".join(['foi_name', 'foi_obs', 'n_fois', 'bg_obs', 'n_bgs', 'odds_ratio',"ci_lower","ci_upper", 'shrunken_odds_ratio', str(stat_test) + '_ p_val','p_rand' if run_randomization_test else "",'p_mod' if run_randomization_test else ""]) + "\n",detailed_outpath) curr_prog.current, curr_prog.max = 0,len(gfs) # check if any good fois exist after background filtering if len(good_fois) == 0: logger.error('No valid FOIs to supplied') _write_progress("ERROR: No valid FOI files supplied. Terminating run. See Analysis Log.", curr_prog) return # remove old detailed enrichment result files if they exit enr_path = os.path.join(run_files_dir,"enrichment") for f in good_fois: f_path = os.path.join(enr_path, base_name(f)+'.txt') if os.path.exists(f_path): os.remove(f_path) _write_progress("Performing calculations on the background.", curr_prog) for gf in gfs: current_gf = base_name(gf) _write_progress("Performing {} analysis for {}".format(stat_test,base_name(gf)),curr_prog) write_output("###"+base_name(gf)+"\t"+get_score_strand_settings(gf)+"\t"+get_description(base_name(gf),track_descriptions)+"###"+"\n",detailed_outpath) res = get_overlap_statistics(gf,good_fois) # calculate bg_obs bg_obs = get_bgobs(bg_path,gf,root_data_dir,organism, progress = curr_prog) if bg_obs == None: logger.error("Skipping {}".format(gf)) continue n_bgs = foi_bg[0]["indexregions"] # calculate the pvalues and output the matrix line for the current gf pvals,sors = [],[] # sors = shrunken odds-ratios for i in range(len(good_fois)): [pvalue,shrunken_or] = output_p_value(res[i]["intersectregions"],res[i]["queryregions"],bg_obs,n_bgs ,good_fois[i],gf,bg_path,detailed_outpath,run_randomization_test,stat_test = stat_test,progress = curr_prog) pvals.append(str(pvalue)) sors.append(str(shrunken_or)) # output the matrices file lines write_output("\t".join([base_name(gf)] + pvals)+"\n",matrix_outpath) write_output("\t".join([base_name(gf)] + sors)+"\n",matrix_sor_outpath) curr_prog.current += 1 if run_annotation: logger.info("Annotation started") annot_outdir = os.path.join(outdir,"annotations") if not os.path.exists(annot_outdir): os.mkdir(annot_outdir) curr_prog.current, curr_prog.max = 0,len(fois) for f in fois: _write_progress("Running Annotation Analysis for {}.".format(base_name(f)),curr_prog) logger.info("Running annotation analysis for {}".format(base_name(f))) for i, g in enumerate(_chunks(gfs,100)): with open(os.path.join(annot_outdir,base_name(f) + str(i) + ".txt"),"wb") as wr: anot = get_annotation(f,g).split("\n") anot[0] = anot[0].replace("Region\t\t","Region\t") wr.write("Region"+"\t"+"\t".join(base_name(x) for x in reversed(anot[0].split("\t")[1:])) + "\tTotal") # annotationAnalysis column order is reverse of input order for ind, a in enumerate(anot[1:]): if a.strip() != "": cur_row = a.split("\t") wr.write("\n" + str(ind) + "|"+"\t".join(cur_row + [str(sum([int(x) for x in cur_row[1:] if x != ""]))])) curr_prog.current += 1 logger.info("Annotation finished") if zip_run_files: _write_progress("Preparing run files for download",curr_prog) _zip_run_files(fois,gfs,bg_path,outdir,job_name) curr_prog.current, curr_prog.max = 1,1 _write_progress("Analysis Completed",curr_prog) logger.info("Analysis Completed") except Exception, e: logger.error( traceback.print_exc()) _write_progress("Run crashed. See end of log for details.",curr_prog) raise Exception(e) class front_appender: ''' Appends content to start of file. ''' def __init__(self, fname, mode='a'): self.__write_queue = [] self.__old_content = "" if mode == 'a': self.__old_content = open(fname).read() self.__f = open(fname, 'w') def write(self, s): self.__write_queue.append(s) def close(self): self.__f.writelines(self.__write_queue + [self.__old_content]) self.__f.close() def _load_minmax(path): data = {} if not os.path.exists(path): return data score = [x for x in open(path).read().split("\n") if x != ""] for s in score: name,min_max = s.split('\t') data[name] = min_max return data def main(): global detailed_outpath, progress_outpath, run_files_dir, console_output, print_progress print_progress = True parser = argparse.ArgumentParser(description="Enrichment analysis of several sets of SNPs (FOIs) files against several genomic features (GFs). Example: python hypergeom4.py foi_full_names.txt gf_full_names.txt /path_to_background/snp137.bed.gz") parser.add_argument("fois", nargs=1, help="Text file with paths to FOI files (unless -p used). Required") parser.add_argument("gfs" ,nargs=1, help="Text file with pathrs to GF files (unless -p used). GF files may be gzipped. Required") parser.add_argument("bg_path", nargs=1,
is 0.05. \ If your map has low overall contrast you might need to make this\ bigger such as 0.2. allow_box_if_b_iso_set = False .type = bool .short_caption = Allow box if b_iso set .help = Allow box_in_auto_sharpen (if set to True) even if \ b_iso is set. Default is to set box_n_auto_sharpen=False \ if b_iso is set. soft_mask = True .type = bool .help = Use soft mask (smooth change from inside to outside with radius\ based on resolution of map). Required if you use half-map \ sharpening without a model, otherwise optional. .short_caption = Soft mask use_weak_density = False .type = bool .short_caption = Use box with poor density .help = When choosing box of representative density, use poor \ density (to get optimized map for weaker density) discard_if_worse = None .type = bool .short_caption = Discard sharpening if worse .help = Discard sharpening if worse local_sharpening = None .type = bool .short_caption = Local sharpening .help = Sharpen locally using overlapping regions. \ NOTE: Best to turn off local_aniso_in_local_sharpening \ if symmetry is present.\ If local_aniso_in_local_sharpening is True and symmetry is \ present this can distort the map for some symmetry copies \ because an anisotropy correction is applied\ based on local density in one copy and is transferred without \ rotation to other copies. local_aniso_in_local_sharpening = None .type = bool .short_caption = Local anisotropy .help = Use local anisotropy in local sharpening. \ Default is True unless symmetry is present. overall_before_local = True .type = bool .short_caption = Overall before local .help = Apply overall scaling before local scaling select_sharpened_map = None .type = int .short_caption = Sharpened map to use .help = Select a single sharpened map to use read_sharpened_maps = None .type = bool .short_caption = Read sharpened maps .help = Read in previously-calculated sharpened maps write_sharpened_maps = None .type = bool .short_caption = Write sharpened maps .help = Write out local sharpened maps smoothing_radius = None .type = float .short_caption = Smoothing radius .help = Sharpen locally using smoothing_radius. Default is 2/3 of \ mean distance between centers for sharpening box_center = None .type = floats .short_caption = Center of box .help = You can specify the center of the box (A units) box_size = 40 40 40 .type = ints .short_caption = Size of box .help = You can specify the size of the boxes to use (grid units) target_n_overlap = 10 .type = int .short_caption = Target overlap of boxes .help = You can specify the targeted overlap of boxes in local \ sharpening restrict_map_size = None .type = bool .short_caption = Restrict box map size .help = Restrict box map to be inside full map (required for cryo-EM data).\ Default is True if use_sg_symmetry=False. restrict_z_turns_for_helical_symmetry = 1 .type = float .short_caption = Restrict Z turns for helical symmetry .help = Restrict Z turns for helical symmetry. Number of \ turns of helix going each direction in Z is specified. restrict_z_distance_for_helical_symmetry = None .type = float .short_caption = Restrict Z distance for helical symmetry .help = Restrict Z distance (+/- this distance from center) \ for helical symmetry. remove_aniso = True .type = bool .short_caption = Remove aniso .help = You can remove anisotropy (overall and locally) during sharpening cc_cut = 0.2 .type = float .short_caption = Min reliable CC in half-maps .help = Estimate of minimum highly reliable CC in half-map FSC. Used\ to decide at what CC value to smooth the remaining CC values. max_cc_for_rescale = 0.2 .type = float .short_caption = Max CC for rescaleMin reliable CC in half-maps .help = Used along with cc_cut and scale_using_last to correct for \ small errors in FSC estimation at high resolution. If the \ value of FSC near the high-resolution limit is above \ max_cc_for_rescale, assume these values are correct and do not \ correct them. scale_using_last = 3 .type = int .short_caption = Last N bins in FSC assumed to be about zero .help = If set, assume that the last scale_using_last bins in the FSC \ for half-map or model sharpening are about zero (corrects for \ errors in the half-map process). max_box_fraction = 0.5 .type = float .short_caption = Max size of box for auto_sharpening .help = If box is greater than this fraction of entire map, use \ entire map. density_select_max_box_fraction = 0.95 .type = float .short_caption = Max size of box for density_select .help = If box is greater than this fraction of entire map, use \ entire map for density_select. Default is 0.95 mask_atoms = True .type = bool .short_caption = Mask atoms .help = Mask atoms when using model sharpening mask_atoms_atom_radius = 3 .type =float .short_caption = Mask radius .help = Mask for mask_atoms will have mask_atoms_atom_radius value_outside_atoms = None .type = str .short_caption = Value outside atoms .help = Value of map outside atoms (set to 'mean' to have mean \ value inside and outside mask be equal) k_sharpen = 10 .type = float .short_caption = sharpening transition .help = Steepness of transition between sharpening (up to resolution \ ) and not sharpening (d < resolution). Note: for blurring, \ all data are blurred (regardless of resolution), while for \ sharpening, only data with d about resolution or lower are \ sharpened. This prevents making very high-resolution data too \ strong. Note 2: if k_sharpen is zero, then no \ transition is applied and all data is sharpened or blurred. \ Note 3: only used if b_iso is set. iterate = False .type = bool .short_caption = Iterate auto-sharpening .help = You can iterate auto-sharpening. This is useful in cases where \ you do not specify the solvent content and it is not \ accurately estimated until sharpening is optimized. optimize_b_blur_hires = False .type = bool .short_caption = Optimize value of b_blur_hires .help = Optimize value of b_blur_hires. \ Only applies for auto_sharpen_methods b_iso_to_d_cut and \ b_iso. This is normally carried out and helps prevent \ over-blurring at high resolution if the same map is \ sharpened more than once. optimize_d_cut = None .type = bool .short_caption = Optimize value of d_cut .help = Optimize value of d_cut. \ Only applies for auto_sharpen_methods b_iso_to_d_cut and \ b_iso. Not normally carried out. adjust_region_weight = True .type = bool .short_caption = Adjust region weight .help = Adjust region_weight to make overall change in surface area \ equal to overall change in normalized regions over the range \ of search_b_min to search_b_max using b_iso_to_d_cut. region_weight_method = initial_ratio *delta_ratio b_iso .type = choice .short_caption = Region weight method .help = Method for choosing region_weights. Initial_ratio uses \ ratio of surface area to regions at low B value. Delta \ ratio uses change in this ratio from low to high B. B_iso \ uses resolution-dependent b_iso (not weights) with the \ formula b_iso=5.9*d_min**2 region_weight_factor = 1.0 .type = float .short_caption = Region weight factor .help = Multiplies region_weight after calculation with \ region_weight_method above region_weight_buffer = 0.1 .type = float .short_caption = Region weight factor buffer .help = Region_weight adjusted to be region_weight_buffer \ away from minimum or maximum values region_weight_default = 30. .type = float .short_caption = Region weight default .help = Region_weight adjusted to be region_weight_default\ if no information available target_b_iso_ratio = 5.9 .type = float .short_caption = Target b_iso ratio .help = Target b_iso ratio : b_iso is estimated as \ target_b_iso_ratio * resolution**2 signal_min = 3.0 .type = float .short_caption = Minimum signal .help = Minimum signal in estimation of optimal b_iso. If\ not achieved, use any other method chosen. target_b_iso_model_scale = 0. .type = float .short_caption = scale on target b_iso ratio for model .help = For model sharpening, the target_biso is scaled \ (normally zero). search_b_min = -100 .type = float .short_caption
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: <EMAIL> ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## - Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## - Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## - Neither the name of the New York University nor the names of its ## contributors may be used to endorse or promote products derived from ## this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### from __future__ import division from datetime import datetime, date import hashlib import locale import os.path import re import sys import urllib import urlparse import uuid import vistrails.core.system from vistrails.db.services import io from vistrails.db.services.io import SaveBundle from vistrails.db.domain import DBVistrail, DBWorkflow from vistrails.db import VistrailsDBException from vistrails.core import debug from vistrails.core.system import get_elementtree_library, systemType, \ time_strptime ElementTree = get_elementtree_library() _drive_regex = re.compile(r"/*([a-zA-Z]:/.+)$") def pathname2url(path): """ Takes an absolute filename and turns it into a file:// URL. While urllib.pathname2url seems like a good idea, it doesn't appear to do anything sensible in practice on Windows. """ if path.startswith('file://'): path = urllib.unquote(path[7:]) if systemType in ('Windows', 'Microsoft'): path = path.replace('\\', '/') match = _drive_regex.match(path) if match is not None: path = '/%s' % match.group(1) path = urllib.quote(path, safe='/:') return path def url2pathname(urlpath): """ Takes a file:// URL and turns it into a filename. """ path = urllib.url2pathname(urlpath) if systemType in ('Windows', 'Microsoft'): path = path.replace('/', '\\') path = path.lstrip('\\') return path class BaseLocator(object): def load(self, type): raise NotImplementedError("load is not implemented") def save(self, obj, do_copy=True, version=None): """Saves an object in the given place. """ raise NotImplementedError("save is not implemented") def save_as(self, obj, version=None): return self.save(obj, True, version) # calls save by default def close(self): """Closes locator. """ pass def is_valid(self): """Returns true if locator refers to a valid object. """ raise NotImplementedError("is_valid is not implemented") def get_temporary(self): return None def has_temporaries(self): return self.get_temporary() is not None def clean_temporaries(self): pass def save_temporary(self, obj): pass def serialize(self, dom, element): """Serializes this locator to XML. """ raise NotImplementedError("serialize is not implemented") def to_xml(self, node=None): """ElementTree port of serialize. """ raise NotImplementedError("to_xml is not implemented") @staticmethod def parse(element): """Parse an XML object representing a locator and returns a Locator. """ raise NotImplementedError("parse is not implemented") @staticmethod def real_filename(filename): """ Expand relative path and dereference symbolic links To avoid dereference symbolic links: Remove realpath and add DontResolveSymlinks to QFileDialog calls """ return os.path.realpath(os.path.abspath(filename)) @classmethod def convert_filename_to_url(cls, filename): """ Converts a local filename to a file:// URL. All file:// URLs are absolute, so abspath() will be used on the argument. """ exts = ["vt", "xml"] q_mark = False query_str_idx = None for match in re.finditer("\.(%s)(\??)" % "|".join(exts), filename): if match.group(2): if q_mark: raise VistrailsDBException('Ambiguous URI with ' 'multiple question ' 'marks: "%s"' % filename) else: q_mark = True query_str_idx = match.end() if q_mark: args_str = filename[query_str_idx-1:] filename = filename[:query_str_idx-1] else: args_str = "" return 'file://%s%s' % (pathname2url(cls.real_filename(filename)), urllib.quote(args_str, safe='/?=&')) @staticmethod def from_url(url): """Assumes a valid URL if the scheme is specified. For example, 'file:///C:/My%20Documents/test.vt'. If only a filename is specified, it converts the filename to a URL. """ if '://' in url: scheme = url.split('://', 1)[0] elif url.startswith('untitled:'): scheme = 'untitled' else: scheme = 'file' url = BaseLocator.convert_filename_to_url(url) if scheme == 'untitled': return UntitledLocator.from_url(url) elif scheme == 'db': return DBLocator.from_url(url) elif scheme == 'file': old_uses_query = urlparse.uses_query urlparse.uses_query = urlparse.uses_query + ['file'] scheme, host, path, query, fragment = urlparse.urlsplit(str(url)) urlparse.uses_query = old_uses_query path = url2pathname(path) if path.lower().endswith(".xml"): return XMLFileLocator.from_url(url) else: return ZIPFileLocator.from_url(url) return None @staticmethod def parse_args(arg_str): args = {} parsed_dict = urlparse.parse_qs(arg_str) if 'type' in parsed_dict: args['obj_type'] = parsed_dict['type'][0] if 'id' in parsed_dict: args['obj_id'] = parsed_dict['id'][0] args['version_node'] = None args['version_tag'] = None if 'workflow' in parsed_dict: workflow_arg = parsed_dict['workflow'][0] try: args['version_node'] = int(workflow_arg) except ValueError: args['version_tag'] = workflow_arg if 'workflow_exec' in parsed_dict: args['workflow_exec'] = parsed_dict['workflow_exec'][0] if 'parameterExploration' in parsed_dict: args['parameterExploration'] = \ parsed_dict['parameterExploration'][0] if 'mashuptrail' in parsed_dict: args['mashuptrail'] = parsed_dict['mashuptrail'][0] # should use mashupVersion, but also allow (and preserve) mashup if 'mashupVersion' in parsed_dict: args['mashupVersion'] = parsed_dict['mashupVersion'][0] elif 'mashup' in parsed_dict: args['mashup'] = parsed_dict['mashup'][0] if 'workflow_exec' in parsed_dict: args['workflow_exec'] = parsed_dict['workflow_exec'][0] return args @staticmethod def generate_args(args): generate_dict = {} if 'obj_type' in args and args['obj_type']: generate_dict['type'] = args['obj_type'] if 'obj_id' in args and args['obj_id']: generate_dict['id'] = args['obj_id'] if 'version_node' in args and args['version_node']: generate_dict['workflow'] = args['version_node'] elif 'version_tag' in args and args['version_tag']: generate_dict['workflow'] = args['version_tag'] if 'parameterExploration' in args and args['parameterExploration']: generate_dict['parameterExploration'] = args['parameterExploration'] if 'mashuptrail' in args and args['mashuptrail']: generate_dict['mashuptrail'] = args['mashuptrail'] if 'mashupVersion' in args and args['mashupVersion']: generate_dict['mashupVersion'] = args['mashupVersion'] elif 'mashup' in args and args['mashup']: generate_dict['mashup'] = args['mashup'] if 'workflow_exec' in args and args['workflow_exec']: generate_dict['workflow_exec'] = args['workflow_exec'] return urllib.urlencode(generate_dict) def _get_name(self): return None # Returns a name that will be displayed for the object name = property(_get_name) def _get_short_filename(self): """ Returns a short name that can be used to derive other filenames """ return None short_filename = property(_get_short_filename) def _get_short_name(self): """ Returns a short name that can be used for display """ return None short_name = property(_get_short_name) ########################################################################### # Operators def __eq__(self, other): pass # Implement equality def __ne__(self, other): pass # Implement nonequality def __hash__(self): return hash(self.name) def is_untitled(self): return False class SaveTemporariesMixin(object): """A mixin class that saves temporary copies of a file. It requires self.name to exist for proper functioning. """ @staticmethod def get_autosave_dir(): dot_vistrails = vistrails.core.system.current_dot_vistrails() auto_save_dir = os.path.join(dot_vistrails, "autosave") if not os.path.exists(auto_save_dir): # !!! we assume dot_vistrails exists !!! os.mkdir(auto_save_dir) if not os.path.isdir(auto_save_dir): raise VistrailsDBException('Auto-save path "%s" is not a ' 'directory' % auto_save_dir) return auto_save_dir def get_temp_basename(self): return self.name def get_temporary(self): temp_fname = self.encode_name(self.get_temp_basename()) if os.path.isfile(temp_fname): return temp_fname return None def save_temporary(self, obj): """ Writes a backup file to disk """ temp_fname = self.encode_name(self.get_temp_basename()) new_temp_fname = temp_fname + '.tmp' # Write a temporary backup before deleting the old one io.save_to_xml(obj, new_temp_fname) if os.path.isfile(temp_fname): os.unlink(temp_fname) os.rename(new_temp_fname, temp_fname) def clean_temporaries(self): """_remove_temporaries() -> None Erases all temporary files. """ temp_fname = self.encode_name(self.get_temp_basename()) if os.path.isfile(temp_fname): os.unlink(temp_fname) if os.path.isfile(temp_fname + '.tmp'): os.unlink(temp_fname + '.tmp') def encode_name(self, filename): """encode_name(filename) -> str Encodes a file path using urllib.quoteplus """ name = urllib.quote_plus(filename) + '_tmp' return os.path.join(self.get_autosave_dir(), name) class UntitledLocator(SaveTemporariesMixin, BaseLocator): UNTITLED_NAME = "Untitled" UNTITLED_PREFIX = UNTITLED_NAME + "_" def __init__(self, my_uuid=None, **kwargs): if my_uuid is not None: self._uuid = my_uuid else: self._uuid = uuid.uuid4() self._vnode = kwargs.get('version_node', None) self._vtag = kwargs.get('version_tag', '') self._mshptrail = kwargs.get('mashuptrail', None) if 'mashupVersion' in kwargs: self._mshpversion = kwargs.get('mashupVersion', None) else: self._mshpversion = kwargs.get('mashup', None) self._parameterexploration = kwargs.get('parameterExploration', None) self.kwargs = kwargs def load(self, type): fname = self.get_temporary() if fname: obj = io.open_from_xml(fname, type) else: obj = DBVistrail() obj.locator = self return obj def is_valid(self): return False def get_temp_basename(self): return UntitledLocator.UNTITLED_PREFIX + self._uuid.hex def _get_name(self): return UntitledLocator.UNTITLED_NAME name = property(_get_name) def _get_short_filename(self): return self._get_name() short_filename = property(_get_short_filename) def _get_short_name(self): return self._get_name().decode('ascii') short_name = property(_get_short_name) @staticmethod def from_url(url): if not url.startswith('untitled:'): raise VistrailsDBException("URL does not start with untitled:") rest = url[9:] my_uuid = None
<filename>qa/common/gen_qa_models.py # Copyright 2018-2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import argparse from builtins import range import os import numpy as np import gen_ensemble_model_utils as emu FLAGS = None np_dtype_string = np.dtype(object) def np_to_model_dtype(np_dtype): if np_dtype == bool: return "TYPE_BOOL" elif np_dtype == np.int8: return "TYPE_INT8" elif np_dtype == np.int16: return "TYPE_INT16" elif np_dtype == np.int32: return "TYPE_INT32" elif np_dtype == np.int64: return "TYPE_INT64" elif np_dtype == np.uint8: return "TYPE_UINT8" elif np_dtype == np.uint16: return "TYPE_UINT16" elif np_dtype == np.float16: return "TYPE_FP16" elif np_dtype == np.float32: return "TYPE_FP32" elif np_dtype == np.float64: return "TYPE_FP64" elif np_dtype == np_dtype_string: return "TYPE_STRING" return None def np_to_tf_dtype(np_dtype): if np_dtype == bool: return tf.bool elif np_dtype == np.int8: return tf.int8 elif np_dtype == np.int16: return tf.int16 elif np_dtype == np.int32: return tf.int32 elif np_dtype == np.int64: return tf.int64 elif np_dtype == np.uint8: return tf.uint8 elif np_dtype == np.uint16: return tf.uint16 elif np_dtype == np.float16: return tf.float16 elif np_dtype == np.float32: return tf.float32 elif np_dtype == np.float64: return tf.float64 elif np_dtype == np_dtype_string: return tf.string return None def np_to_trt_dtype(np_dtype): if np_dtype == bool: return trt.bool elif np_dtype == np.int8: return trt.int8 elif np_dtype == np.int32: return trt.int32 elif np_dtype == np.float16: return trt.float16 elif np_dtype == np.float32: return trt.float32 return None def np_to_onnx_dtype(np_dtype): if np_dtype == bool: return onnx.TensorProto.BOOL elif np_dtype == np.int8: return onnx.TensorProto.INT8 elif np_dtype == np.int16: return onnx.TensorProto.INT16 elif np_dtype == np.int32: return onnx.TensorProto.INT32 elif np_dtype == np.int64: return onnx.TensorProto.INT64 elif np_dtype == np.uint8: return onnx.TensorProto.UINT8 elif np_dtype == np.uint16: return onnx.TensorProto.UINT16 elif np_dtype == np.float16: return onnx.TensorProto.FLOAT16 elif np_dtype == np.float32: return onnx.TensorProto.FLOAT elif np_dtype == np.float64: return onnx.TensorProto.DOUBLE elif np_dtype == np_dtype_string: return onnx.TensorProto.STRING return None def np_to_torch_dtype(np_dtype): if np_dtype == bool: return torch.bool elif np_dtype == np.int8: return torch.int8 elif np_dtype == np.int16: return torch.int16 elif np_dtype == np.int32: return torch.int elif np_dtype == np.int64: return torch.long elif np_dtype == np.uint8: return torch.uint8 elif np_dtype == np.uint16: return None # Not supported in Torch elif np_dtype == np.float16: return None elif np_dtype == np.float32: return torch.float elif np_dtype == np.float64: return torch.double elif np_dtype == np_dtype_string: return None # Not supported in Torch def create_graphdef_modelfile(models_dir, max_batch, model_version, input_shape, output0_shape, output1_shape, input_dtype, output0_dtype, output1_dtype, swap=False): if not tu.validate_for_tf_model(input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape): return tf_input_dtype = np_to_tf_dtype(input_dtype) tf_output0_dtype = np_to_tf_dtype(output0_dtype) tf_output1_dtype = np_to_tf_dtype(output1_dtype) # Create the model. If non-batching then don't include the batch # dimension. tf.reset_default_graph() if max_batch == 0: in0 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape), "INPUT0") in1 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape), "INPUT1") else: in0 = tf.placeholder(tf_input_dtype, [ None, ] + tu.shape_to_tf_shape(input_shape), "INPUT0") in1 = tf.placeholder(tf_input_dtype, [ None, ] + tu.shape_to_tf_shape(input_shape), "INPUT1") # If the input is a string, then convert each string to the # equivalent int32 value. if tf_input_dtype == tf.string: in0 = tf.strings.to_number(in0, tf.int32) in1 = tf.strings.to_number(in1, tf.int32) add = tf.add(in0, in1, "ADD") sub = tf.subtract(in0, in1, "SUB") # Cast or convert result to the output dtype. if tf_output0_dtype == tf.string: cast0 = tf.dtypes.as_string(add if not swap else sub, name="TOSTR0") else: cast0 = tf.cast(add if not swap else sub, tf_output0_dtype, "CAST0") if tf_output1_dtype == tf.string: cast1 = tf.dtypes.as_string(sub if not swap else add, name="TOSTR1") else: cast1 = tf.cast(sub if not swap else add, tf_output1_dtype, "CAST1") out0 = tf.identity(cast0, "OUTPUT0") out1 = tf.identity(cast1, "OUTPUT1") # Use a different model name for the non-batching variant model_name = tu.get_model_name( "graphdef_nobatch" if max_batch == 0 else "graphdef", input_dtype, output0_dtype, output1_dtype) model_version_dir = models_dir + "/" + model_name + "/" + str(model_version) try: os.makedirs(model_version_dir) except OSError as ex: pass # ignore existing dir with tf.Session() as sess: graph_io.write_graph(sess.graph.as_graph_def(), model_version_dir, "model.graphdef", as_text=False) def create_graphdef_modelconfig(models_dir, max_batch, model_version, input_shape, output0_shape, output1_shape, input_dtype, output0_dtype, output1_dtype, output0_label_cnt, version_policy): if not tu.validate_for_tf_model(input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape): return # Unpack version policy version_policy_str = "{ latest { num_versions: 1 }}" if version_policy is not None: type, val = version_policy if type == 'latest': version_policy_str = "{{ latest {{ num_versions: {} }}}}".format( val) elif type == 'specific': version_policy_str = "{{ specific {{ versions: {} }}}}".format(val) else: version_policy_str = "{ all { }}" # Use a different model name for the non-batching variant model_name = tu.get_model_name( "graphdef_nobatch" if max_batch == 0 else "graphdef", input_dtype, output0_dtype, output1_dtype) config_dir = models_dir + "/" + model_name config = ''' name: "{}" platform: "tensorflow_graphdef" max_batch_size: {} version_policy: {} input [ {{ name: "INPUT0" data_type: {} dims: [ {} ] }}, {{ name: "INPUT1" data_type: {} dims: [ {} ] }} ] output [ {{ name: "OUTPUT0" data_type: {} dims: [ {} ] label_filename: "output0_labels.txt" }}, {{ name: "OUTPUT1" data_type: {} dims: [ {} ] }} ] '''.format(model_name, max_batch, version_policy_str, np_to_model_dtype(input_dtype), tu.shape_to_dims_str(input_shape), np_to_model_dtype(input_dtype), tu.shape_to_dims_str(input_shape), np_to_model_dtype(output0_dtype), tu.shape_to_dims_str(output0_shape), np_to_model_dtype(output1_dtype), tu.shape_to_dims_str(output1_shape)) try: os.makedirs(config_dir) except OSError as ex: pass # ignore existing dir with open(config_dir + "/config.pbtxt", "w") as cfile: cfile.write(config) with open(config_dir + "/output0_labels.txt", "w") as lfile: for l in range(output0_label_cnt): lfile.write("label" + str(l) + "\n") def create_savedmodel_modelfile(models_dir, max_batch, model_version, input_shape, output0_shape, output1_shape, input_dtype, output0_dtype, output1_dtype, swap=False): if not tu.validate_for_tf_model(input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape): return tf_input_dtype = np_to_tf_dtype(input_dtype) tf_output0_dtype = np_to_tf_dtype(output0_dtype) tf_output1_dtype = np_to_tf_dtype(output1_dtype) # Create the model. If non-batching then don't include the batch # dimension. tf.reset_default_graph() if max_batch == 0: in0 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape), "TENSOR_INPUT0") in1 = tf.placeholder(tf_input_dtype, tu.shape_to_tf_shape(input_shape), "TENSOR_INPUT1") else: in0 = tf.placeholder(tf_input_dtype, [ None, ] + tu.shape_to_tf_shape(input_shape), "TENSOR_INPUT0") in1 = tf.placeholder(tf_input_dtype, [ None, ] + tu.shape_to_tf_shape(input_shape), "TENSOR_INPUT1") # If the input is a string, then convert each string to the # equivalent float value. if tf_input_dtype == tf.string: in0 = tf.strings.to_number(in0, tf.int32) in1 = tf.strings.to_number(in1, tf.int32) add = tf.add(in0, in1, "ADD") sub = tf.subtract(in0, in1, "SUB") # Cast or convert result to the output dtype. if tf_output0_dtype == tf.string: cast0 = tf.dtypes.as_string(add if not swap else sub, name="TOSTR0") else: cast0 = tf.cast(add if not swap else sub, tf_output0_dtype, "CAST0") if tf_output1_dtype == tf.string: cast1 = tf.dtypes.as_string(sub if not swap else add, name="TOSTR1") else: cast1 = tf.cast(sub if not swap else add, tf_output1_dtype, "CAST1") out0 = tf.identity(cast0, "TENSOR_OUTPUT0") out1 = tf.identity(cast1, "TENSOR_OUTPUT1") # Use a different model name for the non-batching variant model_name = tu.get_model_name( "savedmodel_nobatch" if max_batch == 0 else "savedmodel", input_dtype, output0_dtype, output1_dtype) model_version_dir = models_dir + "/" + model_name + "/" + str(model_version) try: os.makedirs(model_version_dir) except OSError as ex: pass # ignore existing dir with tf.Session() as sess: input0_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_INPUT0:0") input1_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_INPUT1:0") output0_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_OUTPUT0:0") output1_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_OUTPUT1:0") tf.saved_model.simple_save(sess, model_version_dir + "/model.savedmodel", inputs={ "INPUT0": input0_tensor, "INPUT1": input1_tensor }, outputs={ "OUTPUT0": output0_tensor, "OUTPUT1": output1_tensor }) def create_savedmodel_modelconfig(models_dir, max_batch, model_version, input_shape, output0_shape, output1_shape, input_dtype, output0_dtype, output1_dtype, output0_label_cnt, version_policy): if not tu.validate_for_tf_model(input_dtype, output0_dtype, output1_dtype, input_shape, output0_shape, output1_shape): return # Unpack version policy version_policy_str = "{ latest { num_versions: 1 }}" if version_policy
writeFile.write(" # Get back to \"Home\" folder\n") writeFile.write(" cd.go(\"~\")\n") writeFile.write(" # Reset the lastdir variable\n") writeFile.write(" systemvariables.lastdir = \"\"\n\n") writeFile.write(" # Do this until told to exit\n") writeFile.write(" while(zzz == 1):\n") writeFile.write(" # Change display depending on where the user is in the file system\n") writeFile.write(" if(os.getcwd() == systemvariables.ROOT):\n") writeFile.write(" display = \"/\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.HOME):\n") writeFile.write(" display = \"~\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.USRDOCS):\n") writeFile.write(" display = \"~/Documents\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.settingspath):\n") writeFile.write(" display = \"/Bash/Bash\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.loginfopath):\n") writeFile.write(" display = \"/Bash/Bash/Settings\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.srcpath):\n") writeFile.write(" display = \"/Bash/Bash/Source\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.usrpath):\n") writeFile.write(" display = \"/Bash/Users\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.exepath):\n") writeFile.write(" display = \"/Bash/Bash/Source/Include\"\n") writeFile.write(" elif(os.getcwd() == systemvariables.bshpath):\n") writeFile.write(" display = \"/Bash\"\n") writeFile.write(" else:\n") writeFile.write(" display = os.getcwd()\n\n") writeFile.write(" # Prompt\n") writeFile.write(" command = input(usr + \"@\" + socket.gethostname() + \":\" + display + \" $ \")\n\n") writeFile.write(" # Find a space. If one is found, put it in another variable.\n") writeFile.write(" args = command.find(\" \", 0, len(command))\n") writeFile.write(" argsArr = ['']\n\n") writeFile.write(" # Counters\n") writeFile.write(" i = 0\n") writeFile.write(" j = 0\n") writeFile.write(" k = 0\n\n") writeFile.write(" # Only do it if there is indeed a space\n") writeFile.write(" if(args != -1):\n") writeFile.write(" for i in command:\n") writeFile.write(" # Only do this after a space\n") writeFile.write(" if(j > args):\n") writeFile.write(" # If we come across a space, add an item to the array of arguments and skip the rest\n") writeFile.write(" if(i == \" \"):\n") writeFile.write(" k += 1\n") writeFile.write(" argsArr.append(\"\")\n") writeFile.write(" continue\n\n") writeFile.write(" # Take the current item in the args array and put in each character of the input\n") writeFile.write(" # string, then delete that same character from the input string\n") writeFile.write(" argsArr[k] = argsArr[k] + i\n") writeFile.write(" command = command[0 : j : ]\n") writeFile.write(" else:\n") writeFile.write(" j += 1\n") writeFile.write(" # Reset the counters\n") writeFile.write(" i = 0\n") writeFile.write(" j = 0\n") writeFile.write(" k = 0\n\n") writeFile.write(" # If we have at least 1 space, make sure you take out the last character\n") writeFile.write(" # in the command variable that happens to be a space\n") writeFile.write(" if(args != -1):\n") writeFile.write(" command = command[:-1:]\n\n") writeFile.write(" # Run the command. If it dosen't exist, display a message\n") writeFile.write(" if(command == \"exit\"):\n") writeFile.write(" zzz = 0\n") writeFile.write(" elif(command == \"ls\"):\n") writeFile.write(" ls.show(argsArr)\n") writeFile.write(" elif(command == \"cd\"):\n") writeFile.write(" cd.go(argsArr)\n") writeFile.write(" elif(command == \"pwd\"):\n") writeFile.write(" out = os.getcwd()\n") writeFile.write(" flag = 0\n") writeFile.write(" if(\">>\" in argsArr):\n") writeFile.write(" flag = 1\n") writeFile.write(" tofile.write(\">>\", out, argsArr[1])\n") writeFile.write(" elif(\">\" in argsArr):\n") writeFile.write(" if(flag == 0):\n") writeFile.write(" tofile.write(\">\", out, argsArr[1])\n") writeFile.write(" else:\n") writeFile.write(" print(out)\n") writeFile.write(" elif(command == \"cat\"):\n") writeFile.write(" cat.show(argsArr)\n") writeFile.write(" elif(command == \"nano\"):\n") writeFile.write(" file = argsArr\n") writeFile.write(" nano.write(file) \n") writeFile.write(" elif(command == \"vi\"):\n") writeFile.write(" file = argsArr\n") writeFile.write(" nano.write(file) \n") writeFile.write(" elif(command == \"vim\"):\n") writeFile.write(" file = argsArr\n") writeFile.write(" nano.write(file) \n") writeFile.write(" elif(command == \"emacs\"):\n") writeFile.write(" file = argsArr\n") writeFile.write(" nano.write(file) \n") writeFile.write(" elif(command == \"clear\"):\n") writeFile.write(" os.system(\"cls\")\n") writeFile.write(" elif(command == \"lsvar\"):\n") writeFile.write(" ls.vars(argsArr)\n") writeFile.write(" elif(command == \"echo\"):\n") writeFile.write(" echo.reg(argsArr)\n") writeFile.write(" elif(command == \"touch\"):\n") writeFile.write(" touch.write(argsArr)\n") writeFile.write(" elif(command == \"rm\"):\n") writeFile.write(" rm.remove(argsArr)\n") writeFile.write(" elif(command == \"mv\"):\n") writeFile.write(" file = argsArr[0]\n") writeFile.write(" dstfile = argsArr[1]\n") writeFile.write(" mv.move(file, dstfile)\n") writeFile.write(" elif(command == \"cp\"):\n") writeFile.write(" file = argsArr[0]\n") writeFile.write(" newfile = argsArr[1]\n") writeFile.write(" cp.copy(file, newfile)\n") writeFile.write(" elif(command == \"pushd\"):\n") writeFile.write(" path = argsArr\n") writeFile.write(" pushd.go(path)\n") writeFile.write(" elif(command == \"popd\"):\n") writeFile.write(" popd.go()\n") writeFile.write(" elif(command == \"uname\"):\n") writeFile.write(" if(argsArr[0] == \"-g\"):\n") writeFile.write(" print(\"Bash for Windows: The Bourne Again Shell! Version 1.2.1.1\")\n") writeFile.write(" print(\"Taking you to the GitHub page...\")\n") writeFile.write(" os.system(\"iexplore https://github.com/JR-Tech-and-Software/Bash-for-Windows\")\n") writeFile.write(" else:\n") writeFile.write(" print(\"Bash for Windows: The Bourne Again Shell! Version 1.2.1.1\")\n") writeFile.write(" print(\"\\nAll the code is avalible at GitHub! Check it out! Use the -g argument\")\n") writeFile.write(" print(\"to be taken to the page!\\n\\nBash for Windows is under the MIT License.\")\n") writeFile.write(" print(\"Check it out on GitHub as well.\")\n") writeFile.write(" elif(command == \"mkdir\"):\n") writeFile.write(" mkdir.create(argsArr)\n") writeFile.write(" else:\n") writeFile.write(" if(command == \"\"):\n") writeFile.write(" sleep(0)\n") writeFile.write(" else:\n") writeFile.write(" if(os.path.exists(os.getcwd() + \"/\" + command) == True):\n") writeFile.write(" typee = argsArr[0]\n") writeFile.write(" if(typee == \"exe\"):\n") writeFile.write(" os.system(command)\n") writeFile.write(" elif(typee == \"py\"):\n") writeFile.write(" os.system(\"py \" + command)\n") writeFile.write(" else:\n") writeFile.write(" print(command + \": command not found\")\n") writeFile.write(" exit()\n\n") writeFile.write("# More checking for other scripts to use\n") writeFile.write("def usrcheck():\n") writeFile.write(" incorrect = True\n") writeFile.write(" while(incorrect == True):\n") writeFile.write(" user = open(\"Settings/ivhzadgz.bws\", \"r\")\n") writeFile.write(" userguess = input(\"Type a user name # \")\n") writeFile.write(" if(userguess == user.read()):\n") writeFile.write(" incorrect = False\n") writeFile.write(" else:\n") writeFile.write(" print(\"Incorrect Username.\")\n") writeFile.write(" user.close()\n") writeFile.write("def passcheck():\n") writeFile.write(" incorrect = True\n") writeFile.write(" while(incorrect == True):\n") writeFile.write(" password = open(\"Settings/kvnnadgz.bws\", \"r\")\n") writeFile.write(" passguess = input(\"password # \")\n") writeFile.write(" if(passguess == password.read()):\n") writeFile.write(" incorrect = False\n") writeFile.write(" else:\n") writeFile.write(" print(\"Incorrect Password.\")\n") writeFile.write(" password.close()\n") writeFile.write("# If the end user tries to run bash.py without Startup.py, then display this message\n") writeFile.write("print(\"This file isn't ment to be run by itself. To run Bash for Windows,\")\n") writeFile.write("print(\"run the Startup program.\")\n") writeFile.close() writeFile = open("cat.py", "w") writeFile.write("'''\n") writeFile.write("This file is under the MIT License.\n\n") writeFile.write("Copyright 2019-2020 <NAME>\n\n") writeFile.write("Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files \n") writeFile.write("(the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, \n") writeFile.write("publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, \n") writeFile.write("subject to the following conditions:\n\n") writeFile.write("The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n") writeFile.write("THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \n") writeFile.write("MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE \n") writeFile.write("FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION \n") writeFile.write("WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n") writeFile.write("'''\n") writeFile.write("# Cat is a basic script to show the contents of a file\n\n") writeFile.write("# Libraries\n") writeFile.write("import os, touch, rm, tofile\n\n") writeFile.write("# Main Function. First check if the file exists\n") writeFile.write("def show(args):\n") writeFile.write(" file = args[0]\n") writeFile.write(" output = \"\"\n") writeFile.write(" firstLetter = \"\"\n") writeFile.write(" flag = 0\n\n") writeFile.write(" # Make sure the requested file exists and is indeed a file and not a folder.\n") writeFile.write(" if(os.path.exists(file) == False):\n") writeFile.write(" print(\"cat: \" + file + \" file not found\")\n") writeFile.write(" elif(os.path.isdir(file) == True):\n") writeFile.write(" print(\"cat: \" + file + \": Is a directory\")\n") writeFile.write(" else:\n") writeFile.write(" show = open(file)\n") writeFile.write(" output = show.read()\n") writeFile.write(" show.close()\n") writeFile.write(" # If told to do so, either append or overwrite a file where we send all output to\n") writeFile.write(" if(\">>\" in args):\n") writeFile.write(" i = 0\n") writeFile.write(" index = 0\n") writeFile.write(" flag = 1\n") writeFile.write(" for j in args:\n") writeFile.write(" if(i == 0):\n") writeFile.write(" i += 1\n") writeFile.write(" continue\n") writeFile.write(" if(args[i] == \">>\"):\n") writeFile.write(" index = i + 1\n") writeFile.write(" break\n") writeFile.write(" i += 1\n") writeFile.write(" tofile.write(\">>\", output, args[index])\n") writeFile.write(" elif(\">\" in args):\n") writeFile.write(" if(flag == 0):\n") writeFile.write(" i = 0\n") writeFile.write(" index = 0\n") writeFile.write(" for j in args:\n") writeFile.write(" if(i == 0):\n") writeFile.write(" i += 1\n") writeFile.write(" continue\n") writeFile.write(" if(args[i] == \">\"):\n") writeFile.write(" index = i + 1\n") writeFile.write(" break\n") writeFile.write(" i += 1\n") writeFile.write(" tofile.write(\">\", output, args[index])\n") writeFile.write(" # If not told to send output to a file, print to screen.\n") writeFile.write(" else:\n") writeFile.write(" print(output)\n") writeFile.close() writeFile = open("cd.py", "w") writeFile.write("'''\n") writeFile.write("This file is under the MIT License.\n\n") writeFile.write("Copyright 2019-2020 <NAME>\n\n") writeFile.write("Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files \n") writeFile.write("(the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
'body') if self.body: self.body.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = ListSubSpaceResponseBody() self.body = temp_model.from_map(m['body']) return self class UpdateResideceGroupHeaders(TeaModel): def __init__( self, common_headers: Dict[str, str] = None, x_acs_dingtalk_access_token: str = None, ): self.common_headers = common_headers self.x_acs_dingtalk_access_token = x_acs_dingtalk_access_token def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.common_headers is not None: result['commonHeaders'] = self.common_headers if self.x_acs_dingtalk_access_token is not None: result['x-acs-dingtalk-access-token'] = self.x_acs_dingtalk_access_token return result def from_map(self, m: dict = None): m = m or dict() if m.get('commonHeaders') is not None: self.common_headers = m.get('commonHeaders') if m.get('x-acs-dingtalk-access-token') is not None: self.x_acs_dingtalk_access_token = m.get('x-acs-dingtalk-access-token') return self class UpdateResideceGroupRequest(TeaModel): def __init__( self, manager_user_id: str = None, department_name: str = None, department_id: int = None, ): # 组长userid self.manager_user_id = manager_user_id # 组名字 self.department_name = department_name # 组id self.department_id = department_id def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.manager_user_id is not None: result['managerUserId'] = self.manager_user_id if self.department_name is not None: result['departmentName'] = self.department_name if self.department_id is not None: result['departmentId'] = self.department_id return result def from_map(self, m: dict = None): m = m or dict() if m.get('managerUserId') is not None: self.manager_user_id = m.get('managerUserId') if m.get('departmentName') is not None: self.department_name = m.get('departmentName') if m.get('departmentId') is not None: self.department_id = m.get('departmentId') return self class UpdateResideceGroupResponseBody(TeaModel): def __init__( self, result: bool = None, ): # 是否更新成功 self.result = result def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.result is not None: result['result'] = self.result return result def from_map(self, m: dict = None): m = m or dict() if m.get('result') is not None: self.result = m.get('result') return self class UpdateResideceGroupResponse(TeaModel): def __init__( self, headers: Dict[str, str] = None, body: UpdateResideceGroupResponseBody = None, ): self.headers = headers self.body = body def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = UpdateResideceGroupResponseBody() self.body = temp_model.from_map(m['body']) return self class GetResidentInfoHeaders(TeaModel): def __init__( self, common_headers: Dict[str, str] = None, x_acs_dingtalk_access_token: str = None, ): self.common_headers = common_headers self.x_acs_dingtalk_access_token = x_acs_dingtalk_access_token def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.common_headers is not None: result['commonHeaders'] = self.common_headers if self.x_acs_dingtalk_access_token is not None: result['x-acs-dingtalk-access-token'] = self.x_acs_dingtalk_access_token return result def from_map(self, m: dict = None): m = m or dict() if m.get('commonHeaders') is not None: self.common_headers = m.get('commonHeaders') if m.get('x-acs-dingtalk-access-token') is not None: self.x_acs_dingtalk_access_token = m.get('x-acs-dingtalk-access-token') return self class GetResidentInfoRequest(TeaModel): def __init__( self, resident_corp_id: str = None, ): self.resident_corp_id = resident_corp_id def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.resident_corp_id is not None: result['residentCorpId'] = self.resident_corp_id return result def from_map(self, m: dict = None): m = m or dict() if m.get('residentCorpId') is not None: self.resident_corp_id = m.get('residentCorpId') return self class GetResidentInfoResponseBodyProjectManager(TeaModel): def __init__( self, user_id: str = None, user_name: str = None, avatar: str = None, ): # 人员唯一标识 self.user_id = user_id # 姓名 self.user_name = user_name # 头像 self.avatar = avatar def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.user_id is not None: result['userId'] = self.user_id if self.user_name is not None: result['userName'] = self.user_name if self.avatar is not None: result['avatar'] = self.avatar return result def from_map(self, m: dict = None): m = m or dict() if m.get('userId') is not None: self.user_id = m.get('userId') if m.get('userName') is not None: self.user_name = m.get('userName') if m.get('avatar') is not None: self.avatar = m.get('avatar') return self class GetResidentInfoResponseBody(TeaModel): def __init__( self, type: int = None, location: str = None, address: str = None, prov_id: int = None, building_area: float = None, name: str = None, telephone: str = None, delivery_time: int = None, contact_mode: int = None, scope_east: str = None, scope_west: str = None, scope_south: str = None, scope_north: str = None, city_id: int = None, county_id: int = None, town_id: int = None, project_manager: GetResidentInfoResponseBodyProjectManager = None, ): # 1纯住宅;2:商住混合;3:办公;4:办公商业混合;5:商业;6:公共场所;7:其他 self.type = type # 经纬度,格式:经度,纬度 self.location = location # 小区地址 self.address = address # 小区归属的省的id self.prov_id = prov_id self.building_area = building_area # 小区名称 self.name = name # 物业电话 self.telephone = telephone # 交付时间 self.delivery_time = delivery_time # 通信录模式:0标准/1自定义 self.contact_mode = contact_mode # 物业管理范围-东 self.scope_east = scope_east # 物业管理范围-西 self.scope_west = scope_west # 物业管理范围-南 self.scope_south = scope_south # 物业管理范围-北 self.scope_north = scope_north # 小区归属的市的id self.city_id = city_id # 小区归属的区/县的id self.county_id = county_id # 小区归属的街道/镇的id self.town_id = town_id self.project_manager = project_manager def validate(self): if self.project_manager: self.project_manager.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.type is not None: result['type'] = self.type if self.location is not None: result['location'] = self.location if self.address is not None: result['address'] = self.address if self.prov_id is not None: result['provId'] = self.prov_id if self.building_area is not None: result['buildingArea'] = self.building_area if self.name is not None: result['name'] = self.name if self.telephone is not None: result['telephone'] = self.telephone if self.delivery_time is not None: result['deliveryTime'] = self.delivery_time if self.contact_mode is not None: result['contactMode'] = self.contact_mode if self.scope_east is not None: result['scopeEast'] = self.scope_east if self.scope_west is not None: result['scopeWest'] = self.scope_west if self.scope_south is not None: result['scopeSouth'] = self.scope_south if self.scope_north is not None: result['scopeNorth'] = self.scope_north if self.city_id is not None: result['cityId'] = self.city_id if self.county_id is not None: result['countyId'] = self.county_id if self.town_id is not None: result['townId'] = self.town_id if self.project_manager is not None: result['projectManager'] = self.project_manager.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('type') is not None: self.type = m.get('type') if m.get('location') is not None: self.location = m.get('location') if m.get('address') is not None: self.address = m.get('address') if m.get('provId') is not None: self.prov_id = m.get('provId') if m.get('buildingArea') is not None: self.building_area = m.get('buildingArea') if m.get('name') is not None: self.name = m.get('name') if m.get('telephone') is not None: self.telephone = m.get('telephone') if m.get('deliveryTime') is not None: self.delivery_time = m.get('deliveryTime') if m.get('contactMode') is not None: self.contact_mode = m.get('contactMode') if m.get('scopeEast') is not None: self.scope_east = m.get('scopeEast') if m.get('scopeWest') is not None: self.scope_west = m.get('scopeWest') if m.get('scopeSouth') is not None: self.scope_south = m.get('scopeSouth') if m.get('scopeNorth') is not None: self.scope_north = m.get('scopeNorth') if m.get('cityId') is not None: self.city_id = m.get('cityId') if m.get('countyId') is not None: self.county_id = m.get('countyId') if m.get('townId') is not None: self.town_id = m.get('townId') if m.get('projectManager') is not None: temp_model = GetResidentInfoResponseBodyProjectManager() self.project_manager = temp_model.from_map(m['projectManager']) return self class GetResidentInfoResponse(TeaModel): def __init__( self, headers: Dict[str, str] = None, body: GetResidentInfoResponseBody = None, ): self.headers = headers self.body = body def validate(self): self.validate_required(self.headers, 'headers') self.validate_required(self.body, 'body') if self.body: self.body.validate() def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if self.headers is not None: result['headers'] = self.headers if self.body is not None: result['body'] = self.body.to_map() return result def from_map(self, m: dict = None): m = m or dict() if m.get('headers') is not None: self.headers = m.get('headers') if m.get('body') is not None: temp_model = GetResidentInfoResponseBody() self.body = temp_model.from_map(m['body']) return self class SearchResidentHeaders(TeaModel): def __init__( self, common_headers: Dict[str, str] = None, x_acs_dingtalk_access_token: str = None, ): self.common_headers = common_headers self.x_acs_dingtalk_access_token = x_acs_dingtalk_access_token def validate(self): pass def to_map(self): _map = super().to_map() if _map is not None: return _map result = dict() if
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. from argparse import RawTextHelpFormatter from jdcloud_cli.cement.ext.ext_argparse import expose from jdcloud_cli.controllers.base_controller import BaseController from jdcloud_cli.client_factory import ClientFactory from jdcloud_cli.parameter_builder import collect_user_args, collect_user_headers from jdcloud_cli.printer import Printer from jdcloud_cli.skeleton import Skeleton class VqdController(BaseController): class Meta: label = 'vqd' help = 'Video Quality Detection' description = ''' vqd cli 子命令,视频质量检测相关接口。 OpenAPI文档地址为:https://docs.jdcloud.com/cn/xxx/api/overview ''' stacked_on = 'base' stacked_type = 'nested' @expose( arguments=[ (['--callback-type'], dict(help="""(string) 回调方式,目前只支持 http """, dest='callbackType', required=True)), (['--http-url'], dict(help="""(string) HTTP方式的该字段为必选项 """, dest='httpUrl', required=False)), (['--callback-events'], dict(help="""(array: string) 回调事件列表。; - VqdSuccess 视频质检成功; - VqdFailure 视频质检失败; - VqdStart 视频质检开始; """, dest='callbackEvents', required=False)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 设置回调配置 ''', description=''' 设置回调配置。 示例: jdc vqd set-callback --callback-type xxx ''', ) def set_callback(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.SetCallbackRequest import SetCallbackRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = SetCallbackRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 查询回调配置 ''', description=''' 查询回调配置。 示例: jdc vqd query-callback ''', ) def query_callback(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.QueryCallbackRequest import QueryCallbackRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = QueryCallbackRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--media'], dict(help="""(vqdMediaObject) NA """, dest='media', required=True)), (['--template-id'], dict(help="""(string) 检测模板ID """, dest='templateId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 提交视频质检任务 ''', description=''' 提交视频质检任务。 示例: jdc vqd submit-vqd-task --media '{"":""}' --template-id xxx ''', ) def submit_vqd_task(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.SubmitVqdTaskRequest import SubmitVqdTaskRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = SubmitVqdTaskRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--media-list'], dict(help="""(array: vqdMediaObject) 媒体列表 """, dest='mediaList', required=True)), (['--template-id'], dict(help="""(string) 检测模板ID """, dest='templateId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 批量提交视频质检任务,一次同时最多提交50个输入媒体 ''', description=''' 批量提交视频质检任务,一次同时最多提交50个输入媒体。 示例: jdc vqd batch-submit-vqd-tasks --media-list ['{"":""}'] --template-id xxx ''', ) def batch_submit_vqd_tasks(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.BatchSubmitVqdTasksRequest import BatchSubmitVqdTasksRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = BatchSubmitVqdTasksRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--page-number'], dict(help="""(int) 页码;默认值为 1 """, dest='pageNumber', type=int, required=False)), (['--page-size'], dict(help="""(int) 分页大小;默认值为 10;取值范围 [10, 100] """, dest='pageSize', type=int, required=False)), (['--filters'], dict(help="""(array: filter) NA """, dest='filters', required=False)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"<PASSWORD>"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 查询视频质检任务列表; 支持过滤查询:; - createTime,ge 最早任务创建时间; - createTime,le 最晚任务创建时间; - status,in 任务状态; ''', description=''' 查询视频质检任务列表; 支持过滤查询:; - createTime,ge 最早任务创建时间; - createTime,le 最晚任务创建时间; - status,in 任务状态; 。 示例: jdc vqd list-vqd-tasks ''', ) def list_vqd_tasks(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.ListVqdTasksRequest import ListVqdTasksRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = ListVqdTasksRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--task-id'], dict(help="""(string) 任务ID,路径参数 """, dest='taskId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 获取视频质检任务详细信息 ''', description=''' 获取视频质检任务详细信息。 示例: jdc vqd get-vqd-task --task-id xxx ''', ) def get_vqd_task(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.GetVqdTaskRequest import GetVqdTaskRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = GetVqdTaskRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--task-id'], dict(help="""(string) 任务ID,路径参数 """, dest='taskId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 删除视频质检任务。删除任务时,会同时删除任务相关的数据,如任务执行结果等 ''', description=''' 删除视频质检任务。删除任务时,会同时删除任务相关的数据,如任务执行结果等。 示例: jdc vqd delete-vqd-task --task-id xxx ''', ) def delete_vqd_task(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.DeleteVqdTaskRequest import DeleteVqdTaskRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = DeleteVqdTaskRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--task-id'], dict(help="""(string) 任务ID,路径参数 """, dest='taskId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 查询视频质检任务结果 ''', description=''' 查询视频质检任务结果。 示例: jdc vqd query-vqd-task-result --task-id xxx ''', ) def query_vqd_task_result(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.QueryVqdTaskResultRequest import QueryVqdTaskResultRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = QueryVqdTaskResultRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--task-ids'], dict(help="""(array: string) NA """, dest='taskIds', required=False)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 批量删除视频质检任务。删除任务时,会同时删除任务相关的数据,如任务执行结果等。一次最多删除50条 ''', description=''' 批量删除视频质检任务。删除任务时,会同时删除任务相关的数据,如任务执行结果等。一次最多删除50条。 示例: jdc vqd batch-delete-vqd-tasks ''', ) def batch_delete_vqd_tasks(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.BatchDeleteVqdTasksRequest import BatchDeleteVqdTasksRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = BatchDeleteVqdTasksRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--page-number'], dict(help="""(int) 页码;默认值为 1 """, dest='pageNumber', type=int, required=False)), (['--page-size'], dict(help="""(int) 分页大小;默认值为 10;取值范围 [10, 100] """, dest='pageSize', type=int, required=False)), (['--filters'], dict(help="""(array: filter) NA """, dest='filters', required=False)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 查询视频质检模板列表。; 支持过滤查询:; - templateId,eq 精确匹配模板ID,非必选; ''', description=''' 查询视频质检模板列表。; 支持过滤查询:; - templateId,eq 精确匹配模板ID,非必选; 。 示例: jdc vqd list-vqd-templates ''', ) def list_vqd_templates(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.ListVqdTemplatesRequest import ListVqdTemplatesRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = ListVqdTemplatesRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--template-name'], dict(help="""(string) 模板名称。长度不超过128个字符。UTF-8编码。; """, dest='templateName', required=True)), (['--threshold'], dict(help="""(float) 缺陷判定时间阈值,非必须,默认值为 3.0 """, dest='threshold', required=False)), (['--detections'], dict(help="""(array: string) 检测项列表 """, dest='detections', required=False)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 创建视频质检模板 ''', description=''' 创建视频质检模板。 示例: jdc vqd create-vqd-template --template-name xxx ''', ) def create_vqd_template(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.CreateVqdTemplateRequest import CreateVqdTemplateRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = CreateVqdTemplateRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--template-id'], dict(help="""(string) 模板ID,路径参数 """, dest='templateId', required=True)), (['--input-json'], dict(help='(json) 以json字符串或文件绝对路径形式作为输入参数。\n字符串方式举例:--input-json \'{"field":"value"}\';\n文件格式举例:--input-json file:///xxxx.json', dest='input_json', required=False)), (['--headers'], dict(help="""(json) 用户自定义Header,举例:'{"x-jdcloud-security-token":"abc","test":"123"}'""", dest='headers', required=False)), ], formatter_class=RawTextHelpFormatter, help=''' 查询视频质检模板 ''', description=''' 查询视频质检模板。 示例: jdc vqd get-vqd-template --template-id xxx ''', ) def get_vqd_template(self): client_factory = ClientFactory('vqd') client = client_factory.get(self.app) if client is None: return try: from jdcloud_sdk.services.vqd.apis.GetVqdTemplateRequest import GetVqdTemplateRequest params_dict = collect_user_args(self.app) headers = collect_user_headers(self.app) req = GetVqdTemplateRequest(params_dict, headers) resp = client.send(req) Printer.print_result(resp) except ImportError: print('{"error":"This api is not supported, please use the newer version"}') except Exception as e: print(e) @expose( arguments=[ (['--template-id'], dict(help="""(string) 模板ID,路径参数 """, dest='templateId', required=True)), (['--template-name'], dict(help="""(string) 模板名称。长度不超过128个字符。UTF-8编码。; """, dest='templateName', required=False)), (['--threshold'], dict(help="""(float) 缺陷判定时间阈值
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Namespace for registering numpy_extension ops for imperative programming.""" from ..ndarray import numpy_extension as _mx_nd_npx from ..util import set_module __all__ = ['softmax', 'log_softmax', 'masked_softmax', 'masked_log_softmax', 'activation', 'batch_norm', 'fully_connected', 'pick', 'convolution', 'deconvolution'] # pylint: disable=too-many-arguments @set_module('mxnet.numpy_extension') def softmax(data, axis=-1, length=None, temperature=None, use_length=False, dtype=None): r"""Applies the softmax function. The resulting array contains elements in the range (0,1) and the elements along the given axis sum up to 1. .. math:: softmax(\mathbf{z/t})_j = \frac{e^{z_j/t}}{\sum_{k=1}^K e^{z_k/t}} for :math:`j = 1, ..., K` t is the temperature parameter in softmax function. By default, t equals 1.0 Parameters ---------- data : NDArray The input array. axis : int, optional, default='-1' The axis along which to compute softmax. length : NDArray The length array. temperature : double or None, optional, default=None Temperature parameter in softmax dtype : {None, 'float16', 'float32', 'float64'},optional, default='None' DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None). use_length : boolean or None, optional, default=0 Whether to use the length input as a mask over the data input. Returns ------- out : NDArray or list of NDArrays The output of this function. Example ------- >>> data = np.ones((2, 3)) >>> npx.softmax(data, axis=0) array([[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]]) >>> npx.softmax(data, axis=1) array([[0.33333334, 0.33333334, 0.33333334], [0.33333334, 0.33333334, 0.33333334]]) """ return _mx_nd_npx.softmax(data, axis=axis, length=length, temperature=temperature, use_length=use_length, dtype=dtype) # pylint: disable=too-many-arguments @set_module('mxnet.numpy_extension') def log_softmax(data, axis=-1, length=None, temperature=None, use_length=False, dtype=None): r"""Computes the log softmax of the input. This is equivalent to computing softmax followed by log. Parameters ---------- data : NDArray The input array. axis : int, optional, default='-1' The axis along which to compute softmax. length : NDArray The length array. temperature : double or None, optional, default=None Temperature parameter in softmax dtype : {None, 'float16', 'float32', 'float64'},optional, default='None' DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None). use_length : boolean or None, optional, default=0 Whether to use the length input as a mask over the data input. Returns ------- out : NDArray or list of NDArrays The output of this function. Examples -------- >>> data = np.array([1, 2, .1]) >>> npx.log_softmax(data) array([-1.4170278, -0.4170278, -2.3170278]) >>> data = np.array([[1, 2, .1],[.1, 2, 1]]) >>> npx.log_softmax(data, axis=0) array([[-0.34115386, -0.6931472 , -1.2411538 ], [-1.2411538 , -0.6931472 , -0.34115386]]) """ return _mx_nd_npx.log_softmax(data, axis=axis, length=length, temperature=temperature, use_length=use_length, dtype=dtype) # pylint: disable=too-many-arguments @set_module('mxnet.numpy_extension') def masked_softmax(data, mask, axis=-1, temperature=1.0, dtype=None): r"""Applies the softmax function masking elements according to the mask provided Parameters ---------- data : NDArray The input array. mask : NDArray Mask to apply. axis : int, optional, default='-1' The axis along which to compute softmax. temperature : double or None, optional, default=None Temperature parameter in softmax dtype : {None, 'float16', 'float32', 'float64'},optional, default='None' DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None). normalize : boolean or None, optional, default=1 Whether to normalize input data x: x = x - max(x) Returns ------- out : NDArray or list of NDArrays The output of this function. Examples -------- >>> data = np.arange(5) >>> mask = np.array([1, 0, 1, 0, 1]) >>> npx.masked_softmax(data, mask) array([0.01587624, 0. , 0.11731042, 0. , 0.8668133 ]) >>> data = np.arange(10).reshape((2, 5)) >>> npx.masked_softmax(data, mask, axis=0) array([[0.00669285, 0. , 0.00669285, 0. , 0.00669285], [0.9933072 , 0. , 0.9933072 , 0. , 0.9933072 ]]) """ return _mx_nd_npx.masked_softmax(data, mask, axis=axis, temperature=temperature, dtype=dtype) # pylint: disable=too-many-arguments @set_module('mxnet.numpy_extension') def masked_log_softmax(data, mask, axis=-1, temperature=1.0, dtype=None): r"""Computes the masked log softmax of the input. This is equivalent to computing masked softmax followed by log. Parameters ---------- data : NDArray The input array. mask : NDArray Mask to apply. axis : int, optional, default='-1' The axis along which to compute softmax. temperature : double or None, optional, default=None Temperature parameter in softmax dtype : {None, 'float16', 'float32', 'float64'},optional, default='None' DType of the output in case this can't be inferred. Defaults to the same as input's dtype if not defined (dtype=None). normalize : boolean or None, optional, default=1 Whether to normalize input data x: x = x - max(x) Returns ------- out : NDArray or list of NDArrays The output of this function. Examples -------- >>> data = np.arange(5) >>> mask = np.array([1, 0, 1, 0, 1]) >>> npx.masked_log_softmax(data, mask) array([-4.1429286 , -inf, -2.1429286 , -inf, -0.14292854]) >>> data = np.arange(10).reshape((2, 5)) >>> npx.masked_log_softmax(data, mask, axis=0) array([[-5.0067153 , -inf, -5.0067153 , -inf, -5.0067153 ], [-0.00671535, -inf, -0.00671535, -inf, -0.00671535]]) """ return _mx_nd_npx.masked_log_softmax(data, mask, axis=axis, temperature=temperature, dtype=dtype) # pylint: disable=too-many-arguments, unused-argument @set_module('mxnet.numpy_extension') def activation(data, act_type='relu', **kwargs): r"""Applies an activation function element-wise to the input. The following activation functions are supported: - `relu`: Rectified Linear Unit, :math:`y = max(x, 0)` - `sigmoid`: :math:`y = \frac{1}{1 + exp(-x)}` - `tanh`: Hyperbolic tangent, :math:`y = \frac{exp(x) - exp(-x)}{exp(x) + exp(-x)}` - `softrelu`: Soft ReLU, or SoftPlus, :math:`y = log(1 + exp(x))` - `softsign`: :math:`y = \frac{x}{1 + abs(x)}` Parameters ---------- data : NDArray The input array. act_type : {'relu', 'sigmoid', 'softrelu', 'softsign', 'tanh'}, required Activation function to be applied. Returns ------- out : NDArray or list of NDArrays The output of this function. """ return _mx_nd_npx.activation(data, act_type=act_type) # pylint: disable=too-many-arguments, unused-argument @set_module('mxnet.numpy_extension') def batch_norm(x, gamma, beta, running_mean, running_var, eps=1e-3, momentum=0.9, fix_gamma=True, use_global_stats=False, output_mean_var=False, axis=1, cudnn_off=False, min_calib_range=None, max_calib_range=None, **kwargs): r"""Batch normalization. Normalizes a data batch by mean and variance, and applies a scale ``gamma`` as well as offset ``beta``. Assume the input has more than one dimension and we normalize along axis 1. We first compute the mean and variance along this axis: .. math:: data\_mean[i] = mean(data[:,i,:,...]) \\ data\_var[i] = var(data[:,i,:,...]) Then compute the normalized output, which has the same shape as input, as following: .. math:: out[:,i,:,...] = \frac{data[:,i,:,...] - data\_mean[i]}{\sqrt{data\_var[i]+\epsilon}} * gamma[i] + beta[i] Both *mean* and *var* returns a scalar by treating the input as a vector. Assume the input has size *k* on axis 1, then both ``gamma`` and ``beta`` have shape *(k,)*. If ``output_mean_var`` is set to be true, then outputs both ``data_mean`` and the inverse of ``data_var``, which are needed for the backward pass. Note that gradient of these two outputs are blocked. Besides the inputs and the outputs, this operator accepts two auxiliary states, ``moving_mean`` and ``moving_var``, which are *k*-length vectors. They are global statistics for the whole dataset, which are updated by:: moving_mean = moving_mean * momentum + data_mean * (1 - momentum) moving_var = moving_var * momentum + data_var * (1 - momentum) If ``use_global_stats`` is set to be true, then ``moving_mean`` and ``moving_var`` are used instead of ``data_mean`` and ``data_var`` to compute the output. It is often used during inference. The parameter ``axis`` specifies which axis of the input shape denotes the 'channel' (separately normalized groups). The default is 1. Specifying -1 sets the channel axis to be the last item in the input shape. Both ``gamma`` and ``beta`` are learnable parameters. But if ``fix_gamma`` is true, then set ``gamma`` to 1 and its gradient to 0. .. Note:: When ``fix_gamma`` is set to True, no sparse support is provided. If ``fix_gamma is`` set to False, the sparse tensors will fallback. Parameters ---------- data : NDArray Input data to batch normalization gamma : NDArray gamma
import sublime import sublime_plugin import datetime import re import os import fnmatch import OrgExtended.orgparse.node as node import OrgExtended.orgutil.util as util import OrgExtended.orgutil.navigation as nav import OrgExtended.orgutil.template as templateEngine import logging import sys import traceback import OrgExtended.orgdb as db import OrgExtended.asettings as sets import OrgExtended.orgcapture as capture import sys import os.path import fnmatch log = logging.getLogger(__name__) # Stolen from the original orgmode class CheckState: Unchecked, Checked, Indeterminate, Error = range(1, 5) indent_regex = re.compile(r'^(\s*).*$') summary_regex = re.compile(r'(\[\d*[/%]\d*\])') checkbox_regex = re.compile(r'(\[[xX\- ]\])') checkbox_line_regex = re.compile(r'\s*[-+]?\s*(\[[xX\- ]\])\s+') # Extract the indent of this checkbox. # RETURNS: a string with the indent of this line. def get_indent(view, content): if isinstance(content, sublime.Region): content = view.substr(content) match = indent_regex.match(content) if(match): return match.group(1) else: log.debug("Could not match indent: " + content) return "" RE_HEADING = re.compile('^[*]+ ') # Try to find the parent of a region (by indent) def find_parent(view, region): row, col = view.rowcol(region.begin()) content = view.substr(view.line(region)) indent = len(get_indent(view, content)) row -= 1 found = False # Look upward while row >= 0: point = view.text_point(row, 0) content = view.substr(view.line(point)) if len(content.strip()): if(RE_HEADING.search(content)): break cur_indent = len(get_indent(view, content)) if cur_indent < indent: found = True break row -= 1 if found: # return the parent we found. return view.line(view.text_point(row,0)) def find_children(view, region, cre = checkbox_regex, includeSiblings=False, recursiveChildFind=False): row, col = view.rowcol(region.begin()) line = view.line(region) content = view.substr(line) # print content indent = get_indent(view, content) if(not indent): log.debug("Unable to locate indent for line: " + str(row)) indent = len(indent) # print repr(indent) row += 1 child_indent = None children = [] last_row, _ = view.rowcol(view.size()) while row <= last_row: point = view.text_point(row, 0) line = view.line(point) content = view.substr(line) summary = get_summary(view, line) lc = content.lstrip() if summary and lc.startswith("*") or lc.startswith('#'): break if cre.search(content): cur_indent = len(get_indent(view, content)) # check for end of descendants if includeSiblings and cur_indent < indent: break elif not includeSiblings and cur_indent <= indent: break # only immediate children (and siblings) if(not recursiveChildFind): if child_indent is None: child_indent = cur_indent if cur_indent == child_indent: children.append(line) if(includeSiblings and cur_indent < child_indent): children.append(line) else: children.append(line) row += 1 return children def find_siblings(view, child, parent): row, col = view.rowcol(parent.begin()) parent_indent = get_indent(view, parent) child_indent = get_indent(view, child) siblings = [] row += 1 last_row, _ = view.rowcol(view.size()) while row <= last_row: # Don't go past end of document. line = view.text_point(row, 0) line = view.line(line) content = view.substr(line) # print content if len(content.strip()): cur_indent = get_indent(view, content) if len(cur_indent) <= len(parent_indent): break # Indent same as parent found! if len(cur_indent) == len(child_indent): siblings.append((line, content)) row += 1 return siblings def get_summary(view, line): row, _ = view.rowcol(line.begin()) content = view.substr(line) match = summary_regex.search(content) if not match: return None col_start, col_stop = match.span() return sublime.Region( view.text_point(row, col_start), view.text_point(row, col_stop), ) def get_checkbox(view, line): row, _ = view.rowcol(line.begin()) content = view.substr(line) # print content match = checkbox_regex.search(content) if not match: return None # checkbox = match.group(1) # print repr(checkbox) # print dir(match), match.start(), match.span() col_start, col_stop = match.span() return sublime.Region( view.text_point(row, col_start), view.text_point(row, col_stop), ) def get_check_state(view, line): if '[-]' in view.substr(line): return CheckState.Indeterminate if '[ ]' in view.substr(line): return CheckState.Unchecked if '[X]' in view.substr(line) or '[x]' in view.substr(line): return CheckState.Checked return CheckState.Error def get_check_char(view, check_state): if check_state == CheckState.Unchecked: return ' ' elif check_state == CheckState.Checked: return 'x' elif check_state == CheckState.Indeterminate: return '-' else: return 'E' def recalc_summary(view, region): recursive = sets.Get("checkboxSummaryRecursive",False) at = db.Get().AtInView(view) if(at): props = at.properties if(props and 'COOKIE_DATA' in props): cook = props['COOKIE_DATA'] if(cook and 'notrecursive' in cook): recursive = False elif(cook and 'recursive' in cook): recursive = True children = None children = find_children(view, region, checkbox_regex, False, recursive) if not len(children) > 0: return (0, 0) num_children = len(children) checked_children = len( [child for child in children if (get_check_state(view,child) == CheckState.Checked)]) # print ('checked_children: ' + str(checked_children) + ', num_children: ' + str(num_children)) return (num_children, checked_children) def update_line(view, edit, region, parent_update=True): #print ('update_line', self.view.rowcol(region.begin())[0]+1) (num_children, checked_children) = recalc_summary(view, region) # No children we don't have to update anything else. if num_children <= 0: return False # update region checkbox if checked_children == num_children: newstate = CheckState.Checked else: if checked_children != 0: newstate = CheckState.Indeterminate else: newstate = CheckState.Unchecked toggle_checkbox(view, edit, region, newstate) # update region summary update_summary(view, edit, region, checked_children, num_children) children = find_children(view, region) for child in children: line = view.line(child) summary = get_summary(view, view.line(child)) if summary: return update_line(view, edit, line, parent_update=False) if parent_update: parent = find_parent(view, region) if parent: update_line(view, edit, parent) return True def update_summary(view, edit, region, checked_children, num_children): # print('update_summary', self.view.rowcol(region.begin())[0]+1) summary = get_summary(view, region) if not summary: return False # print('checked_children: ' + str(checked_children) + ', num_children: ' + str(num_children)) line = view.substr(summary) if("%" in line): view.replace(edit, summary, '[{0}%]'.format(int(checked_children/num_children*100))) else: view.replace(edit, summary, '[%d/%d]' % (checked_children, num_children)) def toggle_checkbox(view, edit, region, checked=None, recurse_up=False, recurse_down=False): # print 'toggle_checkbox', self.view.rowcol(region.begin())[0]+1 checkbox = get_checkbox(view, region) if not checkbox: return False if checked is None: check_state = get_check_state(view, region) if (check_state == CheckState.Unchecked) | (check_state == CheckState.Indeterminate): check_state = CheckState.Checked elif (check_state == CheckState.Checked): check_state = CheckState.Unchecked else: check_state = checked view.replace(edit, checkbox, '[%s]' % ( get_check_char(view, check_state))) if recurse_down: # all children should follow children = find_children(view, region) for child in children: toggle_checkbox(view, edit, child, check_state, recurse_down=True) if recurse_up: # update parent parent = find_parent(view, region) if parent: update_line(view, edit, parent) def is_checkbox(view, sel): names = view.scope_name(sel.end()) return 'orgmode.checkbox' in names or 'orgmode.checkbox.checked' in names or 'orgmode.checkbox.blocked' in names def is_checkbox_line(view,sel=None): point = None if(sel == None): row = view.curRow() point = view.text_point(row, 0) else: point = sel.end() line = view.line(point) content = view.substr(line) return checkbox_line_regex.search(content) def find_all_summaries(view): return view.find_by_selector("orgmode.checkbox.summary") def recalculate_checkbox_summary(view, sel, edit): line = view.line(sel.begin()) update_line(view, edit, line) def recalculate_all_checkbox_summaries(view, edit): sums = find_all_summaries(view) for sel in sums: recalculate_checkbox_summary(view, sel, edit) cline_info_regex = re.compile(r'^(\s*)([-+0-9](\.)?)?.*$') class OrgInsertCheckboxCommand(sublime_plugin.TextCommand): def run(self, edit,insertHere=True): row = self.view.curRow() line = self.view.getLine(row) match = cline_info_regex.match(line) indent = match.group(1) start = match.group(2) if(start): indent = indent + start + " [ ] " reg = self.view.curLine() list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])') children = find_children(self.view, reg, list_regex, not insertHere) if(children and len(children) > 0): reg = children[len(children) - 1] row,_ =self.view.rowcol(reg.begin()) self.view.insert(edit,reg.end(),"\n" + indent) # Move to end of line row = row + 1 pt = self.view.text_point(row,0) ln = self.view.line(pt) self.view.sel().clear() self.view.sel().add(ln.end()) uline_info_regex = re.compile(r'^(\s*)([-+]) .*$') def isUnorderedList(line): return uline_info_regex.match(line) RE_THING = re.compile(r'^\s*[+-](\s\[[ xX-]\])?\s(?P<data>.*)$') RE_NOTHEADERS = re.compile(r'^\s*[\#|0-9]') def getListAtPointForSorting(view): parent = view.findParentByIndent(view.curLine(),RE_NOTHEADERS, RE_THING) if(None != parent): prow, _ = view.rowcol(parent.begin()) list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])') children = find_children(view, parent, list_regex, True) sortby = view.getLine(prow) m = RE_THING.search(sortby) if(m): sortby = m.group('data') things = [[[prow,0],sortby]] for c in children: srow, _ = view.rowcol(c.begin()) if(len(things) > 0): things[len(things)-1][0][1] = srow sortby = view.getLine(srow) m = RE_THING.search(sortby) if(m): sortby = m.group('data') things.append([[srow,0],sortby]) if(len(things) > 0): srow, _ = view.rowcol(children[len(children)-1].end()) things[len(things)-1][0][1] = srow+1 return things return None def getListAtPoint(view,pt=None): if(pt): line = view.line(pt) else: line = view.curLine() parent = view.findParentByIndent(line,RE_NOTHEADERS, RE_THING) if(None != parent): prow, _ = view.rowcol(parent.begin()) list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])') children = find_children(view, parent, list_regex, True) sortby = view.getLine(prow) m = RE_THING.search(sortby) if(m): sortby = m.group('data') things = [] lastAppend = False for c in children: srow, _ = view.rowcol(c.begin()) if(lastAppend and len(things) > 0): things[len(things)-1][0][1] = srow lastAppend = False sortby = view.getLine(srow) m = RE_THING.search(sortby) if(m): sortby = m.group('data') things.append([[srow,0],sortby]) lastAppend = True if(len(things) > 0): srow, _ = view.rowcol(children[len(children)-1].end()) things[len(things)-1][0][1] = srow+1 return things return None class OrgInsertUnorderedListCommand(sublime_plugin.TextCommand): def run(self, edit,insertHere=True): row = self.view.curRow() line = self.view.getLine(row) match = uline_info_regex.match(line) indent = match.group(1) start = match.group(2) if(start): indent = indent + start + " " reg = self.view.curLine() list_regex = re.compile(r'\s*([-+]|[^#*|])') children = find_children(self.view, reg, list_regex, not insertHere) if(children and len(children) > 0): reg = children[len(children) - 1] row,_ =self.view.rowcol(reg.begin()) self.view.insert(edit,reg.end(),"\n" + indent) # Move to end of line row = row + 1 pt = self.view.text_point(row,0) ln = self.view.line(pt) self.view.sel().clear() self.view.sel().add(ln.end()) cbsline_info_regex = re.compile(r'^(\s*)(.*)\[\s*[0-9]*/[0-9]\s*\]\s*$') class OrgInsertCheckboxSummaryCommand(sublime_plugin.TextCommand): def run(self, edit): row = self.view.curRow() line = self.view.getLine(row) match = cbsline_info_regex.match(line) if(not match): reg = self.view.curLine() self.view.insert(edit,reg.end()," [/] ") recalculate_all_checkbox_summaries(self.view, edit) class OrgToggleCheckboxCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view for sel in view.sel(): if(not is_checkbox_line(view, sel)): continue line = view.line(sel.end()) toggle_checkbox(view, edit, line,
done since the last commit or just some" " things, or just save what you have done?" ) return title, body class CommittedReallyState(State): """The committed really state. Ancestors are StartState -> CommitedQuestionState -> CommittedState. """ def __init__(self, parent): """Initialize the state.""" super().__init__(parent) self.options = ["Yes, pushes were made", "No pushes"] def on_event(self, event): """Decide on the next state, based on the event.""" choice = self.parse_choice(event) if choice == "Parent": return self.parent elif choice == "Yes, pushes were made": return PushedState(self) elif choice == "No pushes": return UnpushedState(self) return self def describe(self): """Describe the state.""" title = "Have you pushed?" body = """So you have committed, the question is now whether you have \ made your changes (or at least the changes you are interesting in "fixing") \ publicly available or not. Publishing history has a big impact on others working \ on the same repository. If you are dealing with commits someone else made, then this question covers \ whether they have pushed, and since you have their commits, the answer is almost \ certainly "yes". Please note in any and all events, the recipes provided here will typically only \ modify the current branch you are on (only one exception which will self-notify). \ Specifically, any tags or branches involving the commit you are changing or a child \ of that commit will not be modified. You must deal with those separately. Look at \ `gitk --all --date-order` to help visualize what other git references might also \ need to be updated. Also note that these commands will fix up the referenced commits in your repository. \ There will be reflog'd and dangling commits holding the state you just corrected. \ This is normally a good thing and it will eventually go away by itself, but if for \ some reason you want to cut your seat belts, you can expire the reflog now and \ garbage collect with immediate pruning.""" return title, body class UncommittedEverythingState(State): """Uncommitted Everything state. Ancestors are StartState -> CommitedQuestionState -> UncommittedState. """ def __init__(self, parent): """Initialize the state.""" super().__init__(parent) self.options = [] def on_event(self, event): """Decide on the next state, based on the event.""" choice = self.parse_choice(event) if choice == "Parent": return self.parent return self def describe(self): """Describe the state.""" title = "How to undo all uncommitted changes" body = """So you have not yet committed and you want to undo everything.\ Well, best practice is for you to stash the changes in case you were mistaken \ and later decide that you really wanted them after all. \ `git stash push -m "description of changes"`. You can revisit those stashes later \ `git stash list` and decide whether to `git stash drop` them after some time \ has passed. Please note that untracked and ignored files are not stashed by \ default. See `--include-untracked` and `--all` for stash options to handle \ those two cases. However, perhaps you are confident enough to know for sure that you will \ never ever want the uncommitted changes. If so, you can run `git reset --hard`\ , however please be quite aware that this is almost certainly a completely \ unrecoverable operation. Any changes which are removed here cannot be restored \ later. This will not delete untracked or ignored files. Those can be deleted \ with `git clean -nd` and `git clean -ndX` respectively, or `git clean -ndx` for \ both at once. Well, actually those command do not delete the files. They \ show what files will be deleted. Replace the "n" in "-nd…" with "f" to \ actually delete the files. Best practice is to ensure you are not deleting \ what you should not by looking at the filenames first.""" return title, body class UncommittedCommitState(State): """Uncommitted Commit state. Ancestors are StartState -> CommitedQuestionState -> UncommittedState. """ def __init__(self, parent): """Initialize the state.""" super().__init__(parent) self.options = [] def on_event(self, event): """Decide on the next state, based on the event.""" choice = self.parse_choice(event) if choice == "Parent": return self.parent return self def describe(self): """Describe the state.""" title = "How to save uncommitted changes" body = """There are five ways you can save your uncommitted change. |Description|Command| |:------------|:------| |Commit them on the local branch.|`git commit -a -m "message"`| |Commit them on another branch, no checkout conflicts.|`git checkout other_branch && git commit -am "message"`| |Commit them on another branch, conflicts.|`git stash; git checkout other_branch; git stash apply; : "resolve conflicts"; git commit -am "message"`| |Commit them on a new branch.|`git checkout -b new_branch; git commit -am "message"`| |Stash them for later|`git stash push -m "description"`| """ return title, body class PushedState(State): """Pushed state. Ancestors are StartState -> CommitedQuestionState -> CommittedState -> CommittedReallyState. """ def __init__(self, parent): """Initialize the state.""" super().__init__(parent) self.options = [ "Yes, I can make a new commit, but the bad commit trashed a particular file" " in error (among other good things I want to keep)", "Yes, I can make a new commit, and the bad commit is a merge commit I want" " to totally remove", "Yes, I can make a new commit, but the bad commit is a simple commit I want" " to totally remove", "Yes, I can make a new commit, and the bad commit has an error in it I want" " to fix", "Yes, I can make a new commit, but history is all messed up and I have a" " replacement branch", "No, I must rewrite published history and will have to inform others", ] def on_event(self, event): """Decide on the next state, based on the event.""" choice = self.parse_choice(event) if choice == "Parent": return self.parent elif ( choice == "Yes, I can make a new commit, but the bad commit trashed a particular" " file in error (among other good things I want to keep)" ): return PushedRestoreFileState(self) elif ( choice == "Yes, I can make a new commit, and the bad commit is a merge commit I" " want to totally remove" ): return PushedNewMergeState(self) elif ( choice == "Yes, I can make a new commit, but the bad commit is a simple commit I" " want to totally remove" ): return PushedNewSimpleState(self) elif ( choice == "Yes, I can make a new commit, and the bad commit has an error in it I" " want to fix" ): return PushedFixitState(self) elif ( choice == "Yes, I can make a new commit, but history is all messed up and I have a" " replacement branch" ): return BranchOverlayMergeState(self) elif ( choice == "No, I must rewrite published history and will have to inform others" ): return PushedOldState(self) return self def describe(self): """Describe the state.""" title = ( "Can you make a positive commit to fix the problem and what is the fix" " class?" ) body = """Rewriting public history is a bad idea. It requires everyone \ else to do special things and you must publicly announce your failure. Ideally, \ you will create either a commit to just fix the problem, or a new `git revert` \ commit to create a new commit which undoes the changes made in a previous commit.""" return title, body class UnpushedState(State): """The unpushed state. Ancestors are StartState -> CommitedQuestionState -> CommittedState -> CommittedReallyState. Ancestors are StartState -> CommitedQuestionState -> CommittedState -> CommittedReallyState -> PushedState -> PushedOldState. """ def __init__(self, parent): """Initialize the state.""" super().__init__(parent) self.options = [ "Yes, I want to discard all unpushed changes", "Yes, and I want to make my branch identical to some non-upstream ref", "No, I want to fix some unpushed changes", ] def on_event(self, event): """Decide on the next state, based on the event.""" choice = self.parse_choice(event) if choice == "Parent": return self.parent elif choice == "Yes, I want to discard all unpushed changes": return DiscardAllUnpushedState(self) elif ( choice == "Yes, and I want to make my branch identical to some non-upstream ref" ): return ReplaceAllUnpushedState(self) elif choice == "No, I want to fix some unpushed changes": return FixUnpushedState(self) return self def describe(self): """Describe the state.""" title = "Do you
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2016, Anaconda, Inc. All rights reserved. # # Licensed under the terms of the BSD 3-Clause License. # The full license is in the file LICENSE.txt, distributed with this software. # ----------------------------------------------------------------------------- """YAML file loading and manipulation.""" from __future__ import absolute_import, print_function # ruamel.yaml supports round-trip preserving dict ordering, # comments, etc., which is why we use it instead of the usual yaml # module. Remember the project file is intended to go into source # control. try: # this is the conda-packaged version of ruamel.yaml which has the # module renamed import ruamel_yaml as ryaml from ruamel_yaml.error import YAMLError from ruamel_yaml.comments import CommentedMap from ruamel_yaml.comments import CommentedSeq except ImportError: # pragma: no cover # this is the upstream version import ruamel.yaml as ryaml # pragma: no cover from ruamel.yaml.error import YAMLError # pragma: no cover from ruamel.yaml.comments import CommentedMap # pragma: no cover from ruamel.yaml.comments import CommentedSeq # pragma: no cover import codecs import errno import os import sys import uuid from anaconda_project.internal.makedirs import makedirs_ok_if_exists from anaconda_project.internal.rename import rename_over_existing from anaconda_project.internal.py2_compat import is_string # We use this in other files (to abstract over the imports above) _YAMLError = YAMLError _CommentedMap = CommentedMap _CommentedSeq = CommentedSeq def _atomic_replace(path, contents, encoding='utf-8'): tmp = path + ".tmp-" + str(uuid.uuid4()) try: with codecs.open(tmp, 'w', encoding) as file: file.write(contents) file.flush() file.close() rename_over_existing(tmp, path) finally: try: os.remove(tmp) except (IOError, OSError): pass def _load_string(contents): if contents.strip() == '': # ryaml.load below returns None for an empty file, we want # to return an empty dict instead. return {} else: # using RoundTripLoader incorporates safe_load # (we don't load code) assert issubclass(ryaml.RoundTripLoader, ryaml.constructor.SafeConstructor) return ryaml.load(contents, Loader=ryaml.RoundTripLoader) def _dump_string(yaml): return ryaml.dump(yaml, Dumper=ryaml.RoundTripDumper) def _save_file(yaml, filename, contents=None): if contents is None: contents = _dump_string(yaml) try: # This is to ensure we don't corrupt the file, even if ruamel.yaml is broken ryaml.load(contents, Loader=ryaml.RoundTripLoader) except YAMLError as e: # pragma: no cover (should not happen) print("ruamel.yaml bug; it failed to parse a file that it generated.", file=sys.stderr) print(" the parse error was: " + str(e), file=sys.stderr) print("Generated file was:", file=sys.stderr) print(contents, file=sys.stderr) raise RuntimeError("Bug in ruamel.yaml library; failed to parse a file that it generated: " + str(e)) if not os.path.isfile(filename): # might have to make the directory dirname = os.path.dirname(filename) makedirs_ok_if_exists(dirname) _atomic_replace(filename, contents) def _block_style_all_nodes(yaml): if hasattr(yaml, 'fa'): yaml.fa.set_block_style() if isinstance(yaml, list): for element in yaml: _block_style_all_nodes(element) elif isinstance(yaml, dict): for value in yaml.values(): _block_style_all_nodes(value) class YamlFile(object): """Abstract YAML file, base class for ``ProjectFile`` and ``LocalStateFile``. Be careful with creating your own instance of this class, because you have to think about when other code might load or save in a way that conflicts with your loads and saves. """ def __init__(self, filename): """Load a YamlFile with the given filename. Raises an exception on an IOError, but if the file is missing this succeeds (then creates the file if and when you call ``save()``). If the file has syntax problems, this sets the ``corrupted`` and ``corrupted_error_message`` properties, and attempts to modify the file will raise an exception. """ self.filename = filename self._previous_content = "" self._change_count = 0 self.load() def load(self): """Reload the file from disk, discarding any unsaved changes. If the file has syntax problems, this sets the ``corrupted`` and ``corrupted_error_message`` properties, and attempts to modify the file will raise an exception. Returns: None """ self._corrupted = False self._corrupted_error_message = None self._corrupted_maybe_line = None self._corrupted_maybe_column = None self._change_count = self._change_count + 1 try: with codecs.open(self.filename, 'r', 'utf-8') as file: contents = file.read() self._yaml = _load_string(contents) # we re-dump instead of using "contents" because # when loading a hand-edited file, we may reformat # in trivial ways because our round-tripping isn't perfect, # and we don't want to count those trivial reformats as # a reason to save. self._previous_content = _dump_string(self._yaml) except IOError as e: if e.errno == errno.ENOENT: self._yaml = None else: raise e except YAMLError as e: self._corrupted = True self._corrupted_error_message = str(e) # Not sure all this paranoia is needed # about whether these values really exist, # but hard to prove it isn't. mark = getattr(e, 'problem_mark', None) if mark is not None: if mark.line is not None and mark.line >= 0: self._corrupted_maybe_line = mark.line if mark.column is not None and mark.column >= 0: self._corrupted_maybe_column = mark.column self._yaml = None if self._yaml is None: if self._corrupted: # don't want to throw exceptions if people get_value() # so stick an empty dict in here self._yaml = dict() else: self._yaml = self._default_content() # make it pretty _block_style_all_nodes(self._yaml) if not self._save_default_content(): # pretend we already saved self._previous_content = _dump_string(self._yaml) def _default_comment(self): return "yaml file" def _default_content(self): # ruamel.yaml returns None if you load an empty file, # so we have to build this ourselves root = CommentedMap() root.yaml_set_start_comment(self._default_comment()) return root def _save_default_content(self): """Override to change whether we consider a default, unmodified file dirty.""" return True def _throw_if_corrupted(self): if self._corrupted: raise ValueError( "Cannot modify corrupted YAML file %s\n%s" % (self.filename, self._corrupted_error_message)) @property def basename(self): """Basename of the filename.""" return os.path.basename(self.filename) @property def corrupted(self): """Get whether the file is corrupted. A corrupted file has a syntax error so we can't modify and save it. See ``corrupted_error_message`` for what's wrong with it. Returns: True if file is corrupted. """ return self._corrupted @property def corrupted_error_message(self): """Get the error message if file is corrupted, or None if it isn't. Use this to display the problem if the file is corrupted. Returns: Corruption message or None. """ return self._corrupted_error_message @property def corrupted_maybe_line(self): """Get the line number for syntax error, or None if unavailable. Returns: Corruption line or None. """ return self._corrupted_maybe_line @property def corrupted_maybe_column(self): """Get the column for syntax error, or None if unavailable. Returns: Corruption column or None. """ return self._corrupted_maybe_column @property def change_count(self): """Get the number of times we've resynced with the file on disk (reloaded or saved changes). This is used for cache invalidation. If a cached value becomes invalid whenever ``change_count`` increments, then the cached value will be recomputed whenever we save new changes or reload the file. """ return self._change_count @property def has_unsaved_changes(self): """Get whether changes are all saved.""" # this is a fairly expensive check return self._previous_content != _dump_string(self._yaml) def use_changes_without_saving(self): """Apply any in-memory changes as if we'd saved, but don't actually save. This is used to "try out" a change before we save it. We can load() to undo our changes. """ self._change_count = self._change_count + 1 def save(self): """Write the file to disk, only if any changes have been made. Raises ``IOError`` if it fails for some reason. Returns: None """ self._throw_if_corrupted() contents = _dump_string(self._yaml) if contents != self._previous_content: _save_file(self._yaml, self.filename, contents) self._change_count = self._change_count + 1 self._previous_content = contents @classmethod def _path(cls, path): if is_string(path): return (path, ) else: try: return list(element for element in path) except TypeError: raise ValueError("YAML file path must be a string or an iterable of strings") def _get_dict_or_none(self, pieces): current = self._yaml for p in pieces: if p in current and isinstance(current[p], dict): current = current[p] else: return None return current def _ensure_dicts_at_path(self, pieces): self._throw_if_corrupted() current = self._yaml for p in pieces: if p not in current or not isinstance(current[p], dict): # It's important to use CommentedMap because it preserves # order. current[p] = CommentedMap() _block_style_all_nodes(current[p]) current = current[p] return current def set_value(self, path, value): """Set a single value at the given path. Overwrites any existing value at the path. This method does not save the file, call ``save()`` to do that. Args: path (str or list of str): single key, or list of nested keys value: any YAML-compatible value type """ self._throw_if_corrupted() path = self._path(path) existing = self._ensure_dicts_at_path(path[:-1]) existing[path[-1]] = value def unset_value(self, path): """Remove a single value at the given path. This method does not save the file, call ``save()`` to do that. Args: path (str or list of str): single key, or list of nested keys """ self._throw_if_corrupted() path = self._path(path) existing = self._get_dict_or_none(path[:-1]) key = path[-1] if existing is not
<filename>code/UI/OpenAPI/python-flask-server/swagger_server/models/edge.py # coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util from swagger_server.models.biolink_relation import BiolinkRelation # noqa: F401,E501 from swagger_server.models.edge_attribute import EdgeAttribute # noqa: F401,E501 class Edge(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: str=None, type: BiolinkRelation=None, relation: str=None, source_id: str=None, target_id: str=None, is_defined_by: str=None, defined_datetime: str=None, provided_by: str=None, confidence: float=None, weight: float=None, publications: List[str]=None, evidence_type: str=None, qualifiers: str=None, negated: bool=None, edge_attributes: List[EdgeAttribute]=None, qedge_ids: List[str]=None): # noqa: E501 """Edge - a model defined in Swagger :param id: The id of this Edge. # noqa: E501 :type id: str :param type: The type of this Edge. # noqa: E501 :type type: BiolinkRelation :param relation: The relation of this Edge. # noqa: E501 :type relation: str :param source_id: The source_id of this Edge. # noqa: E501 :type source_id: str :param target_id: The target_id of this Edge. # noqa: E501 :type target_id: str :param is_defined_by: The is_defined_by of this Edge. # noqa: E501 :type is_defined_by: str :param defined_datetime: The defined_datetime of this Edge. # noqa: E501 :type defined_datetime: str :param provided_by: The provided_by of this Edge. # noqa: E501 :type provided_by: str :param confidence: The confidence of this Edge. # noqa: E501 :type confidence: float :param weight: The weight of this Edge. # noqa: E501 :type weight: float :param publications: The publications of this Edge. # noqa: E501 :type publications: List[str] :param evidence_type: The evidence_type of this Edge. # noqa: E501 :type evidence_type: str :param qualifiers: The qualifiers of this Edge. # noqa: E501 :type qualifiers: str :param negated: The negated of this Edge. # noqa: E501 :type negated: bool :param edge_attributes: The edge_attributes of this Edge. # noqa: E501 :type edge_attributes: List[EdgeAttribute] :param qedge_ids: The qedge_ids of this Edge. # noqa: E501 :type qedge_ids: List[str] """ self.swagger_types = { 'id': str, 'type': BiolinkRelation, 'relation': str, 'source_id': str, 'target_id': str, 'is_defined_by': str, 'defined_datetime': str, 'provided_by': str, 'confidence': float, 'weight': float, 'publications': List[str], 'evidence_type': str, 'qualifiers': str, 'negated': bool, 'edge_attributes': List[EdgeAttribute], 'qedge_ids': List[str] } self.attribute_map = { 'id': 'id', 'type': 'type', 'relation': 'relation', 'source_id': 'source_id', 'target_id': 'target_id', 'is_defined_by': 'is_defined_by', 'defined_datetime': 'defined_datetime', 'provided_by': 'provided_by', 'confidence': 'confidence', 'weight': 'weight', 'publications': 'publications', 'evidence_type': 'evidence_type', 'qualifiers': 'qualifiers', 'negated': 'negated', 'edge_attributes': 'edge_attributes', 'qedge_ids': 'qedge_ids' } self._id = id self._type = type self._relation = relation self._source_id = source_id self._target_id = target_id self._is_defined_by = is_defined_by self._defined_datetime = defined_datetime self._provided_by = provided_by self._confidence = confidence self._weight = weight self._publications = publications self._evidence_type = evidence_type self._qualifiers = qualifiers self._negated = negated self._edge_attributes = edge_attributes self._qedge_ids = qedge_ids @classmethod def from_dict(cls, dikt) -> 'Edge': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The Edge of this Edge. # noqa: E501 :rtype: Edge """ return util.deserialize_model(dikt, cls) @property def id(self) -> str: """Gets the id of this Edge. Local identifier for this node which is unique within this KnowledgeGraph, and perhaps within the source reasoner's knowledge graph # noqa: E501 :return: The id of this Edge. :rtype: str """ return self._id @id.setter def id(self, id: str): """Sets the id of this Edge. Local identifier for this node which is unique within this KnowledgeGraph, and perhaps within the source reasoner's knowledge graph # noqa: E501 :param id: The id of this Edge. :type id: str """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def type(self) -> BiolinkRelation: """Gets the type of this Edge. :return: The type of this Edge. :rtype: BiolinkRelation """ return self._type @type.setter def type(self, type: BiolinkRelation): """Sets the type of this Edge. :param type: The type of this Edge. :type type: BiolinkRelation """ self._type = type @property def relation(self) -> str: """Gets the relation of this Edge. Lower-level relationship type of this edge # noqa: E501 :return: The relation of this Edge. :rtype: str """ return self._relation @relation.setter def relation(self, relation: str): """Sets the relation of this Edge. Lower-level relationship type of this edge # noqa: E501 :param relation: The relation of this Edge. :type relation: str """ self._relation = relation @property def source_id(self) -> str: """Gets the source_id of this Edge. Corresponds to the @id of source node of this edge # noqa: E501 :return: The source_id of this Edge. :rtype: str """ return self._source_id @source_id.setter def source_id(self, source_id: str): """Sets the source_id of this Edge. Corresponds to the @id of source node of this edge # noqa: E501 :param source_id: The source_id of this Edge. :type source_id: str """ if source_id is None: raise ValueError("Invalid value for `source_id`, must not be `None`") # noqa: E501 self._source_id = source_id @property def target_id(self) -> str: """Gets the target_id of this Edge. Corresponds to the @id of target node of this edge # noqa: E501 :return: The target_id of this Edge. :rtype: str """ return self._target_id @target_id.setter def target_id(self, target_id: str): """Sets the target_id of this Edge. Corresponds to the @id of target node of this edge # noqa: E501 :param target_id: The target_id of this Edge. :type target_id: str """ if target_id is None: raise ValueError("Invalid value for `target_id`, must not be `None`") # noqa: E501 self._target_id = target_id @property def is_defined_by(self) -> str: """Gets the is_defined_by of this Edge. A CURIE/URI for the translator group that made the KG # noqa: E501 :return: The is_defined_by of this Edge. :rtype: str """ return self._is_defined_by @is_defined_by.setter def is_defined_by(self, is_defined_by: str): """Sets the is_defined_by of this Edge. A CURIE/URI for the translator group that made the KG # noqa: E501 :param is_defined_by: The is_defined_by of this Edge. :type is_defined_by: str """ self._is_defined_by = is_defined_by @property def defined_datetime(self) -> str: """Gets the defined_datetime of this Edge. Datetime at which the KG builder/updater pulled the information from the original source. Used as a freshness indicator. # noqa: E501 :return: The defined_datetime of this Edge. :rtype: str """ return self._defined_datetime @defined_datetime.setter def defined_datetime(self, defined_datetime: str): """Sets the defined_datetime of this Edge. Datetime at which the KG builder/updater pulled the information from the original source. Used as a freshness indicator. # noqa: E501 :param defined_datetime: The defined_datetime of this Edge. :type defined_datetime: str """ self._defined_datetime = defined_datetime @property def provided_by(self) -> str: """Gets the provided_by of this Edge. A CURIE/URI for the knowledge source that defined this edge # noqa: E501 :return: The provided_by of this Edge. :rtype: str """ return self._provided_by @provided_by.setter def provided_by(self, provided_by: str): """Sets the provided_by of this Edge. A CURIE/URI for the knowledge source that defined this edge # noqa: E501 :param provided_by: The provided_by of this Edge. :type provided_by: str """ self._provided_by = provided_by @property def confidence(self) -> float: """Gets the confidence of this Edge. Confidence metric for this edge, a value between (inclusive) 0.0 (no confidence) and 1.0 (highest confidence) # noqa: E501 :return: The confidence of this Edge. :rtype: float """ return self._confidence @confidence.setter def confidence(self, confidence: float): """Sets the confidence of this Edge. Confidence metric for this edge, a value between (inclusive) 0.0 (no confidence) and 1.0 (highest confidence) # noqa: E501 :param confidence: The confidence of this Edge. :type confidence: float """ self._confidence = confidence @property def weight(self) -> float: """Gets the weight of this Edge. Weight metric for this edge, with no upper bound. Perhaps useful when formal confidence metrics are not available # noqa: E501 :return: The weight of this Edge. :rtype: float """ return self._weight @weight.setter def weight(self, weight: float): """Sets the weight of this Edge. Weight metric for this edge, with no upper bound. Perhaps useful when formal confidence metrics are not available # noqa: E501 :param weight: The weight of this Edge. :type weight: float """ self._weight = weight @property def publications(self) -> List[str]: """Gets the publications of this
from __future__ import unicode_literals from decimal import Decimal import logging import warnings from future.utils import python_2_unicode_compatible from .ewsdatetime import UTC_NOW from .extended_properties import ExtendedProperty from .fields import BooleanField, IntegerField, DecimalField, Base64Field, TextField, CharListField, ChoiceField, \ URIField, BodyField, DateTimeField, MessageHeaderField, PhoneNumberField, EmailAddressesField, \ PhysicalAddressField, ExtendedPropertyField, AttachmentField, RecurrenceField, MailboxField, MailboxListField, \ AttendeesField, Choice, OccurrenceField, OccurrenceListField, MemberListField, EWSElementField, \ EffectiveRightsField, TimeZoneField, CultureField, IdField, CharField, TextListField, EnumAsIntField, \ EmailAddressField, FreeBusyStatusField, ReferenceItemIdField, AssociatedCalendarItemIdField from .properties import EWSElement, ItemId, ConversationId, ParentFolderId, Attendee, ReferenceItemId, \ AssociatedCalendarItemId, PersonaId, InvalidField from .recurrence import FirstOccurrence, LastOccurrence, Occurrence, DeletedOccurrence from .util import is_iterable from .version import EXCHANGE_2007_SP1, EXCHANGE_2010, EXCHANGE_2013 log = logging.getLogger(__name__) # Overall Types Schema: https://msdn.microsoft.com/en-us/library/hh354700(v=exchg.150).aspx # MessageDisposition values. See https://msdn.microsoft.com/en-us/library/office/aa565209(v=exchg.150).aspx SAVE_ONLY = 'SaveOnly' SEND_ONLY = 'SendOnly' SEND_AND_SAVE_COPY = 'SendAndSaveCopy' MESSAGE_DISPOSITION_CHOICES = (SAVE_ONLY, SEND_ONLY, SEND_AND_SAVE_COPY) # SendMeetingInvitations values: see https://msdn.microsoft.com/en-us/library/office/aa565209(v=exchg.150).aspx # SendMeetingInvitationsOrCancellations: see https://msdn.microsoft.com/en-us/library/office/aa580254(v=exchg.150).aspx # SendMeetingCancellations values: see https://msdn.microsoft.com/en-us/library/office/aa562961(v=exchg.150).aspx SEND_TO_NONE = 'SendToNone' SEND_ONLY_TO_ALL = 'SendOnlyToAll' SEND_ONLY_TO_CHANGED = 'SendOnlyToChanged' SEND_TO_ALL_AND_SAVE_COPY = 'SendToAllAndSaveCopy' SEND_TO_CHANGED_AND_SAVE_COPY = 'SendToChangedAndSaveCopy' SEND_MEETING_INVITATIONS_CHOICES = (SEND_TO_NONE, SEND_ONLY_TO_ALL, SEND_TO_ALL_AND_SAVE_COPY) SEND_MEETING_INVITATIONS_AND_CANCELLATIONS_CHOICES = (SEND_TO_NONE, SEND_ONLY_TO_ALL, SEND_ONLY_TO_CHANGED, SEND_TO_ALL_AND_SAVE_COPY, SEND_TO_CHANGED_AND_SAVE_COPY) SEND_MEETING_CANCELLATIONS_CHOICES = (SEND_TO_NONE, SEND_ONLY_TO_ALL, SEND_TO_ALL_AND_SAVE_COPY) # AffectedTaskOccurrences values. See https://msdn.microsoft.com/en-us/library/office/aa562961(v=exchg.150).aspx ALL_OCCURRENCIES = 'AllOccurrences' SPECIFIED_OCCURRENCE_ONLY = 'SpecifiedOccurrenceOnly' AFFECTED_TASK_OCCURRENCES_CHOICES = (ALL_OCCURRENCIES, SPECIFIED_OCCURRENCE_ONLY) # Conference Type values. See https://msdn.microsoft.com/en-US/library/office/aa563529(v=exchg.150).aspx CONFERENCE_TYPES = ('NetMeeting', 'NetShow', 'Chat') # ConflictResolution values. See https://msdn.microsoft.com/en-us/library/office/aa580254(v=exchg.150).aspx NEVER_OVERWRITE = 'NeverOverwrite' AUTO_RESOLVE = 'AutoResolve' ALWAYS_OVERWRITE = 'AlwaysOverwrite' CONFLICT_RESOLUTION_CHOICES = (NEVER_OVERWRITE, AUTO_RESOLVE, ALWAYS_OVERWRITE) # DeleteType values. See https://msdn.microsoft.com/en-us/library/office/aa562961(v=exchg.150).aspx HARD_DELETE = 'HardDelete' SOFT_DELETE = 'SoftDelete' MOVE_TO_DELETED_ITEMS = 'MoveToDeletedItems' DELETE_TYPE_CHOICES = (HARD_DELETE, SOFT_DELETE, MOVE_TO_DELETED_ITEMS) # Traversal enums SHALLOW = 'Shallow' SOFT_DELETED = 'SoftDeleted' ASSOCIATED = 'Associated' ITEM_TRAVERSAL_CHOICES = (SHALLOW, SOFT_DELETED, ASSOCIATED) # Shape enums ID_ONLY = 'IdOnly' DEFAULT = 'Default' # AllProperties doesn't actually get all properties in FindItem, just the "first-class" ones. See # http://msdn.microsoft.com/en-us/library/office/dn600367(v=exchg.150).aspx ALL_PROPERTIES = 'AllProperties' SHAPE_CHOICES = (ID_ONLY, DEFAULT, ALL_PROPERTIES) # Contacts search (ResolveNames) scope enums ACTIVE_DIRECTORY = 'ActiveDirectory' ACTIVE_DIRECTORY_CONTACTS = 'ActiveDirectoryContacts' CONTACTS = 'Contacts' CONTACTS_ACTIVE_DIRECTORY = 'ContactsActiveDirectory' SEARCH_SCOPE_CHOICES = (ACTIVE_DIRECTORY, ACTIVE_DIRECTORY_CONTACTS, CONTACTS, CONTACTS_ACTIVE_DIRECTORY) class RegisterMixIn(EWSElement): INSERT_AFTER_FIELD = None @classmethod def register(cls, attr_name, attr_cls): """ Register a custom extended property in this item class so they can be accessed just like any other attribute """ if not cls.INSERT_AFTER_FIELD: raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls) try: cls.get_field_by_fieldname(attr_name) except InvalidField: pass else: raise ValueError("'%s' is already registered" % attr_name) if not issubclass(attr_cls, ExtendedProperty): raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls) # Check if class attributes are properly defined attr_cls.validate_cls() # ExtendedProperty is not a real field, but a placeholder in the fields list. See # https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx # # Find the correct index for the new extended property, and insert. field = ExtendedPropertyField(attr_name, value_cls=attr_cls) cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD) @classmethod def deregister(cls, attr_name): """ De-register an extended property that has been registered with register() """ try: field = cls.get_field_by_fieldname(attr_name) except InvalidField: raise ValueError("'%s' is not registered" % attr_name) if not isinstance(field, ExtendedPropertyField): raise ValueError("'%s' is not registered as an ExtendedProperty" % attr_name) cls.remove_field(field) class Item(RegisterMixIn): """ MSDN: https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx """ ELEMENT_NAME = 'Item' # FIELDS is an ordered list of attributes supported by this item class FIELDS = [ Base64Field('mime_content', field_uri='item:MimeContent', is_read_only_after_send=True), IdField('id', field_uri=ItemId.ID_ATTR, is_read_only=True), IdField('changekey', field_uri=ItemId.CHANGEKEY_ATTR, is_read_only=True), EWSElementField('parent_folder_id', field_uri='item:ParentFolderId', value_cls=ParentFolderId, is_read_only=True), CharField('item_class', field_uri='item:ItemClass', is_read_only=True), CharField('subject', field_uri='item:Subject'), ChoiceField('sensitivity', field_uri='item:Sensitivity', choices={ Choice('Normal'), Choice('Personal'), Choice('Private'), Choice('Confidential') }, is_required=True, default='Normal'), TextField('text_body', field_uri='item:TextBody', is_read_only=True, supported_from=EXCHANGE_2013), BodyField('body', field_uri='item:Body'), # Accepts and returns Body or HTMLBody instances AttachmentField('attachments', field_uri='item:Attachments'), # ItemAttachment or FileAttachment DateTimeField('datetime_received', field_uri='item:DateTimeReceived', is_read_only=True), IntegerField('size', field_uri='item:Size', is_read_only=True), # Item size in bytes CharListField('categories', field_uri='item:Categories'), ChoiceField('importance', field_uri='item:Importance', choices={ Choice('Low'), Choice('Normal'), Choice('High') }, is_required=True, default='Normal'), TextField('in_reply_to', field_uri='item:InReplyTo'), BooleanField('is_submitted', field_uri='item:IsSubmitted', is_read_only=True), BooleanField('is_draft', field_uri='item:IsDraft', is_read_only=True), BooleanField('is_from_me', field_uri='item:IsFromMe', is_read_only=True), BooleanField('is_resend', field_uri='item:IsResend', is_read_only=True), BooleanField('is_unmodified', field_uri='item:IsUnmodified', is_read_only=True), MessageHeaderField('headers', field_uri='item:InternetMessageHeaders', is_read_only=True), DateTimeField('datetime_sent', field_uri='item:DateTimeSent', is_read_only=True), DateTimeField('datetime_created', field_uri='item:DateTimeCreated', is_read_only=True), # Placeholder for ResponseObjects DateTimeField('reminder_due_by', field_uri='item:ReminderDueBy', is_required_after_save=True, is_searchable=False), BooleanField('reminder_is_set', field_uri='item:ReminderIsSet', is_required=True, default=False), IntegerField('reminder_minutes_before_start', field_uri='item:ReminderMinutesBeforeStart', is_required_after_save=True, min=0, default=0), CharField('display_cc', field_uri='item:DisplayCc', is_read_only=True), CharField('display_to', field_uri='item:DisplayTo', is_read_only=True), BooleanField('has_attachments', field_uri='item:HasAttachments', is_read_only=True), # ExtendedProperty fields go here CultureField('culture', field_uri='item:Culture', is_required_after_save=True, is_searchable=False), EffectiveRightsField('effective_rights', field_uri='item:EffectiveRights', is_read_only=True), CharField('last_modified_name', field_uri='item:LastModifiedName', is_read_only=True), DateTimeField('last_modified_time', field_uri='item:LastModifiedTime', is_read_only=True), BooleanField('is_associated', field_uri='item:IsAssociated', is_read_only=True, supported_from=EXCHANGE_2010), URIField('web_client_read_form_query_string', field_uri='item:WebClientReadFormQueryString', is_read_only=True, supported_from=EXCHANGE_2010), URIField('web_client_edit_form_query_string', field_uri='item:WebClientEditFormQueryString', is_read_only=True, supported_from=EXCHANGE_2010), EWSElementField('conversation_id', field_uri='item:ConversationId', value_cls=ConversationId, is_read_only=True, supported_from=EXCHANGE_2010), BodyField('unique_body', field_uri='item:UniqueBody', is_read_only=True, supported_from=EXCHANGE_2010), ] # Used to register extended properties INSERT_AFTER_FIELD = 'has_attachments' # We can't use __slots__ because we need to add extended properties dynamically def __init__(self, **kwargs): # 'account' is optional but allows calling 'send()' and 'delete()' # 'folder' is optional but allows calling 'save()'. If 'folder' has an account, and 'account' is not set, # we use folder.root.account. from .folders import Folder from .account import Account self.account = kwargs.pop('account', None) if self.account is not None and not isinstance(self.account, Account): raise ValueError("'account' %r must be an Account instance" % self.account) self.folder = kwargs.pop('folder', None) if self.folder is not None: if not isinstance(self.folder, Folder): raise ValueError("'folder' %r must be a Folder instance" % self.folder) if self.folder.root.account is not None: if self.account is not None: # Make sure the account from kwargs matches the folder account if self.account != self.folder.root.account: raise ValueError("'account' does not match 'folder.root.account'") self.account = self.folder.root.account if 'item_id' in kwargs: warnings.warn("The 'item_id' attribute is deprecated. Use 'id' instead.", PendingDeprecationWarning) kwargs['id'] = kwargs.pop('item_id') super(Item, self).__init__(**kwargs) # pylint: disable=access-member-before-definition if self.attachments: for a in self.attachments: if a.parent_item and a.parent_item is not self: raise ValueError("'parent_item' of attachment %s must point to this item" % a) else: a.parent_item = self self.attach(self.attachments) else: self.attachments = [] @property def item_id(self): warnings.warn("The 'item_id' attribute is deprecated. Use 'id' instead.", PendingDeprecationWarning) return self.id @item_id.setter def item_id(self, value): warnings.warn("The 'item_id' attribute is deprecated. Use 'id' instead.", PendingDeprecationWarning) self.id = value @classmethod def get_field_by_fieldname(cls, fieldname): if fieldname == 'item_id': warnings.warn("The 'item_id' attribute is deprecated. Use 'id' instead.", PendingDeprecationWarning) fieldname = 'id' return super(Item, cls).get_field_by_fieldname(fieldname) def save(self, update_fields=None, conflict_resolution=AUTO_RESOLVE, send_meeting_invitations=SEND_TO_NONE): if self.id: item_id, changekey = self._update( update_fieldnames=update_fields, message_disposition=SAVE_ONLY, conflict_resolution=conflict_resolution, send_meeting_invitations=send_meeting_invitations ) if self.id != item_id: raise ValueError("'id' mismatch in returned update response") # Don't check that changekeys are different. No-op saves will sometimes leave the changekey intact self.changekey = changekey else: if update_fields: raise ValueError("'update_fields' is only valid for updates") tmp_attachments = None if self.account and self.account.version.build < EXCHANGE_2010 and self.attachments: # Exchange 2007 can't save attachments immediately. You need to first save, then attach. Store # the attachment of this item temporarily and attach later. tmp_attachments, self.attachments = self.attachments, [] item = self._create(message_disposition=SAVE_ONLY, send_meeting_invitations=send_meeting_invitations) self.id, self.changekey = item.id, item.changekey for old_att, new_att in zip(self.attachments, item.attachments): if old_att.attachment_id is not None: raise ValueError("Old 'attachment_id' is not empty") if new_att.attachment_id is None: raise ValueError("New 'attachment_id' is empty") old_att.attachment_id = new_att.attachment_id if tmp_attachments: # Exchange 2007 workaround. See above self.attach(tmp_attachments) return self def _create(self, message_disposition, send_meeting_invitations): if not self.account: raise ValueError('%s must have an account' % self.__class__.__name__) # bulk_create() returns an Item because we want to return the ID of both the main item *and* attachments res = self.account.bulk_create( items=[self], folder=self.folder, message_disposition=message_disposition, send_meeting_invitations=send_meeting_invitations) if message_disposition in (SEND_ONLY, SEND_AND_SAVE_COPY): if res: raise ValueError('Got a response in non-save mode') return None if len(res) != 1: raise ValueError('Expected result length 1, but got %s' % res) if isinstance(res[0], Exception): raise res[0] return res[0] def _update_fieldnames(self): # Return the list of fields we are allowed to update update_fieldnames = [] for f in self.supported_fields(version=self.account.version): if f.name == 'attachments': # Attachments are handled separately after item creation continue if f.is_read_only: # These cannot be changed continue if f.is_required or f.is_required_after_save: if getattr(self, f.name) is None or (f.is_list and not getattr(self, f.name)): # These are required and cannot be deleted continue if not self.is_draft and f.is_read_only_after_send: # These cannot be changed when the item is no longer a draft continue if f.name == 'message_id' and f.is_read_only_after_send: # 'message_id' doesn't support updating, no matter the draft status continue if f.name == 'mime_content' and isinstance(self, (Contact, DistributionList)): # Contact and DistributionList don't support updating mime_content, no matter the draft status continue update_fieldnames.append(f.name) return update_fieldnames def _update(self, update_fieldnames, message_disposition, conflict_resolution, send_meeting_invitations): if not self.account: raise ValueError('%s must have an account' % self.__class__.__name__) if not self.changekey: raise ValueError('%s must have changekey' % self.__class__.__name__) if not update_fieldnames: # The fields to update was not specified explicitly. Update all fields where update is possible update_fieldnames = self._update_fieldnames() # bulk_update() returns a tuple res = self.account.bulk_update( items=[(self, update_fieldnames)], message_disposition=message_disposition, conflict_resolution=conflict_resolution, send_meeting_invitations_or_cancellations=send_meeting_invitations) if message_disposition == SEND_AND_SAVE_COPY: if res: raise ValueError('Got a response in non-save mode') return None if len(res) != 1: raise ValueError('Expected result length 1, but got
much more flexibility to study different types of driving forces. We can reuse our earlier code by simply adding a driving force. If we stay in the $x$-direction only this can be easily done by adding a term $F_{\mathrm{ext}}(x,t)$. Note that we have kept it rather general here, allowing for both a spatial and a temporal dependence. Before we dive into the code, we need to briefly remind ourselves about the equations we started with for the case with damping, namely $$ m\frac{d^2x}{dt^2} + b\frac{dx}{dt}+kx(t) =0, $$ with no external force applied to the system. Let us now for simplicty assume that our external force is given by $$ F_{\mathrm{ext}}(t) = F_0\cos{(\omega t)}, $$ where $F_0$ is a constant (what is its dimension?) and $\omega$ is the frequency of the applied external driving force. **Small question:** would you expect energy to be conserved now? Introducing the external force into our lovely differential equation and dividing by $m$ and introducing $\omega_0^2=\sqrt{k/m}$ we have $$ \frac{d^2x}{dt^2} + \frac{b}{m}\frac{dx}{dt}+\omega_0^2x(t) =\frac{F_0}{m}\cos{(\omega t)}, $$ Thereafter we introduce a dimensionless time $\tau = t\omega_0$ and a dimensionless frequency $\tilde{\omega}=\omega/\omega_0$. We have then $$ \frac{d^2x}{d\tau^2} + \frac{b}{m\omega_0}\frac{dx}{d\tau}+x(\tau) =\frac{F_0}{m\omega_0^2}\cos{(\tilde{\omega}\tau)}, $$ Introducing a new amplitude $\tilde{F} =F_0/(m\omega_0^2)$ (check dimensionality again) we have $$ \frac{d^2x}{d\tau^2} + \frac{b}{m\omega_0}\frac{dx}{d\tau}+x(\tau) =\tilde{F}\cos{(\tilde{\omega}\tau)}. $$ Our final step, as we did in the case of various types of damping, is to define $\gamma = b/(2m\omega_0)$ and rewrite our equations as $$ \frac{d^2x}{d\tau^2} + 2\gamma\frac{dx}{d\tau}+x(\tau) =\tilde{F}\cos{(\tilde{\omega}\tau)}. $$ This is the equation we will code below using the Euler-Cromer method. DeltaT = 0.001 #set up arrays tfinal = 20 # in years n = ceil(tfinal/DeltaT) # set up arrays for t, v, and x t = np.zeros(n) v = np.zeros(n) x = np.zeros(n) # Initial conditions as one-dimensional arrays of time x0 = sqrt(1./3.) v0 = 0.0 x[0] = x0 v[0] = v0 gamma = 0.0 Omegatilde = 8./sqrt(2.) Ftilde = 1.75 # Start integrating using Euler-Cromer's method for i in range(n-1): # Set up the acceleration # Here you could have defined your own function for this a = -2*gamma*v[i]-x[i]+Ftilde*cos(t[i]*Omegatilde) # update velocity, time and position v[i+1] = v[i] + DeltaT*a x[i+1] = x[i] + DeltaT*v[i+1] t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots() ax.set_ylabel('x[m]') ax.set_xlabel('t[s]') ax.plot(t, x) fig.tight_layout() save_fig("ForcedBlockEulerCromer") plt.show() In the above example we have focused on the Euler-Cromer method. This method has a local truncation error which is proportional to $\Delta t^2$ and thereby a global error which is proportional to $\Delta t$. We can improve this by using the Runge-Kutta family of methods. The widely popular Runge-Kutta to fourth order or just **RK4** has indeed a much better truncation error. The RK4 method has a global error which is proportional to $\Delta t$. Let us revisit this method and see how we can implement it for the above example. ## Differential Equations, Runge-Kutta methods Runge-Kutta (RK) methods are based on Taylor expansion formulae, but yield in general better algorithms for solutions of an ordinary differential equation. The basic philosophy is that it provides an intermediate step in the computation of $y_{i+1}$. To see this, consider first the following definitions <!-- Equation labels as ordinary links --> <div id="_auto16"></div> $$ \begin{equation} \frac{dy}{dt}=f(t,y), \label{_auto16} \tag{25} \end{equation} $$ and <!-- Equation labels as ordinary links --> <div id="_auto17"></div> $$ \begin{equation} y(t)=\int f(t,y) dt, \label{_auto17} \tag{26} \end{equation} $$ and <!-- Equation labels as ordinary links --> <div id="_auto18"></div> $$ \begin{equation} y_{i+1}=y_i+ \int_{t_i}^{t_{i+1}} f(t,y) dt. \label{_auto18} \tag{27} \end{equation} $$ To demonstrate the philosophy behind RK methods, let us consider the second-order RK method, RK2. The first approximation consists in Taylor expanding $f(t,y)$ around the center of the integration interval $t_i$ to $t_{i+1}$, that is, at $t_i+h/2$, $h$ being the step. Using the midpoint formula for an integral, defining $y(t_i+h/2) = y_{i+1/2}$ and $t_i+h/2 = t_{i+1/2}$, we obtain <!-- Equation labels as ordinary links --> <div id="_auto19"></div> $$ \begin{equation} \int_{t_i}^{t_{i+1}} f(t,y) dt \approx hf(t_{i+1/2},y_{i+1/2}) +O(h^3). \label{_auto19} \tag{28} \end{equation} $$ This means in turn that we have <!-- Equation labels as ordinary links --> <div id="_auto20"></div> $$ \begin{equation} y_{i+1}=y_i + hf(t_{i+1/2},y_{i+1/2}) +O(h^3). \label{_auto20} \tag{29} \end{equation} $$ However, we do not know the value of $y_{i+1/2}$. Here comes thus the next approximation, namely, we use Euler's method to approximate $y_{i+1/2}$. We have then <!-- Equation labels as ordinary links --> <div id="_auto21"></div> $$ \begin{equation} y_{(i+1/2)}=y_i + \frac{h}{2}\frac{dy}{dt}=y(t_i) + \frac{h}{2}f(t_i,y_i). \label{_auto21} \tag{30} \end{equation} $$ This means that we can define the following algorithm for the second-order Runge-Kutta method, RK2. 6 0 < < < ! ! M A T H _ B L O C K <!-- Equation labels as ordinary links --> <div id="_auto23"></div> $$ \begin{equation} k_2=hf(t_{i+1/2},y_i+k_1/2), \label{_auto23} \tag{32} \end{equation} $$ with the final value <!-- Equation labels as ordinary links --> <div id="_auto24"></div> $$ \begin{equation} y_{i+i}\approx y_i + k_2 +O(h^3). \label{_auto24} \tag{33} \end{equation} $$ The difference between the previous one-step methods is that we now need an intermediate step in our evaluation, namely $t_i+h/2 = t_{(i+1/2)}$ where we evaluate the derivative $f$. This involves more operations, but the gain is a better stability in the solution. The fourth-order Runge-Kutta, RK4, has the following algorithm 6 3 < < < ! ! M A T H _ B L O C K $$ k_3=hf(t_i+h/2,y_i+k_2/2)\hspace{0.5cm} k_4=hf(t_i+h,y_i+k_3) $$ with the final result $$ y_{i+1}=y_i +\frac{1}{6}\left( k_1 +2k_2+2k_3+k_4\right). $$ Thus, the algorithm consists in first calculating $k_1$ with $t_i$, $y_1$ and $f$ as inputs. Thereafter, we increase the step size by $h/2$ and calculate $k_2$, then $k_3$ and finally $k_4$. The global error goes as $O(h^4)$. However, at this stage, if we keep adding different methods in our main program, the code will quickly become messy and ugly. Before we proceed thus, we will now introduce functions that enbody the various methods for solving differential equations. This means that we can separate out these methods in own functions and files (and later as classes and more generic functions) and simply call them when needed. Similarly, we could easily encapsulate various forces or other quantities of interest in terms of functions. To see this, let us bring up the code we developed above for the simple sliding block, but now only with the simple forward Euler method. We introduce two functions, one for the simple Euler method and one for the force. Note that here the forward Euler method does not know the specific force function to be called. It receives just an input the name. We can easily change the force by adding another function. def ForwardEuler(v,x,t,n,Force): for i in range(n-1): v[i+1] = v[i] + DeltaT*Force(v[i],x[i],t[i]) x[i+1] = x[i] + DeltaT*v[i] t[i+1] = t[i] + DeltaT def SpringForce(v,x,t): # note here that we have divided by mass and we return the acceleration return -2*gamma*v-x+Ftilde*cos(t*Omegatilde) It is easy to add a new method like the Euler-Cromer def ForwardEulerCromer(v,x,t,n,Force): for i in range(n-1): a = Force(v[i],x[i],t[i]) v[i+1] = v[i] + DeltaT*a x[i+1] = x[i] + DeltaT*v[i+1] t[i+1] = t[i] + DeltaT and the Velocity Verlet method (be careful with time-dependence here, it is not an ideal method for non-conservative forces)) def VelocityVerlet(v,x,t,n,Force): for i in range(n-1): a = Force(v[i],x[i],t[i]) x[i+1] = x[i] + DeltaT*v[i]+0.5*a anew = Force(v[i],x[i+1],t[i+1]) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT Finally, we can now add the Runge-Kutta2 method via a new function def RK2(v,x,t,n,Force): for i in range(n-1): # Setting up k1 k1x = DeltaT*v[i] k1v = DeltaT*Force(v[i],x[i],t[i]) # Setting up k2 vv = v[i]+k1v*0.5 xx = x[i]+k1x*0.5 k2x = DeltaT*vv k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5) # Final result x[i+1] = x[i]+k2x v[i+1] = v[i]+k2v t[i+1] = t[i]+DeltaT Finally, we can now add the Runge-Kutta2 method via a new function def RK4(v,x,t,n,Force): for i in range(n-1): # Setting up k1 k1x = DeltaT*v[i] k1v = DeltaT*Force(v[i],x[i],t[i]) # Setting up k2 vv = v[i]+k1v*0.5 xx = x[i]+k1x*0.5 k2x = DeltaT*vv k2v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5) # Setting up k3 vv = v[i]+k2v*0.5 xx = x[i]+k2x*0.5 k3x = DeltaT*vv k3v = DeltaT*Force(vv,xx,t[i]+DeltaT*0.5) # Setting up k4 vv = v[i]+k3v xx = x[i]+k3x k4x = DeltaT*vv k4v = DeltaT*Force(vv,xx,t[i]+DeltaT) # Final result x[i+1] = x[i]+(k1x+2*k2x+2*k3x+k4x)/6. v[i+1] = v[i]+(k1v+2*k2v+2*k3v+k4v)/6. t[i+1] = t[i] + DeltaT The Runge-Kutta family of methods are particularly useful when we have a time-dependent acceleration. If we have forces which depend only the spatial degrees of freedom (no velocity and/or time-dependence), then energy conserving methods like the Velocity Verlet or the Euler-Cromer method are preferred. As soon as we introduce an explicit time-dependence and/or add dissipitave forces like friction or air resistance, then methods like the family of Runge-Kutta methods are well suited for this. The code below uses the Runge-Kutta4 methods. DeltaT = 0.001 #set up arrays tfinal = 10 # in years n = ceil(tfinal/DeltaT) # set up arrays for t, v, and x t = np.zeros(n) v = np.zeros(n) x = np.zeros(n) # Initial conditions (can change to more than one dim) x0 = 1.0 v0 = 0.0 x[0] = x0 v[0] = v0 gamma = 0.0 Omegatilde = 0.2 Ftilde = 1.0 # Start integrating using Euler's method # Note that we define the force function as a SpringForce RK4(v,x,t,n,SpringForce) # Plot position as function of time fig, ax = plt.subplots() ax.set_ylabel('x[m]') ax.set_xlabel('t[s]') ax.plot(t, x) fig.tight_layout() save_fig("ForcedBlockRK4") plt.show() <!-- !split --> ## Principle of Superposition and
) ) ] : merge["operation"].setValue( operation ) self.assertAlmostEqual( sampler["color"]["r"].getValue(), expected[0], msg=operation ) self.assertAlmostEqual( sampler["color"]["g"].getValue(), expected[1], msg=operation ) self.assertAlmostEqual( sampler["color"]["b"].getValue(), expected[2], msg=operation ) self.assertAlmostEqual( sampler["color"]["a"].getValue(), expected[3], msg=operation ) def testChannelRequest( self ) : a = GafferImage.Constant() a["color"].setValue( imath.Color4f( 0.1, 0.2, 0.3, 0.4 ) ) ad = GafferImage.DeleteChannels() ad["in"].setInput( a["out"] ) ad["mode"].setValue( GafferImage.DeleteChannels.Mode.Delete ) ad["channels"].setValue( "R" ) b = GafferImage.Constant() b["color"].setValue( imath.Color4f( 1.0, 0.3, 0.1, 0.2 ) ) bd = GafferImage.DeleteChannels() bd["in"].setInput( b["out"] ) bd["mode"].setValue( GafferImage.DeleteChannels.Mode.Delete ) bd["channels"].setValue( "G" ) merge = GafferImage.Merge() merge["in"][0].setInput( ad["out"] ) merge["in"][1].setInput( bd["out"] ) merge["operation"].setValue( GafferImage.Merge.Operation.Add ) sampler = GafferImage.ImageSampler() sampler["image"].setInput( merge["out"] ) sampler["pixel"].setValue( imath.V2f( 10 ) ) self.assertAlmostEqual( sampler["color"]["r"].getValue(), 0.0 + 1.0 ) self.assertAlmostEqual( sampler["color"]["g"].getValue(), 0.2 + 0.0 ) self.assertAlmostEqual( sampler["color"]["b"].getValue(), 0.3 + 0.1 ) self.assertAlmostEqual( sampler["color"]["a"].getValue(), 0.4 + 0.2 ) def testNonFlatThrows( self ) : deep = GafferImage.Empty() flat = GafferImage.Constant() merge = GafferImage.Merge() merge["in"][0].setInput( flat["out"] ) merge["in"][1].setInput( flat["out"] ) self.assertNotEqual( GafferImage.ImageAlgo.imageHash( merge["out"] ), GafferImage.ImageAlgo.imageHash( flat["out"] ) ) merge["in"][0].setInput( deep["out"] ) six.assertRaisesRegex( self, RuntimeError, 'Deep data not supported in input "in.in0"', GafferImage.ImageAlgo.image, merge["out"] ) merge["in"][0].setInput( flat["out"] ) merge["in"][1].setInput( deep["out"] ) six.assertRaisesRegex( self, RuntimeError, 'Deep data not supported in input "in.in1"', GafferImage.ImageAlgo.image, merge["out"] ) def testDefaultFormat( self ) : a = GafferImage.Constant() a["format"].setValue( GafferImage.Format( 100, 200 ) ) m = GafferImage.Merge() m["in"][1].setInput( a["out"] ) with Gaffer.Context() as c : GafferImage.FormatPlug().setDefaultFormat( c, GafferImage.Format( 1000, 2000 ) ) self.assertEqual( m["out"]["format"].getValue(), GafferImage.Format( 1000, 2000 ) ) def testDataWindowWhenBNotConnected( self ) : a = GafferImage.Constant() a["format"].setValue( GafferImage.Format( 100, 200 ) ) m = GafferImage.Merge() m["in"][1].setInput( a["out"] ) self.assertEqual( m["out"]["dataWindow"].getValue(), a["out"]["dataWindow"].getValue() ) # Make sure we don't fail by pulling tiles outside the data window when merging images with # misaligned data def testTilesOutsideDataWindow( self ) : r = GafferImage.ImageReader() r["fileName"].setValue( self.checkerPath ) o = GafferImage.Offset() o["in"].setInput( r["out"] ) o["offset"].setValue( imath.V2i( -10 ) ) merge = GafferImage.Merge() merge["in"][0].setInput( r["out"] ) merge["in"][1].setInput( o["out"] ) GafferImage.ImageAlgo.image( merge["out"] ) def testPassthroughs( self ) : ts = GafferImage.ImagePlug.tileSize() checkerboardB = GafferImage.Checkerboard() checkerboardB["format"]["displayWindow"].setValue( imath.Box2i( imath.V2i( 0 ), imath.V2i( 4096 ) ) ) checkerboardA = GafferImage.Checkerboard() checkerboardA["format"]["displayWindow"].setValue( imath.Box2i( imath.V2i( 0 ), imath.V2i( 4096 ) ) ) checkerboardA["size"].setValue( imath.V2f( 5 ) ) cropB = GafferImage.Crop() cropB["in"].setInput( checkerboardB["out"] ) cropB["area"].setValue( imath.Box2i( imath.V2i( ts * 0.5 ), imath.V2i( ts * 4.5 ) ) ) cropB["affectDisplayWindow"].setValue( False ) cropA = GafferImage.Crop() cropA["in"].setInput( checkerboardA["out"] ) cropA["area"].setValue( imath.Box2i( imath.V2i( ts * 2.5 ), imath.V2i( ts * 6.5 ) ) ) cropA["affectDisplayWindow"].setValue( False ) merge = GafferImage.Merge() merge["in"][0].setInput( cropB["out"] ) merge["in"][1].setInput( cropA["out"] ) merge["operation"].setValue( 8 ) sampleTileOrigins = { "insideBoth" : imath.V2i( ts * 3, ts * 3 ), "outsideBoth" : imath.V2i( ts * 5, ts ), "outsideEdgeB" : imath.V2i( ts, 0 ), "insideB" : imath.V2i( ts, ts ), "internalEdgeB" : imath.V2i( ts * 4, ts ), "internalEdgeA" : imath.V2i( ts * 5, ts * 2 ), "insideA" : imath.V2i( ts * 5, ts * 5 ), "outsideEdgeA" : imath.V2i( ts * 6, ts * 5 ) } for opName, onlyA, onlyB in [ ( "Atop", "black", "passB" ), ( "Divide", "operate", "black" ), ( "Out", "passA", "black" ), ( "Multiply", "black", "black" ), ( "Over", "passA", "passB" ), ( "Subtract", "passA", "operate" ), ( "Difference", "operate", "operate" ) ]: op = getattr( GafferImage.Merge.Operation, opName ) merge["operation"].setValue( op ) results = {} for name, tileOrigin in sampleTileOrigins.items(): # We want to check the value pass through code independently # of the hash passthrough code, which we can do by dropping # the value cached and evaluating values first Gaffer.ValuePlug.clearCache() with Gaffer.Context() as c : c["image:tileOrigin"] = tileOrigin c["image:channelName"] = "R" data = merge["out"]["channelData"].getValue( _copy = False ) if data.isSame( GafferImage.ImagePlug.blackTile( _copy = False ) ): computeMode = "black" elif data.isSame( cropB["out"]["channelData"].getValue( _copy = False ) ): computeMode = "passB" elif data.isSame( cropA["out"]["channelData"].getValue( _copy = False ) ): computeMode = "passA" else: computeMode = "operate" h = merge["out"]["channelData"].hash() if h == GafferImage.ImagePlug.blackTile().hash(): hashMode = "black" elif h == cropB["out"]["channelData"].hash(): hashMode = "passB" elif h == cropA["out"]["channelData"].hash(): hashMode = "passA" else: hashMode = "operate" self.assertEqual( hashMode, computeMode ) results[name] = hashMode self.assertEqual( results["insideBoth"], "operate" ) self.assertEqual( results["outsideBoth"], "black" ) self.assertEqual( results["outsideEdgeB"], onlyB ) self.assertEqual( results["insideB"], onlyB ) self.assertEqual( results["outsideEdgeA"], onlyA ) self.assertEqual( results["insideA"], onlyA ) if onlyA == "black" or onlyB == "black": self.assertEqual( results["internalEdgeB"], onlyB ) self.assertEqual( results["internalEdgeA"], onlyA ) else: self.assertEqual( results["internalEdgeB"], "operate" ) self.assertEqual( results["internalEdgeA"], "operate" ) # This somewhat sloppy test cobbled together from a Gaffer scene tests a bunch of the weird cases # for how data windows can overlap each other and the tile. It was added because I'm experimenting # with an approach for treating the tile in regions, which does add a little bit of arithmetic that # I could get wrong def runBoundaryCorrectness( self, scale ): testMerge = GafferImage.Merge() subImageNodes = [] for checkSize, col, bound in [ ( 2, ( 0.672299981, 0.672299981, 0 ), ((11, 7), (61, 57)) ), ( 4, ( 0.972599983, 0.493499994, 1 ), ((9, 5), (59, 55)) ), ( 6, ( 0.310799986, 0.843800008, 1 ), ((0, 21), (1024, 41)) ), ( 8, ( 0.958999991, 0.672299981, 0.0296 ), ((22, 0), (42, 1024)) ), ( 10, ( 0.950900018, 0.0899000019, 0.235499993 ), ((7, 10), (47, 50)) ), ]: checkerboard = GafferImage.Checkerboard() checkerboard["format"].setValue( GafferImage.Format( 1024 * scale, 1024 * scale, 1.000 ) ) checkerboard["size"].setValue( imath.V2f( checkSize * scale ) ) checkerboard["colorA"].setValue( imath.Color4f( 0.1 * col[0], 0.1 * col[1], 0.1 * col[2], 0.3 ) ) checkerboard["colorB"].setValue( imath.Color4f( 0.5 * col[0], 0.5 * col[1], 0.5 * col[2], 0.7 ) ) crop = GafferImage.Crop( "Crop" ) crop["in"].setInput( checkerboard["out"] ) crop["area"].setValue( imath.Box2i( imath.V2i( scale * bound[0][0], scale * bound[0][1] ), imath.V2i( scale * bound[1][0], scale * bound[1][1] ) ) ) crop["affectDisplayWindow"].setValue( False ) subImageNodes.append( checkerboard ) subImageNodes.append( crop ) testMerge["in"][-1].setInput( crop["out"] ) testMerge["expression"] = Gaffer.Expression() testMerge["expression"].setExpression( 'parent["operation"] = context[ "loop:index" ]' ) inverseScale = GafferImage.ImageTransform() inverseScale["in"].setInput( testMerge["out"] ) inverseScale["filter"].setValue( "box" ) inverseScale["transform"]["scale"].setValue( imath.V2f( 1.0/scale ) ) crop1 = GafferImage.Crop() crop1["in"].setInput( inverseScale["out"] ) crop1["area"].setValue( imath.Box2i( imath.V2i( 0, 0 ), imath.V2i( 64, 64 ) ) ) loopInit = GafferImage.Constant() loopInit["format"].setValue( GafferImage.Format( 896, 64, 1.000 ) ) loopInit["color"].setValue( imath.Color4f( 0 ) ) loopOffset = GafferImage.Offset() loopOffset["in"].setInput( crop1["out"] ) loopOffset["expression"] = Gaffer.Expression() loopOffset["expression"].setExpression( 'parent["offset"]["x"] = 64 * context[ "loop:index" ]' ) loopMerge = GafferImage.Merge() loopMerge["in"][1].setInput( loopOffset["out"] ) loop = Gaffer.Loop() loop.setup( GafferImage.ImagePlug( "in", ) ) loop["iterations"].setValue( 14 ) loop["in"].setInput( loopInit["out"] ) loop["next"].setInput( loopMerge["out"] ) loopMerge["in"][0].setInput( loop["previous"] ) # Uncomment for debug #imageWriter = GafferImage.ImageWriter( "ImageWriter" ) #imageWriter["in"].setInput( loop["out"] ) #imageWriter['openexr']['dataType'].setValue( "float" ) #imageWriter["fileName"].setValue( "/tmp/mergeBoundaries.exr" ) #imageWriter.execute() reader = GafferImage.ImageReader() reader["fileName"].setValue( self.mergeBoundariesRefPath ) self.assertImagesEqual( loop["out"], reader["out"], ignoreMetadata = True, maxDifference = 1e-5 if scale > 1 else 0 ) def testBoundaryCorrectness( self ): self.runBoundaryCorrectness( 1 ) self.runBoundaryCorrectness( 2 ) self.runBoundaryCorrectness( 4 ) self.runBoundaryCorrectness( 8 ) self.runBoundaryCorrectness( 16 ) self.runBoundaryCorrectness( 32 ) def testEmptyDataWindowMerge( self ): constant = GafferImage.Constant() constant["format"].setValue( GafferImage.Format( 512, 512, 1.000 ) ) constant["color"].setValue( imath.Color4f( 1 ) ) offset = GafferImage.Offset() offset["in"].setInput( constant["out"] ) offset["offset"].setValue( imath.V2i( -1024 ) ) emptyCrop = GafferImage.Crop() emptyCrop["in"].setInput( constant["out"] ) emptyCrop["area"].setValue( imath.Box2i( imath.V2i( -10 ), imath.V2i( -100 ) ) ) merge = GafferImage.Merge() merge["in"][0].setInput( offset["out"] ) merge["in"][1].setInput( emptyCrop["out"] ) self.assertEqual( merge["out"].dataWindow(), imath.Box2i( imath.V2i( -1024 ), imath.V2i( -512 ) ) ) def mergePerf( self, operation, mismatch ): r = GafferImage.Checkerboard( "Checkerboard" ) r["format"].setValue( GafferImage.Format( 4096, 3112, 1.000 ) ) # Make the size of the checkerboard not a perfect multiple of tile size # in case we ever fix Checkerboard to notice when tiles are repeated # and return an identical hash ( which would invalidate this performance # test ) r["size"].setValue( imath.V2f( 64.01 ) ) alphaShuffle = GafferImage.Shuffle() alphaShuffle["in"].setInput( r["out"] ) alphaShuffle["channels"].addChild( GafferImage.Shuffle.ChannelPlug( "A", "R" ) ) transform = GafferImage.Offset() transform["in"].setInput( alphaShuffle["out"] ) if mismatch: transform["offset"].setValue( imath.V2i( 4000, 3000 ) ) else: transform["offset"].setValue( imath.V2i( 26, 42 ) ) merge = GafferImage.Merge() merge["operation"].setValue( operation ) merge["in"][0].setInput( alphaShuffle["out"] ) merge["in"][1].setInput( transform["out"] ) # Precache upstream network, we're only interested in the performance of Merge GafferImageTest.processTiles( alphaShuffle["out"] ) GafferImageTest.processTiles( transform["out"] ) with GafferTest.TestRunner.PerformanceScope() : GafferImageTest.processTiles( merge["out"] ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testAddPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Add, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testAddMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Add, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testAtopPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Atop, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testAtopMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Atop, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testDividePerf( self ): self.mergePerf( GafferImage.Merge.Operation.Divide, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testDivideMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Divide, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testInPerf( self ): self.mergePerf( GafferImage.Merge.Operation.In, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testInMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.In, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testOutPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Out, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testOutMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Out, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testMaskPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Mask, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testMaskMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Mask, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testOutPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Out, False ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform" ) @GafferTest.TestRunner.PerformanceTestMethod( repeat = 5) def testOutMismatchPerf( self ): self.mergePerf( GafferImage.Merge.Operation.Out, True ) @unittest.skipIf( GafferTest.inCI(), "Performance not relevant on CI platform"
import psycopg2 import re import json from MedTAG_sket_dock_App.models import * import os import pandas as pd import numpy from psycopg2.extensions import register_adapter, AsIs def addapt_numpy_float64(numpy_float64): return AsIs(numpy_float64) def addapt_numpy_int64(numpy_int64): return AsIs(numpy_int64) register_adapter(numpy.float64, addapt_numpy_float64) register_adapter(numpy.int64, addapt_numpy_int64) from django.db.models import Count from django.db import transaction import datetime from MedTAG_sket_dock_App.utils import * def check_uploaded_files(files): """This method checks whether the files uploaded by the user to copy the ground-truths are well formatted""" json_resp = {} json_resp['message'] = '' for i in range(len(files)): # Error if the file is not csv if not files[i].name.endswith('csv'): json_resp['message'] = 'ERROR - ' + files[i].name + ' - The file must be .csv' return json_resp try: df = pd.read_csv(files[i]) df = df.where(pd.notnull(df), None) df = df.reset_index(drop=True) # Useful if the csv includes only commas except Exception as e: print(e) json_resp['message'] = 'ERROR - ' + files[ i].name + ' - An error occurred while parsing the csv. Check if it is well formatted. Check if it contains as many columns as they are declared in the header.' return json_resp else: # check if colunns are allowed and without duplicates cols = list(df.columns) labels = ['username', 'annotation_mode', 'id_report', 'language', 'batch', 'institute', 'usecase', 'label'] mentions = ['username', 'annotation_mode', 'id_report', 'language', 'batch', 'institute', 'usecase', 'start', 'stop', 'mention_text'] concepts = ['username', 'annotation_mode', 'id_report', 'language', 'batch', 'institute', 'usecase', 'concept_url', 'concept_name', 'area'] linking = ['username', 'annotation_mode', 'id_report', 'language', 'batch', 'institute', 'usecase', 'start', 'stop', 'mention_text', 'concept_name', 'concept_url', 'area'] if set(cols) != set(labels) and set(cols) != set(mentions) and set(cols) != set(concepts) and set(cols) != set(linking): json_resp['message'] = 'ERROR - ' + files[ i].name + ' - The set of columns you inserted in the csv does not correspond to those we ask. ' \ 'Check the examples.' return json_resp if 'usecase' in cols: df['usecase'] = df['usecase'].str.lower() # Check if the csv is empty with 0 rows if df.shape[0] == 0: json_resp['message'] = 'ERROR - ' + files[ i].name + ' - You must provide at least a row.' return json_resp if len(files) > 0: if json_resp['message'] == '': json_resp['message'] = 'Ok' return json_resp def upload_files(files,user_to,overwrite): """This method handles the upload of csv files to copy th annotations from""" json_resp = {'message':'Ok'} mode_rob = NameSpace.objects.get(ns_id='Robot') mode_hum = NameSpace.objects.get(ns_id='Human') print(user_to) username_rob = User.objects.get(username='Robot_user', ns_id=mode_rob) try: with transaction.atomic(): for i in range(len(files)): df = pd.read_csv(files[i]) df = df.where(pd.notnull(df), None) df = df.reset_index(drop=True) # Useful if the csv includes only commas df.sort_values(['id_report','language','annotation_mode']) cols = list(df.columns) labels = ['username', 'annotation_mode', 'id_report', 'language','batch', 'institute', 'usecase', 'label'] mentions = ['username', 'annotation_mode', 'id_report', 'language','batch', 'institute', 'usecase', 'start', 'stop', 'mention_text'] concepts = ['username', 'annotation_mode', 'id_report', 'language','batch', 'institute', 'usecase', 'concept_url', 'concept_name', 'area'] linking = ['username', 'annotation_mode', 'id_report', 'language','batch', 'institute', 'usecase', 'start', 'stop', 'mention_text', 'concept_name', 'concept_url', 'area'] for i, g in df.groupby(['id_report','language','annotation_mode']): count_rows = g.shape[0] deleted_mentions = False if df.annotation_mode.unique()[0] == 'Manual': a = 'Human' else: a = 'Robot' report_cur = Report.objects.get(id_report = str(g.id_report.unique()[0]), language = g.language.unique()[0] ) mode = NameSpace.objects.get(ns_id =a) anno_mode = mode if a == 'Robot' and GroundTruthLogFile.objects.filter(username = username_rob).count() == 0: json_resp = {'message':'automatic missing'} return json_resp report = report_cur g = g.reset_index() action = '' user = User.objects.get(username=user_to, ns_id=mode) if set(cols) == set(labels): user_to_gt = GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='labels') if overwrite == False: if mode.ns_id == 'Robot': if not user_to_gt.exists(): Associate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() else: GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='labels').delete() Associate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() elif set(cols) == set(mentions): user_to_gt = GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='mentions') robot_gt = GroundTruthLogFile.objects.filter(username=username_rob, ns_id=mode_rob, id_report=report, language=report.language, gt_type='mentions') # ins_time = '' # if robot_gt.exists(): # rob_first_gt = robot_gt.first() # ins_time = rob_first_gt.insertion_time if overwrite == False: if mode.ns_id == 'Robot': if not user_to_gt.exists(): # user_to_gt_first = user_to_gt.first() # if user_to_gt_first.insertion_time == ins_time: # GroundTruthLogFile.objects.filter(username=user, ns_id=mode, # id_report=report, # language=report.language, # gt_type='mentions').delete() if Linked.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).exists(): GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concept-mention').delete() GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').delete() Annotate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() links = Linked.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language) for e in links: concept = e.concept_url Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, concept_url=concept).delete() links.delete() else: GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='mentions').delete() if Linked.objects.filter(username=user, ns_id=mode,id_report=report,language=report.language).exists(): GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concept-mention').delete() GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').delete() Annotate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() links = Linked.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language) for e in links: concept = e.concept_url Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, concept_url=concept).delete() links.delete() elif set(cols) == set(concepts): user_to_gt = GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts') robot_gt = GroundTruthLogFile.objects.filter(username=username_rob, ns_id=mode_rob, id_report=report, language=report.language, gt_type='concepts') # ins_time = '' # if robot_gt.exists(): # rob_first_gt = robot_gt.first() # ins_time = rob_first_gt.insertion_time if overwrite == False: if mode.ns_id == 'Robot': if not user_to_gt.exists(): # user_to_gt_first = user_to_gt.first() # if user_to_gt_first.insertion_time == ins_time: # GroundTruthLogFile.objects.filter(username=user, ns_id=mode, # id_report=report, # language=report.language, # gt_type='concepts').delete() Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() else: GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').delete() Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() elif set(cols) == set(linking): user_to_gt = GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concept-mention') if overwrite == False: if mode.ns_id == 'Robot': if not user_to_gt.exists(): GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').delete() GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='mentions').delete() links = Linked.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language) for e in links: concept = e.concept_url area = e.name Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, name=area, concept_url=concept).delete() links.delete() Annotate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() else: GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').delete() GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concept-mention').delete() GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='mentions').delete() links = Linked.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language) for ll in links: concept = ll.concept_url area = ll.name Contains.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, concept_url=concept,name = area).delete() Annotate.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language).delete() links.delete() for i in range(count_rows): usecase = str(df.loc[i, 'usecase']) usecase_obj = UseCase.objects.get(name=usecase) mode = str(g.loc[i, 'annotation_mode']) id_report = str(g.loc[i, 'id_report']) language = str(g.loc[i, 'language']) institute = str(g.loc[i, 'institute']) # user_from = str(g.loc[i, 'username']) if mode == 'Manual': mode = 'Human' elif mode == 'Automatic': mode = 'Robot' # username_from = User.objects.get(username=user_from, ns_id=mode) mode = NameSpace.objects.get(ns_id = mode) report = Report.objects.get(id_report=id_report, language=language, institute=institute) if set(cols) == set(labels): label = AnnotationLabel.objects.get(label = str(g.loc[i, 'label']),name = usecase_obj) if (overwrite == False and not GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='labels').exists()) or overwrite == True: if not Associate.objects.filter(username=user, ns_id=mode, id_report=report, label=label,seq_number=label.seq_number, language=report.language).exists(): Associate.objects.create(username=user, ns_id=mode, id_report=report, label=label, seq_number=label.seq_number, language=report.language, insertion_time=Now()) action = 'labels' elif set(cols) == set(mentions): mention = Mention.objects.get(id_report = report, language = language, start = int(g.loc[i, 'start']), stop = int(g.loc[i, 'stop'])) if (overwrite == False and not GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='mentions').exists()) or overwrite == True: if not Annotate.objects.filter(username=user, ns_id=mode, id_report=report,start = mention,stop = mention.stop, language=report.language).exists(): Annotate.objects.create(username=user, ns_id=mode, id_report=report,start = mention,stop = mention.stop, language=report.language, insertion_time=Now()) action = 'mentions' elif set(cols) == set(concepts): concept = Concept.objects.get(concept_url = str(g.loc[i, 'concept_url'])) area = SemanticArea.objects.get(name=str(g.loc[i, 'area'])) if (overwrite == False and not GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concepts').exists()) or overwrite == True: if not Contains.objects.filter(username = user, ns_id =mode, id_report = report,concept_url = concept,name = area, language = report.language).exists(): Contains.objects.create(username = user, ns_id =mode, id_report = report,concept_url = concept,name = area, language = report.language,insertion_time = Now()) action = 'concepts' elif set(cols) == set(linking): concept = Concept.objects.get(concept_url = str(g.loc[i, 'concept_url'])) area = SemanticArea.objects.get(name=str(g.loc[i, 'area'])) mention = Mention.objects.get(id_report=report, language=language,start=int(g.loc[i, 'start']), stop=int(g.loc[i, 'stop'])) if (overwrite == False and not GroundTruthLogFile.objects.filter(username=user, ns_id=mode, id_report=report, language=report.language, gt_type='concept-mention').exists()) or overwrite == True: if not deleted_mentions: Annotate.objects.filter(username=user, ns_id=mode, id_report=report,language=report.language).delete() deleted_mentions = True a = Annotate.objects.filter(username = user, ns_id = mode, id_report = report, language = report.language,start=mention,stop = mention.stop) c = Contains.objects.filter(username = user, ns_id = mode, id_report = report,concept_url = concept,name = area, language = report.language) l = Linked.objects.filter(username = user, ns_id = mode, id_report = report,concept_url = concept,name = area, language = report.language,start=mention,stop = mention.stop) if not a.exists(): Annotate.objects.create(username=user, ns_id=mode, id_report=report, language=report.language, start=mention, stop=mention.stop, insertion_time = Now()) if not c.exists(): Contains.objects.create(username = user, ns_id = mode, id_report = report,concept_url = concept,name = area, language = report.language,insertion_time = Now()) if not l.exists(): Linked.objects.create(username = user, ns_id = mode, id_report = report,concept_url = concept,name = area, language = report.language,start=mention,stop = mention.stop,insertion_time = Now()) action = 'concept-mention' if action != '': # gt_json = serialize_gt(action, usecase, user_to, report_cur.id_report, report_cur.language, # anno_mode) # GroundTruthLogFile.objects.create(username=user, ns_id=anno_mode, gt_type=action,gt_json=gt_json, insertion_time=Now(),id_report=report_cur, language=language) if action == 'concept-mention': gt_json = serialize_gt('mentions', usecase, user_to, report_cur.id_report, report_cur.language, anno_mode) GroundTruthLogFile.objects.create(username=user, ns_id=anno_mode, gt_type='mentions', gt_json=gt_json, insertion_time=Now(), id_report=report_cur, language=language) gt_json = serialize_gt('concepts', usecase, user_to, report_cur.id_report, report_cur.language, anno_mode) GroundTruthLogFile.objects.create(username=user,
<filename>colormaps/twilights512_colormap.py from numpy import array # **************************************************************************************** # 512-level colormap created by make_colormap utility from file twilight.png # **************************************************************************************** twilights512 = array( [ [43, 21, 53], [43, 21, 53], [44, 20, 54], [44, 20, 54], [45, 20, 55], [45, 20, 55], [46, 20, 56], [46, 20, 57], [47, 20, 58], [47, 20, 58], [48, 19, 60], [48, 19, 61], [48, 19, 62], [49, 19, 63], [49, 20, 64], [49, 20, 64], [50, 20, 65], [51, 20, 66], [52, 20, 67], [52, 20, 68], [53, 21, 71], [54, 21, 72], [55, 21, 74], [56, 21, 75], [57, 22, 76], [57, 22, 76], [57, 22, 80], [58, 22, 81], [59, 23, 82], [59, 23, 82], [61, 23, 86], [62, 23, 87], [63, 24, 89], [63, 24, 90], [64, 25, 90], [64, 25, 91], [66, 26, 95], [67, 27, 96], [67, 27, 96], [67, 27, 98], [68, 27, 99], [70, 28, 103], [70, 28, 104], [70, 29, 106], [71, 30, 108], [71, 30, 109], [73, 32, 113], [73, 32, 114], [75, 33, 116], [75, 33, 116], [76, 35, 119], [76, 35, 120], [77, 37, 122], [77, 37, 122], [78, 38, 123], [78, 38, 124], [79, 40, 128], [79, 40, 128], [80, 41, 129], [80, 41, 130], [81, 44, 134], [81, 44, 134], [82, 46, 136], [82, 46, 136], [82, 47, 138], [82, 47, 138], [83, 49, 140], [84, 50, 141], [84, 52, 144], [84, 52, 144], [85, 54, 146], [85, 54, 146], [85, 56, 148], [85, 56, 148], [86, 57, 149], [86, 57, 149], [86, 60, 151], [86, 61, 152], [87, 62, 152], [87, 62, 152], [88, 64, 154], [88, 65, 155], [88, 66, 156], [88, 66, 156], [88, 69, 157], [88, 70, 158], [89, 71, 159], [89, 72, 160], [89, 74, 161], [89, 75, 161], [89, 76, 162], [89, 76, 162], [90, 79, 163], [91, 79, 164], [91, 80, 165], [91, 81, 166], [91, 82, 167], [91, 83, 167], [91, 84, 167], [91, 85, 167], [92, 86, 168], [92, 87, 169], [92, 90, 170], [92, 91, 170], [93, 92, 171], [93, 93, 171], [93, 94, 172], [93, 94, 172], [94, 96, 174], [95, 97, 174], [95, 97, 174], [95, 99, 175], [95, 99, 175], [95, 101, 176], [95, 101, 176], [95, 102, 176], [96, 103, 176], [96, 106, 177], [96, 106, 177], [97, 108, 178], [97, 108, 178], [98, 109, 178], [98, 110, 178], [98, 113, 179], [98, 113, 179], [100, 115, 180], [100, 115, 180], [100, 116, 181], [101, 118, 181], [101, 118, 181], [102, 120, 182], [102, 120, 182], [103, 122, 182], [103, 122, 182], [103, 124, 182], [104, 125, 182], [105, 127, 183], [105, 128, 183], [106, 129, 184], [106, 129, 184], [107, 131, 184], [107, 131, 184], [108, 133, 185], [108, 133, 185], [110, 135, 186], [110, 135, 186], [110, 136, 186], [110, 136, 186], [111, 137, 186], [112, 138, 186], [113, 141, 187], [114, 142, 187], [115, 143, 187], [116, 144, 187], [117, 145, 187], [117, 146, 187], [118, 147, 188], [118, 148, 188], [119, 149, 188], [120, 149, 188], [121, 151, 188], [122, 151, 188], [123, 153, 189], [123, 153, 189], [124, 153, 190], [124, 153, 190], [125, 154, 190], [126, 155, 190], [128, 157, 191], [129, 158, 191], [130, 159, 191], [131, 160, 191], [132, 161, 191], [133, 162, 191], [135, 163, 192], [135, 164, 192], [136, 165, 192], [137, 166, 192], [138, 167, 192], [139, 168, 192], [140, 169, 193], [140, 169, 193], [143, 170, 193], [144, 171, 193], [144, 171, 193], [146, 173, 195], [146, 173, 195], [148, 175, 195], [148, 175, 195], [151, 177, 195], [151, 177, 195], [153, 179, 196], [154, 179, 196], [156, 180, 196], [156, 180, 196], [158, 182, 197], [159, 182, 197], [161, 184, 198], [161, 184, 198], [163, 186, 198], [164, 186, 198], [166, 187, 199], [167, 187, 199], [169, 189, 200], [169, 189, 201], [171, 191, 201], [172, 191, 201], [174, 192, 202], [175, 192, 202], [177, 194, 203], [178, 194, 203], [180, 195, 204], [180, 195, 204], [181, 196, 204], [185, 198, 206], [186, 198, 206], [188, 200, 207], [188, 200, 207], [189, 202, 207], [190, 202, 207], [192, 203, 208], [193, 204, 209], [195, 205, 210], [196, 205, 210], [198, 206, 211], [199, 207, 211], [200, 208, 212], [200, 208, 213], [202, 209, 214], [203, 209, 214], [205, 210, 215], [206, 210, 215], [207, 211, 215], [207, 211, 215], [209, 212, 217], [210, 213, 218], [211, 214, 218], [212, 214, 218], [213, 214, 219], [214, 214, 219], [215, 215, 220], [216, 215, 220], [217, 216, 222], [217, 216, 222], [218, 216, 222], [218, 216, 222], [218, 216, 222], [219, 216, 222], [220, 217, 223], [221, 217, 223], [222, 217, 224], [222, 217, 224], [223, 217, 225], [223, 217, 225], [223, 216, 225], [223, 216, 225], [223, 216, 224], [223, 216, 224], [223, 216, 223], [223, 216, 223], [223, 216, 223], [223, 216, 222], [223, 216, 222], [222, 215, 221], [222, 215, 221], [222, 215, 220], [222, 215, 219], [221, 214, 217], [221, 214, 216], [221, 213, 215], [221, 212, 214], [220, 211, 213], [220, 211, 212], [220, 210, 211], [220, 210, 210], [219, 209, 208], [219, 208, 207], [218, 207, 205], [218, 207, 204], [217, 206, 203], [217, 205, 202], [216, 204, 201], [216, 203, 200], [215, 202, 197], [215, 201, 196], [214, 200, 194], [214, 199, 193], [213, 198, 191], [213, 198, 190], [212, 196, 188], [212, 195, 187], [211, 194, 184], [210, 194, 183], [210, 192, 182], [210, 192, 182], [208, 191, 179], [208, 191, 178], [208, 190, 177], [208, 190, 177], [207, 188, 172], [206, 185, 169], [206, 185, 168], [205, 183, 166], [205, 183, 165], [204, 181, 162], [203, 180, 161], [202, 178, 160], [202, 178, 159], [202, 176, 157], [202, 176, 156], [201, 174, 153], [201, 173, 152], [199, 171, 150], [199, 171, 149], [199, 169, 147], [199, 169, 146], [198, 167, 144], [198, 166, 143], [198, 164, 141], [198, 164, 140], [196, 162, 138], [196, 162, 137], [195, 160, 135], [195, 159, 135], [195, 157, 133], [195, 157, 132], [194, 156, 130], [194, 155, 129], [194, 154, 127], [194, 154, 127], [193, 153, 126], [192, 150, 124], [192, 150, 123], [192, 149, 122], [192, 148, 121], [191, 145, 118], [191, 144, 118], [191, 143, 117], [190, 142, 116], [189, 141, 115], [189, 140, 114], [188, 138, 113], [188, 138, 113], [188, 137, 112], [188, 136, 111], [187, 133, 109], [187, 132, 108], [186, 131, 107], [186, 131, 106], [185, 129, 105], [185, 128, 104], [184, 127, 103], [184, 126, 102], [183, 124, 101], [183, 123, 101], [182, 122, 100], [182, 121, 99], [182, 119, 98], [182, 118, 98], [181, 117, 97], [181, 117, 97], [180, 116, 96], [180, 115, 96], [178, 113, 94], [178, 112, 94], [177, 111, 93], [177, 111, 93], [176, 109, 91], [176, 108, 91], [175, 106, 91], [175, 106, 91], [174, 105, 90], [174, 105, 90], [173, 102, 89], [173, 101, 89], [171, 99, 88], [171, 99, 88], [170, 97, 87], [170, 97, 87], [169, 96, 86], [169, 95, 86], [168, 93, 85], [168, 93, 85], [167, 91, 85], [165, 89, 84], [165, 89, 84], [163, 87, 84], [163, 86, 84], [161, 84, 83], [161, 84, 83], [160, 82, 82], [160, 82, 82], [159, 81, 82], [159, 81, 82], [157, 80, 82], [157, 79, 82], [155, 77, 81], [155, 76, 81], [155, 75, 81], [155, 75, 81], [153, 73, 81], [152, 72, 81], [150, 70, 80], [150, 70, 80], [150, 69, 80], [149, 68, 80], [148, 67, 80], [147, 66, 80], [147, 66, 80], [146, 65, 80], [145, 64, 80], [144, 63, 80], [144, 62, 80], [143, 61, 80], [142, 60, 79], [141, 59, 79], [140, 58, 79], [139, 57, 79], [138, 57, 79], [137, 56, 79], [136, 55,
import os import re import cv2 import sys import glob import json import shutil import numpy as np import torch from PIL import Image from easydict import EasyDict from torchvision.transforms import transforms # Profile def load_profile(filepath): """ Load experiment profile as EasyDict :param filepath: path to profile :type filepath: str :return: hyper-parameters :rtype: EasyDict """ if os.path.exists(filepath): with open(filepath) as f: return EasyDict(json.load(f)) # Device def get_devices(devices, verbose=True): """ Get devices for running model :param devices: list of devices from profile :type devices: list :param verbose: print log :type verbose: bool :return: list of usable devices according to desired and available hardware :rtype: list[str] """ def parse_cuda_device(device): """ Parse device into device id :param device: given device :type device: str or int :return: device id :rtype: int """ origin = str(device) if isinstance(device, str) and re.search('cuda:([\d]+)', device): device = int(re.findall('cuda:([\d]+)', device)[0]) if isinstance(device, int): if 0 <= device <= torch.cuda.device_count() - 1: return device _print('[Builder] Incorrect device "{}"'.format(origin), verbose=verbose) return use_cpu = any([d.find('cpu') >= 0 for d in devices]) use_cuda = any([(d.find('cuda') >= 0 or isinstance(d, int)) for d in devices]) assert not (use_cpu and use_cuda), 'CPU and GPU cannot be mixed.' if use_cuda: devices = [parse_cuda_device(d) for d in devices] devices = [d for d in devices if d is not None] if len(devices) == 0: _print('[Builder] No available GPU found, use CPU only', verbose=verbose) devices = ['cpu'] return devices # Logger class OutputLogger(object): """Output logger""" def __init__(self): self.file = None self.buffer = '' def set_log_file(self, filename, mode='wt'): assert self.file is None self.file = open(filename, mode) if self.buffer is not None: self.file.write(self.buffer) self.buffer = None def write(self, data): if self.file is not None: self.file.write(data) if self.buffer is not None: self.buffer += data def flush(self): if self.file is not None: self.file.flush() class TeeOutputStream(object): """Redirect output stream""" def __init__(self, child_streams, autoflush=False): self.child_streams = child_streams self.autoflush = autoflush def write(self, data): if isinstance(data, bytes): data = data.decode('utf-8') for stream in self.child_streams: stream.write(data) if self.autoflush: self.flush() def flush(self): for stream in self.child_streams: stream.flush() output_logger = None def init_output_logging(): """ Initialize output logger """ global output_logger if output_logger is None: output_logger = OutputLogger() sys.stdout = TeeOutputStream([sys.stdout, output_logger], autoflush=True) sys.stderr = TeeOutputStream([sys.stderr, output_logger], autoflush=True) def set_output_log_file(filename, mode='wt'): """ Set file name of output log :param filename: file name of log :type filename: str :param mode: the mode in which the file is opened :type mode: str """ if output_logger is not None: output_logger.set_log_file(filename, mode) # Result directory def create_result_subdir(result_dir, desc, profile): """ Create and initialize result sub-directory :param result_dir: path to root of result directory :type result_dir: str :param desc: description of current experiment :type desc: str :param profile: profile :type profile: dict :return: path to result sub-directory :rtype: str """ result_dir = 'results' # determine run id run_id = 0 for fname in glob.glob(os.path.join(result_dir, '*')): fbase = os.path.basename(fname) finds = re.findall('^([\d]+)-', fbase) if len(finds) != 0: ford = int(finds[0]) run_id = max(run_id, ford + 1) # create result sub-directory result_subdir = os.path.join(result_dir, '{:03d}-{:s}'.format(run_id, desc)) if not os.path.exists(result_subdir): os.makedirs(result_subdir) set_output_log_file(os.path.join(result_subdir, 'log.txt')) print("[Builder] Saving results to {}".format(result_subdir)) # export profile with open(os.path.join(result_subdir, 'config.json'), 'w') as f: json.dump(profile, f) return result_subdir def locate_result_subdir(result_dir, run_id_or_result_subdir): """ Locate result subdir by given run id or path :param result_dir: path to root of result directory :type result_dir: str :param run_id_or_result_subdir: run id or subdir path :type run_id_or_result_subdir: int or str :return: located result subdir :rtype: str """ # if isinstance(run_id_or_result_subdir, str) and os.path.isdir(run_id_or_result_subdir): # return run_id_or_result_subdir # # searchdirs = ['', 'results', 'networks'] # # for searchdir in searchdirs: # d = result_dir if searchdir == '' else os.path.join(result_dir, searchdir) # # search directly by name # d = os.path.join(d, str(run_id_or_result_subdir)) # if os.path.isdir(d): # return d # # search by prefix # if isinstance(run_id_or_result_subdir, int): # prefix = '{:03d}'.format(run_id_or_result_subdir) # else: # prefix = str(run_id_or_result_subdir) # dirs = sorted(glob.glob(os.path.join(result_dir, searchdir, prefix + '-*'))) # dirs = [d for d in dirs if os.path.isdir(d)] # if len(dirs) == 1: # return dirs[0] # print('[Builder] Cannot locate result subdir for run: {}'.format(run_id_or_result_subdir)) # return None return result_dir def format_time(seconds): """ Format seconds into desired format :param seconds: number of seconds :type seconds: float :return: formatted time :rtype: str """ s = int(np.rint(seconds)) if s < 60: return '{:d}s'.format(s) elif s < 60 * 60: return '{:d}m {:02d}s'.format(s // 60, s % 60) elif s < 24 * 60 * 60: return '{:d}h {:02d}m {:02}ds'.format(s // (60 * 60), (s // 60) % 60, s % 60) else: return '{:d}d {:02d}h {:02d}m'.format(s // (24 * 60 * 60), (s // (60 * 60)) % 24, (s // 60) % 60) # Model def get_model_name(step): """ Return filename of model snapshot by step :param step: global step of model :type step: int :return: model snapshot file name :rtype: str """ return 'network-snapshot-{:06d}.pth'.format(step) def get_best_model_name(): """ Return filename of best model snapshot by step :return: filename of best model snapshot :rtype: str """ return 'network-snapshot-best.pth' def get_last_model_name(result_subdir): """ Return filename of best model snapshot by step :param result_subdir: path to result sub-directory :type result_subdir: str :return: filename of last model snapshot :rtype: str """ latest = -1 for f in os.listdir(result_subdir): if os.path.isfile(os.path.join(result_subdir, f)) and \ re.search('network-snapshot-([\d]+).pth', f): f_step = int(re.findall('network-snapshot-([\d]+).pth', f)[0]) if latest < f_step: latest = f_step return get_model_name(latest) def save_model(result_subdir, step, graph, optimizer, seconds, is_best, criterion_dict=None): """ Save model snapshot to result subdir :param result_subdir: path to result sub-directory :type result_subdir: str :param step: global step of model :type step: int :param graph: model graph :type graph: torch.nn.Module :param optimizer: optimizer :type optimizer: torch.optim.Optimizer :param seconds: seconds of running time :type seconds: float :param is_best: whether this model is best :type is_best: bool :param criterion_dict: dict of criterion :type criterion_dict: dict """ # construct state state = { 'step': step, # DataParallel wraps model in `module` attribute. 'graph': graph.module.state_dict() if hasattr(graph, "module") else graph.state_dict(), 'optimizer': optimizer.state_dict(), 'criterion': {}, 'seconds': seconds } if criterion_dict is not None: state['criterion'] = {k: v.state_dict() for k, v in criterion_dict.items()} # save current state save_path = os.path.join(result_subdir, get_model_name(step)) torch.save(state, save_path) # save best state if is_best: best_path = os.path.join(result_subdir, get_best_model_name()) shutil.copy(save_path, best_path) def load_model(result_subdir, step_or_model_path, graph, optimizer=None, criterion_dict=None, device=None): """ lOad model snapshot from esult subdir :param result_subdir: path to result sub-directory :type result_subdir: str :param step_or_model_path: step or model path :type step_or_model_path: int or str :param graph: model graph :type graph: torch.nn.Module :param optimizer: optimizer :type optimizer: torch.optim.Optimizer :param criterion_dict: dict of criterion :type criterion_dict: dict :param device: device to run mode :type device: str :return: state :rtype: dict """ # check existence of model file model_path = step_or_model_path if isinstance(step_or_model_path, int): model_path = get_model_name(step_or_model_path) if step_or_model_path == 'best': model_path = get_best_model_name() if step_or_model_path == 'latest': model_path = None if not os.path.exists(model_path): model_path = os.path.join(result_subdir, model_path) if not os.path.exists(model_path): raise FileNotFoundError('Failed to find model snapshot with {}'.format(step_or_model_path)) # load model snapshot if isinstance(device, int): device = 'cuda:{}'.format(device) state = torch.load(model_path, map_location=device) step = state['step'] graph.load_state_dict(state['graph']) graph.set_actnorm_inited() if optimizer is not None: optimizer.load_state_dict(state['optimizer']) if criterion_dict is not None: for k in criterion_dict.keys(): criterion_dict[k].load_state_dict(state['criterion'][k]) print('[Builder] Load model snapshot successfully from {}'.format(model_path)) return state # Dataset def is_image(filepath): """ Determine whether file is an image or not :param filepath: file path :type filepath: str :return: whether file is an image :rtype: bool """ image_extensions = ['.png', '.jpg', '.jpeg'] basename = os.path.basename(filepath) _, extension = os.path.splitext(basename) return extension.lower() in image_extensions def tensor_to_ndarray(tensor): """ Convert float tensor into numpy image :param tensor: input tensor :type tensor: torch.Tensor :return: numpy image :rtype: np.ndarray """ tensor_np = tensor.permute(1, 2, 0).cpu().numpy() tensor_np = tensor_np.astype(np.float32) tensor_np = (tensor_np * 255).astype(np.uint8) return tensor_np def tensor_to_pil(tensor): """ Convert float tensor into PIL image :param tensor: input tensor :type tensor: torch.Tensor :return: PIL image :rtype: Image.Image """ transform = transforms.ToPILImage() tensor = tensor.cpu() return transform(tensor) def ndarray_to_tensor(img, shape=(128, 128, 3), bgr2rgb=True): """ Convert numpy image to float tensor :param img: numpy image :type img: np.ndarray :param shape: image shape in (H, W, C) :type shape: tuple or list :param bgr2rgb: convert color space
maximal cells sage: p4 = Polyhedron(vertices=[(0, -1), (0, 0), (1, 0), (1, -1)]) sage: pc.union(PolyhedralComplex([p4])) Traceback (most recent call last): ... ValueError: the given cells are not face-to-face """ maximal_cells = list(self.maximal_cell_iterator()) + list( right.maximal_cell_iterator()) return PolyhedralComplex(maximal_cells, maximality_check=True, face_to_face_check=True, is_immutable=(self._is_immutable and right._is_immutable), backend=self._backend) def join(self, right): """ The join of this polyhedral complex with another one. INPUT: - ``right`` -- the other polyhedral complex (the right-hand factor) EXAMPLES:: sage: pc = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc_join = pc.join(pc) sage: pc_join Polyhedral complex with 1 maximal cell sage: next(pc_join.maximal_cell_iterator()).vertices() (A vertex at (0, 0, 0), A vertex at (0, 0, 1), A vertex at (0, 1, 1), A vertex at (1, 0, 0)) """ maximal_cells = [f.join(g) for f in self.maximal_cell_iterator() for g in right.maximal_cell_iterator()] return PolyhedralComplex(maximal_cells, maximality_check=False, is_immutable=(self._is_immutable and right._is_immutable), backend=self._backend) ############################################################ # abstract methods not implemented in generic cell complex ############################################################ def wedge(self, right): """ The wedge (one-point union) of ``self`` with ``right``. .. TODO:: Implement the wedge product of two polyhedral complexes. EXAMPLES:: sage: pc = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc.wedge(pc) Traceback (most recent call last): ... NotImplementedError: wedge is not implemented for polyhedral complex """ raise NotImplementedError("wedge is not implemented for " + "polyhedral complex") ############################################################ # chain complexes, homology ############################################################ def chain_complex(self, subcomplex=None, augmented=False, verbose=False, check=True, dimensions=None, base_ring=ZZ, cochain=False): """ The chain complex associated to this polyhedral complex. .. TODO:: Implement chain complexes of a polyhedral complex. EXAMPLES:: sage: pc = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc.chain_complex() Traceback (most recent call last): ... NotImplementedError: chain_complex is not implemented for polyhedral complex """ raise NotImplementedError("chain_complex is not implemented for " + "polyhedral complex") def alexander_whitney(self, cell, dim_left): """ The decomposition of ``cell`` in this complex into left and right factors, suitable for computing cup products. .. TODO:: Implement :meth:`alexander_whitney` of a polyhedral complex. EXAMPLES:: sage: pc = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc.alexander_whitney(None, 1) Traceback (most recent call last): ... NotImplementedError: alexander_whitney is not implemented for polyhedral complex """ raise NotImplementedError("alexander_whitney is not implemented for " + "polyhedral complex") ############################################################ # end of chain complexes, homology ############################################################ # this function overrides the standard one for GenericCellComplex, # this one counts the number of maximal cells, not all cells, to # avoid calling and computing self.cells() def _repr_(self): """ Print representation. .. WARNING:: This may give the wrong answer if the polyhedral complex was constructed with ``maximality_check`` set to ``False``. EXAMPLES:: sage: p1 = Polyhedron(vertices=[(1, 1), (0, 0), (1, 2)]) sage: p2 = Polyhedron(vertices=[(1, 2), (0, 0), (0, 2)]) sage: p3 = Polyhedron(vertices=[(1, 2), (0, 2)]) sage: PolyhedralComplex([p1, p2, p3]) Polyhedral complex with 2 maximal cells Wrong answer due to ``maximality_check=False``:: sage: PolyhedralComplex([p1, p2, p3], maximality_check=False) Polyhedral complex with 3 maximal cells """ num = len(list(self.maximal_cell_iterator())) if num == 1: return "Polyhedral complex with %s maximal cell" % num else: return "Polyhedral complex with %s maximal cells" % num def set_immutable(self): """ Make this polyhedral complex immutable. EXAMPLES:: sage: pc = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc.is_mutable() True sage: pc.set_immutable() sage: pc.is_mutable() False """ self._is_immutable = True def is_mutable(self): """ Return whether ``self`` is mutable. EXAMPLES:: sage: pc1 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc1.is_mutable() True sage: pc2 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])], ....: is_mutable=False) sage: pc2.is_mutable() False sage: pc1 == pc2 True sage: pc3 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])], ....: is_immutable=True) sage: pc3.is_mutable() False sage: pc2 == pc3 True """ return not self._is_immutable def is_immutable(self): """ Return whether ``self`` is immutable. EXAMPLES:: sage: pc1 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])]) sage: pc1.is_immutable() False sage: pc2 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])], ....: is_mutable=False) sage: pc2.is_immutable() True sage: pc3 = PolyhedralComplex([Polyhedron(vertices=[[0], [1]])], ....: is_immutable=True) sage: pc3.is_immutable() True """ return self._is_immutable def add_cell(self, cell): """ Add a cell to this polyhedral complex. INPUT: - ``cell`` -- a polyhedron This **changes** the polyhedral complex, by adding a new cell and all of its subfaces. EXAMPLES: Set up an empty complex in the intended ambient space, then add a cell:: sage: pc = PolyhedralComplex(ambient_dim=2) sage: pc.add_cell(Polyhedron(vertices=[(1, 2), (0, 2)])) sage: pc Polyhedral complex with 1 maximal cell If you add a cell which is already present, there is no effect:: sage: pc.add_cell(Polyhedron(vertices=[(1, 2)])) sage: pc Polyhedral complex with 1 maximal cell sage: pc.dimension() 1 Add a cell and check that dimension is correctly updated:: sage: pc.add_cell(Polyhedron(vertices=[(1, 2), (0, 0), (0, 2)])) sage: pc.dimension() 2 sage: pc.maximal_cells() {2: {A 2-dimensional polyhedron in ZZ^2 defined as the convex hull of 3 vertices}} sage: pc.is_convex() True Add another cell and check that the properties are correctly updated:: sage: pc.add_cell(Polyhedron(vertices=[(1, 1), (0, 0), (1, 2)])) sage: pc Polyhedral complex with 2 maximal cells sage: len(pc._cells[1]) 5 sage: pc._face_poset Finite poset containing 11 elements sage: pc._is_convex True sage: pc._polyhedron.vertices_list() [[0, 0], [0, 2], [1, 1], [1, 2]] Add a ray which makes the complex non convex:: sage: pc.add_cell(Polyhedron(rays=[(1, 0)])) sage: pc Polyhedral complex with 3 maximal cells sage: len(pc._cells[1]) 6 sage: (pc._is_convex is False) and (pc._polyhedron is None) True TESTS:: sage: pc.add_cell(Polyhedron(vertices=[[0]])) Traceback (most recent call last): ... ValueError: the given cell is not a polyhedron in the same ambient space sage: pc.add_cell(Polyhedron(vertices=[(1, 1), (0, 0), (2, 0)])) Traceback (most recent call last): ... ValueError: the cell is not face-to-face with complex sage: pc.set_immutable() sage: pc.add_cell(Polyhedron(vertices=[(-1, -1)])) Traceback (most recent call last): ... ValueError: this polyhedral complex is not mutable """ if self._is_immutable: raise ValueError("this polyhedral complex is not mutable") if not is_Polyhedron(cell) or cell.ambient_dim() != self._ambient_dim: raise ValueError("the given cell is not a polyhedron " + "in the same ambient space") # if cell is already in self, do nothing. if self.is_cell(cell): return if self._backend: cell = cell.base_extend(cell.base_ring(), self._backend) # update cells and face poset cells = self.cells() covers = {p: self.face_poset().upper_covers(p) for p in self.cell_iterator()} d = cell.dimension() d_cells = [cell] if d not in cells: cells[d] = set(d_cells) else: cells[d].add(cell) covers[cell] = [] while d > 0: d = d - 1 new_facets = [] for c in d_cells: for facet in c.facets(): p = facet.as_polyhedron() if d not in cells: cells[d] = set([]) if p not in cells[d]: cells[d].add(p) covers[p] = [c] new_facets.append(p) else: covers[p].append(c) d_cells = new_facets self._face_poset = poset = Poset(covers) self._cells = cells # check face-to-face between cell and previous maximal cells for p in self.maximal_cell_iterator(): r = p.intersection(cell) if not (r.is_empty() or (r in poset) and poset.is_gequal(p, r) and poset.is_gequal(cell, r)): raise ValueError("the cell is not face-to-face with complex") # update dim and maximal cells d = cell.dimension() if d > self._dim: self._dim = d maximal_cells = poset.maximal_elements() # a list self._maximal_cells = cells_list_to_cells_dict(maximal_cells) # update convexity if self was known to be convex, reset otherwise. if self._is_convex: try: new_complex = PolyhedralComplex([self._polyhedron, cell], face_to_face_check=True) except ValueError: self._is_convex = False self._polyhedron = None else: self._is_convex = new_complex.is_convex() self._polyhedron = new_complex._polyhedron else: self._is_convex = None self._polyhedron = None # reset cached attribute self._maximal_cells_sorted = None # needed for hash def remove_cell(self, cell, check=False): r""" Remove ``cell`` from ``self`` and all the cells that contain ``cell`` as a subface. INPUT: - ``cell`` -- a cell of the polyhedral complex - ``check`` -- boolean (default: ``False``); if ``True``, raise an error if ``cell`` is not a cell of this complex This does not return anything; instead, it **changes** the polyhedral complex. EXAMPLES: If you add a cell which is already present, there is no effect:: sage: p1 = Polyhedron(vertices=[(1, 1), (0, 0), (1, 2)]) sage: p2 = Polyhedron(vertices=[(1, 2), (0, 0), (0, 2)]) sage: r = Polyhedron(rays=[(1, 0)]) sage: pc = PolyhedralComplex([p1, p2, r]) sage: pc.dimension() 2 sage: pc.remove_cell(Polyhedron(vertices=[(0, 0), (1, 2)])) sage: pc.dimension() 1 sage: pc Polyhedral complex with 5 maximal cells sage: pc.remove_cell(Polyhedron(vertices=[(1, 2)])) sage: pc.dimension() 1 sage: pc Polyhedral complex with 3 maximal cells sage: pc.remove_cell(Polyhedron(vertices=[(0, 0)])) sage: pc.dimension() 0 TESTS: Check that ValueError and empty complex are treated properly:: sage: p = Polyhedron(vertices=[[1]]) sage: pc = PolyhedralComplex([p]) sage: pc.remove_cell(Polyhedron(vertices=[[0]]), check=True) Traceback (most recent call last): ... ValueError: trying
# coding: utf-8 import os from io import StringIO from typing import TYPE_CHECKING, Any, BinaryIO, Dict, List, Optional, Union from .constants import UP_AMAZON_S3 from .exceptions import InvalidBatch from .utils import guess_mimetype if TYPE_CHECKING: from .endpoint import APIEndpoint # Base classes class Model(object): """Base class for all entities.""" __slots__ = {"service": None} # type: Dict[str, Any] def __init__(self, service=None, **kwargs): # type: (Optional[APIEndpoint], Any) -> None self.service = service # type: APIEndpoint # Declare attributes for key, default in type(self).__slots__.copy().items(): # Reset mutable objects to prevent data leaks if isinstance(default, dict): default = {} elif isinstance(default, list): default = [] key = key.replace("-", "_") setattr(self, key, kwargs.get(key, default)) def __repr__(self): # type: () -> str attrs = ", ".join( f"{attr.replace('_', '-')}={getattr(self, attr, None)!r}" for attr in sorted(self.__slots__) ) return f"<{self.__class__.__name__} {attrs}>" def as_dict(self): # type: () -> Dict[str, Any] """Returns a dict representation of the resource.""" result = {} for key in self.__slots__: val = getattr(self, key) if val is None: continue # Parse lists of objects elif isinstance(val, list) and len(val) > 0 and isinstance(val[0], Model): val = [item.as_dict() for item in val] result[key.replace("_", "-")] = val return result @classmethod def parse(cls, json, service=None): # type: (Dict[str, Any], Optional[APIEndpoint]) -> Model """Parse a JSON object into a model instance.""" kwargs = {k: v for k, v in json.items()} return cls(service=service, **kwargs) def save(self): # type: () -> None """Save the resource.""" self.service.put(self) class RefreshableModel(Model): __slots__ = () def load(self, model=None): # type: (Optional[Union[Model, Dict[str, Any]]]) -> None """ Reload the Model. If model is not None, copy from its attributes, otherwise query the server for the entity with its uid. :param model: the entity to copy :return: the refreshed model """ if not model: model = self.service.get(self.uid) if isinstance(model, dict): def get_prop(obj, key): return obj.get(key) else: def get_prop(obj, key): return getattr(obj, key) for key in self.__slots__.keys(): setattr(self, key, get_prop(model, key)) # Entities class Batch(Model): """Upload batch.""" __slots__ = { "batchId": None, "blobs": {}, "dropped": None, "extraInfo": None, "etag": None, "key": "", "multiPartUploadId": None, "provider": None, "upload_idx": 0, } @property def uid(self): # type: () -> str return self.batchId @uid.setter def uid(self, value): # type: (str) -> None self.batchId = value def cancel(self): # type: () -> None """Cancel an upload batch.""" if not self.batchId: return self.service.delete(self.uid) self.batchId = None def delete(self, file_idx): """Delete a blob from the batch.""" if self.batchId: self.service.delete(self.uid, file_idx=file_idx) self.blobs[file_idx] = None def get(self, file_idx): # type: (int) -> Blob """ Get the blob info. :param file_idx: the index of the blob in the batch :return: the corresponding blob """ if self.batchId is None: raise InvalidBatch("Cannot fetch blob for inexistant/deleted batch.") blob = self.service.get(self.uid, file_idx=file_idx) self.blobs[file_idx] = blob return blob def get_uploader(self, blob, **kwargs): # type: (Blob, Any) -> Blob """ Get an uploader for blob. :param blob: the blob to upload :param kwargs: the upload settings :return: the uploader """ return self.service.get_uploader(self, blob, **kwargs) def is_s3(self): # type: () -> bool """Return True if the upload provider is Amazon S3.""" provider = self.provider or "" if not provider: return False if isinstance(self.extraInfo, dict): provider = self.extraInfo.get("provider_type", "") or provider return provider.lower() == UP_AMAZON_S3 def upload(self, blob, **kwargs): # type: (Blob, Any) -> Blob """ Upload a blob. :param blob: the blob to upload :param kwargs: the upload settings :return: the blob info """ return self.service.upload(self, blob, **kwargs) def execute(self, operation, file_idx=None, params=None): # type: (str, int, Dict[str, Any]) -> Any """ Execute an operation on this batch. :param operation: operation to execute :param file_idx: target file of the operation :param params: parameters of the operation :return: the output of the operation """ return self.service.execute(self, operation, file_idx, params) def attach(self, doc, file_idx=None): # type: (str, Optional[int]) -> Any """ Attach one or all files of this batch to a document. :param doc: document to attach :param file_idx: target file :return: the output of the attach operation """ return self.service.attach(self, doc, file_idx) def complete(self, **kwargs): # type: (Any) -> Any """ Complete a S3 Direct Upload. :param kwargs: additional arguments fowarded at the underlying level :return: the output of the complete operation """ return self.service.complete(self, **kwargs) class Blob(Model): """Blob superclass used for metadata.""" __slots__ = { "batchId": "", "chunkCount": 0, "fileIdx": None, "mimetype": None, "name": None, "size": 0, "uploadType": None, "uploaded": "true", "uploadedChunkIds": [], "uploadedSize": 0, } @classmethod def parse(cls, json, service=None): # type: (Dict[str, Any], Optional[APIEndpoint]) -> Blob """Parse a JSON object into a blob instance.""" kwargs = {k: v for k, v in json.items()} model = cls(service=service, **kwargs) if model.uploaded and model.uploadedSize == 0: model.uploadedSize = model.size return model def to_json(self): # type: () -> Dict[str, str] """Return a JSON object used during the upload.""" return {"upload-batch": self.batchId, "upload-fileId": str(self.fileIdx)} class BufferBlob(Blob): """ InMemory content to upload to Nuxeo. Acts as a context manager so its data can be read with the `with` statement. """ def __init__(self, data, **kwargs): # type: (str, Any) -> None """ :param data: content to upload to Nuxeo :param **kwargs: named attributes """ super().__init__(**kwargs) self.stringio = None # type: Optional[StringIO] self.buffer = data self.size = len(self.buffer) self.mimetype = "application/octet-stream" @property def data(self): # type: () -> StringIO """Request data.""" return self.stringio def __enter__(self): if not self.buffer: return None self.stringio = StringIO(self.buffer) return self.stringio def __exit__(self, *args): if self.stringio: self.stringio.close() class Comment(Model): """Comment.""" __slots__ = { "ancestorIds": [], "author": None, "creationDate": None, "entity": None, "entity_type": "comment", "entityId": None, "id": None, "lastReplyDate": None, "modificationDate": None, "numberOfReplies": 0, "origin": None, "parentId": None, "text": None, } @property def uid(self): # type: () -> str return self.id def delete(self): # type: () -> None """Delete the comment.""" self.service.delete(self.uid) def has_replies(self): # type: () -> bool """Return True is the comment has at least one reply.""" return self.numberOfReplies > 0 def replies(self, **params): # type: (str, Any) -> List[Comment] """ Get the replies of the comment. Any additionnal arguments will be passed to the *params* parent's call. :param uid: the ID of the comment :return: the list of replies """ return self.service.replies(self.uid, params=params) def reply(self, text): # type: (str) -> Comment """Add a reply to the comment.""" # Add the reply reply_comment = self.service.post(self.uid, text) # Update comment attributes self.numberOfReplies += 1 self.lastReplyDate = reply_comment.creationDate # And return the reply return reply_comment class FileBlob(Blob): """ File to upload to Nuxeo. Acts as a context manager so its data can be read with the `with` statement. """ def __init__(self, path, **kwargs): # type: (str, Any) -> None """ :param path: file path :param **kwargs: named attributes """ super().__init__(**kwargs) self.fd = None # type: Optional[BinaryIO] self.path = path self.name = os.path.basename(self.path) self.size = os.path.getsize(self.path) self.mimetype = self.mimetype or guess_mimetype(self.path) # type: str @property def data(self): # type: () -> BinaryIO """ Request data. The caller has to close the file descriptor himself if he doesn't open it with the context manager. """ return self.fd def __enter__(self): self.fd = open(self.path, "rb") return self.fd def __exit__(self, *args): if self.fd: self.fd.close() class Directory(Model): """Directory.""" __slots__ = { "directoryName": None, "entries": [], "entity_type": "directory", } @property def uid(self): # type: () -> str return self.directoryName def get(self, entry): # type: (str) -> DirectoryEntry """ Get an entry of the directory. :param entry: the name of the entry :return: the corresponding directory entry """ return self.service.get(self.uid, dir_entry=entry) def create(self, entry): # type: (DirectoryEntry) -> DirectoryEntry """Create an entry in the directory.""" return self.service.post(entry, dir_name=self.uid) def save(self, entry): # type: (DirectoryEntry) -> DirectoryEntry """Save a modified entry of the directory.""" return self.service.put(entry, dir_name=self.uid) def delete(self, entry): # type: (str) -> None """ Delete one of the directory's entries. :param entry: the entry to delete """ self.service.delete(self.uid, entry) def exists(self, entry): # type: (str) -> bool """ Check if an entry is in the directory. :param entry: the entry name :return: True if it exists, else False """ return self.service.exists(self.uid, dir_entry=entry) class DirectoryEntry(Model): """Directory entry.""" __slots__ = { "directoryName": None, "entity_type": "directoryEntry", "properties": {},
import subprocess import yaml import subprocess from pathlib import Path from ctfcli.utils.utils import errorlogger,redprint,DEBUG from ctfcli.utils.utils import debugblue,debuggreen,debugred,debugyellow class Linter(): """ I wasnt thinking the best when I wrote this so its pretty procedural Class to lint challenge.yaml files to decrease size of Challenge class codebase Challenge.yaml files are NOT processed by ClassConstructor.py They are NOT automatically converted into code, they follow a different pipeline where the files are suspect and require linting if the directory contains a metadata.yaml or kubernetes spec its for a deployment and should be handled differently """ def __init__(self, #kwargs:dict, togglevisibility=True): debuggreen("[DEBUG] Creating Linter() Class") self.jsonpayload = {} self.scorepayload = {} # the base repo has too few challenges to justify making any invisible # right from the get go, so its set to true by default self.toggle = togglevisibility # BSIDES STUFF ONLY # This is the standard metadata for a challenge with a web component. # In terms of file structure, please also have the following: # # - A challenge/ folder with everything needed to create the challenge assets # - A distfiles/ folder which contains all files (or symlinks to files) that # will be attached to the challenge # - A solution/ folder with a working solution to the challenge (or a README.md # file documenting the solution) self.name:dict = None self.category:dict = None self.description:dict = None self.scorepayload:dict = None self.flags:dict = None self.topics:dict = None self.tags:dict = None self.files:dict = None self.hints:dict = None self.requirements:dict = None self.max_attempts:dict = None self.extratags:dict = None self.notes:dict = None self.author:dict = None self.typeof:dict = None self.extra:dict = None wat = ['replicas', 'environ', ] self.deploymentfields = [ 'port', 'protocol', 'use_http_loadbalancer', "image","host","connection_info" ] self.depfieldstype = { 'port':[int], 'protocol':[str], 'use_http_loadbalancer':[str], "image": [str], "host":[str], "connection_info":[str] } self.flagstags = ['flag','flags'] self.reqfieldstypes = { "name": [str], "category": [str], "description":[str], 'value':[int], "version":[str,int], 'flag':[str,list], 'flags':[str,list], "state":[str] } self.requiredfields = [ "name", "category", "description", 'value', "version", "type",# "extra", #"state" ] self.optionalfields = ["topics","hints","max_attempts","requirements",'notes', 'tags','scoreboard_name','author','files'] #Required sections get the "pop()" function # a KeyError will be raised if the key does not exist def lintchallengeyaml(self,dictfromyaml:dict): """ Lints a challenge.yaml and spits out a dict >>> linter = Linter() >>> outputdict = linter.lintchallengeyaml(yamlfilelocation) >>> newchallenge = Challenge(**outputdict) """ try: debuggreen("[DEBUG] linting challenge yaml file") #process required fields requirementsdict = self.extractrequired(dictfromyaml) #did a shitty hack in the scope above to push the category into the dict # this value needs to be assigned by the yaml eventually self._processcategory(requirementsdict) self._processrequired(requirementsdict) #process optional fields optionaldict = self.extractoptional(dictfromyaml) self.lintoptional(optionaldict) # ssets everything into self.jsonpayload self.setpayload() return self.jsonpayload except Exception: errorlogger("[-] ERROR linting challenge yaml \n ") def validatetags(self, tag, dictfromyaml:dict, template:dict): """ Checks if field data is of a type allowed by the spec Args: tag (str): tag to validate dictfromyaml (dict): dict to validate template (dict): template to validate against """ debuggreen("[DEBUG] validating tags in linter") # get the types allowed for that tag allowedtagtypes = template.get(tag) # get the tag contents and compare the two # check to see if the tag is in the list of things REQUIRED! if type(dictfromyaml.get(tag)) in allowedtagtypes: return True else: return False def validaterequired(self,tag, dictfromyaml:dict, template:dict): """ Validates tag field types for required components of challenge.yaml """ debuggreen("[DEBUG] validating required tags in linter") #check if the challenge is MISSING any required tags! if type(dictfromyaml.get(tag)) not in self.requiredtagtypes: return False else: return True def extractrequired(self,dictfromyaml:dict): """ POPs all the required, thorws an exception if they arent present """ try: debuggreen("[DEBUG] extracting required tags in linter") reqdict = {} # some challenges have no state assigned self._processstate(dictfromyaml) # field with more than one tag for the same data self._processflags(dictfromyaml) # type is higher level important # required flags are indicated by its existance self._processtype(dictfromyaml) if self.typeof.get("typeof") == "dynamic": self.requiredfields.append("extra") # finally, process the required fields for each in self.requiredfields: if dictfromyaml.get(each) != None: reqdict.update({each: dictfromyaml.pop(each)}) return reqdict except Exception: errorlogger("[-] ERROR: Failed to validate Required Fields \n") def extractoptional(self, optionaldict:dict): """ """ debuggreen("[DEBUG] extracting optional tags in linter") self.optionalfields = ['author',"topics","hints","max_attempts", "requirements",'notes', 'tags', 'scoreboard_name','files'] try: optdict = {} for tag in self.optionalfields: tagdata = optionaldict.get(tag) if tagdata != None: optdict.update({tag: tagdata}) return optdict except Exception: errorlogger("[-] ERROR: Failed to validate Required Fields \n") def _processvalue(self,requirementsdict:dict): """ """ try: debuggreen("[DEBUG] processing value in linter") tagdata = requirementsdict.pop('value') if (type(tagdata) != int): redprint("[-] ERROR: Value field should be an integer, skipping challenge \n") raise ValueError else: self.value = {'value':tagdata} except Exception: errorlogger("[-] ERROR: Failed to validate Required Fields \n") def _processtype(self,requirementsdict:dict): """ """ debuggreen("[DEBUG] processing score fields in linter") tagdata = requirementsdict.pop('type') if tagdata in ["static","standard","dynamic"]: self.typeof = {"typeof" : tagdata} def _processscore(self,requirementsdict:dict): """ """ try: debuggreen("[DEBUG] processing score fields in linter") #self.typeof = requirementsdict.pop('type') # dynamic challenges if self.typeof['typeof'] == 'dynamic': # have the extra field self.extra:dict = requirementsdict.pop("extra") for each in self.extra: if (type(self.extra.get(each)) != int): redprint(f"[-] ERROR: {each} field should be an integer, skipping challenge \n") raise ValueError else: self.scorepayload = { **self.value, 'initial': self.extra['initial'], 'decay' : self.extra['decay'], 'minimum': self.extra['minimum'] } # static challenges only have the "value" field elif (self.typeof.get('typeof') == 'static') or (self.typeof.get('typeof') == 'standard'): self.scorepayload = self.value #{'value' : self.value} except Exception: errorlogger("[-] ERROR: Score data does not match specification, skipping challenge! \n") def _processstate(self, dictfromyaml:dict): """ Process state tag from challenge yaml file """ debuggreen("[DEBUG] processing visibility state in linter") # check state field # we should set state to visible unless self.toggle is set to false # then we use the value in the yaml file if dictfromyaml.get("state") != None: state = dictfromyaml.pop("state") #if state != None: # they want to toggle all challenges to visible if state == 'hidden' and self.toggle == True: self.state = {"state":'visible'} # no toggle, just assignment else: self.state = {"state":state} # there was no "state" field in the yaml # presume its gor hidden prereqs? else: self.state = {"state": 'hidden'} def _processname(self,requirementsdict:dict): """ """ debuggreen("[DEBUG] processing name in linter") tagdata = requirementsdict.pop("name") self.name = {"name":tagdata} def _processdescription(self,requirementsdict): """ """ debuggreen("[DEBUG] processing description in linter") if requirementsdict.get('description') != None: tagdata = requirementsdict.pop("description") self.description = {"description":tagdata} else: debugred("[DEBUG] no Version tag in yaml") self.description = {"description": "EMPTY NOT IN YAML"} def _processversion(self,requirementsdict): """ """ debuggreen("[DEBUG] processing version in linter") if requirementsdict.get('version') != None: tagdata = requirementsdict.pop("version") self.version = {"version":tagdata} # if version is not present in the yaml file else: debugred("[DEBUG] no Version tag in yaml") self.version = {"version": "0.1"} #raise Exception def _processintitem(self, tag:str,yamldict:dict): """ UNUSED, FUTURE checks existance of str item, adds to output if valid """ debuggreen("[DEBUG] processing tag in linter") if yamldict.get(tag) != None: tagdata = yamldict.pop(tag) setattr(self,tag, {tag: tagdata}) else: debugred(f"[DEBUG] no {tag} tag in yaml") if DEBUG: setattr(self,tag,{tag: "field was empty during loading"}) else: raise Exception def _processstritem(self, tag:str, yamldict:dict): """ UNUSED, FUTURE checks existance of str item, adds to output if valid """ debuggreen("[DEBUG] processing tag in linter") if yamldict.get(tag) != None: tagdata = yamldict.pop(tag) self.category = {tag: tagdata} else: debugred(f"[DEBUG] no {tag} tag in yaml") raise Exception def _processcategory(self, requirementsdict:dict): """ """ debuggreen("[DEBUG] processing category in linter") # dangly bit for future additions if requirementsdict.get("category") != None: tagdata = requirementsdict.pop("category") self.category = {"category": tagdata} else: debugred("[DEBUG] no category tag in yaml") raise Exception def _processflags(self,requirementsdict:dict): """ """ self.flagstemplate = { "content":str, #"data":str, "type":str, #"static", "challenge":str#int } flagsdict = {} try: debuggreen("[DEBUG] processing flags in linter") try: flagsdata = requirementsdict.pop("flags") except: try: flagsdata = requirementsdict.pop("flag") except: errorlogger("[-] ERROR: Flags missing from challenge, rejecting") #single flag, inline with tag if (type(flagsdata) == str): self.flagstemplate["content"] = flagsdata self.flagstemplate["type"] = "static" flagsdict.update(self.flagstemplate) #multiple flags, on thier own lines elif type(flagsdata) == list: for flag in flagsdata: # special flags if type(flag) == dict: flagsdict.update(flag) #string flag on its own line
import numpy as np import copy import sys from nsrl.helper import tree try: import cPickle as pickle except ModuleNotFoundError: import pickle class DataSet(object): """A replay memory consisting of circular buffers for observations, actions, rewards and terminals.""" def __init__(self, env, random_state=None, max_size=1000000, use_priority=False, only_full_history=True, secondary_rewards=False, head_num=1): """Initializer. Parameters ----------- inputDims : list of tuples Each tuple relates to one of the observations where the first value is the history size considered for this observation and the rest describes the shape of each punctual observation (e.g., scalar, vector or matrix). See base_classes.Environment.inputDimensions() documentation for more info. random_state : Numpy random number generator If None, a new one is created with default numpy seed. max_size : float The replay memory maximum size. Default : 1000000 """ self._environment = env self._batch_dimensions = env.inputDimensions() self._max_history_size = np.max([self._batch_dimensions[i][0] for i in range (len(self._batch_dimensions))]) self._size = max_size self._use_priority = use_priority self._only_full_history = only_full_history if ( isinstance(env.nActions(),int) ): self._actions = CircularBuffer(max_size, dtype="int8") else: self._actions = CircularBuffer(max_size, dtype='object') # FOR BOOTSTRAP DQN - if number of heads > 1, we save a mask self._masks = None self._head_num = head_num if self._head_num > 1: self._masks = CircularBuffer(max_size, elemShape=(head_num,), dtype="int8") self._rewards = CircularBuffer(max_size) self._secondary_rewards = None if secondary_rewards: self._secondary_rewards = CircularBuffer(max_size) self._terminals = CircularBuffer(max_size, dtype="bool") if (self._use_priority): self._prioritiy_tree = tree.SumTree(max_size) self._translation_array = np.zeros(max_size) self._observations = np.zeros(len(self._batch_dimensions), dtype='object') # Initialize the observations container if necessary for i in range(len(self._batch_dimensions)): self._observations[i] = CircularBuffer(max_size, elemShape=self._batch_dimensions[i][1:], dtype=env.observationType(i)) if (random_state == None): self._random_state = np.random.RandomState() else: self._random_state = random_state self.n_elems = 0 self.sticky_action=1 # Number of times the agent is forced to take the same action as part of one actual time step def save(self, fname): """ Saves the DataSet to specified filename :return: """ def is_picklable(obj): try: pickle.dumps(obj) except pickle.PicklingError: return False return True with open(fname, 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) @staticmethod def load(fname): with open(fname, 'rb') as inp: return pickle.load(inp) def actions(self): """Get all actions currently in the replay memory, ordered by time where they were taken.""" return self._actions.getSlice(0) def rewards(self): """Get all rewards currently in the replay memory, ordered by time where they were received.""" return self._rewards.getSlice(0) def secondaryRewards(self): """Get all secondary rewards currently in replay memory, ordered by time where they were received.""" return self._secondary_rewards.getSlice(0) def terminals(self): """Get all terminals currently in the replay memory, ordered by time where they were observed. terminals[i] is True if actions()[i] lead to a terminal state (i.e. corresponded to a terminal transition), and False otherwise. """ return self._terminals.getSlice(0) def masks(self): if self._masks is not None: return self._masks.getSlice(0) return None def observations(self): """Get all observations currently in the replay memory, ordered by time where they were observed. """ ret = np.zeros_like(self._observations) for input in range(len(self._observations)): ret[input] = self._observations[input].getSlice(0) return ret def observationsMatchingBatchDim(self): """ Get all observations currently in replay memory, ordered by time they were observed, and in shape according to self._batch_dimensions """ ret = [] for inp in range(len(self._observations)): all_obs = self._observations[inp].getSlice(0) processed = all_obs # If we have more than 1 observation per state if self._batch_dimensions[inp][0] > 1 and len(all_obs) > 0: obs_per_state = self._batch_dimensions[inp][0] processed = np.zeros((len(all_obs), obs_per_state, ) + all_obs.shape[1:]) # for every observation, we create a state for i in range(all_obs.shape[0]): state = np.zeros((obs_per_state,) + all_obs.shape[1:]) # everything before state_start_idx is all_obs[0] state_start_idx = 0 # start index in all_obs start_idx = i - obs_per_state # if we're in the first obs_per_state observations, we need to fill the first # -start_idx elements with all_obs[0] if start_idx < 0: n_to_fill = -start_idx state[0:n_to_fill] = np.repeat(all_obs[0][None, :, :], n_to_fill, axis=0) # start of where to fill the rest state_start_idx = n_to_fill # new start_idx for start_idx = 0 state[state_start_idx:] = all_obs[start_idx+1:i+1] processed[i] = state ret.append(processed) return ret def updateRewards(self, new_rewards, indices, secondary=False): if secondary: self._secondary_rewards[indices] = new_rewards else: self._rewards[indices] = new_rewards def updatePriorities(self, priorities, rndValidIndices): """ """ for i in range( len(rndValidIndices) ): self._prioritiy_tree.update(rndValidIndices[i], priorities[i]) def randomBatch(self, batch_size, use_priority): """Returns a batch of states, actions, rewards, terminal status, and next_states for a number batch_size of randomly chosen transitions. Note that if terminal[i] == True, then next_states[s][i] == np.zeros_like(states[s][i]) for each s. Parameters ----------- batch_size : int Number of transitions to return. use_priority : Boolean Whether to use prioritized replay or not Returns ------- states : numpy array of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). States are taken randomly in the data with the only constraint that they are complete regarding the history size for each observation. actions : numpy array of integers [batch_size] actions[i] is the action taken after having observed states[:][i]. rewards : numpy array of floats [batch_size] rewards[i] is the reward obtained for taking actions[i-1]. next_states : numpy array of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). terminals : numpy array of booleans [batch_size] terminals[i] is True if the transition leads to a terminal state and False otherwise Throws ------- SliceError If a batch of this batch_size could not be built based on current data set (not enough data or all trajectories are too short). """ batch = {} if (self._max_history_size + self.sticky_action - 1 >= self.n_elems): raise SliceError( "Not enough elements in the dataset to create a " "complete state. {} elements in dataset; requires {}" .format(self.n_elems, self._max_history_size)) if (self._use_priority): #FIXME : take into account the case where self._only_full_history is false rndValidIndices, rndValidIndices_tree = self._randomPrioritizedBatch(batch_size) if (rndValidIndices.size == 0): raise SliceError("Could not find a state with full histories") else: rndValidIndices = np.zeros(batch_size, dtype='int32') if (self._only_full_history): for i in range(batch_size): # TODO: multithread this loop? rndValidIndices[i] = self._randomValidStateIndex(self._max_history_size+self.sticky_action-1) else: for i in range(batch_size): # TODO: multithread this loop? rndValidIndices[i] = self._randomValidStateIndex(minimum_without_terminal=self.sticky_action) actions = self._actions.getSliceBySeq(rndValidIndices) rewards = self._rewards.getSliceBySeq(rndValidIndices) if self._secondary_rewards is not None: secondary_rewards = self._secondary_rewards.getSliceBySeq(rndValidIndices) terminals = self._terminals.getSliceBySeq(rndValidIndices) if self._masks is not None: masks = self._masks.getSliceBySeq(rndValidIndices) batch['actions'] = actions batch['rewards'] = rewards if self._secondary_rewards is not None: batch['secondary_rewards'] = secondary_rewards batch['terminals'] = terminals if self._masks is not None: batch['masks'] = masks states = np.zeros(len(self._batch_dimensions), dtype='object') next_states = np.zeros_like(states) # We calculate the first terminal index backward in time and set it # at maximum to the value self._max_history_size+self.sticky_action-1 first_terminals=[] for rndValidIndex in rndValidIndices: first_terminal=1 while first_terminal<self._max_history_size+self.sticky_action-1: if (self._terminals[rndValidIndex-first_terminal]==True or first_terminal>rndValidIndex): break first_terminal+=1 first_terminals.append(first_terminal) for input in range(len(self._batch_dimensions)): states[input] = np.zeros((batch_size,) + self._batch_dimensions[input], dtype=self._observations[input].dtype) next_states[input] = np.zeros_like(states[input]) for i in range(batch_size): slice=self._observations[input].getSlice( rndValidIndices[i]-self.sticky_action+2-min(self._batch_dimensions[input][0],first_terminals[i]+self.sticky_action-1), rndValidIndices[i]+1 ) if (len(slice)==len(states[input][i])): states[input][i] = slice else: for j in range(len(slice)): states[input][i][-j-1]=slice[-j-1] # If transition leads to terminal, we don't care about next state if rndValidIndices[i] == self.n_elems - 1: next_states[input][i] = self._environment.observe()[0] elif rndValidIndices[i] >= self.n_elems or terminals[i]: next_states[input][i] = np.zeros_like(states[input][i]) else: slice = self._observations[input].getSlice( rndValidIndices[i]+2-min(self._batch_dimensions[input][0],first_terminals[i]+1), rndValidIndices[i]+2 ) if (len(slice)==len(states[input][i])): next_states[input][i] = slice else: for j in range(len(slice)): next_states[input][i][-j-1]=slice[-j-1] #next_states[input][i] = self._observations[input].getSlice(rndValidIndices[i]+2-min(self._batch_dimensions[input][0],first_terminal), rndValidIndices[i]+2) batch['states'] = states batch['next_states'] = next_states batch['rndValidIndices'] = rndValidIndices if (self._use_priority): batch['rndValidIndices_tree'] = rndValidIndices_tree return batch def randomBatch_nstep(self, batch_size, nstep, use_priority): """Return corresponding states, actions, rewards, terminal status, and next_states for a number batch_size of randomly chosen transitions. Note that if terminal[i] == True, then next_states[s][i] == np.zeros_like(states[s][i]) for each s. Parameters ----------- batch_size : int Number of transitions to return. nstep : int Number of transitions to be considered for each element use_priority : Boolean Whether to use prioritized replay or not Returns ------- states : numpy array of objects Each object is a numpy array that relates to one of the observations with size [batch_size * (history size+nstep-1) * size of punctual observation (which is 2D,1D or scalar)]). States are taken randomly in the data with the only constraint that they are complete regarding the history size for each observation. actions : numpy array of integers [batch_size, nstep] actions[i] is the
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Reversible Graph Neural Network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensor2tensor.layers import common_layers import tensorflow as tf import numpy as np import re flags = tf.app.flags flags.DEFINE_bool('use_decay', False, 'Whether to use decay or not in the update equations.') flags.DEFINE_bool('use_sigmoid', False, 'Whether to use sigmoid transformation over the sum/can'\ 'be replaced by any bijective non-linearity') flags.DEFINE_enum('function_type', 'sigmoid', ['sigmoid', 'tanh'], 'Non-linearity to be applied to the system.') flags.DEFINE_bool('dampen_grad', False, 'Whether to dampen the gradients passing on to the variables') FLAGS = flags.FLAGS LAYER_RE = re.compile(".*rev_mp/layer_([0-9]*)/([fgb])/.*") def _print_tensors(*args): """Print tensor shapes while graph construction.""" print ('Printing Tensors =====================') for idxs, arg in enumerate(args): if isinstance(arg, list): for idx, val in enumerate(arg): print (val) else: print (arg) print ('End Printing Tensors ==================') def _get_variable_util(f, g, variables, num_layers): """Get back the variable list from scopes. Used from tensor2tensor revnet block.""" f_vars = [] g_vars = [] vars_in_scope = variables var_name_dict = dict() id_cntr = 0 # Assumes that parameters across layers are shared for i, var in enumerate(vars_in_scope): print (var.name) regex = LAYER_RE.match(var.name) layer_num = int(regex.group(1)) fn_name = regex.group(2) if var.name not in var_name_dict: var_name_dict[var.name] = id_cntr id_cntr += 1 if fn_name == 'f' or fn_name == 'b': f_vars.append(var) if fn_name == 'g' or fn_name == 'b': g_vars.append(var) return f_vars, g_vars, var_name_dict def message_passing_step(inputs, msg_fn, agg_fn, state_fn, *args): """Vanilla Message passing step implementing f/g.""" num_nodes = args[0] adj_mat = args[1] dims_for_state_fn = args[2] incr_node_rep = inputs for i in range(1): # Message passing code here init_shape = tf.shape(incr_node_rep) temp_t = tf.tile(tf.expand_dims(incr_node_rep,2), [1, 1, init_shape[1], 1]) m_t = msg_fn(temp_t) incoming_node = agg_fn(m_t*tf.expand_dims(adj_mat, 3)) incr_node_rep = state_fn(incr_node_rep, incoming_node, {'dim': dims_for_state_fn}) return incr_node_rep def _mp_forward(xs, f, g, parity, lower_triangular_op=False, lambda_t=0): """One layer of message passing.""" h0, h1 = xs non_lin_fn = None if FLAGS.function_type == "sigmoid": non_lin_fn = tf.nn.sigmoid elif FLAGS.function_type == "tanh": non_lin_fn = tf.nn.tanh if parity: if FLAGS.use_decay: h0_next = f(h1) + h0*lambda_t elif FLAGS.use_sigmoid: h0_next = non_lin_fn(f(h1) + h0) else: h0_next = f(h1) + h0 h1_next = h1 else: h0_next = h0 if FLAGS.use_decay: h1_next = g(h0) + h1*lambda_t elif FLAGS.use_sigmoid: h1_next = non_lin_fn(g(h0) + h1) else: h1_next = h1 + g(h0) return (h0_next, h1_next) def _mp_backward(ys, grad_ys, f, g, parity, f_vars, g_vars, lambda_t=0): """Backprop operation for one layer.""" y0, y1 = ys grad_y0, grad_y1 = grad_ys # Compute the parameter values for the previous step if parity: x1 = y1 y1_stop = tf.stop_gradient(y1) x1_stop = tf.stop_gradient(x1) fy1 = f(y1_stop) if FLAGS.use_decay: x0 = (y0 - fy1)/(lambda_t) elif FLAGS.use_sigmoid: y0_stop = tf.stop_gradient(y0) if FLAGS.function_type == "tanh": x0 = 0.5*(tf.log(1 + y0_stop) - tf.log(1 - y0_stop)) - fy1 elif FLAGS.function_type == "sigmoid": x0 = tf.log(y0_stop + 1e-10) - tf.log(1 - y0_stop + 1e-10) - fy1 else: x0 = y0 - fy1 else: x0 = y0 y0_stop = tf.stop_gradient(y0) x0_stop = tf.stop_gradient(x0) gy0 = g(y0_stop) if FLAGS.use_decay: x1 = (y1 - gy0)/(lambda_t) elif FLAGS.use_sigmoid: y1_stop = tf.stop_gradient(y1) if FLAGS.function_type == "tanh": x1 = 0.5*(tf.log(1 + y1_stop) - tf.log(1 - y1_stop)) - gy0 else: x1 = tf.log(y1_stop + 1e-10) - tf.log(1 - y1_stop + 1e-10) - gy0 else: x1 = y1 - gy0 # Compute the gradients with respect to x0, x1, ws retval = [None] non_lin_fn = None if FLAGS.function_type == "sigmoid": non_lin_fn = tf.nn.sigmoid elif FLAGS.function_type == "tanh": non_lin_fn = tf.nn.tanh if parity: grad_fy1 = tf.gradients(fy1, y1_stop, grad_y0)[0] if FLAGS.use_decay: grad_x0 = lambda_t*grad_y0 grad_x1 = grad_y1 + grad_fy1 grad_w_f = [gr for gr in tf.gradients(fy1, f_vars, grad_y0)] elif FLAGS.use_sigmoid: print ('Y0 stop: ', y0_stop, grad_y0) temp_y0 = tf.stop_gradient(x0) + tf.stop_gradient(fy1) grad_x0 = tf.gradients(non_lin_fn(temp_y0), temp_y0, grad_y0)[0] grad_x1 = grad_y1 + tf.gradients(fy1, y1_stop, grad_x0)[0] grad_w_f = tf.gradients(fy1, f_vars, grad_x0) else: grad_x0 = grad_y0 grad_x1 = grad_y1 + grad_fy1 grad_w_f = tf.gradients(fy1, f_vars, grad_y0) retval = [(x0, x1), (grad_x0, grad_x1), grad_w_f] else: grad_gy0 = tf.gradients(gy0, y0_stop, grad_y1)[0] if FLAGS.use_decay: grad_x1 = lambda_t*grad_y1 grad_x0 = grad_y0 + grad_gy0 grad_w_g = [gr for gr in tf.gradients(gy0, g_vars, grad_y1)] elif FLAGS.use_sigmoid: temp_y1 = tf.stop_gradient(x1) + tf.stop_gradient(gy0) grad_x1 = tf.gradients(non_lin_fn(temp_y1), temp_y1, grad_y1)[0] grad_x0 = grad_y0 + tf.gradients(gy0, y0_stop, grad_x1) grad_w_g = tf.gradients(gy0, g_vars, grad_x1) else: grad_x1 = grad_y1 grad_x0 = grad_y0 + grad_gy0 grad_w_g = tf.gradients(gy0, g_vars, grad_y1) retval = [(x0, x1), (grad_x0, grad_x1), grad_w_g] retval_t = tf.tuple(tf.contrib.framework.nest.flatten(retval)) retval_tupled = tf.contrib.framework.nest.pack_sequence_as(retval, retval_t) return retval def _rev_mp_block_forward(x0, x1, f, g, num_layers=1): """Forward computation for a series of layers.""" out = (x0, x1) # Perform f step once and g step once (this comprises one message passing # step in the system. lambda_series = [1.0/np.sqrt(cnt+1) for cnt in range(2*num_layers)] for i in range(num_layers): prev_out = out out = _mp_forward(out, f[i], g[i], 1, lambda_t=lambda_series[2*i]) out = _mp_forward(out, f[i], g[i], 0, lambda_t=lambda_series[2*i+1]) y0, y1 = out return y0, y1 class RevMessagePassingBlock(object): """Block to perform reversible message passing.""" def __init__(self, f, g, num_layers=1, is_training=True, use_efficient_backprop=True): if isinstance(f, list): assert len(f) == num_layers else: f = [f]* num_layers if isinstance(g, list): assert len(g) == num_layers else: g = [g]*num_layers scope_prefix = "rev_mp/layer_%d/" f_scope = scope_prefix + "f" g_scope = scope_prefix + "g" self.f = f self.g = g self.num_layers = num_layers self.is_training = is_training self._use_efficient_backprop = use_efficient_backprop def _efficient_grad_fn(self, inputs, variables, ys, grad_ys): """Computes gradient for a block of rev GNN layers.""" f_vars, g_vars, var_names = _get_variable_util(self.f, self.g, variables, self.num_layers) _print_tensors(grad_ys) f_var_grads = [] g_var_grads = [] # Reversing essential while gradient computation f = list(self.f) g = list(self.g) f.reverse() g.reverse() lambda_series = [1.0/(np.sqrt(cnt+1)) for cnt in range(2*self.num_layers)] lambda_series.reverse() for i in range(self.num_layers): ys, grad_ys, grad_w_g = _mp_backward(ys, grad_ys, f[i], g[i], 0, f_vars, g_vars, lambda_t=lambda_series[2*i]) ys, grad_ys, grad_w_f = _mp_backward(ys, grad_ys, f[i], g[i], 1, f_vars, g_vars, lambda_t=lambda_series[2*i+1]) g_var_grads.append(grad_w_g) f_var_grads.append(grad_w_f) # Reverse variable grads: as variable utility outputs reverse f_var_grads.reverse() g_var_grads.reverse() variable_grads = [None]*len(variables) tmp_cntr = 0 variable_mappings = dict() for idx, v in enumerate(variables): variable_mappings[v.name] = idx # grad_w_g = [variables] # Assumption: all variables are present at all time steps num_vars_f = len(f_var_grads[0]) assert num_vars_f == len(f_var_grads[1]), "Number of variables in f" num_vars_g = len(g_var_grads[0]) assert num_vars_g == len(g_var_grads[1]), "Number of variables in g" for idxs, values in enumerate(f_var_grads): for var_t, grad in list(zip(f_vars, values)): indx = variable_mappings[var_t.name] if isinstance(grad, tf.IndexedSlices): grad = tf.convert_to_tensor(grad) variable_grads[indx] = (variable_grads[indx] + grad if variable_grads[indx] is not None else grad if grad is not None else variable_grads[idx]) for idxs, values in enumerate(g_var_grads): for var_t, grad in list(zip(g_vars, values)): indx = variable_mappings[var_t.name] if isinstance(grad, tf.IndexedSlices): grad = tf.convert_to_tensor(grad) variable_grads[indx] = (variable_grads[indx] + grad if variable_grads[indx] is not None else grad) grad_x0, grad_x1 = grad_ys # _print_tensors(grad_x0, grad_x1, variable_grads) return [grad_x0, grad_x1], variable_grads def forward(self, x0, x1): custom_grad_fn = (self._efficient_grad_fn if self._use_efficient_backprop else None) # @common_layers.fn_with_custom_grad(custom_grad_fn) def _forward(x0, x1): return _rev_mp_block_forward(x0, x1, self.f, self.g, self.num_layers) return _forward(x0, x1) def backward(self, y0, y1): f = list(self.f) g = list(self.g) f.reverse() g.reverse() f_vars = [v for v in tf.trainable_variables() if 'rev_mp/layer_0' in v.name] print (y0, y1) for i in range(self.num_layers): x0_i = y0 if FLAGS.use_sigmoid: if FLAGS.function_type == "sigmoid": x1_i = tf.log(y1 + 1e-10) - tf.log(1 - y1 + 1e-10) - g[i](y0) else: x1_i = 0.5*(tf.log(1 + y1 + 1e-10) - tf.log(1 - y1 + 1e-10)) - g[i](x0_i) else: x1_i = y1 - g[i](x0_i) x1 = x1_i if FLAGS.use_sigmoid: if FLAGS.function_type == "sigmoid": x0 = tf.log(x0_i + 1e-10) - tf.log(1 - x0_i + 1e-10) - f[i](x1) else: x0 = 0.5*(tf.log(1 + x0_i + 1e-10) - tf.log(1 - x0_i + 1e-10)) - f[i](x1) else: x0 = x0_i - f[i](x1) y1, y0 = x1, x0 # y1 = tf.Print(y1,
########################################################################## # # OpenMP code generator # # This routine is called by op2_fortran which parses the input files # # It produces a file xxx_kernel.F90 for each kernel, # plus a master kernel file # ########################################################################## import re import datetime import os def comm(line): global file_text, FORTRAN, CPP global depth if len(line) == 0: prefix = '' else: prefix = ' '*depth if len(line) == 0: file_text +='\n' elif FORTRAN: file_text +='! '+line+'\n' elif CPP: file_text +=prefix+'//'+line+'\n' def rep(line,m): global dims, idxs, typs, indtyps, inddims if FORTRAN: if m < len(inddims): line = re.sub('INDDIM',str(inddims[m]),line) line = re.sub('INDTYP',str(indtyps[m]),line) line = re.sub('INDARG','ind_arg'+str(m+1),line) line = re.sub('DIMS',str(dims[m]),line) line = re.sub('ARG','arg'+str(m+1),line) line = re.sub('TYP',typs[m],line) line = re.sub('IDX',str(int(idxs[m])),line) elif CPP: line = re.sub('INDDIM',str(inddims[m]),line) line = re.sub('INDTYP',str(indtyps[m]),line) line = re.sub('INDARG','ind_arg'+str(m),line) line = re.sub('DIM',str(dims[m]),line) line = re.sub('ARG','arg'+str(m),line) line = re.sub('TYP',typs[m],line) line = re.sub('IDX',str(int(idxs[m])),line) return line def code(text): global file_text, FORTRAN, CPP, g_m global depth if len(text) == 0: file_text += '\n' return if len(text) == 0: prefix = '' else: prefix = ' '*depth if FORTRAN: file_text += prefix+rep(text,g_m)+'\n' elif CPP: file_text += prefix+rep(text,g_m)+'\n' def code_pre(text): global file_text, FORTRAN, CPP, g_m if FORTRAN: file_text += rep(text,g_m)+'\n' elif CPP: file_text += rep(text,g_m)+'\n' def DO(i,start,finish): global file_text, FORTRAN, CPP, g_m global depth if FORTRAN: code('DO '+i+' = '+start+', '+finish+'-1, 1') elif CPP: code('for ( int '+i+'='+start+'; '+i+'<'+finish+'; '+i+'++ ){') depth += 2 def FOR(i,start,finish): global file_text, FORTRAN, CPP, g_m global depth if FORTRAN: code('DO '+i+' = '+start+', '+finish+'-1') elif CPP: code('for ( int '+i+'='+start+'; '+i+'<'+finish+'; '+i+'++ ){') depth += 2 def ENDDO(): global file_text, FORTRAN, CPP, g_m global depth depth -= 2 if FORTRAN: code('END DO') elif CPP: code('}') def ENDFOR(): global file_text, FORTRAN, CPP, g_m global depth depth -= 2 if FORTRAN: code('END DO') elif CPP: code('}') def IF(line): global file_text, FORTRAN, CPP, g_m global depth if FORTRAN: code('IF ('+line+') THEN') elif CPP: code('if ('+ line + ') {') depth += 2 def ELSE(): global file_text, FORTRAN, CPP, g_m global depth depth -= 2 if FORTRAN: code('ELSE') elif CPP: code('else {') depth += 2 def ENDIF(): global file_text, FORTRAN, CPP, g_m global depth depth -= 2 if FORTRAN: code('END IF') elif CPP: code('}') def op2_gen_mpiseq2(master, date, consts, kernels, hydra): global dims, idxs, typs, indtyps, inddims global FORTRAN, CPP, g_m, file_text, depth OP_ID = 1; OP_GBL = 2; OP_MAP = 3; OP_READ = 1; OP_WRITE = 2; OP_RW = 3; OP_INC = 4; OP_MAX = 5; OP_MIN = 6; accsstring = ['OP_READ','OP_WRITE','OP_RW','OP_INC','OP_MAX','OP_MIN' ] any_soa = 0 for nk in range (0,len(kernels)): any_soa = any_soa or sum(kernels[nk]['soaflags']) ########################################################################## # create new kernel file ########################################################################## for nk in range (0,len(kernels)): name = kernels[nk]['name'] nargs = kernels[nk]['nargs'] dims = kernels[nk]['dims'] maps = kernels[nk]['maps'] var = kernels[nk]['var'] typs = kernels[nk]['typs'] accs = kernels[nk]['accs'] idxs = kernels[nk]['idxs'] inds = kernels[nk]['inds'] soaflags = kernels[nk]['soaflags'] optflags = kernels[nk]['optflags'] ninds = kernels[nk]['ninds'] inddims = kernels[nk]['inddims'] indaccs = kernels[nk]['indaccs'] indtyps = kernels[nk]['indtyps'] invinds = kernels[nk]['invinds'] optidxs = [0]*nargs indopts = [-1]*nargs nopts = 0 for i in range(0,nargs): if optflags[i] == 1 and maps[i] == OP_ID: optidxs[i] = nopts nopts = nopts+1 elif optflags[i] == 1 and maps[i] == OP_MAP: if i == invinds[inds[i]-1]: #i.e. I am the first occurence of this dat+map combination optidxs[i] = nopts indopts[inds[i]-1] = i nopts = nopts+1 else: optidxs[i] = optidxs[invinds[inds[i]-1]] # # set two logicals # j = -1 for i in range(0,nargs): if maps[i] == OP_MAP and accs[i] == OP_INC: j = i ind_inc = j >= 0 j = -1 for i in range(0,nargs): if maps[i] == OP_GBL and accs[i] <> OP_READ: j = i reduct = j >= 0 FORTRAN = 1; CPP = 0; g_m = 0; file_text = '' depth = 0 ########################################################################## # Generate Header ########################################################################## if hydra: code('MODULE '+kernels[nk]['mod_file'][4:]+'_MODULE') else: code('MODULE '+name.upper()+'_MODULE') code('USE OP2_FORTRAN_DECLARATIONS') code('USE OP2_FORTRAN_RT_SUPPORT') code('USE ISO_C_BINDING') if hydra == 0: code('USE OP2_CONSTANTS') code('') ########################################################################## # Inline user kernel function ########################################################################## code('') code('CONTAINS') code('') if hydra == 0: comm('user function') code('#include "'+name+'.inc"') code('') else: modfile = kernels[nk]['mod_file'][4:] filename = modfile.split('_')[1].lower() + '/' + modfile.split('_')[0].lower() + '/' + name + '.F95' if not os.path.isfile(filename): filename = modfile.split('_')[1].lower() + '/' + modfile.split('_')[0].lower() + '/' + name[:-1] + '.F95' fid = open(filename, 'r') text = fid.read() fid.close() text = text.replace('recursive subroutine','subroutine') text = text.replace('module','!module') text = text.replace('contains','!contains') text = text.replace('end !module','!end module') file_text += text #code(kernels[nk]['mod_file']) code('') ########################################################################## # Generate SEQ host stub ########################################################################## code('SUBROUTINE '+name+'_host( userSubroutine, set, &'); depth = depth + 2 for g_m in range(0,nargs): if g_m == nargs-1: code('& opArg'+str(g_m+1)+' )') else: code('& opArg'+str(g_m+1)+', &') code('') code('IMPLICIT NONE') code('character(kind=c_char,len=*), INTENT(IN) :: userSubroutine') code('type ( op_set ) , INTENT(IN) :: set') code('') for g_m in range(0,nargs): code('type ( op_arg ) , INTENT(IN) :: opArg'+str(g_m+1)) code('') code('type ( op_arg ) , DIMENSION('+str(nargs)+') :: opArgArray') code('INTEGER(kind=4) :: numberOfOpDats') code('INTEGER(kind=4), DIMENSION(1:8) :: timeArrayStart') code('INTEGER(kind=4), DIMENSION(1:8) :: timeArrayEnd') code('REAL(kind=8) :: startTime') code('REAL(kind=8) :: endTime') code('INTEGER(kind=4) :: returnSetKernelTiming') code('INTEGER(kind=4) :: n_upper') code('type ( op_set_core ) , POINTER :: opSetCore') code('') for g_m in range(0,ninds): code('INTEGER(kind=4), POINTER, DIMENSION(:) :: opDat'+str(invinds[g_m]+1)+'Map') code('INTEGER(kind=4) :: opDat'+str(invinds[g_m]+1)+'MapDim') code(typs[invinds[g_m]]+', POINTER, DIMENSION(:) :: opDat'+str(invinds[g_m]+1)+'Local') code('INTEGER(kind=4) :: opDat'+str(invinds[g_m]+1)+'Cardinality') code('') for g_m in range(0,nargs): if maps[g_m] == OP_ID: code(typs[g_m]+', POINTER, DIMENSION(:) :: opDat'+str(g_m+1)+'Local') code('INTEGER(kind=4) :: opDat'+str(g_m+1)+'Cardinality') code('') if maps[g_m] == OP_GBL: code(typs[g_m]+', POINTER, DIMENSION(:) :: opDat'+str(g_m+1)+'Local') for g_m in range(0,nargs): if maps[g_m] == OP_MAP and optflags[g_m]==1: code(typs[g_m]+', POINTER, DIMENSION(:) :: opDat'+str(g_m+1)+'OptPtr') code('') code('INTEGER(kind=4) :: i1') code('') code('numberOfOpDats = '+str(nargs)) code('') for g_m in range(0,nargs): code('opArgArray('+str(g_m+1)+') = opArg'+str(g_m+1)) code('') code('returnSetKernelTiming = setKernelTime('+str(nk)+' , userSubroutine//C_NULL_CHAR, &') code('& 0.d0, 0.00000,0.00000, 0)') code('call op_timers_core(startTime)') code('') #mpi halo exchange call code('n_upper = op_mpi_halo_exchanges(set%setCPtr,numberOfOpDats,opArgArray)') code('') code('opSetCore => set%setPtr') code('') for g_m in range(0,ninds): code('opDat'+str(invinds[g_m]+1)+'Cardinality = opArg'+str(invinds[g_m]+1)+'%dim * getSetSizeFromOpArg(opArg'+str(invinds[g_m]+1)+')') code('opDat'+str(invinds[g_m]+1)+'MapDim = getMapDimFromOpArg(opArg'+str(invinds[g_m]+1)+')') for g_m in range(0,nargs): if maps[g_m] == OP_ID: code('opDat'+str(g_m+1)+'Cardinality = opArg'+str(g_m+1)+'%dim * getSetSizeFromOpArg(opArg'+str(g_m+1)+')') for g_m in range(0,ninds): code('CALL c_f_pointer(opArg'+str(invinds[g_m]+1)+'%data,opDat'+str(invinds[g_m]+1)+'Local,(/opDat'+str(invinds[g_m]+1)+'Cardinality/))') code('CALL c_f_pointer(opArg'+str(invinds[g_m]+1)+'%map_data,opDat'+str(invinds[g_m]+1)+'Map,(/opSetCore%size*opDat'+str(invinds[g_m]+1)+'MapDim/))') for g_m in range(0,nargs): if maps[g_m] == OP_ID: code('CALL c_f_pointer(opArg'+str(g_m+1)+'%data,opDat'+str(g_m+1)+'Local,(/opDat'+str(g_m+1)+'Cardinality/))') elif maps[g_m] == OP_GBL: code('CALL c_f_pointer(opArg'+str(g_m+1)+'%data,opDat'+str(g_m+1)+'Local, (/opArg'+str(g_m+1)+'%dim/))') code('') code('') DO('i1','0','n_upper') if ninds > 0: IF('i1 .EQ. opSetCore%core_size') code('CALL op_mpi_wait_all(numberOfOpDats,opArgArray)') ENDIF() code('') for g_m in range(0,nargs): if maps[g_m] == OP_MAP and optflags[g_m]==1: IF('opArg'+str(g_m+1)+'%opt == 1') if (not dims[g_m].isdigit()) or int(dims[g_m]) > 1: code('opDat'+str(g_m+1)+'OptPtr => opDat'+str(invinds[inds[g_m]-1]+1)+'Local(1 + opDat'+str(invinds[inds[g_m]-1]+1)+'Map(1 + i1 * opDat'+str(invinds[inds[g_m]-1]+1)+'MapDim + '+str(int(idxs[g_m])-1)+') * ('+dims[g_m]+'):)') ELSE() code('opDat'+str(g_m+1)+'OptPtr => opDat'+str(invinds[inds[g_m]-1]+1)+'Local(1:)') ENDIF() comm('kernel call') line = 'CALL '+name+'( &' indent = '\n'+' '*depth for g_m in range(0,nargs): if maps[g_m] == OP_ID: if (not dims[g_m].isdigit()) or int(dims[g_m]) > 1: line = line + indent + '& opDat'+str(g_m+1)+'Local(1 + i1 * ('+dims[g_m]+') : i1 * ('+dims[g_m]+') + '+dims[g_m]+')' else: line = line + indent + '& opDat'+str(g_m+1)+'Local(1 + i1)' if maps[g_m] == OP_MAP and optflags[g_m]==0: if (not dims[g_m].isdigit()) or int(dims[g_m]) > 1: line = line +indent + '& opDat'+str(invinds[inds[g_m]-1]+1)+'Local(1 + opDat'+str(invinds[inds[g_m]-1]+1)+'Map(1 + i1 * opDat'+str(invinds[inds[g_m]-1]+1)+'MapDim + '+str(int(idxs[g_m])-1)+') * ('+dims[g_m]+') : opDat'+str(invinds[inds[g_m]-1]+1)+'Map(1 + i1 * opDat'+str(invinds[inds[g_m]-1]+1)+'MapDim + '+str(int(idxs[g_m])-1)+') * ('+dims[g_m]+') + '+dims[g_m]+')' else: line = line +indent + '& opDat'+str(invinds[inds[g_m]-1]+1)+'Local(1 + opDat'+str(invinds[inds[g_m]-1]+1)+'Map(1 + i1 * opDat'+str(invinds[inds[g_m]-1]+1)+'MapDim + '+str(int(idxs[g_m])-1)+'))' elif maps[g_m] == OP_MAP and optflags[g_m]==1: if (not dims[g_m].isdigit()) or int(dims[g_m]) > 1: line = line +indent + '& opDat'+str(g_m+1)+'OptPtr(1:'+dims[g_m]+')' else: line = line +indent + '& opDat'+str(g_m+1)+'OptPtr(1)' if maps[g_m] == OP_GBL: if (not dims[g_m].isdigit()) or int(dims[g_m]) > 1: line = line + indent +'& opDat'+str(g_m+1)+'Local(1:'+dims[g_m]+')' else: line = line + indent +'& opDat'+str(g_m+1)+'Local(1)' if g_m < nargs-1: line = line +', &' else: line = line +' &' depth = depth - 2 code(line + indent + '& )') depth = depth + 2 ENDDO() code('') IF('(n_upper .EQ. 0) .OR. (n_upper .EQ. opSetCore%core_size)') code('CALL op_mpi_wait_all(numberOfOpDats,opArgArray)') ENDIF() code('') code('') code('CALL op_mpi_set_dirtybit(numberOfOpDats,opArgArray)') code('') #reductions for g_m in range(0,nargs): if maps[g_m] == OP_GBL and (accs[g_m] == OP_INC or accs[g_m] == OP_MIN or accs[g_m] == OP_MAX or accs[g_m] == OP_WRITE): if typs[g_m] == 'real(8)' or typs[g_m] == 'REAL(kind=8)': code('CALL op_mpi_reduce_double(opArg'+str(g_m+1)+',opArg'+str(g_m+1)+'%data)') elif typs[g_m] == 'real(4)' or typs[g_m] == 'REAL(kind=4)': code('CALL op_mpi_reduce_float(opArg'+str(g_m+1)+',opArg'+str(g_m+1)+'%data)') elif typs[g_m] == 'integer(4)' or typs[g_m] == 'INTEGER(kind=4)': code('CALL op_mpi_reduce_int(opArg'+str(g_m+1)+',opArg'+str(g_m+1)+'%data)') elif typs[g_m] == 'logical' or typs[g_m] == 'logical*1': code('CALL op_mpi_reduce_bool(opArg'+str(g_m+1)+',opArg'+str(g_m+1)+'%data)') code('') code('call op_timers_core(endTime)') code('') code('returnSetKernelTiming = setKernelTime('+str(nk)+' , userSubroutine//C_NULL_CHAR, &') code('& endTime-startTime,0.00000,0.00000, 1)') depth = depth - 2 code('END SUBROUTINE') code('END
= { 'userKey': user_id, } service = get_service( 'admin', 'directory_v1', ['https://www.googleapis.com/auth/admin.directory.user.security']) result = service.tokens().list(**command_args).execute() return result.get('items', []) def search_all_mailboxes(): next_page_token = None service = get_service('admin', 'directory_v1') while True: command_args = { 'maxResults': 100, 'domain': ADMIN_EMAIL.split('@')[1], # type: ignore 'pageToken': next_page_token } result = service.users().list(**command_args).execute() next_page_token = result.get('nextPageToken') entries = [search_command(user['primaryEmail']) for user in result['users']] # if these are the final result push - return them if next_page_token is None: entries.append("Search completed") return entries # return midway results demisto.results(entries) def search_command(mailbox=None): args = demisto.args() user_id = args.get('user-id') if mailbox is None else mailbox mailbox = ADMIN_EMAIL if user_id == 'me' else user_id subject = args.get('subject', '') _from = args.get('from', '') to = args.get('to', '') before = args.get('before', '') after = args.get('after', '') filename = args.get('filename', '') _in = args.get('in', '') query = args.get('query', '') fields = args.get('fields') # TODO label_ids = [lbl for lbl in args.get('labels-ids', '').split(',') if lbl != ''] max_results = int(args.get('max-results', 100)) page_token = args.get('page-token') include_spam_trash = args.get('include-spam-trash', False) has_attachments = args.get('has-attachments') has_attachments = None if has_attachments is None else bool( strtobool(has_attachments)) if max_results > 500: raise ValueError( 'maxResults must be lower than 500, got %s' % (max_results, )) mails, q = search(user_id, subject, _from, to, before, after, filename, _in, query, fields, label_ids, max_results, page_token, include_spam_trash, has_attachments) res = emails_to_entry('Search in {}:\nquery: "{}"'.format(mailbox, q), mails, 'full', mailbox) return res def search(user_id, subject='', _from='', to='', before='', after='', filename='', _in='', query='', fields=None, label_ids=None, max_results=100, page_token=None, include_spam_trash=False, has_attachments=None): query_values = { 'subject': subject, 'from': _from, 'to': to, 'before': before, 'after': after, 'filename': filename, 'in': _in, 'has': 'attachment' if has_attachments else '' } q = ' '.join('%s:%s ' % (name, value, ) for name, value in query_values.iteritems() if value != '') q = ('%s %s' % (q, query, )).strip() command_args = { 'userId': user_id, 'q': q, 'maxResults': max_results, 'fields': fields, 'labelIds': label_ids, 'pageToken': page_token, 'includeSpamTrash': include_spam_trash, } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.readonly'], command_args['userId']) result = service.users().messages().list(**command_args).execute() return [get_mail(user_id, mail['id'], 'full') for mail in result.get('messages', [])], q def get_mail_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) _id = args.get('message-id') _format = args.get('format') mail = get_mail(user_id, _id, _format) return emails_to_entry('Email:', [mail], _format, user_id) def get_mail(user_id, _id, _format): command_args = { 'userId': user_id, 'id': _id, 'format': _format, } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.readonly'], delegated_user=command_args['userId']) result = service.users().messages().get(**command_args).execute() return result def get_attachments_command(): args = demisto.args() user_id = args.get('user-id') _id = args.get('message-id') attachments = get_attachments(user_id, _id) return [fileResult(name, data) for name, data in attachments] def get_attachments(user_id, _id): mail_args = { 'userId': user_id, 'id': _id, 'format': 'full', } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.readonly'], delegated_user=mail_args['userId']) result = service.users().messages().get(**mail_args).execute() result = get_email_context(result, user_id)[0] command_args = { 'userId': user_id, 'messageId': _id, } files = [] for attachment in result['Attachments']: command_args['id'] = attachment['ID'] result = service.users().messages().attachments().get(**command_args).execute() file_data = base64.urlsafe_b64decode(result['data'].encode('ascii')) files.append((attachment['Name'], file_data)) return files def move_mail_command(): args = demisto.args() user_id = args.get('user-id') _id = args.get('message-id') add_labels = [lbl for lbl in args.get('add-labels', '').split(',') if lbl != ''] remove_labels = [lbl for lbl in args.get( 'remove-labels', '').split(',') if lbl != ''] mail = move_mail(user_id, _id, add_labels, remove_labels) return emails_to_entry('Email:', [mail], 'full', user_id) def move_mail(user_id, _id, add_labels, remove_labels): command_args = { 'userId': user_id, 'id': _id, 'body': { 'addLabelIds': add_labels, 'removeLabelIds': remove_labels, } } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.modify'], delegated_user=user_id) result = service.users().messages().modify(**command_args).execute() return result def move_mail_to_mailbox_command(): args = demisto.args() src_user_id = args.get('src-user-id') message_id = args.get('message-id') dst_user_id = args.get('dst-user-id') new_mail_id = move_mail_to_mailbox(src_user_id, message_id, dst_user_id) mail = get_mail(dst_user_id, new_mail_id, 'full') return emails_to_entry('Email:', [mail], 'full', dst_user_id) def move_mail_to_mailbox(src_mailbox, message_id, dst_mailbox): # get the original mail mail = get_mail(src_mailbox, message_id, 'raw') # import the mail to the destination mailbox command_args = { 'userId': dst_mailbox, 'body': { 'raw': mail['raw'], } } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.modify'], delegated_user=dst_mailbox) result = service.users().messages().import_(**command_args).execute() # delete the original mail delete_mail(src_mailbox, message_id, True) return result['id'] def delete_mail_command(): args = demisto.args() user_id = args['user-id'] _id = args['message-id'] permanent = bool(strtobool(args.get('permanent', 'false'))) return delete_mail(user_id, _id, permanent) def delete_mail(user_id, _id, permanent): command_args = { 'userId': user_id, 'id': _id, } service = get_service( 'gmail', 'v1', ['https://mail.google.com', 'https://www.googleapis.com/auth/gmail.modify'], delegated_user=command_args['userId']) if permanent: service.users().messages().delete(**command_args).execute() return 'Email has been successfully deleted.' else: service.users().messages().trash(**command_args).execute() return 'Email has been successfully moved to trash.' def get_thread_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) _id = args.get('thread-id') _format = args.get('format') messages = get_thread(user_id, _id, _format) return emails_to_entry('Emails of Thread:', messages, _format, user_id) def get_thread(user_id, _id, _format): command_args = { 'userId': user_id, 'id': _id, 'format': _format } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.readonly'], delegated_user=user_id) result = service.users().threads().get(**command_args).execute() return result['messages'] def add_delete_filter_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) user_id = user_id if user_id.lower() != 'me' else ADMIN_EMAIL _from = args.get('email-address') _filter = add_filter(user_id, _from=_from, add_labels=['TRASH', ]) return filters_to_entry('New filter:', user_id, [_filter]) def add_filter_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) user_id = user_id if user_id.lower() != 'me' else ADMIN_EMAIL _from = args.get('from') to = args.get('to') subject = args.get('subject') query = args.get('query') has_attachments = args.get('has-attachments') size = args.get('size') size_comparison = args.get('size-comparison') forward = args.get('forward') add_labels = args.get('add-labels', '').split(',') add_labels = add_labels if any(add_labels) else None remove_labels = args.get('remove-labels', '').split(',') remove_labels = remove_labels if any(remove_labels) else None _filter = add_filter(user_id, _from=_from, to=to, subject=subject, query=query, has_attachments=has_attachments, size=size, size_comparison=size_comparison, forward=forward, add_labels=add_labels, remove_labels=remove_labels, ) return filters_to_entry('New filter:', user_id, [_filter]) def add_filter(user_id, _from=None, to=None, subject=None, query=None, has_attachments=None, size=None, size_comparison=None, forward=None, add_labels=None, remove_labels=None): command_args = { 'userId': user_id, 'body': { 'criteria': {}, 'action': {}, } } if _from is not None: command_args['body']['criteria']['from'] = _from if to is not None: command_args['body']['criteria']['to'] = to if subject is not None: command_args['body']['criteria']['subject'] = subject if query is not None: command_args['body']['criteria']['query'] = query if has_attachments is not None: command_args['body']['criteria']['hasAttachment'] = has_attachments if size is not None: command_args['body']['criteria']['size'] = size if size_comparison is not None: command_args['body']['criteria']['size_comparison'] = size_comparison if add_labels is not None: command_args['body']['action']['addLabelIds'] = add_labels if remove_labels is not None: command_args['body']['action']['removeLabelIds'] = remove_labels if forward is not None: command_args['body']['action']['forward'] = forward service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.settings.basic'], delegated_user=user_id) result = service.users().settings().filters().create(**command_args).execute() return result def list_filters_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) user_id = user_id if user_id.lower() != 'me' else ADMIN_EMAIL address = args.get('address') limit = int(args.get('limit', 100)) filters = list_filters( user_id, address=address, limit=limit) return filters_to_entry('filters:', user_id, filters) def list_filters(user_id, address=None, limit=100): command_args = { 'userId': user_id, } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.settings.basic'], delegated_user=user_id) result = service.users().settings().filters().list(**command_args).execute() filters = result.get('filter', []) if address is not None: filters = [f for f in filters if address in {f['criteria'].get('from'), f['criteria'].get('to')}] return filters[:limit] def remove_filter_command(): args = demisto.args() user_id = args.get('user-id', ADMIN_EMAIL) ids = args.get('filter_ids', '') if isinstance(ids, STRING_TYPES): # alternativly it could be an array ids = ids.split(',') for _id in ids: remove_filter(user_id, _id) return 'filters were removed successfully.' def remove_filter(user_id, _id): command_args = { 'userId': user_id, 'id': _id } service = get_service( 'gmail', 'v1', ['https://www.googleapis.com/auth/gmail.settings.basic'], delegated_user=user_id) result = service.users().settings().filters().delete(**command_args).execute() return result '''MAIL SENDER FUNCTIONS''' def randomword(length): """ Generate a random string of given length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) def header(s): if not s: return None s_no_newlines = ' '.join(s.splitlines()) return Header(s_no_newlines, 'utf-8') def template_params(paramsStr): """ Translate the template params if they exist from the context """ actualParams = {} if paramsStr: try: params = json.loads(paramsStr) except ValueError as e: return_error('Unable to parse templateParams: {}'.format(str(e))) # Build a simple key/value for p in params: if params[p].get('value'): actualParams[p] = params[p]['value'] elif params[p].get('key'): actualParams[p] = demisto.dt(demisto.context(), params[p]['key']) return actualParams else: return None def transient_attachments(transientFile, transientFileContent, transientFileCID): if transientFile is None or len(transientFile) == 0: return [] if transientFileContent is None: transientFileContent = [] if transientFileCID is None: transientFileCID = [] attachments = [] for file_name, file_data, file_cid in it.izip_longest(transientFile, transientFileContent, transientFileCID): if file_name is None: break content_type, encoding = mimetypes.guess_type(file_name) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) attachments.append({ 'name': file_name, 'maintype': main_type, 'subtype': sub_type, 'data': file_data, 'cid': file_cid }) return attachments def handle_html(htmlBody): """ Extract all data-url content from within the html and return as separate attachments. Due to security implications, we support only images here We might not have Beautiful Soup so just do regex search """ attachments =
file...") print('Writing dataset to a file...Please wait...') f = open(full_path_to_TXT_dataset, 'wb') f.write(TXT_String.encode('utf-8', 'replace')) f.close() print('Dataset was saved as:', full_path_to_TXT_dataset) print('Task complete! Enjoy :)') ################################################################################### def Tegridy_Pickle_File_Writer(Data, input_file_name='TMIDI_Pickle_File'): '''Tegridy Pickle File Writer Input: Data to write (I.e. a list) Full path and file name without extention Output: Named Pickle file Project Los Angeles Tegridy Code 2021''' print('Tegridy Pickle File Writer') full_path_to_output_dataset_to = input_file_name + '.pickle' if os.path.exists(full_path_to_output_dataset_to): os.remove(full_path_to_output_dataset_to) print('Removing old Dataset...') else: print("Creating new Dataset file...") with open(full_path_to_output_dataset_to, 'wb') as filehandle: # store the data as binary data stream pickle.dump(Data, filehandle, protocol=pickle.HIGHEST_PROTOCOL) print('Dataset was saved as:', full_path_to_output_dataset_to) print('Task complete. Enjoy! :)') ################################################################################### def Tegridy_Pickle_File_Loader(input_file_name='TMIDI_Pickle_File', ext='.pickle'): '''Tegridy Pickle File Loader Input: Full path and file name without extention File extension if different from default .pickle Output: Chords list in TMIDI MIDI Processor format Melody list in TMIDI MIDI Processor format Project Los Angeles Tegridy Code 2021''' print('Tegridy Pickle File Loader') print('Loading the pickle file. Please wait...') dataset = open(input_file_name + ext, "rb") chords_list_f, melody_list_f = pickle.load(dataset) dataset.close() print('Loading complete.') print('Number of MIDI chords recorded:', len(chords_list_f)) print('The longest chord:', len(max(chords_list_f, key=len)), 'notes') print(max(chords_list_f, key=len)) print('Number of recorded melody events:', len(melody_list_f)) print('First melody event:', melody_list_f[0], 'Last Melody event:', melody_list_f[-1]) print('Total number of MIDI events recorded:', len(chords_list_f)) print('Task complete. Enjoy! :)') return chords_list_f, melody_list_f def Tegridy_Any_Pickle_File_Loader(input_file_name='TMIDI_Pickle_File', ext='.pickle'): '''Tegridy Pickle File Loader Input: Full path and file name without extention File extension if different from default .pickle Output: Standard Python 3 unpickled data object Project Los Angeles Tegridy Code 2021''' print('Tegridy Pickle File Loader') print('Loading the pickle file. Please wait...') with open(input_file_name + ext, 'rb') as pickle_file: content = pickle.load(pickle_file) return content ################################################################################### def Tegridy_Karaoke_Pitches_Words_List_to_CSV_Writer(pitches_words_list, file_name='pitches_words.csv'): '''Tegridy Karaoke Pitches Words List to CSV Writer Input: Pitches/Words list in TMIDI Karaoke MIDI to TXT Converter format Desired full output CSV file name with extension Output: CSV file with all Pitches/Words that were in the input pitches/words list Project Los Angeles Tegridy Code 2021''' print('Tegridy Karaoke Pitches/Words CSV Writer') print('Starting up...') print('Grouping input pitches/words list...Please stand by...') values = set(map(lambda x:x[0], pitches_words_list)) groups = [[y for y in pitches_words_list if y[0]==x] for x in values] print('Preparing final CSV list...') final_list = {} for g in groups: pitch = g[0][0] f_list = [] for value in g: if value[1] not in f_list: f_list.append(value[1]) final_list[pitch] = f_list print('Writing CSV file to disk...') with open(file_name,'w',newline='') as f: w = csv.writer(f) w.writerow(['pitch','words']) for key,items in final_list.items(): w.writerow([key, ' '.join(sorted(items))]) print('Task complete! Enjoy :)') ################################################################################### # TMIDI 2.0 Code is below ################################################################################### def Optimus_MIDI_TXT_Processor(MIDI_file, line_by_line_output=True, chordify_TXT=False, dataset_MIDI_events_time_denominator=1, output_velocity=True, output_MIDI_channels = False, MIDI_channel=0, MIDI_patch=[0, 1], char_offset = 30000, transpose_by = 0, flip=False, melody_conditioned_encoding=False, melody_pitch_baseline = 0, number_of_notes_to_sample = -1, sampling_offset_from_start = 0, karaoke=False, karaoke_language_encoding='utf-8', song_name='Song', perfect_timings=False, musenet_encoding=False, transform=0): '''Project Los Angeles Tegridy Code 2021''' ########### debug = False ev = 0 chords_list_final = [] chords_list = [] events_matrix = [] melody = [] melody1 = [] itrack = 1 min_note = 0 max_note = 0 ev = 0 patch = 0 score = [] rec_event = [] txt = '' txtc = '' chords = [] melody_chords = [] karaoke_events_matrix = [] karaokez = [] sample = 0 start_sample = 0 bass_melody = [] ########### def list_average(num): sum_num = 0 for t in num: sum_num = sum_num + t avg = sum_num / len(num) return avg ########### #print('Loading MIDI file...') midi_file = open(MIDI_file, 'rb') if debug: print('Processing File:', file_address) try: opus = midi2opus(midi_file.read()) except: print('Problematic MIDI. Skipping...') print('File name:', MIDI_file) midi_file.close() return txt, melody, chords midi_file.close() score1 = to_millisecs(opus) score2 = opus2score(score1) # score2 = opus2score(opus) # TODO Improve score timings when it will be possible. if MIDI_channel == 16: # Process all MIDI channels score = score2 if MIDI_channel >= 0 and MIDI_channel <= 15: # Process only a selected single MIDI channel score = grep(score2, [MIDI_channel]) if MIDI_channel == -1: # Process all channels except drums (except channel 9) score = grep(score2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15]) #print('Reading all MIDI events from the MIDI file...') while itrack < len(score): for event in score[itrack]: if perfect_timings: if event[0] == 'note': event[1] = round(event[1], -1) event[2] = round(event[2], -1) if event[0] == 'text_event' or event[0] == 'lyric' or event[0] == 'note': karaokez.append(event) if event[0] == 'text_event' or event[0] == 'lyric': try: event[2] = str(event[2].decode(karaoke_language_encoding, 'replace')).replace('/', '').replace(' ', '').replace('\\', '') except: event[2] = str(event[2]).replace('/', '').replace(' ', '').replace('\\', '') continue karaoke_events_matrix.append(event) if event[0] == 'patch_change': patch = event[3] if event[0] == 'note' and patch in MIDI_patch: if len(event) == 6: # Checking for bad notes... eve = copy.deepcopy(event) eve[1] = int(event[1] / dataset_MIDI_events_time_denominator) eve[2] = int(event[2] / dataset_MIDI_events_time_denominator) eve[4] = int(event[4] + transpose_by) if flip == True: eve[4] = int(127 - (event[4] + transpose_by)) if number_of_notes_to_sample > -1: if sample <= number_of_notes_to_sample: if start_sample >= sampling_offset_from_start: events_matrix.append(eve) sample += 1 ev += 1 else: start_sample += 1 else: events_matrix.append(eve) ev += 1 start_sample += 1 itrack +=1 # Going to next track... #print('Doing some heavy pythonic sorting...Please stand by...') fn = os.path.basename(MIDI_file) song_name = song_name.replace(' ', '_').replace('=', '_').replace('\'', '-') if song_name == 'Song': sng_name = fn.split('.')[0].replace(' ', '_').replace('=', '_').replace('\'', '-') song_name = sng_name txt += 'SONG=' + song_name + '_with_' + str(len(events_matrix)-1) + '_notes' txtc += 'SONG=' + song_name + '_with_' + str(len(events_matrix)-1) + '_notes' if line_by_line_output: txt += chr(10) txtc += chr(10) else: txt += chr(32) txtc += chr(32) #print('Sorting input by start time...') events_matrix.sort(key=lambda x: x[1]) # Sorting input by start time chords.extend(events_matrix) #print(chords) #print('Extracting melody...') melody_list = [] #print('Grouping by start time. This will take a while...') values = set(map(lambda x:x[1], events_matrix)) # Non-multithreaded function version just in case groups = [[y for y in events_matrix if y[1]==x and len(y) == 6] for x in values] # Grouping notes into chords while discarting bad notes... #print('Sorting events...') for items in groups: items.sort(reverse=True, key=lambda x: x[4]) # Sorting events by pitch if melody_conditioned_encoding: items[0][3] = 0 # Melody should always bear MIDI Channel 0 for code to work melody_list.append(items[0]) # Creating final melody list melody_chords.append(items) # Creating final chords list bass_melody.append(items[-1]) # Creating final bass melody list # [WIP] Melody-conditioned chords list if melody_conditioned_encoding == True: if not karaoke: previous_event = copy.deepcopy(melody_chords[0][0]) for ev in melody_chords: hp = True ev.sort(reverse=False, key=lambda x: x[4]) # Sorting chord events by pitch for event in ev: # Computing events details start_time = int(event[1] - previous_event[1]) duration = int(previous_event[2]) if hp == True: if int(previous_event[4]) >= melody_pitch_baseline: channel = int(0) hp = False else: channel = int(previous_event[3]+1) hp = False else: channel = int(previous_event[3]+1) hp = False pitch = int(previous_event[4]) velocity = int(previous_event[5]) # Converting to TXT if possible... try: txtc += str(chr(start_time + char_offset)) txtc += str(chr(duration + char_offset)) txtc += str(chr(pitch + char_offset)) if output_velocity: txtc += str(chr(velocity + char_offset)) if output_MIDI_channels: txtc += str(chr(channel + char_offset)) if line_by_line_output: txtc += chr(10) else: txtc += chr(32) previous_event = copy.deepcopy(event) except: # print('Problematic MIDI event! Skipping...') continue if not line_by_line_output: txtc += chr(10) txt = txtc chords = melody_chords # Default stuff (not melody-conditioned/not-karaoke) else: melody_chords.sort(reverse=False, key=lambda x: x[0][1]) mel_chords = [] for mc in melody_chords: mel_chords.extend(mc) if transform != 0: chords = Tegridy_Transform(mel_chords, transform) else: chords = mel_chords # TXT Stuff previous_event = copy.deepcopy(chords[0]) for event in chords: # Computing events details start_time = int(event[1] - previous_event[1]) duration = int(previous_event[2]) channel = int(previous_event[3]) pitch = int(previous_event[4] + transpose_by) if flip == True: pitch = 127 - int(previous_event[4] + transpose_by) velocity = int(previous_event[5]) # Converting to TXT if possible... try: txt += str(chr(start_time + char_offset))
import datetime import os, sys import numpy as np import matplotlib.pyplot as plt import casadi as cas ##### For viewing the videos in Jupyter Notebook import io import base64 from IPython.display import HTML # from ..</src> import car_plotting # from .import src.car_plotting PROJECT_PATH = '/home/nbuckman/Dropbox (MIT)/DRL/2020_01_cooperative_mpc/mpc-multiple-vehicles/' sys.path.append(PROJECT_PATH) import src.MPC_Casadi as mpc import src.car_plotting as cplot import src.TrafficWorld as tw np.set_printoptions(precision=2) import src.IterativeBestResponseMPCMultiple as mibr import pickle SAVE = False PLOT = False rounds_ibr = 225 n_other_cars = 4 N = 50 ###### LATEX Dimensions (Not currently Working) fig_width_pt = 246.0 # Get this from LaTeX using \showthe\columnwidth inches_per_pt = 1.0/72.27 # Convert pt to inches golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio fig_width = fig_width_pt*inches_per_pt # width in inches fig_height =fig_width*golden_mean # height in inches fig_size = [fig_width,fig_height] fig_size = [6, 4] #################33 def find_t_final(x, goal_x): i_upper = np.searchsorted(x[0,:], goal_x) i_lower = i_upper - 1 dt = 0.2 # if i_upper >= x.shape[1]: # print(i_upper, x[0,i_lower]) # print("Check: %.03f < %.03f"%(x[0,i_lower], goal_x)) t_lower = i_lower*dt x_lower = x[0, i_lower] x_remaining = goal_x - x_lower v_x = np.cos(x[2, i_lower]) * x[4, i_lower] t_remaining = x_remaining / v_x t_final = t_lower + t_remaining # print("%.03f %.03f"%(t_lower, t_final)) return t_final #### STEP 1: Sort all the files into the correct SVO all_subdir = [ "20200301_215332random_ego", "20200301_215346random_pro", "20200301_215432random_altru", "20200301_215520random_pro", "20200301_215526random_altru", "20200301_215537random_ego", "20200301_215551random_pro", "20200301_215602random_altru", "20200301_215608random_ego", "20200301_215623random_pro", "20200301_215629random_altru", "20200301_215636random_ego", "20200301_215652random_pro", "20200301_215658random_altru", "20200301_215703random_ego", "20200301_215713random_pro", "20200301_215724random_altru", "20200301_215742random_ego", "20200301_215751random_pro", "20200301_215757random_altru", "20200301_215806random_ego", "20200302_104840random_1p", "20200302_104913random_2p", "20200302_104916random_3p", "20200302_104920random_4p", "20200302_104926random_1e", "20200302_104941random_2e", "20200302_104946random_3e", "20200302_105002random_4e", "20200302_105059random_1a", "20200302_105101random_2a", "20200302_105104random_3a", "20200302_105108random_4a", "20200302_114834random_5e", "20200302_114839random_6e", "20200302_114841random_7e", "20200302_114844random_8e", "20200302_114853random_5p", "20200302_114856random_6p", "20200302_114859random_7p", "20200302_114902random_8p", "20200302_114909random_5a", "20200302_114912random_6a", "20200302_114914random_7a", "20200302_114916random_8a", "20200227_133704less_kxdotlarger", "20200228_114359random_pro", "20200228_114437random_pro", "20200228_114440random_pro", "20200228_114443random_pro", "20200228_114448random_pro", "20200228_114450random_pro", "20200228_114913random_pro", "20200228_114914random_pro", "20200228_114916random_pro", "20200228_114917random_pro", "20200227_142916pi_01_ego", "20200228_114517random_ego", "20200228_114518random_ego", "20200228_114528random_ego", "20200228_114532random_ego", "20200228_114547random_ego", "20200228_114551random_ego", "20200228_114803random_ego", "20200228_114805random_ego", "20200228_114806random_ego", "20200227_141954pi2_5altru", "20200228_114501random_altru", "20200228_114503random_altru", "20200228_114505random_altru", "20200228_114506random_altru", "20200228_114507random_altru", "20200228_114509random_altru", "20200228_114850random_altru", "20200228_114851random_altru", "20200228_114852random_altru", ] subdir_name_prosocial_list = [] subdir_name_ego_list = [] subdir_name_altruistic_list = [] altr_theta = [] ego_theta = [] pro_theta = [] NO_GRASS = False world = tw.TrafficWorld(2, 0, 1000) for subdir in all_subdir: try: file_name = "results/" + subdir+"/data/"+"mpc3.p" mpc = pickle.load(open(file_name,'rb')) if mpc.min_y < -999999 or mpc.max_y > 9999999: print("Messed up ymin/max", file_name) continue elif mpc.min_y > world.y_min + 0.000001: print("Grass is NOT allowed!", file_name) if not NO_GRASS: print("Too grass lmmited, ignored", file_name) continue elif mpc.min_y <= world.y_min + 0.00001: print("Grass is allowed!", file_name) if NO_GRASS: print("NO Grass, dataset ignored", file_name) continue if mpc.theta_iamb > np.pi/3: subdir_name_altruistic_list += [subdir] altr_theta += [mpc.theta_iamb] elif mpc.theta_iamb <= np.pi/6.0: subdir_name_ego_list += [subdir] ego_theta += [mpc.theta_iamb] else: subdir_name_prosocial_list += [subdir] pro_theta += [mpc.theta_iamb] except FileNotFoundError: print("Not found:", file_name) print("Atruistic np.pi/2 = 1.5ish") print(subdir_name_altruistic_list) print(altr_theta) print("Egoistic 0") print(subdir_name_ego_list) print(ego_theta) print("Pro-Social", np.pi/2) print(subdir_name_prosocial_list) print(pro_theta) # subdir_name_prosocial_list = [ # "20200227_133704less_kxdotlarger", # "20200228_114359random_pro", # "20200228_114437random_pro", # "20200228_114440random_pro", # "20200228_114443random_pro", # "20200228_114448random_pro", # "20200228_114450random_pro", # "20200228_114913random_pro", # "20200228_114914random_pro", # "20200228_114916random_pro", # "20200228_114917random_pro", # ] # subdir_name_prosocial = "20200227_133704less_kxdotlarger" # folder_prosocial = "results/" + subdir_name_prosocial + "/" # subdir_name_ego_list = [ # "20200227_142916pi_01_ego", # "20200228_114517random_ego", # "20200228_114518random_ego", # "20200228_114528random_ego", # "20200228_114532random_ego", # "20200228_114547random_ego", # "20200228_114551random_ego", # "20200228_114803random_ego", # "20200228_114805random_ego", # "20200228_114806random_ego", # ] # subdir_name_ego = "20200227_142916pi_01_ego" # folder_ego = "results/" + subdir_name_ego + "/" # subdir_name_altruistic_list = [ # "20200227_141954pi2_5altru", # "20200228_114501random_altru", # "20200228_114503random_altru", # "20200228_114505random_altru", # "20200228_114506random_altru", # "20200228_114507random_altru", # "20200228_114509random_altru", # "20200228_114850random_altru", # "20200228_114851random_altru", # "20200228_114852random_altru"] # subdir_name_altruistic = "20200227_141954pi2_5altru" # folder_altruistic = "results/" + subdir_name_altruistic + "/" ################ Analyze Results all_xamb_pro = [] all_uamb_pro = [] all_other_x_pro = [] all_other_u_pro = [] ibr_brounds_array_pro = [] all_xamb_ego = [] all_uamb_ego = [] all_other_x_ego = [] all_other_u_ego = [] ibr_brounds_array_ego = [] all_xamb_altru = [] all_uamb_altru = [] all_other_x_altru = [] all_other_u_altru = [] ibr_brounds_array_altru = [] all_tfinalamb_pro = [] all_tfinalamb_ego = [] all_tfinalamb_altru = [] for sim_i in range(3): if sim_i==0: subdir_name_list = subdir_name_prosocial_list elif sim_i==1: subdir_name_list = subdir_name_ego_list else: subdir_name_list = subdir_name_altruistic_list for folder in subdir_name_list: n_full_rounds = 0 # rounods that the ambulance planned n_all_rounds = 0 all_xamb = np.zeros((6, N+1, rounds_ibr)) all_uamb = np.zeros((2, N, rounds_ibr)) all_xcost = np.zeros((3, rounds_ibr)) all_tfinalamb = np.zeros((1, rounds_ibr)) all_other_x = [np.zeros((6, N+1, rounds_ibr)) for i in range(n_other_cars)] all_other_u = [np.zeros((2, N, rounds_ibr)) for i in range(n_other_cars)] all_other_cost = [np.zeros((3, rounds_ibr)) for i in range(n_other_cars)] all_other_tfinal = [np.zeros((1, rounds_ibr)) for i in range(n_other_cars)] for amb_ibr_i in range(rounds_ibr): if (amb_ibr_i % (n_other_cars + 1) == 1) and amb_ibr_i>51: # We only look at sims when slack activated ibr_prefix = '%03d'%amb_ibr_i try: xamb, uamb, xamb_des, xothers, uothers, xothers_des = mibr.load_state("results/" + folder + "/" + "data/" + ibr_prefix, n_other_cars) all_xamb[:,:,n_full_rounds] = xamb all_uamb[:,:,n_full_rounds] = uamb x_goal = 130 all_tfinalamb[:, n_full_rounds] = find_t_final(xamb, x_goal) for i in range(n_other_cars): all_other_x[i][:,:,n_full_rounds] = xothers[i] all_other_u[i][:,:,n_full_rounds] = uothers[i] # all_other_tfinal[i][:,n_full_rounds] = find_t_final(xothers[i], 120) n_full_rounds += 1 except FileNotFoundError: # print("amb_ibr_i %d missing"%amb_ibr_i) pass n_all_rounds += 1 ### Clip the extra dimension all_xamb = all_xamb[:,:,:n_full_rounds] all_uamb = all_uamb[:,:,:n_full_rounds] all_tfinalamb = all_tfinalamb[:,:n_full_rounds] for i in range(n_other_cars): all_other_x[i] = all_other_x[i][:,:,:n_full_rounds] all_other_u[i] = all_other_u[i][:,:,:n_full_rounds] ibr_brounds_array = np.array(range(1, n_full_rounds +1)) if n_full_rounds > 0 : # only save those that meet slack requirement if sim_i==0: #prosocial directory all_xamb_pro += [all_xamb] all_uamb_pro += [all_uamb] all_other_x_pro += [all_other_x] all_other_u_pro += [all_other_u] ibr_brounds_array_pro += [ibr_brounds_array] all_tfinalamb_pro += [all_tfinalamb] elif sim_i==1: #egoistic directory all_xamb_ego += [all_xamb] all_uamb_ego += [all_uamb] all_other_x_ego += [all_other_x] all_other_u_ego += [all_other_u] ibr_brounds_array_ego += [ibr_brounds_array] all_tfinalamb_ego += [all_tfinalamb] else: #altruistic directory all_xamb_altru += [all_xamb] all_uamb_altru += [all_uamb] all_other_x_altru += [all_other_x] all_other_u_altru += [all_other_u] ibr_brounds_array_altru += [ibr_brounds_array] all_tfinalamb_altru += [all_tfinalamb] else: print("No slack eligible", folder) ### SAVING IN PROSOCIAL'S DIRECTORy folder = "random" #<---- fig_trajectory, ax_trajectory = plt.subplots(1,1) ax_trajectory.set_title("Ambulance Trajectories") # fig_trajectory.set_figheight(fig_height) # fig_trajectory.set_figwidth(fig_width) fig_trajectory.set_size_inches((8,6)) print(len(all_xamb_pro)) print(all_xamb_pro[0].shape) ax_trajectory.plot(all_xamb_pro[0][0,:,-1], all_xamb_pro[0][1,:,-1], '-o', label="Prosocial") ax_trajectory.plot(all_xamb_ego[0][0,:,-1], all_xamb_ego[0][1,:,-1], '-o', label="Egoistic") ax_trajectory.plot(all_xamb_altru[0][0,:,-1], all_xamb_altru[0][1,:,-1], '-o', label="Altruistic") ax_trajectory.set_xlabel("X [m]") ax_trajectory.set_ylabel("Y [m]") if SAVE: fig_file_name = folder + 'plots/' + 'cfig1_amb_trajectory.eps' fig_trajectory.savefig(fig_file_name, dpi=95, format='eps') print("Save to....", fig_file_name) ##########################################333333 svo_labels = ["Egoistic", "Prosocial", "Altruistic"] fig_uamb, ax_uamb = plt.subplots(3,1) fig_uamb.set_size_inches((8,8)) fig_uamb.suptitle("Ambulance Control Input over IBR Iterations") # ax_uamb[0].plot(ibr_brounds_array, np.sum(all_uamb[0,:,:] * all_uamb[0,:,:], axis=0), '-o') ax_uamb[0].bar(range(3), [ np.mean([np.sum(all_x[0,:,-1] * all_x[0,:,-1],axis=0) for all_x in all_uamb_ego]), np.mean([np.sum(all_x[0,:,-1] * all_x[0,:,-1],axis=0) for all_x in all_uamb_pro]), np.mean([np.sum(all_x[0,:,-1] * all_x[0,:,-1],axis=0) for all_x in all_uamb_altru])] ) # ax_uamb[0].set_xlabel("IBR Iteration") ax_uamb[0].set_ylabel(r"$\sum u_{\delta}^2$") ax_uamb[0].set_xticks(range(3)) ax_uamb[0].set_xticklabels(svo_labels) ax_uamb[1].bar(range(3), [ np.mean([np.sum(all_x[1,:,-1] * all_x[1,:,-1],axis=0) for all_x in all_uamb_ego]), np.mean([np.sum(all_x[1,:,-1] * all_x[1,:,-1],axis=0) for all_x in all_uamb_pro]), np.mean([np.sum(all_x[1,:,-1] * all_x[1,:,-1],axis=0) for all_x in all_uamb_altru])] ) # ax_uamb[1].set_xlabel("IBR Iteration") ax_uamb[1].set_ylabel(r"$\sum u_{v}^2$") ax_uamb[1].set_xticks(range(3)) ax_uamb[1].set_xticklabels(svo_labels) # ax_uamb[2].bar(range(3), [ # np.sum(all_uamb_ego[0,:,-1] * all_uamb_ego[0,:,-1],axis=0) + np.sum(all_uamb_ego[1,:,-1] * all_uamb_ego[1,:,-1],axis=0), # np.sum(all_uamb_pro[0,:,-1] * all_uamb_pro[1,:,-1], axis=0) + np.sum(all_uamb_pro[1,:,-1] * all_uamb_pro[1,:,-1], axis=0), # np.sum(all_uamb_altru[0,:,-1] * all_uamb_altru[0,:,-1],axis=0) + np.sum(all_uamb_altru[1,:,-1] * all_uamb_altru[1,:,-1],axis=0)],) # ax_uamb[2].set_xlabel("Vehicles' Social Value Orientation") # ax_uamb[2].set_ylabel("$\sum ||u||^2$") ax_uamb[1].set_xticks(range(3)) ax_uamb[1].set_xticklabels(svo_labels) if SAVE: fig_file_name = folder + 'plots/' + 'cfig2_amb_ctrl_iterations.eps' fig_uamb.savefig(fig_file_name, dpi=95, format='eps') print("Save to....", fig_file_name) ########################################################## #### Convergence ######################################################### fig_reluamb, ax_reluamb = plt.subplots(2,1) # fig_reluamb.set_figheight(fig_height) # fig_reluamb.set_figwidth(fig_width) fig_reluamb.set_size_inches((8,6)) for sim_i in range(3): if sim_i==0: #prosocial directory all_uamb = all_uamb_ego label = "Egoistic" ibr_brounds_array = ibr_brounds_array_ego elif sim_i==1: #egoistic directory all_uamb = all_uamb_pro label = "Prosocial" ibr_brounds_array = ibr_brounds_array_pro else: #altruistic directory all_uamb = all_uamb_altru all_other_u = all_other_u_altru label = "Altruistic" ibr_brounds_array = ibr_brounds_array_altru ax_reluamb[0].plot(ibr_brounds_array[0][1:], np.sum((all_uamb[0][0,:,1:]-all_uamb[0][0,:,0:-1])*(all_uamb[0][0,:,1:]-all_uamb[0][0,:,0:-1]), axis=0), '-o', label=label) ax_reluamb[1].plot(ibr_brounds_array[0][1:], np.sum((all_uamb[0][1,:,1:]-all_uamb[0][1,:,0:-1])*(all_uamb[0][1,:,1:]-all_uamb[0][1,:,0:-1]), axis=0), '-o', label=label) ax_reluamb[0].set_ylabel("$\sum (u_{v\delta,t}-u_{\delta,t-1})^2$") ax_reluamb[1].set_xlabel("IBR Iteration") ax_reluamb[1].set_ylabel("$\sum (u_{v,t}-u_{v,t-1})^2$") ax_reluamb[0].legend() ax_reluamb[1].legend() fig_reluamb.suptitle("Change in Ambulance Control Input over IBR Iterations") if SAVE: fig_file_name = folder + 'plots/' + 'cfig3_change_amb_ctrl_iterations.eps' fig_reluamb.savefig(fig_file_name, dpi=95, format='eps') print("Save to....", fig_file_name) ###################################################################3 ################################################################## fig_xfinal, ax_xfinal = plt.subplots(2,1) fig_xfinal.suptitle("Final Ambulance State Over Iterations") fig_xfinal.set_size_inches((8,6)) # fig_xfinal.set_figheight(fig_height) # fig_xfinal.set_figwidth(fig_width) for sim_i in range(3): if sim_i==0: #prosocial directory all_uamb = all_uamb_ego all_xamb = all_xamb_ego all_other_x = all_other_x_ego label = "Egoistic" ibr_brounds_array = ibr_brounds_array_ego elif sim_i==1: #egoistic directory all_uamb = all_uamb_pro all_xamb = all_xamb_pro all_other_x = all_other_x_pro label = "Prosocial" ibr_brounds_array = ibr_brounds_array_pro else: #altruistic directory all_uamb = all_uamb_altru all_xamb = all_xamb_altru all_other_x = all_other_x_altru all_other_u = all_other_u_altru label = "Altruistic" ibr_brounds_array = ibr_brounds_array_altru ax_xfinal[0].plot(ibr_brounds_array[0], all_xamb[0][0,-1,:], '-o', label=label) ax_xfinal[1].plot(ibr_brounds_array[0], all_xamb[0][2,-1,:], '-o', label=label) # ax_reluamb[0].set_xlabel("IBR Iteration") ax_xfinal[0].set_ylabel("$x_{final}$") ax_xfinal[0].legend() ax_xfinal[1].set_xlabel("IBR Iteration") ax_xfinal[1].set_ylabel(r"$\Theta_{final}$") ax_xfinal[1].legend() if SAVE: fig_file_name = folder + 'plots/' + 'cfig4_iterations_ambperformance.eps' fig_xfinal.savefig(fig_file_name, dpi=95, format='eps') print("Save to....", fig_file_name) ################################################################################ ###################### NOW PLOTTING THE OTHER VEHICLES ######################### fig_xfinal_all, ax_xfinal_all = plt.subplots(3,1) fig_xfinal_all.suptitle("Comparing Distance Travel for the Vehicles") fig_xfinal_all.set_size_inches((8,8)) # fig_xfinal_all.set_figheight(fig_height) # fig_xfinal_all.set_figwidth(fig_width) for sim_i in range(3): if sim_i==0: #prosocial directory all_uamb = all_uamb_ego all_xamb = all_xamb_ego all_other_x = all_other_x_ego label = "Egoistic" ibr_brounds_array = ibr_brounds_array_ego elif sim_i==1: #egoistic directory all_uamb = all_uamb_pro all_xamb = all_xamb_pro all_other_x = all_other_x_pro label = "Prosocial" ibr_brounds_array = ibr_brounds_array_pro else: #altruistic directory all_uamb = all_uamb_altru all_xamb = all_xamb_altru all_other_x = all_other_x_altru all_other_u = all_other_u_altru label = "Altruistic" ibr_brounds_array = ibr_brounds_array_altru bar_width = 0.5 inter_car_width = 2*bar_width width_offset = bar_width*sim_i ticks = [width_offset + (2*bar_width + inter_car_width)*c for c in range(n_other_cars + 1)] # print(len(all_ither_x)) # ax_xfinal_all[0].bar(ticks, # [np.mean([all_x[0, -1, -1] - all_x[0, 0, -1] for all_x in all_xamb])] + [np.mean(all_o_x[i][0,-1,-1] - all_o_x[i][0,0,-1]) for i in range(n_other_cars) for all_o_x in all_other_x], # bar_width, label=label) # ax_xfinal_all[0].set_xticks(range(n_other_cars + 1)) # ax_xfinal_all[0].set_xticklabels(["A"] + [str(i) for i in range(1, n_other_cars+1)]) # ax_xfinal_all[1].bar(ticks, # [all_xamb[-1, -1, -1] - all_xamb[-1, 0, -1]] + [all_other_x[i][-1,-1,-1] - all_other_x[i][-1,0,-1] for i in range(n_other_cars)], # bar_width, label=label) # # ax_xfinal_all[1].set_xticks(range(n_other_cars + 1)) # # ax_xfinal_all[1].set_xticklabels(["A"] + [str(i) for i in range(1, n_other_cars+1)]) # ax_xfinal_all[2].bar(ticks, # [np.sum(all_xamb[2,:,-1]*all_xamb[2,:,-1])] + [np.sum(all_other_x[i][2,:,-1]*all_other_x[i][2,:,-1]) for i in range(n_other_cars)], # bar_width, label=label) width_offset = bar_width*1 ticks = [width_offset + (2*bar_width + inter_car_width)*c for c in range(n_other_cars + 1)] ax_xfinal_all[2].legend() ax_xfinal_all[2].set_xticks(ticks) ax_xfinal_all[2].set_xticklabels(["A"] + [str(i) for i in range(1, n_other_cars+1)]) ax_xfinal_all[0].set_ylabel("Horizontal Displacement $\Delta x$") ax_xfinal_all[0].legend() ax_xfinal_all[0].set_xticks(ticks) ax_xfinal_all[0].set_xticklabels(["A"] + [str(i) for i in range(1, n_other_cars+1)]) ax_xfinal_all[1].set_ylabel("Total Distance $s_f - s_i$") ax_xfinal_all[1].legend() ax_xfinal_all[1].set_xticks(ticks) ax_xfinal_all[1].set_xticklabels(["A"]
Bar) is ' 'incorrect.', six.text_type(ex)) self.stack.delete() self.assertEqual((self.stack.DELETE, self.stack.COMPLETE), self.stack.state) def test_stack_load_no_param_value_validation(self): """Test stack loading with disabled parameter value validation.""" tmpl = template_format.parse(''' heat_template_version: 2013-05-23 parameters: flavor: type: string description: A flavor. constraints: - custom_constraint: nova.flavor resources: a_resource: type: GenericResourceType ''') # Mock objects so the query for flavors in server.FlavorConstraint # works for stack creation fc = fakes.FakeClient() self.m.StubOutWithMock(nova.NovaClientPlugin, '_create') nova.NovaClientPlugin._create().AndReturn(fc) fc.flavors = self.m.CreateMockAnything() flavor = collections.namedtuple("Flavor", ["id", "name"]) flavor.id = "1234" flavor.name = "dummy" fc.flavors.get('1234').AndReturn(flavor) self.m.ReplayAll() test_env = environment.Environment({'flavor': '1234'}) self.stack = stack.Stack(self.ctx, 'stack_with_custom_constraint', template.Template(tmpl, env=test_env)) self.stack.validate() self.stack.store() self.stack.create() stack_id = self.stack.id self.m.VerifyAll() self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE), self.stack.state) loaded_stack = stack.Stack.load(self.ctx, stack_id=self.stack.id) self.assertEqual(stack_id, loaded_stack.parameters['OS::stack_id']) # verify that fc.flavors.list() has not been called, i.e. verify that # parameter value validation did not happen and FlavorConstraint was # not invoked self.m.VerifyAll() def test_snapshot_delete(self): snapshots = [] class ResourceDeleteSnapshot(generic_rsrc.ResourceWithProps): def handle_delete_snapshot(self, data): snapshots.append(data) resource._register_class( 'ResourceDeleteSnapshot', ResourceDeleteSnapshot) tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'AResource': {'Type': 'ResourceDeleteSnapshot'}}} self.stack = stack.Stack(self.ctx, 'snapshot_stack', template.Template(tmpl)) data = self.stack.prepare_abandon() fake_snapshot = collections.namedtuple('Snapshot', ('data',))(data) self.stack.delete_snapshot(fake_snapshot) self.assertEqual([data['resources']['AResource']], snapshots) def test_delete_snapshot_without_data(self): tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'R1': {'Type': 'GenericResourceType'}}} self.stack = stack.Stack(self.ctx, 'snapshot_stack', template.Template(tmpl)) fake_snapshot = collections.namedtuple('Snapshot', ('data',))(None) self.assertIsNone(self.stack.delete_snapshot(fake_snapshot)) def test_incorrect_outputs_cfn_get_attr(self): tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'AResource': {'Type': 'ResourceWithPropsType', 'Properties': {'Foo': 'abc'}}}, 'Outputs': { 'Resource_attr': { 'Value': { 'Fn::GetAtt': ['AResource', 'Bar']}}}} self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) self.assertRaisesRegex( exception.StackValidationFailed, ('Outputs.Resource_attr.Value.Fn::GetAtt: The Referenced ' r'Attribute \(AResource Bar\) is incorrect.'), self.stack.validate) def test_incorrect_outputs_cfn_incorrect_reference(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Outputs: Output: Value: Fn::GetAtt: - Resource - Foo """) self.stack = stack.Stack(self.ctx, 'stack_with_incorrect_outputs', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('The specified reference "Resource" ' '(in unknown) is incorrect.', six.text_type(ex)) def test_incorrect_outputs_incorrect_reference(self): tmpl = template_format.parse(""" heat_template_version: 2013-05-23 outputs: output: value: { get_attr: [resource, foo] } """) self.stack = stack.Stack(self.ctx, 'stack_with_incorrect_outputs', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('The specified reference "resource" ' '(in unknown) is incorrect.', six.text_type(ex)) def test_incorrect_outputs_cfn_missing_value(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: Foo: abc Outputs: Resource_attr: Description: the attr """) self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('Each output definition must contain a Value key.', six.text_type(ex)) self.assertIn('Outputs.Resource_attr', six.text_type(ex)) def test_incorrect_outputs_cfn_empty_value(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: Foo: abc Outputs: Resource_attr: Value: '' """) self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) self.assertIsNone(self.stack.validate()) def test_incorrect_outputs_cfn_none_value(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: Foo: abc Outputs: Resource_attr: Value: """) self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) self.assertIsNone(self.stack.validate()) def test_incorrect_outputs_cfn_string_data(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: Foo: abc Outputs: Resource_attr: This is wrong data """) self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('Found a %s instead' % six.text_type.__name__, six.text_type(ex)) self.assertIn('Outputs.Resource_attr', six.text_type(ex)) def test_prop_validate_value(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: FooInt: notanint """) self.stack = stack.Stack(self.ctx, 'stack_with_bad_property', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn("'notanint' is not an integer", six.text_type(ex)) self.stack.strict_validate = False self.assertIsNone(self.stack.validate()) def test_disable_validate_required_param(self): tmpl = template_format.parse(""" heat_template_version: 2013-05-23 parameters: aparam: type: number resources: AResource: type: ResourceWithPropsRefPropOnValidate properties: FooInt: {get_param: aparam} """) self.stack = stack.Stack(self.ctx, 'stack_with_reqd_param', template.Template(tmpl)) ex = self.assertRaises(exception.UserParameterMissing, self.stack.validate) self.assertIn("The Parameter (aparam) was not provided", six.text_type(ex)) self.stack.strict_validate = False ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn("The Parameter (aparam) was not provided", six.text_type(ex)) self.assertIsNone(self.stack.validate(validate_res_tmpl_only=True)) def test_nodisable_validate_tmpl_err(self): tmpl = template_format.parse(""" heat_template_version: 2013-05-23 resources: AResource: type: ResourceWithPropsRefPropOnValidate depends_on: noexist properties: FooInt: 123 """) self.stack = stack.Stack(self.ctx, 'stack_with_tmpl_err', template.Template(tmpl)) ex = self.assertRaises(exception.InvalidTemplateReference, self.stack.validate) self.assertIn( "The specified reference \"noexist\" (in AResource) is incorrect", six.text_type(ex)) self.stack.strict_validate = False ex = self.assertRaises(exception.InvalidTemplateReference, self.stack.validate) self.assertIn( "The specified reference \"noexist\" (in AResource) is incorrect", six.text_type(ex)) ex = self.assertRaises(exception.InvalidTemplateReference, self.stack.validate, validate_res_tmpl_only=True) self.assertIn( "The specified reference \"noexist\" (in AResource) is incorrect", six.text_type(ex)) def test_validate_property_getatt(self): tmpl = { 'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'R1': {'Type': 'ResourceWithPropsType'}, 'R2': {'Type': 'ResourceWithPropsType', 'Properties': {'Foo': {'Fn::GetAtt': ['R1', 'Foo']}}}} } self.stack = stack.Stack(self.ctx, 'test_stack', template.Template(tmpl)) self.assertIsNone(self.stack.validate()) def test_param_validate_value(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Parameters: foo: Type: Number """) env1 = environment.Environment({'parameters': {'foo': 'abc'}}) self.stack = stack.Stack(self.ctx, 'stack_with_bad_param', template.Template(tmpl, env=env1)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn("Parameter 'foo' is invalid: could not convert " "string to float:", six.text_type(ex)) self.assertIn("abc", six.text_type(ex)) self.stack.strict_validate = False self.assertIsNone(self.stack.validate()) def test_incorrect_outputs_cfn_list_data(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Resources: AResource: Type: ResourceWithPropsType Properties: Foo: abc Outputs: Resource_attr: - Data is not what it seems """) self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('Found a list', six.text_type(ex)) self.assertIn('Outputs.Resource_attr', six.text_type(ex)) def test_incorrect_deletion_policy(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Parameters: Deletion_Policy: Type: String Default: [1, 2] Resources: AResource: Type: ResourceWithPropsType DeletionPolicy: {Ref: Deletion_Policy} Properties: Foo: abc """) self.stack = stack.Stack(self.ctx, 'stack_bad_delpol', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('Invalid deletion policy "[1, 2]"', six.text_type(ex)) def test_deletion_policy_apply_ref(self): tmpl = template_format.parse(""" HeatTemplateFormatVersion: '2012-12-12' Parameters: Deletion_Policy: Type: String Default: Delete Resources: AResource: Type: ResourceWithPropsType DeletionPolicy: wibble Properties: Foo: abc DeletionPolicy: {Ref: Deletion_Policy} """) self.stack = stack.Stack(self.ctx, 'stack_delpol_get_param', template.Template(tmpl)) self.stack.validate() self.stack.store() self.stack.create() self.assertEqual((self.stack.CREATE, self.stack.COMPLETE), self.stack.state) def test_deletion_policy_apply_get_param(self): tmpl = template_format.parse(""" heat_template_version: 2016-04-08 parameters: deletion_policy: type: string default: Delete resources: AResource: type: ResourceWithPropsType deletion_policy: {get_param: deletion_policy} properties: Foo: abc """) self.stack = stack.Stack(self.ctx, 'stack_delpol_get_param', template.Template(tmpl)) self.stack.validate() self.stack.store() self.stack.create() self.assertEqual((self.stack.CREATE, self.stack.COMPLETE), self.stack.state) def test_incorrect_deletion_policy_hot(self): tmpl = template_format.parse(""" heat_template_version: 2013-05-23 parameters: deletion_policy: type: string default: [1, 2] resources: AResource: type: ResourceWithPropsType deletion_policy: {get_param: deletion_policy} properties: Foo: abc """) self.stack = stack.Stack(self.ctx, 'stack_bad_delpol', template.Template(tmpl)) ex = self.assertRaises(exception.StackValidationFailed, self.stack.validate) self.assertIn('Invalid deletion policy "[1, 2]', six.text_type(ex)) def test_incorrect_outputs_hot_get_attr(self): tmpl = {'heat_template_version': '2013-05-23', 'resources': { 'AResource': {'type': 'ResourceWithPropsType', 'properties': {'Foo': 'abc'}}}, 'outputs': { 'resource_attr': { 'value': { 'get_attr': ['AResource', 'Bar']}}}} self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs', template.Template(tmpl)) self.assertRaisesRegex( exception.StackValidationFailed, ('outputs.resource_attr.value.get_attr: The Referenced Attribute ' r'\(AResource Bar\) is incorrect.'), self.stack.validate) def test_snapshot_save_called_first(self): def snapshotting_called_first(stack, action, status, reason): self.assertEqual(stack.status, stack.IN_PROGRESS) self.assertEqual(stack.action, stack.SNAPSHOT) tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'A': {'Type': 'GenericResourceType'}, 'B': {'Type': 'GenericResourceType'}}} self.stack = stack.Stack(self.ctx, 'stack_details_test', template.Template(tmpl)) self.stack.store() self.stack.create() self.stack.snapshot(save_snapshot_func=snapshotting_called_first) def test_restore(self): tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'A': {'Type': 'GenericResourceType'}, 'B': {'Type': 'GenericResourceType'}}} self.stack = stack.Stack(self.ctx, 'stack_details_test', template.Template(tmpl)) self.stack.store() self.stack.create() data = copy.deepcopy(self.stack.prepare_abandon()) fake_snapshot = collections.namedtuple( 'Snapshot', ('data', 'stack_id'))(data, self.stack.id) new_tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'A': {'Type': 'GenericResourceType'}}} updated_stack = stack.Stack(self.ctx, 'updated_stack', template.Template(new_tmpl)) self.stack.update(updated_stack) self.assertEqual(1, len(self.stack.resources)) self.stack.restore(fake_snapshot) self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE), self.stack.state) self.assertEqual(2, len(self.stack.resources)) def test_restore_with_original_env(self): tmpl = { 'heat_template_version': '2013-05-23', 'parameters': { 'foo': {'type': 'string'} }, 'resources': { 'A': { 'type': 'ResourceWithPropsType', 'properties': {'Foo': {'get_param': 'foo'}} } } } self.stack = stack.Stack(self.ctx, 'stack_restore_test', template.Template( tmpl, env=environment.Environment( {'foo': 'abc'}))) self.stack.store() self.stack.create() self.assertEqual('abc', self.stack.resources['A'].properties['Foo']) data = copy.deepcopy(self.stack.prepare_abandon()) fake_snapshot = collections.namedtuple( 'Snapshot', ('data', 'stack_id'))(data, self.stack.id) updated_stack = stack.Stack(self.ctx, 'updated_stack', template.Template( tmpl, env=environment.Environment( {'foo': 'xyz'}))) self.stack.update(updated_stack) self.assertEqual('xyz', self.stack.resources['A'].properties['Foo']) self.stack.restore(fake_snapshot) self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE), self.stack.state) self.assertEqual('abc', self.stack.resources['A'].properties['Foo']) def test_hot_restore(self): tpl = {'heat_template_version': '2013-05-23', 'resources': {'A': {'type': 'ResourceWithRestoreType'}}} self.stack = stack.Stack(self.ctx, 'stack_details_test', template.Template(tpl)) self.stack.store() self.stack.create() data = self.stack.prepare_abandon() data['resources']['A']['resource_data']['a_string'] = 'foo' fake_snapshot = collections.namedtuple( 'Snapshot', ('data', 'stack_id'))(data, self.stack.id) self.stack.restore(fake_snapshot) self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE), self.stack.state) self.assertEqual( 'foo', self.stack.resources['A'].properties['a_string']) @mock.patch.object(stack.Stack, 'db_resource_get') def test_lightweight_stack_getatt(self, mock_drg): tmpl = template.Template({ 'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'foo': {'Type': 'GenericResourceType'}, 'bar': { 'Type': 'ResourceWithPropsType', 'Properties': { 'Foo': {'Fn::GetAtt': ['foo', 'bar']}, } } } }) rsrcs_data = {'foo': {'reference_id': 'foo-id', 'attrs': {'bar': 'baz'}, 'uuid': mock.ANY, 'id': mock.ANY, 'action': 'CREATE', 'status': 'COMPLETE'}, 'bar': {'reference_id': 'bar-id', 'uuid': mock.ANY, 'id': mock.ANY, 'action': 'CREATE', 'status': 'COMPLETE'}} cache_data = {n: node_data.NodeData.from_dict(d) for n, d in rsrcs_data.items()} tmpl_stack = stack.Stack(self.ctx, 'test', tmpl) tmpl_stack.store() lightweight_stack = stack.Stack.load(self.ctx, stack_id=tmpl_stack.id, cache_data=cache_data) # Check if the property has the appropriate resolved value. bar = resource.Resource( 'bar', lightweight_stack.defn.resource_definition('bar'), lightweight_stack) self.assertEqual('baz', bar.properties['Foo']) # Make sure FnGetAtt returns the cached value. attr_value = lightweight_stack.defn['foo'].FnGetAtt('bar') self.assertEqual('baz', attr_value) # Make sure calls are not made to the database to retrieve the # resource state. self.assertFalse(mock_drg.called) @mock.patch.object(stack.Stack, 'db_resource_get') def test_lightweight_stack_getrefid(self, mock_drg): tmpl = template.Template({ 'HeatTemplateFormatVersion': '2012-12-12', 'Resources': { 'foo': {'Type': 'GenericResourceType'}, 'bar': { 'Type': 'ResourceWithPropsType', 'Properties': { 'Foo': {'Ref': 'foo'}, } } } }) rsrcs_data = {'foo': {'reference_id': 'physical-resource-id', 'uuid': mock.ANY, 'id': mock.ANY, 'action': 'CREATE', 'status': 'COMPLETE'}, 'bar': {'reference_id': 'bar-id', 'uuid': mock.ANY, 'id': mock.ANY, 'action': 'CREATE', 'status': 'COMPLETE'}} cache_data = {n: node_data.NodeData.from_dict(d) for n, d in rsrcs_data.items()} tmpl_stack = stack.Stack(self.ctx, 'test', tmpl) tmpl_stack.store() lightweight_stack = stack.Stack.load(self.ctx, stack_id=tmpl_stack.id, cache_data=cache_data) # Check if the property has the appropriate resolved value. bar = resource.Resource( 'bar', lightweight_stack.defn.resource_definition('bar'), lightweight_stack) self.assertEqual('physical-resource-id',
<filename>training/instance_segmentation/mask-rcnn/train_maskrcnn.py # Sample code from the TorchVision 0.3 Object Detection Finetuning Tutorial # http://pytorch.org/tutorials/intermediate/torchvision_tutorial.html import os import sys sys.path.append("/home/native/projects/cranberry_counting/") import numpy as np import torch from PIL import Image from glob import glob import ast from tqdm import tqdm import pandas as pd import torchvision import matplotlib.patches as patches # from models.mask_rcnn.faster_rcnn import FastRCNNPredictor # from models.mask_rcnn.mask_rcnn import MaskRCNNPredictor from models.points_rcnn.faster_rcnn import FastRCNNPredictor from models.points_rcnn.mask_rcnn import MaskRCNNPredictor import models # from datasets.cranberries import cranberry_dataset from engine import train_one_epoch, evaluate from torch.utils.data import Dataset import utils import cv2 import transforms as T import matplotlib.pyplot as plt IMG_EXTENSIONS = ['*.png', '*.jpeg', '*.jpg','*.npy'] def dictionary_contents(path,types): files = [] # types = ["*.png","*.jpg","*.PNG","*.JPG"] for type in types: for x in glob(path+type): files.append(os.path.join(path,x)) return files class CBDatasetPoints(Dataset): def __init__(self,directory,transformers=None,target_transformers=None,test=False,has_mask=True): """CBDataset: Cranberry Dataset. The sample images of this dataset must be all inside one directory. Inside the same directory, there must be one CSV file. This file must contain one row per image. It can contain as many columns as wanted, i.e, filename, count... :param directory: Directory with all the images and the CSV file. :param transform: Transform to be applied to each image. :param max_dataset_size: Only use the first N images in the directory. :param ignore_gt: Ignore the GT of the dataset, i.e, provide samples without locations or counts. :param seed: Random seed. """ self.test = test self.has_mask = has_mask self.root_dir = directory self.transforms = transformers self.target_transformers = target_transformers self.image_path = self.root_dir + "images/" self.mask_path = self.root_dir + "masks/" self.image_paths = sorted(dictionary_contents(self.image_path,types=IMG_EXTENSIONS)) self.mask_paths = sorted(dictionary_contents(self.mask_path,types=IMG_EXTENSIONS)) if len(self.image_paths) == 0: raise ValueError("There are no images in {}".format(directory)) # self.csv_path = None # elif self.csv_path == None: # raise ValueError("There is no groundtruth in {}".format(directory)) # self.csv_path = utils.dictionary_contents(directory,types=["*.csv"])[0] # self.csv_df = pd.read_csv(self.csv_path) # self.csv_df = self.csv_df.sample(frac=1).reset_index(drop=True) def __len__(self): return len(self.image_paths) def __getitem__(self,index): img_path = self.image_paths[index] mask_path = self.mask_paths[index] print(img_path) image = Image.open(img_path).convert("RGB") mask = Image.open(mask_path).convert("L") mask = np.array(mask) obj_ids = np.unique(mask) # first id is the background, so remove it obj_ids = obj_ids[1:] masks = mask == obj_ids[:, None, None] num_objs = len(obj_ids) boxes = [] for i in range(num_objs): pos = np.where(masks[i]) xmin = np.min(pos[1]) - 15 xmax = np.max(pos[1]) + 15 ymin = np.min(pos[0]) - 15 ymax = np.max(pos[0]) + 15 boxes.append([xmin, ymin, xmax, ymax]) ### sanity check for boxes ##### # cvimg = cv2.imread(img_path) # cvimg = np.asarray(image) # fig = plt.figure() # ax = fig.add_subplot(111, aspect='equal') # ax.imshow(cvimg) # for box in boxes: # x1,y1,x2,y2 = box # rect = patches.Rectangle((x1,y1),x2-x1,y2-y1,fill=False,edgecolor='r') # ax.add_patch(rect) # cv2.imshow("rectangles for sanity check maskrcnn dataq",cvimg) # cv2.waitKey(0) # plt.show() boxes = torch.as_tensor(boxes, dtype=torch.float32) labels = torch.ones((num_objs,), dtype=torch.int64) masks = torch.as_tensor(masks, dtype=torch.uint8) image_id = torch.tensor([index]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) target = {} target["boxes"] = boxes target["labels"] = labels target["masks"] = masks target["image_id"] = image_id target["area"] = area target["iscrowd"] = iscrowd if self.transforms is not None: image, target = self.transforms(image, target) return image, target class CBMaskRCNNDataset(Dataset): def __init__(self, directory, transforms=None, readsave=False): self.transforms = transforms self.root_dir = directory self.images_path = self.root_dir + "images/" self.masks_path = self.root_dir + "masks/" self.image_paths = sorted(dictionary_contents(self.images_path,types=IMG_EXTENSIONS)) self.mask_paths = sorted(dictionary_contents(self.masks_path,types=IMG_EXTENSIONS)) self.csv_path = None # print(directory) self.csv_path = dictionary_contents(directory,types=["*.csv"])[0] self.csv_df = pd.read_csv(self.csv_path) self.csv_df = self.csv_df.sample(frac=1).reset_index(drop=True) def __getitem__(self, idx): img_path = self.image_paths[idx] mask_path = self.mask_paths[idx] filename = img_path.split("/")[-1] image = Image.open(img_path).convert("RGB") # 0 encoding non-damaged is supposed to be 1 for training. # In training, 0 is of background mask = Image.open(mask_path).convert("L") mask = np.array(mask) # print(mask.shape) obj_ids = np.unique(mask) # print(obj_ids) # first id is the background, so remove it obj_ids = obj_ids[1:] masks = mask == obj_ids[:, None, None] num_objs = len(obj_ids) boxes = [] for i in range(num_objs): pos = np.where(masks[i]) xmin = np.min(pos[1]) xmax = np.max(pos[1]) ymin = np.min(pos[0]) ymax = np.max(pos[0]) # if xmax==xmin: # xmax = xmin+5 # if ymax==ymin: # ymax = ymin +5 # if xmin <5: # xmin = 5 # if ymin < 5: # ymin = 5 # if xmax > 607: # xmax = 607 # if ymax > 455: # ymax = 455 # print(f"index: {i}, xmin: {xmin},ymin: {ymin}, xmax: {xmax}, ymax: {ymax}") boxes.append([xmin, ymin, xmax, ymax]) # print(f"number of objects: {num_objs}, numbers of masks: {masks.shape}") ### sanity check for boxes ##### # cvimg = cv2.imread(img_path) # cvimg = np.asarray(image) # fig = plt.figure() # ax = fig.add_subplot(111, aspect='equal') # # ax.set_ylim(ax.get_ylim()[::-1]) # ax.imshow(cvimg) # for box in boxes: # x1,y1,x2,y2 = box # # print(f"output from dataloader: {box}") # # print(f"x1:{x1}\ny1:{y1}\nx2:{x2}\ny2:{y2}") # # cv2.rectangle(cvimg,(x1,y1),(x2,y2),(255,255,0)) # # rect = patches.Rectangle((x1,y2),x2-x1,y2-y1,fill=False,edgecolor='r') # rect = patches.Rectangle((x1,y1),x2-x1,y2-y1,fill=False,edgecolor='r') # ax.add_patch(rect) # cv2.imshow("rectangles for sanity check maskrcnn dataq",cvimg) # cv2.waitKey(0) # plt.show() # convert everything into a torch.Tensor boxes = torch.as_tensor(boxes, dtype=torch.float32) labels = torch.ones((num_objs,), dtype=torch.int64) masks = torch.as_tensor(masks, dtype=torch.uint8) image_id = torch.tensor([idx]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) # print(f"area: {area}\narea_shape: {area.shape}\nnum_boxes: {num_objs}\nboxes: {boxes}") target = {} target["boxes"] = boxes target["labels"] = labels target["masks"] = masks target["image_id"] = image_id target["area"] = area target["iscrowd"] = iscrowd if self.transforms is not None: image, target = self.transforms(image, target) return image, target def __len__(self): return len(self.image_paths) class PennFudanDataset(object): def __init__(self, root, transforms): self.root = root self.transforms = transforms # load all image files, sorting them to # ensure that they are aligned self.imgs = list(sorted(os.listdir(os.path.join(root, "PNGImages")))) self.masks = list(sorted(os.listdir(os.path.join(root, "PedMasks")))) def __getitem__(self, idx): # load images ad masks img_path = os.path.join(self.root, "PNGImages", self.imgs[idx]) mask_path = os.path.join(self.root, "PedMasks", self.masks[idx]) img = Image.open(img_path).convert("RGB") # note that we haven't converted the mask to RGB, # because each color corresponds to a different instance # with 0 being background mask = Image.open(mask_path).convert("L") mask = np.asarray(mask) # instances are encoded as different colors obj_ids = np.unique(mask) # first id is the background, so remove it obj_ids = obj_ids[1:] # split the color-encoded mask into a set # of binary masks masks = mask == obj_ids[:, None, None] # get bounding box coordinates for each mask num_objs = len(obj_ids) boxes = [] for i in range(num_objs): pos = np.where(masks[i]) xmin = np.min(pos[1]) xmax = np.max(pos[1]) ymin = np.min(pos[0]) ymax = np.max(pos[0]) boxes.append([xmin, ymin, xmax, ymax]) # print(boxes) # plt.imshow(mask) # plt.show() # cvimg = cv2.imread(img_path) # cvimg = np.asarray(img) # fig = plt.figure() # ax = fig.add_subplot(111) # # ax.set_ylim(ax.get_ylim()[::-1]) # ax.imshow(cvimg) # for box in boxes: # x1,y1,x2,y2 = box # # print(f"output from dataloader: {box}") # # print(f"x1:{x1}\ny1:{y1}\nx2:{x2}\ny2:{y2}") # # cv2.rectangle(cvimg,(x1,y1),(x2,y2),(255,255,0)) # rect = patches.Rectangle((x1,y1),x2-x1,y2-y1,fill=False,edgecolor='r') # ax.add_patch(rect) # cv2.imshow("rectangles for sanity check maskrcnn dataq",cvimg) # cv2.waitKey(0) # plt.show() boxes = torch.as_tensor(boxes, dtype=torch.float32) # there is only one class labels = torch.ones((num_objs,), dtype=torch.int64) masks = torch.as_tensor(masks, dtype=torch.uint8) image_id = torch.tensor([idx]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) target = {} target["boxes"] = boxes target["labels"] = labels target["masks"] = masks target["image_id"] = image_id target["area"] = area target["iscrowd"] = iscrowd if self.transforms is not None: img, target = self.transforms(img, target) return img, target def __len__(self): return len(self.imgs) def get_model_instance_segmentation(num_classes): # load an instance segmentation model pre-trained pre-trained on COCO # model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=False,num_classes=2) # model = models.mask_rcnn.mask_rcnn.maskrcnn_resnet50_fpn(pretrained=False,num_classes=2) model = models.points_rcnn.mask_rcnn.maskrcnn_resnet50_fpn(pretrained=False,num_classes=2,pretrained_backbone=True) # get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # now get the number of input features for the mask classifier in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels hidden_layer = 256 # and replace the mask predictor with a new one model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes) return model def get_transform(train): transforms = [] transforms.append(T.ToTensor()) if train: transforms.append(T.RandomHorizontalFlip(0.5)) return T.Compose(transforms) def main(): # train on the GPU or on the CPU, if a GPU is not available device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # our dataset has two classes only - background and person num_classes = 2 # use our dataset and
<filename>CapsuleRoute.py from CapsuleMemory import CapsuleMemory from NeuralNet import NeuralNet from NeuralNetGamma import NeuralNetGamma from NeuralNetG import NeuralNetG from Attribute import Attribute from Utility import Utility from Observation import Observation from itertools import permutations from HyperParameters import HyperParameters import math class CapsuleRoute: def __init__(self, parentCapsule, capsuleRouteName : str, fromCapsules : list): self._name : str = capsuleRouteName self._memory : CapsuleMemory = CapsuleMemory() self._fromCapsules : list = fromCapsules # Capsules self._parentCapsule = parentCapsule self._agreementFunctionLambda = None self._gInputMapping : dict = None # Attribute - List of Indices (Always 1 Element) self._gOutputMapping : dict = None # Index - Attribute self._gammaInputMapping : dict = None # Attribute - List of Indices self._gammaOutputMapping : dict = None # Index - Attribute self._neuralNetGamma : NeuralNetGamma = None self._neuralNetG : NeuralNetG = None self._isSemanticCapsule : bool = True # TODO: Get Rotational Label from PrimitivesRenderer self._rotationalLabels : list = ["Rotation"] # Per Axis def getJSONMain(self): return self._memory.getJSONMain() def getJSONMemory(self): return {"route" : self._name, "memory" : self._memory.getJSONMemory()} def getName(self): return self._name def haveSameParent(self, capsules : list): # capsules # List of Capsules for caps in capsules: if caps not in self._fromCapsules: return False return True def addSavedObservations(self, observations : list): self._memory.addSavedObservations(observations) def addObservations(self, observations : list): self._memory.addObservations(observations) def clearObservations(self): self._memory.clearObservations() def getObservations(self): return self._memory.getObservations() def getObservation(self, index : int): return self._memory.getObservation(index) def getNumObservations(self): return self._memory.getNumObservations() def cleanupObservations(self, offsetLabelX : str, offsetLabelY : str, offsetLabelRatio : str, targetLabelX : str, targetLabelY : str, targetLabelSize : str): self._memory.cleanupObservations(lambda attributes: self.applySymmetries(attributes), offsetLabelX, offsetLabelY, offsetLabelRatio, targetLabelX, targetLabelY, targetLabelSize) def removeObservation(self, observation : Observation): return self._memory.removeObservation(observation) def isSemantic(self): return self._isSemanticCapsule def getInputCapsuleCount(self): counts = {} for caps in self._fromCapsules: if caps in counts: counts[caps] = counts[caps] + 1 else: counts[caps] = 1 return counts # Capsule - Count def getProbabilityCutOff(self): if self._isSemanticCapsule is True: return HyperParameters.SemanticProbabilityCutOff else: return HyperParameters.PrimitiveProbabilityCutOff def getMeanProbability(self): return self._memory.getMeanProbability() def observationFromInputs(self, inputObservations : list, forcedProbability : float = 1.0): inputs = {} # Attribute - List of Values for obs in inputObservations: newInputs = obs.getOutputs(True) # Attribute - Value for newAttr, newValue in newInputs.items(): if newAttr in inputs: inputs[newAttr].append(newValue) else: inputs[newAttr] = [newValue] outputs = self.runGammaFunction(inputs, False) # TODO: Use actual probability return Observation(self._parentCapsule, self, inputObservations, outputs, min(forcedProbability, 1.0)) def getAttributeDistance(self, fromObservations : list, attribute : Attribute, attributeValue : float): # This is an trivial implementation to find an initial guess for the "distance" between # Attributes, without knowledge of the geometry of the configuration space. # For a more accurate estimate, a bayesian approach should be chosen to incorporate # gained knowledge of the geometry. # TODO: This is highly unoptimized... newObs = self.observationFromInputs(fromObservations, 1.0) targetAttr = newObs.getOutputsList() targetAttr[attribute] = [0.0] zeroPoint = self.runGFunction(targetAttr, isTraining = False) targetAttr[attribute] = [attributeValue] offPoint = self.runGFunction(targetAttr, isTraining = False) totalLen = 0.0 for i in range(len(zeroPoint)): totalLen += (offPoint[i] - zeroPoint[i]) * (offPoint[i] - zeroPoint[i]) return totalLen / float(len(zeroPoint)) def getAttributeDistanceRaw(self, fromObservations : list, attribute : Attribute): # See self.getAttributeDistance() newObs = self.observationFromInputs(fromObservations, 1.0) targetAttr = newObs.getOutputsList() targetAttr[attribute] = [0.0] zeroPoint = self.runGFunction(targetAttr, isTraining = False) offPoint = Utility.mapDataOneWayDictRevList(newObs.getInputs(), self._gammaInputMapping) totalLen = 0.0 for i in range(len(zeroPoint)): totalLen += (offPoint[i] - zeroPoint[i]) * (offPoint[i] - zeroPoint[i]) return totalLen / float(len(zeroPoint)) def createSemanticRoute(self, initialObservations : list): self._isSemanticCapsule = True self.addTrainingData(initialObservations, 1.0) self._memory.setLambdaKnownGamma((lambda attributes : self.runGammaFunction(attributes))) self.resizeInternals() def addTrainingData(self, observations : list, forcedProbability : float = 1.0, appendAttr : Attribute = None, appendValue : float = 0.0): newObs = self.observationFromInputs(observations, forcedProbability) if appendAttr is not None: newObs.appendOutputAttribute(appendAttr, appendValue) self._memory.addSavedObservations([newObs]) def rescaleAttribute(self, attribute : Attribute, scale : float): self._memory.rescaleAttribute(attribute, scale) def createPrimitiveRoute(self, gInputMapping : dict, gOutputMapping : dict, gammaInputMapping : dict, gammaOutputMapping : dict, lambdaGenerator, lambdaRenderer, lambdaAgreement, modelSplit : list, width : int, height : int, depth : int): self._isSemanticCapsule = False self._gInputMapping = gInputMapping self._gOutputMapping = gOutputMapping self._gammaInputMapping = gammaInputMapping self._gammaOutputMapping = gammaOutputMapping self._memory.setLambdaKnownG(lambdaGenerator, lambdaRenderer, gOutputMapping, gammaOutputMapping) self._agreementFunctionLambda = lambdaAgreement self._neuralNetGamma = NeuralNetGamma(self._gammaInputMapping, self._gInputMapping, self._name + "-gamma", False) self._neuralNetGamma.setModelSplit(modelSplit) self._neuralNetGamma.setInputShape([width, height, depth]) if self._neuralNetGamma.hasTraining() is False: self.retrain() def getInputCount(self): return len(self._fromCapsules) def getFromCapsules(self): return self._fromCapsules def getInputAttributes(self): return [item for sublist in [x.getAttributes() for x in self._fromCapsules] for item in sublist if item.isInheritable() is True] def getOutputAttributes(self): return self._parentCapsule.getAttributes() def pairInputCapsuleAttributes(self, attributes : dict): # attributes # Attribute - List of Values # We mostly work with {Attribute - List of Values} dictionaries without the associated capsule # Here we just pair them back up again. Used to store in Observation outputs = {} for inputCapsule in self._fromCapsules: outputs[inputCapsule] = {} for attribute, valueList in attributes.items(): if inputCapsule.hasAttribute(attribute): outputs[inputCapsule][attribute] = valueList return outputs # Capsule - {Attribute - List of Values} def resizeInternals(self): prevSizeGamma = 0 prevSizeG = 0 if self._gInputMapping is not None: prevSizeG = len(self._gInputMapping) if self._gammaInputMapping is not None: prevSizeGamma = len(self._gammaInputMapping) self._gInputMapping : dict = dict() # Attribute - List of Indices (with 1 Element) self._gOutputMapping : dict = dict() # Index - Attribute self._gammaInputMapping : dict = dict() # Attribute - List of Indices self._gammaOutputMapping : dict = dict() # Index - Attribute for idx, attribute in enumerate(self.getInputAttributes()): if attribute in self._gammaInputMapping: self._gammaInputMapping[attribute].append(idx) else: self._gammaInputMapping[attribute] = [idx] self._gOutputMapping[idx] = attribute for idx, attribute in enumerate(self.getOutputAttributes()): self._gInputMapping[attribute] = [idx] self._gammaOutputMapping[idx] = attribute self._neuralNetG : NeuralNetG = NeuralNetG(self._gInputMapping, self._gammaInputMapping, self._name + "-g", True) hasChanged = False if prevSizeG > 0 and prevSizeGamma > 0 and (prevSizeG != len(self._gInputMapping) or prevSizeGamma != len(self._gammaInputMapping)): hasChanged = True if self._neuralNetG.hasTraining() is True and hasChanged is True: self._neuralNetG.delete() if self._neuralNetG.hasTraining() is False or hasChanged is True: self.retrain() def retrain(self, showDebugOutput : bool = True, specificSplit : list = None, fromScratch : bool = False): if self._isSemanticCapsule is True: if fromScratch is True and self._neuralNetG.hasTraining() is True: self._neuralNetG.delete() self._neuralNetG.trainFromData(self._memory, showDebugOutput, specificSplit) else: if fromScratch is True and self._neuralNetGamma.hasTraining() is True: self._neuralNetGamma.delete() self._neuralNetGamma.trainFromData(self._memory, showDebugOutput, specificSplit) def getSymmetry(self, attributes : dict): # attributes # Attribute - List of Values # Find symmetry from outputs if self._isSemanticCapsule is True and self._neuralNetG is None: return attributes # We try to find the symmetries on the fly, as they are # highly dependend on the current attributes highestAgreementN = 0 copyRotations = {} # Attribute - List of Values for attr, valueList in attributes.items(): copyRotations[attr] = valueList.copy() originalResult = self.runGFunction(attributes, isTraining = False) n = 2 while(n <= 20): gResult = {} agreement = {} testAngle = 1.0 / float(n) for attr, valueList in copyRotations.items(): if attr.getName() in self._rotationalLabels: for idx in range(len(attributes[attr])): copyRotations[attr][idx] = (attributes[attr][idx] + testAngle) % 1.0 gResult = self.runGFunction(copyRotations, isTraining = False) agreement = self.agreementFunction(originalResult, gResult) agreementSum = 0.0 totLen = 0 for attr, valueList in agreement.items(): agreementSum += sum(valueList) totLen += len(valueList) agreementSum = agreementSum / max(1, totLen) # TODO: This is only for 1 Axis! if agreementSum > HyperParameters.SymmetryCutOff: # Yes, we do have a Symmetry! Can we go deeper? highestAgreementN = n n = n * 2 elif highestAgreementN > 0 or (highestAgreementN == 0 and n >= 9): # Either we found symmetry # or we are doing so tiny rotations that agreement will happen by default break else: n = n + 1 return (1 / max(1, highestAgreementN)) def getSymmetryInverse(self, attributes : dict): # attributes # Attribute - List of Values # Find symmetry from inputs # We try to find the symmetries on the fly, as they are # highly dependend on the current attributes highestAgreementN = 0 originalResult = self.runGammaFunction(attributes, isTraining = False) # TODO: Remove all references to const strings centerX = [valueList for (key, valueList) in originalResult.items() if key.getName() == "Position-X"][0][0] centerY = [valueList for (key, valueList) in originalResult.items() if key.getName() == "Position-Y"][0][0] originalInputs = {} # Attribute - List of Values copyInputs = {} # Attribute - List of Values for attr, valueList in attributes.items(): if attr.getName() == "Position-X": originalInputs[attr] = [] for val in valueList: originalInputs[attr].append(val - centerX)
############## downloadGreenspace.py ################### # Author: <NAME> # Developed for <NAME>, Oregon State University # Date last modified: June 5, 2018 # Description: this script downloads annual MODIS NDVI averages from Google Earth Engine. # Annual averages range from 2003-2017. NDVI values are based on TOA-scaled reflectance. # Multiple Landsat sensors are used to cover the time range as follows: # Requirements: # Active Google Earth Engine account associated with the installed version of Python. # ArcGIS with a liscence for the Spatial Analysis Library # Tested and developed on: # Windows 10 # Python 2.7 # ArcGIS 10.3.2 ################### setup #################### # import modules import ee import time import datetime import math import os import sys import arcpy import urllib2 import zipfile import pandas as pd # folder paths and variables # the script, input csv need to be in the main folder. Raster images should be downloaded to subfolders within the main folder parentFolder = os.path.dirname(sys.argv[0]) + "/" inputCSVFile = parentFolder + "Stations2017_v3_csv_version.csv" # file with PURE location data CSV_DICT = ['NAPS_ID','Lat_Decimal','Long_Decimal','StartYear'] # PURE attributes needed for the analysis START_YEAR = 2016 END_YEAR = 2016 collectionName = 'LANDSAT/LC8_L1T_32DAY_NDVI' # environmental variables and checkout necessary extensions and libraries arcpy.CheckOutExtension("Spatial") arcpy.env.overwriteOutput = True ee.Initialize() # use a water mask to remove NDVI values over water bodies waterMaskCollection = ee.ImageCollection("GLCF/GLS_WATER") waterMask = waterMaskCollection.reduce(ee.Reducer.median()) waterMaskScreen = ee.Image(waterMask).neq(2) # reduce image catalog to a specific year and geographic region of interest # INPUTS: # byear (str) - year of interest # filterBoundaries (ee.Geometry) - Google Earth Engine geometry object defining region of interest # collection (ee.ImageCollection) - Goolge Earth Engine image collection object containing rasters of interest # OUTPUTS: # datedCollect (ee.ImageCollection ) - Google Earth Engine image collection containing filtered raster dataset def filterCatalogSet(byear,filterBoundaries,collection): startDate = str(int(byear)) + "-01-01" endDate = str(byear) + "-12-31" datedCollect = collection.filterDate(startDate,endDate) datedCollect = datedCollect.filterBounds(filterBoundaries) return(datedCollect) # test if all raster images for all years for a specific location have been downloaded # INPUTS: # inputParams (dict) # startYear (int) - start year of data to download rasters for # endYear (int) - end year of data to download rasters for # randID (int) - random id for the community to identify exposures for # folderToTest (str) - full filepath to the folder to test # OUTPUTS: # boolean - True if folder contains all raster images, false otherwise def testComplete(inputParams,folderToTest): startYear = inputParams['startYear'] endYear = inputParams['endYear'] randID = inputParams['randID'] startYear = inputParams['startYear'] endYear = inputParams['endYear'] randID = inputParams['randID'] for year in range(startYear,endYear+1): yearFolder = folderToTest + str(year) zipFile = yearFolder + "/"+ str(randID) + ".zip" if not(os.path.exists(zipFile)): return False return True # download all raster images for a single location # INPUTS: # inputParams (dict) # startYear (int) - start year of data to download rasters for # endYear (int) - end year of data to download rasters for # randID (int) - random id for the community to identify exposures for # reducer (ee.reducer) - custom Google Earth Engine object # outputFolder (str) - full filepath to where rasters should be saved def downloadSinglePoint(inputParams, reducer,outputFolder): isComplete = testComplete(inputParams,outputFolder) if(isComplete): return True randID = inputParams['randID'] latit = inputParams['lat'] longit = inputParams['longit'] startYear = inputParams['startYear'] endYear = inputParams['endYear'] padding = 0.51 # amount of padding around boundary to add to the raster filterBoundaries = ee.Geometry.Rectangle(longit + padding, latit + padding, longit - padding, latit - padding) for year in range(startYear,endYear+1): yearFolder = outputFolder + str(year) zipFile = yearFolder + "/"+ str(randID) + ".zip" download=False timeToSleep=2 while download==False: if not(os.path.exists(zipFile)): try: download = downloadSingleRaster(year,yearFolder,filterBoundaries,reducer,zipFile,timeToSleep) except Exception as e: print(str(e)) finally: time.sleep(timeToSleep) else: print(zipFile + " already exists, did you already download this raster?") download=True # download one raster # INPUTS: # year (str) - year of raster coverage # yearFolder (str) - full filepath where image will be downloaded # filterBoundaries (ee.Geometry.Rectangle) - spatial exxtent of raster to download # reducer (ee.Reducer) - custom Google Earth Engine object - defines which type of summar stat to use (e.g. mean) # zipFile (str) - full filepath where the zipped raster should be written to # OUTPUTS: # True if raster download was successful, false otherwise def downloadSingleRaster(year,yearFolder,filterBoundaries,reducer,zipFile,timeToSleep): params = {'scale':'30'} # spatial resolution, in units of meters. Finest possible reoslution for MODIS is 250m, for Landsat8 is 30m collection = ee.ImageCollection(collectionName) imageCatalog = filterCatalogSet(year,filterBoundaries,collection) screenedImg = imageCatalog.map(mapMask) reducedImage = screenedImg.reduce(reducer) clippedImage = reducedImage.clip(filterBoundaries) url = clippedImage.getDownloadURL(params) print("the url to download is " + url) try: if(os.path.exists(yearFolder) == False): os.mkdir(yearFolder) f = open(zipFile ,'wb') f.write(urllib2.urlopen(url,timeout= 10*6).read()) f.close() zip_ref = zipfile.ZipFile(zipFile, 'r') zip_ref.extractall(yearFolder) zip_ref.close() return(True) except Exception as e: print(str(e)) if(str(e) == "HTTP Error 400: Bad Request"): return(True) time.sleep(timeToSleep) timeToSleep = min(60,timeToSleep+10) print(timeToSleep) try: f.close() except Exception as e: print(e) if(os.path.exists(zipFile)): os.remove(zipFile) return(False) # map an NDVI calculation and mask function to apply to each image in the NDVI dataset # Inputs: # image (Google Earth Engine image object) - raster image to apply the NDVI calculation # and mask function to # Outputs: # image (Google Earth Engine image object) - NDVI values of the input image after applying # the cloud and water mask def mapMask(image): #ndvi = ee.Image(image).select('NDVI') #fmaskVals = ee.Image(image).select('SummaryQA') validVals = [0,1] #screenedImg = ee.Image(fmaskVals).neq(-1) #screenedImg3 = ee.Image(fmaskVals).neq(2) #screenedImg4 = ee.Image(fmaskVals).neq(3) screenedImg = ee.Image(image).updateMask(waterMaskScreen) return screenedImg # process downloaded NDVI raster so ArcGIS properly recognizes null values as "NULL" # Inputs: # inputFolder (string) - folder containing .tif images to process # outputFolder (string) - folder containing input .tif images with NULL values # recognizable by ArcGIS def createRasters(inputFolder,outputFolder): filesToProcess = os.listdir(inputFolder) fileList = [] # for each file in the folder, change exact 0 values to NULL for filename in filesToProcess: if(filename[len(filename)-3:len(filename)] == "tif"): fileList.append(filename) for filename in fileList: outSetNull = arcpy.sa.SetNull(inputFolder + filename, inputFolder + filename, "VALUE = 0") outputName = outputFolder + filename[2:len(filename)-4] + "null" outSetNull.save(outputName.replace('.','')+ ".tif") # get data from a single row of a pandas dataframe # INPUTS: # rawData (pandas df) - contains raw data to read from # index (int) - row number to read # startYear (int) - first year of data coverage # endYear (int) - last year of data coverage # OUTPUTS: # tempDict (dictionary) # randID (int) - id previously assigned randomly to row instance # lat (float) - latitude coordinate # longit (float) - longitude coordinate # startYear (int) - starting year of data coverage # endYear (int) - ending year of data coverage def getRowData(rawData,index,startYear,endYear): tempRow = rawData.iloc[index] print(tempRow.head()) tempRandID = int(tempRow[CSV_DICT[0]]) tempLat = tempRow[CSV_DICT[1]] tempLong = tempRow[CSV_DICT[2]] tempDict = {'randID':tempRandID,'lat':tempLat,'longit':tempLong,'startYear':startYear,'endYear':endYear} return(tempDict) # test all zipped files in an input folder for correctness and remove corrupted files # INPUTS: # inputFolder (str) - folder containing zip files to test (and clean) def cleanZip(inputFolder): candidateZips = os.listdir(inputFolder) for candidate in candidateZips: if(candidate[len(candidate)-3:len(candidate)] == "zip"): try: a = zipfile.ZipFile(inputFolder + "/" + candidate) if(len(a.namelist()))==0: del(a) os.remove(inputFolder + "/" + candidate) except: print("removing file " + candidate) os.remove(inputFolder + "/" + candidate) # perform focal statistics on a single raster # INPUTS: # inputRaster (str) - full filepath to the raster # numCells (int) - radius of the focal statistics, in number of cells # outputFile (str) - full filepath where the output focal statistics raster will be written def focalStatsOnOneRaster(inputRaster,numCells, outputFile): outRaster = arcpy.sa.FocalStatistics(inputRaster, arcpy.sa.NbrCircle(numCells, "CELL"), "MEAN", "DATA") outRaster.save(outputFile) # perform focal statistics on all rasters located within a given input folder # INPUTS: # inputFolder (str) - folder where rasters to perform focal stats on are stored # numCells (int) - radius of the focal statistics, in number of cells # outputFolder (str) - full filepath where the output focal statistics raster will be written def focalStatisticsAllRasters(inputFolder,numCells,outputFolder): candidateFiles = os.listdir(inputFolder) filesToProcess = [] for candidateFile in candidateFiles: if(candidateFile[len(candidateFile)-3:len(candidateFile)] == "tif"): outputFile = outputFolder + "/" + candidateFile[0:len(candidateFile)-8] + ".tif" if not (os.path.exists(outputFile)): print(outputFile) focalStatsOnOneRaster(inputFolder + "/" + candidateFile, numCells,outputFile) else: print(outputFile + ' already exists') # merge multiple rasters into a single mosaiced raster # INPUTS: # inputFolder (str) - folder containing all rasters to merge # year (int) - year all rasters represent - used in mosaic filename def mergeRasters(inputFolder,year): candidateFiles = os.listdir(inputFolder) filesToMerge = [] for candidateFile in candidateFiles: if(candidateFile[len(candidateFile)-3:len(candidateFile)] == "tif"): filesToMerge.append(inputFolder + "/" + candidateFile) print(filesToMerge) arcpy.MosaicToNewRaster_management( input_rasters=filesToMerge, output_location=parentFolder, raster_dataset_name_with_extension="uNDVIx" + str(year) + ".tif", coordinate_system_for_the_raster="", pixel_type="32_BIT_FLOAT", cellsize="", number_of_bands="1", mosaic_method="MAXIMUM", mosaic_colormap_mode="FIRST" ) #################### main function
""" * Returns true if this bounding box is open in the Ymax direction. :rtype: bool """ return _Bnd.Bnd_Box_IsOpenYmax(self, *args) def IsOpenZmin(self, *args): """ * Returns true if this bounding box is open in the Zmin direction. :rtype: bool """ return _Bnd.Bnd_Box_IsOpenZmin(self, *args) def IsOpenZmax(self, *args): """ * Returns true if this bounding box is open in the Zmax direction. :rtype: bool """ return _Bnd.Bnd_Box_IsOpenZmax(self, *args) def IsWhole(self, *args): """ * Returns true if this bounding box is infinite in all 6 directions (WholeSpace flag). :rtype: bool """ return _Bnd.Bnd_Box_IsWhole(self, *args) def IsVoid(self, *args): """ * Returns true if this bounding box is empty (Void flag). :rtype: bool """ return _Bnd.Bnd_Box_IsVoid(self, *args) def IsXThin(self, *args): """ * true if xmax-xmin < tol. :param tol: :type tol: float :rtype: bool """ return _Bnd.Bnd_Box_IsXThin(self, *args) def IsYThin(self, *args): """ * true if ymax-ymin < tol. :param tol: :type tol: float :rtype: bool """ return _Bnd.Bnd_Box_IsYThin(self, *args) def IsZThin(self, *args): """ * true if zmax-zmin < tol. :param tol: :type tol: float :rtype: bool """ return _Bnd.Bnd_Box_IsZThin(self, *args) def IsThin(self, *args): """ * Returns true if IsXThin, IsYThin and IsZThin are all true, i.e. if the box is thin in all three dimensions. :param tol: :type tol: float :rtype: bool """ return _Bnd.Bnd_Box_IsThin(self, *args) def Transformed(self, *args): """ * Returns a bounding box which is the result of applying the transformation T to this bounding box. Warning Applying a geometric transformation (for example, a rotation) to a bounding box generally increases its dimensions. This is not optimal for algorithms which use it. :param T: :type T: gp_Trsf :rtype: Bnd_Box """ return _Bnd.Bnd_Box_Transformed(self, *args) def Add(self, *args): """ * Adds the box <Other> to <self>. :param Other: :type Other: Bnd_Box & :rtype: None * Adds a Pnt to the box. :param P: :type P: gp_Pnt :rtype: None * Extends <self> from the Pnt <P> in the direction <D>. :param P: :type P: gp_Pnt :param D: :type D: gp_Dir :rtype: None * Extends the Box in the given Direction, i.e. adds an half-line. The box may become infinite in 1,2 or 3 directions. :param D: :type D: gp_Dir :rtype: None """ return _Bnd.Bnd_Box_Add(self, *args) def IsOut(self, *args): """ * Returns True if the Pnt is out the box. :param P: :type P: gp_Pnt :rtype: bool * Returns False if the line intersects the box. :param L: :type L: gp_Lin :rtype: bool * Returns False if the plane intersects the box. :param P: :type P: gp_Pln :rtype: bool * Returns False if the <Box> intersects or is inside <self>. :param Other: :type Other: Bnd_Box & :rtype: bool * Returns False if the transformed <Box> intersects or is inside <self>. :param Other: :type Other: Bnd_Box & :param T: :type T: gp_Trsf :rtype: bool * Returns False if the transformed <Box> intersects or is inside the transformed box <self>. :param T1: :type T1: gp_Trsf :param Other: :type Other: Bnd_Box & :param T2: :type T2: gp_Trsf :rtype: bool * Returns False if the flat band lying between two parallel lines represented by their reference points <P1>, <P2> and direction <D> intersects the box. :param P1: :type P1: gp_Pnt :param P2: :type P2: gp_Pnt :param D: :type D: gp_Dir :rtype: bool """ return _Bnd.Bnd_Box_IsOut(self, *args) def Distance(self, *args): """ * Computes the minimum distance between two boxes. :param Other: :type Other: Bnd_Box & :rtype: float """ return _Bnd.Bnd_Box_Distance(self, *args) def Dump(self, *args): """ :rtype: None """ return _Bnd.Bnd_Box_Dump(self, *args) def SquareExtent(self, *args): """ * Computes the squared diagonal of me. :rtype: float """ return _Bnd.Bnd_Box_SquareExtent(self, *args) __swig_destroy__ = _Bnd.delete_Bnd_Box Bnd_Box.SetWhole = new_instancemethod(_Bnd.Bnd_Box_SetWhole,None,Bnd_Box) Bnd_Box.SetVoid = new_instancemethod(_Bnd.Bnd_Box_SetVoid,None,Bnd_Box) Bnd_Box.Set = new_instancemethod(_Bnd.Bnd_Box_Set,None,Bnd_Box) Bnd_Box.Update = new_instancemethod(_Bnd.Bnd_Box_Update,None,Bnd_Box) Bnd_Box.GetGap = new_instancemethod(_Bnd.Bnd_Box_GetGap,None,Bnd_Box) Bnd_Box.SetGap = new_instancemethod(_Bnd.Bnd_Box_SetGap,None,Bnd_Box) Bnd_Box.Enlarge = new_instancemethod(_Bnd.Bnd_Box_Enlarge,None,Bnd_Box) Bnd_Box.Get = new_instancemethod(_Bnd.Bnd_Box_Get,None,Bnd_Box) Bnd_Box.OpenXmin = new_instancemethod(_Bnd.Bnd_Box_OpenXmin,None,Bnd_Box) Bnd_Box.OpenXmax = new_instancemethod(_Bnd.Bnd_Box_OpenXmax,None,Bnd_Box) Bnd_Box.OpenYmin = new_instancemethod(_Bnd.Bnd_Box_OpenYmin,None,Bnd_Box) Bnd_Box.OpenYmax = new_instancemethod(_Bnd.Bnd_Box_OpenYmax,None,Bnd_Box) Bnd_Box.OpenZmin = new_instancemethod(_Bnd.Bnd_Box_OpenZmin,None,Bnd_Box) Bnd_Box.OpenZmax = new_instancemethod(_Bnd.Bnd_Box_OpenZmax,None,Bnd_Box) Bnd_Box.IsOpenXmin = new_instancemethod(_Bnd.Bnd_Box_IsOpenXmin,None,Bnd_Box) Bnd_Box.IsOpenXmax = new_instancemethod(_Bnd.Bnd_Box_IsOpenXmax,None,Bnd_Box) Bnd_Box.IsOpenYmin = new_instancemethod(_Bnd.Bnd_Box_IsOpenYmin,None,Bnd_Box) Bnd_Box.IsOpenYmax = new_instancemethod(_Bnd.Bnd_Box_IsOpenYmax,None,Bnd_Box) Bnd_Box.IsOpenZmin = new_instancemethod(_Bnd.Bnd_Box_IsOpenZmin,None,Bnd_Box) Bnd_Box.IsOpenZmax = new_instancemethod(_Bnd.Bnd_Box_IsOpenZmax,None,Bnd_Box) Bnd_Box.IsWhole = new_instancemethod(_Bnd.Bnd_Box_IsWhole,None,Bnd_Box) Bnd_Box.IsVoid = new_instancemethod(_Bnd.Bnd_Box_IsVoid,None,Bnd_Box) Bnd_Box.IsXThin = new_instancemethod(_Bnd.Bnd_Box_IsXThin,None,Bnd_Box) Bnd_Box.IsYThin = new_instancemethod(_Bnd.Bnd_Box_IsYThin,None,Bnd_Box) Bnd_Box.IsZThin = new_instancemethod(_Bnd.Bnd_Box_IsZThin,None,Bnd_Box) Bnd_Box.IsThin = new_instancemethod(_Bnd.Bnd_Box_IsThin,None,Bnd_Box) Bnd_Box.Transformed = new_instancemethod(_Bnd.Bnd_Box_Transformed,None,Bnd_Box) Bnd_Box.Add = new_instancemethod(_Bnd.Bnd_Box_Add,None,Bnd_Box) Bnd_Box.IsOut = new_instancemethod(_Bnd.Bnd_Box_IsOut,None,Bnd_Box) Bnd_Box.Distance = new_instancemethod(_Bnd.Bnd_Box_Distance,None,Bnd_Box) Bnd_Box.Dump = new_instancemethod(_Bnd.Bnd_Box_Dump,None,Bnd_Box) Bnd_Box.SquareExtent = new_instancemethod(_Bnd.Bnd_Box_SquareExtent,None,Bnd_Box) Bnd_Box_swigregister = _Bnd.Bnd_Box_swigregister Bnd_Box_swigregister(Bnd_Box) class Bnd_Box2d(object): thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ * Creates an empty 2D bounding box. The constructed box is qualified Void. Its gap is null. :rtype: None """ _Bnd.Bnd_Box2d_swiginit(self,_Bnd.new_Bnd_Box2d(*args)) def SetWhole(self, *args): """ * Sets this bounding box so that it covers the whole 2D space, i.e. it is infinite in all directions. :rtype: None """ return _Bnd.Bnd_Box2d_SetWhole(self, *args) def SetVoid(self, *args): """ * Sets this 2D bounding box so that it is empty. All points are outside a void box. :rtype: None """ return _Bnd.Bnd_Box2d_SetVoid(self, *args) def Set(self, *args): """ * Sets this 2D bounding box so that it bounds the point P. This involves first setting this bounding box to be void and then adding the point PThe rectangle bounds the point <P>. :param P: :type P: gp_Pnt2d :rtype: None * Sets this 2D bounding box so that it bounds the half-line defined by point P and direction D, i.e. all points M defined by M=P+u*D, where u is greater than or equal to 0, are inside the bounding area. This involves first setting this 2D box to be void and then adding the half-line. :param P: :type P: gp_Pnt2d :param D: :type D: gp_Dir2d :rtype: None """ return _Bnd.Bnd_Box2d_Set(self, *args) def Update(self, *args): """ * Enlarges this 2D bounding box, if required, so that it contains at least: - interval [ aXmin,aXmax ] in the 'X Direction', - interval [ aYmin,aYmax ] in the 'Y Direction' :param aXmin: :type aXmin: float :param aYmin: :type aYmin: float :param aXmax: :type aXmax: float :param aYmax: :type aYmax: float :rtype: None * Adds a point of coordinates (X,Y) to this bounding box. :param X: :type X: float :param Y: :type Y: float :rtype: None """ return _Bnd.Bnd_Box2d_Update(self, *args) def GetGap(self, *args): """ * Returns the gap of this 2D bounding box. :rtype: float """ return _Bnd.Bnd_Box2d_GetGap(self, *args) def SetGap(self, *args): """ * Set the gap of this 2D bounding box to abs(Tol). :param Tol: :type Tol: float :rtype: None """ return _Bnd.Bnd_Box2d_SetGap(self, *args) def Enlarge(self, *args): """ * Enlarges the box with a tolerance value. This means that the minimum values of its X and Y intervals of definition, when they are finite, are reduced by the absolute value of Tol, while the maximum values are increased by the same amount. :param Tol: :type Tol: float :rtype: None """ return _Bnd.Bnd_Box2d_Enlarge(self, *args) def Get(self, *args): """ * Returns the bounds of this 2D bounding box. The gap is included. If this bounding box is infinite (i.e. 'open'), returned values may be equal to +/- Precision::Infinite(). if IsVoid() :param aXmin: :type aXmin: float & :param aYmin: :type aYmin: float & :param aXmax: :type aXmax: float & :param aYmax: :type aYmax: float & :rtype: None """ return _Bnd.Bnd_Box2d_Get(self, *args) def OpenXmin(self, *args): """ * The Box will be infinitely long in the Xmin direction. :rtype: None """ return _Bnd.Bnd_Box2d_OpenXmin(self, *args) def OpenXmax(self, *args): """ * The Box will be infinitely long in the Xmax direction. :rtype: None """ return _Bnd.Bnd_Box2d_OpenXmax(self, *args) def OpenYmin(self, *args): """ * The Box will be infinitely long in the Ymin direction. :rtype: None """ return _Bnd.Bnd_Box2d_OpenYmin(self, *args) def OpenYmax(self, *args): """ * The Box will be infinitely long in the Ymax direction. :rtype: None """ return _Bnd.Bnd_Box2d_OpenYmax(self, *args) def IsOpenXmin(self, *args): """ * Returns true if this bounding box is open in the Xmin direction. :rtype: bool """ return _Bnd.Bnd_Box2d_IsOpenXmin(self, *args) def IsOpenXmax(self, *args): """ * Returns true if this bounding box is open in the Xmax direction. :rtype: bool """ return _Bnd.Bnd_Box2d_IsOpenXmax(self, *args) def IsOpenYmin(self, *args): """ * Returns true if this bounding box is open in the Ymin direction. :rtype: bool """ return _Bnd.Bnd_Box2d_IsOpenYmin(self, *args) def
from os import environ environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' import pygame DEFAULT_LOAD_ADDRESS = 0x0801 SYMBOLS = { 'D6510': 0x0000, 'R6510': 0x0001, } IRQ_RATE = 50 ROMSLIST = [ # (File)Name, begin address, end address, bit of bank switch register (R6510) ("basic", 0xA000, 0xBFFF, 0), ("chargen", 0xD000, 0xDFFF, 1), ("kernal", 0xE000, 0xFFFF, 2), ] COLORS = [0x000000, 0xFFFFFF, 0x93493E, 0x85C6CD, 0x9450B7, 0x73B34A, 0x4637AC, 0xD6E07D, 0x9A6929, 0x675100, 0xC28279, 0x606060, 0x8B8B8B, 0xB4ED92, 0x877BDF, 0xB5B5B5 ] PALETTE = [[q >> 16, (q >> 8) & 0xFF, q & 0xFF] for q in COLORS] ADDRESSING_METHODS = [ "IMP", "IMM", "REL", "ABS", "ZP", "ABS_X", "ABS_Y", "ZP_X", "ZP_Y", "IND", "X_IND" "IND_Y" ] OPCODES = { 0x00: ("BRK", "IMP"), 0x01: ("ORA", "X_IND"), 0x02: (None, ""), 0x03: (None, ""), 0x04: ("NOP", "ZP"), 0x05: ("ORA", "ZP"), 0x06: ("ASL", "ZP"), 0x07: (None, ""), 0x08: ("PHP", "IMP"), 0x09: ("ORA", "IMM"), 0x0a: ("ASL", "IMP"), 0x0b: (None, ""), 0x0c: ("NOP", "ABS"), 0x0d: ("ORA", "ABS"), 0x0e: ("ASL", "ABS"), 0x0f: (None, ""), 0x10: ("BPL", "REL"), 0x11: ("ORA", "IND_Y"), 0x12: (None, ""), 0x13: (None, ""), 0x14: ("NOP", "ZP_X"), 0x15: ("ORA", "ZP_X"), 0x16: ("ASL", "ZP_X"), 0x17: (None, ""), 0x18: ("CLC", "IMP"), 0x19: ("ORA", "ABS_Y"), 0x1a: ("NOP", "IMP"), 0x1b: (None, ""), 0x1c: ("NOP", "ABS_X"), 0x1d: ("ORA", "ABS_X"), 0x1e: ("ASL", "ABS_X"), 0x1f: (None, ""), 0x20: ("JSR", "ABS"), 0x21: ("AND", "X_IND"), 0x22: (None, ""), 0x23: (None, ""), 0x24: ("BIT", "ZP"), 0x25: ("AND", "ZP"), 0x26: ("ROL", "ZP"), 0x27: (None, ""), 0x28: ("PLP", "IMP"), 0x29: ("AND", "IMM"), 0x2a: ("ROL", "IMP"), 0x2b: ("ANC", "IMM"), 0x2c: ("BIT", "ABS"), 0x2d: ("AND", "ABS"), 0x2e: ("ROL", "ABS"), 0x2f: (None, ""), 0x30: ("BMI", "REL"), 0x31: ("AND", "IND_Y"), 0x32: (None, ""), 0x33: ("RLA", "IND_Y"), 0x34: ("NOP", "ZP_X"), 0x35: ("AND", "ZP_X"), 0x36: ("ROL", "ZP_X"), 0x37: (None, ""), 0x38: ("SEC", "IMP"), 0x39: ("AND", "ABS_Y"), 0x3a: ("NOP", "IMP"), 0x3b: ("RLA", "ABS_Y"), 0x3c: ("NOP", "ABS_X"), 0x3d: ("AND", "ABS_X"), 0x3e: ("ROL", "ABS_X"), 0x3f: (None, ""), 0x40: ("RTI", "IMP"), 0x41: ("EOR", "X_IND"), 0x42: (None, ""), 0x43: (None, ""), 0x44: ("NOP", "ZP"), 0x45: ("EOR", "ZP"), 0x46: ("LSR", "ZP"), 0x47: (None, ""), 0x48: ("PHA", "IMP"), 0x49: ("EOR", "IMM"), 0x4a: ("LSR", "IMP"), 0x4b: ("ALR", "IMM"), 0x4c: ("JMP", "ABS"), 0x4d: ("EOR", "ABS"), 0x4e: ("LSR", "ABS"), 0x4f: (None, ""), 0x50: ("BVC", "REL"), 0x51: ("EOR", "IND_Y"), 0x52: (None, ""), 0x53: (None, ""), 0x54: ("NOP", "ZP_X"), 0x55: ("EOR", "ZP_X"), 0x56: ("LSR", "ZP_X"), 0x57: (None, ""), 0x58: ("CLI", "IMP"), 0x59: ("EOR", "ABS_Y"), 0x5a: ("NOP", "IMP"), 0x5b: ("SRE", "ABS_Y"), 0x5c: ("NOP", "ABS_X"), 0x5d: ("EOR", "ABS_X"), 0x5e: ("LSR", "ABS_X"), 0x5f: (None, ""), 0x60: ("RTS", "IMP"), 0x61: ("ADC", "X_IND"), 0x62: (None, ""), 0x63: (None, ""), 0x64: ("NOP", "ZP"), 0x65: ("ADC", "ZP"), 0x66: ("ROR", "ZP"), 0x67: (None, ""), 0x68: ("PLA", "IMP"), 0x69: ("ADC", "IMM"), 0x6a: ("ROR", "IMP"), 0x6b: (None, ""), 0x6c: ("JMP", "IND"), 0x6d: ("ADC", "ABS"), 0x6e: ("ROR", "ABS"), 0x6f: (None, ""), 0x70: ("BVS", "REL"), 0x71: ("ADC", "IND_Y"), 0x72: (None, ""), 0x73: (None, ""), 0x74: ("NOP", "ZP_X"), 0x75: ("ADC", "ZP_X"), 0x76: ("ROR", "ZP_X"), 0x77: ("RRA", "ZP_X"), 0x78: ("SEI", "IMP"), 0x79: ("ADC", "ABS_Y"), 0x7a: ("NOP", "IMP"), 0x7b: (None, ""), 0x7c: ("NOP", "ABS_X"), 0x7d: ("ADC", "ABS_X"), 0x7e: ("ROR", "ABS_X"), 0x7f: (None, ""), 0x80: ("NOP", "IMM"), 0x81: ("STA", "X_IND"), 0x82: (None, ""), 0x83: (None, ""), 0x84: ("STY", "ZP"), 0x85: ("STA", "ZP"), 0x86: ("STX", "ZP"), 0x87: (None, ""), 0x88: ("DEY", "IMP"), 0x89: ("NOP", "IMM"), 0x8a: ("TXA", "IMP"), 0x8b: (None, ""), 0x8c: ("STY", "ABS"), 0x8d: ("STA", "ABS"), 0x8e: ("STX", "ABS"), 0x8f: (None, ""), 0x90: ("BCC", "REL"), 0x91: ("STA", "IND_Y"), 0x92: (None, ""), 0x93: (None, ""), 0x94: ("STY", "ZP_X"), 0x95: ("STA", "ZP_X"), 0x96: ("STX", "ZP_Y"), 0x97: (None, ""), 0x98: ("TYA", "IMP"), 0x99: ("STA", "ABS_Y"), 0x9a: ("TXS", "IMP"), 0x9b: (None, ""), 0x9c: ("SHY", "ABS_X"), 0x9d: ("STA", "ABS_X"), 0x9e: ("SHX", "ABS_X"), 0x9f: (None, ""), 0xa0: ("LDY", "IMM"), 0xa1: ("LDA", "X_IND"), 0xa2: ("LDX", "IMM"), 0xa3: (None, ""), 0xa4: ("LDY", "ZP"), 0xa5: ("LDA", "ZP"), 0xa6: ("LDX", "ZP"), 0xa7: (None, ""), 0xa8: ("TAY", "IMP"), 0xa9: ("LDA", "IMM"), 0xaa: ("TAX", "IMP"), 0xab: (None, ""), 0xac: ("LDY", "ABS"), 0xad: ("LDA", "ABS"), 0xae: ("LDX", "ABS"), 0xaf: (None, ""), 0xb0: ("BCS", "REL"), 0xb1: ("LDA", "IND_Y"), 0xb2: (None, ""), 0xb3: (None, ""), 0xb4: ("LDY", "ZP_X"), 0xb5: ("LDA", "ZP_X"), 0xb6: ("LDX", "ZP_X"), 0xb7: (None, ""), 0xb8: ("CLV", "IMP"), 0xb9: ("LDA", "ABS_Y"), 0xba: ("TSX", "IMP"), 0xbb: (None, ""), 0xbc: ("LDY", "ABS_X"), 0xbd: ("LDA", "ABS_X"), 0xbe: ("LDX", "ABS_X"), 0xbf: (None, ""), 0xc0: ("CPY", "IMM"), 0xc1: ("CMP", "X_IND"), 0xc2: (None, ""), 0xc3: (None, ""), 0xc4: ("CPY", "ZP"), 0xc5: ("CMP", "ZP"), 0xc6: ("DEC", "ZP"), 0xc7: (None, ""), 0xc8: ("INY", "IMP"), 0xc9: ("CMP", "IMM"), 0xca: ("DEX", "IMP"), 0xcb: (None, ""), 0xcc: ("CPY", "ABS"), 0xcd: ("CMP", "ABS"), 0xce: ("DEC", "ABS"), 0xcf: (None, ""), 0xd0: ("BNE", "REL"), 0xd1: ("CMP", "IND_Y"), 0xd2: (None, ""), 0xd3: (None, ""), 0xd4: ("NOP", "ZP_X"), 0xd5: ("CMP", "ZP_X"), 0xd6: ("DEC", "ZP_X"), 0xd7: (None, ""), 0xd8: ("CLD", "IMP"), 0xd9: ("CMP", "ABS_Y"), 0xda: ("NOP", "IMP"), 0xdb: (None, ""), 0xdc: ("NOP", "IMM"), 0xdd: ("CMP", "ABS_X"), 0xde: ("DEC", "ABS_X"), 0xdf: (None, ""), 0xe0: ("CPX", "IMM"), 0xe1: ("SBC", "X_IND"), 0xe2: (None, ""), 0xe3: (None, ""), 0xe4: ("CPX", "ZP"), 0xe5: ("SBC", "ZP"), 0xe6: ("INC", "ZP"), 0xe7: (None, ""), 0xe8: ("INX", "IMP"), 0xe9: ("SBC", "IMM"), 0xea: ("NOP", "IMP"), 0xeb: (None, ""), 0xec: ("CPX", "ABS"), 0xed: ("SBC", "ABS"), 0xee: ("INC", "ABS"), 0xef: (None, ""), 0xf0: ("BEQ", "REL"), 0xf1: ("SBC", "IND_Y"), 0xf2: (None, ""), 0xf3: (None, ""), 0xf4: ("NOP", "ZP_X"), 0xf5: ("SBC", "ZP_X"), 0xf6: ("INC", "ZP_X"), 0xf7: (None, ""), 0xf8: ("SED", "IMP"), 0xf9: ("SBC", "ABS_Y"), 0xfa: ("NOP", "IMP"), 0xfb: (None, ""), 0xfc: ("NOP", "ABS_X"), 0xfd: ("SBC", "ABS_X"), 0xfe: ("INC", "ABS_X"), 0xff: (None, ""), } KEYTABLE = { pygame.K_BACKSPACE: [20, 148, 148], # pygame.K_TAB :[\t , # pygame.K_CLEAR :[ , pygame.K_RETURN: [13, 141, 141], # pygame.K_PAUSE :[ , pygame.K_ESCAPE: [3, 131, 131], pygame.K_SPACE: [32, 160, 160], # pygame.K_EXCLAIM :[33 , # pygame.K_QUOTEDBL :[34 , # pygame.K_HASH :[35 , # pygame.K_DOLLAR :[36 , # pygame.K_AMPERSAND :[38 , pygame.K_QUOTE: [39, 63, None], # pygame.K_LEFTPAREN :[40 , # pygame.K_RIGHTPAREN :[41 , # pygame.K_ASTERISK :[42 , 42, None] , pygame.K_PLUS: [43, 42, None], pygame.K_COMMA: [44, 59, None], pygame.K_MINUS: [45, None, None], pygame.K_PERIOD: [46, 58, None], pygame.K_SLASH: [47, 47, None], pygame.K_0: [48, 61, None], pygame.K_1: [49, 33, 129], pygame.K_2: [50, 34, 149], pygame.K_3: [51, 92, 150], pygame.K_4: [52, 36, 151], pygame.K_5: [53, 37, 152], pygame.K_6: [54, 38, 153], pygame.K_7: [55, 47, 154], pygame.K_8: [56, 40, 155], pygame.K_9: [57, 41, None], # pygame.K_COLON :[58 , None, None] , # pygame.K_SEMICOLON :[59 , None, None] , pygame.K_LESS: [60, 63, None], # pygame.K_EQUALS :[61 , None, None] , # pygame.K_GREATER :[63 , None, None], # pygame.K_QUESTION :[63 , None, None], pygame.K_AT: [64, None, None], # pygame.K_LEFTBRACKET :[[ , # pygame.K_BACKSLASH :[\ , # pygame.K_RIGHTBRACKET:[ ] , # pygame.K_CARET :[^ , # pygame.K_UNDERSCORE :[_ , # pygame.K_BACKQUOTE :[` , pygame.K_a: [65, 193, 176], pygame.K_b: [66, 194, 191], pygame.K_c: [67, 195, 188], pygame.K_d: [68, 196, 172], pygame.K_e: [69, 197, 177], pygame.K_f: [70, 198, 187], pygame.K_g: [71, 199, 165], pygame.K_h: [72, 200, 180], pygame.K_i: [73, 201, 162], pygame.K_j: [74, 202, 181], pygame.K_k: [75, 203, 161], pygame.K_l: [76, 204, 182], pygame.K_m: [77, 205, 167], pygame.K_n: [78, 206, 170], pygame.K_o: [79, 207, 185], pygame.K_p: [80, 208, 175], pygame.K_q: [81, 209, 171], pygame.K_r: [82, 210, 178], pygame.K_s: [83, 211, 174], pygame.K_t: [84, 212, 163], pygame.K_u: [85, 213, 184], pygame.K_v: [86, 214, 190], pygame.K_w: [87, 215, 179], pygame.K_x: [88, 216, 188], pygame.K_y: [89, 217, 183], pygame.K_z: [90, 218, 173], pygame.K_DELETE: [20, 148, 148], pygame.K_KP0: [48, 48, 48], pygame.K_KP1: [49, 49, 49], pygame.K_KP2: [50, 50, 50], pygame.K_KP3: [51, 51, 51], pygame.K_KP4: [52, 52, 52], pygame.K_KP5: [53, 53, 53], pygame.K_KP6: [54, 54, 54], pygame.K_KP7: [55, 55, 55], pygame.K_KP8: [56, 56, 56], pygame.K_KP9: [57, 57, 57], pygame.K_KP_PERIOD: [46, 46, 46], pygame.K_KP_DIVIDE: [47, 47, 47], pygame.K_KP_MULTIPLY: [42, 42, 42], pygame.K_KP_MINUS: [45, 45, 45], pygame.K_KP_PLUS: [43, 43, 43], pygame.K_KP_ENTER: [13, 141, 141], pygame.K_KP_EQUALS: [61, None, None], pygame.K_UP: [145, 145, None], pygame.K_DOWN: [17, 17, None], pygame.K_RIGHT: [29, 29, None], pygame.K_LEFT: [157, 157, None], pygame.K_INSERT: [148, 148, 148], pygame.K_HOME: [19, 147, 147], # pygame.K_END :[ , # pygame.K_PAGEUP :[ , # pygame.K_PAGEDOWN :[ , pygame.K_F1: [133, 133, 133], pygame.K_F2: [137, 137, 137], pygame.K_F3: [134, 134, 134], pygame.K_F4:
<gh_stars>10-100 #!/usr/bin/python # -*- coding: utf-8 -*- # # Reza(User:reza1615), 2011 # Distributed under the terms of the MIT license. # #copy # #become checkdictation-fa #cp zz_checkDictation_cmd.py /data/project/checkdictation-fa/www/python/src/ # #source www/python/venv/bin/activate #webservice2 uwsgi-python restart # update #python /data/project/checkdictation-fa/www/python/src/zz_checkDictation_cmd.py Botupdate # to get list of wrong pages # #jsub -l release=trusty -once -N addbox -mem 3g /data/project/checkdictation-fa/www/python/venv/bin/python /data/project/checkdictation-fa/www/python/src/zz_checkDictation_cmd.py -start:! import sys # version 7.20 sys.path.insert(0, '/data/project/checkdictation-fa/www/python/src/compat/') BotAdress = u'/data/project/checkdictation-fa/www/python/src/' BotAdress_main = u'/data/project/checkdictation-fa/' import codecs, os, json, re, io,string,time,requests,wikipedia,pagegenerators,urllib2 from operator import itemgetter try: import hunspell hobj = hunspell.HunSpell(BotAdress+'fa_IR.dic', BotAdress+'fa_IR.aff') except: print "Could not import hunspell" wikipedia.config.put_throttle = 0 wikipedia.put_throttle.setDelay() persianPastVerbs = ur'(' persianPastVerbs+=ur'ارزید|افتاد|افراشت|افروخت|افزود|افسرد|افشاند|افکند|انباشت|انجامید|انداخت|اندوخت|اندود|اندیشید|انگاشت|انگیخت|انگیزاند|اوباشت|ایستاد' persianPastVerbs+=ur'|آراست|آراماند|آرامید|آرمید|آزرد|آزمود|آسود|آشامید|آشفت|آشوبید|آغازید|آغشت|آفرید|آکند|آگند|آلود|آمد|آمرزید|آموخت|آموزاند' persianPastVerbs+=ur'|آمیخت|آهیخت|آورد|آویخت|باخت|باراند|بارید|بافت|بالید|باوراند|بایست|بخشود|بخشید|برازید|برد|برید|بست|بسود|بسیجید|بلعید' persianPastVerbs+=ur'|بود|بوسید|بویید|بیخت|پاشاند|پاشید|پالود|پایید|پخت|پذیراند|پذیرفت|پراکند|پراند|پرداخت|پرستید|پرسید|پرهیزید|پروراند|پرورد|پرید' persianPastVerbs+=ur'|پژمرد|پژوهید|پسندید|پلاسید|پلکید|پناهید|پنداشت|پوسید|پوشاند|پوشید|پویید|پیچاند|پیچانید|پیچید|پیراست|پیمود|پیوست|تاباند|تابید|تاخت' persianPastVerbs+=ur'|تاراند|تازاند|تازید|تافت|تپاند|تپید|تراشاند|تراشید|تراوید|ترساند|ترسید|ترشید|ترکاند|ترکید|تکاند|تکانید|تنید|توانست|جَست|جُست' persianPastVerbs+=ur'|جست|جنباند|جنبید|جنگید|جهاند|جهید|جوشاند|جوشید|جوید|چاپید|چایید|چپاند|چپید|چراند|چربید|چرخاند|چرخید|چرید|چسباند|چسبید' persianPastVerbs+=ur'|چشاند|چشید|چکاند|چکید|چلاند|چلانید|چمید|چید|خاراند|خارید|خاست|خایید|خراشاند|خراشید|خرامید|خروشید|خرید|خزید|خست|خشکاند' persianPastVerbs+=ur'|خشکید|خفت|خلید|خمید|خنداند|خندانید|خندید|خواباند|خوابانید|خوابید|خواست|خواند|خوراند|خورد|خوفید|خیساند|خیسید|داد|داشت|دانست' persianPastVerbs+=ur'|درخشانید|درخشید|دروید|درید|درگذشت|دزدید|دمید|دواند|دوخت|دوشید|دوید|دید|دیدم|راند|ربود|رخشید|رساند|رسانید|رست|رَست|رُست' persianPastVerbs+=ur'|رسید|رشت|رفت|رُفت|رقصاند|رقصید|رمید|رنجاند|رنجید|رندید|رهاند|رهانید|رهید|روبید|روفت|رویاند|رویید|ریخت|رید|ریسید' persianPastVerbs+=ur'|زاد|زارید|زایید|زد|زدود|زیست|سابید|ساخت|سپارد|سپرد|سپوخت|ستاند|ستد|سترد|ستود|ستیزید|سرایید|سرشت|سرود|سرید' persianPastVerbs+=ur'|سزید|سفت|سگالید|سنجید|سوخت|سود|سوزاند|شاشید|شایست|شتافت|شد|شست|شکافت|شکست|شکفت|شکیفت|شگفت|شمارد|شمرد|شناخت' persianPastVerbs+=ur'|شناساند|شنید|شوراند|شورید|طپید|طلبید|طوفید|غارتید|غرید|غلتاند|غلتانید|غلتید|غلطاند|غلطانید|غلطید|غنود|فرستاد|فرسود|فرمود|فروخت' persianPastVerbs+=ur'|فریفت|فشاند|فشرد|فهماند|فهمید|قاپید|قبولاند|کاست|کاشت|کاوید|کرد|کشاند|کشانید|کشت|کشید|کفت|کفید|کند|کوبید|کوچید' persianPastVerbs+=ur'|کوشید|کوفت|گَزید|گُزید|گایید|گداخت|گذارد|گذاشت|گذراند|گذشت|گرازید|گرایید|گرداند|گردانید|گردید|گرفت|گروید|گریاند|گریخت|گریست' persianPastVerbs+=ur'|گزارد|گزید|گسارد|گستراند|گسترد|گسست|گسیخت|گشت|گشود|گفت|گمارد|گماشت|گنجاند|گنجانید|گنجید|گندید|گوارید|گوزید|لرزاند|لرزید' persianPastVerbs+=ur'|لغزاند|لغزید|لمباند|لمدنی|لمید|لندید|لنگید|لهید|لولید|لیسید|ماسید|مالاند|مالید|ماند|مانست|مرد|مکشید|مکید|مولید|مویید' persianPastVerbs+=ur'|نازید|نالید|نامید|نشاند|نشست|نکوهید|نگاشت|نگریست|نمایاند|نمود|نهاد|نهفت|نواخت|نوردید|نوشاند|نوشت|نوشید|نیوشید|هراسید|هشت' persianPastVerbs+=ur'|ورزید|وزاند|وزید|یارست|یازید|یافت' persianPastVerbs+=ur')' persianPresentVerbs = ur'(' persianPresentVerbs+=ur'ارز|افت|افراز|افروز|افزا|افزای|افسر|افشان|افکن|انبار|انباز|انجام|انداز|اندای|اندوز|اندیش|انگار|انگیز|انگیزان' persianPresentVerbs+=ur'|اوبار|ایست|آرا|آرام|آرامان|آرای|آزار|آزما|آزمای|آسا|آسای|آشام|آشوب|آغار|آغاز|آفرین|آکن|آگن|آلا|آلای' persianPresentVerbs+=ur'|آمرز|آموز|آموزان|آمیز|آهنج|آور|آویز|آی|بار|باران|باز|باش|باف|بال|باوران|بای|باید|بخش|بخشا|بخشای' persianPresentVerbs+=ur'|بر|بَر|بُر|براز|بساو|بسیج|بلع|بند|بو|بوس|بوی|بیز|بین|پا|پاش|پاشان|پالا|پالای|پذیر|پذیران' persianPresentVerbs+=ur'|پر|پراکن|پران|پرداز|پرس|پرست|پرهیز|پرور|پروران|پز|پژمر|پژوه|پسند|پلاس|پلک|پناه|پندار|پوس|پوش|پوشان' persianPresentVerbs+=ur'|پوی|پیچ|پیچان|پیرا|پیرای|پیما|پیمای|پیوند|تاب|تابان|تاران|تاز|تازان|تپ|تپان|تراش|تراشان|تراو|ترس|ترسان' persianPresentVerbs+=ur'|ترش|ترک|ترکان|تکان|تن|توان|توپ|جنب|جنبان|جنگ|جه|جهان|جو|جوش|جوشان|جوی|چاپ|چای|چپ|چپان' persianPresentVerbs+=ur'|چر|چران|چرب|چرخ|چرخان|چسب|چسبان|چش|چشان|چک|چکان|چل|چلان|چم|چین|خار|خاران|خای|خر|خراش' persianPresentVerbs+=ur'|خراشان|خرام|خروش|خز|خست|خشک|خشکان|خل|خم|خند|خندان|خواب|خوابان|خوان|خواه|خور|خوران|خوف|خیز|خیس' persianPresentVerbs+=ur'|خیسان|دار|درخش|درخشان|درو|دزد|دم|ده|دو|دوان|دوز|دوش|ران|ربا|ربای|رخش|رس|رسان' persianPresentVerbs+=ur'|رشت|رقص|رقصان|رم|رنج|رنجان|رند|ره|رهان|رو|روب|روی|رویان|ریز|ریس|رین|زا|زار|زای|زدا' persianPresentVerbs+=ur'|زدای|زن|زی|ساب|ساز|سای|سپار|سپر|سپوز|ستا|ستان|ستر|ستیز|سر|سرا|سرای|سرشت|سز|سگال|سنب' persianPresentVerbs+=ur'|سنج|سوز|سوزان|شاش|شای|شتاب|شکاف|شکف|شکن|شکوف|شکیب|شمار|شمر|شناس|شناسان|شنو|شو|شور|شوران|شوی' persianPresentVerbs+=ur'|طپ|طلب|طوف|غارت|غر|غلت|غلتان|غلط|غلطان|غنو|فرسا|فرسای|فرست|فرما|فرمای|فروش|فریب|فشار|فشان|فشر' persianPresentVerbs+=ur'|فهم|فهمان|قاپ|قبولان|کار|کاه|کاو|کش|کَش|کُش|کِش|کشان|کف|کن|کوب|کوچ|کوش|گا|گای|گداز' persianPresentVerbs+=ur'|گذار|گذر|گذران|گرا|گراز|گرای|گرد|گردان|گرو|گری|گریان|گریز|گز|گزار|گزین|گسار|گستر|گستران|گسل|گشا' persianPresentVerbs+=ur'|گشای|گمار|گنج|گنجان|گند|گو|گوار|گوز|گوی|گیر|لرز|لرزان|لغز|لغزان|لم|لمبان|لند|لنگ|له|لول' persianPresentVerbs+=ur'|لیس|ماس|مال|مان|مک|مول|موی|میر|ناز|نال|نام|نشان|نشین|نکوه|نگار|نگر|نما|نمای|نمایان|نه' persianPresentVerbs+=ur'|نهنب|نواز|نورد|نوش|نوشان|نویس|نیوش|هراس|هست|هل|ورز|وز|وزان|یاب|یار|یاز' persianPresentVerbs+=ur')' epithet_black_list,most_words_list,Persian_words_list,wiki_titles_list,slang_list,bad_list=[],[],[],[],[],[] Wrong_word_list={} def disambig_get(pagetitle): urlr="https://fa.wikipedia.org/wiki/"+urllib2.quote(pagetitle.encode('utf-8')) page = urllib2.urlopen(urlr) htmltxt= page.read() htmltxt=unicode(htmltxt,'UTF-8') return htmltxt def checkdisambig(htmltxt): disambig_list=[] dismbigresults=[] htmltxt=re.sub(ur'<div role="note" class="hatnote navigation-not-searchable">(.*?)</div>',u'',htmltxt)#حذف ابهام‌زدایی در الگو تغییرمسیر a_list=htmltxt.split(u'<a ') for i in a_list: item=i.split(u'>')[0] if (u'class="mw-disambig"' in item or u'class="mw-redirect mw-disambig"' in item) and u'title="' in item: item=item.split(u'title="')[1].split(u'"')[0] #print item if not item in disambig_list: disambig_suggest=get_page_links(redirect_find(item)) dismbigresults.append({ "type": 8, "word": item, "cleaned_word": item, "suggestions": disambig_suggest }) disambig_list.append(item) return dismbigresults def redirect_find(page_link): page_link=page_link.replace(u' ',u'_') params = { 'action': 'query', 'redirects':"", 'titles': page_link, "format": 'json' } try: return requests.post('https://fa.wikipedia.org/w/api.php', params).json()['query']['redirects'][0]['to'] except: time.sleep(2) try: return requests.post('https://fa.wikipedia.org/w/api.php', params).json()['query']['redirects'][0]['to'] except: return page_link return page_link def get_page_links(linktitle): txt=u'' items=[] items2=[] links=[] params={ "action": 'query', "prop": 'links', "titles": linktitle, "pllimit":500, "plnamespace":0, "format": 'json' } try: links= requests.post('https://fa.wikipedia.org/w/api.php', params).json()['query']['pages'].values()[0]['links'] except: time.sleep(2) try: links= requests.post('https://fa.wikipedia.org/w/api.php', params).json()['query']['pages'].values()[0]['links'] except: pass for i in links: if re.sub(ur'[a-zA-Z\:]+','',i['title'])==i['title']: item_to_add=i['title'] if u' ' +linktitle.replace(u'_',u' ')+u' ' in u' ' +item_to_add.replace(u'_',u' ')+u' ': items.append(item_to_add.strip()) if u'(' in item_to_add: items.append(item_to_add+u'|'+item_to_add.split(u'(')[0].strip()) items2.append(item_to_add) if not items: items=items2 return items def convert_regex (input,new_matchs,dict): if u'?' in input: Char_Index=input.find(u'?') new_match=input.replace(u'?',u'') if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] new_match=input[0:Char_Index-1]+input[Char_Index+1:] if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] if re.sub(ur'[یک]',u'',input)!= input: new_match=input.replace(u'ی',u'ي') if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] new_match=input.replace(u'ک',u'ك') if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] new_match=input.replace(u'ک',u'ك').replace(u'ی',u'ي') if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] new_match=input.replace(u'ک',u'[کك]').replace(u'ی',u'[یي]') if not new_match in new_matchs: try: new_matchs.append(new_match) except: new_matchs[new_match]=dict[input] return new_matchs def load_dict(): add_regex2={} add_regex=[] global epithet_black_list,Wrong_word_list,most_words_list,Persian_words_list,wiki_titles_list,slang_list,bad_list epithet_black_list,most_words_list,Persian_words_list,wiki_titles_list,slang_list,bad_list=[],[],[],[],[],[] Wrong_word_list={} fa_bad_text = codecs.open(BotAdress+u'zz_bad_words.txt', 'r', 'utf8') bad_list = [fa_bad_text.read().strip()] fa_wrong_text = codecs.open(BotAdress+u'zz_Wrong_word_dict.txt', 'r', 'utf8') fa_wrong_text = fa_wrong_text.read() fa_slang_text = codecs.open(BotAdress+u'zz_slang_word_dict.txt', 'r', 'utf8') fa_slang_text = fa_slang_text.read() #---wrong fa_wrong_text=fa_wrong_text.replace(u'\(',u'(').replace(u'\)',u')') lines = fa_wrong_text.split(u'\n') for line in lines: if line.strip().startswith(u'#') or line.strip().startswith(u'=') or line.strip().startswith(u'{'): continue if line.strip().startswith(u'*'):#القاب input=line.split(u'||')[0].replace(u'*',u'').strip() add_regex=convert_regex (input,add_regex,False) epithet_black_list.append(input) if line.startswith(u' ') and u'||' in line:#غلط input2=line.split(u'||')[0].strip() Wrong_word_list[input2]=line.split(u'||')[1].strip() add_regex2=convert_regex (input2,add_regex2,Wrong_word_list) for i in add_regex: if not i in epithet_black_list: epithet_black_list.append(i) for i in add_regex2: if not i in Wrong_word_list: Wrong_word_list[i]=add_regex2[i] #--slang lines = fa_slang_text.split(u'\n') for line in lines: if line.strip().startswith(u'#') or line.strip().startswith(u'=') or line.strip().startswith(u'{'): continue if line.strip().startswith(u'*'):#عامیانه line=re.sub(u'^\*',u'',line) slang_list.append(line) most_words = codecs.open(BotAdress+u'zz_Most_word_dict.txt', 'r', 'utf8') most_words = most_words.read() most_words2 = codecs.open(BotAdress+u'zz_users_word_dict.txt', 'r', 'utf8') most_words2=most_words2.read() most_words2=most_words2.replace(u'* ',u'').replace(u'*',u'').replace(u'\r',u'').strip() most_words = most_words+u'\n'+most_words2 most_words=most_words.replace(u'\r',u'') most_words_list=most_words.split(u'\n') Persian_words = codecs.open(BotAdress+u'zz_Persian_word_dict.txt', 'r', 'utf8') Persian_words = Persian_words.read() Persian_words=Persian_words.replace(u'\r',u'') Persian_words_list=Persian_words.split(u'\n') wiki_titles = codecs.open(BotAdress+u'zz_wiki_titles_dict.txt', 'r', 'utf8') wiki_titles = wiki_titles.read() wiki_titles=wiki_titles.replace(u'\r',u'') wiki_titles_list=wiki_titles.split(u'\n') def find_gumeh_base(txt): lines=txt.split(u'\n') giumeh_place_finall,giumeh_place,min_giumeh_place=[],[],[] for line in lines: if string.count( line,u"«" )>string.count( line,u"»" ): giumeh_place=re.findall(ur'(?!«[^»«]+»)(«[^»«]+)',line) min_giumeh_place=re.findall(ur'(«[^«»]+»)',line) for i in giumeh_place: if not i in min_giumeh_place: if not i in giumeh_place_finall: giumeh_place_finall.append(i) if string.count( line,u"«" )<string.count( line,u"»" ): giumeh_place=re.findall(ur'([^«»]+»)',line) min_giumeh_place=re.findall(ur'(«[^«»]+»)',line) for i in giumeh_place: if not i in min_giumeh_place: if not i in giumeh_place_finall: giumeh_place_finall.append(i) return giumeh_place_finall def find_gumeh(txt): list=find_gumeh_base(txt) new_list=[] for i in list: if i[0]==u"«": if len(i)>30: ourtxt=i[:29] else: ourtxt=i ourtxt2=re.findall(ur"«(?:[^\]\[\'\<»«]+)",ourtxt) if ourtxt2: if len(ourtxt2[0])>5: ourtxt=ourtxt2[0] new_list.append(ourtxt) else: if len(i)>30: ourtxt=i[-29:] else: ourtxt=i ourtxt2=re.findall(ur"(?![\]\[\'\<»«]+)(?:[^\]\[\'\<»«]+)»",ourtxt) if ourtxt2: if len(ourtxt2[0])>5: ourtxt=ourtxt2[0] new_list.append(ourtxt) return new_list def clean_text(txt,remove_regex,faTitle): Syntaxs_list=[] Syntaxs_list2=[] Erab_words=[] giumeh_place=[] fa_syntax_text=re.sub(ur'<(nowiki|math|code|pre|source|syntaxhighlight)(?:[^<]|<(?!\/\1>))*?<\/\1>',u'',txt) fa_syntax_text=re.sub(ur'%7B%7B',u'{{',fa_syntax_text) fa_syntax_text=re.sub(ur'%7D%7D',u'}}',fa_syntax_text) fa_syntax_text=re.sub(ur'\<\!\-\-(?:[^-]|-(?!->))*?\-\-\>',u'',fa_syntax_text) fa_syntax_text_old=fa_syntax_text fa_syntax_text=re.sub(ur'\{\{\{[^\}\{]+\}\}\}',u'',fa_syntax_text) fa_syntax_text=re.sub(ur'\{\{\{[^\}\{]+\}\}\}',u'',fa_syntax_text) fa_syntax_text=re.sub(ur'\{\{\{[^\}\{]+\}\}\}',u'',fa_syntax_text) if fa_syntax_text_old!=fa_syntax_text: Syntaxs_list.append(u'استفاده از متغییر الگو مانند {{{ }}} در مقاله') if string.count( fa_syntax_text,u"{{" )> string.count( fa_syntax_text,u"}}" ): Syntaxs_list.append(u'{{') if string.count( fa_syntax_text,u"{{" )< string.count( fa_syntax_text,u"}}" ): Syntaxs_list.append(u'}}') if string.count( fa_syntax_text,u"[[" )>string.count( fa_syntax_text,u"]]" ): Syntaxs_list.append(u'[[') if string.count( fa_syntax_text,u"[[" )<string.count( fa_syntax_text,u"]]" ): Syntaxs_list.append(u']]') if string.count( fa_syntax_text,u"«" )>string.count( fa_syntax_text,u"»" ): Syntaxs_list2.append(u'»') giumeh_place.append(find_gumeh(fa_syntax_text_old)) if string.count( fa_syntax_text,u"«" )<string.count( fa_syntax_text,u"»" ): Syntaxs_list2.append(u'«') giumeh_place.append(find_gumeh(fa_syntax_text_old)) if string.count( fa_syntax_text,u"<!--" )!=string.count( fa_syntax_text,u"-->" ): Syntaxs_list.append(u'<!-- یکی از علامت‌های شروع یا پایان توضیح وجود ندارد -->') txt=re.sub(ur'<(nowiki|math|code|pre|source|syntaxhighlight)(?:[^<]|<(?!\/\1>))*?<\/\1>',u'',txt) txt=re.sub(ur'\[\[[^\[]*?\]\]',u' ',txt) txt=re.sub(ur'\{\{(?:عربی|شروع عربی|آغاز عربی)\}\}([\s\S]*?)\{\{(?:پایان عربی)\}\}',u'',txt) txt=re.sub(ur'\{\{(?:به .+?|به انگلیسی|انگلیسی|عربی|حدیث|به عربی|به اردو|اردو|lang\-[au]r)[\s\S]*?\}\}',u'',txt) txt=re.sub(ur'\[\[[^\]]\]\]',u'',txt) txt=re.sub(ur'[…  ᠎           

   ]',u' ',txt) txt=re.sub(ur'\/\/.*?(?=[\s\n\|\}\]<]|$)',u' ',txt)#حذف نشانی اینترنتی txt=re.sub(ur'(\|.*?\=)',u' ',txt) txt=re.sub(ur'\[\[رده\:.*?\]\]',u' ',txt) txt=re.sub(ur'(\{\{.*?\}\})',u' ',txt) txt=re.sub(ur'(\{\{.*?\|)',u' ',txt) txt=re.sub(ur'(\<.*?\>)',u' ',txt) txt=re.sub(ur'\r',u'',txt) txt=re.sub(ur"([\^\%\$\#\@\&\,\=\{\[\}\]\'\|۱۲۳۴۵۶۷۸۹۰\?\.\!؟،\:؛\"\/\\\t\'\*\+\–\-\n0-9٬٫a-zA-Z\_\ـ])+",u' ',txt) isolated_char=u'ﭖﭗﭘﭙﭺﭻﭼﭽﮊﮋﮎﮏﮐﮑﻙﻚﻛﻜﮒﮓﮔﮕﮤﮥﯼﯽﯾﯿﻯﻰﻱﻲﻳﻴﺁﺁﺂﺄﺃﺃﺅﺅﺆﺇﺈﺇﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻫﻭﻮﻰﻲﻵﻶﻸﻷﻹﻺﻻﻼ' txt=re.sub(ur'([^ ‌ء-يٓ-ٕپچژگکكڪﻙﻚیﻱﻲكﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴ\(\)«»'+isolated_char+u'ً-ِْٰٔٔأإؤئءةٓ])+',u'',txt) txt=re.sub(ur"[\s]{2,}",u' ',txt) Erab_words_List = re.findall(ur'(?=\S*[أإؤئءةًٌٍَُِْٰٓٓ])\S+\s', txt) if Erab_words_List: for Eword in Erab_words_List: Eword=Eword.strip() without_erab_word=re.sub(ur"([ًٌٍَُِّْٰٓ])+",u'',Eword) without_erab_word2=re.sub(ur"([أإؤئءةٓ])+",u'',without_erab_word) ErabNum=len(Eword)-len(without_erab_word2.strip()) if ErabNum >2 and (not without_erab_word in Erab_words): Erab_words.append(without_erab_word) txt=re.sub(ur"([ً-ِْٰٔٔ])+",u'',txt) clean_fa_text=txt txt=txt.replace(u'»',u' ').replace(u'«',u' ') txt=re.sub(ur"[\(\)]",u' ',txt) txt=re.sub(ur"[\s]{2,}",u' ',txt) txt=re.sub(ur'(\s)'+remove_regex+ur'(\s)',u' ',u' '+txt+u' ') #print txt txt_list=txt.strip().split(u' ') txt_list2=txt_list txt_list = list(set(txt_list)) faTitle2=re.sub(ur"([\(\)\^\%\$\#\@\&\,\=\{\[\}\]\'\|۱۲۳۴۵۶۷۸۹۰\?\.\!؟»«،\:؛\"\/\\\t\'\*\+\–\-\n0-9٬٫a-zA-Z\_\ـ])+",u' ',faTitle) faTitle_list=faTitle2.strip()+u' '+faTitle.replace(u'‌',u'')+u' '+faTitle.replace(u'‌',u' ')+u' '+faTitle+u'‌ها'+u' '+faTitle+u'‌های'+u' '+faTitle+u'‌هایی'+u' '+faTitle+u'ی'+u' ' faTitle_list=faTitle_list.strip().split(u' ') txt_list=[x for x in txt_list if x not in Erab_words] txt_list=[x for x in txt_list if x not in faTitle_list] return txt_list,clean_fa_text,Syntaxs_list,Syntaxs_list2,Erab_words,giumeh_place,txt_list2 def regex_maker(list, Correct, faText, correct_dict,my_suggestions,faTitle): result = [] suggestions=[] for wrong_word in list: if correct_dict: suggestions = [list[wrong_word]] if not correct_dict and my_suggestions: suggestions=my_suggestions.get(wrong_word, []) if u' ' + wrong_word + u' ' in faText and not u' ' + wrong_word + u' ' in u' ' +faTitle+ u' ': clean_wrong_word=clean_word(wrong_word) if u'|' in clean_wrong_word: clean_wrong_word=clean_wrong_word.split(u'|')[1] result.append({ u"type": Correct, u"word": wrong_word, u"cleaned_word":clean_wrong_word, u"suggestions": suggestions }) return result def regex_maker_slang(regex_list,Correct, faText): result = [] suggestions=[] hun_list=[] slang_ok=[] for myregex in regex_list: myregex = re.compile(myregex, re.MULTILINE | re.UNICODE) slang_results = re.findall(myregex, faText) if slang_results: for slangs in slang_results: if slangs: hun_list2=[] try: slangs=slangs.strip() except: slangs=slangs[0] if slangs in slang_ok: continue try: if not hobj.spell(slangs): hun_list=hobj.suggest(slangs) for a in hun_list: hun_list2.append(unicode(a,'UTF-8')) except: pass if u' ' + slangs + u' ' in faText: clean_wrong_word=clean_word(slangs) if u'|' in clean_wrong_word: clean_wrong_word=clean_wrong_word.split(u'|')[1] slang_ok.append(slangs) result.append({ u"type": Correct, u"word": slangs, u"cleaned_word":clean_wrong_word, u"suggestions": hun_list2 }) return result,slang_ok def clean_word(txt): txt2=u'' txt1=txt txt=re.sub(ur'‌?تر(ها|ین‌?ها|ین|)(ی|)$',u'',txt) txt=re.sub(ur'‌?های(م|ت|ش|مان|تان|شان)$',u'',txt) txt=re.sub(ur'‌?های?ی?$',u'',txt) txt=re.sub(ur'‌?(است|بود|شد|گذاری)$',u'',txt) txt=re.sub(ur'‌?(ای|ام|ات|اید|اش|مان|تان|شان|گاه)$',u'',txt) if txt1==txt: txt=re.sub(ur'‌?(یی|ست|ند)$',u'',txt) if txt1==txt: txt2=txt txt=re.sub(ur'(م|ت|ش|ان|ی|یم|ید)$',u'',txt) if txt1==txt: txt=re.sub(ur'^(نا|غیر|بی|با|در|بر|پر)‌?',u'',txt) txt=txt.strip() if txt2: txt=txt+u"|"+txt2.strip() return txt def get_page(title): txt=u'' try: txt= requests.post('https://fa.wikipedia.org/w/api.php', params={"titles": title,"action": "query", "prop": "revisions", "rvprop": "content", "format": "json"}).json()['query']['pages'].values()[0]['revisions'][0]['*'] except: time.sleep(2) try: txt= requests.post('https://fa.wikipedia.org/w/api.php', params={"titles": title,"action": "query", "prop": "revisions", "rvprop": "content", "format": "json"}).json()['query']['pages'].values()[0]['revisions'][0]['*'] except: pass return txt def check_grammer(faText_list,words_text_list): first_step_words = [] for item in faText_list: if item in words_text_list: continue item2=re.sub(ur'(ب|ن|م|می|نمی|)‌?'+persianPastVerbs+u'(ه|)‌?(بوده?|شده?|می‌شود?|)(م|ی|یم|ید|ند|ام|ای|است|ایم|اید|اند|)',u'',item) if not item2.replace(u'‌',u'').strip(): continue item2=re.sub(ur'(ب|ن|م|می|نمی|)‌?'+persianPresentVerbs+ur'(م|ی|یم|ید|ند|)',u'',item) if not item2.replace(u'‌',u'').strip(): continue item1=clean_word(item).split(u'|')[0] if item!=item1: if item1 in words_text_list: continue if item1+u'ن' in words_text_list: continue item1 = item.replace(u'‌',u'').strip() if item!=item1: if item1 in words_text_list: continue first_step_words.append(item) return first_step_words def connected_word(pre,word,my_list): try: if word[0:len(pre)]==pre: my_list=[word.replace(pre,pre+u' ',1)] + my_list if word[-len(pre):]==pre: my_list=[word[:-len(pre)]+u' '+pre]+ my_list except: pass return my_list def main(faTitle,word): if (u'نظرخواهی' in faTitle or u'قهوه‌خانه' in faTitle or u'تابلو' in faTitle or u'/' in faTitle) and u'ویکی‌پدیا:' in faTitle: if faTitle!=u'ویکی‌پدیا:اشتباه‌یاب/تست' and faTitle!=u'ویکی‌پدیا:اشتباه‌یاب/تمرین': return { u"result":[],"error": "not supposed to work on RfCs" } if faTitle: try: faText =u'\n' +get_page(faTitle)+ u'\n' faText=faText.replace(u'[[ ',u'[[').replace(u'[[ ',u'[[').replace(u' ]]',u']]').replace(u' ]]',u']]') faText=faText.replace(u' |',u'|').replace(u' |',u'|') if not faText.strip(): return { u"result":[],"error": "the page couldn't be retrieved" } except: return { u"result":[],"error": "the page couldn't be retrieved" } result = [] remove_regex = u'('+u'|'.join(epithet_black_list)+u'|'+u'|'.join(Wrong_word_list)+u')' faText_list,clean_fa_text,Syntaxs_list,Syntaxs_list2,Erab_words,giumeh_place,txt_list2 = clean_text(faText,remove_regex,faTitle) faNewText = u' ' + u' '.join(faText_list) + u' ' clean_fa_text2=re.sub(ur'«[^»]+»',u' ',clean_fa_text) result = result + sorted(regex_maker(epithet_black_list,0,clean_fa_text2,False,{},faTitle), key=itemgetter('word')) result_slang,slang_ok=regex_maker_slang(slang_list,5,clean_fa_text2) result = result + sorted(result_slang, key=itemgetter('word')) result_bad,bad_ok=regex_maker_slang(bad_list,6,clean_fa_text2) result = result + sorted(result_bad, key=itemgetter('word')) clean_fa_text=clean_fa_text.replace(u'»',u' ').replace(u'«',u' ') result = result + sorted(regex_maker(Wrong_word_list,2,clean_fa_text,True,{},faTitle), key=itemgetter('word')) del clean_fa_text if word: result ,Syntaxs_list,Syntaxs_list2= [],[],[] faNewText=u' '+word+u' ' faText_list=[word] #--------first step check -------- first_step_words=check_grammer(faText_list,most_words_list) del faText_list #--------Second step check -------- second_step_words=check_grammer(first_step_words,Persian_words_list) del first_step_words #--------Third step check -------- Third_step_words=[] for item in second_step_words: if not item in wiki_titles_list: Third_step_words.append(item) del second_step_words for Syntaxs in Syntaxs_list: result= result+ [{ u"type": 3, u"word": Syntaxs, u"suggestions":[] }] #for Syntaxs in Syntaxs_list2: if giumeh_place: for Syntaxs in giumeh_place[0]: result= result+ [{ u"type": 7, u"word": Syntaxs, u"suggestions":[] }] hun_suggest={} isolated_char=u'ﭖﭗﭘﭙﭺﭻﭼﭽﮊﮋﮎﮏﮐﮑﻙﻚﻛﻜﮒﮓﮔﮕﮤﮥﯼﯽﯾﯿﻯﻰﻱﻲﻳﻴﺁﺁﺂﺄﺃﺃﺅﺅﺆﺇﺈﺇﺉﺊﺋﺌﺍﺎﺏﺐﺑﺒﺕﺖﺗﺘﺙﺚﺛﺜﺝﺞﺟﺠﺡﺢﺣﺤﺥﺦﺧﺨﺩﺪﺫﺬﺭﺮﺯﺰﺱﺲﺳﺴﺵﺶﺷﺸﺹﺺﺻﺼﺽﺾﺿﻀﻁﻂﻃﻄﻅﻆﻇﻈﻉﻊﻋﻌﻍﻎﻏﻐﻑﻒﻓﻔﻕﻖﻗﻘﻝﻞﻟﻠﻡﻢﻣﻤﻥﻦﻧﻨﻩﻪﻫﻬﻫﻭﻮﻰﻲﻵﻶﻸﻷﻹﻺﻻﻼ' similar_char=u'كﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ' Fourth_step_words=Third_step_words Fifth_step_words=[] for item in Third_step_words: if item!=re.sub(ur'['+isolated_char+similar_char+ur'\u200e\u200f]',u'',item): Fifth_step_words.append(item) Fourth_step_words.remove(item) result = result + sorted(regex_maker(Fifth_step_words,4,faNewText,False,{},faTitle), key=itemgetter('word')) Fourth_step_words=[x for x in Fourth_step_words if x not in slang_ok] Fourth_step_words=[x for x in Fourth_step_words if x not in bad_ok] try: for wo in Fourth_step_words: if not hobj.spell(wo): hun_list=hobj.suggest(wo) hun_list2=[] for a in hun_list: hun_list2.append(unicode(a,'UTF-8')) hun_list2=connected_word(u'و',wo,hun_list2) hun_list2=connected_word(u'در',wo,hun_list2) hun_list2=connected_word(u'با',wo,hun_list2) hun_list2=connected_word(u'هم',wo,hun_list2) hun_list2=connected_word(u'از',wo,hun_list2) hun_list2=connected_word(u'که',wo,hun_list2) hun_list2=connected_word(u'هزار',wo,hun_list2) hun_suggest[wo]=hun_list2 else: Fourth_step_words.remove(wo) except: pass # if a wrong word is repaeted at the
import time import numpy as np import types import torch.nn as nn import torch.utils.data import ummon.utils as uu from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data.dataset import ConcatDataset from torch.utils.data.dataset import Subset from .logger import Logger from .schedulers import * from .trainingstate import * from .analyzer import Analyzer __all__ = ["Trainer", "SupervisedTrainer", "ClassificationTrainer", "UnsupervisedTrainer", "SiameseTrainer", "KamikazeTrainer"] class Trainer: """ This class provides a generic trainer for training PyTorch-models. For specialized use in Regression or Classification this class needs to be subclassed. Constructor ----------- logger : ummon.Logger The logger to use (if NULL default logger will be used) model : torch.nn.module The model used for training loss_function : torch.nn.module : The loss function for the optimization optimizer : torch.optim.optimizer The optimizer for the training trainingstate : ummon.Trainingstate A previously instantiated training state variable. Can be used to initialize model and optimizer with a previous saved state. scheduler : torch.optim.lr_scheduler._LRScheduler OPTIONAL A learning rate scheduler model_filename : String : OPTIONAL Name of the persisted model files model_keep_epochs : bool OPTIONAL Specifies intermediate (for every epoch) model persistency (default False). precision : np.dtype OPTIONAL Specifiec FP32 or FP64 Training (default np.float32). convergence_eps : float OPTIONAL Specifies when the training has converged (default np.float32.min). combined_training_epochs : int OPTIONAL Specifies how many epochs combined retraining (training and validation data) shall take place after the usal training cycle (default 0). optim_closure : callable OPTIONAL Callable closure that gets passed to step(closure) of optimizer if torch.optim.LBFGS Methods ------- fit() : trains a model _evaluate() : validates the model _moving_average(): helper method """ def __init__(self, *args, **kwargs): # required arguments if len(args) != 4: raise ValueError('You must provide at least a logger, model, loss_function and optimizer for training.') self.logger = args[0] assert type(self.logger) == Logger self.model = args[1] assert isinstance(self.model, nn.Module) self.criterion = args[2] if self.criterion is None: self.criterion = lambda X,y : X # just replays model output assert isinstance(self.criterion, nn.Module) or isinstance(self.criterion, types.LambdaType) self.optimizer = args[3] if self.optimizer is None: self.optimizer = torch.optim.SGD([Variable(torch.zeros(0))], lr=0) # just does nothing assert isinstance(self.optimizer, torch.optim.Optimizer) # defaults self.trainingstate = Trainingstate(filename=None, model_keep_epochs=False) self.scheduler = None self.precision = np.float32 self.convergence_eps = np.finfo(np.float32).min self.combined_training_epochs = False self.use_cuda = False # optional arguments for key in kwargs: if key == 'trainingstate': if not isinstance(kwargs[key], Trainingstate): raise TypeError('{} is not a training state'.format(type(kwargs[key]).__name__)) self.trainingstate = kwargs[key] if 'model_filename' in kwargs.keys(): self.trainingstate.filename = str(kwargs["model_filename"]).split(self.trainingstate.extension)[0] if 'model_keep_epochs' in kwargs.keys(): self.trainingstate.model_keep_epochs = int(kwargs["model_keep_epochs"]) elif key == 'scheduler': if not isinstance(kwargs[key], torch.optim.lr_scheduler._LRScheduler) and not \ isinstance(kwargs[key], StepLR_earlystop): raise TypeError('{} is not a scheduler'.format(type(kwargs[key]).__name__)) if isinstance(kwargs[key], StepLR_earlystop) and 'trainingstate' not in kwargs.keys(): raise ValueError('StepLR_earlystop needs an external Trainingstate (you provided None).') self.scheduler = kwargs[key] elif key == 'precision': assert kwargs[key] == np.float32 or kwargs[key] == np.float64 self.precision = kwargs[key] elif key == 'convergence_eps': self.convergence_eps = float(kwargs[key]) elif key == 'combined_training_epochs': if self.trainingstate.filename is None: raise ValueError('Combined retraining needs a model_filename to load the best model after training. (you provided None).') self.combined_training_epochs = int(kwargs[key]) elif key == 'model_keep_epochs': self.trainingstate.model_keep_epochs = int(kwargs[key]) elif key == 'model_filename': self.trainingstate.filename = str(kwargs[key]).split(self.trainingstate.extension)[0] elif key == 'use_cuda': self.use_cuda = kwargs[key] elif key == 'optim_closure': self.optim_closure = kwargs[key] else: raise ValueError('Unknown keyword {} in constructor.'.format(key)) # Training parameters self.epoch = 0 # training state was filled by previous training or by persisted training state if 'trainingstate' in kwargs.keys() and self.trainingstate.state != None: self._status_summary() self.epoch = self.trainingstate.state["training_loss[]"][-1][0] self.trainingstate.load_optimizer_(self.optimizer) self.trainingstate.load_weights_(self.model, self.optimizer) if isinstance(self.scheduler, StepLR_earlystop): self.trainingstate.load_scheduler_(self.scheduler) # Computational configuration if self.use_cuda: if not torch.cuda.is_available(): self.logger.error('CUDA is not available on your system.') else: self.use_cuda = next(self.model.parameters()).is_cuda self.model = Trainingstate.transform_model(self.model, self.optimizer, self.precision, self.use_cuda) def fit(self, dataloader_training, epochs=1, validation_set=None, eval_interval=1, eval_batch_size=-1, analyzer=Analyzer, metrics=[]): """ Fits a model with given training and validation dataset Arguments --------- dataloader_training : torch.utils.data.DataLoader OR tuple (X,y,batch) The dataloader that provides the training data epochs : int Epochs to train validation_set : torch.utils.data.Dataset OR tuple (X,y) OR torch.utils.data.DataLoader The validation dataset eval_interval : int Evaluation interval for validation dataset in epochs eval_batch_size : OPTIONAL int batch size used for evaluation (default: -1 == ALL) Analyzer (ummon.Analyzer) : A training type specific analyzer. metrics (ummon.metrics) : a list of metrics """ # INPUT VALIDATION epochs = int(epochs) if epochs < 1: self.logger.error('Number of epochs must be > 0.', ValueError) dataloader_training = uu.gen_dataloader(dataloader_training, has_labels=True, logger=self.logger) batches = len(dataloader_training) if eval_batch_size == -1: eval_batch_size = dataloader_training.batch_size dataloader_validation = uu.gen_dataloader(validation_set, batch_size=eval_batch_size, has_labels=True, logger=self.logger) # PROBLEM SUMMARY self._problem_summary(epochs, dataloader_training, dataloader_validation, self.scheduler) for epoch in range(self.epoch, self.epoch + epochs): # switch on training mode self.model.train() # EPOCH PREPARATION time_dict = self._prepare_epoch() # COMPUTE ONE EPOCH for batch, data in enumerate(dataloader_training, 0): # time dataloader time_dict["loader"] = time_dict["loader"] + (time.time() - time_dict["t"]) # Get the inputs inputs, targets = self._get_batch(data) output, time_dict = self._forward_one_batch(inputs, time_dict) loss, time_dict = self._loss_one_batch(output, targets, time_dict) # Backpropagation time_dict = self._backward_one_batch(loss, time_dict, output, targets) # Reporting time_dict = self._finish_one_batch(batch, batches, epoch, loss.item(), dataloader_training.batch_size, time_dict) # Evaluate if epoch % eval_interval == 0 and not torch.isnan(loss): self.model.eval() self._evaluate_training(analyzer, batch, batches, time_dict, epoch, dataloader_validation, dataloader_training, eval_batch_size, metrics) # SAVE MODEL self.trainingstate.save_state() # CHECK TRAINING CONVERGENCE if self._has_converged(): break if torch.isnan(loss) and epoch == 0: raise Exception("Loss was NaN in 1st epoch.") # ANNEAL LEARNING RATE if self.scheduler: try: self.scheduler.step() except StepsFinished: break # DO COMBINED RETRAINING WITH BEST VALIDATION MODEL self._combined_retraining(dataloader_training, validation_set, eval_batch_size) def _prepare_epoch(self): """ Some epoch initialization stuff like adjusting the learning rate scheduler and initializing the clock. Return ------ time_dict (dictionary of timestamps): Dictionary that is used for profiling executing time. """ # TAKE TIME time_dict = {"t" : time.time(), "loader" : 0, "model" : 0, "loss" : 0, "backprop" : 0, "total" : 0} return time_dict def _forward_one_batch(self, inputs, time_dict): """ Some epoch initialization stuff like adjusting the learning rate scheduler and initializing the clock. Arguments --------- *inputs (torch.autograd.Variable): A packed torch.Tensor representing a single mini-batch. *time_dict (dict) : Dictionary that is used for profiling executing time. Return ------ *output (torch.autograd.Variable): A packed torch.Tensor representing a single output of a mini-batch. *time_dict (dict) : Dictionary that is used for profiling executing time. """ # Execute Model output = self.model(inputs) # time model time_dict["model"] = time_dict["model"] + (time.time() - time_dict["t"]) return output, time_dict def _loss_one_batch(self, output, targets, time_dict): """ Computes the loss for a single mini-batch Arguments --------- *output (torch.Tensor): A packed torch.Tensor representing a single output of a mini-batch. *targets (torch.Tensor): The targets for a mini-batch *time_dict (dict) : Dictionary that is used for profiling executing time. Return ------ *loss (torch.Tensor): The computed loss as scalar *time_dict (dict) : Dictionary that is used for profiling executing time. """ if type(output) != tuple and type(output) != list and targets is not None and type(targets) != list and type(targets) != tuple: if targets.is_cuda or output.is_cuda: output, targets = output.to('cuda'), targets.to('cuda') if (type(output) == tuple or type(output) == list) and targets is not None: if output[0].is_cuda or output[1].is_cuda: output = uu.tensor_tuple_to_cuda(output) if type(targets) == tuple or type(targets) == list: targets = uu.tensor_tuple_to_cuda(targets) try: loss = self.criterion(output, targets) except (ValueError, TypeError): try: # case: loss does not have targets e.g. entropy loss loss = self.criterion(output) except (ValueError, TypeError): try: # case: case targets are not formatted correctly loss = self.criterion(output, targets.view_as(output)) except RuntimeError: # case: targets are not formatted correctly loss = self.criterion(output, targets.view_as(output).float()) # time loss time_dict["loss"] = time_dict["loss"] + (time.time() - time_dict["t"]) return loss, time_dict def _backward_one_batch(self, loss, time_dict, output=None, targets=None): """ Computes the loss for a single mini-batch Arguments --------- *loss (torch.autograd.Variable): The computed loss as scalar *time_dict (dict) : Dictionary that is used for profiling executing time. *OPTIONAL output
in books: content_id = b['ContentID'] isbn = b['ISBN'] title = b['Title'].strip() # ugh. not sure about that, but sometimes helped author = b['Attribution'] # TODO not so sure about that; it was the case for KoboShelfes databases time_spent = b.get('TimeSpentReading', 0) percent = b['___PercentRead'] status = int(b['ReadStatus']) last_read = b['DateLastRead'] mimetype = b['MimeType'] if mimetype == 'application/x-kobo-html+pocket': # skip Pocket articles continue if mimetype == 'image/png': # skip images continue user_id = b['___UserID'] if user_id == '': # that seems to mean that book is an ad, not an actual book loaded on device continue book = Book( title=title, author=author, content_id=content_id, isbn=isbn, ) extra = Extra( time_spent=time_spent, percent=percent, status=status, last_read=_parse_utcdt(last_read), ) items.append((book, extra)) return items # TODO Event table? got all sort of things from june 2017 # 1012 looks like starting to read.. # 1012/1013 -- finishing? class EventTbl: EventType = 'EventType' EventCount = 'EventCount' LastOccurrence = 'LastOccurrence' ContentID = 'ContentID' Checksum = 'Checksum' ExtraData = 'ExtraData' # TODO ExtraData got some interesting blobs.. class Types: # occurs occasionally throughout reading.. first event looks like a good candidate for 'started to read' T3 = 3 # always appears as one of the last events. also seems to be same as DateLastRead. So reasonable to assume it means book finished BOOK_FINISHED = 5 # could be book purchases? although for one book, occurst 4 times so doesn't make sense.. T7 = 7 # not sure what are these, doen't have contentid and accumulates throughout history T0 = 0 T1 = 1 T6 = 6 T8 = 8 T79 = 79 # looks like dictionary lookups (judging to DictionaryName in blob) T9 = 9 # 80 occurs in pair with 5, but also sometimes repeats for dozens of times. T80 = 80 # some random totally unrelated timestamp appearing for some Epubs T37 = 37 # happens very often, sometimes in bursts of 5 over 5 seconds. could be page turns? T46 = 46 PROGRESS_25 = 1012 # TODO hmm. not sure if progress evennts are true for books which are actually still in progress though.. PROGRESS_50 = 1013 PROGRESS_75 = 1014 # almost always occurs in pairs with T3, but not sure what is it T1020 = 1020 # 1021 seems to coincide with 'progress' T1021 = 1021 # ??? in test database T99999 = 99999 # ??? appeared on 20190701 T4 = 4 T68 = 68 # ??? from KoboShelfes db T73 = 73 # 3 of these T74 = 74 # 2 of these T27 = 27 # 3 of these T28 = 28 # 5 of these T36 = 36 # 6 of these # def dataset_connect_ro(db: Path): # support read only filesystems (also guarantees we don't change the database by accident) import sqlite3 creator = lambda: sqlite3.connect(f'file:{db}?immutable=1', uri=True) return dataset.connect('sqlite:///', engine_kwargs={'creator': creator}) # TODO use literal mypy types? def _iter_events_aux(limit=None, errors='throw') -> Iterator[Res[Event]]: # TODO handle all_ here? logger = get_logger() dbs = DATABASES if limit is not None: # pylint: disable=invalid-unary-operand-type dbs = dbs[-limit:] # TODO do it if it's defensive? books = Books(create_if_missing=True) for fname in dbs: logger.info('processing %s', fname) db = dataset_connect_ro(fname) for b, extra in _load_books(db): books.add(b) if extra is None: continue dt = extra.last_read if extra.status == 2: assert dt is not None yield FinishedEvent(dt=dt, book=b, time_spent_s=extra.time_spent, eid=f'{b.content_id}-{fname.name}') ET = EventTbl for i, row in enumerate(db.query(f'SELECT {ET.EventType}, {ET.EventCount}, {ET.LastOccurrence}, {ET.ContentID}, {ET.Checksum}, hex({ET.ExtraData}) from Event')): # TODO order by? try: yield from _iter_events_aux_Event(row=row, books=books, idx=i) except Exception as e: if errors == 'throw': raise e elif errors == 'return': yield e else: raise AssertionError(f'errors={errors}') AE = AnalyticsEvents # events_table = db.load_table('AnalyticsEvents') # TODO ugh. used to be events_table.all(), but started getting some 'Mandatory' field with a wrong schema at some point... for row in db.query(f'SELECT {AE.Id}, {AE.Timestamp}, {AE.Type}, {AE.Attributes}, {AE.Metrics} from AnalyticsEvents'): # TODO order by?? try: yield from _iter_events_aux_AnalyticsEvents(row=row, books=books) except Exception as e: if errors == 'throw': raise e elif errors == 'return': yield e else: raise AssertionError(f'errors={errors}') # TODO FIXME remove idx def _iter_events_aux_Event(*, row, books: Books, idx=0) -> Iterator[Event]: logger = get_logger() ET = EventTbl ETT = ET.Types tp, count, last, cid, checksum, extra_data = row[ET.EventType], row[ET.EventCount], row[ET.LastOccurrence], row[ET.ContentID], row[ET.Checksum], row[f'hex({ET.ExtraData})'] if tp in ( ETT.T37, ETT.T7, ETT.T9, ETT.T1020, ETT.T80, ETT.T46, ETT.T0, ETT.T1, ETT.T6, ETT.T8, ETT.T79, ETT.T1021, ETT.T99999, ETT.T4, ETT.T68, ETT.T73, ETT.T74, ETT.T27, ETT.T28, ETT.T36, ): return # TODO should assert this in 'full' mode when we rebuild from the very start... # assert book is not None book = books.by_dict({ 'volumeid': cid, }) # TODO FIXME need unique uid... # TODO def needs tests.. need to run ignored through tests as well if tp not in (ETT.T3, ETT.T1021, ETT.PROGRESS_25, ETT.PROGRESS_50, ETT.PROGRESS_75, ETT.BOOK_FINISHED): logger.error('unexpected event: %s %s', book, row) raise RuntimeError(str(row)) blob = bytearray.fromhex(extra_data) pos = 0 parsed = {} # type: Dict[bytes, Any] def context(): return f'row: {row}\nblob: {blob}\n remaining: {blob[pos:]}\n parsed: {parsed}\n xxx {blob[pos:pos+30]}\n idx: {idx}\n parts: {parts}\n pos: {pos}' def consume(fmt): nonlocal pos sz = struct.calcsize(fmt) try: res = struct.unpack_from(fmt, blob, offset=pos) except Exception as e: raise RuntimeError(context()) from e pos += sz return res lengths = { b'ExtraDataSyncedCount' : 9, b'PagesTurnedThisSession' : 9, b'IsMarkAsFinished' : 6, b'ExtraDataReadingSessions' : 9, b'ExtraDataReadingSeconds' : 9, b'ContentType' : None, # TODO weird, these contain stringified dates b'ExtraDataLastModified' : 49, b'ExtraDataDateCreated' : 49, b'ExtraDataSyncedTimeElapsed': None, # TODO eh, wordsRead is pretty weird; not sure what's the meaning. some giant blob. b'wordsRead' : 9, b'Monetization' : None, b'ViewType' : None, b'eventTimestamps' : None, b'wordCounts' : None, # TODO not so sure... these might be part of monetization b'Sideloaded' : 0, b'Paid' : 0, b'Preview' : 0, } parts, = consume('>I') # ugh. apparently can't trust parts? # for _ in range(parts): while pos < len(blob): if blob[pos:] == b'\x000': pos = len(blob) continue part_name_len, = consume('>I') if part_name_len == 0: break # sanity check... assert part_name_len < 1000, context() assert part_name_len % 2 == 0, context() fmt = f'>{part_name_len}s' prename, = consume(fmt) # looks like b'\x00P\x00a\x00g\x00e\x00s' assert prename[::2].count(0) == part_name_len // 2, context() name = prename[1::2] if name not in lengths: raise RuntimeError(f'Unexpected event kind: {name}\n' + context()) part_len = lengths[name] if part_len is not None: part_data = consume(f'>{part_len}s') elif name == b'eventTimestamps': cnt, = consume('>5xI') dts = [] for _ in range(cnt): ts, = consume('>5xI') dt = pytz.utc.localize(datetime.utcfromtimestamp(ts)) dts.append(dt) part_data = dts elif name == b'ViewType': vt_len, = consume('>5xI') vt_body, = consume(f'>{vt_len}s') part_data = vt_body elif name == b'Monetization': qqq, = consume('>5s') if qqq != b'\x00\x00\x00\n\x00': _, = consume('>4s') # no idea what's that.. continue elif name == b'ExtraDataSyncedTimeElapsed': qqq, = consume('>5s4x') # TODO wtf??? if qqq == b'\x00\x00\x00\n\x00': consume('>2x') continue elif name == b'wordCounts': vt_cnt, = consume('>5xI') vt_len = vt_cnt * 9 vt_body, = consume(f'>{vt_len}s') part_data = vt_body elif name == b'ContentType': qqq, = consume('>4s') if qqq == b'\x00\x00\x00\x00': # wtf? consume('>5x') continue vt_len, = consume('>xI') vt_body, = consume(f'>{vt_len}s') part_data = vt_body else: raise RuntimeError('Expected fixed length\n' + context()) parsed[name] = part_data assert pos == len(blob), context() # assert cnt == count # weird mismatches do happen. I guess better off trusting binary data # TODO FIXME handle remaining items timestamps = parsed.get(b'eventTimestamps', []) # type: List[datetime] for i, x in enumerate(timestamps): eid = checksum + "_" + str(i) if tp == ETT.T3: yield ProgressEvent(dt=x, book=book, eid=eid) elif tp == ETT.BOOK_FINISHED: yield FinishedEvent(dt=x, book=book, eid=eid) elif tp == ETT.PROGRESS_25: yield ProgressEvent(dt=x, book=book, prog=25, eid=eid) elif tp == ETT.PROGRESS_50: yield ProgressEvent(dt=x, book=book, prog=50, eid=eid) elif tp == ETT.PROGRESS_75: yield ProgressEvent(dt=x, book=book, prog=75, eid=eid) else: yield MiscEvent(dt=x, book=book, payload='EVENT ' + str(tp), eid=eid) def _iter_events_aux_AnalyticsEvents(*, row, books: Books) -> Iterator[Event]: logger = get_logger() AE = AnalyticsEvents eid, ts, tp, att, met = row[AE.Id], row[AE.Timestamp], row[AE.Type], row[AE.Attributes], row[AE.Metrics] ts = _parse_utcdt(ts) # TODO make dynamic? att = json.loads(att) met = json.loads(met) if tp == EventTypes.LEAVE_CONTENT: book = books.by_dict(att) prog = att.get('progress',
db_chains_ids: #colortext.warning('PDB chains: {0}\t DB chains: {1}'.format(','.join(chain_ids), ','.join(db_chains_ids))) #colortext.error('Missing chains.') new_chain_ids = sorted(set(chain_ids).difference(db_chains_ids)) for c in new_chain_ids: db_chain = get_or_create_in_transaction(tsession, PDBChain, dict( PDBFileID = database_pdb_id, Chain = c, MoleculeType = pdb_object.chain_types[c] ), missing_columns = ['WildtypeProteinID', 'FullProteinID', 'SegmentProteinID', 'WildtypeAlignedProteinID', 'AcquiredProteinID', 'Coordinates']) db_chains = {} for r in tsession.query(PDBChain).filter(PDBChain.PDBFileID == database_pdb_id): db_chains[r.Chain] = r db_chains_ids = sorted(db_chains.keys()) assert(chain_ids == db_chains_ids) for chain_id in pdb_object.chain_types.keys(): if pdb_object.chain_types[chain_id] != db_chains[chain_id].MoleculeType: db_chain = tsession.query(PDBChain).filter(and_(PDBChain.PDBFileID == database_pdb_id, PDBChain.Chain == chain_id)).one() # we expect exactly one record db_chain.MoleculeType = pdb_object.chain_types[chain_id] tsession.flush() return # todo: Extract and store the coordinates # Extract and store the coordinates for chain_id in pdb_object.atom_sequences.keys(): chain_dataframe = pdb_object.extract_xyz_matrix_from_chain(chain_id) if isinstance(chain_dataframe, NoneType): raise Exception('The coordinates dataframe could not be created for {0}, chain {1}'.format(pdb_id, chain_id)) ufname, cfname = None, None if isinstance(ppi_api.get_pdb_chain_coordinates(pdb_id, chain_id), NoneType): try: f, ufname = open_temp_file('/tmp', suffix = '.hdf5') f.close() f, cfname = open_temp_file('/tmp', suffix = '.hdf5.gz') f.close() store = pandas.HDFStore(ufname) store['dataframe'] = chain_dataframe store.close() content = read_file(ufname, binary = True) with gzip.open(cfname, 'wb') as f: f.write(content) f = open(cfname) zipped_contents = f.read() f.close() ppi_api.DDG_db.execute('UPDATE PDBChain SET Coordinates=%s WHERE PDBFileID=%s AND Chain=%s', parameters=(zipped_contents, pdb_id, chain_id)) os.remove(ufname) os.remove(cfname) except Exception, e: print('Failed to add coordinates for {0}, chain {1}'.format(pdb_id, chain_id)) if ufname: os.remove(ufname) if cfname: os.remove(cfname) print(str(e)) print(traceback.format_exc()) else: print(pdb_id + chain_id + ' has coordinates') def _add_pdb_molecules(self, tsession, database_pdb_id, pdb_object = None, allow_missing_molecules = False, chain_mapping = {}): ''' Add PDBMolecule and PDBMoleculeChain records Touched tables: PDBMolecule PDBMoleculeChain ''' assert(allow_missing_molecules == False) # todo: do we ever use allow_missing_molecules? We can inspect that case when it presents itself pdb_object = pdb_object or self.get_pdb_object(database_pdb_id, tsession = tsession) # Sanity checks for derived structures self._check_derived_record_against_rcsb_record(tsession, database_pdb_id, pdb_object, chain_mapping) if not(chain_mapping): try: molecules = pdb_object.get_molecules_and_source() except MissingRecordsException: molecules = [] for molecule in molecules: chains = molecule['Chains'] molecule['PDBFileID'] = database_pdb_id molecule['Organism'] = molecule['OrganismScientificName'] or molecule['OrganismCommonName'] md = {} for k in ['PDBFileID', 'MoleculeID', 'Name', 'Organism', 'Fragment', 'Synonym', 'Engineered', 'EC', 'Mutation', 'OtherDetails']: md[k] = molecule[k] # Add the PDBMolecule record db_molecule = get_or_create_in_transaction(tsession, PDBMolecule, md) # Add the PDBMoleculeChain records for c in chains: try: db_molecule_chain = get_or_create_in_transaction(tsession, PDBMoleculeChain, dict( PDBFileID = database_pdb_id, MoleculeID = md['MoleculeID'], Chain = c )) except: if allow_missing_molecules: pass else: raise else: # Copy the molecule information from the original RCSB structure # First, get the DB records for the derived structure and the original RCSB structure db_record = tsession.query(PDBFile).filter(PDBFile.ID == database_pdb_id).one() assert(db_record.FileSource != 'RCSB') rcsb_record = self.get_rcsb_record(db_record, tsession = tsession) # Get the list of RCSB chains rcsb_chains = chain_mapping.values() # Get the list of PDB molecules associated with chains that are in the derived PDB (accounting for chain renaming) rcsb_molecule_chains = {} # a dict mapping RCSB chain IDs to the associated PDBMoleculeChain record rcsb_molecule_ids = set() for r in tsession.query(PDBMoleculeChain).filter(PDBMoleculeChain.PDBFileID == rcsb_record.ID): if r.Chain in rcsb_chains: rcsb_molecule_chains[r.Chain] = r rcsb_molecule_ids.add(r.MoleculeID) # Add the PDBMolecule records for r in tsession.query(PDBMolecule).filter(PDBMolecule.PDBFileID == rcsb_record.ID): if r.MoleculeID in rcsb_molecule_ids: db_molecule = get_or_create_in_transaction(tsession, PDBMolecule, dict( PDBFileID = database_pdb_id, MoleculeID = r.MoleculeID, Name = r.Name, Organism = r.Organism, Fragment = r.Fragment, Synonym = r.Synonym, Engineered = r.Engineered, EC = r.EC, Mutation = r.Mutation, OtherDetails = r.OtherDetails, )) # Add the PDBMoleculeChain records for derived_chain_id, rcsb_chain_id in sorted(chain_mapping.iteritems()): associated_molecule_id = rcsb_molecule_chains[rcsb_chain_id].MoleculeID try: db_molecule_chain = get_or_create_in_transaction(tsession, PDBMoleculeChain, dict( PDBFileID = database_pdb_id, MoleculeID = associated_molecule_id, Chain = derived_chain_id )) except: if allow_missing_molecules: pass else: raise def _add_pdb_residues(self, tsession, database_pdb_id, pdb_object = None): ''' The code here is the same for both RCSB and non-RCSB structures. Touched tables: PDBResidue ''' pdb_object = pdb_object or self.get_pdb_object(database_pdb_id, tsession = tsession) residue_bfactors = pdb_object.get_B_factors().get('PerResidue') # Run DSSP over the entire structure dssp_complex_d, dssp_monomer_d = None, None try: # This fails for some PDB e.g. if they only have CA atoms dssp_complex_d = ComplexDSSP(pdb_object, read_only = True) except MissingAtomException, e: print('DSSP (complex) failed for this case: {0}.'.format(database_pdb_id)) for db_chain in tsession.query(PDBChain).filter(PDBChain.PDBFileID == database_pdb_id): print(db_chain.Chain, db_chain.MoleculeType) assert(db_chain.MoleculeType != 'Protein') # we should always pass on protein chains # Run DSSP over the individual chains try: # This fails for some PDB e.g. if they only have CA atoms dssp_monomer_d = MonomerDSSP(pdb_object, read_only = True) except MissingAtomException, e: print('DSSP (monomer) failed for this case: {0}.'.format(database_pdb_id)) for db_chain in tsession.query(PDBChain).filter(PDBChain.PDBFileID == database_pdb_id): print(db_chain.Chain, db_chain.MoleculeType) assert(db_chain.MoleculeType != 'Protein') # we should always pass on protein chains # Generate a list of residues with coordinates in the PDB file parsed_residues = set() for c, seq in pdb_object.atom_sequences.iteritems(): for s in seq: res_id, r = s parsed_residues.add(c + r.ResidueID) # Sanity checks: make sure that the residue records exist for all results of DSSP monomeric_records, complex_records = {}, {} if dssp_monomer_d: for chain_id, mapping in dssp_monomer_d: if pdb_object.chain_types[chain_id] == 'Protein' or pdb_object.chain_types[chain_id] == 'Protein skeleton': for residue_id, residue_details in sorted(mapping.iteritems()): if residue_details['3LC'] != 'UNK': # todo: should we handle these residues? chain_residue_id = chain_id + residue_id assert(chain_residue_id in parsed_residues) monomeric_records[chain_residue_id] = residue_details if dssp_complex_d: for chain_id, mapping in dssp_complex_d: if pdb_object.chain_types[chain_id] == 'Protein' or pdb_object.chain_types[chain_id] == 'Protein skeleton': for residue_id, residue_details in sorted(mapping.iteritems()): if residue_details['3LC'] != 'UNK': # todo: should we handle these residues? chain_residue_id = chain_id + residue_id assert(chain_residue_id in parsed_residues) complex_records[chain_residue_id] = residue_details # Read existing data from the database existing_residues = {} for r in tsession.query(PDBResidue).filter(PDBResidue.PDBFileID == database_pdb_id): chain_residue_id = r.Chain + r.ResidueID assert(chain_residue_id not in existing_residues) existing_residues[chain_residue_id] = r # Add PDBResidue records # dssp_monomer_d and dssp_complex_d are maps: chain -> residue_id -> DSSP record for c, seq in sorted(pdb_object.atom_sequences.iteritems()): count = 1 for s in seq: res_id, r = s assert(len(r.ResidueID) == 5) assert(c == r.Chain) chain_residue_id = c + r.ResidueID dssp_res_complex_ss, dssp_res_complex_exposure, dssp_res_monomer_ss, dssp_res_monomer_exposure = ' ', None, ' ', None monomeric_record = monomeric_records.get(chain_residue_id) if monomeric_record: dssp_res_monomer_ss = monomeric_record['ss'] dssp_res_monomer_exposure = monomeric_record['exposure'] complex_record = complex_records.get(chain_residue_id) if complex_record: dssp_res_complex_ss = complex_record['ss'] dssp_res_complex_exposure = complex_record['exposure'] average_bfactors = residue_bfactors.get(chain_residue_id, {}) existing_residue_record = existing_residues.get(chain_residue_id) if not existing_residue_record: db_residue = get_or_create_in_transaction(tsession, PDBResidue, dict( PDBFileID = database_pdb_id, Chain = c, ResidueID = r.ResidueID, ResidueAA = r.ResidueAA, ResidueType = r.residue_type, IndexWithinChain = count, CoordinatesExist = True, RecognizedByRosetta = None, BFactorMean = average_bfactors.get('mean'), BFactorDeviation = average_bfactors.get('stddev'), MonomericExposure = dssp_res_monomer_exposure, MonomericDSSP = dssp_res_monomer_ss, ComplexExposure = dssp_res_complex_exposure, ComplexDSSP = dssp_res_complex_ss, ), missing_columns = ['ID']) else: # Sanity check: make sure that the current data matches the database #print('EXISTING RESIDUE') #pprint.pprint(existing_residue_record.__dict__) if existing_residue_record.BFactorMean != None: assert(abs(float(existing_residue_record.BFactorMean) - average_bfactors.get('mean')) < 0.001) if existing_residue_record.BFactorDeviation != None: assert(abs(float(existing_residue_record.BFactorDeviation) - average_bfactors.get('stddev')) < 0.001) if existing_residue_record.MonomericExposure != None: assert(abs(float(existing_residue_record.MonomericExposure) - dssp_res_monomer_exposure) < 0.001) if existing_residue_record.MonomericDSSP != None: assert(r.ResidueAA == 'X' or (existing_residue_record.MonomericDSSP == dssp_res_monomer_ss)) if existing_residue_record.ComplexExposure != None: assert(abs(float(existing_residue_record.ComplexExposure) - dssp_res_complex_exposure) < 0.001) if existing_residue_record.ComplexDSSP != None: assert(r.ResidueAA == 'X' or (existing_residue_record.ComplexDSSP == dssp_res_complex_ss)) # Update data (add new data if is was previously missing) existing_residue_record.BFactorMean = average_bfactors.get('mean') existing_residue_record.BFactorDeviation = average_bfactors.get('stddev') existing_residue_record.MonomericExposure = dssp_res_monomer_exposure existing_residue_record.MonomericDSSP = dssp_res_monomer_ss existing_residue_record.ComplexExposure = dssp_res_complex_exposure existing_residue_record.ComplexDSSP = dssp_res_complex_ss tsession.flush() #self.ddGdb.insertDictIfNew('PDBResidue', db_res, ['PDBFileID', 'Chain', 'ResidueID']) count += 1 #print(count) def _add_pdb_rcsb_ligands(self, tsession, database_pdb_id, pdb_object = None, ligand_mapping = {}, ligand_params_file_paths = {}): '''This function associates the ligands of a PDB file (which may be arbitrarily named) with ligands entered in the database using the ligand's PDB code. The insertion is handled by a transaction which should be set up by the caller. Touched tables: PDBLigand Other Ligand tables by proxy (via add_ligand_by_pdb_code) ''' pdb_object = pdb_object or self.get_pdb_object(database_pdb_id, tsession = tsession) db_record = get_single_record_from_query(tsession.query(PDBFile).filter(PDBFile.ID == database_pdb_id)) db_ligand_ids = {} if db_record.FileSource == 'RCSB': # This structure came straight from the RCSB. We trust the ligand codes to be correct assert(not(ligand_mapping)) # Add the ligand description using data from the RCSB if they do not exist. for ligand_code in pdb_object.get_ligand_codes(): db_ligand_ids[ligand_code] = self.add_ligand_by_pdb_code(ligand_code) else: # This structure is not from the RCSB and may use non-standard ligand codes. # We therefore require a mapping from all ligand codes in the PDB to RCSB ligand codes. ligand_codes = pdb_object.get_ligand_codes() if ligand_codes: assert(ligand_mapping) # Check all
is missing from i_currents calculation", m ) if showinfo: print( "\n [soma] find_i0 Species: %s cell type: %s Temp %6.1f" % (self.status["species"], self.status["modelType"], h.celsius) ) print(" *** found V0 = %f" % v0) print(" *** and cell has mechanisms: ", self.mechanisms) return v0 def compute_rmrintau(self, auto_initialize=True, vrange=None): """ Run the model for 2 msec after initialization - then compute the inverse of the sum of the conductances to get Rin at rest compute Cm*Rin to get tau at rest Parameters ---------- auto_initialize : boolean (default: True) If true, forces initialization of cell in NEURON befor the computation. Returns ------- A dictionary containing: Rin (Mohm), tau (ms) and Vm (mV) """ gnames = { # R&M 03 and related: "nacn": "gna", "na": "gna", "jsrna": "gna", "nav11": "gna", "nacncoop": "gna", "nabu": "gna", "leak": "gbar", "klt": "gklt", "kht": "gkht", "ka": "gka", "ihvcn": "gh", "hcno": "gh", "hcnobo": "gh", # pyramidal cell specific: "napyr": "gna", "nap": "gnap", "nappyr": "gnap", "kdpyr": "gk", "kif": "gkif", "kis": "gkis", "ihpyr": "gh", "ihpyrlc": "gh", "ihpyr_adj": "gh", "kcnq": "gk", "kir": "gkir", # cartwheel cell specific: "bkpkj": "gbkpkj", "hpkj": "gh", "kpkj": "gk", "kpkj2": "gk", "kpkjslow": "gk", "kpksk": "gk", "lkpkj": "gbar", "naRsg": "gna", # SGC Ih specific: "ihsgcApical": "gh", "ihsgcBasalMiddle": "gh", } if auto_initialize: self.cell_initialize(vrange=vrange) custom_init() self.computeAreas() soma_sections = self.all_sections[self.somaname] # 1e-8*np.pi*soma.diam*soma.L # somaarea = np.sum([1e-8 * np.pi * s.L * s.diam for s in soma_sections]) self.somaarea = 0.0 # units are um2 print("soma sections: ", soma_sections) for sec in soma_sections: # print(f" segment: {i:d} area={seg.area():.3f}") print("sec: ", sec) print("self.areamethod: ", self.area_method) if self.area_method == "segment": for seg in sec.allseg(): print("seg area: ", seg.area()) self.somaarea += seg.area() elif self.area_method == "pt3d": print("sec.n3d(): ", sec.n3d()) for i in range(sec.n3d()): print("sec arc, diam: ", sec.arc3d(i), sec.diam3d(i)) self.somaarea += np.pi * sec.arc3d(i) * sec.diam3d(i) else: raise ValueError(f"Area method {self.ara_method:s} is not valid for area computations [cnmodel.cells.py]") print("self.somaarea = ", self.somaarea) # print(f'{name:s} area: {area:.3f} ') gsum = 0.0 # total condutance in us/cm2 for sec in soma_sections: u = self.get_mechs(sec) for m in u: # gx = 'section().'+m+'.'+gnames[m] gm = "%s_%s" % (gnames[m], m) gsum += getattr(sec(), gm) # eval(gx) # print('{0:>12s} : gx '.format(m)) # convert gsum from us/cm2 to nS using cell area # print ('gsum, self.somaarea: ', gsum, self.somaarea) gs = mho2ns(gsum, self.somaarea*1e-8) Rin = 1e3 / gs # convert to megohms tau = Rin*1e3 * self.totcap*1e-6 # MOhm->Ohm * uF->F, 1e3 convert to msec # print("INIT: gs: ", gs, 'nS ', self.totcap*1e-6, 'pF ', self.somaarea, 'um2 ', self.somaarea*self.c_m, 'pF') return {"Rin": Rin, "tau": tau, "v": self.soma(0.5).v} def set_soma_size_from_Cm(self, cap): """ Use soma capacitance to set the cell size. Area of the open cylinder is same as a sphere of the same diameter. Compute area and save total capacitance as well """ if self.use_morphology: return # do not do this if we are using morphology # print("Setting soma size from Cm (cap)") # assert self.use_morphology is False # do not reset values if we are using hoc file self.totcap = cap self.somaarea = self.totcap * 1e-6 / self.c_m # pf -> uF, cm = 1uf/cm^2 nominal lstd = 1e4 * ((self.somaarea / np.pi) ** 0.5) # convert from cm to um self.soma.diam = lstd self.soma.L = lstd def set_soma_size_from_Diam(self, diam): """ Use diameter to set the cell size. Area of the open cylinder is same as a sphere of the same diameter. Compute area and total capacitance as well """ if self.use_morphology: return # do not do this if we are using morphology # print("Setting soma size from Diameter",) # assert self.use_morphology is False # do not reset values if we are using hoc file self.somaarea = 1e-8 * 4.0 * np.pi * (diam / 2.0) ** 2 # in microns^2 self.totcap = self.c_m * self.somaarea * 1e6 # lstd = diam # 1E4 * ((self.somaarea / np.pi) ** 0.5) # convert from cm to um self.soma.diam = diam self.soma.L = diam def set_soma_size_from_soma_Sections(self, repeat=False): """ Set the soma total cap and area from the seg/section measures Note that we find our own soma sections here... Parameters repeat : bool (default: False) Allow this to be called repeatedly when adjusting areas. Otherwise, we only allow this to be called ONCE per cell """ #print("Setting soma size from soma section(s) (morphology)") self.somaarea = 0. for secname in self.all_sections: # keys for names of section types s = self.all_sections[secname] # get all the sections with that name if secname == self.somaname: for sec in s: self.somaarea += self.segareasec(sec=sec) self.totcap = self.c_m * self.somaarea * 1e-8 # in uF # print(f"Original soma area: {self.somaarea:9.3f} Cap: {self.totcap:.4e}") self.nsets += 1 if not repeat: if self.nsets > 1: raise ValueError() def print_soma_info(self, indent=0): print("-" * (40+indent)) indents = " "*indent print(f"{indents:s}Soma Parameters: (from cnmodel.cell)") print(f"{indents:s} Area: {self.somaarea:9.2f} um^2") print(f"{indents:s} Cap: {self.totcap*1e6:9.2f} pF") print(f"{indents:s} L: {self.soma.L:9.2f} um") print(f"{indents:s} diam: {self.soma.diam:9.2f} um") print(f"{indents:s} c_m: {self.c_m:9.2f} uF/cm^2") print("-" * (40*indent)) # soma_sections = self.all_sections[self.somaname] # somaarea = np.sum([ np.pi * s.L * s.diam for s in soma_sections]) # print("Soma area by summing cylinders: ", somaarea, " of ", len(soma_sections), "sections") def distances(self, section=None): self.distanceMap = {} if self.hr is None: return if section is None: # print(self.soma.name()) self.hr.h("access %s" % self.soma.name()) # reference point else: self.hr.h("access %s" % section.name()) d = self.hr.h.distance() for sec in self.all_sections: s = self.all_sections[sec] if len(s) > 0: for u in s: self.hr.h("access %s" % u.name()) self.distanceMap[u.name()] = ( self.hr.h.distance(0.5) - d ) # should be distance from first point def segareasec(self, sec: object): """ Sum up the areas of all the _segments_ in a section """ area = 0 for i, seg in enumerate(sec.allseg()): # print(f" segment: {i:d} area={seg.area():.3f}") area += seg.area() # print(f'{name:s} area: {area:.3f} ') return area def secareasec(self, sec: object) -> float: """ compute area using built-in neuron area function """ area = h.area(0.5, sec=sec) return area def pt3dareasec(self, sec: object) -> float: """ Sum up the areas of all the pt3d pieces in a section """ area = 0 for i in range(sec.n3d()): area += np.pi * sec.arc3d(i) * sec.diam3d(i) return area def computeAreas(self, source:str='seg'): """ Compute the surface area for all sections 3 ways to compute: 'sec': use the area of the middle of the section (ok if not pt3d data) 'seg': sum up area of segments 'pt3d': use authorative pt3d data """ assert source in ['pt3d', 'sec', 'seg'] self.areaMap = {} if source == 'seg': method = self.segareasec elif source == 'pt3d': method = self.pt3dareasec elif source == "sec": method = self.secareasec for secname in self.all_sections: # keys for names of section types s = self.all_sections[secname] # get all the sections with that name if secname not in list(self.areaMap.keys()): self.areaMap[secname] = {} for n, u in enumerate(s): # aseg = h.area(0.5, sec=u) # self.areaMap[secname][u] = aseg# np.pi*u.diam*u.L # The following verifies that the area summed by segment and by the h.area call # are infact the same self.areaMap[secname][u] = method(sec=u) # np.pi*u.diam*u.L # if self.areaMap[secname][u] != aseg: # print(f"Areas differ: areaMap: {self.areaMap[secname][u]:8.3f} vs. h.area(0.5): {aseg:8.3f} vs section: {np.pi*u.diam*u.L:8.3f}") # assert self.areaMap[secname][u] == aseg else: pass # for s in self.areaMap: # print(f"{s:>24s} : {np.sum([self.areaMap[s][x] for x in self.areaMap[s]]):>9.3f} ({len(self.areaMap[s]):>4d} sections)") def add_axon( self, c_m=1.0, R_a=150, axonsf=1.0, nodes=5, debug=False, internodeDiameter=None, internodeLength=None, nodeDiameter=None, nodeLength=None, seg=None, internodeELeak=-65, nodeELeak=-65, natype="nacn", ): """ Add an axon to the soma with an initial segment (tapered), and multiple nodes of Ranvier The size of the axon is determined by self.axonsf, which in turn is set by the species The somaarea is used to scale the density of ion channels in the initial segment """ nnodes = range(nodes) axnode = [] internode = [] initsegment = h.Section() initsegment.connect(self.soma) for i in nnodes: axnode.append(h.Section()) if i < nodes - 1: internode.append(h.Section()) axnode[0].connect(initsegment) for i in nnodes: if i <
<filename>wildlifecompliance/utils/excel_utils.py from __future__ import unicode_literals from django.conf import settings from collections import OrderedDict from wildlifecompliance.components.applications.models import Application, ApplicationType, ExcelApplication, ExcelActivityType from wildlifecompliance.components.licences.models import DefaultActivityType, WildlifeLicence, WildlifeLicenceClass, WildlifeLicenceActivity from wildlifecompliance.components.organisations.models import Organisation from ledger.accounts.models import OrganisationAddress from django.contrib.postgres.fields.jsonb import JSONField from wildlifecompliance.utils import SearchUtils, search_multiple_keys from wildlifecompliance.components.licences.models import DefaultActivity from ledger.accounts.models import EmailUser import xlsxwriter from xlsxwriter.utility import xl_rowcol_to_cell, xl_cell_to_rowcol, xl_col_to_name import xlrd#, xlwt import openpyxl from openpyxl.styles import Protection import os import re import shutil import logging logger = logging.getLogger(__name__) import json from datetime import datetime from django.db import models APP_SHEET_NAME = 'Applications' META_SHEET_NAME = 'Meta' SYSTEM = 'System' FIRST_COL = 'First Col' LAST_COL = 'Last Col' NSYS_COLS = 6 # number of system columns (cols --> 0 to 5) LODGEMENT_NUMBER = 'lodgement_number' APPLICATION_ID = 'application_id' LICENCE_NUMBER = 'licence_number' APPLICANT = 'applicant' APPLICANT_TYPE = 'applicant_type' APPLICANT_ID = 'applicant_id' PURPOSE = 'purpose' ADDITIONAL_INFO = 'additional_info' STANDARD_ADVANCED = 'standard_advanced' COVER_PROCESSED = 'cover_processed' COVER_PROCESSED_DATE = 'cover_processed_date' COVER_PROCESSED_BY = 'cover_processed_by' CONDITIONS = 'conditions' ISSUE_DATE = 'issue_date' START_DATE = 'start_date' EXPIRY_DATE = 'expiry_date' TO_BE_ISSUED = 'to_be_issued' PROCESSED = 'processed' APPLICANT_TYPE_ORGANISATION = 'ORG' APPLICANT_TYPE_PROXY = 'PRX' APPLICANT_TYPE_SUBMITTER = 'SUB' class ExcelWriter(): def __init__(self): self.cur_datetime = datetime.now() if not ExcelApplication.objects.exists(): # hack to allow templates to run when no ExcelApplication exists yet - need the System header columns from the excel_app object (cols_output) app = Application.objects.all().last() self.create_excel_model(app.licence_category, use_id=app.id) def update_workbooks(self): for licence_category in WildlifeLicenceClass.objects.all(): filename = '{}.xlsx'.format(self.replace_special_chars(licence_category.short_name)) self.archive_workbook(filename) self.read_workbook(settings.EXCEL_OUTPUT_PATH + '/' + filename, licence_category.short_name) logger.info('Completed: ' + licence_category.short_name + ' - ' + settings.EXCEL_OUTPUT_PATH + '/' + filename) def archive_workbook(self, filename): src_file = settings.EXCEL_OUTPUT_PATH + '/' + filename if os.path.isfile(src_file): archive_dir = '{}/archive/{}'.format(settings.EXCEL_OUTPUT_PATH, self.cur_datetime.strftime('%Y%m%dT%H%M%S')) dest_file = archive_dir + '/' + filename if not os.path.exists(archive_dir): os.makedirs(archive_dir) shutil.copyfile(src_file, dest_file) def set_formats(self, workbook): self.bold = workbook.add_format({'bold': True}) self.bold_unlocked = workbook.add_format({'bold': True, 'locked': False}) self.unlocked = workbook.add_format({'locked': False}) self.locked = workbook.add_format({'locked': True}) self.wrap = workbook.add_format({'text_wrap': True}) self.unlocked_wrap = workbook.add_format({'text_wrap': True, 'locked': False}) self.integer = workbook.add_format({'num_format': '0', 'align': 'center'}) def replace_special_chars(self, input_str, new_char='_'): return re.sub('[^A-Za-z0-9]+', new_char, input_str).strip('_').lower() def get_purposes(self, licence_class_short_name): """ activity_type --> purpose for licence_class in DefaultActivityType.objects.filter(licence_class_id=13): #print '{} {}'.format(licence_class.licence_class.id, licence_class.licence_class.name) for activity_type in DefaultActivity.objects.filter(activity_type_id=licence_class.activity_type_id): print ' {}'.format(activity_type.activity.name, activity_type.activity.short_name) ____________________ DefaultActivityType.objects.filter(licence_class__short_name='Flora Other Purpose').values_list('licence_class__activity_type__activity__name', flat=True).distinct() """ activity_type = DefaultActivityType.objects.filter(licence_class__short_name=licence_class_short_name).order_by('licence_class__activity_type__activity__name') return activity_type.values_list('licence_class__activity_type__activity__name', flat=True).distinct() def get_licence_type(self, activity_type_name): """ activity_type name -- purpose name--> 'Importing Fauna (Non-Commercial)' """ return DefaultActivityType.objects.filter(licence_class__activity_type__activity__name=activity_type_name).distinct('licence_class')[0].licence_class.name def get_index(self, values_list, name): indices = [i for i, s in enumerate(values_list) if name in s] return indices[0] if indices else None def get_activity_type_sys_questions(self, activity_name): """ Looks up the activity type schema and return all questions (marked isEditable) that need to be added to the Excel WB. Allows us to know the block size for each activity type in the WB (start_col, end_col) """ ordered_dict=OrderedDict([]) schema = WildlifeLicenceActivity.objects.get(name=activity_name).schema res = search_multiple_keys(schema, 'isEditable', ['name', 'label']) [ordered_dict.update([(i['name'],i['label'])]) for i in res] return ordered_dict def get_tab_index(self, qs_activity_type): application = qs_activity_type[0].application activity_name = qs_activity_type[0].name # 'Fauna Other - Importing' return application.data[0][activity_name][0].keys()[0].split('_')[1] def get_activity_type_sys_answers(self, qs_activity_type, activity_name): """ Looks up the activity type return all answers for question marked isEditable that need to be added to the Excel WB. """ ordered_dict=OrderedDict([]) questions = self.get_activity_type_sys_questions(activity_name) for k,v in questions.iteritems(): # k - section name # v - question if qs_activity_type: # must append tab index to 'section name' k = k + '_' + self.get_tab_index(qs_activity_type) #, activity_name) s = SearchUtils(qs_activity_type[0].application) answer = s.search_value(k) #ordered_dict.update(OrderedDict([(v,answer)])) ordered_dict.update(OrderedDict([(k,answer)])) else: # this part for the Excel column headers #ordered_dict.update(OrderedDict([(v,None)])) ordered_dict.update(OrderedDict([(k,None)])) return ordered_dict def create_excel_model(self, licence_category, cur_app_ids=[], use_id=None): """ from wildlifecompliance.utils.excel_utils import write_excel_model write_excel_model('Fauna Other Purpose') """ if use_id: # get a filterset with single application applications = Application.objects.filter(id=Application.objects.all().last().id) else: applications = Application.objects.filter(licence_category=licence_category).exclude(processing_status=Application.PROCESSING_STATUS_DRAFT[0]).exclude(id__in=cur_app_ids) new_excel_apps = [] for application in applications.order_by('id'): excel_app, created = ExcelApplication.objects.get_or_create(application=application) new_excel_apps.append(excel_app) activities = self.get_purposes(application.licence_type_data['short_name']).values_list('activity_type__short_name', flat=True) for activity_type in application.licence_type_data['activity_type']: if activity_type['short_name'] in list(activities): excel_activity_type, created = ExcelActivityType.objects.get_or_create( excel_app=excel_app, activity_name=activity_type['activity'][0]['name'], name=activity_type['name'], short_name=activity_type['short_name'] ) return new_excel_apps def create_workbook_template(self, filename, licence_category='Fauna Other Purpose'): """ Creates a blank template with purposes and column headings only """ meta = OrderedDict() if os.path.isfile(filename): logger.warn('File already exists {}'.format(filename)) return None wb = xlsxwriter.Workbook(filename) ws = wb.add_worksheet(APP_SHEET_NAME) self.set_formats(wb) row_num = 0 col_num = 0 cell_dict = {} cell_start = xl_rowcol_to_cell(row_num, col_num, row_abs=True, col_abs=True) sys_cols = ExcelApplication.objects.all().last().cols_output.keys() for col_name in sys_cols: ws.write(row_num, col_num, col_name, self.bold_unlocked) col_num += 1 cell_end = xl_rowcol_to_cell(row_num, col_num-1, row_abs=True, col_abs=True) cell_dict.update({SYSTEM: [cell_start, cell_end]}) activity_name_list = self.get_purposes(licence_category) for activity_name in activity_name_list: #cols = self.cols_output(None, 'Importing Fauna (Non-Commercial)') activity_type_cols = self.cols_output(None, activity_name).keys() ws.write(row_num, col_num, '', self.bold); col_num += 1 cell_start = xl_rowcol_to_cell(row_num, col_num, row_abs=True, col_abs=True) for col_name in activity_type_cols: ws.write(row_num, col_num, col_name, self.bold_unlocked) col_num += 1 cell_end = xl_rowcol_to_cell(row_num, col_num-1, row_abs=True, col_abs=True) cell_dict.update({activity_name: [cell_start, cell_end]}) self.write_sheet_meta(wb, cell_dict, activity_name_list) wb.close() def read_workbook(self, input_filename, licence_category='Fauna Other Purpose'): """ Read the contents of input_filename, create licences if to_be_processed='Y' and append new applications to the workbook """ meta = OrderedDict() if not os.path.isfile(input_filename): logger.warn('Cannot find file {}. Creating ...'.format(input_filename)) self.create_workbook_template(input_filename, licence_category) wb = xlrd.open_workbook(input_filename) sh = wb.sheet_by_name(APP_SHEET_NAME) sh_meta = wb.sheet_by_name(META_SHEET_NAME) # Read Meta number_of_rows = sh_meta.nrows hdr = sh_meta.row_values(0) for row in range(1, number_of_rows): row_values = sh_meta.row_values(row) purpose = row_values[0] meta.update([(purpose, {})]) for i in zip(hdr, row_values)[1:]: meta[purpose].update( {i[0]: i[1]} ) # Read Application Data excel_data = {} number_of_rows = sh.nrows hdr = sh.row_values(0) for row in range(1, number_of_rows): row_values = sh.row_values(row) lodgement_number = row_values[hdr.index(LODGEMENT_NUMBER)] application_id = int(row_values[hdr.index(APPLICATION_ID)]) licence_number = row_values[hdr.index(LICENCE_NUMBER)] applicant = row_values[hdr.index(APPLICANT)] applicant_type = row_values[hdr.index(APPLICANT_TYPE)] applicant_id = int(row_values[hdr.index(APPLICANT_ID)]) application = Application.objects.get(lodgement_number=lodgement_number) for purpose in meta.keys(): if purpose != SYSTEM: try: idx_start = int(meta[purpose][FIRST_COL]) idx_end = int(meta[purpose][LAST_COL]) purpose_row = row_values[idx_start:idx_end] hdr_row = hdr[idx_start:idx_end] idx_to_be_issued = self.get_index(hdr_row, TO_BE_ISSUED) to_be_issued = purpose_row[idx_to_be_issued] if to_be_issued in ['y', 'Y'] and not licence_number: # create licence, if not already created # check if user already has a licence. if so, re-use licence_number and update the licence_sequence if application.licences.all().count() > 0: licence_number = application.licences.all().first().reference else: licence_number = self.create_licence(application, purpose, licence_category, applicant_type, applicant_id).reference row_values[hdr.index(LICENCE_NUMBER)] = licence_number except ValueError, e: logger.error('Cannot find activity_type {} in Excel header./n{}'.format(purpose, e)) # except Exception, e: # import ipdb; ipdb.set_trace() excel_data.update({lodgement_number: row_values}) #wb.release_resources() #del wb # Re-output Application Data with licence_numbers #wb = xlsxwriter.Workbook(input_filename) #self.set_formats(wb_out) #ws_out = wb_out.add_worksheet(APP_SHEET_NAME) #ws = wb.get_worksheet_by_name(APP_SHEET_NAME) #sh_meta = wb.sheet_by_name(META_SHEET_NAME) wb = openpyxl.load_workbook(input_filename) ws = wb.get_sheet_by_name(APP_SHEET_NAME) ws.protection.sheet = True row_num = 0 col_num = 0 #ws.write_row(row_num, col_num, hdr, self.bold); row_num += 1 #import ipdb; ipdb.set_trace() self.write_row(row_num, col_num, hdr, ws, is_header=True); row_num += 1 for k,v in excel_data.iteritems(): #ws.write_row(row_num, col_num, v) self.write_row(row_num, col_num, v, ws) row_num += 1 # Append new applications to output #cur_app_ids = [int(v[1]) for k,v in excel_data.iteritems()] # existing app id's #new_app_ids = Application.objects.exclude(processing_status='draft').exclude(id__in=cur_app_ids) self.write_new_app_data(excel_data, meta, licence_category, ws, row_num) #wb_out.close() try: wb.save(input_filename) except IOError, e: raise Exception("Cannot write to file {}. File is already open. Please close the file first".format(input_filename)) def write_row(self, row_num, col_num, values, worksheet, is_header=False): # openpyxl helper function """ Openpyxl helper function. Writes values as a row of data. If values is a single value, writes to a single cell """ if not isinstance(values, list): values = [values] if values else [''] for col, val in enumerate(values, start=col_num): cell = worksheet.cell(row=row_num+1, column=col+1, value=val) # openpyxl count rows and cols from 1 if not is_header and col > NSYS_COLS: # don't protect data cells cell.protection = Protection(locked=False) else: cell.protection = Protection(locked=True) def write_new_app_data(self, excel_data, meta, licence_category, worksheet, next_row): cur_app_ids = [int(v[1]) for k,v in excel_data.iteritems()] # existing app id's new_excel_apps = self.create_excel_model(licence_category, cur_app_ids=cur_app_ids) row_num = next_row for excel_app in new_excel_apps: # System data col_num = int(meta[SYSTEM][FIRST_COL]) for k,v in excel_app.cols_output.iteritems(): #worksheet.write(row_num, col_num, v, self.locked) self.write_row(row_num, col_num, v, worksheet) col_num += 1 # Application data for purpose in meta.keys(): if purpose != SYSTEM: activity_type = excel_app.excel_activity_types.filter(activity_name=purpose) activity_type_cols = self.cols_output(activity_type, purpose) col_num = int(meta[purpose][FIRST_COL])# + 1 if activity_type.exists(): for k,v in activity_type_cols.iteritems(): #ws.write('B1', 'Here is\nsome long text\nthat\nwe wrap', wrap) #worksheet.write(row_num, col_num, v, self.unlocked_wrap) self.write_row(row_num, col_num, v, worksheet) col_num += 1 else: # create a blank activity_type bilock for _ in activity_type_cols.keys(): #worksheet.write(row_num, col_num, '', self.unlocked) self.write_row(row_num, col_num, '', worksheet) col_num += 1 row_num += 1 # def cols_system(self, qs_activity_type, activity_name): # """ qs_excel_app --> ExcelApplication """ # return OrderedDict([ # ('lodgement_number', qs_activity_type[0].excel_app.lodgement_number if qs_activity_type else None), # ('application_id', qs_activity_type[0].excel_app.application.id if qs_activity_type else None), # ('licence_number', qs_activity_type[0].excel_app.licence_number if qs_activity_type else None), # ('applicant', qs_activity_type[0].excel_app.applicant_details if qs_activity_type else None), # ('applicant_type', qs_activity_type[0].excel_app.applicant_type if qs_activity_type else None), # ('applicant_id', qs_activity_type[0].excel_app.applicant_id if qs_activity_type else None), #
# 0x8d Mask for rockers/buttons present in variant ('transmission_options', c_uint8), # 0x8e Transmission options ('variant_options', c_uint8), # 0x8f variant ('misc_options', c_uint8), # 0x90 state report, add/del facility, et. ('button_transmit_options', c_uint8), # 0x91 mask for what transmits ('output_options', c_uint8), # 0x92 # dimmers ('reserved2', c_char * 3), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids_1', c_uint8 * 8), ('preset_level_table_1', c_uint8 * 8), ('preset_fade_table_1', c_uint8 * 8), ('link_ids_2', c_uint8 * 8), ('preset_level_table_2', c_uint8 * 8), ('preset_fade_table_2', c_uint8 * 8), ('link_ids_3', c_uint8 * 8), ('preset_level_table_3', c_uint8 * 8), ('preset_fade_table_3', c_uint8 * 8), ('link_ids_4', c_uint8 * 8), ('preset_level_table_4', c_uint8 * 8), ('preset_fade_table_4', c_uint8 * 8), ('reserved3', c_char * 10) ] # SA US22 class UPBUS22(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('reserved1', c_char * 32), ('rockers', RockerAction * 4), ('dim_options_1', c_uint8), # 0x88 ('dim_options_2', c_uint8), # 0x89 ('reserved2', c_char * 2), # 0x8a - 0x8b ('led_options', c_uint8), # 0x8c LED Control ('button_config', c_uint8), # 0x8d Mask for rockers/buttons present in variant ('transmission_options', c_uint8), # 0x8e Transmission options ('variant_options', c_uint8), # 0x8f variant, add/del facility, long body bit ('misc_options', c_uint8), # 0x90 state report ('button_transmit_options', c_uint8), # 0x91 mask for what transmits ('output_options', c_uint8), # 0x92 # dimmers. Always 2 ('reserved3', c_char * 3), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids_1', c_uint8 * 16), ('preset_level_table_1', c_uint8 * 16), ('preset_fade_table_1', c_uint8 * 16), ('link_ids_2', c_uint8 * 16), ('preset_level_table_2', c_uint8 * 16), ('preset_fade_table_2', c_uint8 * 16), ('reserved4', c_char * 10) ] # SA US2-40 class UPBUS2(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('link_ids', c_uint8 * 16), ('preset_level_table', c_uint8 * 16), ('preset_fade_table', c_uint8 * 16), ('reserved1', c_char * 26), ('rocker_transmit_options', c_uint8), # 0x8a ('led_options', c_uint8), # 0x8b LED Control ('rocker_config', c_uint8), # 0x8c ('dim_options', c_uint8), # 0x8d ('transmission_options', c_uint8), # 0x8e Transmission options ('rocker_options', c_uint8), # 0x8f rocker options and variant ('rocker_action', RockerAction * 4), ('reserved2', c_char * 72) ] # SA UFQ20 class UPBUFQ(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('button_action_table', UPBButtonAction * 4), ('reserved1', c_char * 55), ('led_options', c_uint8), # 0x8b LED Control ('reserved2', c_char * 2), ('transmission_options', c_uint8), # 0x8e Transmission options ('reserved3', c_char), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids_1', c_uint8 * 8), ('preset_level_table_1', c_uint8 * 8), ('preset_fade_table_1', c_uint8 * 8), ('link_ids_2', c_uint8 * 8), ('preset_level_table_2', c_uint8 * 8), ('preset_fade_table_2', c_uint8 * 8), ('link_ids_3', c_uint8 * 8), ('preset_level_table_3', c_uint8 * 8), ('preset_fade_table_3', c_uint8 * 8), ('link_ids_4', c_uint8 * 8), ('preset_level_table_4', c_uint8 * 8), ('preset_fade_table_4', c_uint8 * 8), ('reserved4', c_char * 2), ('timeout_enables', c_uint8), # 0xf2 ('timeout_1', c_uint8), ('timeout_2', c_uint8), ('timeout_3', c_uint8), ('timeout_4', c_uint8), ('variant_options', c_uint8), ('reserved5', c_char * 8) ] class IOMInput(BigEndianStructure): _pack_ = 1 _fields_ = [ ('close_link_id', c_uint8), ('close_cmd', c_uint8), ('close_b1', c_uint8), ('close_b2', c_uint8), ('open_link_id', c_uint8), ('open_cmd', c_uint8), ('open_b1', c_uint8), ('open_b2', c_uint8) ] # WMT 3 input and 2 output module class UPBIOM(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids_1', c_uint8 * 16), ('state_1', c_uint8 * 16), # 0: open 1: closed ('unused_1', c_uint8 * 16), ('link_ids_2', c_uint8 * 16), ('state_2', c_uint8 * 16), ('unused_2', c_uint8 * 16), ('input', IOMInput * 3), ('reserved1', c_char * 8), ('transmission_options', c_uint8), # 0xc0 Transmission options ('led_options', c_uint8), # 0xc1 LED Control ('reserved2', c_char), # 0xc2 ('device_options', c_uint8), # 0xc3 ('reserved3', c_char * 60) ] # Fixture relay class UPBFR(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids', c_uint8 * 16), # 0x40 ('preset_level_table', c_uint8 * 16), # 0x50 ('preset_fade_table', c_uint8 * 16), # 0x60 ('rocker', RockerAction), # 0x70 ('top_rocker_sc_level', c_uint8), # 0x7aI'll come by 4:00 + ('top_rocker_sc_rate', c_uint8), ('top_rocker_dc_level', c_uint8), ('top_rocker_dc_rate', c_uint8), ('bottom_rocker_sc_level', c_uint8), ('bottom_rocker_sc_rate', c_uint8), ('bottom_rocker_dc_level', c_uint8), ('bottom_rocker_dc_rate', c_uint8), ('reserved1', c_char * 8), ('tap_options', c_uint8), # 0x8a ('led_options', c_uint8), # 0x8b LED Control ('reserved2', c_char), # 0x8c ('output_options', c_uint8), # 0x8d Options ('transmission_options', c_uint8), # 0x8e Transmission options ('rocker_options', c_uint8), # 0x8f flags and variant ('reserved3', c_char * 112) ] # SA USM class UPBUSM(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('rocker1', RockerAction), ('rocker2', RockerAction), ('reserved1', c_char * 46), ('calib_0', c_uint8), # 0x82 ('calib_1', c_uint8), # 0x83 ('calib_2', c_uint8), # 0x84 ('calib_3', c_uint8), # 0x85 ('reserved2', c_char * 4), # USMR1 # <= 1.07 # 0x8c: byte1 rockerOptions # 0x8d: byte2 transmissionOptions # 0x8e: byte3 reserved # # >= 1.08 (or USM2) # 0x8c: byte1 reserved # 0x8d: byte2 rockerOptions # 0x8e: byte3 transmissionOptions ('rocker_transmit', c_uint8), # 0x8a ('led_options', c_uint8), # 0x8b LED Control ('byte_1', c_uint8), # 0x8c ('byte_2', c_uint8), # 0x8d ('byte_3', c_uint8), # 0x8e ('calib_scale', c_uint8), # 0x8f # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_ids_1', c_uint8 * 8), ('preset_level_table_1', c_uint8 * 8), ('preset_fade_table_1', c_uint8 * 8), ('link_ids_2', c_uint8 * 8), ('preset_level_table_2', c_uint8 * 8), ('preset_fade_table_2', c_uint8 * 8), ('reserved4', c_char * 64) ] class DSTDate(BigEndianStructure): _pack_ = 1 _fields_ = [ ('start_month', c_uint8), ('start_day', c_uint8), ('end_month', c_uint8), ('end_day', c_uint8) ] class TECFlash(BigEndianStructure): _pack_ = 1 _fields_ = [ ('clock', c_uint8 * 8), # 0x100 ('jan_1_sunrise_hours', c_uint8), # 0x108 ('jan_1_sunrise_minutes', c_uint8), ('jan_1_sunset_hours', c_uint8), # 0x10a ('jan_1_sunset_minutes', c_uint8), ('dst_start_month', c_uint8), # 0x10c Current year ('dst_start_day', c_uint8), ('dst_stop_month', c_uint8), # 0x10e ('dst_stop_day', c_uint8), ('suntime_table', c_uint8 * 366), # 0x110 ('dst_table', DSTDate * 30) # 0x300 [0] = 2006 ] class TimedEvent(BigEndianStructure): _pack_ = 1 _fields_ = [ ('time1', c_uint8), ('time2', c_uint8), ('minute', c_uint8), ('vary', c_uint8), ('transmit_link', c_uint8), ('transmit_cmd', c_uint8), ('receive_link', c_uint8), ('receive_level', c_uint8) ] # TEC class UPBTEC(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('led_options', c_uint8), # 0x40 LED Control ('transmission_options', c_uint8), # 0x41 Transmission options ('reserved1', c_char * 5), ('ct_events_in_use', c_uint8), ('event_table', TimedEvent * 20), ('reserved2', c_char * 24) ] class ESIComponent(BigEndianStructure): _pack_ = 1 _fields_ = [ ('link_id', c_uint8), ('cm_msg', c_uint8), ('msg', c_uint8 * 7) ] # ESI class UPBESI(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('rct', ESIComponent * 16), ('reserved1', c_char * 16), ('transmission_options', c_uint8), # 0xe0 Transmission options ('led_options', c_uint8), # 0xe1 LED Control ('reserved2', c_char * 30) ] # Alarm Panel Interface (API) class UPBAPI(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), ('house_code_map', c_uint8 * 16), ('command_map', c_uint8 * 16), ('reserved1', c_char * 46), ('transmission_options', c_uint8), # 0x8e Transmission options ('reserved2', c_char * 113) ] # PCS RFI class UPBRFI(BigEndianStructure, Dictionary): _pack_ = 1 _anonymous_ = ('upbid',) _fields_ = [ ('upbid', UPBID), # Not stored in this manner but as triplets. Does take up # the same number of bytes ('link_id', c_uint8 * 32), ('scdc', c_uint8 * 32), ('hold_release', c_uint8 * 32), ('remote_type', c_uint8 * 32), # A1 to A7 ('name_update', c_uint8), # A8 ('reserved1', c_char * 2), ('led_options', c_uint8), # 0xab LED Control ('reserved2', c_char * 2), ('transmission_options', c_uint8), # 0xae ('reserved3', c_char * 49), ('remote_1_id', c_uint8 * 4), ('remote_2_id', c_uint8 * 4), ('remote_3_id', c_uint8 * 4), ('remote_4_id', c_uint8 * 4), ('remote_5_id', c_uint8 * 4), ('remote_6_id', c_uint8 * 4), ('remote_7_id', c_uint8 * 4), ('remote_8_id', c_uint8 * 4) ] def get_register_map(product): if product in UPBKindSwitch: return UPBSwitch elif product in UPBKindModule1: return UPBModule elif product in UPBKindModule2: return UPBModule2 elif product in UPBKindKeypad: return UPBKeypad elif product in UPBKindKeypadDimmer: return UPBKeypadDimmer elif product in UPBKindInput: return UPBICM elif product in UPBKindUSQ: return UPBUSQ elif product in UPBKindUS4: return UPBUS4 elif product in UPBKindUS22: return UPBUS22 elif product in UPBKindUS2: return UPBUS2 elif product in UPBKindUFQ: return UPBUFQ elif product in UPBKindIOM: return UPBIOM elif product in UPBKindFR: return UPBFR elif product
#! /usr/bin/env python """Python Functions for CellRanger BCL->Fastq->SCP Pipeline Arguments: -c command to be run: count: -id, --sampleId Id of sample being run -cf, --commaFastqs Comma seperated String with list of fastq directories -fs, --fastqs List of fastq directories -E, --expectCells Number of cells to expect -F --forceCells Force number of cells -C, --chemistry Chemistry of fastqs -S, --secondary Run cellranger secondary analysis -tf, --transcriptome Transcriptome file -dfc, --doForceCells Boolean to use force cells mkfastq: -b, --bcl Location of bcl -M, --masterCsv Master Csv file containing maps of information -O, --output_directory List of fastq directories parse: -M, --masterCsv Master Csv file containing maps of information analysis: -M, --masterCsv Master Csv file containing maps of information -hs, --h5s H5 output files filter: -M, --masterCsv Master Csv file containing maps of information -p, --paths Paths to fastq directories -S, --sampleIds help='List of sample names -t, --transMap CSV map of reference names to gsurls """ # Imports import os from subprocess import call import xml.etree.ElementTree as ET import pandas as pd from subprocess import run from subprocess import check_output import sys import argparse def cellranger_count(sample_id, transcriptome, comma_fastqs='',fastqs='', expect_cells='', force_cells='', secondary='false', chemistry='threeprime', do_force_cells = ''): """Run Cell Ranger count on directory (s) of fastqs. Arguments: sample_id- name of sample transcriptome- path of transcriptome file comma_fastqs- comma seperated string of fastq directory gsurls fastqs- wdl formatted array of fastqs secondary- CellRanger count argument, run Cell Ranger built in analysis expect_cells- CellRanger count argument force_cells- CellRanger count argument do_force_cells- pass force cells to CellRanger? chemistry- CellRanger count argument Outputs- CellRanger Count Files { barcodes genes matrix qc report sorted_bam sorted_bam_index filtered_gene_h5 raw_gene_h5 raw_barcodes raw_genes raw_matrix mol_info_h5 cloupe } """ # download the transcriptome file to directory os.mkdir('transcriptome_dir') call(['tar', 'xf', transcriptome, '-C', 'transcriptome_dir', '--strip-components', '1']) # create a unique list (set) of fastq directories and download them dirs = set() if comma_fastqs is not '': fastqs = comma_fastqs.split(',') for i, fastq in enumerate(fastqs): # download the fastqs to a unique location and add that location to set os.mkdir(str(i)) call(['gsutil', '-q', '-m', 'cp', '-r', fastq, str(i)]) os.path.join(str(i), sample_id, '') dirs.add(os.path.join(str(i), sample_id, '')) # create the cellranger count command and execute it call_args = list() call_args.append('cellranger') call_args.append('count') call_args.append('--jobmode=local') call_args.append('--transcriptome=transcriptome_dir') call_args.append('--sample=' + sample_id) call_args.append('--id=results_' + sample_id) call_args.append('--fastqs=' + ','.join(dirs)) if secondary is not 'true': call_args.append('--nosecondary') if (force_cells is not '') and (do_force_cells is 'true'): call_args.append('--force-cells=' + str(force_cells)) elif expect_cells is not '': call_args.append('--expect-cells=' + str(expect_cells)) if chemistry is not '': call_args.append('--chemistry=' + chemistry) call(call_args) def cellranger_mkfastq(bcl, master_csv, output_directory, samples_csv = 'sample.csv'): """Run Cell Ranger mkfastq on a single BCL. Arguments: bcl- gsurl of bcl directory masterCsv- Csv File mapping samples, lanes and indices to bcl output_directory- gsurl path where fastqs will be outputted too Outputs- path.txt- fastq output gsurl undetermined.txt- undetermined fastq gsurl """ # copy the BCL over call(['gsutil', '-q', '-m', 'cp', '-r', bcl, '.']) # Create local fastq output directory os.mkdir('fastqs') # get the name of the flowcell, need this to know fastq output directory name path = bcl run = list(filter(None, path.split('/')))[-1] # get flowcell tree = ET.parse(os.path.join(run, 'RunInfo.xml')) root = tree.getroot() flowcell = root.find('Run').find('Flowcell').text # create the sample lane index csv df = pd.read_csv(master_csv, header=0) df = df.loc[df['Flowcell'] == path] df = df[['Lane','Sample', 'Index']] df.to_csv(samples_csv, index=False) # run mkfastq command call_args = list() call_args.append('cellranger') call_args.append('mkfastq') call_args.append('--run=' + os.path.join(run,'')) call_args.append('--csv=' + samples_csv) call_args.append('--output-dir=fastqs') call(call_args) # move the fastqs to the output directory call(['gsutil', '-q', '-m', 'mv', os.path.join('fastqs', flowcell), output_directory]) # move and rename the qc summary file to fastq output directory, rename it so it doesn't get rewritten if there are multiple bcls call(['gsutil', '-q', '-m', 'mv', os.path.join(flowcell,'outs','qc_summary.json'), os.path.join(output_directory,flowcell + '_qc_summary.json')]) # write the path of fastqs for cromwell with open('path.txt', 'w') as file: file.write(os.path.join(output_directory, flowcell, '')) # move the undetermined fastqs over to the bucket try: call(['gsutil', '-q', '-m', 'mv', os.path.join('fastqs', 'Undetermined_*'), os.path.join(output_directory, flowcell + '_Undetermined', '')]) # write the undetermined fastqs path for cromwell with open('undetermined.txt', 'w') as file: file.write(os.path.join(output_directory, flowcell + '_Undetermined', '')) except: print('Unable to move Undetermined to Bucket') def orchestra_parse_csv(master_csv): """Parse the initial csv input to orchestra. Arguments: master_csv- Csv File mapping samples, lanes and indices to bcl Outputs- samples_file- list of samples for scattering bcl_file- list of bcl gsurls for scattering """ # Read the master_csv df = pd.read_csv(master_csv, header=0) # Get unique gsurls of bcls bcl_paths = set(df['Flowcell'].tolist()) # Write the bcls for Cromwell with open('bcls.txt', 'w+') as bcl_file: for item in bcl_paths: bcl_file.write('%s\n' % item) # Get unique sample names sampleIds = set(df['Sample'].tolist()) # Write the sample names for Cromwell with open('samples.txt', 'w+') as samples_file: for item in sampleIds: samples_file.write('%s\n' % item) def orchestra_analysis_csv(master_csv, h5s): """Map the initial csv input to CellRanger Count h5 file outputs for analysis WDL. Arguments: master_csv- Csv File mapping samples, lanes and indices to bcl h5s- array of cromwell localized file strings of h5 files from CellRanger Count Outputs- analysis_csv- list of samples for scattering """ # Read master Csv df = pd.read_csv(master_csv, header=0) # We don't need Flowcell, Lane or Index for Bo's Wdl df = df.drop(columns = ['Flowcell', 'Lane', 'Index']) # Sort by sample name df = df.sort_values(by=['Sample']).drop_duplicates(subset=['Sample']) sorted_h5s = [] # TODO this is more robust but still not good enough-- calling sample in might not work if your sample names are something like 'test_sample' and 'test_sample2' for sample in df['Sample']: for h5 in h5s: if sample in h5: sorted_h5s = sorted_h5s + [h5.replace('/cromwell_root/', 'gs://')] break # Add the location column df['Location'] = sorted_h5s # Save the csv, output it df.to_csv('analysis.csv', index=False) def orchestra_filter(paths, master_csv, sample_ids,trans_map): """Map the initial inputs to CellRanger Count. Arguments: paths- gsurls to every fastq directory master_csv- Csv File mapping samples, lanes and indices to bcl sample_ids- list of every sample, not actually needed, just easier trans_map- map of reference name to gsurl of transcriptome files Outputs- paths.tsv- Cromwell mapping of sample to a comma seperated string of fastq gsurls reference_list.tsv- Cromwell mapping of sample to genome transcriptome_list.tsv- Cromwell mapping of sample to transcriptome file chemistry.tsv- Cromwell mapping of sample to chemistry """ # get a list of every fastq/sample directory using gsutil ls fastqs = [] for path in paths: fastqs = fastqs + check_output(['gsutil', 'ls', path]).decode('utf-8').split('\n') # open the files for writing with open('chemistry.tsv', 'w+') as chemistry_list, open('reference.tsv', 'w+') as reference_list, open('transcriptome.tsv', 'w+') as transcriptome_list, open('paths.tsv', 'w+') as paths_list: # open the masterCsv and transcriptome map csv df = pd.read_csv(master_csv) tm = pd.read_csv(trans_map) # create the maps for sample in sample_ids: # Sample paths map # a path matches if it ends with .../sample_id/ key = os.path.join(sample, '') filter_paths = ','.join([path for path in fastqs if path.endswith(key)]) # Write to file paths_list.write('%s\t%s\n' % (sample, filter_paths)) # Chemistry and Genome map # Chemistry and Genome are the same across sample (assumed) so we can just use the first one we get rows = df.loc[df['Sample'] == sample] chemistry = rows['Chemistry'].tolist()[0] # first get the genome for the sample reference = rows['Reference'].tolist()[0] # we have a map of reference names to gsurls transcriptome_file = list(tm[tm['Reference Name'] == reference]['Location'])[0] # Write to files chemistry_list.write('%s\t%s\n' % (sample, chemistry)) reference_list.write('%s\t%s\n' % (sample, reference)) transcriptome_list.write('%s\t%s\n' % (sample, transcriptome_file)) def __main__(argv): """Command Line parser for scRna-Seq pipeline. Inputs- command line arguments """ # the first command, -c, tells us which arguments we need to check for next, and which function we are going to call command = argv[1].replace('-c=', '') # create the argument parser parser = argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter) if command == 'count': # CellRanger count method # add arguments parser.add_argument('--sampleId', '-id', help='Id of sample being run') parser.add_argument('--commaFastqs', '-cf', help='Comma seperated String with list of fastq directories', default='') parser.add_argument('--fastqs', '-fs', help='List of fastq directories', nargs='+', default=['']) parser.add_argument('--expectCells', '-E', help='Number of cells to expect', default='') parser.add_argument('--forceCells', '-F', help='Force number of cells', default='') parser.add_argument('--chemistry', '-C', help='Chemistry of fastqs', default = 'threeprime') parser.add_argument('--secondary', '-S', help='Run cellranger secondary analysis', default = 'true') parser.add_argument('--transcriptome', '-tf', help='Transcriptome file', default = '') parser.add_argument('--doForceCells', '-dfc', help='Boolean to
%s" % repro.state) with build_ssh_command( repro.ip, repro.auth.private_key, command="-T" ) as ssh_cmd: gdb_script = [ "target remote | %s sudo /onefuzz/bin/repro-stdout.sh" % " ".join(ssh_cmd) ] if debug_command: gdb_script += [debug_command, "quit"] with temp_file("gdb.script", "\n".join(gdb_script)) as gdb_script_path: dbg = ["gdb", "--silent", "--command", gdb_script_path] if debug_command: dbg += ["--batch"] try: # security note: dbg is built from content coming from # the server, which is trusted in this context. return subprocess.run( # nosec dbg, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ).stdout.decode(errors="ignore") except subprocess.CalledProcessError as err: self.logger.error( "debug failed: %s", err.output.decode(errors="ignore") ) raise err else: # security note: dbg is built from content coming from the # server, which is trusted in this context. subprocess.call(dbg) # nosec return None def _dbg_windows( self, repro: models.Repro, debug_command: Optional[str] ) -> Optional[str]: """Setup an SSH tunnel, then connect via CDB over SSH tunnel""" if ( repro.auth is None or repro.ip is None or repro.state != enums.VmState.running ): raise Exception("vm setup failed: %s" % repro.state) bind_all = which("wslpath") is not None and repro.os == enums.OS.windows proxy = "*:" + REPRO_SSH_FORWARD if bind_all else REPRO_SSH_FORWARD with ssh_connect(repro.ip, repro.auth.private_key, proxy=proxy): dbg = ["cdb.exe", "-remote", "tcp:port=1337,server=localhost"] if debug_command: dbg_script = [debug_command, "qq"] with temp_file("db.script", "\r\n".join(dbg_script)) as dbg_script_path: dbg += ["-cf", _wsl_path(dbg_script_path)] logging.debug("launching: %s", dbg) try: # security note: dbg is built from content coming from the server, # which is trusted in this context. return subprocess.run( # nosec dbg, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ).stdout.decode(errors="ignore") except subprocess.CalledProcessError as err: self.logger.error( "debug failed: %s", err.output.decode(errors="ignore") ) raise err else: logging.debug("launching: %s", dbg) # security note: dbg is built from content coming from the # server, which is trusted in this context. subprocess.call(dbg) # nosec return None def connect( self, vm_id: UUID_EXPANSION, delete_after_use: bool = False, debug_command: Optional[str] = None, ) -> Optional[str]: """Connect to an existing Reproduction VM""" self.logger.info("connecting to reproduction VM: %s", vm_id) if which("ssh") is None: raise Exception("unable to find ssh") def missing_os() -> Tuple[bool, str, models.Repro]: repro = self.get(vm_id) return ( repro.os is not None, "waiting for os determination", repro, ) repro = wait(missing_os) if repro.os == enums.OS.windows: if which("cdb.exe") is None: raise Exception("unable to find cdb.exe") if repro.os == enums.OS.linux: if which("gdb") is None: raise Exception("unable to find gdb") def func() -> Tuple[bool, str, models.Repro]: repro = self.get(vm_id) state = repro.state return ( repro.auth is not None and repro.ip is not None and state not in [enums.VmState.init, enums.VmState.extensions_launch], "launching reproducing vm. current state: %s" % state, repro, ) repro = wait(func) result: Optional[str] = None if repro.os == enums.OS.windows: result = self._dbg_windows(repro, debug_command) elif repro.os == enums.OS.linux: result = self._dbg_linux(repro, debug_command) else: raise NotImplementedError if delete_after_use: self.logger.debug("deleting vm %s", repro.vm_id) self.delete(repro.vm_id) return result def create_and_connect( self, container: primitives.Container, path: str, duration: int = 24, delete_after_use: bool = False, debug_command: Optional[str] = None, ) -> Optional[str]: """Create and connect to a Reproduction VM""" repro = self.create(container, path, duration=duration) return self.connect( repro.vm_id, delete_after_use=delete_after_use, debug_command=debug_command ) class Notifications(Endpoint): """Interact with models.Notifications""" endpoint = "notifications" def create( self, container: primitives.Container, config: models.NotificationConfig, *, replace_existing: bool = False, ) -> models.Notification: """Create a notification based on a config file""" config = requests.NotificationCreate( container=container, config=config.config, replace_existing=replace_existing ) return self._req_model("POST", models.Notification, data=config) def create_teams( self, container: primitives.Container, url: str ) -> models.Notification: """Create a Teams notification integration""" self.logger.debug("create teams notification integration: %s", container) config = models.NotificationConfig(config=models.TeamsTemplate(url=url)) return self.create(container, config) def create_ado( self, container: primitives.Container, project: str, base_url: str, auth_token: str, work_item_type: str, unique_fields: List[str], comment: Optional[str] = None, fields: Optional[Dict[str, str]] = None, on_dup_increment: Optional[List[str]] = None, on_dup_comment: Optional[str] = None, on_dup_set_state: Optional[Dict[str, str]] = None, on_dup_fields: Optional[Dict[str, str]] = None, ) -> models.Notification: """Create an Azure DevOps notification integration""" self.logger.debug("create ado notification integration: %s", container) entry = models.NotificationConfig( config=models.ADOTemplate( base_url=base_url, auth_token=auth_token, project=project, type=work_item_type, comment=comment, unique_fields=unique_fields, ado_fields=fields, on_duplicate=models.ADODuplicateTemplate( increment=on_dup_increment or [], comment=on_dup_comment, ado_fields=on_dup_fields or {}, set_state=on_dup_set_state or {}, ), ), ) return self.create(container, entry) def delete(self, notification_id: UUID_EXPANSION) -> models.Notification: """Delete a notification integration""" notification_id_expanded = self._disambiguate_uuid( "notification_id", notification_id, lambda: [str(x.notification_id) for x in self.list()], ) self.logger.debug( "create notification integration: %s", notification_id_expanded, ) return self._req_model( "DELETE", models.Notification, data=requests.NotificationGet(notification_id=notification_id_expanded), ) def list( self, *, container: Optional[List[primitives.Container]] = None ) -> List[models.Notification]: """List notification integrations""" self.logger.debug("listing notification integrations") return self._req_model_list( "GET", models.Notification, data=requests.NotificationSearch(container=container), ) class Tasks(Endpoint): """Interact with tasks""" endpoint = "tasks" def delete(self, task_id: UUID_EXPANSION) -> models.Task: """Stop an individual task""" task_id_expanded = self._disambiguate_uuid( "task_id", task_id, lambda: [str(x.task_id) for x in self.list()] ) self.logger.debug("delete task: %s", task_id_expanded) return self._req_model( "DELETE", models.Task, data=requests.TaskGet(task_id=task_id_expanded) ) def get(self, task_id: UUID_EXPANSION) -> models.Task: """Get information about a task""" task_id_expanded = self._disambiguate_uuid( "task_id", task_id, lambda: [str(x.task_id) for x in self.list()] ) self.logger.debug("get task: %s", task_id_expanded) return self._req_model( "GET", models.Task, data=requests.TaskGet(task_id=task_id_expanded) ) def create_with_config(self, config: models.TaskConfig) -> models.Task: """Create a Task using TaskConfig""" return self._req_model("POST", models.Task, data=config) def create( self, job_id: UUID_EXPANSION, task_type: enums.TaskType, target_exe: str, containers: List[Tuple[enums.ContainerType, primitives.Container]], *, analyzer_env: Optional[Dict[str, str]] = None, analyzer_exe: Optional[str] = None, analyzer_options: Optional[List[str]] = None, check_asan_log: bool = False, check_debugger: bool = True, check_retry_count: Optional[int] = None, check_fuzzer_help: Optional[bool] = None, expect_crash_on_failure: Optional[bool] = None, debug: Optional[List[enums.TaskDebugFlag]] = None, duration: int = 24, ensemble_sync_delay: Optional[int] = None, generator_exe: Optional[str] = None, generator_options: Optional[List[str]] = None, pool_name: primitives.PoolName, prereq_tasks: Optional[List[UUID]] = None, reboot_after_setup: bool = False, rename_output: bool = False, stats_file: Optional[str] = None, stats_format: Optional[enums.StatsFormat] = None, supervisor_env: Optional[Dict[str, str]] = None, supervisor_exe: Optional[str] = None, supervisor_input_marker: Optional[str] = None, supervisor_options: Optional[List[str]] = None, tags: Optional[Dict[str, str]] = None, task_wait_for_files: Optional[enums.ContainerType] = None, target_env: Optional[Dict[str, str]] = None, target_options: Optional[List[str]] = None, target_options_merge: bool = False, target_timeout: Optional[int] = None, target_workers: Optional[int] = None, vm_count: int = 1, preserve_existing_outputs: bool = False, colocate: bool = False, report_list: Optional[List[str]] = None, minimized_stack_depth: Optional[int] = None, coverage_filter: Optional[str] = None, ) -> models.Task: """ Create a task :param bool ensemble_sync_delay: Specify duration between syncing inputs during ensemble fuzzing (0 to disable). """ self.logger.debug("creating task: %s", task_type) job_id_expanded = self._disambiguate_uuid( "job_id", job_id, lambda: [str(x.job_id) for x in self.onefuzz.jobs.list()], ) if tags is None: tags = {} containers_submit = [] for (container_type, container) in containers: containers_submit.append( models.TaskContainers(name=container, type=container_type) ) config = models.TaskConfig( containers=containers_submit, debug=debug, job_id=job_id_expanded, pool=models.TaskPool(count=vm_count, pool_name=pool_name), prereq_tasks=prereq_tasks, tags=tags, colocate=colocate, task=models.TaskDetails( analyzer_env=analyzer_env, analyzer_exe=analyzer_exe, analyzer_options=analyzer_options, check_asan_log=check_asan_log, check_debugger=check_debugger, check_retry_count=check_retry_count, check_fuzzer_help=check_fuzzer_help, expect_crash_on_failure=expect_crash_on_failure, duration=duration, ensemble_sync_delay=ensemble_sync_delay, generator_exe=generator_exe, generator_options=generator_options, reboot_after_setup=reboot_after_setup, rename_output=rename_output, stats_file=stats_file, stats_format=stats_format, supervisor_env=supervisor_env, supervisor_exe=supervisor_exe, supervisor_input_marker=supervisor_input_marker, supervisor_options=supervisor_options, target_env=target_env, target_exe=target_exe, target_options=target_options, target_options_merge=target_options_merge, target_timeout=target_timeout, target_workers=target_workers, type=task_type, wait_for_files=task_wait_for_files, report_list=report_list, preserve_existing_outputs=preserve_existing_outputs, minimized_stack_depth=minimized_stack_depth, coverage_filter=coverage_filter, ), ) return self.create_with_config(config) def list( self, job_id: Optional[UUID_EXPANSION] = None, state: Optional[List[enums.TaskState]] = enums.TaskState.available(), ) -> List[models.Task]: """Get information about all tasks""" self.logger.debug("list tasks") job_id_expanded: Optional[UUID] = None if job_id is not None: job_id_expanded = self._disambiguate_uuid( "job_id", job_id, lambda: [str(x.job_id) for x in self.onefuzz.jobs.list()], ) return self._req_model_list( "GET", models.Task, data=requests.TaskSearch(job_id=job_id_expanded, state=state), ) class JobContainers(Endpoint): """Interact with Containers used within tasks in a Job""" endpoint = "jobs" def list( self, job_id: UUID_EXPANSION, container_type: Optional[ enums.ContainerType ] = enums.ContainerType.unique_reports, ) -> Dict[str, List[str]]: """ List the files for all of the containers of a given container type for the specified job """ containers = set() tasks = self.onefuzz.tasks.list(job_id=job_id, state=[]) for task in tasks: containers.update( set(x.name for x in task.config.containers if x.type == container_type) ) results: Dict[str, List[str]] = {} for container in containers: results[container] = self.onefuzz.containers.files.list(container).files return results def download( self, job_id: UUID_EXPANSION, *, output: Optional[primitives.Directory] = None ) -> None: to_download = {} tasks = self.onefuzz.tasks.list(job_id=job_id, state=None) if not tasks: raise Exception("no tasks with job_id:%s" % job_id) for task in tasks: for container in task.config.containers: info = self.onefuzz.containers.get(container.name) name = os.path.join(container.type.name, container.name) to_download[name] = info.sas_url if output is None: output = primitives.Directory(os.getcwd()) for name in to_download: outdir = os.path.join(output, name) if not os.path.exists(outdir): os.makedirs(outdir) self.logger.info("downloading: %s", name) # security note: the src for azcopy comes from the server which is # trusted in this context, while the destination is provided by the # user azcopy_sync(to_download[name], outdir) def delete( self, job_id: UUID_EXPANSION, *, only_job_specific: bool = True, dryrun: bool = False, ) -> None: SAFE_TO_REMOVE =
import os import errno import numpy as np from torch.nn import init import torch import torch.nn as nn from torch.autograd import Variable import torchvision from PIL import Image, ImageDraw, ImageFont from copy import deepcopy import skimage.transform import ntpath import sys from miscc.config import cfg # For visualization ################################################ COLOR_DIC = {0:[128,64,128], 1:[244, 35,232], 2:[70, 70, 70], 3:[102,102,156], 4:[190,153,153], 5:[153,153,153], 6:[250,170, 30], 7:[220, 220, 0], 8:[107,142, 35], 9:[152,251,152], 10:[70,130,180], 11:[220,20, 60], 12:[255, 0, 0], 13:[0, 0, 142], 14:[119,11, 32], 15:[0, 60,100], 16:[0, 80, 100], 17:[0, 0, 230], 18:[0, 0, 70], 19:[0, 0, 0]} FONT_MAX = 50 def drawCaption(convas, captions, ixtoword, vis_size, off1=2, off2=2): num = captions.size(0) img_txt = Image.fromarray(convas) # get a font # fnt = None # ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) fnt = ImageFont.truetype('../share/Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) sentence_list = [] for i in range(num): cap = captions[i].data.cpu().numpy() sentence = [] for j in range(len(cap)): if cap[j] == 0: break word = ixtoword[cap[j]].encode('ascii', 'ignore').decode('ascii') d.text(((j + off1) * (vis_size + off2), i * FONT_MAX), '%d:%s' % (j, word[:6]), font=fnt, fill=(255, 255, 255, 255)) sentence.append(word) sentence_list.append(sentence) return img_txt, sentence_list def build_super_images(real_imgs, captions, ixtoword, attn_maps, att_sze, lr_imgs=None, batch_size=cfg.TRAIN.BATCH_SIZE, max_word_num=cfg.TEXT.WORDS_NUM): nvis = 8 real_imgs = real_imgs[:nvis] if lr_imgs is not None: lr_imgs = lr_imgs[:nvis] if att_sze == 17: vis_size = att_sze * 16 else: vis_size = real_imgs.size(2) text_convas = \ np.ones([batch_size * FONT_MAX, (max_word_num + 2) * (vis_size + 2), 3], dtype=np.uint8) for i in range(max_word_num): istart = (i + 2) * (vis_size + 2) iend = (i + 3) * (vis_size + 2) text_convas[:, istart:iend, :] = COLOR_DIC[i] real_imgs = \ nn.Upsample(size=(vis_size, vis_size), mode='bilinear')(real_imgs) # [-1, 1] --> [0, 1] real_imgs.add_(1).div_(2).mul_(255) real_imgs = real_imgs.data.numpy() # b x c x h x w --> b x h x w x c real_imgs = np.transpose(real_imgs, (0, 2, 3, 1)) pad_sze = real_imgs.shape middle_pad = np.zeros([pad_sze[2], 2, 3]) post_pad = np.zeros([pad_sze[1], pad_sze[2], 3]) if lr_imgs is not None: lr_imgs = \ nn.Upsample(size=(vis_size, vis_size), mode='bilinear')(lr_imgs) # [-1, 1] --> [0, 1] lr_imgs.add_(1).div_(2).mul_(255) lr_imgs = lr_imgs.data.numpy() # b x c x h x w --> b x h x w x c lr_imgs = np.transpose(lr_imgs, (0, 2, 3, 1)) # batch x seq_len x 17 x 17 --> batch x 1 x 17 x 17 seq_len = max_word_num img_set = [] num = nvis # len(attn_maps) text_map, sentences = \ drawCaption(text_convas, captions, ixtoword, vis_size) text_map = np.asarray(text_map).astype(np.uint8) bUpdate = 1 for i in range(num): attn = attn_maps[i].cpu().view(1, -1, att_sze, att_sze) # --> 1 x 1 x 17 x 17 attn_max = attn.max(dim=1, keepdim=True) attn = torch.cat([attn_max[0], attn], 1) # attn = attn.view(-1, 1, att_sze, att_sze) attn = attn.repeat(1, 3, 1, 1).data.numpy() # n x c x h x w --> n x h x w x c attn = np.transpose(attn, (0, 2, 3, 1)) num_attn = attn.shape[0] # img = real_imgs[i] if lr_imgs is None: lrI = img else: lrI = lr_imgs[i] row = [lrI, middle_pad] row_merge = [img, middle_pad] row_beforeNorm = [] minVglobal, maxVglobal = 1, 0 for j in range(num_attn): one_map = attn[j] if (vis_size // att_sze) > 1: one_map = \ skimage.transform.pyramid_expand(one_map, sigma=20, upscale=vis_size // att_sze) row_beforeNorm.append(one_map) minV = one_map.min() maxV = one_map.max() if minVglobal > minV: minVglobal = minV if maxVglobal < maxV: maxVglobal = maxV for j in range(seq_len + 1): if j < num_attn: one_map = row_beforeNorm[j] one_map = (one_map - minVglobal) / (maxVglobal - minVglobal) one_map *= 255 # PIL_im = Image.fromarray(np.uint8(img)) PIL_att = Image.fromarray(np.uint8(one_map)) merged = \ Image.new('RGBA', (vis_size, vis_size), (0, 0, 0, 0)) mask = Image.new('L', (vis_size, vis_size), (210)) merged.paste(PIL_im, (0, 0)) merged.paste(PIL_att, (0, 0), mask) merged = np.array(merged)[:, :, :3] else: one_map = post_pad merged = post_pad row.append(one_map) row.append(middle_pad) # row_merge.append(merged) row_merge.append(middle_pad) row = np.concatenate(row, 1) row_merge = np.concatenate(row_merge, 1) txt = text_map[i * FONT_MAX: (i + 1) * FONT_MAX] if txt.shape[1] != row.shape[1]: print('txt', txt.shape, 'row', row.shape) bUpdate = 0 break row = np.concatenate([txt, row, row_merge], 0) img_set.append(row) if bUpdate: img_set = np.concatenate(img_set, 0) img_set = img_set.astype(np.uint8) return img_set, sentences else: return None def build_super_images2(real_imgs, captions, ixtoword, attn_maps, att_sze, lr_imgs=None, batch_size=cfg.TRAIN.BATCH_SIZE, max_word_num=cfg.TEXT.WORDS_NUM): nvis = 8 real_imgs = real_imgs[:nvis] if lr_imgs is not None: lr_imgs = lr_imgs[:nvis] if att_sze == 17: vis_size = att_sze * 16 else: vis_size = real_imgs.size(2) text_convas = \ np.ones([batch_size * FONT_MAX, (max_word_num + 2) * (vis_size + 2), 3], dtype=np.uint8) for i in range(max_word_num): istart = (i + 2) * (vis_size + 2) iend = (i + 3) * (vis_size + 2) text_convas[:, istart:iend, :] = COLOR_DIC[i] real_imgs = \ nn.Upsample(size=(vis_size, vis_size), mode='bilinear')(real_imgs) # [-1, 1] --> [0, 1] real_imgs.add_(1).div_(2).mul_(255) real_imgs = real_imgs.data.numpy() # b x c x h x w --> b x h x w x c real_imgs = np.transpose(real_imgs, (0, 2, 3, 1)) pad_sze = real_imgs.shape middle_pad = np.zeros([pad_sze[2], 2, 3]) post_pad = np.zeros([pad_sze[1], pad_sze[2], 3]) if lr_imgs is not None: lr_imgs = \ nn.Upsample(size=(vis_size, vis_size), mode='bilinear')(lr_imgs) # [-1, 1] --> [0, 1] lr_imgs.add_(1).div_(2).mul_(255) lr_imgs = lr_imgs.data.numpy() # b x c x h x w --> b x h x w x c lr_imgs = np.transpose(lr_imgs, (0, 2, 3, 1)) # batch x seq_len x 17 x 17 --> batch x 1 x 17 x 17 seq_len = max_word_num img_set = [] num = nvis # len(attn_maps) text_map, sentences = \ drawCaption(text_convas, captions, ixtoword, vis_size) text_map = np.asarray(text_map).astype(np.uint8) bUpdate = 1 for i in range(num): attn = attn_maps[i].cpu().view(1, -1, att_sze, att_sze) # --> 1 x 1 x 17 x 17 attn_max = attn.max(dim=1, keepdim=True) attn = torch.cat([attn_max[0], attn], 1) # attn = attn.view(-1, 1, att_sze, att_sze) attn = attn.repeat(1, 3, 1, 1).data.numpy() # n x c x h x w --> n x h x w x c attn = np.transpose(attn, (0, 2, 3, 1)) num_attn = attn.shape[0] # img = real_imgs[i] if lr_imgs is None: lrI = img else: lrI = lr_imgs[i] row = [lrI, middle_pad] row_merge = [img, middle_pad] row_beforeNorm = [] minVglobal, maxVglobal = 0.0, 0.75 for j in range(num_attn): one_map = attn[j] if (vis_size // att_sze) > 1: one_map = \ skimage.transform.pyramid_expand(one_map, sigma=20, upscale=vis_size // att_sze) row_beforeNorm.append(one_map) '''minV = one_map.min() maxV = one_map.max() if minVglobal > minV: minVglobal = minV if maxVglobal < maxV: maxVglobal = maxV''' for j in range(seq_len + 1): if j < num_attn: one_map = row_beforeNorm[j] one_map = np.clip(one_map, minVglobal, maxVglobal) one_map = (one_map - minVglobal) / (maxVglobal - minVglobal) one_map *= 255 # PIL_im = Image.fromarray(np.uint8(img)) PIL_att = Image.fromarray(np.uint8(one_map)) merged = \ Image.new('RGBA', (vis_size, vis_size), (0, 0, 0, 0)) mask = Image.new('L', (vis_size, vis_size), (210)) merged.paste(PIL_im, (0, 0)) merged.paste(PIL_att, (0, 0), mask) merged = np.array(merged)[:, :, :3] else: one_map = post_pad merged = post_pad row.append(one_map) row.append(middle_pad) # row_merge.append(merged) row_merge.append(middle_pad) row = np.concatenate(row, 1) row_merge = np.concatenate(row_merge, 1) txt = text_map[i * FONT_MAX: (i + 1) * FONT_MAX] if txt.shape[1] != row.shape[1]: print('txt', txt.shape, 'row', row.shape) bUpdate = 0 break row = np.concatenate([txt, row, row_merge], 0) img_set.append(row) if bUpdate: img_set = np.concatenate(img_set, 0) img_set = img_set.astype(np.uint8) return img_set, sentences else: return None #################################################################### def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.orthogonal(m.weight.data, 1.0) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) elif classname.find('Linear') != -1: nn.init.orthogonal(m.weight.data, 1.0) if m.bias is not None: m.bias.data.fill_(0.0) def load_params(model, new_param): for p, new_p in zip(model.parameters(), new_param): p.data.copy_(new_p) def copy_G_params(model): flatten = deepcopy(list(p.data for p in model.parameters())) return flatten def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def path_leaf(path): return ntpath.basename(path) def read_hmap(hmap_path): hmap = Image.open(hmap_path) hmap = np.asarray(hmap) hmap = np.squeeze(hmap[:,:,0]) return hmap def crop_rois(roi_cnn_model, fmaps, fm_rois, num_rois, roi_size, nef): # input: # fmaps (type = variable): batch_size x nef x H x W # rois (type = numpy): batch_size x cfg.ROI.BOXES_NUM x cfg.ROI.BOXES_DIM (left, top, width, height, category id, iscrowd) # num_rois (type = list): batch_size # output: # cropped_rois (variable): batch_size x nef x max_num_rois x 1 num_rois = num_rois.cpu().data.numpy().tolist() fmap_size = int(fmaps.size(2)) max_num_roi = np.amax(num_rois) cropped_rois = [] batch_size = len(num_rois) cropped_rois
<filename>dim/dim/models/ip.py import datetime import logging import re from sqlalchemy import Column, BigInteger, Integer, String, Numeric, TIMESTAMP, ForeignKey, UniqueConstraint from sqlalchemy.ext.compiler import compiles from sqlalchemy.orm import relationship, backref, validates from sqlalchemy.sql import bindparam, or_, between, func, expression, text from sqlalchemy.types import DateTime from dim import db from dim.errors import InvalidParameterError from dim.ipaddr import IP from dim.iptrie import IPTrie from dim.models import WithAttr, TrackChanges, get_session_username from dim.rrtype import validate_uint32 class minus_days(expression.FunctionElement): type = DateTime() name = 'minus_days' @compiles(minus_days, 'mysql') def mysql_minus_days(element, compiler, **kw): date, days = list(element.clauses) return "DATE_SUB(%s, INTERVAL %s DAY)" % (compiler.process(date), compiler.process(days)) class Vlan(db.Model): id = Column(BigInteger, primary_key=True, nullable=False) vid = Column(Integer, unique=True, nullable=False) @property def display_name(self): return self.vid class IpblockStatus(db.Model): id = Column(BigInteger, primary_key=True, nullable=False) name = Column(String(64), nullable=False, unique=True) @property def display_name(self): return self.name class Layer3Domain(db.Model, TrackChanges): VRF = 'vrf' TYPES = {VRF: ('rd', )} id = Column(BigInteger, primary_key=True, nullable=False) name = Column(String(128), nullable=False, unique=True) type = Column(String(20), nullable=False) comment = Column(String(255), nullable=True, index=False) # Vrf rd = Column(BigInteger, nullable=True, unique=True) validate_uint32 = validates('rd')(validate_uint32) @property def display_name(self): return self.name @property def display_rd(self): return '%d:%d' % (self.rd >> 16, self.rd & 0xFFFF) def set_comment(self, comment): self.comment = comment self.update_modified() def set_rd(self, rd_str): if self.type != Layer3Domain.VRF: raise InvalidParameterError('Layer3domain %s is not of type vrf' % self.name) rd = Layer3Domain.parse_rd(rd_str) if Layer3Domain.query.filter_by(rd=rd).count() > 0: raise InvalidParameterError('Layer3domain with type vrf rd %s already exists' % rd_str) self.rd = rd @staticmethod def parse_rd(rd): m = re.match(r'(\d{1,5}):(\d{1,5})', rd) if m is None: raise InvalidParameterError("Invalid rd '%s'" % rd) def validate_uint16(s): value = int(s) if value < 0 or value > 2 ** 16 - 1: raise InvalidParameterError("Invalid rd '%s'" % rd) return value a = validate_uint16(m.group(1)) b = validate_uint16(m.group(2)) return (a << 16) + b class Pool(db.Model, WithAttr): __tablename__ = 'ippool' id = Column(BigInteger, primary_key=True, nullable=False) name = Column(String(128), unique=True, nullable=False) version = Column(Integer, index=True, default=0, nullable=False) # TODO allow null description = Column(String(128)) vlan_id = Column(BigInteger, ForeignKey('vlan.id')) created = Column(TIMESTAMP, nullable=False, default=datetime.datetime.utcnow, server_default='1970-01-02 00:00:01') modified = Column(TIMESTAMP, nullable=False, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, server_default='1970-01-02 00:00:01') modified_by = Column(String(128), default=get_session_username, onupdate=get_session_username) owner_id = Column(BigInteger, ForeignKey('usergroup.id', ondelete='SET NULL'), nullable=True) layer3domain_id = Column(BigInteger, ForeignKey('layer3domain.id'), nullable=False) vlan = relationship(Vlan) owner = relationship('Group') layer3domain = relationship(Layer3Domain) @property def display_name(self): return self.name def __str__(self): return self.name @validates('name') def validate_name(self, key, name): if not re.match('^[A-Za-z0-9][-_A-Za-z0-9]*$', name): raise ValueError("Invalid pool name: '%s'" % name) return name def __contains__(self, ip): if isinstance(ip, Ipblock): if ip.pool == self: return True ip = ip.ip for subnet in self.subnets: if ip in subnet.ip: return True return False def update_modified(self): ''' Update the modified and modified_by fields. This only needs to be called when a change to the pool doesn't modify any columns in the ippool table. ''' self.modified = datetime.datetime.utcnow() self.modified_by = get_session_username() @property def total_ips(self): return sum(s.total for s in self.subnets) @property def used_ips(self): return sum(s.used for s in self.subnets) def allocation_history(self, days_ago): return AllocationHistory.query\ .filter_by(pool=self)\ .filter(func.date(AllocationHistory.date) == func.date(minus_days(func.now(), days_ago)))\ .order_by(AllocationHistory.date)\ .first() class PoolAttrName(db.Model): __tablename__ = 'ippoolattrname' id = Column(BigInteger, primary_key=True, nullable=False) name = Column(String(128), nullable=False, unique=True) reserved = ['name', 'vlan', 'description', 'version', 'created', 'modified', 'modified_by'] class PoolAttr(db.Model): __tablename__ = 'ippoolattr' __table_constraints__ = (UniqueConstraint('name', 'ippool_id'), ) id = Column(BigInteger, primary_key=True, nullable=False) ippool_id = Column(BigInteger, ForeignKey('ippool.id'), nullable=False) name_id = Column('name', BigInteger, ForeignKey('ippoolattrname.id'), nullable=False) value = Column(String(255), nullable=False) pool = relationship(Pool, backref=backref('attributes', cascade='all, delete-orphan')) name = relationship(PoolAttrName) Pool.AttrNameClass = PoolAttrName Pool.AttrClass = PoolAttr Pool.attr_backref = 'pool' class FavoritePool(db.Model): __tablename__ = 'favoriteippool' ippool_id = Column(BigInteger, ForeignKey('ippool.id'), primary_key=True) user_id = Column(BigInteger, ForeignKey('user.id'), primary_key=True) user = relationship('User', uselist=False, backref=backref('favorite_pools', cascade='all, delete-orphan')) pool = relationship('Pool', uselist=False, backref=backref('favorited_by', cascade='all, delete-orphan', collection_class=set)) class AllocationHistory(db.Model): id = Column(BigInteger, primary_key=True, nullable=False) date = Column(TIMESTAMP, nullable=False) ippool_id = Column(BigInteger, ForeignKey('ippool.id'), nullable=False) total_ips = Column(Numeric(precision=40, scale=0), nullable=False) used_ips = Column(Numeric(precision=40, scale=0), nullable=False) pool = relationship(Pool, backref=backref('allocationhistory', cascade='all, delete-orphan')) @staticmethod def collect_data(): for pool in Pool.query.all(): db.session.add( AllocationHistory( pool=pool, total_ips=pool.total_ips, used_ips=pool.used_ips)) class Ipblock(db.Model, WithAttr, TrackChanges): __table_constraints__ = (UniqueConstraint('address', 'prefix', 'layer3domain_id'), ) id = Column(BigInteger, primary_key=True, nullable=False) version = Column(Integer, index=True, nullable=False) address = Column(Numeric(precision=40, scale=0), nullable=False) prefix = Column(Integer, nullable=False) priority = Column(Integer) gateway = Column(Numeric(precision=40, scale=0)) parent_id = Column(BigInteger, ForeignKey('ipblock.id')) status_id = Column(BigInteger, ForeignKey('ipblockstatus.id')) ippool_id = Column(BigInteger, ForeignKey('ippool.id')) vlan_id = Column(BigInteger, ForeignKey('vlan.id')) layer3domain_id = Column(BigInteger, ForeignKey('layer3domain.id'), nullable=False) # relationships parent = relationship('Ipblock', remote_side=[id], backref=backref('children', lazy='dynamic', order_by='Ipblock.address')) status = relationship(IpblockStatus) pool = relationship(Pool, backref=backref('subnets', order_by='Ipblock.priority')) vlan = relationship(Vlan) layer3domain = relationship(Layer3Domain) def __str__(self): return str(self.ip) def label(self, expanded=False): return self.ip.label(expanded) @property def ip(self): return IP(int(self.address), self.prefix, self.version) @property def gateway_ip(self): return IP(int(self.gateway), version=self.version) @property def is_host(self): return self.ip.is_host @property def free(self): return self.total - self.used @property def total(self): return self.ip.numhosts def _used(self, only_static): ret = 0 q = db.session.query(Ipblock.prefix, func.count()).filter(Ipblock.parent == self) if only_static: q = q.join(IpblockStatus).filter(IpblockStatus.name == 'Static') for prefix, count in q.group_by(Ipblock.prefix).all(): ret += count * 2 ** (self.ip.bits - prefix) return ret @property def used(self): return self._used(only_static=False) @property def static(self): return self._used(only_static=True) @property def subnet(self): return self._ancestor('Subnet') @property def delegation(self): return self._ancestor('Delegation') @staticmethod def free_ranges(block, children): '''Return ranges of free addresses inside block as tuples (start_address, stop_address)''' start = block.ip.address for child in children: if start < child.ip.address - 1: yield start, child.ip.address - 1 start = child.ip.broadcast.address + 1 if start < block.ip.broadcast.address: yield start, block.ip.broadcast.address @property def free_space(self): ''' Returns the shortest list of IP objects that cover all the free space. ''' def max_hostbits(address, max_): '''Return the maximum number of host bits, but no more than max_''' hb = 0 mask = 1 while address & mask == 0 and hb < max_: hb += 1 mask *= 2 return hb def fill(range_start, range_end): ''' Fill the free space between range_start and range_end with the least amount of blocks. ''' if range_start >= range_end: return [] hb = max_hostbits(range_start, bits - self.prefix) while range_start + 2 ** hb - 1 > range_end: hb -= 1 return [IP(range_start, bits - hb, self.version)] + fill(range_start + 2 ** hb, range_end) bits = self.ip.bits result = [] for (start, stop) in Ipblock.free_ranges(self, self.children.all()): result.extend(fill(start, stop)) return result def __contains__(self, item): if isinstance(item, Ipblock): return item.ip in self.ip else: return item in self.ip @staticmethod def create(*args, **kwargs): ipblock = Ipblock(*args, **kwargs) db.session.add(ipblock) ipblock._tree_update() ipblock._validate() return ipblock def delete(self): logging.debug("Deleting %s" % self) if not self.is_host: logging.debug('Updating parents for children of %s' % self) Ipblock.query.filter_by(parent=self).update({'parent_id': self.parent_id}) db.session.delete(self) def delete_subtree(self): logging.debug("Deleting subtree %s" % self) # Because the children relationship is dynamic, we have to manually sort # the deletes to satisfy fk constraints for block in Ipblock.query\ .filter(Ipblock.version == self.version)\ .filter(Ipblock.layer3domain_id == self.layer3domain_id)\ .filter(Ipblock.prefix >= self.prefix)\ .filter(between(Ipblock.address, self.ip.network.address, self.ip.broadcast.address))\ .order_by(Ipblock.prefix.desc()).all(): db.session.delete(block) @staticmethod def query_ip(ip, layer3domain): filters = {} if layer3domain is not None: filters['layer3domain'] = layer3domain return Ipblock.query.filter_by(address=ip.address, prefix=ip.prefix, version=ip.version, **filters) @staticmethod def build_tree_mem(layer3domain, version): logging.debug('build_tree_mem(%s, %d)' % (layer3domain.name, version)) new_parents = [] blocks = db.session.query(Ipblock.id, Ipblock.address, Ipblock.prefix, Ipblock.parent_id)\ .filter(Ipblock.version == version, Ipblock.layer3domain_id == layer3domain.id)\ .order_by(Ipblock.prefix).all() tree = IPTrie(version) for id, address, prefix, parent in blocks: ip = IP(int(address), prefix, version) if prefix == tree._bits: new_parent = tree.parent(ip) else: new_parent = tree.insert(ip, id) new_parent_id = new_parent.data if new_parent else None if new_parent_id != parent: new_parents.append((id, new_parent_id)) return tree, new_parents @staticmethod def build_tree_parents(layer3domain, version): tree, new_parents = Ipblock.build_tree_mem(layer3domain, version) if new_parents: logging.warning('%d wrong parents found during tree rebuild in layer3domain %s version %d' % ( len(new_parents), layer3domain.name, version)) update = Ipblock.__table__.update() \ .where(Ipblock.id == bindparam('_id')) \ .values(parent_id=bindparam('_parent')) db.session.execute(update, params=[dict(_id=id, _parent=parent) for id, parent in new_parents]) db.session.expire_all() return tree def _tree_update(self): db.session.flush() # we need self.id logging.debug('Updating tree for %s', self) ancestors = Ipblock._ancestors_noparent(self.ip, self.layer3domain) new_parent_id = ancestors[0].id if ancestors else None if self.parent_id != new_parent_id: self.parent_id = new_parent_id if not self.is_host: # TODO patch sqlalchemy to support with_hint for update statements Ipblock.query\ .with_hint(Ipblock, 'USE INDEX (address)', 'mysql')\ .filter(Ipblock.parent_id == self.parent_id)\ .filter(Ipblock.prefix > self.prefix)\ .filter(Ipblock.address >= self.ip.network.address)\ .filter(Ipblock.address <= self.ip.broadcast.address)\ .update({'parent_id': self.id}) def _validate(self): status = self.status.name if self.is_host: if status in ('Container', 'Subnet', 'Delegation'): raise Exception("Creating %s blocks with only one IP addresss is not allowed" % status) else: if status in ('Available', 'Static'): raise Exception("%s blocks must be host addresses" % status) if self.parent and self.parent.status:
<gh_stars>1-10 # -*- coding: utf-8 -*- """ SCRIPT # 6 Created on Sun Aug 2 12:19:09 2020 @author: omid """ import pandas as pd import numpy as np from datetime import datetime from khayyam import * import statsmodels.api as sm from scipy.stats import ttest_ind # seed the random number generator allFunds = pd.read_pickle("./allFunds.pkl") bookvalues = pd.read_pickle("./bookvalues.pkl") risk_premium = pd.read_pickle("./risk_premium.pkl") No = 30 # No. of funds # allFunds & risk_premium with Gregorian date index: dates_convert = pd.DataFrame() dates_convert["date_j"] = allFunds.index.astype(str).str.split().str.get(0) # date column dates_convert["date_j"] = dates_convert["date_j"].apply(lambda x : (JalaliDatetime.strptime(x, '%Y-%m-%d'))) dates_convert["date_g"] = dates_convert["date_j"].apply(lambda x : x.todate()) ## funds = allFunds.set_index(dates_convert["date_g"]) dates_convert = pd.DataFrame() dates_convert["date_j"] = risk_premium.index.astype(str).str.split().str.get(0) # date column dates_convert["date_j"] = dates_convert["date_j"].apply(lambda x : (JalaliDatetime.strptime(x, '%Y-%m-%d'))) dates_convert["date_g"] = dates_convert["date_j"].apply(lambda x : x.todate()) ## factors = risk_premium.set_index(dates_convert["date_g"]) # Total study window: 1392/1/1 to 1399/1/1 start_date_j = JalaliDate(1392,4,1) start_date_g = start_date_j.todate() # '2010-06-21' #Q = 4*(bookvalues["year"].iloc[-1] - bookvalues["year"].iloc[0]) - 1 # total quarters Q = 4*(bookvalues["year"].iloc[-1] - bookvalues["year"].iloc[0] - 3) - 1 # total quarters ########################################## 1.1 Stock selection alphas = pd.DataFrame() performance_deciles_Ranking_quarter_alpha = pd.DataFrame() performance_deciles_Post_ranking_alpha = pd.DataFrame() dfs = [] for t in (pd.date_range(start_date_g, periods=Q, freq='Q') - pd.DateOffset(days = 8)) : # -8 to offset between j & g quarter start dates g = pd.DataFrame() # PREVIOUS 3 months: funds_evaluation_period = funds[(funds.index < t) & (funds.index >= (t - pd.DateOffset(months=3)))] factors_evaluation_period = factors[(factors.index < t) & (factors.index >= (t - pd.DateOffset(months=3)))] # Post-ranking quarter: funds_Post_ranking = funds[(funds.index >= t) & (funds.index < (t + pd.DateOffset(months=3)))] factors_Post_ranking = factors[(factors.index >= t) & (factors.index < (t + pd.DateOffset(months=3)))] funds_names = funds_evaluation_period.columns for f in funds_names : ### Regression on the PREVIOUS 3 months: Y = pd.DataFrame() Y["fund_excess_return"] = funds_evaluation_period[f] - factors_evaluation_period["Rf"] factors_evaluation_period.loc[:, "Market-Rf"] = factors_evaluation_period.loc[:,"TEPIX"].values - factors_evaluation_period.loc[:,"Rf"].values X = factors_evaluation_period[["Market-Rf", "SMB", "HML", "MOM"]] X = sm.add_constant(X) fitted_model = sm.OLS(Y["fund_excess_return"].astype(float), X.astype(float), missing='drop').fit() ### Regression on the Post-ranking quarter: Y2 = pd.DataFrame() Y2["fund_excess_return"] = funds_Post_ranking[f] - factors_Post_ranking["Rf"] factors_Post_ranking.loc[:, "Market-Rf"] = factors_Post_ranking.loc[:,"TEPIX"].values - factors_Post_ranking.loc[:,"Rf"].values X2 = factors_Post_ranking[["Market-Rf", "SMB", "HML", "MOM"]] X2 = sm.add_constant(X2) fitted_model2 = sm.OLS(Y2["fund_excess_return"].astype(float), X2.astype(float), missing='drop').fit() g = g.append({'Fund': f, 'Date': t, 'alpha': fitted_model.params[0], '5% significance': fitted_model.pvalues[0]<0.025, 'Post alpha': fitted_model2.params[0], 'Post 5% significance': fitted_model2.pvalues[0]<0.025}, ignore_index=True) # Sorting and recording the decile number: sorted_g = g.sort_values(by = 'alpha', ascending=False, ignore_index=True) i = 0 d = 1 groupSize = No//10 while i < No : sorted_g.loc[i, 'decile'] = d i += 1 if (i % groupSize) == 0 : d += 1 dfs.append(sorted_g) # Creating report table: decile_mean_alphas = sorted_g.groupby('decile')['alpha'].mean() decile_mean_Post_alphas = sorted_g.groupby('decile')['Post alpha'].mean() performance_deciles_Ranking_quarter_alpha = performance_deciles_Ranking_quarter_alpha.join( decile_mean_alphas, how='outer', lsuffix='_left', rsuffix='_right') performance_deciles_Post_ranking_alpha = performance_deciles_Post_ranking_alpha.join( decile_mean_Post_alphas, how='outer', lsuffix='_left', rsuffix='_right') alphas = pd.concat(dfs, ignore_index=True) # For the report: # Ranking quarter: performance_deciles_Ranking_quarter_alpha = performance_deciles_Ranking_quarter_alpha.mean(axis=1) performance_deciles_Ranking_quarter_alpha = 100* performance_deciles_Ranking_quarter_alpha # Post Ranking quarter: zero = np.zeros(performance_deciles_Post_ranking_alpha.shape[1]) pval = ttest_ind(performance_deciles_Post_ranking_alpha.T, zero)[1] performance_deciles_Post_ranking_alpha = performance_deciles_Post_ranking_alpha.mean(axis=1) performance_deciles_Post_ranking_alpha = 100* performance_deciles_Post_ranking_alpha performance_deciles_Post_ranking_alpha = performance_deciles_Post_ranking_alpha.to_frame('Mean') performance_deciles_Post_ranking_alpha.loc[:, "P-val"] = pval for i in performance_deciles_Post_ranking_alpha.index : if performance_deciles_Post_ranking_alpha.loc[i, "P-val"] <= 1 : #nothing performance_deciles_Post_ranking_alpha.loc[i, "significance"] = ' ' if performance_deciles_Post_ranking_alpha.loc[i, "P-val"] <= 0.05 : #10% performance_deciles_Post_ranking_alpha.loc[i, "significance"] = '*' if performance_deciles_Post_ranking_alpha.loc[i, "P-val"] <= 0.025 : #5% performance_deciles_Post_ranking_alpha.loc[i, "significance"] = ' ' if performance_deciles_Post_ranking_alpha.loc[i, "P-val"] <= 0.005 : #1% performance_deciles_Post_ranking_alpha.loc[i, "significance"] = '***' ########################################## 1.4 Total returns R = pd.DataFrame() performance_deciles_Ranking_quarter_R = pd.DataFrame() performance_deciles_Post_ranking_R = pd.DataFrame() dfs = [] for t in (pd.date_range(start_date_g, periods=Q, freq='Q') - pd.DateOffset(days = 8)) : # -8 to offset between j & g quarter start dates g = pd.DataFrame() # PREVIOUS 3 months: funds_evaluation_period = funds[(funds.index < t) & (funds.index >= (t - pd.DateOffset(months=3)))] # Post-ranking quarter: funds_Post_ranking = funds[(funds.index >= t) & (funds.index < (t + pd.DateOffset(months=3)))] funds_names = funds_evaluation_period.columns for f in funds_names : g = g.append({'Fund': f, 'Date': t, 'R': funds_evaluation_period[f].mean(), 'Post R': funds_Post_ranking[f].mean()}, ignore_index=True) # Sorting and recording the decile number: sorted_g = g.sort_values(by = 'R', ascending=False, ignore_index=True) i = 0 d = 1 groupSize = No//10 while i < No : sorted_g.loc[i, 'decile'] = d i += 1 if (i % groupSize) == 0 : d += 1 dfs.append(sorted_g) # Creating report table: decile_mean_R = sorted_g.groupby('decile')['R'].mean() decile_mean_Post_R = sorted_g.groupby('decile')['Post R'].mean() performance_deciles_Ranking_quarter_R = performance_deciles_Ranking_quarter_R.join( decile_mean_R, how='outer', lsuffix='_left', rsuffix='_right') performance_deciles_Post_ranking_R = performance_deciles_Post_ranking_R.join( decile_mean_Post_R, how='outer', lsuffix='_left', rsuffix='_right') R = pd.concat(dfs, ignore_index=True) # For the report: # Ranking quarter: performance_deciles_Ranking_quarter_R = performance_deciles_Ranking_quarter_R.mean(axis=1) performance_deciles_Ranking_quarter_R = 100* performance_deciles_Ranking_quarter_R # Post Ranking quarter: performance_deciles_Post_ranking_R = performance_deciles_Post_ranking_R.mean(axis=1) performance_deciles_Post_ranking_R = 100* performance_deciles_Post_ranking_R ########################################## 1.2 Market timing # Method 1: Treynor and Mazuy (TM) TM = pd.DataFrame() performance_deciles_Ranking_quarter_TM = pd.DataFrame() performance_deciles_Post_ranking_TM = pd.DataFrame() dfs = [] for t in (pd.date_range(start_date_g, periods=Q, freq='Q') - pd.DateOffset(days = 8)) : g = pd.DataFrame() # PREVIOUS 3 months: funds_evaluation_period = funds[(funds.index < t) & (funds.index >= (t - pd.DateOffset(months=3)))] factors_evaluation_period = factors[(factors.index < t) & (factors.index >= (t - pd.DateOffset(months=3)))] # Post-ranking quarter: funds_Post_ranking = funds[(funds.index >= t) & (funds.index < (t + pd.DateOffset(months=3)))] factors_Post_ranking = factors[(factors.index >= t) & (factors.index < (t + pd.DateOffset(months=3)))] N = factors_evaluation_period.shape[0] funds_names = funds_evaluation_period.columns for f in funds_names : # Regression on the PREVIOUS 3 months: Y = pd.DataFrame() Y["fund_excess_return"] = funds_evaluation_period[f] - factors_evaluation_period["Rf"] factors_evaluation_period.loc[:, "Market-Rf"] = factors_evaluation_period.loc[:,"TEPIX"].values - factors_evaluation_period.loc[:,"Rf"].values factors_evaluation_period["(Market-Rf)^2"] = factors_evaluation_period["Market-Rf"]**2 X = factors_evaluation_period[["Market-Rf", "(Market-Rf)^2", "SMB", "HML", "MOM"]] X = sm.add_constant(X) fitted_model = sm.OLS(Y["fund_excess_return"].astype(float), X.astype(float), missing='drop').fit() r = fitted_model.params[0] + fitted_model.params[2] * (factors_evaluation_period["(Market-Rf)^2"].sum()) * (1/N) # Regression on the Post-ranking quarter: Y2 = pd.DataFrame() Y2["fund_excess_return"] = funds_Post_ranking[f] - factors_Post_ranking["Rf"] factors_Post_ranking.loc[:, "Market-Rf"] = factors_Post_ranking.loc[:,"TEPIX"].values - factors_Post_ranking.loc[:,"Rf"].values factors_Post_ranking["(Market-Rf)^2"] = factors_Post_ranking["Market-Rf"]**2 X2 = factors_Post_ranking[["Market-Rf", "(Market-Rf)^2", "SMB", "HML", "MOM"]] X2 = sm.add_constant(X2) fitted_model2 = sm.OLS(Y2["fund_excess_return"].astype(float), X2.astype(float), missing='drop').fit() r2 = fitted_model2.params[0] + fitted_model2.params[2] * (factors_Post_ranking["(Market-Rf)^2"].sum()) * (1/N) g = g.append({'Fund': f, 'Date': t, 'alpha': fitted_model.params[0], 'lambda': fitted_model.params[2], '5% significance of lambda': fitted_model.pvalues[2]<0.025, 'r': r, 'Post alpha': fitted_model2.params[0], 'Post lambda': fitted_model2.params[2], 'Post 5% significance of lambda': fitted_model2.pvalues[2]<0.025, 'Post r': r2,}, ignore_index=True) # Sorting and recording the decile number: sorted_g = g.sort_values(by = 'r', ascending=False, ignore_index=True) i = 0 d = 1 groupSize = No//10 while i < No : sorted_g.loc[i, 'decile'] = d i += 1 if (i % groupSize) == 0 : d += 1 dfs.append(sorted_g) # Creating report table: decile_means = sorted_g.groupby('decile')['r'].mean() decile_means_post = sorted_g.groupby('decile')['Post r'].mean() performance_deciles_Ranking_quarter_TM = performance_deciles_Ranking_quarter_TM.join( decile_means, how='outer', lsuffix='_left', rsuffix='_right') performance_deciles_Post_ranking_TM = performance_deciles_Post_ranking_TM.join( decile_means_post, how='outer', lsuffix='_left', rsuffix='_right') TM = pd.concat(dfs, ignore_index=True) # For the report: # Ranking quarter: performance_deciles_Ranking_quarter_TM = performance_deciles_Ranking_quarter_TM.mean(axis=1) performance_deciles_Ranking_quarter_TM = 100 * performance_deciles_Ranking_quarter_TM # Post Ranking quarter: zero = np.zeros(performance_deciles_Post_ranking_TM.shape[1]) pval = ttest_ind(performance_deciles_Post_ranking_TM.T, zero)[1] performance_deciles_Post_ranking_TM = performance_deciles_Post_ranking_TM.mean(axis=1) performance_deciles_Post_ranking_TM = 100* performance_deciles_Post_ranking_TM performance_deciles_Post_ranking_TM = performance_deciles_Post_ranking_TM.to_frame('Mean') performance_deciles_Post_ranking_TM.loc[:, "P-val"] = pval for i in performance_deciles_Post_ranking_TM.index : if performance_deciles_Post_ranking_TM.loc[i, "P-val"] <= 1 : #nothing performance_deciles_Post_ranking_TM.loc[i, "significance"] = '*' if performance_deciles_Post_ranking_TM.loc[i, "P-val"] <= 0.05 : #10% performance_deciles_Post_ranking_TM.loc[i, "significance"] = '*' if performance_deciles_Post_ranking_TM.loc[i, "P-val"] <= 0.025 : #5% performance_deciles_Post_ranking_TM.loc[i, "significance"] = '**' if performance_deciles_Post_ranking_TM.loc[i, "P-val"] <= 0.005 : #1% performance_deciles_Post_ranking_TM.loc[i, "significance"] = '***' ### Method 2: Henriksson and Merton (HM) HM = pd.DataFrame() performance_deciles_Ranking_quarter_HM = pd.DataFrame() performance_deciles_Post_ranking_HM = pd.DataFrame() dfs = [] for t in (pd.date_range(start_date_g, periods=Q, freq='Q') - pd.DateOffset(days = 8)) : g = pd.DataFrame() # PREVIOUS 3 months: funds_evaluation_period = funds[(funds.index < t) & (funds.index >= (t - pd.DateOffset(months=3)))] factors_evaluation_period = factors[(factors.index < t) & (factors.index >= (t - pd.DateOffset(months=3)))] # Post-ranking quarter: funds_Post_ranking = funds[(funds.index >= t) & (funds.index < (t + pd.DateOffset(months=3)))] factors_Post_ranking = factors[(factors.index >= t) & (factors.index < (t + pd.DateOffset(months=3)))] N = factors_evaluation_period.shape[0] funds_names = funds_evaluation_period.columns for f in funds_names : # Regression on the previous 3 months: Y = pd.DataFrame() Y["fund_excess_return"] = funds_evaluation_period[f] - factors_evaluation_period["Rf"] factors_evaluation_period.loc[:, "Market-Rf"] = factors_evaluation_period.loc[:,"TEPIX"].values - factors_evaluation_period.loc[:,"Rf"].values factors_evaluation_period["(Market-Rf)>0"] = factors_evaluation_period["Market-Rf"] * pd.Series(factors_evaluation_period["Market-Rf"]>0).astype(int) X = factors_evaluation_period[["Market-Rf", "(Market-Rf)>0", "SMB", "HML", "MOM"]] X = sm.add_constant(X) fitted_model = sm.OLS(Y["fund_excess_return"].astype(float), X.astype(float), missing='drop').fit() r = fitted_model.params[0] + fitted_model.params[2] * (factors_evaluation_period["(Market-Rf)>0"].sum()) * (1/N) # Regression on the Post-ranking quarter: Y2 = pd.DataFrame() Y2["fund_excess_return"] = funds_Post_ranking[f] - factors_Post_ranking["Rf"] factors_Post_ranking.loc[:, "Market-Rf"] = factors_Post_ranking.loc[:,"TEPIX"].values - factors_Post_ranking.loc[:,"Rf"].values factors_Post_ranking["(Market-Rf)>0"] = factors_Post_ranking["Market-Rf"] * pd.Series(factors_Post_ranking["Market-Rf"]>0).astype(int) X2 = factors_Post_ranking[["Market-Rf", "(Market-Rf)>0", "SMB", "HML", "MOM"]] X2 = sm.add_constant(X2) fitted_model2 = sm.OLS(Y2["fund_excess_return"].astype(float), X2.astype(float), missing='drop').fit() r2 = fitted_model2.params[0] + fitted_model2.params[2] * (factors_Post_ranking["(Market-Rf)>0"].sum()) * (1/N) g = g.append({'Fund': f, 'Date': t, 'alpha': fitted_model.params[0], 'lambda': fitted_model.params[2], '5% significance of lambda': fitted_model.pvalues[2]<0.025, 'r': r, 'Post alpha': fitted_model2.params[0], 'Post lambda': fitted_model2.params[2], 'Post 5% significance of lambda': fitted_model2.pvalues[2]<0.025, 'Post r': r2,}, ignore_index=True) # Sorting and recording the decile number: sorted_g = g.sort_values(by = 'r', ascending=False, ignore_index=True) i = 0 d = 1 groupSize = No//10 while i < No : sorted_g.loc[i,
SINGLE_LIST_ENTRY() self.VerifierContext = v_ptr64() self.KernelStackReference = v_uint32() self._pad0758 = v_bytes(size=4) self.AdjustedClientToken = v_ptr64() self.UserFsBase = v_uint32() self._pad0768 = v_bytes(size=4) self.UserGsBase = v_uint64() self.PicoContext = v_ptr64() class PROCESS_DISK_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.BytesRead = v_uint64() self.BytesWritten = v_uint64() self.ReadOperationCount = v_uint64() self.WriteOperationCount = v_uint64() self.FlushOperationCount = v_uint64() class _unnamed_10667(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.CommittedSize = v_uint32() self.UnCommittedSize = v_uint32() self.FirstEntry = v_ptr64() self.LastEntry = v_ptr64() class _unnamed_10666(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Settable = v_uint64() self.TagIndex = v_uint16() self.AllocatorBackTraceIndex = v_uint16() self.Reserved = vstruct.VArray([ v_uint32() for i in xrange(2) ]) self._pad0018 = v_bytes(size=4) class RTL_BITMAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SizeOfBitMap = v_uint32() self._pad0008 = v_bytes(size=4) self.Buffer = v_ptr64() class LARGE_INTEGER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.LowPart = v_uint32() self.HighPart = v_uint32() class _unnamed_9296(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UserApcRoutine = v_ptr64() self.UserApcContext = v_ptr64() class NPAGED_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.L = GENERAL_LOOKASIDE() class CLIENT_ID32(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.UniqueProcess = v_uint32() self.UniqueThread = v_uint32() class VPB(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Type = v_uint16() self.Size = v_uint16() self.Flags = v_uint16() self.VolumeLabelLength = v_uint16() self.DeviceObject = v_ptr64() self.RealDevice = v_ptr64() self.SerialNumber = v_uint32() self.ReferenceCount = v_uint32() self.VolumeLabel = vstruct.VArray([ v_uint16() for i in xrange(32) ]) class _unnamed_9593(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.InterfaceType = v_ptr64() self.Size = v_uint16() self.Version = v_uint16() self._pad0010 = v_bytes(size=4) self.Interface = v_ptr64() self.InterfaceSpecificData = v_ptr64() class PP_LOOKASIDE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.P = v_ptr64() self.L = v_ptr64() class _unnamed_9546(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SecurityInformation = v_uint32() self._pad0008 = v_bytes(size=4) self.SecurityDescriptor = v_ptr64() class JOBOBJECT_WAKE_FILTER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.HighEdgeFilter = v_uint32() self.LowEdgeFilter = v_uint32() class OBJECT_NAME_INFORMATION(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Name = UNICODE_STRING() class IO_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Version = v_uint16() self.Revision = v_uint16() self.Count = v_uint32() self.Descriptors = vstruct.VArray([ IO_RESOURCE_DESCRIPTOR() for i in xrange(1) ]) class KUSER_SHARED_DATA(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.TickCountLowDeprecated = v_uint32() self.TickCountMultiplier = v_uint32() self.InterruptTime = KSYSTEM_TIME() self.SystemTime = KSYSTEM_TIME() self.TimeZoneBias = KSYSTEM_TIME() self.ImageNumberLow = v_uint16() self.ImageNumberHigh = v_uint16() self.NtSystemRoot = vstruct.VArray([ v_uint16() for i in xrange(260) ]) self.MaxStackTraceDepth = v_uint32() self.CryptoExponent = v_uint32() self.TimeZoneId = v_uint32() self.LargePageMinimum = v_uint32() self.AitSamplingValue = v_uint32() self.AppCompatFlag = v_uint32() self.RNGSeedVersion = v_uint64() self.GlobalValidationRunlevel = v_uint32() self.TimeZoneBiasStamp = v_uint32() self.Reserved2 = v_uint32() self.NtProductType = v_uint32() self.ProductTypeIsValid = v_uint8() self.Reserved0 = vstruct.VArray([ v_uint8() for i in xrange(1) ]) self.NativeProcessorArchitecture = v_uint16() self.NtMajorVersion = v_uint32() self.NtMinorVersion = v_uint32() self.ProcessorFeatures = vstruct.VArray([ v_uint8() for i in xrange(64) ]) self.Reserved1 = v_uint32() self.Reserved3 = v_uint32() self.TimeSlip = v_uint32() self.AlternativeArchitecture = v_uint32() self.AltArchitecturePad = vstruct.VArray([ v_uint32() for i in xrange(1) ]) self.SystemExpirationDate = LARGE_INTEGER() self.SuiteMask = v_uint32() self.KdDebuggerEnabled = v_uint8() self.MitigationPolicies = v_uint8() self.Reserved6 = vstruct.VArray([ v_uint8() for i in xrange(2) ]) self.ActiveConsoleId = v_uint32() self.DismountCount = v_uint32() self.ComPlusPackage = v_uint32() self.LastSystemRITEventTickCount = v_uint32() self.NumberOfPhysicalPages = v_uint32() self.SafeBootMode = v_uint8() self.Reserved12 = vstruct.VArray([ v_uint8() for i in xrange(3) ]) self.SharedDataFlags = v_uint32() self.DataFlagsPad = vstruct.VArray([ v_uint32() for i in xrange(1) ]) self.TestRetInstruction = v_uint64() self.QpcFrequency = v_uint64() self.SystemCallPad = vstruct.VArray([ v_uint64() for i in xrange(3) ]) self.TickCount = KSYSTEM_TIME() self.TickCountPad = vstruct.VArray([ v_uint32() for i in xrange(1) ]) self.Cookie = v_uint32() self.CookiePad = vstruct.VArray([ v_uint32() for i in xrange(1) ]) self.ConsoleSessionForegroundProcessId = v_uint64() self.TimeUpdateLock = v_uint64() self.BaselineSystemTimeQpc = v_uint64() self.BaselineInterruptTimeQpc = v_uint64() self.QpcSystemTimeIncrement = v_uint64() self.QpcInterruptTimeIncrement = v_uint64() self.QpcSystemTimeIncrement32 = v_uint32() self.QpcInterruptTimeIncrement32 = v_uint32() self.QpcSystemTimeIncrementShift = v_uint8() self.QpcInterruptTimeIncrementShift = v_uint8() self.UnparkedProcessorCount = v_uint16() self.Reserved8 = vstruct.VArray([ v_uint8() for i in xrange(12) ]) self.UserModeGlobalLogger = vstruct.VArray([ v_uint16() for i in xrange(16) ]) self.ImageFileExecutionOptions = v_uint32() self.LangGenerationCount = v_uint32() self.Reserved4 = v_uint64() self.InterruptTimeBias = v_uint64() self.QpcBias = v_uint64() self.ActiveProcessorCount = v_uint32() self.ActiveGroupCount = v_uint8() self.Reserved9 = v_uint8() self.QpcData = v_uint16() self.TimeZoneBiasEffectiveStart = LARGE_INTEGER() self.TimeZoneBiasEffectiveEnd = LARGE_INTEGER() self.XState = XSTATE_CONFIGURATION() class SYSTEM_POWER_STATE_CONTEXT(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Reserved1 = v_uint32() class SYNCH_COUNTERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.SpinLockAcquireCount = v_uint32() self.SpinLockContentionCount = v_uint32() self.SpinLockSpinCount = v_uint32() self.IpiSendRequestBroadcastCount = v_uint32() self.IpiSendRequestRoutineCount = v_uint32() self.IpiSendSoftwareInterruptCount = v_uint32() self.ExInitializeResourceCount = v_uint32() self.ExReInitializeResourceCount = v_uint32() self.ExDeleteResourceCount = v_uint32() self.ExecutiveResourceAcquiresCount = v_uint32() self.ExecutiveResourceContentionsCount = v_uint32() self.ExecutiveResourceReleaseExclusiveCount = v_uint32() self.ExecutiveResourceReleaseSharedCount = v_uint32() self.ExecutiveResourceConvertsCount = v_uint32() self.ExAcqResExclusiveAttempts = v_uint32() self.ExAcqResExclusiveAcquiresExclusive = v_uint32() self.ExAcqResExclusiveAcquiresExclusiveRecursive = v_uint32() self.ExAcqResExclusiveWaits = v_uint32() self.ExAcqResExclusiveNotAcquires = v_uint32() self.ExAcqResSharedAttempts = v_uint32() self.ExAcqResSharedAcquiresExclusive = v_uint32() self.ExAcqResSharedAcquiresShared = v_uint32() self.ExAcqResSharedAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaits = v_uint32() self.ExAcqResSharedNotAcquires = v_uint32() self.ExAcqResSharedStarveExclusiveAttempts = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedStarveExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedStarveExclusiveWaits = v_uint32() self.ExAcqResSharedStarveExclusiveNotAcquires = v_uint32() self.ExAcqResSharedWaitForExclusiveAttempts = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresExclusive = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresShared = v_uint32() self.ExAcqResSharedWaitForExclusiveAcquiresSharedRecursive = v_uint32() self.ExAcqResSharedWaitForExclusiveWaits = v_uint32() self.ExAcqResSharedWaitForExclusiveNotAcquires = v_uint32() self.ExSetResOwnerPointerExclusive = v_uint32() self.ExSetResOwnerPointerSharedNew = v_uint32() self.ExSetResOwnerPointerSharedOld = v_uint32() self.ExTryToAcqExclusiveAttempts = v_uint32() self.ExTryToAcqExclusiveAcquires = v_uint32() self.ExBoostExclusiveOwner = v_uint32() self.ExBoostSharedOwners = v_uint32() self.ExEtwSynchTrackingNotificationsCount = v_uint32() self.ExEtwSynchTrackingNotificationsAccountedCount = v_uint32() class FS_FILTER_PARAMETERS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.AcquireForModifiedPageWriter = _unnamed_12019() self._pad0028 = v_bytes(size=24) class HEAP(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Entry = HEAP_ENTRY() self.SegmentSignature = v_uint32() self.SegmentFlags = v_uint32() self.SegmentListEntry = LIST_ENTRY() self.Heap = v_ptr64() self.BaseAddress = v_ptr64() self.NumberOfPages = v_uint32() self._pad0040 = v_bytes(size=4) self.FirstEntry = v_ptr64() self.LastValidEntry = v_ptr64() self.NumberOfUnCommittedPages = v_uint32() self.NumberOfUnCommittedRanges = v_uint32() self.SegmentAllocatorBackTraceIndex = v_uint16() self.Reserved = v_uint16() self._pad0060 = v_bytes(size=4) self.UCRSegmentList = LIST_ENTRY() self.Flags = v_uint32() self.ForceFlags = v_uint32() self.CompatibilityFlags = v_uint32() self.EncodeFlagMask = v_uint32() self.Encoding = HEAP_ENTRY() self.Interceptor = v_uint32() self.VirtualMemoryThreshold = v_uint32() self.Signature = v_uint32() self._pad00a0 = v_bytes(size=4) self.SegmentReserve = v_uint64() self.SegmentCommit = v_uint64() self.DeCommitFreeBlockThreshold = v_uint64() self.DeCommitTotalFreeThreshold = v_uint64() self.TotalFreeSize = v_uint64() self.MaximumAllocationSize = v_uint64() self.ProcessHeapsListIndex = v_uint16() self.HeaderValidateLength = v_uint16() self._pad00d8 = v_bytes(size=4) self.HeaderValidateCopy = v_ptr64() self.NextAvailableTagIndex = v_uint16() self.MaximumTagIndex = v_uint16() self._pad00e8 = v_bytes(size=4) self.TagEntries = v_ptr64() self.UCRList = LIST_ENTRY() self.AlignRound = v_uint64() self.AlignMask = v_uint64() self.VirtualAllocdBlocks = LIST_ENTRY() self.SegmentList = LIST_ENTRY() self.AllocatorBackTraceIndex = v_uint16() self._pad0134 = v_bytes(size=2) self.NonDedicatedListLength = v_uint32() self.BlocksIndex = v_ptr64() self.UCRIndex = v_ptr64() self.PseudoTagEntries = v_ptr64() self.FreeLists = LIST_ENTRY() self.LockVariable = v_ptr64() self.CommitRoutine = v_ptr64() self.FrontEndHeap = v_ptr64() self.FrontHeapLockCount = v_uint16() self.FrontEndHeapType = v_uint8() self.RequestedFrontEndHeapType = v_uint8() self._pad0180 = v_bytes(size=4) self.FrontEndHeapUsageData = v_ptr64() self.FrontEndHeapMaximumIndex = v_uint16() self.FrontEndHeapStatusBitmap = vstruct.VArray([ v_uint8() for i in xrange(129) ]) self._pad0210 = v_bytes(size=5) self.Counters = HEAP_COUNTERS() self.TuningParameters = HEAP_TUNING_PARAMETERS() class IO_STATUS_BLOCK(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Status = v_uint32() self._pad0008 = v_bytes(size=4) self.Information = v_uint64() class _unnamed_12664(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Length64 = v_uint32() self.Alignment64 = v_uint32() self.MinimumAddress = LARGE_INTEGER() self.MaximumAddress = LARGE_INTEGER() class CM_RESOURCE_LIST(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Count = v_uint32() self.List = vstruct.VArray([ CM_FULL_RESOURCE_DESCRIPTOR() for i in xrange(1) ]) class WNF_STATE_NAME(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Data = vstruct.VArray([ v_uint32() for i in xrange(2) ]) class EPROCESS(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.Pcb = KPROCESS() self.ProcessLock = EX_PUSH_LOCK() self.CreateTime = LARGE_INTEGER() self.RundownProtect = EX_RUNDOWN_REF() self.UniqueProcessId = v_ptr64() self.ActiveProcessLinks = LIST_ENTRY() self.Flags2 = v_uint32() self.Flags = v_uint32() self.ProcessQuotaUsage = vstruct.VArray([ v_uint64() for i in xrange(2) ]) self.ProcessQuotaPeak = vstruct.VArray([ v_uint64() for i in xrange(2) ]) self.PeakVirtualSize = v_uint64() self.VirtualSize = v_uint64() self.SessionProcessLinks = LIST_ENTRY() self.ExceptionPortData = v_ptr64() self.Token = EX_FAST_REF() self.WorkingSetPage = v_uint64() self.AddressCreationLock = EX_PUSH_LOCK() self.PageTableCommitmentLock = EX_PUSH_LOCK() self.RotateInProgress = v_ptr64() self.ForkInProgress = v_ptr64() self.CommitChargeJob = v_ptr64() self.CloneRoot = RTL_AVL_TREE() self.NumberOfPrivatePages = v_uint64() self.NumberOfLockedPages = v_uint64() self.Win32Process = v_ptr64() self.Job = v_ptr64() self.SectionObject = v_ptr64() self.SectionBaseAddress = v_ptr64() self.Cookie = v_uint32() self._pad03c0 = v_bytes(size=4) self.WorkingSetWatch = v_ptr64() self.Win32WindowStation = v_ptr64() self.InheritedFromUniqueProcessId = v_ptr64() self.LdtInformation = v_ptr64() self.OwnerProcessId = v_uint64() self.Peb = v_ptr64() self.Session = v_ptr64() self.AweInfo = v_ptr64() self.QuotaBlock = v_ptr64() self.ObjectTable = v_ptr64() self.DebugPort = v_ptr64() self.Wow64Process = v_ptr64() self.DeviceMap = v_ptr64() self.EtwDataSource = v_ptr64() self.PageDirectoryPte = v_uint64() self.ImageFileName = vstruct.VArray([ v_uint8() for i in xrange(15) ]) self.PriorityClass = v_uint8() self.SecurityPort = v_ptr64() self.SeAuditProcessCreationInfo = SE_AUDIT_PROCESS_CREATION_INFO() self.JobLinks = LIST_ENTRY() self.HighestUserAddress = v_ptr64() self.ThreadListHead = LIST_ENTRY() self.ActiveThreads = v_uint32() self.ImagePathHash = v_uint32() self.DefaultHardErrorProcessing = v_uint32() self.LastThreadExitStatus = v_uint32() self.PrefetchTrace = EX_FAST_REF() self.LockedPagesList = v_ptr64() self.ReadOperationCount = LARGE_INTEGER() self.WriteOperationCount = LARGE_INTEGER() self.OtherOperationCount = LARGE_INTEGER() self.ReadTransferCount = LARGE_INTEGER() self.WriteTransferCount = LARGE_INTEGER() self.OtherTransferCount = LARGE_INTEGER() self.CommitCharge = v_uint64() self.Vm = MMSUPPORT() self.MmProcessLinks = LIST_ENTRY() self.ModifiedPageCount = v_uint32() self.ExitStatus = v_uint32() self.VadRoot = RTL_AVL_TREE() self.VadHint = v_ptr64() self.VadCount = v_uint64() self.VadPhysicalPages = v_uint64() self.VadPhysicalPagesLimit = v_uint64() self.AlpcContext = ALPC_PROCESS_CONTEXT() self.TimerResolutionLink = LIST_ENTRY() self.TimerResolutionStackRecord = v_ptr64() self.RequestedTimerResolution = v_uint32() self.SmallestTimerResolution = v_uint32() self.ExitTime = LARGE_INTEGER() self.InvertedFunctionTable = v_ptr64() self.InvertedFunctionTableLock = EX_PUSH_LOCK() self.ActiveThreadsHighWatermark = v_uint32() self.LargePrivateVadCount = v_uint32() self.ThreadListLock = EX_PUSH_LOCK() self.WnfContext = v_ptr64() self.Spare0 = v_uint64() self.SignatureLevel = v_uint8() self.SectionSignatureLevel = v_uint8() self.Protection = PS_PROTECTION() self.SpareByte20 = vstruct.VArray([ v_uint8() for i in xrange(1) ])
# Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Arnold to RadeonProRender Converter import maya.mel as mel import maya.cmds as cmds import time import os import math import traceback # log functions def write_converted_property_log(rpr_name, ai_name, rpr_attr, ai_attr): try: file_path = cmds.file(q=True, sceneName=True) + ".log" with open(file_path, 'a') as f: f.write(u" property {}.{} is converted to {}.{} \r\n".format(ai_name, ai_attr, rpr_name, rpr_attr).encode('utf-8')) except: pass def write_own_property_log(text): try: file_path = cmds.file(q=True, sceneName=True) + ".log" with open(file_path, 'a') as f: f.write(" {} \r\n".format(text)) except: pass def start_log(ai, rpr): try: text = u"Found node: \r\n name: {} \r\n".format(ai).encode('utf-8') text += "type: {} \r\n".format(cmds.objectType(ai)) text += u"Converting to: \r\n name: {} \r\n".format(rpr).encode('utf-8') text += "type: {} \r\n".format(cmds.objectType(rpr)) text += "Conversion details: \r\n" file_path = cmds.file(q=True, sceneName=True) + ".log" with open(file_path, 'a') as f: f.write(text) except: pass def end_log(ai): try: text = u"Conversion of {} is finished.\n\n \r\n".format(ai).encode('utf-8') file_path = cmds.file(q=True, sceneName=True) + ".log" with open(file_path, 'a') as f: f.write(text) except: pass # additional fucntions # copy from 3rd party engine to rpr def copyProperty(rpr_name, conv_name, rpr_attr, conv_attr): # full name of attribute conv_field = conv_name + "." + conv_attr rpr_field = rpr_name + "." + rpr_attr ai_type = type(getProperty(conv_name, conv_attr)) rpr_type = type(getProperty(rpr_name, rpr_attr)) try: listConnections = cmds.listConnections(conv_field) # connection convert if listConnections and cmds.objectType(listConnections[0]) != "transform": obj, channel = cmds.connectionInfo(conv_field, sourceFromDestination=True).split('.') source_name, source_attr = convertMaterial(obj, channel).split('.') connectProperty(source_name, source_attr, rpr_name, rpr_attr) # complex color conversion for each channel (RGB/XYZ/HSV) elif not listConnections and rpr_type == ai_type == tuple: # RGB if cmds.objExists(conv_field + "R") and cmds.objExists(rpr_field + "R"): copyProperty(rpr_name, conv_name, rpr_attr + "R", conv_attr + "R") copyProperty(rpr_name, conv_name, rpr_attr + "G", conv_attr + "G") copyProperty(rpr_name, conv_name, rpr_attr + "B", conv_attr + "B") elif cmds.objExists(conv_field + "R") and cmds.objExists(rpr_field + "X"): copyProperty(rpr_name, conv_name, rpr_attr + "X", conv_attr + "R") copyProperty(rpr_name, conv_name, rpr_attr + "Y", conv_attr + "G") copyProperty(rpr_name, conv_name, rpr_attr + "Z", conv_attr + "B") elif cmds.objExists(conv_field + "R") and cmds.objExists(rpr_field + "H"): copyProperty(rpr_name, conv_name, rpr_attr + "H", conv_attr + "R") copyProperty(rpr_name, conv_name, rpr_attr + "S", conv_attr + "G") copyProperty(rpr_name, conv_name, rpr_attr + "V", conv_attr + "B") # XYZ elif cmds.objExists(conv_field + "X") and cmds.objExists(rpr_field + "R"): copyProperty(rpr_name, conv_name, rpr_attr + "R", conv_attr + "X") copyProperty(rpr_name, conv_name, rpr_attr + "G", conv_attr + "Y") copyProperty(rpr_name, conv_name, rpr_attr + "B", conv_attr + "Z") elif cmds.objExists(conv_field + "X") and cmds.objExists(rpr_field + "X"): copyProperty(rpr_name, conv_name, rpr_attr + "X", conv_attr + "X") copyProperty(rpr_name, conv_name, rpr_attr + "Y", conv_attr + "Y") copyProperty(rpr_name, conv_name, rpr_attr + "Z", conv_attr + "Z") elif cmds.objExists(conv_field + "X") and cmds.objExists(rpr_field + "H"): copyProperty(rpr_name, conv_name, rpr_attr + "H", conv_attr + "X") copyProperty(rpr_name, conv_name, rpr_attr + "S", conv_attr + "Y") copyProperty(rpr_name, conv_name, rpr_attr + "V", conv_attr + "Z") # HSV elif cmds.objExists(conv_field + "H") and cmds.objExists(rpr_field + "R"): copyProperty(rpr_name, conv_name, rpr_attr + "R", conv_attr + "H") copyProperty(rpr_name, conv_name, rpr_attr + "G", conv_attr + "S") copyProperty(rpr_name, conv_name, rpr_attr + "B", conv_attr + "V") elif cmds.objExists(conv_field + "H") and cmds.objExists(rpr_field + "X"): copyProperty(rpr_name, conv_name, rpr_attr + "X", conv_attr + "H") copyProperty(rpr_name, conv_name, rpr_attr + "Y", conv_attr + "S") copyProperty(rpr_name, conv_name, rpr_attr + "Z", conv_attr + "V") elif cmds.objExists(conv_field + "H") and cmds.objExists(rpr_field + "H"): copyProperty(rpr_name, conv_name, rpr_attr + "H", conv_attr + "H") copyProperty(rpr_name, conv_name, rpr_attr + "S", conv_attr + "S") copyProperty(rpr_name, conv_name, rpr_attr + "V", conv_attr + "V") else: print("[ERROR] Failed to find right variant for {}.{} conversion".format(conv_name, conv_attr)) # field conversion else: if ai_type == rpr_type or ai_type == unicode: setProperty(rpr_name, rpr_attr, getProperty(conv_name, conv_attr)) elif ai_type == tuple and rpr_type == float: if cmds.objExists(conv_field + "R"): conv_attr += "R" elif cmds.objExists(conv_field + "X"): conv_attr += "X" elif cmds.objExists(conv_field + "H"): conv_attr += "H" setProperty(rpr_name, rpr_attr, getProperty(conv_name, conv_attr)) elif ai_type == float and rpr_type == tuple: if cmds.objExists(rpr_field + "R"): rpr_attr1 = rpr_attr + "R" rpr_attr2 = rpr_attr + "G" rpr_attr3 = rpr_attr + "B" elif cmds.objExists(rpr_field + "X"): rpr_attr1 = rpr_attr + "X" rpr_attr2 = rpr_attr + "Y" rpr_attr3 = rpr_attr + "Z" elif cmds.objExists(conv_field + "H"): rpr_attr1 = rpr_attr + "H" rpr_attr2 = rpr_attr + "S" rpr_attr3 = rpr_attr + "V" setProperty(rpr_name, rpr_attr1, getProperty(conv_name, conv_attr)) setProperty(rpr_name, rpr_attr2, getProperty(conv_name, conv_attr)) setProperty(rpr_name, rpr_attr3, getProperty(conv_name, conv_attr)) write_converted_property_log(rpr_name, conv_name, rpr_attr, conv_attr) except Exception as ex: traceback.print_exc() print(u"[ERROR] Failed to copy parameters from {} to {}".format(conv_field, rpr_field).encode('utf-8')) write_own_property_log(u"[ERROR] Failed to copy parameters from {} to {}".format(conv_field, rpr_field).encode('utf-8')) def setProperty(rpr_name, rpr_attr, value): # full name of attribute rpr_field = rpr_name + "." + rpr_attr try: # break existed connection if not mapDoesNotExist(rpr_name, rpr_attr): source = cmds.connectionInfo(rpr_field, sourceFromDestination=True) cmds.disconnectAttr(source, rpr_field) if type(value) == tuple: cmds.setAttr(rpr_field, value[0], value[1], value[2]) elif type(value) == str or type(value) == unicode: cmds.setAttr(rpr_field, value, type="string") else: cmds.setAttr(rpr_field, value) write_own_property_log(u"Set value {} to {}.".format(value, rpr_field).encode('utf-8')) except Exception as ex: traceback.print_exc() print(u"[ERROR] Set value {} to {} is failed. Check the values and their boundaries. ".format(value, rpr_field).encode('utf-8')) write_own_property_log(u"[ERROR] Set value {} to {} is failed. Check the values and their boundaries. ".format(value, rpr_field).encode('utf-8')) def getProperty(material, attr, size=False): # full name of attribute field = material + "." + attr try: if size: value = cmds.getAttr(field, size=True) else: value = cmds.getAttr(field) # used for color. it has [(),(),()] structure. if type(value) == list: value = value[0] except Exception as ex: print(u"[ERROR] Failed to get information about {} field in {} node.".format(attr, material).encode('utf-8')) write_own_property_log(u"[ERROR] Failed to get information about {} field in {} node.".format(attr, material).encode('utf-8')) return return value def mapDoesNotExist(rs_name, rs_attr): # full name of attribute rs_field = rs_name + "." + rs_attr try: if cmds.listConnections(rs_field): return 0 elif cmds.objExists(rs_field + "R"): if cmds.listConnections(rs_field + "R") or cmds.listConnections(rs_field + "G") or cmds.listConnections(rs_field + "B"): return 0 elif cmds.objExists(rs_field + "X"): if cmds.listConnections(rs_field + "X") or cmds.listConnections(rs_field + "Y") or cmds.listConnections(rs_field + "Z"): return 0 elif cmds.objExists(rs_field + "H"): if cmds.listConnections(rs_field + "H") or cmds.listConnections(rs_field + "S") or cmds.listConnections(rs_field + "V"): return 0 except Exception as ex: traceback.print_exc() print(u"[ERROR] There is no {} field in this node. Check the field and try again. ".format(rs_field).encode('utf-8')) write_own_property_log(u"[ERROR] There is no {} field in this node. Check the field and try again. ".format(rs_field).encode('utf-8')) return return 1 def connectProperty(source_name, source_attr, rpr_name, rpr_attr): # full name of attribute source = source_name + "." + source_attr rpr_field = rpr_name + "." + rpr_attr try: source_type = type(getProperty(source_name, source_attr)) dest_type = type(getProperty(rpr_name, rpr_attr)) if rpr_attr in ("surfaceShader", "volumeShader"): cmds.connectAttr(source, rpr_field, force=True) elif cmds.objExists(source_name + ".outAlpha") and cmds.objExists(source_name + ".outColor"): if cmds.objectType(source_name) == "file": setProperty(source_name, "ignoreColorSpaceFileRules", 1) if source_type == dest_type: cmds.connectAttr(source, rpr_field, force=True) elif source_type == tuple and dest_type == float: source = source_name + ".outAlpha" cmds.connectAttr(source, rpr_field, force=True) elif source_type == float and dest_type == tuple: source = source_name + ".outColor" cmds.connectAttr(source, rpr_field, force=True) else: if source_type == dest_type: cmds.connectAttr(source, rpr_field, force=True) elif source_type == tuple and dest_type == float: if cmds.objExists(source + "R"): source += "R" elif cmds.objExists(source + "X"): source += "X" elif cmds.objExists(source + "X"): source += "H" cmds.connectAttr(source, rpr_field, force=True) elif source_type == float and dest_type == tuple: if cmds.objExists(rpr_field + "R"): rpr_field1 = rpr_field + "R" rpr_field2 = rpr_field + "G" rpr_field3 = rpr_field + "B" elif cmds.objExists(rpr_field + "X"): rpr_field1 = rpr_field + "X" rpr_field2 = rpr_field + "Y" rpr_field3 = rpr_field + "Z" elif cmds.objExists(rpr_field + "H"): rpr_field1 = rpr_field + "H" rpr_field2 = rpr_field + "S" rpr_field3 = rpr_field + "V" cmds.connectAttr(source, rpr_field1, force=True) cmds.connectAttr(source, rpr_field2, force=True) cmds.connectAttr(source, rpr_field3, force=True) write_own_property_log(u"Created connection from {} to {}.".format(source, rpr_field).encode('utf-8')) except Exception as ex: traceback.print_exc() print(u"[ERROR] Connection {} to {} is failed.".format(source, rpr_field).encode('utf-8')) write_own_property_log(u"[ERROR] Connection {} to {} is failed.".format(source, rpr_field).encode('utf-8')) def invertValue(rpr_name, conv_name, rpr_attr, conv_attr): connection = cmds.listConnections(conv_name + "." + conv_attr) if connection and cmds.objectType(connection[0]) == "reverse": if mapDoesNotExist(connection[0], "input"): setProperty(rpr_name, rpr_attr, getProperty(connection[0], "input")) else: if cmds.listConnections(connection[0] + ".input"): copyProperty(rpr_name, connection[0], rpr_attr, "input") elif cmds.listConnections(connection[0] + ".inputX"): copyProperty(rpr_name, connection[0], rpr_attr, "inputX") elif cmds.listConnections(connection[0] + ".inputY"): copyProperty(rpr_name, connection[0], rpr_attr, "inputY") elif cmds.listConnections(connection[0] + ".inputZ"): copyProperty(rpr_name, connection[0], rpr_attr, "inputZ") elif connection: reverse_arith = cmds.shadingNode("RPRArithmetic", asUtility=True) reverse_arith = cmds.rename(reverse_arith, "Reverse_arithmetic") setProperty(reverse_arith, "operation", 1) setProperty(reverse_arith, "inputA", (1, 1, 1)) copyProperty(reverse_arith, conv_name, "inputB", conv_attr) connectProperty(reverse_arith, "out", rpr_name, rpr_attr) else: conv_value = getProperty(conv_name, conv_attr) if type(conv_value) == float: setProperty(rpr_name, rpr_attr, 1 - conv_value) elif type(conv_value) == tuple: setProperty(rpr_name, rpr_attr, (1 - conv_value[0], 1 - conv_value[1], 1 - conv_value[2])) # dispalcement convertion def convertDisplacement(ai_sg, rpr_name): try: displacement = cmds.listConnections(ai_sg + ".displacementShader") if displacement: displacementType = cmds.objectType(displacement[0]) if displacementType == "displacementShader": displacement_file = cmds.listConnections(displacement[0], type="file") if displacement_file: setProperty(rpr_name, "displacementEnable", 1) connectProperty(displacement_file[0], "outColor", rpr_name, "displacementMap") copyProperty(rpr_name, displacement[0], "scale", "displacementMax") copyProperty(rpr_name, displacement[0], "displacementMin", "aiDisplacementZeroValue") elif displacementType == "file": setProperty(rpr_name, "displacementEnable", 1) connectProperty(displacement[0], "outColor", rpr_name, "displacementMap") meshs = cmds.listConnections(ai_sg, type="mesh") if meshs: shapes = cmds.listRelatives(meshs[0], type="mesh") copyProperty(rpr_name, shapes[0], "displacementSubdiv", "aiSubdivIterations") displacementMax = getProperty(shapes[0], 'aiDispHeight') displacementMin = getProperty(shapes[0], 'aiDispZeroValue') if displacementMin > displacementMax: copyProperty(rpr_name, shapes[0], "displacementMax", "aiDispHeight") copyProperty(rpr_name, shapes[0], "displacementMin", "aiDispHeight") else: copyProperty(rpr_name, shapes[0], "displacementMax", "aiDispHeight") copyProperty(rpr_name, shapes[0], "displacementMin", "aiDispZeroValue") except Exception as ex: traceback.print_exc() print(u"Failed to convert displacement for {} material".format(rpr_name).encode('utf-8')) # dispalcement convertion def convertShadowDisplacement(ai_sg, rpr_name): try: displacement = cmds.listConnections(ai_sg + ".displacementShader") if displacement: displacementType = cmds.objectType(displacement[0]) if displacementType == "displacementShader": displacement_file = cmds.listConnections(displacement[0], type="file") if displacement_file: setProperty(rpr_name, "useDispMap", 1) connectProperty(displacement_file[0], "outColor", rpr_name, "dispMap") elif displacementType == "file": setProperty(rpr_name, "useDispMap", 1) connectProperty(displacement[0], "outColor", rpr_name, "dispMap") elif displacementType == "aiVectorMap": displacement_file = cmds.listConnections(displacement[0], type="file") if displacement_file: setProperty(rpr_name, "useDispMap", 1) connectProperty(displacement_file[0], "outColor", rpr_name, "dispMap") except Exception as ex: traceback.print_exc() print(u"Failed to convert displacement for {} material".format(rpr_name).encode('utf-8')) def convertaiAdd(ai, source): if cmds.objExists(ai + "_rpr"): rpr
= [args.arch] for arch in archs: if not self._check_tools_arg_combination(os_name, tool_name, arch): self.logger.warning( "Specified target combination is not valid: {} {} {}".format( os_name, tool_name, arch ) ) try: tool_archives = ToolArchives( os_name=os_name, tool_name=tool_name, target=target, base=base, version_str=version, arch=arch, timeout=timeout, ) except ArchiveConnectionError: try: self.logger.warning( "Connection to the download site failed and fallback to mirror site." ) tool_archives = ToolArchives( os_name=os_name, target=target, tool_name=tool_name, base=random.choice(Settings.fallbacks), version_str=version, arch=arch, timeout=timeout, ) except Exception: self.logger.error( "Connection to the download site failed. Aborted..." ) exit(1) except ArchiveDownloadError or ArchiveListError: exit(1) run_installer(tool_archives.get_packages(), base_dir, sevenzip, keep) self.logger.info("Finished installation") self.logger.info( "Time elapsed: {time:.8f} second".format( time=time.perf_counter() - start_time ) ) def run_list(self, args: argparse.ArgumentParser) -> int: """Print tools, versions of Qt, extensions, modules, architectures""" if not args.target: print(" ".join(ArchiveId.TARGETS_FOR_HOST[args.host])) return 0 if args.target not in ArchiveId.TARGETS_FOR_HOST[args.host]: self.logger.error( "'{0.target}' is not a valid target for host '{0.host}'".format(args) ) return 1 for version_str in (args.modules, args.extensions, args.arch): if not Cli._is_valid_version_str( version_str, allow_latest=True, allow_empty=True ): self.logger.error( "Invalid version: '{}'! Please use the form '5.X.Y'.".format( version_str ) ) exit(1) meta = MetadataFactory( archive_id=ArchiveId( args.category, args.host, args.target, args.extension if args.extension else "", ), filter_minor=args.filter_minor, is_latest_version=args.latest_version, modules_ver=args.modules, extensions_ver=args.extensions, architectures_ver=args.arch, tool_name=args.tool, tool_long_listing=args.tool_long, ) return show_list(meta) def _make_list_parser(self, subparsers: argparse._SubParsersAction): """Creates a subparser that works with the MetadataFactory, and adds it to the `subparsers` parameter""" list_parser: argparse.ArgumentParser = subparsers.add_parser( "list", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="Examples:\n" "$ aqt list qt5 mac # print all targets for Mac OS\n" "$ aqt list tools mac desktop # print all tools for mac desktop\n" "$ aqt list tools mac desktop --tool tools_ifw # print all tool variant names for QtIFW\n" "$ aqt list qt5 mac desktop # print all versions of Qt 5\n" "$ aqt list qt5 mac desktop --extension wasm # print all wasm versions of Qt 5\n" "$ aqt list qt5 mac desktop --filter-minor 9 # print all versions of Qt 5.9\n" "$ aqt list qt5 mac desktop --filter-minor 9 --latest-version # print latest Qt 5.9\n" "$ aqt list qt5 mac desktop --modules 5.12.0 # print modules for 5.12.0\n" "$ aqt list qt5 mac desktop --filter-minor 9 --modules latest # print modules for latest 5.9\n" "$ aqt list qt5 mac desktop --extensions 5.9.0 # print choices for --extension flag\n" "$ aqt list qt5 mac desktop --arch 5.9.9 " "# print architectures for 5.9.9/mac/desktop\n" "$ aqt list qt5 mac desktop --arch latest " "# print architectures for the latest Qt 5\n", ) list_parser.add_argument( "category", choices=["tools", "qt5", "qt6"], help="category of packages to list", ) list_parser.add_argument( "host", choices=["linux", "mac", "windows"], help="host os name" ) list_parser.add_argument( "target", nargs="?", default=None, choices=["desktop", "winrt", "android", "ios"], help="Target SDK. When omitted, this prints all the targets available for a host OS.", ) list_parser.add_argument( "--extension", choices=ArchiveId.ALL_EXTENSIONS, help="Extension of packages to list. " "Use the `--extensions` flag to list all relevant options for a host/target.", ) list_parser.add_argument( "--filter-minor", type=int, metavar="MINOR_VERSION", help="print versions for a particular minor version. " "IE: `aqt list qt5 windows desktop --filter-minor 12` prints all versions beginning with 5.12", ) output_modifier_exclusive_group = list_parser.add_mutually_exclusive_group() output_modifier_exclusive_group.add_argument( "--modules", type=str, metavar="(VERSION | latest)", help='Qt version in the format of "5.X.Y", or the keyword "latest". ' "When set, this prints all the modules available for either Qt 5.X.Y or the latest version of Qt.", ) output_modifier_exclusive_group.add_argument( "--extensions", type=str, metavar="(VERSION | latest)", help='Qt version in the format of "5.X.Y", or the keyword "latest". ' "When set, this prints all valid arguments for the `--extension` flag " "for either Qt 5.X.Y or the latest version of Qt.", ) output_modifier_exclusive_group.add_argument( "--arch", type=str, metavar="(VERSION | latest)", help='Qt version in the format of "5.X.Y", or the keyword "latest". ' "When set, this prints all architectures available for either Qt 5.X.Y or the latest version of Qt.", ) output_modifier_exclusive_group.add_argument( "--latest-version", action="store_true", help="print only the newest version available", ) output_modifier_exclusive_group.add_argument( "--tool", type=str, metavar="TOOL_NAME", help="The name of a tool. Use 'aqt list tools <host> <target>' to see accepted values. " "This flag only works with the 'tools' category, and cannot be combined with any other flags. " "When set, this prints all 'tool variant names' available. " # TODO: find a better word ^^^^^^^^^^^^^^^^^^^^; this is a mysterious help message "The output of this command is intended to be used with `aqt tool`.", ) output_modifier_exclusive_group.add_argument( "--tool-long", type=str, metavar="TOOL_NAME", help="The name of a tool. Use 'aqt list tools <host> <target>' to see accepted values. " "This flag only works with the 'tools' category, and cannot be combined with any other flags. " "When set, this prints all 'tool variant names' available, along with versions and release dates. " # TODO: find a better word ^^^^^^^^^^^^^^^^^^^^; this is a mysterious help message "The output of this command is formatted as a table.", ) list_parser.set_defaults(func=self.run_list) def show_help(self, args=None): """Display help message""" self.parser.print_help() def show_aqt_version(self, args=None): """Display version information""" py_version = platform.python_version() py_impl = platform.python_implementation() py_build = platform.python_compiler() self.logger.info( "aqtinstall(aqt) v{} on Python {} [{} {}]".format( aqt.__version__, py_version, py_impl, py_build ) ) def _set_common_options(self, subparser): subparser.add_argument( "-O", "--outputdir", nargs="?", help="Target output directory(default current directory)", ) subparser.add_argument( "-b", "--base", nargs="?", help="Specify mirror base url such as http://mirrors.ocf.berkeley.edu/qt/, " "where 'online' folder exist.", ) subparser.add_argument( "--timeout", nargs="?", type=float, help="Specify connection timeout for download site.(default: 5 sec)", ) subparser.add_argument( "-E", "--external", nargs="?", help="Specify external 7zip command path." ) subparser.add_argument( "--internal", action="store_true", help="Use internal extractor." ) subparser.add_argument( "-k", "--keep", action="store_true", help="Keep downloaded archive when specified, otherwise remove after install", ) def _set_module_options(self, subparser): subparser.add_argument( "-m", "--modules", nargs="*", help="Specify extra modules to install" ) subparser.add_argument( "--archives", nargs="*", help="Specify subset packages to install (Default: all standard and extra modules).", ) def _set_common_argument(self, subparser): subparser.add_argument("qt_version", help='Qt version in the format of "5.X.Y"') subparser.add_argument( "host", choices=["linux", "mac", "windows"], help="host os name" ) subparser.add_argument( "target", choices=["desktop", "winrt", "android", "ios"], help="target sdk" ) def _create_parser(self): parser = argparse.ArgumentParser( prog="aqt", description="Installer for Qt SDK.", formatter_class=argparse.RawTextHelpFormatter, add_help=True, ) parser.add_argument( "-c", "--config", type=argparse.FileType("r"), help="Configuration ini file.", ) subparsers = parser.add_subparsers( title="subcommands", description="Valid subcommands", help="subcommand for aqt Qt installer", ) install_parser = subparsers.add_parser( "install", formatter_class=argparse.RawTextHelpFormatter ) install_parser.set_defaults(func=self.run_install) self._set_common_argument(install_parser) self._set_common_options(install_parser) install_parser.add_argument( "arch", nargs="?", help="\ntarget linux/desktop: gcc_64, wasm_32" "\ntarget mac/desktop: clang_64, wasm_32" "\ntarget mac/ios: ios" "\nwindows/desktop: win64_msvc2019_64, win32_msvc2019" "\n win64_msvc2017_64, win32_msvc2017" "\n win64_msvc2015_64, win32_msvc2015" "\n win64_mingw81, win32_mingw81" "\n win64_mingw73, win32_mingw73" "\n win32_mingw53" "\n wasm_32" "\nwindows/winrt: win64_msvc2019_winrt_x64, win64_msvc2019_winrt_x86" "\n win64_msvc2017_winrt_x64, win64_msvc2017_winrt_x86" "\n win64_msvc2019_winrt_armv7" "\n win64_msvc2017_winrt_armv7" "\nandroid: Qt 5.14: android (optional)" "\n Qt 5.13 or below: android_x86_64, android_arm64_v8a" "\n android_x86, android_armv7", ) self._set_module_options(install_parser) install_parser.add_argument( "--noarchives", action="store_true", help="No base packages; allow mod amendment with --modules option.", ) # doc_parser = subparsers.add_parser("doc") doc_parser.set_defaults(func=self.run_doc) self._set_common_argument(doc_parser) self._set_common_options(doc_parser) self._set_module_options(doc_parser) # examples_parser = subparsers.add_parser("examples") examples_parser.set_defaults(func=self.run_examples) self._set_common_argument(examples_parser) self._set_common_options(examples_parser) self._set_module_options(examples_parser) # src_parser = subparsers.add_parser("src") src_parser.set_defaults(func=self.run_src) self._set_common_argument(src_parser) self._set_common_options(src_parser) self._set_module_options(src_parser) src_parser.add_argument( "--kde", action="store_true", help="patching with KDE patch kit." ) # tools_parser = subparsers.add_parser("tool") tools_parser.set_defaults(func=self.run_tool) tools_parser.add_argument( "host", choices=["linux", "mac", "windows"], help="host os name" ) tools_parser.add_argument( "target", default=None, choices=["desktop", "winrt", "android", "ios"], help="Target SDK.", ) tools_parser.add_argument( "tool_name", help="Name of tool such as tools_ifw, tools_mingw" ) tools_parser.add_argument( "arch", nargs="?", default=None, help="Name of full tool name such as qt.tools.ifw.31. " "Please use 'aqt list --tool' to list acceptable values for this parameter.", ) self._set_common_options(tools_parser) self._make_list_parser(subparsers) # help_parser = subparsers.add_parser("help") help_parser.set_defaults(func=self.show_help) # version_parser = subparsers.add_parser("version") version_parser.set_defaults(func=self.show_aqt_version) parser.set_defaults(func=self.show_help) self.parser = parser def _setup_settings(self, args=None): # setup logging setup_logging() self.logger = getLogger("aqt.main") # setup settings if args is not None and args.config is not None: Settings.load_settings(args.config) else: config = os.getenv("AQT_CONFIG", None) if config is not None and os.path.exists(config): Settings.load_settings(config) self.logger.debug("Load configuration from {}".format(config)) else: Settings.load_settings() def run(self, arg=None): args = self.parser.parse_args(arg) self._setup_settings(args) result = args.func(args) return result @staticmethod def _is_valid_version_str( version_str: str, *, allow_latest: bool = False, allow_empty: bool = False ) -> bool: if (allow_latest and version_str == "latest") or ( allow_empty and not version_str ): return True try: Version(version_str) return True except ValueError: return False def run_installer( archives: List[QtPackage], base_dir: str, sevenzip: Optional[str], keep: bool ): queue = multiprocessing.Manager().Queue(-1) listener = MyQueueListener(queue) listener.start() # tasks = [] for arc in archives: tasks.append((arc, base_dir, sevenzip, queue, keep)) ctx = multiprocessing.get_context("spawn") pool = ctx.Pool(Settings.concurrency) pool.starmap(installer, tasks)
str(r)) return self._render_response(r, OK_CODE) def jsonrpc_is_first_run(self): """ Check if this is the first time lbrynet daemon has been run Args: None Returns: True if first run, otherwise False """ log.info("Check if is first run") try: d = self.session.wallet.is_first_run() except: d = defer.fail(None) d.addCallbacks(lambda r: self._render_response(r, OK_CODE), lambda _: self._render_response(None, OK_CODE)) return d def jsonrpc_get_start_notice(self): """ Get special message to be displayed at startup Args: None Returns: Startup message, such as first run notification """ log.info("Get startup notice") if self.first_run and not self.session.wallet.wallet_balance: return self._render_response(self.startup_message, OK_CODE) elif self.first_run: return self._render_response(None, OK_CODE) else: self._render_response(self.startup_message, OK_CODE) def jsonrpc_version(self): """ Get lbry version information Args: None Returns: "platform": platform string "os_release": os release string "os_system": os name "lbrynet_version: ": lbrynet_version, "lbryum_version: ": lbryum_version, "ui_version": commit hash of ui version being used "remote_lbrynet": most recent lbrynet version available from github "remote_lbryum": most recent lbryum version available from github """ platform_info = self._get_platform() msg = { 'platform': platform_info['platform'], 'os_release': platform_info['os_release'], 'os_system': platform_info['os_system'], 'lbrynet_version': lbrynet_version, 'lbryum_version': lbryum_version, 'ui_version': self.ui_version, 'remote_lbrynet': self.git_lbrynet_version, 'remote_lbryum': self.git_lbryum_version, 'lbrynet_update_available': utils.version_is_greater_than(self.git_lbrynet_version, lbrynet_version), 'lbryum_update_available': utils.version_is_greater_than(self.git_lbryum_version, lbryum_version), } log.info("Get version info: " + json.dumps(msg)) return self._render_response(msg, OK_CODE) def jsonrpc_get_settings(self): """ Get lbrynet daemon settings Args: None Returns: 'run_on_startup': bool, 'data_rate': float, 'max_key_fee': float, 'download_directory': string, 'max_upload': float, 0.0 for unlimited 'max_download': float, 0.0 for unlimited 'upload_log': bool, 'search_timeout': float, 'download_timeout': int 'max_search_results': int, 'wallet_type': string, 'delete_blobs_on_remove': bool, 'peer_port': int, 'dht_node_port': int, 'use_upnp': bool, 'start_lbrycrdd': bool, """ log.info("Get daemon settings") return self._render_response(self.session_settings, OK_CODE) def jsonrpc_set_settings(self, p): """ Set lbrynet daemon settings Args: 'run_on_startup': bool, 'data_rate': float, 'max_key_fee': float, 'download_directory': string, 'max_upload': float, 0.0 for unlimited 'max_download': float, 0.0 for unlimited 'upload_log': bool, 'download_timeout': int Returns: settings dict """ def _log_settings_change(): log.info("Set daemon settings to " + json.dumps(self.session_settings)) d = self._update_settings(p) d.addErrback(lambda err: log.info(err.getTraceback())) d.addCallback(lambda _: _log_settings_change()) d.addCallback(lambda _: self._render_response(self.session_settings, OK_CODE)) return d def jsonrpc_help(self, p=None): """ Function to retrieve docstring for API function Args: optional 'function': function to retrieve documentation for optional 'callable_during_startup': Returns: if given a function, returns given documentation if given callable_during_startup flag, returns list of functions callable during the startup sequence if no params are given, returns the list of callable functions """ if not p: return self._render_response(self._listFunctions(), OK_CODE) elif 'callable_during_start' in p.keys(): return self._render_response(ALLOWED_DURING_STARTUP, OK_CODE) elif 'function' in p.keys(): func_path = p['function'] function = self._getFunction(func_path) return self._render_response(function.__doc__, OK_CODE) else: return self._render_response(self.jsonrpc_help.__doc__, OK_CODE) def jsonrpc_get_balance(self): """ Get balance Args: None Returns: balance, float """ log.info("Get balance") return self._render_response(float(self.session.wallet.wallet_balance), OK_CODE) def jsonrpc_stop(self): """ Stop lbrynet-daemon Args: None Returns: shutdown message """ def _disp_shutdown(): log.info("Shutting down lbrynet daemon") d = self._shutdown() d.addCallback(lambda _: _disp_shutdown()) d.addCallback(lambda _: reactor.callLater(0.0, reactor.stop)) return self._render_response("Shutting down", OK_CODE) def jsonrpc_get_lbry_files(self): """ Get LBRY files Args: None Returns: List of lbry files: 'completed': bool 'file_name': string 'key': hex string 'points_paid': float 'stopped': bool 'stream_hash': base 58 string 'stream_name': string 'suggested_file_name': string 'upload_allowed': bool 'sd_hash': string """ d = self._get_lbry_files() d.addCallback(lambda r: [d[1] for d in r]) d.addCallback(lambda r: self._render_response(r, OK_CODE) if len(r) else self._render_response(False, OK_CODE)) return d def jsonrpc_get_lbry_file(self, p): """ Get lbry file Args: 'name': get file by lbry uri, 'sd_hash': get file by the hash in the name claim, 'file_name': get file by its name in the downloads folder, Returns: 'completed': bool 'file_name': string 'key': hex string 'points_paid': float 'stopped': bool 'stream_hash': base 58 string 'stream_name': string 'suggested_file_name': string 'upload_allowed': bool 'sd_hash': string """ if p.keys()[0] in ['name', 'sd_hash', 'file_name']: search_type = p.keys()[0] d = self._get_lbry_file(search_type, p[search_type]) else: d = defer.fail() d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def jsonrpc_resolve_name(self, p): """ Resolve stream info from a LBRY uri Args: 'name': name to look up, string, do not include lbry:// prefix Returns: metadata from name claim """ force = p.get('force', False) if 'name' in p: name = p['name'] else: return self._render_response(None, BAD_REQUEST) d = self._resolve_name(name, force_refresh=force) d.addCallbacks(lambda info: self._render_response(info, OK_CODE), lambda _: server.failure) return d def jsonrpc_get_claim_info(self, p): """ Resolve claim info from a LBRY uri Args: 'name': name to look up, string, do not include lbry:// prefix Returns: txid, amount, value, n, height """ def _convert_amount_to_float(r): if not r: return False else: r['amount'] = float(r['amount']) / 10**8 return r name = p['name'] txid = p.get('txid', None) d = self.session.wallet.get_claim_info(name, txid) d.addCallback(_convert_amount_to_float) d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def _process_get_parameters(self, p): """Extract info from input parameters and fill in default values for `get` call.""" # TODO: this process can be abstracted s.t. each method # can spec what parameters it expects and how to set default values timeout = p.get('timeout', self.download_timeout) download_directory = p.get('download_directory', self.download_directory) file_name = p.get('file_name') stream_info = p.get('stream_info') sd_hash = get_sd_hash(stream_info) wait_for_write = p.get('wait_for_write', True) name = p.get('name') return Parameters( timeout=timeout, download_directory=download_directory, file_name=file_name, stream_info=stream_info, sd_hash=sd_hash, wait_for_write=wait_for_write, name=name ) def jsonrpc_get(self, p): """Download stream from a LBRY uri. Args: 'name': name to download, string 'download_directory': optional, path to directory where file will be saved, string 'file_name': optional, a user specified name for the downloaded file 'stream_info': optional, specified stream info overrides name 'timeout': optional 'wait_for_write': optional, defaults to True Returns: 'stream_hash': hex string 'path': path of download """ params = self._process_get_parameters(p) if not params.name: return server.failure if params.name in self.waiting_on: return server.failure d = self._download_name(name=params.name, timeout=params.timeout, download_directory=params.download_directory, stream_info=params.stream_info, file_name=params.file_name, wait_for_write=params.wait_for_write) d.addCallback(get_output_callback(params)) d.addCallback(lambda message: self._render_response(message, OK_CODE)) return d def jsonrpc_stop_lbry_file(self, p): """ Stop lbry file Args: 'name': stop file by lbry uri, 'sd_hash': stop file by the hash in the name claim, 'file_name': stop file by its name in the downloads folder, Returns: confirmation message """ def _stop_file(f): d = self.lbry_file_manager.toggle_lbry_file_running(f) d.addCallback(lambda _: "Stopped LBRY file") return d if p.keys()[0] in ['name', 'sd_hash', 'file_name']: search_type = p.keys()[0] d = self._get_lbry_file(search_type, p[search_type], return_json=False) d.addCallback(lambda l: _stop_file(l) if not l.stopped else "LBRY file wasn't running") d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def jsonrpc_start_lbry_file(self, p): """ Stop lbry file Args: 'name': stop file by lbry uri, 'sd_hash': stop file by the hash in the name claim, 'file_name': stop file by its name in the downloads folder, Returns: confirmation message """ def _start_file(f): d = self.lbry_file_manager.toggle_lbry_file_running(f) return defer.succeed("Started LBRY file") if p.keys()[0] in ['name', 'sd_hash', 'file_name']: search_type = p.keys()[0] d = self._get_lbry_file(search_type, p[search_type], return_json=False) d.addCallback(lambda l: _start_file(l) if l.stopped else "LBRY file was already running") d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def jsonrpc_get_est_cost(self, p): """ Get estimated cost for a lbry uri Args: 'name': lbry uri Returns: estimated cost """ name = p['name'] force = p.get('force', False) if force: d = self._get_est_cost(name) else: d = self._search(name) d.addCallback(lambda r: [i['cost'] for i in r][0]) d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def jsonrpc_search_nametrie(self, p): """ Search the nametrie for claims Args: 'search': search query, string Returns: List of search results """ # TODO: change this function to "search" if 'search' in p.keys(): search = p['search'] else: return self._render_response(None, BAD_REQUEST) # TODO: have ui accept the actual outputs def _clean(n): t = [] for i in n: td = {k: i['value'][k] for k in i['value']} td['cost_est'] = float(i['cost']) td['thumbnail'] = i['value'].get('thumbnail', "img/Free-speech-flag.svg") td['name'] = i['name'] t.append(td) return t log.info('Search: %s' % search) d = self._search(search) d.addCallback(_clean) d.addCallback(lambda results: self._render_response(results, OK_CODE)) return d def jsonrpc_delete_lbry_file(self, p): """ Delete a lbry file Args: 'file_name': downloaded file name, string Returns: confirmation message """ if 'delete_target_file' in p.keys(): delete_file = p['delete_target_file'] else: delete_file = True def _delete_file(f): file_name = f.file_name d = self._delete_lbry_file(f, delete_file=delete_file) d.addCallback(lambda _: "Deleted LBRY file" + file_name) return d if 'name' in p.keys() or 'sd_hash' in p.keys() or 'file_name' in p.keys(): search_type = [k for k in p.keys() if k != 'delete_target_file'][0] d = self._get_lbry_file(search_type, p[search_type], return_json=False) d.addCallback(lambda l: _delete_file(l) if l else False) d.addCallback(lambda r: self._render_response(r, OK_CODE)) return d def jsonrpc_publish(self, p): """ Make a new name claim and publish associated data to lbrynet Args: 'name': name to be claimed, string 'file_path': path to file to be associated with name, string 'bid': amount of credits to commit in this claim, float 'metadata': metadata dictionary optional 'fee'
import sys import os import glob import string import logging import yaml import yamlordereddictloader def extract_data(c, param_map): """ Method to generate a CPAC input subject list python file. The method extracts anatomical and functional data for each site( if multiple site) and/or scan parameters for each site and put it into a data structure read by python Example: subjects_list =[ { 'subject_id' : '0050386', 'unique_id' : 'session_1', 'anat': '/Users/home/data/NYU/0050386/session_1/anat_1/anat.nii.gz', 'rest':{ 'rest_1_rest' : '/Users/home/data/NYU/0050386/session_1/rest_1/rest.nii.gz', 'rest_2_rest' : '/Users/home/data/NYU/0050386/session_1/rest_2/rest.nii.gz', } 'scan_parameters':{ 'tr': '2', 'acquisition': 'alt+z2', 'reference': '17', 'first_tr': '', 'last_tr': '', } }, ] or subjects_list =[ { 'subject_id' : '0050386', 'unique_id' : 'session_1', 'anat': '/Users/home/data/NYU/0050386/session_1/anat_1/anat.nii.gz', 'rest':{ 'rest_1_rest' : '/Users/home/data/NYU/0050386/session_1/rest_1/rest.nii.gz', 'rest_2_rest' : '/Users/home/data/NYU/0050386/session_1/rest_2/rest.nii.gz', } }, ] """ #method to read each line of the file into list #returns list def get_list(arg): if isinstance(arg, list): ret_list = arg else: ret_list = [fline.rstrip('\r\n') for fline in open(arg, 'r').readlines()] return ret_list exclusion_list = [] if c.exclusionSubjectList is not None: exclusion_list = get_list(c.exclusionSubjectList) subject_list = [] if c.subjectList is not None: subject_list = get_list(c.subjectList) #check if Template is correct def checkTemplate(template): if template.count('%s') != 2: msg = "Please provide '%s' in the template" \ "where your site and subjects are present"\ "Please see examples" logging.exception(msg) raise Exception(msg) filename, ext = os.path.splitext(os.path.basename(template)) ext = os.path.splitext(filename)[1] + ext if ext not in [".nii", ".nii.gz"]: msg = "Invalid file name", os.path.basename(template) logging.exception(msg) raise Exception(msg) def get_site_list(path): base, relative = path.split('%s') sites = os.listdir(base) return sites def check_length(scan_name, file_name): if len(file_name) > 30: msg = "filename- %s is too long."\ "It should not be more than 30 characters."%(file_name) logging.exception(msg) raise Exception(msg) if len(scan_name) - len(os.path.splitext(os.path.splitext(file_name)[0])[0])>= 40: msg = "scan name %s is too long."\ "It should not be more than 20 characters"\ %(scan_name.replace("_"+os.path.splitext(os.path.splitext(file_name)[0])[0], '')) logging.exception(msg) raise Exception(msg) def create_site_subject_mapping(base, relative): #mapping between site and subject site_subject_map = {} base_path_list = [] if c.siteList is not None: site_list = get_list(c.siteList) else: site_list = get_site_list(base) for site in site_list: paths = glob.glob(string.replace(base, '%s', site)) base_path_list.extend(paths) for path in paths: for sub in os.listdir(path): #check if subject is present in subject_list if subject_list: if sub in subject_list and sub not in exclusion_list: site_subject_map[sub] = site elif sub not in exclusion_list: if sub not in '.DS_Store': site_subject_map[sub] = site return base_path_list, site_subject_map #method to split the input template path #into base, path before subject directory #and relative, path after subject directory def getPath(template): checkTemplate(template) base, relative = template.rsplit("%s", 1) base, subject_map = create_site_subject_mapping(base, relative) base.sort() relative = relative.lstrip("/") return base, relative, subject_map #get anatomical base path and anatomical relative path anat_base, anat_relative = getPath(c.anatomicalTemplate)[:2] #get functional base path, functional relative path and site-subject map func_base, func_relative, subject_map = getPath(c.functionalTemplate) if not anat_base: msg = "Anatomical Data template incorrect. No such file or directory %s", anat_base logging.exception(msg) raise Exception(msg) if not func_base: msg = "Functional Data template incorrect. No such file or directory %s, func_base" logging.exception(msg) raise Exception(msg) if len(anat_base) != len(func_base): msg1 = "Some sites are missing, Please check your template"\ , anat_base, "!=", func_base logging.exception(msg1) msg2 = " Base length Unequal. Some sites are missing."\ "extract_data doesn't script support this.Please" \ "Provide your own subjects_list file" logging.exception(msg2) raise Exception(msg2) #calculate the length of relative paths(path after subject directory) func_relative_len = len(func_relative.split('/')) anat_relative_len = len(anat_relative.split('/')) def check_for_sessions(relative_path, path_length): """ Method to check if there are sessions present """ #default session_present = False session_path = 'session_1' #session present if path_length is equal to 3 if path_length == 3: relative_path_list = relative_path.split('/') session_path = relative_path_list[0] relative_path = string.join(relative_path_list[1:], "/") session_present = True elif path_length > 3: msg = "extract_data script currently doesn't support this directory structure."\ "Please provide the subjects_list file to run CPAC."\ "For more information refer to manual" logging.exception(msg) raise Exception(msg) return session_present, session_path, relative_path func_session_present, func_session_path, func_relative = \ check_for_sessions(func_relative, func_relative_len) anat_session_present, anat_session_path, anat_relative = \ check_for_sessions(anat_relative, anat_relative_len) f = open(os.path.join(c.outputSubjectListLocation, "CPAC_subject_list_%s.yml" % c.subjectListName), 'wb') def fetch_path(i, anat_sub, func_sub, session_id): """ Method to extract anatomical and functional path for a session and print to file Parameters ---------- i : int index of site anat_sub : string string containing subject/ concatenated subject-session path for anatomical file func_sub: string string containing subject/ concatenated subject-session path for functional file session_id: string session Raises ------ Exception """ try: def print_begin_of_file(sub, session_id): print("-", file=f) print(" subject_id: '" + sub + "'", file=f) print(" unique_id: '" + session_id + "'", file=f) def print_end_of_file(sub): if param_map is not None: try: logging.debug("site for sub %s -> %s" %(sub, subject_map.get(sub))) logging.debug("scan parameters for the above site %s"%param_map.get(subject_map.get(sub))) print(" scan_parameters:", file=f) print(" tr: '" + param_map.get(subject_map.get(sub))[4] + "'", file=f) print(" acquisition: '" + param_map.get(subject_map.get(sub))[0] + "'", file=f) print(" reference: '" + param_map.get(subject_map.get(sub))[3] + "'", file=f) print(" first_tr: '" + param_map.get(subject_map.get(sub))[1] + "'", file=f) print(" last_tr: '" + param_map.get(subject_map.get(sub))[2] + "'", file=f) except: msg = " No Parameter values for the %s site is defined in the scan"\ " parameters csv file" %subject_map.get(sub) raise ValueError(msg) #get anatomical file anat_base_path = os.path.join(anat_base[i], anat_sub) func_base_path = os.path.join(func_base[i], func_sub) anat = None func = None anat = glob.glob(os.path.join(anat_base_path, anat_relative)) func = glob.glob(os.path.join(func_base_path, func_relative)) if anat and func: print_begin_of_file(anat_sub.split("/")[0], session_id) print(" anat: '" + os.path.realpath(anat[0]) + "'", file=f) print(" rest: ", file=f) #iterate for each rest session for iter in func: #get scan_id iterable = os.path.splitext(os.path.splitext(iter.replace(func_base_path, '').lstrip("/"))[0])[0] iterable = iterable.replace("/", "_") check_length(iterable, os.path.basename(os.path.realpath(iter))) print(" " + iterable + ": '" + os.path.realpath(iter) + "'", file=f) print_end_of_file(anat_sub.split("/")[0]) else: logging.debug("skipping subject %s"%anat_sub.split("/")[0]) except ValueError: logging.exception(ValueError.message) raise except Exception as e: err_msg = 'Exception while felching anatomical and functional ' \ 'paths: \n' + str(e) logging.exception(err_msg) raise Exception(err_msg) def walk(index, sub): """ Method which walks across each subject path in the data site path Parameters ---------- index : int index of site sub : string subject_id Raises ------ Exception """ try: if func_session_present: #if there are sessions if "*" in func_session_path: session_list = glob.glob(os.path.join(func_base[index], os.path.join(sub, func_session_path))) else: session_list = [func_session_path] if session_list: for session in session_list: session_id = os.path.basename(session) if anat_session_present: if func_session_path == anat_session_path: fetch_path(index, os.path.join(sub, session_id), os.path.join(sub, session_id), session_id) else: fetch_path(index, os.path.join(sub, anat_session_path), os.path.join(sub, session_id), session_id) else: fetch_path(index, sub, os.path.join(sub, session_id), session_id) else: logging.debug("Skipping subject %s", sub) else: logging.debug("No sessions") session_id = '' fetch_path(index, sub, sub, session_id) except Exception: logging.exception(Exception.message) raise except: err_msg = 'Please make sessions are consistent across all ' \ 'subjects.\n\n' logging.exception(err_msg) raise Exception(err_msg) try: for i in range(len(anat_base)): for sub in os.listdir(anat_base[i]): #check if subject is present in subject_list if subject_list: if sub in subject_list and sub not in exclusion_list: logging.debug("extracting data for subject: %s", sub) walk(i, sub) #check that subject is not in exclusion list elif sub not in exclusion_list and sub not in '.DS_Store': logging.debug("extracting data for subject: %s", sub) walk(i, sub) name = os.path.join(c.outputSubjectListLocation, 'CPAC_subject_list.yml') print("Extraction Successfully Completed...Input Subjects_list for CPAC - %s" % name) except Exception: logging.exception(Exception.message) raise finally: f.close() def generate_supplementary_files(data_config_outdir, data_config_name): """ Method to generate phenotypic template file and subject list for group analysis """ import os from sets import Set import csv data_config_path = os.path.join(data_config_outdir, data_config_name) try: subjects_list = yaml.safe_load(open(data_config_path, 'r')) except: err = "\n\n[!] Data configuration file couldn't be read!\nFile " \ "path: {0}\n".format(data_config_path) subject_scan_set = Set() subID_set = Set() session_set = Set() subject_set = Set() scan_set = Set() data_list = [] try: for sub in subjects_list: if sub['unique_id']: subject_id = sub['subject_id'] + "_" + sub['unique_id'] else: subject_id = sub['subject_id'] try: for scan in sub['func']: subject_scan_set.add((subject_id, scan)) subID_set.add(sub['subject_id']) session_set.add(sub['unique_id']) subject_set.add(subject_id) scan_set.add(scan) except KeyError: try: for scan in sub['rest']: subject_scan_set.add((subject_id, scan)) subID_set.add(sub['subject_id']) session_set.add(sub['unique_id']) subject_set.add(subject_id) scan_set.add(scan) except KeyError: # one of the participants in the subject list has no # functional scans subID_set.add(sub['subject_id']) session_set.add(sub['unique_id']) subject_set.add(subject_id) except TypeError as e: print('Subject list could not be populated!') print('This is most likely due to a mis-formatting in your '\ 'inclusion and/or exclusion subjects txt file or your '\ 'anatomical and/or functional path templates.') print('Error: %s' % e) err_str = 'Check formatting of your anatomical/functional path '\ 'templates and inclusion/exclusion subjects text
""" TODO: Resolve the following bug in the firmware: >>> spdc.heater_voltage_limit = 3 >>> spdc.heater_voltage = 2 >>> spdc.heater_voltage_limit = 1 >>> spdc.heater_voltage # expected: 1.0 2.0 This in contrast to laser current: >>> spdc.laser_current_limit = 3 >>> spdc.laser_current = 2 >>> spdc.laser_current_limit = 1 >>> spdc.laser_current # expected: ~1.0 0.952 Bug occurs for peltier_voltage as well, independent on POWER setting. This bug does not occur with peltier/heater loops on. """ import time import numpy as np # for type checking with numpy types from .serial_connection import SerialConnection class SPDCDriver(object): """Python wrapper to communcate with SPDC board.""" DEVICE_IDENTIFIER = "SPDC driver" def __init__(self, device_path: str = ""): if device_path == "": self._com = SerialConnection.connect_by_name(self.DEVICE_IDENTIFIER) else: self._com = SerialConnection(device_path) @staticmethod def _raise_if_oob(value, low, high, propname, propunits): """Raises ValueError if value is invalid / out of bounds (oob). Note: See `heater_voltage` notes for rationale behind input validation and exception used. """ if not (isinstance(value, (int, float, np.number)) and low <= value <= high): raise ValueError( f"{propname} can only take values between [{low}, {high}] {propunits}" ) def help(self) -> str: return self._com.get_help() @property def identity(self) -> str: return self._com.get_identity() def reset(self) -> None: """Resets the device.""" self._com.writeline("*RST") def save_settings(self) -> str: """Save device settings into storage. Returns: Success message if save is successful. Note: Saving of settings typically take longer than 100ms. One second is a reasonable upper bound. """ return self._com.getresponse("SAVE", timeout=1) def close(self) -> None: """Close connection to device.""" self._com.close() @property def heater_loop(self) -> int: return int(self._com.getresponse("HLOOP?")) def heater_loop_on(self): """Switches on the crystal heater temperature PID loop. Note: The `HLOOP 1` command is encapsulated within the `heater_loop_on()` subroutine, since it is usually compounded with the power command. See `heater_loop_off()`. """ self._com.writeline("HLOOP 1") self._power_on_heater_peltier() def heater_loop_off(self): """Switches off the crystal heater temperature PID loop. Note: Heater voltage is automatically set to zero, which is not part of the device command set, and hence is implemented as a method instead of a `heater_loop` setter. This avoids the cognitive inconsistency between `heater_loop = 0` and `HLOOP 0`. Implemented because there is likely no use case for a voltage hold after PID is switched off, except for debugging. """ self._com.writeline("HLOOP 0") # holds voltage at current value self.heater_voltage = 0 if not self.peltier_loop: # switch off power only if peltier loop also off self._power_off_heater_peltier() @property def peltier_loop(self) -> int: return int(self._com.getresponse("PLOOP?")) def peltier_loop_on(self): """Switches on the laser peltier temperature PID loop. Note: See `heater_loop_on()`. """ self._com.writeline("PLOOP 1") self._power_on_heater_peltier() def peltier_loop_off(self): """Switches off the laser peltier temperature PID loop. Note: See `peltier_loop_off()`. """ self._com.writeline("PLOOP 0") # holds voltage at current value self.peltier_voltage = 0 if not self.heater_loop: # switch off power only if heater loop also off self._power_off_heater_peltier() @property def heater_voltage(self) -> float: return float(self._com.getresponse("HVOLT?")) @heater_voltage.setter def heater_voltage(self, voltage: float) -> None: """Sets voltage across crystal heater, in volts. The set voltage should be non-negative and less than or equal to `heater_voltage_limit`. Raises: ValueError: `voltage` is not a valid number. Note: Outside of the allowable range, the driver itself will return an error message, otherwise there is no return value. This leaves three implementation options for the return value: - Allow the setter to forward the wrong command, and raise a ValueError if there is a device response. This incurs an additional read timeout for successful commands with no device response. - Allow the setter to fail silently (ignore response). This shaves off read timeout due to pre-emptive clearing of buffer, but users are left unaware of the failure unless explicitly checked. - Enforce the setter to check for bounding values from the get-go. Requires an additional attribute query, but shaves off the timeout as well. Risks hardcoding outdated values when firmware changes. At the moment the last option is preferable due to the mix of explicit failure and input sanitization. Replacing TypeError with ValueError to minimize the possible exceptions raised. """ hlimit_low, hlimit_high = 0, self.heater_voltage_limit self._raise_if_oob(voltage, hlimit_low, hlimit_high, "Heater voltage", "V") self._com.writeline(f"HVOLT {voltage:.3f}") @property def peltier_voltage(self) -> float: return float(self._com.getresponse("PVOLT?")) @peltier_voltage.setter def peltier_voltage(self, voltage: float) -> None: """Sets voltage across laser peltier, in volts. The set voltage should have magnitude less than or equal to `peltier_voltage_limit`. Raises: ValueError: `voltage` is not a valid number. """ plimit = self.peltier_voltage_limit self._raise_if_oob(voltage, -plimit, plimit, "Peltier voltage", "V") self._com.writeline(f"PVOLT {voltage:.3f}") @property def heater_voltage_limit(self) -> float: return float(self._com.getresponse("HLIMIT?")) @heater_voltage_limit.setter def heater_voltage_limit(self, voltage: float) -> None: """Sets the crystal heater voltage limit, in volts. The voltage limit should be within [0, 10] V. Raises: ValueError: `voltage` is not a valid number. """ hlimit_low, hlimit_high = 0, 10 # hardcoded based on firmware self._raise_if_oob( voltage, hlimit_low, hlimit_high, "Heater voltage limit", "V" ) self._com.writeline(f"HLIMIT {voltage:.3f}") @property def peltier_voltage_limit(self) -> float: return float(self._com.getresponse("PLIMIT?")) @peltier_voltage_limit.setter def peltier_voltage_limit(self, voltage: float) -> None: """Sets the laser peltier voltage limit, in volts. Raises: ValueError: `voltage` is not a valid number. """ plimit_low, plimit_high = 0, 2.5 # hardcoded based on firmware self._raise_if_oob( voltage, plimit_low, plimit_high, "Peltier voltage limit", "V" ) self._com.writeline(f"PLIMIT {voltage:.3f}") @property def heater_temp(self) -> float: """Measures the instantaneous temperature near the crystal.""" return float(self._com.getresponse("HTEMP?")) @heater_temp.setter def heater_temp(self, temp: float): """Alias for `heater_temp_setpoint` setter, temp in Celsius.""" self.heater_temp_setpoint = temp @property def heater_temp_setpoint(self) -> float: return float(self._com.getresponse("HSETTEMP?")) @heater_temp_setpoint.setter def heater_temp_setpoint(self, temp: float) -> None: """Sets the target temperature of the crystal, in Celsius. Raises: ValueError: `temp` is not a valid number. """ htemp_low, htemp_high = 20, 100 # hardcoded based on firmware self._raise_if_oob(temp, htemp_low, htemp_high, "Heater temp setpoint", "°C") self._com.writeline(f"HSETTEMP {temp:.3f}") @property def heater_temp_rate(self) -> float: return float(self._com.getresponse("HRATE?")) @heater_temp_rate.setter def heater_temp_rate(self, rate: float) -> None: """Sets the heater temperature ramp rate, in K/s. Two separate and distinct heating profiles are used depending on the value of `rate`. If `rate` is set at 0, the change in heater temp setpoint will be instantaneous. Otherwise, the heater setpoint will ramp up/down linearly, starting from the previous value when `rate` > 0. Raises: ValueError: `rate` is not a valid number. Note: Strongly related to `heater_temp_target`, which determines the instantaneous time-varying heater setpoint. """ hrate_low, hrate_high = 0.0, 1.0 # hardcoded based on firmware self._raise_if_oob(rate, hrate_low, hrate_high, "Heater temp ramp", "K/s") self._com.writeline(f"HRATE {rate:.3f}") @property def heater_temp_target(self) -> float: return float(self._com.getresponse("HTARGET?")) @property def peltier_temp(self) -> float: """Measures the instantaneous temperature near the laser.""" return float(self._com.getresponse("PTEMP?")) @peltier_temp.setter def peltier_temp(self, temp: float): """Alias for `peltier_temp_setpoint` setter, temp in Celsius.""" self.peltier_temp_setpoint = temp @property def peltier_temp_setpoint(self) -> float: return float(self._com.getresponse("PSETTEMP?")) @peltier_temp_setpoint.setter def peltier_temp_setpoint(self, temp: float) -> None: """Sets the target temperature of the laser, in Celsius. Raises: ValueError: `temp` is not a valid number. """ ptemp_low, ptemp_high = 20, 50 # hardcoded based on firmware self._raise_if_oob(temp, ptemp_low, ptemp_high, "Peltier temp setpoint", "°C") self._com.writeline(f"PSETTEMP {temp:.3f}") @property def hconstp(self) -> float: return float(self._com.getresponse("HCONSTP?")) @hconstp.setter def hconstp(self, constant: float) -> None: """Sets the proportional control constant for crystal heater, in V/K.""" hconstp_low, hconstp_high = 0, 10 # hardcoded based on firmware self._raise_if_oob( constant, hconstp_low, hconstp_high, "Heater P constant", "V/K" ) self._com.writeline(f"HCONSTP {constant:.3f}") @property def hconsti(self) -> float: return float(self._com.getresponse("HCONSTI?")) @hconsti.setter def hconsti(self, constant: float) -> None: """Sets the integral control constant for crystal heater, in V/(Ks).""" hconsti_low, hconsti_high = 0, 10 # hardcoded based on firmware self._raise_if_oob( constant, hconsti_low, hconsti_high, "Heater I constant", "V/(Ks)" ) self._com.writeline(f"HCONSTI {constant:.3f}") @property def hconstd(self) -> float: return float(self._com.getresponse("HCONSTD?")) @hconstd.setter def hconstd(self, constant: float) -> None: """Sets the derivative control constant for crystal heater, in Vs/K.""" hconstd_low, hconstd_high = 0, 10 # hardcoded based on firmware self._raise_if_oob( constant, hconstd_low, hconstd_high, "Heater D constant", "Vs/K" ) self._com.writeline(f"HCONSTD {constant:.3f}") @property def pconstp(self) -> float: return float(self._com.getresponse("PCONSTP?")) @pconstp.setter def pconstp(self, constant: float) -> None: """Sets the proportional control constant for laser peltier, in V/K.""" pconstp_low, pconstp_high = 0, 10 # hardcoded based on firmware self._raise_if_oob( constant, pconstp_low, pconstp_high, "Peltier P constant", "V/K" ) self._com.writeline(f"PCONSTP {constant:.3f}") @property def pconsti(self) -> float: return float(self._com.getresponse("PCONSTI?")) @pconsti.setter def pconsti(self, constant: float) -> None: """Sets the
<filename>sdk/lusid/api/calendars_api.py<gh_stars>0 # coding: utf-8 """ LUSID API FINBOURNE Technology # noqa: E501 The version of the OpenAPI document: 0.11.3192 Contact: <EMAIL> Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from lusid.api_client import ApiClient from lusid.exceptions import ( ApiTypeError, ApiValueError ) class CalendarsApi(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def add_date_to_calendar(self, scope, code, create_date_request, **kwargs): # noqa: E501 """[EXPERIMENTAL] Add a date to a calendar # noqa: E501 Add an event to the calendar. These Events can be a maximum of 24 hours and must be specified in UTC. A local date will be calculated by the system and applied to the calendar before processing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_date_to_calendar(scope, code, create_date_request, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str scope: Scope of the calendar (required) :param str code: Code of the calendar (required) :param CreateDateRequest create_date_request: Add date to calendar request (required) :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: CalendarDate If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.add_date_to_calendar_with_http_info(scope, code, create_date_request, **kwargs) # noqa: E501 def add_date_to_calendar_with_http_info(self, scope, code, create_date_request, **kwargs): # noqa: E501 """[EXPERIMENTAL] Add a date to a calendar # noqa: E501 Add an event to the calendar. These Events can be a maximum of 24 hours and must be specified in UTC. A local date will be calculated by the system and applied to the calendar before processing. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_date_to_calendar_with_http_info(scope, code, create_date_request, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str scope: Scope of the calendar (required) :param str code: Code of the calendar (required) :param CreateDateRequest create_date_request: Add date to calendar request (required) :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(CalendarDate, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = ['scope', 'code', 'create_date_request'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method add_date_to_calendar" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'scope' is set if ('scope' not in local_var_params or local_var_params['scope'] is None): raise ApiValueError("Missing the required parameter `scope` when calling `add_date_to_calendar`") # noqa: E501 # verify the required parameter 'code' is set if ('code' not in local_var_params or local_var_params['code'] is None): raise ApiValueError("Missing the required parameter `code` when calling `add_date_to_calendar`") # noqa: E501 # verify the required parameter 'create_date_request' is set if ('create_date_request' not in local_var_params or local_var_params['create_date_request'] is None): raise ApiValueError("Missing the required parameter `create_date_request` when calling `add_date_to_calendar`") # noqa: E501 if ('scope' in local_var_params and len(local_var_params['scope']) > 64): raise ApiValueError("Invalid value for parameter `scope` when calling `add_date_to_calendar`, length must be less than or equal to `64`") # noqa: E501 if ('scope' in local_var_params and len(local_var_params['scope']) < 1): raise ApiValueError("Invalid value for parameter `scope` when calling `add_date_to_calendar`, length must be greater than or equal to `1`") # noqa: E501 if 'scope' in local_var_params and not re.search(r'^[a-zA-Z0-9\-_]+$', local_var_params['scope']): # noqa: E501 raise ApiValueError("Invalid value for parameter `scope` when calling `add_date_to_calendar`, must conform to the pattern `/^[a-zA-Z0-9\-_]+$/`") # noqa: E501 if ('code' in local_var_params and len(local_var_params['code']) > 64): raise ApiValueError("Invalid value for parameter `code` when calling `add_date_to_calendar`, length must be less than or equal to `64`") # noqa: E501 if ('code' in local_var_params and len(local_var_params['code']) < 1): raise ApiValueError("Invalid value for parameter `code` when calling `add_date_to_calendar`, length must be greater than or equal to `1`") # noqa: E501 if 'code' in local_var_params and not re.search(r'^[a-zA-Z0-9\-_]+$', local_var_params['code']): # noqa: E501 raise ApiValueError("Invalid value for parameter `code` when calling `add_date_to_calendar`, must conform to the pattern `/^[a-zA-Z0-9\-_]+$/`") # noqa: E501 collection_formats = {} path_params = {} if 'scope' in local_var_params: path_params['scope'] = local_var_params['scope'] # noqa: E501 if 'code' in local_var_params: path_params['code'] = local_var_params['code'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'create_date_request' in local_var_params: body_params = local_var_params['create_date_request'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['text/plain', 'application/json', 'text/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/json', 'text/json', 'application/*+json']) # noqa: E501 # Authentication setting auth_settings = ['oauth2'] # noqa: E501 # set the LUSID header header_params['X-LUSID-SDK-Language'] = 'Python' header_params['X-LUSID-SDK-Version'] = '0.11.3192' return self.api_client.call_api( '/api/calendars/generic/{scope}/{code}/dates', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='CalendarDate', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_calendar(self, create_calendar_request, **kwargs): # noqa: E501 """[EXPERIMENTAL] Create a calendar in its generic form # noqa: E501 Create a calendar in a generic form which can be used to store date events. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_calendar(create_calendar_request, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param CreateCalendarRequest create_calendar_request: A request to create the calendar (required) :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Calendar If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_calendar_with_http_info(create_calendar_request, **kwargs) # noqa: E501 def create_calendar_with_http_info(self, create_calendar_request, **kwargs): # noqa: E501 """[EXPERIMENTAL] Create a calendar in its generic form # noqa: E501 Create a calendar in a generic form which can be used to store date events. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_calendar_with_http_info(create_calendar_request, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param CreateCalendarRequest create_calendar_request: A request to create the calendar (required) :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(Calendar, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = ['create_calendar_request'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_calendar" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'create_calendar_request' is set if ('create_calendar_request' not in local_var_params or local_var_params['create_calendar_request'] is None): raise ApiValueError("Missing the required parameter `create_calendar_request` when calling `create_calendar`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'create_calendar_request' in local_var_params: body_params = local_var_params['create_calendar_request'] # HTTP header
<filename>src/theanets-0.6.1/theanets/layers/recurrent.py # -*- coding: utf-8 -*- r'''Recurrent layers for neural network computation graphs. Recurrent layers are basically defined by the presence of explicitly modeled time dependencies in the computation graph. ''' from __future__ import division import climate import numpy as np import theano import theano.tensor as TT import pdb from . import base from .. import util logging = climate.get_logger(__name__) FLOAT = theano.config.floatX __all__ = [ 'RNN', 'ARRNN', 'LRRNN', 'GRU', 'LSTM', 'LSTMEnc', 'LSTMEncPlain', 'LSTMDecPlain', 'LSTMDec', 'Clockwork', 'MRNN', 'Bidirectional', ] class Recurrent(base.Layer): r'''A recurrent network layer incorporates some dependency on past values. In many respects, a recurrent network layer is much like a basic feedforward layer: both layers take an input signal, apply some transformation to it, and produce an output signal. Recurrent layers, however, additionally preserve the previous state(s) of the layer's output and incorporate them into the transformation of the current input. This layer type is actually just a base class for the many different types of recurrent network layers, for example :class:`RNN` or :class:`LSTM`. Recurrent layer types can only be included in ``theanets`` models that use recurrent inputs and outputs, i.e., :class:`theanets.recurrent.Autoencoder`, :class:`theanets.recurrent.Predictor`, :class:`theanets.recurrent.Classifier`, or :class:`theanets.recurrent.Regressor`. Parameters ---------- radius : float, optional If given, rescale the initial weights for the recurrent units to have this spectral radius. No scaling is performed by default. direction : {None, 'back', 'backwards'}, optional If given, this string indicates whether the recurrency for this layer should run "backwards", with future states influencing the current state. The default is None, which runs the recurrency forwards in time so that past states influence the current state of the layer. bptt_limit : int, optional If given, limit backpropagation of gradient information in scans (loops) to the given number of time steps. Defaults to -1, which imposes no limit. ''' def __init__(self, **kwargs): super(Recurrent, self).__init__(**kwargs) def initial_state(self, name, batch_size): '''Return an array of suitable for representing initial state. Parameters ---------- name : str Name of the variable to return. batch_size : int Number of elements in a batch. This can be symbolic. Returns ------- initial : theano shared variable A variable containing the initial state of some recurrent variable. ''' values = theano.shared( np.zeros((1, self.size), FLOAT), name=self._fmt('{}0'.format(name))) return TT.repeat(values, batch_size, axis=0) def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, radius=0, diagonal=0): '''Helper method to create a new weight matrix. Parameters ---------- name : str Name of parameter to define. nin : int, optional Size of "input" for this weight matrix. Defaults to self.nin. nout : int, optional Size of "output" for this weight matrix. Defaults to self.nout. mean : float, optional Mean of initial matrix values. Defaults to 0. std : float, optional Standard deviation of initial matrix values. Defaults to :math:`1 / sqrt(n_i + n_o)`. sparsity : float, optional Fraction of weights to set randomly to zero. Defaults to 0. radius : float, optional If nonzero, rescale initial weights to have this spectral radius. Defaults to 0. ''' glorot = 1 / np.sqrt(nin + nout) mean = self.kwargs.get( 'mean_{}'.format(name), self.kwargs.get('mean', mean)) std = self.kwargs.get( 'std_{}'.format(name), self.kwargs.get('std', std or glorot)) s = self.kwargs.get( 'sparsity_{}'.format(name), self.kwargs.get('sparsity', sparsity)) r = self.kwargs.get( 'radius_{}'.format(name), self.kwargs.get('radius', radius)) d = self.kwargs.get( 'diagonal_{}'.format(name), self.kwargs.get('diagonal', diagonal)) if nin == self.size and nout % nin == 0: arr = np.concatenate([ util.random_matrix(nin, nin, mean, std, sparsity=s, radius=r, diagonal=d, rng=self.nrng) for _ in range(nout // nin)], axis=1) else: arr = util.random_matrix(nin, nout, mean, std, sparsity=s, rng=self.nrng) self._params.append(theano.shared(arr, name=self._fmt(name))) def _scan(self, fn, inputs, inits=None, name='scan'): '''Helper method for defining a basic loop in theano. Parameters ---------- fn : callable The callable to apply in the loop. inputs : sequence of theano expressions Inputs to the scan operation. inits : sequence of None, tensor, tuple, or scan output specifier Specifiers for the outputs of the scan operation. This should be a list containing: - None for values that are output by the scan but not tapped as inputs, - a theano tensor variable with a 'shape' attribute, or - a tuple containing a string and an integer for output values that are also tapped as inputs, or - a dictionary containing a full output specifier. See "outputs_info" in the Theano documentation for ``scan``. name : str, optional Name of the scan variable to create. Defaults to 'scan'. Returns ------- output(s) : theano expression(s) Theano expression(s) representing output(s) from the scan. updates : sequence of update tuples A sequence of updates to apply inside a theano function. ''' outputs = [] for i, x in enumerate(inits or inputs): if hasattr(x, 'shape'): x = self.initial_state(str(i), x.shape[1]) elif isinstance(x, int): x = self.initial_state(str(i), x) elif isinstance(x, tuple): x = self.initial_state(*x) outputs.append(x) return theano.scan( fn, name=self._fmt(name), sequences=inputs, outputs_info=outputs, go_backwards='back' in self.kwargs.get('direction', '').lower(), truncate_gradient=self.kwargs.get('bptt_limit', -1), ) class RNN(Recurrent): r'''Standard recurrent network layer. There are many different styles of recurrent network layers, but the one implemented here is known as an Elman layer or an SRN (Simple Recurrent Network) -- the output from the layer at the previous time step is incorporated into the input of the layer at the current time step. ''' def setup(self): '''Set up the parameters and initial values for this layer.''' self.add_weights('xh', self.input_size, self.size) self.add_weights('hh', self.size, self.size) self.add_bias('b', self.size) def transform(self, inputs): '''Transform the inputs for this layer into an output for the layer. Parameters ---------- inputs : dict of theano expressions Symbolic inputs to this layer, given as a dictionary mapping string names to Theano expressions. See :func:`base.Layer.connect`. Returns ------- outputs : dict of theano expressions A map from string output names to Theano expressions for the outputs from this layer. This layer type generates a "pre" output that gives the unit activity before applying the layer's activation function, and an "out" output that gives the post-activation output. updates : list of update pairs A sequence of updates to apply inside a theano function. ''' def fn(x_t, h_tm1): pre = x_t + TT.dot(h_tm1, self.find('hh')) return [pre, self.activate(pre)] x = TT.dot(self._only_input(inputs), self.find('xh')) + self.find('b') (pre, out), updates = self._scan(fn, [x], [None, x]) return dict(pre=pre, out=out), updates class LRRNN(Recurrent): r'''A learned-rate RNN defines per-hidden-unit accumulation rates. In a normal RNN, a hidden unit is updated completely at each time step, :math:`h_t = f(x_t, h_{t-1})`. With an explicit update rate, the state of a hidden unit is computed as a mixture of the new and old values, `h_t = \alpha_t h_{t-1} + (1 - \alpha_t) f(x_t, h_{t-1})`. Rates might be defined in a number of ways, spanning a continuum between vanilla RNNs (i.e., all rate parameters are fixed at 1), fixed but non-uniform rates for each hidden unit [Ben12]_, parametric rates that are dependent only on the input (i.e., the :class:`ARRNN`), all the way to parametric rates that are computed as a function of the inputs and the hidden state at each time step (i.e., something more like the :class:`gated recurrent unit <GRU>`). This class represents rates as a single learnable vector of parameters. This representation uses the fewest number of parameters for learnable rates, but the simplicity of the model comes at the cost of effectively fixing the rate for each unit as a constant value across time. References ---------- .. [Ben12] <NAME>, <NAME>, <NAME>. (2012) "Advances in Optimizing Recurrent Networks." http://arxiv.org/abs/1212.0901 ''' def setup(self): '''Set up the parameters and initial values for this layer.''' self.add_weights('xh', self.input_size, self.size) self.add_weights('hh', self.size, self.size) self.add_bias('b', self.size) self.add_bias('r', self.size, mean=2, std=1) def transform(self, inputs): '''Transform the inputs for this layer into an output for the layer. Parameters ---------- inputs : dict of theano expressions Symbolic inputs to this layer, given as a dictionary mapping string names to Theano expressions. See :func:`base.Layer.connect`. Returns ------- outputs : theano expression A map from string output names to Theano expressions for the outputs from this layer. This layer type generates a "pre" output that gives the unit activity before applying the layer's activation function, a "hid" output that gives the rate-independent, post-activation hidden state, a "rate" output that gives the
**kwargs ): self.channel_widths = channel_widths self.final_pool_shape = final_pool_shape self.init_kernel_shape = init_kernel_shape self.init_kernel_strides = init_kernel_strides self.kernel_shape = kernel_shape self.output_size = dense_hidden_size self.activation = get_tf_activation(act_name) self.reg_coef = reg_coef self.dropout_final_layer = dropout_params[0] self.dropout_params = dropout_params[1:] self.max_num_ratios = max_num_ratios self.use_cond_scale_shift = use_cond_scale_shift self.shift_scale_per_channel = shift_scale_per_channel self.use_instance_norm = use_instance_norm self.use_attention = use_attention if max_spectral_norm_params is not None: self.max_spectral_norm_params = max_spectral_norm_params[1:] else: self.max_spectral_norm_params = None self.just_track_spectral_norm = just_track_spectral_norm self.img_shape = img_shape self.use_average_pooling = use_average_pooling self.use_global_sum_pooling = use_global_sum_pooling if max_spectral_norm_params or just_track_spectral_norm: self.conv_fn = SpectralConv self.dense_fn = SpectralDense else: self.conv_fn = make_flexible_Conv2D_fn() self.dense_fn = make_flexible_Dense_fn() self.model = self.build_resnet(self.channel_widths, self.img_shape) for loss in self.model.losses: tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, loss) def build_resnet(self, channel_widths, shape): inputs = k_layers.Input(shape=shape) if self.use_cond_scale_shift: cond_idxs = k_layers.Input(shape=(), dtype=tf.int32) else: cond_idxs = None x = self.init_layer(channel_widths, cond_idxs, inputs, shape) x = self.res_blocks(channel_widths, self.kernel_shape, cond_idxs, x) x = self.activation()(x) reduce = k_layers.Lambda(lambda a: tf.reduce_sum(a, axis=[1, 2])) x = reduce(x) # global sum pooling x = self.dense_and_shift_scale(x, cond_idxs, self.output_size, name='final_layer') x = self.activation()(x) if self.dropout_final_layer: x = self.dropout(x, cond_idxs) if self.use_cond_scale_shift: model = Model(inputs=[inputs, cond_idxs], outputs=x) else: model = Model(inputs=inputs, outputs=x) return model def init_layer(self, channel_widths, cond_idxs, inputs, shape): x = self.conv_fn(channel_widths[0][0], self.init_kernel_shape, strides=self.init_kernel_strides, padding='SAME', input_shape=shape, kernel_regularizer=regularizers.l2(self.reg_coef), name='conv2d', use_bias=(cond_idxs is None), just_track_spectral_norm=self.just_track_spectral_norm)(inputs) if cond_idxs is not None: x = CondConvScaleShift(self.max_num_ratios, self.shift_scale_per_channel, self.use_instance_norm, self.max_spectral_norm_params)([x, cond_idxs]) return x def res_blocks(self, channel_widths, kernel_shape, cond_idxs, x): block_counter = 0 for i, widths in enumerate(channel_widths[1:]): for j, width in enumerate(widths): name = 'res_block_{}'.format(block_counter) use_adaptive = (j == 0) and (width != channel_widths[i - 1][-1]) x = self.res_block(x, width, kernel_shape, name=name, pool_shape=(2, 2), use_pooling=(j == 0), adaptive=use_adaptive, cond_idxs=cond_idxs) block_counter += 1 if block_counter == 1 and self.use_attention: x = self.attention(x, channel_widths[0][0]) return x def res_block(self, x, n_channels, kernel_shape, name, pool_shape=(2, 2), use_pooling=False, adaptive=False, cond_idxs=None): """ act - conv - condshiftscale - act - conv - condshiftscale - average pool - add residual""" res = x res = self.activation()(res) res = self.conv_and_shift_scale(res, n_channels, kernel_shape, name + "_conv1", cond_idxs=cond_idxs) res = self.dropout(res, cond_idxs) res = self.activation()(res) res = self.conv_and_shift_scale(res, n_channels, kernel_shape, name + "_conv2", cond_idxs=cond_idxs) # zero_init=True breaks when used in conjuction with spectral norm if use_pooling: if self.use_average_pooling: res = k_layers.AveragePooling2D(pool_size=pool_shape, padding='SAME')(res) else: res = k_layers.MaxPooling2D(pool_size=pool_shape, padding='SAME')(res) if adaptive: x = self.conv_and_shift_scale(x, n_channels, (1, 1), name + "_conv3", cond_idxs=cond_idxs) if use_pooling: if self.use_average_pooling: x = k_layers.AveragePooling2D(pool_size=pool_shape, padding='SAME')(x) else: x = k_layers.MaxPooling2D(pool_size=pool_shape, padding='SAME')(x) x = k_layers.Add()([x, res]) return x def conv_and_shift_scale(self, x, n_channels, kernel_shape, name, cond_idxs=None, zero_init=False): kernel_init = 'zeros' if zero_init else 'glorot_uniform' x = self.conv_fn(n_channels, kernel_shape, padding='SAME', name=name, kernel_initializer=kernel_init, kernel_regularizer=regularizers.l2(self.reg_coef), use_bias=(cond_idxs is None), just_track_spectral_norm=self.just_track_spectral_norm)(x) if cond_idxs is not None: x = CondConvScaleShift(self.max_num_ratios, self.shift_scale_per_channel, self.use_instance_norm, self.max_spectral_norm_params)([x, cond_idxs]) return x def dropout(self, x, cond_idxs): if cond_idxs is not None: x = CondDropout(*self.dropout_params, max_n_ratios=self.max_num_ratios, is_wmark_dim=False)([x, cond_idxs]) else: x = k_layers.Dropout(self.dropout_params[0])(x) # 'params' just contains dropout rate in this case return x def dense_and_shift_scale(self, h, cond_idxs, size, name): reg = regularizers.l2(self.reg_coef) h = self.dense_fn(units=size, kernel_regularizer=reg, name=name, just_track_spectral_norm=self.just_track_spectral_norm)(h) if self.use_cond_scale_shift: h = CondScaleShift(self.max_num_ratios, size, name, self.max_spectral_norm_params)([h, cond_idxs]) return h @staticmethod def attention(x, channels): f = k_layers.Conv2D(channels // 8, (1, 1), padding='SAME', name='f_attn_conv')(x) # [bs, h, w, c'] g = k_layers.Conv2D(channels // 8, (1, 1), padding='SAME', name='g_attn_conv')(x) # [bs, h, w, c'] h = k_layers.Conv2D(channels, (1, 1), padding='SAME', name='h_attn_conv')(x) # [bs, h, w, c'] # N = h * w s = tf_keras_matmul(tf_keras_hw_flatten(g), tf_keras_hw_flatten(f), transpose_b=True) # # [bs, N, N] beta = k_layers.Softmax()(s) # attention map o = tf_keras_matmul(beta, tf_keras_hw_flatten(h)) # [bs, N, C] o = k_layers.Reshape(x.shape[1:])(o) # [bs, h, w, C] o = k_layers.Conv2D(channels, (1, 1), padding='SAME', name='attn_conv')(o) o = ScaleShift(1, "attn_gamma", use_shift=False, scale_init='zeros')(o) x = o + x return x class ResNetEnergy(ResNet): """Resnet energy function""" def __init__(self, **kwargs): self._bridge_idxs = kwargs["bridge_idxs"] self.num_ratios = shape_list(self._bridge_idxs)[0] super().__init__(**kwargs) if (kwargs["max_spectral_norm_params"] is not None) and kwargs["max_spectral_norm_params"][0]: head_spec_params = kwargs["max_spectral_norm_params"][1:] else: head_spec_params = None del kwargs["max_spectral_norm_params"] self.heads = init_heads(body_output_size=self.output_size, max_spectral_norm_params=head_spec_params, **kwargs ) # self.assign_new_head = self.final_layer.assign_new_head self.head_assignments = self.heads.head_assignments @property def bridge_idxs(self): return self._bridge_idxs @bridge_idxs.setter def bridge_idxs(self, val): self.heads.bridge_idxs = val self._bridge_idxs = val self.num_ratios = shape_list(self._bridge_idxs)[0] def neg_energy(self, x, is_train, is_wmark_input=False): x_shp = shape_list(x) if self.use_cond_scale_shift: x, cond_idxs = ready_x_for_per_bridge_convnet(x, is_wmark_input, self.bridge_idxs) h = self.model([x, cond_idxs], training=is_train) h = tf.reshape(h, [-1, self.num_ratios, self.output_size]) # (?, num_ratios, out_dim) neg_e = self.heads.eval(h, is_train=is_train, is_wmark_input=is_wmark_input) # (?, num_ratios) else: if is_wmark_input: x = tf.reshape(x, [-1, *x_shp[2:]]) # (n*n_waymarks, ...) h = self.model(x, training=is_train) if is_wmark_input: h = tf.reshape(h, [-1, self.num_ratios + 1, self.output_size]) # (n, n_waymarks, out_dim) h = ready_x_for_per_bridge_computation(h, is_wmark_input, self.bridge_idxs) neg_e = self.heads.eval(h, is_train=is_train, is_wmark_input=is_wmark_input) # (?, num_ratios) return neg_e # (?, num_ratios) class SeparableEnergy: def __init__(self, bridge_idxs, max_num_ratios, config, only_f=False): # note: this code duplicates code from elsewhere - needs refactoring eventually self._bridge_idxs = bridge_idxs if bridge_idxs is not None: self.num_ratios = shape_list(self.bridge_idxs)[0] self.max_num_ratios = max_num_ratios self.use_cond_scale_shift = config.use_cond_scale_shift self.network_type = config.network_type self.only_f = only_f self.build_nets(config) self.output_size = self.f.output_size if not only_f: self.heads = BilinearHeads( input_dim=self.output_size, bridge_idxs=bridge_idxs, max_num_ratios=max_num_ratios, use_single_head=config.get("use_single_head", False), max_spectral_norm_params=config.get("max_spectral_norm_params", None) ) @property def bridge_idxs(self): return self._bridge_idxs @bridge_idxs.setter def bridge_idxs(self, val): self.heads.bridge_idxs = val self._bridge_idxs = val self.num_ratios = shape_list(self._bridge_idxs)[0] def neg_energy(self, xy, is_train, is_wmark_input=False): assert not self.only_f, "'only_f=True' was passed into the constructor, which means that the g network" \ "was not built, and thus the log-ratio cannot be computed" x, y = xy # x.shape = (n_batch, *event_dims), y.shape = (n_batch, n_waymarks, *event_dims) # compute the final hidden vectors for each x & y_k f_x = self.compute_f_hiddens(x, is_train) g_y = self.compute_g_hiddens(y, is_train, is_wmark_input) # (?, n_ratios, output_size) # duplicate fx along axis 0 # (by default, the duplication factor will be 2 to account for positive & negative samples) dup_factor = tf.cast(shape_list(g_y)[0] / shape_list(f_x)[0], dtype=tf.int32) f_x = tf.tile(f_x, [dup_factor, 1]) # map these vectors to a scalar neg_e = self.heads.eval(f_x, g_y, is_train=is_train, is_wmark_input=is_wmark_input) return neg_e # (?, num_ratios) def compute_f_hiddens(self, x, is_train): if self.network_type == "mlp": x = collapse_event_dims(x, is_wmark_input=False) return self.f.model(x, training=is_train) # (?, output_size) def compute_g_hiddens(self, y, is_train, is_wmark_input): if self.network_type == "mlp": y = collapse_event_dims(y, is_wmark_input=is_wmark_input) y_shp = shape_list(y) if self.network_type == "resnet": if self.use_cond_scale_shift: y, cond_idxs = ready_x_for_per_bridge_convnet(y, is_wmark_input, self.bridge_idxs) h = self.g.model([y, cond_idxs], training=is_train) h = tf.reshape(h, [-1, self.num_ratios, self.output_size]) # (?, num_ratios, out_dim) else: if is_wmark_input: y = tf.reshape(y, [-1, *y_shp[2:]]) # (n*n_waymarks, ...) h = self.g.model(y, training=is_train) if is_wmark_input: h = tf.reshape(h, [-1, self.num_ratios + 1, self.output_size]) # (n, n_waymarks, out_dim) h = ready_x_for_per_bridge_computation(h, is_wmark_input, self.bridge_idxs) # (?, n_ratios, d) elif self.network_type == "mlp": if self.use_cond_scale_shift: y = ready_x_for_per_bridge_computation(y, is_wmark_input, self.bridge_idxs) # (?, n_ratios, d) h = self.g.model([y, tf.convert_to_tensor(self.bridge_idxs)], training=is_train) else: h = self.g.model([y, tf.convert_to_tensor(self.bridge_idxs)], training=is_train) h = ready_x_for_per_bridge_computation(h, is_wmark_input, self.bridge_idxs) # (?, n_ratios, d) return h # (?, n_ratios, output_size) def build_nets(self, config): if config.network_type == "resnet": if not self.only_f: with tf.variable_scope("g_network"): self.g = ResNet(channel_widths=config.channel_widths, dense_hidden_size=config.mlp_hidden_size, act_name=config.activation_name, reg_coef=config.energy_reg_coef, dropout_params=config.dropout_params, max_num_ratios=self.max_num_ratios, use_cond_scale_shift=config.use_cond_scale_shift, shift_scale_per_channel=config.shift_scale_per_channel, use_instance_norm=config.use_instance_norm, max_spectral_norm_params=config.get("max_spectral_norm_params", None), just_track_spectral_norm=config.get("just_track_spectral_norm", False), img_shape=config.data_args["img_shape"][:-1], use_average_pooling=config.get("use_average_pooling", True), use_global_sum_pooling=config.use_global_sum_pooling, use_attention=config.use_attention, final_pool_shape=config.final_pool_shape, kernel_shape=config.conv_kernel_shape, init_kernel_shape=config.get("init_kernel_shape", (3, 3)), init_kernel_strides=config.get("init_kernel_strides", (1, 1)) ) with tf.variable_scope("f_network"): self.f = ResNet(channel_widths=config.channel_widths, dense_hidden_size=config.mlp_hidden_size, act_name=config.activation_name, reg_coef=config.energy_reg_coef, dropout_params=config.dropout_params, max_num_ratios=None, use_cond_scale_shift=False, shift_scale_per_channel=False, use_instance_norm=False, max_spectral_norm_params=config.get("max_spectral_norm_params", None), just_track_spectral_norm=config.get("just_track_spectral_norm", False), img_shape=config.data_args["img_shape"][:-1], use_average_pooling=config.get("use_average_pooling", True), use_global_sum_pooling=config.use_global_sum_pooling, use_attention=config.use_attention, final_pool_shape=config.final_pool_shape, kernel_shape=config.conv_kernel_shape, init_kernel_shape=config.get("init_kernel_shape", (3, 3)), init_kernel_strides=config.get("init_kernel_strides", (1, 1)) ) elif config.network_type == "mlp": if not self.only_f: with tf.variable_scope("g_network"): self.g = CondMlp(input_size=int(config.n_dims/2), hidden_size=config.mlp_hidden_size, output_size=config.mlp_output_size, num_blocks=config.mlp_n_blocks, act_name=config.activation_name, reg_coef=config.energy_reg_coef, dropout_params=config.dropout_params, max_num_ratios=self.max_num_ratios, use_cond_scale_shift=config.use_cond_scale_shift, use_residual=config.use_residual_mlp, max_spectral_norm_params=config.get("max_spectral_norm_params", None) ) with tf.variable_scope("f_network"): self.f = CondMlp(input_size=int(config.n_dims/2), hidden_size=config.mlp_hidden_size, output_size=config.mlp_output_size, num_blocks=config.mlp_n_blocks, act_name=config.activation_name, reg_coef=config.energy_reg_coef, dropout_params=config.dropout_params, max_num_ratios=None, use_cond_scale_shift=False, use_residual=config.use_residual_mlp, max_spectral_norm_params=config.get("max_spectral_norm_params", None) ) class GaussEnergy: """Unnormalised gaussian with identity covariance matrix""" def __init__(self, n_dims, normalised=False): self.n_dims = n_dims self.c = 0. # scaling param (approximates log partition) self.true_partition = tf.constant(0., tf.float32) self.normalised = normalised @tf_cache_template("mlp_energy", initializer=initializers.glorot_normal()) def log_prob(self, x): if self.normalised: loc = tf.compat.v1.get_variable("gauss_loc", shape=self.n_dims, dtype=tf.float32, initializer=tf.zeros_initializer()) scale = tf.compat.v1.get_variable("gauss_scale", dtype=tf.float32, initializer=tf.eye(self.n_dims)) ebm = tfd.MultivariateNormalFullCovariance(loc=loc, covariance_matrix=scale) energy = -ebm.log_prob(x) else: # use diagonal covariance, so partition function is simple mean = tf.compat.v1.get_variable("gauss_mean", self.n_dims, dtype=tf.float32) diag = tf.compat.v1.get_variable("gauss_diag", self.n_dims, dtype=tf.float32) self.true_partition = 0.5 * (self.n_dims * tf.log(2 * np.pi) - tf.reduce_sum(diag)) x_centred = x - mean energy = 0.5 * tf.reduce_sum(tf.square(x_centred) * tf.exp(diag), axis=1) self.c = tf.compat.v1.get_variable("scaling_param",
#!/usr/bin/env python3 """ c19_make_pipeline.py: creates a snakemake-based pipeline directory, given a set of input .fastq.gz files. The input .fastq.gz filenames must contain substrings such as '_R1_' or '_R2_' indicating the read direction. Usage: # First create the directory $HOME/data, which should contain a copy of (or be a symlink to) # galaxylab:/home/kmsmith/data (warning: 61 GB!) # Create pipeline ./c19_make_pipeline.py -o Iran1 $HOME/data/MT-swab-Iran-Liverpool*.fastq.gz # Run pipeline (cacheing conda envs in $HOME/.snakemake) cd Iran1/ # directory created by 'c19_make_pipeline.py' snakemake -p --cores=16 --use-conda --conda-prefix=$HOME/.snakemake all TODO: this script only creates single-sample pipelines, but the Snakemake workflow supports multiple samples. """ import os import re import sys import shutil import argparse from collections import OrderedDict class Pipeline: """ The default constructor initializes a Pipeline from command-line arguments in sys.argv. The following members are initialized: self.outdir pipeline directory to be created self.original_fastq_files_R1 list of "out-of-tree" filenames specified on command line self.original_fastq_files_R2 list of "out-of-tree" filenames specified on command line self.input_fastq_files_R1 list of "in-tree" filenames, relative to sample subdir (not toplevel dir) self.input_fastq_files_R2 list of "in-tree" filenames, relative to sample subdir (not toplevel dir) self.copies for debugging: number of redundant copies of sample to be analyzed in parallel """ # TODO datadir currently hardcoded as '$HOME/data', should introduce command-line flag to override default datadir = os.path.join(os.environ['HOME'], 'data') # TODO lots of hardcoded parameters here, is this what we want? # Used as -a,-A arguments to 'cutadapt' primer_rc = os.path.join(datadir, 'wuhan_primers_28.01.20_trim_RC.fa') primer_fw = os.path.join(datadir, 'wuhan_primers_28.01.20_trim_FW.fa') # Last arguments on 'trimmomatic' command line (after input, output files) trimmomatic_args = 'ILLUMINACLIP:/home/kmsmith/data/NexteraPE-PE.fa:2:30:10 SLIDINGWINDOW:4:20' # Used as hisat2 reference genome when removing host sequences. # Also used as 'ivar' reference genome in variant detection + consensus. hostremove_reference = os.path.join(datadir, 'MN908947_3.fasta') # Used as --reference argument to 'breseq' breseq_reference = os.path.join(datadir, 'MN908947_primer_annotated_prot_clinical.gb') # Used as --db argument to 'kraken2' kraken2_db = os.path.join(datadir, 'Kraken2/db') # Consensus and variant calling ivar/samtools params from https://github.com/connor-lab/ncov2019-artic-nf/blob/master/conf/illumina.config mpileup_depth = 100000 # ivar frequency threshold to build consensus ivar_freq_threshold = 0.75 # Minimum coverage depth to call variant ivar_min_coverage_depth = 10 # iVar frequency threshold to call variant (ivar variants: -t ) ivar_min_freq_threshold = 0.25 # iVar minimum mapQ to call variant (ivar variants: -q) ivar_min_variant_quality = 20 # lmat_fragment_size: size of fragments (in bp) analyzed by 'lmat' # Absolute pathname of the LMAT DB is {lmat_basedir}/data/{lmat_db}. # LMAT's expected "runtime inputs" (e.g. 'ncbi_taxid_to_rank.txt') should be in {lmat_basedir}/runtime_inputs. lmat_fragment_size = 250 lmat_basedir = os.path.join(datadir, 'LMAT-1.2.6') lmat_db = 'kML+Human.v4-14.20.g10.db' # Used as -r,-g arguments to 'quast' quast_reference_genome = os.path.join(datadir, 'MN908947_3.fasta') quast_feature_coords = os.path.join(datadir, 'MN908947_3.gff3') def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outdir', required=True, help='pipeline directory (will be created, must not already exist)') parser.add_argument('--copies', type=int, default=1, help='for debugging: number of redundant copies of sample to be analyzed in parallel') parser.add_argument('input_fastq_files', nargs='+', help='list of .fastq.gz input files') args = parser.parse_args() assert args.copies >= 1 # Currently 'prefix' is deduced from the output directory name. (This behavior could # be overridden with optional command-line argument, if this seems like a useful feature.) self.outdir = args.outdir self.ncopies = args.copies # We fail with an error if the pipeline output directory already exists. # This behavior is heavy-handed, but ensures that a pipeline user can never # inadvertantly overwrite or modify previous runs. # TODO: add command-line flag to override this behavior? if os.path.exists(self.outdir): self._die(f"output directory {self.outdir} already exists; must be deleted or renamed before making a new pipeline.") # The rest of this method mostly consists of sanity-checking code, to verify that # the input filenames "pair" nicely into (R1,R2) pairs. If this sanity check fails, # then we currently fail with an error -- is this the right thing to do? # # An example of a well-formed (R1,R2) filename pair: # MT-swab-Iran-Liverpool-pool1_S3_L001_R1_001.fastq.gz # MT-swab-Iran-Liverpool-pool1_S3_L001_R2_001.fastq.gz # Hash (prefix, suffix) -> (R1_filename, R2_filename) pair_analysis = OrderedDict() for input_file in args.input_fastq_files: # Currently we require all input files to be .fastq.gz files. # TODO: allow input files to be either .fastq or .fastq.gz instead? if not input_file.endswith('.fastq.gz'): self._die(f"expected input filename {input_file} to end in .fastq.gz") if not os.path.exists(input_file): self._die(f"input file {input_file} not found") # Regex pattern for identifying a substring such as '_R1_' or '_R2_' indicating read direction. # We allow a little flexibility here (case-insensitive, underscore can be replaced by hyphen or period). # This pattern is just a guess and we may want to rethink it later! pattern = r'([-_.][rR][12][-_.])' b = os.path.basename(input_file) m = re.search(pattern, b) if m is None: self._die(f"expected input filename {input_file} to contain substring such as '_R1_' or '_R2_' indicating read direction") assert m.group(0)[2] in ['1','2'] r = int(m.group(0)[2]) # read direction (either 1 or 2) x = b[:m.start()] # prefix (part of basename preceding regex pattern match) y = b[m.end():] # suffix (part of basename following regex pattern match) if re.search(pattern, y) is not None: self._die(f"input filename {input_file} contains multiple substrings such as '_R1_' or '_R2_' indicating read direction") if (x,y) not in pair_analysis: pair_analysis[x,y] = [None, None] if pair_analysis[x,y][r-1] is not None: self._die(f"confused by similar filenames {pair_analysis[x,y][r-1]} and {input_file}") pair_analysis[x,y][r-1] = input_file # Reorganize the input filenames into (R1,R2) pairs. self.original_fastq_files_R1 = [ ] self.original_fastq_files_R2 = [ ] pair_analysis_ok = True for ((x,y),(f1,f2)) in pair_analysis.items(): self.original_fastq_files_R1.append(f1) self.original_fastq_files_R2.append(f2) if (f1 is None) or (f2 is None): pair_analysis_ok = False # If the input filenames don't "pair" nicely into (R1,R2) pairs, # we currently fail with an error and let the user sort it out. if not pair_analysis_ok: print("Fatal: couldn't pair input filenames into (R1,R2) pairs", file=sys.stderr) print("Filename pair analysis follows", file=sys.stderr) for (f1,f2) in self.original_fastq_file_pairs: for f in (f1,f2): t = f if (f is not None) else "[** missing **]" print(f" {t}", file=sys.stderr, end='') print(file=sys.stderr) sys.exit(1) # Assign in-tree filenames to the input files. (Each input file is represented by # an "original" filename which was specified on the command line, and an "in-tree" # or "input" copy which will be used in the actual pipeline. The original files # are copied to their in-tree counterparts in self.copy_input_fastq_files().) self.input_fastq_files_R1 = [ ] self.input_fastq_files_R2 = [ ] for f in self.original_fastq_files_R1: self.input_fastq_files_R1.append(os.path.join('fastq_inputs', os.path.basename(f))) for f in self.original_fastq_files_R2: self.input_fastq_files_R2.append(os.path.join('fastq_inputs', os.path.basename(f))) def write(self): self.write_config_yaml() self.copy_workflow_files() self.copy_input_fastq_files() def write_config_yaml(self): """Writes {pipeline_output_dir}/config.yaml.""" filename = os.path.join(self.outdir, 'config.yaml') self._mkdir_for_file(filename) print(f"Writing {filename}") with open(filename,'w') as f: print(f"# Autogenerated by c19_make_pipeline.py -- do not edit!", file=f) print(file=f) print(f"# This file contains a high-level summary of pipeline configuration and inputs.", file=f) print(f"# It is ingested by the Snakefile, and also intended to be human-readable.", file=f) print(file=f) print("# Used as -a,-A arguments to 'cutadapt'", file=f) print(f"primer_rc: {repr(self.primer_rc)}", file=f) print(f"primer_fw: {repr(self.primer_fw)}", file=f) print(file=f) print(f"# Last arguments on 'trimmomatic' command line (after input, output files)", file=f) print(f"trimmomatic_args: {repr(self.trimmomatic_args)}", file=f) print(file=f) print("# Used as hisat2 reference genome when removing host sequences.", file =f) print("# Also used as 'ivar' reference genome in variant detection + consensus.", file =f) print(f"hostremove_reference: {repr(self.hostremove_reference)}", file=f) print(file=f) print(f"# Used as --reference argument to 'breseq'", file=f) print(f"breseq_reference: {repr(self.breseq_reference)}", file=f) print(file=f) print(f"# Used as --db argument to 'kraken2'", file=f) print(f"kraken2_db: {repr(self.kraken2_db)}", file=f) print(file=f) print(f"# Consensus and variant calling ivar/samtools params from https://github.com/connor-lab/ncov2019-artic-nf/blob/master/conf/illumina.config", file=f) print(f"mpileup_depth: {repr(self.mpileup_depth)}", file=f) print(f"# ivar frequency threshold to build consensus", file=f) print(f"ivar_freq_threshold: {repr(self.ivar_freq_threshold)}", file=f) print(f"# Minimum coverage depth to call variant", file=f) print(f"ivar_min_coverage_depth: {repr(self.ivar_min_coverage_depth)}", file=f) print(f"# iVar frequency threshold to call variant (ivar variants: -t )", file=f) print(f"ivar_min_freq_threshold: {repr(self.ivar_min_freq_threshold)}", file=f) print(f"# iVar minimum mapQ to call variant (ivar variants: -q)", file=f) print(f"ivar_min_variant_quality: {repr(self.ivar_min_variant_quality)}", file=f) print(file=f) print(f"# lmat_fragment_size: size of fragments (in bp) analyzed by 'lmat'", file=f) print(f"# Absolute pathname of the LMAT DB is {{lmat_basedir}}/data/{{lmat_db}}.", file=f) print(f"# LMAT's expected \"runtime inputs\" (e.g. 'ncbi_taxid_to_rank.txt') should be in {{lmat_basedir}}/runtime_inputs.", file=f) print(f"lmat_fragment_size: {repr(self.lmat_fragment_size)}", file=f) print(f"lmat_basedir: {repr(self.lmat_basedir)}", file=f) print(f"lmat_db: {repr(self.lmat_db)}", file=f) print(file=f) print(f"# Used as -r,-g arguments to 'quast'", file=f)
labels_cityscapes = [ # name id trainId category catId hasInstances ignoreInEval color ( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), ( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), ( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), ( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), ( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), ( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ), ( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ), ( 'road' , 7 , 0 , 'flat' , 1 , False , False , (128, 64,128) ), ( 'sidewalk' , 8 , 1 , 'flat' , 1 , False , False , (244, 35,232) ), ( 'parking' , 9 , 255 , 'flat' , 1 , False , True , (250,170,160) ), ( 'rail track' , 10 , 255 , 'flat' , 1 , False , True , (230,150,140) ), ( 'building' , 11 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ), ( 'wall' , 12 , 3 , 'construction' , 2 , False , False , (102,102,156) ), ( 'fence' , 13 , 4 , 'construction' , 2 , False , False , (190,153,153) ), ( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ), ( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ), ( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ), ( 'pole' , 17 , 5 , 'object' , 3 , False , False , (153,153,153) ), ( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ), ( 'traffic light' , 19 , 6 , 'object' , 3 , False , False , (250,170, 30) ), ( 'traffic sign' , 20 , 7 , 'object' , 3 , False , False , (220,220, 0) ), ( 'vegetation' , 21 , 8 , 'nature' , 4 , False , False , (107,142, 35) ), ( 'terrain' , 22 , 9 , 'nature' , 4 , False , False , (152,251,152) ), ( 'sky' , 23 , 10 , 'sky' , 5 , False , False , ( 70,130,180) ), ( 'person' , 24 , 11 , 'human' , 6 , True , False , (220, 20, 60) ), ( 'rider' , 25 , 12 , 'human' , 6 , True , False , (255, 0, 0) ), ( 'car' , 26 , 13 , 'vehicle' , 7 , True , False , ( 0, 0,142) ), ( 'truck' , 27 , 14 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ), ( 'bus' , 28 , 15 , 'vehicle' , 7 , True , False , ( 0, 60,100) ), ( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ), ( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ), ( 'train' , 31 , 16 , 'vehicle' , 7 , True , False , ( 0, 80,100) ), ( 'motorcycle' , 32 , 17 , 'vehicle' , 7 , True , False , ( 0, 0,230) ), ( 'bicycle' , 33 , 18 , 'vehicle' , 7 , True , False , (119, 11, 32) ), ( 'license plate' , -1 , -1 , 'vehicle' , 7 , False , True , ( 0, 0,142) ), ] labels_carla = [ ('unlabeled', 0, 255, (0, 0, 0)), ('Building', 1, 0, (70, 70, 70)), ('Fence', 2, 1, (100, 40, 40)), ('Pedestrian', 4, 2, (220, 20, 60)), ('Pole', 5, 3, (153, 153, 153)), ('RoadLine', 6, 4, (157, 234, 50)), ('Road', 7, 5, (128, 64, 128)), ('Sidewalk', 8, 6, (244, 35, 232)), ('Vegetation', 9, 7, (107, 142, 35)), ('Vehicles', 10, 8, (0, 0, 142)), ('Wall', 11, 9, (102, 102, 156)), ('TrafficSign', 12, 10, (220, 220, 0)), ('Sky', 13, 11, (7, 130, 180)), ('Ground', 14, 12, (81, 0, 81)), ('Bridge', 15, 13, (150, 100, 100)), ('RailTrack', 16, 14, (230, 150, 140)), ('GuardRail', 17, 15, (180, 165, 180)), ('TrafficLight', 18, 16, (250, 170, 30)), ('Static', 19, 254, (110, 190, 160)), ('Dynamic', 20, 254, (110, 190, 160)), ('Water', 21, 17, (45, 60, 150)), ('Terrain', 22, 18, (145, 170, 100)), ] labels_idd = [ # name csId csTrainId level4id level3Id category level2Id level1Id hasInstances ignoreInEval color ( 'road' , 7 , 0 , 0 , 0 , 'drivable' , 0 , 0 , False , False , (128, 64,128) ), ( 'parking' , 9 , 255 , 1 , 1 , 'drivable' , 1 , 0 , False , False , (250,170,160) ), ( 'drivable fallback' , 255 , 255 , 2 , 1 , 'drivable' , 1 , 0 , False , False , ( 81, 0, 81) ), ( 'sidewalk' , 8 , 1 , 3 , 2 , 'non-drivable' , 2 , 1 , False , False , (244, 35,232) ), ( 'rail track' , 10 , 255 , 3 , 3 , 'non-drivable' , 3 , 1 , False , False , (230,150,140) ), ( 'non-drivable fallback', 255 , 9 , 4 , 3 , 'non-drivable' , 3 , 1 , False , False , (152,251,152) ), ( 'person' , 24 , 11 , 5 , 4 , 'living-thing' , 4 , 2 , True , False , (220, 20, 60) ), ( 'animal' , 255 , 19 , 6 , 4 , 'living-thing' , 4 , 2 , True , True , (246, 198, 145)), ( 'rider' , 25 , 12 , 7 , 5 , 'living-thing' , 5 , 2 , True , False , (255, 0, 0) ), ( 'motorcycle' , 32 , 17 , 8 , 6 , '2-wheeler' , 6 , 3 , True , False , ( 0, 0,230) ), ( 'bicycle' , 33 , 18 , 9 , 7 , '2-wheeler' , 6 , 3 , True , False , (119, 11, 32) ), ( 'autorickshaw' , 255 , 20 , 10 , 8 , 'autorickshaw' , 7 , 3 , True , False , (255, 204, 54) ), ( 'car' , 26 , 13 , 11 , 9 , 'car' , 7 , 3 , True , False , ( 0, 0,142) ), ( 'truck' , 27 , 14 , 12 , 10 , 'large-vehicle' , 8 , 3 , True , False , ( 0, 0, 70) ), ( 'bus' , 28 , 15 , 13 , 11 , 'large-vehicle' , 8 , 3 , True , False , ( 0, 60,100) ), ( 'caravan' , 29 , 255 , 14 , 12 , 'large-vehicle' , 8 , 3 , True , True , ( 0, 0, 90) ), ( 'trailer' , 30 , 255 , 15 , 12 , 'large-vehicle' , 8 , 3 , True , True , ( 0, 0,110) ), ( 'train' , 31 , 16 , 15 , 12 , 'large-vehicle' , 8 , 3 , True , True , ( 0, 80,100) ), ( 'vehicle fallback' , 355 , 255 , 15 , 12 , 'large-vehicle' , 8 ,
'zvalue'): self.zvalue.list() elif (single == 'tvalue'): self.tvalue.list() elif (single == 'mean'): self.mean.list() elif (single == 'min'): self.min.list() elif (single == 'max'): self.max.list() elif (single == 'xtic1'): self.xtic1.list() elif (single == 'xtic2'): self.xtic2.list() elif (single == 'xmintic1'): self.xmintic1.list() elif (single == 'xmintic2'): self.xmintic2.list() elif (single == 'ytic1'): self.ytic1.list() elif (single == 'ytic2'): self.ytic2.list() elif (single == 'ymintic1'): self.ymintic1.list() elif (single == 'ymintic2'): self.ymintic2.list() elif (single == 'xlabel1'): self.xlabel1.list() elif (single == 'xlabel2'): self.xlabel2.list() elif (single == 'ylabel1'): self.ylabel1.list() elif (single == 'ylabel2'): self.ylabel2.list() elif (single == 'box1'): self.box1.list() elif (single == 'box2'): self.box2.list() elif (single == 'box3'): self.box3.list() elif (single == 'box4'): self.box4.list() elif (single == 'line1'): self.line1.list() elif (single == 'line2'): self.line2.list() elif (single == 'line3'): self.line3.list() elif (single == 'line4'): self.line4.list() elif (single == 'legend'): self.legend.list() elif (single == 'data'): self.data.list() list.__doc__ = list.__doc__ % (listdoc.format(name="template", parent="")) ########################################################################### # # # Script out template object in VCS to a file. # # # ########################################################################### def script(self, script_filename=None, mode=None): if (script_filename is None): raise ValueError( 'Error - Must provide an output script file name.') if (mode is None): mode = 'a' elif (mode not in ('w', 'a')): raise ValueError( 'Error - Mode can only be "w" for replace or "a" for append.') # By default, save file in json scr_type = script_filename.split(".") if len(scr_type) == 1 or len(scr_type[-1]) > 5: scr_type = "json" if script_filename != "initial.attributes": script_filename += ".json" else: scr_type = scr_type[-1] if scr_type == '.scr': raise vcs.VCSDeprecationWarning("scr script are no longer generated") elif scr_type == "py": mode = mode + '+' py_type = script_filename[ len(script_filename) - 3:len(script_filename)] if (py_type != '.py'): script_filename = script_filename + '.py' # Write to file fp = open(script_filename, mode) if (fp.tell() == 0): # Must be a new file, so include below fp.write("#####################################\n") fp.write("# #\n") fp.write("# Import and Initialize VCS #\n") fp.write("# #\n") fp.write("#############################\n") fp.write("import vcs\n") fp.write("v=vcs.init()\n\n") unique_name = '__P__' + self.name fp.write( "#----------Template (P) member " "(attribute) listings ----------\n") fp.write("p_list=v.listelements('template')\n") fp.write("if ('%s' in p_list):\n" % self.name) fp.write( " %s = v.gettemplate('%s')\n" % (unique_name, self.name)) fp.write("else:\n") fp.write( " %s = v.createtemplate('%s')\n" % (unique_name, self.name)) fp.write("orientation = '%d'\n" % self.orientation) # Write out the TEXT template j = 0 a = [ self.file, self.function, self.logicalmask, self.transformation, self.source, self.dataname, self.title, self.units, self.crdate, self.crtime, self.comment1, self.comment2, self.comment3, self.comment4, self.xname, self.yname, self.zname, self.tname, self.xunits, self.yunits, self.zunits, self.tunits] for i in ('file', 'function', 'logicalmask', 'transformation', 'source', 'dataname', 'title', 'units', 'crdate', 'crtime', 'comment1', 'comment2', 'comment3', 'comment4', 'xname', 'yname', 'zname', 'tname', 'xunits', 'yunits', 'zunits', 'tunits'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.x = %g\n" % (unique_name, i, a[j].x)) fp.write("%s.%s.y = %g\n" % (unique_name, i, a[j].y)) fp.write( "%s.%s.texttable = '%s'\n" % (unique_name, i, a[j].texttable)) fp.write( "%s.%s.textorientation = '%s'\n\n" % (unique_name, i, a[j].textorientation)) j = j + 1 # Write out the FORMAT template j = 0 a = [ self.xvalue, self.yvalue, self.zvalue, self.tvalue, self.mean, self.min, self.max] for i in ( 'xvalue', 'yvalue', 'zvalue', 'tvalue', 'mean', 'min', 'max'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.x = %g\n" % (unique_name, i, a[j].x)) fp.write("%s.%s.y = %g\n" % (unique_name, i, a[j].y)) fp.write( "%s.%s.texttable = '%s'\n" % (unique_name, i, a[j].format)) fp.write( "%s.%s.texttable = '%s'\n" % (unique_name, i, a[j].texttable)) fp.write( "%s.%s.textorientation = '%s'\n\n" % (unique_name, i, a[j].textorientation)) j = j + 1 # Write out the X-TICK template j = 0 a = [self.xtic1, self.xtic2, self.xmintic1, self.xmintic2] for i in ('xtic1', 'xtic2', 'xmintic1', 'xmintic2'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.y1 = %g\n" % (unique_name, i, a[j].y1)) fp.write("%s.%s.y2 = %g\n" % (unique_name, i, a[j].y2)) fp.write("%s.%s.line = '%s'\n\n" % (unique_name, i, a[j].line)) j = j + 1 # Write out the Y-TICK template j = 0 a = [self.ytic1, self.ytic2, self.ymintic1, self.ymintic2] for i in ('ytic1', 'ytic2', 'ymintic1', 'ymintic2'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.x1 = %g\n" % (unique_name, i, a[j].x1)) fp.write("%s.%s.x2 = %g\n" % (unique_name, i, a[j].x2)) fp.write("%s.%s.line = '%s'\n\n" % (unique_name, i, a[j].line)) j = j + 1 # Write out the X-LABELS template j = 0 a = [self.xlabel1, self.xlabel2] for i in ('xlabel1', 'xlabel2'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.y = %g\n" % (unique_name, i, a[j].y)) fp.write( "%s.%s.texttable = '%s'\n" % (unique_name, i, a[j].texttable)) fp.write( "%s.%s.textorientation = '%s'\n\n" % (unique_name, i, a[j].textorientation)) j = j + 1 # Write out the Y-LABELS template j = 0 a = [self.ylabel1, self.ylabel2] for i in ('ylabel1', 'ylabel2'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.x = %g\n" % (unique_name, i, a[j].x)) fp.write( "%s.%s.texttable = '%s'\n" % (unique_name, i, a[j].texttable)) fp.write( "%s.%s.textorientation = '%s'\n\n" % (unique_name, i, a[j].textorientation)) j = j + 1 # Write out the BOXES and LINES template j = 0 a = [ self.box1, self.box2, self.box1, self.box2, self.line1, self.line2, self.line3, self.line4] for i in ('box1', 'box2', 'box3', 'box4', 'line1', 'line2', 'line3', 'line4'): fp.write("# member = %s\n" % i) fp.write( "%s.%s.priority = %g\n" % (unique_name, i, a[j].priority)) fp.write("%s.%s.x1 = %g\n" % (unique_name, i, a[j].x1)) fp.write("%s.%s.y1 = %g\n" % (unique_name, i, a[j].y1)) fp.write("%s.%s.x2 = %g\n" % (unique_name, i, a[j].x2)) fp.write("%s.%s.y2 = %g\n" % (unique_name, i, a[j].y2)) fp.write("%s.%s.line = '%s'\n\n" % (unique_name, i, a[j].line)) j = j + 1 # Write out the LEGEND SPACE template fp.write("# member = %s\n" % 'legend') fp.write( "%s.legend.priority = %g\n" % (unique_name, self.legend.priority)) fp.write("%s.legend.x1 = %g\n" % (unique_name, self.legend.x1)) fp.write("%s.legend.y1 = %g\n" % (unique_name, self.legend.y1)) fp.write("%s.legend.x2 = %g\n" % (unique_name, self.legend.x2)) fp.write("%s.legend.y2 = %g\n" % (unique_name, self.legend.y2)) fp.write( "%s.legend.line = '%s'\n" % (unique_name, self.legend.line)) fp.write( "%s.legend.texttable = '%s'\n" % (unique_name, self.legend.texttable)) fp.write( "%s.legend.textorientation = '%s'\n\n" % (unique_name, self.legend.textorientation)) # Write out the DATA SPACE template fp.write("# member = %s\n" % 'data') fp.write( "%s.data.priority = %g\n" % (unique_name, self.data.priority)) fp.write("%s.data.x1 = %g\n" % (unique_name, self.data.x1)) fp.write("%s.data.y1 = %g\n" % (unique_name, self.data.y1)) fp.write("%s.data.x2 = %g\n" % (unique_name, self.data.x2)) fp.write("%s.data.y2 = %g\n\n" % (unique_name, self.data.y2)) else: # Json type mode += "+" f = open(script_filename, mode) vcs.utils.dumpToJson(self, f) f.close() script.__doc__ = scriptdocs['template'] # Adding the drawing functionnality to plot all these attributes on the # Canvas def drawTicks(self, slab, gm, x, axis, number, vp, wc, bg=False, X=None, Y=None, mintic=False, **kargs): """Draws the ticks for the axis x number number using the label passed by the graphic method vp and wc are from the actual canvas, they have been reset when they get here... .. pragma: skip-doctest TODO add example/doctest """ kargs["donotstoredisplay"] = True if X is None: X = slab.getAxis(-1) if Y is None: Y = slab.getAxis(-2) displays = [] dx = wc[1] - wc[0] dy = wc[3] - wc[2] dx = dx / (vp[1] - vp[0]) dy = dy / (vp[3] - vp[2]) # get the actual labels if mintic is False: loc = copy.copy(getattr(gm, axis + 'ticlabels' + number)) else: loc = copy.copy(getattr(gm, axis + 'mtics' + number)) # Are they set or do we need to it ? if (loc is None or loc == '*'): # well i guess we have to do it ! if axis == 'x': x1 = wc[0] x2 = wc[1] else: x1 = wc[2] x2 = wc[3] loc = vcs.mkscale(x1, x2) loc = vcs.mklabels(loc) if number == '2': for t in list(loc.keys()): loc[t] = '' if isinstance(loc, str): loc = copy.copy(vcs.elements["list"].get(loc, {})) # Make sure the label passed are not outside the world coordinates dw1 = 1.E20 dw2 = 1.E20 if axis == 'x': dw1, dw2 = wc[0], wc[1] else: dw1, dw2 = wc[2], wc[3] for k in list(loc.keys()): if dw2 > dw1: if not(dw1 <= k <= dw2): del(loc[k]) else: if not (dw1 >= k >= dw2): del(loc[k]) # The ticks if mintic is False: obj = getattr(self, axis + 'tic' + number)
# -*- coding: utf-8 -*- """ Created on Thu Sep 8 13:55:16 2016 as a copy+paste of the previous version of this file. For making a journal figure. Calculate the color and magnitude (3.6 - 4.5 microns) of IC 10 X-2, and compare it to the population of massive stars in the LMC with IRAC and SAGE measurements. Source for colormap: http://stackoverflow.com/questions/12965075/matplotlib-sca tter-plot-colour-as-function-of-third-variable Source for zoom-in inset plot: http://akuederle.com/matplotlib-zoomed-up-inset """ import numpy as np import matplotlib.pyplot as plt import fluxes_with_xdates_170314_copy as flc from math import log10 from matplotlib.patches import ConnectionPatch #from array import * from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes # from mpl_toolkits.axes_grid1.inset_locator import mark_inset # Doesn't work with Python 2 anymore :( import matplotlib.patches as patches plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rc('text', usetex = True) from matplotlib.ticker import MultipleLocator # Rename arrays from photometry calculations f_36, f_36_sig = flc.circFlux36, flc.fluxError36 f_45, f_45_sig = flc.circFlux45, flc.fluxError45 jdates = flc.jdates # Open the file f = 'table3_only_Ch1_Ch2.dat' ref_mu = 18.91 dat = np.genfromtxt(f, dtype=(float, float, 'U10'), #|S10 delimiter = '\t', skip_header = 43, missing_values = ' ', filling_values ='0', usecols=(2, 3, 4)) # Make copy of data from which we will remove invalid stars (hence list type) data = dat.tolist() badindex = [] # list of bad indices as ints # Check if entries have a zero measurement for one of their fluxes for i in range(len(dat)): if 0 in data[i]: badindex.append(i) # Now remove the indices from the data array, in reverse order for b in badindex[::-1]: del data[b] # Calculate absolute magnitudes based on given distance modulus. refAbsMag36, refAbsMag45 = np.zeros((2, len(data))) for i in range(len(data)): refAbsMag36[i] = np.asarray(data[i][0]) - ref_mu refAbsMag45[i] = np.asarray(data[i][1]) - ref_mu refColor = refAbsMag36 - refAbsMag45 # Now create lists of the different spectral classes. nclasses = 10 # There are 9 in the paper but make a 10th one for rejects Ostar, earlyB, lateB, AFG, RSG, WR, sgB_e, LBV, BeXray, reject = \ [[] for _ in range(nclasses)] # Using the spectral type, sort the objects for i in range(len(data)): if 'O' in data[i][2] and 'W' not in data[i][2]: Ostar.append(data[i]) elif any(s in data[i][2] for s in ('B0','B1','B2','B3','B4','earl')) and \ not any(s in data[i][2] for s in ('Be', 'Fe', '[e]', 'K', 'XRB')): earlyB.append(data[i]) elif any(s in data[i][2] for s in ('B5','B6','B7','B8','B9')) and\ '[e]' not in data[i][2] and 'Be' not in data[i][2]: lateB.append(data[i]) elif any(s in data[i][2] for s in ('A','F','G')) and 'Be' not in \ data[i][2] and 'LBV' not in data[i][2]: AFG.append(data[i]) elif 'W' in data[i][2]: WR.append(data[i]) elif 'LBV' in data[i][2]: LBV.append(data[i]) elif 'K' in data[i][2] or 'M' in data[i][2]: RSG.append(data[i]) elif '[e]' in data[i][2]: sgB_e.append(data[i]) elif any(s in data[i][2] for s in ('XRB', 'Fe', 'extr', 'Be')): # B extr? BeXray.append(data[i]) elif any(s in data[i][2] for s in ('B0.5', 'B1')): earlyB.append(data[i]) elif any(s in data[i][2] for s in ('B5', 'B6', 'B9')): lateB.append(data[i]) elif any(s in data[i][2] for s in ('1', '2')): # BC 1 and BC2 and BN?2 earlyB.append(data[i]) elif any(s in data[i][2] for s in ('BN6')): lateB.append(data[i]) else: reject.append(data[i]) O_col, O_Mag = np.zeros((2, 1, len(Ostar))) earlyB_col, earlyB_Mag = np.zeros((2, 1, len(earlyB))) lateB_col, lateB_Mag = np.zeros((2, 1, len(lateB))) AFG_col, AFG_Mag = np.zeros((2, 1, len(AFG))) RSG_col, RSG_Mag = np.zeros((2, 1, len(RSG))) WR_col, WR_Mag = np.zeros((2, 1, len(WR))) sgB_e_col, sgB_e_Mag = np.zeros((2, 1, len(sgB_e))) LBV_col, LBV_Mag = np.zeros((2, 1, len(LBV))) BeXray_col, BeXray_Mag = np.zeros((2, 1, len(BeXray))) sortColors = [O_col, earlyB_col, lateB_col, AFG_col, RSG_col, WR_col, sgB_e_col, LBV_col, BeXray_col] sortAbsMag36 = [O_Mag, earlyB_Mag, lateB_Mag, AFG_Mag, RSG_Mag, WR_Mag, sgB_e_Mag, LBV_Mag, BeXray_Mag] cat_list = (Ostar, earlyB, lateB, AFG, RSG, WR, sgB_e, LBV, BeXray) # Calculate the x- and y-values for each star category for cat in (Ostar, earlyB, lateB, AFG, RSG, WR, LBV, sgB_e, BeXray): ind = cat_list.index(cat) for i in range(len(cat)): sortColors[ind][0][i] = np.asarray(cat[i][0]) - np.asarray(cat[i][1]) sortAbsMag36[ind][0][i] = np.asarray(cat[i][0]) - ref_mu # Scatter plot the categories using unique shapes and colors markershapes = '^', 's', 'v', 'p', 'v', 'o', 'D', '<', 'o' colors = 'k', 'silver','white', 'dimgrey', 'lightgrey', '#ffffff', \ 'g', 'deepskyblue', 'gainsboro' edgecolorlist = 'White', 'None', 'k', 'darkgrey', 'k', 'k', 'k',\ 'k', 'k' catnames = 'O stars', 'Early B', 'Late B', 'AFG/comp', 'RSG', 'WR','sgB[e]', 'LBV',\ 'Be-Xray' linewidthlist = 0.3, 0.3, 0.3, 0.3, 0.3, 0.5, 0.3, 0.3, 1 sizelist = 30, 10, 20, 30, 12, 12, 25, 30, 35 # Plot results fig, ax = plt.subplots() #plt.hold(True) for cat in (earlyB, Ostar, WR, AFG, RSG, sgB_e, lateB, LBV, BeXray): ind = cat_list.index(cat) ax.scatter(sortColors[ind], sortAbsMag36[ind], c = colors[ind], marker = markershapes[ind], linewidths = linewidthlist[ind], s = sizelist[ind], edgecolors = edgecolorlist[ind], label = catnames[ind]) axGrab = plt.gca() axGrab.set_ylim(ax.get_ylim()[::-1]) # Add minor tick labels. 0.1 and 1 intervals minorLocatorx = MultipleLocator(0.1) minorLocatory = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocatorx) ax.yaxis.set_minor_locator(minorLocatory) plt.legend(loc='lower right', fontsize = 9, scatterpoints = 1, frameon = True, markerscale = 1.0) plt.xlabel('m$_{[3.6]}$ - m$_{[4.5]}$', fontsize = 14) plt.ylabel('M$_{[3.6]}$', fontsize = 14) def mag(flux, zeropt): # flux and zeropt are in Jansky return -2.5 * log10(flux / zeropt) # Handle the IC 10 X-2 fluxes abs_Mag36, abs_Mag45, app_Mag36, app_Mag45, color = np.zeros((5,len(jdates))) app_Mag36_sig, app_Mag45_sig, colorsig = np.zeros((3, len(jdates))) mu_X2 = 24.1 # Distance modulus of IC 10-X2 f0_36 = 280.9 # zero-point flux for the 3.6 channel f0_45 = 179.7 # zero-point flux for the 4.5 channel for j in range(len(jdates)): app_Mag36[j] = mag(f_36[j] * 10**-3, f0_36) app_Mag45[j] = mag(f_45[j] * 10**-3, f0_45) # From Mathematica: propagate error: derivative of the abs_Mag36 calculation is app_Mag36_sig[j] = np.abs(f_36_sig[j] * (2.5/np.log(10)) / f_36[j] ) app_Mag45_sig[j] = np.abs(f_45_sig[j] * (2.5/np.log(10)) / f_45[j] ) abs_Mag36[j] = app_Mag36[j] - mu_X2 abs_Mag45[j] = app_Mag45[j] - mu_X2 color[j] = app_Mag36[j] - app_Mag45[j] colorsig[j] = np.sqrt((app_Mag36_sig[j])**2 + (app_Mag45_sig[j])**2) # Plot IC 10 X-2's journey across the CMD with a colormap ic10x2 = plt.scatter(color, abs_Mag36, marker = 'o', c = jdates, cmap = plt.cm.plasma, linewidth = 0.3, s = 30, edgecolor = 'k') ax.errorbar(0.2, -8 , xerr = np.mean(colorsig), yerr = np.mean(app_Mag36_sig), ecolor = 'r', capthick = 1, elinewidth = 1) # Error in app_Mag_36 same as for the absolute one #print(np.mean(colorsig)) #print(np.mean(app_Mag36_sig)) #for i in range(len(f_36)): # print(mag((f_36[i] + f_36_sig[i]) * 10**-3, f0_36) - mag(f_36[i] * 10**-3, f0_36)) #sn2010da = plt.scatter(0.76, -10.36, marker = 's', c = 'red', linewidth = 0.3, # s = 35, edgecolor = 'k') #ax.text(0.85,-10,'(SN)2010da') # Add a colorbar cb = plt.colorbar(ic10x2, shrink = 0.6, ticks = [53500, 54375, 55250, 56125, 57000], orientation = 'vertical') cb.set_label('IC 10 X-2 \n Date (MJD)', y = 1.25, rotation = 0, fontsize = 14) cb.ax.xaxis.set_label_position('top') cb.ax.invert_yaxis() x1, x2 = -0.5, 2.5 y1, y2 = -1, -13.5 ax.set_xlim(x1, x2) ax.set_ylim(y1, y2) insetx1, insetx2, insety1, insety2 = -0.05, 0.38, -7.75, -9.55 # Create a rectangle patch in the original plot rect = patches.Rectangle((insetx1, insety1), insetx2 - insetx1, insety2 - insety1, linewidth = 1, edgecolor = 'k', facecolor = 'none') ax.add_patch(rect) # Make a zoomed inset: zoom-factor, location: upper center axins = zoomed_inset_axes(ax, 3, loc = 1) for category in (earlyB, Ostar, WR, AFG, RSG, sgB_e, lateB, LBV, BeXray): ind = cat_list.index(category) axins.scatter(sortColors[ind], sortAbsMag36[ind], c = colors[ind], marker = markershapes[ind], linewidth = linewidthlist[ind], s = sizelist[ind], edgecolors = edgecolorlist[ind]) axins.scatter(color, abs_Mag36, marker = 'o', c = jdates, cmap = plt.cm.plasma, s = 40, linewidth = 0.3, edgecolor = 'k') # Add error bar to inset axins.errorbar(color[0] - np.mean(colorsig), -8.00 , xerr = np.mean(colorsig), yerr = np.mean(app_Mag36_sig), ecolor = 'r', capthick = 1, elinewidth = 1) # Create labels for points in the inset labels = ['{0}'.format(i + 1) for i in range(len(jdates))] #for label, x, y in zip(labels, color, abs_Mag36): # axins.annotate(label, xy = (x, y), xytext = (-20, 20), # textcoords = 'offset points', ha='right', va='bottom', # bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), # arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) # Don't know how to automate this so I'm just going to do it by hand axins.annotate('1', xy = (color[0], abs_Mag36[0]), xytext = (17, -20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.15', fc = 'yellow', alpha = 0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) axins.annotate('2', xy = (color[1], abs_Mag36[1]), xytext = (30, -20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.15', fc = 'yellow', alpha = 0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) axins.annotate('3', xy = (color[2], abs_Mag36[2]), xytext = (-15, -30), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.15', fc = 'yellow', alpha = 0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) axins.annotate('4', xy = (color[3], abs_Mag36[3]), xytext = (-5, -30), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.15',
#! /usr/bin/python3 # -*- coding: utf-8 -*- import pickle import pandas as pd import xml.etree.ElementTree as ET import math import seaborn as sns import matplotlib.pyplot as plt import numpy as np import csv import glob import scikit_posthocs as sp from scipy import stats import os from scipy import stats import scikit_posthocs as sp sns.set(context='paper', style='whitegrid') hue_order = ["traffic light", "crossing intention", "trajectory"] eps=0.01 tl_black_list = [ "3_3_96tl", "3_3_102tl", "3_4_107tl", "3_4_108tl", "3_5_112tl", "3_5_113tl", "3_5_116tl", "3_5_117tl", "3_5_118tl", "3_5_119tl", "3_5_122tl", "3_5_123tl", "3_5_126tl", "3_5_127tl", "3_6_128tl", "3_6_137tl", "3_7_142tl", "3_8_153tl", "3_8_160tl", "3_9_173tl", "3_9_174tl", "3_9_179tl", "3_10_185tl", "3_10_188tl", "3_11_205tl", "3_12_218tl", "3_12_221tl", "3_15_241tl", "3_16_256tl", "3_16_257tl", ] opposite_anno_list = ["3_16_259tl", "3_16_258tl", "3_16_249tl"] log_data = None data_path = "/home/kuriatsu/Dropbox/data/pie202203" for file in glob.glob(os.path.join(data_path, "log*.csv")): buf = pd.read_csv(file) filename =file.split("/")[-1] count = int(filename.replace("log_data_", "").split("_")[-1].replace(".csv", "")) print("{}".format(filename)) if count in [0, 1, 2]: print("skipped") continue trial = filename.split("_")[-1].replace(".csv", "") buf["subject"] = filename.replace("log_data_", "").split("_")[0] buf["task"] = filename.replace("log_data_", "").split("_")[1] correct_list = [] response_list = [] for idx, row in buf.iterrows(): if row.id in tl_black_list: row.last_state = -2 if row.last_state == -1: # no intervention correct_list.append(-1) response_list.append(-1) elif int(row.last_state) == int(row.state): if row.id in opposite_anno_list: correct_list.append(1) if row.last_state == 1: response_list.append(3) elif row.last_state == 0: response_list.append(0) else: print(f"last_state{row.last_state}, state{row.state}") response_list.append(4) # ignored=4 else: correct_list.append(0) if row.last_state == 1: response_list.append(1) elif row.last_state == 0: response_list.append(2) else: print(f"last_state{row.last_state}, state{row.state}") response_list.append(4) # ignored=4 else: if row.id in opposite_anno_list: correct_list.append(0) if row.last_state == 1: response_list.append(1) elif row.last_state == 0: response_list.append(2) else: print(f"last_state{row.last_state}, state{row.state}") response_list.append(4) # ignored=4 else: correct_list.append(1) if row.last_state == 1: response_list.append(3) elif row.last_state == 0: response_list.append(0) else: print(f"last_state{row.last_state}, state{row.state}") response_list.append(4) # ignored=4 buf["correct"] = correct_list buf["response"] = response_list len(correct_list) if log_data is None: log_data = buf else: log_data = log_data.append(buf, ignore_index=True) task_list = {"int": "crossing intention", "tl": "traffic light", "traj":"trajectory"} subject_data = pd.DataFrame(columns=["subject", "task", "acc", "int_length", "missing"]) for subject in log_data.subject.drop_duplicates(): for task in log_data.task.drop_duplicates(): for length in log_data.int_length.drop_duplicates(): target = log_data[(log_data.subject == subject) & (log_data.task == task) & (log_data.int_length == length)] # acc = len(target[target.correct == 1])/(len(target)) acc = len(target[target.correct == 1])/(len(target[target.correct == 0]) + len(target[target.correct == 1])+eps) missing = len(target[target.correct == -1])/(len(target[target.correct != -2])+eps) buf = pd.DataFrame([(subject, task_list.get(task), acc, length, missing)], columns=subject_data.columns) subject_data = pd.concat([subject_data, buf]) subject_data.acc = subject_data.acc * 100 subject_data.missing = subject_data.missing * 100 # sns.barplot(x="task", y="acc", hue="int_length", data=subject_data, ci="sd") # sns.barplot(x="task", y="acc", data=subject_data, ci="sd") ################################################ print("check intervene acc") ################################################ for length in subject_data.int_length.drop_duplicates(): print(f"acc : length={length}") target_df = subject_data[subject_data.int_length == length] _, norm_p = stats.shapiro(target_df.acc.dropna()) _, var_p = stats.levene( target_df[target_df.task == 'trajectory'].acc.dropna(), target_df[target_df.task == 'crossing intention'].acc.dropna(), target_df[target_df.task == 'traffic light'].acc.dropna(), center='median' ) # if norm_p < 0.05 or var_p < 0.05: # print(f"norm:{norm_p}, var:{var_p}") # print('steel-dwass\n', sp.posthoc_dscf(target_df, val_col='acc', group_col='task')) # else: # multicomp_result = multicomp.MultiComparison(np.array(target_df.dropna(how='any').acc, dtype="float64"), target_df.dropna(how='any').type) # print(f"norm:{norm_p}, var:{var_p}") # print('levene', multicomp_result.tukeyhsd().summary()) if norm_p < 0.05 or var_p < 0.05: _, anova_p = stats.friedmanchisquare( target_df[target_df.task == "trajectory"].acc, target_df[target_df.task == "crossing intention"].acc, target_df[target_df.task == "traffic light"].acc, ) print(f"norm:{norm_p}, var:{var_p}") print("anova(friedman test)", anova_p) if anova_p < 0.05: print('conover\n', sp.posthoc_conover(target_df, val_col="acc", group_col="task")) print('steel-dwass\n', sp.posthoc_dscf(target_df, val_col='acc', group_col='task')) else: # melted_df = pd.melt(target_df, id_vars=["subject", "acc", "int_length"], var_name="task", value_name="rate") aov = stats_anova.AnovaRM(melted_df, "missing", "subject", ["task"]) print(f"norm:{norm_p}, var:{var_p}") print("reperted anova: ", aov.fit()) multicomp_result = multicomp.MultiComparison(melted_df[length], nasa_df.task) print(melted_df.tukeyhsd().summary()) fig, ax = plt.subplots() sns.pointplot(x="int_length", y="acc", data=subject_data, hue="task", hue_order=hue_order, ax=ax, capsize=0.1, ci="sd") ax.set_ylim(0.0, 100.0) ax.set_xlabel("intervention time [s]", fontsize=18) ax.set_ylabel("intervention accuracy [%]", fontsize=18) ax.tick_params(labelsize=14) ax.legend(fontsize=14) plt.show() ################################################ print("check miss rate") ################################################ for length in subject_data.int_length.drop_duplicates(): print(f"miss : length={length}") target_df = subject_data[subject_data.int_length == length] _, norm_p = stats.shapiro(target_df.missing.dropna()) _, var_p = stats.levene( target_df[target_df.task == 'trajectory'].missing.dropna(), target_df[target_df.task == 'crossing intention'].missing.dropna(), target_df[target_df.task == 'traffic light'].missing.dropna(), center='median' ) # if norm_p < 0.05 or var_p < 0.05: # print(f"norm:{norm_p}, var:{var_p}") # print('steel-dwass\n', sp.posthoc_dscf(target_df, val_col='missing', group_col='task')) # else: # multicomp_result = multicomp.MultiComparison(np.array(target_df.dropna(how='any').missing, dtype="float64"), target_df.dropna(how='any').type) # print(f"norm:{norm_p}, var:{var_p}") # print('levene', multicomp_result.tukeyhsd().summary()) if norm_p < 0.05 or var_p < 0.05: _, anova_p = stats.friedmanchisquare( target_df[target_df.task == "trajectory"].missing, target_df[target_df.task == "crossing intention"].missing, target_df[target_df.task == "traffic light"].missing, ) print(f"norm:{norm_p}, var:{var_p}") print("anova(friedman test)", anova_p) if anova_p < 0.05: print('steel-dwass\n', sp.posthoc_dscf(target_df, val_col='missing', group_col='task')) print('conover\n', sp.posthoc_conover(target_df, val_col="missing", group_col="task")) else: # melted_df = pd.melt(target_df, id_vars=["subject", "acc", "int_length"], var_name="task", value_name="rate") aov = stats_anova.AnovaRM(melted_df, "missing", "subject", ["task"]) print(f"norm:{norm_p}, var:{var_p}") print("reperted anova: ", aov.fit()) multicomp_result = multicomp.MultiComparison(melted_df[length], nasa_df.task) print(melted_df.tukeyhsd().summary()) fig, ax = plt.subplots() sns.pointplot(x="int_length", y="missing", data=subject_data, hue="task", hue_order=hue_order, ax = ax, capsize=0.1, ci=95) ax.set_ylim(0.0, 100.0) ax.set_xlabel("intervention time [s]", fontsize=18) ax.set_ylabel("intervention missing rate [%]", fontsize=18) ax.tick_params(labelsize=14) ax.legend(fontsize=14) plt.show() ##################################### # mean val show ##################################### target = subject_data[subject_data.task == "crossing intention"] print("int acc mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].acc.mean(), target[target.int_length == 3.0].acc.mean(), target[target.int_length == 5.0].acc.mean(), target[target.int_length == 8.0].acc.mean(), target[target.int_length == 1.0].acc.std(), target[target.int_length == 3.0].acc.std(), target[target.int_length == 5.0].acc.std(), target[target.int_length == 8.0].acc.std(), )) target = subject_data[subject_data.task == "trajectory"] print("traj acc mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].acc.mean(), target[target.int_length == 3.0].acc.mean(), target[target.int_length == 5.0].acc.mean(), target[target.int_length == 8.0].acc.mean(), target[target.int_length == 1.0].acc.std(), target[target.int_length == 3.0].acc.std(), target[target.int_length == 5.0].acc.std(), target[target.int_length == 8.0].acc.std(), )) target = subject_data[subject_data.task == "traffic light"] print("tl acc mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].acc.mean(), target[target.int_length == 3.0].acc.mean(), target[target.int_length == 5.0].acc.mean(), target[target.int_length == 8.0].acc.mean(), target[target.int_length == 1.0].acc.std(), target[target.int_length == 3.0].acc.std(), target[target.int_length == 5.0].acc.std(), target[target.int_length == 8.0].acc.std(), )) target = subject_data[subject_data.task == "crossing intention"] print("int missing mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].missing.mean(), target[target.int_length == 3.0].missing.mean(), target[target.int_length == 5.0].missing.mean(), target[target.int_length == 8.0].missing.mean(), target[target.int_length == 1.0].missing.std(), target[target.int_length == 3.0].missing.std(), target[target.int_length == 5.0].missing.std(), target[target.int_length == 8.0].missing.std(), )) target = subject_data[subject_data.task == "trajectory"] print("traj missing mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].missing.mean(), target[target.int_length == 3.0].missing.mean(), target[target.int_length == 5.0].missing.mean(), target[target.int_length == 8.0].missing.mean(), target[target.int_length == 1.0].missing.std(), target[target.int_length == 3.0].missing.std(), target[target.int_length == 5.0].missing.std(), target[target.int_length == 8.0].missing.std(), )) target = subject_data[subject_data.task == "traffic light"] print("tl missing mean: 1.0:{}, 3.0:{}, 5.0:{}, 8.0:{}\n std {} {} {} {}".format( target[target.int_length == 1.0].missing.mean(), target[target.int_length == 3.0].missing.mean(), target[target.int_length == 5.0].missing.mean(), target[target.int_length == 8.0].missing.mean(), target[target.int_length == 1.0].missing.std(), target[target.int_length == 3.0].missing.std(), target[target.int_length == 5.0].missing.std(), target[target.int_length == 8.0].missing.std(), )) ########################################### # collect wrong intervention ids ########################################### task_list = {"int": "crossing intention", "tl": "traffic light", "traj":"trajectory"} id_data = pd.DataFrame(columns=["id", "task", "false_rate", "missing", "total"]) for id in log_data.id.drop_duplicates(): for task in log_data.task.drop_duplicates(): for length in log_data.int_length.drop_duplicates(): target = log_data[(log_data.id == id) & (log_data.task == task) & (log_data.int_length == length)] # acc = len(target[target.correct == 1])/(len(target)) total = len(target) name = id.replace("tl","")+task+"_"+str(length) if len(target) > 0: false_rate = len(target[target.correct == 0])/len(target) else: false_rate = 0.0 missing = len(target[target.correct == -1]) buf = pd.DataFrame([(name, task, false_rate, missing, total)], columns=id_data.columns) id_data = pd.concat([id_data, buf]) pd.set_option("max_rows", None) sort_val = id_data.sort_values(["false_rate","total"], ascending=False) false_playlist = sort_val[(sort_val.false_rate>0.0)&(sort_val.total>1)] print(false_playlist) false_playlist.to_csv("/home/kuriatsu/Dropbox/data/pie202203/false_playlist.csv") # sns.barplot(x="id", y="acc", hue="int_length", data=id_data) ############################################################################################### print("response rate stacked bar plot") ############################################################################################### response_summary_pred = pd.DataFrame(columns=["int_length", "task", "response", "count"]) for int_length in log_data.int_length.drop_duplicates(): for task in log_data.task.drop_duplicates(): for response in [0, 1, 2, 3, -1]: buf = pd.Series([int_length, task, response, len(log_data[(log_data.int_length==int_length) & (log_data.task==task) & (log_data.response <= response)])/len(log_data[(log_data.int_length==int_length) & (log_data.task==task) & (log_data.response!=4)])], index=response_summary_pred.columns) response_summary_pred = response_summary_pred.append(buf, ignore_index=True) fig, axes = plt.subplots() cr = sns.barplot(x="task", y="count", hue="int_length", data=response_summary_pred[response_summary_pred.response==3], ax=axes, palette=sns.color_palette(["turquoise"]*6), edgecolor="0.2", order=["tl", "int", "traj"]) fa = sns.barplot(x="task", y="count", hue="int_length", data=response_summary_pred[response_summary_pred.response==2], ax=axes, palette=sns.color_palette(["orangered"]*6), edgecolor="0.2", order=["tl", "int", "traj"]) miss = sns.barplot(x="task", y="count", hue="int_length", data=response_summary_pred[response_summary_pred.response==1], ax=axes, palette=sns.color_palette(["lightsalmon"]*6), edgecolor="0.2", order=["tl", "int", "traj"]) hit = sns.barplot(x="task", y="count", hue="int_length", data=response_summary_pred[response_summary_pred.response==0], ax=axes, palette=sns.color_palette(["teal"]*6), edgecolor="0.2", order=["tl", "int", "traj"]) no_int = sns.barplot(x="task", y="count", hue="int_length", data=response_summary_pred[response_summary_pred.response==-1], ax=axes, palette=sns.color_palette(["gray"]*6), edgecolor="0.2", order=["tl", "int", "traj"]) axes.set_xticks([-0.3, -0.1, 0.1, 0.3, 0.7, 0.9, 1.1, 1.3, 1.7, 1.9, 2.1, 2.3]) axes.set_xticklabels(["1.0", "3.0", "5.0", "8.0", "1.0", "3.0", "5.0", "8.0", "1.0", "3.0", "5.0", "8.0"], fontsize=14) # axes.set_yticklabels(fontsize=14) ax_pos = axes.get_position() fig.text(ax_pos.x1-0.75, ax_pos.y1-0.84, "traffic light", fontsize=14) fig.text(ax_pos.x1-0.55, ax_pos.y1-0.84, "crossing intention", fontsize=14) fig.text(ax_pos.x1-0.25, ax_pos.y1-0.84, "trajectory", fontsize=14) axes.tick_params(labelsize=14) axes.set_ylabel("Response Rate", fontsize=18) axes.set_xlabel("") handles, labels = axes.get_legend_handles_labels() axes.legend(handles[::4], ["CR", "FA", "miss", "hit", "no_int"], bbox_to_anchor=(1.0, 1.0), loc='upper left', fontsize=14) plt.show() ############################################### # Workload ############################################### workload = pd.read_csv("{}/workload.csv".format(data_path)) workload.satisfy = 10-workload.satisfy workload_melted = pd.melt(workload, id_vars=["subject", "type"], var_name="scale", value_name="score") #### nasa-tlx #### for item in workload_melted.scale.drop_duplicates(): print(item) _, norm_p1 = stats.shapiro(workload[workload.type == "trajectory"][item]) _, norm_p2 = stats.shapiro(workload[workload.type == "crossing intention"][item]) _, norm_p3 = stats.shapiro(workload[workload.type == "traffic light"][item]) _, var_p = stats.levene( workload[workload.type == "trajectory"][item], workload[workload.type == "crossing intention"][item], workload[workload.type == "traffic light"][item], center='median' ) if norm_p1 < 0.05 or norm_p2 < 0.05 or norm_p3 < 0.05 or norm_p4 < 0.05: _, anova_p = stats.friedmanchisquare( workload[workload.type == "trajectory"][item], workload[workload.type == "crossing intention"][item], workload[workload.type == "traffic light"][item], ) print("anova(friedman test)", anova_p) if anova_p < 0.05: print(sp.posthoc_conover(workload, val_col=item, group_col="type")) else: melted_df = pd.melt(nasa_df, id_vars=["name", "experiment_type"], var_name="type", value_name="score") aov = stats_anova.AnovaRM(workload_melted[workload_melted.type == item], "score", "subject", ["type"]) print("reperted anova: ", aov.fit()) multicomp_result = multicomp.MultiComparison(workload_melted[item], nasa_df.type) print(multicomp_result.tukeyhsd().summary()) fig, ax = plt.subplots() sns.barplot(x="scale", y="score", data=workload_melted, hue="type", hue_order=hue_order, ax=ax) ax.set_ylim(0, 10) ax.legend(bbox_to_anchor=(0.0, 1.0), loc='lower left', fontsize=14) ax.set_xlabel("scale", fontsize=18) ax.set_ylabel("score (lower is better)", fontsize=18) ax.tick_params(labelsize=14) plt.show() ############################################### # necessary time ############################################### time = pd.read_csv("/home/kuriatsu/Dropbox/documents/subjective_time.csv") fig, ax = plt.subplots() # mean_list = [ # time[time.type=="crossing intention"].ideal_time.mean(), # time[time.type=="trajectory"].ideal_time.mean(), # time[time.type=="traffic light"].ideal_time.mean(), # ] # sem_list = [ # time[time.type=="crossing intention"].ideal_time.sem(), # time[time.type=="trajectory"].ideal_time.sem(), # time[time.type=="traffic light"].ideal_time.sem(), # ] _, norm_p = stats.shapiro(time.ideal_time.dropna()) _, var_p = stats.levene( time[time.type == 'crossing intention'].ideal_time.dropna(), time[time.type == 'trajectory'].ideal_time.dropna(),