idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
|---|---|---|
10,100
|
def trimSegments ( self , minPermanence = None , minNumSyns = None ) : if minPermanence is None : minPermanence = self . connectedPerm if minNumSyns is None : minNumSyns = self . activationThreshold totalSegsRemoved , totalSynsRemoved = 0 , 0 for c , i in product ( xrange ( self . numberOfCols ) , xrange ( self . cellsPerColumn ) ) : ( segsRemoved , synsRemoved ) = self . trimSegmentsInCell ( colIdx = c , cellIdx = i , segList = self . cells [ c ] [ i ] , minPermanence = minPermanence , minNumSyns = minNumSyns ) totalSegsRemoved += segsRemoved totalSynsRemoved += synsRemoved return totalSegsRemoved , totalSynsRemoved
|
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining .
|
10,101
|
def checkPrediction2 ( self , patternNZs , output = None , confidence = None , details = False ) : numPatterns = len ( patternNZs ) orAll = set ( ) orAll = orAll . union ( * patternNZs ) if output is None : assert self . currentOutput is not None output = self . currentOutput output = set ( output . sum ( axis = 1 ) . nonzero ( ) [ 0 ] ) totalExtras = len ( output . difference ( orAll ) ) totalMissing = len ( orAll . difference ( output ) ) if confidence is None : confidence = self . confidence [ 't' ] colConfidence = self . columnConfidences ( confidence ) confidences = [ ] for i in xrange ( numPatterns ) : positivePredictionSum = colConfidence [ patternNZs [ i ] ] . sum ( ) positiveColumnCount = len ( patternNZs [ i ] ) totalPredictionSum = colConfidence . sum ( ) totalColumnCount = len ( colConfidence ) negativePredictionSum = totalPredictionSum - positivePredictionSum negativeColumnCount = totalColumnCount - positiveColumnCount if positiveColumnCount != 0 : positivePredictionScore = positivePredictionSum / positiveColumnCount else : positivePredictionScore = 0.0 if negativeColumnCount != 0 : negativePredictionScore = negativePredictionSum / negativeColumnCount else : negativePredictionScore = 0.0 predictionScore = positivePredictionScore - negativePredictionScore confidences . append ( ( predictionScore , positivePredictionScore , negativePredictionScore ) ) if details : missingPatternBits = [ set ( pattern ) . difference ( output ) for pattern in patternNZs ] return ( totalExtras , totalMissing , confidences , missingPatternBits ) else : return ( totalExtras , totalMissing , confidences )
|
This function will replace checkPrediction .
|
10,102
|
def isSegmentActive ( self , seg , activeState ) : return isSegmentActive ( seg . syns , activeState , self . connectedPerm , self . activationThreshold )
|
A segment is active if it has > = activationThreshold connected synapses that are active due to activeState .
|
10,103
|
def getActiveSegment ( self , c , i , timeStep ) : nSegments = len ( self . cells [ c ] [ i ] ) bestActivation = self . activationThreshold which = - 1 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , self . activeState [ timeStep ] , connectedSynapsesOnly = True ) if activity >= bestActivation : bestActivation = activity which = j if which != - 1 : return self . cells [ c ] [ i ] [ which ] else : return None
|
For a given cell return the segment with the strongest _connected_ activation i . e . sum up the activations of the connected synapses of the segments only . That is a segment is active only if it has enough connected synapses .
|
10,104
|
def chooseCellsToLearnFrom ( self , c , i , s , n , timeStep ) : if n <= 0 : return [ ] tmpCandidates = [ ] if timeStep == 't-1' : tmpCandidates = numpy . where ( self . learnState [ 't-1' ] == 1 ) else : tmpCandidates = numpy . where ( self . learnState [ 't' ] == 1 ) if len ( tmpCandidates [ 0 ] ) == 0 : return [ ] if s is None : cands = [ syn for syn in zip ( tmpCandidates [ 0 ] , tmpCandidates [ 1 ] ) ] else : synapsesAlreadyInSegment = set ( ( syn [ 0 ] , syn [ 1 ] ) for syn in s . syns ) cands = [ syn for syn in zip ( tmpCandidates [ 0 ] , tmpCandidates [ 1 ] ) if ( syn [ 0 ] , syn [ 1 ] ) not in synapsesAlreadyInSegment ] if n == 1 : idx = self . _random . getUInt32 ( len ( cands ) ) return [ cands [ idx ] ] self . _random . getUInt32 ( 10 ) indices = array ( [ j for j in range ( len ( cands ) ) ] , dtype = 'uint32' ) tmp = zeros ( min ( n , len ( indices ) ) , dtype = 'uint32' ) self . _random . getUInt32Sample ( indices , tmp , True ) return [ cands [ j ] for j in tmp ]
|
Choose n random cells to learn from .
|
10,105
|
def getBestMatchingCell ( self , c , activeState ) : bestActivityInCol = self . minThreshold bestSegIdxInCol = - 1 bestCellInCol = - 1 for i in xrange ( self . cellsPerColumn ) : maxSegActivity = 0 maxSegIdx = 0 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , activeState , connectedSynapsesOnly = False ) if self . verbosity >= 6 : print " Segment Activity for column " , c , " cell " , i , " segment " , " j is " , activity if activity > maxSegActivity : maxSegActivity = activity maxSegIdx = j if maxSegActivity >= bestActivityInCol : bestActivityInCol = maxSegActivity bestSegIdxInCol = maxSegIdx bestCellInCol = i if self . verbosity >= 6 : print "Best Matching Cell In Col: " , bestCellInCol if bestCellInCol == - 1 : return ( None , None ) else : return bestCellInCol , self . cells [ c ] [ bestCellInCol ] [ bestSegIdxInCol ]
|
Find weakly activated cell in column . Returns index and segment of most activated segment above minThreshold .
|
10,106
|
def getBestMatchingSegment ( self , c , i , activeState ) : maxActivity , which = self . minThreshold , - 1 for j , s in enumerate ( self . cells [ c ] [ i ] ) : activity = self . getSegmentActivityLevel ( s , activeState , connectedSynapsesOnly = False ) if activity >= maxActivity : maxActivity , which = activity , j if which == - 1 : return None else : return self . cells [ c ] [ i ] [ which ]
|
For the given cell find the segment with the largest number of active synapses . This routine is aggressive in finding the best match . The permanence value of synapses is allowed to be below connectedPerm . The number of active synapses is allowed to be below activationThreshold but must be above minThreshold . The routine returns the segment index . If no segments are found then an index of - 1 is returned .
|
10,107
|
def getLeastUsedCell ( self , c ) : segmentsPerCell = numpy . zeros ( self . cellsPerColumn , dtype = 'uint32' ) for i in range ( self . cellsPerColumn ) : segmentsPerCell [ i ] = self . getNumSegmentsInCell ( c , i ) cellMinUsage = numpy . where ( segmentsPerCell == segmentsPerCell . min ( ) ) [ 0 ] self . _random . getUInt32 ( len ( cellMinUsage ) ) return cellMinUsage [ self . _random . getUInt32 ( len ( cellMinUsage ) ) ]
|
For the least used cell in a column
|
10,108
|
def updateSynapses ( self , segment , synapses , delta ) : reached0 = False if delta > 0 : for synapse in synapses : segment [ synapse ] [ 2 ] = newValue = segment [ synapse ] [ 2 ] + delta if newValue > self . permanenceMax : segment [ synapse ] [ 2 ] = self . permanenceMax else : for synapse in synapses : segment [ synapse ] [ 2 ] = newValue = segment [ synapse ] [ 2 ] + delta if newValue < 0 : segment [ synapse ] [ 2 ] = 0 reached0 = True return reached0
|
Update a set of synapses of the given segment delta can be permanenceInc or permanenceDec .
|
10,109
|
def adaptSegment ( self , segUpdate , positiveReinforcement ) : trimSegment = False c , i , segment = segUpdate . columnIdx , segUpdate . cellIdx , segUpdate . segment activeSynapses = segUpdate . activeSynapses synToUpdate = set ( [ syn for syn in activeSynapses if type ( syn ) == int ] ) if segment is not None : if positiveReinforcement : if self . verbosity >= 4 : print "Reinforcing segment for cell[%d,%d]" % ( c , i ) , segment . printSegment ( ) segment . positiveActivations += 1 segment . dutyCycle ( active = True ) lastSynIndex = len ( segment . syns ) - 1 inactiveSynIndices = [ s for s in xrange ( 0 , lastSynIndex + 1 ) if s not in synToUpdate ] trimSegment = segment . updateSynapses ( inactiveSynIndices , - self . permanenceDec ) activeSynIndices = [ syn for syn in synToUpdate if syn <= lastSynIndex ] segment . updateSynapses ( activeSynIndices , self . permanenceInc ) synsToAdd = [ syn for syn in activeSynapses if type ( syn ) != int ] for newSyn in synsToAdd : segment . addSynapse ( newSyn [ 0 ] , newSyn [ 1 ] , self . initialPerm ) if self . verbosity >= 4 : print " after" , segment . printSegment ( ) else : desc = "" if self . verbosity >= 4 : print "Negatively Reinforcing %s segment for cell[%d,%d]" % ( desc , c , i ) , segment . printSegment ( ) segment . dutyCycle ( active = True ) trimSegment = segment . updateSynapses ( synToUpdate , - self . permanenceDec ) if self . verbosity >= 4 : print " after" , segment . printSegment ( ) else : newSegment = Segment ( tp = self , isSequenceSeg = segUpdate . sequenceSegment ) for synapse in activeSynapses : newSegment . addSynapse ( synapse [ 0 ] , synapse [ 1 ] , self . initialPerm ) if self . verbosity >= 3 : print "New segment for cell[%d,%d]" % ( c , i ) , newSegment . printSegment ( ) self . cells [ c ] [ i ] . append ( newSegment ) return trimSegment
|
This function applies segment update information to a segment in a cell .
|
10,110
|
def getSegmentInfo ( self , collectActiveData = False ) : nSegments , nSynapses = 0 , 0 nActiveSegs , nActiveSynapses = 0 , 0 distSegSizes , distNSegsPerCell = { } , { } distPermValues = { } numAgeBuckets = 20 distAges = [ ] ageBucketSize = int ( ( self . lrnIterationIdx + 20 ) / 20 ) for i in range ( numAgeBuckets ) : distAges . append ( [ '%d-%d' % ( i * ageBucketSize , ( i + 1 ) * ageBucketSize - 1 ) , 0 ] ) for c in xrange ( self . numberOfCols ) : for i in xrange ( self . cellsPerColumn ) : if len ( self . cells [ c ] [ i ] ) > 0 : nSegmentsThisCell = len ( self . cells [ c ] [ i ] ) nSegments += nSegmentsThisCell if distNSegsPerCell . has_key ( nSegmentsThisCell ) : distNSegsPerCell [ nSegmentsThisCell ] += 1 else : distNSegsPerCell [ nSegmentsThisCell ] = 1 for seg in self . cells [ c ] [ i ] : nSynapsesThisSeg = seg . getNumSynapses ( ) nSynapses += nSynapsesThisSeg if distSegSizes . has_key ( nSynapsesThisSeg ) : distSegSizes [ nSynapsesThisSeg ] += 1 else : distSegSizes [ nSynapsesThisSeg ] = 1 for syn in seg . syns : p = int ( syn [ 2 ] * 10 ) if distPermValues . has_key ( p ) : distPermValues [ p ] += 1 else : distPermValues [ p ] = 1 age = self . lrnIterationIdx - seg . lastActiveIteration ageBucket = int ( age / ageBucketSize ) distAges [ ageBucket ] [ 1 ] += 1 if collectActiveData : if self . isSegmentActive ( seg , self . infActiveState [ 't' ] ) : nActiveSegs += 1 for syn in seg . syns : if self . activeState [ 't' ] [ syn [ 0 ] ] [ syn [ 1 ] ] == 1 : nActiveSynapses += 1 return ( nSegments , nSynapses , nActiveSegs , nActiveSynapses , distSegSizes , distNSegsPerCell , distPermValues , distAges )
|
Returns information about the distribution of segments synapses and permanence values in the current TP . If requested also returns information regarding the number of currently active segments and synapses .
|
10,111
|
def updateSynapses ( self , synapses , delta ) : reached0 = False if delta > 0 : for synapse in synapses : self . syns [ synapse ] [ 2 ] = newValue = self . syns [ synapse ] [ 2 ] + delta if newValue > self . tp . permanenceMax : self . syns [ synapse ] [ 2 ] = self . tp . permanenceMax else : for synapse in synapses : self . syns [ synapse ] [ 2 ] = newValue = self . syns [ synapse ] [ 2 ] + delta if newValue <= 0 : self . syns [ synapse ] [ 2 ] = 0 reached0 = True return reached0
|
Update a set of synapses in the segment .
|
10,112
|
def maxEntropy ( n , k ) : s = float ( k ) / n if s > 0.0 and s < 1.0 : entropy = - s * math . log ( s , 2 ) - ( 1 - s ) * math . log ( 1 - s , 2 ) else : entropy = 0 return n * entropy
|
The maximum enropy we could get with n units and k winners
|
10,113
|
def binaryEntropy ( x ) : entropy = - x * x . log2 ( ) - ( 1 - x ) * ( 1 - x ) . log2 ( ) entropy [ x * ( 1 - x ) == 0 ] = 0 return entropy , entropy . sum ( )
|
Calculate entropy for a list of binary random variables
|
10,114
|
def plotDutyCycles ( dutyCycle , filePath ) : _ , entropy = binaryEntropy ( dutyCycle ) bins = np . linspace ( 0.0 , 0.3 , 200 ) plt . hist ( dutyCycle , bins , alpha = 0.5 , label = 'All cols' ) plt . title ( "Histogram of duty cycles, entropy=" + str ( float ( entropy ) ) ) plt . xlabel ( "Duty cycle" ) plt . ylabel ( "Number of units" ) plt . savefig ( filePath ) plt . close ( )
|
Create plot showing histogram of duty cycles
|
10,115
|
def compute ( self , inputVector , learn , activeArray ) : super ( SpatialPoolerWrapper , self ) . compute ( inputVector , learn , activeArray ) self . _updateAvgActivityPairs ( activeArray )
|
This method resembles the primary public method of the SpatialPooler class .
|
10,116
|
def computeMaxPool ( input_width ) : wout = math . floor ( ( input_width + 2 * PADDING - KERNEL_SIZE ) / STRIDE + 1 ) return int ( math . floor ( wout / 2.0 ) )
|
Compute CNN max pool width . see cnn_sdr . py
|
10,117
|
def createRandomObjects ( self , numObjects , numPoints , numLocations = None , numFeatures = None ) : if numObjects > 0 : if numLocations is None : numLocations = numPoints if numFeatures is None : numFeatures = numPoints assert ( numPoints <= numLocations ) , ( "Number of points in object cannot be " "greater than number of locations" ) locationArray = numpy . array ( range ( numLocations ) ) numpy . random . seed ( self . seed ) for _ in xrange ( numObjects ) : locationArray = numpy . random . permutation ( locationArray ) self . addObject ( [ ( locationArray [ p ] , numpy . random . randint ( 0 , numFeatures ) ) for p in xrange ( numPoints ) ] , )
|
Creates a set of random objects and adds them to the machine . If numLocations and numFeatures and not specified they will be set to the desired number of points .
|
10,118
|
def getUniqueFeaturesLocationsInObject ( self , name ) : uniqueFeatures = set ( ) uniqueLocations = set ( ) for pair in self . objects [ name ] : uniqueLocations = uniqueLocations . union ( { pair [ 0 ] } ) uniqueFeatures = uniqueFeatures . union ( { pair [ 1 ] } ) return uniqueLocations , uniqueFeatures
|
Return two sets . The first set contains the unique locations Ids in the object . The second set contains the unique feature Ids in the object .
|
10,119
|
def _generateLocations ( self ) : size = self . externalInputSize bits = self . numInputBits random . seed ( self . seed ) self . locations = [ ] for _ in xrange ( self . numColumns ) : self . locations . append ( [ self . _generatePattern ( bits , size ) for _ in xrange ( self . numLocations ) ] )
|
Generates a pool of locations to be used for the experiments .
|
10,120
|
def getDetectorClassConstructors ( detectors ) : detectorConstructors = { d : globals ( ) [ detectorNameToClass ( d ) ] for d in detectors } return detectorConstructors
|
Takes in names of detectors . Collects class names that correspond to those detectors and returns them in a dict . The dict maps detector name to class names . Assumes the detectors have been imported .
|
10,121
|
def select_action ( self , state ) : value = 0 if self . steps < self . min_steps : action = np . random . randint ( self . actions ) else : self . eps = max ( self . eps_end , self . eps * self . eps_decay ) if random . random ( ) < self . eps : action = np . random . randint ( self . actions ) else : self . local . eval ( ) with torch . no_grad ( ) : state = torch . tensor ( state , device = self . device , dtype = torch . float ) . unsqueeze ( 0 ) Q = self . local ( state ) value , action = torch . max ( Q , 1 ) return int ( action ) , float ( value )
|
Select the best action for the given state using e - greedy exploration to minimize overfitting
|
10,122
|
def inferObjects ( self , bodyPlacement , maxTouches = 2 ) : for monitor in self . monitors . itervalues ( ) : monitor . afterBodyWorldLocationChanged ( bodyPlacement ) numTouchesRequired = collections . defaultdict ( int ) for objectName , objectFeatures in self . objects . iteritems ( ) : self . reset ( ) objectPlacement = self . objectPlacements [ objectName ] featureIndexByColumnIterator = ( greedySensorPositions ( self . numCorticalColumns , len ( objectFeatures ) ) ) for touch in xrange ( maxTouches ) : featureIndexByColumn = featureIndexByColumnIterator . next ( ) sensedFeatures = [ objectFeatures [ i ] for i in featureIndexByColumn ] featureSDRByColumn = [ self . features [ ( iCol , feature [ "name" ] ) ] for iCol , feature in enumerate ( sensedFeatures ) ] worldLocationByColumn = np . array ( [ [ objectPlacement [ 0 ] + feature [ "top" ] + feature [ "height" ] / 2 , objectPlacement [ 1 ] + feature [ "left" ] + feature [ "width" ] / 2 ] for feature in sensedFeatures ] ) for monitor in self . monitors . itervalues ( ) : monitor . afterSensorWorldLocationChanged ( worldLocationByColumn ) egocentricLocationByColumn = worldLocationByColumn - bodyPlacement prevCellActivity = None for t in xrange ( self . maxSettlingTime ) : for monitor in self . monitors . itervalues ( ) : monitor . beforeCompute ( egocentricLocationByColumn , featureSDRByColumn , isRepeat = ( t > 0 ) ) self . compute ( egocentricLocationByColumn , featureSDRByColumn , learn = False ) cellActivity = ( tuple ( c . getAllCellActivity ( ) for c in self . corticalColumns ) , tuple ( set ( module . activeCells ) for module in self . bodyToSpecificObjectModules ) ) if cellActivity == prevCellActivity : for monitor in self . monitors . itervalues ( ) : monitor . clearUnflushedData ( ) break else : prevCellActivity = cellActivity for monitor in self . monitors . itervalues ( ) : monitor . flush ( ) if self . isObjectClassified ( objectName ) : numTouchesRequired [ touch + 1 ] += 1 break else : numTouchesRequired [ None ] += 1 return numTouchesRequired
|
Touch each object with multiple sensors twice .
|
10,123
|
def plotAccuracy ( suite , name ) : path = suite . cfgparser . get ( name , "path" ) path = os . path . join ( path , name ) accuracy = defaultdict ( list ) sensations = defaultdict ( list ) for exp in suite . get_exps ( path = path ) : params = suite . get_params ( exp ) maxTouches = params [ "num_sensations" ] cells = params [ "cells_per_axis" ] res = suite . get_history ( exp , 0 , "Correct classification" ) classified = [ any ( x ) for x in res ] accuracy [ cells ] = float ( sum ( classified ) ) / float ( len ( classified ) ) touches = [ np . argmax ( x ) or maxTouches for x in res ] sensations [ cells ] = [ np . mean ( touches ) , np . max ( touches ) ] plt . title ( "Classification Accuracy" ) accuracy = OrderedDict ( sorted ( accuracy . items ( ) , key = lambda t : t [ 0 ] ) ) fig , ax1 = plt . subplots ( ) ax1 . plot ( accuracy . keys ( ) , accuracy . values ( ) , "b" ) ax1 . set_xlabel ( "Cells per axis" ) ax1 . set_ylabel ( "Accuracy" , color = "b" ) ax1 . tick_params ( "y" , colors = "b" ) sensations = OrderedDict ( sorted ( sensations . items ( ) , key = lambda t : t [ 0 ] ) ) ax2 = ax1 . twinx ( ) ax2 . set_prop_cycle ( linestyle = [ "-" , "--" ] ) ax2 . plot ( sensations . keys ( ) , sensations . values ( ) , "r" ) ax2 . set_ylabel ( "Sensations" , color = "r" ) ax2 . tick_params ( "y" , colors = "r" ) ax2 . legend ( ( "Mean" , "Max" ) ) path = suite . cfgparser . get ( name , "path" ) plotPath = os . path . join ( path , "{}.pdf" . format ( name ) ) plt . savefig ( plotPath ) plt . close ( )
|
Plots classification accuracy
|
10,124
|
def get_error ( data , labels , pos_neurons , neg_neurons = [ ] , add_noise = True ) : num_correct = 0 num_false_positives = 0 num_false_negatives = 0 classifications = numpy . zeros ( data . nRows ( ) ) for neuron in pos_neurons : classifications += neuron . calculate_on_entire_dataset ( data ) for neuron in neg_neurons : classifications -= neuron . calculate_on_entire_dataset ( data ) if add_noise : classifications += ( numpy . random . rand ( ) - 0.5 ) / 1000 classifications = numpy . sign ( classifications ) for classification , label in zip ( classifications , labels ) : if classification > 0 and label > 0 : num_correct += 1.0 elif classification <= 0 and label <= 0 : num_correct += 1.0 elif classification > 0 and label <= 0 : num_false_positives += 1 else : num_false_negatives += 1 return ( 1. * num_false_positives + num_false_negatives ) / data . nRows ( ) , num_false_positives , num_false_negatives
|
Calculates error including number of false positives and false negatives .
|
10,125
|
def computeActivity ( self , activeInputsBySource , permanenceThreshold = None ) : overlaps = None for source , connections in self . connectionsBySource . iteritems ( ) : o = connections . computeActivity ( activeInputsBySource [ source ] , permanenceThreshold ) if overlaps is None : overlaps = o else : overlaps += o return overlaps
|
Calculate the number of active synapses per segment .
|
10,126
|
def createSegments ( self , cells ) : segments = None for connections in self . connectionsBySource . itervalues ( ) : created = connections . createSegments ( cells ) if segments is None : segments = created else : np . testing . assert_equal ( segments , created ) return segments
|
Create a segment on each of the specified cells .
|
10,127
|
def growSynapses ( self , segments , activeInputsBySource , initialPermanence ) : for source , connections in self . connectionsBySource . iteritems ( ) : connections . growSynapses ( segments , activeInputsBySource [ source ] , initialPermanence )
|
Grow synapses to each of the specified inputs on each specified segment .
|
10,128
|
def setPermanences ( self , segments , presynapticCellsBySource , permanence ) : permanences = np . repeat ( np . float32 ( permanence ) , len ( segments ) ) for source , connections in self . connectionsBySource . iteritems ( ) : if source in presynapticCellsBySource : connections . matrix . setElements ( segments , presynapticCellsBySource [ source ] , permanences )
|
Set the permanence of a specific set of synapses . Any synapses that don t exist will be initialized . Any existing synapses will be overwritten .
|
10,129
|
def loadImage ( t , filename = "cajal.jpg" ) : image = Image . open ( "cajal.jpg" ) . convert ( "1" ) image . load ( ) box = ( 0 , 0 , t . inputWidth , t . inputHeight ) image = image . crop ( box ) a = np . asarray ( image ) im = np . ones ( ( t . inputWidth , t . inputHeight ) ) im [ a ] = 0 return im
|
Load the given gray scale image . Threshold it to black and white and crop it to be the dimensions of the FF input for the thalamus . Return a binary numpy matrix where 1 corresponds to black and 0 corresponds to white .
|
10,130
|
def inferThalamus ( t , l6Input , ffInput ) : print ( "\n-----------" ) t . reset ( ) t . deInactivateCells ( l6Input ) ffOutput = t . computeFeedForwardActivity ( ffInput ) return ffOutput
|
Compute the effect of this feed forward input given the specific L6 input .
|
10,131
|
def filtered ( w = 250 ) : kernels = [ ] for theta in range ( 4 ) : theta = theta / 4. * np . pi for sigma in ( 1 , 3 ) : for frequency in ( 0.05 , 0.25 ) : kernel = np . real ( gabor_kernel ( frequency , theta = theta , sigma_x = sigma , sigma_y = sigma ) ) kernels . append ( kernel ) print ( "Initializing thalamus" ) t = Thalamus ( trnCellShape = ( w , w ) , relayCellShape = ( w , w ) , inputShape = ( w , w ) , l6CellCount = 128 * 128 , trnThreshold = 15 , ) ff = loadImage ( t ) for i , k in enumerate ( kernels ) : plotActivity ( k , "kernel" + str ( i ) + ".jpg" , "Filter kernel" , vmax = k . max ( ) , vmin = k . min ( ) ) filtered0 = power ( ff , k ) ft = np . zeros ( ( w , w ) ) ft [ filtered0 > filtered0 . mean ( ) + filtered0 . std ( ) ] = 1.0 plotActivity ( ft , "filtered" + str ( i ) + ".jpg" , "Filtered image" , vmax = 1.0 ) encoder = createLocationEncoder ( t , w = 17 ) trainThalamusLocations ( t , encoder ) filtered0 = power ( ff , kernels [ 3 ] ) ft = np . zeros ( ( w , w ) ) ft [ filtered0 > filtered0 . mean ( ) + filtered0 . std ( ) ] = 1.0 print ( "Getting unions" ) l6Code = list ( getUnionLocations ( encoder , 125 , 125 , 150 , step = 10 ) ) print ( "Num active cells in L6 union:" , len ( l6Code ) , "out of" , t . l6CellCount ) ffOutput = inferThalamus ( t , l6Code , ft ) plotActivity ( t . burstReadyCells , "relay_burstReady_filtered.jpg" , title = "Burst-ready cells" , ) plotActivity ( ffOutput , "cajal_relay_output_filtered.jpg" , title = "Filtered activity" , cmap = "Greys" ) print ( "Getting unions" ) l6Code = list ( getUnionLocations ( encoder , 125 , 125 , 150 , step = 3 ) ) print ( "Num active cells in L6 union:" , len ( l6Code ) , "out of" , t . l6CellCount ) ffOutput_all = inferThalamus ( t , l6Code , ff ) ffOutput_filtered = inferThalamus ( t , l6Code , ft ) ffOutput3 = ffOutput_all * 0.4 + ffOutput_filtered plotActivity ( t . burstReadyCells , "relay_burstReady_all.jpg" , title = "Burst-ready cells" , ) plotActivity ( ffOutput3 , "cajal_relay_output_filtered2.jpg" , title = "Filtered activity" , cmap = "Greys" )
|
In this example we filter the image into several channels using gabor filters . L6 activity is used to select one of those channels . Only activity selected by those channels burst .
|
10,132
|
def get_delimited_message_bytes ( byte_stream , nr = 4 ) : ( length , pos ) = decoder . _DecodeVarint32 ( byte_stream . read ( nr ) , 0 ) if log . getEffectiveLevel ( ) == logging . DEBUG : log . debug ( "Delimited message length (pos %d): %d" % ( pos , length ) ) delimiter_bytes = nr - pos byte_stream . rewind ( delimiter_bytes ) message_bytes = byte_stream . read ( length ) if log . getEffectiveLevel ( ) == logging . DEBUG : log . debug ( "Delimited message bytes (%d): %s" % ( len ( message_bytes ) , format_bytes ( message_bytes ) ) ) total_len = length + pos return ( total_len , message_bytes )
|
Parse a delimited protobuf message . This is done by first getting a protobuf varint from the stream that represents the length of the message then reading that amount of from the message and then parse it . Since the int can be represented as max 4 bytes first get 4 bytes and try to decode . The decoder returns the value and the position where the value was found so we need to rewind the buffer to the position because the remaining bytes belong to the message after .
|
10,133
|
def read ( self , n ) : bytes_wanted = n - self . buffer_length + self . pos + 1 if bytes_wanted > 0 : self . _buffer_bytes ( bytes_wanted ) end_pos = self . pos + n ret = self . buffer [ self . pos + 1 : end_pos + 1 ] self . pos = end_pos return ret
|
Reads n bytes into the internal buffer
|
10,134
|
def rewind ( self , places ) : log . debug ( "Rewinding pos %d with %d places" % ( self . pos , places ) ) self . pos -= places log . debug ( "Reset buffer to pos %d" % self . pos )
|
Rewinds the current buffer to a position . Needed for reading varints because we might read bytes that belong to the stream after the varint .
|
10,135
|
def create_rpc_request_header ( self ) : rpcheader = RpcRequestHeaderProto ( ) rpcheader . rpcKind = 2 rpcheader . rpcOp = 0 rpcheader . callId = self . call_id rpcheader . retryCount = - 1 rpcheader . clientId = self . client_id [ 0 : 16 ] if self . call_id == - 3 : self . call_id = 0 else : self . call_id += 1 s_rpcHeader = rpcheader . SerializeToString ( ) log_protobuf_message ( "RpcRequestHeaderProto (len: %d)" % ( len ( s_rpcHeader ) ) , rpcheader ) return s_rpcHeader
|
Creates and serializes a delimited RpcRequestHeaderProto message .
|
10,136
|
def send_rpc_message ( self , method , request ) : log . debug ( "############## SENDING ##############" ) rpc_request_header = self . create_rpc_request_header ( ) request_header = self . create_request_header ( method ) param = request . SerializeToString ( ) if log . getEffectiveLevel ( ) == logging . DEBUG : log_protobuf_message ( "Request" , request ) rpc_message_length = len ( rpc_request_header ) + encoder . _VarintSize ( len ( rpc_request_header ) ) + len ( request_header ) + encoder . _VarintSize ( len ( request_header ) ) + len ( param ) + encoder . _VarintSize ( len ( param ) ) if log . getEffectiveLevel ( ) == logging . DEBUG : log . debug ( "RPC message length: %s (%s)" % ( rpc_message_length , format_bytes ( struct . pack ( '!I' , rpc_message_length ) ) ) ) self . write ( struct . pack ( '!I' , rpc_message_length ) ) self . write_delimited ( rpc_request_header ) self . write_delimited ( request_header ) self . write_delimited ( param )
|
Sends a Hadoop RPC request to the NameNode .
|
10,137
|
def parse_response ( self , byte_stream , response_class ) : log . debug ( "############## PARSING ##############" ) log . debug ( "Payload class: %s" % response_class ) len_bytes = byte_stream . read ( 4 ) total_length = struct . unpack ( "!I" , len_bytes ) [ 0 ] log . debug ( "Total response length: %s" % total_length ) header = RpcResponseHeaderProto ( ) ( header_len , header_bytes ) = get_delimited_message_bytes ( byte_stream ) log . debug ( "Header read %d" % header_len ) header . ParseFromString ( header_bytes ) log_protobuf_message ( "RpcResponseHeaderProto" , header ) if header . status == 0 : log . debug ( "header: %s, total: %s" % ( header_len , total_length ) ) if header_len >= total_length : return response = response_class ( ) response_bytes = get_delimited_message_bytes ( byte_stream , total_length - header_len ) [ 1 ] if len ( response_bytes ) > 0 : response . ParseFromString ( response_bytes ) if log . getEffectiveLevel ( ) == logging . DEBUG : log_protobuf_message ( "Response" , response ) return response else : self . handle_error ( header )
|
Parses a Hadoop RPC response .
|
10,138
|
def close_socket ( self ) : log . debug ( "Closing socket" ) if self . sock : try : self . sock . close ( ) except : pass self . sock = None
|
Closes the socket and resets the channel .
|
10,139
|
def CallMethod ( self , method , controller , request , response_class , done ) : try : self . validate_request ( request ) if not self . sock : self . get_connection ( self . host , self . port ) self . send_rpc_message ( method , request ) byte_stream = self . recv_rpc_message ( ) return self . parse_response ( byte_stream , response_class ) except RequestError : raise except Exception : self . close_socket ( ) raise
|
Call the RPC method . The naming doesn t confirm PEP8 since it s a method called by protobuf
|
10,140
|
def getLogger ( name ) : log = logging . getLogger ( name ) log . addHandler ( _NullHandler ( ) ) return log
|
Create and return a logger with the specified name .
|
10,141
|
def put ( self , src , dst ) : src = "%s%s" % ( self . _testfiles_path , src ) return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-put' , src , self . _full_hdfs_path ( dst ) ] , True )
|
Upload a file to HDFS
|
10,142
|
def ls ( self , src , extra_args = [ ] ) : src = [ self . _full_hdfs_path ( x ) for x in src ] output = self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-ls' ] + extra_args + src , True ) return self . _transform_ls_output ( output , self . hdfs_url )
|
List files in a directory
|
10,143
|
def df ( self , src ) : return self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-df' , self . _full_hdfs_path ( src ) ] , True )
|
Perform df on a path
|
10,144
|
def du ( self , src , extra_args = [ ] ) : src = [ self . _full_hdfs_path ( x ) for x in src ] return self . _transform_du_output ( self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-du' ] + extra_args + src , True ) , self . hdfs_url )
|
Perform du on a path
|
10,145
|
def count ( self , src ) : src = [ self . _full_hdfs_path ( x ) for x in src ] return self . _transform_count_output ( self . _getStdOutCmd ( [ self . _hadoop_cmd , 'fs' , '-count' ] + src , True ) , self . hdfs_url )
|
Perform count on a path
|
10,146
|
def handleError ( self , error_code , message ) : self . _fail = True self . reason = error_code self . _error = message
|
Log and set the controller state .
|
10,147
|
def ls ( self , paths , recurse = False , include_toplevel = False , include_children = True ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) for item in self . _find_items ( paths , self . _handle_ls , include_toplevel = include_toplevel , include_children = include_children , recurse = recurse ) : if item : yield item
|
Issues ls command and returns a list of maps that contain fileinfo
|
10,148
|
def _handle_ls ( self , path , node ) : entry = { } entry [ "file_type" ] = self . FILETYPES [ node . fileType ] entry [ "permission" ] = node . permission . perm entry [ "path" ] = path for attribute in self . LISTING_ATTRIBUTES : entry [ attribute ] = node . __getattribute__ ( attribute ) return entry
|
Handle every node received for an ls request
|
10,149
|
def chmod ( self , paths , mode , recurse = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "chmod: no path given" ) if not mode : raise InvalidInputException ( "chmod: no mode given" ) processor = lambda path , node , mode = mode : self . _handle_chmod ( path , node , mode ) for item in self . _find_items ( paths , processor , include_toplevel = True , include_children = False , recurse = recurse ) : if item : yield item
|
Change the mode for paths . This returns a list of maps containing the resut of the operation .
|
10,150
|
def count ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "count: no path given" ) for item in self . _find_items ( paths , self . _handle_count , include_toplevel = True , include_children = False , recurse = False ) : if item : yield item
|
Count files in a path
|
10,151
|
def df ( self ) : processor = lambda path , node : self . _handle_df ( path , node ) return list ( self . _find_items ( [ '/' ] , processor , include_toplevel = True , include_children = False , recurse = False ) ) [ 0 ]
|
Get FS information
|
10,152
|
def du ( self , paths , include_toplevel = False , include_children = True ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "du: no path given" ) processor = lambda path , node : self . _handle_du ( path , node ) for item in self . _find_items ( paths , processor , include_toplevel = include_toplevel , include_children = include_children , recurse = False ) : if item : yield item
|
Returns size information for paths
|
10,153
|
def rmdir ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "rmdir: no path given" ) processor = lambda path , node : self . _handle_rmdir ( path , node ) for item in self . _find_items ( paths , processor , include_toplevel = True ) : if item : yield item
|
Delete a directory
|
10,154
|
def touchz ( self , paths , replication = None , blocksize = None ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "touchz: no path given" ) if not replication or not blocksize : defaults = self . serverdefaults ( ) if not replication : replication = defaults [ 'replication' ] if not blocksize : blocksize = defaults [ 'blockSize' ] processor = lambda path , node , replication = replication , blocksize = blocksize : self . _handle_touchz ( path , node , replication , blocksize ) for item in self . _find_items ( paths , processor , include_toplevel = True , check_nonexistence = True , include_children = False ) : if item : yield item
|
Create a zero length file or updates the timestamp on a zero length file
|
10,155
|
def setrep ( self , paths , replication , recurse = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "setrep: no path given" ) if not replication : raise InvalidInputException ( "setrep: no replication given" ) processor = lambda path , node , replication = replication : self . _handle_setrep ( path , node , replication ) for item in self . _find_items ( paths , processor , include_toplevel = True , include_children = False , recurse = recurse ) : if item : yield item
|
Set the replication factor for paths
|
10,156
|
def cat ( self , paths , check_crc = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "cat: no path given" ) processor = lambda path , node , check_crc = check_crc : self . _handle_cat ( path , node , check_crc ) for item in self . _find_items ( paths , processor , include_toplevel = True , include_children = False , recurse = False ) : if item : yield item
|
Fetch all files that match the source file pattern and display their content on stdout .
|
10,157
|
def copyToLocal ( self , paths , dst , check_crc = False ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "copyToLocal: no path given" ) if not dst : raise InvalidInputException ( "copyToLocal: no destination given" ) dst = self . _normalize_path ( dst ) processor = lambda path , node , dst = dst , check_crc = check_crc : self . _handle_copyToLocal ( path , node , dst , check_crc ) for path in paths : self . base_source = None for item in self . _find_items ( [ path ] , processor , include_toplevel = True , recurse = True , include_children = True ) : if item : yield item
|
Copy files that match the file source pattern to the local name . Source is kept . When copying multiple files the destination must be a directory .
|
10,158
|
def getmerge ( self , path , dst , newline = False , check_crc = False ) : if not path : raise InvalidInputException ( "getmerge: no path given" ) if not dst : raise InvalidInputException ( "getmerge: no destination given" ) temporary_target = "%s._COPYING_" % dst f = open ( temporary_target , 'w' ) processor = lambda path , node , dst = dst , check_crc = check_crc : self . _handle_getmerge ( path , node , dst , check_crc ) try : for item in self . _find_items ( [ path ] , processor , include_toplevel = True , recurse = False , include_children = True ) : for load in item : if load [ 'result' ] : f . write ( load [ 'response' ] ) elif not load [ 'error' ] is '' : if os . path . isfile ( temporary_target ) : os . remove ( temporary_target ) raise FatalException ( load [ 'error' ] ) if newline and load [ 'response' ] : f . write ( "\n" ) yield { "path" : dst , "response" : '' , "result" : True , "error" : load [ 'error' ] , "source_path" : path } finally : if os . path . isfile ( temporary_target ) : f . close ( ) os . rename ( temporary_target , dst )
|
Get all the files in the directories that match the source file pattern and merge and sort them to only one file on local fs .
|
10,159
|
def stat ( self , paths ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "stat: no path given" ) processor = lambda path , node : self . _handle_stat ( path , node ) return list ( self . _find_items ( paths , processor , include_toplevel = True ) ) [ 0 ]
|
Stat a fileCount
|
10,160
|
def tail ( self , path , tail_length = 1024 , append = False ) : if not path : raise InvalidInputException ( "tail: no path given" ) block_size = self . serverdefaults ( ) [ 'blockSize' ] if tail_length > block_size : raise InvalidInputException ( "tail: currently supports length up to the block size (%d)" % ( block_size , ) ) if tail_length <= 0 : raise InvalidInputException ( "tail: tail_length cannot be less than or equal to zero" ) processor = lambda path , node : self . _handle_tail ( path , node , tail_length , append ) for item in self . _find_items ( [ path ] , processor , include_toplevel = True , include_children = False , recurse = False ) : if item : yield item
|
Show the end of the file - default 1KB supports up to the Hadoop block size .
|
10,161
|
def mkdir ( self , paths , create_parent = False , mode = 0o755 ) : if not isinstance ( paths , list ) : raise InvalidInputException ( "Paths should be a list" ) if not paths : raise InvalidInputException ( "mkdirs: no path given" ) for path in paths : if not path . startswith ( "/" ) : path = self . _join_user_path ( path ) fileinfo = self . _get_file_info ( path ) if not fileinfo : try : request = client_proto . MkdirsRequestProto ( ) request . src = path request . masked . perm = mode request . createParent = create_parent response = self . service . mkdirs ( request ) yield { "path" : path , "result" : response . result } except RequestError as e : yield { "path" : path , "result" : False , "error" : str ( e ) } else : yield { "path" : path , "result" : False , "error" : "mkdir: `%s': File exists" % path }
|
Create a directoryCount
|
10,162
|
def serverdefaults ( self , force_reload = False ) : if not self . _server_defaults or force_reload : request = client_proto . GetServerDefaultsRequestProto ( ) response = self . service . getServerDefaults ( request ) . serverDefaults self . _server_defaults = { 'blockSize' : response . blockSize , 'bytesPerChecksum' : response . bytesPerChecksum , 'writePacketSize' : response . writePacketSize , 'replication' : response . replication , 'fileBufferSize' : response . fileBufferSize , 'encryptDataTransfer' : response . encryptDataTransfer , 'trashInterval' : response . trashInterval , 'checksumType' : response . checksumType } return self . _server_defaults . copy ( )
|
Get server defaults caching the results . If there are no results saved or the force_reload flag is True it will query the HDFS server for its default parameter values . Otherwise it will simply return the results it has already queried .
|
10,163
|
def _glob_find ( self , path , processor , include_toplevel ) : path_elements = path . split ( "/" ) for i , element in enumerate ( path_elements ) : if glob . has_magic ( element ) : first_magic = i break if first_magic == 1 : check_path = "/" else : check_path = "/" . join ( path_elements [ : first_magic ] ) match_path = "/" . join ( path_elements [ : first_magic + 1 ] ) rest_elements = path_elements [ first_magic + 1 : ] if len ( rest_elements ) == 1 : rest = rest_elements [ 0 ] else : rest = "/" . join ( rest_elements ) fileinfo = self . _get_file_info ( check_path ) if fileinfo and self . _is_dir ( fileinfo . fs ) : for node in self . _get_dir_listing ( check_path ) : full_path = self . _get_full_path ( check_path , node ) if fnmatch . fnmatch ( full_path , match_path ) : if rest and glob . has_magic ( rest ) : traverse_path = "/" . join ( [ full_path , rest ] ) for item in self . _glob_find ( traverse_path , processor , include_toplevel ) : yield item elif rest : final_path = posixpath . join ( full_path , rest ) fi = self . _get_file_info ( final_path ) if fi and self . _is_dir ( fi . fs ) : for n in self . _get_dir_listing ( final_path ) : full_child_path = self . _get_full_path ( final_path , n ) yield processor ( full_child_path , n ) elif fi : yield processor ( final_path , fi . fs ) else : if self . _is_dir ( node ) : if include_toplevel : yield processor ( full_path , node ) fp = self . _get_full_path ( check_path , node ) dir_list = self . _get_dir_listing ( fp ) if dir_list : for n in dir_list : full_child_path = self . _get_full_path ( fp , n ) yield processor ( full_child_path , n ) else : yield processor ( full_path , node )
|
Handle globs in paths . This is done by listing the directory before a glob and checking which node matches the initial glob . If there are more globs in the path we don t add the found children to the result but traverse into paths that did have a match .
|
10,164
|
def _ha_return_method ( func ) : def wrapped ( self , * args , ** kw ) : self . _reset_retries ( ) while ( True ) : try : return func ( self , * args , ** kw ) except RequestError as e : self . __handle_request_error ( e ) except socket . error as e : self . __handle_socket_error ( e ) return wrapped
|
Method decorator for return type methods
|
10,165
|
def _ha_gen_method ( func ) : def wrapped ( self , * args , ** kw ) : self . _reset_retries ( ) while ( True ) : try : results = func ( self , * args , ** kw ) while ( True ) : yield results . next ( ) except RequestError as e : self . __handle_request_error ( e ) except socket . error as e : self . __handle_socket_error ( e ) return wrapped
|
Method decorator for generator type methods
|
10,166
|
def _validate_number_sequence ( self , seq , n ) : if seq is None : return np . zeros ( n ) if len ( seq ) is n : try : l = [ float ( e ) for e in seq ] except ValueError : raise ValueError ( "One or more elements in sequence <" + repr ( seq ) + "> cannot be interpreted as a real number" ) else : return np . asarray ( l ) elif len ( seq ) is 0 : return np . zeros ( n ) else : raise ValueError ( "Unexpected number of elements in sequence. Got: " + str ( len ( seq ) ) + ", Expected: " + str ( n ) + "." )
|
Validate a sequence to be of a certain length and ensure it s a numpy array of floats .
|
10,167
|
def _from_axis_angle ( cls , axis , angle ) : mag_sq = np . dot ( axis , axis ) if mag_sq == 0.0 : raise ZeroDivisionError ( "Provided rotation axis has no length" ) if ( abs ( 1.0 - mag_sq ) > 1e-12 ) : axis = axis / sqrt ( mag_sq ) theta = angle / 2.0 r = cos ( theta ) i = axis * sin ( theta ) return cls ( r , i [ 0 ] , i [ 1 ] , i [ 2 ] )
|
Initialise from axis and angle representation
|
10,168
|
def random ( cls ) : r1 , r2 , r3 = np . random . random ( 3 ) q1 = sqrt ( 1.0 - r1 ) * ( sin ( 2 * pi * r2 ) ) q2 = sqrt ( 1.0 - r1 ) * ( cos ( 2 * pi * r2 ) ) q3 = sqrt ( r1 ) * ( sin ( 2 * pi * r3 ) ) q4 = sqrt ( r1 ) * ( cos ( 2 * pi * r3 ) ) return cls ( q1 , q2 , q3 , q4 )
|
Generate a random unit quaternion .
|
10,169
|
def conjugate ( self ) : return self . __class__ ( scalar = self . scalar , vector = - self . vector )
|
Quaternion conjugate encapsulated in a new instance .
|
10,170
|
def inverse ( self ) : ss = self . _sum_of_squares ( ) if ss > 0 : return self . __class__ ( array = ( self . _vector_conjugate ( ) / ss ) ) else : raise ZeroDivisionError ( "a zero quaternion (0 + 0i + 0j + 0k) cannot be inverted" )
|
Inverse of the quaternion object encapsulated in a new instance .
|
10,171
|
def _fast_normalise ( self ) : if not self . is_unit ( ) : mag_squared = np . dot ( self . q , self . q ) if ( mag_squared == 0 ) : return if ( abs ( 1.0 - mag_squared ) < 2.107342e-08 ) : mag = ( ( 1.0 + mag_squared ) / 2.0 ) else : mag = sqrt ( mag_squared ) self . q = self . q / mag
|
Normalise the object to a unit quaternion using a fast approximation method if appropriate .
|
10,172
|
def rotate ( self , vector ) : if isinstance ( vector , Quaternion ) : return self . _rotate_quaternion ( vector ) q = Quaternion ( vector = vector ) a = self . _rotate_quaternion ( q ) . vector if isinstance ( vector , list ) : l = [ x for x in a ] return l elif isinstance ( vector , tuple ) : l = [ x for x in a ] return tuple ( l ) else : return a
|
Rotate a 3D vector by the rotation stored in the Quaternion object .
|
10,173
|
def exp ( cls , q ) : tolerance = 1e-17 v_norm = np . linalg . norm ( q . vector ) vec = q . vector if v_norm > tolerance : vec = vec / v_norm magnitude = exp ( q . scalar ) return Quaternion ( scalar = magnitude * cos ( v_norm ) , vector = magnitude * sin ( v_norm ) * vec )
|
Quaternion Exponential .
|
10,174
|
def log ( cls , q ) : v_norm = np . linalg . norm ( q . vector ) q_norm = q . norm tolerance = 1e-17 if q_norm < tolerance : return Quaternion ( scalar = - float ( 'inf' ) , vector = float ( 'nan' ) * q . vector ) if v_norm < tolerance : return Quaternion ( scalar = log ( q_norm ) , vector = [ 0 , 0 , 0 ] ) vec = q . vector / v_norm return Quaternion ( scalar = log ( q_norm ) , vector = acos ( q . scalar / q_norm ) * vec )
|
Quaternion Logarithm .
|
10,175
|
def sym_exp_map ( cls , q , eta ) : sqrt_q = q ** 0.5 return sqrt_q * Quaternion . exp ( eta ) * sqrt_q
|
Quaternion symmetrized exponential map .
|
10,176
|
def sym_log_map ( cls , q , p ) : inv_sqrt_q = ( q ** ( - 0.5 ) ) return Quaternion . log ( inv_sqrt_q * p * inv_sqrt_q )
|
Quaternion symmetrized logarithm map .
|
10,177
|
def absolute_distance ( cls , q0 , q1 ) : q0_minus_q1 = q0 - q1 q0_plus_q1 = q0 + q1 d_minus = q0_minus_q1 . norm d_plus = q0_plus_q1 . norm if ( d_minus < d_plus ) : return d_minus else : return d_plus
|
Quaternion absolute distance .
|
10,178
|
def distance ( cls , q0 , q1 ) : q = Quaternion . log_map ( q0 , q1 ) return q . norm
|
Quaternion intrinsic distance .
|
10,179
|
def sym_distance ( cls , q0 , q1 ) : q = Quaternion . sym_log_map ( q0 , q1 ) return q . norm
|
Quaternion symmetrized distance .
|
10,180
|
def intermediates ( cls , q0 , q1 , n , include_endpoints = False ) : step_size = 1.0 / ( n + 1 ) if include_endpoints : steps = [ i * step_size for i in range ( 0 , n + 2 ) ] else : steps = [ i * step_size for i in range ( 1 , n + 1 ) ] for step in steps : yield cls . slerp ( q0 , q1 , step )
|
Generator method to get an iterable sequence of n evenly spaced quaternion rotations between any two existing quaternion endpoints lying on the unit radius hypersphere .
|
10,181
|
def derivative ( self , rate ) : rate = self . _validate_number_sequence ( rate , 3 ) return 0.5 * self * Quaternion ( vector = rate )
|
Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector rate
|
10,182
|
def integrate ( self , rate , timestep ) : self . _fast_normalise ( ) rate = self . _validate_number_sequence ( rate , 3 ) rotation_vector = rate * timestep rotation_norm = np . linalg . norm ( rotation_vector ) if rotation_norm > 0 : axis = rotation_vector / rotation_norm angle = rotation_norm q2 = Quaternion ( axis = axis , angle = angle ) self . q = ( self * q2 ) . q self . _fast_normalise ( )
|
Advance a time varying quaternion to its value at a time timestep in the future .
|
10,183
|
def rotation_matrix ( self ) : self . _normalise ( ) product_matrix = np . dot ( self . _q_matrix ( ) , self . _q_bar_matrix ( ) . conj ( ) . transpose ( ) ) return product_matrix [ 1 : ] [ : , 1 : ]
|
Get the 3x3 rotation matrix equivalent of the quaternion rotation .
|
10,184
|
def transformation_matrix ( self ) : t = np . array ( [ [ 0.0 ] , [ 0.0 ] , [ 0.0 ] ] ) Rt = np . hstack ( [ self . rotation_matrix , t ] ) return np . vstack ( [ Rt , np . array ( [ 0.0 , 0.0 , 0.0 , 1.0 ] ) ] )
|
Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation .
|
10,185
|
def yaw_pitch_roll ( self ) : self . _normalise ( ) yaw = np . arctan2 ( 2 * ( self . q [ 0 ] * self . q [ 3 ] - self . q [ 1 ] * self . q [ 2 ] ) , 1 - 2 * ( self . q [ 2 ] ** 2 + self . q [ 3 ] ** 2 ) ) pitch = np . arcsin ( 2 * ( self . q [ 0 ] * self . q [ 2 ] + self . q [ 3 ] * self . q [ 1 ] ) ) roll = np . arctan2 ( 2 * ( self . q [ 0 ] * self . q [ 1 ] - self . q [ 2 ] * self . q [ 3 ] ) , 1 - 2 * ( self . q [ 1 ] ** 2 + self . q [ 2 ] ** 2 ) ) return yaw , pitch , roll
|
Get the equivalent yaw - pitch - roll angles aka . intrinsic Tait - Bryan angles following the z - y - x convention
|
10,186
|
def get_axis ( self , undefined = np . zeros ( 3 ) ) : tolerance = 1e-17 self . _normalise ( ) norm = np . linalg . norm ( self . vector ) if norm < tolerance : return undefined else : return self . vector / norm
|
Get the axis or vector about which the quaternion rotation occurs
|
10,187
|
def req_string ( self , model ) : if model not in self . models : model = self . models if self . min_ykver and self . max_ykver : return "%s %d.%d..%d.%d" % ( model , self . min_ykver [ 0 ] , self . min_ykver [ 1 ] , self . max_ykver [ 0 ] , self . max_ykver [ 1 ] , ) if self . max_ykver : return "%s <= %d.%d" % ( model , self . max_ykver [ 0 ] , self . max_ykver [ 1 ] ) return "%s >= %d.%d" % ( model , self . min_ykver [ 0 ] , self . min_ykver [ 1 ] )
|
Return string describing model and version requirement .
|
10,188
|
def is_compatible ( self , model , version ) : if not model in self . models : return False if self . max_ykver : return ( version >= self . min_ykver and version <= self . max_ykver ) else : return version >= self . min_ykver
|
Check if this flag is compatible with a YubiKey of version ver .
|
10,189
|
def get_set ( self , flag , new ) : old = self . _is_set ( flag ) if new is True : self . _set ( flag ) elif new is False : self . _clear ( flag ) return old
|
Return the boolean value of flag . If new is set the flag is updated and the value before update is returned .
|
10,190
|
def _read_capabilities ( self ) : frame = yubikey_frame . YubiKeyFrame ( command = SLOT . YK4_CAPABILITIES ) self . _device . _write ( frame ) response = self . _device . _read_response ( ) r_len = yubico_util . ord_byte ( response [ 0 ] ) if not yubico_util . validate_crc16 ( response [ : r_len + 3 ] ) : raise YubiKey4_USBHIDError ( "Read from device failed CRC check" ) return response [ 1 : r_len + 1 ]
|
Read the capabilities list from a YubiKey > = 4 . 0 . 0
|
10,191
|
def status ( self ) : data = self . _read ( ) self . _status = YubiKeyUSBHIDStatus ( data ) return self . _status
|
Poll YubiKey for status .
|
10,192
|
def _write_config ( self , cfg , slot ) : old_pgm_seq = self . _status . pgm_seq frame = cfg . to_frame ( slot = slot ) self . _debug ( "Writing %s frame :\n%s\n" % ( yubikey_config . command2str ( frame . command ) , cfg ) ) self . _write ( frame ) self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) self . status ( ) self . _debug ( "Programmed slot %i, sequence %i -> %i\n" % ( slot , old_pgm_seq , self . _status . pgm_seq ) ) cfgs = self . _status . valid_configs ( ) if not cfgs and self . _status . pgm_seq == 0 : return if self . _status . pgm_seq == old_pgm_seq + 1 : return raise YubiKeyUSBHIDError ( 'YubiKey programming failed (seq %i not increased (%i))' % ( old_pgm_seq , self . _status . pgm_seq ) )
|
Write configuration to YubiKey .
|
10,193
|
def _read_response ( self , may_block = False ) : res = self . _waitfor_set ( yubikey_defs . RESP_PENDING_FLAG , may_block ) [ : 7 ] while True : this = self . _read ( ) flags = yubico_util . ord_byte ( this [ 7 ] ) if flags & yubikey_defs . RESP_PENDING_FLAG : seq = flags & 0b00011111 if res and ( seq == 0 ) : break res += this [ : 7 ] else : break self . _write_reset ( ) return res
|
Wait for a response to become available and read it .
|
10,194
|
def _read ( self ) : request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN value = _REPORT_TYPE_FEATURE << 8 recv = self . _usb_handle . controlMsg ( request_type , _HID_GET_REPORT , _FEATURE_RPT_SIZE , value = value , timeout = _USB_TIMEOUT_MS ) if len ( recv ) != _FEATURE_RPT_SIZE : self . _debug ( "Failed reading %i bytes (got %i) from USB HID YubiKey.\n" % ( _FEATURE_RPT_SIZE , recv ) ) raise YubiKeyUSBHIDError ( 'Failed reading from USB HID YubiKey' ) data = b'' . join ( yubico_util . chr_byte ( c ) for c in recv ) self . _debug ( "READ : %s" % ( yubico_util . hexdump ( data , colorize = True ) ) ) return data
|
Read a USB HID feature report from the YubiKey .
|
10,195
|
def _write ( self , frame ) : for data in frame . to_feature_reports ( debug = self . debug ) : debug_str = None if self . debug : ( data , debug_str ) = data self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) self . _raw_write ( data , debug_str ) return True
|
Write a YubiKeyFrame to the USB HID .
|
10,196
|
def _write_reset ( self ) : data = b'\x00\x00\x00\x00\x00\x00\x00\x8f' self . _raw_write ( data ) self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) return True
|
Reset read mode by issuing a dummy write .
|
10,197
|
def _raw_write ( self , data , debug_str = None ) : if self . debug : if not debug_str : debug_str = '' hexdump = yubico_util . hexdump ( data , colorize = True ) [ : - 1 ] self . _debug ( "WRITE : %s %s\n" % ( hexdump , debug_str ) ) request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_OUT value = _REPORT_TYPE_FEATURE << 8 sent = self . _usb_handle . controlMsg ( request_type , _HID_SET_REPORT , data , value = value , timeout = _USB_TIMEOUT_MS ) if sent != _FEATURE_RPT_SIZE : self . debug ( "Failed writing %i bytes (wrote %i) to USB HID YubiKey.\n" % ( _FEATURE_RPT_SIZE , sent ) ) raise YubiKeyUSBHIDError ( 'Failed talking to USB HID YubiKey' ) return sent
|
Write data to YubiKey .
|
10,198
|
def _waitfor ( self , mode , mask , may_block , timeout = 2 ) : finished = False sleep = 0.01 wait_num = ( timeout * 2 ) - 1 + 6 resp_timeout = False while not finished : time . sleep ( sleep ) this = self . _read ( ) flags = yubico_util . ord_byte ( this [ 7 ] ) if flags & yubikey_defs . RESP_TIMEOUT_WAIT_FLAG : if not resp_timeout : resp_timeout = True seconds_left = flags & yubikey_defs . RESP_TIMEOUT_WAIT_MASK self . _debug ( "Device indicates RESP_TIMEOUT (%i seconds left)\n" % ( seconds_left ) ) if may_block : seconds_left = min ( 20 , seconds_left ) wait_num = ( seconds_left * 2 ) - 1 + 6 if mode is 'nand' : if not flags & mask == mask : finished = True else : self . _debug ( "Status %s (0x%x) has not cleared bits %s (0x%x)\n" % ( bin ( flags ) , flags , bin ( mask ) , mask ) ) elif mode is 'and' : if flags & mask == mask : finished = True else : self . _debug ( "Status %s (0x%x) has not set bits %s (0x%x)\n" % ( bin ( flags ) , flags , bin ( mask ) , mask ) ) else : assert ( ) if not finished : wait_num -= 1 if wait_num == 0 : if mode is 'nand' : reason = 'Timed out waiting for YubiKey to clear status 0x%x' % mask else : reason = 'Timed out waiting for YubiKey to set status 0x%x' % mask raise yubikey_base . YubiKeyTimeout ( reason ) sleep = min ( sleep + sleep , 0.5 ) else : return this
|
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte .
|
10,199
|
def _open ( self , skip = 0 ) : usb_device = self . _get_usb_device ( skip ) if usb_device : usb_conf = usb_device . configurations [ 0 ] self . _usb_int = usb_conf . interfaces [ 0 ] [ 0 ] else : raise YubiKeyUSBHIDError ( 'No USB YubiKey found' ) try : self . _usb_handle = usb_device . open ( ) self . _usb_handle . detachKernelDriver ( 0 ) except Exception as error : if 'could not detach kernel driver from interface' in str ( error ) : self . _debug ( 'The in-kernel-HID driver has already been detached\n' ) else : self . _debug ( "detachKernelDriver not supported!\n" ) try : self . _usb_handle . setConfiguration ( 1 ) except usb . USBError : self . _debug ( "Unable to set configuration, ignoring...\n" ) self . _usb_handle . claimInterface ( self . _usb_int ) return True
|
Perform HID initialization
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.