| 1 |
# Programming with PyCIFRW |
| 2 |
|
| 3 |
PyCIFRW provides facilities for reading, manipulating and writing |
| 4 |
CIF and STAR files. In addition, CIF files and dictionaries may |
| 5 |
be validated against DDL1/2/m dictionaries. |
| 6 |
|
| 7 |
## Installing and Initialising PyCIFRW |
| 8 |
|
| 9 |
(Note: these instructions refer to version 4.0 and higher. For |
| 10 |
older versions, see the documentation provided with those versions). |
| 11 |
|
| 12 |
As of version 4.0, it is sufficient to install the PyCIFRW “wheel” |
| 13 |
using `pip`, for example: |
| 14 |
|
| 15 |
pip install --use-wheel PyCifRW-4.2-cp27-none-linux_i686.whl |
| 16 |
|
| 17 |
or using the platform independent source package found on PyPI: |
| 18 |
|
| 19 |
pip install pycifrw |
| 20 |
|
| 21 |
If you want to include PyCIFRW with your package, you can install the |
| 22 |
PyCIFRW wheel into your development environment and then bundle the |
| 23 |
contents of the `CifFile` directory found in the Python local |
| 24 |
libraries directory (usually `site-packages`). |
| 25 |
|
| 26 |
If PyCIFRW has installed properly, the following command should |
| 27 |
complete without any errors: |
| 28 |
|
| 29 |
import CifFile |
| 30 |
|
| 31 |
## Working with CIF files |
| 32 |
|
| 33 |
### Reading CIF files |
| 34 |
|
| 35 |
CIF files are represented in PyCIFRW as `CifFile` objects. These |
| 36 |
objects behave identically to Python dictionaries, with some |
| 37 |
additional methods. `CifFile` objects can be created by calling the |
| 38 |
`ReadCif` function on a filename or URL: |
| 39 |
|
| 40 |
from CifFile import ReadCif |
| 41 |
cf = ReadCif("mycif.cif") |
| 42 |
df = ReadCif("ftp://ftp.iucr.org/pub/cifdics/cifdic.register") |
| 43 |
|
| 44 |
Errors are raised if CIF syntax/grammar violations are |
| 45 |
encountered in the input file or line length limits are exceeded. |
| 46 |
|
| 47 |
A compiled extension (`StarScan.so`) is available in binary |
| 48 |
distributions which increases parsing speed by a factor of three or |
| 49 |
more. To use this facility, include the keyword argument |
| 50 |
`scantype='flex'` in `ReadCif` commands: |
| 51 |
|
| 52 |
cf = ReadCif("mycif.cif",scantype="flex") |
| 53 |
|
| 54 |
Binary distributions are generally only provided for the 'manylinux' |
| 55 |
target, but may also be generated from the source distribution for any |
| 56 |
platform if the appropriate compilers are available on that platform. |
| 57 |
|
| 58 |
Alternatively, you may initialise a CifFile object with the URI: |
| 59 |
|
| 60 |
cf = CifFile("mycif.cif",scantype="flex") |
| 61 |
|
| 62 |
If your CIF file contains characters that are not encoded in UTF8 or |
| 63 |
ASCII, you may pass the 'permissive' option to `ReadCif`, which will |
| 64 |
try other encodings (currently only `latin1`). Use of this option |
| 65 |
is not encouraged. |
| 66 |
|
| 67 |
#### Grammar options |
| 68 |
|
| 69 |
There are three variations in CIF file syntax. An early, little-used |
| 70 |
version of the standard allowed non-quoted data strings to begin with |
| 71 |
square bracket characters ('['). This was disallowed in version 1.1 in |
| 72 |
order to reserve such usage for later developments. The recently |
| 73 |
introduced CIF2 standard adds list and table datastructures to |
| 74 |
CIF1. Detection of the appropriate CIF grammar is automatic, but |
| 75 |
potentially time-consuming for multiple files, so specification of the |
| 76 |
particular version to use is possible with the grammar keyword: |
| 77 |
|
| 78 |
cf = ReadCif('oldcif.cif',grammar='1.0') #oldest CIF syntax |
| 79 |
cf = ReadCif('normcif.cif',grammar='1.1') #widespread |
| 80 |
cf = ReadCif('future.cif',grammar='2.0') #latest standard |
| 81 |
cf = ReadCif('unknown.cif',grammar='auto') #try 2.0->1.1->1.0 |
| 82 |
|
| 83 |
Reading of STAR2 files is also possible by setting `grammar='STAR2'`. |
| 84 |
Currently, the default is set to 'auto'. |
| 85 |
|
| 86 |
### Creating a new CifFile |
| 87 |
|
| 88 |
A new `CifFile` object is usually created empty: |
| 89 |
|
| 90 |
~~~{.python} |
| 91 |
from CifFile import CifFile |
| 92 |
cf = CifFile() |
| 93 |
~~~ |
| 94 |
|
| 95 |
You will need to create at least one `CifBlock` object to hold your |
| 96 |
data. The `CifBlock` is then added to the `CifFile` using the usual |
| 97 |
Python dictionary notation. The dictionary 'key' becomes the |
| 98 |
blockname used for output. |
| 99 |
|
| 100 |
~~~{.python} |
| 101 |
from CifFile import CifBlock |
| 102 |
myblock = CifBlock() |
| 103 |
cf['a_block'] = myblock |
| 104 |
~~~ |
| 105 |
|
| 106 |
A `CifBlock` object may be initialised with another `CifBlock`, in |
| 107 |
which case a copy operation is performed. |
| 108 |
|
| 109 |
Note that most operations on data provided by PyCIFRW involve |
| 110 |
`CifBlock` objects. |
| 111 |
|
| 112 |
## Manipulating values in a CIF file |
| 113 |
|
| 114 |
### Accessing data |
| 115 |
|
| 116 |
The simplest form of access is using standard Python square |
| 117 |
bracket notation. Data blocks and data names within each data |
| 118 |
block are referenced identically to normal Python dictionaries: |
| 119 |
|
| 120 |
~~~{.python} |
| 121 |
my_data = cf['a_data_block']['_a_data_name'] |
| 122 |
~~~ |
| 123 |
|
| 124 |
All values read in are stored as strings ^[ |
| 125 |
This deviates from the current CIF standard, which mandates |
| 126 |
interpreting unquoted strings as numbers where possible and in |
| 127 |
the absence of dictionary definitions to the contrary |
| 128 |
(International Tables, Vol. G., p24). |
| 129 |
], with CIF syntactical |
| 130 |
elements stripped, that is, no enclosing quotation marks or semicolons are |
| 131 |
included in the values. The value associated with a `CifFile` |
| 132 |
dictionary key is always a `CifBlock` object. All standard Python |
| 133 |
dictionary methods (e.g. `get`, `update`, `items()`, `keys()`) are available |
| 134 |
for both `CifFile` and `CifBlock` objects. Note also the convenience |
| 135 |
method `first_block()`, which will return the first datablock stored _which |
| 136 |
is not necessarily the first datablock in the physical file_: |
| 137 |
|
| 138 |
~~~{.python} |
| 139 |
my_data = cf.first_block() |
| 140 |
~~~ |
| 141 |
|
| 142 |
If a data name occurs in a loop, a list of values is |
| 143 |
returned for the value of that dataname - the next section |
| 144 |
describes ways to access looped data. |
| 145 |
|
| 146 |
#### Tabular (“looped”) data |
| 147 |
|
| 148 |
For the purpose of the examples, we use the following |
| 149 |
example CIF file: |
| 150 |
|
| 151 |
~~~~~~~~~~~~~~ |
| 152 |
data_testblock |
| 153 |
loop_ |
| 154 |
_item_5 |
| 155 |
_item_7 |
| 156 |
_item_6 |
| 157 |
1 a 5 |
| 158 |
2 b 6 |
| 159 |
3 c 7 |
| 160 |
4 d 8 |
| 161 |
~~~~~~~~~~~~~~~ |
| 162 |
|
| 163 |
Any table can be interacted with in a column-based |
| 164 |
or a row-based way. A PyCIFRW `CifBlock` object provides |
| 165 |
column-based access using normal square bracket syntax |
| 166 |
as described above: for example `cf['testblock']['_item_6']` |
| 167 |
will return `['5','6','7','8']`. |
| 168 |
|
| 169 |
#### Table row access |
| 170 |
|
| 171 |
The `CifLoopBlock` object represents a loop structure in the CIF file |
| 172 |
and facilitates row-based access. A `CifLoopBlock` object can be |
| 173 |
obtained by calling the `CifBlock` method `GetLoop(dataname)`. |
| 174 |
Column-based access remains available for this object (e.g. `keys()` |
| 175 |
returns a list of datanames in the loop and square bracket notation |
| 176 |
returns a list of column values for that column). |
| 177 |
|
| 178 |
A particular row can be selected using the `CifLoopBlock` |
| 179 |
`GetKeyedPacket` method: |
| 180 |
|
| 181 |
~~~{.python} |
| 182 |
>>> lb = cf['testblock'].GetLoop('_item_6') |
| 183 |
>>> myrow = lb.GetKeyedPacket('_item_7','c') |
| 184 |
>>> myrow._item_5 |
| 185 |
'3' |
| 186 |
~~~ |
| 187 |
|
| 188 |
In this example, the single packet with a value of `'c'` for `_item_7` |
| 189 |
is returned, and packet values can then be accessed using the |
| 190 |
dataname as an attribute of the packet. Note that a `KeyError` is |
| 191 |
raised if more than one packet matches, or no packets match, and |
| 192 |
that the packet returned is a copy of the data read in from the |
| 193 |
file, and therefore can be changed without affecting the `CifBlock` |
| 194 |
object. |
| 195 |
|
| 196 |
You may also access the nth value in this `CifLoopBlock` |
| 197 |
object. ^[Warning: row and column order in a CIF loop is arbitrary; |
| 198 |
while PyCIFRW currently maintains the row order seen in the input |
| 199 |
file, there is nothing in the CIF standards which mandates this |
| 200 |
behaviour, and later implementations may change this behaviour ], and |
| 201 |
values can be obtained from these packets as attributes. |
| 202 |
|
| 203 |
~~~{.python} |
| 204 |
>>> lb = cb.GetLoop("_item_5") |
| 205 |
>>> lb[0] |
| 206 |
['1', 'a', '5'] |
| 207 |
>>> lb[0]._item_7 |
| 208 |
'a' |
| 209 |
~~~ |
| 210 |
|
| 211 |
An alternative way of accessing loop data uses Python iterators, |
| 212 |
allowing the following syntax: |
| 213 |
|
| 214 |
~~~{.python} |
| 215 |
>>> for a in lb: print `a["_item_7"]` |
| 216 |
'a' 'b' 'c' 'd' |
| 217 |
~~~ |
| 218 |
|
| 219 |
Note that in both the above examples the row packet is a copy of |
| 220 |
the looped data, and therefore changes to it will not silently |
| 221 |
alter the contents of the original `CifFile` object, unlike the lists |
| 222 |
returned when column-based access is used. |
| 223 |
|
| 224 |
### Changing or adding data values |
| 225 |
|
| 226 |
If many operations are going to be performed on a single data |
| 227 |
block, it is convenient to assign that block to a new variable: |
| 228 |
|
| 229 |
~~~{.python} |
| 230 |
cb = cf['my_block'] |
| 231 |
~~~ |
| 232 |
|
| 233 |
A new data name and value may be added, or the value of an |
| 234 |
existing name changed, by straight assignment: |
| 235 |
|
| 236 |
~~~{.python} |
| 237 |
cb['_new_data_name'] = 4.5 |
| 238 |
cb['_old_data_name'] = 'cucumber' |
| 239 |
~~~ |
| 240 |
|
| 241 |
By default, old values are overwritten silently. To instead |
| 242 |
raise an error when an item value is going to be overwritten, |
| 243 |
set attribute 'overwrite' to `False`: |
| 244 |
|
| 245 |
~~~{.python} |
| 246 |
cb.overwrite = False |
| 247 |
cb['_old_data_name'] = 'cucumber' # Error is raised |
| 248 |
~~~ |
| 249 |
|
| 250 |
To return to the original behaviour, set `overwrite` to True. |
| 251 |
To allow/disallow overwriting for all blocks in a file, call methods |
| 252 |
unlock()/lock() respectively. |
| 253 |
|
| 254 |
Note that values may be strings or numbers. |
| 255 |
|
| 256 |
#### Creating loops |
| 257 |
|
| 258 |
To create a loop, simply set the column values to same-length lists, |
| 259 |
and then call the `CifBlock` method `CreateLoop` with a list of the |
| 260 |
looped datanames as a single argument. This method will raise an |
| 261 |
error if the datanames have different length columns assigned to them. |
| 262 |
For example, the following commands create the example loop above: |
| 263 |
|
| 264 |
~~~{.python} |
| 265 |
cb['_item_5'] = [1,2,3,4] |
| 266 |
cb['_item_7'] = ['a','b','c','d'] |
| 267 |
cb['_item_6'] = [5,6,7,8] |
| 268 |
cb.CreateLoop(['_item_5','_item_7','_item_6']) |
| 269 |
~~~ |
| 270 |
|
| 271 |
As a special case, if `CreateLoop` is called with data names that are |
| 272 |
*not* list-valued, these items will be first placed into |
| 273 |
single-element lists before creating the loop, resulting in a loop |
| 274 |
with one row. |
| 275 |
|
| 276 |
Another method, `AddToLoop(dataname,newdata)`, adds columns in |
| 277 |
`newdata` to the pre-existing loop containing `dataname`, silently |
| 278 |
overwriting duplicate data. `newdata` should be a Python dictionary of |
| 279 |
dataname - datavalue pairs. |
| 280 |
|
| 281 |
Note that lists (and other listlike objects except packets) |
| 282 |
returned by PyCIFRW actually point to the list currently inside |
| 283 |
the `CifBlock` object, and therefore any modification to them will |
| 284 |
modify the stored list. While this is often the desired |
| 285 |
behaviour, if you intend to manipulate such a list in other parts |
| 286 |
of your program while preserving the original CIF information, |
| 287 |
you should first copy the list to avoid destroying the loop |
| 288 |
structure: |
| 289 |
|
| 290 |
~~~{.python} |
| 291 |
mysym = cb['_symmetry_ops'][:] |
| 292 |
mysym.append('x-1/2,y+1/2,z') |
| 293 |
~~~ |
| 294 |
|
| 295 |
#### Changing item order |
| 296 |
|
| 297 |
Item (and block) order has *no* semantic significance in CIF files. |
| 298 |
However, the readability of CIF files in simple text editors leads to |
| 299 |
a desire to organise the output order for human readers. The |
| 300 |
`ChangeItemOrder` method allows the order in which data items appear |
| 301 |
in the printed file to be changed: |
| 302 |
|
| 303 |
~~~{.python} |
| 304 |
mycif['testblock'].ChangeItemOrder('_item_5',0) |
| 305 |
~~~ |
| 306 |
|
| 307 |
will move `_item_5` to the beginning of the datablock. When |
| 308 |
changing the order inside a loop block, the loop block's method |
| 309 |
must be called i.e.: |
| 310 |
|
| 311 |
~~~{.python} |
| 312 |
aloop = mycif['testblock'].GetLoop('_loop_item_1') |
| 313 |
aloop.ChangeItemOrder('_loop_item_1',4) |
| 314 |
~~~ |
| 315 |
|
| 316 |
Note also that the position of a loop within the file can be |
| 317 |
changed in this way as well, by passing the 'block number' |
| 318 |
object as the first argument. Each loop is assigned a simple |
| 319 |
integer number, which can be found by calling `FindLoop` with |
| 320 |
the name of a column in that loop: |
| 321 |
|
| 322 |
~~~{.python} |
| 323 |
loop_id = mycif['testblock'].FindLoop('_item_6') |
| 324 |
mycif['testblock'].ChangeItemOrder(loop_id,0) |
| 325 |
~~~ |
| 326 |
|
| 327 |
will move the loop block to the beginning of the printed |
| 328 |
datablock. |
| 329 |
|
| 330 |
#### Adding and removing table rows |
| 331 |
|
| 332 |
While it is most efficient to add columns to the `CifBlock` and then |
| 333 |
bind them together once into a loop, it is possible to add a new row |
| 334 |
into an existing loop using the `AddPacket(packet)` method of `CifLoopBlock` |
| 335 |
objects: |
| 336 |
|
| 337 |
~~~{.python} |
| 338 |
aloop = mycif['testblock'].GetLoop('_item_7') |
| 339 |
template = aloop.GetKeyedPacket('_item_7','d') |
| 340 |
template._item_5 = '5' |
| 341 |
template._item_7 = 'e' |
| 342 |
template._item_6 = '9' |
| 343 |
aloop.AddPacket(template) |
| 344 |
~~~ |
| 345 |
|
| 346 |
Note we use an existing packet as a template in this example. If |
| 347 |
you wish to create a packet from scratch, you should instantiate |
| 348 |
a `StarPacket`: |
| 349 |
|
| 350 |
~~~{.python} |
| 351 |
from CifFile import StarFile #installed with PyCIFRW |
| 352 |
newpack = StarFile.StarPacket() |
| 353 |
newpack._item_5 = '5' |
| 354 |
... |
| 355 |
aloop.AddPacket(newpack) |
| 356 |
~~~ |
| 357 |
|
| 358 |
Note that an error will be raised when calling `AddPacket` if the |
| 359 |
packet attributes do not exactly match the item names in the |
| 360 |
loop. |
| 361 |
|
| 362 |
A packet may be removed using the `RemoveKeyedPacket` method, which |
| 363 |
chooses the packet to be removed based on the value of the given |
| 364 |
dataname: |
| 365 |
|
| 366 |
~~~{.python} |
| 367 |
aloop.RemoveKeyedPacket('_item_7','a') |
| 368 |
~~~ |
| 369 |
|
| 370 |
## Writing CIF Files |
| 371 |
|
| 372 |
The `CifFile` method `WriteOut` returns a string which may be passed |
| 373 |
to an open file descriptor: |
| 374 |
|
| 375 |
~~~{.python} |
| 376 |
outfile = open("mycif.cif") |
| 377 |
outfile.write(cf.WriteOut()) |
| 378 |
~~~ |
| 379 |
|
| 380 |
Or the built-in Python `str()` function can be used: |
| 381 |
|
| 382 |
outfile.write(str(cf)) |
| 383 |
|
| 384 |
`WriteOut` takes an optional keyword argument, `comment`, which should be a |
| 385 |
string containing a comment which will be placed at the top of |
| 386 |
the output file. This comment string must already contain # |
| 387 |
characters at the beginning of lines: |
| 388 |
|
| 389 |
~~~{.python} |
| 390 |
outfile.write(cf.WriteOut("#This is a test file")) |
| 391 |
~~~ |
| 392 |
|
| 393 |
Two additional keyword arguments control line length in the output |
| 394 |
file: `wraplength` and `maxoutlength`. Lines in the output file are |
| 395 |
guaranteed to be shorter than `maxoutlength` characters, and PyCIFRW |
| 396 |
will additionally insert a line break if putting two data values or a |
| 397 |
dataname/datavalue pair together on the same line would exceed |
| 398 |
`wraplength`. In other words, unless data values are longer than |
| 399 |
`maxoutlength` characters long, no line breaks will be inserted into |
| 400 |
those datavalues the output file. By default, `wraplength = 80` and |
| 401 |
`maxoutlength = 2048`. Note that the CIF line folding protocol is |
| 402 |
used, which makes wrapping of long datavalues reversible. |
| 403 |
|
| 404 |
These values may be set on a per block basis by calling the |
| 405 |
`SetOutputLength` method of the block. |
| 406 |
|
| 407 |
The order of output of items within a `CifFile` or `CifBlock` is |
| 408 |
specified using the `ChangeItemOrder` method (see above). The |
| 409 |
default order is the order that items were first added in to |
| 410 |
the `CifFile`/`CifBlock`. Note that this order is not guaranteed |
| 411 |
to be the order in which they appear in the input file. |
| 412 |
|
| 413 |
### Templating system |
| 414 |
|
| 415 |
If you want precise control of the layout of your CIF file, you can |
| 416 |
pass a template file to the `CifBlock.process_template` method. A |
| 417 |
'template' is a CIF file containing a |
| 418 |
single block, where the datanames are laid out in the way that the |
| 419 |
user desires. The layout elements that are picked up from this template are: |
| 420 |
|
| 421 |
1. order (overrides current order of `CifBlock`) |
| 422 |
2. column position of datavalues (only the first row of a loop block is inspected) |
| 423 |
3. delimiters |
| 424 |
4. If a semicolon-delimited string outside a loop contains 3 or more spaces in a row |
| 425 |
at the beginning of a line, that |
| 426 |
datavalue will be wrapped and indented by the same amount on output |
| 427 |
|
| 428 |
Constraints on the template: |
| 429 |
|
| 430 |
1. There should only ever be one dataname on each line |
| 431 |
2. `loop_` and and `datablock` tokens should appear as the only non-blank |
| 432 |
characters on their lines |
| 433 |
3. Comments are flagged by a '#' as the first character in the line |
| 434 |
4. Blank lines are acceptable (and ignored) |
| 435 |
5. The dummy datavalues should use only alphanumeric characters |
| 436 |
6. Semicolon-delimited strings are not allowed in loops |
| 437 |
|
| 438 |
After calling `process_template` with the template file as the |
| 439 |
argument, subsequent calls to `WriteOut` will respect the template |
| 440 |
information, and revert to default behaviour for any datanames that |
| 441 |
were not found in the template. Templating is most useful when |
| 442 |
formatting CIF dictionaries which are read heavily by |
| 443 |
human readers, and have many (thousands!) of datablocks, each |
| 444 |
containing the same limited number of datanames. |
| 445 |
|
| 446 |
#### Output format |
| 447 |
|
| 448 |
CIF files are output by default in CIF2 grammar, but with the |
| 449 |
CIF2-only triple quotes avoided unless explicitly requested through a |
| 450 |
template. Therefore, as long as CIF2-only datastructures (lists and |
| 451 |
tables) are absent, the output CIF files will conform to 1.0,1.1 and |
| 452 |
2.0 grammar. The grammar of the output files can be changed by |
| 453 |
calling `CifFile.set_grammar` with the choices being `1.0`,`1.1`,`2.0` or |
| 454 |
`STAR2`. |
| 455 |
|
| 456 |
# Example programs |
| 457 |
|
| 458 |
A program which uses PyCIFRW for validation, `validate_cif.py`, is |
| 459 |
included in the distribution in the `Programs` subdirectory. It |
| 460 |
will validate a CIF file (including dictionaries) against one or |
| 461 |
more dictionaries which may be specified by name and version or |
| 462 |
as a filename on the local disk. If name and version are |
| 463 |
specified, the IUCr canonical registry or a local registry is |
| 464 |
used to find the dictionary and download it if necessary. |
| 465 |
|
| 466 |
## Usage |
| 467 |
|
| 468 |
python validate_cif.py [options] ciffile |
| 469 |
|
| 470 |
## Options |
| 471 |
|
| 472 |
--version show version number and exit |
| 473 |
-h,--help print short help message |
| 474 |
-d dirname directory to find/store dictionary files |
| 475 |
-f dictname filename of locally-stored dictionary |
| 476 |
-u version dictionary version to resolve using registry |
| 477 |
-n name dictionary name to resolve using registry |
| 478 |
-s store downloaded dictionary locally (default True) |
| 479 |
-c fetch and use canonical registry from IUCr |
| 480 |
-r registry location of registry as filename or URL |
| 481 |
-t The file to be checked is itself a DDL2 dictionary |