signature:
def get_lipid_vdwradii ( outdir = os . path . curdir , libdir = None ) :
    """Find vdwradii . dat and add special entries for lipids .
 See : data : ` gromacs . setup . vdw _ lipid _ resnames ` for lipid
 resnames . Add more if necessary ."""

implementation:
vdwradii_dat = os . path . join ( outdir , "vdwradii.dat" )
if libdir is not None :
    filename = os . path . join ( libdir , 'vdwradii.dat' )
    # canonical name
    if not os . path . exists ( filename ) :
        msg = 'No VDW database file found in {filename!r}.' . format ( ** vars ( ) )
        logger . exception ( msg )
        raise OSError ( msg , errno . ENOENT )
else :
    try :
        filename = os . path . join ( os . environ [ 'GMXLIB' ] , 'vdwradii.dat' )
    except KeyError :
        try :
            filename = os . path . join ( os . environ [ 'GMXDATA' ] , 'top' , 'vdwradii.dat' )
        except KeyError :
            msg = "Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs')."
            logger . exception ( msg )
            raise OSError ( msg , errno . ENOENT )
if not os . path . exists ( filename ) :
    msg = "Cannot find {filename!r}; something is wrong with the Gromacs installation." . format ( ** vars ( ) )
    logger . exception ( msg , errno . ENOENT )
    raise OSError ( msg )
# make sure to catch 3 and 4 letter resnames
patterns = vdw_lipid_resnames + list ( { x [ : 3 ] for x in vdw_lipid_resnames } )
# TODO : should do a tempfile . . .
with open ( vdwradii_dat , 'w' ) as outfile : # write lipid stuff before general
    outfile . write ( '; Special larger vdw radii for solvating lipid membranes\n' )
    for resname in patterns :
        for atom , radius in vdw_lipid_atom_radii . items ( ) :
            outfile . write ( '{resname:4!s} {atom:<5!s} {radius:5.3f}\n' . format ( ** vars ( ) ) )
    with open ( filename , 'r' ) as infile :
        for line in infile :
            outfile . write ( line )
logger . debug ( 'Created lipid vdW radii file {vdwradii_dat!r}.' . format ( ** vars ( ) ) )
return realpath ( vdwradii_dat )


signature:
def solvate ( struct = 'top/protein.pdb' , top = 'top/system.top' , distance = 0.9 , boxtype = 'dodecahedron' , concentration = 0 , cation = 'NA' , anion = 'CL' , water = 'tip4p' , solvent_name = 'SOL' , with_membrane = False , ndx = 'main.ndx' , mainselection = '"Protein"' , dirname = 'solvate' , ** kwargs ) :
    """Put protein into box , add water , add counter - ions .
 Currently this really only supports solutes in water . If you need
 to embedd a protein in a membrane then you will require more
 sophisticated approaches .
 However , you * can * supply a protein already inserted in a
 bilayer . In this case you will probably want to set * distance * =
 ` ` None ` ` and also enable * with _ membrane * = ` ` True ` ` ( using extra
 big vdw radii for typical lipids ) .
 . . Note : : The defaults are suitable for solvating a globular
 protein in a fairly tight ( increase * distance * ! ) dodecahedral
 box .
 : Arguments :
 * struct * : filename
 pdb or gro input structure
 * top * : filename
 Gromacs topology
 * distance * : float
 When solvating with water , make the box big enough so that
 at least * distance * nm water are between the solute * struct *
 and the box boundary .
 Set * boxtype * to ` ` None ` ` in order to use a box size in the input
 file ( gro or pdb ) .
 * boxtype * or * bt * : string
 Any of the box types supported by : class : ` ~ gromacs . tools . Editconf `
 ( triclinic , cubic , dodecahedron , octahedron ) . Set the box dimensions
 either with * distance * or the * box * and * angle * keywords .
 If set to ` ` None ` ` it will ignore * distance * and use the box
 inside the * struct * file .
 * bt * overrides the value of * boxtype * .
 * box *
 List of three box lengths [ A , B , C ] that are used by : class : ` ~ gromacs . tools . Editconf `
 in combination with * boxtype * ( ` ` bt ` ` in : program : ` editconf ` ) and * angles * .
 Setting * box * overrides * distance * .
 * angles *
 List of three angles ( only necessary for triclinic boxes ) .
 * concentration * : float
 Concentration of the free ions in mol / l . Note that counter
 ions are added in excess of this concentration .
 * cation * and * anion * : string
 Molecule names of the ions . This depends on the chosen force field .
 * water * : string
 Name of the water model ; one of " spc " , " spce " , " tip3p " ,
 " tip4p " . This should be appropriate for the chosen force
 field . If an alternative solvent is required , simply supply the path to a box
 with solvent molecules ( used by : func : ` ~ gromacs . genbox ` ' s * cs * argument )
 and also supply the molecule name via * solvent _ name * .
 * solvent _ name *
 Name of the molecules that make up the solvent ( as set in the itp / top ) .
 Typically needs to be changed when using non - standard / non - water solvents .
 [ " SOL " ]
 * with _ membrane * : bool
 ` ` True ` ` : use special ` ` vdwradii . dat ` ` with 0.1 nm - increased radii on
 lipids . Default is ` ` False ` ` .
 * ndx * : filename
 How to name the index file that is produced by this function .
 * mainselection * : string
 A string that is fed to : class : ` ~ gromacs . tools . Make _ ndx ` and
 which should select the solute .
 * dirname * : directory name
 Name of the directory in which all files for the solvation stage are stored .
 * includes *
 List of additional directories to add to the mdp include path
 * kwargs *
 Additional arguments are passed on to
 : class : ` ~ gromacs . tools . Editconf ` or are interpreted as parameters to be
 changed in the mdp file ."""

implementation:
sol = solvate_sol ( struct = struct , top = top , distance = distance , boxtype = boxtype , water = water , solvent_name = solvent_name , with_membrane = with_membrane , dirname = dirname , ** kwargs )
ion = solvate_ion ( struct = sol [ 'struct' ] , top = top , concentration = concentration , cation = cation , anion = anion , solvent_name = solvent_name , ndx = ndx , mainselection = mainselection , dirname = dirname , ** kwargs )
return ion


signature:
def check_mdpargs ( d ) :
    """Check if any arguments remain in dict * d * ."""

implementation:
if len ( d ) > 0 :
    wmsg = "Unprocessed mdp option are interpreted as options for grompp:\n" + str ( d )
    logger . warn ( wmsg )
    warnings . warn ( wmsg , category = UsageWarning )
return len ( d ) == 0


signature:
def energy_minimize ( dirname = 'em' , mdp = config . templates [ 'em.mdp' ] , struct = 'solvate/ionized.gro' , top = 'top/system.top' , output = 'em.pdb' , deffnm = "em" , mdrunner = None , mdrun_args = None , ** kwargs ) :
    """Energy minimize the system .
 This sets up the system ( creates run input files ) and also runs
 ` ` mdrun _ d ` ` . Thus it can take a while .
 Additional itp files should be in the same directory as the top file .
 Many of the keyword arguments below already have sensible values .
 : Keywords :
 * dirname *
 set up under directory dirname [ em ]
 * struct *
 input structure ( gro , pdb , . . . ) [ solvate / ionized . gro ]
 * output *
 output structure ( will be put under dirname ) [ em . pdb ]
 * deffnm *
 default name for mdrun - related files [ em ]
 * top *
 topology file [ top / system . top ]
 * mdp *
 mdp file ( or use the template ) [ templates / em . mdp ]
 * includes *
 additional directories to search for itp files
 * mdrunner *
 : class : ` gromacs . run . MDrunner ` instance ; by default we
 just try : func : ` gromacs . mdrun _ d ` and : func : ` gromacs . mdrun ` but a
 MDrunner instance gives the user the ability to run mpi jobs
 etc . [ None ]
 * mdrun _ args *
 arguments for * mdrunner * ( as a dict ) , e . g . ` ` { ' nt ' : 2 } ` ` ;
 empty by default
 . . versionaddedd : : 0.7.0
 * kwargs *
 remaining key / value pairs that should be changed in the
 template mdp file , eg ` ` nstxtcout = 250 , nstfout = 250 ` ` .
 . . note : : If : func : ` ~ gromacs . mdrun _ d ` is not found , the function
 falls back to : func : ` ~ gromacs . mdrun ` instead ."""

implementation:
structure = realpath ( struct )
topology = realpath ( top )
mdp_template = config . get_template ( mdp )
deffnm = deffnm . strip ( )
mdrun_args = { } if mdrun_args is None else mdrun_args
# write the processed topology to the default output
kwargs . setdefault ( 'pp' , 'processed.top' )
# filter some kwargs that might come through when feeding output
# from previous stages such as solvate ( ) ; necessary because * all *
# * * kwargs must be * either * substitutions in the mdp file * or * valid
# command line parameters for ` ` grompp ` ` .
kwargs . pop ( 'ndx' , None )
# mainselection is not used but only passed through ; right now we
# set it to the default that is being used in all argument lists
# but that is not pretty . TODO .
mainselection = kwargs . pop ( 'mainselection' , '"Protein"' )
# only interesting when passed from solvate ( )
qtot = kwargs . pop ( 'qtot' , 0 )
# mdp is now the * output * MDP that will be generated from mdp _ template
mdp = deffnm + '.mdp'
tpr = deffnm + '.tpr'
logger . info ( "[{dirname!s}] Energy minimization of struct={struct!r}, top={top!r}, mdp={mdp!r} ..." . format ( ** vars ( ) ) )
cbook . add_mdp_includes ( topology , kwargs )
if qtot != 0 : # At the moment this is purely user - reported and really only here because
# it might get fed into the function when using the keyword - expansion pipeline
# usage paradigm .
    wmsg = "Total charge was reported as qtot = {qtot:g} <> 0; probably a problem." . format ( ** vars ( ) )
    logger . warn ( wmsg )
    warnings . warn ( wmsg , category = BadParameterWarning )
with in_dir ( dirname ) :
    unprocessed = cbook . edit_mdp ( mdp_template , new_mdp = mdp , ** kwargs )
    check_mdpargs ( unprocessed )
    gromacs . grompp ( f = mdp , o = tpr , c = structure , r = structure , p = topology , ** unprocessed )
    mdrun_args . update ( v = True , stepout = 10 , deffnm = deffnm , c = output )
    if mdrunner is None :
        mdrun = run . get_double_or_single_prec_mdrun ( )
        mdrun ( ** mdrun_args )
    else :
        if type ( mdrunner ) is type : # class
        # user wants full control and provides simulation . MDrunner * * class * *
        # NO CHECKING - - - in principle user can supply any callback they like
            mdrun = mdrunner ( ** mdrun_args )
            mdrun . run ( )
        else : # anything with a run ( ) method that takes mdrun arguments . . .
            try :
                mdrunner . run ( mdrunargs = mdrun_args )
            except AttributeError :
                logger . error ( "mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method" )
                raise TypeError ( "mdrunner: Provide a gromacs.run.MDrunner class or instance or a callback with a run() method" )
    # em . gro - - > gives ' Bad box in file em . gro ' warning - - - why ? ?
    # - - > use em . pdb instead .
    if not os . path . exists ( output ) :
        errmsg = "Energy minimized system NOT produced."
        logger . error ( errmsg )
        raise GromacsError ( errmsg )
    final_struct = realpath ( output )
logger . info ( "[{dirname!s}] energy minimized structure {final_struct!r}" . format ( ** vars ( ) ) )
return { 'struct' : final_struct , 'top' : topology , 'mainselection' : mainselection , }


signature:
def em_schedule ( ** kwargs ) :
    """Run multiple energy minimizations one after each other .
 : Keywords :
 * integrators *
 list of integrators ( from ' l - bfgs ' , ' cg ' , ' steep ' )
 [ [ ' bfgs ' , ' steep ' ] ]
 * nsteps *
 list of maximum number of steps ; one for each integrator in
 in the * integrators * list [ [ 100,1000 ] ]
 * kwargs *
 mostly passed to : func : ` gromacs . setup . energy _ minimize `
 : Returns : dictionary with paths to final structure ( ' struct ' ) and
 other files
 : Example :
 Conduct three minimizations :
 1 . low memory Broyden - Goldfarb - Fletcher - Shannon ( BFGS ) for 30 steps
 2 . steepest descent for 200 steps
 3 . finish with BFGS for another 30 steps
 We also do a multi - processor minimization when possible ( i . e . for steep
 ( and conjugate gradient ) by using a : class : ` gromacs . run . MDrunner ` class
 for a : program : ` mdrun ` executable compiled for OpenMP in 64 bit ( see
 : mod : ` gromacs . run ` for details ) : :
 import gromacs . run
 gromacs . setup . em _ schedule ( struct = ' solvate / ionized . gro ' ,
 mdrunner = gromacs . run . MDrunnerOpenMP64,
 integrators = [ ' l - bfgs ' , ' steep ' , ' l - bfgs ' ] ,
 nsteps = [ 50,200 , 50 ] )
 . . Note : : You might have to prepare the mdp file carefully because at the
 moment one can only modify the * nsteps * parameter on a
 per - minimizer basis ."""

implementation:
mdrunner = kwargs . pop ( 'mdrunner' , None )
integrators = kwargs . pop ( 'integrators' , [ 'l-bfgs' , 'steep' ] )
kwargs . pop ( 'integrator' , None )
# clean input ; we set intgerator from integrators
nsteps = kwargs . pop ( 'nsteps' , [ 100 , 1000 ] )
outputs = [ 'em{0:03d}_{1!s}.pdb' . format ( i , integrator ) for i , integrator in enumerate ( integrators ) ]
outputs [ - 1 ] = kwargs . pop ( 'output' , 'em.pdb' )
files = { 'struct' : kwargs . pop ( 'struct' , None ) }
# fake output from energy _ minimize ( )
for i , integrator in enumerate ( integrators ) :
    struct = files [ 'struct' ]
    logger . info ( "[em %d] energy minimize with %s for maximum %d steps" , i , integrator , nsteps [ i ] )
    kwargs . update ( { 'struct' : struct , 'output' : outputs [ i ] , 'integrator' : integrator , 'nsteps' : nsteps [ i ] } )
    if not integrator == 'l-bfgs' :
        kwargs [ 'mdrunner' ] = mdrunner
    else :
        kwargs [ 'mdrunner' ] = None
        logger . warning ( "[em %d]  Not using mdrunner for L-BFGS because it cannot " "do parallel runs." , i )
    files = energy_minimize ( ** kwargs )
return files


signature:
def _setup_MD ( dirname , deffnm = 'md' , mdp = config . templates [ 'md_OPLSAA.mdp' ] , struct = None , top = 'top/system.top' , ndx = None , mainselection = '"Protein"' , qscript = config . qscript_template , qname = None , startdir = None , mdrun_opts = "" , budget = None , walltime = 1 / 3. , dt = 0.002 , runtime = 1e3 , ** mdp_kwargs ) :
    """Generic function to set up a ` ` mdrun ` ` MD simulation .
 See the user functions for usage ."""

implementation:
if struct is None :
    raise ValueError ( 'struct must be set to a input structure' )
structure = realpath ( struct )
topology = realpath ( top )
try :
    index = realpath ( ndx )
except AttributeError : # ( that ' s what realpath ( None ) throws . . . )
    index = None
    # None is handled fine below
qname = mdp_kwargs . pop ( 'sgename' , qname )
# compatibility for old scripts
qscript = mdp_kwargs . pop ( 'sge' , qscript )
# compatibility for old scripts
qscript_template = config . get_template ( qscript )
mdp_template = config . get_template ( mdp )
nsteps = int ( float ( runtime ) / float ( dt ) )
mdp = deffnm + '.mdp'
tpr = deffnm + '.tpr'
mainindex = deffnm + '.ndx'
final_structure = deffnm + '.gro'
# guess . . . really depends on templates , could also be DEFFNM . pdb
# write the processed topology to the default output
mdp_parameters = { 'nsteps' : nsteps , 'dt' : dt , 'pp' : 'processed.top' }
mdp_parameters . update ( mdp_kwargs )
cbook . add_mdp_includes ( topology , mdp_parameters )
logger . info ( "[%(dirname)s] input mdp  = %(mdp_template)r" , vars ( ) )
with in_dir ( dirname ) :
    if not ( mdp_parameters . get ( 'Tcoupl' , '' ) . lower ( ) == 'no' or mainselection is None ) :
        logger . info ( "[{dirname!s}] Automatic adjustment of T-coupling groups" . format ( ** vars ( ) ) )
        # make index file in almost all cases ; with mainselection = = None the user
        # takes FULL control and also has to provide the template or index
        groups = make_main_index ( structure , selection = mainselection , oldndx = index , ndx = mainindex )
        natoms = { g [ 'name' ] : float ( g [ 'natoms' ] ) for g in groups }
        tc_group_names = ( '__main__' , '__environment__' )
        # defined in make _ main _ index ( )
        try :
            x = natoms [ '__main__' ] / natoms [ '__environment__' ]
        except KeyError :
            x = 0
            # force using SYSTEM in code below
            wmsg = "Missing __main__ and/or __environment__ index group.\n" "This probably means that you have an atypical system. You can " "set mainselection=None and provide your own mdp and index files " "in order to set up temperature coupling.\n" "If no T-coupling is required then set Tcoupl='no'.\n" "For now we will just couple everything to 'System'."
            logger . warn ( wmsg )
            warnings . warn ( wmsg , category = AutoCorrectionWarning )
        if x < 0.1 : # couple everything together
            tau_t = firstof ( mdp_parameters . pop ( 'tau_t' , 0.1 ) )
            ref_t = firstof ( mdp_parameters . pop ( 'ref_t' , 300 ) )
            # combine all in one T - coupling group
            mdp_parameters [ 'tc-grps' ] = 'System'
            mdp_parameters [ 'tau_t' ] = tau_t
            # this overrides the commandline !
            mdp_parameters [ 'ref_t' ] = ref_t
            # this overrides the commandline !
            mdp_parameters [ 'gen-temp' ] = mdp_parameters . pop ( 'gen_temp' , ref_t )
            wmsg = "Size of __main__ is only %.1f%% of __environment__ so " "we use 'System' for T-coupling and ref_t = %g K and " "tau_t = %g 1/ps (can be changed in mdp_parameters).\n" % ( x * 100 , ref_t , tau_t )
            logger . warn ( wmsg )
            warnings . warn ( wmsg , category = AutoCorrectionWarning )
        else : # couple protein and bath separately
            n_tc_groups = len ( tc_group_names )
            tau_t = asiterable ( mdp_parameters . pop ( 'tau_t' , 0.1 ) )
            ref_t = asiterable ( mdp_parameters . pop ( 'ref_t' , 300 ) )
            if len ( tau_t ) != n_tc_groups :
                tau_t = n_tc_groups * [ tau_t [ 0 ] ]
                wmsg = "%d coupling constants should have been supplied for tau_t. " "Using %f 1/ps for all of them." % ( n_tc_groups , tau_t [ 0 ] )
                logger . warn ( wmsg )
                warnings . warn ( wmsg , category = AutoCorrectionWarning )
            if len ( ref_t ) != n_tc_groups :
                ref_t = n_tc_groups * [ ref_t [ 0 ] ]
                wmsg = "%d temperatures should have been supplied for ref_t. " "Using %g K for all of them." % ( n_tc_groups , ref_t [ 0 ] )
                logger . warn ( wmsg )
                warnings . warn ( wmsg , category = AutoCorrectionWarning )
            mdp_parameters [ 'tc-grps' ] = tc_group_names
            mdp_parameters [ 'tau_t' ] = tau_t
            mdp_parameters [ 'ref_t' ] = ref_t
            mdp_parameters [ 'gen-temp' ] = mdp_parameters . pop ( 'gen_temp' , ref_t [ 0 ] )
        index = realpath ( mainindex )
    if mdp_parameters . get ( 'Tcoupl' , '' ) . lower ( ) == 'no' :
        logger . info ( "Tcoupl == no: disabling all temperature coupling mdp options" )
        mdp_parameters [ 'tc-grps' ] = ""
        mdp_parameters [ 'tau_t' ] = ""
        mdp_parameters [ 'ref_t' ] = ""
        mdp_parameters [ 'gen-temp' ] = ""
    if mdp_parameters . get ( 'Pcoupl' , '' ) . lower ( ) == 'no' :
        logger . info ( "Pcoupl == no: disabling all pressure coupling mdp options" )
        mdp_parameters [ 'tau_p' ] = ""
        mdp_parameters [ 'ref_p' ] = ""
        mdp_parameters [ 'compressibility' ] = ""
    unprocessed = cbook . edit_mdp ( mdp_template , new_mdp = mdp , ** mdp_parameters )
    check_mdpargs ( unprocessed )
    gromacs . grompp ( f = mdp , p = topology , c = structure , n = index , o = tpr , ** unprocessed )
    runscripts = qsub . generate_submit_scripts ( qscript_template , deffnm = deffnm , jobname = qname , budget = budget , startdir = startdir , mdrun_opts = mdrun_opts , walltime = walltime )
logger . info ( "[%(dirname)s] output mdp = %(mdp)r" , vars ( ) )
logger . info ( "[%(dirname)s] output ndx = %(ndx)r" , vars ( ) )
logger . info ( "[%(dirname)s] output tpr = %(tpr)r" , vars ( ) )
logger . info ( "[%(dirname)s] output runscripts = %(runscripts)r" , vars ( ) )
logger . info ( "[%(dirname)s] All files set up for a run time of %(runtime)g ps " "(dt=%(dt)g, nsteps=%(nsteps)g)" % vars ( ) )
kwargs = { 'struct' : realpath ( os . path . join ( dirname , final_structure ) ) , # guess
'top' : topology , 'ndx' : index , # possibly mainindex
'qscript' : runscripts , 'mainselection' : mainselection , 'deffnm' : deffnm , # return deffnm ( tpr = deffnm . tpr ! )
}
kwargs . update ( mdp_kwargs )
# return extra mdp args so that one can use them for prod run
return kwargs


signature:
def MD_restrained ( dirname = 'MD_POSRES' , ** kwargs ) :
    """Set up MD with position restraints .
 Additional itp files should be in the same directory as the top file .
 Many of the keyword arguments below already have sensible values . Note that
 setting * mainselection * = ` ` None ` ` will disable many of the automated
 choices and is often recommended when using your own mdp file .
 : Keywords :
 * dirname *
 set up under directory dirname [ MD _ POSRES ]
 * struct *
 input structure ( gro , pdb , . . . ) [ em / em . pdb ]
 * top *
 topology file [ top / system . top ]
 * mdp *
 mdp file ( or use the template ) [ templates / md . mdp ]
 * ndx *
 index file ( supply when using a custom mdp )
 * includes *
 additional directories to search for itp files
 * mainselection *
 : program : ` make _ ndx ` selection to select main group [ " Protein " ]
 ( If ` ` None ` ` then no canonical index file is generated and
 it is the user ' s responsibility to set * tc _ grps * ,
 * tau _ t * , and * ref _ t * as keyword arguments , or provide the mdp template
 with all parameter pre - set in * mdp * and probably also your own * ndx *
 index file . )
 * deffnm *
 default filename for Gromacs run [ md ]
 * runtime *
 total length of the simulation in ps [ 1000]
 * dt *
 integration time step in ps [ 0.002]
 * qscript *
 script to submit to the queuing system ; by default
 uses the template : data : ` gromacs . config . qscript _ template ` , which can
 be manually set to another template from : data : ` gromacs . config . templates ` ;
 can also be a list of template names .
 * qname *
 name to be used for the job in the queuing system [ PR _ GMX ]
 * mdrun _ opts *
 option flags for the : program : ` mdrun ` command in the queuing system
 scripts such as " - stepout 100 " . [ " " ]
 * kwargs *
 remaining key / value pairs that should be changed in the template mdp
 file , eg ` ` nstxtcout = 250 , nstfout = 250 ` ` or command line options for
 ` ` grompp ` such as ` ` maxwarn = 1 ` ` .
 In particular one can also set * * define * * and activate
 whichever position restraints have been coded into the itp
 and top file . For instance one could have
 * define * = " - DPOSRES _ MainChain - DPOSRES _ LIGAND "
 if these preprocessor constructs exist . Note that there
 * * must not be any space between " - D " and the value . * *
 By default * define * is set to " - DPOSRES " .
 : Returns : a dict that can be fed into : func : ` gromacs . setup . MD `
 ( but check , just in case , especially if you want to
 change the ` ` define ` ` parameter in the mdp file )
 . . Note : : The output frequency is drastically reduced for position
 restraint runs by default . Set the corresponding ` ` nst * ` `
 variables if you require more output . The ` pressure coupling ` _
 option * refcoord _ scaling * is set to " com " by default ( but can
 be changed via * kwargs * ) and the pressure coupling
 algorithm itself is set to * Pcoupl * = " Berendsen " to
 run a stable simulation .
 . . _ ` pressure coupling ` : http : / / manual . gromacs . org / online / mdp _ opt . html # pc"""

implementation:
logger . info ( "[{dirname!s}] Setting up MD with position restraints..." . format ( ** vars ( ) ) )
kwargs . setdefault ( 'struct' , 'em/em.pdb' )
kwargs . setdefault ( 'qname' , 'PR_GMX' )
kwargs . setdefault ( 'define' , '-DPOSRES' )
# reduce size of output files
kwargs . setdefault ( 'nstxout' , '50000' )
# trr pos
kwargs . setdefault ( 'nstvout' , '50000' )
# trr veloc
kwargs . setdefault ( 'nstfout' , '0' )
# trr forces
kwargs . setdefault ( 'nstlog' , '500' )
# log file
kwargs . setdefault ( 'nstenergy' , '2500' )
# edr energy
kwargs . setdefault ( 'nstxtcout' , '5000' )
# xtc pos
# try to get good pressure equilibration
kwargs . setdefault ( 'refcoord_scaling' , 'com' )
kwargs . setdefault ( 'Pcoupl' , "Berendsen" )
new_kwargs = _setup_MD ( dirname , ** kwargs )
# clean up output kwargs
new_kwargs . pop ( 'define' , None )
# but make sure that - DPOSRES does not stay . . .
new_kwargs . pop ( 'refcoord_scaling' , None )
new_kwargs . pop ( 'Pcoupl' , None )
return new_kwargs


signature:
def MD ( dirname = 'MD' , ** kwargs ) :
    """Set up equilibrium MD .
 Additional itp files should be in the same directory as the top file .
 Many of the keyword arguments below already have sensible values . Note that
 setting * mainselection * = ` ` None ` ` will disable many of the automated
 choices and is often recommended when using your own mdp file .
 : Keywords :
 * dirname *
 set up under directory dirname [ MD ]
 * struct *
 input structure ( gro , pdb , . . . ) [ MD _ POSRES / md _ posres . pdb ]
 * top *
 topology file [ top / system . top ]
 * mdp *
 mdp file ( or use the template ) [ templates / md . mdp ]
 * ndx *
 index file ( supply when using a custom mdp )
 * includes *
 additional directories to search for itp files
 * mainselection *
 ` ` make _ ndx ` ` selection to select main group [ " Protein " ]
 ( If ` ` None ` ` then no canonical index file is generated and
 it is the user ' s responsibility to set * tc _ grps * ,
 * tau _ t * , and * ref _ t * as keyword arguments , or provide the mdp template
 with all parameter pre - set in * mdp * and probably also your own * ndx *
 index file . )
 * deffnm *
 default filename for Gromacs run [ md ]
 * runtime *
 total length of the simulation in ps [ 1000]
 * dt *
 integration time step in ps [ 0.002]
 * qscript *
 script to submit to the queuing system ; by default
 uses the template : data : ` gromacs . config . qscript _ template ` , which can
 be manually set to another template from : data : ` gromacs . config . templates ` ;
 can also be a list of template names .
 * qname *
 name to be used for the job in the queuing system [ MD _ GMX ]
 * mdrun _ opts *
 option flags for the : program : ` mdrun ` command in the queuing system
 scripts such as " - stepout 100 - dgdl " . [ " " ]
 * kwargs *
 remaining key / value pairs that should be changed in the template mdp
 file , e . g . ` ` nstxtcout = 250 , nstfout = 250 ` ` or command line options for
 : program ` grompp ` such as ` ` maxwarn = 1 ` ` .
 : Returns : a dict that can be fed into : func : ` gromacs . setup . MD `
 ( but check , just in case , especially if you want to
 change the * define * parameter in the mdp file )"""

implementation:
logger . info ( "[{dirname!s}] Setting up MD..." . format ( ** vars ( ) ) )
kwargs . setdefault ( 'struct' , 'MD_POSRES/md.gro' )
kwargs . setdefault ( 'qname' , 'MD_GMX' )
return _setup_MD ( dirname , ** kwargs )


signature:
def generate_submit_scripts ( templates , prefix = None , deffnm = 'md' , jobname = 'MD' , budget = None , mdrun_opts = None , walltime = 1.0 , jobarray_string = None , startdir = None , npme = None , ** kwargs ) :
    """Write scripts for queuing systems .
 This sets up queuing system run scripts with a simple search and replace in
 templates . See : func : ` gromacs . cbook . edit _ txt ` for details . Shell scripts
 are made executable .
 : Arguments :
 * templates *
 Template file or list of template files . The " files " can also be names
 or symbolic names for templates in the templates directory . See
 : mod : ` gromacs . config ` for details and rules for writing templates .
 * prefix *
 Prefix for the final run script filename ; by default the filename will be
 the same as the template . [ None ]
 * dirname *
 Directory in which to place the submit scripts . [ . ]
 * deffnm *
 Default filename prefix for : program : ` mdrun ` ` ` - deffnm ` ` [ md ]
 * jobname *
 Name of the job in the queuing system . [ MD ]
 * budget *
 Which budget to book the runtime on [ None ]
 * startdir *
 Explicit path on the remote system ( for run scripts that need to ` cd `
 into this directory at the beginning of execution ) [ None ]
 * mdrun _ opts *
 String of additional options for : program : ` mdrun ` .
 * walltime *
 Maximum runtime of the job in hours . [ 1]
 * npme *
 number of PME nodes
 * jobarray _ string *
 Multi - line string that is spliced in for job array functionality
 ( see : func : ` gromacs . qsub . generate _ submit _ array ` ; do not use manually )
 * kwargs *
 all other kwargs are ignored
 : Returns : list of generated run scripts"""

implementation:
if not jobname [ 0 ] . isalpha ( ) :
    jobname = 'MD_' + jobname
    wmsg = "To make the jobname legal it must start with a letter: changed to {0!r}" . format ( jobname )
    logger . warn ( wmsg )
    warnings . warn ( wmsg , category = AutoCorrectionWarning )
if prefix is None :
    prefix = ""
if mdrun_opts is not None :
    mdrun_opts = '"' + str ( mdrun_opts ) + '"'
# TODO : could test if quotes already present
dirname = kwargs . pop ( 'dirname' , os . path . curdir )
wt = Timedelta ( hours = walltime )
walltime = wt . strftime ( "%h:%M:%S" )
wall_hours = wt . ashours
def write_script ( template ) :
    submitscript = os . path . join ( dirname , prefix + os . path . basename ( template ) )
    logger . info ( "Setting up queuing system script {submitscript!r}..." . format ( ** vars ( ) ) )
    # These substitution rules are documented for the user in the module doc string
    qsystem = detect_queuing_system ( template )
    if qsystem is not None and ( qsystem . name == 'Slurm' ) :
        cbook . edit_txt ( template , [ ( '^ *DEFFNM=' , '(?<==)(.*)' , deffnm ) , ( '^#.*(-J)' , '((?<=-J\s))\s*\w+' , jobname ) , ( '^#.*(-A|account_no)' , '((?<=-A\s)|(?<=account_no\s))\s*\w+' , budget ) , ( '^#.*(-t)' , '(?<=-t\s)(\d+:\d+:\d+)' , walltime ) , ( '^ *WALL_HOURS=' , '(?<==)(.*)' , wall_hours ) , ( '^ *STARTDIR=' , '(?<==)(.*)' , startdir ) , ( '^ *NPME=' , '(?<==)(.*)' , npme ) , ( '^ *MDRUN_OPTS=' , '(?<==)("")' , mdrun_opts ) , # only replace literal " "
        ( '^# JOB_ARRAY_PLACEHOLDER' , '^.*$' , jobarray_string ) , ] , newname = submitscript )
        ext = os . path . splitext ( submitscript ) [ 1 ]
    else :
        cbook . edit_txt ( template , [ ( '^ *DEFFNM=' , '(?<==)(.*)' , deffnm ) , ( '^#.*(-N|job_name)' , '((?<=-N\s)|(?<=job_name\s))\s*\w+' , jobname ) , ( '^#.*(-A|account_no)' , '((?<=-A\s)|(?<=account_no\s))\s*\w+' , budget ) , ( '^#.*(-l walltime|wall_clock_limit)' , '(?<==)(\d+:\d+:\d+)' , walltime ) , ( '^ *WALL_HOURS=' , '(?<==)(.*)' , wall_hours ) , ( '^ *STARTDIR=' , '(?<==)(.*)' , startdir ) , ( '^ *NPME=' , '(?<==)(.*)' , npme ) , ( '^ *MDRUN_OPTS=' , '(?<==)("")' , mdrun_opts ) , # only replace literal " "
        ( '^# JOB_ARRAY_PLACEHOLDER' , '^.*$' , jobarray_string ) , ] , newname = submitscript )
        ext = os . path . splitext ( submitscript ) [ 1 ]
    if ext in ( '.sh' , '.csh' , '.bash' ) :
        os . chmod ( submitscript , 0o755 )
    return submitscript
return [ write_script ( template ) for template in config . get_templates ( templates ) ]


signature:
def generate_submit_array ( templates , directories , ** kwargs ) :
    """Generate a array job .
 For each ` ` work _ dir ` ` in * directories * , the array job will
 1 . cd into ` ` work _ dir ` `
 2 . run the job as detailed in the template
 It will use all the queuing system directives found in the
 template . If more complicated set ups are required , then this
 function cannot be used .
 : Arguments :
 * templates *
 Basic template for a single job ; the job array logic is spliced into
 the position of the line : :
 # JOB _ ARRAY _ PLACEHOLDER
 The appropriate commands for common queuing systems ( Sun Gridengine , PBS )
 are hard coded here . The queuing system is detected from the suffix of
 the template .
 * directories *
 List of directories under * dirname * . One task is set up for each
 directory .
 * dirname *
 The array script will be placed in this directory . The * directories *
 * * must * * be located under * dirname * .
 * kwargs *
 See : func : ` gromacs . setup . generate _ submit _ script ` for details ."""

implementation:
dirname = kwargs . setdefault ( 'dirname' , os . path . curdir )
reldirs = [ relpath ( p , start = dirname ) for p in asiterable ( directories ) ]
missing = [ p for p in ( os . path . join ( dirname , subdir ) for subdir in reldirs ) if not os . path . exists ( p ) ]
if len ( missing ) > 0 :
    logger . debug ( "template=%(template)r: dirname=%(dirname)r reldirs=%(reldirs)r" , vars ( ) )
    logger . error ( "Some directories are not accessible from the array script: " "%(missing)r" , vars ( ) )
def write_script ( template ) :
    qsystem = detect_queuing_system ( template )
    if qsystem is None or not qsystem . has_arrays ( ) :
        logger . warning ( "Not known how to make a job array for %(template)r; skipping..." , vars ( ) )
        return None
    kwargs [ 'jobarray_string' ] = qsystem . array ( reldirs )
    return generate_submit_scripts ( template , ** kwargs ) [ 0 ]
# returns list of length 1
# must use config . get _ templates ( ) because we need to access the file for detecting
return [ write_script ( template ) for template in config . get_templates ( templates ) ]


signature:
def array ( self , directories ) :
    """Return multiline string for simple array jobs over * directories * .
 . . Warning : : The string is in ` ` bash ` ` and hence the template must also
 be ` ` bash ` ` ( and * not * ` ` csh ` ` or ` ` sh ` ` ) ."""

implementation:
if not self . has_arrays ( ) :
    raise NotImplementedError ( 'Not known how make array jobs for ' 'queuing system %(name)s' % vars ( self ) )
hrule = '#' + 60 * '-'
lines = [ '' , hrule , '# job array:' , self . array_flag ( directories ) , hrule , '# directories for job tasks' , 'declare -a jobdirs' ]
for i , dirname in enumerate ( asiterable ( directories ) ) :
    idx = i + 1
    # job array indices are 1 - based
    lines . append ( 'jobdirs[{idx:d}]={dirname!r}' . format ( ** vars ( ) ) )
lines . extend ( [ '# Switch to the current tasks directory:' , 'wdir="${{jobdirs[${{{array_variable!s}}}]}}"' . format ( ** vars ( self ) ) , 'cd "$wdir" || { echo "ERROR: failed to enter $wdir."; exit 1; }' , hrule , '' ] )
return "\n" . join ( lines )


signature:
def isMine ( self , scriptname ) :
    """Primitive queuing system detection ; only looks at suffix at the moment ."""

implementation:
suffix = os . path . splitext ( scriptname ) [ 1 ] . lower ( )
if suffix . startswith ( '.' ) :
    suffix = suffix [ 1 : ]
return self . suffix == suffix


signature:
def anumb_to_atom ( self , anumb ) :
    '''Returns the atom object corresponding to an atom number'''

implementation:
assert isinstance ( anumb , int ) , "anumb must be integer"
if not self . _anumb_to_atom : # empty dictionary
    if self . atoms :
        for atom in self . atoms :
            self . _anumb_to_atom [ atom . number ] = atom
        return self . _anumb_to_atom [ anumb ]
    else :
        self . logger ( "no atoms in the molecule" )
        return False
else :
    if anumb in self . _anumb_to_atom :
        return self . _anumb_to_atom [ anumb ]
    else :
        self . logger ( "no such atom number ({0:d}) in the molecule" . format ( anumb ) )
        return False


signature:
def renumber_atoms ( self ) :
    """Reset the molecule ' s atoms : attr : ` number ` to be 1 - indexed"""

implementation:
if self . atoms : # reset the mapping
    self . _anumb_to_atom = { }
    for i , atom in enumerate ( self . atoms ) :
        atom . number = i + 1
# starting from 1
else :
    self . logger ( "the number of atoms is zero - no renumbering" )


signature:
def total_regular_pixels_from_mask ( mask ) :
    """Compute the total number of unmasked regular pixels in a masks ."""

implementation:
total_regular_pixels = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            total_regular_pixels += 1
return total_regular_pixels


signature:
def total_sparse_pixels_from_mask ( mask , unmasked_sparse_grid_pixel_centres ) :
    """Given the full ( i . e . without removing pixels which are outside the regular - masks ) pixelization grid ' s pixel centers
 and the regular - masks , compute the total number of pixels which are within the regular - masks and thus used by the
 pixelization grid .
 Parameters
 mask : ccd . masks . Mask
 The regular - masks within which pixelization pixels must be inside
 unmasked _ sparse _ grid _ pixel _ centres : ndarray
 The centres of the unmasked pixelization grid pixels ."""

implementation:
total_sparse_pixels = 0
for unmasked_sparse_pixel_index in range ( unmasked_sparse_grid_pixel_centres . shape [ 0 ] ) :
    y = unmasked_sparse_grid_pixel_centres [ unmasked_sparse_pixel_index , 0 ]
    x = unmasked_sparse_grid_pixel_centres [ unmasked_sparse_pixel_index , 1 ]
    if not mask [ y , x ] :
        total_sparse_pixels += 1
return total_sparse_pixels


signature:
def mask_circular_from_shape_pixel_scale_and_radius ( shape , pixel_scale , radius_arcsec , centre = ( 0.0 , 0.0 ) ) :
    """Compute a circular masks from an input masks radius and regular shape ."""

implementation:
mask = np . full ( shape , True )
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre ( shape = mask . shape , pixel_scale = pixel_scale , centre = centre )
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        y_arcsec = ( y - centres_arcsec [ 0 ] ) * pixel_scale
        x_arcsec = ( x - centres_arcsec [ 1 ] ) * pixel_scale
        r_arcsec = np . sqrt ( x_arcsec ** 2 + y_arcsec ** 2 )
        if r_arcsec <= radius_arcsec :
            mask [ y , x ] = False
return mask


signature:
def mask_circular_annular_from_shape_pixel_scale_and_radii ( shape , pixel_scale , inner_radius_arcsec , outer_radius_arcsec , centre = ( 0.0 , 0.0 ) ) :
    """Compute an annular masks from an input inner and outer masks radius and regular shape ."""

implementation:
mask = np . full ( shape , True )
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre ( shape = mask . shape , pixel_scale = pixel_scale , centre = centre )
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        y_arcsec = ( y - centres_arcsec [ 0 ] ) * pixel_scale
        x_arcsec = ( x - centres_arcsec [ 1 ] ) * pixel_scale
        r_arcsec = np . sqrt ( x_arcsec ** 2 + y_arcsec ** 2 )
        if outer_radius_arcsec >= r_arcsec >= inner_radius_arcsec :
            mask [ y , x ] = False
return mask


signature:
def mask_elliptical_from_shape_pixel_scale_and_radius ( shape , pixel_scale , major_axis_radius_arcsec , axis_ratio , phi , centre = ( 0.0 , 0.0 ) ) :
    """Compute a circular masks from an input masks radius and regular shape ."""

implementation:
mask = np . full ( shape , True )
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre ( shape = mask . shape , pixel_scale = pixel_scale , centre = centre )
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        y_arcsec = ( y - centres_arcsec [ 0 ] ) * pixel_scale
        x_arcsec = ( x - centres_arcsec [ 1 ] ) * pixel_scale
        r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio ( y_arcsec , x_arcsec , phi , axis_ratio )
        if r_arcsec_elliptical <= major_axis_radius_arcsec :
            mask [ y , x ] = False
return mask


signature:
def mask_elliptical_annular_from_shape_pixel_scale_and_radius ( shape , pixel_scale , inner_major_axis_radius_arcsec , inner_axis_ratio , inner_phi , outer_major_axis_radius_arcsec , outer_axis_ratio , outer_phi , centre = ( 0.0 , 0.0 ) ) :
    """Compute a circular masks from an input masks radius and regular shape ."""

implementation:
mask = np . full ( shape , True )
centres_arcsec = mask_centres_from_shape_pixel_scale_and_centre ( shape = mask . shape , pixel_scale = pixel_scale , centre = centre )
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        y_arcsec = ( y - centres_arcsec [ 0 ] ) * pixel_scale
        x_arcsec = ( x - centres_arcsec [ 1 ] ) * pixel_scale
        inner_r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio ( y_arcsec , x_arcsec , inner_phi , inner_axis_ratio )
        outer_r_arcsec_elliptical = elliptical_radius_from_y_x_phi_and_axis_ratio ( y_arcsec , x_arcsec , outer_phi , outer_axis_ratio )
        if inner_r_arcsec_elliptical >= inner_major_axis_radius_arcsec and outer_r_arcsec_elliptical <= outer_major_axis_radius_arcsec :
            mask [ y , x ] = False
return mask


signature:
def mask_blurring_from_mask_and_psf_shape ( mask , psf_shape ) :
    """Compute a blurring masks from an input masks and psf shape .
 The blurring masks corresponds to all pixels which are outside of the masks but will have a fraction of their light blur into the masked region due to PSF convolution ."""

implementation:
blurring_mask = np . full ( mask . shape , True )
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            for y1 in range ( ( - psf_shape [ 0 ] + 1 ) // 2 , ( psf_shape [ 0 ] + 1 ) // 2 ) :
                for x1 in range ( ( - psf_shape [ 1 ] + 1 ) // 2 , ( psf_shape [ 1 ] + 1 ) // 2 ) :
                    if 0 <= x + x1 <= mask . shape [ 1 ] - 1 and 0 <= y + y1 <= mask . shape [ 0 ] - 1 :
                        if mask [ y + y1 , x + x1 ] :
                            blurring_mask [ y + y1 , x + x1 ] = False
                    else :
                        raise exc . MaskException ( "setup_blurring_mask extends beyond the sub_grid_size of the masks - pad the " "datas array before masking" )
return blurring_mask


signature:
def masked_grid_1d_index_to_2d_pixel_index_from_mask ( mask ) :
    """Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its ( y , x ) pixel indexes .
 For howtolens if pixel [ 2,5 ] corresponds to the second pixel on the 1D array , grid _ to _ pixel [ 1 ] = [ 2,5]"""

implementation:
total_regular_pixels = total_regular_pixels_from_mask ( mask )
grid_to_pixel = np . zeros ( shape = ( total_regular_pixels , 2 ) )
pixel_count = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            grid_to_pixel [ pixel_count , : ] = y , x
            pixel_count += 1
return grid_to_pixel


signature:
def masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask ( mask , sub_grid_size ) :
    """Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its ( y , x ) pixel indexes .
 For howtolens if pixel [ 2,5 ] corresponds to the second pixel on the 1D array , grid _ to _ pixel [ 1 ] = [ 2,5]"""

implementation:
total_sub_pixels = total_sub_pixels_from_mask_and_sub_grid_size ( mask = mask , sub_grid_size = sub_grid_size )
sub_grid_to_sub_pixel = np . zeros ( shape = ( total_sub_pixels , 2 ) )
sub_pixel_count = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            for y1 in range ( sub_grid_size ) :
                for x1 in range ( sub_grid_size ) :
                    sub_grid_to_sub_pixel [ sub_pixel_count , : ] = ( y * sub_grid_size ) + y1 , ( x * sub_grid_size ) + x1
                    sub_pixel_count += 1
return sub_grid_to_sub_pixel


signature:
def total_edge_pixels_from_mask ( mask ) :
    """Compute the total number of borders - pixels in a masks ."""

implementation:
border_pixel_total = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            if mask [ y + 1 , x ] or mask [ y - 1 , x ] or mask [ y , x + 1 ] or mask [ y , x - 1 ] or mask [ y + 1 , x + 1 ] or mask [ y + 1 , x - 1 ] or mask [ y - 1 , x + 1 ] or mask [ y - 1 , x - 1 ] :
                border_pixel_total += 1
return border_pixel_total


signature:
def edge_pixels_from_mask ( mask ) :
    """Compute a 1D array listing all edge pixel indexes in the masks . An edge pixel is a pixel which is not fully surrounding by False masks values i . e . it is on an edge ."""

implementation:
edge_pixel_total = total_edge_pixels_from_mask ( mask )
edge_pixels = np . zeros ( edge_pixel_total )
edge_index = 0
regular_index = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            if mask [ y + 1 , x ] or mask [ y - 1 , x ] or mask [ y , x + 1 ] or mask [ y , x - 1 ] or mask [ y + 1 , x + 1 ] or mask [ y + 1 , x - 1 ] or mask [ y - 1 , x + 1 ] or mask [ y - 1 , x - 1 ] :
                edge_pixels [ edge_index ] = regular_index
                edge_index += 1
            regular_index += 1
return edge_pixels


signature:
def total_border_pixels_from_mask_and_edge_pixels ( mask , edge_pixels , masked_grid_index_to_pixel ) :
    """Compute the total number of borders - pixels in a masks ."""

implementation:
border_pixel_total = 0
for i in range ( edge_pixels . shape [ 0 ] ) :
    if check_if_border_pixel ( mask , edge_pixels [ i ] , masked_grid_index_to_pixel ) :
        border_pixel_total += 1
return border_pixel_total


signature:
def border_pixels_from_mask ( mask ) :
    """Compute a 1D array listing all borders pixel indexes in the masks . A borders pixel is a pixel which :
 1 ) is not fully surrounding by False masks values .
 2 ) Can reach the edge of the array without hitting a masked pixel in one of four directions ( upwards , downwards ,
 left , right ) .
 The borders pixels are thus pixels which are on the exterior edge of the masks . For example , the inner ring of edge pixels in an annular masks are edge pixels but not borders pixels ."""

implementation:
edge_pixels = edge_pixels_from_mask ( mask )
masked_grid_index_to_pixel = masked_grid_1d_index_to_2d_pixel_index_from_mask ( mask )
border_pixel_total = total_border_pixels_from_mask_and_edge_pixels ( mask , edge_pixels , masked_grid_index_to_pixel )
border_pixels = np . zeros ( border_pixel_total )
border_pixel_index = 0
for edge_pixel_index in range ( edge_pixels . shape [ 0 ] ) :
    if check_if_border_pixel ( mask , edge_pixels [ edge_pixel_index ] , masked_grid_index_to_pixel ) :
        border_pixels [ border_pixel_index ] = edge_pixels [ edge_pixel_index ]
        border_pixel_index += 1
return border_pixels


signature:
def bin_up_mask_2d ( mask_2d , bin_up_factor ) :
    """Bin up an array to coarser resolution , by binning up groups of pixels and using their sum value to determine the value of the new pixel .
 If an array of shape ( 8,8 ) is input and the bin up size is 2 , this would return a new array of size ( 4,4 ) where every pixel was the sum of each collection of 2x2 pixels on the ( 8,8 ) array .
 If binning up the array leads to an edge being cut ( e . g . a ( 9,9 ) array binned up by 2 ) , an array is first extracted around the centre of that array .
 Parameters
 mask _ 2d : ndarray
 The 2D array that is resized .
 new _ shape : ( int , int )
 The ( y , x ) new pixel dimension of the trimmed array .
 origin : ( int , int )
 The oigin of the resized array , e . g . the central pixel around which the array is extracted .
 Returns
 ndarray
 The resized 2D array from the input 2D array .
 Examples
 array _ 2d = np . ones ( ( 5,5 ) )
 resize _ array = resize _ array _ 2d ( array _ 2d = array _ 2d , new _ shape = ( 2,2 ) , origin = ( 2 , 2 ) )"""

implementation:
padded_array_2d = array_util . pad_2d_array_for_binning_up_with_bin_up_factor ( array_2d = mask_2d , bin_up_factor = bin_up_factor , pad_value = True )
binned_array_2d = np . zeros ( shape = ( padded_array_2d . shape [ 0 ] // bin_up_factor , padded_array_2d . shape [ 1 ] // bin_up_factor ) )
for y in range ( binned_array_2d . shape [ 0 ] ) :
    for x in range ( binned_array_2d . shape [ 1 ] ) :
        value = True
        for y1 in range ( bin_up_factor ) :
            for x1 in range ( bin_up_factor ) :
                padded_y = y * bin_up_factor + y1
                padded_x = x * bin_up_factor + x1
                if padded_array_2d [ padded_y , padded_x ] == False :
                    value = False
        binned_array_2d [ y , x ] = value
return binned_array_2d


signature:
def plot_fit_subplot_lens_plane_only ( fit , should_plot_mask = True , extract_array_from_mask = False , zoom_around_mask = False , positions = None , should_plot_image_plane_pix = False , units = 'arcsec' , figsize = None , aspect = 'square' , cmap = 'jet' , norm = 'linear' , norm_min = None , norm_max = None , linthresh = 0.05 , linscale = 0.01 , cb_ticksize = 10 , cb_fraction = 0.047 , cb_pad = 0.01 , cb_tick_values = None , cb_tick_labels = None , titlesize = 10 , xlabelsize = 10 , ylabelsize = 10 , xyticksize = 10 , mask_pointsize = 10 , position_pointsize = 10 , grid_pointsize = 1 , output_path = None , output_filename = 'lens_fit' , output_format = 'show' ) :
    """Plot the model datas _ of an analysis , using the * Fitter * class object .
 The visualization and output type can be fully customized .
 Parameters
 fit : autolens . lens . fitting . Fitter
 Class containing fit between the model datas _ and observed lens datas _ ( including residual _ map , chi _ squared _ map etc . )
 output _ path : str
 The path where the datas _ is output if the output _ type is a file format ( e . g . png , fits )
 output _ filename : str
 The name of the file that is output , if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the datas _ is output . File formats ( e . g . png , fits ) output the datas _ to harddisk . ' show ' displays the datas _ in the python interpreter window ."""

implementation:
rows , columns , figsize_tool = plotter_util . get_subplot_rows_columns_figsize ( number_subplots = 6 )
mask = lens_plotter_util . get_mask ( fit = fit , should_plot_mask = should_plot_mask )
if figsize is None :
    figsize = figsize_tool
plt . figure ( figsize = figsize )
plt . subplot ( rows , columns , 1 )
kpc_per_arcsec = fit . tracer . image_plane . kpc_per_arcsec
image_plane_pix_grid = lens_plotter_util . get_image_plane_pix_grid ( should_plot_image_plane_pix , fit )
lens_plotter_util . plot_image ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , image_plane_pix_grid = image_plane_pix_grid , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , grid_pointsize = grid_pointsize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 2 )
lens_plotter_util . plot_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 3 )
lens_plotter_util . plot_signal_to_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 4 )
lens_plotter_util . plot_model_data ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 5 )
lens_plotter_util . plot_residual_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 6 )
lens_plotter_util . plot_chi_squared_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plotter_util . output_subplot_array ( output_path = output_path , output_filename = output_filename , output_format = output_format )
plt . close ( )


signature:
def plot_fit_subplot_lens_and_source_planes ( fit , should_plot_mask = True , extract_array_from_mask = False , zoom_around_mask = False , should_plot_source_grid = False , positions = None , should_plot_image_plane_pix = False , plot_mass_profile_centres = True , units = 'arcsec' , figsize = None , aspect = 'square' , cmap = 'jet' , norm = 'linear' , norm_min = None , norm_max = None , linthresh = 0.05 , linscale = 0.01 , cb_ticksize = 10 , cb_fraction = 0.047 , cb_pad = 0.01 , cb_tick_values = None , cb_tick_labels = None , titlesize = 10 , xlabelsize = 10 , ylabelsize = 10 , xyticksize = 10 , mask_pointsize = 10 , position_pointsize = 10 , grid_pointsize = 1 , output_path = None , output_filename = 'lens_fit' , output_format = 'show' ) :
    """Plot the model datas _ of an analysis , using the * Fitter * class object .
 The visualization and output type can be fully customized .
 Parameters
 fit : autolens . lens . fitting . Fitter
 Class containing fit between the model datas _ and observed lens datas _ ( including residual _ map , chi _ squared _ map etc . )
 output _ path : str
 The path where the datas _ is output if the output _ type is a file format ( e . g . png , fits )
 output _ filename : str
 The name of the file that is output , if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the datas _ is output . File formats ( e . g . png , fits ) output the datas _ to harddisk . ' show ' displays the datas _ in the python interpreter window ."""

implementation:
rows , columns , figsize_tool = plotter_util . get_subplot_rows_columns_figsize ( number_subplots = 9 )
mask = lens_plotter_util . get_mask ( fit = fit , should_plot_mask = should_plot_mask )
if figsize is None :
    figsize = figsize_tool
plt . figure ( figsize = figsize )
kpc_per_arcsec = fit . tracer . image_plane . kpc_per_arcsec
image_plane_pix_grid = lens_plotter_util . get_image_plane_pix_grid ( should_plot_image_plane_pix , fit )
plt . subplot ( rows , columns , 1 )
lens_plotter_util . plot_image ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , image_plane_pix_grid = image_plane_pix_grid , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , grid_pointsize = grid_pointsize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 2 )
lens_plotter_util . plot_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = None , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 3 )
lens_plotter_util . plot_signal_to_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = None , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , position_pointsize = position_pointsize , mask_pointsize = mask_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 4 )
lens_plotter_util . plot_lens_subtracted_image ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , title = 'Fit Lens Subtracted Image' , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , position_pointsize = position_pointsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
if fit . tracer . image_plane . has_light_profile :
    plt . subplot ( rows , columns , 5 )
    lens_plotter_util . plot_model_image_of_planes ( fit = fit , plot_foreground = True , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , plot_mass_profile_centres = plot_mass_profile_centres , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , title = 'Fit Image-Plane Model Image' , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 6 )
lens_plotter_util . plot_model_image_of_planes ( fit = fit , plot_source = True , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , plot_mass_profile_centres = plot_mass_profile_centres , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , title = 'Fit Source-Plane Model Image' , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = 'lens_subtracted_image' , output_format = output_format )
if fit . total_inversions == 0 :
    plt . subplot ( rows , columns , 7 )
    plane_plotters . plot_plane_image ( plane = fit . tracer . source_plane , positions = None , plot_grid = should_plot_source_grid , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , grid_pointsize = grid_pointsize , position_pointsize = position_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
elif fit . total_inversions == 1 :
    ratio = float ( ( fit . inversion . mapper . geometry . arc_second_maxima [ 1 ] - fit . inversion . mapper . geometry . arc_second_minima [ 1 ] ) / ( fit . inversion . mapper . geometry . arc_second_maxima [ 0 ] - fit . inversion . mapper . geometry . arc_second_minima [ 0 ] ) )
    if aspect is 'square' :
        aspect_inv = ratio
    elif aspect is 'auto' :
        aspect_inv = 1.0 / ratio
    elif aspect is 'equal' :
        aspect_inv = 1.0
    plt . subplot ( rows , columns , 7 , aspect = float ( aspect_inv ) )
    inversion_plotters . plot_reconstructed_pixelization ( inversion = fit . inversion , positions = None , should_plot_grid = False , should_plot_centres = False , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = None , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = None , output_format = output_format )
plt . subplot ( rows , columns , 8 )
lens_plotter_util . plot_residual_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 9 )
lens_plotter_util . plot_chi_squared_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plotter_util . output_subplot_array ( output_path = output_path , output_filename = output_filename , output_format = output_format )
plt . close ( )


signature:
def plot_fit_individuals_lens_plane_only ( fit , should_plot_mask = True , extract_array_from_mask = False , zoom_around_mask = False , positions = None , should_plot_image_plane_pix = False , should_plot_image = False , should_plot_noise_map = False , should_plot_signal_to_noise_map = False , should_plot_model_image = False , should_plot_residual_map = False , should_plot_chi_squared_map = False , units = 'arcsec' , output_path = None , output_format = 'show' ) :
    """Plot the model datas _ of an analysis , using the * Fitter * class object .
 The visualization and output type can be fully customized .
 Parameters
 fit : autolens . lens . fitting . Fitter
 Class containing fit between the model datas _ and observed lens datas _ ( including residual _ map , chi _ squared _ map etc . )
 output _ path : str
 The path where the datas _ is output if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the datas _ is output . File formats ( e . g . png , fits ) output the datas _ to harddisk . ' show ' displays the datas _ in the python interpreter window ."""

implementation:
mask = lens_plotter_util . get_mask ( fit = fit , should_plot_mask = should_plot_mask )
kpc_per_arcsec = fit . tracer . image_plane . kpc_per_arcsec
if should_plot_image :
    image_plane_pix_grid = lens_plotter_util . get_image_plane_pix_grid ( should_plot_image_plane_pix , fit )
    lens_plotter_util . plot_image ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , image_plane_pix_grid = image_plane_pix_grid , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_noise_map :
    lens_plotter_util . plot_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_signal_to_noise_map :
    lens_plotter_util . plot_signal_to_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_model_image :
    lens_plotter_util . plot_model_data ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_residual_map :
    lens_plotter_util . plot_residual_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_chi_squared_map :
    lens_plotter_util . plot_chi_squared_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )


signature:
def plot_fit_individuals_lens_and_source_planes ( fit , should_plot_mask = True , extract_array_from_mask = False , zoom_around_mask = False , positions = None , should_plot_image_plane_pix = False , should_plot_image = False , should_plot_noise_map = False , should_plot_signal_to_noise_map = False , should_plot_lens_subtracted_image = False , should_plot_model_image = False , should_plot_lens_model_image = False , should_plot_source_model_image = False , should_plot_source_plane_image = False , should_plot_residual_map = False , should_plot_chi_squared_map = False , units = 'arcsec' , output_path = None , output_format = 'show' ) :
    """Plot the model datas _ of an analysis , using the * Fitter * class object .
 The visualization and output type can be fully customized .
 Parameters
 fit : autolens . lens . fitting . Fitter
 Class containing fit between the model datas _ and observed lens datas _ ( including residual _ map , chi _ squared _ map etc . )
 output _ path : str
 The path where the datas _ is output if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the datas _ is output . File formats ( e . g . png , fits ) output the datas _ to harddisk . ' show ' displays the datas _ in the python interpreter window ."""

implementation:
mask = lens_plotter_util . get_mask ( fit = fit , should_plot_mask = should_plot_mask )
kpc_per_arcsec = fit . tracer . image_plane . kpc_per_arcsec
if should_plot_image :
    image_plane_pix_grid = lens_plotter_util . get_image_plane_pix_grid ( should_plot_image_plane_pix , fit )
    lens_plotter_util . plot_image ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , image_plane_pix_grid = image_plane_pix_grid , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_noise_map :
    lens_plotter_util . plot_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_signal_to_noise_map :
    lens_plotter_util . plot_signal_to_noise_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_lens_subtracted_image :
    lens_plotter_util . plot_lens_subtracted_image ( fit = fit , mask = mask , positions = positions , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_model_image :
    lens_plotter_util . plot_model_data ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_lens_model_image :
    lens_plotter_util . plot_model_image_of_planes ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , plot_foreground = True , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_filename = 'fit_lens_plane_model_image' , output_format = output_format )
if should_plot_source_model_image :
    lens_plotter_util . plot_model_image_of_planes ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , plot_source = True , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_filename = 'fit_source_plane_model_image' , output_format = output_format )
if should_plot_source_plane_image :
    if fit . total_inversions == 0 :
        plane_plotters . plot_plane_image ( plane = fit . tracer . source_plane , plot_grid = True , units = units , figsize = ( 20 , 20 ) , output_path = output_path , output_filename = 'fit_source_plane' , output_format = output_format )
    elif fit . total_inversions == 1 :
        inversion_plotters . plot_reconstructed_pixelization ( inversion = fit . inversion , should_plot_grid = True , units = units , figsize = ( 20 , 20 ) , output_path = output_path , output_filename = 'fit_source_plane' , output_format = output_format )
if should_plot_residual_map :
    lens_plotter_util . plot_residual_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )
if should_plot_chi_squared_map :
    lens_plotter_util . plot_chi_squared_map ( fit = fit , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , kpc_per_arcsec = kpc_per_arcsec , output_path = output_path , output_format = output_format )


signature:
def setup_figure ( figsize , as_subplot ) :
    """Setup a figure for plotting an image .
 Parameters
 figsize : ( int , int )
 The size of the figure in ( rows , columns ) .
 as _ subplot : bool
 If the figure is a subplot , the setup _ figure function is omitted to ensure that each subplot does not create a new figure and so that it can be output using the * output _ subplot _ array * function ."""

implementation:
if not as_subplot :
    fig = plt . figure ( figsize = figsize )
    return fig


signature:
def output_figure ( array , as_subplot , output_path , output_filename , output_format ) :
    """Output the figure , either as an image on the screen or to the hard - disk as a . png or . fits file .
 Parameters
 array : ndarray
 The 2D array of image to be output , required for outputting the image as a fits file .
 as _ subplot : bool
 Whether the figure is part of subplot , in which case the figure is not output so that the entire subplot can be output instead using the * output _ subplot _ array * function .
 output _ path : str
 The path on the hard - disk where the figure is output .
 output _ filename : str
 The filename of the figure that is output .
 output _ format : str
 The format the figue is output :
 ' show ' - display on computer screen .
 ' png ' - output to hard - disk as a png .
 ' fits ' - output to hard - disk as a fits file . '"""

implementation:
if not as_subplot :
    if output_format is 'show' :
        plt . show ( )
    elif output_format is 'png' :
        plt . savefig ( output_path + output_filename + '.png' , bbox_inches = 'tight' )
    elif output_format is 'fits' :
        array_util . numpy_array_2d_to_fits ( array_2d = array , file_path = output_path + output_filename + '.fits' , overwrite = True )


signature:
def output_subplot_array ( output_path , output_filename , output_format ) :
    """Output a figure which consists of a set of subplot , , either as an image on the screen or to the hard - disk as a . png file .
 Parameters
 output _ path : str
 The path on the hard - disk where the figure is output .
 output _ filename : str
 The filename of the figure that is output .
 output _ format : str
 The format the figue is output :
 ' show ' - display on computer screen .
 ' png ' - output to hard - disk as a png ."""

implementation:
if output_format is 'show' :
    plt . show ( )
elif output_format is 'png' :
    plt . savefig ( output_path + output_filename + '.png' , bbox_inches = 'tight' )
elif output_format is 'fits' :
    raise exc . PlottingException ( 'You cannot output a subplots with format .fits' )


signature:
def image_psf_shape_tag_from_image_psf_shape ( image_psf_shape ) :
    """Generate an image psf shape tag , to customize phase names based on size of the image PSF that the original PSF is trimmed to for faster run times .
 This changes the phase name ' phase _ name ' as follows :
 image _ psf _ shape = 1 - > phase _ name
 image _ psf _ shape = 2 - > phase _ name _ image _ psf _ shape _ 2
 image _ psf _ shape = 2 - > phase _ name _ image _ psf _ shape _ 2"""

implementation:
if image_psf_shape is None :
    return ''
else :
    y = str ( image_psf_shape [ 0 ] )
    x = str ( image_psf_shape [ 1 ] )
    return ( '_image_psf_' + y + 'x' + x )


signature:
def inversion_psf_shape_tag_from_inversion_psf_shape ( inversion_psf_shape ) :
    """Generate an inversion psf shape tag , to customize phase names based on size of the inversion PSF that the original PSF is trimmed to for faster run times .
 This changes the phase name ' phase _ name ' as follows :
 inversion _ psf _ shape = 1 - > phase _ name
 inversion _ psf _ shape = 2 - > phase _ name _ inversion _ psf _ shape _ 2
 inversion _ psf _ shape = 2 - > phase _ name _ inversion _ psf _ shape _ 2"""

implementation:
if inversion_psf_shape is None :
    return ''
else :
    y = str ( inversion_psf_shape [ 0 ] )
    x = str ( inversion_psf_shape [ 1 ] )
    return ( '_inv_psf_' + y + 'x' + x )


signature:
def bulge_disk_tag_from_align_bulge_disks ( align_bulge_disk_centre , align_bulge_disk_axis_ratio , align_bulge_disk_phi ) :
    """Generate a tag for the alignment of the geometry of the bulge and disk of a bulge - disk system , to customize \
 phase names based on the bulge - disk model . This adds together the bulge _ disk tags generated in the 3 functions
 above"""

implementation:
align_bulge_disk_centre_tag = align_bulge_disk_centre_tag_from_align_bulge_disk_centre ( align_bulge_disk_centre = align_bulge_disk_centre )
align_bulge_disk_axis_ratio_tag = align_bulge_disk_axis_ratio_tag_from_align_bulge_disk_axis_ratio ( align_bulge_disk_axis_ratio = align_bulge_disk_axis_ratio )
align_bulge_disk_phi_tag = align_bulge_disk_phi_tag_from_align_bulge_disk_phi ( align_bulge_disk_phi = align_bulge_disk_phi )
return align_bulge_disk_centre_tag + align_bulge_disk_axis_ratio_tag + align_bulge_disk_phi_tag


signature:
def ordered_plane_redshifts_from_galaxies ( galaxies ) :
    """Given a list of galaxies ( with redshifts ) , return a list of the redshifts in ascending order .
 If two or more galaxies have the same redshift that redshift is not double counted .
 Parameters
 galaxies : [ Galaxy ]
 The list of galaxies in the ray - tracing calculation ."""

implementation:
ordered_galaxies = sorted ( galaxies , key = lambda galaxy : galaxy . redshift , reverse = False )
# Ideally we ' d extract the planes _ red _ Shfit order from the list above . However , I dont know how to extract it
# Using a list of class attributes so make a list of redshifts for now .
galaxy_redshifts = list ( map ( lambda galaxy : galaxy . redshift , ordered_galaxies ) )
return [ redshift for i , redshift in enumerate ( galaxy_redshifts ) if redshift not in galaxy_redshifts [ : i ] ]


signature:
def ordered_plane_redshifts_from_lens_and_source_plane_redshifts_and_slice_sizes ( lens_redshifts , planes_between_lenses , source_plane_redshift ) :
    """Given a set of lens plane redshifts , the source - plane redshift and the number of planes between each , setup the plane redshifts using these values . A lens redshift corresponds to the ' main ' lens galaxy ( s ) ,
 whereas the slices collect line - of - sight halos over a range of redshifts .
 The source - plane redshift is removed from the ordered plane redshifts that are returned , so that galaxies are not planed at the source - plane redshift .
 For example , if the main plane redshifts are [ 1.0 , 2.0 ] , and the bin sizes are [ 1,3 ] , the following redshift slices for planes will be used :
 z = 0.5
 z = 1.0
 z = 1.25
 z = 1.5
 z = 1.75
 z = 2.0
 Parameters
 lens _ redshifts : [ float ]
 The redshifts of the main - planes ( e . g . the lens galaxy ) , which determine where redshift intervals are placed .
 planes _ between _ lenses : [ int ]
 The number of slices between each main plane . The first entry in this list determines the number of slices between Earth ( redshift 0.0 ) and main plane 0 , the next between main planes 0 and 1 , etc .
 source _ plane _ redshift : float
 The redshift of the source - plane , which is input explicitly to ensure galaxies are not placed in the source - plane ."""

implementation:
# Check that the number of slices between lens planes is equal to the number of intervals between the lens planes .
if len ( lens_redshifts ) != len ( planes_between_lenses ) - 1 :
    raise exc . RayTracingException ( 'The number of lens_plane_redshifts input is not equal to the number of ' 'slices_between_lens_planes+1.' )
plane_redshifts = [ ]
# Add redshift 0.0 and the source plane redshifit to the lens plane redshifts , so that calculation below can use
# them when dividing slices . These will be removed by the return function at the end from the plane redshifts .
lens_redshifts . insert ( 0 , 0.0 )
lens_redshifts . append ( source_plane_redshift )
for lens_plane_index in range ( 1 , len ( lens_redshifts ) ) :
    previous_plane_redshift = lens_redshifts [ lens_plane_index - 1 ]
    plane_redshift = lens_redshifts [ lens_plane_index ]
    slice_total = planes_between_lenses [ lens_plane_index - 1 ]
    plane_redshifts += list ( np . linspace ( previous_plane_redshift , plane_redshift , slice_total + 2 ) ) [ 1 : ]
return plane_redshifts [ 0 : - 1 ]


signature:
def galaxies_in_redshift_ordered_planes_from_galaxies ( galaxies , plane_redshifts ) :
    """Given a list of galaxies ( with redshifts ) , return a list of the galaxies where each entry contains a list of galaxies at the same redshift in ascending redshift order .
 Parameters
 galaxies : [ Galaxy ]
 The list of galaxies in the ray - tracing calculation ."""

implementation:
galaxies_in_redshift_ordered_planes = [ [ ] for i in range ( len ( plane_redshifts ) ) ]
for galaxy in galaxies :
    index = ( np . abs ( np . asarray ( plane_redshifts ) - galaxy . redshift ) ) . argmin ( )
    galaxies_in_redshift_ordered_planes [ index ] . append ( galaxy )
return galaxies_in_redshift_ordered_planes


signature:
def compute_deflections_at_next_plane ( plane_index , total_planes ) :
    """This function determines whether the tracer should compute the deflections at the next plane .
 This is True if there is another plane after this plane , else it is False . .
 Parameters
 plane _ index : int
 The index of the plane we are deciding if we should compute its deflections .
 total _ planes : int
 The total number of planes ."""

implementation:
if plane_index < total_planes - 1 :
    return True
elif plane_index == total_planes - 1 :
    return False
else :
    raise exc . RayTracingException ( 'A galaxy was not correctly allocated its previous / next redshifts' )


signature:
def scaled_deflection_stack_from_plane_and_scaling_factor ( plane , scaling_factor ) :
    """Given a plane and scaling factor , compute a set of scaled deflections .
 Parameters
 plane : plane . Plane
 The plane whose deflection stack is scaled .
 scaling _ factor : float
 The factor the deflection angles are scaled by , which is typically the scaling factor between redshifts for multi - plane lensing ."""

implementation:
def scale ( grid ) :
    return np . multiply ( scaling_factor , grid )
if plane . deflection_stack is not None :
    return plane . deflection_stack . apply_function ( scale )
else :
    return None


signature:
def grid_stack_from_deflection_stack ( grid_stack , deflection_stack ) :
    """For a deflection stack , comput a new grid stack but subtracting the deflections"""

implementation:
if deflection_stack is not None :
    def minus ( grid , deflections ) :
        return grid - deflections
    return grid_stack . map_function ( minus , deflection_stack )


signature:
def plot_ray_tracing_subplot ( tracer , mask = None , extract_array_from_mask = False , zoom_around_mask = False , positions = None , units = 'arcsec' , figsize = None , aspect = 'square' , cmap = 'jet' , norm = 'linear' , norm_min = None , norm_max = None , linthresh = 0.05 , linscale = 0.01 , cb_ticksize = 10 , cb_fraction = 0.047 , cb_pad = 0.01 , cb_tick_values = None , cb_tick_labels = None , titlesize = 10 , xlabelsize = 10 , ylabelsize = 10 , xyticksize = 10 , mask_pointsize = 10 , position_pointsize = 10.0 , grid_pointsize = 1.0 , output_path = None , output_filename = 'tracer' , output_format = 'show' ) :
    """Plot the observed _ tracer of an analysis , using the * CCD * class object .
 The visualization and output type can be fully customized .
 Parameters
 tracer : autolens . ccd . tracer . CCD
 Class containing the _ tracer , noise _ map - mappers and PSF that are to be plotted .
 The font size of the figure ylabel .
 output _ path : str
 The path where the _ tracer is output if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the _ tracer is output . File formats ( e . g . png , fits ) output the _ tracer to harddisk . ' show ' displays the _ tracer in the python interpreter window ."""

implementation:
rows , columns , figsize_tool = plotter_util . get_subplot_rows_columns_figsize ( number_subplots = 6 )
if figsize is None :
    figsize = figsize_tool
plt . figure ( figsize = figsize )
plt . subplot ( rows , columns , 1 )
plot_image_plane_image ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , position_pointsize = position_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
if tracer . has_mass_profile :
    plt . subplot ( rows , columns , 2 )
    plot_convergence ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
    plt . subplot ( rows , columns , 3 )
    plot_potential ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plt . subplot ( rows , columns , 4 )
plane_plotters . plot_plane_image ( plane = tracer . source_plane , as_subplot = True , positions = None , plot_grid = False , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , grid_pointsize = grid_pointsize , output_path = output_path , output_filename = '' , output_format = output_format )
if tracer . has_mass_profile :
    plt . subplot ( rows , columns , 5 )
    plot_deflections_y ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
    plt . subplot ( rows , columns , 6 )
    plot_deflections_x ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_filename = '' , output_format = output_format )
plotter_util . output_subplot_array ( output_path = output_path , output_filename = output_filename , output_format = output_format )
plt . close ( )


signature:
def plot_ray_tracing_individual ( tracer , mask = None , extract_array_from_mask = False , zoom_around_mask = False , positions = None , should_plot_image_plane_image = False , should_plot_source_plane = False , should_plot_convergence = False , should_plot_potential = False , should_plot_deflections = False , units = 'arcsec' , output_path = None , output_format = 'show' ) :
    """Plot the observed _ tracer of an analysis , using the * CCD * class object .
 The visualization and output type can be fully customized .
 Parameters
 tracer : autolens . ccd . tracer . CCD
 Class containing the _ tracer , noise _ map - mappers and PSF that are to be plotted .
 The font size of the figure ylabel .
 output _ path : str
 The path where the _ tracer is output if the output _ type is a file format ( e . g . png , fits )
 output _ format : str
 How the _ tracer is output . File formats ( e . g . png , fits ) output the _ tracer to harddisk . ' show ' displays the _ tracer in the python interpreter window ."""

implementation:
if should_plot_image_plane_image :
    plot_image_plane_image ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , units = units , output_path = output_path , output_format = output_format )
if should_plot_convergence :
    plot_convergence ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_potential :
    plot_potential ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_source_plane :
    plane_plotters . plot_plane_image ( plane = tracer . source_plane , positions = None , plot_grid = False , units = units , output_path = output_path , output_filename = 'tracer_source_plane' , output_format = output_format )
if should_plot_deflections :
    plot_deflections_y ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_deflections :
    plot_deflections_x ( tracer = tracer , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )


signature:
def constant_regularization_matrix_from_pixel_neighbors ( coefficients , pixel_neighbors , pixel_neighbors_size ) :
    """From the pixel - neighbors , setup the regularization matrix using the constant regularization scheme .
 Parameters
 coefficients : tuple
 The regularization coefficients which controls the degree of smoothing of the inversion reconstruction .
 pixel _ neighbors : ndarray
 An array of length ( total _ pixels ) which provides the index of all neighbors of every pixel in the Voronoi grid ( entries of - 1 correspond to no neighbor ) .
 pixel _ neighbors _ size : ndarrayy
 An array of length ( total _ pixels ) which gives the number of neighbors of every pixel in the Voronoi grid ."""

implementation:
pixels = len ( pixel_neighbors )
regularization_matrix = np . zeros ( shape = ( pixels , pixels ) )
regularization_coefficient = coefficients [ 0 ] ** 2.0
for i in range ( pixels ) :
    regularization_matrix [ i , i ] += 1e-8
    for j in range ( pixel_neighbors_size [ i ] ) :
        neighbor_index = pixel_neighbors [ i , j ]
        regularization_matrix [ i , i ] += regularization_coefficient
        regularization_matrix [ i , neighbor_index ] -= regularization_coefficient
return regularization_matrix


signature:
def weighted_pixel_signals_from_images ( pixels , signal_scale , regular_to_pix , galaxy_image ) :
    """Compute the ( scaled ) signal in each pixel , where the signal is the sum of its datas _ - pixel fluxes . These pixel - signals are used to compute the effective regularization weight of each pixel .
 The pixel signals are scaled in the following ways :
 1 ) Divided by the number of datas _ - pixels in the pixel , to ensure all pixels have the same ' relative ' signal ( i . e . a pixel with 10 regular - pixels doesn ' t have x2 the signal of one with 5 ) .
 2 ) Divided by the maximum pixel - signal , so that all signals vary between 0 and 1 . This ensures that the regularizations weights are defined identically for any datas _ units or signal - to - noise _ map ratio .
 3 ) Raised to the power of the hyper - parameter * signal _ scale * , so the method can control the relative contribution regularization in different regions of pixelization .
 Parameters
 pixels : int
 The total number of pixels in the pixelization the regularization scheme is applied to .
 signal _ scale : float
 A factor which controls how rapidly the smoothness of regularization varies from high signal regions to low signal regions .
 regular _ to _ pix : ndarray
 A 1D array mapping every pixel on the regular - grid to a pixel on the pixelization .
 galaxy _ image : ndarray
 The image of the galaxy which is used to compute the weigghted pixel signals ."""

implementation:
pixel_signals = np . zeros ( ( pixels , ) )
pixel_sizes = np . zeros ( ( pixels , ) )
for regular_index in range ( galaxy_image . shape [ 0 ] ) :
    pixel_signals [ regular_to_pix [ regular_index ] ] += galaxy_image [ regular_index ]
    pixel_sizes [ regular_to_pix [ regular_index ] ] += 1
pixel_signals /= pixel_sizes
pixel_signals /= np . max ( pixel_signals )
return pixel_signals ** signal_scale


signature:
def weighted_regularization_matrix_from_pixel_neighbors ( regularization_weights , pixel_neighbors , pixel_neighbors_size ) :
    """From the pixel - neighbors , setup the regularization matrix using the weighted regularization scheme .
 Parameters
 regularization _ weights : ndarray
 The regularization _ weight of each pixel , which governs how much smoothing is applied to that individual pixel .
 pixel _ neighbors : ndarray
 An array of length ( total _ pixels ) which provides the index of all neighbors of every pixel in the Voronoi grid ( entries of - 1 correspond to no neighbor ) .
 pixel _ neighbors _ size : ndarrayy
 An array of length ( total _ pixels ) which gives the number of neighbors of every pixel in the Voronoi grid ."""

implementation:
pixels = len ( regularization_weights )
regularization_matrix = np . zeros ( shape = ( pixels , pixels ) )
regularization_weight = regularization_weights ** 2.0
for i in range ( pixels ) :
    for j in range ( pixel_neighbors_size [ i ] ) :
        neighbor_index = pixel_neighbors [ i , j ]
        regularization_matrix [ i , i ] += regularization_weight [ neighbor_index ]
        regularization_matrix [ neighbor_index , neighbor_index ] += regularization_weight [ neighbor_index ]
        regularization_matrix [ i , neighbor_index ] -= regularization_weight [ neighbor_index ]
        regularization_matrix [ neighbor_index , i ] -= regularization_weight [ neighbor_index ]
return regularization_matrix