Ejemplo n.º 1
0
    def draw_line(self, pos):
        if self.viewer._ocr and self.x_clicked or self.y_clicked:
            img_line = cv.line(self.image.copy(),
                               (self.x_clicked, self.y_clicked),
                               (pos.x(), pos.y()), (0, 0, 0), 2)
            image_height, image_width, image_depth = img_line.shape
            QIm = cv.cvtColor(img_line, cv.COLOR_BGR2RGB)
            QIm = QImage(QIm.data, image_width, image_height,
                         image_width * image_depth, QImage.Format_RGB888)
            self.viewer.setPhoto(QPixmap.fromImage(QIm))
        # 终止画线
        if self.x_released or self.y_released:
            self.choosePoints = []  # 初始化存储点组
            inf = float("inf")
            if self.x_released or self.y_released:
                if (self.x_released - self.x_clicked) == 0:
                    slope = inf
                else:
                    slope = (self.y_released - self.y_clicked) / (
                        self.x_released - self.x_clicked)

                siteLenth = 0.5 * math.sqrt(
                    square(self.y_released - self.y_clicked) +
                    square(self.x_released - self.x_clicked))

                mySiteLenth = 2 * siteLenth
                self.siteLenth = ("%.2f" % mySiteLenth)
                self.editSiteLenth.setText(self.siteLenth)
                radian = math.atan(slope)
                self.siteSlope = ("%.2f" % radian)
                self.editSiteSlope.setText(self.siteSlope)
                x_bas = math.ceil(math.fabs(0.5 * siteLenth *
                                            math.sin(radian)))
                y_bas = math.ceil(math.fabs(0.5 * siteLenth *
                                            math.cos(radian)))

                if slope <= 0:
                    self.choosePoints.append([(self.x_clicked - x_bas),
                                              (self.y_clicked - y_bas)])
                    self.choosePoints.append([(self.x_clicked + x_bas),
                                              (self.y_clicked + y_bas)])
                    self.choosePoints.append([(self.x_released + x_bas),
                                              (self.y_released + y_bas)])
                    self.choosePoints.append([(self.x_released - x_bas),
                                              (self.y_released - y_bas)])
                elif slope > 0:
                    self.choosePoints.append([(self.x_clicked + x_bas),
                                              (self.y_clicked - y_bas)])
                    self.choosePoints.append([(self.x_clicked - x_bas),
                                              (self.y_clicked + y_bas)])
                    self.choosePoints.append([(self.x_released - x_bas),
                                              (self.y_released + y_bas)])
                    self.choosePoints.append([(self.x_released + x_bas),
                                              (self.y_released - y_bas)])
            self.viewer._ocr = False
Ejemplo n.º 2
0
def waveform(frequency, rate, duration=1, amplitude=1):
    count = math.ceil(rate * duration)
    return np.fromiter(
        (math.sin(2.0 * math.pi * r * frequency / rate) * amplitude
         for r in range(count)),
        dtype=np.float32,
        count=count)
Ejemplo n.º 3
0
def gaussian_grid(sigma, alpha=4):
    sig = max(sigma, 0.01)
    length = int(math.ceil(sig * alpha)) + 1
    m = length / 2
    n = m + 1
    x, y = mgrid[-m:n, -m:n]
    g = exp(m**2) * exp(-0.5 * (x**2 + y**2))
    return g / g.sum()
Ejemplo n.º 4
0
def linear_interpolation(colors, x):
    max_index = (len(colors) - 1)
    interval = (1. / max_index)
    ci1 = math.floor(x / interval)
    ci2 = min(math.ceil(x / interval), max_index)

    return linear_points_interpolation(colors[ci1], colors[ci2],
                                       (x - interval * ci1) / interval)
def imshow_n_images(*images, rows=1):
    n = len(images)
    cols = math.ceil(n // rows)
    plt.clf()
    for i, img in enumerate(images, start=1):
        plt.subplot(rows, cols, i)
        plt.imshow(img)
    plt.show(block=False)
Ejemplo n.º 6
0
def dataFitting(data):
    try:
        dataLen = len(data)
        tmp = 2**(math.ceil(math.log(dataLen, 2)))
        delta = tmp - dataLen
        meanTmp = ar.histMean(data[:dataLen / 4])
        newData = empty(tmp, dtype='float32')
        newData.fill(meanTmp)
        newData[delta:] = data
        return newData, delta
    except:
        logger.error("dataFitting # Error: {0}".format(sys.exc_info()))
Ejemplo n.º 7
0
    def get_part(self, perc_of_data: float, part_nr: int):
        nr_samples = self.x_train.shape[0]
        part_size = math.ceil(nr_samples * perc_of_data)
        total_nr_parts = int(math.ceil(nr_samples / part_size))

        if perc_of_data == 1.0 or nr_samples == part_size:
            return TrainValSet(self.x_train, self.y_train, self.x_val, self.y_val)
        elif len(self.strat_indices) == 0:
            skf = StratifiedKFold(
                n_splits=total_nr_parts, shuffle=True, random_state=42
            )
            split = list(skf.split(self.x_train, self.y_train))
            for _, fold in split:
                self.strat_indices.append(fold)

        return TrainValSet(
            self.x_train[self.strat_indices[part_nr]],
            self.y_train[self.strat_indices[part_nr]],
            self.x_val,
            self.y_val,
        )
Ejemplo n.º 8
0
def dataFitting(data):
    try:
        dataLen = len(data)
        tmp = 2**(math.ceil(math.log(dataLen, 2)))
        delta = tmp - dataLen
        meanTmp = ar.histMean(data[:dataLen / 4])
        newData = empty(tmp, dtype='float32')
        newData.fill(meanTmp)
        newData[delta:] = data
        return newData, delta
    except:
        logger.error("dataFitting # Error: {0}".format(sys.exc_info()))
Ejemplo n.º 9
0
    def predict_generator(self, model, test_gen, print_report=False):
        test_steps_per_epoch = math.ceil(test_gen.samples /
                                         test_gen.batch_size)
        pred = model.predict_generator(test_gen, steps=test_steps_per_epoch)

        y_pred = argmax(pred, axis=1)
        y_test = test_gen.classes

        #class_labels = list(test_gen.class_indices.keys())

        roc_plot_name = 'ROC_fold_{}.png'.format(self.__len__())
        auc = multiclass_roc_auc(y_test, y_pred, self.savefig, roc_plot_name)

        cm_name = 'CM_fold_{}.png'.format(self.__len__())
        confusion_matrix(y_test, y_pred, True, cm_name)

        report = self.classification_eval(y_test, y_pred)
        report['roc_auc'] = auc['micro']

        if print_report:
            self.print_classification_report(y_test, y_pred, report['acc'])

        self.reports.append(report)
    def Evolvent(self):
        '''Расчет эвольвенты зуба
        '''
        #Расчет эвольветы зуба 
        # Читаем данные из полей формы
        # z = Количество зубьев
        z = self.doubleSpinBox_Z.value() 
        # m = Модуль зуба
        m = self.doubleSpinBox_m.value() 
        # a = Угол главного профиля
        a = self.doubleSpinBox_a.value()
        #b = Угол наклона зубьев
        b = self.doubleSpinBox_b.value()
        #ha = Коэффициент высоты головки
        ha = self.doubleSpinBox_ha.value()
        #pf = К-т радиуса кривизны переходной кривой
        pf = self.doubleSpinBox_pf.value()
        #c = Коэффициент радиального зазора
        c = self.doubleSpinBox_c.value()
        #x = К-т смещения исходного контура
        x = self.doubleSpinBox_x.value()
        #y =Коэффициент уравнительного смещения
        y = self.doubleSpinBox_y.value()
        # n= Количество точек (точность построения)
        #n=int(self.doubleSpinBox_n.value())
        n=100
        # заполня переменные 
        # Делительный диаметр
        d = z * m
        # Высота зуба h=
        h = 2.25 * m
        # Высота головки ha =
        hav = m
        # Высота ножки hf=
        hf = 1.25 * m
        #Диаметр вершин зубьев
        #da = d + (2 * m)*(ha+x+y)
        da = d + 2 * (ha + x - y) * m
        #Диаметр впадин (справочно)
        #df = d -(2 * hf)
        df = d -2 * (ha + c - x) * m
        #Окружной шаг зубьев или Шаг зацепления по дуге делительной окружности: Pt или p
        pt = math.pi * m
        #Окружная толщина зуба или Толщина зуба по дуге делительной окружности: St или S
        #Суммарный коэффициент смещений: XΣ
        X = 0.60 + 0.12
       # St = 0.5 * pf
       # St = 0.5 * pt
        St = 0.5 * pt + 2 * x * m * math.tan(math.radians(a))
        #inv a 
        inva=math.tan(math.radians(a))-math.radians(a)
        #Угол зацепления invαw
        invaw= (2 * X - math.tan(math.radians(a))) / (10+26) + inva
        #Угол профиля
        at = math.ceil(math.degrees(math.atan(math.tan(math.radians(a))
            /math.cos( math.radians(b)))))
        # Диаметр основной окружности
        db = d * math.cos(math.radians(at)) 
        #Диаметр начала выкружки зуба
        D  = 2 * m * ( ( z/( 2 * math.cos(math.radians(b)) )-(1-x)) ** 2 +
            ((1-x)/math.tan(math.radians(at)))**2)**0.5
        #Промежуточные данные
        yi = math.pi/2-math.radians(at)

        hy = yi/(n-1)

        x0 = math.pi/(4*math.cos(math.radians(b))
             )+pf*math.cos(math.radians(at))+math.tan(math.radians(at))

        y0 = 1-pf*math.sin(math.radians(at))-x

        C  = (math.pi/2+2*x*math.tan(math.radians(a))
             )/z+math.tan(math.radians(at))-math.radians(at)
        #Расчетный шаг точек эвольвенты
        hdy = (da-D)/(n-1)
        dyi = da
        fi = 2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi))
        #Заполняем текстовые поля в форме
        # Делительный диаметр
    #    self.lineEdit_d.setText(str(d))
        # Высота зуба h=
    #    self.lineEdit_h.setText(str(h))
        # Высота головки ha =
    #    self.lineEdit_ha.setText(str(hav))
        # Высота ножки hf=
    #    self.lineEdit_hf.setText(str(hf))
        # Диаметр вершин зубьев
    #    self.lineEdit_da.setText(str(da))
        # Диаметр впадин (справочно)
    #    self.lineEdit_df.setText(str(df))
        # Окружной шаг зубьев Pt=
    #    self.lineEdit_Pt.setText(str(math.ceil(pt)))
        # Окружная толщина зуба St=
    #    self.lineEdit_St.setText(str(math.ceil(St)))
        # Угол профиля
    #    self.lineEdit_at.setText(str(at))
        # Диаметр основной окружности
    #    self.lineEdit_db.setText(str(math.ceil(db)))
        
        # Создаем списки 
        List_dyi=[]
        List_Di=[]
        List_Yei=[]
        List_Xei=[]
        List_Minus_Xei=[]
        List_Xdai=[]
        List_Ydai=[]
        List_yi=[]
        List_Ai=[]
        List_Bi=[]
        List_fi=[]
        List_Ypki=[]
        List_Xpki=[]
        List_Minus_Xpki=[]
        # Заполняем нуливой (первый )индекс списка значениями
        List_dyi.append(dyi)
        List_Di.append( math.acos( db/ List_dyi[0] ) - math.tan( math.acos( db / List_dyi[0] ) ) + C )
        List_Yei.append(dyi / 2*math.cos( List_Di[0]))
        List_Xei.append(List_Yei[0]*math.tan(List_Di[0]))
        List_Minus_Xei.append(-List_Xei[0])
        List_Xdai.append(-List_Xei[0])
        List_Ydai.append(((da/2)**2-List_Xdai[0]**2)**0.5)
        hda=(List_Xei[0]-List_Minus_Xei[0])/(n-1)
        # Заполняем первый (второй по счету )индекс списка значениями 
        List_dyi.append(dyi-hdy)
        List_Di.append( math.acos(db/List_dyi[1])-math.tan(math.acos(db/List_dyi[1]))+C)
        List_Yei.append( List_dyi[1]/2*math.cos(List_Di[1]))
        List_Xei.append( List_Yei[1]* math.tan(List_Di[1]))
        List_Minus_Xei.append(-List_Xei[1])
        List_Xdai.append(List_Xdai[0]+hda)
        List_Ydai.append(((da/2)**2-List_Xdai[1]**2)**0.5)
        Xdai=List_Xdai[1]
        dyi=dyi-hdy
        # Начинаем  заполнять списки в цикле 
        i=0
        while i < n-2:  
            i=i+1
            dyi=dyi-hdy
            List_Di.append(math.acos(db/dyi)-math.tan(math.acos(db/dyi))+C)
            Di=math.acos(db/dyi)-math.tan(math.acos(db/dyi))+C
            Yei=dyi/2*math.cos(Di)
            Xei=Yei*math.tan(Di) 
            List_dyi.append(dyi) 
            List_Yei.append(dyi/2*math.cos(Di))
            List_Xei.append(Yei*math.tan(Di))
            List_Minus_Xei.append(-Xei) 
            Xdai=Xdai+hda
            List_Xdai.append(Xdai)
            List_Ydai.append(((da/2)**2-Xdai**2)**0.5)
        #Заполняем последний индекс  списка    
        List_dyi[n-1]=D
        # Заполняем нуливой (первый )индекс списка значениями
        List_yi.append(yi)
        List_Ai.append(z/(2*math.cos(math.radians(b)))-y0-pf*math.cos(List_yi[0]) )
        List_Bi.append(y0*math.tan(List_yi[0])+pf*math.sin(List_yi[0]))
        List_fi.append(fi)
        List_Ypki.append((List_Ai[0] * math.cos(fi)+List_Bi[0] * math.sin(fi)) * m)
        List_Xpki.append((List_Ai[0] * math.sin(fi)-List_Bi[0] * math.cos(fi)) * m)
        List_Minus_Xpki.append(-List_Xpki[0])
        # Начинаем  заполнять списки в цикле 
        i=0
        while i < n-2:
            i=i+1
            yi=yi-hy
            List_yi.append(yi)
            Ai = z / (2 * math.cos(math.radians(b)))-y0-pf*math.cos(yi)
            List_Ai.append( z / (2 * math.cos(math.radians(b)))-y0-pf*math.cos(yi))
            Bi =y0*math.tan(yi)+pf*math.sin(yi)
            List_Bi.append(y0*math.tan(yi)+pf*math.sin(yi))
            fi = 2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi))
            List_fi.append(2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi)))
            List_Ypki.append((Ai*math.cos(fi)+Bi*math.sin(fi))*m)
            Ypki=(Ai*math.cos(fi)+Bi*math.sin(fi))*m
            Xpki=(Ai*math.sin(fi)-Bi*math.cos(fi))*m
            List_Xpki.append((Ai*math.sin(fi)-Bi*math.cos(fi))*m)
            List_Minus_Xpki.append(-Xpki)
        #Заполняем последний индекс  списка  
        List_yi.append(yi-yi)
        List_Ai.append(z/(2*math.cos(math.radians(b)))-y0-pf*math.cos(List_yi[n-1]) )  
        List_Bi.append(y0*math.tan(List_yi[n-1])+pf*math.sin(List_yi[n-1])) 
        List_fi.append(2*math.cos(math.radians(b))/z*(x0+y0*math.tan(List_yi[n-1])))
        List_Ypki.append((List_Ai[n-1] * math.cos(fi)+List_Bi[n-1] * math.sin(List_fi[n-1])) * m)
        List_Xpki.append((List_Ai[n-1] * math.sin(fi)-List_Bi[n-1] * math.cos(List_fi[n-1])) * m)
        List_Minus_Xpki.append(-List_Xpki[n-1])

       # self.WiPfileZub(List_Yei,List_Xei,List_Minus_Xei,List_Ypki,List_Xpki,List_Minus_Xpki,List_Ydai,List_Xdai)
        self.GragEvolvent(List_Minus_Xei+List_Minus_Xpki,List_Yei+List_Ypki,n)

        DFreza = self.lineEditDFreza.text()
        VisotaYAxis = self.lineEditVisota.text()
        Diametr = self.lineEditDiametr.text()
        if DFreza and VisotaYAxis:
            E30 = (int(DFreza)/2) +float(VisotaYAxis)
        else:
            E30 = 0
        angi_B=0
        if ValkosZub:
            angie_A:float = 90# угол А треугольника по высоте детали 
            angie_B:float = float(b) #угол B треугольника по высоте детали ( угол наклона зуба по чертежу)
            angie_Y:float = 180 - (angie_A + angie_B) # трерий уго треугольника по высоте детали 
            side_c:float = float(E30)# высота детали первая сторона треугольника 
            side_a = side_c * math.sin(math.radians(angie_A)) / math.sin(math.radians(angie_Y))# вторая сторона треугольника 
            side_b = side_c * math.sin(math.radians(angie_B)) / math.sin(math.radians(angie_Y))# третия сторона треугольника ( ось Х)
            sid_a:float = float(Diametr)/2 # радиус детали первая и вторая тророны треугольника по торцу
           # sid_a:float = float(self.lineEdit_da.text())/2 # радиус детали первая и вторая тророны треугольника по торцу
            sid_c:float = sid_a
            if sid_c < 10 :
                sid_a:float = 10
                sid_c:float = 10
                angi_B = float('{:.3f}'.format(math.degrees(math.acos((sid_a**2+sid_c**2-side_b**2)/(2*sid_a*sid_c)))))
                QMessageBox.about (self, "Ошибка " , "Диаметр шестерни задан меньше 20 мм. \n Введите риальный диаметр шестерни " )
            else:
                angi_B = float('{:.3f}'.format(math.degrees(math.acos((sid_a**2+sid_c**2-side_b**2)/(2*sid_a*sid_c)))))# результат угол поворота стола 


        self.label_da.setText(str(round(da,1)))
        self.label_d.setText(str(round(d,1)))
        self.label_at.setText(str(round(at,1)))
        self.label_db.setText(str(round(db,1)))
        self.label_df.setText(str(round(df,1)))
        self.label_St.setText(str(round(St,1)))
        self.label_Pt.setText(str(round(pt,1)))
        self.label_hf.setText(str(round(hf,1)))
        self.label_ha.setText(str(round(ha,1)))
        self.label_h.setText(str(round(h,1)))
        self.lineEditDiametr.setText(str(da))
        self.lineEditUgol.setText(str(angi_B))
Ejemplo n.º 11
0
def fpf_calculator(image,filetype,planet_position,radius,method='exact',subpix=20,plot=False,
                 no_planet_nghbr=True,name='fpf_test',save='False',save_dir='None', j=None):


    ####### PARAMETERS:
    ## image : fits OR 2d-array : (PynPointed) image where to perform the SNR & FPF calculation (as an array or a single fits file)
                                # n.b.: during the whole analysis the image is assumed to be centered on the central star.
    ## filetype : string : format of the image. Possibilities are: 'fits' or 'array'
    ## planet_position : array of two values : rough position of the target in (integer) pixels, as an array: [x,y] (n.b.: if the
                                                #  'method' is 'exact' this position will be assumed to be the best position)
    ## radius : float : desired radius for the apertures (in pixels)
    ## method : string : how to search for the best position given the rough one. Possibilities are:
                        # 'exact' : the given planet_position is assumed to be the best one
                        # 'search' : the best position is found performing a search for the local maximum pixel value
                        # around the given planet_position in a square of side = (2 * r) * 2, rounded up
                        # (nb: the best position is found as integer pixels)
                        # 'fit' : the best position is found fitting a 2D gaussian on the given planet_position. The best
                        # position found in this way allows for floating pixels values.
    ## subpix : integer : how much refined the subpixel grid for the creation of the aperture should be. Each pixel is resampled in
                        #  subpix*subpix other pixels. (Quick test showed that after a value of 10-15, the final results are
                        # quite stable, so the default is 20).
    ## plot : boolean : whether to plot or not the final image together with the created apertures, the SNR and the FPF value
    ## no_planet_nghbr : boolean : whether to consider or not the two background apertures near the signal aperture.
    ## name : string : desired name with which save the final result (if save==True).
    ## save : boolean : whether or not save the results. If true, two images will be saved as fits files: the initial image
                        # with the apertures, and the initial image plus the gaussian fit.
    ## save_dir : string : path to a folder where to save (if save==True) the images as fits files

    ##### OUTPUT:
    ## the function returns:
    # fpf : float : value of the False Probability Fraction evaluated from the t_test value
    # t_test : float : value of the t_test
    # snr : float : value of the snr
    # planet_pos : array of two values : best planet position (evaluated with the desired method) in pixels
    # bckg_aps_cntr : multidimensional array : it contains (in pixel values) all the centers of ALL the apertures created
                    # for the analysis (including the signal aperture and the two apertures nearby). n.b.: the last is the
                    # center position of the signal aperture, i.e.: the best position (found with the desired method)
    # fpf_bckgs : array : it contains the FPF values evaluated for all the background apertures with respect to each other.
                        # n.b.: the signal aperture is ALWAYS excluded, while the background apertures nearby are excluded only if requested

    ## if method == 'fit', it also returns:
    # popt : array : best fit parameters found for the 2D gaussian fit (amplitude, xo, yo, sigma_x, sigma_y, theta, offset)
    # pcov : 2d array : the estimated covariance of popt as returned by the function scipy.optimize.curve_fit

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


    #Let's import the image:
    if filetype=='fits':
        data=fits.open(image)[0].data #NB: the fits file must consist of a single image (NO datacube)!
    if filetype=='array':
        data=image

    #Get the image size:
    size = len(data[0])

    #Define the center (i.e.: the image is supposed to be centered on the central star):
    center=np.array([size/2.,size/2.])

    #Round up the size of the range of search for the local maximum:
    ros=math.ceil(radius)#*2) #* 2.
    print 'ROS ',ros

    #Let's find the planet position:
    if method =='exact':
        planet_pos=planet_position
    if method == 'search':
        planet_pos=planets_finder(data,'array','local_max',planet_position=planet_position,range_of_search=ros)[0]
    if method == 'fit':
        planet_pos_guess=planets_finder(data,'array','local_max',planet_position=planet_position,range_of_search=ros)[0]
        #Create grid for the fit:
        x = range(size)
        y = range(size)
        x, y = np.meshgrid(x, y)
        sigma = (radius*2)/(2.*np.sqrt(2.*np.log(2.)))
        #create arrays of initial guess:
        #See which quadrant the planet is in, and give accordingly the correct additional factor for the arctan calculation:
        if planet_position[0]>= size/2. and planet_position[1]>=size/2.: #first quadrant
            arctan_fac=0.
            angle_factor=90.
        if planet_position[0]<=size/2. and planet_position[1]>=size/2.:#second quadrant
            arctan_fac=180.
            angle_factor=360.+90.
        if planet_position[0]<=size/2. and planet_position[1]<=size/2.:#third quadrant
              arctan_fac=180.
              angle_factor=270.+180.
        if planet_position[0]>=size/2. and planet_position[1]<=size/2.:#fourth quadrant
            arctan_fac=360.
            angle_factor=180.+270.

        theta=np.deg2rad(angle_factor-(np.degrees(np.arctan((planet_position[1] - size/2.)/(planet_position[0] - size/2.))) + arctan_fac))

        p0=[data[planet_pos_guess[1]][planet_pos_guess[0]],planet_pos_guess[0],planet_pos_guess[1],sigma,sigma,theta,0.]
        print '\n\ninitial guess : '+str(p0)
        popt, pcov = opt.curve_fit(twoD_Gaussian, (x, y), data.flatten(),p0=p0)
        planet_pos=np.array([popt[1],popt[2]])
        data_fitted=twoD_Gaussian((x,y),*popt)
        print popt
#[planet_pos_guess[0]-5:planet_pos_guess[0]+5, planet_pos_guess[1]-5:planet_pos_guess[1]+5]
    #let's calculate the distance between the planet and the star (i.e.: ASSUMING IMAGE CENTERING):
    d=np.sqrt((planet_pos[0] - center[0])**2 + (planet_pos[1]-center[1])**2)

    #Now, starting from the position of the planet, let's create a series of background apertures:

    #Let's calculate how many apertures can I put at that distance and given a certain radius of the aperture:
    n_bckg_aps=np.int((2*np.pi*d)/(2.*radius)) #NB: np.int assures that the number is rounded down to avoid overlaps

    #Let's save the center positions of all the background apertures:
    bckg_aps_cntr=np.ones((n_bckg_aps,2))
    angle_i=360./n_bckg_aps
    for i_apertures in range(0,n_bckg_aps):
        bckg_aps_cntr[i_apertures]=angular_coords_float(center,planet_pos,angle_i)
        angle_i=angle_i+(360./(n_bckg_aps))

    #Define the area (given the radius):
    area= np.pi * radius**2

    #Create the apertures and calculate the weighted pixel values in all of them: (the LAST one is the signal aperture)

    #Define some void arrays to be filled with the flux inside each aperture (i.e.: sum of all the weighted pixels),
    # the single weighted pixel values for all the apertures, the fractions for to be multiplied for all the apertures
    # and the not-weighted pixel values:
    # flux = np.zeros(len(bckg_aps_cntr), dtype=np.float)
    fractions=[]
    bckg_values=[]
    bckg_apertures=[]
    signal_aperture=[]

    #Let's define the extention of the region of interest for each aperture
    extents = np.zeros((len(bckg_aps_cntr), 4), dtype=int)

    extents[:, 0] = bckg_aps_cntr[:, 0] - radius + 0.5
    extents[:, 1] = bckg_aps_cntr[:, 0] + radius + 1.5
    extents[:, 2] = bckg_aps_cntr[:, 1] - radius + 0.5
    extents[:, 3] = bckg_aps_cntr[:, 1] + radius + 1.5

    ood_filter, extent, phot_extent = get_phot_extents(data, bckg_aps_cntr,extents)

    x_min, x_max, y_min, y_max = extent
    x_pmin, x_pmax, y_pmin, y_pmax = phot_extent

    if no_planet_nghbr==True:
        print 'Ignore the two apertures near the signal aperture'
    #For each aperture, let's calculate the fraction values given by the intersection between the pixel region of interest
    # and a circle of radius r, then use these fractions to evaluate the final weighted pixel values for each aperture:
    for index in range(len(bckg_aps_cntr)):
        fraction= geometry.circular_overlap_grid(x_pmin[index], x_pmax[index],
                                                  y_pmin[index], y_pmax[index],
                                                  x_max[index] - x_min[index],
                                                  y_max[index]- y_min[index],
                                                  radius, 0, subpix)
        fractions.append(fraction)

        #now, let's return the weighted pixel values but erasing the values ==0. (since the subpixel sampling can result
        # in a fraction =0 and so the pixel value is weighted by 0. and so it is =0. But it is not really 0.)

        #Ignore, if requested, the two apertures near the signal aperture:
        if no_planet_nghbr==True:
            if index != len(bckg_aps_cntr)-1 and index != len(bckg_aps_cntr)-2 and index != 0:
                bckg_values += (filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))
                bckg_apertures.append(filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))

            if index==len(bckg_aps_cntr)-1:
                signal_aperture += (filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))

        else:
            if index != len(bckg_aps_cntr)-1:
                bckg_values += (filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))
                bckg_apertures.append(filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))

            else:
                signal_aperture += (filter(lambda a: a !=0.,np.array((data[y_min[index]:y_max[index],x_min[index]:x_max[index]] * fraction)).ravel()))

    signal_aperture=np.array(signal_aperture)
    bckg_values=np.array(bckg_values)
    bckg_apertures=np.array(bckg_apertures)

    ##################################################################################
    ### SNR calculation (as in Meshkat et al. 2014)
    snr=(np.sum(signal_aperture) - (np.mean(bckg_values)) * len(signal_aperture))/\
        (np.std(bckg_values) * np.sqrt(len(signal_aperture)) )

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

    ### t-test value calculation:
    # Define the sample composed by the means inside the background apertures:
    bckg_apertures_means=[]
    bckg_apertures_fluxes=[]

    for index_mean in range(len(bckg_apertures)):
        bckg_apertures_means.append(np.sum(bckg_apertures[index_mean]) / area)
        bckg_apertures_fluxes.append(np.sum(bckg_apertures[index_mean]))

    bckg_apertures_means=np.array(bckg_apertures_means)
    bckg_apertures_fluxes=np.array(bckg_apertures_fluxes)

    #Calculate t-test value (according to Mawet et al. 2014):
    # In this way, the value that I am assigning to each resolution element is the MEAN of the pixel values:
    t_test=np.abs(((np.sum(signal_aperture)/area) - np.sum(bckg_apertures_means)/len(bckg_apertures_means))/\
           (np.std(bckg_apertures_means) * np.sqrt(1. + 1./len(bckg_apertures_means))))

    # #In this way, the value that I am assigning to each resolution element is the FLUX of the pixel values:
    # t_test=np.abs(((np.sum(signal_aperture)) - np.sum(bckg_apertures_fluxes)/len(bckg_apertures_fluxes))/\
    #        (np.std(bckg_apertures_fluxes) * np.sqrt(1. + 1./len(bckg_apertures_fluxes))))


    #Calculate the t-test value and fpf for all of the other background aperture (but always ignoring the signal one):
    fpf_bckgs=np.zeros(len(bckg_apertures_means))
    for i_t_test in range(len(bckg_apertures_means)):
        bckg_apertures_means_i=np.delete(bckg_apertures_means,i_t_test)
        t_test_i=np.abs((np.sum(bckg_apertures[i_t_test])/area - np.sum(bckg_apertures_means_i)/len(bckg_apertures_means_i))/\
                 (np.std(bckg_apertures_means_i) * np.sqrt(1. + 1./len(bckg_apertures_means_i))))
        fpf_i= 1. - t.cdf(t_test_i,len(bckg_apertures_means_i)-1)
        fpf_bckgs[i_t_test]=fpf_i

    #Given the t-test value, calculate the false alarm probability:
    # nb: define in this way, it is a ONE SIDE TEST!!
    fpf= 1. - t.cdf(t_test,len(bckg_apertures_means)-1)
    # print 'FPF : '+str(fpf)
    ##################################################################################

    #Plot the image together with the apertures, if requested:
    if plot ==True:
        # these are matplotlib.patch.Patch properties:
        props = dict(boxstyle='square', facecolor='white')

        #Let's create all the circles:
        #For the planet aperture:
        signal_aperture=plt.Circle((planet_pos[0],planet_pos[1]),radius,color='Crimson',fill=False,linewidth=1)

        fig = plt.gcf()
        ax=fig.add_subplot(111)
        plt.title(name,size=22)
        plt.imshow(data,origin='lower',alpha=0.5)
        fig.gca().add_artist(signal_aperture)

        plt.hold(True)
        if no_planet_nghbr==False:
            for i_plot in range(n_bckg_aps-1):# the minus 1 is to exclude the planet aperture
                background_aperture=plt.Circle((bckg_aps_cntr[i_plot][0],bckg_aps_cntr[i_plot][1]),radius,color='b',fill=False,linewidth=1)
                fig.gca().add_artist(background_aperture)

        if no_planet_nghbr==True:
            for i_plot in range(n_bckg_aps):
                if i_plot != 0 and i_plot != n_bckg_aps-1 and i_plot != n_bckg_aps-2:
                    background_aperture=plt.Circle((bckg_aps_cntr[i_plot][0],bckg_aps_cntr[i_plot][1]),radius,color='b',fill=False,linewidth=1)
                    fig.gca().add_artist(background_aperture)


        plt.text(0.55,0.8,'FPF = '+str('%s' % float('%.2g' % fpf))+'\npos = ['+str('%s' % float('%.3g' % planet_pos[0]))+' , '+str('%s' % float('%.3g' % planet_pos[1]))+']'
                 ,color='black',size=18,bbox=props,transform=ax.transAxes)

        plt.xlim(0,size)
        plt.ylim(0,size)
        plt.colorbar()
        if save==True:
            plt.savefig(str(save_dir)+str(name)+'%s.pdf'%j,clobber=1)
        plt.show()

        #now, let's plot the gaussian fit:
        if method=='fit':
            fig, ax = plt.subplots(1, 1)
            plt.title(name,size=22)
            ax.hold(True)
            ax.imshow(data,origin='lower',alpha=0.5)
            ax.contour(x, y, data_fitted.reshape(size, size), 5, colors='k')
            plt.text(0.55,0.85,'pos = ['+str('%s' % float('%.3g' % planet_pos[0]))+' , '+
                     str('%s' % float('%.3g' % planet_pos[1]))+']'
                     ,color='black',size=18,bbox=props,transform=ax.transAxes)
            plt.xlim(0,size)
            plt.ylim(0,size)
            if save==True:
                plt.savefig(str(save_dir)+'fit/'+str(name)+'_FIT.pdf')
            plt.show()

    # if method=='fit':
    #     print 'Fit : '+str(popt)


    #Save the result as an ASCII table:
    names=['FPF','t_test','SNR','Planet_pos_x','Planet_pos_y','Method']
    results=Table([[fpf],[t_test],[snr],[planet_pos[0]],[planet_pos[1]],[method]],names=names)
    results_name=save_dir+str(name)+'.txt'

    #Print the results:
    results.pprint(max_lines=-1,max_width=-1,align='^')

    #if requested, save the results
    if save==True:
        results.write(results_name,format='ascii.basic',delimiter='\t')
        print 'The result has been saved in '+str(results_name)+'\n'

    #return the final values:
    if method!='fit':
        return (fpf,t_test,snr,planet_pos,bckg_aps_cntr,fpf_bckgs)
    if method=='fit':
        return (fpf,t_test,snr,planet_pos,bckg_aps_cntr,fpf_bckgs,popt,pcov)
Ejemplo n.º 12
0
    if res.find("m") != -1:
        return int(res.replace("m", ""))
    if res.find("Mi") != -1:
        return int(res.replace("Mi", ""))
    return int(res)


print("**mem****", "推荐", "使用", "申请", "pod名称", "deployment名称")
for podInfo in podsInfo[1].split('\n'):
    pod = re.findall(r"[^\s]\S+", podInfo)
    reqInfo = findReq(pod[0])
    reqCpu = getNum(reqInfo[1])
    reqMem = getNum(reqInfo[2])
    usedCpu = getNum(pod[1])
    usedMem = getNum(pod[2])
    # if usedMem > reqMem:
    newMem = (math.ceil(usedMem / 100)) * 100
    if newMem <= 0:
        newMem = 100
    if usedMem <= 20:
        newMem = 20
    print("**mem****", newMem, usedMem, reqMem, pod[0], reqInfo[0])
    # print(
    #     'kubectl patch deploy '+reqInfo[0]+' -p "{\\\"spec\\\":{\\\"template\\\":{\\\"spec\\\":{\\\"containers\\\":[{\\\"name\\\":\\\"'+reqInfo[0] +
    #     '\\\",\\\"resources\\\":{\\\"requests\\\":{\\\"memory\\\":\\\"' +
    #     str(newMem)+'Mi\\\"},\\\"limits\\\":{\\\"memory\\\":\\\"2Gi\\\"}}}]}}}}"')
    # if usedCpu > reqCpu:
    # print("--cpu----", (math.ceil(usedCpu/10)) *
    #       10, usedCpu, reqCpu, pod[0], reqInfo[0])
    # print(pod[0], reqInfo[0], reqCpu, usedCpu, reqMem, usedMem)
Ejemplo n.º 13
0
pagetitle = ""
title = ""
xlabel = ""
ylabel = ""
color = None
legend = -1
name = None

for page in plot_cmds:
    # print "Plotting " + str(page)

    num_plots = len(page)

    print("This figure has " + str(num_plots) + " plots")

    num_cols = math.trunc(math.ceil(math.sqrt(num_plots)))
    num_rows = math.trunc(math.ceil(num_plots * 1.0 / num_cols))

    print("This figure will be " + str(num_rows) + "x" + str(num_cols))

    fig = plt.figure()
    fig.subplots_adjust(top=0.85)
    fig.subplots_adjust(bottom=0.15)

    row = 1
    col = 1
    plot_num = 1

    for plot in page:
        # print "  Plotting " + str(plot)
Ejemplo n.º 14
0
 def draw(self, surface, image):
     surface.blit(image,(self.x,self.y*self.step))
     for i in range(1,int(math.ceil(self.length /2))):
         surface.blit(image,(self.x + 1.5*i*self.step,self.y*self.step))
         surface.blit(image,(self.x - 1.5*i*self.step,self.y*self.step))
'''
Created on Oct 8, 2016

Desc : Sequential Search 

@author: Ajay
'''
from numpy import random, math

dataArray = range(3, 100, 3)
key = math.ceil(random.random() * 10)


def searchInArray(key, dataArray):
    for i in dataArray:
        if i == key:
            return True
    return False


print()

if __name__ == '__main__':
    print("Search Space ", dataArray)
    print("key", key)
    print("found key = ", searchInArray(key, dataArray))
    print("found key = ", searchInArray(3, dataArray))
    print("found key = ", searchInArray(4, dataArray))
    pass
Ejemplo n.º 16
0
def _NeRegressionGraphCalc(dataVctrs, expectedSlope = None, popTable = None):
    #get linear regression stats for all datasets
    LineStats = []
    for line in list(dataVctrs.values()):
        data = line_regress(line)
        LineStats.append(data)
    #flatten the array
    all_points = [val for sublist in list(dataVctrs.values())  for val in sublist]
    #unzip to obtain x and y value vectors for all points
    xVals, yVals = list(zip(*all_points))

    minX = min(xVals)
    maxX = max(xVals)+1
    xVctr = list(set(all_points))
    if maxX - minX>1:

        xVctr = list(range(int(math.floor(minX)),int(math.ceil(maxX))))

    lineVctrs =[]
    colorVctr = []
    styleVctr = []

    #creates expected slope line for comparisons
    if expectedSlope:
        expectedPoints = []
        if expectedSlope == "pop":
            if popTable:
                averagePopPoints = []
                all_points = [val for sublist in popTable for val in popTable[sublist]]
                xVals, yVals = list(zip(*all_points))
                xSet = set(xVals)
                for x in xSet:
                    pointYSet = [point[1] for point in all_points if point[0] == x]
                    averageY = mean(pointYSet)
                    averagePopPoints.append((x,averageY))
            expectedPoints = averagePopPoints
        else:
            #get all slope and intercept values to get means
            slopes = []
            intercepts = []
            for statDict in LineStats:
                slopes.append(statDict["slope"])
                intercepts.append(statDict["intercept"])

            #get expected line Stats
            expectedSlope,expectedIntercept = _getExpectedLineStats(slopes, intercepts, xVctr,expectedSlope)
            expectedPoints = _getGraphLine(expectedSlope, expectedIntercept, xVctr)


        #make expected line for plotting
        if len(expectedPoints)>0:
            lineVctrs.append(expectedPoints)
            colorVctr.append("r")
            styleVctr.append("-")

    for statDict in LineStats:
        slope = statDict["slope"]
        intercept = statDict["intercept"]
        if not isnan(slope):
            linePoints  = _getGraphLine(slope, intercept, xVctr)
            lineVctrs.append(linePoints)
            colorVctr.append("b")
            styleVctr.append("--")
    return lineVctrs, colorVctr,styleVctr