Example #1
0
def fusSensors2(Sensors):
    R_Sensors = np.array([Sensors[0].createR(),Sensors[1].createR(),Sensors[2].createR(),Sensors[3].createR(),Sensors[4].createR()])
    

    def createRfromSensors(R_Sensors):
        R2 = R_Sensors.copy()
        R2 = [la.inv(matrix) for matrix in R2]
        R2 = sum(R2)
        R2 = la.inv(R2)
        return R2
    
    
    R= createRfromSensors(R_Sensors)
    newSensorWithR = Sensor(movingObject)
    newSensorWithR.R = R
    newFilter = Filter(newSensorWithR)
    
    newTrajectory = np.zeros(Trajectory.T.shape)
    for i in range(m):
        for j in range(5):
            newTrajectory[i] += la.inv(R_Sensors[j]) @ Z_Sensors[j].T[i]
        newTrajectory[i] = R @ newTrajectory[i]
    newTrajectory = newTrajectory.T
    
    X_2ndStrategy = np.zeros((6,1))
    allX_2ndStrategy= np.zeros((m,6,1)) # save Xs
    P_2ndStrategy = sensor.createPo(10)
    for i in range(m):
        centerPredicted, pPredicted = newFilter.Predict(X_2ndStrategy,P_2ndStrategy)
        X_2ndStrategy,P_2ndStrategy = newFilter.Filter(centerPredicted,pPredicted,(newTrajectory.T)[i])
        allX_2ndStrategy[i]=X_2ndStrategy
    rx_2ndStrategy_f = list(allX[:,0,:1].T.flat)
    ry_2ndStrategy_f = list(allX[:,1,:2].T.flat)
    plt.scatter(rx_2ndStrategy_f,ry_2ndStrategy_f) # print filtered predictions
    def parseStatement(self, statement, lineNumber, indentation):
        '''
		Parses statement lines. eg if matcher -> action. Also tracks indentation to create
		nested statements.
		'''
        # filter out the 'if; from the start
        tmp = statement[3:].split('->')
        if len(tmp) != 2:
            return handleParseError(lineNumber, statement, "Missing '->'.")

        condition = tmp[0].lstrip().rstrip()
        result = tmp[1].lstrip().rstrip()

        if not condition:
            return handleParseError(lineNumber, statement,
                                    "Missing Matcher before ->.")
        if condition in self.matchers:
            condition = self.matchers[condition]
        elif condition[0] == '{' and condition[-1] == '}':
            condition = Matcher(condition, statement, lineNumber)
        else:
            return handleParseError(
                lineNumber, statement,
                "Unknown Matcher or missing {} before ->.")

        # need to handle there not being a specified result
        if not result:
            filter = Filter(condition)
        else:
            if result in self.actions:
                result = self.actions[result]
            elif result[0] == '[' and result[-1] == ']':
                result = Action(result, statement, lineNumber)
            else:
                return handleParseError(
                    lineNumber, statement,
                    "Unknown Action or missing [] after ->.")
            filter = Filter(condition, result)

        if indentation == 0:
            self.filters.append(filter)
            return

        if not self.filters:
            return handleParseError(
                lineNumber, statement,
                "Invalid indentation, this line has no parent")

        parentFilter = self.filters[-1]
        indentation -= 1

        while (indentation > 0):
            if not parentFilter.childStatements:
                handleParseError(
                    lineNumber, statement,
                    "Invalid indentation, this line has no parent")
            parentFilter = parentFilter.childStatements[-1]
            indentation -= 1
        parentFilter.addChild(filter)
Example #3
0
    def update_anchor(self,
                      name: str,
                      distance: float,
                      robot_id,
                      options=None):
        """Updates distance between anchor and robot.
           Note that anchors names should be unique for this to work"""
        for anchor in self.anchors:
            if anchor.name == name:

                anchor.update_rangings(distance, robot_id)
                anchor.set_raw_distance(distance, robot_id)

                if (options == "SW"):
                    # sliding window enabled

                    sliding_windows = Filter(
                        "SW", [anchor.rangings[robot_id], 20, 12, 0])
                    filtered_distance = sliding_windows.apply()[
                        0]  # output(s) of filters are returned as a list

                    anchor.set_distance(filtered_distance, robot_id)
                else:
                    anchor.set_distance(distance, robot_id)

                # activates the anchor the first time it uploads a distance
                if (not (anchor.isActive) and distance > 0.0):

                    anchor.isActive = True
                return
Example #4
0
 def __init__(self, camera_matrix, dist_coefs, object_path, model_scale = 0.03):
     
     """[Initialize]
     
     Arguments:
         camera_matrix {[np.array]} -- [your camera intrinsic matrix]
         dist_coefs {[np.array]} -- [your camera difference parameters]
         object_path {[string]} -- [your model path]
         model_scale {[float]} -- [your model scale size]
     """
     # Initialise webcam and start thread
     # self.webcam = cv2.VideoCapture(0)
     self.webcam = cv2.VideoCapture(0)
     self.image_w, self.image_h = map(int, (self.webcam.get(3), self.webcam.get(4)))
     self.initOpengl(self.image_w, self.image_h)
     self.model_scale = model_scale
 
     self.cam_matrix,self.dist_coefs = camera_matrix, dist_coefs
     self.projectMatrix = intrinsic2Project(camera_matrix, self.image_w, self.image_h, 0.01, 100.0)
     self.loadModel(object_path)
     
     # Model translate that you can adjust by key board 'w', 's', 'a', 'd'
     self.translate_x, self.translate_y, self.translate_z = 0, 0, 0
     self.pre_extrinsicMatrix = None
     
     self.filter = Filter()
Example #5
0
 def getFilters(self,filterType):
     jsonRes = self.updateUi()
     jdata = json.loads(jsonRes)
     filterList = []
     for strFilter in jdata['result']['filters'][filterType]:
         filterList.append(Filter(strFilter[0], int(strFilter[1])))
     return filterList
Example #6
0
    def __init__(self, config=None):
        super().__init__()

        self.data = config

        self.frame_num = 0
        #self.debug_frame = config['debug_frame']
        self.image = None

        # Camera calibration
        calibration = Calibrate()

        # Load calibration data
        calibration.load()

        pt1 = PerspectiveTransform()
        pt2 = PerspectiveTransform(pt1)
        sw = SlidingWindow()
        tls = TargettedLineSearch()
        lane = Lane()
        b_gradient = Filter()

        self.steps = [calibration, b_gradient, pt1, sw, tls, lane, pt2]

        self.debug = config['debug']

        print('Pipeline object created ...')
Example #7
0
def display_filter(filter, page=0):
    if int(filter) == 99999:  # we are displaying an search query
        filter = Filter(Settings.QUEUE['filter'])
        del Settings.QUEUE['filter']
    else:
        filter = Settings.FILTER_DB.get_filter(int(filter))
    posts = Settings.POST_DB.get_posts_by_filter(filter,
                                                 page * Settings.POST_PER_PAGE,
                                                 Settings.POST_PER_PAGE)
    oc = ObjectContainer(no_cache=True)
    for post in posts:
        oc.add(
            DirectoryObject(key=Callback(display_post,
                                         messageid=post.messageid),
                            title=post.title,
                            tagline="date %s" % post.posted,
                            summary=post.description_markup,
                            thumb=post.image))
    oc.add(
        NextPageObject(key=Callback(display_filter,
                                    filter=filter.id,
                                    page=page + 1),
                       summary='Display the next %d posts' %
                       Settings.POST_PER_PAGE))
    return oc
Example #8
0
 def set_second_semester_filter(self, start: int, end: int,
                                days_excluded: list, lunch_time_start: int,
                                lunch_time_end: int,
                                maximum_lectures_per_day: int,
                                maximum_tutorials_practicals_per_day: int):
     self._second_semester_filter = Filter(
         start, end, days_excluded, lunch_time_start, lunch_time_end,
         maximum_lectures_per_day, maximum_tutorials_practicals_per_day)
Example #9
0
 def get_filters(self, cat):
     data = []
     self.db.open()
     filters = self.db.select(None, category_code=cat)
     self.db.close()
     for filter in filters:
         data.append(Filter(filter))
     return data
Example #10
0
 def on_formBtn_clicked(self):
     # open a search box
     self.sb = QtWidgets.QDialog()
     Filter(self.sb, mode='out')
     returnID = self.sb.exec_()
     if returnID == 0:
         return
     self.unregisterIdIndex = -1
     self.update_field_by_id(returnID)
Example #11
0
 def getFilters(self, filterType):
     jsonRes = self.updateUi()
     jdata = json.loads(jsonRes)
     filterList = []
     if jdata.get('error') is not None:
         raise ValueError(jdata)
     if filterType in jdata['result']['filters']:
         for strFilter in jdata['result']['filters'][filterType]:
             filterList.append(Filter(strFilter[0], int(strFilter[1])))
     return filterList
Example #12
0
 def test_list(self):
     event = Event(0)
     event.the_list = range(10)
     cfg_ana = cfg.Analyzer(Filter,
                            output='filtered',
                            input_objects='the_list',
                            filter_func=lambda x: x % 2 == 0)
     cfg_comp = cfg.Component('test', files=[])
     filter = Filter(cfg_ana, cfg_comp, self.outdir)
     filter.process(event)
     self.assertItemsEqual(event.filtered, [0, 2, 4, 6, 8])
Example #13
0
 def test_dict(self):
     event = Event(0)
     event.the_dict = dict([(x, x**2) for x in range(10)])
     cfg_ana = cfg.Analyzer(Filter,
                            output='filtered',
                            input_objects='the_dict',
                            filter_func=lambda x: x == 9)
     cfg_comp = cfg.Component('test', files=[])
     filter = Filter(cfg_ana, cfg_comp, self.outdir)
     filter.process(event)
     self.assertDictEqual(event.filtered, {3: 9})
Example #14
0
	def __init__(self, paths, completion=None):
		if isinstance(paths, str):
			paths = [paths]
		pool = Pool()
		self.filters = pool.map(lambda x: Filter(x), paths)
		self.shape = self.filters[0].shape
		for f in self.filters:
			if f.shape != self.shape:
				print "The shapes of images are not the same"
		if completion:
			completion()
Example #15
0
    def evaluarFitness(self, solucion):

        #Desde el inicio generé la señal S1
        #Filtro la señal S1 con los coeficientes de la solución que quiero evaluar
        #Inicializo el filtro 1
        filtro1 = Filter(solucion)
        #Obtengo la señal de salida del filtro 1
        T1 = filtro1.filter(self.S1)

        #Desde el principio generé la señal S2
        #Filtro la señal S2 con los coeficientes de la solución que quiero evaluar
        #Inicializo el filtro 2
        filtro2 = Filter(solucion)
        #Obtengo la señal de salida del filtro 2
        T2 = filtro2.filter(self.S2)

        #Calcular la potencia media de T1
        arreglo_absolutos1 = np.absolute(T1.y)
        arreglo_cuadrados1 = list(
            map(lambda elemento: cuadrado(elemento), arreglo_absolutos1))
        sumatoria1 = sumatoria(arreglo_cuadrados1)
        P1 = (float(1) / float(2 * len(T1.y) - 1)) * float(sumatoria1)
        #print('sumatoria1:', sumatoria1)
        #print('P1: ', P1)

        #Calcular la potencia media de T2
        arreglo_absolutos2 = np.absolute(T2.y)
        arreglo_cuadrados2 = list(
            map(lambda elemento: cuadrado(elemento), arreglo_absolutos2))
        sumatoria2 = sumatoria(arreglo_cuadrados2)
        P2 = (float(1) / float(2 * len(T2.y) - 1)) * float(sumatoria2)
        #print('sumatoria2:', sumatoria2)
        #print('P2: ', P2)

        if self.tfiltro == "pb":  #Si el filtro es pasa bajos
            fitness = P1 - P2
            return fitness

        #De lo contrario el filtro es pasa altos
        fitness = P2 - P1
        return fitness
Example #16
0
    def InitMPU6050(self):

        # Accelerometer Values and Device
        self._mpuIdx = ['x', 'y', 'z']
        self._a = [0.0, 0.0, 0.0]  # Acceleration (g's)
        self._w = [0.0, 0.0, 0.0]  # Angular rate (deg/s)
        self._wFilt = [0.0, 0.0, 0.0]  # Filtered Angular rate (deg/s)
        self._theta = [0.0, 0.0, 0.0]  # Angle (deg)
        self._thetaFilt = [0.0, 0.0, 0.0]  # Filtered Angle (deg)
        self._a_off = [0.66, -0.26, 10.22 - 9.81]
        self._w_off = [-1.07, 0.67, -1.55]
        #self._a_off = [0.0, 0.0, 0.0]
        #self._w_off = [0.0, 0.0, 0.0]
        self._thetaXFilt = ComplementaryFilter(alpha=0.05)  # alpha = 0.02
        self._thetaXFilt2 = Filter(timeConst=0.0)
        self._wXFilt = Filter(timeConst=0.0)
        self._mpu6050 = mpu6050(0x68)  # 0x68 - default I2C slave addr
        self._mpu6050.set_accel_range(mpu6050.ACCEL_RANGE_2G)
        self._mpu6050.set_gyro_range(mpu6050.GYRO_RANGE_250DEG)

        return
Example #17
0
    def getEdgeSpec(self):
        ret = ''
        if self._parent:
            ret = '"%s" -> "%s" [ arrowhead = "none", arrowtail = "normal", dir = "both"];' % (
                self._parent, self._id)

        if self._nodeType == 'qdisc' and 'default' in self._params:
            dcls_minor = self._params[self._params.index('default') +
                                      1].lstrip('0x')
            ret += '\n' + Filter('  {0}: default classid {0}:{1}'.format(
                self._id._major, dcls_minor)).getEdgeSpec()
        return ret
Example #18
0
    def set(self, type_, freq, Ts, other=None, start_entry=0):
        self._sample_period = Ts
        self._frequency = freq
        self._phase_filt = Filter("a", "1 - (1-a)*z^-1", "a", 0.5 * freq * Ts)

        if start_entry and start_entry < 0:
            err_msg = "error in SigGen.set:  starting entry for List input must be >= 0\n"
            err_msg += "   (note that a value of 1 corresponds to the first entry)\n"
            err_msg += "   in this case, start_entry = %d\n" % start_entry
            raise Exception(err_msg)

        if self._sample_period < 1e-30:
            err_msg = "error in SigGen.set:  Ts < 1e-30\n"
            err_msg += "   in this case, Ts = %5.3e\n" % Ts
            raise Exception(err_msg)

        if freq < 0.0:
            err_msg = "error in SigGen.set:  freq <= 0.0\n"
            err_msg += "   in this case, freq = %5.3e\n" % freq
            raise Exception(err_msg)

        if type_ == "square":
            self._type_flag = 0
        elif type_ == "sine":
            self._type_flag = 1
        elif type_ == "prbs":
            self._type_flag = 2
        elif type_ == "impulse":
            self._type_flag = 3
        else:
            err_msg = "error in SigGen.set:  type must be either\n"
            err_msg += "  'square', 'sine', 'prbs', or 'impulse'\n"
            err_msg += "  in this case, type = '%s'\n" % type_
            raise Exception(err_msg)

        if other:
            self._end_data_flag = 0
            self._prev_data = 1.0
            self._data_seq = cir_list(other, start_entry)
            self._data = 1.0 if self._data_seq.read() > 0.0 else -1.0

            if self._data != -1.0 and self._data != 1.0:
                print "error in SigGen.set:  data list has values that are not 1.0 or -1.0"
                print "  in this case, the data value is %5.3f" % self._data

            if self._type_flag == 2:
                self._reg1.init(self._data)
                self._data = 1.0 if self._data_seq.read() > 0.0 else -1.0
                if self._data != -1.0 and self._data != 1.0:
                    print "error in SigGen.set:  data list has values that are not 1.0 or -1.0"
                    print "  in this case, the data value is %5.3f" % self._data

            self._prev_data = self._data
Example #19
0
 def delete_filter(self, filter_id):
     '''
  	This method delete a filter create.
     @param $filter_id id of the filter you want to delete.
     '''
     filter = Filter(filter_id)
     result = ExternalApiFilterRequest(
         ExternalApiFilterRequest.DELETE_REQUEST, filter, 0, None)
     return self.http_post(
         self.API_FILTERS_URL,
         None,
         body=result.get_json_encode_for_filter_based_requests())
Example #20
0
 def read_one_filter(self, filter_id):
     '''
     @param $filter_id id of the filter you want to read.
     @return This method returns the details of filter associate with this filter_id.
     '''
     filter = Filter(filter_id)
     result = ExternalApiFilterRequest(
         ExternalApiFilterRequest.READ_REQUEST, filter, 0, None)
     return self.http_post(
         self.API_FILTERS_URL,
         None,
         body=result.get_json_encode_for_filter_based_requests())
Example #21
0
    def getStateList(self, torrentList):
        states = FilterList()

        if len(torrentList) > 0:
            states.append(Filter('All', len(torrentList)))

        for torrent in torrentList:
            states.append(Filter(torrent.state, 1))

        finishedCount = torrentList.finishedCount()
        if finishedCount > 0:
            states.append(Filter('Finished', finishedCount))

        unfinishedCount = torrentList.unfinishedCount()
        if unfinishedCount > 0:
            states.append(Filter('Unfinished', unfinishedCount))

        unstartedCount = torrentList.unstartedCount()
        if unstartedCount > 0:
            states.append(Filter('Unstarted', unstartedCount))

        return states
Example #22
0
    def proof_of_work(self, block):
        block.nonce = 0
        computed_hash = block.get_hash()
        spam_filter = Filter("count.csv")

        for txn in self.unconfirmed_transactions:
            if not spam_filter.classificator(txn["content"], 1):
                return sha256("NaN".encode()).hexdigest()

        while not computed_hash.startswith('0' * Blockchain.difficulty):
            block.nonce += 1
            computed_hash = block.get_hash()

        return computed_hash
Example #23
0
 def __init__(self, paths, success=None, failure=None):
     if isinstance(paths, str):
         paths = [paths]
     pool = Pool()
     self.filters = pool.map(lambda x: Filter(x), paths)
     self.shape = self.filters[0].shape
     for f in self.filters:
         if f.shape != self.shape:
             print "The shapes of images are not the same"
             if failure:
                 failure()
             return
     if success:
         success()
Example #24
0
    def __init__(self):

        # Opent de camera om een foto te makenn
        self.camera = PiCamera()
        self.ControlPin = [31, 33, 35, 37]
        self.filterImage = Filter()
        for pin in self.ControlPin:
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, 0)

        # Sequence om de motor juist te laten draaien
        self.seq = [[1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0],
                    [0, 0, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [1, 0, 0, 1],
                    [1, 0, 0, 0]]
Example #25
0
def thread_run(config):
    rand_num = random.randint(1, 100)
    html = redis.spop('need_parsed_html')
    oss = Oss(config, 'upload-html%d' % rand_num)
    s_filter = Filter(config)
    mongodb = MongoClient(mongo_uri)
    col = mongodb.item.article_big_image
    while True:
        if html is None:
            time.sleep(1)
            html = redis.spop('need_parsed_html')
            continue
        else:
            try:
                html_parts = html.split('|')
                html_name = 'html/{}'.format(html_parts[0])
                html_source = html_parts[1]
                html_path = html_parts[2]
                res = download(html_path, html_source)
                if res is None:
                    raise Exception('download html %s failure' % html_path)
                html_content = res.content
                html_encoding = res.encoding
                if html_source.endswith('wx'):
                    html_content = s_filter.filter_wx_article(
                        html_content, html_encoding)
                    if html_content is None:
                        raise Exception('the {} may be failed'.format(''))
                if html_source == 'toutiao':
                    html_content = s_filter.filter_toutiao_article(
                        html_content, html_encoding)
                if html_source == 'ifeng':
                    html_content = s_filter.filter_ifeng_article(
                        html_content, html_encoding, html_parts[0])
                try:
                    oss.upload('spider-lucas', html_name, html_content)
                    col.update({'content': html_parts[0]},
                               {'$set': {
                                   'status_code': 0
                               }})
                except Exception as e:
                    del oss
                    oss = Oss(config, 'upload-html%d' % rand_num)
            except Exception as e:
                print e
            finally:
                html = redis.spop('need_parsed_html')
                time.sleep(1)
Example #26
0
    def __init__(self, log, filter_filename="__none__"):

        # Call parent init
        UserDict.__init__(self)

        if log[0] != "__none__" and filter_filename != "__none__":
            # Setup log and filter
            self.filter = Filter(filter_filename)
            self.fill(log)

        elif log[0] != "__none__":
            # Setup log without filter
            self.fill(log)
            
        else:
            # Create empty filter
            pass
Example #27
0
    def __init__(self,
                 llwl='Brown',
                 llNL=2,
                 percen=80,
                 NE=True,
                 Col=True,
                 Gram=True,
                 Chu=True):
        '''      
        @param llwl:LogLikleyHood Corpa name ('Brown','AmE06','BE06')
        @param llNL:LogLikleyHood 
        @param percen: Presision of output default = 20, 20% returned
        @param NE: Uses NE default True 
        @param Col: Uses Collocation default True
        @param Gram: Uses N-Grams default True
        @param Chu: Uses Chunking default True
        '''

        self.NEs = NE
        self.Col = Col
        self.Gram = Gram
        self.Chu = Chu
        self.p = percen
        print 'Starting to build ', llwl
        self.LL = LogLikelihood(wordlist=llwl, NLength=llNL)
        print 'LL Loaded'
        self.POS = POS()
        print 'POS Loaded'
        self.GD = GetData()
        print 'GD Loaded'
        self.Cu = Chunker(self.POS)
        print 'Cu Loaded'
        self.FL = Filter()
        print 'FL Loaded'
        self.CC = Collocation(self.POS)
        print 'CC Loaded'
        self.Ng = NGram()
        print 'Ng Loaded'
        self.S = Select(percentil=self.p)
        print 'S Loaded'
        self.To = Tokenize(self.FL)
        print 'To Loaded'
Example #28
0
def fusSensors1(Sensors):
    # does not work
    H_allSensors = np.vstack(Sensors[0].getH(),Sensors[1].getH(),Sensors[2].getH(),Sensors[3].getH(),Sensors[4].getH())
    Z_allSensors = np.vstack(Sensors[0].ProduceNoisedMeasuresCoordinations(),Sensors[1].ProduceNoisedMeasuresCoordinations(),
                             Sensors[2].ProduceNoisedMeasuresCoordinations(),Sensors[3].ProduceNoisedMeasuresCoordinations(),
                             Sensors[4].ProduceNoisedMeasuresCoordinations())
    def createRallSensors():
        R = np.zeros(tuple([5*x for x in Sensors[0].createR().shape]))
        R[0:2,0:2] = Sensors[0].createR()
        R[2:4,2:4] = Sensors[1].createR()
        R[4:6,4:6] =Sensors[2].createR()
        R[6:8,6:8] = Sensors[3].createR()
        R[8:10,8:10] =Sensors[4].createR()
        return R
    
    R_allSensors = createRallSensors()
    newSensorWithRandH = Sensor(movingObject)
    newSensorWithRandH.R = R_allSensors
    newSensorWithRandH.H = H_allSensors
    newFilter = Filter(newSensorWithRandH)
Example #29
0
 def on_formBtn_clicked(self):
     # open a filter window
     self.filterWindow = QtWidgets.QDialog()
     Filter(self.filterWindow)
     returnID = self.filterWindow.exec()
     if not returnID:
         return
     # update the self.idIndex
     self.idIndex = self.getIdIndex(returnID)
     # fetch a record from the db
     con, cursor= connect._get_connection()
     con.row_factory = sqlite3.Row
     cursor = con.cursor()
     sqlstr = ('select * from hvhnonc_in where ID=?')
     params = (returnID,)
     cursor.execute(sqlstr, params)
     record = cursor.fetchone()
     con.close()
     self.init_all_fields()
     self.update_by_record(record)
def main(image_filter=transformations.identity):
    image_filter = Filter(image_filter, data)
    image_filter.initialize()

    model = Model([
        keras.layers.Flatten(input_shape=data.input_shape),
        keras.layers.Dense(128, activation=keras.activations.relu),
        keras.layers.Dense(10, activation=keras.activations.softmax)
    ])

    model.optimizer = keras.optimizers.SGD(lr=0.01, nesterov=True)
    model.epochs = 4
    model.image_filter = image_filter

    model.initialize()
    model.fit()

    image_filter.plot()

    print('Accuracy: {0}'.format(model.test_accuracy))