def __init__(self, *args, **kw):
		Structure.__init__(self, *args, **kw)

		if kw.has_key('size'):
			self.size = kw['size']
		else:
			self.size = 1
예제 #2
0
 def __init__(self, stream, offset, max_size, parent, name):
   import C;
   from GIF_BLOCK import GIF_BLOCK;
   from GIF_EXTENSION_APPLICATION import GIF_EXTENSION_APPLICATION;
   from GIF_EXTENSION_COMMENT import GIF_EXTENSION_COMMENT;
   from GIF_EXTENSION_GRAPHICS_CONTROL import GIF_EXTENSION_GRAPHICS_CONTROL;
   from GIF_EXTENSION_PLAIN_TEXT import GIF_EXTENSION_PLAIN_TEXT;
   Structure.__init__(self, stream, offset, max_size, parent, name);
   
   self._label = self.Member(C.BYTE, 'label');
   if self._label.value == 0x01:
     self._label.notes.append('plain text extension');
     self._data = self.Member( \
         GIF_EXTENSION_PLAIN_TEXT, 'plain_text_extension');
   elif self._label.value == 0xF9:
     self._label.notes.append('graphice control extension');
     self._data = self.Member( \
         GIF_EXTENSION_GRAPHICS_CONTROL, 'graphice_control_extension');
   elif self._label.value == 0xFE:
     self._label.notes.append('comment extension');
     self._data = self.Member( \
         GIF_EXTENSION_COMMENT, 'comment_extension');
   elif self._label.value == 0xFF:
     self._label.notes.append('application extension');
     self._data = self.Member( \
         GIF_EXTENSION_APPLICATION, 'application_extension');
   else:
     self._label.warnings.append('unknown extension');
     self._data = self.Member(GIF_BLOCK, 'data');
     self._data.ContainUnused();
예제 #3
0
  def __init__(self, stream, offset, max_size, parent, name, \
      color_type, bit_depth, palette_entries):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    if color_type in [0, 4]:
      self._grey = self.Member(C.WORD, 'grey', little_endian = False);
      CheckBits(self._grey, bit_depth);
    elif color_type in [2, 6]:
      self._red = self.Member(C.WORD, 'red', little_endian = False);
      CheckBits(self._red, bit_depth);
      self._green = self.Member(C.WORD, 'green', little_endian = False);
      CheckBits(self._green, bit_depth);
      self._blue = self.Member(C.WORD, 'blue', little_endian = False);
      CheckBits(self._blue, bit_depth);
    elif color_type == 3:
      self._palette_index = self.Member(C.BYTE, 'palette index');
      if palette_entries is not None \
          and self._palette_index.value >= palette_entries:
        self._alpha_values.warnings.append(
            'expected value to be at most 0x%X|%d' % \
                (palette_entries, palette_entries));
    elif color_type == None:
      self.warnings.append(
          'chunk has no function when the color type is unknown');
    else:
      self.warnings.append(
          'chunk has no function for color type %d' % color_type);

    self.Unused();
예제 #4
0
  def __init__(self, stream, offset, max_size, parent, name):
    import math, time;
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._year = self.Member(C.WORD, 'year', little_endian = False);
    if self._year.value > time.gmtime()[0] or self._year.value < 1900:
      self._year.notes.append('unlikely value');

    self._month = self.Member(C.BYTE, 'month');
    if self._month.value > 12 or self._month.value < 1:
      self._month.warnings.append('illegal value');

    self._day = self.Member(C.BYTE, 'day');
    if self._day.value > 31 or self._day.value < 1:
      self._day.warnings.append('illegal value');

    self._hour = self.Member(C.BYTE, 'hour');
    if self._hour.value > 23 or self._hour.value < 0:
      self._hour.warnings.append('illegal value');

    self._minute = self.Member(C.BYTE, 'minute');
    if self._minute.value > 59 or self._minute.value < 0:
      self._minute.warnings.append('illegal value');

    self._second = self.Member(C.BYTE, 'second');
    if self._second.value > 60 or self._second.value < 0: # Leap second = 60 :)
      self._second.warnings.append('illegal value');

    self.Unused();
예제 #5
0
    def __init__(self, *args, **kw):
        Structure.__init__(self, *args, **kw)

        if kw.has_key('size'):
            self.size = kw['size']
        else:
            self.size = 1
예제 #6
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    from PNG_CheckText import PNG_CheckText;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    null_seperator_index = self.GetMaxStream().find('\0');
    if null_seperator_index == -1:
      self._keyword = None;
      self._null_seperator = None;
      self.warnings.append('no null found to seperate keyword from text, ' \
          'assuming text only');
    else:
      self._keyword = self.Member(C.STRING, 'keyword', null_seperator_index);
      PNG_CheckText(self._keyword, can_be_empty = False, max_size = 79, \
          no_extra_spaces = True, utf_8 = False, newlines = False, \
          is_keyword = True);

      self._null_seperator = self.Member(C.BYTE, 'null_seperator');

    self._text = self.Member(C.STRING, 'keyword', self.current_max_size);
    PNG_CheckText(self._text, can_be_empty = True, max_size = None, \
        no_extra_spaces = False, utf_8 = False, newlines = True, \
        is_keyword = False);

    self.Unused();
예제 #7
0
  def __init__(self, stream, offset, max_size, parent, name, \
      height_div_2 = False):
    import C;
    from struct_BITMAPINFOHEADER import struct_BITMAPINFOHEADER;
    from struct_RGBQUAD import struct_RGBQUAD;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._header = self.Member(struct_BITMAPINFOHEADER, \
        'header', height_div_2);

    self.format_details = self._header.format_details;
    bit_count = self._header._BitCount.value;
    compression = self._header._Compression.value;
    number_of_colors = 2 ** bit_count;
    used_colors = self._header._ClrUsed.value;
    # http://msdn.microsoft.com/en-us/library/aa930622.aspx

    if used_colors:
      number_of_rgb_quads = used_colors;
    else:
      number_of_rgb_quads = 2 ** bit_count;

    if bit_count in [16, 24, 32]:
      number_of_rgb_quads = 0;
    if compression == 3: # bitfields:
      number_of_rgb_quads = 3;

    if number_of_rgb_quads > 0:
      self._color_table = self.Member(C.ARRAY, 'color_table', \
          number_of_rgb_quads, struct_RGBQUAD);
      self._color_table.dump_simplified = True;
    else:
      self._color_table = None;
예제 #8
0
 def __init__(self, stream, offset, max_size, parent, name):
   import C;
   Structure.__init__(self, stream, offset, max_size, parent, name);
   self._gamma = self.Member(C.DWORD, 'gamma', little_endian = False);
   gamma = 100000.0 / self._gamma.value;
   self._gamma.notes.append('= 1/%f;' % gamma);
   self.Unused();
예제 #9
0
  def __init__(self, stream, offset, max_size, parent, name):
    import math;
    import C;
    from ZLIB_BLOCK import ZLIB_BLOCK;
    from struct_RGBAQUAD import struct_RGBAQUAD;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    null_seperator_index = self.GetMaxStream().find('\0');
    if null_seperator_index == -1:
      self._keyword = None;
      self._null_seperator = None;
      self.warnings.append('no null found to seperate profile name from text, ' \
          'assuming text only');
    else:
      self._profile_name = self.Member(C.STRING, 'profile_name', \
          null_seperator_index);
      CheckName(self._profile_name);

      self._null_seperator = self.Member(C.BYTE, 'null_seperator');

    self._compression_method = self.Member(C.BYTE, 'compression_method');
    if self._compression_method.value == 0:
      self._compression_method.notes.append('zlib deflate');
    else:
      self._compression_method.warnings.append( \
          'unknown methods, zlib deflate assumed');

    self._compressed_profile = self.Member(ZLIB_BLOCK, 'data');
    self._profile = self._compressed_profile.ContainMember( \
        C.STRING, 'profile', \
        self._compressed_profile.current_contained_max_size);
    # TODO (SkyLined): handle profile correctly (I'm assuming it's not a string)

    self.Unused();
예제 #10
0
    def init_structure(self, structure_id):
        """Initiate a new Structure object with given id.

        Arguments:
        o id - string
        """
        self.structure = Structure(structure_id)
예제 #11
0
    def __init__(self, stream, offset, max_size, parent, name):
        import C
        from GIF_BLOCK import GIF_BLOCK
        from GIF_COLORTABLE import GIF_COLORTABLE
        from GIF_IMAGE_DESCRIPTOR import GIF_IMAGE_DESCRIPTOR
        from LZW_compressed_data import LZW_compressed_data

        Structure.__init__(self, stream, offset, max_size, parent, name)

        self._descriptor = self.Member(GIF_IMAGE_DESCRIPTOR, "descriptor")

        flags = self._descriptor._Flags
        self._has_local_color_table = flags._LocalColorTable.value == 1
        if self._has_local_color_table:
            self._local_color_table_entries = 2 ** (flags._SizeLocalColorTable.value + 1)
            self._local_color_table_sorted = flags._Sort.value == 1
            self._local_color_table = self.Member(
                GIF_COLORTABLE, "local_color_table", self._local_color_table_entries, self._local_color_table_sorted
            )
        else:
            self._local_color_table = None

        self._lzw_minimum_code_size = self.Member(C.BYTE, "LZW_minimum_code_size")
        if self._lzw_minimum_code_size.value == 0:
            self._lzw_minimum_code_size.warnings.append("expected value > 0")

        self._compressed_pixel_data_container = self.Member(GIF_BLOCK, "pixel_data")
        self._pixel_data_container = self._compressed_pixel_data_container.ContainMember(
            LZW_compressed_data, "pixel_data", self._lzw_minimum_code_size.value
        )
        self._pixel_data = self._pixel_data_container.ContainMember(
            C.STRING, "pixel_data", self._descriptor._Width.value * self._descriptor._Height.value
        )
예제 #12
0
  def __init__(self, stream, offset, max_size, parent, name, color_type, \
      bit_depth, palette_entries):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    if color_type == 0:
      self._grey = self.Member(C.WORD, 'grey', little_endian = False);
      CheckBits(self._grey, bit_depth);
    elif color_type == 2:
      self._red = self.Member(C.WORD, 'red', little_endian = False);
      CheckBits(self._red, bit_depth);
      self._green = self.Member(C.WORD, 'green', little_endian = False);
      CheckBits(self._green, bit_depth);
      self._blue = self.Member(C.WORD, 'blue', little_endian = False);
      CheckBits(self._blue, bit_depth);
    elif color_type == 3:
      self._alpha_values = self.Member( \
          C.ARRAY, 'alpha_values', max_size, C.BYTE);
      if palette_entries is not None and palette_entries < max_size:
        self._alpha_values.warnings.append(
            'expected 0x%X|%d entries' % (palette_entries, palette_entries));
    elif color_type == None:
      self.warnings.append(
          'chunk has no function when the color type is unknown');
    else:
      self.warnings.append(
          'chunk has no function for color type %d' % color_type);

    self.Unused();
예제 #13
0
 def __init__(self):
     Structure.__init__(self)
     self.RVA = None
     self.Size = None
     self.majorAttributes = ['RVA', 'Size']
     self.section = None
     self.info = None
예제 #14
0
 def __init__(self, stream, offset, max_size, parent, name):
   import C;
   Structure.__init__(self, stream, offset, max_size, parent, name);
   
   # UINT CommonNetworkRelativeLinkSize
   self._CommonNetworkRelativeLinkSize = self.Member(C.UINT, \
       'CommonNetworkRelativeLinkSize');
   if self._CommonNetworkRelativeLinkSize.value < 0x14:
     self._CommonNetworkRelativeLinkSize.warnings.append(
         'Expected value to be larger than or equal to 0x14|20');
   # 32 BITS CommonNetworkRelativeLinkFlags
   self._CommonNetworkRelativeLinkFlags = self.Member(C.BITFIELD, \
     'CommonNetworkRelativeLinkFlags', 
     ('Unused',                                  30),
     ('ValidNetType',                            1),
     ('ValidDevice',                             1)
   );
   # UINT NetNameOffset
   self._NetNameOffset = self.Member(C.UINT, 'NetNameOffset');
   # UINT DeviceNameOffset
   self._DeviceNameOffset = self.Member(C.UINT, 'DeviceNameOffset');
   if self._CommonNetworkRelativeLinkFlags._ValidDevice.value == 0 \
       and self._DeviceNameOffset.value != 0:
     self._DeviceNameOffset.warnings.append('Expected value to be 0');
   # UINT NetworkProviderType
   self._NetworkProviderType = self.Member(C.UINT, 'NetworkProviderType');
   if self._CommonNetworkRelativeLinkFlags._ValidNetType.value == 0 \
       and self._NetworkProviderType.value != 0:
     self._NetworkProviderType.warnings.append('Expected value to be 0');
예제 #15
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._SampleLength = self.Member(C.DWORD, 'SampleLength');
    self.format_details = 'fact';

    self.Unused();
예제 #16
0
파일: file.py 프로젝트: SkyLined/headsup
 def __init__(self, stream, offset, max_size, parent, name, type_name, \
     structure_class):
   self.type_name = type_name;
   Structure.__init__(self, stream, offset, max_size, parent, name);
   self._contents = self.Member(structure_class, 'used');
   if hasattr(self._contents, 'format_details'):
     self.format_details = self._contents.format_details;
   self.Unused();
예제 #17
0
파일: C.py 프로젝트: SkyLined/headsup
  def __init__(self, stream, offset, max_size, parent, name, \
      bit_offset, bit_size, value):
    Structure.__init__(self, stream, offset, max_size, parent, name);
    self.dump_simplified = True;

    self.value = value;
    self.bit_offset = bit_offset;
    self.bit_size = bit_size;
예제 #18
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._compressed_pixel_data = self.Member( \
        C.STRING, 'compressed_pixel_data', max_size);

    self.Unused();
예제 #19
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    from BITMAP import BITMAP;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._Type = self.Member(C.DWORD, 'Type');

    CLIPBOARD_FORMATS = {
        0x0001: ('TEXT',                            None),
        0x0002: ('BITMAP',                          None),
        0x0003: ('METAFILEPICT',                    None),
        0x0004: ('SYLK',                            'Symbolic link'),
        0x0005: ('DIF',                             'Data Interchange Format'),
        0x0006: ('TIFF',                            None),
        0x0007: ('OEMTEXT',                         None),
        0x0008: ('DIB',                             None),
        0x0009: ('PALETTE',                         None),
        0x000A: ('PENDATA',                         None),
        0x000B: ('RIFF(audio)',                     None),
        0x000C: ('WAVE',                            None),
        0x000D: ('UNICODETEXT',                     None),
        0x000E: ('ENHMETAFILE',                     None),
        0x000F: ('HDROP',                           'list of file handles'),
        0x0010: ('LOCALE',                          None),
        0x0011: ('DIBV5',                           'struct BITMAPV5HEADER'),
        0x0080: ('OWNERDISPLAY',                    None),
        0x0081: ('DSPTEXT',                         'private'),
        0x0082: ('DSPBITMAP',                       'private'),
        0x0083: ('DSPMETAFILEPICT',                 'private'),
        0x008E: ('DSPENHMETAFILE',                  'private'),
        0xBF00: ('Link',                            None),
    };
    t = self._Type.value;
    if t in CLIPBOARD_FORMATS:
      format, details = CLIPBOARD_FORMATS[t];
      self.format_details = 'DISP(%s)' % format;
      if details != None:
        self._Type.notes.append('%s(%s)' % (format, details));
      else:
        self._Type.notes.append(format);
    elif t >= 0x200 and t <= 0x2FF:
      t &= 0xFF;
      self.format_details = 'DISP(private %d|0x%02X)' % (t, t);
      self._Type.notes.append('private format %d|%08X' % (t, t));
    elif t >= 0x300 and t <= 0x3FF:
      t &= 0xFF;
      self.format_details = 'DISP(private GDI %d|0x%02X)' % (t, t);
      self._Type.notes.append('private GDI object format %d|%08X' % (t, t));
    else:
      self.format_details = 'DISP(unknown %d|0x%08X)' % (t, t);
      self._Type.warnings.append('unknown type');
    if t == 8:
      self._bitmapinfo = self.Member(BITMAP, 'bitmapinfo');
    else:
      self._data = self.Member(C.STRING, 'data', self.current_max_size);

    self.Unused();
예제 #20
0
  def __init__(self, stream, offset, max_size, parent, name):
    from ICON import ICON;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._icon = self.Member(ICON, 'icon_data');

    self.format_details = self._icon.format_details;

    self.Unused();
예제 #21
0
    def __init__(self, stream, offset, max_size, parent, name):
        import C
        Structure.__init__(self, stream, offset, max_size, parent, name)

        self._CuePointName = self.Member(C.DWORD, 'CuePointName')
        self._Text = self.Member(C.STRING, 'Text')
        self.format_details = 'labl'

        self.Unused()
예제 #22
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._CuePointName = self.Member(C.STRING, 'CuePointName', 4);
    self._Text = self.Member(C.STRING, 'Text', self.current_max_size);
    self.format_details = 'note';

    self.Unused();
예제 #23
0
	def __init__(self, *args, **kw):
		Structure.__init__(self, *args, **kw)
		if kw.has_key('size'):
			size = kw['size']
		else:
			size = 64
		
		if not size in self.sizes.keys():
			raise ValueError("Only supported sizes are %r not %i" % (self.sizes.keys(),size))
		self.size = size
예제 #24
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    from GIF_BLOCK import GIF_BLOCK;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._data = self.Member(GIF_BLOCK, 'data');

    self._comment = self._data.ContainMember(C.STRING, \
        'comment', self._data.contained_current_max_size);

    self._data.ContainUnused(); # Should always be 0.
예제 #25
0
  def __init__(self, stream, offset, max_size, parent, name):
    import math;
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);
    self.dump_simplified = True;

    number_of_sequences = int(math.floor(max_size / 4.0));
    self._sequences = self.Member(C.ARRAY, 'sequences', number_of_sequences, C.DWORD);
    self.format_details = 'seq(%d)' % number_of_sequences;

    self.Unused();
예제 #26
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._PlaylistName = self.Member(C.STRING, 'PlaylistName', 4);
    self._Length = self.Member(C.DWORD, 'Length');
    self._Loops = self.Member(C.DWORD, 'Loops');
    self.format_details = 'plst';
    if self._Length.value == 0:
      self._Length.warnings.append('expected value to be at least 1');

    self.Unused();
예제 #27
0
  def __init__(self, stream, offset, max_size, parent, name):
    import math;
    import C;
    from struct_RGBAQUAD import struct_RGBAQUAD;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    null_seperator_index = self.GetMaxStream().find('\0');
    if null_seperator_index == -1:
      self._palette_name = None;
      self._null_seperator = None;
      self.warnings.append('no null found to seperate palette name from ' \
          'data, assuming data only');
    else:
      self._palette_name = self.Member(C.STRING, 'palette_name', \
          null_seperator_index);
      CheckName(self._palette_name);

      self._null_seperator = self.Member(C.BYTE, 'null_seperator');

    self._sample_depth = self.Member(C.BYTE, 'sample_depth');

    if self._sample_depth.value < 16:
      struct_size = 6;
      struct_definition = (
        ('Red',               C.BYTE),
        ('Green',             C.BYTE),
        ('Blue',              C.BYTE),
        ('Alpha',             C.BYTE),
        ('Frequency',         C.WORD),
      );
      self._sample_depth.notes.append('color/alpha info size = 1 byte');
    else:
      struct_size = 10;
      struct_definition = (
        ('Red',               C.WORD),
        ('Green',             C.WORD),
        ('Blue',              C.WORD),
        ('Alpha',             C.WORD),
        ('Frequency',         C.WORD),
      );
      self._sample_depth.notes.append('color/alpha info size = 2 bytes');

    self._number_of_palette_suggestions = \
        math.floor(self.current_max_size / struct_size);
    self._palette_suggestions = self.Member(C.ARRAY, 'palette_suggestions', \
        self._number_of_palette_suggestions, C.STRUCT, 'PALETTE_SUGGESTION', 
            *struct_definition);
    if self.current_max_size % struct_size != 0:
      self._palette_suggestions.warnings.append(
          'pallete size should be divisible by %d' % struct_size);
    self._palette_suggestions.dump_simplified = True;

    self.Unused();
예제 #28
0
파일: BMP.py 프로젝트: SkyLined/headsup
  def __init__(self, stream, offset, max_size, parent, name):
    from struct_BMPHEADER import struct_BMPHEADER;
    from BITMAP import BITMAP;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._header = self.Member(struct_BMPHEADER, 'header');

    if self._header._FileSize.value != max_size:
      self._header._FileSize.warnings.append( \
          'actual size = 0x%X|%d' % (max_size, max_size));

    self._bitmap = self.Member(BITMAP, 'bitmap', self._header._Offset.value);
예제 #29
0
  def __init__(self, stream, offset, max_size, parent, name, count, ordered):
    import C;
    from struct_RGBTRIPPLE import struct_RGBTRIPPLE;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    if ordered:
      self.notes.append('ordered by decreasing importance');
    else:
      self.notes.append('not ordered');

    self._rgb_tripples = self.Member(C.ARRAY, 'rgb_tripples', \
        count, struct_RGBTRIPPLE);
    self._rgb_tripples.dump_simplified = True;
예제 #30
0
  def __init__(self, stream, offset, max_size, parent, name):
    import C;
    Structure.__init__(self, stream, offset, max_size, parent, name);

    self._size = self.Member(C.BYTE, 'size');

    if self._size.value == 0:
      self._is_terminator = True;
      self.notes.append('block terminator');
      self.ContainStream('data', None, '', 0);
    else:
      self._is_terminator = False;
      self._data = self.Member(C.STRING, 'data', self._size.value);
      self.ContainStream('data', 'data', self._data.value, self._data.size);
	def __init__(self, *args, **kw):
		if kw.has_key('structures'):
			structures = kw['structures']
		else:
			structures = []
		
		if not isinstance(structures, (TupleType, ListType)):
			raise ValueError("Argument must be a list or tuple")

		for structure in structures:
			if not isinstance(structure, Structure):
				raise ValueError("All values in the list must be structures!")

		self.structures = structures
		Structure.__init__(self, *args, **kw)
예제 #32
0
    def __init__(self, stream, offset, max_size, parent, name):
        import math
        import C
        from struct_RGBTRIPPLE import struct_RGBTRIPPLE

        Structure.__init__(self, stream, offset, max_size, parent, name)

        if max_size % 3 != 0:
            self.warnings.append("pallete size should be divisible by 3")

        self._number_of_rgb_tripples = math.floor(max_size / 3.0)
        self._rgb_tripples = self.Member(C.ARRAY, "rgb_tripples", self._number_of_rgb_tripples, struct_RGBTRIPPLE)
        self._rgb_tripples.dump_simplified = True

        self.Unused()
예제 #33
0
파일: LNK.py 프로젝트: SkyLined/headsup
    def __init__(self, stream, offset, max_size, parent, name):
        import C
        from struct_SHELL_LINK_HEADER import struct_SHELL_LINK_HEADER
        from struct_ITEMIDLIST import struct_ITEMIDLIST
        from struct_LINK_INFO import struct_LINK_INFO

        Structure.__init__(self, stream, offset, max_size, parent, name)

        self._ShellLinkHeader = self.Member(struct_SHELL_LINK_HEADER, "Header")

        if self._ShellLinkHeader._LinkFlags._HasLinkTargetIDList.value == 0:
            self._ShellItemIdList = None
        else:
            self._ShellItemIdList = self.Member(struct_ITEMIDLIST, "ShellItemIdList")
        self._LinkInfo = self.Member(struct_LINK_INFO, "LinkInfo")
예제 #34
0
    def __init__(self):
        Structure.__init__(self)
        self.ImportLookupTableRVA = None
        self.TimeStamp = None
        self.ForwardChain = None
        self.NameRVA = None
        self.ImportAddressTableRVA = None

        self.majorAttributes = [
            'ImportLookupTableRVA', 'TimeStamp', 'ForwardChain', 'NameRVA',
            'ImportAddressTableRVA'
        ]
        self.importLookupTable = []
        self.importAddressTable = []
        self.name = None
예제 #35
0
    def __init__(self, *args, **kw):
        if kw.has_key('structures'):
            structures = kw['structures']
        else:
            structures = []

        if not isinstance(structures, (TupleType, ListType)):
            raise ValueError("Argument must be a list or tuple")

        for structure in structures:
            if not isinstance(structure, Structure):
                raise ValueError("All values in the list must be structures!")

        self.structures = structures
        Structure.__init__(self, *args, **kw)
예제 #36
0
 def initPop(self, num, num_struts, strut_length):
     # self.fitness = np.zeros()
     for i in np.arange(num):
         self.pop.append(
             (self.count, self.count, Structure(strut_length, num_struts)))
         self.count += 1
     self.count = 0
class Classifier:

  #constructor
  def __init__(self):
    self.assessments = Assessments()
    self.authority = Authority()
    self.causation = Causation()
    self.conditionals = Conditionals()
    self.contrast = Contrast()
    self.difficulty = Difficulty()
    self.doubt = Doubt()
    self.emphasis = Emphasis()
    self.generalization = Generalization()
    self.inconsistency = Inconsistency()
    self.inyourshoes = Inyourshoes()
    self.necessity = Necessity()
    self.possibility = Possibility()
    self.priority = Priority()
    self.rhetoricalquestion = Rhetoricalquestion()
    self.structure = Structure()
    self.wants = Wants()


  def list_categories_names(self):
    return ["Assessments","Authority","Causation","Conditionals","Contrast","Difficulty","Doubt","Emphasis","Generalization","Inconsistency","Inyourshoes","Necessity","Possibility","Priority","Rhetoricalquestion","Structure","Wants"]


  # function to count Assessments n-grams from text
  def analyse(self,text):

    result = []

    # counter of ngrams matched
    ngrams = 0

    # Analyse the text for each category
    result.append(self.assessments.analyse(text))
    result.append(self.authority.analyse(text))
    result.append(self.causation.analyse(text))
    result.append(self.conditionals.analyse(text))
    result.append(self.contrast.analyse(text))
    result.append(self.difficulty.analyse(text))
    result.append(self.doubt.analyse(text))
    result.append(self.emphasis.analyse(text))
    result.append(self.generalization.analyse(text))
    result.append(self.inconsistency.analyse(text))
    result.append(self.inyourshoes.analyse(text))
    result.append(self.necessity.analyse(text))
    result.append(self.possibility.analyse(text))
    result.append(self.priority.analyse(text))
    result.append(self.rhetoricalquestion.analyse(text))
    result.append(self.structure.analyse(text))
    result.append(self.wants.analyse(text))

    #normalize all categories count by percentage
    ngrams = sum(i for i in result)
    result = list(map((lambda x: round(float(x)/ngrams,5)), result))


    return result
 def __init__(self):
   self.assessments = Assessments()
   self.authority = Authority()
   self.causation = Causation()
   self.conditionals = Conditionals()
   self.contrast = Contrast()
   self.difficulty = Difficulty()
   self.doubt = Doubt()
   self.emphasis = Emphasis()
   self.generalization = Generalization()
   self.inconsistency = Inconsistency()
   self.inyourshoes = Inyourshoes()
   self.necessity = Necessity()
   self.possibility = Possibility()
   self.priority = Priority()
   self.rhetoricalquestion = Rhetoricalquestion()
   self.structure = Structure()
   self.wants = Wants()
예제 #39
0
    def load_object(self, image_name):
        map = Loader()
        self.structure = Structure()

        self.minimum_value, self.maximum_value, self.map_matrix = map.get_map(
            use_script=False, image=image_name)

        self.width = len(self.map_matrix)
        self.height = len(self.map_matrix[0])
        self.depth = np.max(self.map_matrix)

        self.vertex_count = self.width * self.height * 6

        self.generate_vertices()

        self.object_center_x = self.width / 2
        self.object_center_y = self.height / 2
        self.object_center_z = self.maximum_value / 2

        return self.colors, self.vertices
예제 #40
0
    def __init__(self, *args, **kw):
        Structure.__init__(self, *args, **kw)

        if kw.has_key('size'):
            size = kw['size']
        else:
            size = 32

        if kw.has_key('type'):
            type = kw['type']
        else:
            type = 'signed'

        if not size in self.sizes.keys():
            raise ValueError("Only supported sizes are %r not %i" %
                             (self.sizes.keys(), size))
        self.size = size

        if not type in ("signed", "unsigned", "semisigned"):
            raise ValueError("Type can only be signed, unsigned or semisigned")
        self.type = type
예제 #41
0
def parse_structure(structures_list, i, lines, seq, offset):
    base_pairs = []

    for line in lines[1:]:
        items = line.split('\t')
        pos1 = int(items[5])
        pos2 = int(items[4])

        if pos2 != 0 and pos1 < pos2 + offset:
            base_pairs.append(BasePair(pos1, pos2 + offset, seq, offset))

    structures_list[i] = Structure(i, seq, base_pairs, offset)
예제 #42
0
    def __init__(self):
        Structure.__init__(self)
        self.Name = None
        self.VirtualSize = None
        self.VirtualAddress = None
        self.SizeOfRawData = None
        self.PointerToRawData = None
        self.PointerToRelocations = None
        self.PointerToLinenumbers = None
        self.NumberOfRelocations = None
        self.NumberOfLinenumbers = None
        self.Characteristics = None

        self.SectionData = None

        self.majorAttributes = [
            'Name', 'VirtualSize', 'VirtualAddress', 'SizeOfRawData',
            'PointerToRawData', 'PointerToRelocations', 'PointerToLinenumbers',
            'NumberOfRelocations', 'NumberOfLinenumbers', 'Characteristics'
        ]
        self.dataDirectories = None
        self.loaderIrrelvantRange = None
예제 #43
0
def create_uniform_structure(pos_cg, rot0, length, Inertia, mcs, KG, CG, aero,
                             geometry, num_elements):
    ds = length / num_elements
    rot = rot0

    structure = Structure(num_elements)

    for i in range(0, num_elements):
        node1 = Node(mcs, pos_cg, Inertia, ((i - 1) * ds) / 20, aero, geometry)
        node2 = Node(mcs, pos_cg, Inertia, (ds / 2 + (i - 1) * ds) / 20, aero,
                     geometry)
        node3 = Node(mcs, pos_cg, Inertia, i * ds / 20, aero, geometry)

        elem = Element(node1, node2, node3, rot, ds, KG, CG)

        structure.addElem(elem)

        rot.dihedral = 0
        rot.sweep = 0
        rot.twist = 0

    return structure
예제 #44
0
def structure_test():
    """
    Test the Structure module
    Loading/conversion/save
    """
    from ase.visualize import view as ase_viewer

    # file of some type
    test_file = "diamond.pdb"
    dna_file = "dna.pdb"
    fox_file1 = "fox7.car"

    # Generate Structure objects
    diamond = Structure(file=test_file)
    dna = Structure(file=dna_file)
    fox = Structure(file=fox_file1)

    #ase_dna = dna.aseStructure()
    #ase_viewer(ase_dna)

    #ase_diamond = diamond.aseStructure()
    #ase_viewer(ase_diamond)

    ase_fox = fox.aseStructure()
예제 #45
0
    def build_structure_from_net(self, init_placement):
        """Orient SBUs to the nodes on the net, create bonds where needed, etc.."""
        metals = "_".join(["m%i"%(sbu.identifier) for sbu in 
                                self._sbus if sbu.is_metal])
        organics = "_".join(["o%i"%(sbu.identifier) for sbu in 
                                self._sbus if not sbu.is_metal])
        name = "str_%s_%s_%s"%(metals, organics, self._net.name)
        self.name = name
        #name += "_ftol_%11.5e"%self.options.ftol
        #name += "_xtol_%11.5e"%self.options.xtol
        #name += "_eps_%11.5e"%self.options.epsfcn
        #name += "_fac_%6.1f"%self.options.factor
        struct = Structure(self.options, 
                           name=name,
                           params=self._net.get_3d_params())

        cell = struct.cell.lattice
        V = self.net.vertices(0)
        edges = self.net.neighbours(V)
        sbu_pos = self._net.vertex_positions(edges, [], pos={V:init_placement})
        for v in self.sbu_vertices:
            self.sbu_orient(v, cell)
            fc = sbu_pos[v]
            tv = np.dot(fc, cell)
            self.sbu_translate(v, tv)
            # compute dihedral angle, if one exists...
            struct.add_sbu(self._vertex_sbu[v])
        struct.connect_sbus(self._vertex_sbu)
        if self.options.overlap_tolerance != 0.0 and struct.compute_overlap():
            warning("Overlap found in final structure, not creating MOF.")
        else:
            struct.write_cif()
            self.struct = struct
            self.success=True
            if self.options.store_net:
                self.embedded_net = self.store_placement(cell, init_placement) 
            info("Structure Generated!")
예제 #46
0
    chart = Chart()

    # add powder data to the chart. This needs to be made such that
    # setData doesn't need a type (setData1D/setDataCrystal) but rather
    # gets set depending on the type of the argument passed
    chart.setData1D(data_out)

    # create MPL representation of the Chart object
    #mpl_chart = chart.getMplChart()
    #mpl_chart.show()

    # or just show it directly
    chart.show()


if __name__ == "__main__":

    #structure_test()

    # files for testing
    test_file = "diamond.pdb"
    dna_file = "dna.pdb"
    fox_file1 = "fox7.car"

    # Generate Structure objects for use in calculator_test
    diamond = Structure(file=test_file)
    dna = Structure(file=dna_file)
    fox7_1 = Structure(file=fox_file1)

    calculator_test()
예제 #47
0
 def __init__(self):
     Structure.__init__(self)
     self.entry = None
     self.info = None
예제 #48
0
 def __init__(self):
     Structure.__init__(self)
     self.Hint = None
     self.Name = None
     self.Pad = None
     self.majorAttributes = ['Hint', 'Name', 'Pad']
예제 #49
0
import sys
import argparse

from XMLParser import XMLParser
from TXTParser import TXTParser
from Structure import Structure

SCRIPT_ERROR = "I/O Exception!"

input_file_name = ""
output_file_name = ""
parser = None
stats = Structure()


def check_arguments():
    """
    Function that parses inserted arguments and assign them into designed attributes
    argument -i stands for input file
             -o stands for output file
    Function also checks if the input file is in xml or txt format
    """
    global input_file_name, output_file_name, parser

    argument_parser = argparse.ArgumentParser(
        description="XML/TXT parser of enrollment data.")

    required_named = argument_parser.add_argument_group('required arguments')
    required_named.add_argument("-i",
                                dest="input_file",
                                action="store",
예제 #50
0
'''
Created on Aug 22, 2009

@author: javierbareno
'''
from numpy import *
import math
from Structure import Structure

if __name__ == '__main__':
    ifname = "LiCo2O4-spinel.ACE"
    ofname = "LiCo2O4-spinel"

    print "Reading input file"
    ifile = open(ifname)
    Li2Mn2O4 = Structure()
    Li2Mn2O4.read_cell(ifile)
    ifile.close()
    ofile = open(ofname + ".xyz", 'w')
    Li2Mn2O4.write_xyz(ofile, "Converted from Carine cell file")
    ofile.close()
    G = array([[0.5, -1, 0.5], [0.5, 0, -0.5], [1, 1, 1]]).transpose()

    print "Changing to rhomb base"
    rhom = Li2Mn2O4.new_basis(G)
    a, b, c = rhom.basis.a, rhom.basis.b, rhom.basis.c
    alpha, beta, gamma = rhom.basis.alpha, rhom.basis.beta, rhom.basis.gamma
    rhom2 = Structure(a, b, c, alpha, beta, gamma)
    rhom.basis = rhom2.basis

    print "Writing rhomb output"
예제 #51
0
               ["DG3", 0, 10, 12, -7, -1], ["DA3", 0, 10, 12, -7, -1],
               ["DT3", 0, 10, 12, -7, -1], ["DC3", 0, 10, 12, -7, -1]]

DNAlengths = [32, 31, 31, 29, 33, 32, 32, 30, 31, 30, 30, 28, 34, 33, 33, 31]

DNAalias = [["DGN", "DGN", "DG5", "DG", "DG3"],
            ["DAN", "DAN", "DA5", "DA", "DA3"],
            ["DTN", "DTN", "DT5", "DT", "DT3"],
            ["DCN", "DCN", "DC5", "DC", "DC3"],
            ["DG3", "DG3", "DG", "DG",
             "DG3"], ["DA3", "DA3", "DA", "DA", "DA3"],
            ["DT3", "DT3", "DT", "DT",
             "DT3"], ["DC3", "DC3", "DC", "DC", "DC3"],
            ["DG5", "DG5", "DG5", "DG",
             "DG"], ["DA5", "DA5", "DA5", "DA", "DA"],
            ["DT5", "DT5", "DT5", "DT",
             "DT"], ["DC5", "DC5", "DC5", "DC", "DC"],
            ["G", "DGN", "DG5", "DG", "DG3"], ["A", "DAN", "DA5", "DA", "DA3"],
            ["T", "DTN", "DT5", "DT", "DT3"], ["C", "DCN", "DC5", "DC", "DC3"]]

#Specification of DNA-residues ends here -----------------------------------------------------------------------------------------#

#Build Structure-object for DNA residues
DNA = Structure(DNAresidues,
                residue_length=DNAlengths,
                rotating_elements=DNAphosphate + DNAoc5 + DNAbase + DNAoc3,
                backbone_elements=DNAbackbone,
                alias=DNAalias)

WriteStructureXML(DNA, "DNA.xml")
예제 #52
0
'''
Created on 31 ott 2018

@author: marco
'''

from Drawing import Drawing
from Structure import Structure

dwg = Drawing("panel.dwg")

l = 900
h = 1500

bplst = Structure(dwg, 900, 2100)

bplst.baseStructure()
bplst.basePanel()

dwg.save()

if __name__ == '__main__':
    pass
예제 #53
0
import pytest
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath)

from Calculator import Calculator
from Structure import Structure
from PluginBase import PluginBase
from CalcPlugin_ASE import CalcPlugin_ASE

test_file = "diamond.pdb"
dna_file = "dna.pdb"

# Generate Structure objects
diamond = Structure(file=test_file)
dna = Structure(file=dna_file)


def test_calculator_default():

    calc = Calculator()

    assert calc.parameters == {}

    assert calc.DEFAULT_ENGINE['XRD'] == 'ASE'
    assert calc.DEFAULT_ENGINE['SANS'] == 'ASE'
    assert calc.activePlugin == None
    calc.loadPlugin(engine="ASE")
    assert isinstance(calc.activePlugin, CalcPlugin_ASE) == True
예제 #54
0
 def __init__(self, data_directory):
     Structure.__init__(self)
     self.entrys = []
     self.data_directory = data_directory
예제 #55
0
 def __init__(self):
     Structure.__init__(self)
     self.PageRVA = None
     self.BlockSize = None
     self.majorAttributes = ['PageRVA', 'BlockSize']
     self.items = None
예제 #56
0
 def __init__(self):
     super(mainWindow, self).__init__()
     self.data = Structure()
     self.itemList = QtGui.QTreeWidget()
     self.initUI()
예제 #57
0
class mainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(mainWindow, self).__init__()
        self.data = Structure()
        self.itemList = QtGui.QTreeWidget()
        self.initUI()

    '''
    initUI: Method to define the user interface
    '''

    def initUI(self):
        # Call createMenu() method for create Menu Bar
        self.createMenu()
        # Set the Menu Bar
        self.setMenuBar(self.menuBar)
        self.createTreeLayout()
        # Create Status Bar where show clicked info
        self.statusBar()
        self.statusText = QtGui.QLabel("Ready")
        self.statusBar().addWidget(self.statusText, 1)
        # Set Window Size
        self.setGeometry(500, 300, 350, 450)
        self.setWindowTitle('Python Dictionary Explorer')
        self.show()

    '''
    createMenu: Method to generate and add all user interface
                elements to our user interface
    '''

    def createMenu(self):
        # Define actions for Menu Bar
        # Option 1: Load default
        defaultTree = QtGui.QAction('Set Default Tree', self)
        defaultTree.setStatusTip('Create a default tree')
        defaultTree.triggered.connect(self.createDefaultTree)
        # Option 2: Load path to explore
        loadAction = QtGui.QAction('Load Path...', self)
        loadAction.setStatusTip('Load path as python dictionary')
        loadAction.triggered.connect(self.createTreeFromPath)
        # Option 3: Exit option
        exitAction = QtGui.QAction('&Exit', self)
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        # Create Menu Bar
        self.menuBar = QtGui.QMenuBar()
        # Create File Menu
        self.fileMenu = QtGui.QMenu("&File", self)
        # Add actions to File Menu
        self.fileMenu.addAction(defaultTree)
        self.fileMenu.addAction(loadAction)
        self.fileMenu.addAction(exitAction)
        # Add File Menu to Menu Bar
        self.menuBar.addMenu(self.fileMenu)

    '''
    createTree: Method to generate the QTreeWidget with
                all elements and hierarchy
    '''

    def createTreeLayout(self):
        # Define QTreeWidget and set parameters
        self.itemList.setItemsExpandable(True)
        self.itemList.setAnimated(True)
        self.itemList.setItemsExpandable(True)
        self.itemList.setColumnCount(1)
        self.itemList.setHeaderLabels([''])
        self.itemList.header().hide()
        # Create signal to item clicked Action, when any item is
        # clicked, itemClickedAction is called
        self.connect(self.itemList,
                     QtCore.SIGNAL("itemClicked (QTreeWidgetItem *, int)"),
                     self.itemClickedAction)
        # Generate the Layout for the browser
        self.gridLayout = QtGui.QGridLayout()
        self.widget = QtGui.QWidget()
        self.widget.setLayout(self.gridLayout)
        self.setCentralWidget(self.widget)
        self.gridLayout.addWidget(self.itemList)

    '''
    createTreeFromPath: Method to remove current tree and add
                        the new tree
    '''

    def createTreeFromPath(self):
        self.dictionary = self.data.createDataFromPath()
        self.itemList.clear()
        self.addElementToTree(self.dictionary)

    '''
    createTreeFromPath: Method to remove current tree and add
                        the new tree
    '''

    def createDefaultTree(self):
        self.dictionary = self.data.createDefaultData()
        self.itemList.clear()
        self.addElementToTree(self.dictionary)

    '''
    itemClickedAction:  Method called when user make click on any
                        list element. This method call showMessage()
                        to show in the status bar the item clicked info
    '''

    def itemClickedAction(self):
        # Get current item selected
        item = self.itemList.currentItem()
        # Get item selected text
        selected = item.text(0)
        # setNumElements call to set the number of files and
        # directory that the item selected have
        self.data.setNumElements(self.dictionary, 0, selected)
        # Create the info message
        info = ("" + selected + " contains " + str(self.data.getNumFiles()) +
                " files and " + str(self.data.getNumFolders()) + " folders.")
        # Show the info message
        self.statusBar().showMessage(info)

    '''
    addElementToTree: Method that received an element to add to the tree
                      and insert it in the correct hierarchy.
        - src:        path to analyze
        - dpth:       Depth of the current item
        - key:        Key that identifies the current item
        - father:     Element that identifies the father of the current item
    '''

    def addElementToTree(self, src, dpth=0, key='', father=''):
        # Check if the current item is in dictionary
        if isinstance(src, dict):
            # Check key and value to insert the item
            for key, value in src.iteritems():
                if isinstance(father, str):
                    # If has no parent, it is the root
                    if str(father) == '':
                        item = QtGui.QTreeWidgetItem(self.itemList, [str(key)])
                        if value is not None:
                            self.addElementToTree(value, dpth + 1, key, item)
                    else:
                        if value is not None:
                            self.addElementToTree(value, dpth + 1, key, item)
                else:
                    item = QtGui.QTreeWidgetItem(father, [str(key)])
                    if value is not None:
                        self.addElementToTree(value, dpth + 1, key, item)
        else:
            # It is a child item
            item = QtGui.QTreeWidgetItem(father, [str(src)])
예제 #58
0
class StructureBuilder:
    """
    Deals with contructing the Structure object. The StructureBuilder class is used
    by the PDBParser classes to translate a file to a Structure object.
    """
    def __init__(self):
        self.line_counter = 0
        self.header = {}

    def _is_completely_disordered(self, residue):
        "Return 1 if all atoms in the residue have a non blanc altloc."
        atom_list = residue.get_unpacked_list()
        for atom in atom_list:
            altloc = atom.get_altloc()
            if altloc == " ":
                return 0
        return 1

    # Public methods called by the Parser classes

    def set_header(self, header):
        self.header = header

    def set_line_counter(self, line_counter):
        """
        The line counter keeps track of the line in the PDB file that 
        is being parsed.
        
        Arguments:
        o line_counter - int
        """
        self.line_counter = line_counter

    def init_structure(self, structure_id):
        """Initiate a new Structure object with given id.

        Arguments:
        o id - string
        """
        self.structure = Structure(structure_id)

    def init_model(self, model_id):
        """Initiate a new Model object with given id.
        
        Arguments:
        o id - int
        """
        self.model = Model(model_id)
        self.structure.add(self.model)

    def init_chain(self, chain_id):
        """Initiate a new Chain object with given id.

        Arguments:
        o chain_id - string
        """
        if self.model.has_id(chain_id):
            self.chain = self.model[chain_id]
            if __debug__:
                sys.stderr.write(
                    "WARNING: Chain %s is discontinuous at line %i.\n" %
                    (chain_id, self.line_counter))
        else:
            self.chain = Chain(chain_id)
            self.model.add(self.chain)

    def init_seg(self, segid):
        """Flag a change in segid.
        
        Arguments:
        o segid - string
        """
        self.segid = segid

    def init_residue(self, resname, field, resseq, icode):
        """
        Initiate a new Residue object.

        Arguments:
        o resname - string, e.g. "ASN"
        o field - hetero flag, "W" for waters, "H" for 
            hetero residues, otherwise blanc.
        o resseq - int, sequence identifier
        o icode - string, insertion code
        """
        if field != " ":
            if field == "H":
                # The hetero field consists of H_ + the residue name (e.g. H_FUC)
                field = "H_" + resname
        res_id = (field, resseq, icode)
        if field == " ":
            if self.chain.has_id(res_id):
                # There already is a residue with the id (field, resseq, icode).
                # This only makes sense in the case of a point mutation.
                if __debug__:
                    sys.stderr.write(
                        "WARNING: Residue ('%s', %i, '%s') redefined at line %i.\n"
                        % (field, resseq, icode, self.line_counter))
                duplicate_residue = self.chain[res_id]
                if duplicate_residue.is_disordered() == 2:
                    # The residue in the chain is a DisorderedResidue object.
                    # So just add the last Residue object.
                    if duplicate_residue.disordered_has_id(resname):
                        # The residue was already made
                        self.residue = duplicate_residue
                        duplicate_residue.disordered_select(resname)
                    else:
                        # Make a new residue and add it to the already
                        # present DisorderedResidue
                        new_residue = Residue(res_id, resname, self.segid)
                        duplicate_residue.disordered_add(new_residue)
                        self.residue = duplicate_residue
                        return
                else:
                    # Make a new DisorderedResidue object and put all
                    # the Residue objects with the id (field, resseq, icode) in it.
                    # These residues each should have non-blanc altlocs for all their atoms.
                    # If not, the PDB file probably contains an error.
                    if not self._is_completely_disordered(duplicate_residue):
                        # if this exception is ignored, a residue will be missing
                        self.residue = None
                        raise PDBConstructionException(\
                            "Blank altlocs in duplicate residue %s ('%s', %i, '%s')" \
                            % (resname, field, resseq, icode))
                    self.chain.detach_child(res_id)
                    new_residue = Residue(res_id, resname, self.segid)
                    disordered_residue = DisorderedResidue(res_id)
                    self.chain.add(disordered_residue)
                    disordered_residue.disordered_add(duplicate_residue)
                    disordered_residue.disordered_add(new_residue)
                    self.residue = disordered_residue
                    return
        residue = Residue(res_id, resname, self.segid)
        self.chain.add(residue)
        self.residue = residue

    def init_atom(self,
                  name,
                  coord,
                  b_factor,
                  occupancy,
                  altloc,
                  fullname,
                  serial_number=None):
        """
        Initiate a new Atom object.

        Arguments:
        o name - string, atom name, e.g. CA, spaces should be stripped
        o coord - Numeric array (Float0, size 3), atomic coordinates
        o b_factor - float, B factor
        o occupancy - float
        o altloc - string, alternative location specifier
        o fullname - string, atom name including spaces, e.g. " CA "
        """
        residue = self.residue
        # if residue is None, an exception was generated during
        # the construction of the residue
        if residue is None:
            return
        # First check if this atom is already present in the residue.
        # If it is, it might be due to the fact that the two atoms have atom
        # names that differ only in spaces (e.g. "CA.." and ".CA.",
        # where the dots are spaces). If that is so, use all spaces
        # in the atom name of the current atom.
        if residue.has_id(name):
            duplicate_atom = residue[name]
            # atom name with spaces of duplicate atom
            duplicate_fullname = duplicate_atom.get_fullname()
            if duplicate_fullname != fullname:
                # name of current atom now includes spaces
                name = fullname
                if __debug__:
                    sys.stderr.write(
                        "WARNING: atom names %s and %s differ only in spaces at line %i.\n"
                        % (duplicate_fullname, fullname, self.line_counter))
        atom = self.atom = Atom(name, coord, b_factor, occupancy, altloc,
                                fullname, serial_number)
        if altloc != " ":
            # The atom is disordered
            if residue.has_id(name):
                # Residue already contains this atom
                duplicate_atom = residue[name]
                if duplicate_atom.is_disordered() == 2:
                    duplicate_atom.disordered_add(atom)
                else:
                    # This is an error in the PDB file:
                    # a disordered atom is found with a blanc altloc
                    # Detach the duplicate atom, and put it in a
                    # DisorderedAtom object together with the current
                    # atom.
                    residue.detach_child(name)
                    disordered_atom = DisorderedAtom(name)
                    residue.add(disordered_atom)
                    disordered_atom.disordered_add(atom)
                    disordered_atom.disordered_add(duplicate_atom)
                    residue.flag_disordered()
                    if __debug__:
                        sys.stderr.write(
                            "WARNING: disordered atom found with blanc altloc before line %i.\n"
                            % self.line_counter)
            else:
                # The residue does not contain this disordered atom
                # so we create a new one.
                disordered_atom = DisorderedAtom(name)
                residue.add(disordered_atom)
                # Add the real atom to the disordered atom, and the
                # disordered atom to the residue
                disordered_atom.disordered_add(atom)
                residue.flag_disordered()
        else:
            # The atom is not disordered
            residue.add(atom)

    def set_anisou(self, anisou_array):
        "Set anisotropic B factor of current Atom."
        self.atom.set_anisou(anisou_array)

    def set_siguij(self, siguij_array):
        "Set standard deviation of anisotropic B factor of current Atom."
        self.atom.set_siguij(siguij_array)

    def set_sigatm(self, sigatm_array):
        "Set standard deviation of atom position of current Atom."
        self.atom.set_sigatm(sigatm_array)

    def get_structure(self):
        "Return the structure."
        # first sort everything
        # self.structure.sort()
        # Add the header dict
        self.structure.header = self.header
        return self.structure

    def set_symmetry(self, spacegroup, cell):
        pass
예제 #59
0
class Constants:

    varx = Variable('x')
    vary = Variable('y')
    varz = Variable('z')
    varo = Variable('o')

    emptyList = []
    list123 = [Num(1), Num(2), Num(3)]
    listadd123 = [FuncApplication(Variable('+'), list123), Num(-3)]
    list12True = [Num(1), Num(2), Boolean(True)]

    listaddsubtract123 = [
        FuncApplication(Variable('-'), list123),
        FuncApplication('+', list123)
    ]
    listmultiply123 = [FuncApplication(Variable('*'), list123)]
    list84 = [Num(8), Num(4)]
    listdivide84 = [FuncApplication(Variable('/'), list84)]
    listx23 = [varx, Num(2), Num(3)]
    listy3 = [vary, Num(3)]
    list43 = [Num(4), Num(3)]
    list403 = [Num(4), Num(0), Num(3)]

    expradd1 = FuncApplication(Variable('+'), [Num(1)])
    expradd123 = FuncApplication(Variable('+'), list123)
    expradd43 = FuncApplication(Variable('+'), list43)
    expradderror = FuncApplication(Variable('+'), list12True)

    exprsub1 = FuncApplication(Variable('-'), [Num(1)])
    exprsub123 = FuncApplication(Variable('-'), list123)
    exprsub_add123_add123 = FuncApplication(Variable('-'),
                                            [expradd123, expradd43])

    exprdiv1 = FuncApplication(Variable('/'), [Num(1)])
    exprdiv84 = FuncApplication(Variable('/'), list84)
    exprdiv403 = FuncApplication(Variable('/'), list403)

    exprmul1 = FuncApplication(Variable('*'), [Num(1)])
    exprmul84 = FuncApplication(Variable('*'), list84)

    expradd_expradd123_exprdiv84 = FuncApplication(Variable('+'),
                                                   [expradd123, exprdiv84])

    expraddx23 = FuncApplication(Variable('+'), listx23)
    expraddy3 = FuncApplication(Variable('+'), listy3)
    expsub_expraddx23_expradd3 = FuncApplication(Variable('-'),
                                                 [expraddx23, expraddy3])

    #functions
    func_def_varx = FuncDef("f", LambdaExpr(["x"], Variable("x")))
    func_app_varx = FuncApplication(Variable('f'), [Num(4)])

    list_func_app_varx = [func_app_varx, Num(2)]
    expradd_func_app_varx = FuncApplication(Variable('+'), list_func_app_varx)

    funcDef2 = FuncDef('g', LambdaExpr([], expradd_func_app_varx))
    func_app_emptylist = FuncApplication(Variable('g'), [])  ###############

    expradd_varx_vary = FuncApplication(Variable('+'), [varx, vary])

    func_def_add_varx_vary = FuncDef('z',
                                     LambdaExpr(['x', 'y'], expradd_varx_vary))
    func_app_varx_vary = FuncApplication(Variable('z'), [Num(7), Num(7)])
    func_app_error_777 = FuncApplication(
        Variable('z'), [Num(7), Num(7), Num(7)])

    func_app_100 = FuncApplication(Variable('d'), [Num(100)])

    defs1 = Scope(()).add_definitions()
    defs1 = defs1.extend('x', Num(1)).extend('y', Num(4))

    #set the scope by mutating to second arg of the tuple
    defs1 = func_def_varx.eval(defs1)[1]
    defs1 = funcDef2.eval(defs1)[1]
    defs1 = func_def_add_varx_vary.eval(defs1)[1]

    #structs
    posn_def = StructDef('posn', ['x', 'y'])
    defs1 = posn_def.update(defs1)

    zeina_def = StructDef('zeina', ['x', 'y'])
    defs1 = zeina_def.update(defs1)

    make_zeina = FuncApplication(Variable('make-posn'), [Num(10), Num(20)])

    select_zeina_x = FuncApplication(Variable('zeina-x'), [make_zeina])

    make_posn = FuncApplication(Variable('make-posn'), [Num(1), Num(2)])
    make_posn_comp = FuncApplication(Variable('make-posn'),
                                     [make_posn, Num(2)])

    is_posn = FuncApplication(Variable('posn?'), [make_posn])
    is_not_posn = FuncApplication(Variable('posn?'), [Num(3)])

    select_posn_x = FuncApplication(Variable('posn-x'), [make_posn])
    select_posn_y = FuncApplication(Variable('posn-y'), [make_posn])

    select_posn_x_comp = FuncApplication(Variable('posn-x'), [make_posn_comp])
    select_posn_y_comp = FuncApplication(Variable('posn-y'), [make_posn_comp])

    value_posn = Structure('posn', [('x', Num(1)), ('y', Num(2))])
    value_posn_comp = Structure('posn', [('x', value_posn), ('y', Num(2))])

    #functions using struct
    make_posn_func = FuncApplication(Variable('make-posn'),
                                     [func_app_varx, Num(1)])
    func_app_varx_1 = FuncApplication(Variable('f'), [make_posn_func])

    value_posn_func = Structure('posn', [('x', Num(4)), ('y', Num(1))])

    posn_x_func_app_varx_1 = FuncApplication(Variable('posn-x'),
                                             [func_app_varx_1])

    select_posn_x_error = FuncApplication(Variable('posn-x'), [Num(3)])

    ex1 = '(ex*'
    ex_abc = 'abc'
    ex_1 = '1'
    exx1 = ')'
    exx2 = ex_abc + exx1

    #And
    and1 = And([Boolean(True), Boolean(False)])
    and2 = And(
        [Boolean(False),
         FuncApplication(Variable('/'), [Num(1), Num(0)])])
    and3 = And(
        [Boolean(True),
         FuncApplication(Variable('/'), [Num(1), Num(1)])])

    #equals
    equals34 = FuncApplication(Variable('='), [Num(3), Num(4)])
    equals33 = FuncApplication(Variable('='), [Num(3), Num(3)])
    equals_3_true = FuncApplication(Variable('='), [Num(3), Boolean(False)])

    #bigger and less than
    biggerthan34 = FuncApplication(Variable('>'), [Num(3), Num(4)])
    lessthan34 = FuncApplication(Variable('<'), [Num(3), Num(4)])
    lessthan_error = FuncApplication(Variable('>'), [Variable('xyz'), Num(4)])

    #if.
    if_1 = If([equals34, Num(3), Num(4)])
    if_2 = If([equals33, Num(3), Num(4)])