コード例 #1
0
ファイル: OOP.py プロジェクト: lauralunacabrera/LLGEO
    def __init__(self, n, i, j, xc, yc, N1, N2, N3, N4, shape, soil):
        
        # Element numbering and location
        self.n = n
        self.i = i
        self.j = j
        self.xc = xc
        self.yc = yc

        # Node numbering
        self.N1 = N1
        self.N2 = N2
        self.N3 = N3
        self.N4 = N4

        # Shape (triangular or quadrilateral) and type of soil
        self.shape = shape
        self.soil  = soil

        # Basic descriptions
        self.id   = ''
        self.name = ''
        self.desc = ''

        # Non-linear properties
        self.G_strn = np.emtpy([])
        self.G_mred = np.emtpy([])
        self.D_strn = np.emtpy([])
        self.D_damp = np.emtpy([])
コード例 #2
0
def calculateTrajectory(v0, theta, g=EARTH_GRAVITY, npts=100):
    """calculates the trajectory of a projectile 
       
        neglects air resistance
        
        Parameters
        ----------
            v0 : float
                initial velocity (in meters/second): must be >= 0
            theta : float 
                intial angle (in degrees): must be in range [0,90]
            g : float, optional
                acceleration due to gravity (in meters/second^2): must be > 0, default value EARTH_GRAVITY                 
            npts : int, optional
                number of points to calculate along the trajectory
        Returns
        -------
            x,y : ndarray of floats
                x and y positions of the projectile along the trajectory
                in case of error, 'x' and 'y' are empty
    """
    tnext = calculateIntersectionWithGround(v0, theta, g)
    if (np.isnan(tnext) or npts <= 0):
        return (np.emtpy(), np.emtpy())
    tvec = np.linspace(0, tnext, npts)
    vx = v0 * np.cos(np.deg2rad(theta))
    vy = v0 * np.sin(np.deg2rad(theta))
    x = vx * tvec
    y = vy * tvec - 0.5 * g * np.power(tvec, 2)
    return (x, y)
コード例 #3
0
def get_rotation_bbox(self, bbox, deg):
    nvert = 4
    xs = bbox.get_xs()
    ys = bbox.get_ys()
    rad = deg_to_rad(deg)
    mat = np.emtpy((2, 2), dtype='float32')
    mat[0][0] = np.cos(rad)
    mat[0][1] = -np.sin(rad)
    mat[1][0] = np.sin(rad)
    mat[1][1] = np.cos(rad)

    new_xy = np.empty(nvert * 2, dtype='float32')
    for i in range(nvert):
        xy = np.dot(mat, np.array([xs[i], ys[i]], dtype='float32'))
        new_xy[i * 2:i * 2 + 2] = xy
    return new_xy[::2], new_xy[1::2]
コード例 #4
0
ファイル: brightness.py プロジェクト: schuetzgroup/sdt-python
def from_raw_image(positions, frames, radius, bg_frame=2, bg_estimator="mean",
                   columns={}, engine="numba", mask="square"):
    """Determine particle brightness by counting pixel values

    Around each localization, pixel values are summed up (see the `mask`
    parameter) to determine the brightness (mass). Additionally, local
    background is determined by calculating the brightness (see `bg_estimator`
    parameter in a frame (again, see `mask` parameter) around this box,
    where all pixels belonging to any localization are excluded. This
    background is subtracted from the signal brightness.

    Parameters
    ----------
    positions : pandas.DataFrame
        Localization data. "signal", "mass", "bg", and "bg_dev"
        columns are added and/or replaced directly in this object.
    frames : iterable of numpy.ndarrays
        Raw image data
    radius : int
        Half width of the box in which pixel values are summed up. See `mask`
        parameter for details.
    bg_frame : int or infinity, optional
        Width of frame (in pixels) around a feature for background
        determination. If infinity, background is calculated globally from all
        pixels that are not part of any feature. Defaults to 2.
    bg_estimator : {"mean", "median"} or numpy ufunc, optional
        How to determine the background from the background pixels. "mean"
        will use :py:func:`numpy.mean` and "median" will use
        :py:func:`numpy.median`. If a function is given (which takes the
        pixel data as arguments and returns a scalar), apply this to the
        pixels. Defaults to "mean".
    mask : {"square", "circle"} or (array-like, array-like), optional
        If "square", sum pixels in a ``2 * radius + 1`` sized square around
        each localization as the brightness and use `bg_estimator` in a frame
        of `bg_frame` width around it to determine the local background, which
        is subtracted from the brightness. If "circle", sum pixels in a
        ``2 * radius + 1`` sized circle (a :py:class:`CircleMask`
        with radius `radius` and ``extra=0.5`` is used) around each
        localization and get the background from an annulus of width
        ``bg_frame``. One can also pass a tuple ``(feat_mask, bg_mask)`` of
        boolean arrays for brightness and background detection. In this case,
        `radius` and `bg_frame` are ignored. If `bg_mask` is None, calculate
        background globally (per frame) from all pixels that are not
        part of any feature. In all cases, all pixels belonging
        to any signal are automatically excluded from the background detection.
        Defaults to "square".

    Other parameters
    ----------------
    columns : dict, optional
        Override default column names as defined in :py:attr:`config.columns`.
        Relevant names are `coords`, `time`, `mass`, `signal`, `bg`, `bg_dev`.
        This means, if your DataFrame has coordinate columns "x" and "z" and
        the time column "alt_frame", set ``columns={"coords": ["x", "z"],
        "time": "alt_frame"}``.
    engine : {"numba", "python"}, optional
        Numba is faster, but only supports 2D data and mean or median
        bg_estimator. If numba cannot be used, automatically fall back to
        pure python, which support arbitray dimensions and bg_estimator
        functions. Defaults to "numba".
    """
    if not len(positions):
        positions[columns["signal"]] = []
        positions[columns["mass"]] = []
        positions[columns["bg"]] = []
        positions[columns["bg_dev"]] = []
        return

    if isinstance(bg_estimator, str):
        bg_estimator = getattr(np, bg_estimator)

    ndim = len(columns["coords"])

    if engine == "numba":
        if ndim != 2:
            warnings.warn("numba engine supports only 2D data. Falling back "
                          "to python backend.")
            engine = "python"
        if bg_estimator is np.mean:
            bg_estimator = 0
        elif bg_estimator is np.median:
            bg_estimator = 1
        else:
            warnings.warn("numba engine supports only mean and median as "
                          "bg_estimators. Falling back to python backend.")
            engine = "python"

    # Create masks for foreground pixels and background pixels around a
    # feature
    if isinstance(mask, str):
        if mask == "square":
            feat_mask = RectMask((2 * radius + 1,) * ndim)
            if math.isfinite(bg_frame):
                bg_mask = RectMask((2 * (radius + bg_frame) + 1,) * ndim)
            else:
                bg_mask = None
        elif mask == "circle":
            feat_mask = CircleMask(radius, 0.5)
            if math.isfinite(bg_frame):
                bg_mask = CircleMask(radius + bg_frame, 0.5)
            else:
                bg_mask = None
        else:
            raise ValueError('"{}" does not describe a mask'.format(mask))
    else:
        # Assume it is a tuple of arrays
        feat_mask, bg_mask = mask

    # Convert to numpy array for performance reasons
    # This is faster than pos_matrix = positions[columns["coords"]].values
    pos_matrix = []
    for p in columns["coords"]:
        pos_matrix.append(positions[p].values)
    pos_matrix = np.array(pos_matrix).T
    fno_matrix = positions[columns["time"]].values.astype(int)
    # Pre-allocate result array
    ret = np.empty((len(pos_matrix), 4))

    if engine == "numba":
        worker = _from_raw_image_numba
    elif engine == "python":
        worker = _from_raw_image_python
    else:
        raise ValueError("Unknown engine \"{}\".".format(engine))

    if bg_mask is None:
        bg_mask = np.emtpy((0,)*ndim, dtype=bool)
        global_bg = True
    else:
        global_bg = False

    fnos = np.unique(fno_matrix)
    for f in fnos:
        current = (fno_matrix == f)
        ret[current] = worker(pos_matrix[current], frames[f], feat_mask,
                              bg_mask, bg_estimator, global_bg)

    positions[columns["signal"]] = ret[:, 0]
    positions[columns["mass"]] = ret[:, 1]
    positions[columns["bg"]] = ret[:, 2]
    positions[columns["bg_dev"]] = ret[:, 3]
コード例 #5
0
             linewidth=0.5,
             alpha=0.2,
             color='red')

#plot the data point
plt.plot('data', 'data', marker='.', linestyle='none')

#Formulating and Simulating hypothesis
#Hypothesis test : Assessment of how reasonable the observed data are assuming a hypothesis is true.
#Permutation : Random reordering or entries in an array

#Try to figure out whether Pensilvania and Ohio has the same distribution. So mix combine two data and labeled again.

import numpy as np
dem_share_PA = np.empty(100)
dem_share_OH = np.emtpy(100)

dem_share_both = np.concatenate(dem_share_PA, dem_share_OH)
dem_share_perm = np.random.permutation(dem_share_both)
perm_sample_PA = dem_share_perm[:len(dem_share_PA)]
perm_sample_OH = dem_share_perm[len(dem_share_PA):]

#ou learned that permutation sampling is a great way to simulate
#the hypothesis that two variables have identical probability distributions.


def permutation_sample(data1, data2):
    """Generate a permutation dataset from two seperate dataset"""
    """np.concatenate accept tuple as input so double braket"""

    data = np.concatenate((data1, data2))
コード例 #6
0
ファイル: python13_ufunction.py プロジェクト: inJAJA/Study
# Note : 감마 함수(일반화된 계승)와 관련 함수
x = [1, 5, 10]
print('gamma(x)      = ', special.gamma(x))
print('ln|gamma(x)|  = ', special.gammaln(x))
print('beta(x)       = ', special.beta(x, 2))


# Note : 오차 함수(가우스 적분), 그 보수(complement)와 역수(inverse)
x = np.array([0, 0.3, 0.7, 1.0])
print('erf(x)    = ', special.erf(x))
print('erfc(x)   = ', special.erfc(x))
print('erfinv(x) = ', special.erfinv(x))

x = np.arange(5)
y = np.emtpy(5)
np.multiply(x, 10, out = y)
print(y)

y = np.zeros(10)
np.power(2, x, out = y[::2]) # ::n = n의 간격으로 
print(y)


# Note : 객체로부터 직접 연산하 수 있는 집계 함수
x = np.arange(1, 6)
print(np.add.reduce(x))          # 배열의 모든 요소의 합 반환
print(np.multiply.reduce(x))     # 배열의 모든 요소의 곱 반환

print(np.add.accumulate(x))      # 계산의 중간 결과를 모두 저장
print(np.multiply.accumulate(x))
コード例 #7
0
def running_mean_axis_0(
        x, y, halfwidth,
        include_left_bound=True,
        include_right_bound=False,
        assume_equidistant=False,
        assume_sorted=False,
        periodicity=np.inf,
        contains_nans=True,
        ):
    """Return running mean an the corresponding x-positions.
    
        Parameters
        ----------
        x : flat array
            positions of y.
        y : array
            the values at the x-positions to interpolate. The length of `x`
            must be the same as the dimension of `y` along the first axis.
        halfwidth : float > 0 
            half width of the averaging window
        include_left_bound : bool, optional
            use values at position x[i] - halfwidth for averaging or not.
            Default: True
        include_right_bound : bool, optional
            as include_left_bound. Default: False
        assume_equidistant : bool, optional
            set this to True if x is equidistant. Default: False
        assume_sorted : bool, optional
            set this to True if x is sorted. Default: False
        periodicity : {float, np.inf}, optional
            non-positive values (including 0) are interpreted as np.inf.
            Default: np.inf
        contains_nans : bool, optional
            Set this False, if you are sure that y does not contains nan's.
            This will speed up the function. Default: True
                
        Returns
        -------
        ymean : array
            the running mean of y
        x_out : array, same shape
            the x values of the ymean
        
        Note
        ----
        The values in ymean correspond to x_out. x_out may be different
        to x. This is the case if one or more of the following is true:
            a) periodicity is positive and finite
            b) assume_sorted is False
        
        Performance
        -----------
        The following will usually significantly speed up the function:
            a) assume_equidistant is True
            b) assume_sorted is True
            c) contains_nans is False (especially in combination with a)

        Bugs
        ----
        In the non-equadistant case, the include_bounds parameters do not work
        and intended.

        The multi-axes versions does not work.
        
        Author
        ------
        Written in 2015-2016
        by Andreas Anhaeuser
        Insitute for Geophysics and Meteorology
        University of Cologne
        Germany
        <*****@*****.**>
    """ 

    ###################################################
    # INPUT CHECK                                     #
    ###################################################
    assert 0 <= periodicity <= np.inf
    assert len(x) == len(y)

    ###################################################
    # CASE: UNSORTED                                  #
    ###################################################
    # (recursively call function with sorted arrays):
    if not assume_sorted:
        idx = np.argsort(x)
        inv_idx = np.argsort(idx)
        return running_mean_axis_0(
            x[idx], y[idx], halfwidth,
            include_left_bound=include_left_bound,
            include_right_bound=include_right_bound,
            assume_equidistant=assume_equidistant,
            assume_sorted=True,
            periodicity=periodicity,
            contains_nans=contains_nans,
            )

    ###################################################
    # ABBREVIATIONS                                   #
    ###################################################
    N = len(x)
    hw = abs(halfwidth)
    per = periodicity

    ###################################################
    # CASE: NON-EQUIDISTANT                           #
    ###################################################
    if not assume_equidistant:
        return running_mean_non_equidistant(
            x,
            y,
            halfwidth=hw,
            include_left_bound=include_left_bound,
            include_right_bound=include_right_bound,
            periodicity=per,
            contains_nans=contains_nans,
            )

    ###################################################
    # CASE: PERIODIC                                  #
    ###################################################
    periodic = (0 < per < np.inf)

    if periodic:
        # convert periodicity to number of indices
        periodic = True
        Nperiod = nearest_neighbour(x, x[0] + per)[1]
        
        #=============== FOLD ARRAYS ======================
        # case: contains nans 
        if contains_nans and Nperiod != N:
            y_new = np.zeros(Nperiod)
            count = np.zeros(Nperiod)
            for n in range(N):
                val = y[n]
                if np.isnan(val):
                    continue
                idx = n % Nperiod
                y_new[idx] += y[n]
                count[idx] += 1
            y = y_new / count
            x = x[:Nperiod]
            contains_nans = False

        # case: nan-free
        elif Nperiod != N:
            y_new = np.zeros(Nperiod)
            count = np.emtpy(Nperiod)
            beg = N % Nperiod
            count[:beg] = N//Nperiod + 1
            count[beg:] = N//Nperiod
            for n in range(N):
                y_new[n % Nperiod] += y[n]
            y = y_new / count
            x = x[:Nperiod]
        #==================================================

    ###################################################
    # CONVERT HALFWIDTH TO NUMBER OF ELEMENTS         #
    ###################################################
    xhi = x[0] + hw
    xn, n = nearest_neighbour(x, xhi, direction='d', assume_sorted=True)[:2]
    nlo = n
    nhi = n
    # include bounds or not:
    if xn == xhi:
        if not include_left_bound and nlo > 0:
            nlo -= 1
        if not include_right_bound and nhi > 0:
            nhi -= 1
        
    ###################################################
    # CALL SUB-FUNCTION                              #
    ###################################################
    mean = running_mean_equidistant(
                    y,
                    nlo=nlo,
                    nhi=nhi,
                    periodic=periodic,
                    contains_nans=contains_nans,
                    )

    return mean, x