Example #1
0
def ccl(data, rad, loc, npskyrad, mask=None):
    data_copy = data.copy()

    if type(mask) == type(None):
        mask = np.ones(np.shape(data_copy), dtype=bool)
    else:
        mask = mask.astype(bool)

    sky_ann = disk.disk(npskyrad[1], (loc[1],loc[0]), data_copy.shape) ^ \
              disk.disk(npskyrad[0], (loc[1],loc[0]), data_copy.shape)

    sky_mask = sky_ann * mask * np.isfinite(data_copy)

    sky = np.median(data_copy[np.where(sky_mask)])

    data_copy -= sky

    x_data = data_copy.shape[1]
    y_data = data_copy.shape[0]

    x_rad = (x_data - 1) / 2
    y_rad = (y_data - 1) / 2

    weights = np.ones(data_copy.shape, dtype=float)
    ind = np.indices(weights.shape)

    x_ind = ind[1] - x_rad
    y_ind = ind[0] - y_rad
    weights[np.where(np.sqrt(x_ind**2 + y_ind**2) > rad)] = 0

    return ctr.col(data_copy, weights=weights)
Example #2
0
def calcnoisepix(im, y, x, npskyrad, mask=None):
    '''
    Implementation of noise pixel calculation as described in the IRAC
    handbook. The box_centroider.pro routine was used as reference.

    Formula is N = sum(image)**2/sum(image**2).

    Inputs
    ------
    im: array-like
        Intended to be a 2D image, although any array should work.

    y: float
        Y position of the target

    x: float
        X position of the target

    npskyrad: 2-tuple of floats
        Radii for sky annulus (sky should be subtracted before
        calculating noise pixels in case it varies significantly,
        as is the case for spitzer subarrays)

    mask: boolean array
        Mask for the image. Same shape as im.

    Returns
    -------
    N: float
        Noise pixels

    Revisions
    ---------
    rchallen Initial Implementation   [email protected]
    '''

    # Create a mask if not supplied. Otherwise, make sure mask is
    # boolean
    if type(mask) == type(None):
        mask = np.ones(np.shape(im), dtype=bool)
    else:
        mask = mask.astype(bool)

    skymsk = disk.disk(npskyrad[1], (x,y), im.shape) ^ \
             disk.disk(npskyrad[0], (x,y), im.shape)

    sky = np.average(im[mask * skymsk])

    flux = np.sum(im[mask] - sky)

    N = flux**2 / np.sum((im[mask] - sky)**2)

    return N
Example #3
0
def guessDisk():
    for i in ["a","b","c", "d", "e", "f"]:
        for j in ["/dev/sd", "/dev/hd"]:
            path = j+i
            if os.path.exists(path):
                return disk(path)
    return None
Example #4
0
def shrinkLinux(our_disk, our_part):
    print "\nTEDD will now shrink your Linux partition to make room for the encrypted overlay."
    shrink_prompt = raw_input("May we proceed? [Y/n]: ")
    if not shrink_prompt.lower().startswith("n"):
        print "This may take a while depending on your file system and partition size. Please be patient."
        our_part.resize()
        our_disk = disk(our_disk.path)
        our_part = our_disk.partitions[our_part.path]
Example #5
0
def getDisk():
    our_disk = guessDisk()
    disk_prompt = raw_input("\nWhat disk contains your Linux Installation? [%s]: " % our_disk.path)
    while disk_prompt != "" and not os.path.exists(disk_prompt):
        print "Disk not found."
        disk_prompt = raw_input("\nWhat disk contains your Linux Installation? [%s]: " % our_disk.path)
    if disk_prompt != "":
        our_disk = disk(disk_prompt)
    return our_disk
Example #6
0
def col(data, loc, npskyrad, mask=None):
    data_copy = data.copy()

    if type(mask) == type(None):
        mask = np.ones(np.shape(data_copy), dtype=bool)
    else:
        mask = mask.astype(bool)

    sky_ann = disk.disk(npskyrad[1], (loc[1],loc[0]), data_copy.shape) ^ \
              disk.disk(npskyrad[0], (loc[1],loc[0]), data_copy.shape)

    sky_mask = sky_ann * mask * np.isfinite(data_copy)

    sky = np.median(data_copy[np.where(sky_mask)])

    data_copy -= sky

    return ctr.col(data_copy)
Example #7
0
    def getDiskFromDB(self):
        try:

            showDisk = self.cur.execute("SELECT * from disk").fetchall()
            disks = []
            i = 0
            for t in showDisk:
                disks.append(disk(t[0], t[1], t[2]))
                i += 1
            if len(disks) > 0:
                return disks

            print("Nada que mostrar")
            return 1
        except:
            print("Error en consulta de playlist")
            return 1
Example #8
0
def scan_gpt_table2(path, mode, flags=2):
    if os.name == 'nt' and len(path) == 2 and path[1] == ':':
        path = '\\\\.\\' + path
    d = disk.disk(path, mode)
    d.seek(512)
    blk = d.read(512)
    gpt = GPT(blk)
    d.seek(gpt.u64PartitionEntryLBA * 512)
    blk = d.read(gpt.dwNumberOfPartitionEntries *
                 gpt.dwNumberOfPartitionEntries)
    gpt.parse(blk)
    for i in range(gpt.dwNumberOfPartitionEntries):
        if not gpt.partitions[i].u64StartingLBA: break
        blocks = gpt.partitions[i].u64EndingLBA - gpt.partitions[
            i].u64StartingLBA + 1
        print "Found a %s GPT partition:\n- Name: %s\n- Type: %s\n- Offset: 0x%08X" % (
            print_size(blocks * 512), gpt.partitions[i].name(),
            partition_uuids[gpt.partitions[i].gettype()],
            gpt.partitions[i].u64StartingLBA)
        # Bit 0: system partition; bit 63: no auto mount (MS)
        print "- Attributes: 0x%X" % gpt.partitions[i].u64Attributes
        print "Save it? [y=Yes q=QUIT] ",
        C = raw_input().lower()
        if C == 'q':
            sys.exit(1)
        if C == 'y':
            first = gpt.partitions[i].u64StartingLBA
            last = gpt.partitions[i].u64EndingLBA
            #~ src = disk.partition(d, first*512, blocks*512)
            #~ src.seek(0)
            if lz4f and (flags & 1):  # compress with lz4 if available
                dst = lz4file('Partition@%08Xh.bin' % first, 'wb')
            else:
                dst = open(
                    'Partition@%08Xh.%s' % (first,
                                            ('bin', 'vhd')[flags & 2 != 0]),
                    'wb')
            print "Saving partition of %d sectors (%s) at %X" % (
                last - first + 1, print_size((last - first + 1) * 512), first)
            copy_sectors(d, dst, first, last)
            if flags & 2:  # append a fixed VHD footer
                dst.write(mk_vhd_fixed_footer((last - first + 1) * 512))
        print ""
    def resultToDiscObj(self, result):

        artis = None
        dis = None
        co = None
        disks = []

        for y in result:
            for x in y['release-list']:
                dis = x['artist-credit'][0]['name']
                artis = x['title']
                try:
                    co = x['country']

                except:
                    co = "EMPTY"
                dis = disk(dis, artis, co)
                disks.append(dis)

        return disks
Example #10
0
slot_1[0] = bb_sig

snd = sound(debug)

if options.scc_rom:
    parts = options.scc_rom.split(':')
    scc_obj = scc(parts[1], snd, debug)
    scc_sig = scc_obj.get_signature()
    scc_slot = int(parts[0])
    slot_1[scc_slot] = scc_sig
    slot_2[scc_slot] = scc_sig

if options.disk_rom:
    parts = options.disk_rom.split(':')
    disk_slot = int(parts[0])
    disk_obj = disk(parts[1], debug, parts[2])
    slot_1[disk_slot] = disk_obj.get_signature()

if options.rom:
    parts = options.rom.split(':')
    rom_slot = int(parts[0])
    rom_obj = gen_rom(parts[1], debug)
    rom_sig = rom_obj.get_signature()
    slot_1[rom_slot] = rom_sig
    if len(rom_sig[0]) >= 32768:
        slot_2[rom_slot] = rom_sig

subpage = 0x00

slots = (slot_0, slot_1, slot_2, slot_3)
Example #11
0
        dest="cluster_size",
        help=
        "force a specified cluster size between 512, 1024, 2048, 4096, 8192, 16384, 32768 (since MS-DOS) or 65536 bytes (Windows NT+) for FAT. exFAT permits up to 32M. Default: based on medium size. Accepts 'k' and 'm' postfix for Kibibytes and Mebibytes.",
        metavar="CLUSTER")
    opts, args = par.parse_args()

    if not args:
        print "mkfat error: you must specify a target volume to apply a FAT12/16/32 or exFAT file system!"
        par.print_help()
        sys.exit(1)

    if os.name == 'nt' and len(args[0]) == 2 and args[0][1] == ':':
        disk_name = '\\\\.\\' + args[0]
    else:
        disk_name = args[0]
    dsk = disk.disk(disk_name, 'r+b')

    params = {}

    if opts.fs_type:
        t = opts.fs_type.lower()
        if t == 'fat12':
            format = fat12_mkfs
        elif t == 'fat16':
            format = fat16_mkfs
        elif t == 'fat32':
            format = fat32_mkfs
            params['fat32_allows_few_clusters'] = 1
        elif t == 'exfat':
            format = exfat_mkfs
        else:
Example #12
0
from disk import disk
import json

my_disk = disk(json.load(open("input.json")))
my_disk.convert_binary_to_grid_squares()
my_disk.create_groups()

print(my_disk.get_group_count())
Example #13
0
def fitgaussian(y, x=None, bgpars=None, fitbg=0, guess=None,
                mask=None, weights=None, maskg=False, yxguess=None):
  """
    Fits an N-dimensional Gaussian to (value, coordinate) data.

    Parameters
    ----------
    y : ndarray
        Array giving the values of the function.
    x : ndarray
        (optional) Array (any shape) giving the abcissas of y (if
        missing, uses np.indices(y).  The highest dimension must be
        equal to the number of other dimensions (i.e., if x has 6
        dimensions, the highest dimension must have length 5).  The
        rest of the dimensions must have the same shape as y.  Must be
        sorted ascending (which is not checked), if guess is not
        given.
    bgpars : ndarray or tuple, 3-elements
        Background parameters, the elements determine a X- and Y-linearly
        dependant level, of the form:
        f = Y*bgparam[0] + X*bgparam[1] + bgparam[2]
        (Not tested for 1D yet).
    fitbg : Integer
        This flag indicates the level of background fitting:
        fitbg=0: No fitting, estimate the bg as median(data).
        fitbg=1: Fit a constant to the bg (bg = c).
        fitbg=2: Fit a plane as bg (bg = a*x + b*y + c).
    guess : tuple, (width, center, height)
        Tuple giving an initial guess of the Gaussian parameters for
        the optimizer.  If supplied, x and y can be any shape and need
        not be sorted.  See gaussian() for meaning and format of this
        tuple.
    mask : ndarray
        Same shape as y. Values where its corresponding mask value is
        0 are disregarded for the minimization. Only values where the
        mask value is 1 are considered.
    weights : ndarray
        Same shape as y. This array defines weights for the
        minimization, for scientific data the weights should be
        1/sqrt(variance).

    Returns
    -------
    params : ndarray
    
        This array contains the best fitting values parameters: width,
        center, height, and if requested, bgpars. with:
          width :  The fitted Gaussian widths in each dimension.
          center : The fitted Gaussian center coordinate in each dimension.
          height : The fitted height.

    err : ndarray
        An array containing the concatenated uncertainties
        corresponding to the values of params.  For example, 2D input
        gives np.array([widthyerr, widthxerr, centeryerr, centerxerr,
        heighterr]).

    Notes
    -----
    If the input does not look anything like a Gaussian, the result
    might not even be the best fit to that.

    Method: First guess the parameters (if no guess is provided), then
    call a Levenberg-Marquardt optimizer to finish the job.

    Examples
    --------

    >>> import matplotlib.pyplot as plt
    >>> import gaussian as g

    >>> # parameters for X
    >>> lx = -3.  # low end of range
    >>> hx = 5.   # high end of range
    >>> dx = 0.05 # step

    >>> # parameters of the noise
    >>> nc = 0.0  # noice center
    >>> ns = 1.0  # noise width
    >>> na = 0.2  # noise amplitude

    >>> # 1D Example

    >>> # parameters of the underlying Gaussian
    >>> wd = 1.1  # width
    >>> ct = 1.2  # center
    >>> ht = 2.2  # height

    >>> # x and y data to fit
    >>> x  = np.arange(lx, hx + dx / 2., dx)
    >>> x +=                             na * np.random.normal(nc, ns, x.size)
    >>> y  = g.gaussian(x, wd, ct, ht) + na * np.random.normal(nc, ns, x.size)
    >>> s  = x.argsort()    # sort, in case noise violated order
    >>> xs = x[s]
    >>> ys = y[s]

    >>> # calculate guess and fit
    >>> (width, center, height)     = g.gaussianguess(ys, xs)
    >>> (fw,    fc,     fh,    err) = g.fitgaussian(ys, xs)

    >>> # plot results
    >>> plt.clf()
    >>> plt.plot(xs, ys)
    >>> plt.plot(xs,      g.gaussian(xs, wd,    ct,     ht))
    >>> plt.plot(xs,      g.gaussian(xs, width, center, height))
    >>> plt.plot(xs,      g.gaussian(xs, fw,    fc,     fh))
    >>> plt.title('Gaussian Data, Guess, and Fit')
    >>> plt.xlabel('Abcissa')
    >>> plt.ylabel('Ordinate')
    >>> # plot residuals
    >>> plt.clf()
    >>> plt.plot(xs, ys - g.gaussian(xs, fw,    fc,     fh))
    >>> plt.title('Gaussian Fit Residuals')
    >>> plt.xlabel('Abcissa')
    >>> plt.ylabel('Ordinate')

    >>> # 2D Example

    >>> # parameters of the underlying Gaussian
    >>> wd = (1.1, 3.2)  # width
    >>> ct = (1.2, 3.1)  # center
    >>> ht = 2.2         # height

    >>> # x and y data to fit
    >>> nx = (hx - lx) / dx + 1
    >>> x  = np.indices((nx, nx)) * dx + lx
    >>> y  = g.gaussian(x, wd, ct, ht) + na * np.random.normal(nc, ns, x.shape[1:])

    >>> # calculate guess and fit
    >>> #(width, center, height)     = g.gaussianguess(y, x) # not in 2D yet...
    >>> (fw,    fc,     fh,    err) = g.fitgaussian(y, x, (wd, ct, ht))

    >>> # plot results
    >>> plt.clf()
    >>> plt.title('2D Gaussian Given')
    >>> plt.xlabel('X')
    >>> plt.ylabel('Y')
    >>> plt.imshow(    g.gaussian(x, wd,    ct,     ht))
    >>> plt.clf()
    >>> plt.title('2D Gaussian With Noise')
    >>> plt.xlabel('X')
    >>> plt.ylabel('Y')
    >>> plt.imshow(y)
    >>> #plt.imshow(    g.gaussian(x, width, center, height)) # not in 2D yet...
    >>> plt.clf()
    >>> plt.title('2D Gaussian Fit')
    >>> plt.xlabel('X')
    >>> plt.ylabel('Y')
    >>> plt.imshow(    g.gaussian(x, fw,    fc,     fh))
    >>> plt.clf()
    >>> plt.title('2D Gaussian Fit Residuals')
    >>> plt.xlabel('X')
    >>> plt.ylabel('Y')
    >>> plt.imshow(y - g.gaussian(x, fw,    fc,     fh))

    >>> # All cases benefit from...

    >>> # show difference between fit and underlying Gaussian
    >>> # Random data, your answers WILL VARY.
    >>> np.array(fw) - np.array(wd)
    array([ 0.00210398, -0.00937687])
    >>> np.array(fc) - np.array(ct)
    array([-0.00260803,  0.00555011])
    >>> np.array(fh) - np.array(ht)
    0.0030143371034774269

    >>> Last Example:
    >>> x = np.indices((30,30))
    >>> g1 = g.gaussian(x, width=(1.2, 1.15), center=(13.2,15.75), height=1e4,
    >>>                 bgpars=[0.0, 0.0, 100.0])
    >>> error = np.sqrt(g1) * np.random.randn(30,30)
    >>> y = g1 + error
    >>> var = g1
    >>> 
    >>> plt.figure(1)
    >>> plt.clf()
    >>> plt.imshow(y, origin='lower_left', interpolation='nearest')
    >>> plt.colorbar()
    >>> plt.title('2D Gaussian')
    >>> plt.xlabel('X')
    >>> plt.ylabel('Y')
    >>> 
    >>> guess = ((1.2,1.2),(13,16.),1e4)
    >>> reload(g)
    >>> fit = g.fitgaussian(y, x, bgpars=[0.0, 0.0, 110.], fitbg=1, guess=guess,
    >>>                     mask=None, weights=1/np.sqrt(var))
    >>> print(fit[0])


    Revisions
    ---------
    2007-09-17  Joe      Initial version, portions adapted from
                         http://www.scipy.org/Cookbook/FittingData.
                         [email protected]
    2007-11-13  Joe      Made N-dimensional.
    2008-12-02  Nate     Included error calculation, and return Fixed a bug
                         in which if the initial guess was None, and incorrect
                         shape array was generated. This caused gaussian guess
                         to fail.
                         [email protected]
    2009-10-25           Converted to standard doc header, fixed examples to
                         return 4 parameters.
    2011-05-03  patricio Added mask, weights, and background-fitting options.
                         [email protected]
  """

  if x == None:
    x = np.indices(np.shape(y))
  else:
    if (   ((x.ndim == 1) and (x.shape     != y.shape))
        or ((x.ndim >  1) and (x.shape[1:] != y.shape))):
      raise ValueError, "x must give coordinates of points in y."

  # Default mask: all good
  if mask == None:
    mask    = np.ones(np.shape(y))

  # Default weights: no weighting
  if weights == None:
    weights = np.ones(np.shape(y))

  # Mask the gaussian if requested:
  medmask = np.copy(mask)
  if maskg and (yxguess != None or guess != None):
    if yxguess != None:
      center = yxguess
    elif guess != None:
      center = guess[1]
    medmask *= (1 - d.disk(3, center, np.shape(y)))

  # Estimate the median of the image:
  medbg = np.median(y[np.where(medmask)])

  if bgpars == None:
    bgpars = [0.0, 0.0, medbg]

  # get a guess if not provided
  if guess == None:
    if yxguess == None:
      guess = gaussianguess(y-medbg, mask=mask)
    else:
      guess = gaussianguess(y-medbg, mask=mask, yxguess=yxguess)

  # "ravel" the guess
  gparams = np.append(guess[0], guess[1])
  gparams = np.append(gparams,  guess[2])

  # Background params to fit:
  if fitbg == 0:
    bgparams = []
  elif fitbg == 1:
    bgparams = bgpars[2]
  elif fitbg == 2:
    bgparams = bgpars

  # Concatenate sets of parameters we want to fit:
  params = np.append(gparams, bgparams)
  # Rest of parameters needed by residuals:
  args = (x, y, mask, weights, bgpars, fitbg)
  
  # The fit:
  p, cov, info, mesg, success = so.leastsq(residuals, params, args,
                                           full_output=True)
  try:
    err = np.sqrt(np.diagonal(cov))
  except:
    err = None
  
  return p, err
Example #14
0
def apphot(image,
           ctr,
           photap,
           skyin,
           skyout,
           betahw,
           targpos,
           mask=None,
           imerr=None,
           skyfrac=0.0,
           med=False,
           nochecks=False,
           expand=1,
           order=1,
           aperr=False,
           nappix=False,
           skylev=False,
           skyerr=False,
           nskypix=False,
           nskyideal=False,
           status=False,
           isbeta=False,
           betaper=False):
    """
    Perform aperture photometry on the input image.

    Parameters
    ----------
    image    : 2D ndimage
               Float array containing object to measure.
    ctr      : 2 elements tuple
               x,y location of object's center.
    photap   : Scalar
               Size of photometry apperture in pixels.
    skyin    : Scalar
               Inner sky annulus edge, in pixels.
    skyout   : Scalar
               Outer sky annulus edge, in pixels.

    betahw   : Scalar
               Half-width of box size around centroid for beta calculation.

    targpos  : 2 elements tuple
               x,y location of object's center calculated from mean image.

    mask     : 2D ndimage
               Byte array giving status of corresponding pixel in
               Image: bad pixel=0, good pixel=1.  Default: all pixels
               are good. Same shape as image.

    imerr    : 2D ndimage
               Error estimate for each pixel in the image.  Suggest
               sqrt(image/flat/gain+rdnoise^2), with proper adjustment
               if a sky, dark, or bias frame has been removed. Same
               shape as image.

    skyfrac  : Scalar
               Minimum fraction of sky pixels required to be good.
               Must be in range 0 < skyfrac < 1.

    med      : Boolean
               If True use median rather than mean in sky level estimation.
    nochecks : Boolean
               Set to True to skip checks of input sanity.
    expand   : Integer scalar
               Positive integer factor by which to blow up image, for
               more accurate aperture arithmetic.  If expand=5, each
               pixel becomes a 5x5 block of pixels.  If the pixel is
               on the edge of an aperture or annulus radius, some of
               the 5x5 block will be counted and some will not.
    order    : Integer scalar
               Set order to 0 to do nearest-neighbor interpolation if expand.
               Default: 1, bilinear interpolation.

    aperr    : Boolean
               Set to True to return flux error.

    nappix   : Boolean
               Set to True to return number of total pixels in aperture.

    skylev   : Boolean
               Set to True to return the sky level.

    skyerr   : Boolean
               Set to True to return the error in the sky level.

    nskypix  : boolean
               Set to True to return the number of good pixels in sky annulus.

    nskyideal: Boolean
               Set to True to return the number of pixels that should
               be in sky annulus.

    status   : Boolean
               Set to True to return a status flag.
               If status = 0, result is good.  Bits:
               0 = there are NaN(s) in the photometry aperture
               1 = there are masked pixel(s) in the photometry aperture
               2 = the aperture is off the edge of the image
               3 = a fraction less than skyfrac of the sky annulus pixels
		 	is in the image and not masked

    isbeta  :  boolean
               If True photometric extraction aperture scales with noise pixel
               parameter (beta).

    betaper  : Scalar
               Returns aperture size used for beta.

    Returns
    -------
      This function returns the flux within Photap pixels of
      [Cx,Cy], after subtracting the average per-pixel flux in the
      sky annulus.  See POCEDURE for details of the calculation.

    Notes
    -----
      The sky level is the mean, error-weighted mean (if errors are
      present), or median (if /med is set) of the non-masked Image
      pixels in the sky annulus.  NaN values and values whose errors
      are zero (for the error-weighted mean) are not included in the
      average.  No flagging is done if these values are found in the
      sky annulus.  SKYERR is the error in the mean, even for the
      median calculation.  Errors in the median can only be estimated
      using the compute-intensive bootstrap Monte-Carlo method.

      The sky value is subtracted from the Image.  The photometric
      flux is then the total of Image pixels in the aperture, whether
      in the Mask or not.  NaN values are not included in the
      calculation, and set the STATUS flag.  It would be much better
      for the user to pass an interpolated image instead.

      For expansion, it is recommended to use bilinear
      interpolation, which is flux-conserving:

      sz = [50, 50]
      expand = 4
      a = dblarr(sz)
      a[25, 25] = 1
      b = rebin(a, expand * sz) / expand^2
      print, total(b)
      1.0000000
      a[25, 26] = 1
      b = rebin(a, expand * sz) / expand^2
      print, total(b)
      2.0000000
      a[26, 26] = 3
      b = rebin(a, expand * sz) / expand^2
      print, total(b)
      5.0000000

      Of course, pixels on the high-indexed edge will not follow that.
      Neither will integer-arithmetic images, particularly at low
      integer values (such as masks).

      If either the entire sky annulus or the entire aperture is bad
      or filled with NaNs, the function sets a flag and returns NaN
      for all incalculable values.

    Examples
    --------
      This being one of my most important routines, and being also
      complex, the following examples are also its test suite.  Any
      changes should produce exactly the same numerical results.
      These tests should also be available in the accompanying file
      apphottest.pro.


     import sys
     sys.path.append('/home/esp01/code/python/photpipe/lib/')
     import apphot as ap
     import myasym as asy

     test      = 0
     ntest     = 11
     testout   = np.zeros((5, ntest))
     testright = np.zeros((5, ntest))
     sz        = [50, 50]
     sig       = 3.0, 3.0
     ctr       = 25.8, 25.2
     photap    = 12
     skyin     = 12
     skyout    = 15
     ampl      = 1000.0
     sky       = 100.0

     h = ampl/(2*np.pi*sig[0]*sig[1])  # height that make integral equal to ampl

     f = asy.gaussian(h, ctr[0], ctr[1], sig[0], sig[1])
     r,l = np.indices(sz)
     image = f(r,l) + sky

     plt.figure(1,(9,7))
     plt.clf()
     plt.title('Gaussian')
     plt.xlabel('X coordinate')
     plt.ylabel('Y coordinate')
     plt.pcolor(r, l, image, cmap=plt.cm.gray)
     plt.axis([0, sz[1]-1, 0, sz[0]-1])
     plt.colorbar()
     plt.show()

     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # A little of the Gaussian leaks from aperture to sky, rest is right.

     mask = np.ones(sz, byte)
     mask[24,24] = 0
     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout, mask = mask,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, 0, skylev, 0, status]
     test += 1
     # We use the bad value since it's in the aperture, but we flag it.

     image[25,24] = np.nan
     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout, mask = mask,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, 0, skylev, 0, status]
     test += 1
     # We can't use a NaN! Flagged, and value changes.  Bad value still flagged.

     ctr2 = [48.8, 48.2]
     f = asy.gaussian(h, ctr2[0], ctr2[1], sig[0], sig[1])
     image2 = f(r,l) + sky

     plt.figure(2,(9,7))
     plt.clf()
     plt.title('Gaussian')
     plt.xlabel('X coordinate')
     plt.ylabel('Y coordinate')
     plt.pcolor(r, l, image2, cmap=plt.cm.gray)
     plt.axis([0, sz[1]-1, 0, sz[0]-1])
     plt.colorbar()
     plt.show()

     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image2, ctr2, photap, skyin, skyout, mask = mask,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, 0, skylev, 0, status]
     test += 1
     # Flagged that we're off the image.

     skyfrac = 0.5
     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image2, ctr2, photap, skyin, skyout,
                          mask=mask, skyfrac=skyfrac,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, 0, skylev, 0, status]
     test += 1
     # Flagged that we are off the image and have insufficient sky.
     # Same numbers.

     f = asy.gaussian(h, ctr[0], ctr[1], sig[0], sig[1])
     image = f(r,l) + sky
     imerr = np.sqrt(image)
     mask = np.ones(sz, byte)

     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout, mask=mask,
                 imerr=imerr, aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # Estimates for errors above.  Basic numbers don't change.

     imerr[25, 38] = 0
     aplev, aperr, skylev, skyerr, \
      status = ap.apphot(image, ctr, photap, skyin, skyout, mask=mask,
                 imerr=imerr, aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # The zero-error pixel is ignored in the sky average. Small changes result.

     imerr[25, 38] = np.nan
     aplev, aperr, skylev, skyerr, \
     status = ap.apphot(image, ctr, photap, skyin, skyout, mask=mask,
                 imerr=imerr, aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # The NaN in the sky error is ignored, with the same result.

     image[25, 38] = np.nan
     imerr = sqrt(image)
     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout, mask=mask,
                 imerr=imerr, aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # The NaN in the sky data is ignored, with the same result.
     # FINDME: my aplev is changing


     ##
     f = asy.gaussian(h, ctr[0], ctr[1], sig[0], sig[1])
     image = f(r,l) + sky


     imerr  = sqrt(image)
     expand = 5
     order  = 0 # sample = 1

     aplev, aperr, skylev, skyerr, \
     status = ap.apphot(image, ctr, photap, skyin, skyout, expand = expand,
                        mask = mask, imerr = imerr, order=order,
                        aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # Slight changes.

     expand = 5
     order  = 1  # IDL sample = 0
     aplev, aperr, skylev, skyerr, \
       status = ap.apphot(image, ctr, photap, skyin, skyout, expand = expand,
                          mask = mask, imerr = imerr, order=order,
                          aperr=True, skylev=True, skyerr=True, status=True)

     print(aplev, aperr, skylev, skyerr, status)
     testout  [:, test] = [aplev, aperr, skylev, skyerr, status]
     test += 1
     # Slight changes.  Why the flag?

     skyerrest = np.sqrt(sky/(np.pi * (skyout**2 - skyin**2))) # skyerr estimate
     #      0.62687732
     print( 'Correct:' )
     print( [ampl,
     np.sqrt(ampl + np.pi * photap**2 * (sky+skyerrest**2)), # aperr estim.
     # Note that background flux of 100 contributes a lot!
     #       215.44538
     sky,
     skyerrest,
     0] )
     print( 'Test results:')
     print( testout)
     print( 'Correct results:')
     print( testright)
     print( 'Differences:')
     print( testout - testright)


   Revisions:
   ---------
   Written by: Joseph Harrington, Cornell. 27-02-2004
               [email protected]
   18-03-2004 jh	Added nochecks keyword.
   19-03-2004 jh	Added error calculation.
   13-01-2005 jh	Fixed header comment.  Added NAN keyword.
   14-10-2005 jh	Found and fixed major bug in sky mask
			 calculation (needed parens around
			 subtraction next to mask multiplication).
			 Added skyfrac.
   07-11-2005 shl35	Added STATUS keyword, error-weighted sky mean.
   16-11-2005 jh	Rewrote, using meanerr.  Fixed major bug in
			 error calc.  Added scaling and test cases.
   24-11-2005 jh	Return NAPPIX, NSKYPIX, NSKYIDEAL (all renamed).
   30-11-2005 jh	Changed NAPPIX, NSKYPIX, NSKYIDEAL to give
			 fractional, unexpanded pixels.
   21-07-2010 patricio  Converted to python.
  """

    # tini = time.time()

    # Returned values (include aperture size)
    retidx = [
        True, aperr, nappix, skylev, skyerr, nskypix, nskyideal, status,
        betaper
    ]
    # indexes
    # consider return the whole list always
    #FINDME: use iaplev etc ... or use a dicctionary
    aplev,   aperr,   nappix,    skylev, \
    skyerr, nskypix, nskyideal, stat, betaper  = np.arange(9)
    ret = np.zeros(9)  #changed from 8 to 9
    ret[:] = np.nan

    # set error status to 'good' = 0
    ret[stat] = 0
    status = 0

    # bit flag definitions
    statnan = 2**0
    statbad = 2**1
    statap = 2**2
    statsky = 2**3

    # internal skyfrac, so we don't set it in caller
    iskyfrac = skyfrac

    # Check inputs
    sz = np.shape(image)

    if not nochecks:
        if np.ndim(image) != 2:
            # FINDME: raise exceptions instead
            print('image must be a 2D array')
            # break
            return ret[np.where(retidx)]

        if mask is None:
            mask = np.ones(sz, dtype=np.byte)

        if np.ndim(mask) != 2:
            print('mask must be a 2D array')
            return ret[np.where(retidx)]

        if (np.shape(image) != np.shape(mask)):
            print('image and mask sizes differ')
            return ret[np.where(retidx)]

        if imerr is not None:
            if (np.shape(image) != np.shape(imerr)):
                print('image and imerr sizes differ')
                return ret[np.where(retidx)]

        if (iskyfrac < 0.0) or (iskyfrac > 1.0):
            print('skyfrac must be in range [0,1]')
            return ret[np.where(retidx)]

        if expand != np.long(expand) or expand < 1:
            print('invalid expand')
            return ret[np.where(retidx)]

    # Expand
    iexpand = int(expand)
    isz = np.array(sz,
                   dtype=int) + (np.array(sz, dtype=int) - 1) * (iexpand - 1)
    ictr = iexpand * np.array(ctr)
    iphotap = iexpand * photap
    iskyin = iexpand * skyin
    iskyout = iexpand * skyout

    y, x = np.arange(sz[0]), np.arange(sz[1])
    yi, xi = np.linspace(0, sz[0] - 1,
                         isz[0]), np.linspace(0, sz[1] - 1, isz[1])
    iimage = i2d.interp2d(image, expand=iexpand, y=y, x=x, yi=yi, xi=xi)
    imask = i2d.interp2d(mask, expand=iexpand, y=y, x=x, yi=yi, xi=xi)
    imask = imask == True
    if imerr is not None:
        iimerr = i2d.interp2d(imerr, expand=iexpand, y=y, x=x, yi=yi, xi=xi)

    # SKY
    # make sky annulus mask
    skyann = np.bitwise_xor(di.disk(iskyout, ictr, isz),
                            di.disk(iskyin, ictr, isz))
    skymask = skyann * imask * np.isfinite(iimage)  # flag NaNs to eliminate
    # from nskypix
    # Check for skyfrac violation
    # FINDME: include NaNs and zero errors
    ret[nskypix] = np.sum(skymask) / iexpand**2.0
    szsky = (int(np.ceil(iskyout)) * 2 + 3) * np.array([1, 1], dtype=int)
    ctrsky = (ictr % 1.0) + np.ceil(iskyout) + 1.0
    # nskyideal = all pixels in sky
    ret[nskyideal] = np.sum(
        np.bitwise_xor(di.disk(iskyout, ctrsky, szsky),
                       di.disk(iskyin, ctrsky, szsky))) / iexpand**2.0
    if ret[nskypix] < iskyfrac * ret[nskyideal]:
        status |= statsky

    if ret[nskypix] == 0:  # no good pixels in sky?
        status |= statsky
        ret[stat] = status
        print('no good pixels in sky')
        return ret[np.where(retidx)]

    # Calculate the sky and sky error values:
    # Ignore the status flag from meanerr, it will skip bad values intelligently.
    if med:  # Do median sky
        ret[skylev] = np.median(iimage[np.where(skymask)])
        if imerr is not None:
            # FINDME: We compute the standard deviation of the mean, not the
            # median.  The standard deviation of the median is complicated and can
            # only be estimated statistically using the bootstrap method.  It's
            # also very computationally expensive.  We could alternatively use the
            # maximum of the standard deviation of the mean and the mean
            # separation of values in the middle of the distribution.
            dummy, ret[skyerr] = me.meanerr(iimage,
                                            iimerr,
                                            mask=skymask,
                                            err=True)
            ret[skyerr] *= iexpand  # Expand correction. Since repeats are correlated,
            # error in mean was improved by sqrt(iexpand^2).
    else:  # Do mean
        if imerr is not None:
            ret[skylev], ret[skyerr] = me.meanerr(iimage,
                                                  iimerr,
                                                  mask=skymask,
                                                  err=True)
            ret[skyerr] *= iexpand  # Expand correction.
        else:
            ret[skylev] = np.mean(iimage[np.where(skymask)])

    #Calculate Beta values. If True photometric extraction aperture scales with
    #noise pixel parameter (beta).
    if isbeta == True and betahw > 0:
        #Using target position from mean image
        ctr_y = int(targpos[1])
        ctr_x = int(targpos[0])
        betahw = int(betahw)

        # Create a box of width and length (betahw) around the target position
        betabox = image[ctr_y - betahw:ctr_y + betahw + 1,
                        ctr_x - betahw:ctr_x + betahw + 1]

        # Subtract the background
        betabox -= ret[skylev]

        #beta = sum(I(i))^2 / sum(I(i)^2) see details below describing the noise pixels
        #https://irachpp.spitzer.caltech.edu/page/noisepix
        beta = np.sum(betabox)**2 / np.sum(betabox**2)

        iphotap += iexpand * (np.sqrt(beta) + photap)

        #Return aperture size used for beta.
        ret[betaper] = iphotap

    elif betahw == 0:
        raise ValueError(
            "Could not evalaute beta. Please update POET photom.pcf to betahw > 0."
        )

    # APERTURE
    # make aperture mask, extract data and mask
    apmask, dstatus = di.disk(iphotap, ictr, isz, status=True)
    if dstatus:  # is the aperture fully on the image?
        status |= statap

    aploc = np.where(apmask)  # report number of pixels in aperture
    ret[nappix] = np.sum(
        apmask[aploc]) / iexpand**2.0  # make it unexpended pixels
    if ret[nappix] == 0:  # is there *any* good aperture?
        status |= statbad
        ret[stat] = status
        return ret[np.where(retidx)]

    if np.all(np.isfinite(iimage[aploc]) == 0):  # all aperture pixels are NaN?
        status |= statnan
        ret[stat] = status
        return ret[np.where(retidx)]

    # subtract sky here to get a flag if it's NaN
    apdat = iimage[aploc] - ret[skylev]
    apmsk = imask[aploc]

    # flag NaNs and bad pixels
    goodies = np.isfinite(apdat)
    if np.any(goodies == 0):
        status |= statnan

    if np.any(apmsk == 0):
        status |= statbad

    # PHOTOMETRY
    # Do NOT multiply by bad pixel mask!  We need to use the interpolated
    # pixels here, unfortunately.
    ret[aplev] = np.sum(apdat[goodies])

    # Expand correction.  We overcount by iexpand^2.
    ret[aplev] /= iexpand**2.0

    # if we have uncertainties...
    if imerr is not None:
        # Flag NaNs.  Zeros are ok, if weird.
        apunc = iimerr[aploc]
        apuncloc = np.isfinite(apunc)
        if not np.all(apuncloc):
            status |= statnan

        # Multiply by mask for the aperture error calc.  The error on a
        # replaced pixel is unknown.  In one sense, it's infinite.  In
        # another, it's zero, or should be close.  So, ignore those points.
        # Sky error still contributes.
        apunc[np.where(apuncloc == False)] = 0
        ret[aperr] = np.sqrt(
            np.sum(apmsk * apunc**2.0) + np.size(aploc) * ret[skyerr]**2.0)

        # Expand correction.  We overcount by iexpand^2, but that's inside sqrt:
        # sqrt(sum(iexpand^2 * (indep errs))), so div. by iexpand
        ret[aperr] /= iexpand

    ret[stat] = status
    # ttotal =  time.time() - tini

    return ret[np.where(retidx)]
Example #15
0
    sizes = {0:'B', 10:'KiB',20:'MiB',30:'GiB',40:'TiB',50:'EiB'}
    k = 0
    for k in sorted(sizes):
        if (fsinfo['required_size'] / (1<<k)) < 1024: break

    free_clusters = fsinfo['clusters'] - 1
    print "Successfully applied FAT32 to a %d %s volume.\n%d clusters of %.1f KB.\n%d %s free in %d clusters." % (fsinfo['required_size']/(1<<k), sizes[k], fsinfo['clusters'], fsinfo['cluster_size']/1024.0, free_clusters*boot.cluster/(1<<k), sizes[k], free_clusters)
    print "\nFAT #1 @0x%X, Data Region @0x%X, Root (cluster #%d) @0x%X" % (boot.fatoffs, boot.cl2offset(2), 2, boot.cl2offset(2))

    return 0



if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "mkfat error: you must specify a target volume to apply a FAT12/16/32 file system!"
        sys.exit(1)

    if os.name == 'nt' and len(sys.argv[1])==2 and sys.argv[1][1]==':':
        disk_name = '\\\\.\\'+sys.argv[1]
    else:
        disk_name = sys.argv[1]
    dsk = disk.disk(disk_name, 'r+b')

    params = {'reserved_size':32, 'backup_sectors':6}
    if len(sys.argv)==3:
        params['wanted_cluster'] = int(sys.argv[2])

    fat32_mkfs(dsk, dsk.size, params=params)
Example #16
0
# -*- coding: mbcs -*-
import os, sys, optparse

import logging
logging.basicConfig(level=logging.DEBUG, filename='PYTEST.LOG', filemode='w')

from datetime import datetime
from ctypes import *

from utils import FSguess
from FAT import *
import disk

disk = disk.disk('\\\\.\\G:', 'r+b')
#~ disk = disk.disk('FLOPPY.IMA', 'r+b')
#~ disk = disk.disk('G.ima', 'r+b')
fstyp = FSguess(boot_fat16(disk))
disk.seek(0)

if fstyp in ('FAT12', 'FAT16'):
    boot = boot_fat16(disk)
elif fstyp == 'FAT32':
    boot = boot_fat32(disk)
elif fstyp == 'EXFAT':
    boot = boot_exfat(disk)
elif fstyp == 'NTFS':
    print fstyp, "file system not supported. Aborted."
    sys.exit(1)
else:
    print "File system not recognized. Aborted."
    sys.exit(1)
Example #17
0
if options.scc_rom:
    for o in options.scc_rom:
        parts = o.split(':')
        scc_obj = scc(parts[2], snd, debug)
        scc_slot = int(parts[0])
        scc_subslot = int(parts[1])
        put_page(scc_slot, scc_subslot, 1, scc_obj)
        put_page(scc_slot, scc_subslot, 2, scc_obj)

if options.disk_rom:
    for o in options.disk_rom:
        parts = o.split(':')
        disk_slot = int(parts[0])
        disk_subslot = int(parts[1])
        disk_obj = disk(parts[2], debug, parts[3])
        put_page(disk_slot, disk_subslot, 1, disk_obj)

if options.rom:
    for o in options.rom:
        parts = o.split(':')
        rom_slot = int(parts[0])
        rom_subslot = int(parts[1])
        offset = 0x4000
        if len(parts) == 4:
            offset = int(parts[3], 16)
        rom_obj = gen_rom(parts[2], debug, offset=offset)
        page_offset = offset // 0x4000
        for p in range(page_offset, page_offset + rom_obj.get_n_pages()):
            put_page(rom_slot, rom_subslot, p, rom_obj)
Example #18
0
def rotfitgaussian(y,
                   x=None,
                   bgpars=None,
                   fitbg=0,
                   guess=None,
                   mask=None,
                   weights=None,
                   maskg=False,
                   yxguess=None):

    if type(x) == type(None):
        x = np.indices(np.shape(y))
    else:
        if (((x.ndim == 1) and (x.shape != y.shape))
                or ((x.ndim > 1) and (x.shape[1:] != y.shape))):
            raise ValueError("x must give coordinates of points in y.")

    # Default mask: all good
    if type(mask) == type(None):
        mask = np.ones(np.shape(y))

    # Default weights: no weighting
    if type(weights) == type(None):
        weights = np.ones(np.shape(y))

    # Mask the gaussian if requested:
    medmask = np.copy(mask)
    if maskg and (type(yxguess) != type(None) or type(guess) != type(None)):
        if type(yxguess) != type(None):
            center = yxguess
        elif type(guess) != type(None):
            center = guess[1]
        medmask *= (1 - d.disk(3, center, np.shape(y)))

    # Estimate the median of the image:
    medbg = np.median(y[np.where(medmask)])

    if type(bgpars) == type(None):
        bgpars = [0.0, 0.0, medbg]

    # Get a guess if not provided. Note: the guess for rotation is set to 0 rad
    if type(guess) == type(None):
        if type(yxguess) == type(None):
            guess = gaussianguess(y - medbg, mask=mask)
        else:
            guess = gaussianguess(y - medbg, mask=mask, yxguess=yxguess)

        theta = 0
        guess = np.append(guess, theta)

    # "ravel" the guess
    gparams = np.append(guess[0], guess[1])
    gparams = np.append(gparams, guess[2])
    gparams = np.append(gparams, guess[3])

    # Background params to fit:
    if fitbg == 0:
        bgparams = []
    elif fitbg == 1:
        bgparams = bgpars[2]
    elif fitbg == 2:
        bgparams = bgpars

    # Concatenate sets of parameters we want to fit:
    params = np.append(gparams, bgparams)

    # Set up bounds (only for theta)
    lbounds = np.zeros(params.shape) - np.inf
    ubounds = np.zeros(params.shape) + np.inf

    if fitbg == 0:
        lbounds[-1] = 0.
        ubounds[-1] = np.pi / 2.
    elif fitbg == 1:
        lbounds[-2] = 0.
        ubounds[-2] = np.pi / 2
    elif fitbg == 2:
        lbounds[-3] = 0.
        ubounds[-3] = np.pi / 2

    # Rest of parameters needed by residuals:
    args = (x, y, mask, weights, bgpars, fitbg)

    # The fit:

    # These commented lines force a bounded fit. It runs much slower
    # and essentially the same thing can be achieved my modding the
    # fitted rotation.
    # res = so.least_squares(rotresiduals, params, bounds=(lbounds, ubounds),
    #                         args=args)

    # p      = res['x']       # Best-fit parameters
    # jac    = res['jac']     # Jacobian at p
    # status = res['status']  # Status message
    # mesg   = res['message'] # Interpretation of status
    # succ   = res['success'] # Success boolean

    # Get covariance from the jacobian
    # cov = np.linalg.inv(np.dot(jac.T, jac))

    # err = np.sqrt(np.diagonal(cov))

    # The fit:
    p, cov, info, mesg, success = so.leastsq(rotresiduals,
                                             params,
                                             args,
                                             full_output=True)

    err = np.sqrt(np.diagonal(cov))

    return p, err
Example #19
0
    def plu(self, events, UP):
        if self.principal and UP.my_player == self.NAME:
            dev = hackers.detectar(self, UP)
            if dev != None:
                return [dev]
            tim = time.time()
            if tim > self.LM + self.Tdaniado:
                self.daniable = True
                self.first_time = True
                self.permitido_act = True
                self.Tdaniado = self.Tdaniado_init
                self.escudo_activado = False
            else:
                self.titilar()

            if self.PERDIO:
                return ["destroyme"]

            key = events.get_keyboard()
            something = False

            self.programador = False
            if key[pygame.K_F5] and key[pygame.K_F8]:
                self.programador = True
            if self.programador:
                self.speed = 7
            else:
                self.analizar_backgrounds(UP)
                self.speed = self.speed_base
            if (self.ID == 0):
                condA = key[pygame.K_UP]
                condB = key[pygame.K_DOWN]
                condC = key[pygame.K_LEFT]
                condD = key[pygame.K_RIGHT]
                condE = key[pygame.K_SPACE]
            else:
                print self.ID
                print events.get_m()
                print events.fv(self.ID)

                condA = events.get_m()[events.fv(self.ID)][1]
                condB = events.get_m()[events.fv(self.ID)][2]
                condC = events.get_m()[events.fv(self.ID)][3]
                condD = events.get_m()[events.fv(self.ID)][4]
                condE = events.get_m()[events.fv(self.ID)][5]
            if condA:
                if not (ev(self.n_allowed, "arriba")) or self.programador:
                    self._y -= self.speed
                if self.pact != "ad":
                    self.lpact = self.pact
                    self.pact = "ad"
                something = True
            if condB:
                if not (ev(self.n_allowed, "abajo")) or self.programador:
                    self._y += self.speed
                if self.pact != "at":
                    self.lpact = self.pact
                    self.pact = "at"
                something = True
            if condC:
                if not (ev(self.n_allowed, "izquierda")) or self.programador:
                    self._x -= self.speed
                if self.pact != "iz":
                    self.lpact = self.pact
                    self.pact = "iz"
                something = True
            if condD:
                if not (ev(self.n_allowed, "derecha")) or self.programador:
                    self._x += self.speed
                if self.pact != "de":
                    self.lpact = self.pact
                    self.pact = "de"
                something = True

            if (something == False):
                self.surface = ei.tux.adelante.positions[0]
                self.pact = "no"

            if self.pact == "ad":
                if self.lpact != self.pact:
                    self.ciclo += 1

                    if self.ciclo / 8 > 2:
                        self.ciclo = 0
                    self.surface = ei.tux.atras.positions[self.ciclo / 8]
            if self.pact == "at":
                if self.lpact != self.pact:
                    self.ciclo += 1

                    if self.ciclo / 8 > 2:
                        self.ciclo = 0
                    self.surface = ei.tux.adelante.positions[self.ciclo / 8]
            if self.pact == "de":
                if self.lpact != self.pact:
                    self.ciclo += 1

                    if self.ciclo / 4 > 5:
                        self.ciclo = 0
                    self.surface = ei.tux.derecha.positions[self.ciclo / 4]
            if self.pact == "iz":
                if self.lpact != self.pact:
                    self.ciclo += 1

                    if self.ciclo / 4 > 5:
                        self.ciclo = 0
                    self.surface = ei.tux.izquierda.positions[self.ciclo / 4]

            self.colicion_detection(UP)

            if condE:
                if not self.disparando_discos:
                    self.disparando_discos = True
                    if self.discos > 0:
                        if self.pact != "no":
                            pact = self.pact
                        else:
                            pact = "at"
                        UP.objetos.append(
                            disk.disk(self._x, self._y, pact, len(UP.objetos),
                                      "Disco"))
                        self.discos -= 1
            N = False
            for q in UP.objetos:
                if q.TYPE == "Disco":
                    N = True
            if N == False:
                self.disparando_discos = False
Example #20
0
def vopen(path, mode='rb', what='auto'):
    """Opens a disk, partition or volume according to 'what' parameter: 'auto' 
    selects the volume in the first partition or disk; 'disk' selects the raw disk;
    'partitionN' tries to open partition number N; 'volume' tries to open a file
    system. """
    if DEBUG & 2: log("Volume.open in '%s' mode", what)
    # Tries to open a raw disk or disk image (plain or VHD)
    if os.name == 'nt' and len(path) == 2 and path[1] == ':':
        path = '\\\\.\\' + path
    if path.lower().endswith('.vhd'):  # VHD image
        d = vhdutils.Image(path, mode)
    else:
        d = disk.disk(path, mode)  # disk or disk image
    if DEBUG & 2: log("Opened disk: %s", d)
    d.seek(0)
    if what == 'disk':
        return d
    # Tries to access a partition
    mbr = partutils.MBR(d.read(512), disksize=d.size)
    if DEBUG & 2: log("Opened MBR: %s", mbr)
    valid_mbr = 1
    n = mbr.partitions[0].size()
    if mbr.wBootSignature != 0xAA55:
        if DEBUG & 2: log("Invalid Master Boot Record")
        valid_mbr = 0
    elif mbr.partitions[0].bType != 0xEE and (not n or n > d.size):
        if DEBUG & 2: log("Invalid Primary partition size in MBR")
        valid_mbr = 0
    elif mbr.partitions[0].bStatus not in (0, 0x80):
        if DEBUG & 2: log("Invalid Primary partition status in MBR")
        valid_mbr = 0
    if not valid_mbr:
        if DEBUG & 2: log("Invalid Master Boot Record")
        if what in ('auto', 'volume'):
            if DEBUG & 2:
                log("Trying to open a File system (Volume) in plain disk")
            d.seek(0)
            d.mbr = None
            v = openvolume(d)
            if v != 'EINV': return v
            if DEBUG & 2: log("No known file system found, returning RAW disk")
            d.seek(0)
            return d
        else:  # partition mode
            return 'EINVMBR'
    # Tries to open MBR or GPT partition
    if DEBUG & 2: log("Ok, valid MBR")
    partition = 0
    if what.startswith('partition'):
        partition = int(re.match('partition(\d+)', what).group(1))
    if DEBUG & 2: log("Trying to open partition #%d", partition)
    part = None
    if mbr.partitions[0].bType == 0xEE:  # GPT
        d.seek(512)
        gpt = partutils.GPT(d.read(512), 512)
        if DEBUG & 2: log("Opened GPT Header: %s", gpt)
        d.seek(gpt.u64PartitionEntryLBA * 512)
        blk = d.read(gpt.dwNumberOfPartitionEntries *
                     gpt.dwNumberOfPartitionEntries)
        gpt.parse(blk)
        blocks = gpt.partitions[partition].u64EndingLBA - gpt.partitions[
            partition].u64StartingLBA + 1
        if DEBUG & 2:
            log("Opening Partition #%d: %s", partition,
                gpt.partitions[partition])
        part = disk.partition(d,
                              gpt.partitions[partition].u64StartingLBA * 512,
                              blocks * 512)
        part.seek(0)
        part.mbr = mbr
        part.gpt = gpt
        # TODO: protect against invalid partition entries!
    else:
        index = 0
        if partition > 0:
            index = 1  # opens Extended Partition
        part = disk.partition(d, mbr.partitions[index].offset(),
                              mbr.partitions[index].size())
        if DEBUG & 2:
            log("Opened %s partition @%016x (LBA %016x) %s",
                ('Primary', 'Extended')[index],
                mbr.partitions[index].chsoffset(),
                mbr.partitions[index].lbaoffset(),
                partutils.raw2chs(mbr.partitions[index].sFirstSectorCHS))
        if partition > 0:
            wanted = 1
            extpart = part
            while wanted <= partition:
                bs = extpart.read(512)
                ebr = partutils.MBR(
                    bs, disksize=d.size)  # reads Extended Boot Record
                if DEBUG & 2: log("Opened EBR: %s", ebr)
                if ebr.wBootSignature != 0xAA55:
                    if DEBUG & 2: log("Invalid Extended Boot Record")
                    if what == 'auto':
                        return d
                    else:
                        return 'EINV'
                if DEBUG & 2:
                    log("Got partition @%016x (@%016x rel.) %s",
                        ebr.partitions[0].chsoffset(),
                        ebr.partitions[0].lbaoffset(),
                        partutils.raw2chs(ebr.partitions[0].sFirstSectorCHS))
                if DEBUG & 2:
                    log("Next logical partition @%016x (@%016x rel.) %s",
                        ebr.partitions[1].chsoffset(),
                        ebr.partitions[1].lbaoffset(),
                        partutils.raw2chs(ebr.partitions[1].sFirstSectorCHS))
                if wanted == partition:
                    if DEBUG & 2:
                        log(
                            "Opening Logical Partition #%d @%016x %s",
                            partition, ebr.partitions[0].offset(),
                            partutils.raw2chs(
                                ebr.partitions[0].sFirstSectorCHS))
                    part = disk.partition(d, ebr.partitions[0].offset(),
                                          ebr.partitions[0].size())
                    part.seek(0)
                    break
                if ebr.partitions[1].dwFirstSectorLBA and ebr.partitions[
                        1].dwTotalSectors:
                    if DEBUG & 2:
                        log(
                            "Scanning next Logical Partition @%016x %s size %.02f MiB",
                            ebr.partitions[1].offset(),
                            partutils.raw2chs(
                                ebr.partitions[1].sFirstSectorCHS),
                            ebr.partitions[1].size() // (1 << 20))
                    extpart = disk.partition(d, ebr.partitions[1].offset(),
                                             ebr.partitions[1].size())
                else:
                    break
                wanted += 1
        part.mbr = mbr

    def open(x):
        return openvolume(x)

    disk.partition.open = open  # adds an open member to partition object
    if what in ('volume', 'auto'):
        v = part.open()
        if DEBUG & 2: log("Returning opened Volume %s", v)
        return v
    else:
        if DEBUG & 2: log("Returning partition object")
        return part