コード例 #1
0
ファイル: statlab2.py プロジェクト: benehlert/StatLab
    def analyze(self, sw=100):
        #Recalculate everything
        self.calc()

        vals = sp.vstack((self.beta_hat.T,self.deviation, self.tstats, self.pvals)).T
        
        
        print "Analyze".center(sw, "=")
        print ("\tAlpha = %.3f" % self.alpha)
        print ("\tDecision rule = %.5f" % self.drule)
        print ("\tR**2 adjusted = %.5f" % self.r2a())

        #temporaily set scipy pretty print options
        #sp.set_printoptions(precision=5, linewidth=sw, suppress=True)
        
        print "\tBeta\tDev\tT-stats\tP-vals"
        for irow in xrange(self.Xdim):
            if self.vtags.has_key(irow):
                label = self.vtags[irow][:7]
            else:
                label = str(irow)
            print "%s\t" % label,"\t".join([("%.5f"%v)[:7] for v in vals[irow,:]])
            
    
        #print "    Alpha: %.3f" % self.alpha
        #print "    Decision rule: %.5f" %self.drule
        #print "    beta             dev              tstats           pvals"
        #print 
        #return 
        sp.set_printoptions()
コード例 #2
0
    def main_loop(self):
        sp.set_printoptions(precision=16)
        it = 0
        while it <= 1000:
            print("\n\n=====================================================")
            print("cycle = ", self.cycle, "it = ", it)
            print("=====================================================")

            # if it > self.maxs:
            if it > 40:
                sys.exit("Exceeded maximum number of iterations. ABORTING!")

            if self.cycle > 2:
                sys.exit("got to cycle 3, exit")

            for iev in range(self.nev):
                self.iev = iev
                self.extend_right_handed_spaces(iev)
                if self.cycle > 1:
                    self.extend_left_handed_spaces(iev)
                it = it + 1

            # Build subspace matrix : v*Av = v*w
            submat = self.build_subspace_matrix()
            dnorm = self.get_residual_vectors(submat)

            skip = np.ndarray(self.nev, np.bool)
            for ii in range(self.nev):
                if dnorm[ii] <= self.threshold:
                    skip[ii] = True
                else:
                    skip[ii] = False

            print("self.teta = ", self.teta)
            if False in skip[:self.nev]:
                print("Not converged on iteration ", it)
                print("dnorm = ", dnorm, "skip = ", skip)
            else:
                print("Final eigenvalues = ",
                      self.real_precision(self.teta[:self.nev]))
                sys.exit("Converged!!")

            self.cycle = self.cycle + 1
コード例 #3
0
def estimate_dispersion_chunk(gene_counts, matrix, sf, options, test_idx, idx, log=False):

    disp_raw = sp.empty((idx.shape[0], 1), dtype='float')
    disp_raw.fill(sp.nan)
    disp_raw_conv = sp.zeros((idx.shape[0], 1), dtype='bool')

    npr.seed(23)
    for i in range(idx.shape[0]):

        if log:
            log_progress(i, idx.shape[0])

        disp = 0.1
        resp = gene_counts[i, :].astype('int')

        if sum(resp / sf) < options.min_count or sp.mean(resp == 0) > 0.6 or not test_idx[i]:
            continue

        for j in range(10):
            modNB  = sm.GLM(resp, matrix, family=sm.families.NegativeBinomial(alpha=disp), offset=sp.log(sf))
            result = modNB.fit()

            sp.set_printoptions(12)

            last_disp = disp
            yhat = result.mu
            sign = -1.0
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                res = minimize_scalar(likelihood.adj_loglikelihood_scalar, args=(matrix, resp, yhat, sign), method='Bounded', bounds=(0, 10.0), tol=1e-5)
            disp = res.x

            if abs(sp.log(disp) - sp.log(last_disp)) < 1e-4:
                disp_raw[i] = disp
                disp_raw_conv[i] = True
                break
        else:
            disp_raw[i] = disp
            disp_raw_conv[i] = False
    if log:
        log_progress(idx.shape[0], idx.shape[0])

    return (disp_raw, disp_raw_conv, idx)
コード例 #4
0
def main_routine (filelist,writeCnt=8,readCnt=16):
  files  = [line.rstrip('\n') for line in open(filelist)]
  
  coeffs = sp.zeros([2*writeCnt+readCnt,len(files)],complex)
  
  nRead=readCnt
  nDown=nRead+writeCnt
  nUp  =nDown+writeCnt
  
  texDown=writeCnt
  texUp  =texDown+writeCnt
  texRead=texUp+readCnt
  
  myFmt = ""
  
  for i in sp.arange(len(files)) :
    filename=files[i]
    print "read: " + filename
    
    if (myFmt != ""):
      myFmt += " & "
      
    myFmt = myFmt + "$%.3f %+.3f~\im$"

    reGamma,imGamma=sp.loadtxt(filename).T 
    alphaR         =reGamma[0:nRead]    +1j*imGamma[0:nRead]
    alphaD         =reGamma[nRead:nDown]+1j*imGamma[nRead:nDown]
    alphaU         =reGamma[nDown:nUp]  +1j*imGamma[nDown:nUp]

    coeffs[      0:texDown,i]=alphaD  
    coeffs[texDown:texUp  ,i]=alphaU
    coeffs[texUp  :texRead,i]=alphaR

  myFmt = "$\\alpha^{}_{}$ & " + myFmt + "\\\\"

  sp.set_printoptions(precision=3)
  sp.savetxt(filelist+".tbl",coeffs,delimiter="&",fmt=myFmt) 
コード例 #5
0
# Import Standard Libraries
import time
import logging
import argparse
import scipy as np

# Import Local Libraries
from properties import Properties
from modules import ChainModule
from modules import InputModule
from modules import InitModule
from modules import NonlinModule
from modules import SampleModule
from modules import ControlModule
from modules import Execute
np.set_printoptions(precision=4)


def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')

    parser = argparse.ArgumentParser()
    parser.add_argument("file_path", help="Path to properties file", type=str)
    file = parser.parse_args().file_path
    start = time.time()

    # Props & Globdat
    conf = Properties()
    props = Properties()
    globdat = Properties()
    props.parseFile(file)
コード例 #6
0
ファイル: Diffract.py プロジェクト: jlettvin/RPN
###############################################################################
import sys, itertools, scipy

from scipy                       import array, arange, ones, zeros
from scipy                       import exp, sqrt, pi, fabs, ceil
from scipy                       import set_printoptions
from scipy.special               import j1
from scipy.misc                  import imresize
from scipy.ndimage.interpolation import affine_transform
from Image                       import fromarray

from Pickets                     import Pickets
from Report                      import Report
###############################################################################
set_printoptions(precision=2, suppress=True, linewidth=150)

###############################################################################
class Human(Report):

    aawf = {'radius'    : 0e+0,
            'amplitude' : 1e+0,
            'aperture'  : 1e-3,
            'wavelength': 4e-7,
            'focal'     :17e-3}
    zeroPoints = [ # u values where Airy goes to zero, discovered by hand.
            3.83170611001,
            7.01558711101,
            10.1734711001,                  # Maximum kernel radius parameter.
            # u = (pi*r*a) / (w*f) where:
            # r     radius      kernel max
コード例 #7
0
ファイル: grid.py プロジェクト: tjeckleburg/hypsur
 def __str__(self):
     sp.set_printoptions(precision=8)
     return self.defCurveXYZ.__str__()
コード例 #8
0
ファイル: test.py プロジェクト: treygreer/treb
from dynamics.object import Rectangle, Circle, Beam
from dynamics.constraint import Nail, Rod, Pin, Shelf
from dynamics.animation import Animation

from dynamics.constants import foot2meter, inch2meter, meter2foot
from dynamics.misc import length_, rot2radians, radians2rot
from dynamics.constants import lb2kgram, kgram2lb, newton2lb
from dynamics.constants import pine_density, steel_density

import scipy
import scipy.interpolate
import numpy as np
from math import pi, sin, cos, sqrt, acos, atan2
from scipy.optimize.minpack import fsolve

scipy.set_printoptions(precision=5, linewidth=200)

def continue_sim(sim, time, y):
    "continue simulation?"
    return True

sim_duration = 2.0
time_step = 0.001
debug = True

sim = dynamics.simulation.Simulation(max_time=sim_duration,
                                         time_step=time_step)
sim.debug=debug
hinge_pos = (0.0, 0.0)
cw_mass = lb2kgram(2000.)
ramp_length = foot2meter(10.)
コード例 #9
0
import cPickle as pickle
import csv
import re
import scipy

import pylab


__author__ = 'marrabld'

import pidly # Use this to call one of DIMITRI's IDL functions and pass back the data structure

##!! This is required to prevent unwanted linefeeds in the csv file
scipy.set_printoptions(linewidth=2000)


class DimitriSatelliteObject():
    def __init__(self, gdl_path='/usr/bin/gdl'):

        self.idl = pidly.IDL(gdl_path, idl_prompt='GDL> ')
        self.l1b_data = None
        self.bands = {
            'PARASOL': ['443', '490p', '490u', '490q', '565', '670p', '670u', '670q', '763', '765', '865p', '865u',
                        '865q', '910', '1020'],
            'MERIS': ['412', '443', '490', '510', '560', '620', '665', '681', '708', '753', '761', '778',
                      '865', '885', '900']} ## !!! these are the same as DIMITRI FOR NOW!! CHECK
        self.sensor_name = 'PARASOL'
        self.num_bands = 16


    def read_satellite_file(self,
コード例 #10
0
ファイル: PDE.py プロジェクト: atkm/reed-modeling
## finite difference for 2d grid.
## set up
import scipy as sp
sp.set_printoptions(precision = 2, suppress = True, linewidth=200)
## suggested... Tb = 176, Ti = 26, c1 = 3, c2 = .17, w = 1

## step forward
def u_next(S,i,j,c, delta_t, delta_s,m,n):
   return  S[i,j] + c*delta_t/delta_s**2*(S[min(i+1,m-1),j] + S[max(i-1,0),j] - 4*S[i,j] + S[i, min(j+1,n-1)] + S[i,max(j-1,0)])

#bindM will maintain boundary conditions
def bindM(S, Tb):
    M = S.copy()
    m = M.shape[0]
    n = M.shape[1]
    for i in range(m):
        for j in range(n):
            M[i,0] = M[0,j] = M[m-1,j] = M[i,n-1] = Tb
    return M 
# sets up initial conditions
def init_con(In, Ti,w):
    m= In.shape[0]
    n = In.shape[1]
    for i in range(m):
        for j in range(n):
            if (i >= w and j >= w) and (i < m-1 and j < n-1):
                In[i,j] = Ti

def heating_up(m,n, tf, c1, c2,w, Ti, Tb,delta_t,outputfile):
    # define spatial mesh
    S = sp.zeros(m*n).reshape(m,n)
コード例 #11
0
left = PML_WIDTH
right = SIZE_X - PML_WIDTH

# Permittivity and permeability of PML
MU_R = 1
EPSILON_R = 1
muR = sp.ones((SIZE_X, SIZE_Y))
muR[:, bottom:top] *= MU_R
epsR = sp.ones((SIZE_X, SIZE_Y))
epsR[:, bottom:top] *= EPSILON_R

# Electric and magnetic losses
LOSS_X = 0.00025 * (sp.mgrid[0:PML_WIDTH, 0:SIZE_Y][0]**2)
LOSS_Y = 0.00025 * (sp.mgrid[0:SIZE_X, 0:PML_WIDTH][1]**2)
sp.set_printoptions(precision=2,
                    threshold=sp.nan,
                    linewidth=135,
                    suppress=True)
print LOSS_X
loss_x = sp.zeros((SIZE_X, SIZE_Y))
loss_y = sp.zeros((SIZE_X, SIZE_Y))
loss_x[right:, :] += LOSS_X
loss_x[:left, :] += LOSS_X[::-1, :]
loss_y[:, top:] += LOSS_Y
loss_y[:, :bottom] += LOSS_Y[:, ::-1]

# Coefficients multiplying Hx and Ez for the Hx update
chx_loss_y = (loss_y[:, 1:] + loss_y[:, :-1]) / 2
chx_muR = (muR[:, 1:] + muR[:, :-1]) / 2
chxh = (1 - chx_loss_y) / (1 + chx_loss_y)
chxe = -Sc_y / (chx_muR * imp0 * (1 + chx_loss_y))
# Coefficients multiplying Hy and Ez for the Hy update
コード例 #12
0
def setupPrint():
    sp.set_printoptions(edgeitems=3,
                        linewidth=400,
                        precision=16,
                        suppress=False,
                        threshold=10000)
コード例 #13
0
ファイル: Pickets.py プロジェクト: jlettvin/rpna
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys, scipy, itertools

scipy.set_printoptions(precision=3, suppress=True, linewidth=100)


class Pickets(object):
    def __init__(self, radial=1):
        self.radial = radial
        div1 = 1 + 2 * radial
        div2 = 1 if radial < 1 else 2 + 1.0 / radial
        seq = [0] if radial == 0 else scipy.linspace(-1.0, 1.0, div1) / div2
        if len(seq) > 1:
            """Assert that the pickets are evenly spaced."""
            one = 2 * seq[-1] + seq[1 + len(seq) / 2]
            epsilon = scipy.fabs(1.0 - one)
            assert epsilon < 1e-10
        self.pickets = list(itertools.product(seq, repeat=2))
コード例 #14
0
    def get_numpy_evals(self):

        evals, evecs_l, evecs = sp_la.eig(self.mat_orig, left=True)
        sp.set_printoptions(threshold=sys.maxsize)
        print("numpy evals =\n ", sorted(abs(sp.real(evals)), reverse=False))
コード例 #15
0
ファイル: 2d-pml.py プロジェクト: kprokopi/fdtd
bottom = PML_WIDTH
left = PML_WIDTH
right = SIZE_X - PML_WIDTH

# Permittivity and permeability of PML
MU_R = 1
EPSILON_R = 1
muR = sp.ones((SIZE_X, SIZE_Y))
muR[:, bottom:top] *= MU_R
epsR = sp.ones((SIZE_X, SIZE_Y))
epsR[:, bottom:top] *= EPSILON_R

# Electric and magnetic losses
LOSS_X = 0.00025 * (sp.mgrid[0:PML_WIDTH, 0:SIZE_Y][0] ** 2)
LOSS_Y = 0.00025 * (sp.mgrid[0:SIZE_X, 0:PML_WIDTH][1] ** 2)
sp.set_printoptions(precision = 2, threshold = sp.nan, linewidth = 135, suppress = True)
print LOSS_X
loss_x = sp.zeros((SIZE_X, SIZE_Y))
loss_y = sp.zeros((SIZE_X, SIZE_Y))
loss_x[right:, :] += LOSS_X
loss_x[:left, :] += LOSS_X[::-1, :]
loss_y[:, top:] += LOSS_Y
loss_y[:, :bottom] += LOSS_Y[:, ::-1]

# Coefficients multiplying Hx and Ez for the Hx update
chx_loss_y = (loss_y[:, 1:] + loss_y[:, :-1]) / 2
chx_muR = (muR[:, 1:] + muR[:, :-1]) / 2
chxh = (1 - chx_loss_y) / (1 + chx_loss_y)
chxe = - Sc_y / (chx_muR * imp0 * (1+chx_loss_y))
# Coefficients multiplying Hy and Ez for the Hy update
chy_loss_x = (loss_x[1:, :] + loss_x[:-1, :]) / 2
コード例 #16
0
# DSGE Homework: Lab 5b

# <headingcell level=4>

# Import Statements

# <codecell>

import scipy as sp
import sympy as sym
from sympy import symbols, nsolve, Symbol

# <codecell>

sp.set_printoptions(linewidth=140, precision=4)

# <headingcell level=4>

# Parameter Definitions

# <codecell>

gamma = 2.5
xsi= 1.5
beta  = 0.98
alpha = 0.4
a     = 0.5
delta = 0.10
zbar  = 0
tao   = 0.05
コード例 #17
0
ファイル: Airy.py プロジェクト: jlettvin/Airy
                    if terminal: break
                elif abs(vn) <= abs(v0) >= abs(vp):
                    Airy.peaks += [val0,]
                    "Find a below epsilon peak"
                    if abs(val0['amplitude']) < epsilon: terminal = True
                valn, val0 = val0, valp

Airy() # Generate singleton

if __name__ == "__main__":

    def test1(): print len(Airy.zeros), "zeros"
    def test2(): print Airy.zeros[0]['parameter'], Airy.point[1]['amplitude']
    def test3(): print string.join(["%1.16e, %1.16e" % (u,am) for (u,am) in Airy.spike], '\n')
    def test4(): print Airy.zeros[0]['parameter']/Airy.r0

    def runtest(key, val): print '\t%s' %(key); val()

    tests = {"zerocount": test1, "firstzero": test2, "spikes": test3, "u0/r0": test4}

    parser = OptionParser()
    parser.add_option("-d", "--delta",      default=1e-7,  help="radial step size")
    parser.add_option("-e", "--epsilon",    default=1e-3,  help="lower cutoff for kernel")
    parser.add_option("-l", "--linewidth",  default=1000,  help="print width")
    parser.add_option("-p", "--precision",  default=2,     help="print precision")
    (opts, args) = parser.parse_args()
    kwargs = vars(opts)

    set_printoptions(precision=kwargs.get('precision',2), linewidth=kwargs.get('linewidth', 1000))
    [runtest(key,val) for (key,val) in tests.iteritems()]
コード例 #18
0
ファイル: gmres.py プロジェクト: kentonlam/math3204
import scipy as sp
import scipy.linalg as spla
import scipy.sparse as sps
import scipy.sparse.linalg as spsla

import time

from householder import lcd, householder

sp.set_printoptions(edgeitems=30, linewidth=100000)

def gmres(A: sp.matrix, b: sp.matrix, x_0: sp.matrix=None):
    start = time.time() 

    m, n = A.shape
    r = b - A @ x_0
    r_0_norm = spla.norm(r)
    b_norm = spla.norm(b)
    H = sp.ndarray((1, 0))
    Q = r / spla.norm(r)
    Q.reshape((n, 1))
    k = 0

    while True:
        k += 1
        # print(H.shape)
        h = sp.ndarray((k, 1))
        j = k
        q_j = Q[:,j-1]
        z = A @ q_j
        for i in range(j):
コード例 #19
0
ファイル: elastics.py プロジェクト: djw/elastic-constants
	def dumpXML(seedname):
		
		import time
		
		
		S.set_printoptions(threshold=S.nan)  #don't skip printing parts of the array
		
		if os.path.isfile(seedname+"-geomopt1.cml"):
			# we'll inject the data into this file, then
			basefile = seedname+"-geomopt1.cml"
    		
			print "Inserting CML into: "+ basefile
			f = open(basefile, "r")
			tree = etree.parse(f)
			f.close()
			
			fp = d["{http://www.castep.org/cml/dictionary/}finalProperties"]
			finalproperties = fp.findin_context(tree)
			assert len(finalproperties) == 1
		    
			startnode = finalproperties[0]
		elif os.path.isfile(seedname+"-energy.cml"):
			# we'll inject the data into this file, then
			basefile = seedname+"-energy.cml"

			print "Inserting CML into: "+ basefile
			f = open(basefile, "r")
			tree = etree.parse(f)
			f.close()

			fp = d["{http://www.castep.org/cml/dictionary/}finalProperties"]
			finalproperties = fp.findin_context(tree)
			assert len(finalproperties) == 1

			startnode = finalproperties[0]
		else:
			
			
			basefile = seedname+"_cij_analysis.cml"	
			
			print "Outputting CML into: "+ basefile
			
			# create a header
			CML_NAMESPACE = "http://www.xml-cml.org/schema"
			DC_NAMESPACE ="http://purl.org/dc/elements/1.1/"		
			CML = "{%s}" % CML_NAMESPACE
			NSMAP = {None : CML_NAMESPACE, "dc" : DC_NAMESPACE}
				
			startnode = etree.Element(CML +"cml", nsmap=NSMAP)
		
			metadata = etree.Element("metadata")
			metadata.attrib["name"] = "dc:date"
			metadata.attrib["content"] = time.strftime("%Y-%m-%dT%H:%M:%S")
			startnode.append(metadata)
		
			metadata = etree.Element("metadata")
			metadata.attrib["name"] = "dc:creator"
			metadata.attrib["content"] = "MGElastics"
			startnode.append(metadata)
		
			metadata = etree.Element("metadata")
			metadata.attrib["name"] = "dc:hasVersion"
			metadata.attrib["content"] = str(version)
			startnode.append(metadata)
		
			metadata = etree.Element("metadata")
			metadata.attrib["name"] = "dc:subject"
			metadata.attrib["content"] = "Analysis file for Cij calculations"
			startnode.append(metadata)
			
			tree = etree.ElementTree(startnode)
			
			
		# now append Cij data
		cijnode = etree.Element("propertyList")
		cijnode.attrib["title"] = "MaterialsGrid: Elastic Properties"
		cijnode.attrib["dictRef"] = "castep:elastic_properties"  
		startnode.append(cijnode) 
		
		cijProp = etree.Element("property")
		cijProp.attrib["dictRef"] = "castep:elastic_stiffness_constants"
		cijProp.attrib["title"] = "Elastic Stiffness Constants"
		cijnode.append(cijProp)
		
		cijTensor = etree.Element("matrix")
		cijTensor.attrib["rows"] = "6"
		cijTensor.attrib["columns"] = "6"
		cijTensor.attrib["dataType"] = "xsd:double"
		cijTensor.attrib["units"] = "castepunits:"+ units.lower()
		cijTensor.text = S.array2string(finalCijMatrix.reshape(1,36)[0],max_line_width=1000,suppress_small=True).strip("[] ") 
		cijProp.append(cijTensor)
		
		sijProp = etree.Element("property")
		sijProp.attrib["dictRef"] = "castep:elastic_compliance_constants"
		sijProp.attrib["title"] = "Elastic Compliance Constants"
		cijnode.append(sijProp)
		
		sijTensor = etree.Element("matrix")
		sijTensor.attrib["rows"] = "6"
		sijTensor.attrib["columns"] = "6"
		sijTensor.attrib["dataType"] = "xsd:double"
		sijTensor.attrib["units"] = "castepunits:"+ units.lower()+"-1"  #this has to be changed - i don't think the '/' is allowed
		sijTensor.text = S.array2string(sij.reshape(1,36)[0],max_line_width=1000,suppress_small=True).strip("[] ") 
		sijProp.append(sijTensor)
		
		#### Young's Moduli ####
		youngsMod = etree.Element("propertyList")
		youngsMod.attrib["dictRef"] = "castep:youngs_moduli"
		youngsMod.attrib["title"] = "Young's Moduli"
		cijnode.append(youngsMod)
		
		# X
		youngsModValX = etree.Element("property")
		youngsModValX.attrib["title"] = "Young's Modulus X"
		youngsModValX.attrib["dictRef"] = "castep:young_x"
		youngsMod.append(youngsModValX)
		
		youngsModValXScalar = etree.Element("scalar")
		youngsModValXScalar.attrib["dataType"] = "xsd:double"
		youngsModValXScalar.attrib["units"] = "castepunits:"+ units.lower()
		youngsModValXScalar.text = str(youngX)
		youngsModValX.append(youngsModValXScalar)
		
		# Y
		youngsModValY = etree.Element("property")
		youngsModValY.attrib["title"] = "Young's Modulus Y"
		youngsModValY.attrib["dictRef"] = "castep:young_y"
		youngsMod.append(youngsModValY)
		
		youngsModValYScalar = etree.Element("scalar")
		youngsModValYScalar.attrib["dataType"] = "xsd:double"
		youngsModValYScalar.attrib["units"] = "castepunits:"+ units.lower()
		youngsModValYScalar.text = str(youngY)
		youngsModValY.append(youngsModValYScalar)
		
		# Z
		youngsModValZ = etree.Element("property")
		youngsModValZ.attrib["title"] = "Young's Modulus Z"
		youngsModValZ.attrib["dictRef"] = "castep:young_z"
		youngsMod.append(youngsModValZ)
		
		youngsModValZScalar = etree.Element("scalar")
		youngsModValZScalar.attrib["dataType"] = "xsd:double"
		youngsModValZScalar.attrib["units"] = "castepunits:"+ units.lower()
		youngsModValZScalar.text = str(youngZ)
		youngsModValZ.append(youngsModValZScalar)
		
		
		
		#### Poisson's Ratio ####
		poissonMod = etree.Element("propertyList")
		poissonMod.attrib["dictRef"] = "castep:poisson_ratio"
		poissonMod.attrib["title"] = "Poisson Ratio"
		cijnode.append(poissonMod)
		
		# XY
		poissonModValXY = etree.Element("property")
		poissonModValXY.attrib["title"] = "Poisson Ratio XY"
		poissonModValXY.attrib["dictRef"] = "castep:poisson_xy"
		poissonModValXY.attrib["units"] = "castepunits:dimensionless"
		
		poissonMod.append(poissonModValXY)
		
		poissonModValXYScalar = etree.Element("scalar")
		poissonModValXYScalar.attrib["dataType"] = "xsd:double"
		poissonModValXYScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValXYScalar.text = str(poissonXY)
		poissonModValXY.append(poissonModValXYScalar)
		
		# XZ
		poissonModValXZ = etree.Element("property")
		poissonModValXZ.attrib["title"] = "Poisson Ratio XZ"
		poissonModValXZ.attrib["dictRef"] = "castep:poisson_xz"
		poissonMod.append(poissonModValXZ)
		
		poissonModValXZScalar = etree.Element("scalar")
		poissonModValXZScalar.attrib["dataType"] = "xsd:double"
		poissonModValXZScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValXZScalar.text = str(poissonXZ)
		poissonModValXZ.append(poissonModValXZScalar)
		
		# YX
		poissonModValYX = etree.Element("property")
		poissonModValYX.attrib["title"] = "Poisson Ratio YX"
		poissonModValYX.attrib["dictRef"] = "castep:poisson_yx"
		poissonMod.append(poissonModValYX)
		
		poissonModValYXScalar = etree.Element("scalar")
		poissonModValYXScalar.attrib["dataType"] = "xsd:double"
		poissonModValYXScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValYXScalar.text = str(poissonYX)
		poissonModValYX.append(poissonModValYXScalar)
		
		# YZ
		poissonModValYZ = etree.Element("property")
		poissonModValYZ.attrib["title"] = "Poisson Ratio YZ"
		poissonModValYZ.attrib["dictRef"] = "castep:poisson_yz"
		poissonMod.append(poissonModValYZ)
		
		poissonModValYZScalar = etree.Element("scalar")
		poissonModValYZScalar.attrib["dataType"] = "xsd:double"
		poissonModValYZScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValYZScalar.text = str(poissonYZ)
		poissonModValYZ.append(poissonModValYZScalar)
		
		# ZX
		poissonModValZX = etree.Element("property")
		poissonModValZX.attrib["title"] = "Poisson Ratio ZX"
		poissonModValZX.attrib["dictRef"] = "castep:poisson_zx"
		poissonMod.append(poissonModValZX)
		
		poissonModValZXScalar = etree.Element("scalar")
		poissonModValZXScalar.attrib["dataType"] = "xsd:double"
		poissonModValZXScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValZXScalar.text = str(poissonZX)
		poissonModValZX.append(poissonModValZXScalar)
		
		# ZY
		poissonModValZY = etree.Element("property")
		poissonModValZY.attrib["title"] = "Poisson Ratio ZY"
		poissonModValZY.attrib["dictRef"] = "castep:poisson_zy"
		poissonMod.append(poissonModValZY)
		
		poissonModValZYScalar = etree.Element("scalar")
		poissonModValZYScalar.attrib["dataType"] = "xsd:double"
		poissonModValZYScalar.attrib["units"] = "castepunits:dimensionless"
		poissonModValZYScalar.text = str(poissonZY)
		poissonModValZY.append(poissonModValZYScalar)	
		
		
		#### Polycrystalline Results ####
		
		#bulk moduli
		bulkModPL = etree.Element("propertyList")
		bulkModPL.attrib["dictRef"] = "castep:polycrystalline_bulk_moduli"
		bulkModPL.attrib["title"] = "Polycrystalline Bulk Moduli"
		cijnode.append(bulkModPL)
		
		bulkModVoigt = etree.Element("property")
		bulkModVoigt.attrib["title"] = "Voigt"
		bulkModVoigt.attrib["dictRef"] = "castep:bulk_modulus_voigt"
		bulkModPL.append(bulkModVoigt)
		
		bulkModReuss = etree.Element("property")
		bulkModReuss.attrib["title"] = "Reuss"
		bulkModReuss.attrib["dictRef"] = "castep:bulk_modulus_reuss"
		bulkModPL.append(bulkModReuss)
		
		bulkModHill = etree.Element("property")
		bulkModHill.attrib["title"] = "Hill"
		bulkModHill.attrib["dictRef"] = "castep:bulk_modulus_hill"
		bulkModPL.append(bulkModHill)
		
		bulkModVoigtScalar = etree.Element("scalar")
		bulkModVoigtScalar.attrib["dataType"] = "xsd:double"
		bulkModVoigtScalar.attrib["units"] = "castepunits:"+ units.lower()
		bulkModVoigtScalar.text = str(voigtB)
		bulkModVoigt.append(bulkModVoigtScalar)
		
		bulkModReussScalar = etree.Element("scalar")
		bulkModReussScalar.attrib["dataType"] = "xsd:double"
		bulkModReussScalar.attrib["units"] = "castepunits:"+ units.lower()
		bulkModReussScalar.text = str(reussB)
		bulkModReuss.append(bulkModReussScalar)
		
		bulkModHillScalar = etree.Element("scalar")
		bulkModHillScalar.attrib["dataType"] = "xsd:double"
		bulkModHillScalar.attrib["units"] = "castepunits:"+ units.lower()
		bulkModHillScalar.text = str((voigtB+reussB)/2)
		bulkModHill.append(bulkModHillScalar)
		
		
		#shear moduli
		shearModPL = etree.Element("propertyList")
		shearModPL.attrib["dictRef"] = "castep:polycrystalline_shear_moduli"
		shearModPL.attrib["title"] = "Polycrystalline Shear Moduli"
		cijnode.append(shearModPL)
		
		shearModVoigt = etree.Element("property")
		shearModVoigt.attrib["title"] = "Voigt"
		shearModVoigt.attrib["dictRef"] = "castep:shear_modulus_voigt"
		shearModPL.append(shearModVoigt)
		
		shearModReuss = etree.Element("property")
		shearModReuss.attrib["title"] = "Reuss"
		shearModReuss.attrib["dictRef"] = "castep:shear_modulus_reuss"
		shearModPL.append(shearModReuss)
		
		shearModHill = etree.Element("property")
		shearModHill.attrib["title"] = "Hill"
		shearModHill.attrib["dictRef"] = "castep:shear_modulus_hill"
		shearModPL.append(shearModHill)
		
		shearModVoigtScalar = etree.Element("scalar")
		shearModVoigtScalar.attrib["dataType"] = "xsd:double"
		shearModVoigtScalar.attrib["units"] = "castepunits:"+ units.lower()
		shearModVoigtScalar.text = str(voigtG)
		shearModVoigt.append(shearModVoigtScalar)
		
		shearModReussScalar = etree.Element("scalar")
		shearModReussScalar.attrib["dataType"] = "xsd:double"
		shearModReussScalar.attrib["units"] = "castepunits:"+ units.lower()
		shearModReussScalar.text = str(reussG)
		shearModReuss.append(shearModReussScalar)
		
		shearModHillScalar = etree.Element("scalar")
		shearModHillScalar.attrib["dataType"] = "xsd:double"
		shearModHillScalar.attrib["units"] = "castepunits:"+ units.lower()
		shearModHillScalar.text = str((voigtG+reussG)/2)
		shearModHill.append(shearModHillScalar)
		
		if(options.debug):
			print etree.tostring(startnode,pretty_print=True)
		else:
			# wrap it in an ElementTree instance, and save as XML
			tree.write(basefile,pretty_print=True)
			
		return
コード例 #20
0
import sys
import mcta
import mcta_vis
import mcta_rw
import scipy as sp

# options
verbose = False
showfigs = False
figs2png = False
savememdump = False

# global variables
base = None

sp.set_printoptions(suppress=True,precision=3,linewidth=140)

### Data processing ######################################################################

def ProcessCLI():
	"""Process CLI parameters"""
	global base
	global verbose
	global showfigs
	global figs2png
	global savememdump

	if len(sys.argv) == 1:
		print("Missing argument\n\nSyntax:\n\tipython mcta_cli.py -- [options] {BaseName}")
		print(HELP_MSG)
		sys.exit(0)
コード例 #21
0
# -*- coding: utf-8 -*-
import npfs as npfs
import scipy as sp
from sklearn.cross_validation import train_test_split, StratifiedKFold
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC
from sklearn import preprocessing
import time
import pickle

sp.set_printoptions(precision=3)

data_name = 'aisa'
data = sp.load('Data/' + data_name + '.npz')
X = data['X']
y = data['Y']
C = len(sp.unique(y))
print "Nb of samples: ", X.shape[0], " Nb of features: ", X.shape[
    1], "Nb of classes: ", C, "\n"

ntrial = 20

Nts = [(50, False), (100, False), (200, False), (0.005, True), (0.01, True),
       (0.025, True)]  # Nb of samples per class in training set

param_grid_gmm = [0.01, 0.1, 1, 10, 100, 1000, 10000, 100000, 1000000]

svmTest = True
param_grid_svm = [
    {
        'C': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000],
コード例 #22
0
import cPickle as pickle
import csv
import re
import scipy

import pylab

__author__ = 'marrabld'

import pidly  # Use this to call one of DIMITRI's IDL functions and pass back the data structure

##!! This is required to prevent unwanted linefeeds in the csv file
scipy.set_printoptions(linewidth=2000)


class DimitriSatelliteObject():
    def __init__(self, gdl_path='/usr/bin/gdl'):

        self.idl = pidly.IDL(gdl_path, idl_prompt='GDL> ')
        self.l1b_data = None
        self.bands = {
            'PARASOL': [
                '443', '490p', '490u', '490q', '565', '670p', '670u', '670q',
                '763', '765', '865p', '865u', '865q', '910', '1020'
            ],
            'MERIS': [
                '412', '443', '490', '510', '560', '620', '665', '681', '708',
                '753', '761', '778', '865', '885', '900'
            ]
        }  ## !!! these are the same as DIMITRI FOR NOW!! CHECK
        self.sensor_name = 'PARASOL'
コード例 #23
0
import matplotlib.pyplot as plt
import networkx as nx
import sys
import scipy as sp
from networkx.generators.expanders import *
import itertools

n=int(input("enter n value")) #size of the graph or number of nodes in the graph
i=int(input("enter i value")) #To choose type of the graph

if i == 1:
	G =  nx.cycle_graph(n)#creates cycle graph of n nodes
	print(nx.info(G))
	A = nx.adjacency_matrix(G)
	sp.set_printoptions(linewidth=sp.inf)
	sp.set_printoptions(threshold=sys.maxsize)
	print(A.todense(),file=open("cycle_graph\%d.txt"%(n),'w')) #Outputs the adjacency matrix to a textfile and stores it in a folder called 'cycle graph'
	nx.draw(G)
	plt.show()
elif i == 2:
	G =  nx.wheel_graph(n) #creates wheel graph of n nodes
	print(nx.info(G))
	A = nx.adjacency_matrix(G) #creates an adjacency matrix for graph G
	sp.set_printoptions(linewidth=sp.inf)
	sp.set_printoptions(threshold=sys.maxsize)
	print(A.todense(),file=open("wheel_graph\%d.txt"%(n),'w')) #Outputs the adjacency matrix to a textfile and stores it in a folder called 'wheel graph'
	nx.draw(G)
	plt.show()
elif i == 3:
	k=int(input("enter k value")) %Clique size
	G =  nx.windmill_graph(n,k) #creates wheel graph of n nodes
コード例 #24
0
ファイル: ungray.py プロジェクト: jlettvin/NoisyGrayStep
from itertools  import (product)

# Imports from OpenCV
try:
    from cv2        import (filter2D)
    from cv2.cv     import (GetSubRect, NamedWindow, GetCaptureProperty)
    from cv2.cv     import (CaptureFromCAM, CreateMat, GetMat)
    from cv2.cv     import (QueryFrame, ShowImage)
    from cv2.cv     import (WaitKey, DestroyAllWindows, CV_8UC3)
    from cv2.cv     import (CV_CAP_PROP_FRAME_WIDTH, CV_CAP_PROP_FRAME_HEIGHT)
except ImportError:
    print("Module OpenCV (cv2) is required")

#SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
# Change how scipy displays numbers.
set_printoptions(precision=2)

class Control(object):

    def __init__(self, name, limits, factor=1.1):
        assert isinstance(limits, tuple) or isinstance(limits, list)
        self.limit = list(limits)
        assert len(self.limit) == 3
        assert self.limit[0] <= self.limit[1] <= self.limit[2]
        assert self.limit[0] > 0.0
        self.factor = factor
        self.name = name
        self.todo = True

    def increment(self):
        self.todo = (self.limit[1] < self.limit[2])
コード例 #25
0
"""
Created May 30, 2012

Author: Spencer Lyon

"""
import numpy as np
import scipy as sp
import scipy.sparse.linalg as spla
import scipy.linalg as la
import matplotlib.pyplot as plt
import pylab
import Bandpass_Filter as bpf
import hp_filter as hpf

sp.set_printoptions(linewidth=140, suppress = True, precision = 5)

def problem_1():
    """
    This function uses the file GPDIC96.txt as the data for this problem.
    It produces the T, cycle sets and plots what Ben asked for in 1.d.
    """
    data = sp.loadtxt('GPDIC96.txt', skiprows=1, dtype=float,
                      converters={0:pylab.datestr2num})
    yData = data[:,1]
    T, c  = hpf.hp_filter(yData)
    time = sp.linspace(0, T.size, T.size)
    plt.plot(time, yData)
    plt.plot(time, T)
    plt.figure()
    plt.plot(time, c)
コード例 #26
0
ファイル: Control.py プロジェクト: gnavvy/ParaIF
                j = nodes.index(nj)
                guidance_matrix[i, j] = 1.0

        guidance_matrix = sparse.lil_matrix(guidance_matrix)

        # pos = sum(x > 0 for x in guidance_matrix)
        print(guidance_matrix)
        ward = Ward(n_clusters=6, n_components=2, connectivity=guidance_matrix)
        predicts = ward.fit_predict(self.A)

        print(predicts)
        # print(circles.keys(), len(circles.itervalues())


if __name__ == "__main__":
    sp.set_printoptions(precision=2, suppress=True)

    nodes = [1, 2, 3, 4, 5, 6]
    edges = [[1, 2], [1, 3], [2, 3], [3, 4], [4, 5], [4, 6], [5, 6]]
    Q1 = sp.asmatrix(sp.identity(6))

    Q = sp.mat([[1.0, 1.0, 1.0, 1.0, -1.0, -1.0],
                [1.0, 1.0, 1.0, 1.0, -1.0, -1.0],
                [1.0, 1.0, 1.0, 1.0, -1.0, -1.0],
                [1.0, 1.0, 1.0, 1.0, -1.0, -1.0],
                [-1.0, -1.0, -1.0, -1.0, 1.0, 1.0],
                [-1.0, -1.0, -1.0, -1.0, 1.0, 1.0]])

    c = Cluster(nodes, edges)
    vec = c.spectral(2)
    print(vec)
コード例 #27
0
ファイル: runTestSelectionGMM.py プロジェクト: Laadr/FFFS
# -*- coding: utf-8 -*-
import npfs as npfs
import scipy as sp
from sklearn.cross_validation import train_test_split, StratifiedKFold
import time
import pickle

sp.set_printoptions(precision=10)

data_name      = 'aisa'
data = sp.load('Data/'+data_name+'.npz')
X    = data['X']
y    = data['Y']
C    = len(sp.unique(y))
print "Nb of samples: ",X.shape[0]," Nb of features: ",X.shape[1],"Nb of classes: ",C,"\n"


ntrial = 20
minVar = 2
maxVar = 25

Nts        = [(50,False), (100,False), (200,False), (0.005,True), (0.01,True), (0.025,True)] # Nb of samples per class in training set
methods    = ['SFFS']#['forward','SFFS']
criterions = ['accuracy', 'kappa', 'F1Mean','JM', 'divKL']

for Nt,stratification in Nts:
    for criterion in criterions:
        for method in methods:

            if stratification:
                filename = data_name+'_'+method+'_spls_'+str(Nt)+'_stratified_trials_'+str(ntrial)+'_'+criterion
コード例 #28
0
ファイル: Paraboloid.py プロジェクト: jlettvin/Paraboloid
__email__      = "*****@*****.**"
__contact__    = "*****@*****.**"
__status__     = "Demonstration"
__date__       = "20111110"

###############################################################################
from scipy      import array, sqrt, arange, rot90, fabs, where, around
from scipy      import set_printoptions
from itertools  import product
from optparse   import OptionParser
from subprocess import call

import pylab as p
#import mpl_toolkits.mplot3d.axes3d as p3

set_printoptions(precision=2, linewidth=500)

class Paraboloid(object):
    def __init__(self, **kw):
        self.kw = kw
        self.E  = kw.get('E', 12.0) # Edge halflength of the containing cube.
        self.dE = kw.get('dE', 0.2) # Edge increment length.
        self.dR = kw.get('dR', 0.1) # Radial increment for coincidence.
        #print self.E, self.dE, self.dR
        rng     = list(arange(-self.E,self.E+self.dE, self.dE)) # Edge values.
        # Force rebalance
        rng    -= (rng[-1] + rng[0])/2.0
        self.X  = array([rng,] * len(rng))      # x values plane segment
        self.Y  = rot90(self.X)                 # y values plane segment
        self.r  = sqrt(self.X**2 + self.Y**2)   # r values plane segment
        #print self.kw
コード例 #29
0
#mmc with different values for service rates 
from scipy import mean, digitize, cumsum, array, concatenate, set_printoptions, nonzero, insert, ones, random
from scipy.stats import uniform, expon

import numpy as np
from QueueingTheory import mm1, getRandomArrivalServiceTimes
def prints(s):
    print s
    return s

set_printoptions(precision = 7)
set_printoptions(suppress=True)

arrival_rate = 1
service_rate = 1/6.0 * ones(3) #array([1.09, 2.000005, 1])
server_prob = array([0.25, 0.25, 0.5])
n_server = server_prob.size
n_process = 100
time_interval = 10

initial_state = (7,2,3)
arrival_times = getRandomArrivalServiceTimes(n_process, arrival_rate, None)[0]
sum_initial_state = sum(initial_state)
# preparing initial state for each mm1 simulation

initial_states = zip(initial_state, [arrival_times[sum_initial_state]] * len(initial_state))

# maps kth process to ith server
server_address_table_forced = random.permutation(concatenate([ones(state) * i for i,state in enumerate(initial_state)]))
print "forced server address table", server_address_table_forced
server_address_table = concatenate([server_address_table_forced, digitize(uniform.rvs(size = n_process-sum_initial_state), cumsum(server_prob))])
コード例 #30
0

last_sub = tconv(subs, -1)[1]
print(last_sub)
print(subs[-1])
pb_array = sp.zeros((int(last_sub), 3))
count = sp.arange(int(last_sub))
pb_array[:, 0] = count[:]  # an index for each sample starting at 0
pb_array[:,
         1] = pb_array[:,
                       0] * 0.01  #0.01 is the size of the MFCC windows used in play.py, this is the starting point for each window

#print(pb_array)
#print(tconv(subs,1))
#print(len(subs))
sp.set_printoptions(threshold=sp.nan)
#print(subs)
#print(pb_array)

i = 0
j = 0  # i is counter over subs array, j is counter over sample array (stored in pb_array)
while True:
    if i + 1 > len(
            pb_array
    ) - 1:  #matrices are indexed from 0 but the length returns the 'normal' length i.e len([1]) returns 1 not 0
        print('substimes length exceeded')
        print(i)
        break
    if j > len(subs) - 1:
        print('pb array length exceeded')
        print(j)
コード例 #31
0
[1] Xiangnan He, Min-Yen Kan, Peichu Xie, and Xiao Chen. 2014. Comment-based multi-view clustering of web 2.0 items. 
In Proceedings of the 23rd international conference on World wide web (WWW '14).

@author: HeXiangnan ([email protected])
'''
import scipy as sp
import numpy as np
import scipy.sparse as sparse
import data_load as dl
import metrics
from operator import div
from utils import dot, multiply, elop, initialize_random, labels_to_matrix
from kmeans import kmeans

np.set_printoptions(threshold='nan')
sp.set_printoptions(threshold='nan')


def conmf(datas,
          cluster_size,
          weights,
          regu_weights,
          norm="l2",
          seed="k-means",
          post="direct",
          method="pair-wise",
          gt=None):
    """
    CoNMF on multi-view dataset (represented as datas).
    
    :param datas (type: list<csr_matrix>). [data_k] 
コード例 #32
0
ファイル: MPI2.py プロジェクト: JohanJu/python_scipy
# -*- coding: utf-8 -*-
import scipy as sci
import scipy.linalg as linalg
from mpi4py import MPI
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pylab as py
import sys
sci.set_printoptions(linewidth =1000)
sci.set_printoptions(threshold=50000)
py.rcParams['figure.figsize'] = 12, 12

'''
ln = lambda neumann
ld = lambda dirichlet
ldo = lambda dirichlet old

'''
rank = MPI.COMM_WORLD.rank

N = 20
Tn = 15.
Tw = 5.
Th = 40.
T0 = -20
w = 0.5

NbrItr = 20


def setAb(r,k,m,n):
コード例 #33
0
#------------------------------------------------------------
import time
import numpy as np
import scipy as sp
import matplotlib
matplotlib.use('Agg')  # needed for using matplotlib on remote machine
import matplotlib.pyplot as plt
#------------------------------------------------------------
import gen_data
import ipm_func
import svm_func
import load_real_data
from parameters import m, w, n, p, gamma, sigma_step, sigma, tol_cg, MAXIT_cg, DENSITY, power
#------------------------------------------------------------
np.random.seed(0)  # reset random seed
sp.set_printoptions(precision=4, suppress=True)
np.set_printoptions(precision=4)
#------------------------------------------------------------
# Sketched IPM vs Standard IPM, 1 Run, number of iterations, condition number
#------------------------------------------------------------

directory = '/Users/grego/GitProjects/SketchIPM_python/ipm_figures'

#------------------------------------------------------------
if __name__ == '__main__':
    print('---------------------------', '\n')
    print('Test IPM SVM real or synthetic dataset, 1 Run', '\n')
    #------------------------------------------------------------

    #------------------------------------------------------------
    # Data LOAD
コード例 #34
0
ファイル: Spectrum.py プロジェクト: jlettvin/Spectrum
When a sensor changes state, it generates a difference signal.

"""
###############################################################################

import os, inspect, scipy, random

from optparse import OptionParser

from scipy import arange, exp, random, zeros, ones, array
from scipy.constants import *

###############################################################################

scipy.set_printoptions(precision=2, linewidth=1000)

#CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
class Spectrum(object):

    # First instance forces initialization, wait for OptionParser to parse argv.
    initialized   = False
    stepsize      = None
    visible       = None
    wavelengths   = None
    energy        = None
    length        = None
    named         = {}
    rand          = 0

    def id(this, name=None):
コード例 #35
0
from __future__ import division, print_function, absolute_import

from scipy import array, arange, ones, sort, cos, pi, rand, \
     set_printoptions, r_
from scipy.sparse.linalg import lobpcg
from scipy import sparse
from pylab import loglog, show, xlabel, ylabel, title
set_printoptions(precision=8,linewidth=90)
import time


def sakurai(n):
    """ Example taken from
        T. Sakurai, H. Tadano, Y. Inadomi and U. Nagashima
        A moment-based method for large-scale generalized eigenvalue problems
        Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004) """

    A = sparse.eye(n, n)
    d0 = array(r_[5,6*ones(n-2),5])
    d1 = -4*ones(n)
    d2 = ones(n)
    B = sparse.spdiags([d2,d1,d0,d1,d2],[-2,-1,0,1,2],n,n)

    k = arange(1,n+1)
    w_ex = sort(1./(16.*pow(cos(0.5*k*pi/(n+1)),4)))  # exact eigenvalues

    return A,B, w_ex

m = 3  # Blocksize

#
コード例 #36
0
import networkx as nx
import matplotlib.pyplot as plt
import sklearn

import trilearn.graph.trajectory as mc
import trilearn.graph.graph as glib
import trilearn.graph.decomposable as dlib
import trilearn.graph.junction_tree as jtlib
import trilearn.graph.empirical_graph_distribution as gdist
import trilearn.pgibbs
import trilearn.smc as smc

from trilearn.distributions import multivariate_students_t as tdist
from trilearn.distributions import sequential_junction_tree_distributions as seqjtdist

scipy.set_printoptions(precision=2, suppress=True)


class GraphPredictive(sklearn.base.BaseEstimator):
    def __init__(self,
                 n_particles=None,
                 n_pgibbs_samples=None,
                 prompt_burnin=False,
                 only_map_graph=False,
                 standard_bayes=False,
                 cta_alpha=0.5,
                 cta_beta=0.5,
                 true_graphs=None,
                 async=False):
        self.n_particles = n_particles
        self.n_pgibbs_samples = n_pgibbs_samples