コード例 #1
0
ファイル: sig.py プロジェクト: joseph8th/mandelbrat
    def _read_sighash_config(self, sig_cfgf):

        # get pool/poolkey config from given .mbrat file
        self.cfgparser.read(path.abspath(sig_cfgf))

        print path.abspath(sig_cfgf)


        # set precision try
        try:
            prec = self.cfgparser.getint('poolkey', 'prec')
        except ConfigParser.NoOptionError:
            return None

        gmpy2.get_context().precision = prec

        # check to see if the poolkey already exists, else create it
#        sig_pool = 

        sig_d = {}
        for sec in self.cfgparser.sections():
            if sec == 'poolkey':
                sig_d[sec] = { 'name': self.cfgparser.get(sec, 'name'), 
                               'prec': prec,
                               'iters': self.cfgparser.getint(sec, 'iters'),
                               'mpoint': mpc( self.cfgparser.get(sec, 'mpoint') ),
                               }
            elif sec == 'signature':
                hash_sig_s = self.cfgparser.get(sec, 'hash_sig')
                sig_d[sec] = { 'hash_sig': [mpc(pt) for pt in hash_sig_s.split('\n')] }

        return sig_d
コード例 #2
0
ファイル: sig.py プロジェクト: joseph8th/mandelbrat
    def run_sign(self, args, return_dict=False):
        """ 
        Method to sign a hash of a given file, returning either True or a dict if return_dict==True.
        """

        from mbrat.spi.sign import SignSPI
        spi = SignSPI(mandelfun)

        print "Signing '{0}' with profile '{1}:{2}' and pool '{3}:{4}' ...".format(
            args.file, self.config.get('name'), self.privkey_cfg.get('name'),
            self.pool_cfg.get('name'), self.poolkey_cfg.get('name')
            )

        # put together arguments for the SPI
        args.spi['iters'] = int(self.pool_cfg.get('iters')) + \
            int(self.privkey_cfg.get_from_section('pool', 'iters'))

        # set the precision
        args.spi['prec'] = int(self.privkey_cfg.get('prec'))

        gmpy2.get_context().precision = args.spi['prec']

        # format the keys for mpc
        args.spi['poolkey'] = mpc( self.poolkey_cfg.get('real') + " " \
                                   + self.poolkey_cfg.get('imag') )
        args.spi['privkey'] = mpc( self.privkey_cfg.get('real') + " " \
                                   + self.privkey_cfg.get('imag') )

        ######## sign the hash ########
        hash_sig = spi.run(args)

        # init a ConfigParser compat dict with a top-section of 'mhash'
        sig_d = {'mhash': {'prec': args.spi['prec']}}

        for sec in ['pool', 'poolkey']:
            sig_d[sec] = self.cfgmgr.secmgr[sec].get_as_args(
                subsection=sec, return_dict=True)

        sig_d['signature'] = { 'hash_sig': hash_sig }        # add hash_sig

        # return a dict if desired ...
        if return_dict:
            return sig_d

        # ... or get the filename for the signature 'BASENAME.mbrat' file
        sig_cfgf = path.splitext(path.basename(args.file))[0] + ".mbrat"
        sig_cfgf = path.join( path.dirname(path.abspath(args.file)), 
                              sig_cfgf )

        self._write_sig_config(sig_d, sig_cfgf)

        return True
コード例 #3
0
def exact_fft(x, debug=False):
    ''' Calculates the exact DFT using gmpy2

    Has ~N^2 efficiency but I tried to optimize the calculation a bit.
    '''
    N = x.shape[0]
    start = time.clock()
    arg = -2j * (gmpy2.const_pi() / N)
    exp1d = np.array([gmpy2.exp(arg * idx) for idx in range(N)])
    exp = np.diag(exp1d)
    for i in range(N):
        for j in range(i+1):
            exp[j, i] = exp[i, j] = exp1d[(j * i) % N]
    stop = time.clock()
    if debug:
        print('preparation %.2fms' % ((stop-start)*1e3))

    start = time.clock()
    x = np.array([gmpy2.mpc(xi) for xi in x])
    # fsum solution - I noticed no difference except that it ran slower
#    y = []
#    for i in range(N):
#        mul = x * exp[i, :]
#        y.append(gmpy2.fsum([m.real for m in mul]) + 1j *
#                 gmpy2.fsum([m.imag for m in mul]))
#    y = np.array(y, dtype=np.complex128)
    y = np.sum(exp * x, axis=-1)
    y = np.array(y, dtype=np.complex128)
    stop = time.clock()
    if debug:
        print('calculation %.2fms' % ((stop-start)*1e3))
    return y
コード例 #4
0
def H_mpc(a,z):
    '''Returns generating function value. Takes in the a vector, the current position 
    on the parametrized variable t and the gamma function. Uses MPC and is
    not vectorized.'''
    temp=1
    n=len(a)
    for k in range(0,n):
        temp = gmpy2.div(temp, mpc((1-((z))**a[k])))
    return temp
コード例 #5
0
ファイル: sign.py プロジェクト: joseph8th/mandelbrat
    def _hash2mpc(self, hashtext, prec):
        
        # first split the hashtext in two
        reals_txt = hashtext[:(len(hashtext)/2)]
        imags_txt = hashtext[(len(hashtext)/2):]

        mpc_l = []
        for i in range(len(hashtext)/2):
            mpc_l.append( mpc( 1.0 / float(ord(reals_txt[i])), 
                               1.0 / float(ord(imags_txt[i])), 
                               precision=prec ) )
        
        return mpc_l
コード例 #6
0
ファイル: mscreen.py プロジェクト: joseph8th/mandelbrat
    def _init_from(self, args):
#        from mbrat.util import Arguments

        # 1st set the precision ...
        if not hasattr(args, 'prec'):
            args.prec = MBRAT_DEF_PRECISION
        self.prec = int(args.prec)

        gmpy2.get_context().precision = self.prec

        # ... make sure lims dict is right ...
        if not hasattr(args, 'lims'):
            self.limits = { 'low': mpc(mpfr(args.x_lo), mpfr(args.y_lo)),
                            'high': mpc(mpfr(args.x_hi), mpfr(args.y_hi)), }
        else:
            self.limits = args.lims

        # ... init the core stuff ...
        self._init_new(args)

        # ... if 'ini_d' dict provided then init more depending...
        if hasattr(args, 'ini_d'):
            if 'image' in args.ini_d:
                self.gen_mscreen_from_img( args.ini_d['image'] )
コード例 #7
0
ファイル: mscreen.py プロジェクト: joseph8th/mandelbrat
    def gen_mscreen(self):
        """
        Generate a set-rendering matrix set to the current instance properties. """

#        with precision(self.prec):
        d = float(1.0/self.ppu)
        rows = []
        for iy in range(self.px_height):
            rows.append([])
            for ix in range(self.px_width):
                x = self.limits['low'].real + d*(0.5 + ix)
                y = self.limits['high'].imag - d*(0.5 + iy)
                rows[iy].append( MPoint(mpc(x, y), self.prec) )
                rows[iy][ix].Set_Index(ix, iy)

        self.screen = rows
コード例 #8
0
ファイル: main.py プロジェクト: Ansh191/Math_Language
def evaluate(txt: str) -> object:
    global result
    num = False
    try:
        f, full_f, remaining = get_function(txt)
    except (ValueError, TypeError):
        if get_function(txt) is None:
            num = True
        else:
            return get_function(txt)

    # print(num)

    if not num:
        args = get_args(full_f, f)
        eval_args = []
        for arg in args:
            eval_args.append(evaluate(arg))
        return evaluate(str(functions[f](*eval_args)))
    elif num:

        try:
            txt = mpz(txt)
        except ValueError:
            try:
                txt = mpq(txt)
            except ValueError:
                try:
                    txt = mpc(txt)
                except ValueError:
                    if str(bool(txt)) == txt:
                        txt = bool(txt)
        try:
            if '=' in txt:
                return assign(txt)
            if '+' in txt:
                return binary_add(txt)
            if '-' in txt:
                return binary_sub(txt)
            if '*' in txt:
                return binary_mul(txt)
            if '/' in txt:
                return binary_div(txt)
        except TypeError:
            pass
        # print(txt)
        return txt
コード例 #9
0
ファイル: utils.py プロジェクト: GiggleLiu/nrg_mapping
def eigh_pauliv_mpc(a0,a1,a2,a3):
    '''
    eigen values for pauli vectors - gmpy version.

    Parameters:
        a0/a1/a2/a3: Pauli vectors.
    Return:
        Tuple of (eval,evecs), the eigenvalue decomposition of A.
    '''
    gmsqrt=gmpy2.sqrt
    gmnorm=gmpy2.norm
    e0=gmsqrt(a1**2+a2**2+a3**2)
    evals=array([a0-e0,a0+e0])
    if gmnorm(a1+a2*1j)<1e-50:
        evecs=array([[gmpy2.mpc(0),gmpy2.mpc(1)],[gmpy2.mpc(1),gmpy2.mpc(0)]])
    else:
        evecs=array([[(a3-e0)/(a1+a2*1j),gmpy2.mpc(1)],[(a3+e0)/(a1+a2*1j),gmpy2.mpc(1)]])
    for i in xrange(2):
        #evecs[i]=evecs[i]/gmsqrt(sum(gmnorm(evecs[i])))
        evecs[i]=evecs[i]/gmsqrt(gmnorm(evecs[i,0])+gmnorm(evecs[i,1]))
    return evals,evecs.T
コード例 #10
0
def f_(z,a,b):
    '''Returns the function value at z using MPC'''
    return gmpy2.div(mpc(H_mpc(a,z)),mpc((z**(b+1))))
コード例 #11
0
    def __mpc__(self): return gmpy2.mpc(42,67)
class B:
コード例 #12
0
    def __mpc__(self): return gmpy2.mpc(42,67)

z = Z()
コード例 #13
0
ファイル: utils.py プロジェクト: GiggleLiu/nrg_mapping
from matplotlib.pyplot import *
import gmpy2,pdb

__all__=['sx','sy','sz','Gmat','eigh_pauliv_npy','plot_pauli_components','mpconj','mpqr','H2G','s2vec','vec2s','sqrth2']

############################ DEFINITIONS ##############################
# pauli spin
sx = array([[0, 1],[ 1, 0]])
sy = array([[0, -1j],[1j, 0]])
sz = array([[1, 0],[0, -1]])
Gmat=array([kron(sz,sx),kron(identity(2),sy),kron(sx,sx),kron(sy,sx),kron(identity(2),sz)])

############################ FUNCTIONS ##############################

#Get the conjugate of matrix A(to avoid a bug of gmpy2.mpc.conj).
mpconj=vectorize(lambda x:gmpy2.mpc(x.real,-x.imag))

def eigh_pauliv_npy(a0,a1,a2,a3):
    '''
    eigen values for pauli vectors - numpy version.

    Parameters:
        :a0/a1/a2/a3: Pauli components.

    Return:
        Tuple of (eval,evecs), the eigenvalue decomposition of A.
    '''
    e0=sqrt(a1**2+a2**2+a3**2)
    evals=array([a0-e0,a0+e0])
    if abs(a1+a2*1j)<1e-50:
        evecs=array([[0,1],[1,0j]])
コード例 #14
0
import numpy as np
import ormsgpack

from tno.mpc.communication.serialization import GmpyTypes, typeguard_ignore
from tno.mpc.communication.test.test_packing import pack_unpack_test


@typeguard_ignore
@pytest.mark.parametrize(
    "obj",
    [
        gmpy2.xmpz(10),
        gmpy2.mpz(10),
        gmpy2.mpfr(10.0),
        gmpy2.mpq(10, 3),
        gmpy2.mpc("10+3j"),
    ],
)
def test_gmpy_serialization(obj: GmpyTypes) -> None:
    """
    Tests packing and unpacking of gmpy object

    :param obj: gmpy object to pack/unpack
    """
    pack_unpack_test(obj)


def test_gmpy_serialization_list() -> None:
    """
    Tests packing and unpacking of gmpy list object
    """
コード例 #15
0
 def mpc(a, b=None):
     "converts input into multiprecision complex - type gmpy2.mpc"
     if not b: return gm.mpc(a)
     else: return gm.mpc(a, b)