Profile


Name
Ebola 4.3
ID
101746
Shared with
Public
Parent
None
Children
Created on
January 05, 2019 at 17:30 PM UTC
Updated on
January 05, 2019 at 17:30 PM UTC
Description

Interlinked edrw and GAB worst. With a wizard for the options, an ooc (options out of context)

Best for


Code


--[[A reset of Ebola concept, By Bruno Kestemont: A merge of TvdL250beta and GABcut Based on Tvdl Rav3n_pl Deep Rebuild v3.x (and Rav3n_pl GAB (both enhanced by BK) edrw on each zone of x segments, then GAB using always the same zones then next zone of y segment, then GAB etc. Note: GAB is always started, even if no rebuild gain This is different from original Ebola, where GAB was only started if DRW minimum gain. To Do: change this WARNING! 1) Script uses a lot of save slots 2) (selected) Best score are always in slot 3 Slot attribution: 2= BestScoreNF3Slot = best score (filters disabled) 3 = BestScoreSlot = selected best (could be score or filter or both) 4 = TotalSlot = Fuse or rebuild results (Total) 5 = LocTotalSlot = loctotal (MUST be 5 for edrw) 6-17 used by edrw (initialized) for subscore slots WARNING ! May be more !!!!! then it will bug 18 = BestFilterBonus3 --- This slot to be evaluated !! not sure is not used in edrw BK 11/11/2014 19 = PreferredScoreSlot = preferred see Savebest 20 = BestItelligentSlot = best compromise between filter and score 21 =BestFilterSlot -- BK 11/11/2014 -- Best filter score only 22 =PreferrredFilterSlot -- BK 11/11/2014 -- best filter not on any cost 50-100 gradually used for recipe GAB Slots 23 = BestGABslot (was 3 in original recipe) 24 = GABrbSlot 25 = GABherSlot 30-49 used to record each big steps for movie at the end Description: This is a long run rebuilder. Idea is to rebuild given/found area so many tyimes to found better position. Each rebuild is scored in different ways and saved if better. After rebuild finishes script is trying to stabilize each different saved position. Because some positions are best in more than 1 way sometimes it is only 1 positions to stabilize. On the best position a fuze is run if it looks promising enough. Changed by: Timo van der Laan 17-12-2011 till 28-12-2012 Changed by Bruno Kestemont 29-12-2012 till 11-11-2014 added Idealize, remix, filter management... all experimental ]]-- Introduction --[[ Overview: This version of Rav3n_pl DRW has several new features. First of all it is made totally V2 and uses option dialogs. It has an optimised fuze and qStab, and will run a lot faster as the original. The main optimalisation is that futile shakes and allready tried rebuilds are skipped. Another one is that unprommissing fuzes can be skipped. Features (most have parameters): 1. Can be used in design puzzles, has mutate options for that. 2. It will only recompute the next rebuild if there has been enough gain 3. It will not try to rebuild the exact same segments for a second time 4. It will not try a fuze if the loss is too great depending on the size of the rebuild 5. It will not try to rebuild frozen or locked parts 6. You can specify what parts of the protein to work on. 7. If you want it can keep disulfide bridges intact (thanks Brow42) 8. If the starting score is negative, default is that no wiggles will be done to avoid exploding the protein. 9. If stopped, it will reset CI, best score and secondary structures. 10. You can skip a number of worst parts (handy after a crash) 11. It breaks off rebuild tries if no chance of success. 12. It works on puzzles even if the score is < -1000000 (but will be slower). 13. Fuze and qStab can be suppressed (default if score is negative from the start) 14. You can specify to disable bands when rebuilding and enable them afterwards. NEW in version 2 15. You can choose which slots will be active (slots = archive of subscores) "After each rebuild there is a small local shake to remove clashes. After the rebuild phase qstab is run on each slot selected and only the best result will be fuzed if the score is high enough. I always include slot 4 (total score)" 16. You can choose which segment scoreparts count for finding worst 17. It will recognize puzzle properties and set defaults for it 18. Instead of skipping cycles you can specify nr of worst to skip 19. On ED puzzles the other component is given proper weight for finding worst 20. Code has been cleaned up 21. And something special for Auntdeen :-) 2.1.0 Added code for disjunct searching, fixed bridgesaving init. 2.1.1 Changed some max and min slider values and autodetects Layer Filter 2.2.0 Added ligand slot 2.3.0 GRRR Had to change other by Density 2.4.0 Dynamic list of active subscores, Puts back the old selection when stopped, Added rebuildnumber to the gainslot, Added alternative local cleanup after rebuild, Resets the original structure if mutated after rebuild for the next rb, Sets default mutate settings if a design puzzle. 2.4.0 nc BK adapted for New Chapter 08/02/2014 2.4.1 nc BK 09/02/2014 optimized for new Chapter (longer but better wiggle) 2.5.0 beta BK 11/11/2014 added filter score management for slots options EBOLA 3.0 = first merge 3.1 = better score concepts management 3.1.1 = added slot subscore name 17/12/2014 in order to better understand what happens 3.2. Original edrw50 wiggle function + added filter management inside it 3.2.1 Trying to optimize filters versus score 3.2.2 Enable filter on each score computing: NOTE that if you start with filter disabled, it will do everything like this unless the score computing more gab generations like in original ebola 3.3 Filter included in slots 3.3.1 Reset options, from fast to slow 3.3.2 Generic Filter Management by BitSpawn 3.4 GAB options 3.4.1 Log cleaning ("recovering" was not correct) + optimize the GAB breeding generations 3.4.2 Filter management default at the start of the recipe, debugged, added FUZE2BEST 3.4.3 trying to fig cut bug (by including save and recentbest in generic filter funtions) 3.4.4 skipping slot RB solutions when cost of total slot points it too high (>100 pts) trying to fix the bug preferred GAB score ingnored 3.4.5 huge threshold for missed gains (went against the new slot policy) skipping threshold default changed, changed filter skip default threshold 3.4.6 Trying to fix bug filters default always disabled 3.4.7 Trying to correct the starting fuze problem 3.4.8 Higher Max length limit in order to be able to rebuild a very big part 3.4.9 Higher cost for filters allowed (but still not allowing to looze > 2 pts filter for 1 pt score) included automatic options for herds and critters 3.5 TOOMUCHFILTERLOSS implemented in order to stop going down too far with herd 3.6 Contextual options TOOMUCHFILTERLOSS: on the level of critters, not herd reinitialize UseSegments each starting GAB (onterwise it was cumulative) 3.6.1 debugged contextual options for ED 3.6.2 Use ligand in rebuild and GAB if ligands 3.6.3 Slow Filter cleaning + delete power test + some GAB slower on choice 5 + only GAB compatible TO DO: not allowing lost = always taking only the best score (for quick run) 3.7: TvdLmaxbonus for fast filter management 29/03/2015 reducing the number of time score is calculated (this is slow) 3.7.1 refinements of scores & NEGATIVEFILTER filter default options + bigger SkipSlotThreshold 3.7.2 started new SaveBest3 3.7.3 added CUTWORST 3.7.4 refinements of NEGATIVEFILTER and ScorePriority 3.7.5 bug score log hopefully fixed 3.7.6 refinement default options, scores, filters and added gabfilterHigh 3.7.7 tvdl filter option implemented (test with prefered score) 3.7.8 still trying to debug the score log 3.7.9 debugged for Marburg 3.8 jeff101 info each generation, and reduced GAB threshold 3.8.1 debugged and added last which 3.8.2 hopefully debugged cut in worst 3.8.3 starting with "backbone" worst till 2 days before the end, 30/11/2015, and other WorstGroups like in parent ER contextual option if recipe already used (nskip skipping 2 worst parts to save time ) 3/12/2015 Most options are in QuickOptions(choice) where choice = velocity 3.8.4 better score log for cycles Skip fuze on first days when running on HANDFOLD puzzles 3.8.5 From can be longer than to (first dialog) and thus deleted Longest in the "more" options 3.9.0 FILTERPROTECT: No significant filter loss allowed on mutate (it's a loss of time) LostFpgain will be the loss allowed for filter if any gain in mutate Avoids to calculate filters again and again (hopefully saving time) 3.9.1 Keeps user bands and activated bandflip in DRW (disabling existing bands in rebuild) AddBand2UserBands optional on each critter if existing bands between symmetrics (experimental) Bands to space are already working (but they must start from an active segment) 3.9.2 Debug bands 3.9.3 Accelerating start (GENERICFILTER problem) and with FILTERON feature 4.0.0 maxLenLimit till full length of the protein, also on min (allows a kind of FSP) GAB option for Band in Space probability designProtect: freezes backbones of non selected (avoids some macro moves) 4.0.1 made a function StatusGen(nrofRuns) Only turning hydrophobics to center AlwUseLigand= false always by default because there is a Foldit bug of false ligands after using auto structure BUG useLigand should also be false in case of the bug. 4.0.2 Fixed turning hydrophobics only for BBS 4.0.3 Archiving changed options in note. The idea is to keep track on default options that have been changed, in order to inform other players of succesfull options 4.0.5 fixed: bug some options don't change when changing velocity ! (nrskip) and from-to don't change after subdialogs 4.0.6 Added undo disabling (to save time on old computers) and reset default nb worst on velocity 5 4.1.0 Added remix tool and no rebuild case 4.1.1 Reactivated GAB in all cases 4.1.2 Split idealize and remix for better performance Introduced StartEbolaScoreLater in case of very long run 4.1.3 tvdl filter fixed (hopefully) when priority = score: TvdLFilteractive and ScorePriority==0 4.1.4 if NOREBUILDMODE then GABfilter=-1 always as default (ebola is then mainly used for its remix) 4.1.5 if rebuild =0, not necessarilly only gab + other ways to identify no rebuild mode from description fixed uncut worst 4.1.6 small thinks for mutates when not HASMUTABLE 4.1.7 added SUSPECTNOREBUILD in case "no rebuild" is not mentioned in a design puzzle (the user can confirm or still want to rebuild) to ensure that remix and idealize will replace Rebuild in most Design puzzles 4.1.8 filters on on band.commands (in order to prevent unideal loop bug) 4.1.9 oops fixed SUSPECTNOREBUILD 4.2. higher SkipSlotThreshold jeff101 verbose StatusGen and SaveBigSteps on each sub-loop ContextualOptions() every day (for very long run, user options will be partially erased every day) Auto Pilot Mode after some time: HoursResetOptions 4.2.1 oops fixed previous autopilot 4.2.2 OOPS !! fixed GAB error (it didn't start from rebuild recult but from best result !!!) 4.2.3 Option in case of Sketchbook puzzle 4.2.4 added minppi option in first dialog for SKETCHBOOK 4.2.5 new wiggle 4.2.6 changed defminppi in evaluations TE BE EVALUATED ! 4.3 GRRR adapted filter setting to new lua commands: return2GlobalOriginalFilterSetting() NOTE: to verify FILTERON use TO DO: freeze segments (backbone/sidechain) with higher scores, or select only x higher TO DO: duplicated bands for hydrophobics pull on worst hide scores ]]-- Versions recipename="Ebola 4.3" defUndo= false undo.SetUndo(defUndo) print(recipename) print("Inspired by Ebola Rebuild by Jean-Bob and L'Alliance Francophone") print(os.date()) CIfactor=1 function CI(CInr) behavior.SetClashImportance(CInr*CIfactor) end function CheckCI() local ask=dialog.CreateDialog("Clash importance reset to 1") ask.l1=dialog.AddLabel("Last change to change it") ask.l2=dialog.AddLabel("CI settings will be multiplied by set CI") ask.l3=dialog.AddLabel("WAIT for main dialog ! (now adjusting best options to power conditions)") ask.continue=dialog.AddButton("Continue",1) dialog.Show(ask) end if behavior.GetClashImportance() < 0.99 then CI(1) CheckCI() end -- default = 1 it's rare we want something else CIfactor=behavior.GetClashImportance() userbands=band.GetCount() print(userbands..' user-supplied bands.\n ') function round3(x)--cut all afer 3-rd place return x-x%0.001 end function down(x) return x-x%1 end function Max(x,y) if x>y then return x else return y end end --ooc parameters startRecTimeSec= os.time() -- also for HoursRun() timeLeft=os.difftime(puzzle.GetExpirationTime(),startRecTimeSec)/86400 -- in days startRecTime=os.clock () -- New BK 11/10/13 to calculate client power for options LoopOptions=0 function HoursRun(StartTime) local StartTime = StartTime or startRecTimeSec -- in seconds local result= os.difftime(os.time(),StartTime)/3600 -- in hours local minutes = down((result - down(result))*60) print(down(result)..":"..minutes.." hours busy with same options") return result -- in hours end -- START Wiggle Power Setting stuff function DisplayLongWigglePower () local PowerSetting = behavior.GetWigglePower() local result = "" if PowerSetting == "l" then result = "Low" elseif PowerSetting == "m" then result = "Medium" elseif PowerSetting == "h" then result = "High" elseif PowerSetting == "a" then result = "Auto" end return result end OriginalWPowerSetting= DisplayLongWigglePower () print(OriginalWPowerSetting .. " Wiggle Power") function CheckWP() -- including Alarm Dialog if OriginalWPowerSetting == "Low" or OriginalWPowerSetting == "Auto" then local ask=dialog.CreateDialog("Wiggle Power is ".. OriginalWPowerSetting) ask.l1=dialog.AddLabel("Are you sure ?") ask.continue=dialog.AddButton("Continue",1) ask.stop=dialog.AddButton("Cancel",0) askresult=dialog.Show(ask) if askresult < 1 then return false end end return true end -- STOP Wiggle Power Setting stuff --START Generic Filter Management by BitSpawn 21/12/2014 --Source: http://fold.it/portal/node/1998917 --identifying filtered puzzles and all properties OriginalFilterSetting = filter.AreAllEnabled() PROBABLEFILTER= false GENERICFILTER=false FIRSTGENERICFILTER=false -- used if changing GENERICFILTER on the fly FILTERMANAGE= false FILTERON=not OriginalFilterSetting -- order to save time in score functions NEGATIVEFILTER= false -- true= big preference for filter growth (on the cost of score) new 15/4/2015 HASMUTABLE= false IDEALCHECK= false PROBABLESYM= false SEPSIS= false ELECTRON= false DISULFIDEBONUS= false -- NOT USED CENTROID= false HOTSPOT= false HANDFOLD=false -- identifies recipes just after a hand fold (necessity to protect the HF design) NOREBUILDMODE= false SUSPECTNOREBUILD= false SKETCHBOOK = false sym=1 function return2GlobalOriginalFilterSetting() if OriginalFilterSetting then -- if true, all filters are default enabled filter.EnableAll() --Enables all filters else filter.DisableAll() --Disables all filters end end function detectfilterandmut() -- new BK 10/10/2013; 13/2/2015; 5/12/2016; 4/1/2019 local descrTxt=puzzle.GetDescription() local puzzletitle=puzzle.GetName() if #descrTxt>0 and (descrTxt:find("Sketchbook") or descrTxt:find("Sketchbook")) then SKETCHBOOK =true end if #puzzletitle>0 and puzzletitle:find("Sketchbook") then -- new BK 17/6/2013 SKETCHBOOK =true end if #descrTxt>0 and (descrTxt:find("filter") or descrTxt:find("filters") or descrTxt:find("bonus") or descrTxt:find("bonuses") and not descrTxt:find("disabled"))then PROBABLEFILTER=true FILTERMANAGE=true -- default yes during wiggle (will always be activate when scoring) GENERICFILTER=false -- to be evaluated end if #descrTxt>0 and (descrTxt:find("H-bond networks") or descrTxt:find("Hydrogen Bond Networks") or descrTxt:find("H-bond Networks") or descrTxt:find("H-bond Network") and not descrTxt:find("disabled"))then PROBABLEFILTER=true FILTERMANAGE=false -- default no GENERICFILTER=false -- to be evaluated end if #descrTxt>0 and (descrTxt:find("design") or descrTxt:find("designs")) then HASMUTABLE=true IDEALCHECK=true HANDFOLD=true end if #descrTxt>0 and (descrTxt:find("De-novo") or descrTxt:find("de-novo") or descrTxt:find("freestyle") or descrTxt:find("prediction") or descrTxt:find("predictions")) then IDEALCHECK=true HANDFOLD=true end if #puzzletitle>0 then if (puzzletitle:find("Sym") or puzzletitle:find("Symmetry") or puzzletitle:find("Symmetric") or puzzletitle:find("Dimer") or puzzletitle:find("Trimer") or puzzletitle:find("Tetramer") or puzzletitle:find("Pentamer")) then PROBABLESYM=true if puzzletitle:find("Dimer") and not puzzletitle:find("Dimer of Dimers") then sym=2 elseif puzzletitle:find("Trimer") or puzzletitle:find("trimer") then sym=3 elseif puzzletitle:find("Dimer of Dimers") or puzzletitle:find("Tetramer") then sym=4 elseif puzzletitle:find("Pentamer") then sym=5 else sym=6 end end end if #descrTxt>0 and (descrTxt:find("Sym") or descrTxt:find("Symmetry") or descrTxt:find("Symmetric") or descrTxt:find("sym") or descrTxt:find("symmetry") or descrTxt:find("symmetric")) then PROBABLESYM=true if (descrTxt:find("Dimer") or descrTxt:find("dimer") or descrTxt:find("C2 symmetry") or descrTxt:find("twoo symmetric")) and not (descrTxt:find("Dimer of Dimers") or descrTxt:find("dimer of dimers")) then sym=2 elseif descrTxt:find("Trimer") or descrTxt:find("trimer") or descrTxt:find("C3 symmetry") or descrTxt:find("three symmetric") then sym=3 elseif (descrTxt:find("Dimer of Dimers") or descrTxt:find("Tetramer") or descrTxt:find("C4 symmetry") or descrTxt:find("four symmetric")) and not (descrTxt:find("dimer of dimers") or descrTxt:find("tetramer"))then sym=4 elseif descrTxt:find("Pentamer") or descrTxt:find("pentamer") or descrTxt:find("C5 symmetry") or descrTxt:find("five symmetric") then sym=5 else sym=6 end end --print resulting sym info if PROBABLESYM then print("Symmetric") if sym==2 then print("Dimer") elseif sym==3 then print("Trimer") elseif sym==4 then print("Tetramer") elseif sym==5 then print("Pentamer") elseif sym>5 then print("Terrible polymer") end else print("Monomer") end if #puzzletitle>0 and puzzletitle:find("Sepsis") then -- new BK 17/6/2013 SEPSIS=true HANDFOLD=true --p(true,"-Sepsis") print("Sepsis") end if #puzzletitle>0 and puzzletitle:find("Electron Density") then -- for Electron Density --p(true,"-Electron Density") ELECTRON=true HANDFOLD=true print("Electron density") end if #puzzletitle>0 and puzzletitle:find("Centroid") then -- New BK 20/10/2013 --p(true,"-Centroid") CENTROID=true print("Centroid") end if #puzzletitle>0 and puzzletitle:find("Hotspot") then -- New BK 21/01/2014 HOTSPOT=true print("Hotspot") end if #puzzletitle>0 and (puzzletitle:find("No Rebuilding!") or puzzletitle:find("No Rebuilding")) then -- New BK 21/01/2014 NOREBUILDMODE=true print("No Rebuild allowed") end if #descrTxt>0 and (descrTxt:find("Rebuild action has been disabled") or descrTxt:find("No Rebuilding")) then NOREBUILDMODE=true print("No Rebuild allowed") end return end detectfilterandmut() -- function to copy class/table function CopyTable(orig) local copy = {} for orig_key, orig_value in pairs(orig) do copy[orig_key] = orig_value end return copy end -- functions for filters function FiltersOn() if not FILTERON then --if filter.AreAllEnabled() then filter.EnableAll() FILTERON=true --end end end function FiltersOff() if FILTERON then --if behavior.GetFiltersDisabled()==false then filter.DisableAll() FILTERON=false --end end end -- function to overload a funtion function mutFunction(func) local currentfunc = func local function mutate(func, newfunc) local lastfunc = currentfunc currentfunc = function(...) return newfunc(lastfunc, ...) end end local wrapper = function(...) return currentfunc(...) end return wrapper, mutate end -- function to overload a class -- to do: set the name of function classes_copied = 0 myclcp = {} function MutClass(cl, filters) classes_copied = classes_copied+1 myclcp[classes_copied] = CopyTable(cl) local mycl =myclcp[classes_copied] for orig_key, orig_value in pairs(cl) do myfunc, mutate = mutFunction(mycl[orig_key]) if filters==true then mutate(myfunc, function(...) FiltersOn() if table.getn(arg)>1 then -- first arg is self (function pointer), we pack from second argument local arguments = {} for i=2,table.getn(arg) do arguments[i-1]=arg[i] end return mycl[orig_key](unpack(arguments)) else --print("No arguments") return mycl[orig_key]() end end) cl[orig_key] = myfunc else mutate(myfunc, function(...) FiltersOff() if table.getn(arg)>1 then local arguments = {} for i=2, table.getn(arg) do arguments[i-1]=arg[i] end return mycl[orig_key](unpack(arguments)) else return mycl[orig_key]() end end) cl[orig_key] = myfunc end end end -- how to use: --setting default options if filters BK 4/2/2015 --MutClass(structure, false) --MutClass(band, false) --MutClass(current, true) --[[ it does not work well here, better to put it after dialog? if GENERICFILTER then -- WARNING: TO VERIFY !! (may be it's irreversible for several funtions bellow) MutClass(structure, false) MutClass(band, false) MutClass(current, true) MutClass(recentbest, true) -- otherwise, it remembers cut solutions MutClass(save, true) -- better to save with full score end ]]-- --STOP Generic Filter Management ---COMMON DRW and GAB FiltersFirst=false -- new BK 11/11/2014 To evaluate (will be true for filtered puzzles depending on options) GABfilter=5 -- max loss (0-50) for launching GAB after each rebuild (on slots). 70-GABfilter is the min rebuild gain for full GAB after each rebuild session SkipGAB=false -- not really needed in dialog since we can put GAB threshold at minimum FUZE2BEST=true -- also fuze the second best solution after stabilizing slots (unless it is too low) GABfilterHigh=20 -- max gain (if more, continue only with rebuilds - case normal edrw) onlyGAB=false -- not used yet, but it's envisageable last day may be? function p(fmt, ...) if #arg==0 then print(fmt or '') elseif arg==nil then return--print(fmt or '')-- added BK 23/3/13 -- supressed empty lines 11/6/2013 elseif fmt==nil then return--print('')-- added BK 23/3/13 -- supressed empty lines 11/6/2013 else print(string.format(fmt, unpack(arg))) end end --eDRW START ############################################################ -- Handy shorts module normal= (current.GetExplorationMultiplier() == 0) segCnt=structure.GetCount() segCnt2=segCnt while structure.GetSecondaryStructure(segCnt2)=="M" do segCnt2=segCnt2-1 end --SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS SLOTS SLOTS SLOTS SLOTS SLOTS --SelectedSlot=3 -- BK 11/11/2014 -- What we keep depending on options CurrentHigh=1 -- temporary slot BestScoreNF3Slot=2 -- -- best score filter disabled BestScoreSlot=3 -- best score only, at any cost for filter ALWAYS HERE THE BEST ONE from start TotalSlot=4 -- Fuse or rebuild result MUST BE 4 for edrw LocTotalSlot= 5 -- MUST BE 5 for edrw --6-17 used by edrw (initialized) for subscore slots WARNING ! May be more !!!!! then it will bug --18 = best filter slot ???? BestFilterBonus3Slot=18 --- WARNING not evaluated, may be used already by edrw !!!!! PreferredScoreSlot=19 -- -- preferred see Savebest BestItelligentSlot=20 -- best compromise between filter and score BestFilterSlot=21 -- BK 11/11/2014 -- Best filter score only PreferrredFilterSlot=22 -- BK 11/11/2014 -- best filter not on any cost --GAB Slots BestGABslot=23 -- (was 3 in original recipe) GABrbSlot=24 GABherSlot=25 --30-49 used to record each big steps for movie at the end StartRemixSlot=50 --50-100 gradually used for recipe --SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS SLOTS SLOTS SLOTS SLOTS SLOTS -- Score functions -- filter strategy: default FILTERMANAGE -- FILTERMANAGE default false on normal filter, default (or select) true on PROBABLEFILTER -- the filters will be disabled on normal, enabled on filtered (unless specified by "false" or "no filter manage") function ScoreRank(FilterOn)--return total score displayed on the rank, BK (filter on or off depending on argument) local CurrentFilterSetting = filter.AreAllEnabled() local FilterOn=FilterOn -- or (not CurrentFilterSetting) = BUG !?? local function return2CurrentOriginalFilterSetting() if OriginalFilterSetting then -- if true, all filters are default enabled filter.EnableAll() --Enables all filters else filter.DisableAll() --Disables all filters end end if FilterOn then FiltersOn() elseif FilterOn==false then FiltersOff() end if energy==true then -- TO DO, energy does not exist here ! return current.GetEnergyScore() else return current.GetScore() -- WARNING it's the default of this new function !!!! end return2CurrentOriginalFilterSetting() FILTERON=not CurrentFilterSetting end function Score(pose, FilterOn) -- original tvdl (filters enabled) local CurrentFilterSetting = filter.AreAllEnabled() local FilterOn=FilterOn local function return2CurrentOriginalFilterSetting() if OriginalFilterSetting then -- if true, all filters are default enabled filter.EnableAll() --Enables all filters else filter.DisableAll() --Disables all filters end end if FilterOn then FiltersOn() elseif FilterOn==false then FiltersOff() end -- elseif nil, don't change the filter if pose==nil then pose=current end local total= pose.GetEnergyScore() -- FIX for big negatives if total < -999999 and total > -1000001 then total=SegScore(pose) end if normal then return total else return total*pose.GetExplorationMultiplier() end if FilterOn~=nil then return2CurrentOriginalFilterSetting() FILTERON=not CurrentFilterSetting end end function Score3() -- best with and without filter NEW fixed version 4/1/2019 --ScoreNF3=ScoreRank(false) --global Score3=ScoreRank(true) --global --FilterBonus3=Score3-ScoreNF3 --global FilterBonus3=filter.GetBonusTotal() --Total bonus score of the filters ScoreNF3=Score3-FilterBonus3 end -- for contextual options Score3() -- NEW It's here that we calculate filter bonus StartEbolaScore=Score3 StartEbolaScoreLater = StartEbolaScore -- after reset when gain very high StartEbolaScoreNF=ScoreNF3 StartEbolaFilterBonus=FilterBonus3 WorstGroups="All" --{"All", "Backbone", "Sidechain", "Other"} --[[ subscores={ --select given score parts for calculating worst/best areas {"clashing", "packing", "hiding", "bonding", "backbone", "sidechain", "disulfides", "density", "ideality", "reference"}, -- 1:All {"clashing", "packing", "backbone", "ideality"}, -- 2:Backbone 07/02/2014 {"hiding", "bonding", "sidechain"}, -- 3:Sidechain {"density", "reference"}, -- 4:Other mode={"All", "Backbone", "Sidechain", "Other"} }]]-- --if OriginalFilterSetting then filterstatus=" with filters (Filters are disabled !!)" else filterstatus=" with filters (filters enabled)" end --print(">>>>>>Start Score = "..StartEbolaScore..filterstatus) print(">>>>>>Start Score = "..round3(StartEbolaScore).." (disabled: "..down(StartEbolaScoreNF).."). Filter="..down(StartEbolaFilterBonus)) function TestPower() local RealRecTime=(os.clock()-startRecTime) RecTime=RealRecTime*segCnt2*sym if PROBABLEFILTER then RecTime=RecTime*2 end local Weight=RecTime/RealRecTime print("Test time= " ..RealRecTime.."sec. Weight= "..Weight) -- pc performance till now in seconds, for options end TestPower() -- end for contextual options function SegScore(pose, FilterOn) -- version including symmetry BK 4/1/2019 local CurrentFilterSetting = filter.AreAllEnabled() local FilterOn=FilterOn local symmetry = sym or 1 -- global sym local function return2CurrentOriginalFilterSetting() if OriginalFilterSetting then -- if true, all filters are default enabled filter.EnableAll() --Enables all filters else filter.DisableAll() --Disables all filters end end if FilterOn then FiltersOn() elseif not FilterOn then FiltersOff() end if pose==nil then pose=current end local total=8000 for i=1,segCnt2 do total=total+symmetry*pose.GetSegmentEnergyScore(i) -- added sym end return2CurrentOriginalFilterSetting() FILTERON=not CurrentFilterSetting return total end bestScore3=StartEbolaScore BestScoreNF3=StartEbolaScoreNF BestFilterBonus3=StartEbolaFilterBonus TvdLmaxbonus=StartEbolaFilterBonus LastFilter=TvdLmaxbonus -- new 23/12/2015 GotMaxFilter=false ShadowFilter=true PreferShadowFilter=true -- necessary for first show in dialog TestSimpleFilterPref= false ScorePriority=0 -- 0= score first or normal; 1= both filter AND score must rise; 2=Only filter must rise --Not used anymore: function FilterBonus(pose) -- changed by BK (independent from score functions) local pose=pose or current local CurrentFilterSetting = filter.AreAllEnabled() local function return2CurrentOriginalFilterSetting() if OriginalFilterSetting then -- if true, all filters are default enabled filter.EnableAll() --Enables all filters else filter.DisableAll() --Disables all filters end end FiltersOn() TvdLscore=pose.GetEnergyScore() FiltersOff() TvdLscore2=pose.GetEnergyScore() return2CurrentOriginalFilterSetting() FILTERON=not CurrentFilterSetting TvdLbonus=TvdLscore-TvdLscore2 -- global return TvdLbonus end function FilterScore() -- new BK 11/11/2014, 23/12/2015, 4/1/2019 TO DO: user defined "filter" ! local Thisfilter=TvdLmaxbonus -- the one given by the user at start local filterShadow=0 -- shadow filter local filterObserved=0 -- current observed filter if GotMaxFilter then -- saves time but it's risky case filter loss ! Thisfilter=TvdLmaxbonus else filterObserved=FilterBonus() -- needed to calculate global TvdLbonus if filterObserved==TvdLmaxbonus then TvdLmaxbonus=filterObserved GotMaxFilter=true print("Max bonus achieved !") elseif filterObserved>TvdLmaxbonus then TvdLmaxbonus=filterObserved end end if ShadowFilter and PreferShadowFilter then -- case official filter or shadow filter choice filterShadow=ScoreRank(true)-SegScore(current,true) -- filters enabled if filterShadow > filterObserved + 10 or filterShadow < filterObserved - 10 then -- signif. different if PreferShadowFilter then Thisfilter =filterShadow end ShadowFilter=true -- will show in first dialog else Thisfilter= filterObserved ShadowFilter=false end else -- the normal case when we only want to rise the official filter bonus Thisfilter= filterObserved end LastFilter=Thisfilter return Thisfilter end -- new BK 11/11/2014, 29/03/2015, 4/1/2019 --for archiving options by Bruno Kestemont ChangedOptionsTxt="Ebola non-default options: \n " function ChangedOptions(label,before,after) -- archiving the changed options local label, before, after = label, before, after -- or "", 0, 0 or "", true, true if label== "subscore" then ChangedOptionsTxt=ChangedOptionsTxt..after.." "..label.." added "..'\n ' -- new line return after else if before ==true or before == false then -- boolean if not ((before and after) or (not before and not after)) then -- changed boolean option if after then ChangedOptionsTxt=ChangedOptionsTxt..label.." turned on \n " -- new line else ChangedOptionsTxt=ChangedOptionsTxt..label.." turned off \n " -- new line end return after end elseif before > 0 or after > 0 or before <1 or after < 1 then -- numbers if before~= after then -- numbers ChangedOptionsTxt=ChangedOptionsTxt..label..": "..after..'\n ' -- new line return after end --else return before end return before -- always return something ! can be after also here if it is the same ! end end --end for archiving options function TvdLFilterDialog() -- changed by BK, ONLY if PROBABLEFILTER in text local ask=dialog.CreateDialog("Slow filters seem to be active") TvdLmaxbonus1=TvdLbonus -- already calculated in last FilterScore local ShadowFilterScore= LastFilter -- first calculation before knowing preferences --ask.disable=dialog.AddCheckbox("Run with disabled slow filters",TvdLFilteractive) if ShadowFilter then ask.l5=dialog.AddLabel("Total current shadow filter: "..ShadowFilterScore) ask.l6=dialog.AddLabel("Improve shadow filter OR filter bonus?") ask.PreferShadowFilter=dialog.AddCheckbox("Improve shadow filter (slow)",false) end ask.l1=dialog.AddLabel("Current filter bonus: "..TvdLmaxbonus1) ask.l2=dialog.AddLabel("If this is not the maximum bonus, change next line") if TvdLmaxbonus1<200 then tvdlSupermaxbonus= 200 else tvdlSupermaxbonus=TvdLmaxbonus1/5 end if TvdLmaxbonus < 0 then if TvdLmaxbonus < 1000 then ScorePriority= 1 else ScorePriority= 2 end -- 1 filter and score must rise; 2= only filter TvdLmaxbonus=0 NEGATIVEFILTER=true -- for contextual options end ask.maxbonus=dialog.AddSlider("Set maxbonus/10",TvdLmaxbonus/10,0,tvdlSupermaxbonus,0) --ask.l3=dialog.AddLabel("Scores will only be checked for real gains if") --ask.l4=dialog.AddLabel("Score with filter off+maxbonus is a potential gain") ask.l7=dialog.AddLabel("Priority to 0=score; 1=both; 2=filter bonus") -- WARNING: both is complex (can be both or score or filter) ask.ScorePriority=dialog.AddSlider("",ScorePriority,0,2,0) ask.continue=dialog.AddButton("Continue",1) dialog.Show(ask) ScorePriority=ChangedOptions("ScorePriority",ScorePriority,ask.ScorePriority.value) if ScorePriority==2 then FiltersFirst=true end TvdLmaxbonus=ChangedOptions("TvdLmaxbonus",TvdLmaxbonus,10*ask.maxbonus.value) if ShadowFilter then PreferShadowFilter=ChangedOptions("PreferShadowFilter",PreferShadowFilter,ask.PreferShadowFilter.value) end --TvdLFilteractive=ask.disable.value end BetterRecentBest=false function FilterOff() -- TO DO: check slots !!!!!!! -- Filters off but restore a better recentbest with filter off FiltersOff() if BetterRecentBest then save.Quicksave(99) save.Quickload(98) recentbest.Save() save.Quickload(99) end end function FilterOn() -- Filter on but remember recent best if better than current BetterRecentBest= Score(recentbest) > Score() if BetterRecentBest then save.Quicksave(99) recentbest.Restore() save.Quicksave(98) save.Quickload(99) end FiltersOn() end TvdLFilteractive=(math.abs(TvdLmaxbonus) > 0.1) -- TvdLmaxbonus is calculated lines 599 & 647 if TvdLFilteractive then PROBABLEFILTER= true end bestScore=Score() if TvdLFilteractive and ScorePriority==0 then FilterOff() end -- TO DO verify, may be duplicate, should come after choosing ScorePriority function RBScore() return Score(recentbest) end --[[Concepts: Scores: 1) "Score()" = Score3 = classical (filtered) score 1a) ScoreNF3 = score with filters disabled 2) 3) 4) FilterBonus3 = net macro filter as displayed above the window (negative red or positive blue) 4a) ShadowFilterScore = difference between sum of segment score and macro score (filters enabled) 4b) ShadowFilterScoreNF = difference between sum of segment score and macro score (filters disabled) Best scores: 1) bestScore = classical absolute best score only 1a) BestScoreNF3 = best score with filters disabled 2) PreferedScore= WHAT WE KEEP depending on options. WARNING !! 3) BestItelligentScore= Score or filter must gain only at no cost (no cost for filter or score) 4) BestFilterBonus3 = best net macro filter as displayed above the window (negative red or positive blue) 4a) bestFScore= classical absolute best filter only 5) preferredFScore= best filter but not at any cost (cost is an option) 6) BestSolution ???? Related slots: 1) BestScoreSlot -- classical best score only, at any cost for filter 1a) BestScoreNF3Slot = best score with filters disabled 2) PreferredScoreSlot -- WHAT WE KEEP depending on options. WARNING !! 3) BestItelligentSlot -- best compromise between filter and score (no cost allowed) 4) BestFilterBonus3Slot= Best filter bonus (red/blue credited as displayed top of screen) 4a) BestFilterSlot -- BK 11/11/2014 -- Best filter score only (any kind of filter selected) 5) PreferrredFilterSlot -- BK 11/11/2014 -- best filter not on any cost 6) BestSlot ????? Related booleans: 1) improvedscore= if bestScore improved 1a) improvedScoreNF3 = best score with filters disabled improved 2) 3) 4) improvedFilterBonus = classical absolute best filter only 4a) improvedFilter= if filter improved 4b) samefilter = same filter score 5a) improvedPfilter= if preferred filter improved 5b) samePfilter= if same preferred filter 6) ???? Related gains 1) g = g3 = bestScore gain (classical absolute gain) 1a) gN3= BestScoreNF3 = best score with filters disabled 2) pg= preferred score gain (gain on last kept) 3a) ig= intelligent score gain (might be zero if only filter rose) 3b) ifg= intelligent filter gain (might be zero if only score rose) 4) fg=fg3= best filter gain (classical absolute gain) 5) pfg= preferred filter gain 6) sg = selected score gain WARNING error here ! Related costs 1) tfc = total filter cost of bestScore (relative to absolute best filter) 2a) fc= filter cost of preferred score gain (gain & cost on last kept) 2b) sc= score cost on preferred score gain (gain & cost on last kept) 3) (no short term cost allowed here) 4) tsc= total score cost of this best filter (score relative to absolute best score) 5a) tpfsc= preferred filter score cost (score relative to absolute best score) 5b) LostpFgain = score lost allowed for each pt of preferred filter gain 5c) LostAllowed=pgf*LostpFgain 6a) ssc= selected score cost (score relative to absolute best score) 6b) sfc= selected filter cost (score relative to absolute best filter) ]]--Score Concepts by Bruno Kestemont 15/12/2014 PreferedScore=StartEbolaScore bestScore=PreferedScore -- init BestItelligentScore=PreferedScore LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain --this default is no filter preference (score gain = filter gain) LostFpgain= 9 -- default filter lost allowed per 10 pt score gain --this default is quite strong score preference (score gain at almost any filter lost) -- case only gain iff also at least same filter gain= -10 -- case no filter loss: 0 -- case small filter loss allowed: <10 -- almost full priority to score: 100 -- Remark: I don't allow pure full score priority defminppi= 0.1 -- default minppi will be changed if only big jumps are wanted defiter= 2 -- default iteration base for wiggles etc. Will be changed for Sketchbook puzzles: Can be only 2-5-8-11-14 because ((defiter+1)/3) must be integer minGain = 50 -- force a new round if gain is MORE than this (nothing to do with Sketchbook) --otherwise, the score collapses ! --[[Strategy for best scores: SaveBesttvdl reacts like original one: with no filter, it's a normal savebest; with filter, it tries to identify the max potential score by using the maxbonus given by user. SaveBest selects which savebest to use according to preferences. If there is a filter bonus,it depends on the score priority. If it's 1, it does only a very simple SaveBest3 Otherwise: 0) calculates the filter bonus and the potential score, like in edrw28. 1) and normal puzzle without bonus: if bonus declared by user on beginning ]]-- function SaveBesttvdl() -- original tvdl solution (filter must be always off) priority to score if (not TvdLFilteractive) or (Score()+TvdLmaxbonus>bestScore) then -- if filteractive but potential filtered gain if TvdLFilteractive then FilterOn() end local g=Score()-bestScore if g>defminppi then -- was 0 but I will not save small gains (default 0.02) if g>0.01 then print("Gained another "..round3(g).." pts.") end bestScore=Score() PreferedScore=bestScore -- new save.Quicksave(BestScoreSlot) save.Quicksave(PreferredScoreSlot) WhriteNote() end if TvdLFilteractive then FilterOff() end end end function SaveBest() -- By Bruno Kestemont 22/1/2015, 12/4/2015, 2/6/2015 DEFAULT generic - Filter priority included local SBScore=-99999 local tempfilter=-999 if SKETCHBOOK and not current.AreConditionsMet() then -- we are obliged to take the latest good one ! print("FAILED CONDITIONS! retrieving older solution") --save.Quickload(PreferredScoreSlot) -- it's too close to the condition limit. save.Quickload(SlotStep) -- it's the latest big step return -- breaking the function end if ScorePriority<=1 then -- priority to score => normal tvdl SaveBesttvdl() return else -- scorePriority different than score will be controlled by FiltersFirst if (not TvdLFilteractive) or (Score()+TvdLmaxbonus>bestScore) then -- if potential filtered gain if TvdLFilteractive then FilterOn() end WhriteNote() local SBScore=Score() local g=SBScore-bestScore -- since best absolute score local pg=SBScore-PreferedScore -- since latest selection improvedPscore=false if pg>0.01 then improvedPscore=true end improvedscore = false if g>defminppi then -- classical absolute gain bestScore=SBScore if g>0.01 then print(">>>Gained another "..round3(g).." pts. Best score= "..round3(bestScore)) end save.Quicksave(BestScoreSlot) improvedscore = true end if TvdLFilteractive then -- new 29/03/2015 deactivate this when no filter. Priority to Filter or both SaveBestFilter()-- new BK 11/11/2014 LostFilterAllowed=LostFpgain*g/10 --selection of solution to go further --print("Selecting preferred solution") if (improvedscore and (improvedfilter or samefilter)) or (g>=0 and improvedfilter) then print("Well done ! Archiving this best solution") BestItelligentScore=SBScore PreferedScore=SBScore -- always bestScore=SBScore save.Quicksave(BestScoreSlot) -- update in case of filter gain on same score save.Quicksave(BestItelligentSlot) -- archive for info only save.Quicksave(PreferredScoreSlot) -- this case is evident ! All scores reinitialized elseif improvedfilter and FiltersFirst and improvedPscore then -- case improved filter but lowest score -- added condition on improvedPscore, for safety: --you can win on filter only once, the second time, you should at least also improve your preferred score if g-LostAllowed>0 then -- not at any cost ! save.Quicksave(PreferredScoreSlot) -- be careful, we loose our best preferred score here !! PreferedScore=SBScore print("Priority to filter. Filter score "..round3(LastFilter).. " Score: "..round3(PreferedScore).."/"..round3(bestScore)) print("Total SCORE COST accepted: "..round3(bestScore-PreferedScore)) end elseif improvedscore then -- case filter cost for this gain if fg+LostFilterAllowed>0.1 then -- not at any filter cost ! (fg is negative) save.Quicksave(PreferredScoreSlot) -- be careful, we loose our best score here !! PreferedScore=SBScore if fg<-5 then print("Priority to score: "..round3(PreferedScore).."/"..round3(bestScore)) print("FILTER COST accepted: "..round3(LastFilter-bestFScore).." Filter now: "..round3(LastFilter)) end else TOOMUCHFILTERLOSS= true -- reinitialized and used in ScoreHerd if fg<-10 then print("Oops ! Filter change: "..round3(fg).." too high, REJECTING this solution") end --here we do not save the solution end else -- now the simple default preferred gains, but with smaller thresholds if (improvedPscore and (improvedPfilter or samePfilter)) or (pg>=0 and improvedPfilter) then print("Not bad ! Better than the preferred solution") if SBScore>BestItelligentScore then BestItelligentScore=SBScore save.Quicksave(BestItelligentSlot) -- archive for info only print("Updating intelligent score") --print("Intelligent filter cost accepted: "..round3(LastFilter-bestFScore)) end save.Quicksave(PreferredScoreSlot) -- this case is evident ! PreferedScore=SBScore preferredFScore=LastFilter elseif improvedPfilter and FiltersFirst then -- case improved P filter but lowest P score LostAllowed=pfg*LostpFgain/10 --new score smaller lost allowed for this P filter gain if pg-LostAllowed>0 then -- not at any cost ! save.Quicksave(PreferredScoreSlot) -- be careful, we loose score here !! PreferedScore=SBScore preferredFScore=LastFilter print("Priority to filter score "..round3(LastFilter).. " Score: "..round3(PreferedScore).."/"..round3(bestScore)) print("Rising SCORE COST accepted: "..round3(bestScore-PreferedScore)) end elseif improvedPscore then -- case filter cost for this gain LostFilterAllowed=LostFpgain*pg/10 -- renewed threshold here with pg if pfg-LostFilterAllowed>0 then -- not at any filter cost ! save.Quicksave(PreferredScoreSlot) -- be careful, we loose filter score here !! PreferedScore=SBScore preferredFScore=LastFilter print("Priority to score "..round3(LastFilter).. " Score: "..round3(PreferedScore).."/"..round3(bestScore)) print("Total preferred filter cost accepted: "..round3(LastFilter-bestFScore)) else TOOMUCHFILTERLOSS= true -- reinitialized and used in ScoreHerd if pfg<-10 then print("Oops ! preferred filter change: "..round3(pfg).." too high, rejecting this solution") end end end end end end if TvdLFilteractive then FilterOn() end end end -- by BK Including filter score optimization bestFScore=FilterScore() -- with preferred options. FIRST Calculation gives also LastFilter, don't delete ! if bestFScore >10 or bestFScore <-10 then -- note that it will not see this at very begin, when no filter gains were achieved yet PROBABLEFILTER=true print("Start Filter or bonus Score ~= "..round3(bestFScore)) end preferredFScore=bestFScore -- new BK 11/11/2014 -- best preferred filter score --deleted generic filter re-initialization here. TO VERIFY function SaveBestFilter()-- new BK 11/11/2014 local SBfilterscore=FilterScore() fg=SBfilterscore-bestFScore -- global !! pfg=SBfilterscore-preferredFScore LostAllowed=fg*LostpFgain --score lost allowed for this filter gain improvedfilter = false samefilter=false improvedPfilter = false samePfilter=false if fg>0 then bestFScore=SBfilterscore if fg>20 then print(" Found "..round3(fg).." filter pts. Best Filter= "..round3(bestFScore)) end save.Quicksave(BestFilterSlot) improvedfilter = true elseif fg==0 then samefilter=true end if pfg>0 then --preferredFScore=LastFilter -- later when selected only if pfg>20 then print(" Found "..round3(pfg).." preferred filter pts. Filter= " ..round3(preferredFScore).."/"..round3(bestFScore)) end improvedPfilter = true elseif pfg==0 then samePfilter=true end end -- by BK 15/12/2014 function SaveBest3() -- only trivial best filtered, unfiltered and filter bonus NOT USED if ScorePriority==0 then -- priority to score SaveBesttvdl() else -- priority to both score AND filter Score3() -- calculates the 2 types scores & official filter local fg3=FilterBonus3-BestFilterBonus3 local gN3=ScoreNF3-BestScoreNF3 local g3=Score3-bestScore3 -- same as global --filter module if fg3>0 then BestFilterBonus3=FilterBonus3 if fg3>20 then print(" Found "..round3(fg3).." filter pts. Best Filter= "..round3(BestFilterBonus3)) end save.Quicksave(BestFilterBonus3Slot) -- global !? improvedfilter = true -- global !? elseif fg3>-0.1 then samefilter=true end if TvdLmaxbonus<BestFilterBonus3+0.2 then GotMaxFilter= true ScorePriority=0 end -- only score --filtered score module if g3>defminppi then -- classical absolute gain bestScore3=Score3 if g3>0.01 then print(">>>Gained another "..round3(g3).." pts. Best score= "..round3(bestScore3)) end save.Quicksave(BestScoreSlot) -- global !? improvedscore = true -- global !? end --unfiltered score module (filters disabled) if gN3>0 then -- gains on filters disabled NOT USED = to be deleted BestScoreNF3=ScoreNF3 if gN3>10 then print(">>>Found another "..round3(gN3).." uncredited pts. Best uncredited score= "..round3(BestScoreNF3)) end save.Quicksave(BestScoreNF3Slot) -- global !? improvedScoreNF3 = true -- global end if (ScorePriority==1 and (improvedfilter or (samefilter and improvedscore))) or (ScorePriority==2 and (improvedfilter or samefilter) and improvedscore) then save.Quicksave(PreferredScoreSlot) end -- else nothing end end -- New WiggleFactor WF=1 -- Wiggle function -- Optimized due to Susumes ideas -- Note the extra parameter to be used if only selected parts must be done function Wiggle(how, iters, minppi,onlyselected, filtered, valit, mingps) --score conditioned recursive wiggle/shake --fixed a bug, absolute difference is the threshold now if how==nil then how="wa" end --if iters==nil then iters=3 end if minppi==nil then minppi=defminppi end if onlyselected==nil then onlyselected=false end if filtered==nil then filtered=true end local wf=1 if maxCI then wf=WF end if iters==nil then iters=6 end if valit==nil then valit= 1 end if mingps==nil then mingps= 80 end if susume then valit= defiter*wf*iters end if iters>0 then startRecTime=os.clock () iters=iters-1 local sp=Score() if onlyselected then if how == "s" then -- Shake is not considered to do much in second or more rounds structure.ShakeSidechainsSelected((defiter+1)/3) return else if FILTERMANAGE and not filtered then FiltersOff() end-- new BK 8/5/2013, always disable filter here if how == "wb" then structure.WiggleSelected(valit,true,false) elseif how == "ws" then structure.WiggleSelected(valit,false,true) elseif how == "wa" then structure.WiggleSelected(valit,true,true) end if FILTERMANAGE and not filtered then return2GlobalOriginalFilterSetting() FILTERON=not OriginalFilterSetting end -- new BK 8/5/2013, always back to user settings end else if how == "s" then -- Shake is not considered to do much in second or more rounds structure.ShakeSidechainsAll((defiter+1)/3) return else if FILTERMANAGE and not filtered then FiltersOff() end-- new BK 8/5/2013, always disable filter here if how == "wb" then structure.WiggleAll(valit,true,false) elseif how == "ws" then structure.WiggleAll(valit,false,true) elseif how == "wa" then structure.WiggleAll(valit,true,true) end if FILTERMANAGE and not filtered then return2GlobalOriginalFilterSetting() FILTERON=not OriginalFilterSetting end -- new BK 8/5/2013, always back to user settings end end ep = Score() ig=ep-sp timeperiteration =os.clock ()-startRecTime tppii=ig/timeperiteration if math.abs(Score()-sp) > minppi and tppii > mingps then return Wiggle(how, iters, minppi,onlyselected, filtered, valit, mingps) end end end -- end of handy shorts module -- Segment set and list module -- Notice that most functions assume that the sets are well formed -- (=ordered and no overlaps) -- 02-05-2012 TvdL Free to use for non commercial purposes function SegmentListToSet(list) local result={} local f=0 local l=-1 table.sort(list) for i=1,#list do if list[i] ~= l+1 and list[i] ~= l then -- note: duplicates are removed if l>0 then result[#result+1]={f,l} end f=list[i] end l=list[i] end if l>0 then result[#result+1]={f,l} end --print("list to set") --SegmentPrintSet(result) return result end function SegmentSetToList(set) local result={} for i=1,#set do --print(set[i][1],set[i][2]) for k=set[i][1],set[i][2] do result[#result+1]=k end end return result end function SegmentCleanSet(set) -- Makes it well formed return SegmentListToSet(SegmentSetToList(set)) end function SegmentInvertSet(set,maxseg) -- Gives back all segments not in the set -- maxseg is added for ligand local result={} if maxseg==nil then maxseg=segCnt end if #set==0 then return {{1,maxseg}} end if set[1][1] ~= 1 then result[1]={1,set[1][1]-1} end for i=2,#set do result[#result+1]={set[i-1][2]+1,set[i][1]-1} end if set[#set][2] ~= maxseg then result[#result+1]={set[#set][2]+1,maxseg} end return result end function SegmentInList(s,list) table.sort(list) for i=1,#list do if list[i]==s then return true elseif list[i]>s then return false end end return false end function SegmentInSet(set,s) for i=1,#set do if s>=set[i][1] and s<=set[i][2] then return true elseif s<set[i][1] then return false end end return false end function SegmentJoinList(list1,list2) local result=list1 if result == nil then return list2 end for i=1,#list2 do result[#result+1]=list2[i] end table.sort(result) return result end function SegmentJoinSet(set1,set2) return SegmentListToSet(SegmentJoinList(SegmentSetToList(set1),SegmentSetToList(set2))) end function SegmentCommList(list1,list2) local result={} table.sort(list1) table.sort(list2) if #list2==0 then return result end local j=1 for i=1,#list1 do while list2[j]<list1[i] do j=j+1 if j>#list2 then return result end end if list1[i]==list2[j] then result[#result+1]=list1[i] end end return result end function SegmentCommSet(set1,set2) return SegmentListToSet(SegmentCommList(SegmentSetToList(set1),SegmentSetToList(set2))) end function SegmentSetMinus(set1,set2) return SegmentCommSet(set1,SegmentInvertSet(set2)) end function SegmentPrintSet(set) print(SegmentSetToString(set)) end function SegmentSetToString(set) local line = "" for i=1,#set do if i~=1 then line=line..", " end line=line..set[i][1].."-"..set[i][2] end return line end function SegmentSetInSet(set,sub) if sub==nil then return true end -- Checks if sub is a proper subset of set for i=1,#sub do if not SegmentRangeInSet(set,sub[i]) then return false end end return true end function SegmentRangeInSet(set,range) if range==nil or #range==0 then return true end local b=range[1] local e=range[2] for i=1,#set do if b>=set[i][1] and b<=set[i][2] then return (e<=set[i][2]) elseif e<=set[i][1] then return false end end return false end function SegmentSetToBool(set) local result={} for i=1,segCnt do result[i]=SegmentInSet(set,i) end return result end --- End of Segment Set module -- Module Find Segment Types function FindMutablesList() local result={} for i=1,segCnt2 do if structure.IsMutable(i) then result[#result+1]=i end end return result end function FindMutables() return SegmentListToSet(FindMutablesList()) end function FindFrozenList() local result={} for i=1,segCnt2 do if freeze.IsFrozen(i) then result[#result+1]=i end end return result end function FindFrozen() return SegmentListToSet(FindFrozenList()) end function FindLockedList() local result={} for i=1,segCnt2 do if structure.IsLocked(i) then result[#result+1]=i end end return result end function FindLocked() return SegmentListToSet(FindLockedList()) end function FindSelectedList() local result={} for i=1,segCnt do if selection.IsSelected(i) then result[#result+1]=i end end return result end function FindSelected() return SegmentListToSet(FindSelectedList()) end function FindAAtypeList(aa) local result={} for i=1,segCnt2 do if structure.GetSecondaryStructure(i)== aa then result[#result+1]=i end end return result end function FindAAtype(aa) return SegmentListToSet(FindAAtypeList(aa)) end function FindAminotype(at) --NOTE: only this one gives a list not a set local result={} for i=1,segCnt2 do if structure.GetAminoAcid(i) == at then result[#result+1]=i end end return result end -- end Module Find Segment Types -- Module to compute subscores -- TvdL, 14-12-2012 function GetSubscore(types,seg1,seg2,pose) if FILTERMANAGE then FiltersOff() end-- new BK 8/5/2013, always disable filter here local result=0 if type(types) == "table" then for i=1,#types do result=result+GetSubscore(types[i],seg1,seg2,pose) end else if types==nil and seg1==nil and seg2==nil then return Score(pose) end if seg1==nil then seg1=1 end if seg2==nil then seg2=segCnt end --includes ligands! if seg1>seg2 then seg1,seg2=seg2,seg1 end if pose==nil then pose=current end if types==nil then for i=seg1,seg2 do result=result+pose.GetSegmentEnergyScore(i) end else for i=seg1,seg2 do result=result+pose.GetSegmentEnergySubscore(i,types) end end end if normal then return result else return result*pose.GetExplorationMultiplier() end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end end function FindActiveSubscores(show) if FILTERMANAGE then FiltersOff() end-- new BK 8/5/2013, always disable filter here local result={} local Subs=puzzle.GetPuzzleSubscoreNames() local Showlist ="Computing Active Subscores" if show then print(Showlist) end for i=1,#Subs do local total=0 for j=1,segCnt do total=total+math.abs(current.GetSegmentEnergySubscore(j,Subs[i])) if total>10 then result[#result+1]=Subs[i] break end end end if show then for i=1,#result do local totalpts=0 for j=1,segCnt do totalpts=totalpts+current.GetSegmentEnergySubscore(j,result[i]) end print("Active subscore "..result[i].." :"..down(totalpts)) end end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end-- new BK 8/5/2013, always disable filter here return result end function FindActiveFilter()-- BK 11/2/2015 local result=true if bestFScore > -10 and bestFScore < 10 then result= false else result=true PROBABLEFILTER=true -- if one time on the fly we have a filter score, then it's a filtered puzzle end return result end -- End module to compute subscores -- Position stack module 1.0 -- uses slot 50 and higher Stackmin=50 StackMarks={} StackPos=50 function PushPosition() if StackPos==100 then print("Position stack overflow available slots, exiting") exit() end save.Quicksave(StackPos) StackPos=StackPos+1 end function PopPosition() if StackPos==50 then print("Position stack underflow, exiting") exit() end StackPos=StackPos-1 save.Quickload(StackPos) end function PushMarkPosition() -- not used StackMarks[#StackMarks+1]=StackPos PushPosition() end function PopMarkPosition() -- not used if #StackMarks == 0 then print("No marked position found, just popping") else StackPos=StackMarks[#StackMarks]+1 StackMarks[#StackMarks]= nil end PopPosition() end function GetTopPosition() if StackPos==50 then print("No top position on the stack, exiting") exit() end save.Quickload(StackPos-1) end function ClrTopPosition() if StackPos > 50 then StackPos=StackPos-1 end end -- Start of module for bridgechecking Cyslist={} savebridges=false --default no bridgechecking nrofbridges=0 function setCyslist() Cyslist=FindAminotype("c") nrofbridges=CountBridges() end function IsBridge(i) if structure.IsLocked(i) then return false end if FILTERMANAGE then FiltersOff() end local dsscore=current.GetSegmentEnergySubscore(i,'disulfides') if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end return ''..dsscore ~= '-0' end function CountBridges() local count = 0 for i = 1,#Cyslist do if IsBridge(Cyslist[i]) then count = count + 1 end end return count end function BridgesBroken() return savebridges == true and CountBridges() < nrofbridges end function Bridgesave() if savebridges then PushPosition() end end function Bridgerestore() if savebridges then if BridgesBroken() then PopPosition() else ClrTopPosition() end end end -- End module bridgechecking -- Module find puzzle properties -- Tvdl 14-12-2012 HASMUTABLE=false HASDENSITY=false HASLIGAND= (segCnt2<segCnt) DENSITYWEIGHT=0 PROBABLESYM=false FREEDESIGN=false LAYERFILTER=false function SetPuzzleProperties() print("Computing puzzle properties") -- Find out if the puzzle has mutables local MutList=FindMutablesList() HASMUTABLE= (#MutList>0) if HASMUTABLE then print("Mutables found") end FREEDESIGN= (segCnt2/2 < #MutList) if FREEDESIGN then print("Probable a free design puzzle") end -- Find out if the puzzle has possible bridges setCyslist() if #Cyslist > 1 then print("Puzzle has more than 1 cystine") if nrofbridges > 0 then print("Puzzle has bridges") savebridges=true end end if FILTERMANAGE then FiltersOff() end -- Find out is the puzzle has Density scores and their weight if any local Densitytot=GetSubscore("density") local segtot=GetSubscore(nil,1,segCnt) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end HASDENSITY= math.abs(Densitytot) > 0.0001 if normal and HASDENSITY then print("Puzzle has Density scores") DENSITYWEIGHT=(Score()-segtot-8000)/Densitytot print("The Density component has an extra weight of "..round3(DENSITYWEIGHT)) end -- Check if the puzzle is a probable symmetry one if normal and not HASDENSITY then PROBABLESYM=math.abs(Score()-segtot-8000) > 2 if PROBABLESYM then print("Puzzle is probable a symmetry puzzle") end end end SetPuzzleProperties() -- End of module find puzzle properties -- Standard Fuze module -- Picks up all gains by using recentbest function GetRB(prefun,postfun) if RBScore()> Score() then if prefun ~= nil then prefun() end recentbest.Restore() if postfun ~= nil then postfun() end end end function FuzeEnd(prefun,postfun) if prefun ~= nil then prefun() end CI(1) -- Wiggle("wa",1) -- Wiggle("s",1) Wiggle(nil, nil, nil, false, false) --structure.WiggleAll(25) -- here a normal filtered wiggle ADDED if filtered elsewhere GetRB(prefun,postfun) if postfun ~= nil then postfun() end SaveBest() end function Fuze1(ci1,ci2,prefun,postfun) if prefun ~=nil then prefun() end CI(ci1) Wiggle("s",1) CI(ci2) Wiggle("wa",1) if postfun ~= nil then postfun() end end function Fuze2(ci1,ci2,prefun,postfun) if prefun ~= nil then prefun() end CI(ci1) Wiggle("wa",1) CI(1) Wiggle("wa",15) --structure.WiggleAll(15) -- here a normal filtered wiggle ADDED if filtered elsewhere CI(ci2) Wiggle("wa",1) if postfun ~= nil then postfun() end end function reFuze(scr,slot) local s=Score() if s<scr then save.Quickload(slot) else scr=s save.Quicksave(slot) end return scr end function Fuze(slot,prefun,postfun) local scr=Score() if slot == nil then slot=TotalSlot save.Quicksave(slot) -- Replaces TotalSlot ?? TO VERIFY !! (was like this slot 4 in original edrw) end recentbest.Save() Fuze1(0.3,0.6,prefun,postfun) FuzeEnd(prefun,postfun) scr=reFuze(scr,slot) Fuze2(0.3,1,prefun,postfun) GetRB(prefun,postfun) SaveBest() scr=reFuze(scr,slot) Fuze1(0.05,1,prefun,postfun) GetRB(prefun,postfun) SaveBest() scr=reFuze(scr,slot) Fuze2(0.7,0.5,prefun,postfun) FuzeEnd() scr=reFuze(scr,slot) Fuze1(0.07,1,prefun,postfun) GetRB(prefun,postfun) SaveBest() reFuze(scr,slot) GetRB(prefun,postfun) SaveBest() end -- end standard Fuze module -- Module Random -- Tvdl, 01-11-2012 Randomseed=os.time()%1000000 function Seedrandom() math.randomseed(Randomseed) math.random(100) -- Because the first is not random end Seedrandom() -- Thanks too Rav4pl function ShuffleTable(tab) --randomize order of elements local cnt=#tab for i=1,cnt do local r=math.random(cnt) tab[i],tab[r]=tab[r],tab[i] end return tab end function MutateSel(maxitter) if maxitter == nil then maxitter=2 end if LAYERFILTER then -- Needed because this filter restricts on the combination of restrictions local ss local Sellist=FindSelectedList() local itters=1 repeat ss=Score() ShuffleTable(Sellist) for i=1,#Sellist do selection.DeselectAll() selection.Select(Sellist[i]) structure.MutateSidechainsSelected(itters) end itters=itters+1 until math.abs(ss-Score()) > 0.0001 or itters > maxitter else structure.MutateSidechainsSelected(maxitter) end end function MutateAll(maxitter) selection.SelectAll() MutateSel(maxitter) end -- Module setsegmentset -- Tvdl, 11-05-2012 Free to use for noncommercial purposes function SetSelection(set) selection.DeselectAll() if set ~= nil then for i=1,#set do selection.SelectRange(set[i][1],set[i][2]) end end end function SelectAround(ss,se,radius,nodeselect) if nodeselect~=true then selection.DeselectAll() end for i=1, segCnt2 do for x=ss,se do if structure.GetDistance(x,i)<radius then selection.Select(i) break end end end end function SetAAtype(set,aa) local saveselected=FindSelected() SetSelection(set) structure.SetSecondaryStructureSelected(aa) SetSelection(saveselected) end SAVEDstructs=false function AllLoop() --turning entire structure to loops local anychange=false for i=1,segCnt2 do if structure.GetSecondaryStructure(i)~="L" then anychange=true break end end if anychange then save.SaveSecondaryStructure() SAVEDstructs=true selection.SelectAll() structure.SetSecondaryStructureSelected("L") end end function qStab() -- Do not accept qstab losses local curscore=Score() PushPosition() CI(0.1) Wiggle("s",1,nil,true) --shake only selected part if InQstab then CI(1) doMutate() end if fastQstab==false then CI(0.4) Wiggle("wa",1) CI(1) Wiggle("s",1) Wiggle(nil, nil, nil, false, false, nil, nil) --structure.WiggleAll(6) -- here a normal filtered wiggle ADDED if filtered elsewhere end CI(1) Wiggle("wa") --structure.WiggleAll(25) -- here a normal filtered wiggle ADDED if filtered elsewhere if Score() < curscore then PopPosition() else ClrTopPosition() end end function Sort(tab,items) --BACWARD bubble sorting - lowest on top, only needed items for x=1,items do --items do for y=x+1,#tab do if tab[x][1]>tab[y][1] then tab[x],tab[y]=tab[y],tab[x] end end end return tab end -- part to administrate what has been done Donepart={} --To find fast if to be skipped Blocked={} --A simple list so we can clear Donepart Disj={} --To administrate which segments have be touched disjunct=false donotrevisit=true clrdonelistgain=segCnt curclrscore=StartEbolaScore ProtectBest=0 -- nb best scoring to be freezed (depending on "worst subscores" parameters) BestOnes={} BestFrozen={} function AddDone(first,last) if donotrevisit then Donepart[first+(last-first)*segCnt2]=true Blocked[#Blocked+1]=first+(last-first)*segCnt2 end if disjunct then for i=first,last do Disj[i]=true end end end function CheckDone(first,last) if not donotrevisit then return false end local result=Donepart[first+(last-first)*segCnt2] if disjunct then for i=first,last do if Disj[i] then result=true end end end return result end function ChkDisjunctList(n) if not disjunct then return end local maxlen=0 for i=1,segCnt2 do if Disj[i] then maxlen=0 else maxlen=maxlen+1 end if maxlen == n then return end end -- No part is big enough so clear Disjunctlist print("Clearing disjunct list") for i=1,segCnt2 do Disj[i]=false end end function ClearDoneList() --clear donelist for i=1,#Blocked do Donepart[Blocked[i]]=false end if disjunct then --clear disjunctlist also for i=1,segCnt2 do Disj[i]=false end end Blocked={} curclrscore=Score() end function ChkDoneList() if not donotrevisit and not disjunct then return end if Score() > curclrscore+clrdonelistgain then if donotrevisit then ClearDoneList() end end end --end of administration part function FindWorst(firsttime) print("###########################################") print("Searching worst scoring parts of len "..lengthZ.." (it takes time ...)") ChkDisjunctList(lengthZ) wrst={} GetSegmentScores() local skiplist="" local nrskip=0 for i=1,segCnt2-lengthZ+1 do if not CheckDone(i,i+lengthZ-1) and MustWorkon(i,i+lengthZ-1) then local s=getPartscore(i,i+lengthZ-1) wrst[#wrst+1]={s,i} else if CheckDone(i,i+lengthZ-1) then if nrskip==0 then print("Skipping") end nrskip=nrskip+1 skiplist=skiplist..i.."-"..(i+lengthZ-1).." " if nrskip%7==0 then print(skiplist) skiplist="" end end end end if nrskip%7 ~= 0 then print(skiplist) end if nrskip > 0 then print("Number of skips: "..nrskip) end wrst=Sort(wrst,reBuild) areas={} local rb=reBuild if rb>#wrst then rb=#wrst end for i=1,rb do local w=wrst[i] local ss=w[2] areas[#areas+1]={ss,ss+lengthZ-1} end if firsttime and #wrst == 0 then print("No possibilities left so clearing Done list") ClearDoneList() FindWorst(false) -- not first time any more end end function FindBest (ScoreTable, items) local ScoreTable= ScoreTable local items= items BestOnes=Sort(ScoreTable,items) --BACWARD bubble sorting - lowest on top, only needed items end function ProtectBestSegs(ScoreTable, items) local ScoreTable= ScoreTable local items= items FindBest (ScoreTable, items) BestFrozen={} for i=1, #BestOnes do local seg=BestOnes[i][1] if not freeze.IsFrozen(seg) then freeze.Freeze(seg, true, true) -- backbone and sidechains BestFrozen[#BestFrozen+1]=seg end end print("Freezed"..#BestFrozen.." unfreezed best segments") end function UnProtectBestSegs() print("Unfreezing "..#BestFrozen.." best segments") for i= 1, #BestFrozen do freeze.Unfreeze(BestFrozen[i][1]) end end -- Rebuild section function localRebuild(maxiters) if maxiters==nil then maxiters=3 end local s=Score() local i=0 if bandflip then band.DisableAll() end Bridgesave() repeat i=i+1 if i>maxiters then break end structure.RebuildSelected(i) until Score()~=s and BridgesBroken() == false if bandflip and userbandenabled then band.EnableAll() end Bridgerestore() if Score()~=s then return true else return false end end function ReBuild(ss,se,tries) undo.SetUndo(false) -- it takes too much place in the Undo chart local tries = tries or 10 ClearScores() --reset score tables displaySkipSlots="" -- reset list of skipped RB solutions if ss>se then ss,se=se,ss end --switch if needed local Foundone=false if tries == 0 then else for try=1,tries do -- perform loop for number of tries selection.DeselectAll() CI(rebuildCI) selection.SelectRange(ss,se) local extra_rebuilds = 1 if savebridges then extra_rebuilds=3 end --extra if bridges keep breaking local done repeat done=localRebuild(nil) extra_rebuilds = extra_rebuilds -1 until done or extra_rebuilds == 0 SaveBest() if done==true then Foundone=true Bridgesave() if doSpecial==true then SelectAround(ss,se,9) CI(1) Wiggle("s",1,nil,true) Wiggle("ws",10,nil,true) selection.DeselectAll() selection.SelectRange(ss,se) Wiggle("wb",20,nil,true) elseif doShake==true then CI(shakeCI) Wiggle("s",1,nil,true) end Bridgerestore() if AfterRB then PushPosition() --save the current position for next round doMutate() end SaveScores(ss,se,try) if AfterRB then PopPosition() end end if (try > 3 or savebridges) and Foundone==false then print("No valid rebuild found on this section") print("After 9 or more rebuild attempts, giving up") break end end end if displaySkipSlots ~="" then print("Skipped RBns: "..displaySkipSlots.." user slots cost>"..SkipSlotThreshold) end CI(1) undo.SetUndo(defUndo) return Foundone end -- end rebuild section -- section to compute segmentscore(part)s function getPartscore(ss,se,attr) if FILTERMANAGE then FiltersOn() end local s=0 if attr=='total' then s=Score() elseif attr==nil then --is only called from findWorst for i=ss,se do s=s+SegmentScores[i] end elseif attr=='loctotal' then --total segment scores s=GetSubscore(nil,ss,se) elseif attr=='ligand' then --ligand score for i=segCnt2+1,segCnt do s=s+current.GetSegmentEnergyScore(i) end elseif attr=='filter' then -- new BK s=FilterScore() else s=GetSubscore(attr,ss,se) end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end return s end WORKONbool={} -- list of segments with true if we may work on it and false if not function InitWORKONbool() WORKONbool=SegmentSetToBool(WORKON) end function MustWorkon(i,j) for k=i,j do if not WORKONbool[k] then return false end end return true end SegmentScores={} --Optimalisation for fast worst search lastSegScores=0 -- only to see if it has to be calculated again or not function GetSegmentScores() -- total of all scrPart checked subscores for one segment if FILTERMANAGE then FiltersOn() end if lastSegScores~=Score() then lastSegScores=Score() for i=1,segCnt2 do if WORKONbool[i] then if #scrPart==0 then -- if nothing specified by user default is -- segmentenergy - reference + extra Density score SegmentScores[i]=current.GetSegmentEnergyScore(i) if not structure.IsMutable(i) then --ignore reference part but NOT for mutables) SegmentScores[i]=SegmentScores[i]-current.GetSegmentEnergySubscore(i,'reference') end if math.abs(DENSITYWEIGHT) > 0 then --the Density component has extra weight SegmentScores[i]=SegmentScores[i]+DENSITYWEIGHT*current.GetSegmentEnergySubscore(i,'density') end else SegmentScores[i]=GetSubscore(scrPart,i,i) end end end end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end end -- end section segmentscore(part)s -- Administration of the different slots and best scores Scores={} --{SubscoreSlot_no,points,totscore,showlist,todo,rbnr} --example: {14, 12.5, 9898.2, "print this", true, 15} ? -- SubscoreSlot_no = ScoreParts[i][1]: 14= density = ScoreParts[14][2] I think -- Compute which scoreparts to use ActiveSub=FindActiveSubscores(true) -- false = save time on beginning (not displaying subscores) FILTERS=FindActiveFilter() if PROBABLEFILTER then -- gives TvdLmaxbonus --FilterBonus() TvdLFilterDialog() if ShadowFilter then print("Shadow filters seem present") end if TvdLFilteractive and ScorePriority==0 then FilterOff() end -- TO DO verify, may be duplicate, should come after choosing ScorePriority end ScoreParts={ --{SubscoreSlot_no,name,active} example {14, density, true} {4,'total',true}, {5,'loctotal',true} } nextslot=6 if HASLIGAND then ScoreParts[#ScoreParts+1] = { nextslot,'ligand',true } nextslot=nextslot+1 print("Ligand slot enabled") end for i=1,#ActiveSub do ScoreParts[#ScoreParts+1] = { nextslot,ActiveSub[i],true } nextslot=nextslot+1 end if FILTERS then -- new BK ScoreParts[#ScoreParts+1] = { nextslot,'filter',true } nextslot=nextslot+1 print("Filter slot enabled") end function ClearScores() -- renewed BK Scores={} SlotList={} -- new for i=1,#ScoreParts do -- including totals and filter which are not per segment if ScoreParts[i][3] then Scores[#Scores+1]={ScoreParts[i][1],-9999999,-9999999,'',false,-1} SlotList[#SlotList+1]={ScoreParts[i][1], ScoreParts[i][2]} end end slotScr={} end SkipSlotThresholdBase = 20000 -- set it huge if you want to keep all rebuilds like in original tvdl-edrwa SkipSmallSlotThreshold = 0.5 -- if the rebuilds did not change anything, don't loose time with it (set to zero for default) BestRBscore=-99999998 -- partial total rebuild score for this slots preferences SkipSlotThreshold= Max(SkipSlotThresholdBase, SkipSlotThresholdBase + bestScore) -- global will be upgraded each rebuild round displaySkipSlots="" function SaveScores(ss,se,RBnr) -- total of treated zones for each subscore in latest ReBuild/remix (TO DO Filters?) local scr={} -- example {{1, 10.2},{14, -9.5}} 14 being ideality local RBscore=0 -- only to be able to skip it local CostOK=true for i=1,#ScoreParts do -- archiving all selected scoreparts for this rebuild nb if ScoreParts[i][3] then -- including totals and filter local ThisPartScore=getPartscore(ss,se,ScoreParts[i][2]) scr[#scr+1]={ScoreParts[i][1],ThisPartScore} RBscore=RBscore+ThisPartScore -- NEW 10/2/2015 end end if RBscore > BestRBscore then --NEW 10/2/2015 BestRBscore=RBscore SkipSlotThreshold=Max(SkipSlotThresholdBase, SkipSlotThresholdBase + bestScore) -- it will skip worst RBs elseif RBscore + SkipSlotThreshold < BestRBscore or RBscore + SkipSmallSlotThreshold > BestRBscore then -- will keep any improvement, eliminate any worst from there --print("Skipping RBn "..RBnr.." , user slots cost>"..SkipSlotThreshold) CostOK=false -- eliminate this solution displaySkipSlots=displaySkipSlots..RBnr..", " end if CostOK then local totscore=Score() for i=1,#Scores do local s=scr[i][2] -- the subscore considered if s>Scores[i][2] then -- replacing the best subscore of this type for this zone now, except when total was too low local slot=scr[i][1] -- the slot number is always a subscore type e.g. 14= ideality save.Quicksave(slot) --print("Saved slot ",slot," pts" ,s) --debug Scores[i][2]=s -- the new best subscore for this zone Scores[i][3]=totscore -- the related total score Scores[i][6]=RBnr end end SaveBest() end end function ListSlots() --Give overview of slot occupation --And sets which slots to process local Donelist={} for i=1,#Scores do Donelist[i]=false end local Report="" for i=1,#Scores do if not Donelist[i] then local Curlist=" "..Scores[i][1] Scores[i][5]=true --This one we have to process -- Now find identical filled slots for j=i+1,#Scores do if Scores[j][3] == Scores[i][3] then -- total score of each slot Curlist=Curlist.."="..Scores[j][1] Donelist[j]=true end end Scores[i][4]=Curlist Report=Report.." "..Curlist end end print("Slotlist:"..Report) end -- end of administration of slots and scores function PrintAreas() if #areas<19 then local a="" local x=0 for i=1,#areas do x=x+1 a=a..areas[i][1].."-"..areas[i][2].." " if x>6 then print(a) a="" x=0 end end if x>0 then print(a) end else print("It is "..#areas.." places, not listing.") end end function AddLoop(sS) local ss=sS local ssStart=structure.GetSecondaryStructure(ss) local se=ss for i=ss+1,segCnt2 do if structure.GetSecondaryStructure(i)==ssStart then se=i else break end end if se-ss+2>minLen and loops==true then areas[#areas+1]={ss,se} end return se end function AddOther(sS) local ss=sS local ssStart=structure.GetSecondaryStructure(ss) local se=ss if ss>1 then for i=ss-1,1,-1 do --search bacward for start local sec=structure.GetSecondaryStructure(i) if sec=="L" then ss=i else break end end end if se<segCnt2-1 then --now forward to find end local change=false repeat se=se+1 if se==segCnt2 then break end local sec=structure.GetSecondaryStructure(se) if change==false then if sec~=ssStart then change=true end end until change==true and sec~="L" if se<segCnt2 then se=se-1 end end if sheets==false and ssStart=="E" then return se end if helices==false and ssStart=="H" then return se end if se-ss+2>minLen then areas[#areas+1]={ss,se} end return se end function FindAreas() if loops then local done=false local ss=0 repeat--loops ss=ss+1 local ses=structure.GetSecondaryStructure(ss) if ses=="L" then ss=AddLoop(ss) end if ss==segCnt2 then done=true end until done~=false end if sheets or helices then local done=false local ss=0 repeat--other ss=ss+1 local ses=structure.GetSecondaryStructure(ss) if ses~="L" then ss=AddOther(ss) end if ss==segCnt2 then done=true end until done~=false end end firstRBseg=0 lastRBseg=0 number_of_remix=49 -- max number of remixes (depends on the slots available) function doMutate() -- changed 23/12/2015 for FILTERPROTECT: little filter loss allowed here if not HASMUTABLE then return end -- Do not accept loss if mutating local curscore=Score() local curfilter=FilterScore() PushPosition() CI(MutateCI) Bridgesave() if MUTRB then selection.DeselectAll() selection.SelectRange(firstRBseg,lastRBseg) MutateSel() elseif MUTSur then SelectAround(firstRBseg,lastRBseg,MutSphere) MutateSel() else MutateAll() end Bridgerestore() if (Score() < curscore) or (FILTERPROTECT and FilterScore()<curfilter-LostFpgain) then PopPosition() else ClrTopPosition() end end function IdealAndMore(types,seg1,seg2) -- idealize (only, for the moment) if FILTERMANAGE then FiltersOn() end local types=types or "Ideality" local SpecialSubscore=GetSubscore(types,seg1,seg2) -- e.g. ideality local sz=seg2-seg1+1 if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end if SpecialSubscore<-5 then -- only on relatively bad idealities (absolute, not per segment) if ( seg1 > 0 ) then structure.InsertCut ( seg1 ) end if ( seg2 < segCnt2 ) then structure.InsertCut ( seg2) end --selection.DeselectAll () --selection.SelectRange ( seg1,seg2 ) print("Idealizing "..seg1.."-"..seg2) structure.IdealizeSelected () if ( seg1 > 0 ) then structure.DeleteCut ( seg1 ) end if ( seg2 < segCnt2 ) then structure.DeleteCut ( seg2 ) end SelectAround(seg1,seg2,12) --local wiggle after structure.WiggleSelected ( 25 ) SaveBest() end end IDEALCHECK=true -- 08/03/2014 CUTWORST=false -- 1/5/2015 function DeepRebuild() local ss=Score() local drg=0 if struct==false then AllLoop() end save.Quicksave(PreferredScoreSlot) -- initialization at very begin of the recipe recentbest.Save() print("Ebola started at score: "..round3(ss)) for i=1,#areas do local ss1=Score() local s=areas[i][1] local e=areas[i][2] local CurrentHigh=1 -- slot of current high local CurrentHigh2=1 -- slot of second best local CurrentAll="" -- to report where gains came from local CurrentHighScore= -99999998 local CurrentHighScore2= -99999999 local CurrentScore= -99999999 -- only for local checks firstRBseg=s lastRBseg=e Bridgesave() if Runnr > 0 then --Runnr 0 is to avoid bug when skippingworst zones ENOUGHFORGAB=false print("--") dr_string = "DR "..Runnr.."."..(e-s+1).."."..i print("DR "..Runnr.." len "..(e-s+1).." wrst "..i..": "..s.."-"..e.." ".. rebuilds.." times. Wait... Score: "..round3(Score())) if ReBuild(s,e,rebuilds) then -- false if skip -- Make sure we do not miss an improvement during rebuild if RBScore() > PreferedScore then Bridgesave() recentbest.Restore() Bridgerestore() if Score() > PreferedScore*1.1 and Score()> PreferedScore+ 10 then -- was 0.0001 only for huge miss (here we forget all our good intentions print(" Found a missed gain!!!") SaveScores(s,e,0) -- rebuild Nb 0 end if Score() > bestScore+0.001 then print(" Archiving a missed gain!!!") bestScore=Score() save.Quicksave(BestScoreSlot) end end save.Quickload(PreferredScoreSlot) -- New 11/2/2015 to avoid starting too high This is slot n0 I think ListSlots() -- BUG here for r=1,#Scores do -- now we shake (or wiggle) on each slot depending on subscores preferences if Scores[r][5] then local slot=Scores[r][1] local subscoreName= SlotList[r][2] save.Quickload(slot) SelectAround(s,e,12) --local shake after rebuild Bridgesave() if not skipqstab then qStab() else CI(1) Wiggle("s",1,nil,true) Wiggle("ws",15,nil,true) end Bridgerestore() if AfterQstab then doMutate() end save.Quicksave(slot) if Score() > CurrentHighScore then CurrentHigh2=CurrentHigh -- slot of second best CurrentHigh=slot CurrentAll=CurrentAll..Scores[r][4].."("..subscoreName.. ") " CurrentHighScore2=CurrentHighScore CurrentHighScore=Score() end SaveBest() --subscoreName= SlotList[r][2] --BUG print("Stabilized slot "..slot.." ("..subscoreName..") Score: "..round3(Score()).." (RBnr "..Scores[r][6]..")") --BUG --print("Stabilized slot "..slot.." Score: "..round3(Score())) --print("Stabilized slot "..slot.." Score: "..round3(Score()).." (rebuild nb "..Scores[r][6]..")") end end save.Quickload(CurrentHigh) -- taking the best rebuild in order to fuze it if not skipfuze and ss1-CurrentHighScore < maxlossbeforefuze*(e-s+1)/3 then -- start of the Fuze part print("Fuzing best position scoring "..round3(Score())) if not AfterQstab and BeFuze then doMutate() end tempFuzeSlot=TotalSlot tempFuzeSlot2=LocTotalSlot if CurrentHigh2==tempFuzeSlot then -- avoiding to use TotalSlot if it is the second best (we need it) tempFuzeSlot=LocTotalSlot tempFuzeSlot2=TotalSlot end save.Quicksave(tempFuzeSlot) -- archiving it in TotalSlot or LocTotalSlot because it's free now if savebridges then Fuze(tempFuzeSlot,Bridgesave,Bridgerestore) else Fuze(tempFuzeSlot) end if AfterFuze then doMutate() end CurrentHighFuzedScore=Score() -- New 11/2/2015 CurrentHighFuzedScore2=CurrentHighFuzedScore-1 -- only for initializing in case there is no second best print("Done. Fuzed Score= "..round3(CurrentHighFuzedScore)) SaveBest() --new BK 4/2/2015 if CurrentHighScore2*1.02> CurrentHighScore and CurrentHighScore2<CurrentHighScore and FUZE2BEST and CurrentHigh2~= CurrentHigh then -- fuzing second best save.Quickload(CurrentHigh2) -- taking the second best in order to fuze it if not skipfuze and ss1-CurrentHighScore2 < maxlossbeforefuze*(e-s+1)/3 then print("Fuzing 2d best position scoring "..round3(CurrentHighScore2)) --if not AfterQstab and BeFuze then doMutate() end save.Quicksave(tempFuzeSlot2) if savebridges then Fuze(tempFuzeSlot2,Bridgesave,Bridgerestore) else Fuze(tempFuzeSlot2) end --if AfterFuze then doMutate() end CurrentHighFuzedScore2=Score() -- New 11/2/2015 print("Done. 2d best Fuzed Score= "..round3(CurrentHighFuzedScore2)) end SaveBest() end --selecting the best of the 2 fuzes if CurrentHighFuzedScore> CurrentHighFuzedScore2-0.0001 then -- even if case there is no second best save.Quickload(tempFuzeSlot) CurrentHighScore=CurrentHighFuzedScore else save.Quickload(tempFuzeSlot2) CurrentHighScore=CurrentHighFuzedScore2 end else -- not fuzed end -- end of the fuze part else save.Quickload(PreferredScoreSlot) -- if there was no rebuild, take the absolute best score end save.Quicksave(CurrentHigh) -- keeping it for GAB, 22/8/2017 -- hopefully I have here the CurrentHighFuzedScore score (otherwise, check by adding a score computing) --NOW we have the best "after rebuild" (and Fuze) solution. -- save.Quickload(PreferredScoreSlot) -- sorry, mistake here before 22/8/2017 --improvedscore is from lated saveBest, but we idealize from the latest rebuild if improvedscore or structure.GetSecondaryStructure(s)=="L" or NOREBUILDMODE then -- doing these options only if loop or score is high enough if IDEALCHECK then -- BK 08/03/2014, I think it can be interesting with big SS (like on an entire helix) IdealAndMore("Ideality",s,e) -- test with ideality CurrentScore= Score() if CurrentScore > CurrentHighScore then -- a local savebest CurrentHighScore=CurrentScore save.Quicksave(CurrentHigh) SaveBest() -- for archiving end save.Quickload(CurrentHigh) -- sinon on rebuild le suivant avec le score d'idealize !! end -- we are still on the temporal best "after rebuild and all" score. if IDEALCHECK then -- Remixing local sz=e-s+1 if sz>3 and sz<12 then if ReMix(s,e,number_of_remix) then -- false if no remix found print("Remixing "..s.."-"..e) -- ToDo: check which type of score this is (other?) and adapt scores CurrentScore= Score() if CurrentScore > CurrentHighScore then -- a local savebest CurrentHighScore=CurrentScore save.Quicksave(CurrentHigh) SaveBest() -- for archiving end save.Quickload(CurrentHigh) -- sinon on rebuild le suivant avec le score de remix !! SelectAround(s,e,12) --local wiggle after (shake is already done inside) structure.WiggleSelected ( 25 ) CurrentScore= Score() if CurrentScore > CurrentHighScore then -- a local savebest CurrentHighScore=CurrentScore save.Quicksave(CurrentHigh) SaveBest() -- for archiving end save.Quickload(CurrentHigh) -- sinon on rebuild le suivant avec le score de remix !! end end end -- we are still on the temporal best "after rebuild and all" score. if CUTWORST and s+1 < e then -- new 1/5/2015, 14/1/2017 (don't cut len 2) cut(s+1) print("Cutting seg "..s+1) structure.WiggleAll ( 25 ) uncut(s+1) recentbest.Save() -- NEW 23/11/2015 important to avoid recentbest in cut bug structure.WiggleAll ( 25 ) recentbest.Restore() -- IMPORTANT: recentbest must be saved after deleting cut CurrentScore= Score() if CurrentScore > CurrentHighScore then -- a local savebest CurrentHighScore=CurrentScore save.Quicksave(CurrentHigh) SaveBest() -- for archiving end save.Quickload(CurrentHigh) -- sinon on rebuild le suivant avec le score de remix !! end end -- we are still on the temporal best "after rebuild and all" score. --GAB section 19/10/2016 if ss1-CurrentHighScore < GABfilter and CurrentHighScore-ss1< GABfilterHigh then -- 5/8/2015 no gab if big gain or loss ENOUGHFORGAB=true LaunchGab(s,e) -- will do it including bands to same worst areas, starting from this solution SaveBest() else print("Out of range => skipping GAB") end --SaveBest() save.Quickload(PreferredScoreSlot) end --skip section if savebridges then if BridgesBroken() then -- THIS SHOULD NOT HAPPEN print("Unexpected bridge broken, pls report\n") print("Restoring a good position, discarding wins\n") Bridgerestore() save.Quicksave(PreferredScoreSlot) PreferedScore=Score() else Bridgerestore() end else Bridgerestore() end if ss1+0.00001 < Score() then print("Finally gained from slots: ",CurrentAll) end AddDone(s,e) ChkDoneList() SaveBest() -- New 1/6/2015 not sure it's useful save.Quickload(PreferredScoreSlot) -- NEW 5/12/2014, sinon on rebuild le suivant avec le score avant gab? local currentscore= Score(current, true) drg= currentscore-StartEbolaScore -- (preferred) deep rebuild gain local absoluteGain=bestScore-StartEbolaScore print("<<>>Total Ebola gain: "..round3(drg).." ("..round3(absoluteGain).."). Score from "..round3(StartEbolaScore).." to "..round3(currentscore).." ("..round3(bestScore)..")") drg4compare= currentscore-StartEbolaScoreLater if drg4compare > minGain then StartEbolaScoreLater= currentscore break end -- recalculate worst, force new round end ENOUGHFORGAB2=false if drg4compare > 70-GABfilter then ENOUGHFORGAB2=true end -- note that we reserve full GAB for occasions where there was big gain or small losses print("DeepRebuildGAB gain: "..round3(Score()-ss)) if struct==false and SAVEDstructs then save.LoadSecondaryStructure() end end -- This is the MAIN DRW genEbola= 0 function DR_GAB() genEbola=genEbola+1 PrintAreas() if ProtectBest>0 then ProtectBestSegs(SegmentScores, ProtectBest) end DeepRebuild() -- GAB is included on each loop here if ENOUGHFORGAB2 then LaunchGab() SaveBest() end-- overall GAB at each cycle with all worst areas I think if ProtectBest>0 then UnProtectBestSegs() end SaveBigSteps() -- for movie at the end StatusGen(genEbola) -- printing for jeff101 end function DRcall(how) print("How: "..how) if how=="drw" then local stepsize=1 if minLen>maxLen then stepsize= -1 end for i=minLen,maxLen,stepsize do --search from minl to maxl worst segments lengthZ=i --if longfirst then lengthZ=maxLen-i+minLen end FindWorst(true) --fill areas table. Comment it if you have set them by hand DR_GAB() end elseif how=="fj" then --DRW lengthZ cutted on pieces FindWorst(true) --add to areas table worst part areas2={} for a=1,#areas do local s=areas[a] --{ss,se} local ss=s[1] --start segment of worst area local se=s[2] --end segment of worst area for i=ss,se do for x=1,lengthZ do if i+x<=se then areas2[#areas2+1]={i,i+x} end end end end areas=areas2 DR_GAB() elseif how=="all" then areas={} for i=minLen,maxLen do for x=1,segCnt2 do if i+x-1<=segCnt2 then areas[#areas+1]={x,x+i-1} end end end DR_GAB() elseif how=="simple" then FindWorst(true) DR_GAB() elseif how=="areas" then areas={} FindAreas() DR_GAB() end end function AskMoreOptions() local ask=dialog.CreateDialog("More DRW-Ebola options") ask.l1=dialog.AddLabel("Clear skip list if gain is more") ask.revlist=dialog.AddSlider("Cleargain:",clrdonelistgain,0,500,0) --ask.l2=dialog.AddLabel("Number of rebuilds each pass") ask.nrrebuilds=dialog.AddSlider("#Rebuilds:",rebuilds,0,100,0) --ask.l3=dialog.AddLabel("Number of full cycles") ask.nrcycles=dialog.AddSlider("#Cycles:",maxnrofRuns,1,1000,0) ask.l3a=dialog.AddLabel("Start Auto Pilot after:") ask.HoursResetOptions=dialog.AddSlider("#hours ",HoursResetOptions,1,240,0) ask.l4=dialog.AddLabel("Skip first worst parts (crash resume)") ask.nrskip=dialog.AddSlider("Skip parts:",nrskip,0,down(segCnt2/2),0) ask.reBuild=dialog.AddSlider("#wrst in 1st cycle:",reBuild,1,segCnt2,0) ask.reBuildm=dialog.AddSlider("#add each cycle:",reBuildmore,0,10,0) ask.IDEALCHECK=dialog.AddCheckbox("Idealize & remix",IDEALCHECK) -- 08/03/2014 ask.CUTWORST=dialog.AddCheckbox("cut in worst",CUTWORST) -- 1/5/2015 --ask.longfirst=dialog.AddCheckbox("Longest rebuild first",longfirst) ask.doSpecial=dialog.AddCheckbox("Local cleanup after rebuild SLOW",doSpecial) ask.doShake=dialog.AddCheckbox("Or Shake after rebuild",doShake) ask.shakeCI=dialog.AddSlider("Shake CI:",shakeCI,0,1,2) ask.bandflip=dialog.AddCheckbox("Disable bands during rebuild AND enable after",bandflip) ask.skipqstab=dialog.AddCheckbox("Local shake instead of Qstab",skipqstab) ask.skipfuze=dialog.AddCheckbox("Skip Fuze",skipfuze) ask.l5=dialog.AddLabel("------Launching GAB after rebuilds------") ask.GABfilter=dialog.AddSlider("GAB, loss filter", GABfilter, -10, 50, 0) -- New for ebola ask.GABfilterHigh=dialog.AddSlider("GAB, gain filter", GABfilterHigh, 0, 900, 0) -- New for ebola ask.SkipGAB=dialog.AddCheckbox("Do not launch GAB",SkipGAB) ask.OK = dialog.AddButton("OK",1) dialog.Show(ask) clrdonelistgain=ChangedOptions("clrdonelistgain",clrdonelistgain,ask.revlist.value) --clrdonelistgain=ask.revlist.value rebuilds=ChangedOptions("rebuilds",rebuilds,ask.nrrebuilds.value) if rebuilds == 0 then NOREBUILDMODE= true end -- onlyGAB= true maxnrofRuns=ChangedOptions("maxnrofRuns",maxnrofRuns,ask.nrcycles.value) HoursResetOptions=ChangedOptions("HoursResetOptions",HoursResetOptions,ask.HoursResetOptions.value) nrskip=ChangedOptions("nrskip",nrskip,ask.nrskip.value) reBuild=ChangedOptions("reBuild",reBuild,ask.reBuild.value) reBuildmore=ChangedOptions("reBuildmore",reBuildmore,ask.reBuildm.value) IDEALCHECK=ChangedOptions("IDEALCHECK",IDEALCHECK,ask.IDEALCHECK.value) CUTWORST=ChangedOptions("CUTWORST",CUTWORST,ask.CUTWORST.value) --ChangedOptions("longfirst",longfirst,ask.longfirst.value) doShake=ChangedOptions("doShake",doShake,ask.doShake.value) doSpecial=ChangedOptions("doSpecial",doSpecial,ask.doSpecial.value) shakeCI=ChangedOptions("shakeCI",shakeCI,ask.shakeCI.value) bandflip=ChangedOptions("bandflip",bandflip,ask.bandflip.value) skipqstab=ChangedOptions("skipqstab",skipqstab,ask.skipqstab.value) skipfuze=ChangedOptions("skipfuze",skipfuze,ask.skipfuze.value) GABfilter=ChangedOptions("GABfilter",GABfilter,ask.GABfilter.value) GABfilterHigh=ChangedOptions("GABfilterHigh",GABfilterHigh,ask.GABfilterHigh.value) SkipGAB=ChangedOptions("SkipGAB",SkipGAB,ask.SkipGAB.value) end AfterRB=false InQstab=false AfterQstab=false BeFuze=false AfterFuze=false MutateCI=0.9 MutSphere=8 MUTRB=false MUTSur=false FILTERPROTECT=false -- true=no filter loss allowed on mutate if HASMUTABLE then -- note that the default is many mutates ! Slow ! AfterQstab=true AfterFuze=true MUTSur=true end function AskMutateOptions() local ask = dialog.CreateDialog("Mutate Options") ask.AfterRB = dialog.AddCheckbox("Mutate after rebuild",AfterRB) ask.InQstab = dialog.AddCheckbox("Mutate during Qstab",InQstab) ask.AfterQstab = dialog.AddCheckbox("Mutate after Qstab",AfterQstab) ask.BeFuze = dialog.AddCheckbox("Mutate before Fuze",BeFuze) ask.AfterFuze = dialog.AddCheckbox("Mutate after Fuze",AfterFuze) ask.l1=dialog.AddLabel("-----What to rebuild or all") ask.OnlyRB=dialog.AddCheckbox("Mutate only rebuild part",MUTRB) ask.OnlySur=dialog.AddCheckbox("Mutate rebuild and surround",MUTSur) ask.l2=dialog.AddLabel("Sphere size to use with surround") ask.SurSize=dialog.AddSlider("Sphere:",MutSphere,3,15,0) ask.MutateCI=dialog.AddSlider("MutateCI:",MutateCI,0.1,1,2) ask.l3=dialog.AddLabel("Use workaround if Layer filter is active") ask.Layer=dialog.AddCheckbox("Mutate 1 by 1",LAYERFILTER) ask.FILTERPROTECT=dialog.AddCheckbox("Protect filter bonus",FILTERPROTECT) -- true=no filter loss allowed on mutate ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) if dialog.Show(ask) > 0 then AfterRB=ChangedOptions("AfterRB",AfterRB,ask.AfterRB.value) InQstab=ChangedOptions("InQstab",InQstab,ask.InQstab.value) AfterQstab=ChangedOptions("AfterQstab",AfterQstab,ask.AfterQstab.value) BeFuze=ChangedOptions("BeFuze",BeFuze,ask.BeFuze.value) AfterFuze=ChangedOptions("AfterFuze",AfterFuze,ask.AfterFuze.value) MutateCI=ChangedOptions("MutateCI",MutateCI,ask.MutateCI.value) MutSphere=ChangedOptions("MutSphere",MutSphere,ask.SurSize.value) MUTRB=ChangedOptions("MUTRB",MUTRB,ask.OnlyRB.value) MUTSur=ChangedOptions("MUTSur",MUTSur,ask.OnlySur.value) LAYERFILTER=ChangedOptions("LAYERFILTER",LAYERFILTER,ask.Layer.value) FILTERPROTECT=ChangedOptions("FILTERPROTECT",FILTERPROTECT,ask.FILTERPROTECT.value) end end function printOptions(title) print(title) print("Based on rav4pl DRW 3.4") print("Length of rebuilds: "..minLen.." until "..maxLen) print("Rebuild area: "..SegmentSetToString(WORKON)) if AfterRB then print("Mutates after each rebuild") end if InQstab then print("Mutates inside qStab") end if AfterQstab then print("Mutates after qStab") end if BeFuze then print("Mutates before Fuzing") end if AfterFuze then print("Mutates after Fuzing") end print("Nr of rebuilds each try: "..rebuilds) if not struct then print("Convert everything to loops") end if not donotrevisit then print("Will retry already tried rebuilds") else print("Clear retry blocks if gain raises above "..clrdonelistgain.." pts") end if doSpecial then print("Local cleanup after rebuild") elseif doShake then print("Initial shake after rebuild".."with CI="..shakeCI) end if skipqstab then print("Local shake instead of qStab") end if skipfuze then print("Skipping Fuzes") end print("Nr of full cycles: "..maxnrofRuns) if nrskip > 0 then print("SKIPPING "..nrskip.." worst zones") end end -- Module AskSelections -- 02-05-2012 Timo van der Laan, Free to use for non commercial purposes function AskForSelections(title,mode) -- to do: archive changed values local result={{1,segCnt}} -- All segments if mode == nil then mode={} end if mode.askloops==nil then mode.askloops=true end if mode.asksheets==nil then mode.asksheets=true end if mode.askhelixes==nil then mode.askhelixes=true end if mode.askligands==nil then mode.askligands=false end if mode.askselected==nil then mode.askselected=true end if mode.asknonselected==nil then mode.asknonselected=true end if mode.askmutateonly==nil then mode.askmutateonly=true end if mode.askignorelocks==nil then mode.askignorelocks=true end if mode.askignorefrozen==nil then mode.askignorefrozen=true end if mode.askranges==nil then mode.askranges=true end if mode.defloops==nil then mode.defloops=true end if mode.defsheets==nil then mode.defsheets=true end if mode.defhelixes==nil then mode.defhelixes=true end if mode.defligands==nil then mode.defligands=false end if mode.defselected==nil then mode.defselected=false end if mode.defnonselected==nil then mode.defnonselected=false end if mode.defmutateonly==nil then mode.defmutateonly=false end if mode.defignorelocks==nil then mode.defignorelocks=false end if mode.defignorefrozen==nil then mode.defignorefrozen=false end local Errfound=false repeat local ask = dialog.CreateDialog(title) if Errfound then ask.E1=dialog.AddLabel("Try again, ERRORS found, check output box") result={{1,segCnt}} --reset start Errfound=false end if mode.askloops then ask.loops = dialog.AddCheckbox("Work on loops",mode.defloops) elseif not mode.defloops then ask.noloops= dialog.AddLabel("Loops will be auto excluded") end if mode.askhelixes then ask.helixes = dialog.AddCheckbox("Work on helixes",mode.defhelixes) elseif not mode.defhelixes then ask.nohelixes= dialog.AddLabel("Helixes will be auto excluded") end if mode.asksheets then ask.sheets = dialog.AddCheckbox("Work on sheets",mode.defsheets) elseif not mode.defsheets then ask.nosheets= dialog.AddLabel("Sheets will be auto excluded") end if mode.askligands then ask.ligands = dialog.AddCheckbox("Work on ligands",mode.defligands) elseif not mode.defligands then ask.noligands= dialog.AddLabel("Ligands will be auto excluded") end if mode.askselected then ask.selected = dialog.AddCheckbox("Work only on selected",mode.defselected) end if mode.asknonselected then ask.nonselected = dialog.AddCheckbox("Work only on nonselected",mode.defnonselected) end if mode.askmutateonly then ask.mutateonly = dialog.AddCheckbox("Work only on mutateonly",mode.defmutateonly) end if mode.askignorelocks then ask.ignorelocks =dialog.AddCheckbox("Dont work on locked ones",true) elseif mode.defignorelocks then ask.nolocks=dialog.AddLabel("Locked ones will be auto excluded") end if mode.askignorefrozen then ask.ignorefrozen = dialog.AddCheckbox("Dont work on frozen",true) elseif mode.defignorefrozen then ask.nofrozen=dialog.AddLabel("Frozen ones will be auto excluded") end if mode.askranges then ask.R1=dialog.AddLabel("Or put in segmentranges. Above selections also count") ask.ranges=dialog.AddTextbox("Ranges","1-"..segCnt) end ask.designProtect=dialog.AddCheckbox("Freeze other backbones for design protection",designProtect) ask.ProtectBest=dialog.AddSlider("Don't work on best:",ProtectBest,0,segCnt,0) ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) if dialog.Show(ask) > 0 then -- We start with all the segments including ligands if mode.askloops then mode.defloops=ask.loops.value end if not mode.defloops then result=SegmentSetMinus(result,FindAAtype("L")) end if mode.asksheets then mode.defsheets=ask.sheets.value end if not mode.defsheets then result=SegmentSetMinus(result,FindAAtype("E")) end if mode.askhelixes then mode.defhelixes=ask.helixes.value end if not mode.defhelixes then result=SegmentSetMinus(result,FindAAtype("H")) end if mode.askligands then mode.defligands=ask.ligands.value end if not mode.defligands then result=SegmentSetMinus(result,FindAAtype("M")) end if mode.askignorelocks then mode.defignorelocks=ask.ignorelocks.value end if mode.defignorelocks then result=SegmentSetMinus(result,FindLocked()) end if mode.askignorefrozen then mode.defignorefrozen=ask.ignorefrozen.value end if mode.defignorefrozen then result=SegmentSetMinus(result,FindFrozen()) end if mode.askselected then mode.defselected=ask.selected.value end if mode.defselected then result=SegmentCommSet(result,FindSelected()) end if mode.asknonselected then mode.defnonselected=ask.nonselected.value end if mode.defnonselected then result=SegmentCommSet(result,SegmentInvertSet(FindSelected())) end if mode.askranges and ask.ranges.value ~= "" then local rangetext=ask.ranges.value local function Checknums(nums) -- Now checking if #nums%2 ~= 0 then print("Not an even number of segments found") return false end for i=1,#nums do if nums[i]==0 or nums[i]>segCnt then print("Number "..nums[i].." is not a segment") return false end end return true end local function ReadSegmentSet(data) local nums = {} local NoNegatives='%d+' -- - is not part of a number local result={} for v in string.gfind(data,NoNegatives) do table.insert(nums, tonumber(v)) end if Checknums(nums) then for i=1,#nums/2 do result[i]={nums[2*i-1],nums[2*i]} end result=SegmentCleanSet(result) else Errfound=true result={} end return result end local rangelist=ReadSegmentSet(rangetext) if not Errfound then result=SegmentCommSet(result,rangelist) end end designProtect=ask.designProtect.value -- new BK ProtectBest=ask.ProtectBest.value end until not Errfound return result end -- end of module AskSelections WORKON={{1,segCnt2}} --Start of module protect design FREEZEPROTECT={} designProtect=false -- true avoids macro destructuring function ProtectDesign(NOTWORKON) if designProtect then print("Freezing unused backbones") for i= 1, #NOTWORKON do for seg=NOTWORKON[i][1], NOTWORKON[i][2] do if not freeze.IsFrozen(seg) then freeze.Freeze(seg, true, false) -- only backbone FREEZEPROTECT[#FREEZEPROTECT+1]=seg -- a list end end end end end function UnProtectDesign(FREEZEPROTECT) if designProtect then print("Unfreezing unused backbones") for i= 1, #FREEZEPROTECT do freeze.Unfreeze(FREEZEPROTECT[i][1], true, false) -- only backbone end end end --End of module protect design --ScoreFilterPart=false function AskSubScores() -- slot selection after rebuild local ask = dialog.CreateDialog("Slot selection DRW "..DRWVersion) ask.l1=dialog.AddLabel("Specify which slots based on scorepart to use") for i=1,#ScoreParts do ask[ScoreParts[i][2]]=dialog.AddCheckbox(ScoreParts[i][1].." "..ScoreParts[i][2],ScoreParts[i][3]) end if FILTERS and ScorePriority ==1 then -- BK 2/6/2015 --ask.ScoreFilterPart=dialog.AddCheckbox("Filters",FILTERS) --ask.FiltersFirst=dialog.AddCheckbox("Priority to filters over score",FiltersFirst) -- duplicate ask.l2=dialog.AddLabel("Filter priority grade") ask.l2b=dialog.AddLabel("Lost points allowed per pt filter gain:") ask.LostpFgain=dialog.AddSlider("Multiplier:",LostpFgain,0,100,0) ask.l2c=dialog.AddLabel("Score priority grade") ask.l2d=dialog.AddLabel("Lost filter allowed per 10 points gain:") ask.LostFpgain=dialog.AddSlider("Multiplier:",LostFpgain,0,100,0) end if PROBABLEFILTER then ask.FILTERMANAGE = dialog.AddCheckbox ( "Disable filter during wiggle (fast)" , FILTERMANAGE ) ask.GENERICFILTER = dialog.AddCheckbox ( "Always disable filter unless for score (turbo)" , GENERICFILTER ) end ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) if dialog.Show(ask) > 0 then for i=1,#ScoreParts do ScoreParts[i][3]=ChangedOptions(ScoreParts[i][2].." slot ",ScoreParts[i][3],ask[ScoreParts[i][2]].value) end if FILTERS and ScorePriority ==1 then -- BK 2/6/2015 --ScoreFilterPart=ask.ScoreFilterPart.value --FiltersFirst=ask.FiltersFirst.value -- duplicate LostpFgain=ChangedOptions("LostpFgain",LostpFgain,ask.LostpFgain.value) FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) end if PROBABLEFILTER then FILTERMANAGE=ChangedOptions("FILTERMANAGE",FILTERMANAGE,ask.FILTERMANAGE.value) GENERICFILTER=ChangedOptions("GENERICFILTER",GENERICFILTER,ask.GENERICFILTER.value) end end end -- NOT USED YET, it's implicit in above selection function AskFilterScores() -- user defined filter selection NEW BK 10/2/2015 local ask = dialog.CreateDialog("User filter selection ") ask.l1=dialog.AddLabel("Specify which own filters based on scorepart to use") for i=1,#ScoreParts do ask[ScoreParts[i][2]]=dialog.AddCheckbox(ScoreParts[i][1].." "..ScoreParts[i][2],ScoreParts[i][3]) end if FILTERS then --ask.ScoreFilterPart=dialog.AddCheckbox("Filters",FILTERS) --ask.FiltersFirst=dialog.AddCheckbox("Priority to filters over score",FiltersFirst) -- duplicate ask.l2=dialog.AddLabel("Filter priority grade") ask.l2b=dialog.AddLabel("Lost points allowed per pt filter gain:") ask.LostpFgain=dialog.AddSlider("Multiplier:",LostpFgain,0,100,0) ask.l2c=dialog.AddLabel("Score priority grade") ask.l2d=dialog.AddLabel("Lost filter allowed per 10 points gain:") ask.LostFpgain=dialog.AddSlider("Multiplier:",LostFpgain,0,100,0) end if PROBABLEFILTER then ask.FILTERMANAGE = dialog.AddCheckbox ( "Disable filter during wiggle (fast)" , FILTERMANAGE ) ask.GENERICFILTER = dialog.AddCheckbox ( "Always disable filter unless for score (turbo)" , GENERICFILTER ) end ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) if dialog.Show(ask) > 0 then for i=1,#ScoreParts do ScoreParts[i][3]=ask[ScoreParts[i][2]].value end if FILTERS then -- new BK 11/11/2014 --ScoreFilterPart=ask.ScoreFilterPart.value --FiltersFirst=ask.FiltersFirst.value -- duplicate LostpFgain=ask.LostpFgain.value FiltersFirst=LostpFgain>-2 -- always !!!(depends only on the cost we admit: -1 being default no cost) end if PROBABLEFILTER then FILTERMANAGE=ask.FILTERMANAGE.value GENERICFILTER=ask.GENERICFILTER.value end end end function AskSelScores() -- selecting worst subscores - Will be default all unless if we check something in this dialog local ask = dialog.CreateDialog("Set worst searching DRW "..DRWVersion) ask.l1=dialog.AddLabel("Specify which worst subscoretotal(s) to count") if FILTERS then for i=3,#ScoreParts-1 do -- impossible to select worst filter or total on segments ! ask[ScoreParts[i][2]]=dialog.AddCheckbox(ScoreParts[i][2],false) end else for i=3,#ScoreParts do ask[ScoreParts[i][2]]=dialog.AddCheckbox(ScoreParts[i][2],false) end end ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) scrPart={} if dialog.Show(ask) > 0 then local limit=3 if FILTERS then limit = #ScoreParts-1 else limit = #ScoreParts end for i=3,limit do if ask[ScoreParts[i][2]].value then scrPart[#scrPart+1]=ChangedOptions("subscore","Backbone",ScoreParts[i][2]) end end end end function AskDRWOptions() local askresult local askmutable=HASMUTABLE local ask = dialog.CreateDialog(recipename.." tvdl DRW options") --local velocity=3 -- normal options default local Duration=12 if askmutable then print("Setting default mutate options") AfterQstab=true AfterFuze=true MutSur=true end repeat --ask.l7 = dialog.AddLabel("Time needed with current options: about".. Duration.." hours") --ask.l8 = dialog.AddLabel("Reset options wizard, from 1 fast to 5 slow:") --ask.reset=dialog.AddCheckbox("Reset options wizard, from 1 fast to 5 slow:",false) --ask.velocity = dialog.AddSlider("Reset options:",velocity,1,5,0) --ask.l9 = dialog.AddLabel("OR -------- Fine tuning of options: --------") ask.l1 = dialog.AddLabel("Length to rebuild, From can be bigger than To") ask.minLen = dialog.AddSlider("From:",minLen,1,maxLenLimit,0) --ask.l2 = dialog.AddLabel("Maximum length to rebuild") ask.maxLen = dialog.AddSlider("To:",maxLen,1,maxLenLimit,0) ask.l3 = dialog.AddLabel("Force next round if gain is more than") -- recalculate worst ask.minGain = dialog.AddSlider("MinGain:",minGain,0,500,0) ask.fastQstab=dialog.AddCheckbox("Do a fast qStab",fastQstab) ask.l4 = dialog.AddLabel("Skip fuze if loss is more") ask.l5 = dialog.AddLabel("Threshold used is RBlength*threshold/3") ask.maxLoss = dialog.AddSlider("Skip fuze:",maxlossbeforefuze,-5,200,0) ask.donotrevisit = dialog.AddCheckbox("Do not things twice",donotrevisit) ask.SEL= dialog.AddCheckbox("(Re)select where to work on ",false) if HASMUTABLE then ask.MUTS = dialog.AddCheckbox("(Re)set Mutate Options",askmutable) end ask.selSP= dialog.AddCheckbox("(Re)select slots",false) ask.worst= dialog.AddCheckbox("(Re)set worst search params",false) if nrofbridges > 1 then ask.bridge = dialog.AddCheckbox("Keep sulfide bridges intact",savebridges) end ask.struct = dialog.AddCheckbox("Do not change all to loop",struct) ask.l6=dialog.AddLabel("Search only for disjunct from previous done") ask.disjunct=dialog.AddCheckbox("Disjunct",disjunct) ask.OK = dialog.AddButton("OK",1) ask.Cancel = dialog.AddButton("Cancel",0) ask.Options = dialog.AddButton("More",2) ask.GAB = dialog.AddButton("GAB",3) askresult=dialog.Show(ask) if askresult > 0 then minLen=ChangedOptions("minLen",minLen,ask.minLen.value) maxLen=ChangedOptions("maxLen",maxLen,ask.maxLen.value) minGain=ChangedOptions("minGain",minGain,ask.minGain.value) fastQstab=ChangedOptions("fastQstab",fastQstab,ask.fastQstab.value) maxlossbeforefuze=ChangedOptions("maxlossbeforefuze",maxlossbeforefuze,ask.maxLoss.value) donotrevisit=ChangedOptions("donotrevisit",donotrevisit,ask.donotrevisit.value) disjunct=ChangedOptions("disjunct",disjunct,ask.disjunct.value) struct=ChangedOptions("struct",struct,ask.struct.value) --[[ if velocity~=ask.velocity.value then velocity=ask.velocity.value QuickOptions(velocity) Duration= velocity * 4 if askresult==1 then askresult=4 end -- to force to return to the main menu in case of "OK" end --]] if nrofbridges > 1 then savebridges=ChangedOptions("savebridges",savebridges,ask.bridge.value) end if ask.SEL.value then local SelMode={} SelMode.askignorefrozen=false SelMode.defignorefrozen=true SelMode.askignorelocks=false SelMode.defignorelocks=true SelMode.askligands=false SelMode.defligands=false WORKON=AskForSelections("Tvdl enhanced DRW "..DRWVersion,SelMode) print("Selection is now, reselect if not oke:") print(SegmentSetToString(WORKON)) if askresult==1 then askresult=4 end --to force return to main menu end if ask.selSP.value then AskSubScores() if askresult==1 then askresult=4 end end if ask.worst.value then AskSelScores() if askresult==1 then askresult=4 end end -- Do not try to rebuild frozen or locked parts or ligands WORKON=SegmentSetMinus(WORKON,FindFrozen()) WORKON=SegmentSetMinus(WORKON,FindLocked()) WORKON=SegmentSetMinus(WORKON,FindAAtype("M")) NOTWORKON=SegmentInvertSet(WORKON) if HASMUTABLE and ask.MUTS.value then AskMutateOptions() askmutable=false if askresult==1 then askresult=4 end --to force return to main menu end if askresult==2 then AskMoreOptions() end if askresult==3 then AskGABOptions() end end until askresult < 2 return askresult > 0 end -- Quick fix for failing first rebuild for i=3,13 do save.Quicksave(i) end -- added 13 BK 11/11/2014 function Cleanup(err) print("Restoring CI, initial selection, best result and structures") CI(1) save.Quickload(PreferredScoreSlot) if SAVEDstructs then save.LoadSecondaryStructure() end selection.DeselectAll() if SAFEselection ~= nil then SetSelection(SAFEselection) end --CleanupGAB(err) print("Restoring CIGAB, best result, filter and structures") CIGAB(1) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- new BK 8/4/2013, always back to user settings MovieSteps() -- New 4/11/2014 save.Quickload(PreferredScoreSlot) MovieSteps() WhriteNote() -- New 4/11/2014 TOTALgain=Score(current, true)-DRWstartscore print(">>>>>TOTAL EBOLA GAIN (following preferences)= "..round3(TOTALgain)) print("From "..round3(DRWstartscore).." to "..round3(Score(current, true))) print("Absolute best score = "..round3(bestScore)) print("Total gain till credited score: "..round3(Score(current, true)-StartEbolaScore)) print("Absolute best filter = "..round3(bestFScore)) deletebands() print(err) end --[[ USAGE 1. 'drw' - need 'minLen' and 'maxLen'; finding worst scores by lengthZ betwen that 2 2. 'fj' - need 'lengthZ'; searching lengthZ then cutting in pieces 2->lengthZ and rebuilds pieces 3. 'all' - need 'minLen' and 'maxLen'; rebuilding ENTIRE prorein (from min to max) like in WalkinRebuild script 4. 'simple' - need 'lengthZ'; find and rebuild worst scoring parts of that lenght 5. 'areas' - need secondary structure set and 'true' on at least one of structure ]]-- ----------------- options below VVVV areas={ --start segment, end segment. use for last line call --{1,10}, --{20,30}, --{32,35}, } scrPart={} --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash importance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=true --false --if true faster stabilize reBuild=4 --up to worst parts to look at reBuildmore=1 --increased by every main cycle rebuilds=10 --how many rebuilds to try, set at least 10! (because of slots) rebuildCI=0 --clash importance while rebuild lengthZ=6 --find worst segments part minLen=3 --or specify minimum lengthZ maxLen=5 --and maximim lengthZ maxLenLimit=segCnt2 -- experimental 11/2/2015 -- New options maxnrofRuns=1000 -- Set it very high if you want to run forever Runnr=0 minGain=(segCnt2-segCnt2%4)/4 -- If less gain then try the next one, else recompute if minGain < 40 then minGain=40 end --longfirst=false --true -- Reverse the search, long ones first skipqstab=false skipfuze=false ExistingBands=band.GetCount() bandflip=ExistingBands > 0 -- true if user bands exist userbandenabled= false if bandflip and band.IsEnabled(1) then -- enabled bands will always be re-enabled on default !! --bandflip=false userbandenabled= true end maxlossbeforefuze=(segCnt2-segCnt2%4)/4 -- if loss is more no fuze is done if maxlossbeforefuze < 30 then maxlossbeforefuze=30 end nrskip=0 DRWVersion="2.5.1 beta BK" --2.5.1. added cut worst -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ -- MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ MAIN PROGRAM ++++ firstDRWcall=true DRWstartscore=0 HoursResetOptions= 24 -- number of hours after which to reset options (out of context options)= Auto Pilot function DRW() local scoreNow= Score() local formerScore=scoreNow local StarTime= os.time() -- initialized DRWstartscore=scoreNow gaingen=round3(DRWstartscore) -- list of gain each generation, for jeff101 if firstDRWcall then printOptions("Tvdl enhanced DRW "..DRWVersion) print("###################################") print("OK you can go away ! No more dialog !") firstDRWcall=false if GENERICFILTER then print("Always disabling filter unless for scoring") MutClass(structure, false) MutClass(band, true) -- for unideal loop bug MutClass(current, true) MutClass(recentbest, true) -- otherwise, it remembers cut solutions MutClass(save, true) -- better to save with full score FIRSTGENERICFILTER=true else print("No generic filter disabling") --MutClass(structure, true) --MutClass(band, true) --MutClass(current, true) --MutClass(recentbest, true) -- otherwise, it remembers cut solutions --MutClass(save, true) -- better to save with full score end else if GENERICFILTER then print("Always disabling filter unless for scoring") MutClass(structure, false) MutClass(band, true) MutClass(current, true) MutClass(recentbest, true) -- otherwise, it remembers cut solutions MutClass(save, true) -- better to save with full score FIRSTGENERICFILTER=true elseif FIRSTGENERICFILTER then -- case disabling this on the fly (experimental, not tested) print("No generic filter disabling") MutClass(structure, true) MutClass(band, true) MutClass(current, true) MutClass(recentbest, true) -- otherwise, it remembers cut solutions MutClass(save, true) -- better to save with full score end end InitWORKONbool() if nrskip > 0 then -- if skipping since start, we do a first round with this rebuild number local sreBuild=reBuild reBuild=nrskip Runnr=0 print("Ebola Init cycle") DRcall("drw") reBuild=sreBuild end for nrofRuns=1,maxnrofRuns do --uncomment method/s you want to use It STARTS HERE>>>>>>>>>> if not SKETCHBOOK then undo.SetUndo(false) -- reset after each loop end Runnr=nrofRuns -- global to be able to use it in log print("###########################") print("Main Ebola cycle nr ",nrofRuns) -- TO DO: change settings each round if nrofRuns < 3 then DRcall("drw") elseif nrofRuns < 5 then DRcall("areas") elseif nrofRuns < 7 then DRcall("fj") elseif nrofRuns < 8 then DRcall("simple") elseif nrofRuns == 8 then DRcall("all") elseif nrofRuns > 8 then DRcall("drw") else DRcall("simple") end -- DRcall("areas") -- DRcall("drw") -- DRcall("fj") -- DRcall("all") -- DRcall("simple") undo.SetUndo(defUndo) save.Quickload(PreferredScoreSlot) ChkDoneList() reBuild=reBuild+reBuildmore WhriteNote() -- FILTERS=FindActiveFilter() -- just in case we would discover a filter on the fly if HoursRun(StartTime) > HoursResetOptions then -- changing options every day for very long run StarTime= os.time() -- reinitialized ContextualOptions() end end end -- Change defaults if the startscore is negative if StartEbolaScore < 4000 then local adjust=true if HASDENSITY then if FILTERMANAGE then FiltersOff() end local oscore=GetSubscore("density") if StartEbolaScore-oscore*(DENSITYWEIGHT+1) > 4000 then adjust=false print("ED puzzle, score high enough not counting ED") print("so no auto blocking of qstab and fuze") end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end end if adjust then print("Score < 4000, adjusting defaults") print("Now skipping Fuzes, replacing qStab") print("Can be changed in More options") skipfuze=true skipqstab=true end end SAFEselection=FindSelected() --eDRW END ############################################################ --GABcut START ######################################################## --[[ GAB - Genetic Algorythm on Bands by Rav3n_pl based on CartoonVillan and Crashguard303 scripts Lua V2 Definitions: band: randomised: start segment, end segment, length, strength critter: set of bands herd: set of critters 1. - randomize needed bands - randomly assignig them to criters 2. - score each critter 3. - keep critters scoring above score - breed best critters - breed bastards (best one + random one) - forget about rest of critter - randomize new critters to fill herd VERSIONS: 2.0.5 2.0.5 Filter => Filter management added Bruno Kestemont 10/10/2013 16/04/2014: only added more score info in the log 3.0 : fuze using cuts 28/05/2014 Bruno Kestemont 3.1: cut bug fixed on deletecut 02/06/2014 3.2: using creditebest 3.3: creditbest bug fixed 02/06/2014 (do not use creditebest) 3.3.1: added Notes management and quicksaves for big gains (for archives when undo's) 4/11/2014 3.3.2: replaced shake by QuickShake 8/11/2014 ]]-- recipename2="Rav3n_pl GAB 3.3.1 filter Cuts BK" -- + added use ligands and BIS -- options: energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 1 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 1 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = true --use ligand if true AlwUseLigand= false -- GAB always band to ligand if true else useLigand = false --use ligand if true AlwUseLigand= false end onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = false --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes freqbis = 0.1 -- frequency of Band In Space --cut=structure.InsertCut -- 28/05/2014 allowcut=false -- cuts in GAB and fuze using cuts --uncut=structure.DeleteCut -- 28/05/2014 --SLOTS: --[[ 3 is best 4 used in recipe 5 used in recipe 30-49 used to record each big steps for movie at the end ]]-- SlotStepStart=30 -- New 4/11/2014 SlotStepMax=49 SlotStep=SlotStepStart herd= --herd options { breedBest = 5, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 3, --save up to 3 best scoring critters, rest are forgotten breedBastards = 8, --number of best will have one random bastard firstGen = 10, -- number of herds on first generation newRandom = 4, --adding new random ones each generation maxGen= 3, --maximum generations shuffle = true, --set true to run critters in random order renew=2, --create totally fresh herd after that many gens w/o improvement maxBadGen=2, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=2, --minimum bands maxBands=7, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -20, --will breed kids only if score higher. Basttards always breed maxLoss=30, --maximum loss by critter. set 0 to disable } bands= --bands options { minStr=0.3, --minimum band str maxStr=1.1, --maximum band str minChng = 3, -- minimum change of band length, so the range will be [3;6.1] or [-6.9;-3] maxUpBIS = 12.1, -- maximum band lenght minUpBIS = 0.1, -- debugging case=0 maxUp = 6.1, -- maximum length change up (push) maxDn = 6.9, -- maximum length change down (pull) minSkip = 5, --minimum segment distance minDist = 4, --minimum spatial distance minLen = 2, --minimum length of created band } DoNotUse={--just comment lines below or add more areas to avoid --{segCnt,segCnt}, --ligand cant be used --{120,134}, --{1,10}, } AlwaysUse={ --areas should be always used --{segCnt,segCnt},--ligand need to be at one end --{308,311}, --loopy --{272,319}, --loopy } UseSegments= --use ONLY this segments for random select of bands { --2,3,4,5 } -- bands by secondary structure use= { Sheet=true, --set false to not band sheets Helix=true, --set false to not band helices Loop=true, --set false to not band loops } checkBoth=false --check both ends to above, if false only one end need to be true --end of options segCntGAB=segCnt -- DUPLICATE DRW math.randomseed(os.clock()) -- 28/05/2014 math.random() -- 28/05/2014 --[[ if useLigand==false then while structure.GetSecondaryStructure(segCntGAB)=="M" do segCntGAB=segCntGAB-1 end end ]]-- --p=print function cut(seg) -- 18/2/2016 if (allowcut or CUTWORST) and not freeze.IsFrozen(seg) then if seg==segCnt then seg=segCnt-1 end structure.InsertCut(seg) end -- else nothing ! end function uncut(seg) -- 18/2/2016 if (allowcut or CUTWORST) and not freeze.IsFrozen(seg) then for i=1, segCnt do structure.DeleteCut(i) end end end function CIGAB(c) if c>maxCI then c=maxCI end behavior.SetClashImportance(c) end function round(x)--cut all afer 3-rd place return x-x%0.001 end function ScoreGAB()--return score, exploration too if FILTERMANAGE then FiltersOn() end -- always disable before scoring if energy==true then return current.GetEnergyScore() else return current.GetScore() end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end end --local seed=recipe.GetRandomSeed() --NOT WORKING on windowz!!! --calculate REALLY good seed from current score seed=os.time() seed=1/seed while seed<10000000 do seed=seed*10 end seed=seed-seed%1 --int("Seed is: "..seed) math.randomseed(seed) format=string.format --START Archive in Notes, -- New 4/11/2014; 3/12/2015 added a flag for already used recipe, 24/4/216 added option archives FlagRecipeUsed=false function recipeUsed(lastnote) -- identifies if the recipe has already been used local lastnote=lastnote or "abcdefgh" if lastnote:find(recipename)~=nil then FlagRecipeUsed=true print(recipename .. " already used before") end end function SelectNote(recipename) store={} store.label=recipename or "" -- edit here the recipe name store.note_number=segCnt for seg=segCnt,1,-1 do if structure.GetNote(seg)~="" then recipeUsed(structure.GetNote(seg)) break end -- New 3/12/2015 store.note_number=seg end dr_string = "" print(string.format("Recording results in Note for segment %i",store.note_number)) print(string.format("Recording changed options in Note for segment %i",store.note_number+1)) store.starting_score=StartEbolaScore --structure.SetNote(store.note_number,string.format("(%s) %.3f + FSP",user.GetPlayerName(),store.starting_score)) end SelectNote(recipename) function WhriteNote() -- all inits are in SelectNote function structure.SetNote(store.note_number,string.format("(%s) %.3f + %s(%s) %s %.3f", user.GetPlayerName(),store.starting_score,store.label,dr_string,ChangedOptionsTxt,Score())) end --END Archive in Notes --START quick save algorithm function QuickShake() --[[------------------------------------------------------------------------------------------------ -- Algorithm for faster shake REFERENCES 1. N/A Copyright (C) 2014 Seagat2011 <http://fold.it/port/user/1992490> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. $Id$ ------------------------------------------------------------------------------------------------]]-- --[[ v1 - Inception 1.2 - Loops until nogain ]]-- local idx = 1 local idx2 = structure.GetCount () local hash = {} local cs = Score () --print ( 'Quick Shake Algorithm v1.2 SG2011 - Current Score: '..cs ) local function New ( obj ) return obj -- pass-new-obj-by-value end if FILTERMANAGE then FiltersOn() end local _gses = New ( current.GetSegmentEnergySubscore ) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end local function SmartShake ( iters ) local gain = true while (gain) do gain = false for i=idx,idx2 do local ci = _gses ( i,'clashing' ) if ci < _gses ( i,'hiding' ) and ci < _gses ( i,'packing' ) and ci < _gses ( i,'ideality' ) and ci < _gses ( i,'sidechain') and ci < _gses ( i,'bonding' ) and ci < _gses ( i,'other' ) and ci < _gses ( i,'reference') then selection.Select ( i ) end -- test ci -- end -- loop -- if selection.GetCount () then local css = Score () structure.ShakeSidechainsSelected ( iters ) selection.DeselectAll () if Score () > css then gain = true end -- test -- end -- test -- end -- loopf -- end structure.SmartShake = SmartShake structure.SmartShake ( 1 ) --print ( 'Done.' ) end --END quick save algorithm function WiggleGAB(how, iters, minppi) if how==nil then how="wa" end if iters==nil then iters=6 end if minppi==nil then minppi=defminppi end if FILTERMANAGE then FiltersOff() end if iters>0 then iters=iters-1 sp=ScoreGAB() -- filter will be disabled then returned to user settings here if how == "s" then if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- new BK 8/4/2013, always back to user settings if mutateAlwas==true then structure.MutateSidechainsSelected(defiter/2) --else structure.ShakeSidechainsSelected(1) end else QuickShake() end elseif how == "wb" then structure.WiggleAll(defiter, true,false) elseif how == "ws" then structure.WiggleAll(defiter, false,true) elseif how == "wa" then structure.WiggleAll(defiter) end local ep = ScoreGAB() local ig=ep-sp if how~="s" then if ig > minppi then return WiggleGAB(how, iters, minppi) end --tail call end end if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- new BK 10/10/2013, always back to user settings end wiggleAllGAB=structure.WiggleAll -- 28/05/2014 No filter management function SaveBestGAB() local sg=ScoreGAB() local g=sg-bestScoreGAB local m=PreferedScore-sg SaveBest() -- Test 12/2/2014, only to keep track of best scores and to be able to skip this generation if TOOMUCHFILTERLOSS then print("Rejecting this critter solution (filter cost too high)") else if g>0 then if g>0.01 then if m>= 0 then print(" Recovering "..round(g).." pts, (remaining "..round(m).." pts)") else m=-m print(" Recovering "..round(g).." pts, (total extra "..round(m).." pts). Score: "..round(sg).." pts)") end end bestScoreGAB=sg save.Quicksave(BestGABslot) end end end function SaveRBGAB() if ScoreGAB()>bestScoreGAB then save.Quicksave(GABrbSlot) recentbest.Restore() -- OK only if recentbest saved after deleting cuts SaveBestGAB() save.Quickload(GABrbSlot) end end function QstabGAB() selection.SelectAll() CIGAB(0.1) if mutateOnce==true then CIGAB(mutateOnceCI) structure.MutateSidechainsSelected((defiter+1)/3) else WiggleGAB("s",1) end if fastQstab==false then CIGAB(0.4) WiggleGAB("wa",1) CIGAB(1) WiggleGAB("s",1) end CIGAB(1) WiggleGAB() end function FuzeCuts(ci1) -- 28/05/2014 by pauldunn NB: no filter management here . 02/06/2014 recentbest bug fixed local seg=math.random(segCnt) cut(seg) CIGAB(1) wiggleAllGAB(15,true,true) CIGAB(ci1) --ci(0.01) wiggleAllGAB(1,true,true) CIGAB(1) wiggleAllGAB(25,true,true) uncut(seg) recentbest.Save() -- NEW 02/06/2014 important to avoid recentbest in cut bug wiggleAllGAB(25,true,true) CIGAB(ci1) --ci(0.01) wiggleAllGAB(2,true,true) CIGAB(1) wiggleAllGAB(25,true,true) end function FuzeEndGAB() CIGAB(1) WiggleGAB("wa",1) WiggleGAB("s",1) WiggleGAB() srb() end function Fuse1GAB(ci1,ci2) CIGAB(ci1) WiggleGAB("s",1) CIGAB(ci2) WiggleGAB("wa",1) end function Fuse2GAB(ci1,ci2) CIGAB(ci1) WiggleGAB("wa",1) CIGAB(1) WiggleGAB("wa",1) CIGAB(ci2) WiggleGAB("wa",1) end function srb() recentbest.Restore() -- IMPORTANT: recentbest must be saved after deleting cut SaveBestGAB() end function scb() recentbest.Restore() -- IMPORTANT: recentbest must be saved after deleting cut SaveBestGAB() end function FuzeWithCuts() print("Fuzing with cuts...") local scr=ScoreGAB() selection.SelectAll() recentbest.Save() Fuse1GAB(0.3,0.6) FuzeEndGAB() if SKETCHBOOK then return end -- the remaining part takes too much moves for a decreasing return FuzeCuts(0.01) scb() -- NEW 28/05/2014, 02/06/2014 -- HERE WITH CUTS Fuse2GAB(0.3,1) srb() Fuse1GAB(0.05,1) srb() Fuse2GAB(0.7,0.5) FuzeEndGAB() FuzeCuts(0.1) scb() -- NEW 28/05/2014, 02/06/2014 -- HERE WITH CUTS Fuse1GAB(0.07,1) srb() end function randomGAB(n1,n2) --random function returns int or float depends on input vars if n2==nil and n1==nil then return math.random() --float 0-1 else if n2==nil then if n1%1==0 then return math.random(n1) --integer 1-n1 else return math.random()*n1 --float 0-n1 end else if n1%1==0 and n2%1==0 then return math.random(n1,n2) --integer between else return math.random()*(n2-n1)+n1 --float between, including 0 --return math.random(n1,n2) --float between BK 17/02/2015, this is also correct end end end end function FillHerd() --fill up herd (mixed BIS and BBS) local n=#critters if n>0 then --fill up n=herd.newRandom else --fresh herd if herd.maxGen~=1 and herd.firstGen<herd.keepBest then n=herd.breedBest + herd.keepBest + herd.breedBastards else n=herd.firstGen end end print("Randomizing "..n.." new critters...") for i=1,n do AddCritter() end end function AddCritter() --create new random critter (NEW also for BIS), 15/2/2016 local c={} critterID=critterID+1 c.no=critterID c.name=c.no..'-rnd' c.bands={} local r=randomGAB(critter.minBands, critter.maxBands) local probabis= randomGAB(0.0, 1.0) for i=1,r do if probabis<= freqbis then c.bands[#c.bands+1]=AddBandIS() else c.bands[#c.bands+1]=AddBand() end end critters[#critters+1]=c --print(c.name.." bands: "..#c.bands) end function AddBand() --create one random band // ONLY Bands between segments here ! local cnt=0 local b={} while true do --try till die cnt=cnt+1 local s1=randomGAB(segCntGAB) --integer 1-segCnt if onlyMutable==true or #UseSegments>0 then s1=UseSegments[randomGAB(#UseSegments)] --integer 1-UseSegments nb => s1= one of the use segments end local s2=randomGAB(segCntGAB) --integer 1-segCnt while s1==s2 do s2=randomGAB(segCntGAB) end -- to avoid band to itself New 22/12/2014 if s1>s2 then s1,s2=s2,s1 end --swap if #UseSegments>0 or CanBeUsed(s1,s2) then local str=randomGAB(bands.minStr,bands.maxStr) local increment=-1 -- was 0 but I prefer to avoid 0 in case of bug bellow while true do --randomize correct distance increment=randomGAB(-bands.maxDn,bands.maxUp) if increment<-bands.minChng or increment>bands.minChng then break end -- we stop when it's good: never 0, never [-3;3] indeed end b={s1,s2,str,increment} -- increment is the increment (negative or positive) relative to the segment distance break end if cnt>100 then print("Sorry! Cant create band!") --BreakScript() --there is no such function, so it crashes script break end end return b end function CanBeUsed(sg1,sg2) --checking end of bands // only Bands between segments here ! function ssCheck(ss) local good=false if use.Sheet and ss=="E" then good=true end if use.Helix and ss=="H" then good=true end if use.Loop and ss=="L" then good=true end return good end function AreGood(s1,s2) --check that s1 and s2 can be used local ok=true if s2==s1 then ok=false end -- to avoid a possible bug if s2-s1<bands.minSkip then ok=false end if ok==true and structure.GetDistance(s1,s2)<bands.minDist then ok=false end return ok end local ok=AreGood(sg1,sg2) if ok==true and #DoNotUse>0 then --none of 2 can be in that area for i=1, #DoNotUse do local r=DoNotUse[i] for x=r[1],r[2] do if x==sg1 or x==sg2 then ok=false break end end if ok==false then break end end end if ok==false then return false --if false can`t be used else ok=false if #AlwaysUse>0 then --at least one have to be there for i=1, #AlwaysUse do local r=AlwaysUse[i] for x=r[1],r[2] do if x==sg1 or x==sg2 then ok=true break end end if ok==true then break end end else ok=true end end if ok==true then --check structure ok=false local ss1=structure.GetSecondaryStructure(sg1) local ss2=structure.GetSecondaryStructure(sg2) if checkBoth then if ssCheck(ss1) and ssCheck(ss2) then ok=true end else if ssCheck(ss1) or ssCheck(ss2) then ok=true end end end return ok end function AddBandIS() --create one random band in space // ONLY Bands to center segment here ! local cnt=0 local b={} while true do --try till die cnt=cnt+1 local s1=randomGAB(segCntGAB) if onlyMutable==true or #UseSegments>0 then s1=UseSegments[randomGAB(#UseSegments)] end if #UseSegments>0 or CanBeUsedBIS(s1) then -- adapted for ebola local str=randomGAB(bands.minStr,bands.maxStr) local length=randomGAB(bands.minUpBIS,bands.maxUpBIS) --debugged BK 15/2/2015, length cannot be 0 local theta = math.acos(math.random()) local phi = 2 * math.pi * math.random() local segmentXAxis=0 local segmentYAxis=0 while true do --all 3 must be different segmentXAxis = randomGAB(segCntGAB) segmentYAxis = randomGAB(segCntGAB) if segmentXAxis~=s1 and segmentYAxis~=s1 and segmentXAxis~=segmentYAxis then break end end --{segmentOrigin, segmentXAxis, segmentYAxis, rho, theta, phi, str} b={s1, segmentXAxis, segmentYAxis, length, theta, phi, str} break end if cnt>100 then p("Sorry! Cant create band in space") --BreakScript() --there is no such function, so it crashes script break end end return b end function CanBeUsedBIS(sg1) --checking end of band for BIS function ssCheck(ss) local good=false if use.Sheet and ss=="E" then good=true end if use.Helix and ss=="H" then good=true end if use.Loop and ss=="L" then good=true end return good end local ok=true if #DoNotUse>0 then --none of 2 can be in that area for i=1, #DoNotUse do local r=DoNotUse[i] for x=r[1],r[2] do if x==sg1 then ok=false break end end if ok==false then break end end end if ok==false then return false --if false can`t be used else ok=false if #AlwaysUse>0 then --at least one have to be there for i=1, #AlwaysUse do local r=AlwaysUse[i] for x=r[1],r[2] do if x==sg1 then ok=true break end end if ok==true then break end end else ok=true end end if ok==true then --check structure ok=false if ssCheck(structure.GetSecondaryStructure(sg1)) then ok=true end end return ok end function deletebands() --leave user bands intact nbands=band.GetCount() if nbands>userbands then for i=nbands,userbands+1,-1 do -- count down from nbands to userbands+1 band.Delete(i) end -- for i end -- if nbands end -- function function ScoreHerd() --score all critters from herd (make bands, act, delete bands) save.Quickload(BestGABslot) print("Scoring "..#critters.." critters...") save.Quicksave(GABherSlot) local herdScore=ScoreGAB() for i=1,#critters do deletebands() local crt=critters[i] --critter local s=ScoreGAB() --start score local bnds=crt.bands local crBIS= false -- false = critter of BBS; true = critter of BIS for b=1,#bnds do local DEBUG=false local bnd=bnds[b] if bnd[6] ~= nil then crBIS=true else crBIS=false end -- we have only BIS if DEBUG then if crBIS then print("BIS nb"..b.." / "..#bnds) else print("BBS nb"..b.." / "..#bnds) end end if bnd[1] ~= bnd[2] or crBIS then -- debugging, no band to itself local a1=5 local a2=5 if bnd[1]== segCnt then a1=6 end if bnd[2]== segCnt then a2=6 end -- changed a1 to a2 21/12/2014 if structure.GetAminoAcid(bnd[1])=='g' then a1=0 end if structure.GetAminoAcid(bnd[2])=='g' then a2=0 end if crBIS then --b={segmentOrigin, segmentXAxis, segmentYAxis, rho=length, theta, phi, str} if DEBUG then print("BIS: seg="..bnd[1].." x= "..bnd[2].." y= "..bnd[3].." rho/length= " ..bnd[4].." theta= "..bnd[5].." phi= "..bnd[6].." atom= "..a1.." Str= "..bnd[7]) end band.Add(bnd[1],bnd[2],bnd[3],bnd[4],bnd[5],bnd[6],a1) -- a1= atom, strength is not in list local bc=band.GetCount() band.SetStrength(bc,bnd[7]) else --BBS: b={s1,s2,str,increment} -- increment is the increment (negative or positive) relative to the segment distance if not structure.IsHydrophobic(bnd[1]) and bnd[4]<0 then a1=0 end -- only hiding hydrophobics if not structure.IsHydrophobic(bnd[2]) and bnd[4]<0 then a2=0 end if structure.IsHydrophobic(bnd[1]) and bnd[4]>0 then a1=0 end -- don't push hydropobics to water if structure.IsHydrophobic(bnd[2]) and bnd[4]>0 then a2=0 end if DEBUG then print("Band: "..bnd[1].."-"..bnd[2].." a1: "..a1.." a2: "..a2) end if math.abs(bnd[1] - bnd[2]) < 2 then break end -- fixed band to adjascent segment gives a bug if DEBUG then print("Band: "..bnd[1].."-"..bnd[2].." a1: "..a1.." a2: "..a2) end band.AddBetweenSegments(bnd[1],bnd[2],a1,a2) local bc=band.GetCount() band.SetStrength(bc,bnd[3]) local length=structure.GetDistance(bnd[1],bnd[2])+bnd[4] if length<bands.minLen then length=bands.minLen end band.SetGoalLength(bc,length) if DEBUG then print("Band: "..bnd[1].."-"..bnd[2].." a1: "..a1.." a2: "..a2.." str: "..round3(bnd[3]).." length= "..round3(length)) end end end end local bandDONE=" BBS" if crBIS then bandDONE= " BIS" end AddBand2UserBands() -- NEW 6/1/2016 adding bands to end userbands (for sym) selection.SelectAll() CIGAB(pullCI) recentbest.Save() local seg=math.random(segCnt) -- new 28/05/2014 cut(seg) -- new 28/05/2014 WiggleGAB("wb",1) uncut(seg)-- new 28/05/2014 PROBLEM here, recentbest includes cuts recentbest.Save() -- NEW 02/06/2014 to avoid recent best in cuts deletebands() CIGAB(1) if math.abs(s-ScoreGAB()) > qstabThresh then QstabGAB() else WiggleGAB() end --print("Critter "..crt.name) TOOMUCHFILTERLOSS=false -- reinitialized if ScoreGAB()-bestScoreGAB>fuzeThresh and not skipfuze then -- this will also check TOOMUCHFILTERLOSS SaveRBGAB() FuzeWithCuts() -- new 02/06/2014 else SaveRBGAB() end crt.score=ScoreGAB()-s --print("Critter "..crt.name.." : "..round(crt.score)) if critter.maxLoss>0 and not TOOMUCHFILTERLOSS then -- on critter level if ScoreGAB()>herdScore-critter.maxLoss then -- we accept to loose a bit more on each herd save.Quicksave(GABherSlot) herdScore=ScoreGAB() else save.Quickload(GABherSlot) -- we start again from best herd score end else save.Quickload(BestGABslot) -- we start again from best critter score end end save.Quickload(BestGABslot) if band.GetCount()>0 then --clean bands from best solution (if any) deletebands() save.Quicksave(BestGABslot) end end function BreedCritters(mom,dad,t) --breed 2 critters. bands are taken randomly local kid={} critterID=critterID+1 kid.no=critterID kid.name=kid.no.."-"..t..mom.no..'/'..dad.no kid.bands={} local mb=#mom.bands local db=#dad.bands if mb>db then mb,db=db,mb end --kid have bands count between mom and dad bands local bn=randomGAB(mb,db) for i=1,bn,2 do kid.bands[#kid.bands+1]=mom.bands[randomGAB(#mom.bands)] kid.bands[#kid.bands+1]=dad.bands[randomGAB(#dad.bands)] end --p(kid.name.." bands: "..#kid.bands) return kid end function KeepGood() --copy best scoring critters form last gen if score above local newHerd={} for i=1,herd.keepBest do if critters[i].score>critter.keepScore and (math.abs(critters[i].score)>0.1 or critters[i].score>0) then newHerd[#newHerd+1]=critters[i] end end return newHerd end function SortCritters() --bubble sort for i=1,#critters do for j=i+1,#critters do if critters[i].score<critters[j].score then critters[i],critters[j]=critters[j],critters[i] --love lua :) end end end end function BreedHerd() print("Breeding "..herd.breedBest.." kids and "..herd.breedBastards.." bastards") SortCritters() newHerd=KeepGood() for i=1, herd.breedBest do local mom=critters[i] if mom.score>critter.breedScore or i<2 then --breed only good ones, 1st is always breed anyway for j=i+1, herd.breedBest do local dad=critters[j] newHerd[#newHerd+1]=BreedCritters(mom,dad,"kid-") newHerd[#newHerd+1]=BreedCritters(dad,mom,"kid-") end end end for i=1, herd.breedBastards do --they will always appear ;] local mom=critters[i] local j=randomGAB(herd.breedBastards+1,#critters) local dad=critters[j] newHerd[#newHerd+1]=BreedCritters(mom,dad,"bas-") newHerd[#newHerd+1]=BreedCritters(dad,mom,"bas-") end critters=newHerd FillHerd() end function ShuffleHerd() if herd.shuffle==true then for i=1,#critters do local r=randomGAB(#critters) if r~=i then critters[i],critters[r]=critters[r],critters[i] end end end end -- ReMix section function ReMix(ss,se,nrresults) ClearScores() --reset score tables local Foundone=false if ss>se then ss,se=se,ss end --switch if needed selection.DeselectAll() selection.SelectRange(ss,se) local nfound=structure.RemixSelected(StartRemixSlot,nrresults) print("Nr of remix found "..nfound) for i=0,nfound-1 do save.Quickload(StartRemixSlot+i) if not BridgesBroken() then --print("Remix "..i) Foundone=true Bridgesave() if doSpecial==true then SelectAround(ss,se,9) Wiggle("s",1,nil,true) Wiggle("ws",2,nil,true) selection.DeselectAll() selection.SelectRange(ss,se) Wiggle("wb",4,nil,true) SelectAround(ss,se,9) elseif doShake==true then CI(shakeCI) Wiggle("s",1,nil,true) CI(1) end Bridgerestore() if AfterRB then doMutate() end SaveScores(ss,se,i) -- if any slotted subscore had improved, save it, including savebest end end if Foundone==false then print("No valid Remix found on this section") end CI(1) return Foundone end -- end remix section function GAB() print() print(recipename2) print("Starting GAB at "..round(ScoreGAB()).." Goal= "..round(PreferedScore).." Abs. best= "..round(bestScore)) UseSegments={} -- new to be reinitialized here in ebola each round !! 17/2/2015 if onlyMutable==true then for i=1,segCntGAB do if structure.IsMutable(i) then UseSegments[#UseSegments+1]=i end end end if #AlwaysUse>0 then listused="" for i=1,#AlwaysUse do local ss=AlwaysUse[i][1] local se=AlwaysUse[i][2] if ss>se then ss,se=se,ss end for j=ss,se do UseSegments[#UseSegments+1]=j end listused=listused..ss.."-"..se.." " end print("Always use:") if ENOUGHFORGAB2 then PrintAreas() elseif ENOUGHFORGAB then print(listused) end AlwaysUse={} --added to list, no need to check later else print("Full random bands") end bestScoreGAB=ScoreGAB() -- renamed for ebola critterID=0 gen=0 ss=ScoreGAB() save.Quicksave(BestGABslot) --recentbest.Save() -- WARNING !! TO BE DELETED ? critters={} FillHerd() badGen=0 while true do --this is (almost) endless script ;] genScore=ScoreGAB() gen=gen+1 -- will stop when max gen or max bad gen is achieved --p() print("Generation: "..gen) if badGen>=herd.renew then -- will not occur the first generation print("Creating fresh random herd...") critters={} FillHerd() badGen=0 elseif gen>1 then -- will not occur the first generation BreedHerd() end ShuffleHerd() ScoreHerd() save.Quickload(BestGABslot) if gen==herd.maxGen then break end --end of loop local genScore2=ScoreGAB() if genScore+0.001>=genScore2 then badGen=badGen+1 if badGen==herd.maxBadGen then break end else badGen=0 -- will continue indefinitely when gains end print("Generation ".. gen.." found "..round3(genScore2-genScore).." pts. Score "..round3(genScore2)) end print("Final GAB score: "..round(ScoreGAB()).." GAB improvement: "..round(ScoreGAB()-ss)) if ScoreGAB()<=PreferedScore+0.001 then print ("It's not enough :( Loading preferred solution scoring ".. round(PreferedScore)) else print("OK ! Evaluating GAB gains:") end end preciseBands=true function LaunchGab(alwaysFrom,alwaysTo) if not SkipGAB then if struct==false and SAVEDstructs then save.LoadSecondaryStructure() end recentbest.Save() -- just for security because there are restores in GAB // but TO DO verify cuts local alwaysFrom=alwaysFrom or 0 local alwaysTo=alwaysTo or 0 if preciseBands then if ENOUGHFORGAB and (alwaysFrom*alwaysTo >0) then --print("Score is sufficient for starting precise GAB") AlwaysUse={} table.insert(AlwaysUse, {alwaysFrom, alwaysTo}) end if HASLIGAND then if AlwUseLigand then table.insert(AlwaysUse, {segCnt, segCnt}) -- segCnt is the ligand if ligands end end if ENOUGHFORGAB2 then --print("Score is sufficient for starting whole GAB") AlwaysUse=areas end end GAB() recentbest.Restore() -- TO DO : This is dangerous with cuts end end function onlyGABoptions() GABfilter=20 LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 9 -- default filter lost allowed per 10 pt score gain disjunct=false donotrevisit=true IDEALCHECK=false if HASMUTABLE then AfterRB=false -- default no mutate used InQstab=false AfterQstab=true BeFuze=false AfterFuze=false MutateCI=0.9 MutSphere=8 MUTRB=false MUTSur=true FILTERPROTECT=true end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=false end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=true --false --if true faster stabilize, but longer reBuild=1 --up to worst parts to look at reBuildmore=0 --increased by every main cycle rebuilds=1 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=4 --find worst segments part minLen=4 --or specify minimum lengthZ maxLen=4 --and maximim lengthZ -- New options maxnrofRuns=50 -- Set it very high if you want to run forever minGain=(segCnt2-segCnt2%4)/4 -- If less gain then try the next one, else recompute if minGain < 40 then minGain=40 end --longfirst=false --true -- Reverse the search, long ones first skipqstab=false skipfuze=false --bandflip=false maxlossbeforefuze=(segCnt2-segCnt2%4)/4 -- if loss is more no fuze is done if maxlossbeforefuze < 30 then maxlossbeforefuze=30 end nrskip=0 --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 1 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 1 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = true --use ligand if true AlwUseLigand= false -- always band to ligand if true end onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = false --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes preciseBands=false allowcut=false herd= --herd options { breedBest = 3, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 3, --save up to 3 best scoring critters, rest are forgotten breedBastards = 2, --number of best will have one random bastard firstGen = 10, -- number of herds on first generation newRandom = 4, --adding new random ones each generation maxGen= 20, --maximum generations shuffle = true, --set true to run critters in random order renew=5, --create totally fresh herd after that many gens w/o improvement maxBadGen=10, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=2, --minimum bands maxBands=7, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -20, --will breed kids only if score higher. Basttards always breed maxLoss=0, --maximum loss by critter. set 0 to disable } end function AskGABOptions() local ask=dialog.CreateDialog("GAB options") ask.L1=dialog.AddLabel("Generations:") ask.maxGen=dialog.AddSlider("Max generations", herd.maxGen, 1, 20, 0) -- New for ebola ask.L2=dialog.AddLabel("Max generations without gain for:") ask.renew=dialog.AddSlider("Start full random", herd.renew, 1, 10, 0) ask.maxBadGen=dialog.AddSlider("Stop", herd.maxBadGen, 1, 10, 0) ask.L3=dialog.AddLabel("Critters:") ask.firstGen=dialog.AddSlider("Nb herds 1st gen.", herd.firstGen, 1, 20, 0) ask.maxLoss=dialog.AddSlider("Max loss/critter", critter.maxLoss, 0, 50, 0) ask.L4=dialog.AddLabel("Other:") ask.fuzeThresh=dialog.AddSlider("Fuze filter", fuzeThresh, -10, 50, 0) ask.qstabThresh=dialog.AddSlider("qstab filter", qstabThresh, -10, 50, 0) if HASLIGAND then ask.useLigand=dialog.AddCheckbox("Use ligand",useLigand) ask.AlwUseLigand=dialog.AddCheckbox("Always band to ligand",AlwUseLigand) end if HASMUTABLE then ask.onlyMutable=dialog.AddCheckbox("Use only mutable segments",onlyMutable) end ask.preciseBands=dialog.AddCheckbox("Precise bands to worst part",preciseBands) ask.freqbis=dialog.AddSlider("Freq. BIS", freqbis, 0.0, 1.0, 2) ask.allowcut=dialog.AddCheckbox("Use cuts",allowcut) ask.OK = dialog.AddButton("OK",1) dialog.Show(ask) herd.maxGen=ChangedOptions("herd.maxGen",herd.maxGen,ask.maxGen.value) herd.renew=ChangedOptions("herd.renew",herd.renew,ask.renew.value) maxBadGen=ChangedOptions("herd.maxBadGen",herd.maxBadGen,ask.maxBadGen.value) herd.firstGen=ChangedOptions("herd.firstGen",herd.firstGen,ask.firstGen.value) critter.maxLoss=ChangedOptions("critter.maxLoss",critter.maxLoss,ask.maxLoss.value) fuzeThresh=ChangedOptions("fuzeThresh",fuzeThresh,ask.fuzeThresh.value) qstabThresh=ChangedOptions("qstabThresh",qstabThresh,ask.qstabThresh.value) if HASLIGAND then useLigand=ChangedOptions("useLigand",useLigand,ask.useLigand.value) AlwUseLigand=ChangedOptions("AlwUseLigand",AlwUseLigand,ask.AlwUseLigand.value) end if useLigand==false then while structure.GetSecondaryStructure(segCntGAB)=="M" do segCntGAB=segCntGAB-1 end end if HASMUTABE then onlyMutable=ChangedOptions("onlyMutable",onlyMutable,ask.onlyMutable.value) end preciseBands=ChangedOptions("preciseBands",preciseBands,ask.preciseBands.value) freqbis=ChangedOptions("freqbis",freqbis,ask.freqbis.value) allowcut=ChangedOptions("allowcut",allowcut,ask.allowcut.value) end --START Bands to end existing bands (for symmetrics) distancesb={} -- a list of distances between segments and end bands distScore=Score() probBands2Userbands=0.8 -- on each critter !!! (keep it small !!) if bandflip and PROBABLESYM then BAND2USERBANDS=true -- if existing bands, we'll band to their end (for symmetrics) else BAND2USERBANDS=false end function Band2Userbands(s,b) -- from seg to band local iBand= 0 local Goallength=randomGAB(2.0,4.9) -- small but not too small local Strength=randomGAB(0.2,1.5) iBand = band.AddToBandEndpoint(s, b) band.SetStrength(iBand,Strength) band.SetGoalLength(iBand,Goallength) end function AddBand2UserBands() -- NEW 6/1/2016 , not too many bands local seg=1 local b=0 local Nbband2Ubands=1 if BAND2USERBANDS then if probBands2Userbands>randomGAB(0.00,0.99) then Nbband2Ubands=randomGAB(1,ExistingBands) if Nbband2Ubands> 3 then Nbband2Ubands=3 end for i=1, Nbband2Ubands do seg=randomGAB(segCnt2) b=randomGAB(1,ExistingBands) Band2Userbands(seg,b) end end end end --STOP Bands to end existing bands (for symmetrics) function ContextualOptions() -- to propose options adapted to pc and puzzle (at start only, then every day) --options linked to type of puzzle LoopOptions=LoopOptions+1 timeLeft=os.difftime(puzzle.GetExpirationTime(),startRecTimeSec)/86400 -- in days, reinitialized if LoopOptions==1 then print(down(timeLeft/24).." hours left. Proposing contextual options") else print(down(timeLeft/24).." hours left. Resetting contextual options") end if timeLeft>2 and LoopOptions < 2 and WorstGroups=="All" then -- intial "All", thus it will give "Backbone" on early game WorstGroups="Backbone" elseif timeLeft>2 and LoopOptions < 3 and WorstGroups=="Backbone" then WorstGroups="Sidechains" elseif timeLeft>2 and LoopOptions < 4 and WorstGroups=="Sidechains" then WorstGroups="Others" else WorstGroups="All" -- most of the cases end print("Select Worst "..WorstGroups) if WorstGroups=="Backbone" then--{"clashing", "packing", "backbone", "ideality"}, -- 2:Backbone 07/02/2014 scrPart={"clashing", "packing", "backbone"} -- start with worst backbone scores, like in Ebola Rebuild for i=1,#ScoreParts do -- slots if ScoreParts[i][2]=="backbone" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="clashing" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="packing" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="ideality" then ScoreParts[i][3]=true -- not in worst because it's not always present elseif ScoreParts[i][2]=="total" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="loctotal" then ScoreParts[i][3]=true else ScoreParts[i][3]=false end end elseif WorstGroups=="Sidechains" then--{"hiding", "bonding", "sidechain"} scrPart={"hiding", "bonding"} -- sidechain is not always present for i=1,#ScoreParts do -- slots if ScoreParts[i][2]=="sidechain" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="hiding" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="bonding" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="total" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="loctotal" then ScoreParts[i][3]=true else ScoreParts[i][3]=false end end elseif WorstGroups=="Others" then--{"density", "reference", "other"} scrPart={} -- all because not sure they are present for i=1,#ScoreParts do -- slots if ScoreParts[i][2]=="density" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="reference" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="other" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="total" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="loctotal" then ScoreParts[i][3]=true else ScoreParts[i][3]=false end end else scrPart={} -- worst default = all of them for i=1,#ScoreParts do -- slots ScoreParts[i][3]=true -- all slots the latest days end end if ELECTRON or HASDENSITY then -- score others= density + reference if timeLeft>2 then scrPart={'density'} -- Test. Note that worst default is also perfect for density for i=1,#ScoreParts do -- slots if ScoreParts[i][2]=="density" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="reference" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="other" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="total" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="loctotal" then ScoreParts[i][3]=true else ScoreParts[i][3]=false end end else scrPart={} -- worst default is perfect for density for i=1,#ScoreParts do -- slots ScoreParts[i][3]=true -- all slots the latest days end end end if DISULFIDEBONUS then-- scoreothers --experimental NOT USED for i=1,#ScoreParts do -- slots if ScoreParts[i][2]=="density" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="reference" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="other" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="total" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="loctotal" then ScoreParts[i][3]=true elseif ScoreParts[i][2]=="filter" then ScoreParts[i][3]=true -- added the filters else ScoreParts[i][3]=false end end end if CENTROID then -- nothing yet TO DO --to be experimented in CI() and in Wiggle(): CI=1, no shake, no sidechain end if SEPSIS or HOTSPOT then -- ebola does not work good with zones on sepsis herd.maxGen=10 -- max generations GAB au total herd.renew=5 -- gab aleatoire apres 5 echecs herd.maxBadGen=6-- max echecs successifs reBuild=1 --up to worst parts to look at reduce zone to minimum to avoid bug reBuildmore=0 --increased by every main cycle lengthZ=3 --find worst segments part minLen=1 --or specify minimum lengthZ maxLen=3 --and maximim lengthZ freqbis=0.3 -- I think it's better bands in space in case of sepsis and related puzzle types end if PROBABLESYM then freqbis=0.9 -- for sym, it's much better BIS (unless on the mono at start) end if LoopOptions==2 then -- reinitialize several thinks TO DO nrskip=nrskip+1 -- skipping one worst more (bug resume) end if LoopOptions==3 then -- reinitialize several thinks TO DO nrskip=nrskip+1 -- skipping one worst more (bug resume) freqbis = 0.3 -- frequency of Band In Space end if Score()<7000 then --only drw? or only GAB? -- TO DO end if Score()<4000 then-- no fuze -- already done in DRW end if onlyGAB then -- set long GAB options -- new BK 25/10/2013 onlyGABoptions() end if NOREBUILDMODE then rebuilds= 0 IDEALCHECK=true end wholeProt= false -- not used because it's inplicit when asking for maximum worst parts if wholeProt then --adapted to current pc power TO DO reBuild=segCnt2 -- all worst parts end if RecTime>200 then -- very slow pc or big protein velocity=1 elseif RecTime>100 then -- slow pc or big protein velocity=2 elseif RecTime>10 then velocity=3 elseif RecTime>5 then velocity=3 elseif RecTime>0.5 then velocity=4 else -- very quick pc or very small protein velocity=5 end if timeLeft<2 and RecTime<50 then -- last day I think we can propose the ultimate force velocity=4 -- TO DO: evaluate and refine (copy paste here) for "on the fly" nrskip=nrskip+2 -- skipping worst because we certainly have already used a lot of eDRW recipes reBuild=reBuild +2 -- more worst ones to try after this skips disjunct=true donotrevisit=true end if timeLeft<1 and RecTime<150 then -- last day I think we can propose the ultimate force velocity=5 nrskip=nrskip+4 -- skipping worst because we certainly have already used a lot of eDRW recipes reBuild=reBuild + 10 -- near to all protein last day disjunct=true donotrevisit=true IDEALCHECK=false -- always end if SKETCHBOOK then print("Sketchbook puzzle, reducing action number") defUndo= true undo.SetUndo(defUndo) velocity=5 defminppi= 20 defiter= 8 -- ((defiter+1)/3)=3 for shakes and mutate end print("Velocity= "..velocity) print("Default skipping= "..nrskip.." worst parts") print("Default try = "..reBuild.." worst parts") end function QuickOptions(choice) -- to quick set default options based on velocity (after first dialog only) local choice=choice or 3 -- default, choice is the velocity if FlagRecipeUsed then nrskip=2 end -- not repeating all the same worst as before if choice==1 then -- super quick or start game (rough, about 1 hour) GABfilter= -1 -- only on gain GABfilterHigh=5 if NEGATIVEFILTER then LostpFgain= 100 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 1 -- default filter lost allowed per 10 pt score gain else LostpFgain= -1 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 100 -- default filter lost allowed per 10 pt score gain end disjunct=true donotrevisit=true IDEALCHECK=false if HASMUTABLE then AfterRB=false InQstab=false AfterQstab=false BeFuze=false AfterFuze=false MutateCI=0.9 MutSphere=4 MUTRB=false MUTSur=false FILTERPROTECT=false -- true=no filter loss allowed on mutate end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=true end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=false --false --rebuild helices + surrounding loops doShake=false --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=true --false --if true faster stabilize, but longer if false reBuild=1 --up to worst parts to look at reBuildmore=1 --increased by every main cycle rebuilds=5 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=4 --find worst segments part minLen=3 --or specify minimum lengthZ maxLen=4 --and maximum lengthZ -- New options maxnrofRuns=400 -- Set it very high if you want to run forever minGain=(segCnt2-segCnt2%4)/2 -- If less gain then try the next one, else recompute if minGain < 80 then minGain=80 end --longfirst=false --true -- Reverse the search, long ones first skipqstab=true --skipfuze=false (Initiated on start) if timeLeft>4 and HANDFOLD then -- keep the structure ! skipfuze=true end --bandflip=true maxlossbeforefuze=(segCnt2-segCnt2%4)/40 -- if loss is more no fuze is done if maxlossbeforefuze < 1 then maxlossbeforefuze=1 end nrskip=nrskip+2 -- 2 or 4 if recipe already used before --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = -1 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 10 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = false --use ligand if true AlwUseLigand= false -- always band to ligand if true end if HASMUTABLE then onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = false --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes end preciseBands=true allowcut=false herd= --herd options { breedBest = 2, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 3, --save up to 3 best scoring critters, rest are forgotten breedBastards = 2, --number of best will have one random bastard firstGen = 4, -- number of herds on first generation newRandom = 1, --adding new random ones each generation maxGen= 2, --maximum generations shuffle = true, --set true to run critters in random order renew=1, --create totally fresh herd after that many gens w/o improvement maxBadGen=1, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=2, --minimum bands maxBands=5, --maximum bands keepScore = 1 , --survive to next gen only if score higher than breedScore= -2, --will breed kids only if score higher. Bastards always breed maxLoss=0, --maximum loss by critter. set 0 to disable } elseif choice==2 then -- quick (about 4 hours) GABfilter=1 if NOREBUILDMODE then GABfilter=-1 end GABfilterHigh=10 if NEGATIVEFILTER then LostpFgain= 50 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 1 -- default filter lost allowed per 10 pt score gain else LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 20 -- default filter lost allowed per 10 pt score gain end disjunct=true donotrevisit=true IDEALCHECK=false if HASMUTABLE then AfterRB=false InQstab=false AfterQstab=false BeFuze=false AfterFuze=false MutateCI=0.9 MutSphere=6 MUTRB=true MUTSur=false FILTERPROTECT=true -- true=no filter loss allowed on mutate end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=false end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=true --false --if true faster stabilize, but longer ? reBuild=2 --up to worst parts to look at reBuildmore=1 --increased by every main cycle rebuilds=8 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=4 --find worst segments part minLen=2 --or specify minimum lengthZ maxLen=4 --and maximum lengthZ -- New options maxnrofRuns=1000 -- Set it very high if you want to run forever minGain=(segCnt2-segCnt2%4)/3 -- If less gain then try the next one, else recompute if minGain < 60 then minGain=60 end --longfirst=false --true -- Reverse the search, long ones first --skipqstab=false (initiated on start) --skipfuze=false (Initiated on start) if timeLeft>4 and HANDFOLD then -- keep the structure ! skipfuze=true end --bandflip=false maxlossbeforefuze=(segCnt2-segCnt2%4)/20 -- if loss is more no fuze is done if maxlossbeforefuze < 15 then maxlossbeforefuze=15 end nrskip=nrskip+ 1 -- 1 or 3 if recipe already used before --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 0 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 2 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = false --use ligand if true AlwUseLigand= false -- always band to ligand if true end if HASMUTABLE then onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = false --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes end preciseBands=true allowcut=false herd= --herd options { breedBest = 3, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 4, --save up to 3 best scoring critters, rest are forgotten breedBastards = 2, --number of best will have one random bastard firstGen = 6, -- number of herds on first generation newRandom = 2, --adding new random ones each generation maxGen= 3, --maximum generations shuffle = true, --set true to run critters in random order renew=1, --create totally fresh herd after that many gens w/o improvement maxBadGen=1, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=2, --minimum bands maxBands=6, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -10, --will breed kids only if score higher. Basttards always breed maxLoss=2, --maximum loss by critter. set 0 to disable } elseif choice==3 then -- default (about 8 hours) GABfilter=5 if NOREBUILDMODE then GABfilter=-1 end GABfilterHigh=20 if NEGATIVEFILTER then LostpFgain= 20 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 2 -- default filter lost allowed per 10 pt score gain else LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 9 -- default filter lost allowed per 10 pt score gain end --disjunct=disjunct --donotrevisit=donotrevisit --IDEALCHECK=true if HASMUTABLE then AfterRB=false -- default no mutate used InQstab=false AfterQstab=true BeFuze=false AfterFuze=false MutateCI=0.9 MutSphere=8 MUTRB=false MUTSur=true FILTERPROTECT=true -- true=no filter loss allowed on mutate end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=false end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=true --false --if true faster stabilize, but longer reBuild=3 --up to worst parts to look at reBuildmore=2 --increased by every main cycle rebuilds=10 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=6 --find worst segments part minLen=2 --or specify minimum lengthZ maxLen=4 --and maximim lengthZ -- New options maxnrofRuns=1000 -- Set it very high if you want to run forever minGain=(segCnt2-segCnt2%4)/4 -- If less gain then try the next one, else recompute if minGain < 40 then minGain=40 end --longfirst=false --true -- Reverse the search, long ones first -- skipqstab=false (initiated on start) --skipfuze=false (Initiated on start) if timeLeft>4 and HANDFOLD then -- keep the structure ! skipfuze=true end --bandflip=false maxlossbeforefuze=(segCnt2-segCnt2%4)/4 -- if loss is more no fuze is done if maxlossbeforefuze < 30 then maxlossbeforefuze=30 end nrskip=nrskip -- 0 or 2 if recipe already used before --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 1 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 1 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = true --use ligand if true AlwUseLigand= false -- always band to ligand if true end if HASMUTABLE then onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = false --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes end preciseBands=true allowcut=false herd= --herd options { breedBest = 3, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 3, --save up to 3 best scoring critters, rest are forgotten breedBastards = 2, --number of best will have one random bastard firstGen = 10, -- number of herds on first generation newRandom = 3, --adding new random ones each generation maxGen= 3, --maximum generations shuffle = true, --set true to run critters in random order renew=1, --create totally fresh herd after that many gens w/o improvement maxBadGen=2, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=2, --minimum bands maxBands=7, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -20, --will breed kids only if score higher. Basttards always breed maxLoss=20, --maximum loss by critter. set 0 to disable } elseif choice==4 then -- slow (about 1 day) GABfilter=10 if NOREBUILDMODE then GABfilter=-1 end GABfilterHigh=40 if NEGATIVEFILTER then LostpFgain= 10 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 2 -- default filter lost allowed per 10 pt score gain else LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 5 -- default filter lost allowed per 10 pt score gain end --disjunct=false --donotrevisit=true --IDEALCHECK=true if HASMUTABLE then AfterRB=false InQstab=false AfterQstab=true BeFuze=false AfterFuze=true MutateCI=0.9 MutSphere=8 MUTRB=false MUTSur=true FILTERPROTECT=true -- true=no filter loss allowed on mutate end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=false end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=false --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=false -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=false --set in all loop (if true work in structure mode) fastQstab=false --false --if true faster stabilize, but longer reBuild=4 --up to worst parts to look at reBuildmore=3 --increased by every main cycle rebuilds=15 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=6 --find worst segments part minLen=5 --or specify minimum lengthZ REVERSED in mode 4 maxLen=2 --and maximum lengthZ -- New options maxnrofRuns=1000 -- Set it very high if you want to run forever minGain=(segCnt2-segCnt2%4)/4 -- If less gain then try the next one, else recompute if minGain < 30 then minGain=30 end --longfirst=true --true -- Reverse the search, long ones first -- skipqstab=false (initiated on start) --skipfuze=false (Initiated on start) if timeLeft>4 and HANDFOLD then -- keep the structure ! skipfuze=true end --bandflip=false maxlossbeforefuze=(segCnt2-segCnt2%4)/3 -- if loss is more no fuze is done if maxlossbeforefuze < 35 then maxlossbeforefuze=35 end nrskip=nrskip -- 0 or 2 if recipe already used before --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 5 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 1 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = true --use ligand if true AlwUseLigand= false -- always band to ligand if true end if HASMUTABLE then onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = true --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes end preciseBands=true allowcut=false herd= --herd options { breedBest = 4, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 5, --save up to 3 best scoring critters, rest are forgotten breedBastards = 3, --number of best will have one random bastard firstGen = 10, -- number of herds on first generation newRandom = 3, --adding new random ones each generation maxGen= 4, --maximum generations shuffle = true, --set true to run critters in random order renew=2, --create totally fresh herd after that many gens w/o improvement maxBadGen=2, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=3, --minimum bands maxBands=8, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -25, --will breed kids only if score higher. Basttards always breed maxLoss=30, --maximum loss by critter. set 0 to disable } elseif choice==5 then -- days or end game GABfilter=20 if NOREBUILDMODE then GABfilter=-1 end GABfilterHigh=100 if NEGATIVEFILTER then LostpFgain= 10 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 1 -- default filter lost allowed per 10 pt score gain else LostpFgain= 0 -- default score lost allowed for each pt of preferred filter gain LostFpgain= 1 -- default filter lost allowed per 10 pt score gain end if timeLeft>2 then -- else take the default ones for end game (true, true) disjunct=false donotrevisit=false end if HASMUTABLE then AfterRB=true InQstab=false AfterQstab=true BeFuze=false AfterFuze=true MutateCI=0.9 MutSphere=8 MUTRB=false MUTSur=true FILTERPROTECT=true -- true=no filter loss allowed on mutate end if PROBABLEFILTER then FiltersFirst=LostpFgain>-2 -- always true!!!(depends only on the cost we admit: -1 being default no cost) FILTERMANAGE=true -- note that it will be true on all puzzles where filters are observed GENERICFILTER=false end --DRW options --options for (5)"areas" setting loops=true --rebuild loops alone sheets=true --rebuild sheets + surrounding loops helices=true --false --rebuild helices + surrounding loops doShake=true --false --shake rebuilded area (only!) every rebuild, slowing down process doSpecial=true -- local shake, wiggle sidec, wiggle backbone, even slower shakeCI=0.31 --clash imortance while shaking struct=true --set in all loop (if true work in structure mode) fastQstab=false --false --if true faster stabilize, but longer reBuild=5 --up to worst parts to look at reBuildmore=5 --increased by every main cycle rebuilds=20 --how many rebuilds to try, set at least 10! rebuildCI=0 --clash importance while rebuild lengthZ=6 --find worst segments part minLen=7 --or specify minimum lengthZ REVERSED in mode 5 maxLen=2 --and maximim lengthZ -- New options maxnrofRuns=1000 -- Set it very high if you want to run forever NOT more than 1000 ! minGain=(segCnt2-segCnt2%4)/4 -- If less gain then try the next one, else recompute if minGain < 30 then minGain=30 end --longfirst=true --true -- Reverse the search, long ones first -- skipqstab=false (initiated on start) --skipfuze=false (Initiated on start) if timeLeft>5 and HANDFOLD then -- keep the structure ! skipfuze=true end --bandflip=false maxlossbeforefuze=(segCnt2-segCnt2%4)/2 -- if loss is more no fuze is done if maxlossbeforefuze < 40 then maxlossbeforefuze=40 end nrskip=nrskip -- 0 or 2 if recipe already used before --GAB options energy = false --set true to seek energy in exploration puzzles; false works on all puzzles pullCI = 0.9 --Clash Importance during pull maxCI = 1 --maximum CIGAB used by script --fastQstab = true -- only 1s1w after pull if true DUPLICATE DRW fuzeThresh = 10 -- run fuze if we are close to best score (negative=new best score) qstabThresh = 1 -- run qstab if score drops more than... wiggle only in other case if HASLIGAND then useLigand = true --use ligand if true AlwUseLigand= false -- always band to ligand if true end if HASMUTABLE then onlyMutable = false --if true use ONLY all mutable aas, no matter of always use mutateOnce = true --if true use mutate(1) instead of shake in qstab mutateOnceCI = 0.21 --mutate on what clashing importance mutateAlwas = false --if true use mutate(1) instead of all shakes end preciseBands=true allowcut=true herd= --herd options { breedBest = 5, --breed best 4 critters - all combinations => 6 kids form 4 critters, 3 form 3, 1 form 2, 9 form 5 ;] keepBest = 5, --save up to 3 best scoring critters, rest are forgotten breedBastards = 3, --number of best will have one random bastard firstGen = 10, -- number of herds on first generation newRandom = 3, --adding new random ones each generation maxGen= 4, --maximum generations shuffle = true, --set true to run critters in random order renew=2, --create totally fresh herd after that many gens w/o improvement maxBadGen=4, -- Stop the script after X generations that dont increase the score } critter= --critter options { minBands=4, --minimum bands maxBands=12, --maximum bands keepScore = 0 , --survive to next gen only if score higher than breedScore= -30, --will breed kids only if score higher. Basttards always breed maxLoss=0, --maximum loss by critter. set 0 to disable } end -- now some generic inits if NOREBUILDMODE then rebuilds= 0 IDEALCHECK=true end if SKETCHBOOK then print("Sketchbook puzzle, reducing action number") defUndo= true undo.SetUndo(defUndo) velocity=5 defminppi= 20 defiter= 8 -- ((defiter+1)/3)=3 for shakes and mutate skipqstab=true skipfuze=true rebuilds=25 -- actually, it depends on the remaining moves (this number of moves is needed) maxlossbeforefuze= -5 -- only on gain fuzeThresh=-10 qstabThresh=-10 allowcut=false -- because a cut is a move GABfilter= -10 -- only on big gain doSpecial= false end end --START Movie store big steps StepScore= ScoreGAB() -- New 4/11/2014 function StoreBigStep() StepScore= ScoreGAB() save.Quicksave(SlotStep) if SlotStep==SlotStepMax then -- we erase the first ones, only keeping the latest steps SlotStep=SlotStepStart else SlotStep=SlotStep+1 end end function SaveBigSteps() -- in order to be able to display big steps afterwards in undos local s= ScoreGAB() local g= s-StepScore if s >0 and ( (s <7000 and g>500) or (s <9000 and g>200) or (s <10000 and g>100) or (s >10000 and g>50)) then StoreBigStep() end end function MovieSteps() undo.SetUndo(true) for i= SlotStepStart, SlotStep do save.Quickload(SlotStep) end --save.Quickload(PreferredScoreSlot) print("See remembering of big steps in undos") end --END Movie store big steps --jeff101 status per generation by Bruno Kestemont -- round3 & down must been defined function StatusGen(loop) local loop = loop or 0 if loop==0 then -- init scoreNow=current.GetScore() StatusStartScore= scoreNow formerScore=scoreNow gaingen=round3(scoreNow) elseif loop >0 then formerScore=scoreNow scoreNow=current.GetScore() TOTALgain=scoreNow-StatusStartScore GainThisGen=scoreNow-formerScore print("Score: "..round3(scoreNow)) print(">>Gain loop "..loop..": "..round3(GainThisGen)) print(">>>Total gain till now: "..round3(TOTALgain)) if loop>1 and (loop-1)==5*down((loop-1)/5) then gaingen=(gaingen..'\n ') -- start new line every 5 generations end gaingen=gaingen.." + " ..round3(GainThisGen) gaingen2print=gaingen.." = " ..round3(scoreNow) print(gaingen2print) print("Loop: ".. loop..", score: "..round3(scoreNow)..", gain: "..round3(TOTALgain).." ("..os.date()..")") end end StatusGen(0) -- init --end jeff101 status velocity=3 function AskEbolaOptions() local askresult local askmutable=HASMUTABLE local suspectnorebuild= SUSPECTNOREBUILD local ask = dialog.CreateDialog(recipename) local Duration=12 if askmutable then print("Setting default mutate options") AfterQstab=true AfterFuze=true MutSur=true end --repeat ask.l7 = dialog.AddLabel("Time needed with current options: about ".. Duration.." hours") ask.l8 = dialog.AddLabel("Reset options wizard, from 1 fast to 5 slow:") --ask.reset=dialog.AddCheckbox("Reset options wizard, from 1 fast to 5 slow:",false) ask.velocity = dialog.AddSlider("Reset options:",velocity,1,5,0) if SKETCHBOOK then ask.defminppi=dialog.AddSlider("minppi in wiggle", defminppi, 0, 100, 1) end if SUSPECTNOREBUILD then ask.SUSPECTNOREBUILD=dialog.AddCheckbox("Don't rebuild",suspectnorebuild) end ask.l9 = dialog.AddLabel("Go! = go with wizard options!") ask.l10 = dialog.AddLabel("Options = tune options") --ask.l11 = dialog.AddLabel("More = tune more Ebola and GAB options") --ask.l12 = dialog.AddLabel("GAB = tune GAB options") ask.OK = dialog.AddButton("Go!",1) ask.Cancel = dialog.AddButton("Cancel",0) ask.DRW = dialog.AddButton("Options",2) --ask.More = dialog.AddButton("More",3) --ask.GAB = dialog.AddButton("GAB",4) askresult=dialog.Show(ask) if askresult > 0 then if SUSPECTNOREBUILD then SUSPECTNOREBUILD=ChangedOptions("SUSPECTNOREBUILD",SUSPECTNOREBUILD,ask.SUSPECTNOREBUILD.value) end if SUSPECTNOREBUILD then NOREBUILDMODE= true end velocity=ChangedOptions("velocity",velocity,ask.velocity.value) QuickOptions(velocity) -- reset all options just before to start or add more dialog Duration= velocity * 5 if SKETCHBOOK then defminppi=ChangedOptions("defminppi",defminppi,ask.defminppi.value) end WORKON=SegmentSetMinus(WORKON,FindFrozen()) WORKON=SegmentSetMinus(WORKON,FindLocked()) WORKON=SegmentSetMinus(WORKON,FindAAtype("M")) if askresult==2 then AskDRWOptions() ProtectDesign(NOTWORKON) -- optional in AskForSelections end --if askresult==3 then AskMoreOptions() end --if askresult==4 then AskMoreOptions() end -- To Do: GAB dialog --until askresult < 2 print("Options based on velocity= "..velocity) print("Approximative duration per cycle: about ".. Duration.." hours") return askresult > 0 end end --Not used (copied in Cleanup) function CleanupGAB(err) -- NEW BK 10/10/2013 print("Restoring CIGAB, best result, filter and structures") CIGAB(1) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- new BK 8/4/2013, always back to user settings MovieSteps() -- New 4/11/2014 save.Quickload(PreferredScoreSlot) MovieSteps() WhriteNote() -- New 4/11/2014 TOTALgain=Score()-DRWstartscore print(">>>>>TOTAL EBOLA GAIN (following preferences)= "..round3(TOTALgain)) print("From "..round3(DRWstartscore).." to "..round3(Score())) print("Absolute best score = "..round3(bestScore)) print("Total gain till credited score: "..round3(Score(current, true)-StartEbolaScore)) print("Absolute best filter = "..round3(bestFScore)) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- always back to user settings deletebands() print(err) LastWish() end --GABcut END########################################################### function LastWish() --recentbest.Restore() undo.SetUndo(true) CI(1) return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting band.DisableAll() print("Keeping different best solutions in 5 undos") save.Quicksave(PreferredScoreSlot) save.Quickload(BestScoreSlot) save.Quickload(BestFilterSlot) --save.Quickload(bwslot) save.Quickload(BestItelligentSlot) save.Quickload(PreferredScoreSlot) if Priority==0 then save.Quickload(BestScoreSlot) print("Ending with best score") elseif Priority==1 then save.Quickload(BestFilterSlot) print("Ending with best filter") elseif Priority==2 then save.Quickload(BestItelligentSlot) print("Ending with optimal filter&score solution") else save.Quickload(PreferredScoreSlot) print("Ending with preferred solution") end UnProtectDesign(FREEZEPROTECT) end function DumpErr(err) start,stop,line,msg=err:find(":(%d+):%s()") err=err:sub(msg,#err) p(true, '---') if err:find('Cancelled')~=nil then print("User stop.") else print("unexpected error detected.") --p("Error line: %i.") --p("Error : %s.") p("Error line: ", line) p("Error: ", err) end --Cleanup() undo.SetUndo(true) print("Restoring CI, initial selection, best result and structures") CI(1) save.Quickload(PreferredScoreSlot) if SAVEDstructs then save.LoadSecondaryStructure() end selection.DeselectAll() if SAFEselection ~= nil then SetSelection(SAFEselection) end print("Restoring CIGAB, best result, filter and structures") CIGAB(1) if FILTERMANAGE then return2GlobalOriginalFilterSetting() FILTERON= not OriginalFilterSetting end -- new BK 8/4/2013, always back to user settings MovieSteps() -- New 4/11/2014 save.Quickload(PreferredScoreSlot) if SAVEDstructs then save.LoadSecondaryStructure() end MovieSteps() WhriteNote() -- New 4/11/2014 TOTALgain=Score()-DRWstartscore print(">>>>>TOTAL EBOLA GAIN (following preferences)= "..round3(TOTALgain)) print("From "..round3(DRWstartscore).." to "..round3(Score())) print("Absolute best score = "..round3(bestScore)) print("Total gain till credited score: "..round3(Score(current, true)-StartEbolaScore)) print("Absolute best filter = "..round3(bestFScore)) deletebands() print(err) LastWish() end function MAIN() print("Based on ".."Tvdl enhanced DRW "..DRWVersion.." and "..recipename2) ContextualOptions() if AskEbolaOptions() then print(ChangedOptionsTxt) DRW() end LastWish() end xpcall(MAIN,DumpErr)

Comments


Bruno Kestemont Lv 1

Basically, it's a Deep Rebuild and Band Worst (DRBW) recipe

For the worst scoring zones of several segments:
-rebuild and shake several times
-fuze selected for best rebuild_shake results only
-if it's a good solution, add bands from and to this zone, wiggle selected, fuze if gain, wiggle all
-go to next worst zone

Bruno Kestemont Lv 1

It's a complete reset of Ebola Rebuild.

The strategy is exactly the same as Ebola Rebuild, but with modern eDRW and GAB, and a better user interface.

It takes the advantages of latest tvdl enhanced DRW which constitutes the core of the recipe, including managing puzzle types (less contextual bugs) and optionally selecting where to work on.

In the between of each DRW, it starts an enhanced version of GAB including cuts and banding to ends of user bands (this is usefull to band to symmetrics or to space in the wanted direction).

Bruno Kestemont Lv 1

Its a very long lasting recipe for Middle-End game on Low wiggle power.

I typically use it only:

-on small puzzles
-when eDRW and GAB recipes do not gain anymore, and I don't know what to do and several days are remaining and I don't want to switch to High wiggle power
-when I'll be absent from keyboard for a long time (I need a long lasting patient recipe): > 8 hours

Interesting options:

-Priority to filter: for filtered puzzles, you may give the priority to filter over points;
-Band to Symmetrics: put band to symmetric or to space and disable before to run, GAB will band to the symmetric or wanted space too;
-Band to worst segments;
-Cuts in GAB and in Fuse;
-Idealize and remix
-Auto-proposes the best options considering your computer power and the puzzle state and characteristics
-Quick start: simply click on "ok" if you trust the options "out of context"

Bruno Kestemont Lv 1

Shadow filter is a bonus which is not related to segments, like in Electron Density puzzles.

Filter bonus is explicitly given on the top of your screen. Typical in Design and Contact puzzles. I recommend to select "2" "filter bonus" on start game, and "1" while you did not get the highest possible bonus. "0" should be used the latest 2 days in order to gain points.

Default "0" is fast and corresponds to a classical recipe behaviour.

Note that selecting "1" or "2" reduces the probability of fast score gain: the recipe does not always build on the highest score (but this can be recovered when clicking on "Best credited score" at the end). Read the log in order to follow the recipe's strategy.

Bruno Kestemont Lv 1

(after the eventual preludes above)

The default will depends on the context (puzzle size, computer power, deadline). Just type "Go" and it will be ok.

If you want another set of default options, just change the slide from 1 ("fast") to 5 ("slow") and type "Go !"

After selecting the slide "Reset options", you might want to refine the proposed ones by clicking on "Options". Other dialogs bellow are only accessible by clicking on "Options" here: for advanced or curious players only !

Bruno Kestemont Lv 1


This is a typical eDRW dialog.
Most options are the same as in eDRW.
Some subdialogs might be different depending on context (like Reselect Slots will also give the filter options on filtered puzzles).
"More" and "GAB" are new to Ebola.

Bruno Kestemont Lv 1

MoreMore
New to eDRW: Idealize & remix, cut in worst and GAB launch criteria.

After each rebuild & shake, a GAB will occur on the best rebuild ONLY if it's resulting score is:
-not lower than "last preferred score - loss filter" (negative loss = GAB only after gain)
-not higher than "last preferred score + gain filter"

"Do not launch GAB" results in a simple DRW recipe ! (it might be proposed as default on start game).

Bruno Kestemont Lv 1


This is almost the same as in Ebola Rebuild.

"Full random" means that it will not band to worst parts anymore (a normal random GAB)
More herds = more time needed, less points
Fuze & qstab filters are the loss allowed before to do this (negative = fuze only on gain).
Use cuts in GAB gives a good result on end game.

It's possible to limit Ebola to only GAB by changing the DRW options to minimum rebuild numbers, "launch GAB" almost always, setting a high max generations, never stop here and no precise bands. (But then why not using a normal GAB recipe? for the cuts?).

Bruno Kestemont Lv 1

(Re)select slots(Re)select slots
This is an example of the (Re)select slots Dialog in the case of a puzzle with Filters (this dialog will change with puzzle context).

The first part is the same as in original eDRW. The slots are the Deep rebuild solutions that would be further fuzed and/or used for GAB.

The aim is to favor what you like depending on the game status. Most of the time, we simply select the best total score (and/or segments local total). But in Electron Density puzzles, we might want to also select the rebuild which gives the best Density subscore (this option would be present on the dialog for this type of puzzle).

The second part is specific to filtered puzzles. Check the filter subscore to favor this. Then specify how many points you are ready to loose for each Filter Bonus gain, or the filter lost you are ready to pay for any total score gain.

Finally, decide to disable filter during wiggle (to save a lot of time, on the cost of possible filter gains), or even almost always (turbo but reduced chances to rise bonus).