ordali_sequence.tcl 68.9 KB
Newer Older
luc.moulinier's avatar
luc.moulinier committed
1 2


luc.moulinier's avatar
luc.moulinier committed
3 4 5 6 7
#
# ordali_sequence.tcl
#


8 9 10 11 12 13 14 15
proc OuvrirFichierAlignementDansOrdali {{type "Unk"} {Fichier ""}} {
    global Sequences FichierTFA FichierXML FichierMSF FichierRSF FichierORD FichierALN Defauts

    if {[info exists Sequences]} {
	FaireLire "Close the current file first !"
	return
    }

luc.moulinier's avatar
luc.moulinier committed
16
    if {[string tolow]er $type] eq "macsim"} {set type "XML"}
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    set tyfi $type
    if {$type eq "Unk"} {set tyfi "all"}

    if {$Fichier eq ""} {
	set Fichier [DemandeEtOuvreFichier [string tolower $tyfi]]
    }

    if {$Fichier eq ""} {return}

    DemarrageOrdali .wroom

    if {"tdom" ni [package names]} {
	LoadTclPackages
    }

    if {$type eq "Unk"} {
	set ext [string tolower [file extension $Fichier]]
	if {$ext ni [list ".xml" ".macsim" ".tfa" ".msf" ".rsf" ".ord" ".fasta"]} {
	    set type [DetecteTypeFichier $Fichier]
	    if {$type eq ""} {
		set ctype [tk_dialog .typfi "File type" "Please precise your file format :" "" 0 "Macsim/xml" "MSF" "TFA" "RSF" "Clustal" "Ordalie" "Cancel"]
		switch $ctype {
		    0 {set type "XML"}
		    1 {set type "MSF"}
		    2 {set type "TFA"}
		    3 {set type "RSF"}
		    4 {set type "ALN"}
		    5 {set type "ORD"}
		    6 {return}
		}
	    }
	} else {
	    set type [string toupper [string range $ext 1 end]]
	    if {$type eq "MACSIM"} {set type "XML"}
	}
    }
    if {$type ne "Unk"} {
	LesDefauts TypeAli $type
    }

    set type [string tolower $type]
    InitInfoArrays
    switch $type {
	"msf" {
	    set FichierMSF $Fichier
	    LesDefauts FichierMSF $Fichier
	}
	"xml" {
	    set FichierXML $Fichier
	    LesDefauts FichierXML $Fichier
	}
	"tfa" {
	    set FichierTFA $Fichier
	    LesDefauts FichierTFA $Fichier
	}
	"rsf" {
	    set FichierRSF $Fichier
	    LesDefauts FichierRSF $Fichier
	}
	"aln" {
	    set FichierALN $Fichier
	    LesDefauts FichierALN $Fichier
	}
	"ord" {
	    set FichierORD $Fichier
	    LesDefauts FichierORD $Fichier
	}
    }

    LoadingAlignement
    if {[set Defauts(PreCompute)]} {
	PreCalculs
    }
    InitAffichage
    if {[info exists ::TabSF]} {
	ChangeMode "feature"
    }
    BindingsOrdali
    BindModeNormal

    #FaireLaSuite
    FinDemarrage .wroom

    return
}


proc LitLeTFA {FileOrText aNom aSeq} {
    upvar $aNom Nom $aSeq Seq

    if {[file exists $FileOrText]} {
	set Lignes [LesLignesDuFichier $FileOrText]
    } else {
	set Lignes [split $FileOrText "\n"]
    }
    lappend Lignes ">"

    set n 0
    set laseq ""
    foreach l $Lignes {
	set l [string trim $l]
	if {$l eq ""} {continue}
	if {[string index $l 0] eq ">"} {
	    if {$laseq ne ""} {
		set laseq [string map [list " " "" "-" "." "\n" "" "~" "."] $laseq]
		set laseq [string toupper $laseq]
		lappend Nom $lenom
		set Seq($lenom) $laseq
		set laseq ""
		incr n
	    }

	    set l [string trim [string range $l 1 end]]
	    set ib [string first " " $l]
	    if {$ib == -1} {
		set ib end
	    } else {
		incr ib -1
	    }
	    set lenom [string range $l 0 $ib]
	} else {
	    append laseq $l
	}
    }

    return $n
}


proc CreeLeNEXUS {} {
    
}


proc DecortiqueUnNEXUS {file aNom aSeq} {
    upvar $aNom LNom $aSeq TSeq

    if {[regexp {\n} $file]} {
	set Lignes $file
    } else {
	set Lignes [LesLignesDuFichier $file]
    }

    set LNom [list]
    # 1st line NEXUS
    foreach l [lrange $Lignes 1 end] {
	set l [string trim $l]
	if {[regexp -nocase {^begin} $l]} {
luc.moulinier's avatar
luc.moulinier committed
165
	    set hat [lindex [split $l " "] 1]
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
	}
   }

    return
}


proc DecortiqueUnALN {file aNom aSeq} {
    upvar $aNom LNom $aSeq TSeq

    if {[regexp {\n} $file]} {
	set Lignes $file
    } else {
	set Lignes [LesLignesDuFichier $file]
    }

    set LNom [list]
    foreach l [lrange $Lignes 1 end] {
	if {[regexp {^ } $l] || [string trim $l] eq ""} {
	    continue
	}

	regsub -all { +} [string trim $l] " " l
	lassign [split $l " "] nomori seq tmp
	set nom [BonAccess $nomori]
	if {$nom ni $LNom} {
	    lappend LNom $nom
	    set TSeq($nom) $seq
	} else {
	    append TSeq($nom) $seq
	}
    }

    foreach n [array names TSeq] {
	set TSeq($n) [BonneSequencePourAlignement [set TSeq($n)]]
    }

    return [llength $LNom]
}
    

proc DecortiqueUnTFA {file aNom aSeq} {
    upvar $aNom Nom $aSeq Seq
    
    if {[file exists $file]} {
	set Lignes [LesLignesDuFichier $file]
    } elseif {[string first "\n" $file] != -1} {
	# texte brut
	set Lignes [split $file "\n"]
    } elseif {[llength $file] > 1} {
	set Lignes $file
    }
    lappend Lignes ">"

    set n 0
    set Nom {}
    set laseq ""
    foreach l $Lignes {
	set l [string trim $l]
	if {$l eq ""} {continue}
	if {[string index $l 0] eq ">"} {
	    if {$laseq ne ""} {
		set laseq [BonneSequencePourAlignement $laseq]
		set lenom [BonAccess $lenom]
		lappend Nom $lenom
		set Seq($lenom) $laseq
		set laseq ""
		incr n
	    }

	    set l [string trim [string range $l 1 end]]
	    set ib [string first " " $l]
	    if {$ib == -1} {
		set ib end
	    } else {
		incr ib -1
	    }
	    set lenom [string range $l 0 $ib]
	} else {
	    append laseq $l
	}
    }

    return $n
}


proc VerifieFormatAlignement {file format} {
    set rep [EstLeBonFormat $file $format]
    if {[ModeI] && ! $rep} {
	FaireLire "This seems not to be a $format file !"
    }

    if {$rep} {
	return 1
    } else {
	LesDefauts TypeAli "pasdali"
	return 0
    }
}


proc FormatDuFichierSequence {file} {
    if {[file exists $file]} {
	set l [ContenuDuFichier $file]
    } else {
	set l $file
    }
    set l [string trimleft $l "\n"]
    set Entete [string range $l 0 5]
    switch -regexp $Entete {
	{^\<\?xml }  {set fmt XML}
	{^\<!DOCTY}  {set fmt XML}
	{^PileUp}    {set fmt MSF}
	{^!!RICH}    {set fmt RSF}
	{^\>}        {set fmt TFA}
	{^SQLite}    {set fmt ORD}
	{^CLUSTA}    {set fmt ALN}
	default      {set fmt "unknown"}
    }

    if {$fmt eq "unknown"} {
	set Lt [split [string range $l 0 2000] "\n"]
	set Ix [lsearch -regexp $Lt {MSF:.+Type:.+Check:.+\.\.}]
	if {$Ix != -1} {set fmt MSF}
    }

    return $fmt
}


proc EstLeBonFormat {file format} {
    set format [string toupper $format]
    set fmt [FormatDuFichierSequence $file]
    if {$fmt eq $format} {
	return 1
    } else {
	return 0
    }
}


proc SauveLAlignement {{SauveEn ""} {Out ""}} {
    global AliFilOut OutputFormat Defauts

    # variables AliFilOut and OutputFormat are not initialized
    # at startup.

    if {[TypeAli] eq "pasdali"} {return}
    if {[QuelMode] ne "seqlab"} {
	if {[VueEditee]} {
	    if {[ModeI]} {
		set chx [tk_dialog .chx "Warning" "Warning !\nThis alignment has not been saved !" "" 0 "Overwrite it" "Create a new one" "Cancel"]
		
		if {$chx < 2} {
		    SauveLeMac $chx
		} else {
		    return
		}
	    } else {
		# si mode batch, on overwrite
		SauveLeMac 0
	    }
	}
	VueEditee 0
    }

    # Gere type format : selon save/save as
    # cas "save" -> OUt est ""
    if {$Out eq "JLeSauveAs"} {
	set OutputFormat $SauveEn
    } else {
	if {! [info exists OutputFormat]} {
	    if {$SauveEn eq ""} {
		set SauveEn [TypeAli]
	    }
	    set OutputFormat $SauveEn
	}
	
	if {[QuelMode] ne "seqlab"} {
	    # sqlite s'auto-sauve ...
	    # on remet a jour le backup
	    if {[TypeAli] eq "ORD"} {
		FaireAttendre "Please wait ...\nSaving database file ..."
		if {$Defauts(FichierOBK) eq ""} {
		    file tempfile Defauts(FichierOBK)
		}
		$::db eval {vacuum}
		$::db backup $Defauts(FichierOBK)
		FaireLaSuite
luc.moulinier's avatar
luc.moulinier committed
356

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		return
	    }
	}
    }

    # gere cas mode seqlab.
    # ne peut pas sauver en ORD/XML/RSF
    if {[QuelMode] eq "seqlab"} {
	if {$OutputFormat in {ORD XML RSF}} {
	    FaireLire "In Editor Mode, you can only save the alignment in ALN/TFA/MSF format.\nLeave the Editor to save in other formats"
	    return
	}
    }

    # Gere outname : save "" et "save as" demande
    if {! [info exists AliFilOut]} {
	set v Fichier[TypeAli]
	set AliFilOut [set Defauts($v)]
    }
    if {$Out eq "JLeSauveAs"} {
	set FicDef "[file rootname $AliFilOut].[string tolower $OutputFormat]"
	if {[ModeI]} {
	    set outfile [DemandeEtSauveFichier $SauveEn 1 $FicDef]
	    if {$outfile eq ""} {return}
	} else {
	    set outfile $FicDef
	}
	set AliFilOut $outfile
    } elseif {$Out ne "JLeSauveAs" && $Out ne ""} {
	set AliFilOut $Out
    }
luc.moulinier's avatar
luc.moulinier committed
388 389 390 391
    if { 0 && ! [file is writable $out] } {
	FaireLire "Warning !\nThe file named :\n>$AliFilOut<\ncan not be saved ! Please check location or file permissions."
	return
    }
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    
    switch $OutputFormat {
	"FenetreMSF" {CreeLAlignementDeLaFenetre $AliFileOut}
	"MSF"        {CreeLeMSF $AliFilOut}
	"XML"        {CreeLeXml $AliFilOut}
	"TFA"        {CreeLeTfa $AliFilOut}
	"ALN"        {CreeLeAln $AliFilOut}
	"ORD"        {CreeLeOrd $AliFilOut}
    }

    return
}


proc SequencesASauver {} {
    global NomSeqSel LNOrdali LSOrdali LNSeqlab

    set LesNoms [list]
    set LesSeqs [list]

    if {[info exists NomSeqSel] && $NomSeqSel != {} } {
	set choix [tk_dialog .chx "Beware !!" "There are selected sequences ...\nDo you want to " "" 1 " Save selected" "Save all" "Cancel"]
    } else {
	set choix 1
    }

    switch $choix {
	0 {
	    set LesNoms [LesNomsDesSeqsSel]
	    set LesSeqs [LesSeqsDesSeqsSel]
	}
	1 {
	    if {[QuelMode] eq "seqlab"} {
		set LNoms $LNSeqlab
		set LSeqs [$::NomTextSeq output all]
	    } else {
		set LNoms $LNOrdali
		set LSeqs $LSOrdali
	    }
	    foreach n $LNoms s $LSeqs {
		if {[string trim $n] eq ""} {
		    continue
		}
		lappend LesNoms $n
		lappend LesSeqs $s
	    }
	}
	2 {
	    return
	}
    }

    return [list $LesNoms $LesSeqs]
}


proc CreeLeMSF {{outfile ""} {LNoms {}} {LSeqs {}}} {
    if {$outfile eq ""} {
	set outfile [DemandeEtSauveFichier "msf" 1]
    }
    if {$outfile eq ""} {return}

    if {$LNoms == {} } {
	lassign [SequencesASauver] LNoms LSeqs
    }
    if {$LNoms == {}} {return}

    foreach s $LSeqs {
	set w [SeqGCGCheckSum $s]
	incr SumCheck $w

	lappend Lw $w
	lappend Lt [DefinitTypeSeq $s]
    }
    set SumCheck [expr {$SumCheck % 10000}]
    set len [string length [lindex $LSeqs 0]]
    set Nmax [PlusLongEltDe $LNoms]
    if {$Nmax < 12} {set Nmax 11}
    set uLt [lunique $Lt]
    if {[llength $uLt] > 1} {
	set nmax -1 ; set tmax ""
	foreach e $uLt {
	    set n [llength [lsearch $Lt $e]]
	    if {$n > $nmax} {
		set nmax $n
		set tmax $e
	    }
	}
	set uLt $tmax
    }
    if {$uLt eq "Protein"} {set type "P"} {set type "N"}

    set Llg [list]
    lappend Llg "PileUp\n\n\n\n"
    set ligne ""
    append ligne [format "   MSF:%5d  Type: %1s" $len $type]
    append ligne [format "    Check:%6ld   .. \n\n" $SumCheck]
    lappend Llg "$ligne"
    foreach n $LNoms w $Lw {
	lappend Llg [format " Name: %s oo  Len:%5d  Check:%6ld  Weight:  %.1f" $n $len $w 10.0]
    }
    lappend Llg "\n//"

    set chunks [expr {$len/100}]
    if {$len % 100 != 0} {incr chunks}
    
    for {set block 0} {$block < $chunks} {incr block} {
	lappend Llg "\n\n"
	set pos1 [expr {$block * 100}]
	set pos2 [expr {$len<$pos1+99 ? $len : $pos1+99}]
	foreach nom $LNoms seq $LSeqs {
	    set ligne [format "%${Nmax}s" $nom]
	    set bout [string range $seq $pos1 $pos2]
	    set nbout [expr {($pos2-$pos1+1)/10}]
	    for {set i 0} {$i < $nbout} {incr i} {
		append ligne " [string range $bout [expr {$i*10}] [expr {($i+1)*10-1}]]"
	    }
	    lappend Llg "$ligne"
	}
    }
    lappend Llg "\n\n"

    if {$outfile ne "OnRetourne"} {
luc.moulinier's avatar
luc.moulinier committed
515 516
	set f [CheckOpen $outfile]
	if {$f eq ""} {
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
	    return
	}
	puts $f [join $Llg \n]
	close $f
    }

    return $Llg
}


proc CreeLAlignementDeLaFenetre {format {outfile ""}} {
    global tcl_platform OrdTmpDir NomNomSeq NomTextSeq

    if {! [ModeI]} {return}
    if {[TypeAli] eq "pasdali"} {return}

    if {$outfile eq ""} {set outfile [DemandeEtSauveFichier $format 1]}
    if {$outfile eq ""} {return}

    set d [$NomTextSeq index @0,0]
    lassign [split $d "."] ym xm 
    set f [$NomTextSeq index @[winfo width $NomTextSeq],[winfo height $NomTextSeq]]
    lassign [split $f "."] yx xx 
    while {$xx == 0} {
	set f [$NomTextSeq index "$yx.$xx - 1c"]
	lassign [split $f "."] yx xx 
    }
    # lassign [VisiblePartOfAlignment] xm ym xx yx

    for {set j $ym} {$j <= $yx} {incr j} {
	set n [$NomNomSeq get $j.0 "$j.0 lineend"]
	if {[string trim $n] eq ""} {
	    lappend seqs ""
	    lappend noms ""
	    continue
	}
	set s [$NomTextSeq get $j.$xm $j.$xx]
	if {[string index $s end] == "\n"} {set s [string range $s 0 end-1]}
	lappend seqs $s
	lappend noms $n
    }

    set ftmp [file join $OrdTmpDir "[pid]_tfatmptfatmp.tfa"]
luc.moulinier's avatar
luc.moulinier committed
560
    set f [CheckOpen $ftmp]
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    set LongueurTotale [expr {$xx-$xm}]
    foreach Nm $noms Sq $seqs {
	puts $f ">$Nm"
	set Sq [string map [list "Z" "-" "." "-" " " "-"] $Sq]
	set D 0
	while {$D < $LongueurTotale} {
	    set F [expr {$D + 59}]
	    set L [string range $Sq $D $F]
	    puts $f "$L"
	    incr D 60
	}
    }
    close $f

    if {$format == "TFA"} {
	file rename -force $ftmp $outfile
	return
    }

    set Commande "[ClustalwExe] -convert -output=gscope -outfile=$outfile -infile=$ftmp"
    if {$tcl_platform(platform) == "windows"} {
	regsub -all -- "-" $Commande "/" Commande
    }
    eval exec $Commande

    file delete -force $ftmp

    return
}


proc LongueurDeLAlignement {{quoi ""}} {
    global Sequences LongueurTotale

    if {$quoi eq "seqlab"} {
	set lg [string length [$::NomTextSeq output 0]]
    } else {
	set Ll [list]
	foreach n [array names Sequences] {
	    lappend Ll [string length [set Sequences($n)]]
	}
	set lg [lindex [lsort -unique -integer $Ll] end]
    }

    set LongueurTotale $lg
    
    return $lg
}



proc DonneMemeLongueur {aTseq} {
    upvar $aTseq Tseq

    set lmx -1
    foreach n [array names Tseq] {
	set s [set Tseq($n)]
	set l [string length [string trim $s]]
	if {$l > $lmx} {set lmx $l}
	lappend Ln $n
	lappend Ls $s
    }

    foreach s $Ls n $Ln {
	set l [string length [string trim $s]]
	if {$l != 0 && $l != $lmx} {
	    set d [expr {$lmx-$l}]
	    set add [string repeat "." $d]
	    append s $add
	}
	set Tseq($n) $s
    }

    return $lmx
}


proc ZonesDeSequence {s} {
    global ZoneClusterisation

    if {! [info exists ZoneClusterisation]} {return $s}

    set r ""
    foreach z $ZoneClusterisation {
	lassign $z x1 x2
	append r [string range $s $x1 $x2]
    }
    if {$r eq ""} {set r $s}

    return $r
}


proc CreeLeAln {{FilOut ""}} {
    lassign [SequencesASauver] LNoms LSeqs
    if {$LNoms == {}} {return}

    if {$FilOut eq ""} {
	set FilOut [DemandeEtSauveFichier "tfa" 1]
    }
    if {$FilOut eq ""} {return}

luc.moulinier's avatar
luc.moulinier committed
663 664 665
    set f [CheckOpen $FilOut]
    if {$f eq ""} {
	return
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    }
    puts $f "CLUSTAL W : Created by Ordalie [DonneDateEtHeure]"
    puts $f ""
    set maxn [PlusLongEltDe $LNoms]
    set maxs [PlusLongEltDe $LSeqs]
    set fmt "%${maxn}s %s"

    set D 0
    while {$D < $maxs} {
	set F [expr {$D + 59}]
	foreach Nm $LNoms s $LSeqs {
	    if {[string trim $Nm] eq ""} {continue}

	    set Linit [string range $s $D $F]
	    set Linit [string map [list Z - . -] $Linit]
	    puts $f [format $fmt $Nm $Linit]
	}
	puts $f ""
	puts $f ""
	incr D 60
    }

    close $f

    return
}


proc CreeLeTfa {{FilOut ""} {nmgrp ""}} {
    lassign [SequencesASauver] LNoms LSeqs
    if {$LNoms == {}} {return}

    EcritLeTfa $FilOut $LNoms $LSeqs

    return
}


proc EcritLeTfa {FilOut LesNoms LesSequences} {
    if {$FilOut eq ""} {
	set FilOut [DemandeEtSauveFichier "tfa" 1]
    }
    if {$FilOut eq ""} {return}

luc.moulinier's avatar
luc.moulinier committed
710 711
    set f [CheckOpen $FilOut]
    if {$f eq ""} {
712 713
	return
    }
luc.moulinier's avatar
luc.moulinier committed
714
    
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    foreach Nm $LesNoms s $LesSequences {
	if {[string trim $Nm] eq ""} {continue}
	puts $f ">$Nm"
	set D 0
	while {$D < [string length $s]} {
	    set F [expr {$D + 59}]
	    set Linit [string range $s $D $F]
	    set L [string map {Z - . -} $Linit]
	    puts $f "$L"
	    incr D 60
	}
    }

    close $f

    return
}


proc AlignementDesSelections {{Zone {}} aSAli} {
    upvar $aSAli SAli
    global NomSeqSel Sequences LNOrdali

    set LesNoms {}
    set LesSequences {}
    set LesNomsDesSeqs $LNOrdali

    if {[info exists NomSeqSel] && [llength $NomSeqSel] > 3} {
	set Li {}
	foreach p $NomSeqSel {
	    lassign [split $p .] y x
	    incr y -1
	    lappend Li $y
	}
    } else {
	for {set i 0} {$i < [llength $LesNomsDesSeqs]} {incr i} {
	    lappend Li $i
	}
    }

    if {! [llength $Zone]} {
	set Zone [list [list 0 [expr {[LongueurDeLAlignement]-1}]]]
    }

    set LVide {}
    foreach i $Li {
	set Nm [lindex $LesNomsDesSeqs $i]
	if {$Nm eq ""} {continue}
	set sbrut [set Sequences($Nm)]

	set s ""
	foreach z $Zone {
	    lassign $z x1 x2
	    append s [string range $sbrut $x1 $x2]
	}
	set tmp [string map [list "." "" Z "" " " "" X ""] $s]
	if {[string trim $tmp] eq ""} {
	    lappend LVide $i
	    continue
	}
	lappend LesNoms $Nm
	lappend LesSequences $s
    }

    set SAli {}
    foreach n $LesNoms s $LesSequences {
	lappend SAli $n $s
    }

    return $LVide
}


proc FaitLignesA60 s {

    set rep ""
    set D 0
    while {$D < [string length $s]} {
	set F [expr {$D + 59}]
	set Linit [string range $s $D $F]
	set L [string map [list Z - . -] $Linit]
	append rep "$L\n"
	incr D 60
    }

    return $rep
}


proc LitLesPoidsDuMSF {FichierMSF {ng ""}} {
    global SDG LNOrdali LesPoidsDesSequences

    if {$ng == ""} {
	set LesNomsDesSeqs $LNOrdali
    } else {
	set LesNomsDesSeqs [set SDG($ng)]
    }

    set LesLignes [LesLignesDuFichier $FichierMSF]

    if {[llength $LesLignes] < 2} { return 0 }

    set iSlashSlash [expr {[lsearch -regexp $LesLignes "//"]+1}]
    set iLeWeight [lsearch -regexp $LesLignes "Weight"]

    # lecture du champ Weight: du MSF

    set i 0
    foreach Ligne [lrange $LesLignes $iLeWeight $iSlashSlash] {
	if {![regexp "Weight" $Ligne]} {continue}
	set iw [expr {[string last "Weight" $Ligne]+7}]
	set pd [string trim [string range $Ligne $iw end]]
	set nom [lindex $LesNomsDesSeqs $i]
	set LesPoidsDesSequences($nom) $pd
	incr i
    }

    return
}



proc AssigneLesPoids {{nmgrp ""}} {
    global LesPoidsDesSequences Defauts Sequences LNOrdali OrdTmpDir

    if {! [set Defauts(Poids)] && ![set Defauts(Poids2)] && ![set Defauts(Poids3)]} {
	foreach s $LNOrdali {
	    set LesPoidsDesSequences($s) 1.
	}
	return
    }

    set in [file join $OrdTmpDir "in"]
    set out [file join $OrdTmpDir "out"]

    CreeLeTfa $in $nmgrp

    eval exec "calcule_weight $in $out"

    LitLesPoidsDuMSF $out $nmgrp

    file delete -force $in
    file delete -force $out

    return
}


proc CalculeConservationParSS {LePDB} {
    global ListePCISS Sequences ZoneSelect

    set ZoneSelect [list]
    if {$LePDB eq ""} {
	set LePDB ""
	SelectSSDeType sheet
	SelectSSDeType helix
    } else {
	set chn   [DonneChainDeAccessPDB $LePDB]
	set MolId [DonneIdDeAccessPDB $LePDB]
	if {$chn eq ""} {set chn "a"}
	set Limites [$MolId SecStr -chain $chn]
	foreach Lelt $Limites {
	    # Elt Type No Chn dep res fin res lgt
	    set d [lindex $Lelt 4]
	    set f [lindex $Lelt 6]
	    lappend ZoneSelect [list $d $f]
	}
    }

    foreach e $ZoneSelect {
	lassign $e d f
	set ListePCISS($d,$f) [CalculeLesPCI $d $f "" "" 1]
    }

    return
}


proc NRIdentite {a lga b lgb} {

    foreach ca $a cb $b {
	incr p [expr {$ca ne "." && $ca eq $cb}]
    }

    return [expr {($lga<$lgb)?(1.0*$p/$lga):(1.0*$p/$lgb)}]
}


proc DetermineLesFragmentsLuc {} {
    global TDesPCI LNOrdali Sequences ListeDesFragments TDesFragments

    set ListeDesFragments {}

    FaireAttendre "Please wait ...\nDetermiining sequences corresponding to fragments"

    foreach n [array names Sequences] {
	lappend Ll $n [string length [string trim [set Sequences($n)] "."]]
    }

    set i 2
    foreach {p a} [lrange $Ll 0 end-2] {	
	foreach {q b} [lrange $Ll $i end] {
	    if {$a > $b} {
		set v [expr {double($a)/$b}]
		set ref1 $p
		set ref2 $q
	    } else {
		set v [expr {double($b)/$a}]
		set ref1 $q
		set ref2 $p
	    }
	    if {$v < 0.8} {CalculeLesPCI "" "" $ref1 $ref2}
	}
	incr i 2
    }

    foreach c [array names TDesPCI] {
	lassign [split $c ,] n1 n2
	lassign [set TDesPCI($c)] pc l1 l2 lg
	set bpc [expr {$pc > 0.6}]
	set blg [expr {$lg < 0.8}]
	set bn1 [expr {$n1 ni $ListePDB}]
	set bn2 [expr {$n2 ni $ListePDB}]
	if { $blg && $bpc && $bn1 && $bn2} {
	    lappend Frag $n1
	}
    }

    if {[info exists Frag]} {
	set ListeDesFragments [lsort -unique $Frag]
	foreach n $ListeDesFragments {
	    set TDesFragments($n) 1
	}
    }

    FaireLaSuite .frag

    return $ListeDesFragments
}


proc TraitePDBDeLAlignement {} {
    global ListePDB BadPDB HashPDB Sequences LNOrdali PBV PBW PipeCollection Warn LSOrdali SDG Defauts

    set ListePDB {}
    set BadPDB {}
    set HashPDB(iHmax) 0
    set ix -1
    set PBW "Treating PDB sequences ...."
    set PBV 0.
    set Nseq [llength $LNOrdali]
    set LNtmp $LNOrdali
    set ToChange [list]

    foreach seq $LNtmp {
	set PBV [expr {$PBV + 100. / $Nseq}]
	incr ix
	if {! [EstUnAccessPDB $seq]} {
	    continue
	}

	set pdbid [DonneIdDeAccessPDB $seq]
	set chn   [DonneChainDeAccessPDB $seq]
luc.moulinier's avatar
luc.moulinier committed
978 979 980 981 982 983 984
	
	if {[set Defauts(DownloadPDB)] eq "dont"} {
	    # PDB should not be seeen as PDBs
	    lappend ToChange [list $ix $pdbid $chn 1]
	    continue
	}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	set ChgN 0 ; set ChgC 0
	
	# try DownloadPDB dont
	if {$pdbid ni [info commands] && $Defauts(DownloadPDB) ne "dont"} {
	    set cok [LoadNouveauPDB $pdbid]
	    
	    if {$cok == 0} {
		lappend BadPDB $ix
		
		continue
	    }

	    # obsolete or superseeded
	    if {$cok != 1} {
		set pdbid $cok
		set ChgN 1
	    }
	    if {$chn ni [set Lc [$pdbid _chains]]} {
		set chn [lindex $Lc 0]
		set ChgC 1
	    }
	    
	    if {$ChgN || $ChgC} {
luc.moulinier's avatar
luc.moulinier committed
1008
		lappend ToChange [list $ix $pdbid $chn 0]
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	    }
	} else {
	    # PDB existe deja.
	    # On ne traite pas le PDB mais on 
	    # enregistre la nouvelle chaine 
	}
	# Carefull !!
	# ListePDB contains the RIGHT name
	set newname [BonNomPDB ${pdbid}_$chn]
	lappend ListePDB $newname

	# update names in group array
	if {[info exists SDG]} {
	    foreach grp [array names SDG] {
		if {[set isdg [lsearch [set SDG($grp)] $seq]] != -1} {
		    set SDG($grp) [lreplace [set SDG($grp)] $isdg $isdg $newname]
		}
	    }
	}
    }
    
    # Superseeded/obsolete/chain changed
    if {$ToChange != {} } {
	foreach k [lsort -integer -decreasing -index 0 $ToChange] {
luc.moulinier's avatar
luc.moulinier committed
1033
	    lassign $k i n c justRename
1034 1035 1036 1037

	    set old   [lindex $LNtmp $i]
	    set oldid [DonneIdDeAccessPDB $old]
	    set chn   [DonneChainDeAccessPDB $old]
luc.moulinier's avatar
luc.moulinier committed
1038 1039 1040 1041 1042 1043 1044 1045

	    if {$justRename} {
		set newn "seq_${n}_$c]"
	    } else {
		set newn [BonNomPDB ${n}_$c]
		puts "old $old newn $newn"
	    }

1046 1047 1048 1049 1050
	    set LNtmp [lreplace $LNtmp $i $i $newn]
	    set seq [lindex $LSOrdali $i]
	    unset Sequences($old)
	    set Sequences($newn) $seq
	    
luc.moulinier's avatar
luc.moulinier committed
1051 1052 1053 1054
	    if {! $justRename} {
		# logs ...
		set log "Warning : entry $old changed to $newn"
		AuLog @begin warning
1055
	    AuLog @text $log
luc.moulinier's avatar
luc.moulinier committed
1056 1057 1058 1059 1060 1061 1062 1063
		AuLog @end
		
		puts ""
		puts [string repeat "=" [string length $log]]
		puts $log
		puts [string repeat "=" [string length $log]]
		puts ""
	    }
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
	}
    }
    set LNOrdali $LNtmp

    return
}


proc BonneSequencePourAlignement {s {outtype ""}} {
    if {$outtype eq ""} {set outtype "ordali"}
    if {$outtype eq "same"} {return $s}

    switch $outtype {
	"ordali" -
	"msf" {
	    set rs "."
	    set s [string toupper $s]
	}
	"tfa" {
	    set rs "-"
	    set s [string toupper $s]
	}
	"xml" -
	"macsim" {
	    set rs "-"
	    set s [string tolower $s]
	}
    }

    set s [string map [list "-" $rs "." $rs " " $rs "\n" "" "~" $rs] $s]

    return $s
}

luc.moulinier's avatar
luc.moulinier committed
1098 1099
proc BonAccess {s {AsIs ""}} {
    set s [string trim $s]
1100
    set s [lindex [split $s " "] 0]
luc.moulinier's avatar
luc.moulinier committed
1101
    if {[string equal -nocase $AsIs "AsIs"]} { return $s }
1102
    if {! [info exists ::Defauts] || ! [set ::Defauts(RemoveBankPrefix)]} {
luc.moulinier's avatar
luc.moulinier committed
1103
	return $s
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
    }

    set a [EnlevePrefixeBank $s]
    if {[EstUnAccessPDB $a]} {
	set a [BonNomPDB $a]
    } else {
	if {[regexp {\|} $a]} {
	    set a [string range $a 0 [string first "|" $a]-1]
	}
	if {[regexp {\.|\_|\,|\;|\:|\|} [string index $a end]]} {
	    set a [string range $a 0 end-1]
	}
	# voir InitPosSeqGenGenSeq
	# enleve character separateur : @
	set a [string map [list "@" "_"] $a]
    }
    set a [EnleveVersionDeAccess $a]

    return [string trim $a]
}


proc CreeLookupNoms {} {
    global LookupNoms
    global ListeNomAssocieALAccess

    foreach d $ListeNomAssocieALAccess {
	lassign $d n1 n2
	set LookupNoms($n1) $n2
	set LookupNoms($n2) $n1
    }

    return
}



proc RameneInfoSeq {} {

    global LNOrdali
    global NomOrgaCanon
    global ListeNomAssocieALAccess
    global LaClasseAssocieeAuxSequences
    global LesSequencesAssocieesClassesCanon
    global ListeDesNomsDeGene
    global ListeDesDefinitions

    if {[TypeAli] eq "pasdali"} {return}

    set ListeNomAssocieALAccess {}
    set ListeDesDefinitions {}
    set ListeDesNomsDeGenes {}
    set lorp {}

    FaireAttendre "Please wait ....\nRetrieving canonical names from access numbers ...."

    AuLog "\nCanonical names from access numbers\n===================================\n"
    set k 1
    foreach NmSq $LNOrdali {
	#	    DecortiqueLesLignesEMBL [LaSequenceDesBanques $NmSq $NmSq AccessOK "OnVeutEMBL"] ID AC DE GN OS OC OG

	set ID ""
	set GN ""
	set OS ""
	set OC ""
	set OG ""
	set DE ""
	set leslignes [RecupereUnFichierSurWeb [string toupper $NmSq]]
	if {$leslignes != "ERREUR"} {
	    DecortiqueLesLignesEMBL $leslignes ID AC DE GN OS OC OG
	}
	if {$GN == ""} {set GN "XXXXX"}

	set NomOrgaCanon "Unkn.unknw"
	if {$OS != ""} {
	    set Organisme [OrganismeCanonique $OS Sommaire]
	    if {$Organisme != ""} {
		set NomOrgaCanon [Glossaire "$Organisme" "Demi"]
	    }
	}

	set idx [lsearch -regexp $lorp $NomOrgaCanon]
	if {$idx != -1} {
	    scan [lindex $lorp $idx] "%s %s" n k
	    incr k
	    set NomOrgaCanon "$NomOrgaCanon$k"
	    set nv "$n $k"
	    set lorp [lreplace $lorp $idx $idx $nv]
	} else {
	    lappend lorp "$NomOrgaCanon 1"
	}

	lappend ListeNomAssocieALAccess [list $NmSq $NomOrgaCanon]

	set Phylum "PhylumUnknown"
	if {$OC != ""} {
	    set Classe $OC
	    set Phylum [Phylum $Classe]
	    set LaClasseAssocieeAuxSequences($NmSq) $Classe
	    switch $Phylum {
		"ARCHAEA" {
		    lappend LesSequencesAssocieesClassesCanon(archaea) $NmSq
		}
		"EUKARYOTA" {
		    lappend LesSequencesAssocieesClassesCanon(eukaryota) $NmSq
		}
		"BACTERIA" {
		    lappend LesSequencesAssocieesClassesCanon(bacteria) $NmSq
		}
	    }
	}
	AuLog "$NmSq $NomOrgaCanon $Phylum $DE"

	regsub -all {\-} $DE " " DE
	regsub -all {  +} $DE " " DE
	lappend ListeDesDefinitions $DE
	lappend ListeDesNomsDeGenes $GN
    }

    CreeLookupNoms

    FaireLaSuite .attendre

    return
}



proc InitPosSeqGenGenSeq {} {
    return

    global Sequences ListePDB db TPGS TPSG

    if {[info exists TPGS]} {
	unset TPGS TPSG
    }

    lassign [Ccode_InitPosSGGS [array get Sequences]] TPosGS TPosSG
    foreach {n k v} $TPosGS {
	set TPGS($n@$k) $v
    }
    foreach {n k v} $TPosSG {
	set TPSG($n@$k) $v
    }
	
    foreach nt $ListePDB {
	lassign $nt n tmp
	if {! [info exists Sequences($n)]} {continue}
	set n [BonNomPDB $n]
	array unset TPSG "${n}@*"
	array unset TPGS "${n}@*"
	set mol [DonneIdDeAccessPDB $n]
	set chn [DonneChainDeAccessPDB $n]
	set sp [$mol _resnumber -chain $chn -polymer]
	set lgg [llength $sp]
	set sg [set Sequences($n)]

	set i -1 ; set c -1 ; set v [lindex $sp 0]
	foreach a [split $sg ""] {
	    incr i
	    if {$a ne "."} {
		incr c
		# c could not be greater than $lgg
		# it may happen if the sp != sg degape
		if {$c < $lgg} {
		    set v [lindex $sp $c]
		} else {
		    set v [lindex $sp end]
		}
		set TPSG($n@$v) $i
	    }
	    set TPGS($n@$i) $v
	}
	set TPSG($n@-1) $lgg
	set TPGS($n@-1) $lgg
    }

    return
}


proc DonnePosGS {n x {debug 0}} {
    # Attention ! 
    # renvoie coord avec START=1 !
    #                   ----------

    set o [string length [string map {"." ""} [string range $::Sequences($n) 0 $x]]]
    if {$n in $::ListePDB} {
	set mol [DonneIdDeAccessPDB $n]
	set chn [DonneChainDeAccessPDB $n]
	set lr [$mol _resnumber -chain $chn -polymer]
	if {$o >= [llength $lr]} {
	    set o [lindex $lr end]
	} elseif {$o != 0} {
	    set o [lindex $lr $o-1]
	}
    }
 
   return $o
}


proc DonnePosGS_SL {n w y x {debug 0}} {
    # ==> Pour Mode Seqlab
    #
    # Attention ! 
    # renvoie coord avec START=1 !
    #                   ----------

    set o [string length [string map {"." ""} [string range [$w output [expr {$y-1}]] 0 $x]]]
    if {$n in $::ListePDB} {
	set mol [DonneIdDeAccessPDB $n]
	set chn [DonneChainDeAccessPDB $n]
	set lr [$mol _resnumber -chain $chn -polymer]
	if {$o >= [llength $lr]} {
	    set o [lindex $lr end]
	} elseif {$o != 0} {
	    set o [lindex $lr $o-1]
	}
    }

    return $o
}


proc DonnePosSG {n x} {
    # Attention !
    # renvoie avec start = 0 !
    #             -----------

    if {$n in $::ListePDB} {
	set mol [DonneIdDeAccessPDB $n]
	set chn [DonneChainDeAccessPDB $n]
	set x [lsearch [$mol _resnumber -chain $chn -polymer] $x]
    }

luc.moulinier's avatar
luc.moulinier committed
1340
    #return [lindex [lindex [regexp -all -inline -indices {[A-Z]} $::Sequences($n)] $x] 0]
1341

luc.moulinier's avatar
luc.moulinier committed
1342 1343 1344 1345 1346
    return [Ccode_DonnePosSG $::Sequences($n) $x]
    
    #puts "out3 [time {set out3 [TclPosSeq2Gen $::Sequences($n) $x]}]"

    puts "$x | $out1 $out2 $out3\n"
1347

luc.moulinier's avatar
luc.moulinier committed
1348
    return $out1
1349 1350 1351 1352 1353 1354 1355 1356 1357

    if {[set v [$::db eval {select gen from corrseqgen where nom=$n and seq=$x}]] ne ""} {
	return $v
    } else {
	puts "Pb SG -> $n $x"
	return -999
    }
}

luc.moulinier's avatar
luc.moulinier committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
proc TclPosSeq2Gen {s x} {
    set pos 0 ; set gen 0
    while {$pos < $x} {
	if {[string index $s $gen] ne "."} {
	    incr pos
	}
	incr gen
    }

    return $gen
}


1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514

proc InitPosSeqGenGenSeq_OLD {} {
    global Sequences TPosGS TPosSG ListePDB

    if {[info exists TPosSG]} {
	unset TPosSG TPosGS
    }

    lassign [Ccode_InitPosSGGS [array get Sequences]] TPosGS TPosSG

    foreach nt $ListePDB {
	if {! [info exists Sequences($nt)]} {continue}

	lassign $nt n tmp
	set n [BonNomPDB $n]
	set TPosSG [dict remove $TPosSG $n]
	set TPosGS [dict remove $TPosGS $n]

	set mol [DonneIdDeAccessPDB $n]
	set chn [DonneChainDeAccessPDB $n]
	set sp [$mol _resnumber -chain $chn -polymer]
	set sg [set Sequences($n)]
	set lgg [llength $sp]

	dict set TPosSG $n lgt $lgg
	dict set TPosGS $n lgt $lgg

	set i -1
	set c -1
	set v 0
	foreach a [split $sg ""] {
	    incr i
	    if {$a ne "."} {
		incr c
		dict set TPosSG $n [set v [lindex $sp $c]] $i
	    }
	    dict set TPosGS $n $i $v
	}
    }

    return
    
    foreach {n seq} [array get Sequences] {
	#set seq [set Sequences($n)]
	set tmp [string map [list Z "" . ""] $seq]
	set lg [string length $tmp]
	dict set TPosSG $n lgt $lg
	dict set TPosGS $n lgt $lg

	set c -1
	set i -1
	foreach a [split $seq ""] {
	    incr i
	    if {$a ne "."} {
		incr c
		dict set TPosSG $n $c $i
	    }
	    dict set TPosGS $n $i $c
	}
    }

    return $i
}


proc DefinitTypeSeq {seq} {
    set seq [string map {"." "" "\n" "" "Z" "" " " "" "X" ""} $seq]
    set Ld [string length $seq]
    set No [regsub -all "O"  $seq "" seq]
    set Lo [string length $seq]
    
    if {$Ld == 0} {
	return "Water"
    }
    
    set seq [string map {"A" "" "C" "" "G" "" "T" "" "U" "" "N" ""} $seq]
    set Ll [string length $seq]
    set water [expr {double($Lo)/$Ld}]
    set ratio [expr {double($Ll)/$Ld}]

    if {$water < 0.15} {
	return "ligand"
    }

    if {$ratio < 0.15} {
	return "DNA"
    } else {
	return "Protein"
    }
}


proc DefinitTypeAlignement {} {
    global Sequences LNOrdali TypeSeq ListeDesSimilarites ListeDesAcidesAmines

    if {[info exists TypeSeq]} {return}

    set seq ""
    foreach s $LNOrdali {
	if {[string trim [set Sequences($s)]] ne ""} {
	    append seq [set Sequences($s)]
	}
    }

    set rep [DefinitTypeSeq $seq]
    if {$rep eq "DNA"} {
	set TypeSeq "DNA"
	set ListeDesAcidesAmines {A C G T U N Z}
	set ListeDesSimilarites {1 2 3 4 5 6 Z}
    } elseif {$rep eq "Protein"} {
	set TypeSeq "Protein"
	# liste acides amines de Clustal
	set ListeDesAcidesAmines {A B C D E F G H I K L M N P Q R S T V W X Y Z}
	#set ListeDesAcidesAmines {A C D E F G H I K L M N P Q R S T V W Y Z}
	set ListeDesSimilarites {1 2 3 4 5 6 Z}
    } else {set TypeSeq "Unknown"}

    # Protein
    # 1 =  A,I,L,M,V
    # 2 =  P,A,G,S,T
    # 3 =  D,E,Q,N
    # 4 =  F,Y,W
    # 5 =  K,R,H
    # 6 =  C
    #   Z si sequence manquante

    return
}



proc TypeSeq {} {
    return $::TypeSeq
}


proc InitSequences {} {
    global Defauts LNOrdali LSOrdali Sequences
    global SeqOri LesNomsDesSeqOri
    global NombreDeSequences LongueurTotale
    global OrdEtcDir Warn PBV PBW
    global LesPCI ListeDesFragments
    global ListePDB BadPDB NomEtSeqAssPDB

luc.moulinier's avatar
luc.moulinier committed
1515 1516 1517 1518 1519 1520 1521
    if {[set Defauts(RemoveQuery)]} {
	set iquery [lsearch -regexp -nocase $LNOrdali "query"]
	if {$iquery != -1} {
	    set Qry [lindex $LNOrdali $iquery]
	    unset Sequences($Qry)
	    set LNOrdali [lreplace $LNOrdali $iquery $iquery]
	}
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
    }

    # sequences doublonnees ...
    set Luni [lsort -unique $LNOrdali]
    if {[llength $LNOrdali] != [llength $Luni]} {
	set Msg "Warning !\nMultiple copies of some same sequences :\n"
	set Lden [DenombreLaListe $LNOrdali]
	foreach en $Lden {
	    lassign $en e n
	    if {$n > 1} {
		append Msg "   -->$e\n"
	    } else {
		break
	    }
	}
	append Msg "Please remove duplicated sequences and start again !"
	FaireLire $Msg

	return 0
    }
    
    # Nettoyage Nom et sequences
    set ListePDB {}
    set PBV 0.
    set PBW "Cleaning Sequences and Names ..."
    set Ns [llength $LNOrdali]
    set LiVide [list]
    set i 0
    foreach n $LNOrdali {
	set s [set Sequences($n)]
	set s [BonneSequencePourAlignement $s]
	set Sequences($n) $s

	set nogap [string map {"." "" " " "" "~" "" "-" ""} $s]
	if {! [string length $nogap]} {
	    lappend Warn(Vide) $n
	    set Warn($n) 1
	    lappend LiVide $i
	}
	incr i
	set PBV [expr {$PBV+100./$Ns}]
    }
    # Enleve sequences vides
    foreach i [lsort -integer -decreasing $LiVide] {
luc.moulinier's avatar
luc.moulinier committed
1566
	set n [lindex $LNOrdali $i]
1567
	set LNOrdali [lreplace $LNOrdali $i $i]
luc.moulinier's avatar
luc.moulinier committed
1568
	unset Sequences($n)
1569
    }
luc.moulinier's avatar
luc.moulinier committed
1570
    update
1571

luc.moulinier's avatar
luc.moulinier committed
1572 1573 1574 1575 1576 1577 1578 1579 1580
    set NombreDeSequences [llength $LNOrdali]
    if {! $NombreDeSequences} {
	return 0
    }
        
    DefinitTypeAlignement
    LesDefauts Mapping [EditorMappingData]

    DonneMemeLongueur Sequences
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    foreach n $LNOrdali {
	lappend LSOrdali [set Sequences($n)]
    }
    lappend LNOrdali {}
    lappend LSOrdali {}

    #
    # Traitement PDB
    #
    TraitePDBDeLAlignement

    # Enleve mauvais PDB
    if {$BadPDB != {}} {
	foreach i [lsort -decreasing -integer $BadPDB] {
	    set e [lindex $LNOrdali $i]
	    set Molid [DonneIdDeAccessPDB $e]
	    set Chn   [DonneChainDeAccessPDB $e]
	    set newe "bsq${Molid}_$Chn"
	    lset LNOrdali $i $newe
	    set seq [lindex $LSOrdali $i]
	    unset Sequences($e)
	    set Sequences($newe) $seq
	}
    }

    # traite AA bizarres (Seleno Cysteine, B et Z)
    TraiteAABizarres

    # Info generales sur alignement
    set NombreDeSequences [llength $LNOrdali]
    set Premiere [lindex $LNOrdali 0]
    set LongueurTotale [string length [set Sequences($Premiere)]]
    set NPDB [llength $ListePDB]

    array set SeqOri [array get Sequences]
    set LesNomsDesSeqOri $LNOrdali

    # Determine fragments
    if {! $::Defauts(IsGenome)} {
	set ListeDesFragments [DetermineLesFragmentsLuc]
	if {$ListeDesFragments != ""} {
	    MetDesZDansSequencesDeFragments
	}
	
    }

    # sec. str., setups ... des PDB
    InfosDesPDB

    # not implemented yet ...
    AssigneLesPoids

    if {! $Defauts(IsGenome)} {
	CalculeLength
	CalculeComposition
	CalculePI
	CalculeMolecularWeight
    }
    
    WarningsDesSeqs

    return 1
}


proc WarningsDesSeqs {} {
    global Warn

    if {! [info exists Warn]} {return}
    foreach e [array names Warn] {
	switch $e {
	    "B" {
		FaireLire "There are B amino acids (stands for D or N) in the sequence of :\n[join [set Warn(B)] ","]\nSome computations won't be available !"
		AuLog @begin warning
		AuLog @title Warning : B amino acids
		AuLog @text "There are B amino acids (stands for D or N) in the sequence of :\n[join [set Warn(B)] ","]\nSome computations won't be available !"
		AuLog @end
	    }
	    "Z" {
		FaireLire "There are Z amino acids (stands for E or Q) in the sequence of :\n[join [set Warn(Z)] ","]\nSome computations won't be available !"
		AuLog @begin warning
		AuLog @title Warning : Z amino acids
		AuLog @text "There are Z amino acids (stands for E or Q) in the sequence of :\n[join [set Warn(Z)] ","]\nSome computations won't be available !"
		AuLog @end
	    }
	    "J" {
		FaireLire "There are J amino acids (stands for L or I) in the sequence of :\n[join [set Warn(J)] ","]\nSome computations won't be available !"
		AuLog @begin warning
		AuLog @title Warning : J amino acids
		AuLog @text "There are J amino acids (stands for L or I) in the sequence of :\n[join [set Warn(J)] ","]\nSome computations won't be available !"
		AuLog @end
	    }
	    "O" {
		FaireLire "There are unknown amino acids (O) in the sequence of :\n[join [set Warn(O)] ","]\nSome computations won't be available !"
		AuLog @begin warning
		AuLog @title Warning : unknown amino acids
		AuLog @text "There are unknown amino acids (O) in the sequence of :\n[join [set Warn(O)] ","]\nSome computations won't be available !"
		AuLog @end
	    }
	    "U" {
		if {[ModeI]} {
		    set choix [tk_dialog .uwarn "Warning" "There are seleno-cysteins (U) residues in the sequence of :\n[join [set Warn(U)] ","]\nSome computations won't be available if you keep them.\nDo you want to replace them with C ?" "" 0 " Yes " " No "]
		} else {
		    set choix 1
		}
		AuLog @begin warning
		AuLog @title Warning : seleno-cystein amino acids
		if {$choix} {
		    ChangeSelenoC2C
		    AuLog @text "There are seleno-cystein amino acids (U) in the sequence of :\n[join [set Warn(U)] ","]\nThey have been replaced by cysteins (C)"
		} else {
		    AuLog @text "There are seleno-cystein amino acids (U) in the sequence of :\n[join [set Warn(U)] ","]\nSome computations won't be available !"
		}
		AuLog @end
	    }
	    "Numbers" {
		FaireLire "There are numbers (0-9) in the sequence of :\n[join [set Warn(Numbers)] ","]\nSome computations won't be available !"
		AuLog @title Warning : numbers in sequence
		AuLog @text "There are numbers [0-9] in the sequence of :\n[join [set Warn(Numbers)] ","]\nSome computations won't be available !"
		AuLog @end
	    }
	    "BadPdb" {
		FaireLire "Can't download the following PDB entries from servers :\n[join [set Warn(BadPdb)] ","]\n"
		AuLog @title Warning : problems downloading PDB
		AuLog @text "Can't download the following PDB entries from servers :\n[join [set Warn(BadPdb)] ","]\n"
		AuLog @end
	    }
	    "ChnPdb" {
		FaireLire "Can't find the requested chain in the following PDB entries:\n[join [set Warn(ChnPdb)] ","]\n"
	    }
	    "Vide" {
		FaireLire "The following sequences names do not contain any amino acid sequences :\n[join [set Warn(Vide)] ","].\nThey will be discarded from the alignment."
		AuLog @title Warning : empty sequences
		AuLog @text "The following sequences names do not contain any amino acid sequences :\n[join [set Warn(Vide)] ","].\nThey will be discarded from the alignment."
		AuLog @end
	    }
	}
    }

    return
}


proc ChangeSelenoC2C {} {
    global LNOrdali LSOrdali Sequences

    set LSOrdali {}
    foreach n $LNOrdali {
	if {[string trim $n] eq ""} {continue}
	set s [set Sequences($n)]
	set s [string map [list U C] $s]
	lappend LSOrdali $s
	set Sequences($n) $s
    }

    return
}


proc ExisteAABizarres {nseq} {
    set ya 0
    if {[info exists ::Warn($nseq)] && $::Warn($nseq)} {
	return 1
    } else {
	return 0
    }
}


proc TraiteAABizarres {{force 0}} {
    global Sequences Warn

    foreach n [array names Sequences] {
	set s [set Sequences($n)]
	if {! [info exists Warn($n)] || $force} {
	    set val 0
	    switch -regexp $s {
		{B} {
		    set val 1
		    lappend Warn(B) $n
		}
		{Z} {
		    set val 1
		    lappend Warn(Z) $n
		}
		{U} {
		    set val 1
		    lappend Warn(U) $n
		}
		{X} {
		    set val 1
		    lappend Warn(X) $n
		}
		{J} {
		    set val 1
		    lappend Warn(J) $n
		}
		{O} {
		    set val 1
		    lappend Warn(O) $n
		}
		{[0-9]} {
		    set val 1
		    lappend Warn(Numbers) $n
		}
luc.moulinier's avatar
luc.moulinier committed
1786 1787 1788 1789
		{[^a-zA-Z0-9\.-]} {
		    set val 1
		    set Warn(Unknown) $n
		}
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
	    }
	    set Warn($n) $val
	}
    }

    return
}



proc AssigneLePoidsDesSeqs {} {
luc.moulinier's avatar
luc.moulinier committed
1801 1802
    global LePoidsDesSeqs IdXml LesPoidsDesSequences FichierXML FichierMSF LNOrdali
    
1803 1804 1805 1806
    set LePoidsDesSeqs {}
    if {[info exists FichierMSF]} {
	LitLesPoidsDuMSF $FichierMSF
	foreach n $LNOrdali {
luc.moulinier's avatar
luc.moulinier committed
1807 1808 1809
	    if {$n eq ""} {
		continue
	    }
1810 1811 1812 1813 1814
	    set p [set LesPoidsDesSequences($n)]
	    lappend LePoidsDesSeqs $p
	}
    }
    if {[info exists FichierXML]} {
luc.moulinier's avatar
luc.moulinier committed
1815
	ExtraitLesPoidsDuXML $IdXml LePoidsDesSeqs
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
    }

    return
}


proc CorrespondanceGenSeq {mol x} {
    # ATTENTION ! On considere ici numerotation 
    # commence a 0 !

    set seq [string map [list "." "" "Z" ""] [string range [set ::Sequences($mol)] 0 $x]]

    return [expr {[string length $seq] -1}]
}


proc CorrespondanceSeqGen {mol x} {
    # ATTENTION ! On considere ici numerotation 
    # commence a 0 !

    set seq [set ::Sequences($mol)]
    set seq [string map [list "Z" "."] $seq]
    set tmp [string map [list "." ""]  $seq]
    set lsd [string length $tmp]
    if {$x >= $lsd} {
	return [expr {[string length [string trimright $seq "."]] - 1}]
    }

    set c -1
    set i -1
    foreach a [split $seq ""] {
	incr i
	if {$a eq "."} {continue}
	incr c
	if {$c >= $x} {return $i}
    }

    return $i
}


proc CorrespondancePDBGen {molid x} {
    # Renvoie position generale commencant a 0 !

    set molid [BonAccess $molid]
    set mol [DonneIdDeAccessPDB $molid]
    set chn [DonneChainDeAccessPDB $molid]
    if {$chn eq ""} {set chn "a"}

    set seq [set ::Sequences($molid)]
    set seq [string map [list Z .] $seq]
    set IdxPrem [lsearch [$mol _resnumber -chain $chn -polymer] $x]

    set i -1
    set cpt -1
    set Lc [split $seq ""]
    foreach a $Lc {
	incr i
	if {$a eq "."} {continue}
	incr cpt
	if {$cpt == $IdxPrem} {
	    break
	}
    }

    return $i
}


proc CorrespondanceGenPDB {molid x} {
    # position generale commence a 0

    set molid [BonAccess $molid]
    set mol [DonneIdDeAccessPDB $molid]
    set chn [DonneChainDeAccessPDB $molid]
    if {$chn eq ""} {set chn "a"}

    set seq [set ::Sequences($molid)]
    set s1 [string map [list "Z" "" "." "" " " ""] [string range $seq 0 $x]]
    if {$s1 eq ""} {
	set b1 0
    } else {
	set long1 [expr {[string length $s1] -1}]
	set b1 [lindex [$mol _resnumber -chain $chn -polymer] $long1]
    }

    return $b1
}


proc CorrespondanceAliPDB {molid x1 x2 seqass seqali} {

    set chn [DonneChainDeAccessPDB $molid]
    set mol [DonneIdDeAccessPDB $molid]

    global PDB_[set mol]_Sequence
    global PDB_[set mol]_NmrRes

    regsub -all {\.} [string range $seqali 0 $x1] "" str1
    set long1 [expr {[string length $str1] -1}]
    set b1 [lindex [set PDB_[set mol]_NmrRes($chn)] $long1]

    regsub -all {\.} [string range $seqali 0 $x2] "" str2
    set long2 [expr {[string length $str2] -1}]
    set b2 [lindex [set PDB_[set mol]_NmrRes($chn)] $long2]

    if {$b1 == ""} {set b1 -9999}
    if {$b2 == ""} {set b2 -9999}

    set lgth [expr {$b2 - $b1}]

    return [list $b1 $b2 $lgth]
}



proc CorrespondancePDBAli {MolId Chn Dep Fin SeqAlignee} {

    global PDB_[set MolId]_NmrRes

    set IdxPrem [lsearch [set PDB_[set MolId]_NmrRes($Chn)] $Dep]
    set IdxDern [lsearch [set PDB_[set MolId]_NmrRes($Chn)] $Fin]

    # Cherche correspondance entre no residus PDB et positions de
    # l'alignement global

    incr IdxPrem
    incr IdxDern

    set DebAli -9999
    set FinAli -9999
    set i -1
    set cpt 0
    regsub -all "Z" $SeqAlignee "." seq

    set Lc [split $seq ""]
    foreach a $Lc {
	incr i
	if {$a eq "."} {continue}
	incr cpt
	if {$cpt == $IdxPrem} {set DebAli $i}
	if {$cpt == $IdxDern} {
	    set FinAli $i
	    break
	}
    }

    return [list $DebAli $FinAli]
}



proc EquivPosGenPosSeq pxy {

    global NomNomSeq
    global NomTextSeq
    global NomEtSeqAssPDB
    global Sequences

    lassign [split [$NomTextSeq index $pxy] "."] y x 
    set noms [string trim [$NomNomSeq get $y.0 "$y.0 lineend"]]
    set nomstatus $noms

    if {[regexp "PDB_" $noms]} {
	# recherche seq attachee au pdb. C'est la premiere non-odb
	# en remontant la liste
	set mol [string range $noms 4 7]
	set ny [expr {$y-1}]
	set tst [string range [$NomNomSeq get $ny.0 "$ny.0 lineend"] 0 3]
	while {$tst eq "PDB_"} {
	    incr ny -1
	    set tst [string range [$NomNomSeq get $ny.0 "$ny.0 lineend"] 0 3]
	}
	set idx [lsearch -regexp $NomEtSeqAssPDB $mol]
	set n [lindex $NomEtSeqAssPDB $idx]
	scan $n "%s %s %s" PDBin NmSeqAss MolId
	set chn [string index $MolId 5]
	global PDB_[set mol]_SecStr
	global PDB_[set mol]_Sequence
	set SeqAss [set Sequences($NmSeqAss)]
	set SeqAlignee [lindex [set PDB_[set mol]_Sequence($chn)] 1]
	set nomsqas [lindex $LesNom $ny]
	set SeqAss [lindex $LesSeq $ny]

	set cxseq [CorrespondanceAliPDB $MolId $x $x $SeqAss $SeqAlignee]
	scan $cxseq "%d %s %s" xseq tmp tmp1
    } else {
	set s [string range [lindex $LesSeq [expr {$y-1}]] 0 $x]
	regsub -all {\.} $s "" lsp
	regsub -all " " $lsp "" lnet
	set xseq [string length $lnet]
    }

    return [list $x $xseq]
}


proc AutreCodeLuc {X} {
    if {! [info exists ::AutreCodeLuc]} {
	InitCode3l1l
    }

    if {[info exists ::AutreCodeLuc($X)]} {
	return [set ::AutreCodeLuc($X)]
    } else {
	set n [string length $X]
	switch $n {
	    1 {return "XXX"}
	    3 {return "X"}
	}
    }
}


proc NombreDeZDuPilier Pilana {
    return [regsub -all "Z" $Pilana "" bidon]
}


proc CalculePoidsDuPilier2 {Pilier Laa NmGrp Seuil} {
    global SDG LNDG Sequences LesPoidsDesSequences

    set Lc [split $Pilier ""]
    set poids 0.
    foreach s [set SDG($NmGrp)] c $Lc {
	if {$c in $Laa} {
	    set poids [expr {$poids + [set LesPoidsDesSequences($s)]}]
	}
    }

    if {$poids >= $Seuil} {
	return 1
    } else {
	return 0
    }
}


proc CalculePoidsDuPilier {pilier nmgrp} {
    global LesPoidsDesSequences
    global Sequences
    global LNDG
    global SDG

    set poids 0.
    set i 0
    foreach s [set SDG($nmgrp)] {
	if {[regexp {[0-9]} [string index $pilier $i]]} {
	    set poids [expr {$poids + [set LesPoidsDesSequences($s)]}]
	}
	incr i
    }

    return $poids
}


proc CalculeLesSeuils {pilier {nmgrp ""} {thr ""}} {
    global Threshold ListeDesPiliersDuGroupe SDG LNDG Sequences LNOrdali LesPoidsDesSequences

    set PoidsTotal 0.

    if {$thr eq ""} {
	set thr [expr {double($Threshold)/100.}]
    } else {
	set thr [expr {double($thr)/100.}]
    }
    if {$nmgrp eq ""} {set nmgrp "GroupeToutLeMonde"}

    set i 0
    set Lc [split $pilier ""]
    foreach s [set SDG($nmgrp)] c $Lc {
	if {$c eq "Z"} {continue}
	set PoidsTotal [expr {$PoidsTotal+[set LesPoidsDesSequences($s)]}]
	incr i
    }

    if {$i > 1} {
	set seuil [expr {floor($thr*$PoidsTotal)}]
    } else {
	set seuil -1.
    }

    return $seuil
}


proc DonneCompositionDe {n {s ""}} {
    if {$s eq ""} {
	set i [lsearch $::LNOrdali $n]
	set s [lindex $::LSOrdali $i]
    }
    set s [string map [list "-" "" "Z" "" "X" "" "." ""] $s]

    set ln [string length $s]
    if {! $ln} {return ""}
    foreach a {A C D E F G H I K L M N P Q R S T V W Y} {
	set pa [expr {100.*([string length $s] - [string length [string map [list $a ""] $s]])/$ln}]
	lappend Lf $pa
    }

    return $Lf
}


proc DonnePhysicoChimieDe {n {s ""}} {
    if {$s eq ""} {
	set i [lsearch $::LNOrdali $n]
	set s [lindex $::LSOrdali $i]
    }
    set s [string map [list "-" "" "Z" "" "X" "" "." ""] $s]

    set ln [string length $s]
    if {! $ln} {return ""}
    foreach a {"A|I|L|M|V" "K|R|H" "D|E|Q|N" "F|Y|W" "P|G|S|T"} {
	set pa [expr {100.*[regsub -all "$a" $s "" s]/$ln}]
	lappend Lf $pa
    }

    return $Lf
}


proc CalculeComposition {{force 0}} {
    global TDesCompos LNOrdali LSOrdali

    foreach n $LNOrdali {
	if {$n eq ""} {continue}

	if {! [info exists TDesCompos($n,aa)] || $force} {
	    set TDesCompos($n,aa) [DonneCompositionDe $n]
	    set TDesCompos($n,pc) [DonnePhysicoChimieDe $n]
	}
    }

    return
}


proc LogLesCompositions {} {
    global LNOrdali LSOrdali TDesCompos

    if {! [info exists TDesCompos]} {
	return
    }

    AuLog @begin table
    AuLog @title AminoAcid Composition :
    set Ln [PlusLongEltDe $LNOrdali]
    AuLog @begin tabular
    AuLog @titlecols Protein A C D E F G H I K L M N P Q R S T V W Y
    AuLog @typecols T R R R R R R R R R R R R R R R R R R R R
    foreach s $LNOrdali {
	if {[string trim $s] eq ""} {continue}
	
	set ligne "$s"
	foreach v [set TDesCompos($s,aa)] {
	    #append ligne " [format "%5.2f" $v]"
	    lappend ligne [format %5.2f $v]
	}
	AuLog @row {*}$ligne
    }
    AuLog @end

    AuLog @title Physico-chemical Composition :
    AuLog @begin tabular
    AuLog @titlecols Protein AILMV PGST FYW KRH DEQN
    AuLog @typecols T R R R R R
    foreach s $LNOrdali {
	if {[string trim $s] eq ""} {continue}
	set ligne $s
	foreach v [set TDesCompos($s,pc)] {
	    #append ligne " [format "%5.2f" $v]"
	    lappend ligne [format %5.2f $v]
	}
	AuLog @row {*}$ligne
    }
    AuLog @end
    AuLog @end

    return
}


proc PIAuPH {AspN GluN CysN TyrN HisN LysN ArgN pH} {
    # Valeurs de pK prises dans EMBOSS (fichier emboss/data/Epk.dat)
    # les valeurs commentees correspondent aux valeurs donnees par wikipedia.

    #C-terminal charge
    set QN1 [expr {-1./(1+pow(10,(3.6-$pH)))}]

    #D charge
    set QN2 [expr {-$AspN/(1+pow(10,(3.9-$pH)))}]

    #E charge
    # set QN3 [expr {-$GluN/(1+pow(10,(4.07-$pH)))}]
    set QN3 [expr {-$GluN/(1+pow(10,(4.1-$pH)))}]

    #C charge
    # set QN4 [expr {-$CysN/(1+pow(10,(8.18-$pH)))}]
    set QN4 [expr {-$CysN/(1+pow(10,(8.5-$pH)))}]

    #Y charge
    # set QN5 [expr {-$TyrN/(1+pow(10,(10.46-$pH)))}]
    set QN5 [expr {-$TyrN/(1+pow(10,(10.1-$pH)))}]

    #H charge
    # set QP1 [expr {$HisN/(1+pow(10,($pH-6.04)))}]
    set QP1 [expr {$HisN/(1+pow(10,($pH-6.5)))}]

    #N terminal
    # set QP2 [expr {1./(1+pow(10,($pH-8.2)))}]
    set QP2 [expr {1/(1.+pow(10,($pH-8.6)))}]

    #K charge
    # set QP3 [expr {$LysN/(1+pow(10,($pH-10.54)))}]
    set QP3 [expr {$LysN/(1+pow(10,($pH-10.8)))}]

    #R charge
    # set QP4 [expr {$ArgN/(1+pow(10,($pH-12.48)))}]
    set QP4 [expr {$ArgN/(1+pow(10,($pH-12.5)))}]

    set NQ [expr {$QN1+$QN2+$QN3+$QN4+$QN5+$QP1+$QP2+$QP3+$QP4}]

    return $NQ
}


proc DonnePIDe {n {s ""}} {
    if {$s eq ""} {
	set i [lsearch $::LNOrdali $n]
	set s [lindex $::LSOrdali $i]
    }

    set AspN [regsub -all "D" $s "" tmp]
    set GluN [regsub -all "E" $s "" tmp]
    set CysN [regsub -all "C" $s "" tmp]
    set TyrN [regsub -all "Y" $s "" tmp]
    set HisN [regsub -all "H" $s "" tmp]
    set LysN [regsub -all "K" $s "" tmp]
    set ArgN [regsub -all "R" $s "" tmp]

    set pH 6.5
    set pHprev  0.0
    set pHnext 14.0
    set X 0.0
    set E 0.01
    set temp 0.0
    while {1} {
	set NQ [PIAuPH $AspN $GluN $CysN $TyrN $HisN $LysN $ArgN $pH]
	if {$pH > 14.0} {
	    set NQ -999.
	    FaireLire "Something went wrong while computin\npI for $n !"
	    break
	}

	if {$NQ<0} {
	    set temp $pH
	    set pH [expr {$pH-(($pH-$pHprev)/2)}]
	    set pHnext $temp
	} else {
	    set temp $pH
	    set pH [expr {$pH+(($pHnext-$pH)/2)}]
	    set pHprev $temp
	}

	if {$pH-$pHprev<$E && $pHnext-$pH<$E} {
	    break
	}
    }

    return $pH
}


proc CalculeLength {} {
    global Sequences TDesLength
    
    foreach k [array names Sequences] {
	set s [string map {"." "" - "" ~ ""} $Sequences($k)]
	set TDesLength($k) [string length $s]
    }

    return
}


proc CalculePI {{force 0}} {
    global LNOrdali LSOrdali TDespI

    foreach n $LNOrdali {
	if {[string trim $n] eq ""} {continue}
	if {! [info exists TDespI($n)] || $force} {
	    set TDespI($n) [DonnePIDe $n]
	}
    }

    return
}


proc DonneMolWeightDe {s} {
    global TMassesAA

    if {! [info exists TMassesAA]} {InitMasses}

    set s [string map [list "." "" "Z" ""] $s]
    set M 0.0
    foreach a [split $s ""] {
luc.moulinier's avatar
luc.moulinier committed
2325 2326 2327
	if {[info exists TMassesAA($a)]} {
	    set M [expr {$M + [set TMassesAA($a)]}]
	}
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582