text:
from __future__ import absolute_import
from collections import defaultdict
import os
import click
import ncls
import numpy as np
from . import samclips

def mk_dest(d):
    if d is not None and not os.path.exists(d):
        try:
            os.mkdir(d)
        except:
            raise OSError("Couldn't create directory {}".format(d))

def make_template(rows, args, max_d, last_seen_chrom, fq):
    # Make a pickle-able data object for multiprocessing
    return {"isize": (args["insert_median"], args["insert_stdev"]),
            "max_d": max_d,
            "match_score": args["match_score"],
            "pairing_params": (args["max_insertion"], args["min_aln"], args["max_overlap"], args["ins_cost"],
                               args["ol_cost"], args["inter_cost"], args["u"]),
            "paired_end": int(args["paired"] == "True"),
            "inputdata": rows,
            "bias": args["bias"],
            "read1_length": 0,
            "read2_length": 0,
            "score_mat": {},
            "passed": 0,
            "name": rows[0][0][0],
            "last_seen_chrom": last_seen_chrom,
            "inputfq": fq,
            "read1_seq": 0,  # Some sam records may have seq == '*' , need a record of full seq for adding back in
            "read2_seq": 0,
            "read1_q": 0,
            "read2_q": 0,
            "read1_reverse": 0,  # Set to true if aligner has reverse complemented the sequence
            "read2_reverse": 0,
            "replace_hard": int(args["replace_hardclips"] == "True"),
            "fq_read1_seq": 0,
            "fq_read2_seq": 0,
            "fq_read1_q": 0,
            "fq_read2_q": 0
            }

def to_output(template):

    if "outstr" in template:
        return template["outstr"]

    # Todo make sure all read-pairs have a mapping, otherwise write an unmapped
    sam = samclips.fixsam(template)

    if len(sam) == 0:  # Todo fix unmapped reads
        template["passed"] = 0
        return ""

    # if len(sam) == 1:  # Todo deal with these
    #     click.echo("Single alignment only", err=True)
    #    return None

    if any(i[0] == "*" or i[4] == "*" for i in sam):
        template["passed"] = 0
        return ""

    return sam

def sam_to_str(template_name, sam):
    return "".join(template_name + "\t" + "\t".join(i) + "\n" for i in sam)

def get_bed_regions(bed):
    b = [tuple([int(j) if j.isdigit() else j for j in i.strip().split("\t")[:3]]) for i in open(bed, "r")
         if i[0] != "#" and len(i) > 0 and "\t" in i]
    if len(b) == 0:
        raise ValueError("Bed regions not formatted correctly")
    return b

def overlap_regions(bed):
    if not bed:
        return None
    regions = get_bed_regions(bed)
    chrom_interval_start = defaultdict(list)
    chrom_interval_end = defaultdict(list)
    for c, s, e in regions:
        chrom_interval_start[c].append(int(s))
        chrom_interval_end[c].append(int(e))

    regions = {k: ncls.NCLS(np.array(chrom_interval_start[k]),
                            np.array(chrom_interval_end[k]),
                            np.array(chrom_interval_start[k])) for k in chrom_interval_start}

    return regions

def intersecter(tree, chrom, start, end):
    if tree is None:
        return 0
    elif chrom in tree:
        if len(list(tree[chrom].find_overlap(start, end))) > 0:
            return 1
        else:
            return 0
    else:
        return 0

def get_include_reads(include, bam):

    if not include:
        for r in bam:
            yield r

    regions = [i.strip().split("\t")[:3] for i in open(include, "r") if i[0] != "#"]
    for c, s, e in regions:
        click.echo("Reading {}:{}-{}".format(c, s, e), err=True)
        for r in bam.fetch(c, int(s), int(e)):
            yield r

def sam_itr(args):

    itr = args["sam"]
    tree = overlap_regions(args["include"])

    # First get header
    header_string = ""
    last_seen_chrom = ""
    first_line = ""
    for t in itr:

        # t = str(t.decode("ascii"))

        if t[0] == "@":
            header_string += t
            continue

        first_line = t.split("\t", 4)
        last_seen_chrom = first_line[2]

        yield header_string
        break

    pos = int(first_line[3])
    ol = intersecter(tree, first_line[2], pos, pos + 250)

    yield (first_line, last_seen_chrom, ol)

    for t in itr:
        # t = str(t.decode("ascii"))
        line = t.split("\t", 4)

        if line[3] != last_seen_chrom:
            last_seen_chrom = line[2]

        pos = int(line[3])
        ol = intersecter(tree, line[2], pos, pos + 250)

        yield (line, last_seen_chrom, ol)

def fq_reader(args):
    # Iterate the fq files, send back a generator to use, generate only the read name, seq and qual lines
    # If > is at the start, iterate fasta instead
    def readfq(f):
        for l1 in f:
            l1 = l1.strip()
            last2 = l1[-2:]
            if l1[0] == "@":
                fastq = True
            else:
                fastq = False
            if last2 == "/2" or last2 == "/1":
                l1 = l1[1:-2]  # Strip trailing /1 or /2 and leading @
            else:
                l1 = l1[1:]
            l2 = next(f).strip()
            if fastq:
                next(f)  # Skip "+"
                l4 = next(f).strip()
            else:
                l4 = "1" * len(l2)
            yield l1, l2, l4

    if args["fq1"] is None:
        yield None, None

    if args["fq1"] and args["fq2"] is None:  # Single end
        with open(args["fq1"]) as fq1:
            for item in readfq(fq1):
                yield (item, None)
    else:
        with open(args["fq1"]) as fq1, open(args["fq2"]) as fq2:
            for item1, item2 in zip(readfq(fq1), readfq(fq2)):
                assert item1[0] == item2[0]
                yield item1, item2

def fq_getter(reader, name, args, fbuffer):

    if args["fq1"] is None:
        return None, None

    if name in fbuffer:
        fqlines = fbuffer[name]
        del fbuffer[fqlines[name]]
        return fqlines

    while True:
        fqlines = next(reader)
        q = fqlines[0][0]
        if q == name:
            return fqlines
        else:
            fbuffer[q] = fqlines

def iterate_mappings(args, version):
    arg_str = ", ".join(["{}={}".format(i, j) for i, j in args.items() if j is not None and "sam" not in i])
    inputstream = sam_itr(args)

    total = 0
    name = ""
    rows = []
    header_string = next(inputstream)
    header_string += "@PG\tID:fnfi\tPN:fnfi align\tVN:{}\tCL:{}\n".format(version, arg_str)

    yield header_string

    fq_buffer = defaultdict(list)
    fq_iter = fq_reader(args)

    max_d = args["insert_median"] + 4*args["insert_stdev"]  # Separation distance threshold to call a pair discordant
    last_seen_chrom = ""
    for m, last_seen_chrom, ol in inputstream:  # Alignment

        nm = m[0]
        if name != nm:
            if len(rows) > 0:
                total += 1
                fq = fq_getter(fq_iter, name, args, fq_buffer)

                # if name == "HISEQ2500-10:539:CAV68ANXX:7:2211:10642:81376":
                #     click.echo("io", err=True)

                yield (rows, args, max_d, last_seen_chrom, fq)

            rows = []
            name = nm

        rows.append((m, ol))  # String, ol states if alignment overlaps ROI

    # Deal with last record
    if len(rows) > 0:
        total += 1
        fq = fq_getter(fq_iter, name, args, fq_buffer)
        yield (rows, args, max_d, last_seen_chrom, fq)

    click.echo("Total processed " + str(total), err=True)

max_stars_repo_name: kcleal/fnfi

max_issues_repo_name: kcleal/fufi

max_forks_repo_name: kcleal/fufi


text:
for i in range(1):
    print(i)

print(2**4)

# import scipy.sparse as sp
#
# print(sp.eye(4))

ext: py

reason: import scipy


text:
import cvxpy as cp
import numpy as np
from numpy import newaxis
import control

def OTS(quadrotor_linear,y_ref,d_hat, A_obs,b_obs,Bd,Cd):

    cost = 0.
    constraints = []

    # Create the optimization variables
    x_ref = cp.Variable((10, 1))
    u_ref = cp.Variable((4, 1))

    #Cost we minimize

    cost+=cp.sum_squares(u_ref)
    cost+=cp.sum_squares(y_ref[:,np.newaxis]-x_ref)
    # Constraints
    constraints += [(np.eye(10)-quadrotor_linear.A)@ x_ref - quadrotor_linear.B @ u_ref == Bd @ d_hat]
    constraints += [quadrotor_linear.C @ x_ref == y_ref[:,np.newaxis] - Cd @ d_hat]
    # admissible x_ref and u_ref
    constraints += [A_obs[:,:] @ x_ref[:2] <= b_obs[:,np.newaxis]]
    constraints += [x_ref[6] <= 0.5]
    constraints += [x_ref[7] <= 0.5]
    constraints += [x_ref[6] >= -0.5]
    constraints += [x_ref[7] >= -0.5]
    constraints += [u_ref[:] >= -0.07*30]
    constraints += [u_ref[:] <= 0.07*30]

    problem = cp.Problem(cp.Minimize(cost), constraints)
    problem.solve()
    return x_ref.value,u_ref.value

def get_observer_gain(quadrotor_linear, Bd,Cd,eigen_values):
    # Use contro.place to get the wanted gain matrix
    nb_disturbances=len(Cd[0])
    nb_output=len(Cd)

    C_tilde=np.concatenate((quadrotor_linear.C,Cd), axis=1)
    A_tilde = np.block([[quadrotor_linear.A,               Bd                     ],
                        [np.zeros((nb_disturbances,10)),  np.eye(nb_disturbances) ]])
    L = control.place(A_tilde.T, C_tilde.T, eigen_values).T

    return L

def luenberger_observer(quadrotor_linear, x_hat, d_hat, y, u, Bd, Cd, L):
    nb_disturbances=len(Cd[0])
    nb_input=len(u)

    C_tilde=np.block([quadrotor_linear.C, Cd])
    A_tilde=np.block([[quadrotor_linear.A,              Bd                     ],
                      [np.zeros((nb_disturbances,10)),  np.eye(nb_disturbances)]])
    cur_state = np.block([[x_hat.reshape(-1,1)],
                          [d_hat.reshape(-1,1)]])
    new_state  = A_tilde @ cur_state + np.block([[quadrotor_linear.B                  ],
                                                 [np.zeros((nb_disturbances,nb_input))]]) @ u + L @ (y.reshape(-1,1) - C_tilde @ cur_state)

    return new_state[:10],new_state[10:]

def mpc_control(quadrotor_linear, N, x_init, x_target,u_target, A_obs,b_obs, xy_cost):
       # Weight on the input

    cost = 0.
    constraints = []

    # Create the optimization variables
    x = cp.Variable((10, N + 1)) # cp.Variable((dim_1, dim_2))
    u = cp.Variable((4, N))

    # Get constraints from obstacle list

    # For each stage in the MPC horizon
    Q = np.diag([xy_cost,xy_cost,1,1,1,1,1,1,1,1])
    R = 0.02*np.eye(4)
    for n in range(N):
        cost += (cp.quad_form((x[:,n+1]-x_target),Q)  + cp.quad_form(u[:,n]-u_target, R))
        constraints += [x[:,n+1] == quadrotor_linear.A @ x[:,n] + quadrotor_linear.B @ u[:,n]]
        # State and input constraints
        constraints += [x[6,n+1] <= 0.5]
        constraints += [x[7,n+1] <= 0.5]
        constraints += [x[6,n+1] >= -0.5]
        constraints += [x[7,n+1] >= -0.5]
        constraints += [u[:,n] >= -0.07*30]
        constraints += [u[:,n] <= 0.07*30]
        #Obstacle avoidance
        constraints += [A_obs @ x[:2,n] <= b_obs.flatten()]

    #Initial state
    constraints += [x[:,0] == x_init.flatten()]

    # Solves the problem
    problem = cp.Problem(cp.Minimize(cost), constraints)
    problem.solve(solver=cp.OSQP)
    # We return the MPC input
    return u[:, 0].value

def mpc_control_stable(quadrotor, N, x_init, x_target,u_target, A_obs,b_obs,c=0.01, xy_cost=1):

    cost = 0.
    constraints = []

    # Create the optimization variables
    x = cp.Variable((10, N + 1)) # cp.Variable((dim_1, dim_2))
    u = cp.Variable((4, N))

    # For each stage in the MPC horizon
    Q = np.diag([xy_cost,xy_cost,1,1,1,1,1,1,1,1])
    R = 0.02*np.eye(4)

    #Solve DARE and get eigen values and vectors
    P, L, K = control.dare(quadrotor.A, quadrotor.B, Q, R)
    eig_val,eig_vec=np.linalg.eig(P)
    #print(eig_val,eig_vec)
    for n in range(N):
        cost += (cp.quad_form((x[:,n+1]-x_target),Q)  + cp.quad_form(u[:,n]-u_target, R))
        constraints += [x[:,n+1] == quadrotor.A @ x[:,n] + quadrotor.B @ u[:,n]]
        constraints += [A_obs @ x[:2,n] <= b_obs.flatten()]
        constraints += [x[6,n+1] <= 0.5]
        constraints += [x[7,n+1] <= 0.5]
        constraints += [x[6,n+1] >= -0.5]
        constraints += [x[7,n+1] >= -0.5]
        constraints += [u[:,n] >= -0.07*30]
        constraints += [u[:,n] <= 0.07*30]
    # Terminal cost
    cost+=cp.quad_form((x[:,N]-x_target),P)
    #Initial state
    constraints += [x[:,0] == x_init.flatten()]

    #Terminal set but with linear constraints (cvxpy doesnt accept quadratic constraints)
    for j in range(len(eig_val)):
        constraints+= [(x[:,N]-x_target)  @ eig_vec[j]/np.linalg.norm(eig_vec[j])<=np.sqrt(c/eig_val[j])]
        constraints+= [(x[:,N]-x_target)  @ eig_vec[j]/np.linalg.norm(eig_vec[j])>=-np.sqrt(c/eig_val[j])]

    # Solves the problem
    problem = cp.Problem(cp.Minimize(cost), constraints)
    problem.solve(solver=cp.OSQP)

    # We return the MPC input
    return u[:, 0].value

max_stars_repo_name: smoggy-P/MPC-Collision-Avoidance

max_issues_repo_name: smoggy-P/MPC-Collision-Avoidance

max_forks_repo_name: smoggy-P/MPC-Collision-Avoidance

reason: import numpy,from numpy,import cvxpy


text:
import argparse
from rdkit import Chem
import sys
sys.path.append(".")

import numpy as np

from grammar_model.alphabets import MoleculeAlphabet

parser = argparse.ArgumentParser()
parser.add_argument("data", type=str)
args = parser.parse_args()

a = MoleculeAlphabet()

with open(args.data, 'r') as fhandle:
    mol_strs = fhandle.read().strip().split('\n')

print("Preprocessing, this takes a couple minutes")
clean_strs, clean_idxs = [], []

rejected = 0
for mol_str in mol_strs:
    if not a._validate(mol_str):
        rejected += 1
        continue
    try:
        idx = a.expr2idx(mol_str)
        clean_strs.append(mol_str)
        clean_idxs.append(idx)
    except ValueError:
        rejected += 1
        continue

max_len = np.max([len(idx) for idx in clean_idxs])
print('max_len:', max_len)
max_len = 75
idxs_padding = []
for idx in clean_idxs:
    idxs_padding.append(idx + [a.alphabet.index(' ')] * (max_len - len(idx)))

data = np.array(idxs_padding, dtype=np.uint8)

if "zinc" in args.data:
    print(len(data))
    np.savez_compressed(args.data.split('.')[0], train=data[:-5000], test=data[-5000:])
else:
    np.savez_compressed(args.data.split('.')[0], test=data)

print("File {} processed, {} rejected.".format(args.data, rejected))

reason: import numpy


text:
import unittest

import numpy as np

from rastervision.core.rv_pipeline.utils import (fill_no_data,
                                                 nodata_below_threshold)

class TestUtils(unittest.TestCase):
    def test_fill_no_data(self):
        chip = np.ones((256, 256, 3), dtype=np.uint8)
        label = np.zeros((256, 256), dtype=np.uint8)
        label[:, 128:] = 2

        chip_filled = fill_no_data(chip, label, null_class_id=2)
        self.assertEqual(chip_filled[:, 128:].sum(), 0)
        self.assertEqual(chip_filled[:, :128].sum(), chip[:, :128].sum())

    def test_nodata_below_threshold(self):
        chip = np.ones((256, 256, 3), dtype=np.uint8)
        # different proportions of nodata
        mask_0 = np.ones_like(chip)
        mask_50 = np.ones_like(chip)
        mask_50[:128] = 0
        mask_100 = np.zeros_like(chip)

        # 0% nodata
        test_chip = chip & mask_0
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.00))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=0.25))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=0.50))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=0.75))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=1.00))

        # 50% nodata
        test_chip = chip & mask_50
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.00))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.25))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.50))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=0.75))
        self.assertTrue(nodata_below_threshold(test_chip, threshold=1.00))

        # 100% nodata
        test_chip = chip & mask_100
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.00))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.25))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.50))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=0.75))
        self.assertFalse(nodata_below_threshold(test_chip, threshold=1.00))

if __name__ == '__main__':
    unittest.main()

max_stars_repo_name: theoway/raster-vision

max_issues_repo_name: theoway/raster-vision

max_forks_repo_name: monocilindro/raster-vision


text:
#!/opt/anaconda3/bin/python

import math
import os.path
import statistics
import subprocess
import sys
from collections import namedtuple

import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw

import tabio.pascalvoc

def bbox_union(a, b):
    if a == None:
        return b
    if b == None:
        return a
    return tabio.pascalvoc.BBox(
        min(a.left, b.left), max(a.bottom, b.bottom),
        max(a.right, b.right), min(a.top, b.top))

# holds text, a list of bounding boxes for each char, and an overall box for the line
Line = namedtuple('Line', ['text', 'bboxes', 'bbox', 'side'])

# returns a list of Line structures
# multiple lines may be physically next to eachother on the page
# each line is separated by a '\n' char in the csv

def read_csv(fname):
    obj = csvfile2Object(fname)
    if len(obj) == 0:
        print("{} empty csv".format(fname))
        return []

    text = getText(obj)
    lines = []
    line_bbox = None
    line_bboxes = []
    line_chars = []

    for c, i in zip(text[1], text[2]):
        if c == '\n':
            lines.append(Line(''.join(line_chars),
                         line_bboxes, line_bbox, 'unknown'))
            line_bbox = None
            line_bboxes = []
            line_chars = []
            continue

        bbox = None
        if i != 'None':
            info = obj[i]
            xScale = 300.0/72.0
            yScale = xScale
            bbox = tabio.pascalvoc.BBox(
                (info.x)*xScale,
                (info.y)*yScale,
                (info.x+info.width)*xScale,
                (info.y-info.height)*yScale)

        line_bbox = bbox_union(line_bbox, bbox)
        line_chars.append(c)
        line_bboxes.append(bbox)

    return lines

# returns a list of Line structures
# each Line contains chars that share the same Y (+- epsilon)
# order of the input chars and lines is ignored

def group_lines_spacially(lines):
    if len(lines) == 0:
        return []

    size = mean_char_size(lines)
    y_separation = size[1] * .8

    # ignore the lines in the csv
    # find lines based on spacial location
    chars = []
    for line in lines:
        for c, b in zip(line.text, line.bboxes):
            if b is not None:
                chars.append((c, b))

    chars = sorted(chars, key=lambda x: x[1].top)

    spacial_lines = []

    line_chars = []
    line_bboxes = []
    line_top = chars[0][1].top
    line_bbox = None

    for c, b in chars:
        area = (b.bottom - b.top) * (b.right - b.left)
        # print(area)
        if area == 0.0:
            continue

        if b.top < (line_top + y_separation):
            line_chars.append(c)
            line_bboxes.append(b)
            line_bbox = bbox_union(line_bbox, b)
        else:
            if line_bbox is not None:
                line = Line(''.join(line_chars), line_bboxes,
                            line_bbox, 'unknown')
                spacial_lines.append(line)
            line_bboxes = [b]
            line_chars = [c]
            line_bbox = b
            line_top = b.top

    if line_bbox is not None:
        line = Line(''.join(line_chars), line_bboxes, line_bbox, 'unknown')
        spacial_lines.append(line)
    return spacial_lines

def is_bbox_inside(outside, inside):
    return (outside.left < inside.left
            and outside.right > inside.right
            and outside.bottom < inside.bottom
            and outside.top > inside.top)

def find(f, seq):
    """Return first item in sequence where f(item) == True."""
    for item in seq:
        if f(item):
            return item
    return None

def mean_char_size(lines):
    char_widths = []
    char_heights = []

    for line in lines:
        for b in line.bboxes:
            if b is not None:
                char_widths.append(b.right - b.left)
                char_heights.append(b.bottom - b.top)

    return (statistics.mean(char_widths), statistics.mean(char_heights))

# detects any margins on the top and left side of the chars
# shifts all the chars (left, and up) to remove the margin

def remove_margin(lines):
    min_x = float("inf")
    min_y = float("inf")

    for line in lines:
        for bbox in line.bboxes:
            if bbox.left < 0 or bbox.top < 0:
                continue

            min_x = min(min_x, bbox.left)
            min_y = min(min_y, bbox.top)
    return lines

    result = []
    for line in lines:
        shifted_bboxes = []
        for bbox in line.bboxes:
            shifted_bboxes.append(tabio.pascalvoc.BBox(
                left=bbox.left-min_x,
                top=bbox.top-min_y,
                right=bbox.right-min_x,
                bottom=bbox.bottom-min_y))

        result.append(Line(
            text=line.text,
            bboxes=shifted_bboxes,
            bbox=tabio.pascalvoc.BBox(
                left=line.bbox.left-min_x,
                top=line.bbox.top-min_y,
                right=line.bbox.right-min_x,
                bottom=line.bbox.bottom-min_y),
            side='unknown'))

    return result

def size(lines):
    x = 0.0
    y = 0.0
    for line in lines:
        for bbox in line.bboxes:
            x = max(x, bbox.right)
            y = min(y, bbox.bottom)
    return (x, y)

def draw(lines, ax):
    for line in lines:

        for char, bbox in zip(line.text, line.bboxes):
            if bbox is None:
                continue

            # shade over the char in blue
            b = bbox
            rect = patches.Rectangle(
                (b.left, b.bottom),
                (b.right-b.left),
                (b.top-b.bottom))
            ax.add_patch(rect)

        # draw red rectangle around whole line
        b = line.bbox
        rect = patches.Rectangle(
            (b.left, b.bottom),
            (b.right-b.left),
            (b.top-b.bottom),
            linewidth=1, edgecolor='r', facecolor='none')
        ax.add_patch(rect)

    # draw arrows between lines to show order
    for a, b in zip(lines, lines[1:]):
        dx = b.bbox.left - a.bbox.left
        dy = b.bbox.top - a.bbox.bottom
        ax.arrow(a.bbox.left, a.bbox.bottom, dx, dy, width=3,
                 shape='full', length_includes_head=True)

def create_csv_from_pdf(pdf_fname, page_number):
    '''
    This function gets the CSV from the pdf file and then converts into list of objects.
    '''
    pdfbox_jar = os.path.join(os.path.dirname(__file__), './ExtractText.jar')

    dir_name = os.path.dirname(pdf_fname)
    base_name, _ = os.path.splitext(os.path.basename(pdf_fname))
    out_path = os.path.join(dir_name, base_name+'_'+str(page_number)+'.csv')

    result = subprocess.run(
        [
            'java',
            "-jar",
            "-Xms1024m",
            "-Xmx8196m",
            pdfbox_jar,
            pdf_fname,
            str(page_number),
            out_path
        ],
        check=True,
        timeout=120)

    return out_path

class CSV2Obj():
    """CSV2Obj
    Converts a string read from a CSV format to an object.
    """

    def __init__(self, single_char):
        char_attributes = single_char.split(",")
        if len(char_attributes) == 17 or len(char_attributes) == 18:
            # ipdb.set_trace()
            # print("###################################3")
            # print(char_attributes)
            if char_attributes[0] == '"':
                self.unicode = ','
                #print("yo ",char_attributes[0])
                # print(char_attributes)
                char_attributes.remove(char_attributes[1])
            else:
                # print(char_attributes[0])
                self.unicode = char_attributes[0][1:-1]
            self.characterCode = int((char_attributes[1]))
            self.x = float(char_attributes[2])
            # print(char_attributes)
            self.y = float(char_attributes[3])
            self.fontSize = float(char_attributes[4])
            # print(char_attributes[5])
            self.fontSizeInPt = float(char_attributes[5])
            if len(char_attributes) == 17:
                self.font = char_attributes[6].replace('"', '')

            elif len(char_attributes) == 18:
                self.font = char_attributes[6].replace(
                    '"', '') + char_attributes[7].replace('"', '')
                char_attributes.remove(char_attributes[7])
            elif len(char_attributes) == 19:
                self.font = char_attributes[6].replace(
                    '"', '') + char_attributes[7].replace('"', '') + char_attributes[8].replace('"', '')
                char_attributes.remove(char_attributes[7])
                char_attributes.remove(char_attributes[8])
            self.width = float(char_attributes[7])
            self.height = float(char_attributes[8])
            self.widthDirAdj = float(char_attributes[9])
            self.widthOfSpace = float(char_attributes[10])
            self.heightDir = float(char_attributes[11])
            self.xScale = float(char_attributes[12])
            self.yScale = float(char_attributes[13])
            self.dir = float(char_attributes[14])
            self.xDirAdj = float(char_attributes[15])
            self.yDirAdj = float(char_attributes[16])

        elif len(char_attributes) == 16 or len(char_attributes) == 15:
            if char_attributes[0] == '"':
                self.unicode = ','
                # print(char_attributes)
                char_attributes.remove(char_attributes[1])
            else:
                self.unicode = char_attributes[0].replace('"', '')
            self.characterCode = int((char_attributes[1]))
            self.x = float(char_attributes[2])
            # print(char_attributes)
            self.y = float(char_attributes[3])
            self.fontSize = float(char_attributes[4])
            # print(char_attributes[5])
            self.fontSizeInPt = float(char_attributes[5])
            if len(char_attributes) == 15:
                self.font = char_attributes[6].replace('"', '')

            elif len(char_attributes) == 16:
                self.font = char_attributes[6].replace(
                    '"', '') + char_attributes[7].replace('"', '')
                char_attributes.remove(char_attributes[7])

            self.width = float(char_attributes[7])
            self.height = float(char_attributes[8])
            self.widthDirAdj = float(char_attributes[9])
            self.widthOfSpace = float(char_attributes[10])
            self.heightDir = float(char_attributes[11])
            self.xScale = float(char_attributes[12])
            self.yScale = float(char_attributes[13])
            self.dir = float(char_attributes[14])
            self.xDirAdj = float(char_attributes[2])
            self.yDirAdj = float(char_attributes[3])
        else:
            raise Exception("invalid number of columns in csv '" +
                            str(len(char_attributes))+"'")

def csvfile2Object(file_name):
    '''
    This function reads a csv file and converts into objects
    '''
    lines = []
    with open(file_name) as f:
        for line in f:
            lines.append(line)
    filetext = open(file_name, "r").read()
    # reading csv files
    lines = filetext.split("\n")
    # spliting csv file into lines
    a = len(lines)
    del lines[a-1]
    list_object = []
    for strings in lines:
        # print(strings)
        myobject = CSV2Obj(strings)
        list_object.append(myobject)
        # converting into objects and adding them to the list
    return list_object

def getText(structure):
    '''
    this function extracts rawText, FormattedText and mapping of character by taking in structure as in input.
    '''
    IndexList = []
    plainStringList = []
    FormattedStringList = []
    if len(structure) == 0:
        # Nothing means an empty page or just a space
        return [[" "], [" "], [0]]
    xback = int(round(structure[0].xDirAdj))
    # getting the x co-ordinate of the first object
    yback = int(round(structure[0].yDirAdj))
    # getting the y co-ordinate of the first object
    width = int(math.floor(structure[0].widthDirAdj))
    avg_width = 0
    # getting the width of the first object
    for i in range(len(structure)):
        avg_width += structure[i].widthDirAdj
    index = 0
    avg_width = avg_width/len(structure)
    if avg_width == 0:
        avg_width = 1
        print("WARNING: Found average width zero in getText. Length of structure = "+str(len(structure)))

    for character in structure:
        # processing each object in list of objects
        plainStringList.append(character.unicode)
        # ipdb.set_trace()

        xco = int(round(character.xDirAdj))
        yco = int(round(character.yDirAdj))

        if width == 0:
            width = 1
        # setting to width to 1 if it comes to 0 after rounding off in order to avoid errors

        t_test = int(math.ceil(abs(xco-xback)/avg_width))
        # calculating the spacing between characters

        y_test = abs(yco-yback)
        # calculating the change of line

        if t_test >= 6 or y_test > 5:

            if y_test > 5:
                FormattedStringList.append("\n")
                IndexList.append("None")
                # if there is change in line , then linefeed is inserted
                FormattedStringList.append(character.unicode)
                IndexList.append(int(index))
                index += 1
            else:
                FormattedStringList.append(" ")
                # if there is some spacing, then space is inserted
                IndexList.append("None")

                FormattedStringList.append(character.unicode)
                IndexList.append(int(index))
                index += 1
        else:

            # plainStringList.append(character.unicode)
            FormattedStringList.append(character.unicode)
            IndexList.append(int(index))
            index += 1
        xback = xco
        yback = yco
        width = int((character.widthDirAdj))
    function_output = [plainStringList, FormattedStringList, IndexList]
    # print(plainStringList)
    # print(Format)
    return function_output

if __name__ == '__main__':
    doc_hash = '2ec6960ba691c6dc7880cabeafce2129'
    doc_csv_hash = '2ec6960ba691c6dc7880cabeafce2129'
    #doc_csv_hash = doc_hash

    #csv_contents = sql2box.charDictExtract(None, doc_hash, None)
    # for page,csv in csv_contents.items():
    #    with open(doc_hash+'_'+str(page)+'_'+str(page)+'.csv', 'wt') as f:
    #        f.write(csv)
    # sys.exit(0)

    page_number = int(sys.argv[1])
    base_fname = '../labeled-data/SortedIFP/'+doc_hash+'/' + \
        doc_hash+'_'+str(page_number)+'_'+str(page_number)
    base_csv_fname = '../labeled-data/SortedIFP/'+doc_hash+'/' + \
        doc_csv_hash+'_'+str(page_number)+'_'+str(page_number)

    labeled_boxes = tabio.pascalvoc.read(base_fname+'.xml')

    line_bboxes = []

    line_bbox = None
    line_chars = []
    line_category = None

    im = np.array(Image.open(base_fname+'.jpg'), dtype=np.uint8)

    fig, ax = plt.subplots(1)

    ax.imshow(im)

    lines = read_csv(base_csv_fname+'.csv')
    #lines = group_lines_spacially(lines)

    for line in lines:

        line_category = None

        for char, bbox in zip(line.text, line.bboxes):
            if bbox is None:
                continue

            # detect line category
            if line_category is None:
                found_category = find(lambda x: is_bbox_inside(
                    x.bbox, bbox), labeled_boxes)
                if found_category is not None:
                    line_category = found_category.name

        print(f"{line_category}\t\t{line.text}")

    draw(lines, ax)
    tabio.pascalvoc.draw(labeled_boxes, ax)

    plt.show()
    fig.savefig('fig.jpg', bbox_inches='tight', dpi=150)

max_stars_repo_name: AgileDD/tabio

max_issues_repo_name: AgileDD/tabio

max_forks_repo_name: AgileDD/tabio


text:
import os
import sys
import time
import traceback
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.backends.backend_wx import NavigationToolbar2Wx

import wx

from matplotlib.figure import Figure

class PlotFigure(wx.Frame):

    def OnKeyPressed (self, event):
        key = event.key
        if key=='q':
            self.OnClose(event)

    def __init__(self, func, timer_period):
        wx.Frame.__init__(self, None, -1, "Plot Figure")

        self.fig = Figure((12,9), 75)
        self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        self.canvas.mpl_connect('key_press_event', self.OnKeyPressed)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.func = func
        self.plot = None

        self.timer_period = timer_period
        self.timer = wx.Timer(self)
        self.is_stopped = False

        if os.name=='nt':
            # On Windows, default frame size behaviour is incorrect
            # you don't need this under Linux
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things

        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
        self.Bind(wx.EVT_TIMER, self.OnTimerWrap, self.timer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.timer.Start(timer_period)

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar

    def OnClose(self, event):
        self.is_stopped = True
        print('Closing PlotFigure, please wait.')
        self.timer.Stop()
        self.Destroy()

    def OnTimerWrap (self, evt):
        if self.is_stopped:
            print('Ignoring timer callback')
            return
        t = time.time()
        try:
            self.OnTimer (evt)
        except KeyboardInterrupt:
            self.OnClose(evt)
        duration = 1000*(time.time () - t)
        if duration > self.timer_period:
            print('Changing timer_period from %s to %s msec' % (self.timer_period, 1.2*duration))
            self.timer_period = 1.2*duration
            self.timer.Stop()
            self.timer.Start (self.timer_period)

    def OnTimer(self, evt):

        try:
            xdata, ydata_list, legend = self.func()
        except RuntimeError:
            traceback.print_exc(file=sys.stderr)
            self.OnClose(evt)
            return
        if len (ydata_list.shape)==1:
            ydata_list = ydata_list.reshape((1, ydata_list.size))
        if self.plot is None:
            self.axes = self.fig.add_axes([0.1,0.1,0.8,0.8])
            l = []
            for ydata in ydata_list:
                l.extend ([xdata, ydata])
            self.plot = self.axes.plot(*l)
            self.axes.set_xlabel('Seconds')
            self.axes.set_ylabel('Volts')
            self.axes.set_title('nof samples=%s' % (len(xdata)))
            self.axes.legend (legend)
        else:
            self.axes.set_xlim(xmin = xdata[0], xmax=xdata[-1])
            ymin, ymax = 1e9,-1e9
            for line, data in zip (self.plot, ydata_list):
                line.set_xdata(xdata)
                line.set_ydata(data)
                ymin, ymax = min (data.min (), ymin), max (data.max (), ymax)
            dy = (ymax-ymin)/20
            self.axes.set_ylim(ymin=ymin-dy, ymax=ymax+dy)
        self.canvas.draw()

    def onEraseBackground(self, evt):
        # this is supposed to prevent redraw flicker on some X servers...
        pass

def animated_plot(func, timer_period):
    app = wx.PySimpleApp(clearSigInt=False)
    frame = PlotFigure(func, timer_period)
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    from numpy import *
    import time
    start_time = time.time ()
    def func():
        x = arange (100, dtype=float)/100*pi
        d = sin (x+(time.time ()-start_time))
        return x, d, ['sin (x+time)']

    try:
        animated_plot (func, 1)
    except Exception as msg:
        print('Got exception: %s' % ( msg))
    else:
        print('Exited normally')

max_stars_repo_name: olsonse/pylibnidaqmx

max_issues_repo_name: olsonse/pylibnidaqmx

max_forks_repo_name: olsonse/pylibnidaqmx

reason: from numpy


text:
import os

import numpy as np
import torch

from embryovision.util import load_and_crop_image, augment_focus
from embryovision.localfolders import embryovision_folder
from embryovision.predictor import Predictor, load_classifier
from embryovision.managedata import FilenameParser

class StagePredictor(Predictor):
    loadname = os.path.join(
        embryovision_folder, 'stage', 'stageclassifier.pkl')
    input_shape = (224, 224)
    load_network = staticmethod(load_classifier)

    def _predict(self, filenames_and_boxes):
        input_x = self._read_images_for_stage(filenames_and_boxes)
        stage_probs = self.network.predict_proba(input_x)
        infos = [
            FilenameParser.get_imageinfo_from_filename(nm)
            for nm, box in filenames_and_boxes]
        return self.pack_into_annotated_images(infos, stage_probs)

    def _read_images_for_stage(self, filenames_and_boxes):
        images_numpy = np.array([
            self._load_inputs_at_one_timepoint(f0_filename, box)
            for f0_filename, box in filenames_and_boxes])
        images_torch = torch.from_numpy(images_numpy.astype('float32'))
        images_torch = images_torch.to(self.device)
        return images_torch

    def _load_inputs_at_one_timepoint(self, f0_filename, box):
        bottom, middle, top = augment_focus(f0_filename)
        images = [
            np.array(
                load_and_crop_image(
                    name,
                    box,
                    output_shape=self.input_shape)
                )
            for name in [middle, top, bottom]]
        images = np.array(images).astype('float32') / 255.0
        images = (images - 0.5) / 0.25
        return images

max_stars_repo_name: briandleahy/embryovision

max_issues_repo_name: briandleahy/embryovision

max_forks_repo_name: briandleahy/embryovision


text:
import numpy as np
from typing import Dict, Any, Tuple, Optional, List

import tensorflow as tf

from exprsynth.contexttokenmodel import ContextTokenModel
from exprsynth.seqdecoder import SeqDecoder

class Seq2SeqModel(ContextTokenModel):
    @staticmethod
    def get_default_hyperparameters() -> Dict[str, Any]:
        defaults = ContextTokenModel.get_default_hyperparameters()
        decoder_defaults = SeqDecoder.get_default_hyperparameters()
        defaults.update(decoder_defaults)
        return defaults

    def __init__(self, hyperparameters, run_name: Optional[str]=None, model_save_dir: Optional[str]=None, log_save_dir: Optional[str]=None):
        super().__init__(hyperparameters, run_name, model_save_dir, log_save_dir)
        self._decoder_model = SeqDecoder(self)

    def _make_parameters(self):
        super()._make_parameters()

        hole_cx_hidden_size = self.hyperparameters['hole_rnn_layer_size'] * 2
        self.parameters['cx_representation_to_dec_hidden'] = \
            tf.get_variable(name='cx_representation_to_dec_hidden',
                            initializer=tf.glorot_uniform_initializer(),
                            shape=[hole_cx_hidden_size, self.hyperparameters['decoder_rnn_hidden_size']],
                            )

        self._decoder_model.make_parameters()

    def _make_placeholders(self, is_train: bool) -> None:
        super()._make_placeholders(is_train)
        self._decoder_model.make_placeholders(is_train)

    def _make_model(self, is_train: bool=True):
        super()._make_model(is_train)

        # Linear layer to uncouple the latent space and dimensionality of encoder and decoder:
        num_cx_tokens_per_side = self.hyperparameters['num_cx_tokens_per_side']
        cx_hole_representations = self.ops['cx_hole_context_representations'][num_cx_tokens_per_side]
        self.ops['decoder_initial_state'] = tf.matmul(cx_hole_representations,
                                                      self.parameters['cx_representation_to_dec_hidden'])

        self._decoder_model.make_model(is_train)

    @staticmethod
    def _init_metadata(hyperparameters: Dict[str, Any], raw_metadata: Dict[str, Any]) -> None:
        super(Seq2SeqModel, Seq2SeqModel)._init_metadata(hyperparameters, raw_metadata)
        SeqDecoder.init_metadata(raw_metadata)

    @staticmethod
    def _load_metadata_from_sample(hyperparameters: Dict[str, Any], raw_sample: Dict[str, Any], raw_metadata: Dict[str, Any]) -> None:
        super(Seq2SeqModel, Seq2SeqModel)._load_metadata_from_sample(hyperparameters, raw_sample, raw_metadata)
        SeqDecoder.load_metadata_from_sample(raw_sample, raw_metadata)

    def _finalise_metadata(self, raw_metadata_list: List[Dict[str, Any]]) -> Dict[str, Any]:
        final_metadata = super()._finalise_metadata(raw_metadata_list)
        self._decoder_model.finalise_metadata(raw_metadata_list, final_metadata)
        return final_metadata

    @staticmethod
    def _load_data_from_sample(hyperparameters: Dict[str, Any],
                               metadata: Dict[str, Any],
                               raw_sample: Dict[str, Any],
                               result_holder: Dict[str, Any],
                               is_train: bool=True) -> bool:
        keep_sample = super(Seq2SeqModel, Seq2SeqModel)._load_data_from_sample(hyperparameters, metadata, raw_sample, result_holder, is_train)
        if keep_sample:
            SeqDecoder.load_data_from_sample(hyperparameters, metadata, raw_sample, result_holder, is_train)
        return keep_sample

    def _init_minibatch(self, batch_data: Dict[str, Any]) -> None:
        super()._init_minibatch(batch_data)
        self._decoder_model.init_minibatch(batch_data)

    def _extend_minibatch_by_sample(self, batch_data: Dict[str, Any], sample: Dict[str, Any]) -> bool:
        batch_finished = super()._extend_minibatch_by_sample(batch_data, sample)
        self._decoder_model.extend_minibatch_by_sample(batch_data, sample)
        return batch_finished

    def _finalise_minibatch(self, batch_data: Dict[str, Any], is_train: bool) -> Dict[tf.Tensor, Any]:
        minibatch = super()._finalise_minibatch(batch_data, is_train)
        self._decoder_model.finalise_minibatch(batch_data, minibatch)
        return minibatch

    # ------- These are the bits that we only need for test-time:
    def _encode_one_test_sample(self, sample_data_dict: Dict[tf.Tensor, Any]) -> Tuple[tf.Tensor, Optional[tf.Tensor]]:
        return (self.sess.run(self.ops['decoder_initial_state'],
                              feed_dict=sample_data_dict),
                None)

    def _tensorise_one_test_sample(self, loaded_sample: Dict[str, Any]) -> Dict[tf.Tensor, Any]:
        test_minibatch = {}
        self._init_minibatch(test_minibatch)

        # Note that we are primarily interested in the context encoding:
        super()._extend_minibatch_by_sample(test_minibatch, loaded_sample)
        final_test_minibatch = super()._finalise_minibatch(test_minibatch, is_train=False)

        return final_test_minibatch

max_stars_repo_name: SWerllen/graph-based-code-modelling

max_issues_repo_name: SWerllen/graph-based-code-modelling

max_forks_repo_name: SWerllen/graph-based-code-modelling


text:
from .core import build_jax_fem_eval, build_jax_fem_eval_fwd
from .helpers import jax_to_fenics, jax_to_fenics_numpy
from fenics_numpy import numpy_to_fenics, fenics_to_numpy

max_stars_repo_name: paraklas/jax-fenics-adjoint

max_issues_repo_name: paraklas/jax-fenics-adjoint

max_forks_repo_name: paraklas/jax-fenics-adjoint

reason: import numpy,import jax


text:
#!/usr/bin/env python

"""
Unit tests for the rotmat library
"""

from __future__ import absolute_import, division, print_function
from math import radians, degrees
import unittest
import random
import numpy as np

from pymavlink.rotmat import Vector3, Matrix3, Plane, Line

class VectorTest(unittest.TestCase):

    """
    Class to test Vector3
    """

    def __init__(self, *args, **kwargs):
        """Constructor, set up some data that is reused in many tests"""
        super(VectorTest, self).__init__(*args, **kwargs)

    def test_constructor(self):
        """Test the constructor functionality"""
        v1 = Vector3(1, 0.2, -3)
        v2 = Vector3([1, 0.2, -3])
        v3 = Vector3([1, 0.3, -3])

        assert v1 == v2
        assert v1 != v3
        assert str(v1) == "Vector3(1.00, 0.20, -3.00)"

    def test_maths(self):
        """Test simple maths"""
        v1 = Vector3(1, 2, -3)
        v2 = Vector3(1, 3, 3)

        assert v1 + v2 == Vector3(2, 5, 0)
        assert v1 - v2 == Vector3(0, -1, -6)
        assert (v1 * 3) == Vector3(3, 6, -9)
        assert v1 * v2 == -2

        assert v1 % v2 == Vector3(15.00, -6.00, 1.00)
        np.testing.assert_almost_equal(v2.length(), 4.358898943540674)
        assert v2.normalized().close(Vector3(0.23, 0.69, 0.69), tol=1e-2)
        np.testing.assert_almost_equal(v1.angle(v2), 1.693733631245806)

class MatrixTest(unittest.TestCase):

    """
    Class to test Matrix3
    """

    def __init__(self, *args, **kwargs):
        """Constructor, set up some data that is reused in many tests"""
        super(MatrixTest, self).__init__(*args, **kwargs)

    def test_constructor(self):
        """Test the constructor functionality"""
        m1 = Matrix3(Vector3(1, 0, 0), Vector3(1, 5, 0), Vector3(1, 0, -7))
        m2 = Matrix3()

        assert str(m1) == 'Matrix3((1.00, 0.00, 0.00), (1.00, 5.00, 0.00), (1.00, 0.00, -7.00))'
        assert str(m2) == 'Matrix3((1.00, 0.00, 0.00), (0.00, 1.00, 0.00), (0.00, 0.00, 1.00))'

    def test_maths(self):
        m1 = Matrix3(Vector3(1, 0, 0), Vector3(1, 5, 0), Vector3(1, 0, -7))
        m2 = Matrix3()

        assert m1 + m2 == Matrix3(Vector3(2, 0, 0), Vector3(1, 6, 0), Vector3(1, 0, -6))
        assert m1 - m2 == Matrix3(Vector3(0, 0, 0), Vector3(1, 4, 0), Vector3(1, 0, -8))
        assert m1 * 3 == Matrix3(Vector3(3, 0, 0), Vector3(3, 15, 0), Vector3(3, 0, -21))
        assert m1 * m1 == Matrix3(Vector3(1, 0, 0), Vector3(6, 25, 0), Vector3(-6, 0, 49))
        assert m1.transposed() == Matrix3(Vector3(1, 1, 1), Vector3(0, 5, 0), Vector3(0, 0, -7))

    def test_euler(self):
        '''check that from_euler() and to_euler() are consistent'''
        m = Matrix3()
        for r in range(-179, 179, 10):
            for p in range(-89, 89, 10):
                for y in range(-179, 179, 10):
                    m.from_euler(radians(r), radians(p), radians(y))
                    (r2, p2, y2) = m.to_euler()
                    v1 = Vector3(r, p, y)
                    v2 = Vector3(degrees(r2), degrees(p2), degrees(y2))
                    diff = v1 - v2
                    assert diff.length() < 1.0e-12

    def test_euler312(self):
        '''check that from_euler312() and to_euler312() are consistent'''
        m = Matrix3()
        for r in range(-89, 89, 10):
            for p in range(-179, 179, 10):
                for y in range(-179, 179, 10):
                    m.from_euler312(radians(r), radians(p), radians(y))
                    (r2, p2, y2) = m.to_euler312()
                    v1 = Vector3(r, p, y)
                    v2 = Vector3(degrees(r2), degrees(p2), degrees(y2))
                    diff = v1 - v2
                    assert diff.length() < 1.0e-12

    def test_matrixops(self):
        m1 = Matrix3(Vector3(1, 0, 0), Vector3(1, 5, 0), Vector3(1, 0, -7))

        m1.normalize()
        print(m1)
        assert m1.close(Matrix3(Vector3(0.2, -0.98, 0), Vector3(0.1, 1, 0), Vector3(0, 0, 1)), tol=1e-2)
        np.testing.assert_almost_equal(m1.trace(), 2.19115332535)

        m1.rotate(Vector3(0.2,-0.98,0))
        assert m1.close(Matrix3(Vector3(0.2,-0.98,0), Vector3(0.1,1,-0.3), Vector3(0.98,0.2,1)), tol=1e-2)

    def test_axisangle(self):
        axis = Vector3(0, 1, 0)
        angle = radians(45)

        m1 = Matrix3()
        m1.from_axis_angle(axis, angle)
        #print(m1)
        assert m1.close(Matrix3(Vector3(0.71, 0.00, 0.71),
                                         Vector3(0.00, 1.00, 0.00),
                                         Vector3(-0.71, 0.00, 0.71)), tol=1e-2)

    def test_two_vectors(self):
        '''test the from_two_vectors() method'''
        for i in range(100):
            v1 = Vector3(1, 0.2, -3)
            v2 = Vector3(random.uniform(-5, 5), random.uniform(-5, 5), random.uniform(-5, 5))
            m = Matrix3()
            m.from_two_vectors(v1, v2)
            v3 = m * v1
            diff = v3.normalized() - v2.normalized()
            (r, p, y) = m.to_euler()
            assert diff.length() < 0.001

class LinePlaneTest(unittest.TestCase):

    """
    Class to test Line and Plane classes
    """

    def __init__(self, *args, **kwargs):
        """Constructor, set up some data that is reused in many tests"""
        super(LinePlaneTest, self).__init__(*args, **kwargs)

    def test_plane(self):
        '''testing line/plane intersection'''
        plane = Plane(Vector3(0, 0, 0), Vector3(0, 0, 1))
        line = Line(Vector3(0, 0, 100), Vector3(10, 10, -90))
        p = line.plane_intersection(plane)
        assert p.close(Vector3(11.11, 11.11, 0.00), tol=1e-2)

if __name__ == '__main__':
    unittest.main()


text:
# -*- coding: utf-8 -*-
"""
Combination of
http://scipy-central.org/item/52/1/zplane-function
and
http://www.dsprelated.com/showcode/244.php
with my own modifications
"""

# Copyright (c) 2011 Christopher Felton
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# The following is derived from the slides presented by
# Alexander Kain for CS506/606 "Special Topics: Speech Signal Processing"
# CSLU / OHSU, Spring Term 2011.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
from matplotlib.pyplot import axvline, axhline
from collections import defaultdict

def zplane(z, p, filename=None):
    """Plot the complex z-plane given zeros and poles.
    """

    # get a figure/plot
    ax = plt.subplot(2, 2, 1)
    # TODO: should just inherit whatever subplot it's called in?

    # Add unit circle and zero axes
    unit_circle = patches.Circle((0,0), radius=1, fill=False,
                                 color='black', ls='solid', alpha=0.1)
    ax.add_patch(unit_circle)
    axvline(0, color='0.7')
    axhline(0, color='0.7')

    # Plot the poles and set marker properties
    poles = plt.plot(p.real, p.imag, 'x', markersize=9, alpha=0.5)

    # Plot the zeros and set marker properties
    zeros = plt.plot(z.real, z.imag,  'o', markersize=9,
             color='none', alpha=0.5,
             markeredgecolor=poles[0].get_color(), # same color as poles
             )

    # Scale axes to fit
    r = 1.5 * np.amax(np.concatenate((abs(z), abs(p), [1])))
    plt.axis('scaled')
    plt.axis([-r, r, -r, r])
#    ticks = [-1, -.5, .5, 1]
#    plt.xticks(ticks)
#    plt.yticks(ticks)

    """
    If there are multiple poles or zeros at the same point, put a
    superscript next to them.
    TODO: can this be made to self-update when zoomed?
    """
    # Finding duplicates by same pixel coordinates (hacky for now):
    poles_xy = ax.transData.transform(np.vstack(poles[0].get_data()).T)
    zeros_xy = ax.transData.transform(np.vstack(zeros[0].get_data()).T)

    # dict keys should be ints for matching, but coords should be floats for
    # keeping location of text accurate while zooming

    # TODO make less hacky, reduce duplication of code
    d = defaultdict(int)
    coords = defaultdict(tuple)
    for xy in poles_xy:
        key = tuple(np.rint(xy).astype('int'))
        d[key] += 1
        coords[key] = xy

    print(d)
    for key, value in d.items():
        if value > 1:
            x, y = ax.transData.inverted().transform(coords[key])
            plt.text(x, y,
                        r' ${}^{' + str(value) + '}$',
                        fontsize=13,
                        )

    d = defaultdict(int)
    coords = defaultdict(tuple)
    for xy in zeros_xy:
        key = tuple(np.rint(xy).astype('int'))
        d[key] += 1
        coords[key] = xy
    for key, value in d.items():
        if value > 1:
            x, y = ax.transData.inverted().transform(coords[key])
            plt.text(x, y,
                        r' ${}^{' + str(value) + '}$',
                        fontsize=13,
                        )

    if filename is None:
        plt.show()
    else:
        plt.savefig(filename)
        print( 'Pole-zero plot saved to ' + str(filename))

if __name__ == "__main__":
    from scipy.signal import (freqz, butter, bessel, cheby1, cheby2, ellip,
                              tf2zpk, zpk2tf, lfilter, buttap, bilinear, cheb2ord, cheb2ap
                              )
    from numpy import asarray, tan, array, pi, arange, cos, log10, unwrap, angle
    from matplotlib.pyplot import (stem, title, grid, show, plot, xlabel,
                                  ylabel, subplot, xscale, figure, xlim,
                                  margins)

#    # Cosine function
#    omega = pi/4
#    b = array([1.0, -cos(omega)])
#    a = array([1, -2*cos(omega), 1.0])

    b, a = butter(2, [0.06, 0.7], 'bandpass')

    # Get the poles and zeros
    z, p, k = tf2zpk(b, a)

    # Create zero-pole plot
    figure(figsize=(16, 9))
    subplot(2, 2, 1)
    zplane(z, p)
    grid(True, color='0.9', linestyle='-', which='both', axis='both')
    title('Poles and zeros')

    # Display zeros, poles and gain
    print( str(len(z)) + " zeros: " + str(z))
    print( str(len(p)) + " poles: " + str(p))
    print( "gain: " + str(k))

    # Impulse response
    index = arange(0,20)
    u = 1.0*(index==0)
    y = lfilter(b, a, u)
    subplot(2, 2, 3)
    stem(index,y)
    title('Impulse response')
    margins(0, 0.1)
    grid(True, color='0.9', linestyle='-', which='both', axis='both')
    show()

    # Frequency response
    w, h = freqz(b, a)
    subplot(2, 2, 2)
    plot(w/pi, 20*log10(abs(h)))
    xscale('log')

    title('Frequency response')
    xlabel('Normalized frequency')
    ylabel('Amplitude [dB]')
    margins(0, 0.1)
    grid(True, color = '0.7', linestyle='-', which='major', axis='both')
    grid(True, color = '0.9', linestyle='-', which='minor', axis='both')
    show()

    # Phase
    subplot(2, 2, 4)
    plot(w/pi, 180/pi * unwrap(angle(h)))
    xscale('log')
    xlabel('Normalized frequency')
    ylabel('Phase [degrees]')
    grid(True, color = '0.7', linestyle='-', which='major')
    grid(True, color = '0.9', linestyle='-', which='minor')
    show()

reason: import numpy,from numpy,from scipy


text:
# Faça um programa que peça para n pessoas a sua idade, ao final o programa devera verificar se média de idade da turma varia entre 0 e 25,
    # 26 e 60 e maior que 60; e então dizer se a turma é jovem, adulta ou idosa , conforme a media calculada.

import numpy as np

continuar = 1
lista_idade = []

while continuar != 2:
    idade = int(input('Digite a sua idade: '))
    lista_idade.append(idade)
    print()
    continuar = int(input('Você deseja continuar: 1 - Sim ou 2 - Não: '))
    print()
    while continuar not in [1, 2]:
        print('Informe uma seleção valida para o menu')
        continuar = int(input('Você deseja continuar: 1 - Sim ou 2 - Não: '))
        print()

media = np.mean(lista_idade)

if ((media >= 0) and (media <= 25)):
    print(f'A média foi {media:.2f} - Turma Jovem')

elif ((media > 25) and (media < 60)):
    print(f'A média foi {media:.2f} - Turma Adulta')

else:
    print(f'A média foi {media:.2f} - Turma Idosa')


text:
from sympy import simplify

x = simplify('((s) + (((n) - (s)) // (st)) % 10)')
print(str(x))

reason: from sympy


text:
import os
import argparse
import numpy as np
import h5py
from Q50_config import LoadParameters
from GPSReader import GPSReader
from GPSTransforms import IMUTransforms
from LidarTransforms import loadLDR
from pipeline_config import LANE_FILTER, PARAMS_TO_LOAD, OPT_POS_FILE
from LidarIntegrator import transform_points_in_sweep

'''
Essentially just pieces from LidarIntegrator except avoids
storing the data for all time steps in memory

Writes full point clouds for scan matching later
'''

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Convert ldr files to h5 files containing points')
    parser.add_argument('gps_file')
    parser.add_argument('ldr_file')
    parser.add_argument('h5_file')
    parser.add_argument('--no_transform', action='store_true')
    args = parser.parse_args()

    if not args.no_transform:
        gps_reader = GPSReader(args.gps_file)
        gps_data = gps_reader.getNumericData()
        #imu_transforms = IMUTransforms(gps_data)
        imu_transforms = np.load(OPT_POS_FILE)['data']

    params = LoadParameters(PARAMS_TO_LOAD)

    # FIXME Assuming that ldr file named after frame num
    fnum = int(os.path.splitext(os.path.basename(args.ldr_file))[0])

    data = loadLDR(args.ldr_file)
    if data.shape[0] == 0:
        print '%d data empty' % fnum
        raise

    # Filter
    dist = np.sqrt(np.sum(data[:, 0:3] ** 2, axis=1))
    if LANE_FILTER:
        data_filter_mask = (dist > 3) & \
                           (data[:, 3] > 40) & \
                           (np.abs(data[:, 1]) < 2.2) & \
                           (np.abs(data[:, 1]) > 1.2) & \
                           (data[:, 2] < -1.8) & \
                           (data[:, 2] > -2.5)
    else:
        data_filter_mask = (dist > 3) & \
                           (data[:, 2] > -5)

    filtered_data = data[data_filter_mask, :]

    if filtered_data.shape[0] == 0:
        print '%d data empty after filtering' % fnum
        # FIXME, hack, just include a single point
        data = data[0:1, :]
        #raise
    else:
        data = filtered_data

    pts = data[:, 0:3].transpose()

    if not args.no_transform:
        # Transform data into IMU frame at time t
        pts = np.vstack((pts, np.ones((1, pts.shape[1]))))
        T_from_l_to_i = params['lidar']['T_from_l_to_i']
        pts = np.dot(T_from_l_to_i, pts)

        # Microseconds till end of the sweep
        # TODO Switch everything to use transform_points_by_times
        times = data[:, 5]
        transform_points_in_sweep(pts, times, fnum, imu_transforms)

    pts = pts.transpose()

    # for exporting purposes
    pts_copy = np.array(pts[:, 0:3])
    pts_copy = np.column_stack((pts_copy, np.array(data[:, 3])))
    pts_copy = np.column_stack((pts_copy, fnum*np.ones((pts.shape[0], 1))))

    h5f = h5py.File(args.h5_file, 'w')
    dset = h5f.create_dataset('points', pts_copy.shape, dtype='f')
    dset[...] = pts_copy
    h5f.close()

max_stars_repo_name: sameeptandon/sail-car-log

max_issues_repo_name: sameeptandon/sail-car-log

max_forks_repo_name: sameeptandon/sail-car-log


text:
import re
from os.path import *

import cv2
import numpy as np
import torch.nn.functional as F
from PIL import Image

cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)

TAG_CHAR = np.array([202021.25], np.float32)

def read_flow_middlebury(fn):
    """
    Read .flo file in Middlebury format

    Parameters
    -----------
    fn : str
        Absolute path to flow file

    Returns
    --------
    flow : np.ndarray
        Optical flow map
    """
    # Code adapted from:
    # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy

    # WARNING: this will work on little-endian architectures (eg Intel x86) only!
    # print 'fn = %s'%(fn)
    with open(fn, "rb") as f:
        magic = np.fromfile(f, np.float32, count=1)
        if 202021.25 != magic:
            print("Magic number incorrect. Invalid .flo file")
            return None
        else:
            w = np.fromfile(f, np.int32, count=1)
            h = np.fromfile(f, np.int32, count=1)
            # print 'Reading %d x %d flo file\n' % (w, h)
            data = np.fromfile(f, np.float32, count=2 * int(w) * int(h))
            # Reshape data into 3D array (banda, columns, rows)
            return np.resize(data, (int(h), int(w), 2))

def read_flow_pfm(file):
    """
    Read optical flow from a .pfm file

    Parameters
    -----------
    file : str
        Path to flow file

    Returns
    --------
    flow : np.ndarray
        Optical flow map
    """

    file = open(file, "rb")

    color = None
    width = None
    height = None
    scale = None
    endian = None

    header = file.readline().rstrip()
    if header == b"PF":
        color = True
    elif header == b"Pf":
        color = False
    else:
        raise Exception("Not a PFM file.")

    dim_match = re.match(rb"^(\d+)\s(\d+)\s$", file.readline())
    if dim_match:
        width, height = map(int, dim_match.groups())
    else:
        raise Exception("Malformed PFM header.")

    scale = float(file.readline().rstrip())
    if scale < 0:  # little-endian
        endian = "<"
        scale = -scale
    else:
        endian = ">"  # big-endian

    data = np.fromfile(file, endian + "f")
    shape = (height, width, 3) if color else (height, width)

    data = np.reshape(data, shape)
    data = np.flipud(data)

    return data

def read_flow_png(filename):
    """
    Read optical flow from a png file.

    Parameters
    -----------
    filename : str
        Path to flow file

    Returns
    --------
    flow : np.ndarray
        Optical flow map

    valid : np.ndarray
        Valid flow map
    """
    flow = cv2.imread(filename, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_COLOR)
    flow = flow[:, :, ::-1].astype(np.float32)
    flow, valid = flow[:, :, :2], flow[:, :, 2]
    flow = (flow - 2**15) / 64.0
    return flow, valid

def write_flow(filename, uv, v=None):
    """Write optical flow to file.

    If v is None, uv is assumed to contain both u and v channels,
    stacked in depth.

    Parameters
    ----------
    filename : str
        Path to file
    uv : np.ndarray
        Optical flow
    v : np.ndarray, optional
        Optional second channel
    """

    # Original code by Deqing Sun, adapted from Daniel Scharstein.

    n_bands = 2

    if v is None:
        assert uv.ndim == 3
        assert uv.shape[2] == 2
        u = uv[:, :, 0]
        v = uv[:, :, 1]
    else:
        u = uv

    assert u.shape == v.shape
    height, width = u.shape
    f = open(filename, "wb")
    # write the header
    f.write(TAG_CHAR)
    np.array(width).astype(np.int32).tofile(f)
    np.array(height).astype(np.int32).tofile(f)
    # arrange into matrix form
    tmp = np.zeros((height, width * n_bands))
    tmp[:, np.arange(width) * 2] = u
    tmp[:, np.arange(width) * 2 + 1] = v
    tmp.astype(np.float32).tofile(f)
    f.close()

def read_image(file_name):
    """
    Read images from a variety of file formats

    Parameters
    -----------
    file_name : str
        Path to flow file

    Returns
    --------
    flow : np.ndarray
        Optical flow map
    """

    ext = splitext(file_name)[-1]

    if ext == ".png" or ext == ".jpeg" or ext == ".ppm" or ext == ".jpg":
        return Image.open(file_name)

    elif ext == ".bin" or ext == ".raw":
        return np.load(file_name)

    return []

def read_flow(file_name):
    """
    Read ground truth flow from a variety of file formats

    Parameters
    -----------
    file_name : str
        Path to flow file

    Returns
    --------
    flow : np.ndarray
        Optical flow map

    valid : None if .flo and .pfm files else np.ndarray
        Valid flow map
    """

    ext = splitext(file_name)[-1]

    if ext == ".flo":
        flow = read_flow_middlebury(file_name).astype(np.float32)
        return flow, None

    elif ext == ".pfm":

        flow = read_flow_pfm(file_name).astype(np.float32)

        if len(flow.shape) == 2:
            return flow, None
        else:
            return flow[:, :, :-1], None

    elif ext == ".png":
        return read_flow_png(file_name)

    return []

class InputPadder:
    """
    Class to pad / unpad the input to a network with a given padding

    Parameters
    -----------
    dims : tuple
        Dimensions of the input
    divisor : int
        Divisor to make the input evenly divisible by
    mode : str
        Padding mode
    """

    def __init__(self, dims, divisor=8, mode="sintel"):

        self.ht, self.wd = dims[-2:]
        pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor
        pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor

        if mode == "sintel":
            self._pad = [
                pad_wd // 2,
                pad_wd - pad_wd // 2,
                pad_ht // 2,
                pad_ht - pad_ht // 2,
            ]
        else:
            self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, 0, pad_ht]

    def pad(self, *inputs):
        """
        Pad the input

        Parameters
        -----------
        inputs : list
            List of inputs to pad

        Returns
        --------
        list
            Padded inputs
        """

        return [F.pad(x, self._pad, mode="replicate") for x in inputs]

    def unpad(self, x):
        """
        Unpad the input

        Parameters
        -----------
        x : torch.Tensor
            Input to unpad

        Returns
        --------
        torch.Tensor
            Unpadded input
        """

        ht, wd = x.shape[-2:]
        c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]

        return x[..., c[0] : c[1], c[2] : c[3]]

max_stars_repo_name: neu-vig/ezflow

max_issues_repo_name: neu-vig/ezflow

max_forks_repo_name: neu-vig/ezflow


text:
import os
import sys
import pickle
import numpy as np
from src.Initializers import Initializers
from src.ForwardProp import ForwardProp
from src.BackProp import BackProp
from src.helpers.learning_curves import LearningCurves

class Model:
    ForwardProp = ForwardProp
    BackProp = BackProp

    def __init__(self, layers_dims, initializer=Initializers.he):
        self.params = []
        self.layers_dims = layers_dims
        self.LearningCurves = None

        if layers_dims:
            self.init_params(initializer)

    def predict(self, X):
        """
        :return: probability distribution
        """
        AL, _ = self.ForwardProp.model_forward(X, self.params)
        AL_exps = np.exp(AL)

        return AL_exps / np.sum(AL_exps, axis=0)

    def train(self, X, Y,  X_valid=[], Y_valid=[], epochs=2000, learning_rate=0.001, print_cost=False):
        plot_every = 1
        self.LearningCurves = LearningCurves(learning_rate)
        self.LearningCurves.init_plot(plot_every)

        costs_train = []
        costs_valid = []
        for i in range(0, epochs):
            AL, caches = ForwardProp.model_forward(X, self.params)

            cost = self.cost(AL, Y)

            grads = self.BackProp.model_back_prop(AL, Y, caches)

            self.update_params(grads, learning_rate)

            # todo: allow X_valid,
            # todo: save cost/cost_valid
            if print_cost and i % plot_every == 0:
                if len(X_valid) and len(Y_valid):
                    AL_valid, _ = self.ForwardProp.model_forward(X_valid, self.params)
                    cost_valid = self.cost(AL_valid, Y_valid)
                    costs_valid.append(cost_valid)

                costs_train.append(cost)
                self.LearningCurves.update_plot(costs_train, i, costs_valid)

    def update_params(self, grads, learning_rate):
        L = len(self.params) // 2

        for l in range(L):
            self.params["W" + str(l + 1)] -= learning_rate * grads["dW" + str(l + 1)]
            self.params["b" + str(l + 1)] -= learning_rate * grads["db" + str(l + 1)]

    def forward_prop(self, X):
        return self.ForwardProp.model_forward(X, self.params)

    @staticmethod
    def cost(AL, Y):
        """
        Arguments:
        AL -- probability vector corresponding to your label predictions
        Y -- true "label" vector

        Returns:
        cost -- cross-entropy cost
        """
        assert AL.shape == Y.shape

        m = Y.shape[1]
        cost = -1 / m * np.sum(Y * np.log(AL) + (1 - Y) * np.log(1 - AL))
        cost = np.squeeze(cost)

        return cost

    def back_prop(self, AL, Y, caches):
        return self.BackProp.model_back_prop(AL, Y, caches)

    # params CRUD
    def load_params(self, path):
        try:
            with open(path, "rb") as f:
                self.params = pickle.load(f)
                self.update_layers_dims()
        except OSError as err:
            print(err)
            sys.exit()

    def save_params(self, path):
        with open(path, "wb") as f:
            pickle.dump(self.params, f)

    def init_params(self, initializer):
        if initializer:
            self.params = initializer(self.layers_dims)
            return

        self.params = initializer(self.layers_dims)

    # params CRUD - end

    def update_layers_dims(self):
        # init new layer dims with first layer
        self.layers_dims = [self.params['W' + str(1)].shape[1]]

        for i in range(1, len(self.params) // 2 + 1):
            layer_units = self.params['W' + str(i)].shape[0]
            self.layers_dims.append(layer_units)
        assert len(self.layers_dims) - 1 == len(self.params) // 2

max_stars_repo_name: BRadTone/deep-neural-network-classifier

max_issues_repo_name: BRadTone/deep-neural-network-classifier

max_forks_repo_name: BRadTone/deep-neural-network-classifier


text:
#!/usr/bin/env python3
# Copyright 2021 by Julian Nubert, Robotic Systems Lab, ETH Zurich.
# All rights reserved.
# This file is released under the "BSD-3-Clause License".
# Please see the LICENSE file that has been included as part of this package.
import click
import numpy as np
import torch
import yaml

import deploy.trainer

@click.command()
@click.option('--training_run_name', prompt='MLFlow name of the run',
              help='The name under which the run can be found afterwards.')
@click.option('--experiment_name', help='High-level training sequence name for clustering in MLFlow.',
              default="")
@click.option('--checkpoint', help='Path to the saved checkpoint. Leave empty if none.',
              default="")
def config(training_run_name, experiment_name, checkpoint):
    f = open('config/config_datasets.yaml')
    config = yaml.load(f, Loader=yaml.FullLoader)
    f = open('config/deployment_options.yaml')
    deployment_options = yaml.load(f, Loader=yaml.FullLoader)
    config.update(deployment_options)
    f = open('config/hyperparameters.yaml')
    network_hyperparameters = yaml.load(f, Loader=yaml.FullLoader)
    config.update(network_hyperparameters)

    # Default: load parameters from yaml
    parameters_exist = False

    # CLI Input
    ## Checkpoint for continuing training
    if checkpoint:
        ### Parameters from previous run?
        if 'parameters' in torch.load(checkpoint):
            print("\033[92m" +
                  "Found parameters in checkpoint of previous run! Setting part of parameters to those ones."
                  + "\033[0;0m")
            parameters_exist = True
        else:
            print("Checkpoint does not contain any parameters. Using those ones specified in the YAML files.")

    # Parameters that are set depending on whether provided in checkpoint
    if parameters_exist:
        loaded_config = torch.load(checkpoint)['parameters']
        ## Device to be used
        loaded_config["device"] = torch.device(config["device"])
        loaded_config["datasets"] = config["datasets"]
        for dataset in loaded_config["datasets"]:
            loaded_config[dataset]["training_identifiers"] = config[dataset]["training_identifiers"]
            loaded_config[dataset]["data_identifiers"] = loaded_config[dataset]["training_identifiers"]
        config = loaded_config
    # Some parameters are only initialized when not taken from checkpoint
    else:
        ## Device to be used
        config["device"] = torch.device(config["device"])
        for dataset in config["datasets"]:
            config[dataset]["data_identifiers"] = config[dataset]["training_identifiers"]
        ## Convert angles to radians
        for dataset in config["datasets"]:
            config[dataset]["vertical_field_of_view"][0] *= (np.pi / 180.0)
            config[dataset]["vertical_field_of_view"][1] *= (np.pi / 180.0)
        config["horizontal_field_of_view"][0] *= (np.pi / 180.0)
        config["horizontal_field_of_view"][1] *= (np.pi / 180.0)

    # Parameters that are always set
    if checkpoint:
        config["checkpoint"] = str(checkpoint)
    else:
        config["checkpoint"] = None
    ## Trainings run name --> mandatory
    config["training_run_name"] = str(training_run_name)
    config["run_name"] = config["training_run_name"]
    ## Experiment name, default specified in deployment_options.yaml
    if experiment_name:
        config["experiment"] = experiment_name
    ## Mode
    config["mode"] = "training"

    print("----------------------------------")
    print("Configuration for this run: ")
    print(config)
    print("----------------------------------")

    return config

if __name__ == "__main__":
    config = config(standalone_mode=False)
    trainer = deploy.trainer.Trainer(config=config)
    trainer.train()

max_stars_repo_name: leggedrobotics/DeLORA

max_issues_repo_name: leggedrobotics/DeLORA

max_forks_repo_name: leggedrobotics/DeLORA