コード例 #1
0
def eq2gal(ra, dec):

    rmat = numpy.array(
        [
            [-0.054875539726, -0.873437108010, -0.483834985808],
            [+0.494109453312, -0.444829589425, +0.746982251810],
            [-0.867666135858, -0.198076386122, +0.455983795705],
        ],
        dtype="d",
    )
    cosb = math.cos(dec)
    v1 = numpy.array([math.cos(ra) * cosb, math.sin(ra) * cosb, math.sin(dec)])
    v2 = numpy.dot(rmat, v1)
    x = v2[0]
    y = v2[1]
    z = v2[2]
    r = math.sqrt(x * x + y * y)
    if r == 0.0:
        l = 0.0
    else:
        l = math.atan2(y, x)
    if z == 0.0:
        b = 0.0
    else:
        b = math.atan2(z, r)
    ll = math.fmod(l, 2.0 * math.pi)
    if ll < 0.0:
        ll = ll + 2.0 * math.pi

    bb = math.fmod(b, 2 * math.pi)
    if abs(bb) >= math.pi:
        print "Ugh!"

    return ll, bb
コード例 #2
0
ファイル: slice.py プロジェクト: WikimapsAtlas/make-modules
def slice_linear(zmin, zmax, n, scale=None):
    """The size of result is (n-1)."""
    COMBS = [
        None,  # not used
        (0, ),
        (0, 5, ),
        (0, 3, 7, ),
        (0, 3, 5, 7, ),
        (0, 2, 4, 6, 8, ),
        (0, 2, 3, 5, 7, 8, ),
        (0, 1, 3, 4, 6, 7, 9, ),
        (0, 1, 3, 4, 5, 6, 7, 9, ),
        (0, 1, 2, 3, 4, 6, 7, 8, 9, ),
        (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ),
    ]
    if scale is None:
        scale = 10 * ceil_pow10((zmax - zmin) / n)
    step = scale // 10
    def generate(comb, bases):
        if comb is None:
            return []
        result = [base + _ * step for base in bases for _ in comb]
        return [_ for _ in result if zmin < _ < zmax]
    zmin_floored = math.floor(zmin - math.fmod(zmin, scale))  # XXX: these might be numerically unstable
    zmax_ceiled = math.ceil(zmax - math.fmod(zmax, scale))
    multiples = list(range(zmin_floored, zmax_ceiled + scale, scale))
    multiples = [_ for _ in multiples if zmin < _ < zmax]
    if len(multiples) == 0:
        k = (zmax_ceiled - zmin_floored) // step
        if k == 0:
            return slice_linear(zmin, zmax, n, scale=(scale // 10))
        result = generate(COMBS[k], [zmin_floored])
        # TODO: compensate len(result) to be == (n - 1)
        return result
    k = n // len(multiples)
    if k <= 0:
        return []
    if k > 10:
        return slice_linear(zmin, zmax, n, scale=(scale // 10))
    result_body = generate(COMBS[k], multiples[:-1])
    result_head = []
    result_tail = []
    # len(result_head + result_body + result_tail) should be == (n - 1)
    len_needed = (n - 1) - len(result_body)
    assert len_needed >= 0
    head_length = len_needed // 2
    tail_length = (len_needed + 1) // 2
    for comb in COMBS[:(k + 1)]:
        candidate = generate(comb, [multiples[0] - scale])
        if len(candidate) == head_length:
            result_head = candidate
        candidate = generate(comb, [multiples[-1]])
        if len(candidate) == tail_length:
            result_tail = candidate
    result = result_head + result_body + result_tail
    if len(result) != (n - 1):
        # n is too large  (e.g. zmin = 10, zmax = 1000, n = 50)
        # Once again, do the linear slicing instead
        return slice_linear(zmin, zmax, n, scale=(scale // 10))
    return result
コード例 #3
0
def _rotate_hcline(obj, objdict, cx, cy, ra):
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "HCLine parent is None"
    _lp = obj.getLocation()
    if _lp.getParent() is not _layer:
        raise RuntimeError, "HCLine/Point parent object conflict!"
    _x, _y = _calc_coords(_lp, cx, cy, ra)
    _pts = _layer.find('point', _x, _y)
    if len(_pts) == 0:
        _np = Point(_x, _y)
        _layer.addObject(_np)
    else:
        _np = _most_used(_pts)
    _da = ra/_dtr
    if abs(fmod(_da, 180.0)) < 1e-10:
        obj.setLocation(_np)
        if _adjust_dimension(_lp, _np):
            _layer.delObject(_lp)
    elif abs(fmod(_da, 90.0)) < 1e-10:
        _layer.addObject(VCLine(_np))
        if _adjust_dimension(_lp, _np):
            _layer.delObject(obj)
    else:
        _layer.addObject(ACLine(_np, _da))
        _layer.delObject(obj)
    _pid = id(_lp)
    if objdict.get(_pid) is not False:
        objdict[_pid] = False
コード例 #4
0
    def pattern(self):
        self.trap.send_decay(ALL, 90)
        self.trap.start_pattern(ALL)

        index = 0
        hue_offset = 0.0
        stop = False

        color_rings = [ random_color(), random_color(), random_color() , random_color() ]
        while not stop:
            for bottle, angle in self.geo.enumerate_all_bottles(index % 2 == 0):
                self.trap.set_color(bottle, color_rings[self.geo.get_ring_from_bottle(bottle)])
                sleep(.01)
                if self.stop_thread:
                    stop = True
                    break

            index += 1
            hue_offset = math.fmod(hue_offset + .02, 1.0)
            shift = math.sin(index / self.color_shift_between_rings) / 2.0 + .50
            new_offset = math.fmod(shift, 1.0)
            color_rings.pop()
            color_rings.insert(0, hue_to_color(new_offset))

        self.trap.stop_pattern(ALL)
        if self.transition:
            sleep(.02)
            transition_sweep_out(self.trap)
コード例 #5
0
ファイル: colorv.py プロジェクト: autowitch/dot_files
def draw_palette(H,height,width): 

    H = fmod(H,360) if H >= 360 else 360+fmod(H,360) if H < 0 else H
    name = "_".join([str(H),str(height),str(width)])
    if name not in lookup: 
        p2=[]
        V_step = 100.0/height
        S_step = 100.0/width
        for row in range(height):
            V = 100 - V_step * row
            if V<=0 : V = 1
            l=[]
            for col in range(width):
                S = 100 - S_step * col
                if S<=0 : S = 1
                hex = rgb2hex(hsv2rgb([H,S,V]))
                l.append(hex)
            p2.append(l)
        lookup[name] = p2        # obmit coping as 
                                 # the list ref will not be changed
                                 # when we use [] to creat a new one
    else:
        p2 = lookup[name]
    
    vcmd("call s:clear_match('pal')")
    for row  in range(height):
        for col in range(width):
            hex = p2[row][col]
            hi_grp  = "".join(["cv_pal_",str(row),"_",str(col)])
            pos_ptn = "".join(["\\%",str(row+H_OFF+1),"l\\%"
                                    ,str(col+W_OFF+1),"c"])
            vcmd("call s:hi_color('{}','{}','{}',' ')".format(hi_grp,hex,hex))
            vcmd("sil! let s:pal_dict['{0}'] = matchadd('{0}','{1}')"
                    .format( hi_grp,pos_ptn))
    vcmd("".join(["let s:pal_clr_list=",str(p2)]))
コード例 #6
0
ファイル: sig.py プロジェクト: haraisao/sigclient_py
  def differentialWheelsSetSpeed(self, obj, left, right):
    if self.leftWheelMaxSpeed < left :
      left = self.leftWheelMaxSpeed
    elif left < -self.leftWheelMaxSpeed :
      left = -self.leftWheelMaxSpeed

    if self.leftWheelSpeedUnit > self.Accueacy :
      radiuse = math.fmod(math.fabs(left), self.leftWheelSpeedUnit)
      if  left > 0:
        left -= radiuse
      else:
        left += radiuse
      
    if self.rightWheelMaxSpeed < left :
      left = self.rightWheelMaxSpeed
    elif left < -self.rightWheelMaxSpeed :
      left = -self.rightWheelMaxSpeed

    if self.rightWheelSpeedUnit > self.Accueacy :
      radiuse = math.fmod(math.fabs(left), self.rightWheelSpeedUnit)
      if  right > 0:
        right -= radiuse
      else:
        right += radiuse
      
   
    if  self.leftWheelName:
      obj.setAngularVelocityToParts(self.leftWheelName, left, self.leftMaxForce)
      self.currentLeftWheelSpeed = left

    if  self.rightWheelName:
      obj.setAngularVelocityToParts(self.rightWheelName, right, self.rightMaxForce)
      self.currentRightWheelSpeed = right

    return 
コード例 #7
0
def pCJDNToMilankovic(iCJDN, bDoYear=False, bDoMonth=False, bDoDay=False):
    ''' Returns a Revised Julian date is ISO 8601 YYYY-MM-DD format from a given
        Chronological Julian Day Number (CJDN).
        If only part of the date is required (e.g. just the day), this is returned as an integer.
    '''

    if not isinstance(iCJDN, int):
        return False

    #Perform the calculation
    iK3 = (9 * (iCJDN - 1721120)) + 2
    iX3 = floor(iK3 / 328718)
    iK2 = (100 * floor(int(fmod(iK3, 328718)) / 9)) + 99
    iX2 = floor(iK2 / 36525)
    iK1 = (5 * floor(int(fmod(iK2, 36525)) / 100)) + 2
    iX1 = floor(iK1 / 153)
    iC0 = floor((iX1 + 2) / 12)
    iYear = (100 * iX3) + iX2 + iC0
    iMonth = (iX1 - (12 * iC0)) + 3
    iDay = floor(int(fmod(iK1, 153)) / 5) + 1

    #Return integer part, if only one part of the date is required.
    #Start at year, and rudely ignore any subsequent integers requested.
    if bDoYear:
        return iYear
    if bDoMonth:
        return iMonth
    if bDoDay:
        return iDay

    #Return the ISO 8601 date string
    sISO8601Date = ('0000' + str(iYear))[-4:] + '-' + ('00' + str(iMonth))[-2:] + '-' + ('00' + str(iDay))[-2:]
    return sISO8601Date
コード例 #8
0
ファイル: drift_estimation.py プロジェクト: fqez/kobuki_test
def wrap_angle(angle):
    if angle <= math.pi and angle >= -math.pi:
        return angle
    elif angle < 0.0:
        return math.fmod(angle-math.pi,2.0*math.pi)+math.pi
    else:
        return math.fmod(angle+math.pi,2.0*math.pi)-math.pi;
コード例 #9
0
    def complementaries(self, base_color):
        # return some other colors that "go" with this one
        hsv = RGBtoHSV(base_color)

        (h,s,v,a) = hsv
        
        # take 2 colors which are almost triads
        h = hsv[0]
        delta = random.gauss(0.0, 0.8)
        h2 = math.fmod(h + 2.5 + delta, 6.0)
        h3 = math.fmod(h + 3.5 - delta, 6.0)

        # take darker and lighter versions
        v = hsv[2]
        vlight = self.clamp(v * 1.5, 0.0, 1.0)
        vdark = v * 0.5

        colors = [
            [h, s, vdark, a],
            [h, s, v, a],
            [h, s, vlight, a],
            [h2, s, vlight, a],
            [h2, s, v, a],
            [h2, s, vdark, a],
            [h3, s, vdark, a],
            [h3, s, v, a],
            [h3, s, vlight, a]]

        colors = [ HSVtoRGB(x) for x in colors]
        return colors
コード例 #10
0
ファイル: s3datetime.py プロジェクト: jfmnet/eden
    def from_jd(cls, jd):
        """
            Convert a Julian day number to a year/month/day tuple
            of this calendar (matching jQuery calendars algorithm)

            @param jd: the Julian day number
        """

        jd = math.floor(jd) + 0.5;

        depoch = jd - cls.to_jd(475, 1, 1)

        cycle = math.floor(depoch / 1029983)
        cyear = math.fmod(depoch, 1029983)

        if cyear != 1029982:
            aux1 = math.floor(cyear / 366)
            aux2 = math.fmod(cyear, 366)
            ycycle = math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1
        else:
            ycycle = 2820

        year = ycycle + (2820 * cycle) + 474
        if year <= 0:
            year -= 1

        yday = jd - cls.to_jd(year, 1, 1) + 1
        if yday <= 186:
            month = math.ceil(yday / 31)
        else:
            month = math.ceil((yday - 6) / 30)

        day = jd - cls.to_jd(year, month, 1) + 1

        return (int(year), int(month), int(day))
コード例 #11
0
def pCJDNToJulian(iCJDN, bDoYear=False, bDoMonth=False, bDoDay=False):
    ''' Returns a Julian date is ISO 8601 YYYY-MM-DD format from a given
        Chronological Julian Day Number (CJDN).
        If only part of the date is required (e.g. just the day), this is returned as an integer.
    '''

    if not isinstance(iCJDN, int):
        return False

    #Perform the calculation
    iY2 = iCJDN - 1721118
    iK2 = (4 * iY2) + 3
    iK1 = (5 * floor(int(fmod(iK2, 1461)) / 4)) + 2
    iX1 = floor(iK1 / 153)
    iC0 = floor((iX1 + 2) / 12)
    iYear = floor(iK2 / 1461) + iC0
    iMonth = (iX1 - (12 * iC0)) + 3
    iDay = floor(int(fmod(iK1, 153)) / 5) + 1

    #Return integer part, if only one part of the date is required.
    #Start at year, and rudely ignore any subsequent integers requested.
    if bDoYear:
        return iYear
    if bDoMonth:
        return iMonth
    if bDoDay:
        return iDay

    #Return the ISO 8601 date string
    sISO8601Date = ('0000' + str(iYear))[-4:] + '-' + ('00' + str(iMonth))[-2:] + '-' + ('00' + str(iDay))[-2:]
    return sISO8601Date
コード例 #12
0
ファイル: VRayProxy.py プロジェクト: bdancer/vray_tools
    def getFrameByType(self, animType, animOffset, speed, frame):
        def clamp(value, value_min, value_max):
            return max(min(value, value_max), value_min)

        animLength = len(self.frames)
        animStart  = 0

        if animType in {'0', 'LOOP'}:
            frame = fmod(animOffset+(frame-animStart)*speed, animLength)
            if frame < 0:
                frame += animLength
            frame += animStart

        elif animType in {'1', 'ONCE'}:
            frame = clamp(animOffset+(frame-animStart)*speed, 0.0, animLength-1)+animStart

        elif animType in {'2', 'PINGPONG'}:
            frame = fmod(animOffset+(frame-animStart)*speed, animLength*2-2) # subtract 2 to remove the duplicate frames
            if frame < 0:
                frame += 2*animLength-2
            if frame >= animLength:
                frame = 2*animLength-2-frame
            frame += animStart*speed

        elif animType in {'3', 'STILL'}:
            frame = clamp(animOffset+animStart, 0.0, animLength-1.0)

        return int(frame)
コード例 #13
0
ファイル: rotate.py プロジェクト: chrisbura/pythoncad-legacy
def _adjust_point_users(pt, objdict, da):
    _layer = pt.getParent()
    for _user in pt.getUsers():
        _uid = id(_user)
        if _uid in objdict:
            if isinstance(_user, HCLine) and _layer is not None:
                if abs(fmod(da, 180.0)) < 1e-10:
                    objdict[_uid] = False
                elif abs(fmod(da, 90.0)) < 1e-10:
                    _layer.addObject(VCLine(pt))
                    _layer.delObject(_user)
                    del objdict[_uid]
                else:
                    _layer.addObject(ACLine(pt, da))
                    _layer.delObject(_user)
                    del objdict[_uid]
            elif isinstance(_user, VCLine) and _layer is not None:
                if abs(fmod(da, 180.0)) < 1e-10:
                    objdict[_uid] = False
                elif abs(fmod(da, 90.0)) < 1e-10:
                    _layer.addObject(HCLine(pt))
                    _layer.delObject(_user)
                    del objdict[_uid]
                else:
                    _layer.addObject(ACLine(pt, da))
                    _layer.delObject(_user)
                    del objdict[_uid]
            elif isinstance(_user, ACLine) and _layer is not None:
                _user.setAngle(_user.getAngle() + da)
                objdict[_uid] = False
            else:
                if not isinstance(_user, Dimension):
                    objdict[_uid] = False
コード例 #14
0
ファイル: main.py プロジェクト: steve3003/pmgai-minecraft
    def get_block(self, x, z, y):
        """For any point in the map, return the type of block at that location.
        
        y (int) represents altitude, positive is up and negative is down.
        x and z (int) are the lattitude and logitude in the map. 
        """ 

        # Add simple noise to the coordinates to make it less rigid!
        nx = x + 2*math.sin(z/4.7)
        nz = z + 2*math.cos(x/5.9)
        ny = y + math.sin(0.75 + x/7.8 + z/9.1)

        nx = math.fmod(nx, 60)
        nz = math.fmod(nz, 60)
        ny = ny*8
        # Manhattan distance field to center of map: floating iceberg.
        if math.sqrt(nx*nx + ny*ny + nz*nz) < 17:
            return c.MAT_DIRT

        # Anything that's not solid but under the sea level?
        if y == -1:
            return c.MAT_SNOW
        if y < -1:
            return c.MAT_WATER

        return c.MAT_AIR
コード例 #15
0
ファイル: ex_ephem.py プロジェクト: nirinA/erfa_python
 def __init__(self, utc, longitude, latitude, altitude):
     try:
         super().__init__(longitude, latitude, altitude)
     except TypeError:
         super(TimeScale, self).__init__(longitude, latitude, altitude)
     self.utc = utc
     self.utc1, self.utc2 = strputc(self.utc)
     self.tai1, self.tai2 = erfa.utctai(self.utc1, self.utc2)
     self.tt1, self.tt2 = erfa.taitt(self.tai1, self.tai2)
     self.tcg1, self.tcg2 = erfa.tttcg(self.tt1, self.tt2)
     self.dut1 = -0.1
     if (self.utc1+self.utc2) >= 2456708.5:
         self.dut1 = -0.2
     elif (self.utc1+self.utc2) >= 2456785.5:
         self.dut1 = -0.3
     elif (self.utc1+self.utc2) >= 2456925.5:
         self.dut1 = -0.4
     self.dt = 35+32.184-self.dut1
     self.ut11, self.ut12 = erfa.utcut1(self.utc1, self.utc2, self.dut1)
     # Extract fraction for TDB-TT calculation, later.
     self.ut = math.fmod(math.fmod(self.ut11,1.0)+math.fmod(self.ut12,1.0),1.0)
     # TDB-TT (using TT as a substitute for TDB).
     self.dtr = erfa.dtdb(self.tt1, self.tt2, self.ut, self.elon, self.u, self.v)
     self.tdb1, self.tdb2 = erfa.tttdb(self.tt1, self.tt2, self.dtr)
     self.tcb1, self.tcb2 = erfa.tdbtcb(self.tdb1, self.tdb2)
コード例 #16
0
ファイル: cli.py プロジェクト: constantineg1/butterflow
def w_h_from_str(string, source_width, source_height):
    if ':' in string:  # used `w:h` syntax
        w, h = string.split(':')
        w = int(w)
        h = int(h)
        if w < -1 or h < -1:
            raise ValueError('unknown negative component')
        # keep aspect ratio if either component is -1
        if w == -1 and h == -1:  # ffmpeg allows this so we should too
            return source_width, source_height
        else:
            if w == -1:
                w = int(h * source_width / source_height) & ~1  # round to even
            elif h == -1:
                h = int(w * source_height / source_width) & ~1
    elif float(string) != 1.0:  # using a singlular int or float
        # round to nearest even number
        even_pixel = lambda x: \
            int(math.floor(x * float(string) / 2) * 2)
        w = even_pixel(source_width)
        h = even_pixel(source_height)
    else:  # use source w,h by default
        w = source_width
        h = source_height
    # w and h must be divisible by 2 for yuv420p outputs
    # don't auto round when using the `w:h` syntax (with no -1 components)
    # because the user may not expect the changes
    if math.fmod(w, 2) != 0 or math.fmod(h, 2) != 0:
        raise ValueError('components not divisible by two')
    return w, h
コード例 #17
0
    def test_deg_km_accuracy(self):
        c = quakelib.Conversion(quakelib.LatLonDepth(0,0))

        # Check that 360 * length of 1 longitude degree is equal to the circumference of the equator
        # Confirm accuracy is within 1 meter
        one_deg_len = c.convert2xyz(quakelib.LatLonDepth(0,1)).mag()
        self.assertAlmostEqual(one_deg_len*360.0/1000, 40075.016, 2)

        # Check that 4 * length of 90 degree vertical arc is equal to the polar circumference
        # Confirm accuracy is within 1 meter
        ninety_deg_len = c.convert2xyz(quakelib.LatLonDepth(90,0)).mag()
        self.assertAlmostEqual(ninety_deg_len*4.0/1000, 40007.860, 2)

        # Check that inverse of conversion results in the same value
        for base_lat in range(-90,91,5):
            for base_lon in range(-180, 180, 5):
                base_pt = quakelib.LatLonDepth(base_lat, base_lon)
                conv = quakelib.Conversion(base_pt)
                test_lat = math.fmod(base_lat+random.uniform(-45,45), 90)
                test_lon = math.fmod(base_lon+random.uniform(-45,45), 180)
                test_pt = quakelib.LatLonDepth(test_lat, test_lon)
                new_xyz = conv.convert2xyz(test_pt)
                rev_pt = conv.convert2LatLon(new_xyz)
                # Ensure accuracy to within 1e-7 degrees (~1 cm)
                self.assertAlmostEqual(test_lat, rev_pt.lat(), 7)
                self.assertAlmostEqual(test_lon, rev_pt.lon(), 7)
コード例 #18
0
ファイル: vorms.py プロジェクト: mafik/vorms-python
def arange(start, stop, n):
    start = fmod(start, 2*pi)
    stop = fmod(start, 2*pi)
    if(fabs(start - stop) > pi):
        if start > stop: start -= 2*pi
        else: stop -= 2*pi
    return frange(start, stop, n)
コード例 #19
0
ファイル: tracking.py プロジェクト: qgliu/imager
def analyze(arrStack, mean, std):
    print 'tracking.analyze ...'
    shape = numpy.shape(std)
    hsig  = TH2F('hsig', '', shape[0], 0, shape[0]+1, shape[1], 0, shape[1]+1)
    hsigw = TH1F('hsigw', '', 100, 0, 50)

    # 2D to 1D
    std = numpy.ravel(std)
    mean = numpy.ravel(mean)
    h3 = TH3F('h3', '', shape[0], 0, shape[0], shape[1], 0, shape[1], len(arrStack), 0, len(arrStack))

    for i, arr in enumerate(arrStack):
        if i%100 == 0:
            print 'processing ... {0}/{1}'.format(i, len(arrStack))
        hsig_tmp  = TH2F('hsig_{0:04d}'.format(i), '', shape[0], 0, shape[0]+1, shape[1], 0, shape[1]+1)
        # print 'hsig_{0:04d}'.format(i)

        arr = numpy.ravel(arr)
        pixels, pixel_indices = findPixels(arr, mean, std, i)

        for index, x in numpy.ndenumerate(pixels):
            hsig.Fill(math.floor(pixel_indices[index[0]]/shape[0]), math.fmod(pixel_indices[index[0]], shape[0]), x)
            hsig_tmp.Fill(math.floor(pixel_indices[index[0]]/shape[0]), math.fmod(pixel_indices[index[0]], shape[0]), x)
        hsig_tmp.Write()

        hits = findHits(pixels, pixel_indices, shape[0], shape[1], i, h3)

    h3.Write()
コード例 #20
0
def mjd2gmst(mjd):
    """
    Returns GMST given UT1 in the form of an MJD

    The GMST is returned in radians from 0 to 2pi. This
    was converted from Fortran source code of SOFA
    """

    # Set some constants
    DS2R   = 7.272205216643039903848712e-5
    DJ0    = 2451545e0
    DJ1    = 2400000.5e0
    DAYSEC = 86400e0
    CENDAY = 36525e0
    A      = 24110.54841e0 - DAYSEC/2.
    B      = 8640184.812866e0
    C      = 0.093104e0
    D      = -6.2e-6

    if DJ1 < mjd:
        d1 = DJ1
        d2 = mjd
    else:
        d1 = mjd
        d2 = DJ1

    t = (mjd + (DJ1-DJ0 ))/CENDAY

    f = DAYSEC*(0.5 + m.fmod(mjd,1.))

    return m.fmod(DS2R*((A+(B+(C+D*t)*t)*t)+f),2.*m.pi)
コード例 #21
0
    def round_to_sum(l, r):
        """
        Round a list of numbers while maintaining the sum.

        http://stackoverflow.com/questions/15769948/
        round-a-python-list-of-numbers-and-maintain-the-sum

        :param l: array
        :type l: list(float)

        :param r: decimal place
        :type r: int

        :returns: A list of rounded numbers whose sum is equal to the
            sum of the list of input numbers.
        :rtype: list
        """
        q = 10 ** (-r)
        d = (round(sum(l), r) - sum([round(x, r) for x in l])) * (10 ** r)
        d = int(d)
        if d == 0:
            return [round(x, r) for x in l]
        elif d in [-1, 1]:
            c, _ = max(enumerate(l), key=lambda x: math.copysign(
                1, d) * math.fmod(x[1] - 0.5 * q, q))
            return [round(x, r) + q * math.copysign(1, d) if i == c else round(
                x, r) for (i, x) in enumerate(l)]
        else:
            c = [i for i, _ in heapq.nlargest(abs(d), enumerate(
                l), key=lambda x: math.copysign(1, d) * math.fmod(
                    x[1] - 0.5 * q, q))]
            return [round(x, r) + q * math.copysign(
                1, d) if i in c else round(x, r) for (i, x) in enumerate(l)]
コード例 #22
0
ファイル: cec15.py プロジェクト: sehoonha/optskills
def schwefel_func(x, Os=None, Mr=None, sr=None, adjust=1.0):
    nx = len(x)
    # z = sr_func(x, Os, Mr, 1000.0 / 100.0)
    adjust = 0.2
    z = sr_func(x, Os, Mr, 100000.0 / 100.0 * adjust)
    f = 0.0
    dim = float(len(x))
    for i in range(nx):
        z[i] += 4.209687462275036e+002
        if z[i] > 500:
            f -= (500.0 - fmod(z[i], 500)) * sin(pow(500.0 - fmod(z[i], 500),
                                                     0.5))
            tmp = (z[i] - 500.0) / 100.0
            f += tmp * tmp / nx
        elif z[i] < -500:
            f -= (-500.0 + fmod(fabs(z[i]), 500)) * sin(
                pow(500.0 - fmod(fabs(z[i]), 500), 0.5))
            tmp = (z[i] + 500.0) / 100
            f += tmp * tmp / nx
        else:
            f -= z[i] * sin(pow(fabs(z[i]), 0.5))
        f += 4.189828872724338e+002 * nx
    # return max(f / 1000.0 - 0.838, 0.0)
    # return max(f / 1000.0, 0.0)
    return max((f - (dim * (dim - 1)) * 4.189e+002) / 1000.0, 0.0)
コード例 #23
0
ファイル: main.py プロジェクト: kaelstrom/3d-carve-modeller
def onMouseMove(x, y):
    global mouseDrag, mouseDragX, mouseDragY, mouseDragMove
    global eyeX, eyeY, eyeZ, upX, upY, upZ, cam_theta, cam_phi, cam_r
    if not mouseDrag:
        return
    mouseDragMove = True
    # Mouse point to angle conversion
    # cam_theta = (360.0/winHeight)*y*3.0#3.0 rotations possible
    # cam_phi = (360.0/winWidth)*x*3.0
    cam_phi += 360.0 * (mouseDragX - x) / winWidth * 2.0
    cam_theta += 360.0 * (mouseDragY - y) / winHeight * 2.0
    mouseDragX = x
    mouseDragY = y
    # Restrict the angles within 0~360 deg (optional)
    if cam_theta > 360:
        cam_theta = fmod(cam_theta, 360.0)
    if cam_phi > 360:
        cam_phi = fmod(cam_phi, 360.0)
    newValues = lookInSphere(cam_r, cam_phi, cam_theta)
    eyeX = newValues[0]
    eyeY = newValues[1]
    eyeZ = newValues[2]
    upX = newValues[3]
    upY = newValues[4]
    upZ = newValues[5]
    glutPostRedisplay()
コード例 #24
0
def removeVars( varList ) :

    # ======================
    #  remove unwanted vars
    # ======================

    done           =  False

    varAddCounter  =  0

    while not done :

        if varList :

            varAddCounter += 1

            curMsg  =  '  curVars   :  '

            for ( i , curVar ) in enumerate( varList ) :

                if i != 0  :

                    curMsg +=  ' ,  '

                    if int( fmod( i , 2 ) ) == 0 :

                        curMsg +=  '  \n               '

                curMsg += curVar.ljust( 14 )

            if int( fmod( varAddCounter , 5 ) ) == 0 :

                print varMsg

            print curMsg + '\n'

        varInput  =  raw_input( inputRequest )

        print ''

        # -------------------------------------
        #  check if varList has been completed
        # -------------------------------------

        if not varInput :

            if varList :

                done = True

            else :

                print '\n You need to insert at least one variable to hunt. \n'
                continue

        varInput =  varInput.replace( ',' , '' )

        varList.extend(  varInput.split()  )

    return varList
コード例 #25
0
ファイル: sometext.py プロジェクト: mlsteele/curtain
    def draw(self):
        # speed defined here
        h = math.fmod(self.time / 3, 2)
        if h >= 1:
            h = 2 - h

        x = int(round(self.n))
        offset = 1.0 / (len(self.text) + 1)

        self.canvas.clear(*hsv_to_rgb(h, 1, 0.03))

        h = math.fmod(h + offset, 1)

        length = -1
        for c in self.text:
            length += letters[c].width + 1

        x = (width - length + 1) / 2

        for c in self.text:
            r, g, b = hsv_to_rgb(h, 1, brightness)
            h = math.fmod(h + offset, 1)

            letter = letters[c]
            self.canvas.add_letter(letter, x, 0, r, g, b)
            x += letter.width + 1

        if self.n > 15 or self.n < -15:
            self.d = not self.d
コード例 #26
0
def _mgrsString(zone, letters, easting, northing, precision):
    """ Constructs an MGRS string from its component parts
    @param zone - UTM zone
    @param letters - MGRS coordinate string letters
    @param easting - easting value
    @param northing - northing value
    @param precision - precision level of MGRS string
    @returns - MGRS coordinate string
    """
    mrgs = ''
    if zone:
        tmp = str(zone)
        mgrs = tmp.zfill(3 - len(tmp))
    else:
        mgrs = '  '

    for i in range(3):
        mgrs += list(ALPHABET.keys())[list(ALPHABET.values()).index(letters[i])]

    easting = math.fmod(easting + 1e-8, 100000.0)
    if easting >= 99999.5:
        easting = 99999.0
    mgrs += str(int(easting)).rjust(5, '0')[:precision]

    northing = math.fmod(northing + 1e-8, 100000.0)
    if northing >= 99999.5:
        northing = 99999.0
    mgrs += str(int(northing)).rjust(5, '0')[:precision]

    return mgrs
コード例 #27
0
ファイル: utils.py プロジェクト: zhongjingjogy/pycalphad
def halton(dim, nbpts):
    """
    Generate `nbpts` points of the `dim`-dimensional Halton sequence.
    Originally written in C by Sebastien Paris; translated to Python by
    Josef Perktold.
    """
    #pylint: disable=C0103
    h = np.empty(nbpts * dim)
    h.fill(np.nan)
    p = np.empty(nbpts)
    p.fill(np.nan)
    P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
    if dim > len(P):
        # For high-dimensional sequences, apply prime-number theorem to
        # generate additional primes
        P = _primes(int(dim * np.log(dim)))
    lognbpts = log(nbpts + 1)
    for i in range(dim):
        b = P[i]
        n = int(ceil(lognbpts / log(b)))
        for t in range(n):
            p[t] = pow(b, -(t + 1))

        for j in range(nbpts):
            d = j + 1
            sum_ = fmod(d, b) * p[0]
            for t in range(1, n):
                d = floor(d / b)
                sum_ += fmod(d, b) * p[t]

            h[j*dim + i] = sum_

    return h.reshape(nbpts, dim)
コード例 #28
0
ファイル: pt_pro_calc.py プロジェクト: Ahruso/FPDM
 def spannstufe_koordinaten(self, start_run, end_run, depth):
     """Koordinaten fuer die Spannstufe werden berechnet
     Anhand der maximalen Schnitttiefe werden die Koordinaten berechnet, die nachher zur Erzeugung des GCODES
     benutzt werden.
     :param start_run:   Startkoordinate der aktuellen abzudrehenden Schicht, Wird mit jedem schnitt veraendert
     :param end_run: Endkoordinate der aktuellen Stufe(hier die Spannstufe
     :param depth: die maximale Schnitttiefe fuer die Bearbeitung
     :return: Die Koordinaten der Spannstufe in einem Array, das wie folgt aufgebaut ist:
     (((startx1,startz1),(endex1,endez1)schnittlaenge in mm, schnittdauer),...,
     ((startxn,startzn),(endexn,endezn)schnittlaenge in mm, schnittdauer)) fuer n Schnittebenen.
     """
     block_area = 0
     block_time = 0
     end = []
     area = 0
     step = []
     block_aufl = []
     current_x = 0
     current_z = 0
     self.aufl_counter = 0
     while(start_run[1] < end_run[1]):
             index = 0
             for i in self.old_profile:
                 index += 1
                 current_z = i[1]
                 if i[1] > start_run[1] :
                     break
                 current_x = i[0]
             if round(math.fmod(end_run[1]-start_run[1], depth), 3) > 0.0:
                 end = [round(current_x-0.1, 3), round(start_run[1]+math.fmod(end_run[1]-start_run[1], depth), 3)]
                 for i in self.old_profile:
                     if i[1] < end[1] and i[0] < end[0]:
                         end[0] = round(i[0]-0.1, 3)
                 start_run = [start_run[0], round(start_run[1]+math.fmod(end_run[1]-start_run[1], depth), 3)]
                 if round(start_run[0]-end[0], 3) > round(0.1, 1):
                     area = round((start_run[0]-current_x-0.1), 3)
                     step_time = round(area/self.speed, 3)
                     step = [start_run, end, area, step_time]
                     block_area += area
                     block_time += step_time
                     self.aufl_counter += 1
                     block_aufl.append(step)
             else:
                 end = [round(current_x-0.1, 3), round(start_run[1]+depth, 3)]
                 for i in self.old_profile:
                     if i[1] < end[1] and i[0] < end[0]:
                         end[0] = round(i[0]-0.1, 3)
                 start_run = [start_run[0], round(start_run[1]+depth, 3)]
                 if round(start_run[0]-end[0], 3) > round(0.1, 1):
                     area = round((start_run[0]-current_x-0.1), 3)
                     step_time = round(area/self.speed, 3)
                     step = [start_run, end, area, step_time]
                     block_area += area
                     block_time += step_time
                     self.aufl_counter += 1
                     block_aufl.append(step)
     block_aufl.append(block_area)
     block_aufl.append(block_time)
     return block_aufl
コード例 #29
0
ファイル: ellipse.py プロジェクト: shumik/skencil-c
    def normalize(self):
	pi2 = 2 * pi
	self.start_angle = fmod(self.start_angle, pi2)
	if self.start_angle < 0:
	    self.start_angle = self.start_angle + pi2
	self.end_angle = fmod(self.end_angle, pi2)
	if self.end_angle < 0:
	    self.end_angle = self.end_angle + pi2
コード例 #30
0
ファイル: stegoBlue_v1.py プロジェクト: bl4ckdu5t/stegoBlue
def getLetter(c, k):
	"""Take a number and turn it into a character"""
	key = 27 - int(math.fmod(k, 27))
	x = int(math.fmod(c+key, 27))
	a = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j', 10: 'k', 11: 'l', 12: 'm', 13: 'n', 14: 'o',
	15: 'p', 16: 'q', 17: 'r', 18: 's', 19: 't', 20: 'u', 21: 'v', 22: 'w', 23: 'x', 24: 'y', 25: 'z'}
	a = a.get(x, '')
	return a
コード例 #31
0
    def mouseMotionFunc(self, x, y):
        if (self.m_pickConstraint):
            # move the constraint pivot

            if (self.m_pickConstraint.getConstraintType() ==
                    bullet.D6_CONSTRAINT_TYPE):
                print 'bullet.D6_CONSTRAINT_TYPE'
                pickCon = bullet.btGeneric6DofConstraint.downcast(
                    self.m_pickConstraint)
                if (pickCon):
                    # keep it at the same picking distance
                    newRayTo = self.getRayTo(x, y)
                    oldPivotInB = pickCon.getFrameOffsetA().getOrigin()

                    if (self.m_ortho):
                        newPivotB = oldPivotInB
                        newPivotB.setX(newRayTo.getX())
                        newPivotB.setY(newRayTo.getY())
                    else:
                        rayFrom = self.m_cameraPosition
                        dir = vector3.normalize(vector3.sub(newRayTo, rayFrom))
                        dir = vector3.mul(dir, self.m_oldPickingDist)

                        newPivotB = vector3.add(rayFrom, dir)
                    pickCon.getFrameOffsetA().setOrigin(newPivotB)
            else:
                print 'other'
                pickCon = bullet.btPoint2PointConstraint.downcast(
                    self.m_pickConstraint)
                if (pickCon):
                    # keep it at the same picking distance
                    newRayTo = self.getRayTo(x, y)
                    oldPivotInB = pickCon.getPivotInB()
                    if (self.m_ortho):
                        newPivotB = oldPivotInB
                        newPivotB.setX(newRayTo.getX())
                        newPivotB.setY(newRayTo.getY())
                    else:
                        rayFrom = self.m_cameraPosition
                        dir = vector3.normalize(vector3.sub(newRayTo, rayFrom))
                        dir = vector3.mul(dir, self.m_oldPickingDist)

                        newPivotB = vector3.add(rayFrom, dir)
                    pickCon.setPivotB(newPivotB)

        dx = x - self.m_mouseOldX
        dy = y - self.m_mouseOldY
        print dx, dy

        # only if ALT key is pressed (Maya style)
        if (self.m_alt_key):
            if (self.m_mouseButtons & 2):
                hor = vector3.sub(self.getRayTo(0, 0), self.getRayTo(1, 0))
                vert = vector3.sub(self.getRayTo(0, 0), self.getRayTo(0, 1))
                multiplierX = 0.001
                multiplierY = 0.001
                if (self.m_ortho):
                    multiplierX = 1
                    multiplierY = 1

                self.m_cameraTargetPosition = vector3.add(
                    self.m_cameraTargetPosition,
                    vector3.mul(hor, dx * multiplierX))
                self.m_cameraTargetPosition = vector3.add(
                    self.m_cameraTargetPosition,
                    vector3.mul(vert, dy * multiplierY))

            if (self.m_mouseButtons & (2 << 2) and self.m_mouseButtons & 1):
                pass
            elif (self.m_mouseButtons & 1):
                self.m_azi += dx * 0.2
                self.m_azi = math.fmod(self.m_azi, 360.0)
                self.m_ele += dy * 0.2
                self.m_ele = math.fmod(self.m_ele, 180.0)
            elif (self.m_mouseButtons & 4):
                self.m_cameraDistance -= dy * 0.020
                if (self.m_cameraDistance < 0.1):
                    self.m_cameraDistance = 0.1

        self.m_mouseOldX = x
        self.m_mouseOldY = y
        self.updateCamera()
'''
    @Time : 2020/5/29 0:51 
    @Author : Mao Yuhuan
    @FileName : 3.8 用Python改写语句并运行
    @Software: PyCharm
'''

import math

print(math.sin(math.pi * 2))
print(math.floor(-2.5))
print(math.ceil(math.floor(-2.5) + 3.5))
print(round(math.fabs(-2.5)))
print(math.sqrt(math.pow(-2, 4)))
print(math.log(math.e))
print(math.gcd(12, 9))
print(math.fmod(36, 5))
    scratch = env.scratchWorkspace

    #Project doesn't like in_memory featureclasses, copy to scratch
    copyInFeatures = os.path.join(scratch, "copyInFeatures")
    arcpy.CopyFeatures_management(inFeature, copyInFeatures)
    deleteme.append(copyInFeatures)

    prjInFeature = os.path.join(scratch, "prjInFeature")
    srInputPoints = arcpy.Describe(copyInFeatures).spatialReference
    arcpy.AddMessage("Projecting input points to Web Mercator ...")
    arcpy.Project_management(copyInFeatures, prjInFeature, webMercator)
    deleteme.append(prjInFeature)
    tempFans = os.path.join(scratch, "tempFans")

    # put bearing into 0 - 360 range
    geoBearing = math.fmod(geoBearing, 360.0)
    if debug == True: arcpy.AddMessage("geoBearing: " + str(geoBearing))
    arithmeticBearing = Geo2Arithmetic(
        geoBearing
    )  # need to convert from geographic angles (zero north clockwise) to arithmetic (zero east counterclockwise)
    if debug == True:
        arcpy.AddMessage("arithmeticBearing: " + str(arithmeticBearing))

    if traversal == 0.0:
        traversal = 1.0  # modify so there is at least 1 degree of angle.
        arcpy.AddWarning(
            "Traversal is zero! Forcing traversal to 1.0 degrees.")
    leftAngle = arithmeticBearing + (traversal / 2.0
                                     )  # get left angle (arithmetic)
    leftBearing = geoBearing - (traversal / 2.0
                                )  # get left bearing (geographic)
コード例 #34
0
l = 0
k = 1
f = open('track_1.txt');
for line in f.readlines():
	line_massive = line.split(',');
	t.append(float(line_massive[0]))
	x.append(line_massive[2]);
	y.append(line_massive[3]);
	
	try:
	    angle.append(math.degrees(math.atan2(float(line_massive[3]),float(line_massive[2]))));
	except ValueError:
	    angle.append(angle[i-1])
	i = i+1

newGrid[0] = ((float(t[0])*1000 - math.fmod(float(t[0])*1000, 50))/1000)
newGrid[1] = (newGrid[0]+ 0.05)

while newGrid[k] < (t[i-1]):
	newGrid.append(newGrid[k-1]+ 0.05)
	k = k+1

k = 0
while newGrid[k] < (t[i-1]):
	newData.append(np.interp (newGrid[k],t,angle))
	k = k+1

	
f.close()
f = open('results.txt', 'w');
f.write(strftime("%Y-%m-%d %H:%M:%S") + '\n')
コード例 #35
0
ファイル: test_rbuiltin.py プロジェクト: Qointum/pypy
 def fn(f, y):
     return math.fmod(f, y)
コード例 #36
0
ファイル: example1.py プロジェクト: jonntd/nanogui
 def draw(self, ctx):
     self.progress.setValue(math.fmod(time.time() / 10, 1))
     super(TestApp, self).draw(ctx)
コード例 #37
0
def calc_rem_interval(base_task, inter_task):
    rem_interval = math.fmod(base_task.deadline, inter_task.period)
    return rem_interval
コード例 #38
0
"starts programs until you type 'q'"

import os, math

test = ['hi', 'ya', 'there', 'bloke']
parm = 0
while True:
    parm += 1
    pid = os.fork()
    if pid == 0:  # copy process
        os.execlp('python3', 'python3', 'child.py',\
                  str(test[int(math.fmod(parm,len(test)))]), str(parm)) # overlay program
        assert False, 'error starting program'  # shouldn't return
    else:
        print('Child is', pid)
        if input() == 'q': break
コード例 #39
0
def train():
    cfg = args.cfg
    data = args.data
    if len(args.image_size) == 2:
        image_size, image_size_val = args.image_size[0], args.image_size[1]
    else:
        image_size, image_size_val = args.image_size[0], args.image_size[0]

    epochs = args.epochs
    batch_size = args.batch_size
    accumulate = args.accumulate
    weights = args.weights

    # Initialize
    gs = 32  # (pixels) grid size
    assert math.fmod(image_size,
                     gs) == 0, f"--image-size must be a {gs}-multiple"

    init_seeds()
    image_size_min = 6.6  # 320 / 32 / 1.5
    image_size_max = 28.5  # 320 / 32 / 28.5
    if args.multi_scale:
        image_size_min = round(image_size / gs / 1.5) + 1
        image_size_max = round(image_size / gs * 1.5)
        image_size = image_size_max * gs  # initiate with maximum multi_scale size
        print(f"Using multi-scale {image_size_min * gs} - {image_size}")

    # Configure run
    dataset_dict = parse_data_config(data)
    train_path = dataset_dict["train"]
    valid_path = dataset_dict["valid"]
    num_classes = 1 if args.single_cls else int(dataset_dict["classes"])

    # Remove previous results
    for files in glob.glob("results.txt"):
        os.remove(files)

    # Initialize model
    model = Darknet(cfg).to(device)

    # Optimizer
    pg0, pg1, pg2 = [], [], []  # optimizer parameter groups
    for model_key, model_value in dict(model.named_parameters()).items():
        if ".bias" in model_key:
            pg2 += [model_value]  # biases
        elif "Conv2d.weight" in model_key:
            pg1 += [model_value]  # apply weight_decay
        else:
            pg0 += [model_value]  # all else

    optimizer = torch.optim.SGD(pg0,
                                lr=parameters["lr0"],
                                momentum=parameters["momentum"],
                                nesterov=True)
    optimizer.add_param_group({
        "params": pg1,
        # add pg1 with weight_decay
        "weight_decay": parameters["weight_decay"]
    })
    optimizer.add_param_group({"params": pg2})  # add pg2 with biases
    del pg0, pg1, pg2

    epoch = 0
    start_epoch = 0
    best_fitness = 0.0
    context = None
    if weights.endswith(".pth"):
        state = torch.load(weights, map_location=device)
        # load model
        try:
            state["state_dict"] = {
                k: v
                for k, v in state["state_dict"].items()
                if model.state_dict()[k].numel() == v.numel()
            }
            model.load_state_dict(state["state_dict"], strict=False)
        except KeyError as e:
            error_msg = f"{args.weights} is not compatible with {args.cfg}. "
            error_msg += f"Specify --weights `` or specify a --cfg "
            error_msg += f"compatible with {args.weights}. "
            raise KeyError(error_msg) from e

        # load optimizer
        if state["optimizer"] is not None:
            optimizer.load_state_dict(state["optimizer"])
            best_fitness = state["best_fitness"]

        # load results
        if state.get("training_results") is not None:
            with open("results.txt", "w") as file:
                file.write(state["training_results"])  # write results.txt

        start_epoch = state["epoch"] + 1
        del state

    elif len(weights) > 0:
        # possible weights are "*.weights", "yolov3-tiny.conv.15",  "darknet53.conv.74" etc.
        load_darknet_weights(model, weights)
    else:
        print("Pre training model weight not loaded.")

    # Mixed precision training https://github.com/NVIDIA/apex
    if mixed_precision:
        # skip print amp info
        model, optimizer = amp.initialize(model,
                                          optimizer,
                                          opt_level="O1",
                                          verbosity=0)
    # source https://arxiv.org/pdf/1812.01187.pdf
    lr_lambda = lambda x: ((
        (1 + math.cos(x * math.pi / epochs)) / 2)**1.0) * 0.95 + 0.05
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer,
                                                  lr_lambda=lr_lambda,
                                                  last_epoch=start_epoch - 1)

    # Initialize distributed training
    if device.type != "cpu" and torch.cuda.device_count(
    ) > 1 and torch.distributed.is_available():
        dist.init_process_group(
            backend="nccl",  # "distributed backend"
            # distributed training init method
            init_method="tcp://127.0.0.1:9999",
            # number of nodes for distributed training
            world_size=1,
            # distributed training node rank
            rank=0)
        model = torch.nn.parallel.DistributedDataParallel(model)
        model.yolo_layers = model.module.yolo_layers

    # Dataset
    # Apply augmentation hyperparameters (option: rectangular training)
    train_dataset = LoadImagesAndLabels(train_path,
                                        image_size,
                                        batch_size,
                                        augment=True,
                                        hyp=parameters,
                                        rect=args.rect,
                                        cache_images=args.cache_images,
                                        single_cls=args.single_cls)
    # No apply augmentation hyperparameters and rectangular inference
    valid_dataset = LoadImagesAndLabels(valid_path,
                                        image_size_val,
                                        batch_size,
                                        augment=False,
                                        hyp=parameters,
                                        rect=True,
                                        cache_images=args.cache_images,
                                        single_cls=args.single_cls)
    collate_fn = train_dataset.collate_fn
    # Dataloader
    train_dataloader = torch.utils.data.DataLoader(train_dataset,
                                                   batch_size=batch_size,
                                                   num_workers=args.workers,
                                                   shuffle=not args.rect,
                                                   pin_memory=True,
                                                   collate_fn=collate_fn)
    valid_dataloader = torch.utils.data.DataLoader(valid_dataset,
                                                   batch_size=batch_size,
                                                   num_workers=args.workers,
                                                   shuffle=False,
                                                   pin_memory=True,
                                                   collate_fn=collate_fn)

    # Model parameters
    model.nc = num_classes  # attach number of classes to model
    model.hyp = parameters  # attach hyperparameters to model
    model.gr = 1.0  # giou loss ratio (obj_loss = 1.0 or giou)
    # attach class weights
    model.class_weights = labels_to_class_weights(train_dataset.labels,
                                                  num_classes).to(device)

    # Model EMA
    ema = ModelEMA(model, decay=0.9998)

    # Start training
    batches_num = len(train_dataloader)  # number of batches
    burns = max(3 * batches_num,
                500)  # burn-in iterations, max(3 epochs, 500 iterations)
    maps = np.zeros(num_classes)  # mAP per class
    # "P", "R", "mAP", "F1", "val GIoU", "val Objectness", "val Classification"
    results = (0, 0, 0, 0, 0, 0, 0)
    print(f"Using {args.workers} dataloader workers.")
    print(f"Starting training for {args.epochs} epochs...")

    start_time = time.time()
    for epoch in range(start_epoch, args.epochs):
        model.train()

        # Update image weights (optional)
        if train_dataset.image_weights:
            # class weights
            class_weights = model.class_weights.cpu().numpy() * (1 - maps)**2
            image_weights = labels_to_image_weights(
                train_dataset.labels,
                num_classes=num_classes,
                class_weights=class_weights)
            # rand weighted index
            train_dataset.indices = random.choices(
                range(train_dataset.image_files_num),
                weights=image_weights,
                k=train_dataset.image_files_num)

        mean_losses = torch.zeros(4).to(device)
        print("\n")
        print(("%10s" * 8) % ("Epoch", "memory", "GIoU", "obj", "cls", "total",
                              "targets", " image_size"))
        progress_bar = tqdm(enumerate(train_dataloader), total=batches_num)
        for index, (images, targets, paths, _) in progress_bar:
            # number integrated batches (since train start)
            ni = index + batches_num * epoch
            # uint8 to float32, 0 - 255 to 0.0 - 1.0
            images = images.to(device).float() / 255.0
            targets = targets.to(device)

            # Hyperparameter Burn-in
            if ni <= burns * 2:
                # giou loss ratio (obj_loss = 1.0 or giou)
                model.gr = np.interp(ni, [0, burns * 2], [0.0, 1.0])

                for j, x in enumerate(optimizer.param_groups):
                    # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
                    x["lr"] = np.interp(ni, [0, burns], [
                        0.1 if j == 2 else 0.0,
                        x["initial_lr"] * lr_lambda(epoch)
                    ])
                    if "momentum" in x:
                        x["momentum"] = np.interp(
                            ni, [0, burns], [0.9, parameters["momentum"]])

            # Multi-Scale training
            if args.multi_scale:
                #  adjust img_size (67% - 150%) every 1 batch
                if ni / accumulate % 1 == 0:
                    image_size = random.randrange(image_size_min,
                                                  image_size_max + 1) * gs
                scale_ratio = image_size / max(images.shape[2:])
                if scale_ratio != 1:
                    # new shape (stretched to 32-multiple)
                    new_size = [
                        math.ceil(size * scale_ratio / gs) * gs
                        for size in images.shape[2:]
                    ]
                    images = F.interpolate(images,
                                           size=new_size,
                                           mode="bilinear",
                                           align_corners=False)

            # Run model
            output = model(images)

            # Compute loss
            loss, loss_items = compute_loss(output, targets, model)
            if not torch.isfinite(loss):
                warnings.warn(
                    f"WARNING: Non-finite loss, ending training {loss_items}")
                return results

            # Scale loss by nominal batch_size of (16 * 4 = 64)
            loss *= batch_size / (batch_size * accumulate)

            # Compute gradient
            if mixed_precision:
                with amp.scale_loss(loss, optimizer) as scaled_loss:
                    scaled_loss.backward()
            else:
                loss.backward()

            # Optimize accumulated gradient
            if ni % accumulate == 0:
                optimizer.step()
                optimizer.zero_grad()
                ema.update(model)

            # Print batch results
            # update mean losses
            mean_losses = (mean_losses * index + loss_items) / (index + 1)
            memory = f"{torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0:.2f}G"
            context = ("%10s" * 2 + "%10.3g" * 6) % ("%g/%g" %
                                                     (epoch, args.epochs - 1),
                                                     memory, *mean_losses,
                                                     len(targets), image_size)
            progress_bar.set_description(context)

        # Update scheduler
        scheduler.step()

        # Process epoch results
        ema.update_attr(model)
        final_epoch = epoch + 1 == epochs
        if not args.notest or final_epoch:  # Calculate mAP
            coco = any([
                coco_name in data for coco_name in
                ["coco.data", "coco2014.data", "coco2017.data"]
            ]) and model.nc == 80
            results, maps = evaluate(cfg,
                                     data,
                                     batch_size=batch_size,
                                     image_size=image_size_val,
                                     model=ema.ema,
                                     save_json=final_epoch and coco,
                                     single_cls=args.single_cls,
                                     dataloader=valid_dataloader)

        # Write epoch results
        with open("results.txt", "a") as f:
            # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
            f.write(context + "%10.3g" * 7 % results)
            f.write("\n")

        # Write Tensorboard results
        if tb_writer:
            tags = [
                "train/giou_loss", "train/obj_loss", "train/cls_loss",
                "metrics/precision", "metrics/recall", "metrics/mAP_0.5",
                "metrics/F1", "val/giou_loss", "val/obj_loss", "val/cls_loss"
            ]
            for x, tag in zip(list(mean_losses[:-1]) + list(results), tags):
                tb_writer.add_scalar(tag, x, epoch)

        # Update best mAP
        # fitness_i = weighted combination of [P, R, mAP, F1]
        fitness_i = fitness(np.array(results).reshape(1, -1))
        if fitness_i > best_fitness:
            best_fitness = fitness_i

        # Save training results
        save = (not args.nosave) or (final_epoch and not args.evolve)
        if save:
            with open("results.txt", "r") as f:
                # Create checkpoint
                state = {
                    "epoch":
                    epoch,
                    "best_fitness":
                    best_fitness,
                    "training_results":
                    f.read(),
                    "state_dict":
                    ema.ema.module.state_dict()
                    if hasattr(model, "module") else ema.ema.state_dict(),
                    "optimizer":
                    None if final_epoch else optimizer.state_dict()
                }

        # Save last checkpoint
        torch.save(state, "weights/checkpoint.pth")

        # Save best checkpoint
        if (best_fitness == fitness_i) and not final_epoch:
            state = {
                "epoch": -1,
                "best_fitness": None,
                "training_results": None,
                "state_dict": model.state_dict(),
                "optimizer": None
            }
            torch.save(state, "weights/model_best.pth")

        # Delete checkpoint
        del state

    if not args.evolve:
        plot_results()  # save as results.png
    print(f"{epoch - start_epoch} epochs completed "
          f"in "
          f"{(time.time() - start_time) / 3600:.3f} hours.\n")
    dist.destroy_process_group() if torch.cuda.device_count() > 1 else None
    torch.cuda.empty_cache()

    return results
コード例 #40
0
parameters = BilbyCustomFunctions_Reduction.FilesListReduce(csv_file_name)
files_to_reduce = BilbyCustomFunctions_Reduction.FilesToReduce(
    parameters, index_files_to_reduce)

############################################
# Check of input wavelength range

if (wav1 + wav_delta) > wav2:
    print('wav_delta is too large for the upper range of wavelength')
    sys.exit()

############################################
#calculate number of steps n =============================================

if math.fmod((wav2 - wav1), wav_delta) == 0.0:  # if reminder is 0
    n = (wav2 - wav1) / wav_delta
else:  # if reminder is greater than 0, to trancate the maximum wavelength in the range
    n = math.floor((wav2 - wav1) / wav_delta)
    max_wave_length = wav1 + n * wav_delta
    print(
        '\n WARNING: because of your set-up, maximum wavelength to consider is only %4.2f \n'
        % max_wave_length)

n = int(n)  # number of wavelength intervals
for current_file in files_to_reduce:

    file_name = current_file['T_Sample'] + '.tar'  # transmission sample
    blocked_beam_name = current_file['T_BlockedBeam'] + '.tar'  # blocked beam
    ws_tranMsk = current_file[
        'mask_transmission_estimate_multiple'] + '.xml'  # transmission mask
コード例 #41
0
import math

print("ceil(4.4)", math.ceil(4.4))
print("floor(4.4)", math.floor(4.4))
print("fabs(4.4)", math.fabs(4.4))

#Factorial = 1 * 2 * 3 * 4
print("factorial(4)", math.factorial(4))

#Return remainder of division
print("fmod(5, 4)", math.fmod(5, 4))

#Receive a float and return an int
print("trunc(4.2)", math.trunc(4.2))

#Return x^y
print("pow(2,2)", math.pow(2, 2))

#return the square root
print("sqrt(4)", math.sqrt(4))

#Special values
print("math.e = ", math.e)
print("math.pi = ", math.pi)

#return e^x
print("exp(4)", math.factorial(4))

#Return the natural locarithm e* e *e ~= 20 so log(20) tells
#you that e^3 ~=20
print("log(20) = ", math.log(20))
コード例 #42
0
from itertools import combinations
from numpy import product
from operator import mul,add
import sys
from decimal import Decimal
from math import fmod
T=int(sys.stdin.readline())
M=10**9+7
for i in range(T):
    N=int(sys.stdin.readline())
    L=map(Decimal, sys.stdin.readline().split())
    if len(L)==2: 
        A=L
        res=(product(L)/sum(L))%M
    else: 
        A=sum([map(list,combinations(L,x)) for x in range(2,N+1)],[])[1:]
        R=map(lambda x:fmod(product(x)/sum(x),M),A)
        print(R)
        res=max(R)
    print("Case #"+str(i+1)+": "+"%.f"%(res))
    T-=1
コード例 #43
0
def plot_dataset(trial_param_file, time_data_file, comment_str, pref_stim):
    print(trial_param_file, time_data_file, pref_stim)

    # Get information from the trial_data_file header
    pfp = open(trial_param_file, 'r')
    lines = pfp.readlines()

    # check if first line is a header line starting with '#'
    # This should be in the format:
    #RUNID  stim_delay stim_length trial_interval sample_length
    header = lines[0].split()
    if header[0][0] == "#":
        RUNID = header[0][1:]
        stim_delay = float(header[1])
        stim_length = float(header[2])
        trial_interval = float(header[3])
        sample_length = float(header[4])
    else:
        print("No header information found!")
        sys.exit()

    # print RUNID, stim_delay, stim_length, trial_interval, sample_length

    ntrials = len(lines) - 1
    # count only the trials with this stimulus type
    # allocate array space for the stimulus parameter data
    trial_time = np.zeros(ntrials)
    stim_type = np.zeros(ntrials)

    # Then fill arrays from remaining lines
    first_pref_trial = -1
    for i in range(1, ntrials + 1):
        data = lines[i].split()
        j = i - 1  # trial number 0 is line 1
        trial_time[j] = float(data[0])
        stim_type[j] = int(data[1])
        if (first_pref_trial < 0) and (stim_type[j] == pref_stim):
            first_pref_trial = j
        # print trial_time[j], stim_type[j]

    pfp.close()

    file_out = True

    print('Reading %s' % time_data_file)
    fp = open(time_data_file, 'r')
    lines = fp.readlines()
    count = len(lines)
    print(count, " lines")

    # determine size of the time step
    line_0 = lines[0].split(" ")
    line_1 = lines[1].split(" ")
    dt = float(line_1[0]) - float(line_0[0])
    print("time step = ", dt)

    # determine size of the sample data
    sample_items = int(sample_length / dt + 0.5) + 1

    # Before the first trial, allocate space
    tn = np.zeros(sample_items)
    yn = np.zeros(sample_items)
    # print len(tn), sample_items

    # Now read the data
    i = 0
    trial_num = 0
    nsamples = 0
    line_num = 0
    finished = False
    # last trial to count is the one before final enty in trial_param_file
    last_trial = ntrials - 2
    trial_end = trial_time[trial_num + 1]
    stype = stim_type[trial_num]
    if stype == pref_stim:
        nsamples += 1
    for line in lines:
        data = line.split(" ")
        t = dt * line_num
        line_num += 1
        # see if we have passed the end of the trial
        if t > trial_end:
            if trial_num < last_trial:
                # start over at the begining of the next sample
                trial_num += 1
                i = 0
                trial_end = trial_time[trial_num + 1]
                stype = stim_type[trial_num]
                if stype == pref_stim:
                    nsamples += 1

            else:  # skip (likely incomplete) data for following trial
                finished = True

        sample_t = math.fmod(t, trial_interval)

        # Add to the array if the sample time is within the sample_length
        if not finished and (i < sample_items) and (stype == pref_stim):
            # Note that tn[i] is replaced, and yn[i] is added to
            tn[i] = sample_t
            yn[i] = yn[i] + float(data[1])
            i += 1

    # end of loop over lines

    if (nsamples < 1):
        return

    t_final = trial_end * trial_interval  # run duration to print

    # Average the data over number of samples having 'pref_stim' stim type
    avg_LFP = yn / nsamples

    # Option to subtract the base level LFP (averaged over t < stim_delay)
    # from LFP(t)

    normalize_baseline = True
    n_base_samples = 0
    LFPbase = 0.0

    imax = int(stim_delay / dt)

    if (normalize_baseline):
        for i in range(0, imax):
            LFPbase += yn[i]
            n_base_samples += 1

        LFPbase /= (n_base_samples * nsamples)
        # print ("baseline average ", LFPbase, " over pref_stim ", pref_stim)
        avg_LFP -= LFPbase

    if (file_out):
        outfile_name = 'LFP-out' + str(pref_stim) + '_' + time_data_file
        print('Writing ', outfile_name)
        outfp = open(outfile_name, 'w')
        imax = int(sample_length / dt)
        for i in range(0, imax):
            outfp.write(str(tn[i]) + " " + str(avg_LFP[i]) + "\n")

    # now do the calculation
    print('alculating average of ', nsamples,
          ' preferred stimulus samples from ', RUNID)
    print("number of trials = ", ntrials - 1, " preferred stimulus type = ",
          pref_stim)
    print('run duration (sec): ', t_final, ' data aquisition interval: ', dt)

    # print run description to the "plot" ax3
    text_str = 'Run ' + runid + ' with trial and stimulus parameters from: ' + \
    trial_param_file +'\n' + 'summed Excitatory Local Field Potentials from: ' \
    + time_data_file + '\n' + str(nsamples) +  ' preferred stimulus samples from ' + \
    str(ntrials-1) + ' trials with preferred stiumulus type ' + str(pref_stim) + '\n' + \
    'sample length (sec): ' +  str(sample_length) + '; stimulus delay: ' + str(stim_delay) + \
     '; pulse width: ' + str(stim_length) + '\n' + \
     'trial interval: ' + str(trial_interval) + '; data interval: ' + str(dt) + \
     '; run time ' + str(t_final)  + '\n\n' + 'Comment: ' + comment_str

    if (pref_stim == 1):
        print(text_str)
コード例 #44
0
ファイル: Viner.py プロジェクト: Xenever/pavlov
print('N:{0}\nf:{1}\ne:{2}'.format(N,f,e))
"""
p=12347
q=13001
N=p*q
e=60728973
mas=[]
n=N
E=e
for i in range(0,20):
    """Дробь может быть бесконечной"""
    mas.append(N//e)
    if N%e==0:
        break
    e1=e
    e=fmod(N,e)
    N=e1

P,Q=[],[]
P.append(0)
P.append(1)
Q.append(0)
Q.append(0)
Q.append(1)
for i in range(2,len(mas)+2):
    P.append(mas[i-2]*P[i-1]+P[i-2])
for i in range(2,len(mas)+1):
    Q.append(mas[i-1]*Q[i]+Q[i-1])
#print(mas)
#print(P)
#print(Q)
コード例 #45
0
def normalizeAngle(rad):
    rad = math.fmod(rad, 2*math.pi)
    if rad > math.pi:
        rad -= math.pi
    return rad
コード例 #46
0
ファイル: polar.py プロジェクト: LizardM4/ratcam-illuminator
def normalize_angle(a):
    a = math.fmod(a, 2. * math.pi)
    return a if a >= 0. else a + 2. * math.pi
コード例 #47
0
ファイル: VPwBlin.py プロジェクト: Alex-Rege/VA-P_wB
def SLC(k, f, e, X, V1, V2):
    f0 = copy.deepcopy(f)
    f1 = copy.deepcopy(f)
    k1 = copy.deepcopy(k)
    e1 = copy.deepcopy(e)
    X1 = copy.deepcopy(X)
    V1bis = copy.deepcopy(V1)
    V2bis = copy.deepcopy(V2)
    #initialisation E et norme E
    E = np.zeros((N, Nbt), dtype=complex)
    Enum = np.zeros((1, Nbt), dtype=complex)
    #première colonne E et première valeur norme E
    E[:, 0:1] = e
    Enum[0] = np.linalg.norm(e1)
    #calcul masse initiale
    m_ini = 0
    for k in range(N - 1):
        for i in range(M1):
            for j in range(M2):
                m_ini += f1[k][i, j]
    real_m_ini = m_ini * dx * dv1 * dv2
    l = [0]
    for t in range(1, Nbt):
        start = time.time()
        if (t % mod == 0):
            print("Time=", t * dt, "et Niter=", t)
            #affichage masse initiale
            print("   masse initiale= ", real_m_ini / L)

            #affichage masse à chaque instant
            masse_non_norma = 0
            for k in range(N - 1):
                for i in range(M1 - 1):
                    for j in range(M2 - 1):
                        masse_non_norma += f1[k][i, j]
            masse = masse_non_norma * dx * dv1 * dv2
            print("   masse courante= ", masse / L)
            print("   Erreur relative de masse= ",
                  (masse - real_m_ini) / real_m_ini)

            masse_quadra = 0
            for k in range(N - 1):
                for i in range(M1 - 1):
                    for j in range(M2 - 1):
                        masse_quadra += abs(f1[k][i, j])**2
            masse_quadra = masse_quadra * dx * dv1 * dv2

            masse_quadra_E = 0
            for k in range(N - 1):
                masse_quadra_E += abs(E[k, t - 1:t])**2
            masse_quadra_E = masse_quadra_E * dx
            print("   énergie quadratique= ", masse_quadra + masse_quadra_E)

            mf0 = [np.abs(np.max(f0[i])) for i in range(len(f1))]
            mff0 = max(mf0)

            f_diff = [f1[i] - f0[i] for i in range(len(f0))]

            mf = [
                max(np.abs(np.max(f_diff[i])), np.abs(np.min(f_diff[i])))
                for i in range(len(f1))
            ]
            #mf=[np.linalg.norm(f_diff[i]) for i in range(len(f1))]

            mff = max(mf)
            l.append(mff)
            mE = linalg.norm(E[:, t - 1:t], np.inf)
            print("   Max Densité f-f0= ", mff)
            print("   Max Champ électrique E= ", mE)

        if (t % modbis == 0):
            Time = np.array([i * dt for i in range(t)])
            Enumt = Enum[0, 0:t]
            Ethet = 4 * 0.424666 * np.exp(-0.0661 * Time) * np.linalg.norm(
                np.sin(0.4 * Xbis)) * np.cos(1.2850 * Time - 0.3357725)
            plt.figure(figsize=(30, 20))
            plt.plot(Time, np.log(Enumt), color='black', label=r'$E$ num')
            axes = plt.gca()
            axes.xaxis.set_ticks([i * t * dt / 10 for i in range(11)])
            axes.xaxis.set_tick_params(length=5, width=3, labelsize=20)
            axes.yaxis.set_tick_params(length=5, width=3, labelsize=20)
            if flag == 2:
                plt.plot(Time,
                         np.log(np.abs(Ethet)),
                         color='red',
                         label=r"$E$ theo $k=$" + str(k1))
                plt.title(r'Landau Damping with $k=$' + str(k1), fontsize=40)
                N_t = math.floor(t * dt / (L / dv1))
                for i in range(1, N_t + 1):
                    plt.axvline(x=i * L / dv1, color='green')
            if flag == 1:
                plt.plot(Time,
                         np.log(np.abs(Ethet)),
                         color='red',
                         label=r"$E$ theo $k=$" + str(k))
                plt.title(r'Landau-Bernstein paradox with $k=$' + str(k1) +
                          " et $\omega_c=$ " + str(omega_c),
                          fontsize=40)

                N_t = math.floor(t * dt / (2 * np.pi / omega_c))
                for i in range(1, N_t + 1):
                    plt.axvline(x=i * 2 * np.pi / omega_c, color='green')
            plt.ylabel('Norm of the electric field', fontsize=30)
            plt.xlabel('Time', fontsize=30)
            plt.legend(loc='upper right', prop={'size': 20})

            LocalDestinationPath = '/home/sidd/Bureau/Recherche/Landau Bernstein Scattering/Partie numérique'  # Changer here for your  local directory
            os.chdir(LocalDestinationPath)
            plt.savefig("Norme du Champ électrique jusqu'à l'iter " + str(t))
        """
       """
        #résolution à v1 et v2 constants
        for i in range(M1):
            Xp = X1 - V1bis[i] * dt

            #périodisation des pieds de caractéristiques
            Xp = Xp - X1[0]
            Xp = [math.fmod(x, X1[-1] - X1[0]) for x in Xp]
            for p in range(len(Xp)):
                if Xp[p] < 0:
                    Xp[p] += X1[-1]
                else:
                    Xp[p] += X1[0]
            """
          """

            #Xp=Xp+(Xp<0)*X1[-1]-(Xp>X1[-1])*X1[-1]
            #print(Xp)
            for j in range(M2):
                fij = [f1[k][i, j] for k in range(N)]
                fij[-1] = fij[0]

                #interpolation par splines cubiques
                a = scipy.interpolate.CubicSpline(X1, fij,
                                                  bc_type='periodic')(Xp)
                for k in range(N):
                    f1[k][i, j] = a[k]
        """    
       masse_non_norma=0
       for k in range(N-1):
          for i in range(M1-1):
           for j in range(M2-1):
              masse_non_norma+=f1[k][i,j]
       masse=masse_non_norma*dx*dv1*dv2
       print("     masse courante phase 1= ",masse/L)
       print("     Erreur relative de masse phase 1= ", (masse-real_m_ini)/real_m_ini)
       """
        masse_quadra = 0
        for k in range(N - 1):
            for i in range(M1 - 1):
                for j in range(M2 - 1):
                    masse_quadra += abs(f1[k][i, j])**2
        masse_quadra = masse_quadra * dx * dv1 * dv2

        masse_quadra_E = 0
        for k in range(N - 1):
            masse_quadra_E += abs(E[k, t - 1:t])**2
        masse_quadra_E = masse_quadra_E * dx
        print("   énergie quadratique phase 1= ",
              masse_quadra + masse_quadra_E)

        #résolution de Poisson
        E[:, t:t + 1] = Poisson_trap(f1)
        #        print ('E=',Poisson_trap(dx,dv,f1))
        if (t % mod == 0):
            I = 0.
            for j in range(N - 1):
                I = I + E[:, t:t + 1][j]

            #print ('   Integrale E= ', I*dx)
        Enum[0, t] = np.linalg.norm(E[0:N - 1, t:t + 1])

        #résolution étape avec terme source
        for k in range(N):
            f1[k] = f1[k] - dt * second_membre(E[:, t:t + 1])[k]

        masse_quadra = 0
        for k in range(N - 1):
            for i in range(M1 - 1):
                for j in range(M2 - 1):
                    masse_quadra += abs(f1[k][i, j])**2
        masse_quadra = masse_quadra * dx * dv1 * dv2

        masse_quadra_E = 0
        for k in range(N - 1):
            masse_quadra_E += abs(E[k, t - 1:t])**2
        masse_quadra_E = masse_quadra_E * dx
        print("   énergie quadratique phase 2= ",
              masse_quadra + masse_quadra_E)

        #Seconde actualisation champ électrique
        E[:, t:t + 1] = Poisson_trap(f1)
        #        print ('E=',Poisson_trap(dx,dv,f1))
        if (t % mod == 0):
            I = 0.
            for j in range(N - 1):
                I = I + E[:, t:t + 1][j]

            #print ('   Integrale E= ', I*dx)
        Enum[0, t] = np.linalg.norm(E[0:N - 1, t:t + 1])
        """
       """
        #résolution à x et v2 constants

        for j in range(M2):
            V1bisp = V1bis + omega_c * V2bis[j] * dt

            #périodisation des pieds de caractéristiques
            V1bisp = V1bisp - V1bis[0]
            V1bisp = [math.fmod(x, V1bis[-1] - V1bis[0]) for x in V1bisp]
            for p in range(len(V1bisp)):
                if V1bisp[p] < 0:
                    V1bisp[p] += V1bis[-1]
                else:
                    V1bisp[p] += V1bis[0]
            """
               """
            #V1bisp=V1bisp+(V1bisp<V1bis[0])*(V1bis[-1]-V1bis[0])-(V1bisp>V1bis[-1])*(V1bis[-1]-V1bis[0])
            for k in range(N):
                fkj = [f1[k][i, j] for i in range(M1)]
                fkj[0] = fkj[-1]
                """
                   for i in range(M1):
                       if (V1bisp[i]>=V1[-1] or V1bisp[i]<=V1[0]):
                           fkj[i]=0       
               
                   """

                #interpolation par spline cubique
                #a=scipy.interpolate.CubicSpline(V1bis,fkj,bc_type='clamped')(V1bisp)
                a = scipy.interpolate.CubicSpline(V1bis,
                                                  fkj,
                                                  bc_type='periodic')(V1bisp)
                f1[k][:, j:j + 1] = np.transpose(
                    np.array([[a[i] for i in range(M1)]]))
        """
       masse_non_norma=0
       for k in range(N-1):
          for i in range(M1-1):
           for j in range(M2-1):
              masse_non_norma+=f1[k][i,j]
       masse=masse_non_norma*dx*dv1*dv2
       print("     masse courante phase 2= ",masse/L)
       print("     Erreur relative de masse phase 2= ", (masse-real_m_ini)/real_m_ini)
       """
        masse_quadra = 0
        for k in range(N - 1):
            for i in range(M1 - 1):
                for j in range(M2 - 1):
                    masse_quadra += abs(f1[k][i, j])**2
        masse_quadra = masse_quadra * dx * dv1 * dv2

        masse_quadra_E = 0
        for k in range(N - 1):
            masse_quadra_E += abs(E[k, t - 1:t])**2
        masse_quadra_E = masse_quadra_E * dx
        print("   énergie quadratique phase 3= ",
              masse_quadra + masse_quadra_E)
        #résolution à x et v1 constants

        for i in range(M1):
            V2bisp = V2bis - omega_c * V1bis[i] * dt
            #périodisation des pieds de caractéristiques
            V2bisp = V2bisp - V2bis[0]
            V2bisp = [math.fmod(x, V2bis[-1] - V2bis[0]) for x in V2bisp]
            for p in range(len(V2bisp)):
                if V2bisp[p] < 0:
                    V2bisp[p] += V2bis[-1]
                else:
                    V2bisp[p] += V2bis[0]

            #V2bisp=V2bisp+(V2bisp<V2bis[0])*(V2bis[-1]-V2bis[0])-(V2bisp>V2bis[-1])*(V2bis[-1]-V2bis[0])
            for k in range(N):
                fki = [f1[k][i, j] for j in range(M2)]
                fki[0] = fki[-1]
                """
                   for j in range(M2):
                       if (V2bisp[j]>=V2[-1] or V2bisp[j]<=V2[0]):
                           fki[j]=0     
                   """

                #interpolation par spline cubique
                a = scipy.interpolate.CubicSpline(V2bis,
                                                  fki,
                                                  bc_type='periodic')(V2bisp)
                f1[k][i:i + 1, :] = np.array([[a[j] for j in range(M2)]])
        """
       masse_non_norma=0
       for k in range(N-1):
          for i in range(M1-1):
           for j in range(M2-1):
              masse_non_norma+=f1[k][i,j]
       masse=masse_non_norma*dx*dv1*dv2
       print("     masse courante phase 3= ",masse/L)
       print("     Erreur relative de masse phase 3= ", (masse-real_m_ini)/real_m_ini)
       """
        masse_quadra = 0
        for k in range(N - 1):
            for i in range(M1 - 1):
                for j in range(M2 - 1):
                    masse_quadra += abs(f1[k][i, j])**2
        masse_quadra = masse_quadra * dx * dv1 * dv2

        masse_quadra_E = 0
        for k in range(N - 1):
            masse_quadra_E += abs(E[k, t - 1:t])**2
        masse_quadra_E = masse_quadra_E * dx
        print("   énergie quadratique phase 4= ",
              masse_quadra + masse_quadra_E)
        """
       if(t % mod==0):
         fxv3=np.real(f0[n])
         fxv4=np.imag(f0[n])
         fxv5=np.absolute(f0[n])
         
                  
         
         fxv3end=np.real(f1[n])
         fxv4end=np.imag(f1[n])
         fxv5end=np.absolute(f1[n])
         
         
         
         er=np.real(e1)
         ei=np.imag(e1)
         
         
         Erend=np.real(E[:,t:t+1])
         Eiend=np.imag(E[:,t:t+1])
         
         
         
         
         
         plt.figure()
         plt.figure(figsize = (30, 20))
         plt.subplot(2, 3, 1)
         plt.pcolormesh(V2, V1, fxv3,cmap='RdBu')
         plt.title("densité u initiale REELLE dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 2)
         plt.pcolormesh(V2, V1, np.cos(lambda_m*t*dt)*fxv3-np.sin(lambda_m*t*dt)*fxv4,cmap='RdBu')
         plt.title("densité u théorique REELLE au temps "+str(t)+" dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 3)
         plt.pcolormesh(V2, V1, fxv3end,cmap='RdBu')
         plt.title("densité u numérique REELLE au temps "+str(t)+" dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 4)
         plt.pcolormesh(V2, V1, fxv4,cmap='RdBu')
         plt.title("densité u initiale IMAGINAIRE dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 5)
         plt.pcolormesh(V2, V1, np.sin(lambda_m*t*dt)*fxv3+np.cos(lambda_m*t*dt)*fxv4,cmap='RdBu')
         plt.title("densité u théorique IMAGINAIRE au temps "+str(t)+" dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 6)
         plt.pcolormesh(V2, V1, fxv4end,cmap='RdBu')
         plt.title("densité u numérique IMAGINAIRE au temps "+str(t)+" dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         LocalDestinationPath = '/home/sidd/Bureau/Programmation/Python/Images NumKin 2019/VPlin' 
         os.chdir(LocalDestinationPath)
         plt.savefig("u_VP_"+str(t))
         
         
         plt.figure()
         plt.figure(figsize = (30, 20))
         plt.subplot(2, 2, 1)
         plt.pcolormesh(V2, V1, fxv5,cmap='RdBu')
         plt.title("densité u initiale MODULE dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 2, 2)
         plt.pcolormesh(V2, V1, fxv5end,cmap='RdBu')
         plt.title("densité u numérique MODULE au temps "+str(t)+" dans le plan V1-V2 pour x="+str(0))
         plt.colorbar()
         plt.ylabel('V2')
         plt.xlabel('V1')
         axes = plt.gca()
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.subplot(2, 3, 4)
         plt.plot(X, er,'x',label="initial")
         plt.plot(X,np.cos(lambda_m*t*dt)*er-np.sin(lambda_m*t*dt)*ei,label="théorique au temps"+str(t))
         plt.plot(X, Erend,label="numérique au temps"+str(t))
         plt.title("champ électrique REELLE")
         plt.ylabel('E réel')
         plt.xlabel('X')
         axes = plt.gca()
         plt.xticks([0,np.pi/2, np.pi, 3*np.pi/2,2*np.pi], [r'$0$',r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.grid()
         plt.subplot(2, 3, 5)
         plt.plot(X, ei,'x',label="initial")
         plt.plot(X,np.sin(lambda_m*t*dt)*er+np.cos(lambda_m*t*dt)*ei,label="théorique au temps"+str(t))
         plt.plot(X, Eiend,label="numérique au temps "+str(t))
         plt.title("champ électrique IMAGINAIRE")
         plt.ylabel('E imaginaire')
         plt.xlabel('X')
         axes = plt.gca()
         plt.xticks([0,np.pi/2, np.pi, 3*np.pi/2,2*np.pi], [r'$0$',r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)   
         plt.legend()
         plt.grid()
         plt.subplot(2, 3, 6)
         plt.axis([0,2*np.pi,0, 1.2])
         plt.plot(X, np.absolute(er+1j*ei),label="initial")
         #plt.plot(X,np.absolute(np.sin(lambda_m*T)*er+np.cos(lambda_m*T)*ei),label="théorique final")
         plt.plot(X, np.absolute(E[:,t:t+1]),label="numérique au temps "+str(t))
         plt.title("champ électrique MODULE")
         plt.ylabel('E module')
         plt.xlabel('X')
         axes = plt.gca()
         plt.xticks([0,np.pi/2, np.pi, 3*np.pi/2,2*np.pi], [r'$0$',r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
         axes.xaxis.set_tick_params(length=5, width=3,labelsize=20)
         axes.yaxis.set_tick_params(length=5, width=3,labelsize=20)  
         plt.legend()
         plt.grid()
         LocalDestinationPath = '/home/sidd/Bureau/Programmation/Python/Images NumKin 2019/VPlin' 
         os.chdir(LocalDestinationPath)
         plt.savefig("mu_F_VP_"+str(t))
         """

        end = time.time()
        print("   Elapsed for one iteration = %s" % (end - start))

    return [E, Enum, f1]
コード例 #48
0
    def _compute_extra_keys(self):
        """Compute our extra keys."""
        global unknown_string

        self.extra_keys = {}
        forecastTime = self.startStep

        # regular or rotated grid?
        try:
            longitudeOfSouthernPoleInDegrees = \
                self.longitudeOfSouthernPoleInDegrees
            latitudeOfSouthernPoleInDegrees = \
                self.latitudeOfSouthernPoleInDegrees
        except AttributeError:
            longitudeOfSouthernPoleInDegrees = 0.0
            latitudeOfSouthernPoleInDegrees = 90.0

        centre = gribapi.grib_get_string(self.grib_message, "centre")

        # default values
        self.extra_keys = {'_referenceDateTime': -1.0,
                           '_phenomenonDateTime': -1.0,
                           '_periodStartDateTime': -1.0,
                           '_periodEndDateTime': -1.0,
                           '_levelTypeName': unknown_string,
                           '_levelTypeUnits': unknown_string,
                           '_firstLevelTypeName': unknown_string,
                           '_firstLevelTypeUnits': unknown_string,
                           '_firstLevel': -1.0,
                           '_secondLevelTypeName': unknown_string,
                           '_secondLevel': -1.0,
                           '_originatingCentre': unknown_string,
                           '_forecastTime': None,
                           '_forecastTimeUnit': unknown_string,
                           '_coord_system': None,
                           '_x_circular': False,
                           '_x_coord_name': unknown_string,
                           '_y_coord_name': unknown_string,
                           # These are here to avoid repetition in the rules
                           # files, and reduce the very long line lengths.
                           '_x_points': None,
                           '_y_points': None,
                           '_cf_data': None}

        # cf phenomenon translation
        # Get centre code (N.B. self.centre has default type = string)
        centre_number = gribapi.grib_get_long(self.grib_message, "centre")
        # Look for a known grib1-to-cf translation (or None).
        cf_data = gptx.grib1_phenom_to_cf_info(
            table2_version=self.table2Version,
            centre_number=centre_number,
            param_number=self.indicatorOfParameter)
        self.extra_keys['_cf_data'] = cf_data

        # reference date
        self.extra_keys['_referenceDateTime'] = \
            datetime.datetime(int(self.year), int(self.month), int(self.day),
                              int(self.hour), int(self.minute))

        # forecast time with workarounds
        self.extra_keys['_forecastTime'] = forecastTime

        # verification date
        processingDone = self._get_processing_done()
        # time processed?
        if processingDone.startswith("time"):
            validityDate = str(self.validityDate)
            validityTime = "{:04}".format(int(self.validityTime))
            endYear = int(validityDate[:4])
            endMonth = int(validityDate[4:6])
            endDay = int(validityDate[6:8])
            endHour = int(validityTime[:2])
            endMinute = int(validityTime[2:4])

            # fixed forecastTime in hours
            self.extra_keys['_periodStartDateTime'] = \
                (self.extra_keys['_referenceDateTime'] +
                 datetime.timedelta(hours=int(forecastTime)))
            self.extra_keys['_periodEndDateTime'] = \
                datetime.datetime(endYear, endMonth, endDay, endHour,
                                  endMinute)
        else:
            self.extra_keys['_phenomenonDateTime'] = \
                self._get_verification_date()

        # originating centre
        # TODO #574 Expand to include sub-centre
        self.extra_keys['_originatingCentre'] = CENTRE_TITLES.get(
            centre, "unknown centre %s" % centre)

        # forecast time unit as a cm string
        # TODO #575 Do we want PP or GRIB style forecast delta?
        self.extra_keys['_forecastTimeUnit'] = self._timeunit_string()

        # shape of the earth

        # pre-defined sphere
        if self.shapeOfTheEarth == 0:
            geoid = coord_systems.GeogCS(semi_major_axis=6367470)

        # custom sphere
        elif self.shapeOfTheEarth == 1:
            geoid = coord_systems.GeogCS(
                self.scaledValueOfRadiusOfSphericalEarth *
                10 ** -self.scaleFactorOfRadiusOfSphericalEarth)

        # IAU65 oblate sphere
        elif self.shapeOfTheEarth == 2:
            geoid = coord_systems.GeogCS(6378160, inverse_flattening=297.0)

        # custom oblate spheroid (km)
        elif self.shapeOfTheEarth == 3:
            geoid = coord_systems.GeogCS(
                semi_major_axis=self.scaledValueOfEarthMajorAxis *
                10 ** -self.scaleFactorOfEarthMajorAxis * 1000.,
                semi_minor_axis=self.scaledValueOfEarthMinorAxis *
                10 ** -self.scaleFactorOfEarthMinorAxis * 1000.)

        # IAG-GRS80 oblate spheroid
        elif self.shapeOfTheEarth == 4:
            geoid = coord_systems.GeogCS(6378137, None, 298.257222101)

        # WGS84
        elif self.shapeOfTheEarth == 5:
            geoid = \
                coord_systems.GeogCS(6378137, inverse_flattening=298.257223563)

        # pre-defined sphere
        elif self.shapeOfTheEarth == 6:
            geoid = coord_systems.GeogCS(6371229)

        # custom oblate spheroid (m)
        elif self.shapeOfTheEarth == 7:
            geoid = coord_systems.GeogCS(
                semi_major_axis=self.scaledValueOfEarthMajorAxis *
                10 ** -self.scaleFactorOfEarthMajorAxis,
                semi_minor_axis=self.scaledValueOfEarthMinorAxis *
                10 ** -self.scaleFactorOfEarthMinorAxis)

        elif self.shapeOfTheEarth == 8:
            raise ValueError("unhandled shape of earth : grib earth shape = 8")

        else:
            raise ValueError("undefined shape of earth")

        gridType = gribapi.grib_get_string(self.grib_message, "gridType")

        if gridType in ["regular_ll", "regular_gg", "reduced_ll",
                        "reduced_gg"]:
            self.extra_keys['_x_coord_name'] = "longitude"
            self.extra_keys['_y_coord_name'] = "latitude"
            self.extra_keys['_coord_system'] = geoid
        elif gridType == 'rotated_ll':
            # TODO: Confirm the translation from angleOfRotation to
            # north_pole_lon (usually 0 for both)
            self.extra_keys['_x_coord_name'] = "grid_longitude"
            self.extra_keys['_y_coord_name'] = "grid_latitude"
            southPoleLon = longitudeOfSouthernPoleInDegrees
            southPoleLat = latitudeOfSouthernPoleInDegrees
            self.extra_keys['_coord_system'] = \
                coord_systems.RotatedGeogCS(
                    -southPoleLat,
                    math.fmod(southPoleLon + 180.0, 360.0),
                    self.angleOfRotation, geoid)
        elif gridType == 'polar_stereographic':
            self.extra_keys['_x_coord_name'] = "projection_x_coordinate"
            self.extra_keys['_y_coord_name'] = "projection_y_coordinate"

            if self.projectionCentreFlag == 0:
                pole_lat = 90
            elif self.projectionCentreFlag == 1:
                pole_lat = -90
            else:
                raise TranslationError("Unhandled projectionCentreFlag")

            # Note: I think the grib api defaults LaDInDegrees to 60 for grib1.
            self.extra_keys['_coord_system'] = \
                coord_systems.Stereographic(
                    pole_lat, self.orientationOfTheGridInDegrees, 0, 0,
                    self.LaDInDegrees, ellipsoid=geoid)

        elif gridType == 'lambert':
            self.extra_keys['_x_coord_name'] = "projection_x_coordinate"
            self.extra_keys['_y_coord_name'] = "projection_y_coordinate"

            flag_name = "projectionCenterFlag"

            if getattr(self, flag_name) == 0:
                pole_lat = 90
            elif getattr(self, flag_name) == 1:
                pole_lat = -90
            else:
                raise TranslationError("Unhandled projectionCentreFlag")

            LambertConformal = coord_systems.LambertConformal
            self.extra_keys['_coord_system'] = LambertConformal(
                self.LaDInDegrees, self.LoVInDegrees, 0, 0,
                secant_latitudes=(self.Latin1InDegrees, self.Latin2InDegrees),
                ellipsoid=geoid)
        else:
            raise TranslationError("unhandled grid type: {}".format(gridType))

        if gridType in ["regular_ll", "rotated_ll"]:
            self._regular_longitude_common()
            j_step = self.jDirectionIncrementInDegrees
            if not self.jScansPositively:
                j_step = -j_step
            self._y_points = (np.arange(self.Nj, dtype=np.float64) * j_step +
                              self.latitudeOfFirstGridPointInDegrees)

        elif gridType in ['regular_gg']:
            # longitude coordinate is straight-forward
            self._regular_longitude_common()
            # get the distinct latitudes, and make sure they are sorted
            # (south-to-north) and then put them in the right direction
            # depending on the scan direction
            latitude_points = gribapi.grib_get_double_array(
                    self.grib_message, 'distinctLatitudes').astype(np.float64)
            latitude_points.sort()
            if not self.jScansPositively:
                # we require latitudes north-to-south
                self._y_points = latitude_points[::-1]
            else:
                self._y_points = latitude_points

        elif gridType in ["polar_stereographic", "lambert"]:
            # convert the starting latlon into meters
            cartopy_crs = self.extra_keys['_coord_system'].as_cartopy_crs()
            x1, y1 = cartopy_crs.transform_point(
                self.longitudeOfFirstGridPointInDegrees,
                self.latitudeOfFirstGridPointInDegrees,
                ccrs.Geodetic())

            if not np.all(np.isfinite([x1, y1])):
                raise TranslationError("Could not determine the first latitude"
                                       " and/or longitude grid point.")

            self._x_points = x1 + self.DxInMetres * np.arange(self.Nx,
                                                              dtype=np.float64)
            self._y_points = y1 + self.DyInMetres * np.arange(self.Ny,
                                                              dtype=np.float64)

        elif gridType in ["reduced_ll", "reduced_gg"]:
            self._x_points = self.longitudes
            self._y_points = self.latitudes

        else:
            raise TranslationError("unhandled grid type")
コード例 #49
0
ファイル: _trackball.py プロジェクト: wuyou33/OMG-Planner
 def phi(self, phi):
     self._set_orientation(math.fmod(self._theta, 360.0), math.fmod(phi, 360.0))
コード例 #50
0
    def measureKronInPython(self,
                            objImg,
                            xcen,
                            ycen,
                            nsigma,
                            kfac,
                            nIterForRadius,
                            makeImage=None):
        """Measure the Kron quantities of an elliptical Gaussian in python.

        N.b. only works for XY0 == (0, 0)
        """
        #
        # Measure moments using SDSS shape algorithm
        #
        # Note: this code was converted to the new meas_framework, but is not exercised.
        msConfig = makeMeasurementConfig(False, nsigma, nIterForRadius, kfac)
        center = geom.Point2D(xcen, ycen)
        source = self.measureFree(objImg, center, msConfig)
        algMeta = source.getTable().getMetadata()
        self.assertTrue(
            algMeta.exists('EXT_PHOTOMETRYKRON_KRONFLUX_NRADIUSFORFLUX'))

        Mxx = source.getIxx()
        Mxy = source.getIxy()
        Myy = source.getIyy()
        #
        # Calculate principal axes
        #
        Muu_p_Mvv = Mxx + Myy
        Muu_m_Mvv = math.sqrt((Mxx - Myy)**2 + 4 * Mxy**2)
        Muu = 0.5 * (Muu_p_Mvv + Muu_m_Mvv)
        Mvv = 0.5 * (Muu_p_Mvv - Muu_m_Mvv)
        theta = 0.5 * math.atan2(2 * Mxy, Mxx - Myy)
        a = math.sqrt(Muu)
        b = math.sqrt(Mvv)
        ab = a / b
        #
        # Get footprint
        #
        ellipse = afwEllipses.Ellipse(
            afwEllipses.Axes(nsigma * a, nsigma * b, theta),
            geom.Point2D(xcen, ycen))
        fpEllipse = afwDetection.Footprint(ellipse)

        sumI = 0.0
        sumR = (0.38259771140356325 / ab *
                (1 + math.sqrt(2) *
                 math.hypot(math.fmod(xcen, 1), math.fmod(ycen, 1))) *
                objImg.image[int(xcen), int(ycen), afwImage.LOCAL])

        gal = objImg.image

        c, s = math.cos(theta), math.sin(theta)
        for sp in fpEllipse.getSpans():
            y, x0, x1 = sp.getY(), sp.getX0(), sp.getX1()

            for x in range(x0, x1 + 1):
                dx, dy = x - xcen, y - ycen
                u = c * dx + s * dy
                v = -s * dx + c * dy

                r = math.hypot(u, v * ab)
                try:
                    val = gal[x, y, afwImage.LOCAL]
                except Exception:
                    continue

                sumI += val
                sumR += val * r

        R_K = sumR / sumI

        sumI = 0.0
        for y in range(self.height):
            for x in range(self.width):
                dx, dy = x - xcen, y - ycen
                u = c * dx + s * dy
                v = -s * dx + c * dy
                if math.hypot(u / a, v / b) < kfac:
                    sumI += gal[x, y, afwImage.LOCAL]

        return R_K, sumI, 0, False, False, False
コード例 #51
0
print('ceil(x) Return the smallest integral value >= x')
for x in [0, 0.01, 0.49, 0.5, 0.51, 0.9, -0.9, -0.5, -0.1]:
    ceiled_x = math.ceil(x)
    print('ceil({0: 6.2f}) = {1: 6.2f}'.format(x, ceiled_x))

# floor(x) Return the floor of x as a float. This is the largest integral value <= x.
print('floor(x) Return the largest integral value <= x')
for x in [-1.1, -0.9, -0.1, 0, 0.1, 0.9, 1.1]:
    print('x={0: 6.4f}, math.floor(x)={1: 6.4f}'.format(x, math.floor(x)))

# fabs(x) Return the absolute value of the float x.
for x in [-2, -0.5, 0, 2, 4.5]:
    print('x = {0}, math.fabs(x) = {1}'.format(x, math.fabs(x)))

# fmod(x, y) Return fmod(x, y), according to platform C.  x % y may differ.
print('\nmath.fmod(10, 3):', math.fmod(10, 3))
print('10 % 3:', 10 % 3)

# factorial(x) -> Integral Find x!. Raise a ValueError if x is negative or non-integral.
print('\nmath.factorial(5) =', math.factorial(5))

# fsum(iterable) Return an accurate floating point sum of values in the iterable. Assumes IEEE-754 floating point arithmetic.
print('\nmath.fsum(range(1, 5)) = 1+2+3+4 =', math.fsum(range(1, 5)))

# modf(x) Return the fractional and integer parts of x.  Both results carry the sign of x and are floats.
print('\nmath.modf(2.5) =', math.modf(2.5))

# isinf(x) -> bool Check if float x is infinite (positive or negative).
# isnan(x) -> bool Check if float x is not a number (NaN).

# pow(x, y) Return x**y (x to the power of y).
コード例 #52
0
ファイル: _trackball.py プロジェクト: wuyou33/OMG-Planner
 def theta(self, theta):
     self._set_orientation(math.fmod(theta, 360.0), math.fmod(self._phi, 360.0))
コード例 #53
0
 def __init__(self, windSpeedMetersPerSecond, windDirectionDegrees):
     assert (windSpeedMetersPerSecond >= 0.0)
     assert (windDirectionDegrees >= 0.0) and (windDirectionDegrees <= 360.0)
     
     self.windSpeedMetersPerSecond = windSpeedMetersPerSecond
     self.windDirectionDegrees = math.fmod(windDirectionDegrees + 180.0, 360.0)
コード例 #54
0
ファイル: pathgenerator.py プロジェクト: proto3/pywing
 def get_point(self, degree):
     angle_from_start = (self.ccw * 2 - 1) * self.rad_len * degree
     angle = math.fmod(self.rad_start + angle_from_start + 2 * math.pi, 2 * math.pi)
     return self.center + self.radius * np.array([math.cos(angle), math.sin(angle)])
コード例 #55
0
def stairs(t, n_stair=10, dt_stair=0.5, _min=0, _max=20):
    a = int(math.fmod(t, dt_stair * n_stair) / dt_stair)
    return _min + (_max - _min) * a / n_stair
コード例 #56
0
ファイル: CWOA.py プロジェクト: diogoadias/MetaHeuristics
def CWOA(objf,lb,ub,dim,SearchAgents_no,Max_iter):
    
    #dim=30
    #SearchAgents_no=50
    #lb=-100
    #ub=100
    #Max_iter=500
    if not isinstance(lb, list):
        lb = [lb] * dim
    if not isinstance(ub, list):
        ub = [ub] * dim
            
        
    # initialize position vector and score for the leader
    Leader_pos=numpy.zeros(dim)
    Leader_score=float("inf")  #change this to -inf for maximization problems
        
        
    #Initialize the positions of search agents
    Positions = numpy.zeros((SearchAgents_no, dim))
    for i in range(dim):
        Positions[:, i] = numpy.random.uniform(0,1,SearchAgents_no) *(ub[i]-lb[i])+lb[i]
    

    #Initialize convergence
    convergence_curve=numpy.zeros(Max_iter)
        
        
    ############################
    s=solution()

    print("CWOA is optimizing  \""+objf.__name__+"\"")    

    timerStart=time.time() 
    s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S")
    ############################
        
    t=0  # Loop counter
    
        
    # Main loop
    while t<Max_iter:
        for i in range(0,SearchAgents_no):
                
            # Return back the search agents that go beyond the boundaries of the search space
               
            #Positions[i,:]=checkBounds(Positions[i,:],lb,ub)
            for j in range(dim):        
                Positions[i,j]=numpy.clip(Positions[i,j], lb[j], ub[j])
                
            # Calculate objective function for each search agent
            fitness=objf(Positions[i,:])
               
            # Update the leader
            if fitness<Leader_score: # Change this to > for maximization problem
                Leader_score=fitness; # Update alpha
                Leader_pos=Positions[i,:].copy() # copy current whale position into the leader position
       
       
        a=2-t*((2)/Max_iter); # a decreases linearly fron 2 to 0 in Eq. (2.3)
            
        # a2 linearly decreases from -1 to -2 to calculate t in Eq. (3.12)
        a2=-1+t*((-1)/Max_iter);        
            
        # Update the Position of search agents 
        for i in range(0,SearchAgents_no):
            r1=random.random() # r1 is a random number in [0,1]
            r2=random.random() # r2 is a random number in [0,1]
                
            A=2*a*r1-a  # Eq. (2.3) in the paper
            C=2*r2      # Eq. (2.4) in the paper
                    
            b=1;               #  parameters in Eq. (2.5)
            l=(a2-1)*random.random()+1   #  parameters in Eq. (2.5)
                
            p = random.random()        # p in Eq. (2.6)

            # Chaotic maps
            # cm = numpy.random.choice(numpy.arange(8))
            cm = 8

            if cm == 1:
                # Logistic
                Positions[i,j] = a*Positions[i,j]*(1-Positions[i,j])
            elif cm == 2:
                # Cubic
                Positions[i,j] = a*Positions[i,j]*(1-(Positions[i,j]**2))
            elif cm == 3:
                # Sine
                Positions[i,j] = (a/4)*math.sin(math.pi*Positions[i,j])
            elif cm == 4:
                # Sinusoidal
                Positions[i,j] = a*(Positions[i,j]**2)*math.sin(math.pi*Positions[i,j])
            elif cm == 5:
                # Singer
                u = 1.07
                Positions[i,j] = u*(7.86*Positions[i,j]-23.31*(Positions[i,j]**2)+28.75*(Positions[i,j]**3)-13.302875*(Positions[i,j]**4))
            elif cm == 6:
                # Circle
                b = 1
                k = dim -1
                Positions[i,j] = math.fmod(Positions[i,j]+b-(a/2*math.pi)*math.sin(2*math.pi*Positions[i,k]), 1)
            elif cm == 7:
                # Iterative
                Positions[i,j] = math.sin((a*math.pi)/Positions[i,j])
            elif cm == 8:
                # Tent Chaotic Map
                if(Positions[i,j] < 0.7):
                    Positions[i,j] = Positions[i,j] / 0.7
                else:
                    Positions[i,j] = (10/3)*(1-Positions[i,j])   
                
            for j in range(0,dim):
                    
                if p<0.5:
                    if abs(A)>=1:
                        rand_leader_index = math.floor(SearchAgents_no*random.random());
                        X_rand = Positions[rand_leader_index, :]
                        D_X_rand=abs(C*X_rand[j]-Positions[i,j]) 
                        Positions[i,j]=X_rand[j]-A*D_X_rand      
                            
                    elif abs(A)<1:
                        D_Leader=abs(C*Leader_pos[j]-Positions[i,j]) 
                        Positions[i,j]=Leader_pos[j]-A*D_Leader      
                        
                        
                elif p>=0.5:
                    
                    distance2Leader=abs(Leader_pos[j]-Positions[i,j])
                    # Eq. (2.5)
                    Positions[i,j]=distance2Leader*math.exp(b*l)*math.cos(l*2*math.pi)+Leader_pos[j]
                      
            
        convergence_curve[t]=Leader_score
        if (t%1==0):
            print(['At iteration '+ str(t)+ ' the best fitness is '+ str(Leader_score)]);
        t=t+1
        
    timerEnd=time.time()  
    s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S")
    s.executionTime=timerEnd-timerStart
    s.convergence=convergence_curve
    s.optimizer="CWOA"   
    s.objfname=objf.__name__
    s.best = Leader_score
    s.bestIndividual = Leader_pos
    s.std = numpy.std(convergence_curve)
    s.mean = numpy.average(convergence_curve)
       
    return s
コード例 #57
0
import math

print('{:^4} {:^4} {:^5} {:^5}'.format('x', 'y', '%', 'fmod'))
print('{:-^4} {:-^4} {:-^5} {:-^5}'.format('-', '-', '-', '-'))

INPUTS = [
    (5, 2),
    (5, -2),
    (-5, 2),
]

for x, y in INPUTS:
    print('{:4.1f} {:4.1f} {:5.2f} {:5.2f}'.format(
        x,
        y,
        x % y,
        math.fmod(x, y),
    ))
コード例 #58
0
 def testFmod(self):
     self.assertRaises(TypeError, math.fmod)
     self.ftest('fmod(10,1)', math.fmod(10,1), 0)
     self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
     self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
     self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
     self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
     self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
     self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
     self.assertTrue(math.isnan(math.fmod(1., NAN)))
     self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
     self.assertRaises(ValueError, math.fmod, 1., 0.)
     self.assertRaises(ValueError, math.fmod, INF, 1.)
     self.assertRaises(ValueError, math.fmod, NINF, 1.)
     self.assertRaises(ValueError, math.fmod, INF, 0.)
     self.assertEqual(math.fmod(3.0, INF), 3.0)
     self.assertEqual(math.fmod(-3.0, INF), -3.0)
     self.assertEqual(math.fmod(3.0, NINF), 3.0)
     self.assertEqual(math.fmod(-3.0, NINF), -3.0)
     self.assertEqual(math.fmod(0.0, 3.0), 0.0)
     self.assertEqual(math.fmod(0.0, NINF), 0.0)
コード例 #59
0
def step(t, a0=-1, a1=1, dt=4, t0=0):
    return a0 if math.fmod(t + t0, dt) > dt / 2 else a1
コード例 #60
0
def intersection_point(a_lat,
                       a_lon,
                       a_bearing,
                       b_lat,
                       b_lon,
                       b_bearing,
                       debug=False):
    a_lat = math.radians(a_lat)
    a_lon = math.radians(a_lon)

    b_lat = math.radians(b_lat)
    b_lon = math.radians(b_lon)

    brng13 = math.radians(a_bearing)
    brng23 = math.radians(b_bearing)

    dLat = (b_lat - a_lat)
    dLon = (b_lon - a_lon)

    dist12 = 2.0 * math.asin(
        math.sqrt(
            math.sin(dLat / 2.0) * math.sin(dLat / 2.0) + math.cos(a_lat) *
            math.cos(b_lat) * math.sin(dLon / 2.0) * math.sin(dLon / 2.0)))

    if (dist12 == 0.0):
        if (debug): print "Intersection ERROR: points are too close!"
        return None

    # initial/final bearings between points
    try:
        brngA = math.acos(
            (math.sin(b_lat) - math.sin(a_lat) * math.cos(dist12)) /
            (math.sin(dist12) * math.cos(a_lat)))
    except Exception as inst:
        if (debug): print "Intersection EXCEPTION: " + str(inst)
        return None

    # protect against rounding
    if (math.isnan(brngA)):
        brngA = 0.0

    try:
        brngB = math.acos(
            (math.sin(a_lat) - math.sin(b_lat) * math.cos(dist12)) /
            (math.sin(dist12) * math.cos(b_lat)))
    except Exception as inst:
        if (debug): print "Intersection EXCEPTION: " + str(inst)
        return None

    if (math.sin(b_lon - a_lon) > 0):
        brng12 = brngA
        brng21 = 2.0 * math.pi - brngB
    else:
        brng12 = 2.0 * math.pi - brngA
        brng21 = brngB

    alpha1 = (brng13 - brng12 + math.pi) % (2.0 * math.pi) - math.pi
    alpha2 = (brng21 - brng23 + math.pi) % (2.0 * math.pi) - math.pi

    # infinite intersections
    if ((math.sin(alpha1) == 0.0) and (math.sin(alpha2) == 0.0)):
        if (debug): print "Intersection ERROR: infinite intersections!"
        return None

    # ambiguous intersection
    if ((math.sin(alpha1) * math.sin(alpha2)) < 0.0):
        if (debug): print "Intersection ERROR: ambiguous intersection!"
        return None

    alpha3 = math.acos(-1.0 * math.cos(alpha1) * math.cos(alpha2) +
                       math.sin(alpha1) * math.sin(alpha2) * math.cos(dist12))
    dist13 = math.atan2(
        math.sin(dist12) * math.sin(alpha1) * math.sin(alpha2),
        math.cos(alpha2) + math.cos(alpha1) * math.cos(alpha3))
    c_lat = math.asin(
        math.sin(a_lat) * math.cos(dist13) +
        math.cos(a_lat) * math.sin(dist13) * math.cos(brng13))
    dLon13 = math.atan2(
        math.sin(brng13) * math.sin(dist13) * math.cos(a_lat),
        math.cos(dist13) - math.sin(a_lat) * math.sin(c_lat))

    c_lon = a_lon + dLon13
    c_lon = math.fmod((c_lon + math.pi), (2.0 * math.pi)) - math.pi

    return (math.degrees(c_lat), math.degrees(c_lon))