Ejemplo n.º 1
0
    def __init__(self, fileName):
        #--------read and count chains and number of sites-------------
        linesInBlock = 0
        prevLineIsEmpty = False
        emptyLine = "\n"

        blockNum = 0
        lineNum = 0
        self.N = []
        self.chain = []
        self.chain.append(Chain.Chain())

        with open(fileName) as fp:
            for line in fp:
                if (line == emptyLine):
                    if (prevLineIsEmpty == False):
                        self.N.append(lineNum)
                        blockNum = blockNum + 1
                        self.chain.append(Chain.Chain())
                        lineNum = 0
                    prevLineIsEmpty = True
                else:
                    x, y, z = line.split()
                    self.chain[blockNum].pushCoordinates(
                        float(x), float(y), float(z))
                    lineNum = lineNum + 1
                    prevLineIsEmpty = False

        #self.numBlocks = blockNum-1;
        self.numBlocks = blockNum
        #---------------------------end--------------------------------
        print('Number of chains: %i.' % self.numBlocks)
Ejemplo n.º 2
0
 def boundary(self, chain_or_cell):
     """
 Return the boundary of the given chain or cell
 """
     if isinstance(chain_or_cell, CubicalCell):
         result = chain_or_cell.boundary(self.ring())
     else:
         result = sum([
             chain_or_cell[cell] * cell.boundary(self.ring())
             for cell in chain_or_cell
         ], Chain(self.dimension(), self.ring()))
     # Project out cells not in complex
     return sum([
         result[cell] * ElementaryChain(cell, self.ring())
         for cell in result if cell in self.cells()
     ], Chain(self.dimension(), self.ring()))
 def project(self, chain):
     """
 Project away all cells except critical cells
 """
     return sum((chain[cell] * ElementaryChain(cell, self.ring())
                 for cell in chain if cell in self.cells()),
                Chain(chain.dimension(), self.ring()))
Ejemplo n.º 4
0
 def __init__(self):
     super().__init__()
     # genesis block
     self.node_ = Node.Node("0", "127.0.0.1:10000", Chain.Chain())
     self.node_.chain_.AddBlock(0)
     self.uid_ = str(uuid4())
     BCNet.nodes_[self.uid_] = self.node_
Ejemplo n.º 5
0
    def reset_chain(self):
        """
        Resets the Markov Chain which the sampler has constructed
        """

        self.chain = Chain.Chain(self.initial_params)
        self.current_params = self.initial_params
Ejemplo n.º 6
0
def sfmChainRestoreRender(chainFilePath):

    # load the sfm chain
    headStages, tailStages = Chain.StageRegistry.Load(chainFilePath)

    # render the tail stage (pmvs)
    print Chain.Render(tailStages[0], "persistence.txt")
Ejemplo n.º 7
0
def keymatchChains(imagePath):
    # KeyMatchFull, KeyMatchGPU
    
    imageSource = Sources.ImageSource(imagePath, "pgm")
    sift = FeatureExtraction.Sift(imageSource, False, "SiftHess")
    keyMatch = FeatureMatch.KeyMatch(sift, True, "KeyMatchFull", forceRun=True)
    
    print Chain.Render(keyMatch,"UnitTest-keymatchChains-KeyMatchFull-log.txt")
Ejemplo n.º 8
0
 def project(self, chain):
     """
 Return the projection of a chain in the supercomplex
 into the current complex. (i.e. drop cells not in self.cells())
 """
     return sum((chain[cell] * ElementaryChain(cell, self.ring())
                 for cell in chain if cell in self.cells()),
                Chain(chain.dimension(), self.ring()))
Ejemplo n.º 9
0
	def newChain(self):

		"""
		creates and returns a new chain
		"""

		mychain = Chain()
		self.addChain(mychain)
		return mychain
Ejemplo n.º 10
0
    def __init__(self, config, repnum):
        """Initialize the Replica() object."""

        temp = config.REPLICATEMPS[repnum]
        self.repnum = repnum
        self.repname = 'rep' + string.zfill(str(repnum), 2)
        self.repdir = config.DATADIR + self.repname
        self.chain = Chain.Chain(config)
        self.mc = Monty.Monty(config, temp, self.chain)
    def homotopy(chain):
        """
    Implement the discrete Morse homotopy gamma
    """
        # We clone the input chain to prevent unexpected alterations
        work_chain = copy.deepcopy(chain)

        # We create a dictionary "priority" which gives the rank of queens.
        # Lower priority numbers will be processed first (i.e. priority ranking, not priority value)
        Queens = [Q for Q in cellcomplex if isQueen(Q)]

        def AdjacentQueens(Q):
            return [q for q in bd(M(Q)) if isQueen(q) and q != Q]

        priority = {
            Q: rank
            for (rank, Q) in enumerate(TopologicalSort(Queens, AdjacentQueens))
        }

        # We arrange the priority queue for queens.
        # We use an auxiliary set "enqueued" to prevent the same queen from being
        # placed in the priority queue twice.
        work_queue = PriorityQueue()
        enqueued = set()

        def enqueue(list_of_queens):
            for Q in list_of_queens:
                if Q in enqueued: continue
                enqueued.add(Q)
                work_queue.put((-priority[Q], Q))

        # Initialize queue with the queens in the original chain
        enqueue([Q for Q in work_chain if isQueen(Q)])

        # Make a zero chain of correct dimension to store result in
        gamma_chain = Chain(dim(chain) + 1, cellcomplex.ring())

        # We iteratively process the maximal queen in "work_chain", each time
        # adding the appropriate multiple of the boundary of its mating king in
        # order to cancel it. Doing this can add new queens, which we enqueue.
        # A theorem prevents previously processed queens from being "new_queens"
        # We keep track of the king chain as we go.
        while not work_queue.empty():
            (rank, Q) = work_queue.get()
            a = work_chain[Q]
            if a == 0: continue
            K = M(Q)
            bd_K = bd(K)
            b = bd_K[Q]
            c = -a / b
            gamma_chain[K] += c
            work_chain += c * bd_K
            enqueue([q for q in bd_K if isQueen(q) and q != Q])
        return gamma_chain
Ejemplo n.º 12
0
def siftChains(imagePath):
    #SiftWin32, SiftHess, SiftGPU, VLFeat
    
    imageSource = Sources.ImageSource(imagePath, "pgm")
    sift = FeatureExtraction.Sift(imageSource, False, "SiftWin32", forceRun=True)
    
    # SiftWin32 only on windows
    if (Common.Utility.OSName=="Windows"):
        print Chain.Render(sift,"UnitTest-siftChains-SiftWin32-log.txt")
	
	sift.SetProperty("Sift Method", "VLFeat")
	print Chain.Render(sift,"UnitTest-siftChains-VLFeat-log.txt")

    # daisy only on windows (note: this should not be the last test, as the descriptors are for ROIs)
    if (Common.Utility.OSName=="Windows"):
        imageSource = Sources.ImageSource(imagePath, "jpg")
        daisy = FeatureExtraction.Daisy(imageSource, False, roi="0,0,50,50", forceRun=True)
        print Chain.Render(daisy,"UnitTest-siftChains-daisy-log.txt")    
    
    sift.SetProperty("Sift Method", "SiftHess")
    print Chain.Render(sift,"UnitTest-siftChains-SiftHess-log.txt")
Ejemplo n.º 13
0
def StartGame():
    global objects
    global pairs
    global wind
    global forces
    global RUNNING
    global PAUSED
    global ONETIME
    global TEST
    objects=[]
    forces = []

    rad=const.SPHERE_RADIUS
    #objects.append(Circle(rad, color=const.DARK_GRAY, width= 0, pos=[400,100], velo=[0,0], mass=math.inf))
    firstBall=Circle(rad, color=const.DARK_GRAY, width= 0, pos=[400,100], velo=[0,0], mass=math.inf)
    objects.append(Circle(rad, color=const.ORANGE,  width=0, pos=[400,200], velo=[0,0], mass=const.REALISTIC_MASS))
    objects.append(Circle(rad, color=const.YELLOW, width= 0, pos=[400,300], velo=[0,0], mass=const.REALISTIC_MASS))
    objects.append(Circle(rad, color=const.GREEN, width= 0, pos=[400,400], velo=[0,0], mass=const.REALISTIC_MASS))
    objects.append(Circle(rad, color=const.PINK, width= 0, pos=[400,500], velo=[0,0], mass=const.REALISTIC_MASS))
                                                                               
    forces.append(Gravity(objects=objects.copy(), acc = [0, 9.8* const.MM_TO_PX]))
    wind = AirDrag(windVel=[0,0], objects=objects.copy())
    forces.append(wind)

    pairs =[]
    firstPair=[firstBall,objects[0]]
    pairs.append(firstPair)
    for i in range(len(objects)):
        if(i < len(objects)-1):
            obj1= objects[i]
            obj2= objects[i+1]
            pairs.append([obj1, obj2])

    
   
    forces.append(Chain(k=const.SPRING_FORCE, naturalLen=const.NATURAL_LENGTH, damp=const.DAMPENING, pair=pairs))

    #Add our Infinite mass circle after Forces:
    objects.append(firstBall)
    forces.append(Repulsion(k=const.SPRING_FORCE, objList=objects.copy(), pair=pairs))

    RUNNING=True;
    PAUSED=False;
    GAMEOVER=False;
    READ_FOR_PLAY_AGAIN=False;
    startTime= time.time()
Ejemplo n.º 14
0
    def renderChain2(self):
        self.statusBox.clear()

        if (not self.__visualizationsInitialized):

            # get all tail stages, build "force run" map
            tails = []
            forceRuns = {}
            for stage in Chain.StageRegistry.registry.GetStageInstances():
                if (len(stage.GetOutputStages()) == 0): tails.append(stage)
                if ("Force Run" in stage.GetPropertyMap().keys()):
                    forceRuns[stage] = stage.GetProperty("Force Run")

            try:
                # render once with the chain state as the user defined it
                Chain.Render(tails)

            except:
                pass

            finally:
                # set all force runs to False as image views are initialized
                for stage in forceRuns.keys():
                    stage.SetProperty("Force Run", False)

                self.initializeVisualizations()
                self.__visualizationsInitialized = True

                for vis in self.__visualizations:
                    try:
                        vis.refresh()
                    except:
                        pass

                # revert force runs
                for stage, fr in forceRuns.iteritems():
                    stage.SetProperty("Force Run", fr)

        else:
            #for stage in self.__stages: stage.Reset()

            for vis in self.__visualizations:
                try:
                    vis.refresh()
                except:
                    pass
Ejemplo n.º 15
0
 def boundary(self, ring=int):
     """
 Return boundary of elementary chain
 in a hypothetical full complex
 """
     # d((x,y))  = (dx, y) + (-1)**(dim(x)) (x,dy)
     result = Chain(self.D - 1, ring)
     sign = 1
     for d, interval in enumerate(self.bounds()):
         if interval[0] == interval[1]: continue
         left = list(self.bounds())
         right = list(self.bounds())
         left[d] = (interval[0], interval[0])
         right[d] = (interval[1], interval[1])
         result[CubicalCell(left)] = ring(-sign)
         result[CubicalCell(right)] = ring(sign)
         sign = sign * -1
     return result
Ejemplo n.º 16
0
def bundlerChain(imagePath):
    
    # PMVS path
    pmvsPath = os.path.join(imagePath,"pmvs")

    # build chain
    imageSource = Sources.ImageSource(imagePath, "jpg")
    sift = FeatureExtraction.Sift(imageSource, False, "SiftHess")
    keyMatch = FeatureMatch.KeyMatch(sift, False, "KeyMatchFull")
    bundler = BundleAdjustment.Bundler([keyMatch, imageSource], forceRun=True)
    radialUndistort = Cluster.RadialUndistort([bundler, imageSource], forceRun=True)
    prepCmvsPmvs = Cluster.PrepCmvsPmvs(radialUndistort, pmvsPath, forceRun=True)
    
    # cmvs not build on 32bit Linux yet
    if (Common.Utility.PlatformName != "Linux32bit"):
        cmvs = Cluster.CMVS(prepCmvsPmvs, forceRun=True)
        pmvs = Cluster.PMVS(cmvs, forceRun=True)
    else:
        pmvs = Cluster.PMVS(prepCmvsPmvs, forceRun=True)
        
    # render chain
    print Chain.Render(pmvs,"UnitTest-bundlerChain-log.txt")
    def generate(self, genAmount):
        reddit = Reddit(client_id=Client_id, client_secret=Client_secret, password=Password,
                        user_agent=User_agent, username=Username)
        reddit.read_only = True # makes the program like 2x faster

        sub = reddit.subreddit(self.subreddit)
        posts = sub.top(limit = self.numPosts)

        chain = Chain()

        for post in posts:
            if not post.stickied and not post.title in self.filteredPosts and not 'battleforthenet' in post.url:
                # print(post.title)

                if not self.useCommentData:
                    post = toLetters(post.title)
                    chain.add_words(post)
                    continue

                comments = post.comments
                for i, comment in enumerate(comments):
                    if i>=6: break
                    comment = comment.body.replace('\n', ' ')
                    if self.lettersAndNumsOnly:
                        comment = toLetters(comment)
                    if not 'https' in comment:
                        # print(30*'-')
                        # print(comment)
                        chain.add_words(comment)

        filename = 'r_' + self.subreddit + '.xml'
        output = open(filename, 'w+')

        if self.useCommentData:
            output.write('r_'+self.subreddit)
        else:
            output.write('T r_' + self.subreddit)

        # print(30*'=')
        for x in range(genAmount):
            output.write('\n'+chain.gen_messge())
Ejemplo n.º 18
0
    def renderChain(self):
        self.statusBox.clear()

        tails = []
        for stage in Chain.StageRegistry.registry.GetStageInstances():
            if (len(stage.GetOutputStages()) == 0): tails.append(stage)
        try:
            Chain.Render(tails)
        except:
            pass

        if (not self.__visualizationsInitialized):
            self.initializeVisualizations()
            self.__visualizationsInitialized = True

        for vis in self.__visualizations:
            try:
                vis.refresh()
            except:
                pass

        for pe in self.__propertyEditors.values():
            pe.SetProperties()
            
            self._properties["Prefix Name"] = prefixName


    def GetOutputImagePath(self, inputImagePath):

        # construct the output image path, including the prefix name
        return os.path.join(self._properties["Output Image Path"],
                            self._properties["Prefix Name"] + 
                            os.path.splitext(os.path.basename(inputImagePath))[0] +
                            "."+self._properties["Image Extension"])
    
    def ProcessImage(self, inputImagePath, outputImagePath):

        # copy the input to output
        shutil.copy(inputImagePath, outputImagePath)


#################################################################################
        
# input/output image path
imagePath = os.path.abspath("../Datasets/ET")
imagePathOut = os.path.join(imagePath, "test")
Common.Utility.MakeDir(imagePathOut)

imageSource = Sources.ImageSource(imagePath, "jpg")

imageCopy = CopyImages(imageSource, "test-", imagePathOut, "jpg")

print Chain.Render(imageCopy)
Ejemplo n.º 20
0
    def __init__(self,
                 initial_condition,
                 param_priors,
                 step_sigmas,
                 systematic_error=False,
                 degeneracy=True):
        """
        sampler class

        Parameters:
        ----------
        initial_condition: Dictionary{String: float}
            A dictionary defining the starting parameter values of the sampler
        
        param_priors: Dictionary{String: String}
            A dictionary defining the prior distributions of the input parameters

        step_sigma: [floats]
            A list containing the parameter step standard deviations. The parameter
            standard deviations determine how far each step of the generating function
            is allowed to attempt to travel

        systematic_error: Boolean
            Tells the sampler whether to calculate the likelihood 
            with or without using the systematic error

        degeneracy: Boolean
            Tells the sampler whether the degenerate relationship between
            M and H0 should be preserved or discarded.

        Attributes:
        ----------
        chain: Chain
            An instance of the Chain class which contains the
            Markov Chain which the sampler is creating
            
        LK: likelihood
            An instance of the likelihood class which will
            return the log-likelihood of each set of parameter
            values
            
        sys_error: boolean
            The storage of the systematic_error input

        initial_params: Dictionary{String: float}
            The dictionary mapping the starting parameter values
            to the parameters in question. Stored for the purpose
            of calculating prior probability densities.
        
        current_params: Dictionary{String: float}
            The dictionary mapping the current parameter
            values to the parameters in question

        current_prior_p: float
            The combined prior probability of the current parameter values

        candidate_params: Dictionary{string: float}
            The dictionary mapping the candidate parameter
            values to the parameters in question.

        candidate_prior_p: float
            The combined prior probability of the candidate parameter values
                
        param_priors: Dictionary{String: float}
            The dictionary mapping each parameter to a 
            prior distribution. The float is assumed to
            be the std of a gaussian distribution. If the value
            is zero, then it is instead a uniform distribution

        step_sigmas: [floats]
            Storing the input step_sigmas as described above

        cov_alpha: float
            Determines the coefficient alpha multiplying the covariance
            matrix

        cov: array[floats]
            The covariance matrix of the generating function

        cov_inverse: array[floats]
            The inverse of the covariance matrix

        degeneracy: Boolean
            Described above

        Usage example:
        ---------------
        import MCsampler
        cov = np.identity()
        initial_params = {"Omega_m": 0.3,
                          "Omega_lambda": 0.7,
                          "H0": 74.0,
                          "M_nuisance": -19.23,
                          "Omega_k": 0.0,
                         }
        priors = {"Omega_m": 0.0,
                  "Omega_lambda": 0.0,
                  "H0": 0.0,
                  "M_nuisance": 0.042,
                  "Omega_k": 0.0
        }
        scaling = [0.1, 0.1, 1.0, 0.1, 0.1]
        mcmc = MCsampler.MCMC(initial_params, priors, scaling, True, False)
        mcmc.learncov(cov)
        for _ in range(number_steps):
            mcmc.add_to_chain()
        chain = mcmc.return_chain()
        """

        self.chain = Chain.Chain(initial_condition)
        self.LK = likelihood.LK()
        self.sys_error = systematic_error
        self.initial_params = initial_condition
        self.current_params = initial_condition
        self.current_prior_p = 1.0
        self.candidate_params = {}
        self.candidate_prior_p = 1.0
        self.param_priors = param_priors
        self.step_sigmas = step_sigmas
        self.cov_alpha = 0.1
        self.cov = self.cov_alpha * np.identity(5)
        self.cov_inverse = np.linalg.inv(self.cov)
        self.degeneracy = degeneracy
Ejemplo n.º 21
0
# Copyright (c) 2012, Adam J. Rossi. All rights reserved. See README for licensing details.
import sys, os
sys.path.append(os.path.abspath("."))
import Chain  # Chain must be imported first, requirement of registry
import Sources, FeatureExtraction, Common

# path to images
imagePath = os.path.abspath("../Datasets/ET")

# build chain
imageSource = Sources.ImageSource(imagePath, "jpg")

# insert tap point stage with print function
tap = Common.TapPoint(
    imageSource, {Common.sfmImages: lambda x: "Image Path: " + x.GetPath()})

# insert tap point stage without print function
tap = Common.TapPoint(tap)

sift = FeatureExtraction.Sift(tap, False, "SiftHess")

# render chain
print Chain.Render(sift, "tapPoint.txt")
Ejemplo n.º 22
0
import Block
import Chain

if __name__ == "__main__":
    blockchain = Chain.Chain()

    print("Starting the Program")
    print(blockchain.chain)

    blockchain.get_data(
        sender="0",
        receiver="Jacob",
        amount=1
    )

    block = blockchain.mine_block("Miner")

    block = blockchain.mine_block("Andrew")

    print("Mining Sucuessful")
    print(blockchain.chain)
    print("\n\n")
    for block in blockchain.chain:
        block.print()
        print("")

Ejemplo n.º 23
0
# Copyright (c) 2014, Adam J. Rossi. All rights reserved. See README for licensing details.
import sys, os
sys.path.append(os.path.abspath("."))
import Chain
import Sources, OpenCV

imagePath = os.path.abspath("../Datasets/ET")
imageSource = Sources.ImageSource(imagePath, "jpg")

fd = OpenCV.FeatureDetector(imageSource, forceRun=True)

fm = OpenCV.FeatureMatcher(fd,
                           "BruteForce",
                           os.path.join(imagePath, "matches.txt"),
                           forceRun=True)

print(Chain.Render(fm, 'openCV.txt'))
Ejemplo n.º 24
0
def imageConvertChain(imagePath):
    
    imageSource = Sources.ImageSource(imagePath, "jpg")
    imageConvert = Sources.ImageConvert(imageSource, imagePath, "pgm")
    print Chain.Render(imageConvert,"UnitTest-imageConvertChain-log.txt")
import Chain
import random

blocks = [Chain.GenesisBlock(name='Main', password='******', block_id=str(10))]

previous_digest = blocks[0].compute_hash()

for i in range(0, 10):
    random_id = 10
    block = Chain.Block(name='Prasanna',
                        password='******',
                        previous_hash=previous_digest,
                        bolck_id=str(random_id))
    blocks.append(block)
    previous_digest = block.compute_hash()

hashes = [i.getPreviousHash() for i in blocks[1:]]
print(hashes)

#check integrity of any block:
block_number = 5

#get hash of the block 5 and that hash is stored in 5+1th block , for any n block, n+1 block has its hash

#hash of that block
previous_digest = blocks[block_number + 1].getPreviousHash()

#block:
block = blocks[block_number]

#check integrity:
Ejemplo n.º 26
0
def insert_chain_novacoin(store):
    import Chain
    store.insert_chain(Chain.create("NovaCoin"))
Ejemplo n.º 27
0
 def performRender(self, stageObject):
     print
     print Chain.Render(stageObject,"log.txt")
Ejemplo n.º 28
0
# Copyright (c) 2012, Adam J. Rossi. All rights reserved. See README for licensing details.
import sys, os
sys.path.append(os.path.abspath("."))
import Chain  # Chain must be imported first, requirement of registry
import Sources, FeatureExtraction, FeatureMatch, BundleAdjustment, Cluster, Common

# path to images / PMVS
imagePath = os.path.abspath("../Datasets/ET")
pmvsPath = os.path.join(imagePath, "pmvs")

# build chain
imageSourceJpg = Sources.ImageSource(imagePath, "jpg")
imageSource = Sources.ImageConvert(imageSourceJpg, imagePath, "pgm")
asift = FeatureExtraction.ASIFT(imageSource)
keyMatch = FeatureMatch.ASIFTMatch(asift)
bundler = BundleAdjustment.Bundler([keyMatch, imageSource])
radialUndistort = Cluster.RadialUndistort([bundler, imageSourceJpg])
prepCmvsPmvs = Cluster.PrepCmvsPmvs(radialUndistort, pmvsPath)
cmvs = Cluster.CMVS(prepCmvsPmvs)
pmvs = Cluster.PMVS(cmvs)

# render chain
print Chain.Render(pmvs, "asift.txt")
Ejemplo n.º 29
0
def insert_chain_novacoin(store):
    import Chain
    try:
        store.insert_chain(Chain.create("NovaCoin"))
    except Exception:
        pass
Ejemplo n.º 30
0
def insert_chain_novacoin(store):
    import Chain
    store.insert_chain(Chain.create("NovaCoin"))
Ejemplo n.º 31
0
def insert_chain_novacoin(store):
    import Chain
    try:
        store.insert_chain(Chain.create("NovaCoin"))
    except Exception:
        pass
Ejemplo n.º 32
0
L[1].r = mat([0, -1.054, 0])
L[2].r = mat([0, 0, -6.447])
L[3].r = mat([0, 0.092, -0.054])
L[4].r = mat([0, 0, 0.566])
L[5].r = mat([0, 0, 1.554])

L[0].I = mat([0.276, 0.255, 0.071, 0, 0, 0])
L[1].I = mat([0.108, 0.018, 0.100, 0, 0, 0])
L[2].I = mat([2.51, 2.51, 0.006, 0, 0, 0])
L[3].I = mat([0.002, 0.001, 0.001, 0, 0, 0])
L[4].I = mat([0.003, 0.003, 0.0004, 0, 0, 0])
L[5].I = mat([0.013, 0.013, 0.0003, 0, 0, 0])

L[0].Jm = 0.953
L[1].Jm = 2.193
L[2].Jm = 0.782
L[3].Jm = 0.106
L[4].Jm = 0.097
L[5].Jm = 0.020

L[0].G = 1
L[1].G = 1
L[2].G = 1
L[3].G = 1
L[4].G = 1
L[5].G = 1

qz = [0, 0, 0, 0, 0, 0]

stanf = Chain(L, name='Stanford arm')