source: trunk/import_cif.tcl @ 319

Last change on this file since 319 was 319, checked in by toby, 13 years ago

# on 2000/10/12 21:30:14, toby did:
Add www help support

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