Пример #1
0
def main():
    global trend
    global total_cost
    state = 'start'

    while True:
        try:
            log('====', state, '====')
            now = time.time()
            lifetime = now - start_time
            total_cost = INSTANCE_COST * lifetime
            log("Life Time [sec]: COST", lifetime, total_cost)
            trend = check_trend()
            state = eval(state+"()")
            if check_life():
                died_clean(state)
                notify('DIED', uuid, show_options(), ['text', 'pretext']) 
                log('DIED', uuid, show_options()) 
                break
        except:
            if slack_url:
                notify(uuid, 'ERROR RAISED', str(sys.exc_info()), ['text', 'pretext'])
                notify('DIED', uuid, show_options(), ['text', 'pretext']) 
            died_clean(state)
            log('ERROR RAISED' + str(sys.exc_inf()))
            traceback.print_exc()
            return 1
        sleep(INTERVAL)
Пример #2
0
def main(args=None):
    mode = 'text'
    if (args): mode = args.mode
    soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print('Socket created')

    try:
        if (mode == 'bin'): soc.bind(('', 1200))
        else: soc.bind(('', 1400))
        print('Socket bind complete')
    except socket.error as msg:
        import sys
        print('Bind failed. Error: ' + str(sys.exc_inf()))
        sys.exit()
    ##end try

    t = Process(target=listen, args=(soc, mode))
    t.start()
    try:
        while 1:
            cmd = input()
            if (mode == 'bin'):
                a = bytearray()
                for v in cmd.split():
                    a.append(int(v, base=16))
                soc.sendto(a, ('192.168.1.3', 1200))
            else:
                soc.sendto(cmd.encode(), ('127.0.0.1', 1300))
        ##end while
    except (KeyboardInterrupt, SystemExit):
        t.join()
Пример #3
0
def cat(fname):
    try:
        file = open(fname, "r")
        for line in file:
            # 改行せずに出力
            sys.stdout.write(line)
        file.close()
    except IOError as e:
        print "IOError: {0}".format(e)
    except:
        print "Unexpected error:", sys.exc_inf()[0]
        raise
Пример #4
0
    def process(self, eventId, UCID):
        try:
            self.hub.log("Processing Event: %s Source: %s" % (eventId, UCID))

            if eventId == 0xF0000000L:
                self.updateComponentList()

            if self.updateCounters == True:
                print "Received: %d Sent: %d" % (self.hub.received, self.hub.sent)


        except:
            traceback.print_exc()
            self.hub.log(sys.exc_info([0]))
            if (self.errorHandler <> None):
                self.errorHandler.raiseException(sys.exc_inf()[0], "Error processing message EventID : %s UCID: %s" % (eventId, UCID), false)
            else:
                raise    
Пример #5
0
def import_string(import_name, silent=False):
    """Imports an object based on a string.  This is useful if you want to
    use import paths as endpoints or something similar.  An import path can
    be specified either in dotted notation (``xml.sax.saxutils.escape``)
    or with a colon as object delimiter (``xml.sax.saxutils:escape``).

    If `silent` is True the return value will be `None` if the import fails.

    For better debugging we recommend the new :func:`import_module`
    function to be used instead.

    :param import_name: the dotted name for the object to import.
    :param silent: if set to `True` import errors are ignored and
                   `None` is returned instead.
    :return: imported object

    :copyright: (c) 2011 by the Werkzeug Team
    """
    # force the import name to automatically convert to strings
    if isinstance(import_name, unicode):
        import_name = str(import_name)
    try:
        if ':' in import_name:
            module, obj = import_name.split(':', 1)
        elif '.' in import_name:
            module, obj = import_name.rsplit('.', 1)
        else:
            return __import__(import_name)
        # __import__ is not able to handle unicode strings in the fromlist
        # if the module is a package
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        try:
            return getattr(__import__(module, None, None, [obj]), obj)
        except (ImportError, AttributeError):
            # support importing modules not yet set up by the parent module
            # (or package for that matter)
            modname = module + '.' + obj
            __import__(modname)
            return sys.modules[modname]
    except ImportError as e:
        if not silent:
            six.reraise(ImportStringError, ImportStringError(import_name, e), sys.exc_inf()[2])
Пример #6
0
    def connect(self):
        try:
            #self.errorHandler = new AlertExceptionHandler(this);
            self.server = UDPServer("", 6000)
            #//server = new TCPServer("", 6000)
            #//server = new SuperServer()
            self.server.errorHandler = self.errorHandler
            self.server.start()
            self.hub = Hub.MultimodalHub("hub", self.server)
            self.hub.errorHandler = self.errorHandler
            #self.hub.textOutput = log

            self.hub.setProcessor(self.process)
            self.hub.log("Connect #0")
        except:
            #if self.hub <> None:
            #    self.hub.log(sys.exc_inf()[0])
            if (self.errorHandler <> None):
                self.errorHandler.raiseException(sys.exc_inf()[0], "Error creating server", true)
            else:
                raise
Пример #7
0
def lstsq(a,
          b,
          rcond=None,
          sigma_b=None,
          weight=False,
          uncertainties=True,
          covariances=False,
          digested_output=False,
          svd=True,
          last_svd=None):
    """
    Return the least-squares solution to a linear matrix equation.

    Solves the equation `a x = b` by computing a vector `x` that
    minimizes the Euclidean 2-norm `|| b - a x ||^2`.  The equation may
    be under-, well-, or over- determined (i.e., the number of
    linearly independent rows of `a` can be less than, equal to, or
    greater than its number of linearly independent columns).  If `a`
    is square and of full rank, then `x` (but for round-off error) is
    the "exact" solution of the equation.

    Parameters
    ----------
    a : array_like, shape (M, N)
        "Model" matrix.
    b : array_like, shape (M,) or (M, K)
        Ordinate or "dependent variable" values. If `b` is two-dimensional,
        the least-squares solution is calculated for each of the `K` columns
        of `b`.
    sigma_b : uncertainties on the b values or None. If sigma_b has shape (M,) or (M, 1) and
              b has dimension (M, K), the uncertainty will be the same for all spectra.

    weight: 0 - No data weighting.
                Uncertainty of 1 for each data point.
            1 - Statistical weight.
                Weighted fit using the supplied experimental uncertainties or the
                square root of the b values.

    svd: If not true, a simple matrix inversion will be used in case of weighting with unequal
         data weights. Ignored in any other cases.

    last_svd: Tuple containing U, s, V of the weighted model matrix or None. This is to
                    prevent recalculation on repeated fits.

    uncertainties: If False, no uncertainties will be calculated unless the covariance
                matrix is requested.

    covariances: If True, an array of covariance matrix/matrices will be returned.

    digested_output: If True, returns a dictionary with explicit keys

    Returns
    -------
    x : ndarray, shape (N,) or (N, K)
        Least-squares solution.  The shape of `x` depends on the shape of
        `b`.

    uncertainties: ndarray, shape (N,) or (N, K)

    covariances: ndarray, shape (N, N) or (K, N, N)

    Examples
    --------
    Fit a line, ``y = mx + c``, through some noisy data-points:

    >>> x = np.array([0, 1, 2, 3])
    >>> y = np.array([-1, 0.2, 0.9, 2.1])

    By examining the coefficients, we see that the line should have a
    gradient of roughly 1 and cut the y-axis at, more or less, -1.

    We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
    and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

    >>> A = np.vstack([x, np.ones(len(x))]).T
    >>> A
    array([[ 0.,  1.],
           [ 1.,  1.],
           [ 2.,  1.],
           [ 3.,  1.]])

    >>> m, c = np.linalg.lstsq(A, y)[0]
    >>> print m, c
    1.0 -0.95

    Plot the data along with the fitted line:

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'o', label='Original data', markersize=10)
    >>> plt.plot(x, m*x + c, 'r', label='Fitted line')
    >>> plt.legend()
    >>> plt.show()

    """
    a = numpy.array(a, dtype=numpy.float, copy=False)
    b = numpy.array(b, dtype=numpy.float, copy=False)
    a_shape = a.shape
    b_shape = b.shape
    original = b_shape
    if len(a_shape) != 2:
        raise ValueError("Model matrix must be two dimensional")
    if len(b_shape) == 1:
        b.shape = b_shape[0], 1
        b_shape = b.shape

    m = a.shape[0]
    n = a.shape[1]

    if m != b.shape[0]:
        raise ValueError('Incompatible dimensions between A and b matrices')

    fastest = False
    if weight:
        if sigma_b is not None:
            # experimental uncertainties provided these are the ones to use (if any)
            w = numpy.abs(numpy.array(sigma_b, dtype=numpy.float, copy=False))
            w = w + numpy.equal(w, 0)
            if w.size == b_shape[0]:
                # same uncertainty for every spectrum
                fastest = True
                w.shape = b.shape[0]
            else:
                w.shape = b_shape
        else:
            # "statistical" weight
            # we are asked to somehow weight the data but no uncertainties provided
            # assume the uncertainties are the square root of the b values ...
            w = numpy.sqrt(numpy.abs(b))
            w = w + numpy.equal(w, 0)
    else:
        # we have an unweighted fit with no uncertainties
        # assume all the uncertainties equal to 1
        fastest = True
        w = numpy.ones(b.shape, numpy.float)
    if len(w.shape) == 1:
        w.shape = -1, 1
    if covariances:
        covarianceMatrix = numpy.zeros((b_shape[1], n, n), numpy.float)

    if not weight:
        # no weight is applied
        # get the SVD decomposition of the A matrix
        # One could avoid calculating U, s, V each time ...
        if last_svd is not None:
            U, s, V = last_svd
        else:
            U, s, V = numpy.linalg.svd(a, full_matrices=False)

        if rcond is None:
            s_cutoff = max(m, n) * numpy.finfo(numpy.float).eps
        elif rcond == -1:
            s_cutoff = n * numpy.finfo(numpy.float).eps
        else:
            s_cutoff = rcond * s[0]
        s[s < s_cutoff] = numpy.inf

        # and get the parameters
        s.shape = -1
        dummy = numpy.dot(V.T, numpy.eye(n) * (1. / s))
        parameters = numpy.dot(dummy, numpy.dot(U.T, b))
        parameters.shape = n, b.shape[1]
        if uncertainties or covariances:
            # get the uncertainties
            #(in the no-weight case without experimental uncertainties,
            # the uncertainties on the data points are ignored and the
            # uncertainty on the fitted parameters are independent of the input data!!!!)
            if fastest:
                # This is correct for all weights equal to 1
                _covariance = numpy.dot(dummy, dummy.T)
                sigmapar = numpy.sqrt(numpy.diag(_covariance))
                sigmapar = numpy.outer(sigmapar, numpy.ones(b_shape[1]))
                sigmapar.shape = n, b_shape[1]
                if covariances:
                    covarianceMatrix[:] = _covariance
            elif covariances:
                # loop in order not to use potentially big matrices
                # but calculates the covariance matrices
                # It only makes sense if the covariance matrix is requested
                sigmapar = numpy.zeros((n, b_shape[1]), numpy.float)
                for k in range(b_shape[1]):
                    pseudoData = numpy.eye(b_shape[0]) * w[:, k]
                    tmpTerm = numpy.dot(dummy, numpy.dot(U.T, pseudoData))
                    _covariance[:, :] = numpy.dot(tmpTerm, tmpTerm.T)
                    sigmapar[:, k] = numpy.sqrt(numpy.diag(_covariance))
                    covarianceMatrix[k] = _covariance
            else:
                # loop in order not to use potentially big matrices
                # but not calculating the covariance matrix
                d = numpy.zeros(b.shape, numpy.float)
                sigmapar = numpy.zeros((n, b_shape[1]))
                for k in range(b_shape[0]):
                    d[k] = w[k]
                    sigmapar += (numpy.dot(dummy, numpy.dot(U.T, d)))**2
                    d[k] = 0.0
                sigmapar[:, :] = numpy.sqrt(sigmapar)
    elif fastest:
        # same weight for all spectra
        # it could be made by the calling routine, because it is equivalent to supplying a
        # different model and different independent values ...
        # That way one could avoid calculating U, s, V each time
        A = a / w
        b = b / w
        # get the SVD decomposition of the A matrix
        if last_svd is not None:
            U, s, V = last_svd
        else:
            U, s, V = numpy.linalg.svd(A, full_matrices=False)

        if rcond is None:
            s_cutoff = n * numpy.finfo(numpy.float).eps
        else:
            s_cutoff = rcond * s[0]
        s[s < s_cutoff] = numpy.inf

        # and get the parameters
        s.shape = -1
        dummy = numpy.dot(V.T, numpy.eye(n) * (1. / s))
        parameters = numpy.dot(dummy, numpy.dot(U.T, b))
        parameters.shape = n, b.shape[1]
        if uncertainties or covariances:
            _covariance = numpy.dot(dummy, dummy.T)
            sigmapar = numpy.sqrt(numpy.diag(_covariance))
            sigmapar = numpy.outer(sigmapar, numpy.ones(b_shape[1]))
            sigmapar.shape = n, b_shape[1]
            if covariances:
                covarianceMatrix[:] = _covariance
    else:
        parameters = numpy.zeros((n, b_shape[1]), numpy.float)
        sigmapar = numpy.zeros((n, b_shape[1]), numpy.float)
        if svd:
            # SVD - slower by a factor 2
            for i in range(b_shape[1]):
                tmpWeight = w[:, i:i + 1]
                tmpData = b[:, i:i + 1] / tmpWeight
                A = a / tmpWeight
                U, s, V = numpy.linalg.svd(A, full_matrices=False)
                if rcond is None:
                    s_cutoff = n * numpy.finfo(numpy.float).eps
                else:
                    s_cutoff = rcond * s[0]
                s[s < s_cutoff] = numpy.inf
                s.shape = -1
                dummy = numpy.dot(V.T, numpy.eye(n) * (1. / s))
                parameters[:, i:i + 1] = numpy.dot(dummy,
                                                   numpy.dot(U.T, tmpData))
                if uncertainties or covariances:
                    # get the uncertainties
                    _covariance = numpy.dot(dummy, dummy.T)
                    sigmapar[:, i] = numpy.sqrt(numpy.diag(_covariance))
                    if covariances:
                        covarianceMatrix[i] = _covariance
        elif 1:
            # Pure matrix inversion (faster than SVD)
            # I do not seem to gain anything by re-using the storage
            #alpha = numpy.empty((n, n), numpy.float)
            #beta = numpy.empty((n, 1), numpy.float)
            for i in range(b_shape[1]):
                tmpWeight = w[:, i:i + 1]
                A = a / tmpWeight
                tmpData = b[:, i:i + 1] / tmpWeight
                #numpy.dot(A.T, A, alpha)
                #numpy.dot(A.T, tmpData, beta)
                alpha = numpy.dot(A.T, A)
                beta = numpy.dot(A.T, tmpData)
                try:
                    _covariance = numpy.linalg.inv(alpha)
                except:
                    print("Exception")
                    print("Exception", sys.exc_info()[1])
                    continue
                parameters[:, i:i + 1] = numpy.dot(_covariance, beta)
                if uncertainties:
                    sigmapar[:, i] = numpy.sqrt(numpy.diag(_covariance))
                if covariances:
                    covarianceMatrix[i] = covariance
        else:
            # Matrix inversion with buffers does not improve
            bufferProduct = numpy.empty((n, n + 1), numpy.float)
            bufferAB = numpy.empty((b_shape[0], n + 1), numpy.float)
            alpha = numpy.empty((n, n), numpy.float)
            for i in range(b_shape[1]):
                tmpWeight = w[:, i:i + 1]
                A = a / tmpWeight
                tmpData = b[:, i:i + 1] / tmpWeight
                bufferAB[:, :n] = A
                bufferAB[:, n:n + 1] = tmpData
                numpy.dot(A.T, bufferAB, bufferProduct)
                alpha[:, :] = bufferProduct[:n, :n]
                beta = bufferProduct[:, n]
                try:
                    _covariance = numpy.linalg.inv(alpha)
                except:
                    print("Exception")
                    print("Exception", sys.exc_inf())
                    continue
                parameters[:, i] = numpy.dot(_covariance, beta)
                if uncertainties:
                    sigmapar[:, i] = numpy.sqrt(numpy.diag(_covariance))
                if covariances:
                    covarianceMatrix[i] = covariance
    if len(original) == 1:
        parameters.shape = -1
    if covariances:
        sigmapar.shape = parameters.shape
        if len(original) == 1:
            covarianceMatrix.shape = parameters.shape[0], parameters.shape[0]
        result = [parameters, sigmapar, covarianceMatrix]
    elif uncertainties:
        sigmapar.shape = parameters.shape
        result = [parameters, sigmapar]
    else:
        result = [parameters]

    if digested_output:
        ddict = {}
        ddict['parameters'] = result[0]
        if len(result) > 1:
            ddict['uncertainties'] = result[1]
        elif covariances:
            ddict['covariances'] = result[2]
        if svd or fastest:
            ddict['svd'] = (U, s, V)
        return ddict
    else:
        return result