content
stringlengths
22
815k
id
int64
0
4.91M
def test_directory_origin_configuration_quote_character(sdc_builder, sdc_executor, delimiter_format_type, data_format, quote_character, shell_executor, delimited_file_writer, delimiter_character): """Verify if directory origin can read delimited data with custom quote character. This TC check for different escape characters. Input data fields have delimiter characters. Directory origin should read this data and produce field without escape character. e.g. ;|Field is value of field with "|" as delimiter character and ";" as quote character then output field should be "|Field". """ file_name = 'custom_delimited_file.csv' f = lambda ip_string: ip_string.format(quote_character=quote_character, delimiter_character=delimiter_character) f1 = lambda ip_string: ip_string.replace(quote_character, "") data = [[f('{quote_character}Field11{delimiter_character}{quote_character}'), 'Field12', f('{quote_character},Field13{quote_character}')], [f('{quote_character}Field{delimiter_character}21{quote_character}'), 'Field22', 'Field23']] try: files_directory = create_file_and_directory(file_name, data, shell_executor, delimited_file_writer, delimiter_format_type, delimiter_character) pipeline_builder = sdc_builder.get_pipeline_builder() directory = pipeline_builder.add_stage('Directory') directory.set_attributes(data_format=data_format, files_directory=files_directory, file_name_pattern='custom_delimited_*', file_name_pattern_mode='GLOB', delimiter_format_type=delimiter_format_type, delimiter_character=delimiter_character, quote_character=quote_character) wiretap = pipeline_builder.add_wiretap() directory >> wiretap.destination pipeline = pipeline_builder.build() sdc_executor.add_pipeline(pipeline) sdc_executor.start_pipeline(pipeline) sdc_executor.wait_for_pipeline_metric(pipeline, 'data_batch_count', 1) sdc_executor.stop_pipeline(pipeline) expected_output = [map(f1, data[0]), map(f1, data[1])] verify_delimited_output(wiretap.output_records, expected_output) finally: shell_executor(f'rm -r {files_directory}')
5,345,800
async def test_async_get_config( aiohttp_session: aiohttp.ClientSession, aiohttp_server: Any ) -> None: """Test async_get_event_summary.""" config_in = {"cameras": {"front_door": {"camera_config": "goes here"}}} config_handler = Mock(return_value=web.json_response(config_in)) server = await start_frigate_server( aiohttp_server, [web.get("/api/config", config_handler)] ) frigate_client = FrigateApiClient(str(server.make_url("/")), aiohttp_session) assert config_in == await frigate_client.async_get_config()
5,345,801
def project(dim, states): """Qiskit wrapper of projection operator. """ ket, bra = states if ket in range(dim) and bra in range(dim): return st.basis(dim, ket) * st.basis(dim, bra).dag() else: raise Exception('States are specified on the outside of Hilbert space %s' % states)
5,345,802
def check_service_status(ssh_conn_obj, service_name, status="running", device='server'): """ Author: Chaitanya Vella ([email protected]) Function to check the service status :param ssh_conn_obj: :param service_name: :param status: :return: """ st.log("##### Checking {} status for {} service ######".format(status, service_name)) command = "status {}".format(service_name) result = conn_obj.execute_command(ssh_conn_obj, command) if device == 'server' else st.config(ssh_conn_obj, command) result = utils_obj.remove_last_line_from_string(result) if "command not found" not in result: match = "start/running" if status == "running" else "stop/waiting" if result.find("{}".format(match)) > 1: return True else: command = "service --status-all | grep {}".format(service_name) result = conn_obj.execute_command(ssh_conn_obj, command) result = utils_obj.remove_last_line_from_string(result) operator = "+" if status == "running" else "-" return True if operator in result and service_name in result else False return False
5,345,803
def _persist_block(block_node, block_map): """produce persistent binary data for a single block Children block are assumed to be already persisted and present in block_map. """ data = tuple(_to_value(v, block_map) for v in block_node) return S_BLOCK.pack(*data)
5,345,804
def get_graph_names(test_dir): """Parse test_dir/*GRAPHFILES and return basenames for all .graph files""" graph_list = [] GRAPHFILES_files = [f for f in os.listdir(test_dir) if f.endswith("GRAPHFILES")] for GRAPHFILE in GRAPHFILES_files: with open(os.path.join(test_dir, GRAPHFILE), 'r') as f: for l in f.readlines(): l = l.strip() if not l or l.startswith('#'): continue graph_list.append(os.path.basename(l).replace('.graph', '')) return graph_list
5,345,805
def get_sagemaker_feature_group(feature_group_name: str): """Used to check if there is an existing feature group with a given feature_group_name.""" try: return sagemaker_client().describe_feature_group(FeatureGroupName=feature_group_name) except botocore.exceptions.ClientError as error: logging.error( f"SageMaker could not find a feature group with the name {feature_group_name}. Error {error}" ) return None
5,345,806
def check_system(command, message, exit=0, user=None, stdin=None, shell=False, timeout=None, timeout_signal='TERM'): """Runs the command and checks its exit status code. Handles all of the common steps associated with running a system command: runs the command, checks its exit status code against the expected result, and raises an exception if there is an obvious problem. Returns a tuple of the standard output, standard error, and the failure message generated by diagnose(). See the system() function for more details about the command-line options. """ status, stdout, stderr = system(command, user, stdin, shell=shell, timeout=timeout, timeout_signal=timeout_signal, quiet=False) fail = diagnose(message, command, status, stdout, stderr) if timeout and status == -1: raise osgunittest.TimeoutException(fail) else: assert status == exit, fail return stdout, stderr, fail
5,345,807
def get_repo_data(api_token): """Executes the GraphQL query to get repository data from one or more GitHub orgs. Parameters ---------- api_token : str The GH API token retrieved from the gh_key file. Returns ------- repo_info_df : pandas.core.frame.DataFrame """ import requests import json import pandas as pd from common_functions import read_orgs url = 'https://api.github.com/graphql' headers = {'Authorization': 'token %s' % api_token} repo_info_df = pd.DataFrame() # Read list of orgs from a file try: org_list = read_orgs('orgs.txt') except: print("Error reading orgs. This script depends on the existance of a file called orgs.txt containing one org per line. Exiting") sys.exit() for org_name in org_list: has_next_page = True after_cursor = None print("Processing", org_name) while has_next_page: try: query = make_query(after_cursor) variables = {"org_name": org_name} r = requests.post(url=url, json={'query': query, 'variables': variables}, headers=headers) json_data = json.loads(r.text) df_temp = pd.DataFrame(json_data['data']['organization']['repositories']['nodes']) repo_info_df = pd.concat([repo_info_df, df_temp]) has_next_page = json_data["data"]["organization"]["repositories"]["pageInfo"]["hasNextPage"] after_cursor = json_data["data"]["organization"]["repositories"]["pageInfo"]["endCursor"] except: has_next_page = False print("ERROR Cannot process", org_name) return repo_info_df
5,345,808
def getJson(file, filters={}): """Given a specific JSON file (string) and a set of filters (dictionary key-values pairs), will return a JSON-formatted tree of the matching data entries from that file (starting as a null-key list of objects). """ with open(file, 'r') as f: j = json.loads(f.read()) all = j[''] dicts = basic.filter(all, filters) if len(dicts) > 0: return formatJson(dicts) else: raise Exception('No matching data entries found')
5,345,809
def underline_node_formatter(nodetext, optionstext, caller=None): """ Draws a node with underlines '_____' around it. """ nodetext_width_max = max(m_len(line) for line in nodetext.split("\n")) options_width_max = max(m_len(line) for line in optionstext.split("\n")) total_width = max(options_width_max, nodetext_width_max) separator1 = "_" * total_width + "\n\n" if nodetext_width_max else "" separator2 = "\n" + "_" * total_width + "\n\n" if total_width else "" return separator1 + "|n" + nodetext + "|n" + separator2 + "|n" + optionstext
5,345,810
def compare(path_to_config, config_file): """Rules.""" # This sys.path bookended chunk is common to all entry functions. sys.path.insert(0, './') app_pipeline = importlib.import_module(path_to_config + '.app_pipeline') subproject_name = os.path.basename(os.path.dirname(__file__)) app_configuration, next_subproject_name, next_subproject_module, \ next_entry = app_pipeline.entry_load_next_mod( app_pipeline, subproject_name, path_to_config, config_file) plot_plan = importlib.import_module(subproject_name + '.plot_plan') sequential_run = importlib.import_module(subproject_name + '.sequential_run') sys.path.remove('./') plans, ack = plot_plan.get_plans(app_configuration, subproject_name) sequential_run.all(plans, **ack) #parallel_run.all(plans) #cloud_run.all(plans) if next_subproject_name is not None: call_next_entry(next_subproject_module, next_entry, path_to_config, config_file)
5,345,811
def validategeojson(data_input, mode): """GeoJSON validation example >>> import StringIO >>> class FakeInput(object): ... json = open('point.geojson','w') ... json.write('''{"type":"Feature", "properties":{}, "geometry":{"type":"Point", "coordinates":[8.5781228542328, 22.87500500679]}, "crs":{"type":"name", "properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}''') # noqa ... json.close() ... file = 'point.geojson' >>> class fake_data_format(object): ... mimetype = 'application/geojson' >>> fake_input = FakeInput() >>> fake_input.data_format = fake_data_format() >>> validategeojson(fake_input, MODE.SIMPLE) True """ LOGGER.info('validating GeoJSON; Mode: {}'.format(mode)) passed = False if mode >= MODE.NONE: passed = True if mode >= MODE.SIMPLE: name = data_input.file (mtype, encoding) = mimetypes.guess_type(name, strict=False) passed = data_input.data_format.mime_type in {mtype, FORMATS.GEOJSON.mime_type} if mode >= MODE.STRICT: from pywps.dependencies import ogr data_source = ogr.Open(data_input.file) if data_source: passed = (data_source.GetDriver().GetName() == "GeoJSON") else: passed = False if mode >= MODE.VERYSTRICT: import jsonschema import json # this code comes from # https://github.com/om-henners/GeoJSON_Validation/blob/master/geojsonvalidation/geojson_validation.py schema_home = os.path.join(_get_schemas_home(), "geojson") base_schema = os.path.join(schema_home, "geojson.json") with open(base_schema) as fh: geojson_base = json.load(fh) with open(os.path.join(schema_home, "crs.json")) as fh: crs_json = json.load(fh) with open(os.path.join(schema_home, "bbox.json")) as fh: bbox_json = json.load(fh) with open(os.path.join(schema_home, "geometry.json")) as fh: geometry_json = json.load(fh) cached_json = { "http://json-schema.org/geojson/crs.json": crs_json, "http://json-schema.org/geojson/bbox.json": bbox_json, "http://json-schema.org/geojson/geometry.json": geometry_json } resolver = jsonschema.RefResolver( "http://json-schema.org/geojson/geojson.json", geojson_base, store=cached_json) validator = jsonschema.Draft4Validator(geojson_base, resolver=resolver) try: validator.validate(json.loads(data_input.stream.read())) passed = True except jsonschema.ValidationError: passed = False return passed
5,345,812
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes): """ Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7_out: TF Tensor for VGG Layer 7 output :param num_classes: Number of classes to classify :return: The Tensor for the last layer of output """ fcn8 = tf.layers.conv2d(vgg_layer7_out, filters=num_classes, kernel_size=1, padding="SAME", name='fcn8') fcn9 = tf.layers.conv2d_transpose(fcn8, filters=vgg_layer4_out.get_shape().as_list()[-1], kernel_size=4, strides=(2,2), padding="SAME", name='fcn9') fcn9_skip = tf.add(fcn9, vgg_layer4_out, name='fcn9_plus_layer4') fcn10 = tf.layers.conv2d_transpose(fcn9_skip, filters=vgg_layer3_out.get_shape().as_list()[-1], kernel_size=4, strides=(2,2), padding="SAME", name='fcn10') fcn10_skip = tf.add(fcn10, vgg_layer3_out, name='fcn10_plus_layer3') fcn11 = tf.layers.conv2d_transpose(fcn10_skip, filters=num_classes, kernel_size=16, strides=(8,8), padding="SAME", name='fcn11') return fcn11
5,345,813
def determine_issues(project): """ Get the list of issues of a project. :rtype: list """ issues = project["Issue"] if not isinstance(issues, list): return [issues] return issues
5,345,814
def init_parser(subparsers): """ Initialize the subparser. """ parser = subparsers.add_parser(COMMAND, help="delete a task from the list.") parser.add_argument("id", type=int, nargs='?', default=-1, help="the id of the task which should be deleted.")
5,345,815
def find_image_files(path=None): """ Used to find image files. Argument: path - path to directory of 'img.image' files """ if path is None: path = os.getcwd() folders = [] for folder in os.listdir(path): if folder.endswith("img.image"): folders.append(os.path.join(path, folder)) folders.sort() return folders
5,345,816
def get_media_after_date(mountpoint: str, date:str): """ Date format in EXIF yyyy:mm:dd, look for EXIF:CreateDate """ metadata = get_media_list(mountpoint) filtered_meta = list() for m in metadata: if 'File:FileModifyDate' in m: if is_after(m['File:FileModifyDate'].split(' ')[0],date): filtered_meta.append(m) return filtered_meta
5,345,817
def failure_message_on_plane(context): """Report an informative error message in a popup. Args: context: Blender bpy.context instance. Returns: Nothing. """ pg = context.scene.pdt_pg pg.error = f"{PDT_ERR_NOINT}" context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
5,345,818
def run_normal_game(): """Run a complex game, like the real thing.""" stage = create_stage() contestant_first_pick = random.randrange(3) montys_pick_algorithm(stage, contestant_first_pick) contestant_second_pick = contestants_second_pick_algorithm(stage, contestant_first_pick) wins = contestant_wins(stage, contestant_second_pick) #print (stage, contestant_first_pick, contestant_second_pick, wins) return wins
5,345,819
def reformat_wolfram_entries(titles, entries): """Reformat Wolfram entries.""" output_list = [] for title, entry in zip(titles, entries): try: if ' |' in entry: entry = '\n\t{0}'.format(entry.replace(' |', ':') .replace('\n', '\n\t')) if title == 'Result': new_entry = entry.encode('utf-8') if PY2 else entry else: raw_entry = (title + ': ' + entry) new_entry = raw_entry.encode('utf-8') if PY2 else raw_entry output_list.append(new_entry) except (AttributeError, UnicodeEncodeError): pass return output_list
5,345,820
def project_root() -> str: """Returns path to root directory of a project""" return os.path.join(_file_directory_path(__file__), '..')
5,345,821
def GetAndValidateRowId(row_dict): """Returns the integer ID for a new Row. This method is also responsible for validating the input fields related to making the new row ID. Args: row_dict: A dictionary obtained from the input JSON. Returns: An integer row ID. Raises: BadRequestError: The input wasn't formatted properly. """ if 'revision' not in row_dict: raise BadRequestError('Required field "revision" missing.') try: return int(row_dict['revision']) except (ValueError, TypeError) as e: six.raise_from( BadRequestError('Bad value for "revision", should be numerical.'), e)
5,345,822
def generate_test_cases(ukernel, channel_tile, pixel_tile, isa): """Generates all tests cases for a BILINEAR micro-kernel. Args: ukernel: C name of the micro-kernel function. channel_tile: Number of channels processed per one iteration of the inner loop of the micro-kernel. pixel_tile: Number of pixels processed per one iteration of the outer loop of the micro-kernel. isa: instruction set required to run the micro-kernel. Generated unit test will skip execution if the host processor doesn't support this ISA. Returns: Code for the test case. """ _, test_name = ukernel.split("_", 1) _, datatype, ukernel_type, _ = ukernel.split("_", 3) test_args = [ukernel] return xngen.preprocess(IBILINEAR_TEST_TEMPLATE, { "TEST_NAME": test_name.upper().replace("UKERNEL_", ""), "TEST_FUNC": ukernel, "UKERNEL_TYPE": ukernel_type.upper(), "DATATYPE": datatype, "CHANNEL_TILE": channel_tile, "PIXEL_TILE": pixel_tile, "ISA_CHECK": xnncommon.generate_isa_check_macro(isa), "next_prime": next_prime, })
5,345,823
def string_mask(stringvalue: str): """Method to divide two divide_two_numbers ARGUMENTS: Value1: first value Value2: second value """ for char in stringvalue: print(ord(char), end=' | ')
5,345,824
def get_file_range(ase, offsets, timeout=None): # type: (blobxfer.models.azure.StorageEntity, # blobxfer.models.download.Offsets, int) -> bytes """Retrieve file range :param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity :param blobxfer.models.download.Offsets offsets: download offsets :param int timeout: timeout :rtype: bytes :return: content for file range """ dir, fpath, _ = parse_file_path(ase.name) return ase.client._get_file( share_name=ase.container, directory_name=dir, file_name=fpath, start_range=offsets.range_start, end_range=offsets.range_end, validate_content=False, # HTTPS takes care of integrity during xfer timeout=timeout, snapshot=ase.snapshot, ).content
5,345,825
def parse_cli_args(): """Return parsed command-line arguments.""" parser = ArgumentParser(description='parse and summarize a GLSL file') parser.add_argument('path') shader_type_names = [member.name for member in ShaderType] parser.add_argument('shader_type', nargs='?', choices=shader_type_names, default=ShaderType.Fragment.name) return parser.parse_args()
5,345,826
def genus_species_name(genus, species): """Return name, genus with species if present. Copes with species being None (or empty string). """ # This is a simple function, centralising it for consistency assert genus and genus == genus.strip(), repr(genus) if species: assert species == species.strip(), repr(species) return f"{genus} {species}" else: return genus
5,345,827
def _native_set_to_python_list(typ, payload, c): """ Create a Python list from a native set's items. """ nitems = payload.used listobj = c.pyapi.list_new(nitems) ok = cgutils.is_not_null(c.builder, listobj) with c.builder.if_then(ok, likely=True): index = cgutils.alloca_once_value(c.builder, ir.Constant(nitems.type, 0)) with payload._iterate() as loop: i = c.builder.load(index) item = loop.entry.key itemobj = c.box(typ.dtype, item) c.pyapi.list_setitem(listobj, i, itemobj) i = c.builder.add(i, ir.Constant(i.type, 1)) c.builder.store(i, index) return ok, listobj
5,345,828
def asm(code, arch='x86', mode='32'): """Assemble instructions to bytecode"" Args: code: str, eg: add eax, ebx; pop ecx arch: str, default value: 'x86' mode: str, default value: '32' """ arch = get_kt_arch(arch) if arch is None: print('Unsupported architecture') return mode = get_kt_mod(mode) if mode is None: print('Unsupported mode') return try: ks = kt.Ks(arch, mode) # Initialize engine in X86-32bit mode encoding, count = ks.asm(code) print("%s = %s \n(number of instructions: %u)" % (code, [hex(x) for x in encoding], count)) except: print("ERROR ASSEMBLING")
5,345,829
def JointAngleCalc(frame,vsk): """ Joint Angle Calculation function. Calculates the Joint angles of plugingait and stores the data in array Stores: RPel_angle = [] LPel_angle = [] RHip_angle = [] LHip_angle = [] RKnee_angle = [] LKnee_angle = [] RAnkle_angle = [] LAnkle_angle = [] Joint Axis store like below form The axis is in the form [[origin], [axis]] Origin defines the position of axis and axis is the direction vector of x, y, z axis attached to the origin If it is just single one (Pelvis, Hip, Head, Thorax) Axis = [[origin_x, origin_y, origin_z],[[Xaxis_x,Xaxis_y,Xaxis_z], [Yaxis_x,Yaxis_y,Yaxis_z], [Zaxis_x,Zaxis_y,Zaxis_z]]] If it has both of Right and Left ( knee, angle, foot, clavicle, humerus, radius, hand) Axis = [[[R_origin_x,R_origin_y,R_origin_z], [L_origin_x,L_origin_y,L_origin_z]],[[[R_Xaxis_x,R_Xaxis_y,R_Xaxis_z], [R_Yaxis_x,R_Yaxis_y,R_Yaxis_z], [R_Zaxis_x,R_Zaxis_y,R_Zaxis_z]], [[L_Xaxis_x,L_Xaxis_y,L_Xaxis_z], [L_Yaxis_x,L_Yaxis_y,L_Yaxis_z], [L_Zaxis_x,L_Zaxis_y,L_Zaxis_z]]]] Parameters ---------- frame : dict Dictionaries of marker lists. vsk : dict A dictionary containing subject measurements. Returns ------- r, jc : tuple Returns a tuple containing an array that holds the result of all the joint calculations, followed by a dictionary for joint center marker positions. Examples -------- >>> import numpy as np >>> from .pyCGM import JointAngleCalc >>> from .pycgmIO import loadC3D, loadVSK >>> from .pycgmStatic import getStatic >>> from .pyCGM_Helpers import getfilenames >>> import os >>> fileNames=getfilenames(2) >>> c3dFile = fileNames[1] >>> vskFile = fileNames[2] >>> result = loadC3D(c3dFile) >>> data = result[0] >>> frame = result[0][0] >>> vskData = loadVSK(vskFile, False) >>> vsk = getStatic(data,vskData,flat_foot=False) >>> results = JointAngleCalc(frame, vsk)[1] >>> np.around(results['Pelvis'], 2) array([ 246.15, 353.26, 1031.71]) >>> np.around(results['Thorax'], 2) array([ 250.56, 303.23, 1461.17]) >>> np.around(results['Head'], 2) array([ 244.9 , 325.06, 1730.16]) >>> np.around(results['RHand'], 2) array([ 770.93, 591.05, 1079.05]) """ # THIS IS FOOT PROGRESS ANGLE rfoot_prox,rfoot_proy,rfoot_proz,lfoot_prox,lfoot_proy,lfoot_proz = [None]*6 #First Calculate Pelvis pelvis_axis = pelvisJointCenter(frame) kin_Pelvis_axis = pelvis_axis kin_Pelvis_JC = pelvis_axis[0] #quick fix for storing JC #change to same format Pelvis_vectors = pelvis_axis[1] Pelvis_origin = pelvis_axis[0] #need to update this based on the file global_Axis = vsk['GCS'] #make the array which will be the input of findangle function pelvis_Axis_mod = np.vstack([np.subtract(Pelvis_vectors[0],Pelvis_origin), np.subtract(Pelvis_vectors[1],Pelvis_origin), np.subtract(Pelvis_vectors[2],Pelvis_origin)]) global_pelvis_angle = getangle(global_Axis,pelvis_Axis_mod) pelx=global_pelvis_angle[0] pely=global_pelvis_angle[1] pelz=global_pelvis_angle[2] # and then find hip JC hip_JC = hipJointCenter(frame,pelvis_axis[0],pelvis_axis[1][0],pelvis_axis[1][1],pelvis_axis[1][2],vsk=vsk) kin_L_Hip_JC = hip_JC[0] #quick fix for storing JC kin_R_Hip_JC = hip_JC[1] #quick fix for storing JC hip_axis = hipAxisCenter(hip_JC[0],hip_JC[1],pelvis_axis) knee_JC = kneeJointCenter(frame,hip_JC,0,vsk=vsk) kin_R_Knee_JC = knee_JC[0] #quick fix for storing JC kin_L_Knee_JC = knee_JC[1] #quick fix for storing JC #change to same format Hip_axis_form = hip_axis[1] Hip_center_form = hip_axis[0] R_Knee_axis_form = knee_JC[2][0] R_Knee_center_form = knee_JC[0] L_Knee_axis_form = knee_JC[2][1] L_Knee_center_form = knee_JC[1] #make the array which will be the input of findangle function hip_Axis = np.vstack([np.subtract(Hip_axis_form[0],Hip_center_form), np.subtract(Hip_axis_form[1],Hip_center_form), np.subtract(Hip_axis_form[2],Hip_center_form)]) R_knee_Axis = np.vstack([np.subtract(R_Knee_axis_form[0],R_Knee_center_form), np.subtract(R_Knee_axis_form[1],R_Knee_center_form), np.subtract(R_Knee_axis_form[2],R_Knee_center_form)]) L_knee_Axis = np.vstack([np.subtract(L_Knee_axis_form[0],L_Knee_center_form), np.subtract(L_Knee_axis_form[1],L_Knee_center_form), np.subtract(L_Knee_axis_form[2],L_Knee_center_form)]) R_pelvis_knee_angle = getangle(hip_Axis,R_knee_Axis) L_pelvis_knee_angle = getangle(hip_Axis,L_knee_Axis) rhipx=R_pelvis_knee_angle[0]*-1 rhipy=R_pelvis_knee_angle[1] rhipz=R_pelvis_knee_angle[2]*-1+90 lhipx=L_pelvis_knee_angle[0]*-1 lhipy=L_pelvis_knee_angle[1]*-1 lhipz=L_pelvis_knee_angle[2]-90 ankle_JC = ankleJointCenter(frame,knee_JC,0,vsk=vsk) kin_R_Ankle_JC = ankle_JC[0] #quick fix for storing JC kin_L_Ankle_JC = ankle_JC[1] #quick fix for storing JC #change to same format R_Ankle_axis_form = ankle_JC[2][0] R_Ankle_center_form = ankle_JC[0] L_Ankle_axis_form = ankle_JC[2][1] L_Ankle_center_form = ankle_JC[1] #make the array which will be the input of findangle function # In case of knee axis I mentioned it before as R_knee_Axis and L_knee_Axis R_ankle_Axis = np.vstack([np.subtract(R_Ankle_axis_form[0],R_Ankle_center_form), np.subtract(R_Ankle_axis_form[1],R_Ankle_center_form), np.subtract(R_Ankle_axis_form[2],R_Ankle_center_form)]) L_ankle_Axis = np.vstack([np.subtract(L_Ankle_axis_form[0],L_Ankle_center_form), np.subtract(L_Ankle_axis_form[1],L_Ankle_center_form), np.subtract(L_Ankle_axis_form[2],L_Ankle_center_form)]) R_knee_ankle_angle = getangle(R_knee_Axis,R_ankle_Axis) L_knee_ankle_angle = getangle(L_knee_Axis,L_ankle_Axis) rkneex=R_knee_ankle_angle[0] rkneey=R_knee_ankle_angle[1] rkneez=R_knee_ankle_angle[2]*-1+90 lkneex=L_knee_ankle_angle[0] lkneey=L_knee_ankle_angle[1]*-1 lkneez=L_knee_ankle_angle[2] - 90 # ANKLE ANGLE offset = 0 foot_JC = footJointCenter(frame,vsk,ankle_JC,knee_JC,offset) kin_R_Foot_JC = foot_JC[0] #quick fix for storing JC kin_L_Foot_JC = foot_JC[1] #quick fix for storing JC kin_RHEE = frame['RHEE'] kin_LHEE = frame['LHEE'] # Change to same format R_Foot_axis_form = foot_JC[2][0] R_Foot_center_form = foot_JC[0] L_Foot_axis_form = foot_JC[2][1] L_Foot_center_form = foot_JC[1] R_foot_Axis = np.vstack([np.subtract(R_Foot_axis_form[0],R_Foot_center_form), np.subtract(R_Foot_axis_form[1],R_Foot_center_form), np.subtract(R_Foot_axis_form[2],R_Foot_center_form)]) L_foot_Axis = np.vstack([np.subtract(L_Foot_axis_form[0],L_Foot_center_form), np.subtract(L_Foot_axis_form[1],L_Foot_center_form), np.subtract(L_Foot_axis_form[2],L_Foot_center_form)]) R_ankle_foot_angle = getangle(R_ankle_Axis,R_foot_Axis) L_ankle_foot_angle = getangle(L_ankle_Axis,L_foot_Axis) ranklex=R_ankle_foot_angle[0]*(-1)-90 rankley=R_ankle_foot_angle[2]*(-1)+90 ranklez=R_ankle_foot_angle[1] lanklex=L_ankle_foot_angle[0]*(-1)-90 lankley=L_ankle_foot_angle[2]-90 lanklez=L_ankle_foot_angle[1]*(-1) # ABSOLUTE FOOT ANGLE R_global_foot_angle = getangle(global_Axis,R_foot_Axis) L_global_foot_angle = getangle(global_Axis,L_foot_Axis) rfootx=R_global_foot_angle[0] rfooty=R_global_foot_angle[2]-90 rfootz=R_global_foot_angle[1] lfootx=L_global_foot_angle[0] lfooty=(L_global_foot_angle[2]-90)*-1 lfootz=L_global_foot_angle[1]*-1 #First Calculate HEAD head_axis = headJC(frame,vsk=vsk) kin_Head_JC = head_axis[1] #quick fix for storing JC LFHD = frame['LFHD'] #as above RFHD = frame['RFHD'] LBHD = frame['LBHD'] RBHD = frame['RBHD'] kin_Head_Front = np.array((LFHD+RFHD)/2) kin_Head_Back = np.array((LBHD+RBHD)/2) #change to same format Head_axis_form = head_axis[0] Head_center_form = head_axis[1] #Global_axis_form = [[0,1,0],[-1,0,0],[0,0,1]] Global_center_form = [0,0,0] #*********************************************************** Global_axis_form = vsk['GCS'] #Global_axis_form = rotmat(x=0,y=0,z=180) #this is some weird fix to global axis #make the array which will be the input of findangle function head_Axis_mod = np.vstack([np.subtract(Head_axis_form[0],Head_center_form), np.subtract(Head_axis_form[1],Head_center_form), np.subtract(Head_axis_form[2],Head_center_form)]) global_Axis = np.vstack([np.subtract(Global_axis_form[0],Global_center_form), np.subtract(Global_axis_form[1],Global_center_form), np.subtract(Global_axis_form[2],Global_center_form)]) global_head_angle = getHeadangle(global_Axis,head_Axis_mod) headx=(global_head_angle[0]*-1)# + 24.8 if headx <-180: headx = headx+360 heady=global_head_angle[1]*-1 headz=global_head_angle[2]#+180 if headz <-180: headz = headz-360 # Calculate THORAX thorax_axis = thoraxJC(frame) kin_Thorax_JC = thorax_axis[1] #quick fix for storing JC kin_Thorax_axis = thorax_axis # Change to same format Thorax_axis_form = thorax_axis[0] Thorax_center_form = thorax_axis[1] Global_axis_form = [[0,1,0],[-1,0,0],[0,0,1]] Global_center_form = [0,0,0] #******************************************************* Global_axis_form = rotmat(x=0,y=0,z=180) #this needs to be fixed for the global rotation #make the array which will be the input of findangle function thorax_Axis_mod = np.vstack([np.subtract(Thorax_axis_form[0],Thorax_center_form), np.subtract(Thorax_axis_form[1],Thorax_center_form), np.subtract(Thorax_axis_form[2],Thorax_center_form)]) global_Axis = np.vstack([np.subtract(Global_axis_form[0],Global_center_form), np.subtract(Global_axis_form[1],Global_center_form), np.subtract(Global_axis_form[2],Global_center_form)]) global_thorax_angle = getangle(global_Axis,thorax_Axis_mod) if global_thorax_angle[0] > 0: global_thorax_angle[0] = global_thorax_angle[0] - 180 elif global_thorax_angle[0] < 0: global_thorax_angle[0] = global_thorax_angle[0] + 180 thox=global_thorax_angle[0] thoy=global_thorax_angle[1] thoz=global_thorax_angle[2]+90 # Calculate NECK head_thorax_angle = getHeadangle(head_Axis_mod,thorax_Axis_mod) neckx=(head_thorax_angle[0]-180)*-1# - 24.9 necky=head_thorax_angle[1] neckz=head_thorax_angle[2]*-1 kin_C7 = frame['C7']#quick fix to calculate CoM kin_CLAV = frame['CLAV'] kin_STRN = frame['STRN'] kin_T10 = frame['T10'] # Calculate SPINE pel_tho_angle = getangle_spi(pelvis_Axis_mod,thorax_Axis_mod) spix=pel_tho_angle[0] spiy=pel_tho_angle[2]*-1 spiz=pel_tho_angle[1] # Calculate SHOULDER wand = findwandmarker(frame,thorax_axis) shoulder_JC = findshoulderJC(frame,thorax_axis,wand,vsk=vsk) kin_R_Shoulder_JC = shoulder_JC[0] #quick fix for storing JC kin_L_Shoulder_JC = shoulder_JC[1] #quick fix for storing JC shoulder_axis = shoulderAxisCalc(frame,thorax_axis,shoulder_JC,wand) humerus_JC = elbowJointCenter(frame,thorax_axis,shoulder_JC,wand,vsk=vsk) kin_R_Humerus_JC = humerus_JC[0][0] #quick fix for storing JC kin_L_Humerus_JC = humerus_JC[0][1] #quick fix for storing JC # Change to same format R_Clavicle_axis_form = shoulder_axis[1][0] L_Clavicle_axis_form = shoulder_axis[1][1] R_Clavicle_center_form = shoulder_axis[0][0] L_Clavicle_center_form = shoulder_axis[0][1] # Change to same format R_Humerus_axis_form = humerus_JC[1][0] L_Humerus_axis_form = humerus_JC[1][1] R_Humerus_center_form = humerus_JC[0][0] L_Humerus_center_form = humerus_JC[0][1] # make the array which will be the input of findangle function R_humerus_Axis_mod = np.vstack([np.subtract(R_Humerus_axis_form[0],R_Humerus_center_form), np.subtract(R_Humerus_axis_form[1],R_Humerus_center_form), np.subtract(R_Humerus_axis_form[2],R_Humerus_center_form)]) L_humerus_Axis_mod = np.vstack([np.subtract(L_Humerus_axis_form[0],L_Humerus_center_form), np.subtract(L_Humerus_axis_form[1],L_Humerus_center_form), np.subtract(L_Humerus_axis_form[2],L_Humerus_center_form)]) R_thorax_shoulder_angle = getangle_sho(thorax_Axis_mod,R_humerus_Axis_mod) L_thorax_shoulder_angle = getangle_sho(thorax_Axis_mod,L_humerus_Axis_mod) if R_thorax_shoulder_angle[2] < 0: R_thorax_shoulder_angle[2]=R_thorax_shoulder_angle[2]+180 elif R_thorax_shoulder_angle[2] >0: R_thorax_shoulder_angle[2] = R_thorax_shoulder_angle[2]-180 if R_thorax_shoulder_angle[1] > 0: R_thorax_shoulder_angle[1] = R_thorax_shoulder_angle[1]-180 elif R_thorax_shoulder_angle[1] <0: R_thorax_shoulder_angle[1] = R_thorax_shoulder_angle[1]*-1-180 if L_thorax_shoulder_angle[1] < 0: L_thorax_shoulder_angle[1]=L_thorax_shoulder_angle[1]+180 elif L_thorax_shoulder_angle[1] >0: L_thorax_shoulder_angle[1] = L_thorax_shoulder_angle[1]-180 rshox=R_thorax_shoulder_angle[0]*-1 rshoy=R_thorax_shoulder_angle[1]*-1 rshoz=R_thorax_shoulder_angle[2] lshox=L_thorax_shoulder_angle[0]*-1 lshoy=L_thorax_shoulder_angle[1] lshoz=(L_thorax_shoulder_angle[2]-180)*-1 if lshoz >180: lshoz = lshoz - 360 # Calculate ELBOW radius_JC = wristJointCenter(frame,shoulder_JC,wand,humerus_JC) kin_R_Radius_JC = radius_JC[0][0] #quick fix for storing JC kin_L_Radius_JC = radius_JC[0][1] #quick fix for storing JC # Change to same format R_Radius_axis_form = radius_JC[1][0] L_Radius_axis_form = radius_JC[1][1] R_Radius_center_form = radius_JC[0][0] L_Radius_center_form = radius_JC[0][1] # make the array which will be the input of findangle function R_radius_Axis_mod = np.vstack([np.subtract(R_Radius_axis_form[0],R_Radius_center_form), np.subtract(R_Radius_axis_form[1],R_Radius_center_form), np.subtract(R_Radius_axis_form[2],R_Radius_center_form)]) L_radius_Axis_mod = np.vstack([np.subtract(L_Radius_axis_form[0],L_Radius_center_form), np.subtract(L_Radius_axis_form[1],L_Radius_center_form), np.subtract(L_Radius_axis_form[2],L_Radius_center_form)]) R_humerus_radius_angle = getangle(R_humerus_Axis_mod,R_radius_Axis_mod) L_humerus_radius_angle = getangle(L_humerus_Axis_mod,L_radius_Axis_mod) relbx=R_humerus_radius_angle[0] relby=R_humerus_radius_angle[1] relbz=R_humerus_radius_angle[2]-90.0 lelbx=L_humerus_radius_angle[0] lelby=L_humerus_radius_angle[1] lelbz=L_humerus_radius_angle[2]-90.0 # Calculate WRIST hand_JC = handJointCenter(frame,humerus_JC,radius_JC,vsk=vsk) kin_R_Hand_JC = hand_JC[0][0] #quick fix for storing JC kin_L_Hand_JC = hand_JC[0][1] #quick fix for storing JC # Change to same format R_Hand_axis_form = hand_JC[1][0] L_Hand_axis_form = hand_JC[1][1] R_Hand_center_form = hand_JC[0][0] L_Hand_center_form = hand_JC[0][1] # make the array which will be the input of findangle function R_hand_Axis_mod = np.vstack([np.subtract(R_Hand_axis_form[0],R_Hand_center_form), np.subtract(R_Hand_axis_form[1],R_Hand_center_form), np.subtract(R_Hand_axis_form[2],R_Hand_center_form)]) L_hand_Axis_mod = np.vstack([np.subtract(L_Hand_axis_form[0],L_Hand_center_form), np.subtract(L_Hand_axis_form[1],L_Hand_center_form), np.subtract(L_Hand_axis_form[2],L_Hand_center_form)]) R_radius_hand_angle = getangle(R_radius_Axis_mod,R_hand_Axis_mod) L_radius_hand_angle = getangle(L_radius_Axis_mod,L_hand_Axis_mod) rwrtx=R_radius_hand_angle[0] rwrty=R_radius_hand_angle[1] rwrtz=R_radius_hand_angle[2]*-1 + 90 lwrtx=L_radius_hand_angle[0] lwrty=L_radius_hand_angle[1]*-1 lwrtz=L_radius_hand_angle[2]-90 if lwrtz < -180: lwrtz = lwrtz + 360 # make each axis as same format to store # Pelvis # origin pel_origin = Pelvis_origin pel_ox=pel_origin[0] pel_oy=pel_origin[1] pel_oz=pel_origin[2] # xaxis pel_x_axis = Pelvis_vectors[0] pel_xx=pel_x_axis[0] pel_xy=pel_x_axis[1] pel_xz=pel_x_axis[2] # yaxis pel_y_axis = Pelvis_vectors[1] pel_yx=pel_y_axis[0] pel_yy=pel_y_axis[1] pel_yz=pel_y_axis[2] # zaxis pel_z_axis = Pelvis_vectors[2] pel_zx=pel_z_axis[0] pel_zy=pel_z_axis[1] pel_zz=pel_z_axis[2] # Hip # origin hip_origin = Hip_center_form hip_ox=hip_origin[0] hip_oy=hip_origin[1] hip_oz=hip_origin[2] # xaxis hip_x_axis = Hip_axis_form[0] hip_xx=hip_x_axis[0] hip_xy=hip_x_axis[1] hip_xz=hip_x_axis[2] # yaxis hip_y_axis = Hip_axis_form[1] hip_yx=hip_y_axis[0] hip_yy=hip_y_axis[1] hip_yz=hip_y_axis[2] # zaxis hip_z_axis = Hip_axis_form[2] hip_zx=hip_z_axis[0] hip_zy=hip_z_axis[1] hip_zz=hip_z_axis[2] # R KNEE # origin rknee_origin = R_Knee_center_form rknee_ox=rknee_origin[0] rknee_oy=rknee_origin[1] rknee_oz=rknee_origin[2] # xaxis rknee_x_axis = R_Knee_axis_form[0] rknee_xx=rknee_x_axis[0] rknee_xy=rknee_x_axis[1] rknee_xz=rknee_x_axis[2] # yaxis rknee_y_axis = R_Knee_axis_form[1] rknee_yx=rknee_y_axis[0] rknee_yy=rknee_y_axis[1] rknee_yz=rknee_y_axis[2] # zaxis rknee_z_axis = R_Knee_axis_form[2] rknee_zx=rknee_z_axis[0] rknee_zy=rknee_z_axis[1] rknee_zz=rknee_z_axis[2] # L KNEE # origin lknee_origin = L_Knee_center_form lknee_ox=lknee_origin[0] lknee_oy=lknee_origin[1] lknee_oz=lknee_origin[2] # xaxis lknee_x_axis = L_Knee_axis_form[0] lknee_xx=lknee_x_axis[0] lknee_xy=lknee_x_axis[1] lknee_xz=lknee_x_axis[2] # yaxis lknee_y_axis = L_Knee_axis_form[1] lknee_yx=lknee_y_axis[0] lknee_yy=lknee_y_axis[1] lknee_yz=lknee_y_axis[2] # zaxis lknee_z_axis = L_Knee_axis_form[2] lknee_zx=lknee_z_axis[0] lknee_zy=lknee_z_axis[1] lknee_zz=lknee_z_axis[2] # R ANKLE # origin rank_origin = R_Ankle_center_form rank_ox=rank_origin[0] rank_oy=rank_origin[1] rank_oz=rank_origin[2] # xaxis rank_x_axis = R_Ankle_axis_form[0] rank_xx=rank_x_axis[0] rank_xy=rank_x_axis[1] rank_xz=rank_x_axis[2] # yaxis rank_y_axis = R_Ankle_axis_form[1] rank_yx=rank_y_axis[0] rank_yy=rank_y_axis[1] rank_yz=rank_y_axis[2] # zaxis rank_z_axis = R_Ankle_axis_form[2] rank_zx=rank_z_axis[0] rank_zy=rank_z_axis[1] rank_zz=rank_z_axis[2] # L ANKLE # origin lank_origin = L_Ankle_center_form lank_ox=lank_origin[0] lank_oy=lank_origin[1] lank_oz=lank_origin[2] # xaxis lank_x_axis = L_Ankle_axis_form[0] lank_xx=lank_x_axis[0] lank_xy=lank_x_axis[1] lank_xz=lank_x_axis[2] # yaxis lank_y_axis = L_Ankle_axis_form[1] lank_yx=lank_y_axis[0] lank_yy=lank_y_axis[1] lank_yz=lank_y_axis[2] # zaxis lank_z_axis = L_Ankle_axis_form[2] lank_zx=lank_z_axis[0] lank_zy=lank_z_axis[1] lank_zz=lank_z_axis[2] # R FOOT # origin rfoot_origin = R_Foot_center_form rfoot_ox=rfoot_origin[0] rfoot_oy=rfoot_origin[1] rfoot_oz=rfoot_origin[2] # xaxis rfoot_x_axis = R_Foot_axis_form[0] rfoot_xx=rfoot_x_axis[0] rfoot_xy=rfoot_x_axis[1] rfoot_xz=rfoot_x_axis[2] # yaxis rfoot_y_axis = R_Foot_axis_form[1] rfoot_yx=rfoot_y_axis[0] rfoot_yy=rfoot_y_axis[1] rfoot_yz=rfoot_y_axis[2] # zaxis rfoot_z_axis = R_Foot_axis_form[2] rfoot_zx=rfoot_z_axis[0] rfoot_zy=rfoot_z_axis[1] rfoot_zz=rfoot_z_axis[2] # L FOOT # origin lfoot_origin = L_Foot_center_form lfoot_ox=lfoot_origin[0] lfoot_oy=lfoot_origin[1] lfoot_oz=lfoot_origin[2] # xaxis lfoot_x_axis = L_Foot_axis_form[0] lfoot_xx=lfoot_x_axis[0] lfoot_xy=lfoot_x_axis[1] lfoot_xz=lfoot_x_axis[2] # yaxis lfoot_y_axis = L_Foot_axis_form[1] lfoot_yx=lfoot_y_axis[0] lfoot_yy=lfoot_y_axis[1] lfoot_yz=lfoot_y_axis[2] # zaxis lfoot_z_axis = L_Foot_axis_form[2] lfoot_zx=lfoot_z_axis[0] lfoot_zy=lfoot_z_axis[1] lfoot_zz=lfoot_z_axis[2] # HEAD # origin head_origin = Head_center_form head_ox=head_origin[0] head_oy=head_origin[1] head_oz=head_origin[2] # xaxis head_x_axis = Head_axis_form[0] head_xx=head_x_axis[0] head_xy=head_x_axis[1] head_xz=head_x_axis[2] # yaxis head_y_axis = Head_axis_form[1] head_yx=head_y_axis[0] head_yy=head_y_axis[1] head_yz=head_y_axis[2] # zaxis head_z_axis = Head_axis_form[2] head_zx=head_z_axis[0] head_zy=head_z_axis[1] head_zz=head_z_axis[2] # THORAX # origin tho_origin = Thorax_center_form tho_ox=tho_origin[0] tho_oy=tho_origin[1] tho_oz=tho_origin[2] # xaxis tho_x_axis = Thorax_axis_form[0] tho_xx=tho_x_axis[0] tho_xy=tho_x_axis[1] tho_xz=tho_x_axis[2] # yaxis tho_y_axis = Thorax_axis_form[1] tho_yx=tho_y_axis[0] tho_yy=tho_y_axis[1] tho_yz=tho_y_axis[2] # zaxis tho_z_axis = Thorax_axis_form[2] tho_zx=tho_z_axis[0] tho_zy=tho_z_axis[1] tho_zz=tho_z_axis[2] # R CLAVICLE # origin rclav_origin = R_Clavicle_center_form rclav_ox=rclav_origin[0] rclav_oy=rclav_origin[1] rclav_oz=rclav_origin[2] # xaxis rclav_x_axis = R_Clavicle_axis_form[0] rclav_xx=rclav_x_axis[0] rclav_xy=rclav_x_axis[1] rclav_xz=rclav_x_axis[2] # yaxis rclav_y_axis = R_Clavicle_axis_form[1] rclav_yx=rclav_y_axis[0] rclav_yy=rclav_y_axis[1] rclav_yz=rclav_y_axis[2] # zaxis rclav_z_axis = R_Clavicle_axis_form[2] rclav_zx=rclav_z_axis[0] rclav_zy=rclav_z_axis[1] rclav_zz=rclav_z_axis[2] # L CLAVICLE # origin lclav_origin = L_Clavicle_center_form lclav_ox=lclav_origin[0] lclav_oy=lclav_origin[1] lclav_oz=lclav_origin[2] # xaxis lclav_x_axis = L_Clavicle_axis_form[0] lclav_xx=lclav_x_axis[0] lclav_xy=lclav_x_axis[1] lclav_xz=lclav_x_axis[2] # yaxis lclav_y_axis = L_Clavicle_axis_form[1] lclav_yx=lclav_y_axis[0] lclav_yy=lclav_y_axis[1] lclav_yz=lclav_y_axis[2] # zaxis lclav_z_axis = L_Clavicle_axis_form[2] lclav_zx=lclav_z_axis[0] lclav_zy=lclav_z_axis[1] lclav_zz=lclav_z_axis[2] # R HUMERUS # origin rhum_origin = R_Humerus_center_form rhum_ox=rhum_origin[0] rhum_oy=rhum_origin[1] rhum_oz=rhum_origin[2] # xaxis rhum_x_axis = R_Humerus_axis_form[0] rhum_xx=rhum_x_axis[0] rhum_xy=rhum_x_axis[1] rhum_xz=rhum_x_axis[2] # yaxis rhum_y_axis = R_Humerus_axis_form[1] rhum_yx=rhum_y_axis[0] rhum_yy=rhum_y_axis[1] rhum_yz=rhum_y_axis[2] # zaxis rhum_z_axis = R_Humerus_axis_form[2] rhum_zx=rhum_z_axis[0] rhum_zy=rhum_z_axis[1] rhum_zz=rhum_z_axis[2] # L HUMERUS # origin lhum_origin = L_Humerus_center_form lhum_ox=lhum_origin[0] lhum_oy=lhum_origin[1] lhum_oz=lhum_origin[2] # xaxis lhum_x_axis = L_Humerus_axis_form[0] lhum_xx=lhum_x_axis[0] lhum_xy=lhum_x_axis[1] lhum_xz=lhum_x_axis[2] # yaxis lhum_y_axis = L_Humerus_axis_form[1] lhum_yx=lhum_y_axis[0] lhum_yy=lhum_y_axis[1] lhum_yz=lhum_y_axis[2] # zaxis lhum_z_axis = L_Humerus_axis_form[2] lhum_zx=lhum_z_axis[0] lhum_zy=lhum_z_axis[1] lhum_zz=lhum_z_axis[2] # R RADIUS # origin rrad_origin = R_Radius_center_form rrad_ox=rrad_origin[0] rrad_oy=rrad_origin[1] rrad_oz=rrad_origin[2] # xaxis rrad_x_axis = R_Radius_axis_form[0] rrad_xx=rrad_x_axis[0] rrad_xy=rrad_x_axis[1] rrad_xz=rrad_x_axis[2] # yaxis rrad_y_axis = R_Radius_axis_form[1] rrad_yx=rrad_y_axis[0] rrad_yy=rrad_y_axis[1] rrad_yz=rrad_y_axis[2] # zaxis rrad_z_axis = R_Radius_axis_form[2] rrad_zx=rrad_z_axis[0] rrad_zy=rrad_z_axis[1] rrad_zz=rrad_z_axis[2] # L RADIUS # origin lrad_origin = L_Radius_center_form lrad_ox=lrad_origin[0] lrad_oy=lrad_origin[1] lrad_oz=lrad_origin[2] # xaxis lrad_x_axis = L_Radius_axis_form[0] lrad_xx=lrad_x_axis[0] lrad_xy=lrad_x_axis[1] lrad_xz=lrad_x_axis[2] # yaxis lrad_y_axis = L_Radius_axis_form[1] lrad_yx=lrad_y_axis[0] lrad_yy=lrad_y_axis[1] lrad_yz=lrad_y_axis[2] # zaxis lrad_z_axis = L_Radius_axis_form[2] lrad_zx=lrad_z_axis[0] lrad_zy=lrad_z_axis[1] lrad_zz=lrad_z_axis[2] # R HAND # origin rhand_origin = R_Hand_center_form rhand_ox=rhand_origin[0] rhand_oy=rhand_origin[1] rhand_oz=rhand_origin[2] # xaxis rhand_x_axis= R_Hand_axis_form[0] rhand_xx=rhand_x_axis[0] rhand_xy=rhand_x_axis[1] rhand_xz=rhand_x_axis[2] # yaxis rhand_y_axis= R_Hand_axis_form[1] rhand_yx=rhand_y_axis[0] rhand_yy=rhand_y_axis[1] rhand_yz=rhand_y_axis[2] # zaxis rhand_z_axis= R_Hand_axis_form[2] rhand_zx=rhand_z_axis[0] rhand_zy=rhand_z_axis[1] rhand_zz=rhand_z_axis[2] # L HAND # origin lhand_origin = L_Hand_center_form lhand_ox=lhand_origin[0] lhand_oy=lhand_origin[1] lhand_oz=lhand_origin[2] # xaxis lhand_x_axis = L_Hand_axis_form[0] lhand_xx=lhand_x_axis[0] lhand_xy=lhand_x_axis[1] lhand_xz=lhand_x_axis[2] # yaxis lhand_y_axis = L_Hand_axis_form[1] lhand_yx=lhand_y_axis[0] lhand_yy=lhand_y_axis[1] lhand_yz=lhand_y_axis[2] # zaxis lhand_z_axis = L_Hand_axis_form[2] lhand_zx=lhand_z_axis[0] lhand_zy=lhand_z_axis[1] lhand_zz=lhand_z_axis[2] #----------------------------------------------------- #Store everything in an array to send back to results of process r=[ pelx,pely,pelz, rhipx,rhipy,rhipz, lhipx,lhipy,lhipz, rkneex,rkneey,rkneez, lkneex,lkneey,lkneez, ranklex,rankley,ranklez, lanklex,lankley,lanklez, rfootx,rfooty,rfootz, lfootx,lfooty,lfootz, headx,heady,headz, thox,thoy,thoz, neckx,necky,neckz, spix,spiy,spiz, rshox,rshoy,rshoz, lshox,lshoy,lshoz, relbx,relby,relbz, lelbx,lelby,lelbz, rwrtx,rwrty,rwrtz, lwrtx,lwrty,lwrtz, pel_ox,pel_oy,pel_oz,pel_xx,pel_xy,pel_xz,pel_yx,pel_yy,pel_yz,pel_zx,pel_zy,pel_zz, hip_ox,hip_oy,hip_oz,hip_xx,hip_xy,hip_xz,hip_yx,hip_yy,hip_yz,hip_zx,hip_zy,hip_zz, rknee_ox,rknee_oy,rknee_oz,rknee_xx,rknee_xy,rknee_xz,rknee_yx,rknee_yy,rknee_yz,rknee_zx,rknee_zy,rknee_zz, lknee_ox,lknee_oy,lknee_oz,lknee_xx,lknee_xy,lknee_xz,lknee_yx,lknee_yy,lknee_yz,lknee_zx,lknee_zy,lknee_zz, rank_ox,rank_oy,rank_oz,rank_xx,rank_xy,rank_xz,rank_yx,rank_yy,rank_yz,rank_zx,rank_zy,rank_zz, lank_ox,lank_oy,lank_oz,lank_xx,lank_xy,lank_xz,lank_yx,lank_yy,lank_yz,lank_zx,lank_zy,lank_zz, rfoot_ox,rfoot_oy,rfoot_oz,rfoot_xx,rfoot_xy,rfoot_xz,rfoot_yx,rfoot_yy,rfoot_yz,rfoot_zx,rfoot_zy,rfoot_zz, lfoot_ox,lfoot_oy,lfoot_oz,lfoot_xx,lfoot_xy,lfoot_xz,lfoot_yx,lfoot_yy,lfoot_yz,lfoot_zx,lfoot_zy,lfoot_zz, head_ox,head_oy,head_oz,head_xx,head_xy,head_xz,head_yx,head_yy,head_yz,head_zx,head_zy,head_zz, tho_ox,tho_oy,tho_oz,tho_xx,tho_xy,tho_xz,tho_yx,tho_yy,tho_yz,tho_zx,tho_zy,tho_zz, rclav_ox,rclav_oy,rclav_oz,rclav_xx,rclav_xy,rclav_xz,rclav_yx,rclav_yy,rclav_yz,rclav_zx,rclav_zy,rclav_zz, lclav_ox,lclav_oy,lclav_oz,lclav_xx,lclav_xy,lclav_xz,lclav_yx,lclav_yy,lclav_yz,lclav_zx,lclav_zy,lclav_zz, rhum_ox,rhum_oy,rhum_oz,rhum_xx,rhum_xy,rhum_xz,rhum_yx,rhum_yy,rhum_yz,rhum_zx,rhum_zy,rhum_zz, lhum_ox,lhum_oy,lhum_oz,lhum_xx,lhum_xy,lhum_xz,lhum_yx,lhum_yy,lhum_yz,lhum_zx,lhum_zy,lhum_zz, rrad_ox,rrad_oy,rrad_oz,rrad_xx,rrad_xy,rrad_xz,rrad_yx,rrad_yy,rrad_yz,rrad_zx,rrad_zy,rrad_zz, lrad_ox,lrad_oy,lrad_oz,lrad_xx,lrad_xy,lrad_xz,lrad_yx,lrad_yy,lrad_yz,lrad_zx,lrad_zy,lrad_zz, rhand_ox,rhand_oy,rhand_oz,rhand_xx,rhand_xy,rhand_xz,rhand_yx,rhand_yy,rhand_yz,rhand_zx,rhand_zy,rhand_zz, lhand_ox,lhand_oy,lhand_oz,lhand_xx,lhand_xy,lhand_xz,lhand_yx,lhand_yy,lhand_yz,lhand_zx,lhand_zy,lhand_zz ] r=np.array(r,dtype=np.float64) #Put temporary dictionary for joint centers to return for now, then modify later jc = {} jc['Pelvis_axis'] = kin_Pelvis_axis jc['Thorax_axis'] = kin_Thorax_axis jc['Pelvis'] = kin_Pelvis_JC jc['RHip'] = kin_R_Hip_JC jc['LHip'] = kin_L_Hip_JC jc['RKnee'] = kin_R_Knee_JC jc['LKnee'] = kin_L_Knee_JC jc['RAnkle'] = kin_R_Ankle_JC jc['LAnkle'] = kin_L_Ankle_JC jc['RFoot'] = kin_R_Foot_JC jc['LFoot'] = kin_L_Foot_JC jc['RHEE'] = kin_RHEE jc['LHEE'] = kin_LHEE jc['C7'] = kin_C7 jc['CLAV'] = kin_CLAV jc['STRN'] = kin_STRN jc['T10'] = kin_T10 jc['Front_Head'] = kin_Head_Front jc['Back_Head'] = kin_Head_Back jc['Head'] = kin_Head_JC jc['Thorax'] = kin_Thorax_JC jc['RShoulder'] = kin_R_Shoulder_JC jc['LShoulder'] = kin_L_Shoulder_JC jc['RHumerus'] = kin_R_Humerus_JC jc['LHumerus'] = kin_L_Humerus_JC jc['RRadius'] = kin_R_Radius_JC jc['LRadius'] = kin_L_Radius_JC jc['RHand'] = kin_R_Hand_JC jc['LHand'] = kin_L_Hand_JC return r,jc
5,345,830
def confidence_thresholding_2thresholds_2d( probabilities_per_model: List[np.array], ground_truths: Union[List[np.array], List[pd.Series]], metadata, threshold_output_feature_names: List[str], labels_limit: int, model_names: Union[str, List[str]] = None, output_directory: str = None, file_format: str = 'pdf', **kwargs ) -> None: """Show confidence threshold data vs accuracy for two output feature names. The first plot shows several semi transparent lines. They summarize the 3d surfaces displayed by confidence_thresholding_2thresholds_3d that have thresholds on the confidence of the predictions of the two `threshold_output_feature_names` as x and y axes and either the data coverage percentage or the accuracy as z axis. Each line represents a slice of the data coverage surface projected onto the accuracy surface. # Inputs :param probabilities_per_model: (List[numpy.array]) list of model probabilities. :param ground_truth: (Union[List[np.array], List[pd.Series]]) containing ground truth data :param metadata: (dict) feature metadata dictionary :param threshold_output_feature_names: (List[str]) List containing two output feature names for visualization. :param labels_limit: (int) upper limit on the numeric encoded label value. Encoded numeric label values in dataset that are higher than `label_limit` are considered to be "rare" labels. :param model_names: (Union[str, List[str]], default: `None`) model name or list of the model names to use as labels. :param output_directory: (str, default: `None`) directory where to save plots. If not specified, plots will be displayed in a window :param file_format: (str, default: `'pdf'`) file format of output plots - `'pdf'` or `'png'`. # Return :return: (None) """ try: validate_conf_treshholds_and_probabilities_2d_3d( probabilities_per_model, threshold_output_feature_names ) except RuntimeError: return probs = probabilities_per_model model_names_list = convert_to_list(model_names) filename_template = \ 'confidence_thresholding_2thresholds_2d_{}.' + file_format filename_template_path = generate_filename_template_path( output_directory, filename_template ) if not isinstance(ground_truths[0], np.ndarray): # not np array, assume we need to translate raw value to encoded value feature_metadata = metadata[threshold_output_feature_names[0]] vfunc = np.vectorize(_encode_categorical_feature) gt_1 = vfunc(ground_truths[0], feature_metadata['str2idx']) feature_metadata = metadata[threshold_output_feature_names[1]] gt_2 = vfunc(ground_truths[1], feature_metadata['str2idx']) else: gt_1 = ground_truths[0] gt_2 = ground_truths[1] if labels_limit > 0: gt_1[gt_1 > labels_limit] = labels_limit gt_2[gt_2 > labels_limit] = labels_limit thresholds = [t / 100 for t in range(0, 101, 5)] fixed_step_coverage = thresholds name_t1 = '{} threshold'.format(threshold_output_feature_names[0]) name_t2 = '{} threshold'.format(threshold_output_feature_names[1]) accuracies = [] dataset_kept = [] interps = [] table = [[name_t1, name_t2, 'coverage', ACCURACY]] if labels_limit > 0 and probs[0].shape[1] > labels_limit + 1: prob_limit = probs[0][:, :labels_limit + 1] prob_limit[:, labels_limit] = probs[0][:, labels_limit:].sum(1) probs[0] = prob_limit if labels_limit > 0 and probs[1].shape[1] > labels_limit + 1: prob_limit = probs[1][:, :labels_limit + 1] prob_limit[:, labels_limit] = probs[1][:, labels_limit:].sum(1) probs[1] = prob_limit max_prob_1 = np.max(probs[0], axis=1) predictions_1 = np.argmax(probs[0], axis=1) max_prob_2 = np.max(probs[1], axis=1) predictions_2 = np.argmax(probs[1], axis=1) for threshold_1 in thresholds: threshold_1 = threshold_1 if threshold_1 < 1 else 0.999 curr_accuracies = [] curr_dataset_kept = [] for threshold_2 in thresholds: threshold_2 = threshold_2 if threshold_2 < 1 else 0.999 filtered_indices = np.logical_and( max_prob_1 >= threshold_1, max_prob_2 >= threshold_2 ) filtered_gt_1 = gt_1[filtered_indices] filtered_predictions_1 = predictions_1[filtered_indices] filtered_gt_2 = gt_2[filtered_indices] filtered_predictions_2 = predictions_2[filtered_indices] coverage = len(filtered_gt_1) / len(gt_1) accuracy = ( np.logical_and( filtered_gt_1 == filtered_predictions_1, filtered_gt_2 == filtered_predictions_2 ) ).sum() / len(filtered_gt_1) curr_accuracies.append(accuracy) curr_dataset_kept.append(coverage) table.append([threshold_1, threshold_2, coverage, accuracy]) accuracies.append(curr_accuracies) dataset_kept.append(curr_dataset_kept) interps.append( np.interp( fixed_step_coverage, list(reversed(curr_dataset_kept)), list(reversed(curr_accuracies)), left=1, right=0 ) ) logger.info('CSV table') for row in table: logger.info(','.join([str(e) for e in row])) # ===========# # Multiline # # ===========# filename = None if filename_template_path: os.makedirs(output_directory, exist_ok=True) filename = filename_template_path.format('multiline') visualization_utils.confidence_fitlering_data_vs_acc_multiline_plot( accuracies, dataset_kept, model_names_list, title='Coverage vs Accuracy, two thresholds', filename=filename ) # ==========# # Max line # # ==========# filename = None if filename_template_path: filename = filename_template_path.format('maxline') max_accuracies = np.amax(np.array(interps), 0) visualization_utils.confidence_fitlering_data_vs_acc_plot( [max_accuracies], [thresholds], model_names_list, title='Coverage vs Accuracy, two thresholds', filename=filename ) # ==========================# # Max line with thresholds # # ==========================# acc_matrix = np.array(accuracies) cov_matrix = np.array(dataset_kept) t1_maxes = [1] t2_maxes = [1] for i in range(len(fixed_step_coverage) - 1): lower = fixed_step_coverage[i] upper = fixed_step_coverage[i + 1] indices = np.logical_and(cov_matrix >= lower, cov_matrix < upper) selected_acc = acc_matrix.copy() selected_acc[np.logical_not(indices)] = -1 threshold_indices = np.unravel_index( np.argmax(selected_acc, axis=None), selected_acc.shape) t1_maxes.append(thresholds[threshold_indices[0]]) t2_maxes.append(thresholds[threshold_indices[1]]) model_name = model_names_list[0] if model_names_list is not None and len( model_names_list) > 0 else '' filename = None if filename_template_path: os.makedirs(output_directory, exist_ok=True) filename = filename_template_path.format('maxline_with_thresholds') visualization_utils.confidence_fitlering_data_vs_acc_plot( [max_accuracies, t1_maxes, t2_maxes], [fixed_step_coverage, fixed_step_coverage, fixed_step_coverage], model_names=[model_name + ' accuracy', name_t1, name_t2], dotted=[False, True, True], y_label='', title='Coverage vs Accuracy & Threshold', filename=filename )
5,345,831
def var_to_str(var): """Returns a string representation of the variable of a Jax expression.""" if isinstance(var, jax.core.Literal): return str(var) elif isinstance(var, jax.core.UnitVar): return "*" elif not isinstance(var, jax.core.Var): raise ValueError(f"Idk what to do with this {type(var)}?") c = int(var.count) if c == -1: return "_" str_rep = "" while c > 25: str_rep += chr(c % 26 + ord("a")) c = c // 26 str_rep += chr(c + ord("a")) return str_rep[::-1]
5,345,832
def cut_reset(): """ Select the reference Plane to cut the Object from. """ global myDialog global m_cut_selectObjects del m_cut_selectObjects[:] m_text = "" # deActivate the button_cut_select_line myDialog.ui.button_cut_select_line.setEnabled(False) # deActivate the button_cut_select_plane myDialog.ui.button_cut_select_plane.setEnabled(False) # deActivate the button_cut_apply myDialog.ui.button_cut_apply.setEnabled(False) myDialog.ui.info_cut_select_object.setText(_translate("Form", m_text, None)) myDialog.ui.info_cut_select_axis.setText(_translate("Form", m_text, None)) myDialog.ui.info_cut_select_plane.setText(_translate("Form", m_text, None))
5,345,833
def lal_binary_neutron_star( frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1, phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, lambda_1, lambda_2, **kwargs): """ A Binary Neutron Star waveform model using lalsimulation Parameters ---------- frequency_array: array_like The frequencies at which we want to calculate the strain mass_1: float The mass of the heavier object in solar masses mass_2: float The mass of the lighter object in solar masses luminosity_distance: float The luminosity distance in megaparsec a_1: float Dimensionless primary spin magnitude tilt_1: float Primary tilt angle phi_12: float Azimuthal angle between the two component spins a_2: float Dimensionless secondary spin magnitude tilt_2: float Secondary tilt angle phi_jl: float Azimuthal angle between the total binary angular momentum and the orbital angular momentum theta_jn: float Orbital inclination phase: float The phase at coalescence lambda_1: float Dimensionless tidal deformability of mass_1 lambda_2: float Dimensionless tidal deformability of mass_2 kwargs: dict Optional keyword arguments Supported arguments: waveform_approximant reference_frequency minimum_frequency maximum_frequency catch_waveform_errors pn_spin_order pn_tidal_order pn_phase_order pn_amplitude_order mode_array: Activate a specific mode array and evaluate the model using those modes only. e.g. waveform_arguments = dict(waveform_approximant='IMRPhenomHM', modearray=[[2,2],[2,-2]) returns the 22 and 2-2 modes only of IMRPhenomHM. You can only specify modes that are included in that particular model. e.g. waveform_arguments = dict(waveform_approximant='IMRPhenomHM', modearray=[[2,2],[2,-2],[5,5],[5,-5]]) is not allowed because the 55 modes are not included in this model. Be aware that some models only take positive modes and return the positive and the negative mode together, while others need to call both. e.g. waveform_arguments = dict(waveform_approximant='IMRPhenomHM', modearray=[[2,2],[4,-4]]) returns the 22 a\nd 2-2 of IMRPhenomHM. However, waveform_arguments = dict(waveform_approximant='IMRPhenomXHM', modearray=[[2,2],[4,-4]]) returns the 22 and 4-4 of IMRPhenomXHM. Returns ------- dict: A dictionary with the plus and cross polarisation strain modes """ waveform_kwargs = dict( waveform_approximant='IMRPhenomPv2_NRTidal', reference_frequency=50.0, minimum_frequency=20.0, maximum_frequency=frequency_array[-1], catch_waveform_errors=False, pn_spin_order=-1, pn_tidal_order=-1, pn_phase_order=-1, pn_amplitude_order=0) waveform_kwargs.update(kwargs) return _base_lal_cbc_fd_waveform( frequency_array=frequency_array, mass_1=mass_1, mass_2=mass_2, luminosity_distance=luminosity_distance, theta_jn=theta_jn, phase=phase, a_1=a_1, a_2=a_2, tilt_1=tilt_1, tilt_2=tilt_2, phi_12=phi_12, phi_jl=phi_jl, lambda_1=lambda_1, lambda_2=lambda_2, **waveform_kwargs)
5,345,834
def handledisc(tree): """Binarize discontinuous substitution sites. >>> print(handledisc(Tree('(S (X 0 2 4))'))) (S (X 0 (X|<> 2 (X|<> 4)))) >>> print(handledisc(Tree('(S (X 0 2))'))) (S (X 0 (X|<> 2))) """ for a in tree.postorder(lambda n: len(n) > 1 and isinstance(n[0], int)): binarize(a, rightmostunary=True, threshold=1) return tree
5,345,835
def check_bounds(shape: Shape, point: Coord) -> bool: """Return ``True`` if ``point`` is valid index in ``shape``. Args: shape: Shape of two-dimensional array. point: Two-dimensional coordinate. Return: True if ``point`` is within ``shape`` else ``False``. """ return (0 <= point[0] < shape[0]) and (0 <= point[1] < shape[1])
5,345,836
def logout(home=None): """ Logs out current session and redirects to home :param str home: URL to redirect to after logout success """ flask_login.logout_user() return redirect(request.args.get('redirect', home or url_for('public.home')))
5,345,837
def N(u,i,p,knots): """ u: point for which a spline should be evaluated i: spline knot p: spline order knots: all knots Evaluates the spline basis of order p defined by knots at knot i and point u. """ if p == 0: if knots[int(i)] < u and u <=knots[int(i+1)]: return 1.0 else: return 0.0 else: try: k = ((float((u-knots[int(i)])) / float((knots[int(i+p)] - knots[int(i)]) )) * N(u,i,p-1,knots)) except ZeroDivisionError: k = 0.0 try: q = ((float((knots[int(i+p+1)] - u)) / float((knots[int(i+p+1)] - knots[int(i+1)]))) * N(u,i+1,p-1,knots)) except ZeroDivisionError: q = 0.0 return float(k + q)
5,345,838
def infer_growth_rate(data, od_bounds=None, convert_time=True, groupby=None, cols={'time':'clock_time', 'od':'od_600nm'}, return_opts=True, print_params=True, **kwargs): """ Infers the maximal a posteriori (MAP) parameter set for the steady state growth rate given measurements of optical density. This is performed via optimization by minimization. Parameters ---------- data : pandas DataFrame A tidy long-form pandas DataFrame with columns corresponding to the measurement time and optical density. od_bounds : list of floats The lower and upper bounds of the optical density range to be considered. The default bounds assumed are [0.04, 0.41] inclusive. convert_time : bool If `True`, the provided time column needs to be converted to elapsed time. In this case, the provided time column is assumed to be the clock time of the measurement and is converted to minutes elapsed. groupby : list of str, optional The column names for the groupby operation to operate upon. For example, if there are multiple strains measured in the data set, a groupby of `['strain']` will yield a growth rate estimate for each strain in the data. A groupby of `['strain', 'replicate']` will return a growth rate estimate for each strain and biological replicate. cols : dict, keys 'time', and 'od' The column names of the time and optical density measurements in the DataFrame. return_opts : bool If `True`, the approximated covariance matrix, optimal parameters, and approximate hessian matrix for each grouping is returned as a dictionary. print_params : bool If `True`, the estimated parameters will be printed to the screen when the estimation is finished. Returns ------- data_df : pandas DataFrame A pandas DataFrame with the converted time measurements cropped to the provided optical density bounds. param_df : pandas DataFrame A pandas DataFrame containing the parameters, values, and their 95% credible intervals for each obejct in the provided groupby. opts : dict If `return_opts = True`, the estimated covariance matrix, optimal parameters, and approximate Hessian matrix is returned. Notes ----- This function infers the "maximal a posteriori" parameter set using a Bayesian definition of probability. This function calls the posterior defined by `cremerlab.bayes.steady_state_log_posterior` which contains more information about the construction of the statistical model. """ # TODO: Include type checks if (groupby is not None) & (type(groupby) is not list): groupby = [groupby] # Unpack the time col time_col = cols['time'] od_col = cols['od'] # Determine the OD bounds to consider if od_bounds is not None: data = data[(data[od_col] >= od_bounds[0]) & (data[od_col] <= od_bounds[1])] faux_groupby = False if groupby is None: faux_groupby = True data['__group_idx'] = 1 groupby=['__group_idx'] iterator = data.groupby(groupby) else: iterator = tqdm.tqdm(data.groupby(groupby), desc='Estimating parameters...') # Iterate through each grouping data_dfs = [] param_dfs = [] opts = {'groupby':groupby} iter = 0 # Iterator for opts output = """\n ============================================================ Parameter Estimate Summary ============================================================ \n """ for g, d in iterator: # Convert time if necessary if convert_time: d[time_col] = pd.to_datetime(d[time_col]) d.sort_values(by=time_col, inplace=True) d['elapsed_time_hr'] = d[time_col].values - d[time_col].values[0] d['elapsed_time_hr'] = (d['elapsed_time_hr'].astype('timedelta64[m]') )/60 _time = d['elapsed_time_hr'].values _od = d[od_col].values else: _time = d[time_col].values _od = d[od_col].values # Define the arguments and initial guesses of the parameters # lam_guess = np.mean(np.diff(np.log(_od)) / np.diff(_time)) params = [1, _od.min(), 0.1] args = (_time, _od) # Compute the MAP res = scipy.optimize.minimize(steady_state_growth_rate_log_posterior, params, args=args, method="powell") # Get the optimal parameters popt = res.x # Compute the Hessian and covariance matrix hes = smnd.approx_hess(popt, steady_state_growth_rate_log_posterior, args=args) cov = np.linalg.inv(hes) # Extract the MAP parameters and CI lam_MAP, od_init_MAP, sigma_MAP = popt lam_CI = 1.96 * np.sqrt(cov[0, 0]) od_init_CI = 1.96 * np.sqrt(cov[1, 1]) sigma_CI = 1.96 * np.sqrt(cov[2, 2]) if print_params: if faux_groupby == False: header = f"""Parameter Estimates for grouping {groupby}: {g} ------------------------------------------------------------ """ else: header = """Parameter Estimates ------------------------------------------------------------ """ output += header + f"""growth rate, λ = {lam_MAP:0.2f} ± {lam_CI:0.3f} [per unit time] initial OD, OD_0 = {od_init_MAP:0.2f} ± {lam_CI:0.3f} [a.u.] homoscedastic error, σ = {sigma_MAP:0.2f} ± {sigma_CI:0.3f} [a.u.] \n """ # Assemble the data dataframe _data_df = pd.DataFrame([]) if convert_time: _data_df['elapsed_time_hr'] = _time else: _data_df[time_col] = _time _data_df[od_col] = _od # Include other columns that were not carried through colnames = [k for k in d.keys() if k not in [time_col, od_col]] for c in colnames: _data_df[c] = d[c].values if '__group_idx' in _data_df.keys(): _data_df.drop(columns=['__group_idx'], inplace=True) _data_df.rename(columns={'od':od_col}) # Assemble the parameter dataframe _param_df = pd.DataFrame([]) for title, MAP, CI in zip(['growth_rate', 'od_init', 'sigma'], [lam_MAP, od_init_MAP, sigma_MAP], [lam_CI, od_init_CI, sigma_CI]): _param_df = _param_df.append({'parameter':title, 'map_val': MAP, 'cred_int': CI}, ignore_index=True) # Add grouping identifier if provided if groupby is not None: # if type(g) is not list: # _g = [g] _g = g for title, value in zip(groupby, _g): _data_df[title] = value _param_df[title] = value # Append the dataframes to the storage lists param_dfs.append(_param_df) data_dfs.append(_data_df) opts[iter] = {'groupby': g, 'cov':cov, 'popt':popt, 'hessian':hes} iter += 1 # Concatenate the dataframes for return if len(data_dfs) == 1: data_df = data_dfs[0] param_df = param_dfs[0] else: data_df = pd.concat(data_dfs, sort=False) param_df = pd.concat(param_dfs, sort=False) if print_params: print(output) if return_opts: return_obj = [data_df, param_df, opts] else: return_obj = [data_df, param_df] return return_obj
5,345,839
def check_merge(s, idn) -> bool: """ Check whether a set of nodes is valid to merge """ found = False in_size = None out_size = None stride = None act = None nds = [idn[i] for i in state2iset(s)] if len(nds) == 1: return True for nd in nds: if not isinstance(nd, Conv): # current only merge conv return False if not found: in_size = nd.input_shape[1], nd.input_shape[2] out_size = nd.output_shape[1], nd.output_shape[2] stride = nd.stride[0], nd.stride[1] act = nd.act found = True else: # all input resolution, output resolution and stride must be the same if in_size[0] != nd.input_shape[1] or in_size[1] != nd.input_shape[2]: return False if out_size[0] != nd.output_shape[1] or out_size[1] != nd.output_shape[2]: return False if stride[0] != nd.stride[0] or stride[1] != nd.stride[1]: return False if nd.groups != 1 or act != nd.act: return False if len(nd.inputs) > 1 or len(nd.inputs[0]) > 1 or not (nd.inputs[0][0] == nds[0].inputs[0][0]): return False return True
5,345,840
def _run_server(file_store_path, artifact_root, host, port, workers): """Run the MLflow server, wrapping it in gunicorn""" env_map = {} if file_store_path: env_map[FILE_STORE_ENV_VAR] = file_store_path if artifact_root: env_map[ARTIFACT_ROOT_ENV_VAR] = artifact_root bind_address = "%s:%s" % (host, port) exec_cmd(["gunicorn", "-b", bind_address, "-w", "%s" % workers, "mlflow.server:app"], env=env_map, stream_output=True)
5,345,841
def typeMap(name, package=None): """ typeMap(name: str) -> Module Convert from C/C++ types into VisTrails Module type """ if package is None: package = identifier if isinstance(name, tuple): return [typeMap(x, package) for x in name] if name in typeMapDict: return typeMapDict[name] else: registry = get_module_registry() if not registry.has_descriptor_with_name(package, name): return None else: return registry.get_descriptor_by_name(package, name).module
5,345,842
def _rm_from_diclist(diclist, key_to_check, value_to_check): """Function that removes an entry form a list of dictionaries if a key of an entry matches a given value. If no value of the key_to_check matches the value_to_check for all of the entries in the diclist, the same diclist will be returned that was passed to the function. Parameters: diclist - A list of dictionaries. key_to_check - A key of a dictionary whose value should be checked to determine if a dictionary should be removed from the diclist. value_to_check - The value that should be compared to the value of the key_to_check to determine if a dictionary should be removed from the diclist. Returns the diclist passed to the function with an entry removed if its value of the key_to_check matched the value_to_check. """ for i in xrange(len(diclist)): if diclist[i][key_to_check] == value_to_check: diclist.pop(i) break return diclist
5,345,843
def fix_colocation_after_import(input_map, absolute_import_scope): """Fixes colocation attributes after import according to input_map. This function is meant to be called after importing a GraphDef, in order to rewrite colocate_with constrains analogous to how inputs to ops are rewritten by input_map during import. It also updates devices accordingly. The nodes in the given import scope of the current default graph have their colocation attributes (that is, the "loc:@..." values in the "_class" attr) rewritten as follows: If, before the call, op x has attribute loc:@y, and `input_map` replaces an output of y with an output of z, then loc:@y gets replaced by the colocation attributes of z (that is, loc:@z, if no other constraints are in play). This style of rewriting requires that the other nodes in the graph express their colocation with state and input nodes solely in terms of the state and input nodes themselves, which is what the `input_map` provides. The reverse direction (e.g., a state node referencing a non-state node in a colocation attribute) is prevented by `find_state_op_colocation_error()` and `find_signature_input_colocation_error()`. Args: input_map: a dict mapping from tensor names in the imported graph to existing Tensors, typically the same as passed to tf.import_graph_def(). absolute_import_scope: a string with the full name of the import scope, comprising the current scope when import_graph_def() as called plus the import_scope passed to it. Raises: ValueError: if one imported op has its multiple outputs replaced by different existing ops. (This is unexpected, since placeholders and the current state ops all have only one output.) """ attr_map = _build_colocation_attr_map(input_map, absolute_import_scope) _apply_colocation_attr_map(attr_map, absolute_import_scope)
5,345,844
def odr_linear(x, y, intercept=None, beta0=None): """ Performs orthogonal linear regression on x, y data. Parameters ---------- x: array_like x-data, 1D array. Must be the same lengths as `y`. y: array_like y-data, 1D array. Must be the same lengths as `x`. intercept: float, default None If not None, fixes the intercept. beta0: array_like, shape (2,) Guess at the slope and intercept, respectively. Returns ------- output: ndarray, shape (2,) Array containing slope and intercept of ODR line. """ def linear_fun(p, x): return p[0] * x + p[1] def linear_fun_fixed(p, x): return p[0] * x + intercept # Set the model to be used for the ODR fitting if intercept is None: model = scipy.odr.Model(linear_fun) if beta0 is None: beta0 = (0.0, 1.0) else: model = scipy.odr.Model(linear_fun_fixed) if beta0 is None: beta0 = (1.0,) # Make a Data instance data = scipy.odr.Data(x, y) # Instantiate ODR odr = scipy.odr.ODR(data, model, beta0=beta0) # Perform ODR fit try: result = odr.run() except scipy.odr.odr_error: raise scipy.odr.odr_error('ORD failed.') return result.beta
5,345,845
def get_centroid_world_coordinates(geo_trans, raster_x_size, raster_y_size, x_pixel_size, y_pixel_size): """Return the raster centroid in world coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param raster_x_size: number of columns :type raster_x_size: int :param raster_y_size: number of rows :param x_pixel_size: pixel size in x direction :type: x_pixel_size: float :param y_pixel_size: pixel size in y direction :type y_pixel_size: float :return: """ x0, y0 = pixel_to_world(geo_trans, 0, 0) x1, y1 = pixel_to_world(geo_trans, raster_x_size-1, raster_y_size-1) x1 += x_pixel_size y1 -= y_pixel_size return (x0 + x1) * 0.5, (y0 + y1) * 0.5
5,345,846
def save_change_item(request): """ 保存改变项 算法:在rquest_list中查找对应的uuid,找到后将数据更新其中 :param request: :return: """ if request.method != 'POST': return HttpResponse("数据异常.") str_data = request.POST.get('jsons') logger.info("change_item: " + str_data) jsons = json.loads(str_data) id = jsons['id'] name = jsons['name'] url = jsons['url'] raw_mode_data = jsons['rawModeData'] method = jsons['method'] logger.info("打印send: {}".format(url)) request_list = JsonConf.json_data['requests'] for item in request_list: if id == item["id"]: item["method"] = method item["rawModeData"] = raw_mode_data item["name"] = name item["url"] = url break JsonConf.store(settings.INIT_DATA) return HttpResponse("保存成功.")
5,345,847
def test_starg_mroute_p0(request): """ 1. Verify (*,G) mroute detail on FRR router after BSM rp installed Topology used: b1_____ | | s1-----f1-----i1-----l1----r1 | ______| b2 b1 - BSR 1 b2 - BSR 2 s1 - Source f1 - FHR i1 - Intermediate Router (also RP) r1 - Receiver """ tgen = get_topogen() tc_name = request.node.name write_test_header(tc_name) # Don"t run this test if we have any failure. if tgen.routers_have_failure(): pytest.skip(tgen.errors) app_helper.stop_all_hosts() clear_ip_mroute(tgen) reset_config_on_routers(tgen) clear_ip_pim_interface_traffic(tgen, topo) reset_config_on_routers(tgen) result = pre_config_to_bsm( tgen, topo, tc_name, "b1", "s1", "r1", "f1", "i1", "l1", "packet1" ) assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) result = pre_config_to_bsm( tgen, topo, tc_name, "b2", "s1", "r1", "f1", "i1", "l1", "packet1" ) assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) GROUP_ADDRESS = "226.1.1.1" # Use scapy to send pre-defined packet from senser to receiver result = scapy_send_bsr_raw_packet(tgen, topo, "b1", "f1", "packet1") assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) bsr_ip = topo["routers"]["b1"]["bsm"]["bsr_packets"]["packet1"]["bsr"].split("/")[0] time.sleep(1) result = app_helper.run_join("r1", GROUP_ADDRESS, "l1") assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify bsr state in FHR result = verify_pim_bsr(tgen, topo, "f1", bsr_ip) assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) # Check igmp groups step("Verify IGMP groups in LHR l1") dut = "l1" intf = "l1-r1-eth1" result = verify_igmp_groups(tgen, dut, intf, GROUP_ADDRESS) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) group = "226.1.1.1/32" src_addr = "*" # Find the elected rp from bsrp-info step("Find the elected rp from bsrp-info in LHR in l1") rp = find_rp_from_bsrp_info(tgen, dut, bsr_ip, group) assert rp is not {}, "Testcase {} :Failed \n Error {}".format(tc_name, result) # Check RP detail in LHR step("Verify RP in LHR in l1") result = verify_pim_grp_rp_source(tgen, topo, dut, group, "BSR", rp[group]) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify join state and join timer step("Verify join state and join timer in l1") iif = "l1-i1-eth0" result = verify_join_state_and_timer(tgen, dut, iif, src_addr, GROUP_ADDRESS) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify upstream IIF interface step("Verify upstream IIF interface in l1") result = verify_upstream_iif(tgen, dut, iif, src_addr, GROUP_ADDRESS) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify IIF/OIL in pim state oil = "l1-r1-eth1" result = verify_pim_state(tgen, dut, iif, oil, GROUP_ADDRESS) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify ip mroute step("Verify ip mroute in l1") src_addr = "*" result = verify_ip_mroutes(tgen, dut, src_addr, GROUP_ADDRESS, iif, oil) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Remove the group rp mapping and send bsm step("Remove the grp-rp mapping by sending bsm with hold time 0 for grp-rp") result = scapy_send_bsr_raw_packet(tgen, topo, "b1", "f1", "packet2") assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) # Check RP unreachable step("Check RP unreachability in l1") iif = "Unknown" result = verify_upstream_iif( tgen, dut, iif, src_addr, GROUP_ADDRESS, joinState="NotJoined" ) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify that it is not installed step("Verify that iif is not installed in l1") iif = "<iif?>" result = verify_pim_state(tgen, dut, iif, oil, GROUP_ADDRESS, installed_fl=0) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) # Verify mroute not installed step("Verify mroute not installed in l1") result = verify_ip_mroutes( tgen, dut, src_addr, GROUP_ADDRESS, iif, oil, retry_timeout=20, expected=False ) assert ( result is not True ), "Testcase {} : Failed \n " "mroute installed in l1 \n Error: {}".format( tc_name, result ) # Send BSM again to configure rp step("Add back RP by sending BSM from b1") result = scapy_send_bsr_raw_packet(tgen, topo, "b1", "f1", "packet1") assert result is True, "Testcase {} :Failed \n Error {}".format(tc_name, result) # Verify that (*,G) installed in mroute again iif = "l1-i1-eth0" result = verify_ip_mroutes(tgen, dut, src_addr, GROUP_ADDRESS, iif, oil) assert result is True, "Testcase {}:Failed \n Error: {}".format(tc_name, result) step("clear BSM database before moving to next case") clear_bsrp_data(tgen, topo) write_test_footer(tc_name)
5,345,848
def test_authorization_received(): """Assert that authorization received validation works as expected.""" statement = copy.deepcopy(FINANCING_STATEMENT) del statement['authorizationReceived'] is_valid, errors = validate(statement, 'financingStatement', 'ppr') assert is_valid statement['authorizationReceived'] = False is_valid, errors = validate(statement, 'financingStatement', 'ppr') assert is_valid statement['authorizationReceived'] = True is_valid, errors = validate(statement, 'financingStatement', 'ppr') assert is_valid statement['authorizationReceived'] = 'junk' is_valid, errors = validate(statement, 'financingStatement', 'ppr') if errors: for err in errors: print(err.message) assert not is_valid
5,345,849
def update_tests_if_needed(): """Updates layout tests every day.""" data_directory = environment.get_value('FUZZ_DATA') error_occured = False expected_task_duration = 60 * 60 # 1 hour. retry_limit = environment.get_value('FAIL_RETRIES') temp_archive = os.path.join(data_directory, 'temp.zip') tests_url = environment.get_value('WEB_TESTS_URL') # Check if we have a valid tests url. if not tests_url: return # Layout test updates are usually disabled to speedup local testing. if environment.get_value('LOCAL_DEVELOPMENT'): return # |UPDATE_WEB_TESTS| env variable can be used to control our update behavior. if not environment.get_value('UPDATE_WEB_TESTS'): return last_modified_time = persistent_cache.get_value( TESTS_LAST_UPDATE_KEY, constructor=datetime.datetime.utcfromtimestamp) if (last_modified_time is not None and not dates.time_has_expired( last_modified_time, days=TESTS_UPDATE_INTERVAL_DAYS)): return logs.log('Updating layout tests.') tasks.track_task_start( tasks.Task('update_tests', '', ''), expected_task_duration) # Download and unpack the tests archive. for _ in range(retry_limit): try: shell.remove_directory(data_directory, recreate=True) storage.copy_file_from(tests_url, temp_archive) archive.unpack(temp_archive, data_directory, trusted=True) shell.remove_file(temp_archive) error_occured = False break except: logs.log_error( 'Could not retrieve and unpack layout tests archive. Retrying.') error_occured = True if not error_occured: persistent_cache.set_value( TESTS_LAST_UPDATE_KEY, time.time(), persist_across_reboots=True) tasks.track_task_end()
5,345,850
def save_fig(plot, name): """Save figure. :param plot: Matplotlib's pyplot. :type plot: matplotlib.pyplot :param name: File name. :type name: str """ path = figures_dir / f'{name}.png' plot.savefig(path) log.info(f'Figure saved: {path}') path = figures_dir / f'{name}.svg' plot.savefig(path) log.info(f'Figure saved: {path}')
5,345,851
def get_lastest_stocklist(): """ 使用pytdx从网络获取最新券商列表 :return:DF格式,股票清单 """ import pytdx.hq import pytdx.util.best_ip print(f"优选通达信行情服务器 也可直接更改为优选好的 {{'ip': '123.125.108.24', 'port': 7709}}") # ipinfo = pytdx.util.best_ip.select_best_ip() api = pytdx.hq.TdxHq_API() # with api.connect(ipinfo['ip'], ipinfo['port']): with api.connect('123.125.108.24', 7709): data = pd.concat([pd.concat( [api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh') for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j in range(2)], axis=0) data = data.reindex(columns=['sse', 'code', 'name', 'pre_close', 'volunit', 'decimal_point']) data.sort_values(by=['sse', 'code'], ascending=True, inplace=True) data.reset_index(drop=True, inplace=True) # 这个方法不行 字符串不能运算大于小于,转成int更麻烦 # df = data.loc[((data['sse'] == 'sh') & ((data['code'] >= '600000') | (data['code'] < '700000'))) | \ # ((data['sse'] == 'sz') & ((data['code'] >= '000001') | (data['code'] < '100000'))) | \ # ((data['sse'] == 'sz') & ((data['code'] >= '300000') | (data['code'] < '309999')))] sh_start_num = data[(data['sse'] == 'sh') & (data['code'] == '600000')].index.tolist()[0] sh_end_num = data[(data['sse'] == 'sh') & (data['code'] == '706070')].index.tolist()[0] sz00_start_num = data[(data['sse'] == 'sz') & (data['code'] == '000001')].index.tolist()[0] sz00_end_num = data[(data['sse'] == 'sz') & (data['code'] == '100303')].index.tolist()[0] sz30_start_num = data[(data['sse'] == 'sz') & (data['code'] == '300001')].index.tolist()[0] sz30_end_num = data[(data['sse'] == 'sz') & (data['code'] == '395001')].index.tolist()[0] df_sh = data.iloc[sh_start_num:sh_end_num] df_sz00 = data.iloc[sz00_start_num:sz00_end_num] df_sz30 = data.iloc[sz30_start_num:sz30_end_num] df = pd.concat([df_sh, df_sz00, df_sz30]) df.reset_index(drop=True, inplace=True) return df
5,345,852
def grpc_detect_ledger_id(connection: "GRPCv1Connection") -> str: """ Return the ledger ID from the remote server when it becomes available. This method blocks until a ledger ID has been successfully retrieved, or the timeout is reached (in which case an exception is thrown). """ LOG.debug("Starting a monitor thread for connection: %s", connection) start_time = datetime.utcnow() connect_timeout = connection.options.connect_timeout while connect_timeout is None or (datetime.utcnow() - start_time) < connect_timeout: if connection.invoker.level >= RunLevel.TERMINATE_GRACEFULLY: raise UserTerminateRequest() if connection.closed: raise Exception("connection closed") try: response = connection.ledger_identity_service.GetLedgerIdentity( lapipb.GetLedgerIdentityRequest() ) except RpcError as ex: details_str = ex.details() # suppress some warning strings because they're not particularly useful and just clutter # up the logs if details_str not in GRPC_KNOWN_RETRYABLE_ERRORS: LOG.exception( "An unexpected error occurred when trying to fetch the " "ledger identity; this will be retried." ) sleep(1) continue return response.ledger_id raise ConnectionTimeoutError( f"connection timeout exceeded: {connect_timeout.total_seconds()} seconds" )
5,345,853
def cross_mcs(input_vectors, value_fields, verbose=False, logger=None): """ Compute map comparison statistics between input vector features. MCS (Map Comparison Statistic) indicates the average difference between any pair of feature polygon values, expressed as a fraction of the highest value. MCS is calculated between each polygon in the input vector features and it is required (and checked) that all the inputs are based on the same vector feature. For another application of MCS, see: Schulp, C. J. E., Burkhard, B., Maes, J., Van Vliet, J., & Verburg, P. H. (2014). Uncertainties in Ecosystem Service Maps: A Comparison on the European Scale. PLoS ONE, 9(10), e109643. http://doi.org/10.1371/journal.pone.0109643 :param input_vectors list of input vector paths. :param value_field list of String names indicating which fields contains the values to be compared. :param verbose: Boolean indicating how much information is printed out. :param logger: logger object to be used. :return list of GeoPandas Dataframe with MCS between all rasters in field "mcs". """ # 1. Setup -------------------------------------------------------------- all_start = timer() if not logger: logging.basicConfig() llogger = logging.getLogger('cross_mcs') llogger.setLevel(logging.DEBUG if verbose else logging.INFO) else: llogger = logger # Check the inputs assert len(input_vectors) > 1, "More than one input vector needed" assert len(value_fields) == len(input_vectors), "One value field per vector feature needed" # 2. Calculations -------------------------------------------------------- llogger.info(" [** COMPUTING MCS SCORES **]") all_mcs = pd.DataFrame({"feature1": [], "feature2": [], "mcs": []}) n_vectors = len(input_vectors) # Generate counter information for all the computations. The results # matrix is always diagonally symmetrical. n_computations = int((n_vectors * n_vectors - n_vectors) / 2) no_computation = 1 for i in range(0, n_vectors): # Read in the data as a GeoPandas dataframe vector1_path = input_vectors[i] vector1 = gpd.read_file(vector1_path) for j in range(i+1, n_vectors): vector2_path = input_vectors[j] vector2 = gpd.read_file(vector2_path) prefix = utils.get_iteration_prefix(no_computation, n_computations) llogger.info(("{} Calculating MCS ".format(prefix) + "between {} ".format(vector1_path) + "and {}".format(vector2_path))) mcs_value = compute_mcs(vector1[value_fields[i]], vector2[value_fields[j]]) mcs = pd.DataFrame({"feature1": [vector1_path], "feature2": [vector2_path], "mcs": [mcs_value]}) all_mcs = pd.concat([all_mcs, mcs]) no_computation += 1 all_mcs.index = np.arange(0, len(all_mcs.index), 1) all_end = timer() all_elapsed = round(all_end - all_start, 2) llogger.info(" [TIME] All processing took {} sec".format(all_elapsed)) return all_mcs
5,345,854
def extrapolate_trace(traces_in, spec_min_max_in, fit_frac=0.2, npoly=1, method='poly'): """ Extrapolates trace to fill in pixels that lie outside of the range spec_min, spec_max). This routine is useful for echelle spectrographs where the orders are shorter than the image by a signfiicant amount, since the polynomial trace fits often go wild. Args: traces (np.ndarray): shape = (nspec,) or (nspec, ntrace) Array containing object or slit boundary traces spec_min_max (np.ndarray): shape = (2, ntrace) Array contaning the minimum and maximum spectral region covered by each trace. If this is an array with ndim=1 array, the same numbers will be used for all traces in traces_in. If a 2d array, then this must be an ndarray of shape (2, ntrace,) where the spec_min_max[0,:] are the minimua and spec_min_max[1,:] are the maxima. fit_frac (float): fraction of the good pixels to be used to fit when extrapolating traces. The upper fit_frac pixels are used to extrapolate to larger spectral position, and vice versa for lower spectral positions. npoly (int): Order of polynomial fit used for extrapolation method (str): Method used for extrapolation. Options are 'poly' or 'edge'. If 'poly' the code does a polynomial fit. If 'edge' it just attaches the last good pixel everywhere. 'edge' is not currently used. Returns: trace_extrap (np.ndarray): Array with same size as trace containing the linearly extrapolated values for the bad spectral pixels. """ #embed() # This little bit of code allows the input traces to either be (nspec, nslit) arrays or a single # vectors of size (nspec) spec_min_max_tmp = np.array(spec_min_max_in) if traces_in.ndim == 2: traces = traces_in nslits = traces.shape[1] if np.array(spec_min_max_in).ndim == 1: spec_min_max = np.outer(spec_min_max_tmp, np.ones(nslits)) elif spec_min_max_tmp.ndim == 2: if (spec_min_max_tmp.shape[1] != nslits): msgs.error('If input as any arrays, spec_min_max needs to have dimensions (2,nslits)') spec_min_max = spec_min_max_tmp else: msgs.error('Invalid shapes for traces_min and traces_max') else: nslits = 1 traces = traces_in.reshape(traces_in.size, 1) spec_min_max = spec_min_max_tmp nspec = traces.shape[0] spec_vec = np.arange(nspec,dtype=float) xnspecmin1 = spec_vec[-1] traces_extrap = traces.copy() # TODO should we be doing a more careful extrapolation here rather than just linearly using the nearest pixel # values?? for islit in range(nslits): ibad_max = spec_vec > spec_min_max[1,islit] ibad_min = spec_vec < spec_min_max[0,islit] igood = (spec_vec >= spec_min_max[0,islit]) & (spec_vec <= spec_min_max[1,islit]) nfit = int(np.round(fit_frac*np.sum(igood))) good_ind = np.where(igood)[0] igood_min = good_ind[0:nfit] igood_max = good_ind[-nfit:] if np.any(ibad_min): if 'poly' in method: coeff_min = utils.func_fit(spec_vec[igood_min], traces[igood_min, islit], 'legendre', npoly, minx=0.0, maxx=xnspecmin1) traces_extrap[ibad_min, islit] = utils.func_val(coeff_min, spec_vec[ibad_min], 'legendre', minx=0.0, maxx=xnspecmin1) elif 'edge' in method: traces_extrap[ibad_min, islit] = traces[good_ind[0], islit] if np.any(ibad_max): if 'poly' in method: coeff_max = utils.func_fit(spec_vec[igood_max], traces[igood_max, islit], 'legendre', npoly, minx=0.0,maxx=xnspecmin1) traces_extrap[ibad_max, islit] = utils.func_val(coeff_max, spec_vec[ibad_max], 'legendre', minx=0.0,maxx=xnspecmin1) elif 'edge' in method: traces_extrap[ibad_max, islit] = traces[good_ind[-1], islit] #ibad = np.invert(igood) #traces_extrap[ibad, islit] = interpolate.interp1d(spec_vec[igood], traces[igood, islit], kind='linear', #bounds_error=False, fill_value='extrapolate')(spec_vec[ibad]) return traces_extrap
5,345,855
def getStopWords(stopWordFileName): """Reads stop-words text file which is assumed to have one word per line. Returns stopWordDict. """ stopWordDict = {} stopWordFile = open(stopWordFileName, 'r') for line in stopWordFile: word = line.strip().lower() stopWordDict[word] = None return stopWordDict
5,345,856
def metade(valor): """ -> Realiza o calculo de metade salárial :param valor: Valor do dinheiro :param view: Visualizar ou não retorno formatado :return: Retorna a metade do valor """ if not view: return moeda(valor / 2) else: return valor / 2 return valor / 2
5,345,857
def monopole(uvecs: [float, np.ndarray], order: int=3) -> [float, np.ndarray]: """ Solution for I(r) = 1. Also handles nonzero-w case. Parameters ---------- uvecs: float or ndarray of float The cartesian baselines in units of wavelengths. If a float, assumed to be the magnitude of the baseline. If an array of one dimension, each entry is assumed to be a magnitude. If a 2D array, may have shape (Nbls, 2) or (Nbls, 3). In the first case, w is assumed to be zero. order: int Expansion order to use for non-flat array case (w != 0). Returns ------- ndarray of complex Visibilities, shape (Nbls,) """ if np.isscalar(uvecs) or uvecs.ndim == 1 or uvecs.shape[1] == 2 or np.allclose(uvecs[:, 2], 0): # w is zero. uamps = vec_to_amp(uvecs) return 2 * np.pi * np.sinc(2 * uamps) uvecs = uvecs[..., None] ks = np.arange(order)[None, :] fac0 = (2 * np.pi * 1j * uvecs[:, 2, :])**ks / (gamma(ks + 2)) fac1 = hyp0f1((3 + ks) / 2, -np.pi**2 * (uvecs[:, 0, :]**2 + uvecs[:, 1, :]**2)) return 2 * np.pi * np.sum(fac0 * fac1, axis=-1)
5,345,858
def get_question( numbers: OneOrManyOf(NUMBERS_AVAILABLE), cases: OneOrManyOf(CASES_AVAILABLE), num: hug.types.in_range(1, MAX_NUM + 1) = 10): """When queried for one or multiple numbers and cases, this endpoint returns a random question.""" questions = [] bag = NounCaseQuestionBag( noun_bag, adjective_bag, numbers, cases) while len(questions) < num: question = bag.get_question() questions.append( { 'question_elements': question.get_question_elements(), 'answer_elements': question.get_correct_answer_elements() }) return questions
5,345,859
def delete(ctx, **_): """Deletes a Resource Group""" if ctx.node.properties.get('use_external_resource', False): return azure_config = ctx.node.properties.get('azure_config') if not azure_config.get("subscription_id"): azure_config = ctx.node.properties.get('client_config') else: ctx.logger.warn("azure_config is deprecated please use client_config, " "in later version it will be removed") name = utils.get_resource_name(ctx) api_version = \ ctx.node.properties.get('api_version', constants.API_VER_RESOURCES) resource_group = ResourceGroup(azure_config, ctx.logger, api_version) try: resource_group.get(name) except CloudError: ctx.logger.info("Resource with name {0} doesn't exist".format(name)) return try: resource_group.delete(name) utils.runtime_properties_cleanup(ctx) except CloudError as cr: raise cfy_exc.NonRecoverableError( "delete resource_group '{0}' " "failed with this error : {1}".format(name, cr.message) )
5,345,860
def test_dpp_proto_auth_resp_invalid_r_proto_key(dev, apdev): """DPP protocol testing - invalid R-Proto Key in Auth Resp""" run_dpp_proto_auth_resp_missing(dev, 67, "Invalid Responder Protocol Key")
5,345,861
def _print_attrs(attr, html=False): """ Given a Attr class will print out each registered attribute. Parameters ---------- attr : `sunpy.net.attr.Attr` The attr class/type to print for. html : bool Will return a html table instead. Returns ------- `str` String with the registered attributes. """ attrs = attr._attr_registry[attr] # Only sort the attrs if any have been registered sorted_attrs = _ATTR_TUPLE(*zip(*sorted(zip(*attrs)))) if attrs.name else make_tuple() *other_row_data, descs = sorted_attrs descs = [(dsc[:77] + '...') if len(dsc) > 80 else dsc for dsc in descs] table = Table(names=["Attribute Name", "Client", "Full Name", "Description"], dtype=["U80", "U80", "U80", "U80"], data=[*other_row_data, descs]) class_name = f"{(attr.__module__ + '.') or ''}{attr.__name__}" lines = [class_name] # If the attr lacks a __doc__ this will error and prevent this from returning anything. try: lines.append(dedent(attr.__doc__.partition("\n\n")[0]) + "\n") except AttributeError: pass format_line = "<p>{}</p>" if html else "{}" width = -1 if html else get_width() lines = [*[format_line.format(line) for line in lines], *table.pformat_all(show_dtype=False, max_width=width, align="<", html=html)] return '\n'.join(lines)
5,345,862
def create_wave_header(samplerate=44100, channels=2, bitspersample=16, duration=3600): """Generate a wave header from given params.""" # pylint: disable=no-member file = BytesIO() numsamples = samplerate * duration # Generate format chunk format_chunk_spec = b"<4sLHHLLHH" format_chunk = struct.pack( format_chunk_spec, b"fmt ", # Chunk id 16, # Size of this chunk (excluding chunk id and this field) 1, # Audio format, 1 for PCM channels, # Number of channels int(samplerate), # Samplerate, 44100, 48000, etc. int(samplerate * channels * (bitspersample / 8)), # Byterate int(channels * (bitspersample / 8)), # Blockalign bitspersample, # 16 bits for two byte samples, etc. ) # Generate data chunk data_chunk_spec = b"<4sL" datasize = int(numsamples * channels * (bitspersample / 8)) data_chunk = struct.pack( data_chunk_spec, b"data", # Chunk id int(datasize), # Chunk size (excluding chunk id and this field) ) sum_items = [ # "WAVE" string following size field 4, # "fmt " + chunk size field + chunk size struct.calcsize(format_chunk_spec), # Size of data chunk spec + data size struct.calcsize(data_chunk_spec) + datasize, ] # Generate main header all_chunks_size = int(sum(sum_items)) main_header_spec = b"<4sL4s" main_header = struct.pack(main_header_spec, b"RIFF", all_chunks_size, b"WAVE") # Write all the contents in file.write(main_header) file.write(format_chunk) file.write(data_chunk) # return file.getvalue(), all_chunks_size + 8 return file.getvalue()
5,345,863
def xslugify(value): """ Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't alphanumerics, underscores, slash, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace. (I.e., does the same as slugify, but also converts slashes to dashes.) """ value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub(r'[^\w\s/-]', '', value).strip().lower() return mark_safe(re.sub(r'[-\s/]+', '-', value))
5,345,864
def firstcond(list1, list2): """this is a fixture for testing conditions when the list is a four node list """ ll = LinkedList() ll.insert(1, 5) ll.insert(3, 9) ll.insert(2, 4) return ll
5,345,865
def read_bert_vocab(bert_model_path): """读取bert词典""" dict_path = os.path.join(bert_model_path, 'vocab.txt') token2idx = {} with open(dict_path, 'r', encoding='utf-8') as f: tokens = f.read().splitlines() for word in tokens: token2idx[word] = len(token2idx) return token2idx
5,345,866
def test_get_index(list): """ Vectors should be subscript-able in a way that mimics lists """ inf_vec = V(list) fin_vec = V[len(list)](list) for idx, val in enumerate(list): assert inf_vec[idx] == fin_vec[idx] == val
5,345,867
def _template_message(desc, descriptor_registry): # type: (Descriptor, DescriptorRegistry) -> str """ Returns cls_def string, list of fields, list of repeated fields """ this_file = desc.file desc = SimpleDescriptor(desc) if desc.full_name in WKTBASES: desc.bases.append(WKTBASES[desc.full_name]) descriptor_registry[desc.identifier] = desc slots = desc.field_names # TODO: refactor field partitioning and iskeyword checks # NOTE: the "pass" statement is a hack to provide a body when args is empty initialisers = ['pass'] initialisers += [ 'self.{} = self.{}() # inner_nonrepeated_fields'.format(field_name, field_type) for field_name, field_type in desc.inner_nonrepeated_fields if not iskeyword(field_name) ] repeated_scalar_fields = [fd.name for fd in desc.fields if is_repeated(fd) and not is_composite(fd)] initialisers += [ 'self.{} = [] # repeated_fields'.format(field_name) for field_name in repeated_scalar_fields if not iskeyword(field_name) ] rcfields = { fd for fd in desc.fields if is_repeated(fd) and is_composite(fd) and not is_map_field(fd) } repeated_composite_fields = [ (fd.name, fd.message_type.name, desc.is_nested(fd)) for fd in rcfields ] initialisers += [ _template_composite_field(desc.name, field_name, field_type, is_nested) for field_name, field_type, is_nested in repeated_composite_fields if not iskeyword(field_name) ] # TODO: refactor this external_fields = [ (f, f.message_type) for f in desc.message_fields if not desc.is_nested(f) if f not in rcfields # don't want to double up above ] siblings = [ (f, f.name, full_name(msg_type)) for f, msg_type in external_fields if msg_type.file is this_file ] initialisers += [ 'self.{} = {}() # external_fields (siblings)'.format(field_name, field_type) for _, field_name, field_type in siblings if not iskeyword(field_name) ] externals = [ (f, f.name, _to_module_name(msg_type.file.name), full_name(msg_type)) # TODO: look up name instead of heuristic? for f, msg_type in external_fields if msg_type.file is not this_file ] initialisers += [ 'self.{} = {}.{}() # external_fields (imports)'.format(field_name, qualifier, field_type) for _, field_name, qualifier, field_type in externals if not iskeyword(field_name) ] # Extensions should show up as attributes on message instances but not # as keyword arguments in message constructors initialisers += [ 'self.{} = object() # extensions'.format(ext_name) for ext_name in desc.extensions_by_name if not iskeyword(ext_name) ] args = ['self'] + ['{}=None'.format(f) for f in slots if not iskeyword(f)] init_str = 'def __init__({argspec}):\n{initialisers}\n'.format( argspec=', '.join(args), initialisers=textwrap.indent('\n'.join(initialisers), ' '), ) helpers = "" if desc.options.map_entry: # for map <key, value> fields # This mirrors the _IsMessageMapField check value_type = desc.fields_by_name['value'] if value_type.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: base_class = MessageMap else: base_class = ScalarMap # Rather than (key, value), use the attributes of the correct # MutableMapping type as the "slots" slots = tuple(m for m in dir(base_class) if not m.startswith("_")) helpers = 'def __getitem__(self, idx):\n pass\n' helpers += 'def __delitem__(self, idx):\n pass\n' body = ''.join([ _template_enum(d, descriptor_registry) for d in desc.enum_types ] + [ _template_message(d, descriptor_registry) for d in desc.nested_types ]) cls_str = ( 'class {name}(object):\n' ' {docstring!r}\n' ' __slots__ = {slots}\n' '{helpers}{body}{init}\n' ).format( name=desc.name, docstring="descriptor={}".format(desc.identifier), slots=slots, body=textwrap.indent(body, ' '), helpers=textwrap.indent(helpers, ' '), init=textwrap.indent(init_str, ' '), ) return cls_str
5,345,868
def random_portfolio(n, k, mu=0., sd=0.01, corr=None, dt=1., nan_pct=0.): """ Generate asset prices assuming multivariate geometric Brownian motion. :param n: Number of time steps. :param k: Number of assets. :param mu: Drift parameter. Can be scalar or vector. Default is 0. :param sd: Volatility of single assets. Default is 0.01. :param corr: Correlation matrix of assets. Default is identity. :param dt: Time step. :param nan_pct: Add given percentage of NaN values. Useful for testing """ # default values corr = corr if corr is not None else np.eye(k) sd = sd * np.ones(k) mu = mu * np.ones(k) # drift nu = mu - sd**2 / 2. # do a Cholesky factorization on the correlation matrix R = np.linalg.cholesky(corr).T # generate uncorrelated random sequence x = np.matrix(np.random.normal(size=(n - 1,k))) # correlate the sequences ep = x * R # multivariate brownian W = nu * dt + ep * np.diag(sd) * np.sqrt(dt) # generate potential path S = np.vstack([np.ones((1, k)), np.cumprod(np.exp(W), 0)]) # add nan values if nan_pct > 0: r = S * 0 + np.random.random(S.shape) S[r < nan_pct] = np.nan return pd.DataFrame(S)
5,345,869
def parse_command_line_arguments() -> None: """ Parse command line arguments and save their value in config.py. :return: None """ parser = argparse.ArgumentParser() parser.add_argument("-d", "--dataset", default="CBIS-DDSM", help="The dataset to use. Must be either 'mini-MIAS' or 'CBIS-DDMS'." ) parser.add_argument("-m", "--model", default="basic", help="The model to use. Must be either 'basic' or 'advanced'." ) parser.add_argument("-r", "--runmode", default="train", help="Running mode: train model from scratch and make predictions, otherwise load pre-trained " "model for predictions. Must be either 'train' or 'test'." ) parser.add_argument("-i", "--imagesize", default="small", help="small: use resized images to 512x512, otherwise use 'large' to use 2048x2048 size image with model with extra convolutions for downsizing." ) parser.add_argument("-v", "--verbose", action="store_true", help="Verbose mode: include this flag additional print statements for debugging purposes." ) parser.add_argument("-s", "--segmodel", default="RS50", help="Segmentation model to be used." ) parser.add_argument("-p", "--prep", default="N", help="Preprocessing of images" ) args = parser.parse_args() config.dataset = args.dataset config.model = args.model config.run_mode = args.runmode config.imagesize = args.imagesize config.verbose_mode = args.verbose config.segmodel = args.segmodel config.prep = args.prep
5,345,870
def vulnerabilities_for_image(image_obj): """ Return the list of vulnerabilities for the specified image id by recalculating the matches for the image. Ignores any persisted matches. Query only, does not update the data. Caller must add returned results to a db session and commit in order to persist. :param image_obj: the image :return: list of ImagePackageVulnerability records for the packages in the given image """ # Recompute. Session and persistence in the session is up to the caller try: ts = time.time() computed_vulnerabilties = [] for package in image_obj.packages: pkg_vulnerabilities = package.vulnerabilities_for_package() for v in pkg_vulnerabilities: img_v = ImagePackageVulnerability() img_v.pkg_image_id = image_obj.id img_v.pkg_user_id = image_obj.user_id img_v.pkg_name = package.name img_v.pkg_type = package.pkg_type img_v.pkg_arch = package.arch img_v.pkg_version = package.version img_v.pkg_path = package.pkg_path img_v.vulnerability_id = v.vulnerability_id img_v.vulnerability_namespace_name = v.namespace_name computed_vulnerabilties.append(img_v) #log.debug("TIMER VULNERABILITIES: {}".format(time.time() - ts)) return computed_vulnerabilties except Exception as e: log.exception('Error computing full vulnerability set for image {}/{}'.format(image_obj.user_id, image_obj.id)) raise
5,345,871
def update_cg_itp_obj(ns, parameters_set, update_type): """Update coarse-grain ITP. ns requires: out_itp (edited inplace) opti_cycle exec_mode """ if update_type == 1: # intermediary itp_obj = ns.out_itp elif update_type == 2: # cycles optimized itp_obj = ns.opti_itp else: msg = ( f"Code error in function update_cg_itp_obj.\nPlease consider opening an issue on GitHub " f"at {config.github_url}." ) raise exceptions.InvalidArgument(msg) for i in range(ns.opti_cycle["nb_geoms"]["constraint"]): if ns.exec_mode == 1: itp_obj["constraint"][i]["value"] = round(parameters_set[i], 3) # constraint - distance for i in range(ns.opti_cycle["nb_geoms"]["bond"]): if ns.exec_mode == 1: itp_obj["bond"][i]["value"] = round(parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + i], 3) # bond - distance itp_obj["bond"][i]["fct"] = round( parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + ns.opti_cycle["nb_geoms"]["bond"] + i], 3) # bond - force constant else: itp_obj["bond"][i]["fct"] = round(parameters_set[i], 3) # bond - force constant for i in range(ns.opti_cycle["nb_geoms"]["angle"]): if ns.exec_mode == 1: itp_obj["angle"][i]["value"] = round( parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + 2 * ns.opti_cycle["nb_geoms"]["bond"] + i], 2) # angle - value itp_obj["angle"][i]["fct"] = round(parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + 2 * ns.opti_cycle["nb_geoms"]["bond"] + ns.opti_cycle["nb_geoms"]["angle"] + i], 2) # angle - force constant else: itp_obj["angle"][i]["fct"] = round(parameters_set[ns.opti_cycle["nb_geoms"]["bond"] + i], 2) # angle - force constant for i in range(ns.opti_cycle["nb_geoms"]["dihedral"]): if ns.exec_mode == 1: itp_obj["dihedral"][i]["value"] = round(parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + 2 * ns.opti_cycle["nb_geoms"]["bond"] + 2 * ns.opti_cycle["nb_geoms"]["angle"] + i], 2) # dihedral - value itp_obj["dihedral"][i]["fct"] = round(parameters_set[ns.opti_cycle["nb_geoms"]["constraint"] + 2 * ns.opti_cycle["nb_geoms"]["bond"] + 2 * ns.opti_cycle["nb_geoms"]["angle"] + ns.opti_cycle["nb_geoms"]["dihedral"] + i], 2) # dihedral - force constant else: itp_obj["dihedral"][i]["fct"] = round( parameters_set[ns.opti_cycle["nb_geoms"]["bond"] + ns.opti_cycle["nb_geoms"]["angle"] + i], 2)
5,345,872
def superpose_images(obj, metadata, skip_overlaps=False, num_frames_for_bkgd=100, every=1, color_objs=False, disp_R=False, b=1.7, d=2, false_color=False, cmap='jet', remove_positive_noise=True): """ Superposes images of an object onto one frame. Parameters ---------- vid_path : string Path to video in which object was tracked. Source folder is `src/` obj : TrackedObject Object that has been tracked. Must have 'image', 'local centroid', 'frame_dim', 'bbox', and 'centroid' parameters. skip_overlaps : bool, optional If True, will skip superposing images that overlap with each other to produce a cleaner, though incomplete, image. Default False. every : int, optional Superposes every `every` image (so if every = 1, superposes every image; if every = 2, superposes every *other* image; if every = n, superposes every nth image). Default = 1 color_objs : bool, optional If True, will use image processing to highlight objects in each frame before superposing. Default False disp_R : bool, optional If True, will display the radius measured by image-processing in um above each object. b : float, optional Factor by which to scale brightness of superposed images to match background. Not sure why they don't automatically appear with the same brightness. Default is 1.7. d : int, optional Number of pixels to around the bounding box of the object to transfer to the superposed image. Helps ensure the outer edge of the image is bkgd. Default is 2. Returns ------- im : (M x N) numpy array of uint8 Image of object over time; each snapshot is superposed (likely black-and-white) """ ### initializes image as background ### # loads parameters highlight_kwargs = metadata['highlight_kwargs'] mask_data = highlight_kwargs['mask_data'] row_lo, _, row_hi, _ = mask.get_bbox(mask_data) # computes background bkgd = improc.compute_bkgd_med_thread(metadata['vid_path'], vid_is_grayscale=True, #assumes video is already grayscale num_frames=num_frames_for_bkgd, crop_y=row_lo, crop_height=row_hi-row_lo) # copies background to superpose object images on im = np.copy(bkgd) # converts image to 3-channel if highlighting objects (needs color) if color_objs: im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # initializes previous bounding box bbox_prev = (0,0,0,0) # loads video capture object cap = cv2.VideoCapture(metadata['vid_path']) # gets list of frames with object frame_list = obj.get_props('frame') ### Superposes image from each frame ### ct = 0 for i, f in enumerate(frame_list): # only superposes every "every"th image if (ct % every) != 0: ct += 1 continue # loads bounding box and image within it bbox = obj.get_prop('bbox', f) # skips images that overlap if requested if skip_overlaps: if basic.is_overlapping(bbox_prev, bbox): continue else: bbox_prev = bbox # highlights objects if requested if color_objs: # extracts radius of object R = obj.get_prop('radius [um]', f) # not sure why, but brightness must be 1.5 to match rest of image # selects offset that pushes label out of image offset = bbox[3]-bbox[1]+5 # reads frame and converts to color frame = basic.read_frame(cap, f) # highlights the object in the image im_obj = highlight.highlight_image(frame, f, cfg.highlight_method, metadata, {R : obj}, [R], brightness=b, offset=offset) # shows number ID of object in image centroid = obj.get_prop('centroid', f) # converts centroid from (row, col) to (x, y) for open-cv x = int(centroid[1]) y = int(centroid[0]) # superposes object image on overall image (3-channel images) row_min, col_min, row_max, col_max = bbox d = 2 im[row_min-d:row_max+d, col_min-d:col_max+d, :] = im_obj[row_min-d:row_max+d, col_min-d:col_max+d, :] if disp_R: # prints label on image (radius [um]) im = cv2.putText(img=im, text='{0:.1f}'.format(R), org=(x-10, y-7), fontFace=0, fontScale=0.5, color=cfg.white, thickness=2) else: # loads image im_raw = basic.read_frame(cap, f) im_obj = cv2.cvtColor(basic.adjust_brightness(im_raw, b), cv2.COLOR_BGR2GRAY)[row_lo:row_hi, :] # superposes object image on overall image row_min, col_min, row_max, col_max = bbox im[row_min:row_max, col_min:col_max] = im_obj[row_min:row_max, col_min:col_max] # increments counter ct += 1 # false-colors objects by taking signed difference with background if false_color: signed_diff = im.astype(int) - bkgd.astype(int) # remove noise above 0 (*assumes object is darker than background) if remove_positive_noise: signed_diff[signed_diff > 0] = 0 # defines false-color mapping to range to max difference max_diff = max(np.max(np.abs(signed_diff)), 1) # ensures >= 1 # normalizes image so -max_diff -> 0 and +max_diff -> 1 im_norm = (signed_diff + max_diff) / (2*max_diff) # maps normalized image to color image (still as floats from 0 to 1) color_mapped = cm.get_cmap(cmap)(im_norm) # converts to OpenCV format (uint8 0 to 255) im_false_color = basic.cvify(color_mapped) # converts from RGBA to RGB im = cv2.cvtColor(im_false_color, cv2.COLOR_RGBA2RGB) return im
5,345,873
def gen_s_linear(computed_data, param ): """Generate sensitivity matrix for wavelength dependent sensitivity modeled as line""" mat=np.zeros((computed_data.shape[0],computed_data.shape[0])) #print(mat.shape) for i in range(computed_data.shape[0]): for j in range(computed_data.shape[0]): v1 = computed_data[i, 0] - scenter # col 0 has position v2 = computed_data[j, 0] - scenter # col 0 has position #print(v1, v2) c1 = param[0] mat [i,j]=(1+ (c1/scale1)*v1 )/ \ (1+ (c1/scale1)*v2) return mat
5,345,874
def upsample2(x): """ Up-sample a 2D array by a factor of 2 by interpolation. Result is scaled by a factor of 4. """ n = [x.shape[0] * 2 - 1, x.shape[1] * 2 - 1] + list(x.shape[2:]) y = numpy.empty(n, x.dtype) y[0::2, 0::2] = 4 * x y[0::2, 1::2] = 2 * (x[:, :-1] + x[:, 1:]) y[1::2, 0::2] = 2 * (x[:-1, :] + x[1:, :]) y[1::2, 1::2] = x[:-1, :-1] + x[1:, 1:] + x[:-1, 1:] + x[1:, :-1] return y
5,345,875
def test_should_return_return_invalid_login_msg(db_session): """ Teste deve retornar usuário quando a senha está correta """ user = User( name="John Doe", username="jd", email="[email protected]", ) db_session.add(user) db_session.commit() with pytest.raises(UnauthorizedException) as error: auth.login(username="invalid", password="bla") assert str(error.value) == "Username or password invalid"
5,345,876
def test_surf_pipeline_cont_endpoint(): """Check: Data (Continuous Endpoint): SURF works in a sklearn pipeline""" np.random.seed(240932) clf = make_pipeline(SURF(n_features_to_select=2), RandomForestRegressor(n_estimators=100, n_jobs=-1)) assert abs(np.mean(cross_val_score(clf, features_cont_endpoint, labels_cont_endpoint, cv=3, n_jobs=-1))) < 0.5
5,345,877
def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return SafeBytes(s) if isinstance(s, (six.text_type, Promise)): return SafeText(s) return SafeString(str(s))
5,345,878
def ensure_environment_directory(environment_file_directory): """Ensure directory for environment files exists and is private""" # ensure directory exists os.makedirs(environment_file_directory, mode=0o700, exist_ok=True) # validate permissions mode = os.stat(environment_file_directory).st_mode if mode & 0o077: warnings.warn( f"Fixing permissions on environment directory {environment_file_directory}: {oct(mode)}", RuntimeWarning, ) os.chmod(environment_file_directory, 0o700) else: return # Check again after supposedly fixing. # Some filesystems can have weird issues, preventing this from having desired effect mode = os.stat(environment_file_directory).st_mode if mode & 0o077: warnings.warn( f"Bad permissions on environment directory {environment_file_directory}: {oct(mode)}", RuntimeWarning, )
5,345,879
def _unravel_plug(node, attr): """Convert Maya node/attribute combination into an MPlug. Note: Tries to break up a parent attribute into its child attributes: .t -> [tx, ty, tz] Args: node (str): Name of the Maya node attr (str): Name of the attribute on the Maya node Returns: MPlug or list: MPlug of the Maya attribute, list of MPlugs if a parent attribute was unravelled to its child attributes. """ LOG.debug("_unravel_plug (%s, %s)", node, attr) return_value = om_util.get_mplug_of_node_and_attr(node, attr) # Try to unravel the found MPlug into child attributes child_plugs = om_util.get_child_mplugs(return_value) if child_plugs: return_value = [child_plug for child_plug in child_plugs] return return_value
5,345,880
def index(): """ Root URL response """ return jsonify(name='Payment Demo REST API Service', version='1.0'), status.HTTP_200_OK
5,345,881
def unvoigt(A): """ Converts from 6x1 to 3x3 :param A: 6x1 Voigt vector (strain or stress) :return: 3x3 symmetric tensor (strain or stress) """ a=np.zeros(shape=(3,3)) a[0,0]=A[0] a[0,1]=A[5] a[0,2]=A[4] a[1,0]=A[5] a[1,1]=A[1] a[1,2]=A[3] a[2,0]=A[4] a[2,1]=A[3] a[2,2]=A[2] return (a)
5,345,882
def get_parser(): """ Creates a new argument parser. """ parser = argparse.ArgumentParser('niget_yyyymm.py', formatter_class=argparse.RawDescriptionHelpFormatter, description=""" help description """ ) version = '%(prog)s ' + __version__ parser.add_argument('--version', '-v', action='version', version=version, help='show version of this command') parser.add_argument('--csvfile', '-c', type=str, default="nicer_target_segment_table.csv", help='csvfile') parser.add_argument('--obsid', '-o', type=str, default=None, help='target ObsID (default=None)') return parser
5,345,883
def create_db(): """ Creates the db tables """ db.create_all()
5,345,884
def _calculate_rmsd(P, Q): """Calculates the root-mean-square distance between the points of P and Q. The distance is taken as the minimum over all possible matchings. It is zero if P and Q are identical and non-zero if not. """ distance_matrix = cdist(P, Q, metric='sqeuclidean') matching = linear_sum_assignment(distance_matrix) return np.sqrt(distance_matrix[matching].sum())
5,345,885
def use_backend(backend): """Select a backend for image decoding. Args: backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg` (see https://github.com/lilohuang/PyTurboJPEG) and `tifffile`. `turbojpeg` is faster but it only supports `.jpeg` file format. """ assert backend in supported_backends global imread_backend imread_backend = backend if imread_backend == 'turbojpeg': if TurboJPEG is None: raise ImportError('`PyTurboJPEG` is not installed') global jpeg if jpeg is None: jpeg = TurboJPEG() elif imread_backend == 'pillow': if Image is None: raise ImportError('`Pillow` is not installed') elif imread_backend == 'tifffile': if tifffile is None: raise ImportError('`tifffile` is not installed')
5,345,886
def initialize_parameters(): """ Initializes weight parameters to build a neural network with tensorflow. The shapes are: W1 : [4, 4, 3, 8] W2 : [2, 2, 8, 16] Note that we will hard code the shape values in the function to make the grading simpler. Normally, functions should take values as inputs rather than hard coding. Returns: parameters -- a dictionary of tensors containing W1, W2 """ tf.set_random_seed(1) # so that your "random" numbers match ours ### START CODE HERE ### (approx. 2 lines of code) W1 = tf.get_variable("W1",[4,4,3,8],initializer=tf.contrib.layers.xavier_initializer(seed = 0)) W2 = tf.get_variable("W2",[2,2,8,16],initializer=tf.contrib.layers.xavier_initializer(seed = 0)) ### END CODE HERE ### parameters = {"W1": W1, "W2": W2} return parameters
5,345,887
def generate_dynamic_secret(salt: str) -> str: """Creates a new overseas dynamic secret :param salt: A ds salt """ t = int(time.time()) r = "".join(random.choices(string.ascii_letters, k=6)) h = hashlib.md5(f"salt={salt}&t={t}&r={r}".encode()).hexdigest() return f"{t},{r},{h}"
5,345,888
def upload(slot_id): """ Upload a file """ form = request.form # Is the upload using Ajax, or a direct POST by the form? is_ajax = False if form.get("__ajax", None) == "true": is_ajax = True # Target folder for these uploads. target = os.path.join(APP_ROOT, UPLOAD_ROOT, slot_id) if os.path.isdir(target): shutil.rmtree(target) os.mkdir(target) for upload in request.files.getlist("file"): filename = upload.filename.rsplit("/")[0] destination = "/".join([target, filename]) upload.save(destination) # convert the file to syro format syroconvert(os.path.join(APP_ROOT, destination), slot_id) return ajax_response(True, slot_id)
5,345,889
def is_sim_f(ts_kname): """ Returns True if the TSDist is actually a similarity and not a distance """ return ts_kname in ('linear_allpairs', 'linear_crosscor', 'cross_correlation', 'hsdotprod_autocor_truncated', 'hsdotprod_autocor_cyclic')
5,345,890
def test_coerce() -> None: """Test value coercion.""" @dataclass class _TestClass: ival: int = 0 fval: float = 0.0 # Float value present for int should never work. obj = _TestClass() # noinspection PyTypeHints obj.ival = 1.0 # type: ignore with pytest.raises(TypeError): dataclass_validate(obj, coerce_to_float=True) with pytest.raises(TypeError): dataclass_validate(obj, coerce_to_float=False) # Int value present for float should work only with coerce on. obj = _TestClass() obj.fval = 1 dataclass_validate(obj, coerce_to_float=True) with pytest.raises(TypeError): dataclass_validate(obj, coerce_to_float=False) # Likewise, passing in an int for a float field should work only # with coerce on. dataclass_from_dict(_TestClass, {'fval': 1}, coerce_to_float=True) with pytest.raises(TypeError): dataclass_from_dict(_TestClass, {'fval': 1}, coerce_to_float=False) # Passing in floats for an int field should never work. with pytest.raises(TypeError): dataclass_from_dict(_TestClass, {'ival': 1.0}, coerce_to_float=True) with pytest.raises(TypeError): dataclass_from_dict(_TestClass, {'ival': 1.0}, coerce_to_float=False)
5,345,891
def initialise_pika_connection( host: Text, username: Text, password: Text, port: Union[Text, int] = 5672, connection_attempts: int = 20, retry_delay_in_seconds: float = 5, ) -> "BlockingConnection": """Create a Pika `BlockingConnection`. Args: host: Pika host username: username for authentication with Pika host password: password for authentication with Pika host port: port of the Pika host connection_attempts: number of channel attempts before giving up retry_delay_in_seconds: delay in seconds between channel attempts Returns: Pika `BlockingConnection` with provided parameters """ import pika parameters = _get_pika_parameters( host, username, password, port, connection_attempts, retry_delay_in_seconds ) return pika.BlockingConnection(parameters)
5,345,892
def _validate_game_id(game_id): """ Test whether a game ID is valid. If it is not, raise a 403 Forbidden. """ try: int(str(game_id)) except ValueError: abort(403, message="Malformed game ID {}".format(game_id))
5,345,893
def units(arg_name, unit): """Decorator to define units for an input. Associates a unit of measurement with an input. Parameters ---------- arg_name : str Name of the input to attach a unit to. unit : str Unit of measurement descriptor to use (e.g. "mm"). Example -------- Create an operation where its `x` parameter has its units defined in microns. >>> @OperationPlugin >>> @units('x', '\u03BC'+'m') >>> def op(x: float = -1) -> float: >>> return x *= -1.0 """ def decorator(func): _quick_set(func, 'units', arg_name, unit, {}) return func return decorator
5,345,894
async def to_thread_task(func: Callable, *args, **kwargs) -> Task: """Assign task to thread""" coro = to_thread(func, *args, **kwargs) return create_task(coro)
5,345,895
def setup_logging(stream_or_file=None, debug=False, name=None): """ Create a logger for communicating with the user or writing to log files. By default, creates a root logger that prints to stdout. :param stream_or_file: The destination of the log messages. If None, stdout will be used. :type stream_or_file: `unicode` or `file` or None :param debug: Whether or not the logger will be at the DEBUG level (if False, the logger will be at the INFO level). :type debug: `bool` or None :param name: The logging channel. If None, a root logger will be created. :type name: `unicode` or None :return: A logger that's been set up according to the specified parameters. :rtype: :class:`Logger` """ logger = logging.getLogger(name) if isinstance(stream_or_file, string_types): handler = logging.FileHandler(stream_or_file, mode='w') else: handler = logging.StreamHandler(stream_or_file or sys.stdout) logger.addHandler(handler) logger.setLevel(logging.DEBUG if debug else logging.INFO) return logger
5,345,896
def combo2fname( combo: Dict[str, Any], folder: Optional[Union[str, Path]] = None, ext: Optional[str] = ".pickle", sig_figs: int = 8, ) -> str: """Converts a dict into a human readable filename. Improved version of `combo_to_fname`.""" name_parts = [f"{k}_{maybe_round(v, sig_figs)}" for k, v in sorted(combo.items())] fname = Path("__".join(name_parts) + ext) if folder is None: return fname return str(folder / fname)
5,345,897
def insertTopic(datum): """Load a single topic.""" _insertSingle(datum, 'topic')
5,345,898
def cls_from_str(name_str): """ Gets class of unit type from a string Helper function for end-users entering the name of a unit type and retrieving the class that contains stats for that unit type. Args: name_str: str Returns: UnitStats """ name_str = name_str.lower() for cls in _UNIT_TYPES.values(): if cls.name.lower() == name_str: return cls
5,345,899