text:
# Automatically generated using Clang.jl wrap_c, version 0.0.0

using Compat

# Skipping MacroDefinition: EOF ( - 1
# Skipping MacroDefinition: getc_unlocked ( fp ) __sgetc ( fp
# Skipping MacroDefinition: putc_unlocked ( x , fp ) __sputc ( x , fp
# Skipping MacroDefinition: getchar_unlocked ( ) getc_unlocked ( stdin
# Skipping MacroDefinition: putchar_unlocked ( x ) putc_unlocked ( x , stdout
# Skipping MacroDefinition: fropen ( cookie , fn ) funopen ( cookie , fn , 0 , 0 , 0
# Skipping MacroDefinition: fwopen ( cookie , fn ) funopen ( cookie , 0 , fn , 0 , 0
# Skipping MacroDefinition: feof_unlocked ( p ) __sfeof ( p
# Skipping MacroDefinition: ferror_unlocked ( p ) __sferror ( p
# Skipping MacroDefinition: clearerr_unlocked ( p ) __sclearerr ( p
# Skipping MacroDefinition: fileno_unlocked ( p ) __sfileno ( p
# Skipping MacroDefinition: sprintf ( str , ... ) __builtin___sprintf_chk ( str , 0 , __darwin_obsz ( str ) , __VA_ARGS__
# Skipping MacroDefinition: snprintf ( str , len , ... ) __builtin___snprintf_chk ( str , len , 0 , __darwin_obsz ( str ) , __VA_ARGS__
# Skipping MacroDefinition: vsprintf ( str , format , ap ) __builtin___vsprintf_chk ( str , 0 , __darwin_obsz ( str ) , format , ap
# Skipping MacroDefinition: vsnprintf ( str , len , format , ap ) __builtin___vsnprintf_chk ( str , len , 0 , __darwin_obsz ( str ) , format , ap
# Skipping MacroDefinition: SILO_VERSION_GE ( Maj , Min , Pat ) ( ( ( SILO_VERS_MAJ == Maj ) && ( SILO_VERS_MIN == Min ) && ( SILO_VERS_PAT >= Pat ) ) || ( ( SILO_VERS_MAJ == Maj ) && ( SILO_VERS_MIN > Min ) ) || ( SILO_VERS_MAJ > Maj )
# Skipping MacroDefinition: DB_VERSION_GE ( Maj , Min , Pat ) SILO_VERSION_GE ( Maj , Min , Pat
# Skipping MacroDefinition: DB_HDF5_OPTS ( OptsId ) ( DB_HDF5X | ( ( OptsId & 0x3F ) << 11 )
# Skipping MacroDefinition: DB_HDF5 DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_DEFAULT
# Skipping MacroDefinition: DB_HDF5_SEC2 DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_SEC2
# Skipping MacroDefinition: DB_HDF5_STDIO DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_STDIO
# Skipping MacroDefinition: DB_HDF5_CORE DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_CORE
# Skipping MacroDefinition: DB_HDF5_LOG DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_LOG
# Skipping MacroDefinition: DB_HDF5_SPLIT DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_SPLIT
# Skipping MacroDefinition: DB_HDF5_DIRECT DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_DIRECT
# Skipping MacroDefinition: DB_HDF5_FAMILY DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_FAMILY
# Skipping MacroDefinition: DB_HDF5_MPIO DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_MPIO
# Skipping MacroDefinition: DB_HDF5_MPIOP DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_MPIP
# Skipping MacroDefinition: DB_HDF5_MPIP DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_MPIP
# Skipping MacroDefinition: DB_HDF5_SILO DB_HDF5_OPTS ( DB_FILE_OPTS_H5_DEFAULT_SILO

# const DB_OFF = (-)

# Skipping MacroDefinition: DB_GHOSTTYPE_NOGHOST ( ( char ) 0x00
# Skipping MacroDefinition: DB_GHOSTTYPE_INTDUP ( ( char ) 0x01
# Skipping MacroDefinition: DB_F77NULL ( - 99
# Skipping MacroDefinition: I4D ( s , i , j , k , l ) ( l ) * s [ 3 ] + ( k ) * s [ 2 ] + ( j ) * s [ 1 ] + ( i ) * s [ 0
# Skipping MacroDefinition: I3D ( s , i , j , k ) ( k ) * s [ 2 ] + ( j ) * s [ 1 ] + ( i ) * s [ 0
# Skipping MacroDefinition: I2D ( s , i , j ) ( j ) * s [ 1 ] + ( i ) * s [ 0
# Skipping MacroDefinition: DB_MISSING_VALUE_NOT_SET ( ( double ) 1.0e+308

# const SiloCheckVersion = SILO_VERS_TAG

# Skipping MacroDefinition: DBSetDataReadMask ( A ) ,
# Skipping MacroDefinition: DBGetDataReadMask ( ) ,
# Skipping MacroDefinition: DBOpen ( NM , DR , MD ) ( SiloCheckVersion , DBOpenReal ( NM , DR , MD )
# Skipping MacroDefinition: DBCreate ( NM , MD , TG , NF , DR ) ( SiloCheckVersion , DBCreateReal ( NM , MD , TG , NF , DR )
# Skipping MacroDefinition: DBInqFile ( NM ) ( SiloCheckVersion , DBInqFileReal ( NM )

# type _opaque_pthread_attr_t
#     __sig::Clong
#     __opaque::NTuple{56,UInt8}
# end
#
# type _opaque_pthread_cond_t
#     __sig::Clong
#     __opaque::NTuple{40,UInt8}
# end
#
# type _opaque_pthread_condattr_t
#     __sig::Clong
#     __opaque::NTuple{8,UInt8}
# end
#
# type _opaque_pthread_mutex_t
#     __sig::Clong
#     __opaque::NTuple{56,UInt8}
# end
#
# type _opaque_pthread_mutexattr_t
#     __sig::Clong
#     __opaque::NTuple{8,UInt8}
# end
#
# type _opaque_pthread_once_t
#     __sig::Clong
#     __opaque::NTuple{8,UInt8}
# end
#
# type _opaque_pthread_rwlock_t
#     __sig::Clong
#     __opaque::NTuple{192,UInt8}
# end
#
# type _opaque_pthread_rwlockattr_t
#     __sig::Clong
#     __opaque::NTuple{16,UInt8}
# end
#
# type _opaque_pthread_t
#     __sig::Clong
#     __cleanup_stack::Ptr{Nothing}
#     __opaque::NTuple{8176,UInt8}
# end

# const va_list = __darwin_va_list
# const size_t = __darwin_size_t
# const fpos_t = __darwin_off_t
# const FILE = Nothing
# const off_t = __darwin_off_t
# const ssize_t = __darwin_ssize_t
# const DBVCP1_t = Ptr{Nothing}
# const DBVCP2_t = Ptr{Nothing}
# const DBVCP3_t = Ptr{Nothing}
# const DBCAS_t = Ptr{Cstring}

# begin enum ANONYMOUS_1
const ANONYMOUS_1 = Cint
const DB_INVALID_OBJECT = (Int32)(-1)
const DB_QUADRECT = (Int32)(130)
const DB_QUADCURV = (Int32)(131)
const DB_QUADMESH = (Int32)(500)
const DB_QUADVAR = (Int32)(501)
const DB_UCDMESH = (Int32)(510)
const DB_UCDVAR = (Int32)(511)
const DB_MULTIMESH = (Int32)(520)
const DB_MULTIVAR = (Int32)(521)
const DB_MULTIMAT = (Int32)(522)
const DB_MULTIMATSPECIES = (Int32)(523)
const DB_MULTIBLOCKMESH = (Int32)(520)
const DB_MULTIBLOCKVAR = (Int32)(521)
const DB_MULTIMESHADJ = (Int32)(524)
const DB_MATERIAL = (Int32)(530)
const DB_MATSPECIES = (Int32)(531)
const DB_FACELIST = (Int32)(550)
const DB_ZONELIST = (Int32)(551)
const DB_EDGELIST = (Int32)(552)
const DB_PHZONELIST = (Int32)(553)
const DB_CSGZONELIST = (Int32)(554)
const DB_CSGMESH = (Int32)(555)
const DB_CSGVAR = (Int32)(556)
const DB_CURVE = (Int32)(560)
const DB_DEFVARS = (Int32)(565)
const DB_POINTMESH = (Int32)(570)
const DB_POINTVAR = (Int32)(571)
const DB_ARRAY = (Int32)(580)
const DB_DIR = (Int32)(600)
const DB_VARIABLE = (Int32)(610)
const DB_MRGTREE = (Int32)(611)
const DB_GROUPELMAP = (Int32)(612)
const DB_MRGVAR = (Int32)(613)
const DB_USERDEF = (Int32)(700)
# end enum ANONYMOUS_1

const DBObjectType = Nothing

# begin enum ANONYMOUS_2
const ANONYMOUS_2 = UInt32
const DB_INT = (UInt32)(16)
const DB_SHORT = (UInt32)(17)
const DB_LONG = (UInt32)(18)
const DB_FLOAT = (UInt32)(19)
const DB_DOUBLE = (UInt32)(20)
const DB_CHAR = (UInt32)(21)
const DB_LONG_LONG = (UInt32)(22)
const DB_NOTYPE = (UInt32)(25)
# end enum ANONYMOUS_2

const DBdatatype = Nothing

type DBtoc_
    curve_names::Ptr{Cstring}
    ncurve::Cint
    multimesh_names::Ptr{Cstring}
    nmultimesh::Cint
    multimeshadj_names::Ptr{Cstring}
    nmultimeshadj::Cint
    multivar_names::Ptr{Cstring}
    nmultivar::Cint
    multimat_names::Ptr{Cstring}
    nmultimat::Cint
    multimatspecies_names::Ptr{Cstring}
    nmultimatspecies::Cint
    csgmesh_names::Ptr{Cstring}
    ncsgmesh::Cint
    csgvar_names::Ptr{Cstring}
    ncsgvar::Cint
    defvars_names::Ptr{Cstring}
    ndefvars::Cint
    qmesh_names::Ptr{Cstring}
    nqmesh::Cint
    qvar_names::Ptr{Cstring}
    nqvar::Cint
    ucdmesh_names::Ptr{Cstring}
    nucdmesh::Cint
    ucdvar_names::Ptr{Cstring}
    nucdvar::Cint
    ptmesh_names::Ptr{Cstring}
    nptmesh::Cint
    ptvar_names::Ptr{Cstring}
    nptvar::Cint
    mat_names::Ptr{Cstring}
    nmat::Cint
    matspecies_names::Ptr{Cstring}
    nmatspecies::Cint
    var_names::Ptr{Cstring}
    nvar::Cint
    obj_names::Ptr{Cstring}
    nobj::Cint
    dir_names::Ptr{Cstring}
    ndir::Cint
    array_names::Ptr{Cstring}
    narray::Cint
    mrgtree_names::Ptr{Cstring}
    nmrgtree::Cint
    groupelmap_names::Ptr{Cstring}
    ngroupelmap::Cint
    mrgvar_names::Ptr{Cstring}
    nmrgvar::Cint
end

const DBtoc = Nothing

type DBcurve_
    id::Cint
    datatype::Cint
    origin::Cint
    title::Cstring
    xvarname::Cstring
    yvarname::Cstring
    xlabel::Cstring
    ylabel::Cstring
    xunits::Cstring
    yunits::Cstring
    x::Ptr{Nothing}
    y::Ptr{Nothing}
    npts::Cint
    guihide::Cint
    reference::Cstring
    coord_sys::Cint
    missing_value::Cdouble
end

const DBcurve = Nothing

type DBdefvars_
    ndefs::Cint
    names::Ptr{Cstring}
    types::Ptr{Cint}
    defns::Ptr{Cstring}
    guihides::Ptr{Cint}
end

const DBdefvars = Nothing

type DBpointmesh_
    id::Cint
    block_no::Cint
    group_no::Cint
    name::Cstring
    cycle::Cint
    units::NTuple{3,Cstring}
    labels::NTuple{3,Cstring}
    title::Cstring
    coords::NTuple{3,Ptr{Nothing}}
    time::Cfloat
    dtime::Cdouble
    min_extents::NTuple{6,Cfloat}
    max_extents::NTuple{6,Cfloat}
    datatype::Cint
    ndims::Cint
    nels::Cint
    origin::Cint
    guihide::Cint
    gnodeno::Ptr{Nothing}
    mrgtree_name::Cstring
    gnznodtype::Cint
    ghost_node_labels::Cstring
    alt_nodenum_vars::Ptr{Cstring}
end

const DBpointmesh = Nothing

type DBmultimesh_
    id::Cint
    nblocks::Cint
    ngroups::Cint
    meshids::Ptr{Cint}
    meshnames::Ptr{Cstring}
    meshtypes::Ptr{Cint}
    dirids::Ptr{Cint}
    blockorigin::Cint
    grouporigin::Cint
    extentssize::Cint
    extents::Ptr{Cdouble}
    zonecounts::Ptr{Cint}
    has_external_zones::Ptr{Cint}
    guihide::Cint
    lgroupings::Cint
    groupings::Ptr{Cint}
    groupnames::Ptr{Cstring}
    mrgtree_name::Cstring
    tv_connectivity::Cint
    disjoint_mode::Cint
    topo_dim::Cint
    file_ns::Cstring
    block_ns::Cstring
    block_type::Cint
    empty_list::Ptr{Cint}
    empty_cnt::Cint
    repr_block_idx::Cint
    alt_nodenum_vars::Ptr{Cstring}
    alt_zonenum_vars::Ptr{Cstring}
    meshnames_alloc::Cstring
end

const DBmultimesh = Nothing

type DBmultimeshadj_
    nblocks::Cint
    blockorigin::Cint
    meshtypes::Ptr{Cint}
    nneighbors::Ptr{Cint}
    lneighbors::Cint
    neighbors::Ptr{Cint}
    back::Ptr{Cint}
    totlnodelists::Cint
    lnodelists::Ptr{Cint}
    nodelists::Ptr{Ptr{Cint}}
    totlzonelists::Cint
    lzonelists::Ptr{Cint}
    zonelists::Ptr{Ptr{Cint}}
end

const DBmultimeshadj = Nothing

type DBmultivar_
    id::Cint
    nvars::Cint
    ngroups::Cint
    varnames::Ptr{Cstring}
    vartypes::Ptr{Cint}
    blockorigin::Cint
    grouporigin::Cint
    extentssize::Cint
    extents::Ptr{Cdouble}
    guihide::Cint
    region_pnames::Ptr{Cstring}
    mmesh_name::Cstring
    tensor_rank::Cint
    conserved::Cint
    extensive::Cint
    file_ns::Cstring
    block_ns::Cstring
    block_type::Cint
    empty_list::Ptr{Cint}
    empty_cnt::Cint
    repr_block_idx::Cint
    missing_value::Cdouble
    varnames_alloc::Cstring
end

const DBmultivar = Nothing

type DBmultimat_
    id::Cint
    nmats::Cint
    ngroups::Cint
    matnames::Ptr{Cstring}
    blockorigin::Cint
    grouporigin::Cint
    mixlens::Ptr{Cint}
    matcounts::Ptr{Cint}
    matlists::Ptr{Cint}
    guihide::Cint
    nmatnos::Cint
    matnos::Ptr{Cint}
    matcolors::Ptr{Cstring}
    material_names::Ptr{Cstring}
    allowmat0::Cint
    mmesh_name::Cstring
    file_ns::Cstring
    block_ns::Cstring
    empty_list::Ptr{Cint}
    empty_cnt::Cint
    repr_block_idx::Cint
    matnames_alloc::Cstring
end

const DBmultimat = Nothing

type DBmultimatspecies_
    id::Cint
    nspec::Cint
    ngroups::Cint
    specnames::Ptr{Cstring}
    blockorigin::Cint
    grouporigin::Cint
    guihide::Cint
    nmat::Cint
    nmatspec::Ptr{Cint}
    species_names::Ptr{Cstring}
    speccolors::Ptr{Cstring}
    file_ns::Cstring
    block_ns::Cstring
    empty_list::Ptr{Cint}
    empty_cnt::Cint
    repr_block_idx::Cint
    specnames_alloc::Cstring
end

const DBmultimatspecies = Nothing

type DBzonelist_
    ndims::Cint
    nzones::Cint
    nshapes::Cint
    shapecnt::Ptr{Cint}
    shapesize::Ptr{Cint}
    shapetype::Ptr{Cint}
    nodelist::Ptr{Cint}
    lnodelist::Cint
    origin::Cint
    min_index::Cint
    max_index::Cint
    zoneno::Ptr{Cint}
    gzoneno::Ptr{Nothing}
    gnznodtype::Cint
    ghost_zone_labels::Cstring
    alt_zonenum_vars::Ptr{Cstring}
end

const DBzonelist = Nothing

type DBphzonelist_
    nfaces::Cint
    nodecnt::Ptr{Cint}
    lnodelist::Cint
    nodelist::Ptr{Cint}
    extface::Cstring
    nzones::Cint
    facecnt::Ptr{Cint}
    lfacelist::Cint
    facelist::Ptr{Cint}
    origin::Cint
    lo_offset::Cint
    hi_offset::Cint
    zoneno::Ptr{Cint}
    gzoneno::Ptr{Nothing}
    gnznodtype::Cint
    ghost_zone_labels::Cstring
    alt_zonenum_vars::Ptr{Cstring}
end

const DBphzonelist = Nothing

type DBfacelist_
    ndims::Cint
    nfaces::Cint
    origin::Cint
    nodelist::Ptr{Cint}
    lnodelist::Cint
    nshapes::Cint
    shapecnt::Ptr{Cint}
    shapesize::Ptr{Cint}
    ntypes::Cint
    typelist::Ptr{Cint}
    types::Ptr{Cint}
    nodeno::Ptr{Cint}
    zoneno::Ptr{Cint}
end

const DBfacelist = Nothing

type DBedgelist_
    ndims::Cint
    nedges::Cint
    edge_beg::Ptr{Cint}
    edge_end::Ptr{Cint}
    origin::Cint
end

const DBedgelist = Nothing

type DBquadmesh_
    id::Cint
    block_no::Cint
    group_no::Cint
    name::Cstring
    cycle::Cint
    coord_sys::Cint
    major_order::Cint
    stride::NTuple{3,Cint}
    coordtype::Cint
    facetype::Cint
    planar::Cint
    coords::NTuple{3,Ptr{Nothing}}
    datatype::Cint
    time::Cfloat
    dtime::Cdouble
    min_extents::NTuple{6,Cfloat}
    max_extents::NTuple{6,Cfloat}
    labels::NTuple{3,Cstring}
    units::NTuple{3,Cstring}
    ndims::Cint
    nspace::Cint
    nnodes::Cint
    dims::NTuple{3,Cint}
    origin::Cint
    min_index::NTuple{3,Cint}
    max_index::NTuple{3,Cint}
    base_index::NTuple{3,Cint}
    start_index::NTuple{3,Cint}
    size_index::NTuple{3,Cint}
    guihide::Cint
    mrgtree_name::Cstring
    ghost_node_labels::Cstring
    ghost_zone_labels::Cstring
    alt_nodenum_vars::Ptr{Cstring}
    alt_zonenum_vars::Ptr{Cstring}
end

const DBquadmesh = Nothing

type DBucdmesh_
    id::Cint
    block_no::Cint
    group_no::Cint
    name::Cstring
    cycle::Cint
    coord_sys::Cint
    topo_dim::Cint
    units::NTuple{3,Cstring}
    labels::NTuple{3,Cstring}
    coords::NTuple{3,Ptr{Nothing}}
    datatype::Cint
    time::Cfloat
    dtime::Cdouble
    min_extents::NTuple{6,Cfloat}
    max_extents::NTuple{6,Cfloat}
    ndims::Cint
    nnodes::Cint
    origin::Cint
    faces::Ptr{DBfacelist}
    zones::Ptr{DBzonelist}
    edges::Ptr{DBedgelist}
    gnodeno::Ptr{Nothing}
    nodeno::Ptr{Cint}
    phzones::Ptr{DBphzonelist}
    guihide::Cint
    mrgtree_name::Cstring
    tv_connectivity::Cint
    disjoint_mode::Cint
    gnznodtype::Cint
    ghost_node_labels::Cstring
    alt_nodenum_vars::Ptr{Cstring}
end

const DBucdmesh = Nothing

type DBquadvar_
    id::Cint
    name::Cstring
    units::Cstring
    label::Cstring
    cycle::Cint
    meshid::Cint
    vals::Ptr{Ptr{Nothing}}
    datatype::Cint
    nels::Cint
    nvals::Cint
    ndims::Cint
    dims::NTuple{3,Cint}
    major_order::Cint
    stride::NTuple{3,Cint}
    min_index::NTuple{3,Cint}
    max_index::NTuple{3,Cint}
    origin::Cint
    time::Cfloat
    dtime::Cdouble
    align::NTuple{6,Cfloat}
    mixvals::Ptr{Ptr{Nothing}}
    mixlen::Cint
    use_specmf::Cint
    ascii_labels::Cint
    meshname::Cstring
    guihide::Cint
    region_pnames::Ptr{Cstring}
    conserved::Cint
    extensive::Cint
    centering::Cint
    missing_value::Cdouble
end

const DBquadvar = Nothing

type DBucdvar_
    id::Cint
    name::Cstring
    cycle::Cint
    units::Cstring
    label::Cstring
    time::Cfloat
    dtime::Cdouble
    meshid::Cint
    vals::Ptr{Ptr{Nothing}}
    datatype::Cint
    nels::Cint
    nvals::Cint
    ndims::Cint
    origin::Cint
    centering::Cint
    mixvals::Ptr{Ptr{Nothing}}
    mixlen::Cint
    use_specmf::Cint
    ascii_labels::Cint
    meshname::Cstring
    guihide::Cint
    region_pnames::Ptr{Cstring}
    conserved::Cint
    extensive::Cint
    missing_value::Cdouble
end

const DBucdvar = Nothing

type DBmeshvar_
    id::Cint
    name::Cstring
    units::Cstring
    label::Cstring
    cycle::Cint
    meshid::Cint
    vals::Ptr{Ptr{Nothing}}
    datatype::Cint
    nels::Cint
    nvals::Cint
    nspace::Cint
    ndims::Cint
    origin::Cint
    centering::Cint
    time::Cfloat
    dtime::Cdouble
    align::NTuple{6,Cfloat}
    dims::NTuple{3,Cint}
    major_order::Cint
    stride::NTuple{3,Cint}
    min_index::NTuple{6,Cint}
    max_index::NTuple{6,Cint}
    ascii_labels::Cint
    meshname::Cstring
    guihide::Cint
    region_pnames::Ptr{Cstring}
    conserved::Cint
    extensive::Cint
    missing_value::Cdouble
end

const DBmeshvar = Nothing
const DBpointvar = DBmeshvar

type DBmaterial_
    id::Cint
    name::Cstring
    ndims::Cint
    origin::Cint
    dims::NTuple{3,Cint}
    major_order::Cint
    stride::NTuple{3,Cint}
    nmat::Cint
    matnos::Ptr{Cint}
    matnames::Ptr{Cstring}
    matlist::Ptr{Cint}
    mixlen::Cint
    datatype::Cint
    mix_vf::Ptr{Nothing}
    mix_next::Ptr{Cint}
    mix_mat::Ptr{Cint}
    mix_zone::Ptr{Cint}
    matcolors::Ptr{Cstring}
    meshname::Cstring
    allowmat0::Cint
    guihide::Cint
end

const DBmaterial = Nothing

type DBmatspecies_
    id::Cint
    name::Cstring
    matname::Cstring
    nmat::Cint
    nmatspec::Ptr{Cint}
    ndims::Cint
    dims::NTuple{3,Cint}
    major_order::Cint
    stride::NTuple{3,Cint}
    nspecies_mf::Cint
    species_mf::Ptr{Nothing}
    speclist::Ptr{Cint}
    mixlen::Cint
    mix_speclist::Ptr{Cint}
    datatype::Cint
    guihide::Cint
    specnames::Ptr{Cstring}
    speccolors::Ptr{Cstring}
end

const DBmatspecies = Nothing

type DBcsgzonelist_
    nregs::Cint
    origin::Cint
    typeflags::Ptr{Cint}
    leftids::Ptr{Cint}
    rightids::Ptr{Cint}
    xform::Ptr{Nothing}
    lxform::Cint
    datatype::Cint
    nzones::Cint
    zonelist::Ptr{Cint}
    min_index::Cint
    max_index::Cint
    regnames::Ptr{Cstring}
    zonenames::Ptr{Cstring}
    alt_zonenum_vars::Ptr{Cstring}
end

const DBcsgzonelist = Nothing

type DBcsgmesh_
    block_no::Cint
    group_no::Cint
    name::Cstring
    cycle::Cint
    units::NTuple{3,Cstring}
    labels::NTuple{3,Cstring}
    nbounds::Cint
    typeflags::Ptr{Cint}
    bndids::Ptr{Cint}
    coeffs::Ptr{Nothing}
    lcoeffs::Cint
    coeffidx::Ptr{Cint}
    datatype::Cint
    time::Cfloat
    dtime::Cdouble
    min_extents::NTuple{3,Cdouble}
    max_extents::NTuple{3,Cdouble}
    ndims::Cint
    origin::Cint
    zones::Ptr{DBcsgzonelist}
    bndnames::Ptr{Cstring}
    guihide::Cint
    mrgtree_name::Cstring
    tv_connectivity::Cint
    disjoint_mode::Cint
    alt_nodenum_vars::Ptr{Cstring}
end

const DBcsgmesh = Nothing

type DBcsgvar_
    name::Cstring
    cycle::Cint
    units::Cstring
    label::Cstring
    time::Cfloat
    dtime::Cdouble
    vals::Ptr{Ptr{Nothing}}
    datatype::Cint
    nels::Cint
    nvals::Cint
    centering::Cint
    use_specmf::Cint
    ascii_labels::Cint
    meshname::Cstring
    guihide::Cint
    region_pnames::Ptr{Cstring}
    conserved::Cint
    extensive::Cint
    missing_value::Cdouble
end

const DBcsgvar = Nothing

type DBcompoundarray_
    id::Cint
    name::Cstring
    elemnames::Ptr{Cstring}
    elemlengths::Ptr{Cint}
    nelems::Cint
    values::Ptr{Nothing}
    nvalues::Cint
    datatype::Cint
end

const DBcompoundarray = Nothing

type DBoptlist_
    options::Ptr{Cint}
    values::Ptr{Ptr{Nothing}}
    numopts::Cint
    maxopts::Cint
end

const DBoptlist = Nothing

type DBobject_
    name::Cstring
    _type::Cstring
    comp_names::Ptr{Cstring}
    pdb_names::Ptr{Cstring}
    ncomponents::Cint
    maxcomponents::Cint
    h5_vals::NTuple{1536,UInt8}
    h5_offs::NTuple{64,Cint}
    h5_sizes::NTuple{64,Cint}
    h5_types::NTuple{64,Cint}
    h5_names::NTuple{64,Cstring}
end

const DBobject = Nothing

type _DBmrgtnode
    name::Cstring
    narray::Cint
    names::Ptr{Cstring}
    type_info_bits::Cint
    max_children::Cint
    maps_name::Cstring
    nsegs::Cint
    seg_ids::Ptr{Cint}
    seg_lens::Ptr{Cint}
    seg_types::Ptr{Cint}
    num_children::Cint
    children::Ptr{Ptr{Nothing}}
    walk_order::Cint
    parent::Ptr{Nothing}
end

const DBmrgtnode = Nothing
const DBmrgwalkcb = Ptr{Nothing}

type _DBmrgtree
    name::Cstring
    src_mesh_name::Cstring
    src_mesh_type::Cint
    type_info_bits::Cint
    num_nodes::Cint
    root::Ptr{DBmrgtnode}
    cwr::Ptr{DBmrgtnode}
    mrgvar_onames::Ptr{Cstring}
    mrgvar_rnames::Ptr{Cstring}
end

const DBmrgtree = Nothing

type _DBmrgvar
    name::Cstring
    mrgt_name::Cstring
    ncomps::Cint
    compnames::Ptr{Cstring}
    nregns::Cint
    reg_pnames::Ptr{Cstring}
    datatype::Cint
    data::Ptr{Ptr{Nothing}}
end

const DBmrgvar = Nothing

type _DBgroupelmap
    name::Cstring
    num_segments::Cint
    groupel_types::Ptr{Cint}
    segment_lengths::Ptr{Cint}
    segment_ids::Ptr{Cint}
    segment_data::Ptr{Ptr{Cint}}
    segment_fracs::Ptr{Ptr{Nothing}}
    fracs_data_type::Cint
end

const DBgroupelmap = Nothing

type _DBnamescheme
    fmt::Cstring
    fmtptrs::Ptr{Cstring}
    fmtlen::Cint
    ncspecs::Cint
    delim::UInt8
    nembed::Cint
    embedstrs::NTuple{8,Cstring}
    arralloc::Cint
    narrefs::Cint
    arrnames::Ptr{Cstring}
    arrvals::Ptr{Ptr{Nothing}}
    arrsizes::Ptr{Cint}
    exprstrs::Ptr{Cstring}
end

const DBnamescheme = Nothing

type DBfile_pub
    name::Cstring
    _type::Cint
    toc::Ptr{DBtoc}
    dirid::Cint
    fileid::Cint
    pathok::Cint
    Grab::Cint
    GrabId::Ptr{Nothing}
    file_lib_version::Cstring
    close::Ptr{Nothing}
    exist::Ptr{Nothing}
    newtoc::Ptr{Nothing}
    inqvartype::Ptr{Nothing}
    uninstall::Ptr{Nothing}
    g_obj::Ptr{Nothing}
    c_obj::Ptr{Nothing}
    w_obj::Ptr{Nothing}
    g_comp::Ptr{Nothing}
    g_comptyp::Ptr{Nothing}
    w_comp::Ptr{Nothing}
    write::Ptr{Nothing}
    writeslice::Ptr{Nothing}
    g_dir::Ptr{Nothing}
    mkdir::Ptr{Nothing}
    cd::Ptr{Nothing}
    r_var::Ptr{Nothing}
    _module::Ptr{Nothing}
    r_varslice::Ptr{Nothing}
    g_compnames::Ptr{Nothing}
    g_ca::Ptr{Nothing}
    g_cu::Ptr{Nothing}
    g_defv::Ptr{Nothing}
    g_ma::Ptr{Nothing}
    g_ms::Ptr{Nothing}
    g_mm::Ptr{Nothing}
    g_mv::Ptr{Nothing}
    g_mt::Ptr{Nothing}
    g_mms::Ptr{Nothing}
    g_pm::Ptr{Nothing}
    g_pv::Ptr{Nothing}
    g_qm::Ptr{Nothing}
    g_qv::Ptr{Nothing}
    g_um::Ptr{Nothing}
    g_uv::Ptr{Nothing}
    g_fl::Ptr{Nothing}
    g_zl::Ptr{Nothing}
    g_var::Ptr{Nothing}
    g_varbl::Ptr{Nothing}
    g_varlen::Ptr{Nothing}
    g_vardims::Ptr{Nothing}
    g_vartype::Ptr{Nothing}
    i_meshname::Ptr{Nothing}
    i_meshtype::Ptr{Nothing}
    p_ca::Ptr{Nothing}
    p_cu::Ptr{Nothing}
    p_defv::Ptr{Nothing}
    p_fl::Ptr{Nothing}
    p_ma::Ptr{Nothing}
    p_ms::Ptr{Nothing}
    p_mm::Ptr{Nothing}
    p_mv::Ptr{Nothing}
    p_mt::Ptr{Nothing}
    p_mms::Ptr{Nothing}
    p_pm::Ptr{Nothing}
    p_pv::Ptr{Nothing}
    p_qm::Ptr{Nothing}
    p_qv::Ptr{Nothing}
    p_um::Ptr{Nothing}
    p_sm::Ptr{Nothing}
    p_uv::Ptr{Nothing}
    p_zl::Ptr{Nothing}
    p_zl2::Ptr{Nothing}
    g_phzl::Ptr{Nothing}
    p_phzl::Ptr{Nothing}
    p_csgzl::Ptr{Nothing}
    g_csgzl::Ptr{Nothing}
    p_csgm::Ptr{Nothing}
    g_csgm::Ptr{Nothing}
    p_csgv::Ptr{Nothing}
    g_csgv::Ptr{Nothing}
    g_mmadj::Ptr{Nothing}
    p_mmadj::Ptr{Nothing}
    p_mrgt::Ptr{Nothing}
    g_mrgt::Ptr{Nothing}
    p_grplm::Ptr{Nothing}
    g_grplm::Ptr{Nothing}
    p_mrgv::Ptr{Nothing}
    g_mrgv::Ptr{Nothing}
    free_z::Ptr{Nothing}
    cpdir::Ptr{Nothing}
    sort_obo::Ptr{Nothing}
end

type DBfile
    pub::DBfile_pub
end

const DBErrFunc_t = Ptr{Nothing}

# Skipping MacroDefinition: SIG_DFL ( void ( * ) ( int ) )
# Skipping MacroDefinition: SIG_IGN ( void ( * ) ( int ) )
# Skipping MacroDefinition: SIG_HOLD ( void ( * ) ( int ) )
# Skipping MacroDefinition: SIG_ERR ( ( void ( * ) ( int ) ) - 1

# const sa_handler = __sigaction_u
# const sa_sigaction = __sigaction_u

# Skipping MacroDefinition: SA_USERSPACE_MASK ( SA_ONSTACK | SA_RESTART | SA_RESETHAND | SA_NOCLDSTOP | SA_NODEFER | SA_NOCLDWAIT | SA_SIGINFO
# Skipping MacroDefinition: sigmask ( m ) ( 1 << ( ( m ) - 1 )

# const INT8_MIN = (-)
# const INT16_MIN = (-)

# Skipping MacroDefinition: INT32_MIN ( - INT32_MAX - 1
# Skipping MacroDefinition: INT64_MIN ( - INT64_MAX - 1
# Skipping MacroDefinition: RSIZE_MAX ( SIZE_MAX >> 1
# Skipping MacroDefinition: WCHAR_MIN ( - WCHAR_MAX - 1
# Skipping MacroDefinition: INT8_C ( v ) ( v
# Skipping MacroDefinition: INT16_C ( v ) ( v
# Skipping MacroDefinition: INT32_C ( v ) ( v
# Skipping MacroDefinition: INT64_C ( v ) ( v ## LL
# Skipping MacroDefinition: UINT8_C ( v ) ( v ## U
# Skipping MacroDefinition: UINT16_C ( v ) ( v ## U
# Skipping MacroDefinition: UINT32_C ( v ) ( v ## U
# Skipping MacroDefinition: UINT64_C ( v ) ( v ## ULL
# Skipping MacroDefinition: INTMAX_C ( v ) ( v ## L
# Skipping MacroDefinition: UINTMAX_C ( v ) ( v ## UL

# const PRIO_MIN = (-)
# const RUSAGE_CHILDREN = (-)

# Skipping MacroDefinition: RLIM_INFINITY ( ( ( __uint64_t ) 1 << 63 ) - 1
# Skipping MacroDefinition: WEXITSTATUS ( x ) ( ( _W_INT ( x ) >> 8 ) & 0x000000ff
# Skipping MacroDefinition: WSTOPSIG ( x ) ( _W_INT ( x ) >> 8
# Skipping MacroDefinition: WIFCONTINUED ( x ) ( _WSTATUS ( x ) == _WSTOPPED && WSTOPSIG ( x ) == 0x13
# Skipping MacroDefinition: WIFSTOPPED ( x ) ( _WSTATUS ( x ) == _WSTOPPED && WSTOPSIG ( x ) != 0x13
# Skipping MacroDefinition: WIFEXITED ( x ) ( _WSTATUS ( x ) == 0
# Skipping MacroDefinition: WIFSIGNALED ( x ) ( _WSTATUS ( x ) != _WSTOPPED && _WSTATUS ( x ) != 0
# Skipping MacroDefinition: WTERMSIG ( x ) ( _WSTATUS ( x )
# Skipping MacroDefinition: WCOREDUMP ( x ) ( _W_INT ( x ) & WCOREFLAG
# Skipping MacroDefinition: W_EXITCODE ( ret , sig ) ( ( ret ) << 8 | ( sig )
# Skipping MacroDefinition: W_STOPCODE ( sig ) ( ( sig ) << 8 | _WSTOPPED
# Skipping MacroDefinition: WAIT_ANY ( - 1
# Skipping MacroDefinition: ntohs ( x ) __DARWIN_OSSwapInt16 ( x
# Skipping MacroDefinition: htons ( x ) __DARWIN_OSSwapInt16 ( x
# Skipping MacroDefinition: ntohl ( x ) __DARWIN_OSSwapInt32 ( x
# Skipping MacroDefinition: htonl ( x ) __DARWIN_OSSwapInt32 ( x
# Skipping MacroDefinition: ntohll ( x ) __DARWIN_OSSwapInt64 ( x
# Skipping MacroDefinition: htonll ( x ) __DARWIN_OSSwapInt64 ( x
# Skipping MacroDefinition: NTOHL ( x ) ( x ) = ntohl ( ( __uint32_t ) x
# Skipping MacroDefinition: NTOHS ( x ) ( x ) = ntohs ( ( __uint16_t ) x
# Skipping MacroDefinition: NTOHLL ( x ) ( x ) = ntohll ( ( __uint64_t ) x
# Skipping MacroDefinition: HTONL ( x ) ( x ) = htonl ( ( __uint32_t ) x
# Skipping MacroDefinition: HTONS ( x ) ( x ) = htons ( ( __uint16_t ) x
# Skipping MacroDefinition: HTONLL ( x ) ( x ) = htonll ( ( __uint64_t ) x

# const w_termsig = w_T
# const w_coredump = w_T
# const w_retcode = w_T
# const w_stopval = w_S
# const w_stopsig = w_S

# Skipping MacroDefinition: alloca ( size ) __alloca ( size
# Skipping MacroDefinition: USER_ADDR_NULL ( ( user_addr_t ) 0
# Skipping MacroDefinition: CAST_USER_ADDR_T ( a_ptr ) ( ( user_addr_t ) ( ( uintptr_t ) ( a_ptr ) )

# begin enum ANONYMOUS_3
const ANONYMOUS_3 = UInt32
const P_ALL = (UInt32)(0)
const P_PID = (UInt32)(1)
const P_PGID = (UInt32)(2)
# end enum ANONYMOUS_3

# const idtype_t = Nothing
# const pid_t = Cint
# const id_t = Cint
# const sig_atomic_t = Cint
# const mcontext_t = Ptr{Nothing}
# const pthread_attr_t = __darwin_pthread_attr_t
# const stack_t = Nothing
# const ucontext_t = Nothing
# const sigset_t = __darwin_sigset_t
# const uid_t = __darwin_uid_t
#
# type sigval
#     _sigval::Cint
# end
#
# type sigevent
#     sigev_notify::Cint
#     sigev_signo::Cint
#     sigev_value::Nothing
#     sigev_notify_function::Ptr{Nothing}
#     sigev_notify_attributes::Ptr{pthread_attr_t}
# end
#
# const siginfo_t = Nothing
#
# type sigaction
#     __sigaction_u::Nothing
#     sa_mask::sigset_t
#     sa_flags::Cint
# end
#
# const sig_t = Ptr{Nothing}
#
# type sigvec
#     sv_handler::Ptr{Nothing}
#     sv_mask::Cint
#     sv_flags::Cint
# end
#
# type sigstack
#     ss_sp::Cstring
#     ss_onstack::Cint
# end

const int8_t = UInt8
const int16_t = Int16
const int32_t = Cint
const int64_t = Clonglong
const uint8_t = Cuchar
const uint16_t = UInt16
const uint32_t = UInt32
const uint64_t = Culonglong
const int_least8_t = Int8
const int_least16_t = Int16
const int_least32_t = Int32
const int_least64_t = Int64
const uint_least8_t = UInt8
const uint_least16_t = UInt16
const uint_least32_t = UInt32
const uint_least64_t = UInt64
const int_fast8_t = Int8
const int_fast16_t = Int16
const int_fast32_t = Int32
const int_fast64_t = Int64
const uint_fast8_t = UInt8
const uint_fast16_t = UInt16
const uint_fast32_t = UInt32
const uint_fast64_t = UInt64
# const intptr_t = __darwin_intptr_t
const uintptr_t = Culong
const intmax_t = Clong
const uintmax_t = Culong

# type timeval
#     tv_sec::__darwin_time_t
#     tv_usec::__darwin_suseconds_t
# end

# const rlim_t = __uint64_t

type rusage
    ru_utime::Nothing
    ru_stime::Nothing
    ru_maxrss::Clong
    ru_ixrss::Clong
    ru_idrss::Clong
    ru_isrss::Clong
    ru_minflt::Clong
    ru_majflt::Clong
    ru_nswap::Clong
    ru_inblock::Clong
    ru_oublock::Clong
    ru_msgsnd::Clong
    ru_msgrcv::Clong
    ru_nsignals::Clong
    ru_nvcsw::Clong
    ru_nivcsw::Clong
end

const rusage_info_t = Ptr{Nothing}

type rusage_info_v0
    ri_uuid::NTuple{16,UInt8}
    ri_user_time::UInt64
    ri_system_time::UInt64
    ri_pkg_idle_wkups::UInt64
    ri_interrupt_wkups::UInt64
    ri_pageins::UInt64
    ri_wired_size::UInt64
    ri_resident_size::UInt64
    ri_phys_footprint::UInt64
    ri_proc_start_abstime::UInt64
    ri_proc_exit_abstime::UInt64
end

type rusage_info_v1
    ri_uuid::NTuple{16,UInt8}
    ri_user_time::UInt64
    ri_system_time::UInt64
    ri_pkg_idle_wkups::UInt64
    ri_interrupt_wkups::UInt64
    ri_pageins::UInt64
    ri_wired_size::UInt64
    ri_resident_size::UInt64
    ri_phys_footprint::UInt64
    ri_proc_start_abstime::UInt64
    ri_proc_exit_abstime::UInt64
    ri_child_user_time::UInt64
    ri_child_system_time::UInt64
    ri_child_pkg_idle_wkups::UInt64
    ri_child_interrupt_wkups::UInt64
    ri_child_pageins::UInt64
    ri_child_elapsed_abstime::UInt64
end

type rusage_info_v2
    ri_uuid::NTuple{16,UInt8}
    ri_user_time::UInt64
    ri_system_time::UInt64
    ri_pkg_idle_wkups::UInt64
    ri_interrupt_wkups::UInt64
    ri_pageins::UInt64
    ri_wired_size::UInt64
    ri_resident_size::UInt64
    ri_phys_footprint::UInt64
    ri_proc_start_abstime::UInt64
    ri_proc_exit_abstime::UInt64
    ri_child_user_time::UInt64
    ri_child_system_time::UInt64
    ri_child_pkg_idle_wkups::UInt64
    ri_child_interrupt_wkups::UInt64
    ri_child_pageins::UInt64
    ri_child_elapsed_abstime::UInt64
    ri_diskio_bytesread::UInt64
    ri_diskio_byteswritten::UInt64
end

type rusage_info_v3
    ri_uuid::NTuple{16,UInt8}
    ri_user_time::UInt64
    ri_system_time::UInt64
    ri_pkg_idle_wkups::UInt64
    ri_interrupt_wkups::UInt64
    ri_pageins::UInt64
    ri_wired_size::UInt64
    ri_resident_size::UInt64
    ri_phys_footprint::UInt64
    ri_proc_start_abstime::UInt64
    ri_proc_exit_abstime::UInt64
    ri_child_user_time::UInt64
    ri_child_system_time::UInt64
    ri_child_pkg_idle_wkups::UInt64
    ri_child_interrupt_wkups::UInt64
    ri_child_pageins::UInt64
    ri_child_elapsed_abstime::UInt64
    ri_diskio_bytesread::UInt64
    ri_diskio_byteswritten::UInt64
    ri_cpu_time_qos_default::UInt64
    ri_cpu_time_qos_maintenance::UInt64
    ri_cpu_time_qos_background::UInt64
    ri_cpu_time_qos_utility::UInt64
    ri_cpu_time_qos_legacy::UInt64
    ri_cpu_time_qos_user_initiated::UInt64
    ri_cpu_time_qos_user_interactive::UInt64
    ri_billed_system_time::UInt64
    ri_serviced_system_time::UInt64
end

const rusage_info_current = Nothing

# type rlimit
#     rlim_cur::rlim_t
#     rlim_max::rlim_t
# end

type proc_rlimit_control_wakeupmon
    wm_flags::UInt32
    wm_rate::Int32
end

type wait
    _wait::Cint
end

# const ct_rune_t = __darwin_ct_rune_t
# const rune_t = __darwin_rune_t
# const wchar_t = __darwin_wchar_t
const div_t = Nothing
const ldiv_t = Nothing
const lldiv_t = Nothing
const u_int8_t = Cuchar
const u_int16_t = UInt16
const u_int32_t = UInt32
const u_int64_t = Culonglong
const register_t = Int64
const user_addr_t = u_int64_t
const user_size_t = u_int64_t
const user_ssize_t = Int64
const user_long_t = Int64
const user_ulong_t = u_int64_t
const user_time_t = Int64
const user_off_t = Int64
# const syscall_arg_t = u_int64_t
# const dev_t = __darwin_dev_t
# const mode_t = __darwin_mode_t

# begin enum ANONYMOUS_4
const ANONYMOUS_4 = UInt32
const PMPIO_READ = (UInt32)(1)
const PMPIO_WRITE = (UInt32)(3)
# end enum ANONYMOUS_4

const PMPIO_iomode_t = Nothing
const PMPIO_CreateFileCallBack = Ptr{Nothing}
const PMPIO_OpenFileCallBack = Ptr{Nothing}
const PMPIO_CloseFileCallBack = Ptr{Nothing}

type _PMPIO_baton_t
    ioMode::PMPIO_iomode_t
    commSize::Cint
    rankInComm::Cint
    numGroups::Cint
    groupSize::Cint
    numGroupsWithExtraProc::Cint
    commSplit::Cint
    groupRank::Cint
    rankInGroup::Cint
    procBeforeMe::Cint
    procAfterMe::Cint
    mpiVal::Cint
    mpiTag::Cint
    mpiComm::Cint
    createCb::PMPIO_CreateFileCallBack
    openCb::PMPIO_OpenFileCallBack
    closeCb::PMPIO_CloseFileCallBack
    userData::Ptr{Nothing}
end

const PMPIO_baton_t = Nothing


text:
function partition(t2f,ne,np,metis)

# Generate a temporary file to be used in METIS
print("Writing input files for METIS...\n");
open("temp.txt", "w") do io
     Main.DelimitedFiles.writedlm(io, ne)
end
open("temp.txt", "a") do io
     Main.DelimitedFiles.writedlm(io, t2f')
end

metisstatus0 = Sys.which(metis);
metisstatus1 = Sys.which("mpmetis");
metisstatus2 = Sys.which("/usr/bin/mpmetis");
metisstatus3 = Sys.which("/usr/local/bin/mpmetis");
metisstatus4 = Sys.which("/opt/local/bin/mpmetis");

if metisstatus0 != nothing
elseif metisstatus1 != nothing
    metis = "mpmetis"
elseif metisstatus2 != nothing
    metis = "/usr/bin/mpmetis";
elseif metisstatus3 != nothing
    metis = "/usr/local/bin/mpmetis";
elseif metisstatus4 != nothing
    metis = "/opt/local/bin/mpmetis";
else
    error("Exasim search in /usr/bin, /usr/local/bin, and /opt/local/bin and could not find Metis. Please see the documentation to install it. After installation, please set its path to app.metis");
end

print("Calling METIS and reading output files...\n");
# call mpmetis
nps = string(np);
str = `$metis $"temp.txt" $nps`;
run(str);

# get mesh partitioning data
estr = string("temp.txt.epart.", nps);
#epart = Main.DelimitedFiles.readdlm(estr, ',', Int);
epart = Main.DelimitedFiles.readdlm(estr, Int);

# get node partitioning data
nstr = string("temp.txt.npart.", nps);
#npart = Main.DelimitedFiles.readdlm(nstr, ',', Int);
npart = Main.DelimitedFiles.readdlm(nstr, Int);

# remove files
rm("temp.txt");
rm(estr);
rm(nstr);

return epart, npart

end

# #if size(t2f,2) == ne; t2f = t2f'; end
#
# # current directory
# cdir = pwd();
# ii = findlast("Exasim", cdir);
#
# # move to directory that contains metis programs
# if Sys.isapple()
#     #cd([cdir "/metis/mac"]);
#     metisdir = string(cdir[1:ii[end]],"/metis/mac");
# elseif Sys.isunix()
#     #cd([cdir "/metis/linux"]);
#     metisdir = string(cdir[1:ii[end]],"/metis/linux");
# elseif Sys.iswindows()
#     #cd([cdir "/metis/linux"]);
#     metisdir = string(cdir[1:ii[end]],"/metis/windows");
# end
# cd(metisdir);
#
# # Generate a temporary file to be used in METIS
# display("Writing input files for METIS...");
# open("temp.txt", "w") do io
#      Main.DelimitedFiles.writedlm(io, ne)
# end
# open("temp.txt", "a") do io
#      Main.DelimitedFiles.writedlm(io, t2f')
# end
#
# #open(io -> writedlm(io, ne, ','), "temp.txt", "w") # write
# #open(io -> writedlm(io,t2f, ','), "temp.txt", "a") # append
# # writedlm('temp.txt', ne, 'delimiter', ' ','precision',10);
# # writedlm('temp.txt', t2f, '-append', 'delimiter', ' ','precision',10);
#
# display("Calling METIS and reading output files...");
# # call mpmetis
# nps = string(np);
# str = `$"./mpmetis" $"temp.txt" $nps`;
# run(str);
#
# # get mesh partitioning data
# estr = string("temp.txt.epart.", nps);
# epart = Main.DelimitedFiles.readdlm(estr, ',', Int);
#
# # get node partitioning data
# nstr = string("temp.txt.npart.", nps);
# npart = Main.DelimitedFiles.readdlm(nstr, ',', Int);
#
# # remove files
# rm("temp.txt");
# rm(estr);
# rm(nstr);
#
# # move back to current directory
# cd(cdir);
#
# return epart, npart
#
# end

ext: jl

max_stars_repo_name: glwagner/Exasim

max_issues_repo_name: glwagner/Exasim

max_forks_repo_name: glwagner/Exasim


text:
using Formatting

@testset "$type" for type in [Line, Plane]

    # The object can be constructed from static arrays.
    type(SA[0, 0, 0], SA[1, 0, 0])

    # It can also be constructed from normal arrays.
    obj = type([0, 0], [1, 0])

    @test obj.point isa SVector{2, Int}
    @test obj.point == [0, 0]

    @test obj.vector isa SVector{2, Int}
    @test obj.vector == [1, 0]

    # The point and vector must be Julia vectors (one-dimensional arrays).
    @test_throws MethodError type(0, [1, 0])
    @test_throws MethodError type([0, 0], 1)
    @test_throws MethodError type([0 0; 0 0], [1, 0])
    @test_throws MethodError type([0, 0], [1 0; 0 0])

    template = "expected input array of length {}, got length {}"
    @test_throws DimensionMismatch(format(template, 1, 2)) type([0], [1, 0])
    @test_throws DimensionMismatch(format(template, 2, 3)) type([0, 0], [1, 0, 0])
    @test_throws DimensionMismatch(format(template, 3, 2)) type([0, 0, 0], [1, 0])

    message = "The vector must have a non-zero magnitude."
    @test_throws ArgumentError(message) type([0, 0], [0, 0])

    # The vector magnitude can be checked with a tolerance.
    type([0, 0], [1e-2, 0])
    @test_throws ArgumentError(message) type([0, 0], [1e-2, 0]; atol=1e-4)
end

@testset "Vector aliases" begin
    for (type, alias) in zip((:Line, :Plane), (:direction, :normal))
        eval(
            quote
                obj = $type([0, 0], [1, 0])

                @test obj.$alias isa SVector{2, Int}
                @test obj.$alias == [1, 0]
            end
        )
    end
end


text:
using Parameters, LinearAlgebra

# export System, Reaction, Reactions, Compound, Compounds, IDs

@with_kw struct Reaction
    id::String
    left::Vector{String}
    right::Vector{String}
    metadata::Dict{String}=Dict{String,Any}()
end

@with_kw struct Compound
    entry_id::String
    name::String
    formula::String
    exact_mass::Float64
    mol_weight::Float64
    names::Vector{String}=Vector{String}()
    elements::Vector{String}=Vector{String}()
    reactions::Vector{String}=Vector{String}()
    comment::String=""
    enzymes::Vector{String}=Vector{String}()
    rpairs::Vector{String}=Vector{String}()
    dblinks::Dict{String,Vector{String}}=Dict{String,Vector{String}}()
    pathways::Dict{String,String}=Dict{String,String}()
    kcf::String=""
    remark::String=""
    glycans::Vector{String}=Vector{String}()
end

#consts basically will just check type, but wont actually keep constant
const IDs = Vector{String} #either "C00000" or "R00000"

const Reactions = Dict{String,Reaction}

const Compounds = Dict{String,Compound}

# This is just cosmetic
const TArray{T, N} = Transpose{T, Array{T, N}}

@with_kw struct System
    rstructs::Reactions
    rids::IDs
    sids::IDs
    tids::IDs = IDs()
    allowed_forward::Union{Vector{Bool},Nothing} = nothing
    allowed_backward::Union{Vector{Bool},Nothing} = nothing
    # function System(args...)

    #     new(rstructs, rids, sids, nothing, nothing, nothing)
    # end
end

struct Expansion
    x::Vector{Int}
    t::Vector{Int}
    compounds::IDs
    reactions::IDs
    X::Vector{Vector{Int}}
    Y::Vector{Vector{Int}}
end

max_stars_repo_name: hbsmith/BioXP

max_issues_repo_name: hbsmith/BioXP

max_forks_repo_name: hbsmith/BioXP


text: #specific stuff for su2+higgs (fundamental and adjoint)


text:
module MosekTools

import MathOptInterface
const MOI = MathOptInterface
const MOIU = MOI.Utilities

using Mosek
export Mosek
# Allows the user to use `Mosek.Optimizer` instead of `MosekTools.Optimizer`
# for convenience and for consitency with other solvers where the syntax is
# `SolverName.Optimizer`.
function Mosek.Optimizer(; kws...)
    return MosekTools.Optimizer(; kws...)
end

include("LinkedInts.jl")

const DEBUG = false

struct MosekSolution
    whichsol :: Soltype
    solsta   :: Solsta
    prosta   :: Prosta

    xxstatus :: Vector{Stakey}
    xx       :: Vector{Float64}
    barxj    :: Vector{Vector{Float64}}
    slx      :: Vector{Float64}
    sux      :: Vector{Float64}
    snx      :: Vector{Float64}

    cstatus  :: Vector{Stakey}
    xc       :: Vector{Float64}
    slc      :: Vector{Float64}
    suc      :: Vector{Float64}
    y        :: Vector{Float64}
end

struct ColumnIndex
    value::Int32
end

struct ColumnIndices
    values::Vector{Int32}
end

struct MatrixIndex
    matrix::Int32
    row::Int32
    column::Int32
    function MatrixIndex(matrix::Integer, row::Integer, column::Integer)
        @assert column ≤ row
        new(matrix, row, column)
    end
end

"""
    Optimizer <: MathOptInterface.AbstractModel

Linear variables and constraint can be deleted. For some reason MOSEK
does not support deleting PSD variables.

Note also that adding variables and constraints will permanently add
some (currently between 1 and 3) Int64s that a `delete!` will not
remove. This ensures that Indices (Variable and constraint) that
are deleted are thereafter invalid.
"""
mutable struct Optimizer  <: MOI.AbstractOptimizer
    task :: Mosek.MSKtask
    ## Options passed in `Mosek.Optimizer` that are used to create a new task
    ## in `MOI.empty!`:
    # Should Mosek output be ignored or printed ?
    be_quiet :: Bool
    # Integer parameters, i.e. parameters starting with `MSK_IPAR_`
    ipars :: Dict{String, Int32}
    # Floating point parameters, i.e. parameters starting with `MSK_DPAR_`
    dpars :: Dict{String, Float64}
    # String parameters, i.e. parameters starting with `MSK_SPAR_`
    spars :: Dict{String, AbstractString}
    has_variable_names::Bool
    constrnames :: Dict{String, Vector{MOI.ConstraintIndex}}
    # Mosek only support names for `MOI.ScalarAffineFunction` so we need a
    # fallback for `SingleVariable` and `VectorOfVariables`.
    con_to_name :: Dict{MOI.ConstraintIndex, String}

    # For each MOI index of variables, gives the flags of constraints present
    # The SingleVariable constraints added cannot just be inferred from getvartype
    # and getvarbound so we need to keep them here so implement `MOI.is_valid`
    x_constraints::Vector{UInt8}

    """
        The total length of `x_block` matches the number of variables in
    the underlying task, and the number of blocks corresponds to the
    number variables allocated in the Model.
    """
    x_block::LinkedInts

    """
    One entry per scalar variable in the task indicating in which semidefinite
    block it is and at which index.
    MOI index -> MatrixIndex
    """
    x_sd::Vector{MatrixIndex}

    sd_dim::Vector{Int}

    ###########################
    """
    One scalar entry per constraint in the underlying task. One block
    per constraint allocated in the Model.
    """
    c_block :: LinkedInts

    # i -> 0: Not in a VectorOfVariables constraint
    # i -> +j: In `MOI.ConstraintIndex{MOI.VectorOfVariables, ?}(j)`
    # i -> -j: In `MOI.VectorOfVariables` constraint with `MOI.VariableIndex(j)` as first variable
    variable_to_vector_constraint_id::Vector{Int32}

    ###########################
    trm :: Union{Nothing, Rescode}
    solutions :: Vector{MosekSolution}

    ###########################
    """
    Indicating whether the objective sense is MOI.FEASIBILITY_SENSE. It is
    encoded as a MOI.MIN_SENSE with a zero objective internally but this allows
    MOI.get(::Optimizer, ::ObjectiveSense) to still return the right value
    """
    feasibility :: Bool
    """
    Indicates whether there is an objective set.
    If `has_objective` is `false` then Mosek has a zero objective internally.
    This affects `MOI.ListOfModelAttributesSet`.
    """
    has_objective :: Bool

    fallback :: Union{String, Nothing}

    function Optimizer(; kws...)
        optimizer = new(
            maketask(), # task
            false, # be_quiet
            Dict{String, Int32}(), # ipars
            Dict{String, Float64}(), # dpars
            Dict{String, AbstractString}(), # spars
            false, # has_variable_names
            Dict{String, Vector{MOI.ConstraintIndex}}(), # constrnames
            Dict{MOI.ConstraintIndex, String}(), # con_to_name
            UInt8[], # x_constraints
            LinkedInts(),# x_block
            MatrixIndex[], # x_sd
            Int[], # sd_dim
            LinkedInts(), # c_block
            Int32[], # variable_to_vector_constraint_id
            nothing,# trm
            MosekSolution[],
            true, # feasibility_sense
            false, # has_objective
            nothing,
        )
        Mosek.putstreamfunc(optimizer.task, Mosek.MSK_STREAM_LOG, m -> print(m))
        if length(kws) > 0
            @warn("""Passing optimizer attributes as keyword arguments to
            Mosek.Optimizer is deprecated. Use
                MOI.set(model, MOI.RawOptimizerAttribute("key"), value)
            or
                JuMP.set_optimizer_attribute(model, "key", value)
            instead.
            """)
        end
        for (option, value) in kws
            MOI.set(optimizer, MOI.RawOptimizerAttribute(string(option)), value)
        end
        return optimizer
    end
end

struct IntegerParameter <: MOI.AbstractOptimizerAttribute
    name::String
end
function MOI.set(m::Optimizer, p::IntegerParameter, value)
    m.ipars[p.name] = value
    Mosek.putnaintparam(m.task, p.name, value)
end
function MOI.get(m::Optimizer, p::IntegerParameter)
    Mosek.getnaintparam(m.task, p.name)
end

struct DoubleParameter <: MOI.AbstractOptimizerAttribute
    name::String
end
function MOI.set(m::Optimizer, p::DoubleParameter, value)
    m.dpars[p.name] = value
    Mosek.putnadouparam(m.task, p.name, value)
end
function MOI.get(m::Optimizer, p::DoubleParameter)
    Mosek.getnadouparam(m.task, p.name)
end

struct StringParameter <: MOI.AbstractOptimizerAttribute
    name::String
end
function MOI.set(m::Optimizer, p::StringParameter, value::AbstractString)
    m.spars[p.name] = value
    Mosek.putnastrparam(m.task, p.name, value)
end
function MOI.get(m::Optimizer, p::StringParameter)
    # We need to give the maximum length of the value of the parameter.
    # 255 should be ok in most cases.
    len, str = Mosek.getnastrparam(m.task, p.name, 255)
    return str
end

function MOI.set(m::Optimizer, p::MOI.RawOptimizerAttribute, value)
    if p.name == "QUIET"
        if m.be_quiet != convert(Bool, value)
            m.be_quiet = !m.be_quiet
            if m.be_quiet
                Mosek.putstreamfunc(m.task, Mosek.MSK_STREAM_LOG,
                                    m -> begin end)
            else
                Mosek.putstreamfunc(m.task, Mosek.MSK_STREAM_LOG,
                                    m -> print(m))
            end
        end
    elseif p.name == "fallback"
        m.fallback = value
    else
        if startswith(p.name, "MSK_IPAR_")
            par = IntegerParameter(p.name)
        elseif startswith(p.name, "MSK_DPAR_")
            par = DoubleParameter(p.name)
        elseif startswith(p.name, "MSK_SPAR_")
            par = StringParameter(p.name)
        elseif isa(value, Integer)
            par = IntegerParameter("MSK_IPAR_" * p.name)
        elseif isa(value, AbstractFloat)
            par = DoubleParameter("MSK_DPAR_" * p.name)
        elseif isa(value, AbstractString)
            par = StringParameter("MSK_SPAR_" * p.name)
        else
            error("Value $value for parameter $(p.name) has unrecognized type")
        end
        MOI.set(m, par, value)
    end
end

function MOI.get(m::Optimizer, p::MOI.RawOptimizerAttribute)
    if p.name == "QUIET"
        return m.be_quiet
    elseif p.name == "fallback"
        return m.fallback
    else
        if startswith(p.name, "MSK_IPAR_")
            par = IntegerParameter(p.name)
        elseif startswith(p.name, "MSK_DPAR_")
            par = DoubleParameter(p.name)
        elseif startswith(p.name, "MSK_SPAR_")
            par = StringParameter(p.name)
        else
            error("The parameter $(p.name) should start by `MSK_IPAR_`, `MSK_DPAR_` or `MSK_SPAR_`.")
        end
        MOI.get(m, par)
    end
end

MOI.supports(::Optimizer, ::MOI.Silent) = true
function MOI.set(model::Optimizer, ::MOI.Silent, value::Bool)
    MOI.set(model, MOI.RawOptimizerAttribute("QUIET"), value)
end
function MOI.get(model::Optimizer, ::MOI.Silent)
    MOI.get(model, MOI.RawOptimizerAttribute("QUIET"))
end

MOI.supports(::Optimizer, ::MOI.TimeLimitSec) = true
function MOI.set(model::Optimizer, ::MOI.TimeLimitSec, value::Real)
    MOI.set(model, MOI.RawOptimizerAttribute("MSK_DPAR_OPTIMIZER_MAX_TIME"), value)
end
function MOI.set(model::Optimizer, ::MOI.TimeLimitSec, ::Nothing)
    MOI.set(model, MOI.RawOptimizerAttribute("MSK_DPAR_OPTIMIZER_MAX_TIME"), -1.0)
end
function MOI.get(model::Optimizer, ::MOI.TimeLimitSec)
    value = MOI.get(model, MOI.RawOptimizerAttribute("MSK_DPAR_OPTIMIZER_MAX_TIME"))
    if value < 0.0
        return nothing
    else
        return value
    end
end

function matrix_solution(m::Optimizer, sol)
    return Vector{Float64}[getbarxj(m.task, sol, j) for j in 1:length(m.sd_dim)]
end

function MOI.optimize!(m::Optimizer)
    # See https://github.com/jump-dev/MosekTools.jl/issues/70
    putintparam(m.task,Mosek.MSK_IPAR_REMOVE_UNUSED_SOLUTIONS,Mosek.MSK_ON)
    m.trm = if m.fallback == nothing; optimize(m.task) else optimize(m.task,m.fallback) end
    m.solutions = MosekSolution[]
    # If the problem is conic but a starting value is set,
    # `MSK_SOL_ITG` simply contains the starting value and
    # `MSK_SOL_ITR` contains the actual solution found.
    # We want `VariablePrimal(1)`, ... to be `MSK_SOL_ITR` in that case
    # so puting it first should solve the issue in that case, see
    # https://github.com/jump-dev/MosekTools.jl/issues/66
    if solutiondef(m.task,MSK_SOL_ITR)
        push!(m.solutions,
              MosekSolution(MSK_SOL_ITR,
                            getsolsta(m.task,MSK_SOL_ITR),
                            getprosta(m.task,MSK_SOL_ITR),
                            getskx(m.task,MSK_SOL_ITR),
                            getxx(m.task,MSK_SOL_ITR),
                            matrix_solution(m, MSK_SOL_ITR),
                            getslx(m.task,MSK_SOL_ITR),
                            getsux(m.task,MSK_SOL_ITR),
                            getsnx(m.task,MSK_SOL_ITR),
                            getskc(m.task,MSK_SOL_ITR),
                            getxc(m.task,MSK_SOL_ITR),
                            getslc(m.task,MSK_SOL_ITR),
                            getsuc(m.task,MSK_SOL_ITR),
                            gety(m.task,MSK_SOL_ITR)))
    end
    if solutiondef(m.task,MSK_SOL_ITG)
        push!(m.solutions,
              MosekSolution(MSK_SOL_ITG,
                            getsolsta(m.task, MSK_SOL_ITG),
                            getprosta(m.task, MSK_SOL_ITG),
                            getskx(m.task, MSK_SOL_ITG),
                            getxx(m.task, MSK_SOL_ITG),
                            # See https://github.com/jump-dev/MosekTools.jl/issues/71
                            Float64[], #matrix_solution(m, MSK_SOL_ITG),
                            Float64[],
                            Float64[],
                            Float64[],
                            getskc(m.task, MSK_SOL_ITG),
                            getxc(m.task, MSK_SOL_ITG),
                            Float64[],
                            Float64[],
                            Float64[]))
    end
    if solutiondef(m.task,MSK_SOL_BAS)
        push!(m.solutions,
              MosekSolution(MSK_SOL_BAS,
                            getsolsta(m.task,MSK_SOL_BAS),
                            getprosta(m.task,MSK_SOL_BAS),
                            getskx(m.task,MSK_SOL_BAS),
                            getxx(m.task,MSK_SOL_BAS),
                            # See https://github.com/jump-dev/MosekTools.jl/issues/71
                            Float64[], #matrix_solution(m, MSK_SOL_BAS),
                            getslx(m.task,MSK_SOL_BAS),
                            getsux(m.task,MSK_SOL_BAS),
                            Float64[],
                            getskc(m.task,MSK_SOL_BAS),
                            getxc(m.task,MSK_SOL_BAS),
                            getslc(m.task,MSK_SOL_BAS),
                            getsuc(m.task,MSK_SOL_BAS),
                            gety(m.task,MSK_SOL_BAS)))
    end
end

MOI.supports(::Optimizer, ::MOI.Name) = true
function MOI.set(m::Optimizer, ::MOI.Name, name::String)
    puttaskname(m.task, name)
end
function MOI.get(m::Optimizer, ::MOI.Name)
    return gettaskname(m.task)
end
function MOI.get(m::Optimizer, ::MOI.ListOfModelAttributesSet)
    set = MOI.AbstractModelAttribute[]
    if !m.feasibility
        push!(set, MOI.ObjectiveSense())
    end
    if m.has_objective
        push!(set, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}())
    end
    if !isempty(MOI.get(m, MOI.Name()))
        push!(set, MOI.Name())
    end
    return set
end

function MOI.is_empty(m::Optimizer)
    getnumvar(m.task) == 0 && getnumcon(m.task) == 0 && getnumcone(m.task) == 0 && getnumbarvar(m.task) == 0
end

function MOI.empty!(model::Optimizer)
    model.task               = maketask()
    for (name, value) in model.ipars
        Mosek.putnaintparam(model.task, name, value)
    end
    for (name, value) in model.dpars
        Mosek.putnadouparam(model.task, name, value)
    end
    for (name, value) in model.spars
        Mosek.putnastrparam(model.task, name, value)
    end
    if !model.be_quiet
        Mosek.putstreamfunc(model.task, Mosek.MSK_STREAM_LOG, m -> print(m))
    end
    model.has_variable_names = false
    empty!(model.constrnames)
    empty!(model.con_to_name)
    empty!(model.x_constraints)
    model.x_block            = LinkedInts()
    empty!(model.x_sd)
    empty!(model.sd_dim)
    model.c_block            = LinkedInts()
    empty!(model.variable_to_vector_constraint_id)
    model.trm                = nothing
    empty!(model.solutions)
    model.feasibility        = true
    model.has_objective      = false
end

MOI.get(::Optimizer, ::MOI.SolverName) = "Mosek"

function MOI.get(::Optimizer, ::MOI.SolverVersion)
    major, minor, revision = Mosek.getversion()
    return string(VersionNumber(major, minor, revision))
end

MOI.supports_incremental_interface(::Optimizer) = true
function MOI.copy_to(dest::Optimizer, src::MOI.ModelLike; kws...)
    return MOIU.default_copy_to(dest, src; kws...)
end

function MOI.write_to_file(m::Optimizer, filename :: String)
    putintparam(m.task,MSK_IPAR_OPF_WRITE_SOLUTIONS, MSK_ON)
    writedata(m.task,filename)
end

# For linear objectives we accept:
# EITER affine left-hand side and ranged, unbounded, half-open, fixed (equality), PSD or SOC domains
# OR affine and quadratic left-hand side, and ranged, unbounded, half-open, fixed (equality) domains (quadratic constraints must be unbounded or half-open)
#
# For non-quadratic problems we allow binary and integer variables (but not constraints)
#function supportsconstraints(m::MosekSolver, constraint_types) :: Bool
#    for (fun,dom) in constraint_types
#        if  fun in [MOI.ScalarAffineFunction{Float64},
#                    MOI.VariableIndex,
#                    MOI.VectorOfVariables] &&
#            dom in [MOI.GreaterThan{Float64},
#                    MOI.LessThan{Float64},
#                    MOI.EqualTo{Float64},
#                    MOI.Interval{Float64},
#                    MOI.SecondOrderCone,
#                    MOI.RotatedSecondOrderCone,
#                    MOI.PositiveSemidefiniteConeTriangle,
#                    MOI.PositiveSemidefiniteConeScaled ]
#            # ok
#        elseif dom == MOI.Integer && fun in [MOI.VariableIndex, MOI.VectorOfVariables]
#            # ok
#        else
#            return false
#        end
#    end
#    true
#end

ref2id(vi::MOI.VariableIndex)::Int = vi.value
ref2id(ci::MOI.ConstraintIndex)::Int = ci.value

include("objective.jl")
include("variable.jl")
include("constraint.jl")
include("attributes.jl")

end # module


text:
# sample library (unusable) that shows you how to code up your own Aetherlang libraries in Julia.
# NOTE that for your library to be installed it should be _SAMPLE_namespace_modifyin the "Libs" folder in a folder named exactly as your library and have a .jl file named exactly as your library.
# NOTE that for a library to be observable from Aetherlang, its name should be in all-lowercase style. this library's name is uppercase on purpose.

const TYPE = "_SAMPLE.type" # in case your library defines some types,
                            # you need to create constant strings representing this type in Aetherlang type system.
                            # this string is used when calling (typeof obj)

# constructor for AetherlangObject of your type
AetherlangObject(arg::MyType) = AetherlangObject{MyType}(arg, Ref(TYPE))

# all functions defined for Aetherlang use should have either the AE_ prefix or the specific prefix named exactly as your library (_SAMPLE_ in this case).
function AE_sample_function(line::Ref{UInt}, ns::Namespace, args...)::AetherlangObject
    # you can specify the number of arguments if needed instead of using args...
    # NOTE: arguments come as AetherlangObjects. use arg.dataref unwrap data. use arg.type[] to get a string representing object's type in Aetherlang
    # NOTE: you are provided with mutable arguments line::Ref{UInt} and ns::Namespace but please don't change them, as it would ruin the paradigm and some features may not work properly
    #=
    CODE
    =#
    AetherlangObject()
end

_SAMPLE_namespace_modify = Namespace(
    "name_of_the_function" => AetherlangObject(AE_sample_function)
)

max_stars_repo_name: Aetherlang/aetherlang

max_issues_repo_name: gojakuch/aetherlang

max_forks_repo_name: gojakuch/aetherlang


text:
module Compress
using LinearAlgebra, Statistics

export compress

function compress(series::AbstractVector, tol=0.5::AbstractFloat, max_len=typemax(Int)::Int)
    """
    Approximate a time series using a continuous piecewise linear function.

    Parameters
    ----------
    series -
        Time series as input of numpy array

    tol - default 0.5
        the tolerance will restrict the compression, the higher it is,
        the more accurate the reconstruction will be

    max_len - default typemax(Int)
        The max length of the pieces for the compression

    Returns
    -------
    pieces -
        Array with three columns, each row contains length, increment, error for the segment.
    """
    # print("tol:", tol, "\n");
    pieces = zeros((0, 3));
    # pieces = Any[]
    num_ts = length(series);

    x = range(0, num_ts-1, step=1);
    start = 1;
    _end = 2;
    epsilon = eps(1.0);  # 2.220446049250313e-16
    (lastinc, lasterr) = (0, 0);
    while _end <= num_ts
        inc = series[_end] - series[start];
        term = broadcast(+, series[start] , (inc / (_end-start)) * x[1:_end-start+1]);
        term = broadcast(-, term, series[start:_end]);
        err = opnorm(term', 2)^2;
        if (err <= tol*(_end-start-1) + epsilon) && (_end-start-1 < max_len)
            (lastinc, lasterr) = (inc, err);
            _end = _end + 1;
            # continue
        else
            pieces = vcat(pieces, [_end-start-1, lastinc, lasterr]');
            # push!(pieces, [_end-start-1, lastinc, lasterr]);
            start = _end - 1;
        end
    end

    # push!(pieces, [_end-start-1, lastinc, lasterr]);
    pieces = vcat(pieces, [_end-start-1, lastinc, lasterr]');
    # pieces = to_matrix(pieces, 3);
    return pieces;
end

# function to_matrix(pieces::Array{Any, 1}, dim::Int)
#     T_MATRIX = zeros((length(pieces), dim));
#     row = 1;
#     for piece in pieces
#         T_MATRIX[row, :] = piece;
#         row = row + 1;
#     end
#     return T_MATRIX;
# end

end

max_stars_repo_name: nla-group/Julia-ABBA

max_issues_repo_name: nla-group/Julia-ABBA

max_forks_repo_name: nla-group/Julia-ABBA


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "StarPU"
version = v"1.3.7"

# Collection of sources required to complete build
sources = [
    ArchiveSource("https://files.inria.fr/starpu/starpu-1.3.7/starpu-1.3.7.tar.gz", "1d7e01567fbd4a66b7e563626899374735e37883226afb96c8952fea1dab77c2")
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir
cd starpu*
mkdir build
cd build
../configure --prefix=${prefix} --build=${MACHTYPE} --host=${target} --enable-fortran --disable-build-doc --disable-build-examples
make -j${nproc}
make install
install_license ../COPYING.LGPL
rm -r $prefix/share/doc/starpu
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_gfortran_versions(filter!(p -> !Sys.iswindows(p) && p ≠ Platform("aarch64", "linux", libc="musl"), supported_platforms()))

# The products that we will ensure are always built
products = [
    LibraryProduct(["libstarpu-1.3", "libstarpu-1"], :libstarpu),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency(PackageSpec(name="Hwloc_jll", uuid="e33a78d0-f292-5ffc-b300-72abe9b543c8")),
    Dependency(PackageSpec(name="CompilerSupportLibraries_jll", uuid="e66e0078-7015-5450-92f7-15fbd957f2ae"))
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; preferred_gcc_version = v"9.1.0")

max_stars_repo_name: bzinberg/Yggdrasil

max_issues_repo_name: bzinberg/Yggdrasil

max_forks_repo_name: bzinberg/Yggdrasil


text:
using Flux
using MacroTools: @forward, postwalk

"""
    Stack(topo::NNTopo, layers...)

like Flux.Chain, but you can use a NNTopo to define the order/structure of the function called.
"""
struct Stack{T<:Tuple, FS}
    models::T
    topo::NNTopo{FS}
    Stack(topo::NNTopo{FS}, xs...) where FS = new{typeof(xs), FS}(xs, topo)
end

Flux.functor(s::Stack) = s.models, m -> Stack(s.topo, m...)

@generated function (s::Stack{TP, FS})(xs...) where {TP, FS}
    _code = nntopo_impl(FS)
    n = fieldcount(TP)
    ms = [Symbol(:__model, i, :__) for i = 1:n]
    head = Expr(:(=), Expr(:tuple, ms...), :(s.models))
    pushfirst!(_code.args, head)
    code = postwalk(_code) do x
        if x isa Expr && x.head === :ref && x.args[1] === :model
            i = x.args[2]
            y = :($(ms[i]))
            return y
        else
            x
        end
    end
    return code
end

@forward Stack.models Base.getindex, Base.length

"return a list of n model with give args"
stack(n, modeltype::Type{T}, args...; kwargs...) where T = [modeltype(args...; kwargs...) for i = 1:n]

function Base.show(io::IO, s::Stack)
    print(io, "Stack(")
    join(io, s.models, ", ")
    print(io, ")")
end

"show the structure of the Stack function"
show_stackfunc(s::Stack) = print_topo(s.topo; models=s.models)


text:
"""
    IndependentMOKernel(k::Kernel)

Kernel for multiple independent outputs with kernel `k` each.

# Definition

For inputs ``x, x'`` and output dimensions ``p_x, p_{x'}'``, the kernel ``\\widetilde{k}``
for independent outputs with kernel ``k`` each is defined as
```math
\\widetilde{k}\\big((x, p_x), (x', p_{x'})\\big) = \\begin{cases}
    k(x, x') & \\text{if } p_x = p_{x'}, \\\\
    0 & \\text{otherwise}.
\\end{cases}
```
Mathematically, it is equivalent to a matrix-valued kernel defined as
```math
\\widetilde{K}(x, x') = \\mathrm{diag}\\big(k(x, x'), \\ldots, k(x, x')\\big) \\in \\mathbb{R}^{m \\times m},
```
where ``m`` is the number of outputs.
"""
struct IndependentMOKernel{Tkernel<:Kernel} <: MOKernel
    kernel::Tkernel
end

function (κ::IndependentMOKernel)((x, px)::Tuple{Any,Int}, (y, py)::Tuple{Any,Int})
    if px == py
        return κ.kernel(x, y)
    else
        return 0.0
    end
end

function kernelmatrix(k::IndependentMOKernel, x::MOInput, y::MOInput)
    @assert x.out_dim == y.out_dim
    temp = k.kernel.(x.x, permutedims(y.x))
    return cat((temp for _ in 1:(y.out_dim))...; dims=(1, 2))
end

function Base.show(io::IO, k::IndependentMOKernel)
    return print(io, string("Independent Multi-Output Kernel\n\t", string(k.kernel)))
end


text:
module FloatingTableView

using Blink: Window, body!, active
using TableView

export browse, showtable

# Method for keeping current window active borrowed
# from Plots.jl
mutable struct CurrentWin
    nullablewin::Union{Window, Nothing}
end
const CURRENT_WIN = CurrentWin(nothing)

iswinnull() = CURRENT_WIN.nullablewin === nothing

"""
    current()
Returns the Blink Window object for the current plot
"""
function current()
    if iswinnull()
        error("No current window")
    end
    CURRENT_WIN.nullablewin
end

current(win::Window) = (CURRENT_WIN.nullablewin = win)

"""
	browse(t; newwindow = false, kwargs...)

Browse data source in a new Blink window using
Tables.jl's `showtable` function.

# Arguments

- `t`, a Tables.jl-compatible data source,
  for example a `DataFrame` or a `NamedTuple`
  of `Vector`s
- `newwindow`, boolean keyword argument to view the data
  in a new `Blink` window instead of over-writing.
  Viewing in a new window will be slower than over-writing.
- `kwargs...`, keyword arguments passed to the
  `showtable` command from TableView.jl to
  control the details of the new data viewer.
  See [`showtable`](@ref) for details.

# Examples

```julia
julia> t = (a = rand(10), b = rand(10))

julia> browse(t)
```

```julia
julia> t = rand(100, 100)

julia> browse(t, dark = true)
```

See also: [`showtable`](@ref)
"""
function browse(df; height = "100vh", newwindow::Bool = false, kwargs...)
	if newwindow == true
    body!(Window(), showtable(df; height = height, kwargs...))
  elseif iswinnull() || !active(current())
		w = Window()
		current(w)
		body!(current(), showtable(df; height = height, kwargs...))
	else
		body!(current(), showtable(df; height = height, kwargs...))
	end

    return nothing
end

end # module


text:
using Test, Tracking, GNSSSignals, Random, StaticArrays, TrackingLoopFilters
import Unitful: MHz, kHz, Hz, s, ms, dBHz

include("discriminators.jl")
include("gps_l1.jl")
include("gps_l5.jl")
include("galileo_e1b.jl")
include("secondary_code_or_bit_detector.jl")
include("bit_buffer.jl")
include("correlator.jl")
include("tracking_state.jl")
include("tracking_results.jl")
include("tracking_loop.jl")
include("cn0_estimation.jl")


text:
export Point, RouteSection

"""
    Radius Earth [m]

Source: en.wikipedia.org/wiki/Earth_radius
"""
const Rₑ_m = 6371008.7714

"Point type with latitude `ϕ` [deg] and longitude `λ` [deg]"
struct Point{T<:Float64}
    ϕ::T
    λ::T
end

(-)(x::Point, y::Point) = Point(x.ϕ - y.ϕ, x.λ - y.λ)
(rad2deg)(x::Point) = Point(rad2deg(x.ϕ), rad2deg(x.λ))
(deg2rad)(x::Point) = Point(deg2rad(x.ϕ), deg2rad(x.λ))

"RouteSection type with start position pos₁ [Point] and end position pos₂
[Point_deg]"
struct RouteSection{T}
    pos₁::T
    pos₂::T
end

"""
    normalize(value::Float64[, lower::Float64 = 0.0, upper::Float64 = 360.0])

Normalize a `value` to stay within the `lower` and `upper` limit.

Example:
normalize(370.0, lower=0.0, upper=360.0)
10.0
"""
function normalize(value::Float64, lower::Float64 = 0.0, upper::Float64 = 360.0)
    result = value
    if result > upper || value == lower
        value = lower + abs(value + upper) % (abs(lower) + abs(upper))
    end
    if result < lower || value == upper
        value = upper - abs(value - lower) % (abs(lower) + abs(upper))
    end
    value == upper ? result = lower : result = value
    return result
end

#TODO Get a more efficient way to normalize latitude
"""
    normalize(point::Point)

Normalize a `point`.
"""
function normalize(point::Point)
    return Point(asind(sind(point.ϕ)), normalize(point.λ, -180.0, 180.0))
end


text:
# model_input.jl

mutable struct ModelInput{AT,FT}
    nx::Int64
    ny::Int64
    nz::Int64
    Lx::FT
    Ly::FT
    Lz::FT
    Δx::FT
    Δy::FT
    Δz::FT
    Δt::FT
    tend::FT
    K0::FT
    S0::FT
    h0::FT
    u0::FT
    v0::FT
    w0::FT
    source::FT
    i_src::Int64
    j_src::Int64
    k_src::Int64
    duration::FT
    ΔhConv::FT
    constRecharge::FT
    rechargeFactor::FT
    boundaryPressure::AT
end

"""Returns default model input"""
function getDefaultInput(myFloat, config_file)
    config = TOML.parsefile(config_file)

    Δx   = config["Lx"] / (config["nx"] + 1)
    Δy   = config["Ly"] / (config["ny"] + 1)
    Δz   = config["Lz"] / (config["nz"] + 1)

    constRecharge = config["unit_recharge_flux"] * Δx * Δy / (24 * 3600) # (m3/s)

    boundaryPressure = [myFloat(config["h_bc_west"]), myFloat(config["h_bc_east"])]

    # Store the input in tuple "input"
    AT = typeof(boundaryPressure)
    input = ModelInput{AT,myFloat}(config["nx"], config["nz"], config["nz"],
                                   config["Lx"], config["Ly"], config["Ly"],
                                   Δx, Δy, Δz,
                                   config["delta_t"], config["tend"],
                                   config["K0"], config["S0"],
                                   config["h0"], config["u0"], config["v0"], config["w0"],
                                   config["source"], config["i_src"], config["j_src"], config["k_src"], config["duration"],
                                   config["delta_h_conv"],
                                   constRecharge, config["recharge_factor"],
                                   boundaryPressure)

end


text:
"""
TransitNetwork

* `nstations`: number of stations in network
* `lines`: lines in the network (which can be used to start a master problem)
* `xfrstns`: for each commute (u, v), a list of transfer stations w that could be used to
*            transfer u -> w -> v.
* `odmatrix`: demand for commute (u, v)
* `latlon`: (latlon[u, 1], latlon[u, 2]) provide the coordinates for station u
* `gridtype`: `:euclidan` if `latlon` should be interpreted as Euclidean coordinates and `:latlong" otherwise
* `dists`: (if not specified, then computed using haversine or euclidean distance)
*           dists[u,v] gives the edge distance for edge (u,v)
* `spdists`: (if not specified, then computed using haversine or euclidean distance)
*            spdists[u,v] gives the shortest path distance from u to v
"""
mutable struct TransitNetwork
    nstations::Int
    lines::Vector{Vector{Int}}
    xfrstns::Dict{Tuple{Int,Int},Vector{Int}}
    odmatrix::Array{Float64,2}
    latlon::Array{Float64,2}
    gridtype::Symbol
    dists
    spdists
end

function Base.show(io::IO, np::TransitNetwork; offset::String="")
    println(io, offset, string(typeof(np)))
    println(io, offset, "    * nstations: $(np.nstations)")
end


text:
#
#=
Example: Test of the Dielectronic module
=#
println("Df) Test of the Dielectronic module with ASF from an internally generated initial-, intermediate and final-state multiplets.")
#
setDefaults("print summary: open", "zzz-Dielectronic.sum")
setDefaults("method: continuum, asymptotic Coulomb")  ## setDefaults("method: continuum, Galerkin")
setDefaults("method: normalization, pure sine")   ## setDefaults("method: normalization, pure Coulomb")    setDefaults("method: normalization, pure sine")

wa = Atomic.Computation("xx",  Nuclear.Model(26.); grid=JAC.Radial.Grid("grid: by given parameters"; rnt = 2.0e-5, h = 5.0e-2, hp = 2.0e-2, NoPoints = 600),
                        initialConfigs=[Configuration("1s^2 2s"), Configuration("1s^2 2p")],
                        intermediateConfigs=[Configuration("1s 2s^2 2p"), Configuration("1s 2s 2p^2") ],
                        finalConfigs  =[Configuration("1s^2 2s^2"), Configuration("1s^2 2s 2p") ],
                        process = JAC.Dierec,
                        processSettings=Dielectronic.Settings([E1, M1], [JAC.UseCoulomb, JAC.UseBabushkin], true,
                                                              true, Tuple{Int64,Int64,Int64}[(1,1,0), (1,2,0), (1,3,0)], 0., 0., 0., "Coulomb")  )

wb = perform(wa)
setDefaults("print summary: close", "")


text:
@timed_testset "UIO" begin
    @test_throws ErrorException UIO(rand(2,2), rand(2,1), ones(1,2), rand(2,2))
end


text:
# *********************************************************************************
# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list
# of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# Neither the name of the copyright holder nor the names of its contributors may be
# used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
# *********************************************************************************
"""
    REoptInputs

The data structure for all the inputs necessary to construct the JuMP model.
```julia
struct REoptInputs <: AbstractInputs
    s::AbstractScenario
    techs::Techs
    min_sizes::Dict{String, Float64}  # (techs)
    max_sizes::Dict{String, Float64}  # (techs)
    existing_sizes::Dict{String, Float64}  # (techs)
    cap_cost_slope::Dict{String, Any}  # (techs)
    om_cost_per_kw::Dict{String, Float64}  # (techs)
    time_steps::UnitRange
    time_steps_with_grid::Array{Int, 1}
    time_steps_without_grid::Array{Int, 1}
    hours_per_timestep::Float64
    months::UnitRange
    production_factor::DenseAxisArray{Float64, 2}  # (techs, time_steps)
    levelization_factor::Dict{String, Float64}  # (techs)
    value_of_lost_load_per_kwh::Array{R, 1} where R<:Real #default set to 1 US dollar per kwh
    pwf_e::Float64
    pwf_om::Float64
    third_party_factor::Float64
    pvlocations::Array{Symbol, 1}
    maxsize_pv_locations::DenseAxisArray{Float64, 1}  # indexed on pvlocations
    pv_to_location::Dict{String, Dict{Symbol, Int64}}  # (techs.pv, pvlocations)
    ratchets::UnitRange
    techs_by_exportbin::Dict{Symbol, AbstractArray}  # keys can include [:NEM, :WHL, :CUR]
    export_bins_by_tech::Dict
    n_segs_by_tech::Dict{String, Int}
    seg_min_size::Dict{String, Dict{Int, Float64}}
    seg_max_size::Dict{String, Dict{Int, Float64}}
    seg_yint::Dict{String, Dict{Int, Float64}}
    pbi_pwf::Dict{String, Any}  # (pbi_techs)
    pbi_max_benefit::Dict{String, Any}  # (pbi_techs)
    pbi_max_kw::Dict{String, Any}  # (pbi_techs)
    pbi_benefit_per_kwh::Dict{String, Any}  # (pbi_techs)
    boiler_efficiency::Dict{String, Float64}
end
```
"""
struct REoptInputs <: AbstractInputs
    s::AbstractScenario
    techs::Techs
    min_sizes::Dict{String, Float64}  # (techs)
    max_sizes::Dict{String, Float64}  # (techs)
    existing_sizes::Dict{String, Float64}  # (techs)
    cap_cost_slope::Dict{String, Any}  # (techs)
    om_cost_per_kw::Dict{String, Float64}  # (techs)
    time_steps::UnitRange
    time_steps_with_grid::Array{Int, 1}
    time_steps_without_grid::Array{Int, 1}
    hours_per_timestep::Float64
    months::UnitRange
    production_factor::DenseAxisArray{Float64, 2}  # (techs, time_steps)
    levelization_factor::Dict{String, Float64}  # (techs)
    value_of_lost_load_per_kwh::Array{R, 1} where R<:Real #default set to 1 US dollar per kwh
    pwf_e::Float64
    pwf_om::Float64
    pwf_fuel::Dict{String, Float64}
    third_party_factor::Float64
    pvlocations::Array{Symbol, 1}
    maxsize_pv_locations::DenseAxisArray{Float64, 1}  # indexed on pvlocations
    pv_to_location::Dict{String, Dict{Symbol, Int64}}  # (techs.pv, pvlocations)
    ratchets::UnitRange
    techs_by_exportbin::Dict{Symbol, AbstractArray}  # keys can include [:NEM, :WHL, :CUR]
    export_bins_by_tech::Dict
    n_segs_by_tech::Dict{String, Int}
    seg_min_size::Dict{String, Dict{Int, Float64}}
    seg_max_size::Dict{String, Dict{Int, Float64}}
    seg_yint::Dict{String, Dict{Int, Float64}}
    pbi_pwf::Dict{String, Any}  # (pbi_techs)
    pbi_max_benefit::Dict{String, Any}  # (pbi_techs)
    pbi_max_kw::Dict{String, Any}  # (pbi_techs)
    pbi_benefit_per_kwh::Dict{String, Any}  # (pbi_techs)
    boiler_efficiency::Dict{String, Float64}
end

"""
    REoptInputs(fp::String)

Use `fp` to load in JSON scenario:
```
function REoptInputs(fp::String)
    s = Scenario(JSON.parsefile(fp))
    REoptInputs(s)
end
```
Useful if you want to manually modify REoptInputs before solving the model.
"""
function REoptInputs(fp::String)
    s = Scenario(JSON.parsefile(fp))
    REoptInputs(s)
end

"""
    REoptInputs(s::AbstractScenario)

Constructor for REoptInputs. Translates the `Scenario` into all the data necessary for building the JuMP model.
"""
function REoptInputs(s::AbstractScenario)

    time_steps = 1:length(s.electric_load.loads_kw)
    hours_per_timestep = 1 / s.settings.time_steps_per_hour
    techs, pv_to_location, maxsize_pv_locations, pvlocations,
        production_factor, max_sizes, min_sizes, existing_sizes, cap_cost_slope, om_cost_per_kw, n_segs_by_tech,
        seg_min_size, seg_max_size, seg_yint, techs_by_exportbin, export_bins_by_tech, boiler_efficiency =
        setup_tech_inputs(s)

    pbi_pwf, pbi_max_benefit, pbi_max_kw, pbi_benefit_per_kwh = setup_pbi_inputs(s, techs)

    months = 1:12

    levelization_factor, pwf_e, pwf_om, pwf_fuel, third_party_factor = setup_present_worth_factors(s, techs)
    # the following hardcoded values for levelization_factor matches the public REopt API value
    # and makes the test values match.
    # the REopt code herein uses the Desktop method for levelization_factor, which is more accurate
    # (Desktop has non-linear degradation vs. linear degradation in API)
    # levelization_factor = Dict("PV" => 0.9539)
    # levelization_factor = Dict("ground" => 0.942238, "roof_east" => 0.942238, "roof_west" => 0.942238)
    # levelization_factor = Dict("PV" => 0.9539, "Generator" => 1.0)
    time_steps_with_grid, time_steps_without_grid, = setup_electric_utility_inputs(s)

    if any(pv.existing_kw > 0 for pv in s.pvs)
        adjust_load_profile(s, production_factor)
    end

    REoptInputs(
        s,
        techs,
        min_sizes,
        max_sizes,
        existing_sizes,
        cap_cost_slope,
        om_cost_per_kw,
        time_steps,
        time_steps_with_grid,
        time_steps_without_grid,
        hours_per_timestep,
        months,
        production_factor,
        levelization_factor,
        typeof(s.financial.value_of_lost_load_per_kwh) <: Array{<:Real, 1} ? s.financial.value_of_lost_load_per_kwh : fill(s.financial.value_of_lost_load_per_kwh, length(time_steps)),
        pwf_e,
        pwf_om,
        pwf_fuel,
        third_party_factor,
        pvlocations,
        maxsize_pv_locations,
        pv_to_location,
        1:length(s.electric_tariff.tou_demand_ratchet_timesteps),  # ratchets
        techs_by_exportbin,
        export_bins_by_tech,
        n_segs_by_tech,
        seg_min_size,
        seg_max_size,
        seg_yint,
        pbi_pwf,
        pbi_max_benefit,
        pbi_max_kw,
        pbi_benefit_per_kwh,
        boiler_efficiency
    )
end

"""
    function setup_tech_inputs(s::AbstractScenario)

Create data arrays associated with techs necessary to build the JuMP model.
"""
function setup_tech_inputs(s::AbstractScenario)

    techs = Techs(s)

    boiler_efficiency = Dict{String, Float64}()
    production_factor = DenseAxisArray{Float64}(undef, techs.all, 1:length(s.electric_load.loads_kw))

    # REoptInputs indexed on techs:
    max_sizes = Dict(t => 0.0 for t in techs.all)
    min_sizes = Dict(t => 0.0 for t in techs.all)
    existing_sizes = Dict(t => 0.0 for t in techs.all)
    cap_cost_slope = Dict{String, Any}()
    om_cost_per_kw = Dict(t => 0.0 for t in techs.all)

    # export related inputs
    techs_by_exportbin = Dict(k => [] for k in s.electric_tariff.export_bins)
    export_bins_by_tech = Dict{String, Array{Symbol, 1}}()

    # REoptInputs indexed on techs.segmented
    n_segs_by_tech = Dict{String, Int}()
    seg_min_size = Dict{String, Any}()
    seg_max_size = Dict{String, Any}()
    seg_yint = Dict{String, Any}()

    # PV specific arrays
    pvlocations = [:roof, :ground, :both]
    pv_to_location = Dict(t => Dict(loc => 0) for (t, loc) in zip(techs.pv, pvlocations))
    maxsize_pv_locations = DenseAxisArray([1.0e5, 1.0e5, 1.0e5], pvlocations)
    # default to large max size per location. Max size by roof, ground, both

    if !isempty(techs.pv)
        setup_pv_inputs(s, max_sizes, min_sizes, existing_sizes, cap_cost_slope, om_cost_per_kw, production_factor,
                        pvlocations, pv_to_location, maxsize_pv_locations, techs.segmented, n_segs_by_tech,
                        seg_min_size, seg_max_size, seg_yint, techs_by_exportbin, techs.no_curtail)
    end

    if "Wind" in techs.all
        setup_wind_inputs(s, max_sizes, min_sizes, existing_sizes, cap_cost_slope, om_cost_per_kw, production_factor,
            techs_by_exportbin, techs.segmented, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint, techs.no_curtail)
    end

    if "Generator" in techs.all
        setup_gen_inputs(s, max_sizes, min_sizes, existing_sizes, cap_cost_slope, om_cost_per_kw, production_factor,
            techs_by_exportbin, techs.segmented, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint, techs.no_curtail)
    end

    if "ExistingBoiler" in techs.all
        setup_existing_boiler_inputs(s, max_sizes, min_sizes, existing_sizes, cap_cost_slope, boiler_efficiency)
    end

    # filling export_bins_by_tech MUST be done after techs_by_exportbin has been filled in
    for t in techs.elec
        export_bins_by_tech[t] = [bin for (bin, ts) in techs_by_exportbin if t in ts]
    end

    return techs, pv_to_location, maxsize_pv_locations, pvlocations,
    production_factor, max_sizes, min_sizes, existing_sizes, cap_cost_slope, om_cost_per_kw, n_segs_by_tech,
    seg_min_size, seg_max_size, seg_yint, techs_by_exportbin, export_bins_by_tech, boiler_efficiency
end

"""
    setup_pbi_inputs(s::AbstractScenario, techs::Techs)

Create data arrays for production based incentives.
All arrays can be empty if no techs have production_incentive_per_kwh > 0.
"""
function setup_pbi_inputs(s::AbstractScenario, techs::Techs)

    pbi_pwf = Dict{String, Any}()
    pbi_max_benefit = Dict{String, Any}()
    pbi_max_kw = Dict{String, Any}()
    pbi_benefit_per_kwh = Dict{String, Any}()

    for tech in techs.all
        if !(tech in techs.pv)
            T = typeof(eval(Meta.parse(tech)))
            if :production_incentive_per_kwh in fieldnames(T)
                if eval(Meta.parse("s."*tech*".production_incentive_per_kwh")) > 0
                    push!(techs.pbi, tech)
                    pbi_pwf[tech], pbi_max_benefit[tech], pbi_max_kw[tech], pbi_benefit_per_kwh[tech] =
                        production_incentives(eval(Meta.parse("s."*tech)), s.financial)
                end
            end
        else
            pv = get_pv_by_name(tech, s.pvs)
            if pv.production_incentive_per_kwh > 0
                push!(techs.pbi, tech)
                pbi_pwf[tech], pbi_max_benefit[tech], pbi_max_kw[tech], pbi_benefit_per_kwh[tech] =
                    production_incentives(pv, s.financial)
            end
        end

    end
    return pbi_pwf, pbi_max_benefit, pbi_max_kw, pbi_benefit_per_kwh
end

"""
    update_cost_curve!(tech::AbstractTech, tech_name::String, financial::Financial,
        cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint
    )

Modifies cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint based on tech attributes.
In the simplest case (zero incentives, no existing_kw) the cap_cost_slope is updated with:
```julia
    cap_cost_slope[tech_name] = tech.installed_cost_per_kw
```
However, if there are non-zero incentives or `existing_kw` then there will be more than one cost curve segment typically
and all of the other arguments will be updated as well.
"""
function update_cost_curve!(tech::AbstractTech, tech_name::String, financial::Financial,
    cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint
    )
    cost_slope, cost_curve_bp_x, cost_yint, n_segments = cost_curve(tech, financial)
    cap_cost_slope[tech_name] = cost_slope[1]
    if n_segments > 1
        cap_cost_slope[tech_name] = cost_slope
        push!(segmented_techs, tech_name)
        seg_max_size[tech_name] = Dict{Int,Float64}()
        seg_min_size[tech_name] = Dict{Int,Float64}()
        n_segs_by_tech[tech_name] = n_segments
        seg_yint[tech_name] = Dict{Int,Float64}()
        for s in 1:n_segments
            seg_min_size[tech_name][s] = cost_curve_bp_x[s]
            seg_max_size[tech_name][s] = cost_curve_bp_x[s+1]
            seg_yint[tech_name][s] = cost_yint[s]
        end
    end
    nothing
end

function setup_pv_inputs(s::AbstractScenario, max_sizes, min_sizes,
    existing_sizes, cap_cost_slope, om_cost_per_kw, production_factor,
    pvlocations, pv_to_location, maxsize_pv_locations,
    segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint, techs_by_exportbin, techs_no_curtail)

    pv_roof_limited, pv_ground_limited, pv_space_limited = false, false, false
    roof_existing_pv_kw, ground_existing_pv_kw, both_existing_pv_kw = 0.0, 0.0, 0.0
    roof_max_kw, land_max_kw = 1.0e5, 1.0e5

    for pv in s.pvs
        production_factor[pv.name, :] = prodfactor(pv, s.site.latitude, s.site.longitude)
        for location in pvlocations
            if pv.location == location
                pv_to_location[pv.name][location] = 1
            else
                pv_to_location[pv.name][location] = 0
            end
        end

        beyond_existing_kw = pv.max_kw
        if pv.location == "both"
            both_existing_pv_kw += pv.existing_kw
            if !(s.site.roof_squarefeet === nothing) && !(s.site.land_acres === nothing)
                # don"t restrict unless both land_area and roof_area specified,
                # otherwise one of them is "unlimited"
                roof_max_kw = s.site.roof_squarefeet * pv.kw_per_square_foot
                land_max_kw = s.site.land_acres / pv.acres_per_kw
                beyond_existing_kw = min(roof_max_kw + land_max_kw, beyond_existing_kw)
                pv_space_limited = true
            end
        elseif pv.location == "roof"
            roof_existing_pv_kw += pv.existing_kw
            if !(s.site.roof_squarefeet === nothing)
                roof_max_kw = s.site.roof_squarefeet * pv.kw_per_square_foot
                beyond_existing_kw = min(roof_max_kw, beyond_existing_kw)
                pv_roof_limited = true
            end

        elseif pv.location == "ground"
            ground_existing_pv_kw += pv.existing_kw
            if !(s.site.land_acres === nothing)
                land_max_kw = s.site.land_acres / pv.acres_per_kw
                beyond_existing_kw = min(land_max_kw, beyond_existing_kw)
                pv_ground_limited = true
            end
        end

        existing_sizes[pv.name] = pv.existing_kw
        min_sizes[pv.name] = pv.existing_kw + pv.min_kw
        max_sizes[pv.name] = pv.existing_kw + beyond_existing_kw

        update_cost_curve!(pv, pv.name, s.financial,
            cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint
        )

        om_cost_per_kw[pv.name] = pv.om_cost_per_kw
        fillin_techs_by_exportbin(techs_by_exportbin, pv, pv.name)

        if !pv.can_curtail
            push!(techs_no_curtail, pv.name)
        end
    end

    if pv_roof_limited
        maxsize_pv_locations[:roof] = float(roof_existing_pv_kw + roof_max_kw)
    end
    if pv_ground_limited
        maxsize_pv_locations[:ground] = float(ground_existing_pv_kw + land_max_kw)
    end
    if pv_space_limited
        maxsize_pv_locations[:both] = float(both_existing_pv_kw + roof_max_kw + land_max_kw)
    end

    return nothing
end

function setup_wind_inputs(s::AbstractScenario, max_sizes, min_sizes, existing_sizes,
    cap_cost_slope, om_cost_per_kw, production_factor, techs_by_exportbin,
    segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint, techs_no_curtail
    )
    max_sizes["Wind"] = s.wind.max_kw
    min_sizes["Wind"] = s.wind.min_kw
    existing_sizes["Wind"] = 0.0
    update_cost_curve!(s.wind, "Wind", s.financial,
        cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint
    )
    om_cost_per_kw["Wind"] = s.wind.om_cost_per_kw
    production_factor["Wind", :] = prodfactor(s.wind, s.site.latitude, s.site.longitude, s.settings.time_steps_per_hour)
    fillin_techs_by_exportbin(techs_by_exportbin, s.wind, "Wind")
    if !s.wind.can_curtail
        push!(techs_no_curtail, "Wind")
    end
    return nothing
end

function setup_gen_inputs(s::AbstractScenario, max_sizes, min_sizes, existing_sizes,
    cap_cost_slope, om_cost_per_kw, production_factor, techs_by_exportbin,
    segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint, techs_no_curtail
    )
    max_sizes["Generator"] = s.generator.max_kw
    min_sizes["Generator"] = s.generator.existing_kw + s.generator.min_kw
    existing_sizes["Generator"] = s.generator.existing_kw
    update_cost_curve!(s.generator, "Generator", s.financial,
        cap_cost_slope, segmented_techs, n_segs_by_tech, seg_min_size, seg_max_size, seg_yint
    )
    om_cost_per_kw["Generator"] = s.generator.om_cost_per_kw
    production_factor["Generator", :] = prodfactor(s.generator)
    fillin_techs_by_exportbin(techs_by_exportbin, s.generator, "Generator")
    if !s.generator.can_curtail
        push!(techs_no_curtail, "Generator")
    end
    return nothing
end

function setup_existing_boiler_inputs(s::AbstractScenario, max_sizes, min_sizes, existing_sizes, cap_cost_slope, boiler_efficiency)
    max_sizes["ExistingBoiler"] = s.existing_boiler.max_kw
    min_sizes["ExistingBoiler"] = 0.0
    existing_sizes["ExistingBoiler"] = 0.0
    cap_cost_slope["ExistingBoiler"] = 0.0
    boiler_efficiency["ExistingBoiler"] = s.existing_boiler.efficiency
    # om_cost_per_kw["ExistingBoiler"] = 0.0
    return nothing
end

function setup_present_worth_factors(s::AbstractScenario, techs::Techs)

    lvl_factor = Dict(t => 1.0 for t in techs.all)  # default levelization_factor of 1.0
    for (i, tech) in enumerate(techs.pv)  # replace 1.0 with actual PV levelization_factor (only tech with degradation)
        lvl_factor[tech] = levelization_factor(
            s.financial.analysis_years,
            s.financial.elec_cost_escalation_pct,
            s.financial.offtaker_discount_pct,
            s.pvs[i].degradation_pct  # TODO generalize for any tech (not just pvs)
        )
    end

    pwf_e = annuity(
        s.financial.analysis_years,
        s.financial.elec_cost_escalation_pct,
        s.financial.offtaker_discount_pct
    )

    pwf_om = annuity(
        s.financial.analysis_years,
        s.financial.om_cost_escalation_pct,
        s.financial.owner_discount_pct
    )
    pwf_fuel = Dict{String, Float64}()
    for t in techs.fuel_burning
        if t == "ExistingBoiler"
            pwf_fuel["ExistingBoiler"] = annuity(
                s.financial.analysis_years,
                s.financial.boiler_fuel_cost_escalation_pct,
                s.financial.offtaker_discount_pct
            )
        end
    end

    if s.financial.third_party_ownership
        pwf_offtaker = annuity(s.financial.analysis_years, 0.0, s.financial.offtaker_discount_pct)
        pwf_owner = annuity(s.financial.analysis_years, 0.0, s.financial.owner_discount_pct)
        third_party_factor = (pwf_offtaker * (1 - s.financial.offtaker_tax_pct)) /
                           (pwf_owner * (1 - s.financial.owner_tax_pct))
    else
        third_party_factor = 1.0
    end

    return lvl_factor, pwf_e, pwf_om, pwf_fuel, third_party_factor
end

"""
    setup_electric_utility_inputs(s::AbstractScenario)

Define the `time_steps_with_grid` and `time_steps_without_grid` (detministic outage).

NOTE: v1 of the API spliced the critical_loads_kw into the loads_kw during outages but this splicing is no longer needed
now that the constraints are properly applied over `time_steps_with_grid` and `time_steps_without_grid` using loads_kw
and critical_loads_kw respectively.
"""
function setup_electric_utility_inputs(s::AbstractScenario)
    if s.electric_utility.outage_end_time_step > 0 &&
            s.electric_utility.outage_end_time_step > s.electric_utility.outage_start_time_step
        time_steps_without_grid = Int[i for i in range(s.electric_utility.outage_start_time_step,
                                                    stop=s.electric_utility.outage_end_time_step)]
        if s.electric_utility.outage_start_time_step > 1
            time_steps_with_grid = append!(
                Int[i for i in range(1, stop=s.electric_utility.outage_start_time_step - 1)],
                Int[i for i in range(s.electric_utility.outage_end_time_step + 1,
                                     stop=length(s.electric_load.loads_kw))]
            )
        else
            time_steps_with_grid = Int[i for i in range(s.electric_utility.outage_end_time_step + 1,
                                       stop=length(s.electric_load.loads_kw))]
        end
    else
        time_steps_without_grid = Int[]
        time_steps_with_grid = Int[i for i in range(1, stop=length(s.electric_load.loads_kw))]
    end
    return time_steps_with_grid, time_steps_without_grid
end

"""
    adjust_load_profile(s::AbstractScenario, production_factor::DenseAxisArray)

Adjust the (critical_)loads_kw based off of (critical_)loads_kw_is_net
"""
function adjust_load_profile(s::AbstractScenario, production_factor::DenseAxisArray)
    if s.electric_load.loads_kw_is_net
        for pv in s.pvs if pv.existing_kw > 0
            s.electric_load.loads_kw .+= pv.existing_kw * production_factor[pv.name, :].data
        end end
    end

    if s.electric_load.critical_loads_kw_is_net
        for pv in s.pvs if pv.existing_kw > 0
            s.electric_load.critical_loads_kw .+= pv.existing_kw * production_factor[pv.name, :].data
        end end
    end
end

"""
    production_incentives(tech::AbstractTech, financial::Financial)

Intermediate function for building the PBI arrays in REoptInputs
"""
function production_incentives(tech::AbstractTech, financial::Financial)
    pwf_prod_incent = 0.0
    max_prod_incent = 0.0
    max_size_for_prod_incent = 0.0
    production_incentive_rate = 0.0
    T = typeof(tech)
    # TODO should Generator be excluded? (v1 has the PBI inputs for Generator)
    if !(nameof(T) in [:Generator, :Boiler, :Elecchl, :Absorpchl])
        if :degradation_pct in fieldnames(T)  # PV has degradation
            pwf_prod_incent = annuity_escalation(tech.production_incentive_years, -1*tech.degradation_pct,
                                                 financial.owner_discount_pct)
        else
            # prod incentives have zero escalation rate
            pwf_prod_incent = annuity(tech.production_incentive_years, 0, financial.owner_discount_pct)
        end
        max_prod_incent = tech.production_incentive_max_benefit
        max_size_for_prod_incent = tech.production_incentive_max_kw
        production_incentive_rate = tech.production_incentive_per_kwh
    end

    return pwf_prod_incent, max_prod_incent, max_size_for_prod_incent, production_incentive_rate
end

function fillin_techs_by_exportbin(techs_by_exportbin::Dict, tech::AbstractTech, tech_name::String)
    if tech.can_net_meter && :NEM in keys(techs_by_exportbin)
        push!(techs_by_exportbin[:NEM], tech_name)
        if tech.can_export_beyond_nem_limit && :EXC in keys(techs_by_exportbin)
            push!(techs_by_exportbin[:EXC], tech_name)
        end
    end

    if tech.can_wholesale && :WHL in keys(techs_by_exportbin)
        push!(techs_by_exportbin[:WHL], tech_name)
    end
    return nothing
end

max_stars_repo_name: NREL/REoptLite

max_issues_repo_name: NREL/REoptLite

max_forks_repo_name: NREL/REoptLite


text:
export project_histogram_relaxed!

"""
Computes the projection of x onto a (relaxed) histogram.
P*LB <= P*x <= P*UB
x is a vector and the bounds are vectors as well. P is the orthogonal permutation matrix that
sorts x. The LB and UB are vectors that are the sorted values of the bounds
"""
function project_histogram_relaxed!(x::Vector{TF},LB::Vector{TF},UB::Vector{TF}) where {TF<:Real}

sort_ind = sortperm( x)#, by=abs)
x .= x[sort_ind]
#we use sorting from small to large. LB and UB also need to be sorted from small to large!
@inbounds Threads.@threads for j in (1:length(x))
  @inbounds  x[j] = min(x[j],UB[j])
  @inbounds  x[j] = max(LB[j],x[j])
end
sort_ind_sort_ind = sortperm(sort_ind)
x .= x[sort_ind_sort_ind] #rearrange back to original order

# This version needs two sorts.
# We can also apply the bounds in a loop over the x[sort_ind] coeffs
# without sorting x and sorting it back, but it requires memory access
# to x, LB and UB in non sequential order.
return x
end

max_stars_repo_name: slimgroup/SetIntersectionProjection

max_issues_repo_name: slimgroup/SetIntersectionProjection

max_forks_repo_name: slimgroup/SetIntersectionProjection