def modify_model_horizon(datafile, modelname, start):

    tempfile = '{}{:%m%d%Y%H%M%S}.xml'.format(datafile[:-4], dt.datetime.now())

    if not os.path.exists(datafile):
        raise Exception('"{}" does not exist'.format(datafile))

    # delete the modified file if it already exists
    if os.path.exists(tempfile):
        os.remove(tempfile)

    # copy the PLEXOS input file
    copyfile(datafile, tempfile)

    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection(tempfile)
    '''
    String[] GetChildMembers(
    	CollectionEnum nCollectionId,
    	String strParent
    	)
    '''
    getchildren = db.GetChildMembers[CollectionEnum, String]
    '''
    Boolean UpdateAttribute(
    	ClassEnum nClassId,
    	String strObjectName,
    	Int32 nAttributeEnum,
    	Double dNewValue <--- always a Double... need to convert DateTime to Double
                         <--- using the ToOADate() method of the DateTime class
    	)
    '''

    # aliases for UpdateAttribute and AddAttribute methods
    update = db.UpdateAttribute[ClassEnum, String, Int32, Double]
    add = db.AddAttribute[ClassEnum, String, Int32, Double]

    horizons = getchildren.__invoke__((CollectionEnum.ModelHorizon, modelname))
    for hor in horizons:
        update.__invoke__(
            (ClassEnum.Horizon, hor, int(HorizonAttributeEnum.DateFrom),
             DateTime(start.Year, 1, 1).ToOADate()))
        update.__invoke__(
            (ClassEnum.Horizon, hor, int(HorizonAttributeEnum.StepType), 4))
        update.__invoke__(
            (ClassEnum.Horizon, hor, int(HorizonAttributeEnum.ChronoDateFrom),
             start.ToOADate()))

    # save the data set
    db.Close()

    # return the path of the newly created plexos input file
    return tempfile
Exemple #2
0
def plexos_launch(plexos_db, project_name):
    # launch the model on the local desktop
    # The \n argument is very important because it allows the PLEXOS
    # engine to terminate after completing the simulation
    sp.call([
        os.path.join(DatabaseCore().InstallPath, 'PLEXOS64.exe'), plexos_db,
        r'\n', r'\p', project_name
    ])
Exemple #3
0
def plexos_update(plexos_db,
                  fuel_objects,
                  base_scenarios,
                  gas_scenario,
                  project_name,
                  prices=None):

    # Connect to the PLEXOS input dataset
    cxn = DatabaseCore()
    cxn.DisplayAlerts = False
    cxn.Connection(plexos_db)
    cxn.DataSource = plexos_db

    # price updates
    if plexos_update_prices(cxn, fuel_objects, gas_scenario, prices):
        print('Updated PLEXOS gas prices')
    else:
        print('No update for PLEXOS gas prices')

    # update project and models
    if plexos_update_project(cxn, project_name, base_scenarios, gas_scenario):
        print('Updated PLEXOS project and models')
    else:
        print('No update to PLEXOS project and models')

    # close and save
    cxn.Close()
    enum_id = db.PropertyName2EnumId(parent_class_id.ToString(), \
                                    child_class_id.ToString(), \
                                    child_class_id.ToString()+'s',prop_name)
    params = (mem_id, enum_id, 1, prop_value, None, None, None, \
              None, None, None, 0, PeriodEnum.Interval)

    # c. A call to the alias
    add_prop.__invoke__(params)


# delete the modified file if it already exists
if os.path.exists('new.xml'):
    os.remove('new.xml')

# Create an object to store the input data
db = DatabaseCore()

# create a new database
'''
Boolean NewEmptyDatabase(
	String filePath,
	Boolean overwrite[ = False]
	)
'''
db.NewEmptyDatabase('./new.xml', True)
db.Connection('new.xml')

# Four generators
add_plexos_prop(db, ClassEnum.System, ClassEnum.Generator,
                CollectionEnum.SystemGenerators, 'System', 'A1', 'Units', 1,
                'A')
 def __init__(self, filename):
     self.db = DatabaseCore()
     self.db.Connection(filename)
class PlexosInputDatabase:

    db = DatabaseCore()

    def Connection(strfile):
        self.db.Connection(strfile)


    def GetModelsToExecute(strinputfilename,\
                            strmodellist,\
                            strprojectlist):
        return self.db.GetModelsToExecute(strinputfilename, strmodellist,
                                          strprojectlist)

    def Close():
        self.db.Close()


    def NewEmptyDatabase(filepath,\
                            overwrite = False):
        return self.db.NewEmptyDatabase(filepath, overwrite)

    def get_InstallPath():
        return self.db.get_InstallPath()


    def GetData(tablename,\
                            strfields):
        return self.db.GetData(tablename, strfields)

    def ObjectId2Name(objectid):
        return self.db.ObjectId2Name(objectid)


    def ObjectName2Id(classid,\
                            name):
        return self.db.ObjectName2Id(classid, name)

    def GetObjects(nclassid):
        return self.db.GetObjects(nclassid)

    def GetInputDataSet():
        return self.db.GetInputDataSet()


    def AddObject(strname,\
                            nclassid,\
                            baddsystemmembership,\
                            strcategory = None,\
                            strdescription = None):
        return self.db.AddObject(strname, nclassid, baddsystemmembership,
                                 strcategory, strdescription)


    def RemoveObject(strname,\
                            nclassid):
        return self.db.RemoveObject(strname, nclassid)


    def RenameObject(stroldname,\
                            strnewname,\
                            nclassid):
        return self.db.RenameObject(stroldname, strnewname, nclassid)


    def UpdateObjectDescription(nclassid,\
                            strobjectname,\
                            strnewdescription):
        return self.db.UpdateObjectDescription(nclassid, strobjectname,
                                               strnewdescription)


    def GetObjectsInCategory(nclassid,\
                            strcategory):
        return self.db.GetObjectsInCategory(nclassid, strcategory)


    def AddCategory(nclassid,\
                            strcategory):
        return self.db.AddCategory(nclassid, strcategory)


    def RemoveCategory(nclassid,\
                            strcategory,\
                            bremoveobjects = True):
        return self.db.RemoveCategory(nclassid, strcategory, bremoveobjects)

    def GetCategories(nclassid):
        return self.db.GetCategories(nclassid)


    def CategoryExists(nclassid,\
                            strcategory):
        return self.db.CategoryExists(nclassid, strcategory)


    def CategorizeObject(nclassid,\
                            strobject,\
                            strcategory):
        return self.db.CategorizeObject(nclassid, strobject, strcategory)


    def CopyObject(strname,\
                            strnewname,\
                            nclassid):
        return self.db.CopyObject(strname, strnewname, nclassid)

    def GetMemberships(ncollectionid):
        return self.db.GetMemberships(ncollectionid)


    def AddMembership(ncollectionid,\
                            strparent,\
                            strchild):
        return self.db.AddMembership(ncollectionid, strparent, strchild)


    def RemoveMembership(ncollectionid,\
                            strparent,\
                            strchild):
        return self.db.RemoveMembership(ncollectionid, strparent, strchild)


    def GetMembershipID(ncollectionid,\
                            strparent,\
                            strchild):
        return self.db.GetMembershipID(ncollectionid, strparent, strchild)


    def GetChildMembers(ncollectionid,\
                            strparent):
        return self.db.GetChildMembers(ncollectionid, strparent)


    def GetParentMembers(ncollectionid,\
                            strchild):
        return self.db.GetParentMembers(ncollectionid, strchild)


    def AddAttribute(nclassid,\
                            strobjectname,\
                            nattributeenum,\
                            dvalue):
        return self.db.AddAttribute(nclassid, strobjectname, nattributeenum,
                                    dvalue)


    def RemoveAttribute(nclassid,\
                            strobjectname,\
                            nattributeenum):
        return self.db.RemoveAttribute(nclassid, strobjectname, nattributeenum)


    def UpdateAttribute(nclassid,\
                            strobjectname,\
                            nattributeenum,\
                            dnewvalue):
        return self.db.UpdateAttribute(nclassid, strobjectname, nattributeenum,
                                       dnewvalue)


    def SetAttributeValue(nclassid,\
                            strobjectname,\
                            nattributeenum,\
                            dvalue):
        return self.db.SetAttributeValue(nclassid, strobjectname,
                                         nattributeenum, dvalue)


    def GetAttributeValue(nclassid,\
                            strobjectname,\
                            nattributeenum,\
                            dvalue):
        return self.db.GetAttributeValue(nclassid, strobjectname,
                                         nattributeenum, dvalue)


    def AddProperty(membershipid,\
                            enumid,\
                            bandid,\
                            value,\
                            datefrom,\
                            dateto,\
                            variable,\
                            datafile,\
                            pattern,\
                            scenario,\
                            action,\
                            periodtypeid):
        return self.db.AddProperty(membershipid, enumid, bandid, value,
                                   datefrom, dateto, variable, datafile,
                                   pattern, scenario, action, periodtypeid)


    def RemoveProperty(membershipid,\
                            enumid,\
                            bandid,\
                            datefrom,\
                            dateto,\
                            variable,\
                            datafile,\
                            pattern,\
                            scenario,\
                            action,\
                            periodtypeid):
        return self.db.RemoveProperty(membershipid, enumid, bandid, datefrom,
                                      dateto, variable, datafile, pattern,
                                      scenario, action, periodtypeid)


    def GetPropertyValue(membershipid,\
                            enumid,\
                            bandid,\
                            value,\
                            datefrom,\
                            dateto,\
                            variable,\
                            datafile,\
                            pattern,\
                            scenario,\
                            action,\
                            periodtypeid):
        return self.db.GetPropertyValue(membershipid, enumid, bandid, value,
                                        datefrom, dateto, variable, datafile,
                                        pattern, scenario, action,
                                        periodtypeid)


    def PropertyName2EnumId(strparentclassname,\
                            strchildclassname,\
                            strcollectionname,\
                            strpropertyname):
        return self.db.PropertyName2EnumId(strparentclassname,
                                           strchildclassname,
                                           strcollectionname, strpropertyname)


    def AddReportProperty(strreportname,\
                            nreportpropertyid,\
                            nphaseid,\
                            reportperiod,\
                            reportsummary,\
                            reportstatistics,\
                            reportsamples):
        self.db.AddReportProperty(strreportname, nreportpropertyid, nphaseid,
                                  reportperiod, reportsummary,
                                  reportstatistics, reportsamples)


    def ReportPropertyName2EnumId(strparentclassname,\
                            strchildclassname,\
                            strcollectionname,\
                            strpropertyname):
        return self.db.ReportPropertyName2EnumId(strparentclassname,
                                                 strchildclassname,
                                                 strcollectionname,
                                                 strpropertyname)


    def ReportPropertyName2PropertyId(strparentclassname,\
                            strchildclassname,\
                            strcollectionname,\
                            strpropertyname):
        return self.db.ReportPropertyName2PropertyId(strparentclassname,
                                                     strchildclassname,
                                                     strcollectionname,
                                                     strpropertyname)

    def GetEnabledProperties():
        return self.db.GetEnabledProperties()


    def GetPropertiesTable(collectionid,\
                            parentnamelist = None,\
                            childnamelist = None,\
                            timeslicelist = None,\
                            scenariolist = None,\
                            categorylist = None):
        return self.db.GetPropertiesTable(collectionid, parentnamelist,
                                          childnamelist, timeslicelist,
                                          scenariolist, categorylist)


    def AddAssembly(strfilepath,\
                            strnamespace):
        return self.db.AddAssembly(strfilepath, strnamespace)


    def RemoveAssembly(strfilepath,\
                            strnamespace):
        return self.db.RemoveAssembly(strfilepath, strnamespace)

    def GetAssemblies():
        return self.db.GetAssemblies()


    def SetAssemblyEnabled(strfilepath,\
                            strnamespace,\
                            benabled):
        return self.db.SetAssemblyEnabled(strfilepath, strnamespace, benabled)

    def get_DisplayAlerts():
        return self.db.get_DisplayAlerts()

    def set_DisplayAlerts(autopropertyvalue):
        self.db.set_DisplayAlerts(autopropertyvalue)

    def ToString():
        return self.db.ToString()

    def Equals(obj):
        return self.db.Equals(obj)

    def GetHashCode():
        return self.db.GetHashCode()

    def GetType():
        return self.db.GetType()

    def __init__(self, filename):
        self.db = DatabaseCore()
        self.db.Connection(filename)
# .NET related imports
from PLEXOS7_NET.Core import DatabaseCore
from EEUTILITY.Enums import *
from System import *

if os.path.exists('rts_PLEXOS.xml'):

    # delete the modified file if it already exists
    if os.path.exists('rts4.xml'):
        os.remove('rts4.xml')

    # copy the PLEXOS input file
    copyfile('rts_PLEXOS.xml', 'rts4.xml')

    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection('rts4.xml')

    # Add a category of scenarios if needed
    '''
    Boolean CategoryExists(
    	ClassEnum nClassId,
    	String strCategory
    	)
    Int32 AddCategory(
    	ClassEnum nClassId,
    	String strCategory
    	)
    '''
    if not db.CategoryExists(ClassEnum.Scenario, 'Added by API'):
        db.AddCategory(ClassEnum.Scenario, 'Added by API')
# Python .NET interface
from dotnet.seamless import add_assemblies, load_assembly#, build_assembly

# load PLEXOS assemblies
plexos_path = 'C:/Program Files (x86)/Energy Exemplar/PLEXOS 7.4/'
add_assemblies(plexos_path)
load_assembly('PLEXOS7_NET.Core')
load_assembly('EEUTILITY')

# .NET related imports
from PLEXOS7_NET.Core import DatabaseCore
from EEUTILITY.Enums import *

# Create an object to store the input data
db = DatabaseCore()
'''
Void Connection(
	String strFile
	)
'''
db.Connection('rts_PLEXOS.xml')

output_file = open('rts_PLEXOS.txt','w')

# list the generators
output_file.write('List of generators\n')
'''
String[] GetObjects(
	ClassEnum nClassId
	)
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 24 10:59:45 2018

@author: Steven.Broad
"""

import end_to_end_api

# .NET related imports
from PLEXOS7_NET.Core import DatabaseCore
from EEUTILITY.Enums import *
from System import *

db = DatabaseCore()
db.Connection('test2.xml')
res = db.GetPropertiesTable(CollectionEnum.SystemRegions, 'System', 'B')
while not res.EOF:
    for fld in res.Fields:
        print '"{}" = {}'.format(fld.Name, fld.Value)
    res.MoveNext()
    
def create_datafile_object(plexosfile, datafilename, datafilepath, copyfileto=''):
    if not os.path.exists(plexosfile):
        raise Exception('"{}" does not exist'.format(plexosfile))
        
    if not copyfileto == '':
        if os.path.exists(copyfileto):
            os.remove(copyfileto)
        copyfile(plexosfile, copyfileto)
        plexosfile = copyfileto
        
    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection(plexosfile)

    # Add a scenario
    '''
    Int32 AddObject(
    	String strName,
    	ClassEnum nClassId,
    	Boolean bAddSystemMembership,
    	String strCategory[ = None],
    	String strDescription[ = None]
    	)
    '''
    db.AddObject(datafilename, ClassEnum.DataFile, True)

    # Create data and tag it with the scenario
    '''
    Int32 AddProperty(
    	Int32 MembershipId,
    	Int32 EnumId,
    	Int32 BandId,
    	Double Value,
    	Object DateFrom,
    	Object DateTo,
    	Object Variable,
    	Object DataFile,
    	Object Pattern,
    	Object Scenario,
    	Object Action,
    	PeriodEnum PeriodTypeId
    	)
    '''
    # alias
    add_prop = db.AddProperty[Int32,Int32,Int32,Double,Object,Object, \
                              Object,Object,Object,Object,Object,PeriodEnum]
    
    # parameters
    mem_id = db.GetMembershipID(CollectionEnum.SystemDataFiles, 'System', datafilename)
    enum_id = int(SystemDataFilesEnum.Filename) 
    
    # we'll add three property rows... monthly gas prices for 3 months
    params = [(mem_id, enum_id, 1, 0, None, None, None, datafilepath, None, None, None, PeriodEnum.Interval),]
    
    # invoke
    for p in params:
        add_prop.__invoke__(p)
    
    # Add the scenario to a model
    '''
    Int32 AddMembership(
    	CollectionEnum nCollectionId,
    	String strParent,
    	String strChild
    	)
    db.AddMembership(CollectionEnum.ModelScenarios, 'Q1 DA', scenario)
    '''
    
    # save the data set
    db.Close()
    
    # pass the plexos file path (.xml) whether copied or not
    return plexosfile
def attach_datafile_to_object(plexosfile, datafilename, collectionenum, propertyenum, objectname, parentname = 'System'):
    if not os.path.exists(plexosfile):
        raise Exception('"{}" does not exist'.format(plexosfile))
        
    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection(plexosfile)

    '''
    Recordset GetPropertiesTable(
    	CollectionEnum CollectionId,
    	String ParentNameList[ = None],
    	String ChildNameList[ = None],
    	String TimesliceList[ = None],
    	String ScenarioList[ = None],
    	String CategoryList[ = None]
    	)
    '''
    res = db.GetPropertiesTable(collectionenum, parentname, objectname)
    
    '''
    Int32 RemoveProperty(
	Int32 MembershipId,
	Int32 EnumId,
	Int32 BandId,
	Object DateFrom,
	Object DateTo,
	Object Variable,
	Object DataFile,
	Object Pattern,
	Object Scenario,
	Object Action,
	PeriodEnum PeriodTypeId
	)
    '''
    mem_id = db.GetMembershipID(collectionenum, parentname, objectname)
    enum_id = int(propertyenum) 

    remove_prop = db.RemoveProperty[Int32, Int32, Int32, Object, Object, Object, Object, \
                                    Object, Object, Object, PeriodEnum]
    while not res.EOF:
        fields = dict([(res.Fields[i].Name.replace('_x0020_', ''), res.Fields[i].Value) for i in range(res.Fields.Count)])
        if fields['Property'] == str(propertyenum):
            remove_prop.__invoke__((mem_id, enum_id, \
                                   1 if 'Band' not in fields else int(fields['Band']), \
                                    None if 'DateFrom' not in fields else fields['DateFrom'], \
                                    None if 'DateTo' not in fields else fields['DateTo'], \
                                    None if 'Variable' not in fields else fields['Variable'], \
                                    None if 'DataFile' not in fields else fields['DataFile'], \
                                    None if 'Pattern' not in fields else fields['Pattern'], \
                                    None if 'Scenario' not in fields else fields['Scenario'], \
                                   '=' if 'Action' not in fields else fields['Action'], \
                                   PeriodEnum.Interval))
        print fields
        
        res.MoveNext()
    
    
    
    # Create data and tag it with the scenario
    '''
    Int32 AddProperty(
    	Int32 MembershipId,
    	Int32 EnumId,
    	Int32 BandId,
    	Double Value,
    	Object DateFrom,
    	Object DateTo,
    	Object Variable,
    	Object DataFile,
    	Object Pattern,
    	Object Scenario,
    	Object Action,
    	PeriodEnum PeriodTypeId
    	)
    '''
    # alias
    add_prop = db.AddProperty[Int32,Int32,Int32,Double,Object,Object, \
                              Object,Object,Object,Object,Object,PeriodEnum]
    
    # parameters
    mem_id = db.GetMembershipID(collectionenum, parentname, objectname)
    enum_id = int(propertyenum) 
    
    # we'll add three property rows... monthly gas prices for 3 months
    params = [(mem_id, enum_id, 1, 0, None, None, None, datafilename, None, None, None, PeriodEnum.Interval),]
    
    # invoke
    for p in params:
        add_prop.__invoke__(p)
    
    # Add the scenario to a model
    '''
    Int32 AddMembership(
    	CollectionEnum nCollectionId,
    	String strParent,
    	String strChild
    	)
    db.AddMembership(CollectionEnum.ModelScenarios, 'Q1 DA', scenario)
    '''
    
    # save the data set
    db.Close()
# .NET related imports
from PLEXOS7_NET.Core import DatabaseCore
from EEUTILITY.Enums import *

if os.path.exists('rts_PLEXOS.xml'):

    # delete the modified file if it already exists
    if os.path.exists('rts2.xml'):
        os.remove('rts2.xml')

    # copy the PLEXOS input file
    copyfile('rts_PLEXOS.xml', 'rts2.xml')

    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection('rts2.xml')

    # Add a category
    '''
    Int32 AddCategory(
    	ClassEnum nClassId,
    	String strCategory
    	)
    '''
    db.AddCategory(ClassEnum.Generator, 'API')

    # Add an object (and the System Membership)
    '''
    Int32 AddObject(
    	String strName,
# .NET related imports
from PLEXOS7_NET.Core import DatabaseCore
from EEUTILITY.Enums import *
from System import *

if os.path.exists('rts_PLEXOS.xml'):

    # delete the modified file if it already exists
    if os.path.exists('rts3.xml'):
        os.remove('rts3.xml')

    # copy the PLEXOS input file
    copyfile('rts_PLEXOS.xml', 'rts3.xml')
    
    # Create an object to store the input data
    db = DatabaseCore()
    db.Connection('rts3.xml')

    '''
    Int32 CopyObject(
    	String strName,
    	String strNewName,
    	ClassEnum nClassId
    	)
    '''
    db.CopyObject('Q1 DA','APIModel',ClassEnum.Model)
    db.CopyObject('Q1 DA','APIHorizon',ClassEnum.Horizon)
    
    '''
    Int32 RemoveMembership(
    	CollectionEnum nCollectionId,