示例#1
0
def _createBox(proxy, size, colour, moiScale, withMesh):
    """
    Private function.
    Use createBox() or createArticulatedBox() instead.
    """

    # Mesh and cdps will be set manually
    proxy.meshes = None
    proxy.cdps = None

    # Compute box moi
    size = PyUtils.toVector3d(size)
    proxy.moi = MathLib.Vector3d(
        size.y * size.y + size.z * size.z,
        size.x * size.x + size.z * size.z,
        size.x * size.x + size.y * size.y,
    ) * 1.0 / 12.0 * proxy.mass * moiScale

    box = proxy.createAndFillObject()

    cdp = Physics.BoxCDP()
    halfSize = PyUtils.toVector3d(size) * 0.5

    cdp.setPoint1(MathLib.Point3d(halfSize * -1))
    cdp.setPoint2(MathLib.Point3d(halfSize))

    box.addCollisionDetectionPrimitive(cdp)

    if withMesh:
        mesh = Mesh.createBox(size=size, colour=colour)
        box.addMesh(mesh)

    return box
示例#2
0
    def load(self):
        assert not self._loaded, "Cannot load scenario twice!"

        self._loaded = True

        # Create the rigid bodies for the main staircase
        orientation = PyUtils.angleAxisToQuaternion((self._angle, (0, 1, 0)))
        size = MathLib.Vector3d(self._staircaseWidth, self._riserHeight,
                                self._threadDepth)
        pos = PyUtils.toPoint3d(self._position) + MathLib.Vector3d(
            0, -self._riserHeight / 2.0, 0)
        delta = MathLib.Vector3d(size)
        delta.x = 0
        delta = orientation.rotate(delta)
        for i in range(self._stepCount):
            box = PyUtils.RigidBody.createBox(size,
                                              pos=pos + delta * (i + 1),
                                              locked=True,
                                              orientation=orientation)
            Physics.world().addRigidBody(box)

        # Create the rigid bodies for both ramps
        rampHeights = (self._leftRampHeight, self._rightRampHeight)

        deltaRamp = MathLib.Vector3d(self._staircaseWidth / 2.0, 0, 0)
        deltaRamp = orientation.rotate(deltaRamp)
        deltaRamps = (deltaRamp, deltaRamp * -1)
        for deltaRamp, rampHeight in zip(deltaRamps, rampHeights):
            if rampHeight is None: continue
            deltaRamp.y = rampHeight / 2.0
            box = PyUtils.RigidBody.createBox((0.02, rampHeight, 0.02),
                                              pos=pos + deltaRamp + delta,
                                              locked=True,
                                              orientation=orientation)
            Physics.world().addRigidBody(box)
            box = PyUtils.RigidBody.createBox(
                (0.02, rampHeight, 0.02),
                pos=pos + deltaRamp + (delta * self._stepCount),
                locked=True,
                orientation=orientation)
            Physics.world().addRigidBody(box)
            deltaRamp.y = rampHeight
            rampOrientation = orientation * PyUtils.angleAxisToQuaternion(
                (math.atan2(self._riserHeight, self._threadDepth), (-1, 0, 0)))
            rampLen = self._stepCount * math.sqrt(
                self._riserHeight * self._riserHeight +
                self._threadDepth * self._threadDepth)
            box = PyUtils.RigidBody.createBox(
                (0.04, 0.02, rampLen),
                pos=pos + deltaRamp + (delta * ((self._stepCount + 1) * 0.5)),
                locked=True,
                orientation=rampOrientation)
            Physics.world().addRigidBody(box)
示例#3
0
def createBox(size=(1, 1, 1), position=(0, 0, 0), colour=(0.6, 0.6, 0.6)):
    """
    Creates the mesh for a box having the specified size and a specified position.
    The size should be a 3-tuple (xSize, ySize, zSize).
    The position should be a 3-tuple.
    Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A)
    """

    size = PyUtils.toVector3d(size)
    position = PyUtils.toPoint3d(position)
    vertices = []
    delta = MathLib.Vector3d()
    for repeat in range(3):
        for x in (-0.5, 0.5):
            delta.x = size.x * x
            for y in (-0.5, 0.5):
                delta.y = size.y * y
                for z in (-0.5, 0.5):
                    delta.z = size.z * z
                    vertices.append(position + delta)

    faces = [
        (0, 1, 3, 2),
        (5, 4, 6, 7),  # YZ Faces
        (9, 13, 15, 11),
        (12, 8, 10, 14),  # XY Faces
        (18, 19, 23, 22),
        (17, 16, 20, 21)
    ]  # XZ Faces

    return create(vertices, faces, colour)
示例#4
0
文件: simple.py 项目: sethtroisi/OEIS
def single(d):
    n, factors = d
    # merge some of the primes together
    for grouping in partition(factors):
        #    print ("\tGrouping:", grouping)
        joined = list(map(MathLib.product, grouping))

        counts = Counter(joined)
        modified_sum_of_div = MathLib.product(
            (p**(1 + c) - 1) // (p - 1) for p, c in counts.items())
        if 2 * n == modified_sum_of_div:
            print(n, "\t", factors, grouping)
            return n
    return None
示例#5
0
    def __init__(self,
                 controller,
                 jointName,
                 componentIndex,
                 type='unknown',
                 posInChild=MathLib.Point3d(),
                 oppositeJointName=None,
                 reverseOppositeJoint=False,
                 minValue=-1000,
                 maxValue=1000):
        """
        Creates a handle that can be used to access a specific component in a controller in a standard (direct) way.
        type should be 'circular', 'reverseCircular', 'perpendicular', 'reversePerpendicular' or 'unknown' to indicate how the handle behaves 
        posInChild should be of type MathLib.Point3d
        reverse should be True if the handle works in a reverse way (i.e. going clockwise increase the angle (?))
        oppositeJointName should be the name of the corresponding joint on the other stance.
        reverseOppositeJoint should be True if the opposite joint sign is different
        """

        self._controller = controller
        self._jointName = jointName
        trajectory = controller.getState(0).getTrajectory(
            jointName).getTrajectoryComponent(
                componentIndex).getBaseTrajectory()

        self._oppositeJointName = oppositeJointName
        self._posInChild = posInChild
        if oppositeJointName is not None:
            oppositeTrajectory = controller.getState(0).getTrajectory(
                oppositeJointName).getTrajectoryComponent(
                    componentIndex).getBaseTrajectory()
        else:
            oppositeTrajectory = None
        self._type = type

        super(Handle, self).__init__(trajectory, oppositeTrajectory,
                                     reverseOppositeJoint, minValue, maxValue)
示例#6
0
import MathLib

x = MathLib.Vector3d()
x.setValues(10, 0.44, -132)
print "x = ",
x._print()
y = MathLib.Vector3d()
y.setValues(3, 11, 2)
print "y = ",
y._print()
x.addScaledVector(y, 0.5)
print "x + 0.5y = ",
x._print()
示例#7
0
文件: simple.py 项目: sethtroisi/OEIS
import MathLib
from collections import Counter
from tqdm import tqdm
import multiprocessing

print("Factoring")
factors = MathLib.sieveOfFactors(10**5)
print("Factored!")

# Max factors is ~20 (2^20), so number of partition is small (674)


def partition(values):
    if len(values) == 0:
        return

    if len(values) == 1:
        yield ((values[0], ), )
        return

    first, *rest = values
    for smaller in partition(rest):
        for n, subset in enumerate(smaller):
            yield smaller[:n] + (((first, ) + subset), ) + smaller[n + 1:]
        yield ((first, ), ) + smaller


def single(d):
    n, factors = d
    # merge some of the primes together
    for grouping in partition(factors):
示例#8
0
    def gsplot(self):

        ffit = open(os.path.join(self.p.fit_path, self.p.scannum + '.fit'))
        trfit = ffit.read()[:-1].split('\n')
        ffit.close()
        trfit = [e for e in trfit if not e.startswith('#')]
        try:
            srcname = trfit[0].split()[0]
        except IndexError:
            print('No data found in FITS file !!!')
            return

        fdat = open(os.path.join(self.p.fit_path, self.p.scannum + '.dat'))
        trdat = fdat.readlines()
        fdat.close()
        trdat = [
            e[:-1] for e in trdat if (e[0] != '#' or e[:2] == '#!' or (
                e[0] == '#' and len(e.split()) == 6))
        ]
        trdat = trdat[1:]
        tr = [e for e in trdat if re.match('#! SUBSCAN', e)]
        keys = [trdat.index(e) for e in tr]
        keys.append(len(trdat))

        subs = len(trfit)

        amp, eamp = np.zeros(subs), np.zeros(subs)
        scandir = np.array([])

        n1 = int((subs + 1)**0.5)
        n2 = n1 * 1
        while n1 * n2 < subs + 1:
            n2 = n2 + 1

        self.Figure.clf()
        gsp = gridspec.GridSpec(n1, n2)

        sub_flag = np.array([True] * subs)
        for i in range(subs):
            ax = self.Figure.add_subplot(gsp[i])

            trf = trfit[i].split()
            scandir = np.append(scandir, trf[2])
            mjd = float(trf[4])
            tsys = float(trf[14])
            amp[i], eamp[i] = float(trf[7]), float(trf[8])
            off = float(trf[9])
            hpbw = float(trf[11])
            az, el, sunang = float(trf[5]), float(trf[6]), float(trf[16])
            del trf

            trd = trdat[keys[i] + 2:keys[i + 1]]
            trd = [e.split()[0:3][::2] for e in trd]
            trd = np.array(trd).transpose()

            dataX = trd[0].astype(np.float)
            dataY = trd[1].astype(np.float)
            del trd

            if amp[i] != 0:
                fitY = ML.Gauss(1,
                                1).fGauss(np.array([amp[i], off, hpbw, 0, 0]),
                                          dataX)
            else:
                fitY = dataY * 1.0

            ampcolor, offcolor, hpbwcolor = 'white', 'white', 'white'
            titlecolor, titlebackcolor = 'black', '#00FF00'

            xmin, xmax = min(dataX), max(dataX)
            dy = max(dataY) - min(dataY)
            if self.p.flag == False:
                ymin = max(min(dataY), -0.1 * dy)
                ymax = min(max(dataY) + 0.1 * dy, 1.5 * amp[i])

            else:
                if (amp[i] <= 0) or (eamp[i] / amp[i] > self.p.rerr):
                    ampcolor = 'red'
                elif eamp[i] / amp[i] > 0.5 * self.p.rerr:
                    ampcolor = 'yellow'
                if np.fabs(off) > self.p.doff:
                    offcolor = 'red'
                elif np.fabs(off) > 0.5 * self.p.doff:
                    offcolor = 'yellow'
                if np.fabs(hpbw / self.p.beam - 1) > self.p.dwidth:
                    hpbwcolor = 'red'
                elif np.fabs(hpbw / self.p.beam - 1) > 0.5 * self.p.dwidth:
                    hpbwcolor = 'yellow'

            if 'red' in [ampcolor, offcolor, hpbwcolor]:
                sub_flag[i] = False

                ymin = min(dataY)
                ymax = max(dataY) + 0.1 * dy

            else:
                ymin = max(min(dataY), -0.1 * dy)
                ymax = min(max(dataY) + 0.1 * dy, 1.5 * amp[i])

            ax.text(0.05*xmax+0.95*xmin, 0.9*ymax+0.1*ymin, \
                'Amp=%0.4f' %amp[i], \
                fontsize=14, \
                horizontalalignment='left',\
                verticalalignment='top',\
                linespacing=1.5,\
                color=ampcolor)

            ax.text(0.05*xmax+0.95*xmin, 0.815*ymax+0.185*ymin, \
                'Off=%0.2f' %off, \
                fontsize=14, \
                horizontalalignment='left',\
                verticalalignment='top',\
                linespacing=1.5,\
                color=offcolor)

            ax.text(0.05*xmax+0.95*xmin, 0.73*ymax+0.27*ymin, \
                'HPBW=%0.2f' %hpbw, \
                fontsize=14, \
                horizontalalignment='left',\
                verticalalignment='top',\
                linespacing=1.5,\
                color=hpbwcolor)

            ax.text(0.95*xmax+0.05*xmin, 0.9*ymax+0.1*ymin, \
                'Az=%0.1f\nEl=%0.1f\nSun=%0.1f' %(az, el, sunang), \
                fontsize=14, \
                horizontalalignment='right',\
                verticalalignment='top',\
                linespacing=1.5,\
                color='white')

            ax.set_xlim(xmin, xmax)
            ax.set_ylim(ymin, ymax)
            ax.set_xlabel('%s-OFF (arcsec.)' % scandir[i])
            ax.set_ylabel('COUNTS')
            ax.plot(dataX, dataY, color='white', linewidth=1)
            if amp[i] != 0:
                ax.plot(dataX, fitY, color='#00FF00', linewidth=2)
            ax.grid(True)

        ax = self.Figure.add_subplot(gsp[subs])

        _amp0 = amp + eamp
        _amp1 = amp - eamp
        dy = max(_amp0) - min(_amp1)
        ymin = 1.1 * min(_amp1) - 0.1 * max(_amp0)
        ymax = 1.1 * max(_amp0) - 0.1 * min(_amp1)
        ax.set_xlim(0, subs + 1)
        ax.set_ylim(ymin, ymax)
        del _amp0, _amp1

        ax.set_xlabel('Comparison of Subscans')

        if self.p.flag == True:
            if True not in sub_flag[scandir=='ALON'] or \
                True not in sub_flag[scandir=='ALAT']:
                titlecolor, titlebackcolor = 'white', 'red'

            inv_flag = np.array([not e for e in sub_flag])

            ax.errorbar(np.arange(1,subs+1)[sub_flag], \
                amp[sub_flag], yerr=eamp[sub_flag], fmt='d', \
                ecolor='white', mfc='white', mec='white', \
                ms=8, lw=2)

            ax.errorbar(np.arange(1,subs+1)[inv_flag], \
                amp[inv_flag], yerr=eamp[inv_flag], fmt='o', \
                ecolor='red', mfc='red', mec='red', \
                ms=10, lw=2)
        else:
            ax.errorbar(np.arange(subs)+1, amp, yerr=eamp, fmt='d',\
              ecolor='white', mfc='white', mec='white', \
              ms=8, lw=2)

        ax.plot([0, subs + 1], [np.mean(amp)] * 2, color='white', linewidth=2)

        self.Figure.suptitle('\nScan: %4s     %s     @%0.1fMHz' \
            %(self.p.scannum, srcname, self.p.freq), \
            weight='bold', ha='center', \
            linespacing=0.3, fontsize=20, \
            backgroundcolor=titlebackcolor,\
            color=titlecolor)

        self.UpdatePlot()
        del ax
示例#9
0
MAX_DIGITS = 2000
SIEVE_MAX = 5000

to_test = [[[True, True, False, True, True] for a in range(10)]
           for d in range(MAX_DIGITS + 1)]

# Filter the 6 silly patterns
for a in (3, 6, 9):
    for b in (3, 9):
        for test_d in range(MAX_DIGITS + 1):
            assert (a * pow(10, test_d, 3) + b) % 3 == 0
            to_test[test_d][a][b // 2] = False

# Sieve out "small" prime factors and mark those numbers not to test.
small_primes = MathLib.sieveOfErat(SIEVE_MAX)
factors = MathLib.sieveOfFactors(SIEVE_MAX)

print("\t PrimePi({}) = {}".format(SIEVE_MAX, len(small_primes)))

for p in small_primes:
    if p in (2, 5):
        continue

    divisible_mods = defaultdict(list)

    for a in range(1, 10):
        if a % p == 0:
            continue

        modular_inverse = MathLib.modularInverse(a, p)
    [-1.0,0.0,0.0],
    [0.0,0.0,1.0],
    [0.0,1.0,0.0],
    [1.0,0.0,0.0]
])
m2 = np.array([
    [0.0,0.0,-1.0],
    [0.0,-1.0,0.0],
    [-1.0,0.0,0.0],
    [0.0,0.0,1.0],
    [0.0,1.0,0.0],
    [1.0,0.0,0.0]
])
r = np.array([-90.0,110.0,10.0])
u = np.array([0.0,0.0,1.0])
print(m.VneshPole(0, mU))
print(m.SteerOttalk(mK,u,r))
print(m.Moment(n,mK,mU,u,r))
print(m.Sila(n,mK,mU,u,r))
print(m.MathKernel(mK,mU,m1,m2,0, 0))
print(m.PorvrkaGrani(mK))

# koordi = MatrixUglSkorostiы

# fig = plt.figure(figsize=(12, 12))
# ax = fig.add_subplot(111, projection='3d')

# x, y, z = xp.copy(koordi[:, :1]), xp.copy(koordi[:, 1:2]), xp.copy(koordi[:, 2:3])
# ax.scatter(x, y, z, marker = 'o')

# plt.show()