def acceleration():  # calculating the accelerations
    a_x = np.zeros(N)
    a_y = np.zeros(N)
    P_2nd_virial = 0

    for i in range(N):
        for j in range(i + 1, N):
            # shortest distance between the class of images of two particles. each particle has a class of images due to periodic boundary conditions
            x_ij = math.remainder(x[i] - x[j], L)
            if x_ij < r_c:  # r_c = cutoff length
                y_ij = math.remainder(y[i] - y[j], L)
                if y_ij < r_c:
                    # the i_th and j_th particle are close enough to interact
                    r_ij = x_ij * x_ij + y_ij * y_ij
                    r_ij2 = r_ij * r_ij
                    r_ij6 = r_ij2 * r_ij2 * r_ij2
                    r_ij12 = r_ij6 * r_ij6
                    alpha = -2 * (-12 / r_ij12 + 6 / r_ij6) / r_ij2
                    U += 4 * (1 / r_ij12 - 1 / r_ij6)
                    a_x = alpha * x_ij
                    a_y = alpha * y_ij
                    P_2nd_virial += alpha * r_ij2
                    a_x[i] += a_x
                    a_x[j] -= a_x  # Newton's 3rd law
                    a_y[i] += a_y
                    a_y[j] -= a_y

    return a_x, a_y
def reduce_range(x):
    K = scipy.special.ellipk(k * k)
    xprime = math.remainder(x, 2 * K)
    n = 0.5 * (x - xprime) / K
    if abs(math.floor(math.remainder(n, 2) + 0.1)) > 0.5:
        return (xprime, -1, -1, 1)
    return (xprime, 1, 1, 1)
Example #3
0
def test_remainder():
    assert 10 % 4 == 2.0
    assert 12 % 3 == 0.0

    # New in version 3.7.
    assert remainder(10, 4) == 2.0
    assert remainder(12, 3) == 0.0
Example #4
0
File: range.py Project: tzhen/pyomo
    def _continuous_discrete_disjoint(cont, disc):
        # At this point, we know the ranges overlap (tested for at the
        # beginning of isdisjoint()
        d_lb = disc.start if disc.step > 0 else disc.end
        d_ub = disc.end if disc.step > 0 else disc.start
        if cont.start is None or (
                d_lb is not None and cont.start <= d_lb):
            return False
        if cont.end is None or (
                d_ub is not None and cont.end >= d_ub):
            return False

        EPS = NumericRange._EPS
        if cont.end - cont.start - EPS > abs(disc.step):
            return False
        # At this point, the continuous set is shorter than the discrete
        # step.  We need to see if the continuous set overlaps one of the
        # points, or lies completely between two.
        #
        # Note, taking the absolute value of the step is safe because we are
        # seeing if the continuous range overlaps a discrete point in the
        # underlying (unbounded) discrete sequence grounded by disc.start
        rStart = remainder(cont.start - disc.start, abs(disc.step))
        rEnd = remainder(cont.end - disc.start, abs(disc.step))
        return (
            (abs(rStart) > EPS or not cont.closed[0])
            and (abs(rEnd) > EPS or not cont.closed[1])
            and (rStart - rEnd > 0 or not any(cont.closed))
        )
Example #5
0
def isAutomorphic(inp):
    sqr = inp * inp
    while (inp != 0):
        if (math.remainder(inp, 10) != math.remainder(sqr, 10)):
            return False
        sqr = sqr // 10
        inp = inp // 10
    return True
Example #6
0
def range_it(first, last, step):
    is_integer = math.remainder(first, 1) < 1e-10 and math.remainder(
        last, 1) < 1e-10 and math.remainder(step, 1) < 1e-10
    n = 0
    while first + n * step <= last:
        yield first + n * step if not is_integer else int(first + n * step)
        n += 1
    return
Example #7
0
def eh_bissexto(ano):
    if math.remainder(ano, 400) == 0:
        return "True"
    elif math.remainder(ano, 100) == 0:
        return "False"
    elif ath.remainder(ano, 4) == 0:
        return "True"
    else:
        return "False"
Example #8
0
def eh_bissexto(ano):
    if math.remainder(ano, 400) == 0:
        return True
    elif math.remainder(ano, 100) == 0:
        return False
    elif math.remainder(ano, 4) == 0:
        return True
    else:
        return False
Example #9
0
    def convertToTitle(self, n):
        #letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

        letdic = {
            1: 'A',
            2: 'B',
            3: 'C',
            4: 'D',
            5: 'E',
            6: 'F',
            7: 'G',
            8: 'H',
            9: 'I',
            10: 'J',
            11: 'K',
            12: 'L',
            13: 'M',
            14: 'N',
            15: 'O',
            16: 'P',
            17: 'Q',
            18: 'R',
            19: 'S',
            20: 'T',
            21: 'U',
            22: 'V',
            23: 'W',
            24: 'X',
            25: 'Y',
            26: 'Z'
        }
        if n <= 26:
            return letdic[n]

        else:
            i = n % 26

            if i == 0:
                # when i is zero we are dealing with a multiple of 26
                n_r = math.remainder(n, 26)

                if n_r == 0:
                    nf = n / 26

            else:
                n_r = math.remainder(n, 26)

                n_i = (n - n_r) / 26

                nf = Solution().convertToTitle(n_i)

                nf += Solution().convertToTitle(n_r)
                # this was a test to see if recursion was an applicable approach to this solution

        return nf
Example #10
0
def kahio_timer(*args):
    """
    Sends the standup message from the given u_id

    Parameters:
        args[0] (u_id(int)) : The u_id that standup will be sent from
        args[1] (channel_id(int)) : The channel that the message will be sent to
        args[2] (time_remaining(int)) : The time that kahio has remaining

    Returns:
    """
    #Make a message using the u_id from the user that started the KAHIO game
    new_message_id = data.make_message_id()
    new_message = {}
    new_message["message"] = "The kahoi game has " + str(args[2]) + " seconds remaining"
    new_message["u_id"] = args[0]
    new_message["time_created"] = datetime.datetime.now().replace().timestamp()
    new_message["message_id"] = new_message_id
    new_message["reacts"] = [
        {
            "react_id": 1,
            "u_ids": []
        }
    ]

    if args[2] <= 0:
        #If the timer has finished it will print the end message
        data.end_kahio_game(args[1])
        send_kahio_score(args[1], new_message)
        return

    #Inputs the timing message into the channel messages
    data.add_message(new_message, args[1])

    #Stores how long the multithreading wait will be and the time left
    #after the multithreading ends
    time_remaing = args[2]
    time_interval = 0

    if time_remaing <= 5:
        time_interval = 1
    elif math.remainder(time_remaing, 5) == 0:
        time_interval = 5
    else:
        time_interval = int(math.remainder(time_remaing, 5))

    #Removes how long the timer will wait from the time remaining
    time_remaing -= time_interval

    #Calls this function again after time_interval amount of time
    timer_class = threading.Timer(time_interval, kahio_timer, [args[0], args[1], time_remaing])
    timer_class.start()

    #Stores new timer_class so the timer can still be stopped
    data.kahio_update_timer_class(args[1], timer_class)
Example #11
0
def gold_conversion(units: int):
    """This function receives an int and converts it to gold units.
    For example: 18000005 = 1800g 00s 05c"""
    if math.isnan(units):
        raise TypeError("Function 'gold_conversion' expected a number.")
    copper = int(math.remainder(units, 100))
    units = math.floor(units / 100)
    silver = int(math.remainder(units, 100))
    gold = int(math.floor(units / 100))
    result = '' + str(gold) + 'g ' + str(silver) + 's ' + str(copper) + 'c'
    return result
Example #12
0
def my_can_collide(a, b):
    # ap, av, aa = a
    # bp, bv, ba = b

    ans = None
    for (ap, av, aa), (bp, bv, ba) in zip(zip(*a), zip(*b)):
        kc = ap - bp
        kb = av - bv
        ka = aa - ba

        if ka == 0:
            # print("Kicking the ball to sympy")
            return sympy_can_colide(a, b)

        # print(kb)
        # print(ka)
        if (kb * kb - 4 * ka * kc) < 0:
            return None

        x1 = (-kb + math.sqrt(kb * kb - 4 * ka * kc)) / 2 * ka
        dw1 = math.remainder((-kb + math.sqrt(kb * kb - 4 * ka * kc)), 2 * ka)
        x2 = (-kb - math.sqrt(kb * kb - 4 * ka * kc)) / 2 * ka
        dw2 = math.remainder((-kb - math.sqrt(kb * kb - 4 * ka * kc)), 2 * ka)

        if abs(dw1) < 0.00001:
            if ans is None:
                ans = int(x1)

            if ans != int(x1):
                return None

            # print("YE")
            # print(x1)
            # print(dw1)
        elif abs(dw2) < 0.00001:
            if ans is None:
                ans = int(x1)

            if ans != int(x1):
                return None
        else:
            return None

        # print(x1, dw1)
        # print(x2, dw2)

        # print("HERE")

    return ans
Example #13
0
def modi(args):
    global R
    (x, _, z) = __get_index(args)
    l = ((args >> 15 & 0x1) * 0xFFFF << 16 | args >> 0 & 0xFFFF) & 0xFFFFFFFF
    jmp = 0
    sw_int = False
    msg = None
    PC = R[29]
    try:
        signrx = math.copysign(1, __twos_comp(R[x]))
        signl = math.copysign(1, __twos_comp(l))
        reg = 0x0
        if signl == signrx:
            if signl < 0 and signrx < 0:
                reg = math.remainder(R[x], l) if z != 0 else R[z]
            else:
                reg = R[x] % l
        elif signl < 0:
            reg = math.remainder(R[x], __twos_comp(l)) if z != 0 else R[z]
        elif signrx < 0:
            reg = math.remainder(__twos_comp(R[x]), l) if z != 0 else R[z]

        R[z] = int(reg) + 2**32 & 0xFFFFFFFF if z != 0 else R[z]
        R[31] = R[31] | 0x40 if R[z] == 0 else R[31] & ~(1 << 0x06)
        R[31] &= ~(1 << 0x03)
        __incaddr()
    except ZeroDivisionError:
        R[z] = 0x0
        if (R[31] >> 1 & 0x1) == 1:
            __save_context()
            msg = '\n[SOFTWARE INTERRUPTION]'
            sw_int = True
            PC = R[29]
            R[27] = R[29]
            R[26] = 0
            R[29] = 0x8
            jmp = ((R[29] - PC) // 4) - 1
        else:
            __incaddr()
    except Exception:
        __stdout('[Error ?] Can not resolve for library imports')
    R[31] = R[31] | 0x20 if args >> 0 & 0xFFFF == 0 else R[31] & ~(1 << 0x05)
    ins = 'modi {},{},{}'.format(__r(z), __r(x), __twos_comp(l)).ljust(25)
    res = '{}={}%{}={}'.format(__r(z, True), __r(x, True), __hex(l),
                               __hex(R[z]))
    cmd = '{}:\t{}\t{},SR={}'.format(__hex(PC), ins, res, __hex(R[31]))
    if sw_int: cmd += msg
    return cmd, jmp
def build_sa(string):  #build the suffix arrays.

    #we will use the Skew Algorithm to construct the suffix array

    #we will divide the string into 3 major groups:

    #1: (index mod 3 = 0)
    #2: (index  mod 3 = 1)
    #3: (index mod 3 = 2)

    #then we will handle recursively (index mod 3 = 1) and (index mod 3 = 2) groups
    #merge (index mod 3 = 0) group at the very end

    ########################################################################

    #first we need to pad the string so it has (len mod 3 =0)
    while (not ma.remainder(len(string), 3) == 0):
        string += "&"

    print(string, len(string))
    #then we loop to generate the groups

    suffix_map0 = {}
    array0 = []
    suffix_map12 = {}
    array12 = []

    for i in range(len(string)):

        if int(ma.remainder(i, 3)) == 0:

            triple = string[i:i + 3]
            suffix_map0[triple] = i
            array0.append(triple)

        else:

            triple = string[i:i + 3]
            suffix_map12[triple] = i
            array12.append(triple)

    #now use radix sort to sort array12

    array12 = radix_sort(array12)

    #print("radix sort aftermath: " + str(array12))

    pass
Example #15
0
    def __init__(self, in_size, out_classes: int, channels: list,
                 pool_every: int, hidden_dims: list):
        """
        :param in_size: Size of input images, e.g. (C,H,W).
        :param out_classes: Number of classes to output in the final layer.
        :param channels: A list of of length N containing the number of
            (output) channels in each conv layer.
        :param pool_every: P, the number of conv layers before each max-pool.
        :param hidden_dims: List of of length M containing hidden dimensions of
            each Linear layer (not including the output layer).
        """
        super().__init__()
        assert channels and hidden_dims

        self.in_size = in_size
        self.out_classes = out_classes
        self.channels = channels
        self.pool_every = pool_every
        self.hidden_dims = hidden_dims

        self.P = self.pool_every
        self.N = len(self.channels)
        self.M = len(self.hidden_dims)
        self.quotient = int(self.N / self.P)
        self.reminder = int(math.fabs(math.remainder(self.N, self.P)))

        self.feature_extractor = self._make_feature_extractor()
        self.classifier = self._make_classifier()
Example #16
0
File: range.py Project: tzhen/pyomo
    def __contains__(self, value):
        # NumericRanges must hold items that are comparable to ints
        if value.__class__ not in self._types_comparable_to_int:
            try:
                if value.__class__(0) != 0:
                    return False
                else:
                    self._types_comparable_to_int.add(value.__class__)
            except:
                return False

        if self.step:
            _dir = math.copysign(1, self.step)
            return (
                (value - self.start) * math.copysign(1, self.step) >= 0
                and (self.end is None or
                     _dir*(self.end - self.start) >= _dir*(value - self.start))
                and abs(remainder(value - self.start, self.step)) <= self._EPS
            )
        else:
            return (
                self.start is None
                or ( value >= self.start if self.closed[0] else
                     value > self.start )
            ) and (
                self.end is None
                or ( value <= self.end if self.closed[1] else
                     value < self.end )
            )
Example #17
0
    def followPath(handle, path, followDist, left_motor_handle, right_motor_handle):
        d = 0.0886 / 2  #distance between the wheels
        r = 0.024738  #radius of the wheel
        epsilon = followDist # distance threshold

        for pos, rot in path:
            robot_pos, robotRot = getAbsolutePose(handle, 'block')
            print(math.dist(pos, robot_pos))
            while math.dist(pos[:-1], robot_pos[:-1]) > epsilon:

                angle_diff = robotRot[2] - math.atan2(pos[1] - robot_pos[1], pos[0] - robot_pos[0])
                angle_diff -= math.pi / 2  # robot rotation offset
                angle_diff = math.remainder(angle_diff, 2 * math.pi)  # bound between [-pi,pi]
                if abs(angle_diff) > math.pi / 16:
                    v_des = 0.02
                    w_des = 0.8
                else:
                    v_des = 0.08
                    w_des = 0.8
                w_des *= angle_diff  # total desired angular velocity of the robot
                v_right = v_des - d * w_des
                v_left = v_des + d * w_des
                W_right = v_right / r  # angular velocity of the right wheel of the robot
                W_left = v_left / r  # angular velocity of the left wheel of the robot
                res = sim.simxSetJointTargetVelocity(clientID, right_motor_handle, W_right, sim.simx_opmode_oneshot)
                res = sim.simxSetJointTargetVelocity(clientID, left_motor_handle, W_left, sim.simx_opmode_oneshot)
                # iterate time step
                time.sleep(0.025)
                robot_pos, robotRot = getAbsolutePose(handle, 'block')

        res = sim.simxSetJointTargetVelocity(clientID, right_motor_handle, 0, sim.simx_opmode_oneshot)
        res = sim.simxSetJointTargetVelocity(clientID, left_motor_handle, 0, sim.simx_opmode_oneshot)
Example #18
0
def process_arithmetic(op1, op2, op_type):
    """ Turns string expression into arithmetic operation"""
    ASSERT_MSG(
        type(op1) is not str and type(op2) is not str,
        'operands have strings %s, %s' % (op1, op2))
    if op_type == '*':
        result = op1 * op2
    elif op_type == '/':
        result = op1 / op2
    elif op_type == '//':
        result = op1 // op2
    elif op_type == '%':
        result = math.remainder(op1, op2)
    elif op_type == '-':
        result = int(op1 - op2)
    elif op_type == '+':
        result = int(op1 + op2)
    elif op_type == 'log2':
        result = int(math.ceil(math.log2(op1)))
    elif op_type == 'round':
        result = int(round(op1 / op2,
                           0))  # round according to the first decimal
    elif op_type == 'round_up':
        result = int(math.ceil(op1 / op2))
    else:
        result = None
        ERROR_CLEAN_EXIT('wrong op_type')
    return result
Example #19
0
def sunrise_sunset(latitude, longitude, year, month, day):
    """
    Calculate the sunrise and sunset times for the given location and date
    """
    noon = datetime(year, month, day, 12, 0, 0,
                    tzinfo=timezone.utc).timestamp()
    mean_solar_noon = (noon / 86400 + _UNIX_EPOCH_JULIAN_DAY) - longitude / 360
    solar_mean_anomaly = remainder(
        357.5291 + 0.98560028 * (mean_solar_noon - _J2000), 360)
    if solar_mean_anomaly < 0:
        solar_mean_anomaly += 360
    anomaly_in_rad = solar_mean_anomaly * _DEGREE
    anomaly_sin = sin(anomaly_in_rad)
    anomaly2_sin = sin(2 * anomaly_in_rad)
    anomaly3_sin = sin(3 * anomaly_in_rad)
    equation_of_center = 1.9148 * anomaly_sin + \
        0.02 * anomaly2_sin + 0.0003 * anomaly3_sin
    argument_of_perihelion = 102.93005 + 0.3179526 * \
        (mean_solar_noon - _J2000) / 36525
    ecliptic_longitude = (solar_mean_anomaly + equation_of_center + 180 +
                          argument_of_perihelion) % 360
    solar_transit = mean_solar_noon + \
        (0.0053 * sin(solar_mean_anomaly * _DEGREE) -
         0.0069 * sin(2 * ecliptic_longitude * _DEGREE))
    declination = asin(sin(ecliptic_longitude * _DEGREE) * 0.39779) / _DEGREE
    latitude_rad = latitude * _DEGREE
    declination_rad = declination * _DEGREE
    hour_angle = acos((-0.01449 - sin(latitude_rad) * sin(declination_rad)) /
                      (cos(latitude_rad) * cos(declination_rad))) / _DEGREE
    frac = hour_angle / 360
    sunrise = solar_transit - frac
    sunset = solar_transit + frac
    return _julian_to_unix(sunrise), _julian_to_unix(sunset)
Example #20
0
    def turn_towards_target(self, angle):
        current_yaw = get_yaw_from_pose(self.current_pose.pose.pose)

        # convert angle to radian value in [-pi, pi]
        angle = math.remainder(angle, 2 * np.pi)

        destination_yaw = current_yaw + angle
        if destination_yaw > np.pi:
            destination_yaw -= (2 * np.pi)
        elif destination_yaw < -np.pi:
            destination_yaw += (2 * np.pi)

        r = rospy.Rate(60)
        # turn until we face within 1 degree of destination angle
        while abs(
                get_yaw_from_pose(self.current_pose.pose.pose) -
                destination_yaw) > (np.pi / 180):
            # turn pi/12 rad/sec
            turn_msg = Twist()
            turn_vel = np.sign(destination_yaw - get_yaw_from_pose(
                self.current_pose.pose.pose)) * (np.pi / 12)
            turn_msg.angular = Vector3(0, 0, turn_vel)
            self.movement_pub.publish(turn_msg)
            r.sleep()
            print("{0}/{1}: {2}".format(
                str(get_yaw_from_pose(self.current_pose.pose.pose)),
                str(destination_yaw),
                str(
                    abs(
                        get_yaw_from_pose(self.current_pose.pose.pose) -
                        destination_yaw))))

        # Halt
        self.movement_pub.publish(Twist())
def collisionIndicator(egoPose, egoPoly, objPose, objPoly):
    """
    Indicator function for collision between ego vehicle and moving object
    Param:
        egoPose: ego vehicle
        objPose: pose of object
    Return:
        col_indicator: (float) collision indicator between two object
    """
    dMean = np.array([egoPose.x_m - objPose.x_m, egoPose.y_m - objPose.y_m])
    dCov = egoPose.covUtm + objPose.covUtm
    diff_yaw = abs(egoPose.yaw_rad - objPose.yaw_rad)
    col_indicator = 0

    # handle parallel and orthogonal case
    if abs(math.remainder(diff_yaw, np.pi / 2)) < param._COLLISION_ORTHO_THRES:
        poly, bound = gaussian.minkowskiSumOrthogonal(egoPoly, objPoly)
        col_indicator = collisionIndicatorComputeSimple(bound, dMean, dCov)

    # handle general case
    else:
        poly, bound = gaussian.minkowskiSum(egoPoly, objPoly)
        col_indicator = collisionIndicatorCompute(poly=poly,
                                                  bound=bound,
                                                  dMean=dMean,
                                                  dCov=dCov)
    return col_indicator
Example #22
0
def Simpson(fcn, a, b, npoints=21):

    if a > b:
        print(" Incorrect bounds")
        return None

    if math.remainder(npoints, 2) == 0:
        npoints += 1

    dt = (b - a) / (npoints - 1)
    x = [0] * npoints

    for i in range(len(x)):
        x[i] = a + i * dt

    I = 0

    for i in range(0, npoints):
        if i == 0:
            I += fcn(x[i])
        elif i == npoints - 1:
            I += fcn(x[i])
            break
        elif i % 2 == 0:
            I += 2 * fcn(x[i])
        elif i % 2 == 1:
            I += 4 * fcn(x[i])

    I = dt * I / 3

    return I
Example #23
0
    def __contains__(self, value):
        # NumericRanges must hold items that are comparable to ints
        if value.__class__ not in self._types_comparable_to_int:
            # Special case: because numpy is fond of returning scalars
            # as length-1 ndarrays, we will include a special case that
            # will unpack things that look like single element arrays.
            try:
                # Note: trap "value[0] is not value" to catch things like
                # single-character strings
                if hasattr(value, '__len__') and hasattr(value, '__getitem__') \
                   and len(value) == 1 and value[0] is not value:
                    return value[0] in self
            except:
                pass
            # See if this class behaves like a "normal" number: both
            # comparable and creatable
            try:
                if not (bool(value - 0 > 0) ^ bool(value - 0 <= 0)):
                    return False
                elif value.__class__(0) != 0 or not value.__class__(0) == 0:
                    return False
                else:
                    self._types_comparable_to_int.add(value.__class__)
            except:
                return False

        if self.step:
            _dir = math.copysign(1, self.step)
            _from_start = value - self.start
            return (0 <= _dir * _from_start <= _dir * (self.end - self.start)
                    and abs(remainder(_from_start, self.step)) <= self._EPS)
        else:
            return (value >= self.start if self.closed[0] else value >
                    self.start) and (value <= self.end
                                     if self.closed[1] else value < self.end)
Example #24
0
def standard_env_ext():
    env = standard_env()

    def integer_rule(x, y, ret):
        if not isinstance(x, int) or not isinstance(y, int):
            return ret

        return int(ret)

    def quotient(x, y):
        r = x / y

        return math.ceil(r) if r <= 0 else math.floor(r)

    env.update({
        'even?':
        lambda x: x % 2 == 0,
        'odd?':
        lambda x: x % 2 == 1,
        'quotient':
        lambda x, y: integer_rule(x, y, quotient(x, y)),
        'modulo':
        op.mod,
        'remainder':
        lambda x, y: integer_rule(x, y, math.remainder(x, y)),
    })
    return env
Example #25
0
    def readTemp(self, dt=1, pwr=0):

        if self.mode == 'sin':
            period = 20  # period in seconds
            amplitude = 5  # AC amplitude
            base = 30  # DC amplitude

            phase = math.remainder(time.time(), period) / period
            value = math.sin(2 * math.pi * phase)

            result = base + amplitude * value
            self._temp = result
            return result
        elif self.mode == 'kettle':
            #temp_gain = pwr * 3500 * dt / (self.cp * self.volume)
            heat_gain = 0.01 * pwr * 3500 * dt * self.time_factor  # Joule
            #temp_loss = self.loss_factor * (self._temp - self.t_air) * dt / (self.cp)
            heat_loss = self.loss_factor * (self._temp -
                                            self.t_air) * dt * self.time_factor
            delta_temp = (heat_gain - heat_loss) / (self.cp * self.volume)
            print('delta temp = ', delta_temp)
            #temp = self._temp + temp_gain - temp_loss
            temp = self._temp + delta_temp
            #print('temp_gain = ', temp_gain)
            #print('temp_loss = ', temp_loss)
            self._temp = temp
            return temp
        else:
            raise ValueError('Unknown mode: ', self.mode)
Example #26
0
    def turn_towards_target(self, angle):
        #wait for first pose
        while (not self.seen_first_pose):
            time.sleep(1)

        current_yaw = get_yaw_from_pose(self.current_pose.pose.pose)

        # convert angle to radian value in [-pi, pi]
        angle = math.remainder(angle, 2 * np.pi)
        destination_yaw = current_yaw + angle
        if destination_yaw > np.pi:
            destination_yaw = -np.pi + (destination_yaw - np.pi)

        r = rospy.Rate(60)
        # turn until we face within 1 degree of destination angle
        while abs(
                get_yaw_from_pose(self.current_pose.pose.pose) -
                destination_yaw) > (np.pi / 180):
            # turn pi/16 rad/sec
            turn_msg = Twist()
            turn_vel = np.sign(destination_yaw - get_yaw_from_pose(
                self.current_pose.pose.pose)) * (np.pi / 16)
            turn_msg.angular = Vector3(0, 0, turn_vel)
            self.movement_pub.publish(turn_msg)
            r.sleep()
        # Halt
        self.movement_pub.publish(Twist())
def define_subregions(bed_length, num_subregions):
    """ Define subregion list for model stream.
    

    Keyword arguments:
    bed_length -- The length of the model bed.
    subregions -- The number of subregions to create.

    Returns:
    subregions_arr -- The np array of Subregions

    """
    # TODO: Catch failure of assertion
    assert (math.remainder(bed_length, num_subregions) == 0)

    subregion_length = bed_length / num_subregions
    left_boundary = 0
    subregions_arr = []
    for region in range(num_subregions):
        right_boundary = left_boundary + subregion_length
        subregion = Subregion(f'subregion_{region}', left_boundary,
                              right_boundary)
        left_boundary = right_boundary

        subregions_arr.append(subregion)

    return subregions_arr
Example #28
0
    def run(self, n_steps: int):
        # Mark integrator as running
        self.running = True

        # We want to catch and print all exceptions except for the KeyboardInterrupt.
        try:
            # Check that the target time step of all discrete modules is integer
            # divisible by the integrator time step.
            # Set the module clock divider.
            for module in self.simulation.discrete_modules:
                if not (remainder(module.target_time_step, self.h) < 1e-8):
                    raise SimulationError(
                        f"Discreet module '{module.__class__.__name__}' "
                        f"target time step is not an integer multiple of the integrator time step."
                    )
                else:
                    module.clock_divider = round(module.target_time_step /
                                                 self.h)

            # Miscellaneous stuff that needs to be set before integrating.
            self.simulation.logging.reset(n_steps)
            t0 = self.simulation.states.t
            self.must_differentiate = self.simulation.states.get_differentiation_y(
            ) is not None

            # Previous step states.
            self.k: Deque[Union[None, float]] = deque([None, None, None, None])
            self.previous_step_t1 = self.simulation.states.t
            self.previous_step_y1 = self.simulation.states.get_y()

            # Reset the integrator, this clears the integrator history
            # and switches to the RK4 for the first few steps.
            # The `reset()` function can also be used by modules to
            # reset the history in case of a significant discrete event.
            self.reset()

            # Integrate
            last_step_idx = 0
            for step_idx in range(n_steps):
                last_step_idx = step_idx
                if not self.running:
                    break
                t = t0 + (step_idx + 1) * self.h
                self.run_single_step(step_idx, t, False)

            # Run one last step.
            last_step_idx += 1
            t = t0 + (last_step_idx + 1) * self.h
            self.run_single_step(last_step_idx, t, True)
        except KeyboardInterrupt:
            raise
        except:
            traceback.print_exc()
        finally:
            # Finish integration
            self.running = False
            for module in self.simulation.modules:
                module.run_end()
            return self.simulation.logging.finish()
Example #29
0
 def test_remainder(self):
     import math
     assert math.remainder(3, math.pi) == 3 - math.pi
     assert math.remainder(-3, math.pi) == math.pi - 3
     assert math.remainder(3, -math.pi) == 3 - math.pi
     assert math.remainder(4, math.pi) == 4 - math.pi
     assert math.remainder(6, math.pi) == 6 - 2 * math.pi
     assert math.remainder(3, math.inf) == 3
     assert math.remainder(3, -math.inf) == 3
     assert math.isnan(math.remainder(3, math.nan))
     assert math.isnan(math.remainder(math.nan, 3))
     raises(ValueError, math.remainder, 3, 0)
     raises(ValueError, math.remainder, math.inf, 3)
Example #30
0
def aLtCaSe(s):
    foo = ''
    for pos in range(len(s)):
        if math.remainder(pos,2)==0:
            foo = foo+str.lower(s[pos])
        else:
            foo = foo+str.upper(s[pos])
    return foo