Example #1
0
 def __init__(self, dataStr):
     self.curves = []
     if not re.match(r"^[Mm]", dataStr):
         raise "no start point"
     _ds = re.sub(r"([Mm])", r"\1:", dataStr)
     _ds = re.sub(r"([LHVCSQTAZlhvcsqtaz])", r";\1:", _ds)
     _ds = re.sub(r"-", r",-", _ds)
     _ds = re.sub(r"([:,]),", r"\1", _ds)
     for c in _ds.split(";"):
         _dt = c.split(":")
         if len(_dt) < 2:
             break
         _command = re.sub(r"\s", "", _dt[0])
         _ss = re.sub("-", ",-", _dt[1])
         _ss = re.sub("\s", ",", _ss)
         _ss = re.sub(r"^[,]+", '', _ss)
         _ss = re.sub(r"[,]+", ',', _ss)
         _ps = _ss.split(",")
         
         if 'M' == _command or 'm' == _command:
             _obj = point(_ps[0], _ps[1])
         elif 'L' == _command:
             _obj = line(_obj.end, point(_ps[0], _ps[1]))
         elif 'l' == _command:
             _obj = line(_obj.end, _obj.end.move(_ps[0], _ps[1]))
         elif 'H' == _command:
             _obj = line(_obj.end, point(_ps[0], _obj.end.y))
         elif 'h' == _command:
             _obj = line(_obj.end, _obj.end.move(_ps[0], 0))
         elif 'V' == _command:
             _obj = line(_obj.end, point(_obj.end.x, _ps[1]))
         elif 'v' == _command:
             _obj = line(_obj.end, _obj.end.move(0, _ps[1]))
         elif 'C' == _command:
             _obj = curve(_obj.end, point(_ps[0], _ps[1]), point(_ps[2], _ps[3]), point(_ps[4], _ps[5]))
         elif 'c' == _command:
             _obj = curve(_obj.end, _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]), _obj.end.move(_ps[4], _ps[5]))
         elif 'S' == _command:
             _obj = curve(_obj.end, _obj.refCon(), point(_ps[0], _ps[1]), point(_ps[2], _ps[3]))
         elif 's' == _command:
             _obj = curve(_obj.end, _obj.refCon(), _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]))
         elif 'Q' == _command:
             _obj = qcurve(_obj.end, point(_ps[0], _ps[1]), point(_ps[2], _ps[3]))
         elif 'q' == _command:
             _obj = qcurve(_obj.end, _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]))
         elif 'T' == _command:
             _obj = qcurve(_obj.end, _obj.refCon(), point(_ps[0], _ps[1]))
         elif 't' == _command:
             _obj = qcurve(_obj.end, _obj.refCon(), _obj.end.move(_ps[0], _ps[1]))
         elif 'A' == _command:
             ''
         else: break
         
         
         self.curves.append(_obj)
Example #2
0
 def click_curve(self):
     self.check_click()
     print('click curve')
     self.do_curve += 1
     if (self.do_curve == 1):
         self.click_vec = []
     if (self.do_curve == 2):
         curve_id = self.graphic_id
         max_id = 0
         for i in self.graphics:
             max_id = max(max_id, i.graphic_id)
         self.graphic_id = max_id + 1
         algorithm = 'B-spline'
         print(self.click_vec, self.R, self.G, self.B)
         new_curve = curve.curve(self.canvas_image, curve_id,
                                 self.canvas_width, self.canvas_height,
                                 self.R, self.G, self.B)
         xy_vec = []
         for i in range(len(self.click_vec)):
             xy_vec.append(self.click_vec[i][0])
             xy_vec.append(self.click_vec[i][1])
         print(xy_vec)
         new_curve.draw_curve(xy_vec, algorithm)
         self.do_curve = 0
         self.graphics.append(new_curve)
         self.refresh()
         self.click_vec = []
         self.text2.setText('曲线绘制完毕,点击的所有点为\n' + self.last_click_info)
         return
     self.text2.setText('开始绘制曲线')
Example #3
0
 def append(self, obj):
     if isinstance(obj, curve.curve):
         if obj:
             if obj.filename in self.locations:
                 logging.warn(
                     'Curve {0} is already in the experiment. File NOT appended'
                     .format(obj.filename))
                 return False
             elif obj.basename in self.basenames:
                 logging.error(
                     'Curve with basename {0} is already in the experiment. File NOT appended'
                     .format(obj.basename))
                 return False
             else:
                 self.curves.append(obj)
                 self.locations.append(obj.filename)
                 self.basenames.append(obj.basename)
                 return True
         else:
             logging.warn(
                 'Curve {0} is NOT relevant to the experiment or broken. Curve NOT appended'
             )
             return False
     else:
         return self.append(curve.curve(obj))
Example #4
0
    def curve25519(self, n, q):
        """
        `n` is the private key. It is at least 2**254 and a multiple 
        of 8. It is the scalar which with we want to multiply.
        `q` is the x of point Q. The point Q is the point we want to
        multiply. `q` is an element of the field over `p`.
        Returns `s`, which is the x of `n` * `Q`
        """

        assert len(n) == 32
        assert len(q) == 32

        n = little_endian().from_string(n)
        assert n >= pow(2, 254)
        assert n % 8 == 0

        q = little_endian().from_string(q)

        curve25519 = curve(486662, pow(2, 255) - 19)
        (Q0, Q1) = curve25519.points(q)
        nQ = curve25519.multiply(Q0, n)
        assert nQ[0] == curve25519.multiply(Q1, n)[0]

        s = nQ[0]
        return little_endian().to_string(s)
Example #5
0
 def draw_curve(self,res_cmd):
     curve_id=int(res_cmd[0])
     curve_id=int(res_cmd[0])
     n=int(res_cmd[1])
     algorithm=res_cmd[2]
     xy_vec=res_cmd[3:]
     new_curve= curve.curve(self.canvas_image,curve_id,self.canvas_width,self.canvas_height,self.R,self.G,self.B)  
     new_curve.draw_curve(xy_vec,algorithm)
     self.graphics.append(new_curve)
Example #6
0
    def __init__(self, location, **kwargs):
        if isinstance(location, crv.Curve):
            self._location = crv.curve(location, **kwargs)
        else:
            try:
                location = np.array(location)
                self._location = crv.FixedPoint(location)
            except TypeError:
                raise TypeError(errfmt("""\
                `location` must either be array-like or a curve."""))

        self._cur_location = self._location.startpos
        self._cur_coord_sys = self._location.start_coord_sys
Example #7
0
 def __init__(self, curve_string='NIST K-163'):
     if curve_string == 'NIST K-163':
         p = 0x800000000000000000000000000000000000000C9  #t^163 + t^7 + t^6 + t^3 + 1
         a = 1
         G_x = 0x2fe13c0537bbc11acaa07d793de4e6d5e5c94eee8
         G_y = 0x289070fb05d38ff58321f2e800536d538ccdaa3d9
         G = 0x0402fe13c0537bbc11acaa07d793de4e6d5e5c94eee80289070fb05d38ff58321f2e800536d538ccdaa3d9
         n = 5846006549323611672814741753598448348329118574063
         h = 2
         self.curve = curve.curve(A=a,
                                  B=1,
                                  Polynomial=p,
                                  Generator=G,
                                  Order=n)
         self.Order = n
         self.nfield = field.nfield(n)
Example #8
0
 def append(self,obj):
     if isinstance(obj,curve.curve):
         if obj:
             if obj.filename in self.locations:
                 logging.warn('Curve {0} is already in the experiment. File NOT appended'.format(obj.filename))
                 return False
             elif obj.basename in self.basenames:
                 logging.error('Curve with basename {0} is already in the experiment. File NOT appended'.format(obj.basename))
                 return False
             else:
                 self.curves.append(obj)
                 self.locations.append(obj.filename)
                 self.basenames.append(obj.basename)
                 return True
         else:
             logging.warn('Curve {0} is NOT relevant to the experiment or broken. Curve NOT appended')
             return False
     else:
         return self.append(curve.curve(obj))
Example #9
0
 def test_constructor(self):
     """
     Constructor test 1
     """
     cupdir = "cup_geometry"     
     radUnit  = "8"
     outerCup = "2"
     innerCupSer = "M"
     innerCupNum = "01"
 
     fname  = TestCupCurve.make_cup_name(radUnit, outerCup, innerCupSer, innerCupNum)
     fname += "_" + "KddCurveA.txt"
     filename = os.path.join(cupdir, fname)
     
     print(filename)
 
     cup = curve.curve(filename)
     
     self.assertTrue(cup.curve() != None)
Example #10
0
def make_shots_list(radUnit, outerCup, innerCupSer, innerCupNum, x_range, y_range, z_range, shstep, shmargin):
    """
    Given rad.unit, outer cup, inner cup, ranges, step size and margin,
    produce list of shots for a given conditions
    """
    
    cup_dir = "/home/beamuser/Documents/EGS/CUPS"
    
    file_prefix = clinical.make_cup_name(radUnit, outerCup, innerCupSer, innerCupNum)
    
    cupA_fname = os.path.join( cup_dir, file_prefix + "_" + "KddCurveA.txt")
    #print(cupA_fname)
    cupA = cc.curve( cupA_fname )
    
    liA = linint.linint(cupA)
    
    z_max = liA.zmax()
    
    ny_min = int(y_range[0] / shstep) - 1
    ny_max = int(y_range[1] / shstep) + 1
    #print(ny_min, ny_max)
    
    nz_min = int(z_range[0] / shstep) - 1
    nz_max = int(z_max / shstep) + 1
    #print(nz_min, nz_max)
    
    shots = []
    for iy in range(ny_min, ny_max):
        y = shstep * float(iy)
        if y < 0.0:
            continue
        for iz in range(nz_min, nz_max):
            z = shstep * float(iz)
            if z < 0.0:
                continue
            
            r = liA.extrapolate(z)
            
            if y < r: # we're inside the inner cup
                shot = (y, z)
                shots.append(shot)
                
    return shots
Example #11
0
    def findonlycolors(self):
        graphColor = []
        midpoint=(self.x2+self.x4)/2
        cropped = self.rectangle[self.y4:self.x2, midpoint-50:midpoint+50]
        cv2.imwrite("images/colors.jpg" , cropped)
        imge = cv2.imread("images/colors.jpg",1)
        #imge = cv2.fastNlMeansDenoisingColored(imge,None,10,10,7,21) 
        #imge = cv2.cvtColor(imge, cv2.COLOR_BGR2RGB)
        

        imge = imge.reshape((imge.shape[0] * imge.shape[1], 3))
        n_clusters = 3                                                 #number of clusters in kmeans clustering
        clt = KMeans(n_clusters = 8)
        clt.fit(imge)
        hist = centroid_histogram(clt)
        bar,color = plot_colors_only(hist, n_clusters, clt.cluster_centers_)   #returns all the colors present in the given image "colors.jpg"
        # bar = cv2.cvtColor(bar,cv2.COLOR_GRAY2RGB) 
         # show our color bart
        # plt.figure()
        # plt.axis()
        # plt.imshow(bar)
        # plt.show()


        # color = list(rgb2hsv(color[0],color[1],color[2]))
        #color[1] = color[1]                                      #increasing the picture saturation and value of the image
        #color[2] = color[2]                                       #which got reduced due to processing
        #color = hsv2rgb(color[0],color[1],color[2])     
        print color                                               #list of colors of all the plots in the graph image
        print "len=%d"%(len(color))
        for var in range(0,len(color)):
            # if color[var][0]>240 and color[var][1]>240 and color[var][2]>240:
            #     color[var][0] = 10.00
            #     color[var][1] = 10.00
            #     color[var][2] = 10.00
            c = curve(color[var],"curve"+str(var),var,self.graphID,self.pageno,self.document.docid)
            self.curveList.append(c)
            print color[var]
Example #12
0
 def shared_secret(self, other):
     if not isinstance(other, DHKey):
         raise TypeError("Argument must be a DHKey instance")
     return curve(self.seckey, other.pubkey)
Example #13
0
 def __convertNTC_10K_3V3(self, rawValue):
     vout = float(rawValue) / 1023 * 3.3
     r1_r2 = vout / (3.3 - vout)
     ntc = r1_r2 * 10000
     cc = curve.curve("ntc.10kz.curve.csv")
     return (cc.find_temp(ntc), 'degreesCelsius')
Example #14
0
    def findColorNnumOfPlots(self):
        if self.istextbox==True:
            for i in range(len(self.textBoxImages)):
                #flag=0
                s='images/temp_textbox.png'
                try:
                    img = Image(s,0)

                except:
                    continue     
                img_inv = img.invert()
                img_inv.scale(100,100)
                img_bin = img_inv.binarize()
                
                #elif flag!=1:
                img_bin.save("images/rot_1.png")

                img = cv2.imread("images/rot_1.png") 
                dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21) 
                
                graphs = image_to_string(IMAGE.fromarray(dst),lang='eng')
                graphs = graphs.replace("\n",">%$ ")                               #formatting the string to get the list 
                graphs = graphs.split(">%$ ")                                      #of plots plotted in given graphs                               
                print "the plots in graph are"
                print graphs
                graphNamesList=graphs
                n=len(graphs)                                                      #number of plots in given graph
                img = Image(s,0)
                img = img.resize(img.width*3,img.height*3)                         #resizing the image to make it big enough for cropping
                #print height
                #img = img.crop(15,15,img.width,img.height)                   #removing the edges of the given graph description image
                try:
                    height = (img.height)*1.0/n
                except ZeroDivisionError:
                    continue
                width = img.width 
                graphList=[]
                start = 0
                for i in range(0,n):                                               #cropping the image so as to get a single plot description 
                    cropImg = img.crop(0, start, width, height)                   #in one image
                    graphList.append(cropImg)
                    start+=height
                
                graphList1 = graphList    
               
                
                graphColor = []
                for i in graphList:                                                #finding colors of plots of all the images cropped above
                    i.save("images/temp.png")    
                    #raw_input()
                    imge = cv2.imread("images/temp.png",1)
                    kernel = np.ones((5,5),np.uint8)
                    #imge = cv2.erode(imge,kernel,iterations=3)
                    cv2.imwrite("aman.jpg",imge)
                    imge = cv2.fastNlMeansDenoisingColored(imge,None,10,10,7,21) 
                    imge = cv2.cvtColor(imge, cv2.COLOR_BGR2RGB)
                
                    imge = imge.reshape((imge.shape[0] * imge.shape[1], 3))
                    n_clusters = 3                                                 #number of clusters in kmeans clustering
                    clt = KMeans(n_clusters = 3)
                    clt.fit(imge)
                    hist = centroid_histogram(clt)
                    bar,color = plot_colors(hist, n_clusters, clt.cluster_centers_)
                  
                    
                    print color
                    if color[0]>240 and color[1]>240 and color[2]>240:             
                        color = [10.00, 10.00, 10.00]
                    
                    #color = list(rgb2hsv(color[0],color[1],color[2]))
                    
                    graphColor.append(color)                                    
                    
                    
                for i in range(0,len(graphColor)):
                    c = curve(graphColor[i],graphNamesList[i],i,self.graphID,self.pageno,self.document.docid)
                    print "found curve"
                     
                    self.curveList.append(c)
                
                print graphNamesList
                print graphColor
                print self.curveList

        else:
            pass
Example #15
0
 def __convertNTC_10K_3V3(self, rawValue):
         vout = float(rawValue) / 1023 * 3.3
         r1_r2 = vout/(3.3-vout)
         ntc = r1_r2 * 10000
         cc = curve.curve("ntc.10kz.curve.csv")
         return (cc.find_temp(ntc), 'degreesCelsius')
Example #16
0
import curve
import warnings
warnings.filterwarnings("ignore")
arr = input("Input data x:")
x = [float(n) for n in arr.split()]
arr = input("Input data y:")
y = [float(n) for n in arr.split()]
x_label = input("Input the label of axis x(enter for no label):")
y_label = input("Input the label of axis y(enter for no label):")
title = input("Input the title of the graph(enter for no title):")
curve.curve(x, y, x_label, y_label, title)
            dt = distance(pts[n], pts[n + 1])
        except IndexError:
            dt = distance(pts[0], pts[-1])
        coefs += dt * exp(complex(0, -k * t * 2 * pi / T)) * complex(pts[n][0], pts[n][1])
        n += 1
        t += dt
    return coefs / T


if __name__ == '__main__':
    nb_cercles = 50
    rayon_minimal = 0
    path = 'ens.png'

    print("Détection d'un bord et des coordonnés de la courbe.")
    pts = curve(edge(path))

    print("Séparation des x et y.")
    ptsx = [pt[0] for pt in pts]
    ptsy = [pt[1] for pt in pts]

    print("Calcul de la période.")
    T = periode(pts)

    print("Échantillonage des ts.")
    p = 1  # précision
    ts = [t / p for t in range(ceil(T * p) + 1)]

    print("Calcul des affixes des pts de la série de fourier complexe de la courbe.")
    zs = fourier_iter(ts, pts, T, N=nb_cercles, p=rayon_minimal)