예제 #1
0
def rot_x_matrix( degrees ):
    r = identity( 3, 'd' )
    r[1][1] = cosdg( degrees )
    r[1][2] = -sindg( degrees )
    r[2][1] = sindg( degrees )
    r[2][2] = cosdg( degrees )

    return r
예제 #2
0
    def write_xml(self, filename, lat):
        if self.dim != lat.dim:
            ERROR("dimension mismatch between wavevector and lattice")
        with codecs.open(filename, "w", "utf-8") as f:
            f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
            f.write("<WaveVector>\n")
            f.write(tagged("Comment", lat.name))
            f.write(tagged("NumberOfSites", len(lat.sites)))
            f.write(tagged("NumberOfWaveVectors", self.nk))

            f.write(
                "<!-- <RK> [phase(cos)] [phase(sin)] [isite] [kindx] </RK> -->\n"
            )
            for ik in range(self.nk):
                k = self.ks[:, ik]
                for site in lat.sites:
                    sid = site.id
                    coord = site.coord
                    phase = 0
                    for d in range(self.dim):
                        phase += coord[d] * k[d] / float(lat.size[d])
                    c = spsp.cosdg(360 * phase)
                    s = spsp.sindg(360 * phase)
                    f.write(tagged("RK", [c, s, sid, ik]))

            f.write("</WaveVector>\n")
예제 #3
0
파일: Vector2.py 프로젝트: philetus/l33tC4D
    def rotate( self, degrees ):
        """rotate this vector by given degrees and return as new vector
        """
        # cosine vector is this vector multiplied by cosine of angle
        cosine = self.multiply( cosdg(degrees) )

        # sine vector is cross product of this vector and normalized given
        # vector, multiplied by sine of angle
        sine = self.cross().multiply( sindg(degrees) )

        return cosine.add( sine )
예제 #4
0
파일: kagome.py 프로젝트: huangrzh/dsqss
def generate(param):
    dim = 2
    L = get_as_list(param, "L", extendto=dim)
    bc = get_as_list(param, "bc", default=True, extendto=dim)
    basis = np.array([[1.0, 0.0], [cosdg(120), sindg(120)]])

    sites = [
            {"siteid": 0, "type": 0, "coord": [0.0, 0.0]},
            {"siteid": 1, "type": 0, "coord": [0.5, 0.0]},
            {"siteid": 1, "type": 0, "coord": [0.5, 0.5]},
            ]
    bonds = [
        {
            "bondid": 0,
            "type": 0,
            "source": {"siteid": 0},
            "target": {"siteid": 1, "offset": [0, 0]},
        },
        {
            "bondid": 1,
            "type": 0,
            "source": {"siteid": 0},
            "target": {"siteid": 2, "offset": [0, 0]},
        },
        {
            "bondid": 2,
            "type": 0,
            "source": {"siteid": 1},
            "target": {"siteid": 2, "offset": [0, 0]},
        },
        {
            "bondid": 3,
            "type": 0,
            "source": {"siteid": 1},
            "target": {"siteid": 0, "offset": [1, 0]},
        },
        {
            "bondid": 4,
            "type": 0,
            "source": {"siteid": 2},
            "target": {"siteid": 1, "offset": [0, 1]},
        },
        {
            "bondid": 5,
            "type": 0,
            "source": {"siteid": 2},
            "target": {"siteid": 0, "offset": [1, 1]},
        },
    ]

    parameter = {"name": "kagome", "dim": dim, "L": L, "bc": bc, "basis": basis}
    unitcell = {"sites": sites, "bonds": bonds}

    return {"parameter": parameter, "unitcell": unitcell}
예제 #5
0
def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
           mode='constant', cval=0.0, prefilter=True):
    """
    Rotate an array.

    The array is rotated in the plane defined by the two axes given by the
    `axes` parameter using spline interpolation of the requested order.

    Parameters
    ----------
    %(input)s
    angle : float
        The rotation angle in degrees.
    axes : tuple of 2 ints, optional
        The two axes that define the plane of rotation. Default is the first
        two axes.
    reshape : bool, optional
        If `reshape` is true, the output shape is adapted so that the input
        array is contained completely in the output. Default is True.
    %(output)s
    order : int, optional
        The order of the spline interpolation, default is 3.
        The order has to be in the range 0-5.
    %(mode_interp_constant)s
    %(cval)s
    %(prefilter)s

    Returns
    -------
    rotate : ndarray
        The rotated input.

    Notes
    -----
    For complex-valued `input`, this function rotates the real and imaginary
    components independently.

    .. versionadded:: 1.6.0
        Complex-valued support added.

    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure(figsize=(10, 3))
    >>> ax1, ax2, ax3 = fig.subplots(1, 3)
    >>> img = misc.ascent()
    >>> img_45 = ndimage.rotate(img, 45, reshape=False)
    >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
    >>> ax1.imshow(img, cmap='gray')
    >>> ax1.set_axis_off()
    >>> ax2.imshow(img_45, cmap='gray')
    >>> ax2.set_axis_off()
    >>> ax3.imshow(full_img_45, cmap='gray')
    >>> ax3.set_axis_off()
    >>> fig.set_tight_layout(True)
    >>> plt.show()
    >>> print(img.shape)
    (512, 512)
    >>> print(img_45.shape)
    (512, 512)
    >>> print(full_img_45.shape)
    (724, 724)

    """
    input_arr = numpy.asarray(input)
    ndim = input_arr.ndim

    if ndim < 2:
        raise ValueError('input array should be at least 2D')

    axes = list(axes)

    if len(axes) != 2:
        raise ValueError('axes should contain exactly two values')

    if not all([float(ax).is_integer() for ax in axes]):
        raise ValueError('axes should contain only integer values')

    if axes[0] < 0:
        axes[0] += ndim
    if axes[1] < 0:
        axes[1] += ndim
    if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
        raise ValueError('invalid rotation plane specified')

    axes.sort()

    c, s = special.cosdg(angle), special.sindg(angle)

    rot_matrix = numpy.array([[c, s],
                              [-s, c]])

    img_shape = numpy.asarray(input_arr.shape)
    in_plane_shape = img_shape[axes]
    if reshape:
        # Compute transformed input bounds
        iy, ix = in_plane_shape
        out_bounds = rot_matrix @ [[0, 0, iy, iy],
                                   [0, ix, 0, ix]]
        # Compute the shape of the transformed input plane
        out_plane_shape = (out_bounds.ptp(axis=1) + 0.5).astype(int)
    else:
        out_plane_shape = img_shape[axes]

    out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
    in_center = (in_plane_shape - 1) / 2
    offset = in_center - out_center

    output_shape = img_shape
    output_shape[axes] = out_plane_shape
    output_shape = tuple(output_shape)

    complex_output = numpy.iscomplexobj(input_arr)
    output = _ni_support._get_output(output, input_arr, shape=output_shape,
                                     complex_output=complex_output)

    if ndim <= 2:
        affine_transform(input_arr, rot_matrix, offset, output_shape, output,
                         order, mode, cval, prefilter)
    else:
        # If ndim > 2, the rotation is applied over all the planes
        # parallel to axes
        planes_coord = itertools.product(
            *[[slice(None)] if ax in axes else range(img_shape[ax])
              for ax in range(ndim)])

        out_plane_shape = tuple(out_plane_shape)

        for coordinates in planes_coord:
            ia = input_arr[coordinates]
            oa = output[coordinates]
            affine_transform(ia, rot_matrix, offset, out_plane_shape,
                             oa, order, mode, cval, prefilter)

    return output
예제 #6
0
# Parampreet Singh - 22/06/20
# brief exploration SciPy package

import matplotlib.pyplot as plt
from scipy import interpolate as intpol
from scipy import linalg
from scipy.fftpack import fft, ifft
from scipy import integrate
from scipy import special
import numpy as np

a = special.exp10(3)  # 10 ** 3
print(a)

a = special.sindg(90)  # sin value in degress
print(a)

# integration
# integrate.quad(expression, lower limit, upper limit)
a = integrate.quad(lambda x: x**2, 0, 1)
# quad is a single varibale
# dblquad is two variables
print(a)

# integrate.quad(expression, lower limit, upper limit, lower(2nd), upper(2nd))
a = integrate.dblquad(lambda x, y: x**2 + y**2, 0, 1, 0, 1)
print(a)

# Fourier transformation
x = np.array([1, 2, 3, 4])
y = ifft(x)  # inverse
예제 #7
0
from scipy import special as sp
print(sp.cbrt(27))  #求立方根.
print(sp.sindg(45))  #正弦函数,参数为角度.
print(sp.comb(6, 3))  #6中选3的组合数.
print(sp.perm(5, 3))  #5中选3的排列数.
print(sp.round(5.67))  #返回四舍五入后的整数.
예제 #8
0
# sp.info(fftpack)
# sp.source(cluster)


fun1 = special.kelvin(15)
print(fun1)


fun2 = special.xlogy(2, 10)
print(fun2)

fun3 = special.exp10(50)
print(fun3)

fun4 = special.sindg(60)
print(fun4)

fun5 = special.cosdg(60)
print(fun5)

print('---------------------')


def var1(x): return x**3


fun6 = integrate.quad(var1, 0, 6)
print(fun6)

예제 #9
0
# -*- coding: utf-8 -*-
"""
Created on Fri May  1 20:35:19 2020

@author: Shivanshu
"""

from scipy import special
from scipy import integrate
import numpy as np
from scipy import linalg

n = special.exp10(2)  #exponantial

x = special.sindg(90)  # value of sin angle
print(n, x)

i = integrate.quad(lambda x: special.exp10(2), 0, 1)  #integration
print(i)

a = np.array([[1, 2], [3, 4]])
b = linalg.inv(a)
print(b)  # inverse of matrix (linear algebra)
예제 #10
0
import scipy
from scipy import cluster
from scipy import special
from scipy import integrate

a = special.exp10(2)
print(a)

b = special.exp2(2)
print(b)

c = special.sindg(90)
print(c)

print(special.cosdg(0))

print(scipy.integrate.quad(lambda x: special.exp10(x), 0, 1))
예제 #11
0
from scipy import fftpack
from scipy import special

# use help() function to see sub packages
# help()
# to make reference to scipy use sp
# to see information of the subpackage fftpack
# sp.info(fftpack)
# sp.source(cluster)

# use the special function to access math functions
func = special.kelvin(15)
print(func)

func1 = special.exp10(5)
print(func1)

func2 = special.xlogy(2, 10)
print(func2)

func3 = special.sindg(105)
print(func3)

# Use integrate function to integrate variables
var1 = lambda a: a**3
function1 = integrate.quad(var1, 0, 6)
print(function1)
# Double integration of two variable x and y
var2 = lambda y, x: x * y**4
function2 = integrate.dblquad(var2, 0, 6, lambda x: 0, lambda x: 1)
print(function2)
예제 #12
0
def rotate(input_arr,
           angle,
           axes=(1, 0),
           reshape=True,
           output=None,
           order=1,
           mode='constant',
           cval=0.0,
           prefilter=False,
           output_chunks=None,
           output_shape=None):
    """
    
    Rotate an array using Dask. Chunkwise processing is performed
    using dask_image.ndinterp.affine_transform

    The array is rotated in the plane defined by the two axes given by the
    `axes` parameter using spline interpolation of the requested order.

    Parameters
    ----------
    %(input)s
    angle : float
        The rotation angle in degrees.
    axes : tuple of 2 ints, optional
        The two axes that define the plane of rotation. Default is the first
        two axes.
    reshape : bool, optional
        If `reshape` is true, the output shape is adapted so that the input
        array is contained completely in the output. Default is True.
    %(output)s
    order : int, optional
        The order of the spline interpolation, default is 3.
        The order has to be in the range 0-5.
    %(mode_interp_constant)s
    %(cval)s
    %(prefilter)s

    Returns
    -------
    rotate : ndarray
        The rotated input.

    Notes
    -----
        Differences to `ndimage.affine_transformation`:
        - currently, prefiltering is not supported
          (affecting the output in case of interpolation `order > 1`)
        - default order is 1
        - modes 'reflect', 'mirror' and 'wrap' are not supported
        
        Arguments equal to `ndimage.affine_rotate`,
        except for `output_chunks`.

    .. versionadded:: 1.6.0


    Examples
    --------
    >>> from scipy import ndimage, misc
    >>> import matplotlib.pyplot as plt
    >>> import dask.array as da
    >>> fig = plt.figure(figsize=(10, 3))
    >>> ax1, ax2, ax3 = fig.subplots(1, 3)
    >>> img = da.from_array(misc.ascent(),chunks=(64,64))
    >>> img_45 = dask_image.ndinterp.rotate(img, 45, reshape=False)
    >>> full_img_45 = dask_image.ndinterp.rotate(img, 45, reshape=True)
    >>> ax1.imshow(img, cmap='gray')
    >>> ax1.set_axis_off()
    >>> ax2.imshow(img_45, cmap='gray')
    >>> ax2.set_axis_off()
    >>> ax3.imshow(full_img_45, cmap='gray')
    >>> ax3.set_axis_off()
    >>> fig.set_tight_layout(True)
    >>> plt.show()
    >>> print(img.shape)
    (512, 512)
    >>> print(img_45.shape)
    (512, 512)
    >>> print(full_img_45.shape)
    (724, 724)

    """
    #  input_arr = input#np.asarray(input)

    if not type(input_arr) == da.core.Array:
        input_arr = da.from_array(input_arr)

    if output_shape is None:
        output_shape = input_arr.shape

    ndim = input_arr.ndim

    if reshape & (output_shape != None):
        warnings.warn(
            'Both reshaping desired and output_shape provided.'
            'Will use the explicit output_shape.', UserWarning)

    if ndim < 2:
        raise ValueError('input array should be at least 2D')

    axes = list(axes)

    if len(axes) != 2:
        raise ValueError('axes should contain exactly two values')

    if not all([float(ax).is_integer() for ax in axes]):
        raise ValueError('axes should contain only integer values')

    if axes[0] < 0:
        axes[0] += ndim
    if axes[1] < 0:
        axes[1] += ndim
    if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
        raise ValueError('invalid rotation plane specified')

    axes.sort()

    c, s = special.cosdg(angle), special.sindg(angle)

    rot_matrix = np.array([[c, s], [-s, c]])

    img_shape = np.asarray(input_arr.shape)
    in_plane_shape = img_shape[axes]

    if reshape:
        # Compute transformed input bounds
        iy, ix = in_plane_shape
        out_bounds = rot_matrix @ [[0, 0, iy, iy], [0, ix, 0, ix]]
        # Compute the shape of the transformed input plane
        out_plane_shape = (out_bounds.ptp(axis=1) + 0.5).astype(int)
    else:
        out_plane_shape = img_shape[axes]

    if output_shape is None:
        output_shape = img_shape
        output_shape[axes] = out_plane_shape
    else:
        out_plane_shape = np.asarray(output_shape)[axes]

    out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
    in_center = (in_plane_shape - 1) / 2
    offset = in_center - out_center
    output_shape = tuple(output_shape)

    if ndim <= 2:

        output = affine_transform(input_arr,
                                  rot_matrix,
                                  offset=offset,
                                  output_shape=tuple(output_shape),
                                  order=order,
                                  mode=mode,
                                  cval=cval,
                                  prefilter=prefilter,
                                  output_chunks=output_chunks)

    elif ndim >= 3:
        rotmat_nd = np.eye(ndim)
        offset_nd = np.zeros(ndim)

        for o_x, idx in enumerate(axes):

            rotmat_nd[idx, axes[0]] = rot_matrix[o_x, 0]
            rotmat_nd[idx, axes[1]] = rot_matrix[o_x, 1]

            offset_nd[idx] = offset[o_x]

        output = affine_transform(input_arr,
                                  rotmat_nd,
                                  offset=offset_nd,
                                  output_shape=tuple(output_shape),
                                  order=order,
                                  mode=mode,
                                  cval=cval,
                                  prefilter=prefilter,
                                  output_chunks=output_chunks)

    return output
예제 #13
0
파일: track.py 프로젝트: nikhil-garg/l2race
def find_hit_position(angle, pos, track_map, dl=1.0):
    """
    This function returns the point at which
        a beam coming from point pos at angle given by angle variable
         for the first time crosses a non zero point on the map
         Timing at Marcin computer: dl = 5.0 -> about max 0.4 ms;
         It is roughly valid: dl/n -> time*n
     :param angle: angle (deg) in which the beam is going, e.g the body angle of the car
     :param pos: point ((x,y) in pixels) where the beam starts, e.g. position of the car
     :param track_map: a SPECIAL map which is non-zero in sand region and zero on track. Use map_lidar for it.
     :param dl: determines the precision of the collision point determination
                - the algorithm moves along the beam and checks every dl pixels (does not need to be integer)
                if it left the track
     :return the point on the track boundary which the beam first hits ((x,y) in pixels)
                    (e.g. which the car would hit if it would go on a straight line)
    """
    (h, w) = track_map.shape
    found = False

    # x = meters2pixels(pos[0])
    # y = meters2pixels(pos[1])

    x = pos[0]
    y = pos[1]

    # Depending on direction we take y = ax+b or x = ay+b
    if (45.0 < angle < 135.0) or (225.0 < angle < 315.0):
        # x = ay+b

        dy = dl * sindg(angle)
        # dy = dl
        a = cotdg(angle)
        b = x - a * y

        while 0 < x < w and 0 < y < h:
            if track_map[int(y), int(x)] > 0:
                found = True
                break
            else:
                y = y + dy
                x = a * y + b


    else:
        # dx = dl
        dx = dl * cosdg(angle)
        a = tandg(angle)
        b = y - a * x

        while 0 < x < w and 0 < y < h:
            if track_map[int(y), int(x)] > 0:
                found = True
                break
            else:
                x = x + dx
                y = a * x + b

    if found:
        hit_pos = (x, y)
    else:
        hit_pos = None

    return hit_pos
예제 #14
0
import scipy as sp
from scipy import special

fun1 = special.kelvin(15)
print(fun1)

fun2 = special.xlogy(2, 10)
print(fun2)

fun3 = special.exp10(50)
print(fun3)

fun4 = special.sindg(30)
print(fun4)

fun5 = special.cosdg(90)
print(fun5)
#help(cluster)

#scipy.info(cluster)

#help()

#special functions

from scipy import special

a = special.exp10(4)

print(a)

#getting the sin value
c = special.sindg(45)

print(c)

#intergrations

from scipy import integrate

i = scipy.integrate.quad(lambda x: x * 2 + 4, 2, 6)
print(i)

#fourirer tranformations

from scipy.fftpack import fft, ifft
import numpy as np
예제 #16
0
import scipy as sp
from scipy import special

func1 = special.kelvin(15)
print(func1)

#2 * ^elog(10)
func2 = special.xlogy(2, 10)
print(func2)

#exo10(x) = 10**(x)
func3 = special.exp10(0)
print(func3)

#sin(30)
func4 = special.sindg(90)
print(func4)