gdx

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gdx-reader

pkg.go.dev

A Go package for read-only access to GAMS GDX (.gdx) data files. It loads the GDX shared library that ships with a GAMS installation at runtime via purego, so it builds and runs with CGO_ENABLED=0 on Linux, macOS and Windows.

Requirements

  • Go 1.27+ (per go.mod)
  • A GAMS installation, or the GDX shared library on its own: libgdxc.dylib (macOS), libgdxc.so (Linux) or gdxc.dll (Windows)

The shared library is not distributed with this package; GAMS's license terms apply to it.

Installation

go get codeberg.org/0x2321/gdx-reader

Usage

package main

import (
	"fmt"
	"log"

	"codeberg.org/0x2321/gdx-reader"
)

func main() {
	// An empty library path lets the package locate the library itself.
	f, err := gdx.Open("", "results.gdx")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	sym, err := f.Symbol("distance")
	if err != nil {
		log.Fatal(err)
	}

	for rec, err := range f.ParameterRecords(sym) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(rec.Keys, rec.Value.Float64())
	}
}

Finding the Library

Open takes the path to the shared library as its first argument; pass an empty string to have it located automatically from the GDX_LIBRARY_PATH, GAMS_DIR, GAMSPATH or GAMSDIR environment variables, the working directory and standard installation locations. Use OpenWithGamsDir to search a specific GAMS installation directory. The full search order is documented in the package documentation.

CLI

A command-line tool for quick inspection is included in cmd/gdx-reader:

go install codeberg.org/0x2321/gdx-reader/cmd/gdx-reader@latest
gdx-reader results.gdx                          # file overview
gdx-reader -symbol distance -json results.gdx   # one symbol as JSON

Run gdx-reader -h for the full list of flags.

Limitations

  • Read-only: the package cannot write to or modify GDX files.
  • A File is not safe for concurrent use.
  • GAMS special values (NA, UNDF, EPS, ±INF) are reported via the Value.Special field rather than as ordinary numbers.

Documentation

The complete API documentation is in the package documentation at pkg.go.dev/codeberg.org/0x2321/gdx-reader.

Tests

Run the tests with go test ./.... They use a small C mock of the GDX C API that is compiled on demand, so a C compiler (clang or cc) must be available; without one the tests are skipped.

License

MIT, see LICENSE.

Documentation

Overview

Package gdx provides read-only access to GAMS GDX (.gdx) data files.

The GDX shared library that ships with a GAMS installation (libgdxc) is loaded at runtime via purego, so no CGO is required: the package builds and runs with CGO_ENABLED=0 on Linux, macOS and Windows.

Open a file, inspect its symbols, and stream its records:

f, err := gdx.Open("/path/to/libgdxc.dylib", "results.gdx")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

sym, err := f.Symbol("distance")
if err != nil {
	log.Fatal(err)
}
for rec, err := range f.ParameterRecords(sym) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rec.Keys, rec.Value.Float64())
}

Locating the library

Open accepts the path to the shared library explicitly. If an empty string is passed instead, the library is located automatically: first in the GDX_LIBRARY_PATH, GAMS_DIR, GAMSPATH or GAMSDIR environment variables, then in the current working directory, in platform-specific standard locations, and finally along PATH. Use OpenWithGamsDir to search a specific GAMS installation directory.

Symbols

A GDX file contains symbols of the types Set, Parameter, Variable, Equation and Alias (see SymbolType). Records are read with the method matching the symbol type: SetRecords, ParameterRecords, VariableRecords and EquationRecords. Each record type carries only the fields that are meaningful for its symbol type. Alias symbols are resolved to their target, which is streamed and type-checked.

Special values

GAMS encodes undefined, missing and infinite results with sentinel doubles. When records are read, a raw double matching one of the sentinels is returned as a Value whose Special field names the special value (SpecialNA, SpecialUndef, SpecialEps, SpecialPosInf, SpecialNegInf) and whose Number carries a canonical Go representation: NaN for NA and UNDF, ±Inf for +INF/-INF, and 0 for EPS. Use Value.IsSpecial and Value.Float64 to discriminate; FormatValue renders a plain float64 for display.

Concurrency

A File is not safe for concurrent use. It may be used from a single goroutine at a time and must not be shared between goroutines without external synchronization. While a record sequence is being consumed, no other record read may be started on the same File.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a requested symbol does not exist in the file.
	ErrNotFound = errors.New("gdx: symbol not found")

	// ErrClosed is returned when an operation is attempted on a closed File.
	ErrClosed = errors.New("gdx: file is closed")

	// ErrLibraryNotLoaded is returned when the GDX shared library cannot be
	// located or loaded.
	ErrLibraryNotLoaded = errors.New("gdx: shared library not loaded")

	// ErrWrongType is returned by the typed record readers when the symbol
	// has a different type than the one the reader requires. Use errors.Is
	// to match it and errors.As to recover a *TypeError.
	ErrWrongType = errors.New("gdx: symbol has the wrong type")
)

Sentinel errors returned by the package. Use errors.Is to match them and errors.As to recover an *Error or *TypeError.

Functions

func FindGDXLibrary

func FindGDXLibrary() (string, error)

FindGDXLibrary searches for the GDX dynamic shared library on the current system.

func FormatValue added in v1.0.0

func FormatValue(v float64) string

FormatValue renders a value for display, recognising the Go values that GAMS special values are translated to.

Types

type EquType

type EquType int32

EquType identifies the constraint type of a GAMS equation, stored in the symbol's user-info field when the symbol is an equation.

const (
	// EquTypeE is an equality constraint (=e=).
	EquTypeE EquType = 53
	// EquTypeG is a greater-than-or-equal constraint (=g=).
	EquTypeG EquType = 54
	// EquTypeL is a less-than-or-equal constraint (=l=).
	EquTypeL EquType = 55
	// EquTypeN is a free constraint (=n=).
	EquTypeN EquType = 56
	// EquTypeX is an external constraint (=x=).
	EquTypeX EquType = 57
	// EquTypeC is a conic constraint (=c=).
	EquTypeC EquType = 58
	// EquTypeB is a boolean constraint (=b=).
	EquTypeB EquType = 59
)

func (EquType) String

func (e EquType) String() string

String returns the name of the equation type.

type EquationRecord

type EquationRecord struct {
	// Keys are the element names, one per equation dimension.
	Keys []string
	// Level is the .l value.
	Level Value
	// Marginal is the .m value.
	Marginal Value
	// Lower is the .lo (lower bound) value.
	Lower Value
	// Upper is the .up (upper bound) value.
	Upper Value
	// Scale is the .scale value.
	Scale Value
}

EquationRecord is a single element of an equation. It mirrors VariableRecord but is a distinct type.

type Error added in v1.0.0

type Error struct {
	// Code is the numeric error code reported by the GDX library.
	Code int32
	// Message is a human-readable description of the error.
	Message string
}

Error is an error reported by the GDX C API. It carries the numeric error code from the library and a human-readable message.

func (*Error) Error added in v1.0.0

func (e *Error) Error() string

Error implements the error interface.

type File added in v1.0.0

type File struct {
	// contains filtered or unexported fields
}

File is a read-only handle on a GDX file backed by the GDX shared library.

A File is not safe for concurrent use: it must be used from a single goroutine at a time. While a record sequence is being consumed, no other record read may be started on the same File.

func Open added in v1.0.0

func Open(libPath, gdxPath string) (*File, error)

Open opens gdxPath for reading, loading the GDX shared library from libPath. If libPath is empty the library is located automatically (see the package documentation). Open returns an error if the library cannot be loaded or the file cannot be opened.

func OpenWithGamsDir added in v1.0.0

func OpenWithGamsDir(gamsDir, gdxPath string) (*File, error)

OpenWithGamsDir opens gdxPath for reading, searching for the GDX shared library inside the GAMS installation directory gamsDir. If the library is not found there, it falls back to automatic location.

func (*File) Close added in v1.0.0

func (f *File) Close() error

Close releases the GDX file and the loaded shared library. It is idempotent: calling it more than once is safe.

Close must not be called while a record sequence is being consumed; an active sequence then yields ErrClosed.

func (*File) EquationRecords added in v1.0.0

func (f *File) EquationRecords(sym Symbol) iter.Seq2[EquationRecord, error]

EquationRecords streams the elements of the equation sym as EquationRecords.

The sequence is single-use, as with SetRecords. An alias sym is resolved to its target, which is streamed and type-checked. If the (resolved) symbol is not an equation, the sequence yields exactly one *TypeError that matches ErrWrongType via errors.Is.

func (*File) Info added in v1.0.0

func (f *File) Info() FileInfo

Info returns metadata about the opened file.

func (*File) ParameterRecords added in v1.0.0

func (f *File) ParameterRecords(sym Symbol) iter.Seq2[ParameterRecord, error]

ParameterRecords streams the elements of the parameter sym as ParameterRecords. Scalar parameters have empty Keys.

The sequence is single-use, as with SetRecords. An alias sym is resolved to its target, which is streamed and type-checked. If the (resolved) symbol is not a parameter, the sequence yields exactly one *TypeError that matches ErrWrongType via errors.Is.

func (*File) SetRecords added in v1.0.0

func (f *File) SetRecords(sym Symbol) iter.Seq2[SetRecord, error]

SetRecords streams the elements of the set sym as SetRecords. Each record's Text is the element's explanatory text, empty when the element carries no text.

The sequence is single-use: obtain a fresh sequence for each read, and do not start another record read on the same File while one is being consumed. An alias sym is resolved to its target, which is streamed and type-checked. If the (resolved) symbol is not a set, the sequence yields exactly one *TypeError that matches ErrWrongType via errors.Is.

func (*File) Symbol added in v1.0.0

func (f *File) Symbol(name string) (Symbol, error)

Symbol returns the symbol named name, looked up case-insensitively via gdxFindSymbol. It returns an error wrapping ErrNotFound when the symbol does not exist.

func (*File) Symbols added in v1.0.0

func (f *File) Symbols() ([]Symbol, error)

Symbols returns metadata for every symbol in the file. The metadata is read on the first call and cached; subsequent calls return the cached copy.

func (*File) UELs added in v1.0.0

func (f *File) UELs() ([]string, error)

UELs returns the unique elements (UELs) of the file, indexed by their 1-based UEL number. The table is read on the first call and cached.

func (*File) VariableRecords added in v1.0.0

func (f *File) VariableRecords(sym Symbol) iter.Seq2[VariableRecord, error]

VariableRecords streams the elements of the variable sym as VariableRecords.

The sequence is single-use, as with SetRecords. An alias sym is resolved to its target, which is streamed and type-checked. If the (resolved) symbol is not a variable, the sequence yields exactly one *TypeError that matches ErrWrongType via errors.Is.

type FileInfo

type FileInfo struct {
	// Version is the GDX file format version reported by the library.
	Version string
	// Producer is the application that wrote the file.
	Producer string
	// SymbolCount is the number of symbols in the file.
	SymbolCount int
	// UELCount is the number of unique elements in the file.
	UELCount int
	// FilePath is the path the file was opened from.
	FilePath string
	// LibraryPath is the path of the loaded shared library.
	LibraryPath string
}

FileInfo holds general metadata about an opened GDX file.

type ParameterRecord

type ParameterRecord struct {
	// Keys are the element names, one per parameter dimension.
	Keys []string
	// Value is the parameter value (the .l slot).
	Value Value
}

ParameterRecord is a single element of a parameter. Scalar parameters have empty Keys.

type SetRecord added in v1.0.0

type SetRecord struct {
	// Keys are the element names, one per set dimension.
	Keys []string
	// Text is the explanatory text of the element; it is empty when the
	// element carries no text.
	Text string
}

SetRecord is a single element of a set.

type SpecialValue added in v1.0.0

type SpecialValue int32

SpecialValue identifies a GAMS special value, i.e. a value that is not a regular number.

const (
	// SpecialNone means the value is a regular number.
	SpecialNone SpecialValue = iota
	// SpecialNA is the GAMS "NA" (not available) value.
	SpecialNA
	// SpecialUndef is the GAMS "UNDF" (undefined) value.
	SpecialUndef
	// SpecialEps is the GAMS "EPS" (small epsilon) value, stored as 0.
	SpecialEps
	// SpecialPosInf is the GAMS "+INF" (positive infinity) value.
	SpecialPosInf
	// SpecialNegInf is the GAMS "-INF" (negative infinity) value.
	SpecialNegInf
)

func (SpecialValue) String added in v1.0.0

func (s SpecialValue) String() string

String returns the GAMS name of the special value; SpecialNone renders as "none".

type Symbol added in v1.0.0

type Symbol struct {
	// Name is the symbol name as stored in the file.
	Name string
	// Nr is the 1-based symbol number.
	Nr int
	// Dim is the number of dimensions (0 for a scalar).
	Dim int
	// Type is the symbol type.
	Type SymbolType
	// RecordCount is the number of records (data elements).
	RecordCount int
	// Comment is the explanatory text for the symbol.
	Comment string
	// Domain holds the domain set name for each dimension when the file
	// carries domain information; it is empty otherwise.
	Domain []string
	// VarType is the variable domain type, meaningful for SymbolTypeVar.
	VarType VarType
	// EquType is the equation type, meaningful for SymbolTypeEqu.
	EquType EquType
}

Symbol describes a single symbol stored in a GDX file.

type SymbolType

type SymbolType int32

SymbolType identifies the GAMS symbol type of a GDX entry.

const (
	// SymbolTypeSet is a set.
	SymbolTypeSet SymbolType = 0
	// SymbolTypePar is a parameter.
	SymbolTypePar SymbolType = 1
	// SymbolTypeVar is a variable.
	SymbolTypeVar SymbolType = 2
	// SymbolTypeEqu is an equation.
	SymbolTypeEqu SymbolType = 3
	// SymbolTypeAlias is an alias.
	SymbolTypeAlias SymbolType = 4
)

func (SymbolType) String

func (t SymbolType) String() string

String returns the name of the symbol type.

type TypeError added in v1.0.0

type TypeError struct {
	// Expected is the symbol type the reader requires.
	Expected SymbolType
	// Actual is the type the symbol actually has.
	Actual SymbolType
	// Name is the name of the symbol that was passed to the reader.
	Name string
}

TypeError is returned when a record reader is called on a symbol whose (alias-resolved) type does not match the type the reader expects. It matches ErrWrongType via errors.Is.

func (*TypeError) Error added in v1.0.0

func (e *TypeError) Error() string

Error implements the error interface.

func (*TypeError) Unwrap added in v1.0.0

func (e *TypeError) Unwrap() error

Unwrap returns ErrWrongType.

type Value added in v1.0.0

type Value struct {
	// Number is the numeric representation of the value.
	Number float64
	// Special names the GAMS special value, or SpecialNone for a regular
	// number.
	Special SpecialValue
}

Value is a single value of a record. A Value is either a regular number (Special == SpecialNone) or a GAMS special value, identified by Special. For special values, Number carries a canonical Go representation: NaN for NA and UNDF, +Inf/-Inf for +INF/-INF, and 0 for EPS.

func (Value) Float64 added in v1.0.0

func (v Value) Float64() float64

Float64 returns the numeric representation of v.

func (Value) IsSpecial added in v1.0.0

func (v Value) IsSpecial() bool

IsSpecial reports whether v is a GAMS special value rather than a regular number.

type VarType

type VarType int32

VarType identifies the domain type of a GAMS variable, stored in the symbol's user-info field when the symbol is a variable.

const (
	// VarTypeBinary is a 0/1 (binary) variable.
	VarTypeBinary VarType = 1
	// VarTypeInteger is an integer variable.
	VarTypeInteger VarType = 2
	// VarTypePositive is a positive (>= 0) variable.
	VarTypePositive VarType = 3
	// VarTypeNegative is a negative (<= 0) variable.
	VarTypeNegative VarType = 4
	// VarTypeFree is a free variable.
	VarTypeFree VarType = 5
	// VarTypeSOS1 is an SOS1 variable.
	VarTypeSOS1 VarType = 6
	// VarTypeSOS2 is an SOS2 variable.
	VarTypeSOS2 VarType = 7
	// VarTypeSemiCont is a semi-continuous variable.
	VarTypeSemiCont VarType = 8
	// VarTypeSemiInt is a semi-integer variable.
	VarTypeSemiInt VarType = 9
)

func (VarType) String

func (v VarType) String() string

String returns the name of the variable type.

type VariableRecord

type VariableRecord struct {
	// Keys are the element names, one per variable dimension.
	Keys []string
	// Level is the .l value.
	Level Value
	// Marginal is the .m value.
	Marginal Value
	// Lower is the .lo (lower bound) value.
	Lower Value
	// Upper is the .up (upper bound) value.
	Upper Value
	// Scale is the .scale value.
	Scale Value
}

VariableRecord is a single element of a variable.

Directories

Path Synopsis
cmd
gdx-reader command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL