Exemple #1
0
    def __init__(self, x, y, z, h=0):
        '''New n-vector normal to the earth's surface.

           @param x: X component (scalar).
           @param y: Y component (scalar).
           @param z: Z component (scalar).
           @keyword h: Height above surface (meter).

           @example:

           >>> from sphericalNvector import Nvector
           >>> v = Nvector(0.5, 0.5, 0.7071, 1)
           >>> v.toLatLon()  # 45.0°N, 045.0°E, +1.00m
        '''
        Vector3d.__init__(self, x, y, z)
        if h:
            self._h = float(h)
Exemple #2
0
    def to3llh(self):
        '''Convert this n-vector to (geodetic) lat-, longitude
           and height.

           @return: 3-Tuple (lat, lon, height) in (C{degrees90},
                    C{degrees180}, C{meter}).
        '''
        return Vector3d.to2ll(self) + (self.h, )
Exemple #3
0
    def toVector3d(self):
        '''Convert this n-vector to a normalized 3-d vector,
           ignoring the height.

           @return: Normalized vector (L{Vector3d}).
        '''
        u = self.unit()
        return Vector3d(u.x, u.y, u.z, name=self.name)
Exemple #4
0
    def __init__(self,
                 side_str,
                 device_addr=None,
                 transposition=(0, 1, 2),
                 scaling=(1, 1, 1)):

        self._accel = Vector3d(transposition, scaling, self._accel_callback)
        self._gyro = Vector3d(transposition, scaling, self._gyro_callback)
        self.buf1 = bytearray(
            1)  # Pre-allocated buffers for reads: allows reads to
        self.buf2 = bytearray(2)  # be done in interrupt handlers
        self.buf3 = bytearray(3)
        self.buf6 = bytearray(6)

        sleep_ms(200)  # Ensure PSU and device have settled
        if isinstance(side_str,
                      str):  # Non-pyb targets may use other than X or Y
            self._mpu_i2c = I2C(side_str)
        elif hasattr(side_str,
                     'readfrom'):  # Soft or hard I2C instance. See issue #3097
            self._mpu_i2c = side_str
        else:
            raise ValueError("Invalid I2C instance")

        if device_addr is None:
            devices = set(self._mpu_i2c.scan())
            mpus = devices.intersection(set(self._mpu_addr))
            number_of_mpus = len(mpus)
            if number_of_mpus == 0:
                raise MPUException("No MPU's detected")
            elif number_of_mpus == 1:
                self.mpu_addr = mpus.pop()
            else:
                raise ValueError(
                    "Two MPU's detected: must specify a device address")
        else:
            if device_addr not in (0, 1):
                raise ValueError('Device address must be 0 or 1')
            self.mpu_addr = self._mpu_addr[device_addr]

        self.chip_id  # Test communication by reading chip_id: throws exception on error
        # Can communicate with chip. Set it up.
        self.wake()  # wake it up
        self.passthrough = True  # Enable mag access from main I2C bus
        self.accel_range = 0  # default to highest sensitivity
        self.gyro_range = 0  # Likewise for gyro
Exemple #5
0
def criterion(tmp, particles):
    tmp_particle = Particle(r=Vector3d(*tmp))
    for particle in particles:
        # print((tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)))
        # if (tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)) > -0.3:
        if abs(tmp_particle.r - particle.r) < 0.5 * constants.a_0:
            return False
    return True
Exemple #6
0
    def to3abh(self):
        '''Convert this n-vector to (geodetic) lat-, longitude
           and height.

           @return: 3-Tuple (lat, lon, height) in (C{radians},
                    C{radians}, C{meter}).
        '''
        return Vector3d.to2ab(self) + (self.h, )
Exemple #7
0
    def __init__(self,
                 device_addr,
                 busnum,
                 transposition,
                 scaling,
                 mag_addr=None):
        '''Create an InvenSenseMPU interface.

        Arguments:
            device_addr (0 or 1): There are two possible I2C slave address for the
                MPU9x50. This value decides which of the two to use.
            busnum (integer): Which of the BeagleBone's I2C buses to use.
            transposition
            scaling
            mag_addr: I2C address of the magnetometer (different from the I2C ad
            dress of the main sensor).

        '''

        self._accel = Vector3d(transposition, scaling, self._accel_callback)
        self._gyro = Vector3d(transposition, scaling, self._gyro_callback)
        self.buf1 = bytearray(
            [0] * 1)  # Pre-allocated buffers for reads: allows reads to
        self.buf2 = bytearray([0] * 2)  # be done in interrupt handlers
        self.buf3 = bytearray([0] * 3)
        self.buf6 = bytearray([0] * 6)
        self.timeout = 10  # I2C tieout mS

        if device_addr is None:
            raise ValueError("Adafruit_I2C does not support scanning")
        else:
            if device_addr not in (0, 1):
                raise ValueError('Device address must be 0 or 1')
            self.mpu_addr = self._mpu_addr[device_addr]

        self._mpu_i2c = Adafruit_I2C(self.mpu_addr, busnum=busnum)
        if mag_addr is not None:
            self._mag_i2c = Adafruit_I2C(mag_addr, busnum=busnum)

        self.chip_id  # Test communication by reading chip_id: throws exception on error
        # Can communicate with chip. Set it up.
        self.wake()  # wake it up
        self.passthrough = True  # Enable mag access from main I2C bus
        self.accel_range = 0  # default to highest sensitivity
        self.gyro_range = 0  # Likewise for gyro
Exemple #8
0
    def __init__(self,
                 device_addr=None,
                 transposition=(0, 1, 2),
                 scaling=(1, 1, 1),
                 pins=None):

        self._accel = Vector3d(transposition, scaling, self._accel_callback)
        self._gyro = Vector3d(transposition, scaling, self._gyro_callback)
        self.buf1 = bytearray(
            1)  # Pre-allocated buffers for reads: allows reads to
        self.buf2 = bytearray(2)  # be done in interrupt handlers
        self.buf3 = bytearray(3)
        self.buf6 = bytearray(6)

        sleep_ms(200)  # Ensure PSU and device have settled
        if pins is not None:
            self._mpu_i2c = I2C(-1,
                                mode=I2C.MASTER,
                                pins=pins,
                                baudrate=100000)
        else:
            self._mpu_i2c = I2C(0)

        if device_addr is None:
            devices = set(self._mpu_i2c.scan())
            mpus = devices.intersection(set(self._mpu_addr))
            number_of_mpus = len(mpus)
            if number_of_mpus == 0:
                raise MPUException("No MPU's detected")
            elif number_of_mpus == 1:
                self.mpu_addr = mpus.pop()
            else:
                raise ValueError(
                    "Two MPU's detected: must specify a device address")
        else:
            if device_addr not in (0, 1):
                raise ValueError('Device address must be 0 or 1')
            self.mpu_addr = self._mpu_addr[device_addr]

        self.chip_id  # Test communication by reading chip_id: throws exception on error
        # Can communicate with chip. Set it up.
        self.wake()  # wake it up
        self.passthrough = True  # Enable mag access from main I2C bus
        self.accel_range = 0  # default to highest sensitivity
        self.gyro_range = 0  # Likewise for gyro
Exemple #9
0
    def __init__(self, side_str, device_addr, transposition, scaling):

        self._accel = Vector3d(transposition, scaling, self._accel_callback)
        self._gyro = Vector3d(transposition, scaling, self._gyro_callback)
        self.buf1 = bytearray(
            [0] * 1)  # Pre-allocated buffers for reads: allows reads to
        self.buf2 = bytearray([0] * 2)  # be done in interrupt handlers
        self.buf3 = bytearray([0] * 3)
        self.buf6 = bytearray([0] * 6)
        self.timeout = 10  # I2C tieout mS

        tim = pyb.millis()  # Ensure PSU and device have settled
        if tim < 200:
            pyb.delay(200 - tim)
        if type(side_str) is str:
            sst = side_str.upper()
            if sst in {'X', 'Y'}:
                self._mpu_i2c = pyb.I2C(sst, pyb.I2C.MASTER)
            else:
                raise ValueError('I2C side must be X or Y')
        elif type(side_str) is pyb.I2C:
            self._mpu_i2c = side_str

        if device_addr is None:
            devices = set(self._mpu_i2c.scan())
            mpus = devices.intersection(set(self._mpu_addr))
            number_of_mpus = len(mpus)
            if number_of_mpus == 0:
                raise MPUException("No MPU's detected")
            elif number_of_mpus == 1:
                self.mpu_addr = mpus.pop()
            else:
                raise ValueError(
                    "Two MPU's detected: must specify a device address")
        else:
            if device_addr not in (0, 1):
                raise ValueError('Device address must be 0 or 1')
            self.mpu_addr = self._mpu_addr[device_addr]

        self.chip_id  # Test communication by reading chip_id: throws exception on error
        # Can communicate with chip. Set it up.
        self.wake()  # wake it up
        self.passthrough = True  # Enable mag access from main I2C bus
        self.accel_range = 0  # default to highest sensitivity
        self.gyro_range = 0  # Likewise for gyro
Exemple #10
0
 def cent_of_mass(self):
     """
     Returns a vector of the geometrical center of atoms.
     :return: Vector3d
     """
     com = Vector3d()
     for atom in self.atoms:
         com += atom.coord
     return com / len(self)
Exemple #11
0
    def unit(self):
        '''Normalize this vector to unit length.

           @return: Normalized vector (L{Nvector}).
        '''
        if self._united is None:
            u = Vector3d.unit(self)  # .copy()
            self._united = u._united = _xattrs(u, self, '_h')
        return self._united
Exemple #12
0
    def __init__(self, side_str, device_addr=None, transposition=(0, 1, 2), scaling=(1, 1, 1)):

        super(MPU9250, self).__init__(side_str, device_addr, transposition, scaling)
        self._mag = Vector3d(transposition, scaling, self._mag_callback)
        self.accel_filter_range = 0             # fast filtered response
        self.gyro_filter_range = 0
        self._mag_stale_count = 0               # MPU9250 count of consecutive reads where old data was returned
        self.mag_correction = self._magsetup()  # 16 bit, 100Hz update.Return correction factors.
        self._mag_callback()  # Seems neccessary to kick the mag off else 1st reading is zero (?)
Exemple #13
0
    def toVector3d(self):
        '''Convert this point to a vector normal to earth's surface.

           @return: Vector representing this point (L{Vector3d}).
        '''
        if self._v3d is None:
            x, y, z = self.to3xyz()
            self._v3d = Vector3d(x, y, z)  # XXX .unit()
        return self._v3d
Exemple #14
0
    def copy(self):
        '''Copy this vector.

           @return: Copy (L{Nvector}).
        '''
        n = Vector3d.copy(self)
        if n.h != self.h:
            n.h = self.h
        return n
Exemple #15
0
    def __init__(self, x, y, z, h=0, ll=None):
        '''New n-vector normal to the earth's surface.

           @param x: X component (scalar).
           @param y: Y component (scalar).
           @param z: Z component (scalar).
           @keyword h: Optional height above surface (meter).
           @keyword ll: Optional, original latlon (I{LatLon}).

           @example:

           >>> from sphericalNvector import Nvector
           >>> v = Nvector(0.5, 0.5, 0.7071, 1)
           >>> v.toLatLon()  # 45.0°N, 045.0°E, +1.00m
        '''
        Vector3d.__init__(self, x, y, z, ll=ll)
        if h:
            self._h = scalar(h, None, name='h')
Exemple #16
0
def get_and_plot_density(particles, radii, rotation, center, num=100):
    cm = Vector3d()
    particles_ = copy.deepcopy(particles)

    derotation = np.linalg.inv(rotation)

    for particle in particles_:
        particle.r.x -= center[0]
        particle.r.y -= center[1]
        particle.r.z -= center[2]

        tmp = np.dot(np.array([particle.r.x, particle.r.y, particle.r.z]),
                     derotation)
        particle.r = Vector3d(tmp[0], tmp[1], tmp[2])

        cm += particle.r
    cm = cm * (1 / len(particles_))

    for i in range(len(particles)):
        particles_[i].r.x *= 1 / radii[0]
        particles_[i].r.y *= 1 / radii[1]
        particles_[i].r.z *= 1 / radii[2]

    lengths = sorted([abs(particle.r) for particle in particles_])
    density = []
    l = []
    # particles = sorted(particles, key=lambda particle: abs(particle.r - cm))

    for i in range(len(lengths) // num):
        density.append(num * particles_[0].mass /
                       (4 / 3 * np.pi *
                        (lengths[i * num + num - 1]**3 - lengths[i * num]**3)))
        # l.append(lengths[i*num] + 0.5*(lengths[i*num + num-1] - lengths[i*num]))
        l.append(lengths[i * num])

    ig, ax1 = plt.subplots(figsize=(4, 4))

    ax1.scatter(x=l, y=density, marker='o', c='r', edgecolor='b')
    ax1.set_title('Scatter: $x$ versus $y$')
    ax1.set_xlabel('$x$')
    ax1.set_ylabel('$y$')
    plt.show()

    return density, lengths
Exemple #17
0
 def _to3LLh(self, LL, height, **kwds):
     '''(INTERNAL) Helper for C{subclass.toLatLon} and C{.to3llh}.
     '''
     h = self.h if height is None else height
     r = Vector3d.to2ll(self)  # LatLon2Tuple
     if LL is None:
         r = r._3Tuple(h)  # already ._xnamed
     else:
         r = self._xnamed(LL(r.lat, r.lon, height=h, **kwds))
     return r
Exemple #18
0
    def toStr(self, prec=3, fmt='[%s]', sep=', '):  # PYCHOK expected
        '''Return the string representation of this cartesian.

           @keyword prec: Optional number of decimals, unstripped (int).
           @keyword fmt: Optional enclosing backets format (string).
           @keyword sep: Optional separator to join (string).

           @return: Cartesian represented as "[x, y, z]" (string).
        '''
        return Vector3d.toStr(self, prec=prec, fmt=fmt, sep=sep)
Exemple #19
0
def create_sphere(radii, num_sumples=2000):
    cur_num_particles = 0
    attempts = 100
    particles = []
    while True:
        u = np.random.uniform(0, 2*np.pi)
        # v = np.random.uniform(0, np.pi)

        # cosu = np.random.uniform(-1, 1)
        cosv = np.random.uniform(-1, 1)
        tmp_z = np.random.uniform(0, 1)

        v = np.arccos(cosv)

        mul = tmp_z**(1/3)
        r1 = radii[0]*mul
        r2 = radii[1]*mul
        r3 = radii[2]*mul

        # mul = tmp_z**(1/2)
        # r1 = radii[0]*mul
        # r2 = radii[1]*mul
        # r3 = radii[2]*mul


        # lam = 0.1
        # k = 0.00001
        # r1 = radii[0]*(1-np.exp(tmp_z/lam)**k)
        # r2 = radii[1]*(1-np.exp(tmp_z/lam)**k)
        # r3 = radii[2]*(1-np.exp(tmp_z/lam)**k)

        # k = 1
        # mul = -1/np.log(k - k*0.99999) * np.log(k - k*tmp_z)
        # r1 = radii[0]*mul
        # r2 = radii[1]*mul
        # r3 = radii[2]*mul

        # k = 1
        # mul = (-1/(1+np.exp(-10*(tmp_z-0.5)))+1)**(1/3)
        # r1 = radii[0]*mul
        # r2 = radii[1]*mul
        # r3 = radii[2]*mul

        tmp = [r1 * np.cos(u) * np.sin(v), r2 * np.sin(u) * np.sin(v), r3 * np.cos(v)]
        if criterion(tmp, particles):
            # [x, y, z] = np.dot([tmp[0][0][0], tmp[1][0][0], tmp[2][0][0]], rotation) + center
            [x, y, z] = [tmp[0], tmp[1], tmp[2]]
            particles.append(Particle(r=Vector3d(x, y, z), color=(0, 0, 0), name=len(particles)))

            cur_num_particles += 1
        if cur_num_particles % 1 == 0:
            print(cur_num_particles)
        if cur_num_particles == num_sumples:
            break
    return particles
Exemple #20
0
    def unit(self):
        '''Normalize this vector to unit length.

           @return: Normalised, unit vector (L{Nvector}).
        '''
        if self._united is None:
            u = Vector3d.unit(self).copy()
            if u.h != self.h:
                u.h = self.h
            self._united = u._united = u
        return self._united
Exemple #21
0
    def to3abh(self, height=None):
        '''Convert this n-vector to (geodetic) lat-, longitude
           and height.

           @keyword height: Optional height, overriding this
                            n-vector's height (C{meter}).

           @return: A L{PhiLam3Tuple}C{(phi, lambda, height)}.
        '''
        h = self.h if height is None else height
        return Vector3d.to2ab(self)._3Tuple(h)
Exemple #22
0
    def unit(self, ll=None):
        '''Normalize this vector to unit length.

           @keyword ll: Optional, original latlon (C{LatLon}).

           @return: Normalized vector (L{Nvector}).
        '''
        if self._united is None:
            u = Vector3d.unit(self, ll=ll)  # .copy()
            self._united = u._united = _xattrs(u, self, '_h')
        return self._united
Exemple #23
0
    def __init__(self, line=None, model=0, **kwargs):
        """
        Constructor. Creates an Atom object from string - ATOM/HETATM line from the pdb file.
        If line is empty creates an empty atom equivalent to:
        Atom('HETATM    0 XXXX XXX X   0       0.000   0.000   0.000  0.00  0.00')
        Passing attribute=value to the constructor overwrites default/read values.
        :param line: str 
        :param model: int
        """
        if line:
            self.model = model
            self.hetatm = (line[:6] == "HETATM")
            self.serial = int(line[6:11])
            self.name = line[11:16].strip()
            self.alt = line[16]
            self.resname = line[17:21].strip()
            self.chid = line[21]
            self.resnum = int(line[22:26])
            self.icode = line[26]
            self.coord = Vector3d(line[30:38], line[38:46], line[46:54])
            self.occ = float(line[54:60])
            self.bfac = float(line[60:66])
            self.tail = line[66:].replace('\n', '')
        else:
            self.model = model
            self.hetatm = True
            self.serial = 0
            self.name = "XXXX"
            self.alt = ""
            self.resname = "XXX"
            self.chid = "X"
            self.resnum = 0
            self.icode = ""
            self.coord = Vector3d()
            self.occ = 0.0
            self.bfac = 0.0
            self.tail = ""

        for arg in kwargs:
            if arg in self.__dict__:
                self.__dict__[arg] = kwargs[arg]
 def __init__(self,
              side_str,
              device_addr=None,
              transposition=(0, 1, 2),
              scaling=(1, 1, 1)):
     super().__init__(side_str, device_addr, transposition, scaling)
     self._mag = Vector3d(transposition, scaling, self._mag_callback)
     self.filter_range = 0  # fast filtered response
     self._mag_stale_count = 0  # Count of consecutive reads where old data was returned
     self.mag_triggered = False  # Ensure mag is triggered once only until it's read
     self.mag_correction = self._magsetup()  # Returns correction factors.
     self.mag_wait_func = default_mag_wait
Exemple #25
0
def read(read_path, mode=None):
    particles = []
    with open(read_path, 'r') as inputfile:
        s_tmp = inputfile.read()
        for el in s_tmp.split('\n')[2:]:
            if el != '':
                if mode is None:
                    rx, ry, rz, r, g, b = el.split()
                else:
                    с, rx, ry, rz, c = el.split()
                particles.append(
                    Particle(r=Vector3d(float(rx), float(ry), float(rz)),
                             name=len(particles)))
    return particles
Exemple #26
0
 def __init__(self, position, target, up_dir, projection):
     """Initialize a camera with its position, target point, and up_dir
     @position: Point3d
     @target: Point3d [this is the point towards it is facing
     @up_dir: Vector3d
     """
     self.position = position
     self.target = target
     self.up_dir = up_dir
     self.facing_dir = Vector3d.new(self.position, self.target)
     # check if facing_dir and up_dir are perpendicular
     if self.facing_dir.dot(self.up_dir) != 0.0:
         raise Exception("facing dir and up dir are not perpendicular")
     self.__matrix = None
     self.projection = projection
Exemple #27
0
    def insert_ligand(self, receptor, ligand):

        radius = 0.5 * receptor.dimension + self.separation

        if ligand.location == 'keep':
            location = ligand.cent_of_mass()
        elif ligand.location == 'random':
            location = Vector3d().random() * radius + receptor.center
        else:
            location = receptor.convert_patch(
                ligand.location) * radius + receptor.center

        if ligand.conformation == 'random':
            ligand.random_conformation()

        ligand.move_to(location)
Exemple #28
0
    def cast(self, ch):
        """
        Function that casts a single protein chain onto the lattice.
        Returns a list of tuples with (x, y, z) coordinates of CA atoms.
        """

        if len(ch.atoms) < 3:
            raise Exception('Protein chain too short!')

        prev = None
        coord = [
            Vector3d(round(ch.atoms[0].coord.x / self.grid),
                     round(ch.atoms[0].coord.y / self.grid),
                     round(ch.atoms[0].coord.z / self.grid))
        ]

        for atom in ch.atoms[1:]:
            #  iterate over atoms
            min_dr = 1e12
            min_i = -1

            for i, v in enumerate(self.vectors):
                #  iterate over all possible vectors

                if len(coord) > 2 and self.good[prev, i] == 0:
                    continue

                new = coord[-1] + v
                dr = (self.grid * new - atom.coord).mod2()
                if dr < min_dr:
                    min_dr = dr
                    min_i = i

            if min_i < 0:
                raise Exception('Unsolvable geometric problem!')
            else:
                coord.append(coord[-1] + self.vectors[min_i])
                prev = min_i

        coord.insert(0, coord[0] + coord[1] - coord[2])
        coord.append(coord[-1] + coord[-2] - coord[-3])

        return coord
Exemple #29
0
def calculate_asa(atoms, probe, n_sphere_point=960):
    """
    Returns list of accessible surface areas of the atoms, using the probe
    and atom radius to define the surface.
    """
    sphere_points = generate_sphere_points(n_sphere_point)

    const = 4.0 * math.pi / len(sphere_points)
    test_point = Vector3d()
    areas = []
    for i, atom_i in enumerate(atoms):

        neighbor_indices = find_neighbor_indices(atoms, probe, i)
        n_neighbor = len(neighbor_indices)
        j_closest_neighbor = 0
        radius = probe + atom_i.radius

        n_accessible_point = 0
        for point in sphere_points:
            is_accessible = True

            test_point.x = point[0] * radius + atom_i.pos.x
            test_point.y = point[1] * radius + atom_i.pos.y
            test_point.z = point[2] * radius + atom_i.pos.z

            cycled_indices = range(j_closest_neighbor, n_neighbor)
            cycled_indices.extend(range(j_closest_neighbor))

            for j in cycled_indices:
                atom_j = atoms[neighbor_indices[j]]
                r = atom_j.radius + probe
                diff_sq = pos_distance_sq(atom_j.pos, test_point)
                if diff_sq < r * r:
                    j_closest_neighbor = j
                    is_accessible = False
                    break
            if is_accessible:
                n_accessible_point += 1

        area = const * n_accessible_point * radius * radius
        areas.append(area)
    return areas
Exemple #30
0
    def toStr(self, prec=5, fmt='(%s)', sep=', '):  # PYCHOK expected
        '''Return a string representation of this n-vector.

           Height component is only included if non-zero.

           @keyword prec: Optional number of decimals, unstripped (C{int}).
           @keyword fmt: Optional enclosing backets format (C{str}).
           @keyword sep: Optional separator between components (C{str}).

           @return: Comma-separated "x, y, z [, h]" (C{str}).

           @example:

           >>> Nvector(0.5, 0.5, 0.7071).toStr()  # (0.5, 0.5, 0.7071)
           >>> Nvector(0.5, 0.5, 0.7071, 1).toStr(-3)  # (0.500, 0.500, 0.707, +1.00)
        '''
        t = Vector3d.toStr(self, prec=prec, fmt='%s', sep=sep)
        if self.h:
            t = '%s%s%s%+.2f' % (t, sep, self.H, self.h)
        return fmt % (t, )
 def __init__(self, *args, **kwargs):
     Vector3d.__init__(self, *args, **kwargs)
     PointBase.__init__(self)