Skip to main content
  • Home
  • Development
  • Documentation
  • Donate
  • Operational login
  • Browse the archive

swh logo
SoftwareHeritage
Software
Heritage
Archive
Features
  • Search

  • Downloads

  • Save code now

  • Add forge now

  • Help

https://github.com/brownvc/deep-synth
31 March 2020, 06:46:23 UTC
  • Code
  • Branches (1)
  • Releases (0)
  • Visits
Revision b800e11290b763b58e7d3b30329769a7b77cd12a authored by kwang-ether on 14 June 2019, 23:53:57 UTC, committed by kwang-ether on 14 June 2019, 23:53:57 UTC
remove csv
1 parent 79eaa7f
  • Files
  • Changes
    • Branches
    • Releases
    • HEAD
    • refs/heads/master
    • b800e11290b763b58e7d3b30329769a7b77cd12a
    No releases to show
  • 291f7df
  • /
  • deep-synth
  • /
  • math_utils
  • /
  • __init__.py
Raw File Download
Take a new snapshot of a software origin

If the archived software origin currently browsed is not synchronized with its upstream version (for instance when new commits have been issued), you can explicitly request Software Heritage to take a new snapshot of it.

Use the form below to proceed. Once a request has been submitted and accepted, it will be processed as soon as possible. You can then check its processing state by visiting this dedicated page.
swh spinner

Processing "take a new snapshot" request ...

To reference or cite the objects present in the Software Heritage archive, permalinks based on SoftWare Hash IDentifiers (SWHIDs) must be used.
Select below a type of object currently browsed in order to display its associated SWHID and permalink.

  • revision
  • directory
  • content
  • snapshot
origin badgerevision badge
swh:1:rev:b800e11290b763b58e7d3b30329769a7b77cd12a
origin badgedirectory badge
swh:1:dir:e2713c3a0ca56a4a629d45eecb6fc986259168e5
origin badgecontent badge
swh:1:cnt:12042d5ffbb84d06cb6777e8c0aa4b619d30c4b7
origin badgesnapshot badge
swh:1:snp:0f10b5007a9962ed82323ed2242cf08ba5544645

This interface enables to generate software citations, provided that the root directory of browsed objects contains a citation.cff or codemeta.json file.
Select below a type of object currently browsed in order to generate citations for them.

  • revision
  • directory
  • content
  • snapshot
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Tip revision: b800e11290b763b58e7d3b30329769a7b77cd12a authored by kwang-ether on 14 June 2019, 23:53:57 UTC
remove csv
Tip revision: b800e11
__init__.py
import itertools
import scipy
import math
import matplotlib as mpl
import numpy as np

from scipy.stats import vonmises
from pyquaternion import Quaternion

try:
    import matplotlib.pyplot as plt
except RuntimeError:
    print('ERROR importing pyplot, plotting functions unavailable')


class Transform:
    """
    Represents an affine transformation composed of translation, rotation, scale
    """
    def __init__(self, translation=np.asarray((0, 0, 0)), rotation=Quaternion(), scale=np.asarray((1, 1, 1))):
        self._t = translation
        self._r = rotation
        self._s = scale

    @property
    def rotation(self):
        return self._r

    @property
    def translation(self):
        return self._t

    @property
    def scale(self):
        return self._s

    @classmethod
    def from_mat4(cls, m):
        """
        Construct Transform from matrix m
        :param m: 4x4 affine transformation matrix
        :return: rotation (quaternion), translation, scale
        """
        translation = m[:3, 3]
        scale_rotation = m[:3, :3]
        u, _ = scipy.linalg.polar(scale_rotation)
        rotation_q = Quaternion(matrix=u)
        r_axis = rotation_q.get_axis(undefined=[0, 1, 0])
        # ensure that rotation axis is +y
        if np.array(r_axis).dot(np.array([0, 1, 0])) < 0:
            rotation_q = -rotation_q
        scale = np.linalg.norm(scale_rotation, axis=0)
        return cls(translation=translation, rotation=rotation_q, scale=scale)

    @classmethod
    def from_mat4x4_flat_row_major(cls, mat):
        return cls.from_mat4(np.array(mat).reshape((4, 4)).transpose())

    @classmethod
    def from_node(cls, node):
        if hasattr(node, 'transform'):
            # get rotation and translation out of 4x4 xform
            return cls.from_mat4x4_flat_row_major(node.transform)
        elif hasattr(node, 'type') and hasattr(node, 'bbox'):
            p_min = np.array(node.bbox['min'])
            p_max = np.array(node.bbox['max'])
            center = (p_max + p_min) * 0.5
            half_dims = (p_max - p_min) * 0.5
            return cls(translation=center, scale=half_dims)
        else:
            return None

    def as_mat4(self):
        m = np.identity(4)
        m[:3, 3] = self._t
        r = self._r.rotation_matrix
        for i in range(3):
            m[:3, i] = r[:, i] * self._s[i]
        return m

    def as_mat4_flat_row_major(self):
        return list(self.as_mat4().transpose().flatten())

    def inverse(self):
        return self.from_mat4(np.linalg.inv(self.as_mat4()))

    def set_translation(self, t):
        self._t = t

    def translate(self, t):
        self._t += t

    def rotate(self, radians, axis):
        q = Quaternion(axis=axis, radians=radians)
        self._r = q * Quaternion(matrix=self._r)

    def set_rotation(self, radians, axis=np.asarray((0, 1, 0))):
        self._r = Quaternion(axis=axis, radians=radians)

    def rotate_y(self, radians):
        self.rotate(radians, [0, 1, 0])

    def rescale(self, s):
        self._s = np.multiply(self._s, s)

    def transform_point(self, p):
        # TODO cache optimization
        return np.matmul(self.as_mat4(), np.append(p, [1], axis=0))[:3]

    def transform_direction(self, d):
        # TODO cache optimization
        return np.matmul(np.transpose(self._r.rotation_matrix), d)


def relative_pos_to_xz_distance_angle(p):
    ang = math.atan2(p[2], p[0])
    dist = math.sqrt(p[0] * p[0] + p[2] * p[2])
    return dist, ang


def relative_dir_to_xz_angle(d):
    return math.atan2(d[2], d[0])


def nparr2str_compact(a):
    # drop '[ and ]' at ends and condense whitespace
    v = []
    for i in range(a.shape[0]):
        v.append('%.6g' % a[i])
    return ' '.join(v)
    # return re.sub(' +', ' ', np.array2string(a, precision=5, suppress_small=True)[1:-1]).strip()


def str2nparr(sa):
    return np.fromstring(sa, dtype=float, sep=' ')


def plot_gmm_fit(x, y_, means, covariances, index, title):
    color_iter = itertools.cycle(['navy', 'c', 'cornflowerblue', 'gold', 'darkorange'])
    subplot = plt.subplot(3, 1, 1 + index)
    for i, (mean, covariance, color) in enumerate(zip(means, covariances, color_iter)):
        v, w = scipy.linalg.eigh(covariances)
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        u = w[0] / scipy.linalg.norm(w[0])
        # DP GMM will not use every component it has access to unless it needs it, don't plot redundant components
        if not np.any(y_ == i):
            continue
        plt.scatter(x[y_ == i, 0], x[y_ == i, 1], .8, color=color)
        # Plot an ellipse to show the Gaussian component
        angle = np.arctan(u[1] / u[0])
        angle = 180. * angle / np.pi  # convert to degrees
        ell = mpl.patches.Ellipse(mean, v[0], v[1], 180. + angle, color=color)
        ell.set_clip_box(subplot.bbox)
        ell.set_alpha(0.5)
        subplot.add_artist(ell)
    plt.title(title)


def plot_vmf_fit(x, mu, kappa, scale, index, title):
    subplot = plt.subplot(3, 1, 1 + index)
    plt.hist(x, bins=8, normed=True, histtype='stepfilled')
    domain = np.linspace(vonmises.ppf(0.01, kappa), vonmises.ppf(0.99, kappa), 100)
    plt.plot(domain, vonmises.pdf(domain, kappa=kappa, loc=mu, scale=scale))
    plt.title(title)


def plot_hist_fit(x, hist_dist, index, title):
    subplot = plt.subplot(3, 1, 1 + index)
    plt.hist(x, bins=16, normed=True, histtype='stepfilled')
    domain = np.linspace(-math.pi, math.pi, 16)
    plt.plot(domain, hist_dist.pdf(domain))
    plt.title(title)
The diff you're trying to view is too large. Only the first 1000 changed files have been loaded.
Showing with 0 additions and 0 deletions (0 / 0 diffs computed)
swh spinner

Computing file changes ...

back to top

Software Heritage — Copyright (C) 2015–2026, The Software Heritage developers. License: GNU AGPLv3+.
The source code of Software Heritage itself is available on our development forge.
The source code files archived by Software Heritage are available under their own copyright and licenses.
Terms of use: Archive access, API— Content policy— Contact— JavaScript license information— Web API