source: trunk/import_cif.tcl @ 285

Last change on this file since 285 was 285, checked in by toby, 14 years ago

# on 2000/09/26 14:51:04, toby did:
Various fixes: change data names to all lower case
better error detection
use " or ' quoted strings
fix semicolon recognition -- now characters after ending ; are parsed
improve comments
Add Read_BrowseCIF proc for debug and possibly other use

  • Property rcs:author set to toby
  • Property rcs:date set to 2000/09/26 14:51:04
  • Property rcs:lines set to +155 -48
  • Property rcs:rev set to 1.2
  • Property rcs:state set to Exp
  • Property svn:keywords set to Author Date Revision Id
File size: 17.8 KB
Line 
1# $Id: import_cif.tcl 285 2009-12-04 23:03:30Z toby $
2
3#-------------------------------------------------
4# define info used in addcmds.tcl
5set description "Crystallographic Information File (CIF)"
6set extensions .cif
7set procname ReadCIFFile
8#-------------------------------------------------
9
10proc ReadCIFFile {filename} {
11    global expgui
12    set fp [open $filename r]
13    pleasewait "Reading CIF file"         
14    set blocks [ParseCIF $filename]
15    if {$blocks == ""} {
16        donewait
17        MyMessageBox -parent . -type ok -icon warning \
18                -message "Note: no valid CIF blocks were read from file $filename"
19        return 
20    }
21    set allblocks {}
22    set coordblocks {}
23    # search each block for coordinate
24    for {set i 1} {$i <= $blocks} {incr i} {
25        lappend allblocks $i
26        global block$i
27        set flag 1
28        foreach id {_atom_site_fract_x _atom_site_fract_y _atom_site_fract_z} {
29            if {[array name block$i $id] == ""} {set flag 0}
30        }
31        if $flag {lappend coordblocks $i}
32    }
33    donewait
34    if {$coordblocks == ""} {
35        MyMessageBox -parent . -type ok -icon warning \
36                -message "Note: CIF $filename contains no coordinates"
37        return
38    }
39    set expgui(choose) [lindex $coordblocks 0]
40    # there is more than one appropriate block
41    if {[llength $coordblocks] > 1} {
42        catch {destroy .choose}
43        toplevel .choose
44        wm title .choose "Choose CIF Block"
45        grid [label .choose.0 -text \
46                "More than one block in CIF $filename\ncontains coordinates.\nSelect the block to use" \
47                ] -row 0 -column 0 -columnspan 2
48        set row 0
49        foreach i $coordblocks {
50            incr row
51            set name ""
52            catch {set name [set block${i}(data_)]}
53            grid [radiobutton .choose.$row -value $i \
54                    -text "block $i ($name)" -variable expgui(choose)] \
55                    -row $row -column 0 -sticky w
56        }
57        grid [button .choose.browse -text CIF\nBrowser -command \
58                "BrowseCIF [list $allblocks] [list $coordblocks] .choose.cif" \
59                ] -row 1 -rowspan $row -column 1 
60        grid [button .choose.ok -text OK -command "destroy .choose"] \
61                -row [incr row] -column 0 -columnspan 2
62        tkwait window .choose
63    }
64
65    set i $expgui(choose)
66    # get the space group
67    set spg {}
68    set msg {}
69    catch {
70        set spg [set block${i}(_symmetry_space_group_name_h-m)]
71        regsub -all {'} $spg {} spg
72        # see if this space group exists in the table
73        set fp [open [file join $expgui(scriptdir) spacegrp.ref] r]
74        while {[gets $fp line] >= 0} {
75            if {[string trim $spg] == [lindex $line 8]} {
76                close $fp
77                break
78                set fp {}
79            }
80        }       
81        if {$fp != ""} {
82            close $fp
83            set msg "Warning: the Space Group ($spg) may not be correctly specified for GSAS"
84        }
85    }
86    set cell {}
87    foreach var {_cell_length_a _cell_length_b _cell_length_c \
88            _cell_angle_alpha _cell_angle_beta _cell_angle_gamma} {
89        # leave blank any unspecified data items
90        set val {}
91        catch {set val [set block${i}($var)]}
92        lappend cell [lindex [ParseSU $val] 0]
93    }
94   
95    set atomlist {}
96    set lbllist {}
97    catch {
98        set lbllist [set block${i}(_atom_site_label)]
99    }
100    set uisolist {}
101    catch {
102        set uisolist [set block${i}(_atom_site_u_iso_or_equiv)]
103        set Uconv 1
104    }
105    if {$uisolist == ""} {
106        set uisolist [set block${i}(_atom_site_b_iso_or_equiv)]
107        set Uconv [expr 1/(8*3.14159*3.14159)]
108    }
109    set occlist {}
110    catch {
111        set occlist [set block${i}(_atom_site_occupancy)]
112    }
113    set typelist {}
114    catch {
115        set typelist [set block${i}(_atom_site_type_symbol)]
116    }
117    foreach x [set block${i}(_atom_site_fract_x)] \
118            y [set block${i}(_atom_site_fract_y)] \
119            z [set block${i}(_atom_site_fract_z)] \
120            lbl $lbllist uiso $uisolist occ $occlist type $typelist {
121        # should not be any quotes, but remove them, if there are
122        regsub -all {'} $lbl {} lbl
123        regsub -all {'} $type {} type
124        # CIF specifies types as Cu2+; GSAS uses Cu+2
125        if {[regexp {([A-Za-z]+)([1-9])([+-])} $type junk elem sign val]} {
126            set type ${elem}${val}$sign
127        }
128        # if type is missing, attempt to parse an element in the label
129        if {$type == "" && $lbl != ""} {
130            regexp {[A-Za-z][A-Za-z]?} $lbl type
131        }
132        # get rid of standard uncertainies
133        foreach var {x y z occ uiso} {
134            catch {
135                set $var [lindex [ParseSU [set $var]] 0]
136            }
137        }
138        # convert Biso to Uiso (if needed)
139        if {$Uconv != 1} {
140            catch {set $uiso [expr $Uconv*$uiso]}
141        }
142        lappend atomlist [list $lbl $x $y $z $type $occ $uiso]
143    }
144
145    # clean up -- get rid of the CIF arrays
146    for {set i 1} {$i <= $blocks} {incr i} {
147        unset block$i
148    }
149    return "[list $spg] [list $cell] [list $atomlist] [list $msg]"
150}
151
152# ParseCIF reads and parses a CIF file putting the contents of
153# each block into arrays block1, block2,... in the caller's level
154#    the name of the block is saved as blockN(data_)
155# data names and items are saved as blockN(_data_name) = {data item}
156#    data items are not reformatted, thus quotes, semicolons & newlines
157#    are included in the data item string
158#    CIF names are converted to lower case
159# for looped data names, the data items are included in a list:
160#    blockN(_cif_name) = {item1 "item2 with spaces" item3 ...}
161# the contents of each loop are saved as blockN(loop_M)
162#
163# The proc returns the number of blocks that have been read or a
164#    null string if the file cannot be opened
165#
166# This parser does some error checking [errors are reported in blockN(error)]
167#    but the parser could get confused if the CIF has invalid syntax
168#
169proc ParseCIF {filename} {
170    if [catch {
171        set fp [open $filename r]
172    }] {return ""}
173
174    set blocks 0
175    set EOF 1
176    set line {}
177    set dataname {}
178    # line counter (for error messages)
179    set linenum 0
180    # this flags where we are w/r a loop_
181    #    -1 not in a loop
182    #     0 reading a loop header (data names)
183    #     1 reading the data items in a loop
184    set loopflag -1
185    set loopnum -1
186    # loop over tokens
187    while {$EOF} {
188        # read the next line, unless we have a holdover from the previous
189        if {[string length [string trim $line]] <= 0} {
190            incr linenum
191            if {[gets $fp line] < 0} {set EOF 0}
192        }
193        # flag if the string \' has been replaced
194        set hidden 0
195        set trimline [string trim $line]
196        set firstchar [string index $trimline 0]
197       
198        if {[string length $trimline] <= 0} {
199            # the line is blank
200            set line {}
201            continue
202        } 
203       
204        if {$firstchar == "#"} {
205            # this is a comment
206            set line {}
207            continue
208        } 
209       
210        if {[string tolower [string range $trimline 0 4]] == "data_"} {
211            # this is the beginning of a data block
212            incr blocks
213            # are there other tokens on this line?
214            if {[set pos [string first { } $trimline]] == -1} {
215                set blockname [string range $trimline 5 end]
216                set line {}
217            } else {
218                set blockname [string range $trimline 5 [expr $pos-1]]
219                set line [string range $trimline $pos end]
220            }
221            global block$blocks
222            catch {unset block$blocks}
223            set block${blocks}(data_) $blockname
224            set loopnum -1
225           
226            if {$line == ""} continue
227            if {$dataname != ""} {
228                # this is an error -- data_ block where a data item is expected
229                append block${blocks}(errors) "No data item was found for $dataname near line $linenum\n"
230                set dataname {}
231            }
232        }
233       
234        if {$firstchar == "_"} {
235            # this is a cif data name
236            if {$dataname != ""} {
237                # this is an error -- data name where a data item is expected
238                append block${blocks}(errors) "No data item was found for $dataname near line $linenum\n"
239            }
240            # parse it out & convert it to lower case
241            if {[set pos [string first { } $trimline]] == -1} {
242                # nothing else is on this line
243                set dataname [string tolower $trimline]
244                set line {}
245            } else {
246                # There other tokens on this line
247                set dataname [string range $trimline 0 [expr $pos-1]]
248                set line [string tolower [string range $trimline $pos end]]
249            }
250           
251            if {$loopflag == 0} {
252                # in a loop header, save the names in the loop list
253                lappend looplist $dataname
254                set block${blocks}(loop_${loopnum}) $looplist
255                # clear the array element for the data item
256                # -- should not be needed for a valid CIF but if a name is used
257                # -- twice in the same block, want to wipe out the 1st data
258                set block${blocks}($dataname) {}
259                set dataname {}
260            } elseif {$loopflag > 0} {
261                # in a loop body, so the loop is over
262                set loopflag -1
263            }
264            continue
265        }
266       
267        if {[string tolower [string range $trimline 0 4]] == "loop_"} {
268            set loopflag 0
269            incr loopnum
270            set looplist {}
271            set block${blocks}(loop_${loopnum}) {}
272            # save any other tokens on this line
273            set line [string range $trimline 5 end]
274            continue
275        }
276
277        # keywords not matched, must be some type of data item
278        set item {}
279       
280        if {[string index $line 0] == ";"} {
281            # multiline entry with semicolon termination
282            set item $line
283            # read lines until we get a naked semicolon
284            while {$EOF} {
285                incr linenum
286                if {[gets $fp line] < 0} {set EOF 0}
287                if {[string index $line 0] == ";"} {
288                    append item "\n;"
289                    # make sure the line has a blank in front, so
290                    # a semicolon in col 2 is not treated as a quote character
291                    set line " [string range $line 1 end]"
292                    break
293                }
294            }
295            if {[string trim $line] == ""} {set line ""}
296        } elseif {$firstchar == {"}} {
297            # a quoted string
298            # hide any \" sequences in a non-ASCII character (\201)
299            set hidden [regsub -all {\\"} $trimline \201 trimline]
300            # parse out the quoted string, save the remainder
301            if {![regexp {("[^"]*")(.*)} $trimline junk item line]} {
302                # this is an error -- no end-quote was found
303                set item $line
304                set line {}
305                append block${blocks}(errors) "The quoted string on line $linenum does not have a close quote ([string trim $item])\n"
306            }
307        } elseif {$firstchar == {'}} {
308            # a quoted string
309            # hide any \' sequences in a non-ASCII character (\200)
310            set hidden [regsub -all {\\'} $trimline \200 trimline]
311            # parse out the quoted string, save the remainder
312            if {![regexp {('[^']*')(.*)} $trimline junk item line]} {
313                # this is an error -- no end-quote was found
314                set item $line
315                set line {}
316                append block${blocks}(errors) "The quoted string on line $linenum does not have a close quote ([string trim $item])\n"
317            }
318        } else {
319            # must be a single space-delimited value
320            set pos [string first { } $trimline]
321            if {$pos < 0} {
322                # and the only thing left on the line
323                set item $trimline
324                set line {}
325            } else {
326                # save the rest of the line
327                set line [string range $trimline $pos end]
328                incr pos -1
329                set item [string range $trimline 0 $pos]
330            }
331        }
332       
333        # a data item has been read
334        # fix the hidden characters, if any
335        if $hidden {
336            regsub -all \200 $item {\\'} item
337            regsub -all \201 $item {\\"} item
338        }
339
340        # store the data item
341        if {$loopflag >= 0} {
342            # if in a loop, increment the loop element counter to select the
343            # appropriate array element
344            incr loopflag
345            set i [expr ($loopflag - 1) % [llength $looplist]]
346            lappend block${blocks}([lindex $looplist $i]) $item
347        } elseif {$dataname == ""} {
348            # this is an error -- a data item where we do not expect one
349            append block${blocks}(errors) "The string \"$item\" on line $linenum was unexpected\n"
350        } else {
351            set block${blocks}($dataname) $item
352            set dataname ""
353        }
354    }
355    close $fp
356    return $blocks
357}
358
359# this proc creates a hierarchical CIF browser
360# note that the BWidget package is required
361proc BrowseCIF {blocklist "selected {}" "frame .cif"} {
362
363    if [catch {package require BWidget}] {
364        tk_dialog $frame {No BWidget} \
365                "Sorry, the CIF Browser requires the BWidget package" \
366                warning 0 Continue
367        return
368    }
369    if {$selected == ""} {set selected $blocklist}
370    catch {destroy $frame}
371    toplevel $frame 
372    wm title $frame "CIF Browser"
373
374    set pw    [PanedWindow $frame.pw -side top]
375    grid $pw -sticky news -column 0 -row 0 
376    grid columnconfigure $frame 0 -weight 1
377    grid rowconfigure $frame 0 -minsize 250 -weight 1
378
379    # create a left hand side pane for the hierarchical tree
380    set pane  [$pw add -weight 1]
381    set sw    [ScrolledWindow $pane.lf \
382            -relief sunken -borderwidth 2]
383    set tree  [Tree $sw.tree \
384            -relief flat -borderwidth 0 -width 15 -highlightthickness 0 \
385            -redraw 1]
386    grid $sw
387    grid $sw -sticky news -column 0 -row 0 
388    grid columnconfigure $pane 0 -minsize 275 -weight 1
389    grid rowconfigure $pane 0 -weight 1
390    $sw setwidget $tree
391   
392    # create a right hand side pane to show the value
393    set pane [$pw add -weight 1]
394    set sw   [ScrolledWindow $pane.sw \
395            -relief sunken -borderwidth 2]
396    pack $sw -fill both -expand yes -side bottom
397    set lb [ScrollableFrame::create $sw.lb -width 250]
398    $sw setwidget $lb
399
400    set num 0
401    foreach n $blocklist {
402        global block$n
403        # make a list of data names in loops
404        set looplist {}
405        foreach loop [array names block$n loop_*] {
406            eval lappend looplist [set block${n}($loop)]
407        }
408        # put the block name
409        set blockname [set block${n}(data_)]
410        set open 0
411        if {[lsearch $selected $n] != -1} {set open 1}
412        $tree insert end root block$n -text "_data_$blockname" \
413                -open $open -image [Bitmap::get copy]
414        # loop over the names in each block
415        foreach name [array names block$n _*] {
416            # don't include looped names
417            if {[lsearch $looplist $name] == -1} {
418                $tree insert end block$n [incr num] -text $name \
419                        -image [Bitmap::get folder] -data block$n
420            }
421        }
422        foreach loop [array names block$n loop_*] {
423            $tree insert end block$n block${n}$loop -text $loop \
424                    -image [Bitmap::get file] -data "block$n loop"
425            foreach name [set block${n}($loop)] {
426                $tree insert end block${n}$loop [incr num] -text $name \
427                        -image [Bitmap::get folder] -data "block$n $loop"
428            }
429        }
430        foreach name [array names block$n errors] {
431            $tree insert end block$n [incr num] -text $name \
432                    -image [Bitmap::get undo] -data block$n
433        }
434    }
435    $tree bindImage <1> "showCIFvalue $tree $sw"
436    $tree bindText <1> "showCIFvalue $tree $sw"
437    grid [button $frame.c -text Close -command "destroy $frame"] -column 0 -row 1
438}
439
440# used in BrowseCIF in response to the spinbox
441# show the contents of a loop
442proc ShowLoopVar {array loop frame sb} {
443    global $array
444    set looplist [set ${array}($loop)]
445    set index [$sb getvalue]
446    set i 0
447    foreach var $looplist {
448        incr i
449        [$frame.$i getframe].l config \
450                -text [lindex [set ${array}($var)] $index]
451    }
452}
453
454# used in BrowseCIF in response to the clicking on a CIF dataname
455# shows the contents data name or a loop
456proc showCIFvalue {tree sw name} {
457    set data [$tree itemcget $name -data]
458    set text [$tree itemcget $name -text]
459
460    # delete old contents of frame
461    set frame [$sw.lb getframe]
462    eval destroy [grid slaves $frame]
463    # reset the scrollbars
464    $sw.lb xview moveto 0
465    $sw.lb yview moveto 0
466    # leave room for a scrollbar
467    grid columnconfig $frame 0 -minsize [expr \
468            [winfo width [winfo parent $frame]] - 20]
469    if {$data == ""} {
470        return
471    }
472   
473    #
474    if {[llength $data] == 2} {
475        global [lindex $data 0]
476        if {[lindex $data 1] == "loop"} {
477            set looplist [set [lindex $data 0]($text)]
478            # get number of elements for first name
479            set names [llength [set [lindex $data 0]([lindex $looplist 0])]]
480            set sb $frame.spin
481            grid [SpinBox $sb -range "1 $names 1" \
482                    -label "Loop\nelement #" -labelwidth 10 -width 10 \
483                    -command    "ShowLoopVar [lindex $data 0] $text $frame $sb" \
484                    -modifycmd  "ShowLoopVar [lindex $data 0] $text $frame $sb"] \
485                    -column 0 -row 0 -sticky w
486            set i 0
487            foreach var $looplist {
488                incr i
489                grid [TitleFrame $frame.$i -text $var -side left] \
490                        -column 0 -row $i -sticky ew
491                pack [label [$frame.$i getframe].l -anchor w -justify left] -side left
492            }
493            ShowLoopVar [lindex $data 0] $text $frame $sb
494        } else {
495            grid [TitleFrame $frame.0 -text $text -side left] \
496                    -column 0 -row 0 -sticky ew
497            set row 0
498            set frame0 [$frame.0 getframe]
499            grid columnconfig $frame0 2 -weight 1
500            foreach name [set [lindex $data 0]($text)] {
501                incr row
502                grid [label $frame0.a$row -justify left -text $row]\
503                        -sticky w -column 0 -row $row
504                grid [label $frame0.b$row -bd 2 -relief groove \
505                        -justify left -anchor w -text $name]\
506                        -sticky new -column 1 -row $row 
507            }
508        }
509    } else {
510        # unlooped data name
511        global [lindex $data 0]
512        grid [TitleFrame $frame.0 -text $text -side left] \
513                -column 0 -row 0 -sticky ew
514        pack [label [$frame.0 getframe].l -anchor w -justify left\
515                -text [set ${data}($text)]] -side left
516    }
517}
518
519# Parse a number in CIF, that may include a SU (ESD) value
520# note that this routine will ignore spaces, quotes & semicolons
521proc ParseSU {value} {
522    # if there is no SU just return the value
523    if {[string first "(" $value] == -1} {
524        return $value
525    }
526    # is there a decimal point?
527    if [regexp {([-+]?[0-9]*\.)([0-9]*)\(([0-9]+)\)} $value junk a b err] {
528        set ex [string length $b]
529        return [list ${a}${b} [expr {pow(10.,-$ex)*$err}]]
530    }
531    if [regexp {([-+]?[0-9]*)\(([0-9]+)\)} $value junk a err] {
532        return [list ${a} $err]
533    }
534    tk_dialog .err {ParseSU Error} \
535            "ParseSU: Error processing value $value" \
536            warning 0 Continue
537}
538
539# a stand-alone routine for testing. Select, read and browse a CIF
540proc Read_BrowseCIF {} {
541    global tcl_platform
542    if {$tcl_platform(platform) == "windows"} {
543        set filetypelist {
544            {"CIF files" .CIF} {"All files" *}
545        }
546    } else {
547        set filetypelist {
548            {"CIF files" .CIF} {"CIF files" .cif} {"All files" *}
549        }
550    }   
551    set file [tk_getOpenFile -parent . -filetypes $filetypelist]
552    if {$file == ""} return
553    if {![file exists $file]} return
554    # plasewait and donewait are defined in gsascmds.tcl and may not be present
555    catch {pleasewait "Reading CIF file"}
556    set blocks [ParseCIF $file]
557    if {$blocks == ""} {
558        donewait
559        MessageBox -parent . -type ok -icon warning \
560                -message "Note: no valid CIF blocks were read from file $filename"
561        return
562    }
563    catch {donewait}
564    set allblocks {}
565    for {set i 1} {$i <= $blocks} {incr i} {
566        lappend allblocks $i
567    }
568    if {$allblocks != ""} {
569        BrowseCIF $allblocks "" .cif
570        # wait for the window to close
571        tkwait window .cif
572    } else {
573        puts "no blocks read"
574    }
575    # clean up -- get rid of the CIF arrays
576    for {set i 1} {$i <= $blocks} {incr i} {
577        global block$i
578        unset block$i
579    }
580}
Note: See TracBrowser for help on using the repository browser.