Skip to content

Commit

Permalink
do some cleanup of the codacy identified issues (#731)
Browse files Browse the repository at this point in the history
* do some cleanup of the codacy identified issues

* fix a few more codacy issues with spacing

* more clean up of spaces in the py examples

* change parse_return to parse_output

* more updates for examples and codacy cleanup

* more warnings fixes from codacy

* a few more warnings that just built on cleaning up other ones

* final java warning cleanup

* Apply suggestions from code review

fix spelling on some variables

Co-Authored-By: Ryan Mast <nightlark@users.noreply.github.com>

* remove unused string variables

* Apply suggestions from code review

Co-Authored-By: Ryan Mast <nightlark@users.noreply.github.com>
  • Loading branch information
phlptp and nightlark committed Jul 15, 2019
1 parent 0538db7 commit 149ca28
Show file tree
Hide file tree
Showing 26 changed files with 318 additions and 376 deletions.
1 change: 0 additions & 1 deletion .codacy.yml
Expand Up @@ -17,6 +17,5 @@ exclude_paths:
- interfaces/**/*
- scripts/**/*
- scripts/*
- src/helics/common/cppzmq/*
- tests/csharp/*

1 change: 0 additions & 1 deletion docs/conf.py
Expand Up @@ -59,7 +59,6 @@ def ext_candidates(fpath):
return None

import subprocess
import os

read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'

Expand Down
4 changes: 2 additions & 2 deletions examples/comboFederates1/comboFed.cpp
Expand Up @@ -37,12 +37,12 @@ int main (int argc, char *argv[])
auto ret = app.helics_parse (argc, argv);

helics::FederateInfo fi;
if (ret == helics::helicsCLI11App::parse_return::help_return)
if (ret == helics::helicsCLI11App::parse_output::help_call)
{
fi.loadInfoFromArgs ("--help");
return 0;
}
else if (ret != helics::helicsCLI11App::parse_return::ok)
else if (ret != helics::helicsCLI11App::parse_output::ok)
{
return -1;
}
Expand Down
Expand Up @@ -5,20 +5,14 @@
@author: monish.mukherjee
"""
import scipy.io as spio
from pypower.api import case118, ppoption, runpf, runopf
from pypower.api import case118, ppoption, runpf
import math
import numpy
import copy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime, timedelta
import time
import helics as h
import random
import logging
import json
import sys
import os

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
Expand Down Expand Up @@ -77,32 +71,30 @@ def destroy_federate(fed):
#fed = create_federate()

################################# Registering federate from json ########################################

fed = h.helicsCreateValueFederateFromConfig('Transmission_json.json')
status = h.helicsFederateRegisterInterfaces(fed, 'Transmission_json.json')
federate_name = h.helicsFederateGetName(fed)[-1]
print(" Federate {} has been registered".format(federate_name))
pubkeys_count = h.helicsFederateGetPublicationCount(fed)
subkeys_count = h.helicsFederateGetInputCount(fed)
print(subkeys_count)
###################### Reference to Publications and Subscription form index #############################
###################### Reference to Publications and Subscription form index #############################
pubid = {}
subid = {}
for i in range(0,pubkeys_count):
pubid["m{}".format(i)] = h.helicsFederateGetPublicationByIndex(fed, i)
type = h.helicsPublicationGetType(pubid["m{}".format(i)])
print(type)
pubtype = h.helicsPublicationGetType(pubid["m{}".format(i)])
print(pubtype)
for i in range(0,subkeys_count):
subid["m{}".format(i)] = h.helicsFederateGetInputByIndex(fed, i)
status = h.helicsInputSetDefaultComplex(subid["m{}".format(i)], 0, 0)
sub_key = h.helicsSubscriptionGetKey(subid["m{}".format(i)])
print( 'Registered Subscription ---> {}'.format(sub_key))
###################### Entereing Execution Mode ##########################################################

###################### Entereing Execution Mode ##########################################################
status = h.helicsFederateEnterInitializingMode(fed)
status = h.helicsFederateEnterExecutingMode(fed)



#Pypower Processing (inputs)
hours = 24
Expand All @@ -111,25 +103,25 @@ def destroy_federate(fed):
pf_interval = 5*60 # in seconds (minimim_resolution)
acopf_interval = 15*60 # in seconds (minimim_resolution)
random.seed(0)

peak_demand = []
ppc = []
case_format = case118()
peak_demand = case_format['bus'][:,2][:].copy()
ppc = case_format.copy()
###################### creating fixed load profiles for each bus based on PF interval #############################

###################### creating fixed load profiles for each bus based on PF interval #############################

# load profiles (inputs)
profiles = spio.loadmat('normalized_load_data_1min_ORIGINAL.mat',squeeze_me=True,struct_as_record=False)
load_profiles_1min=profiles['my_data']
resolution_load=numpy.floor(total_inteval/pf_interval)
points = numpy.floor(numpy.linspace(0, len(load_profiles_1min)-1, resolution_load+1))
time_pf = numpy.linspace(0, total_inteval, resolution_load+1)
load_profiles = load_profiles_1min[points.astype(int),:]

################### Creating a fixed profile for buses ##################

bus_profiles_index=[]
profile_number=0
for i in range(len(ppc['bus'])):
Expand All @@ -139,65 +131,65 @@ def destroy_federate(fed):
else:
profile_number=profile_number+1
################### Asserting Profiles to buses ############################

#bus_profiles_index = numpy.random.random_integers(0,load_profiles.shape[1]-1,len(ppc['bus']))
bus_profiles = load_profiles[:,bus_profiles_index]
time_opf=numpy.linspace(0, total_inteval, numpy.floor(total_inteval/acopf_interval)+1)
########################### Cosimulation Bus and Load Amplification Factor #########################################

########################### Cosimulation Bus and Load Amplification Factor #########################################

#Co-sim Bus (inputs)
Cosim_bus_number = 118
cosim_bus= Cosim_bus_number - 1 ## Do not chage this line
cosim_bus= Cosim_bus_number - 1 ## Do not chage this line
load_amplification_factor = 15

#power_flow
fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)
votlage_plot=[]
voltage_plot=[]
x=0
k=0
votlage_cosim_bus = (ppc['bus'][cosim_bus,7]*ppc['bus'][cosim_bus,9])*1.043
######################################### Starting Co-simulation ####################################################
voltage_cosim_bus = (ppc['bus'][cosim_bus,7]*ppc['bus'][cosim_bus,9])*1.043

######################################### Starting Co-simulation ####################################################

for t in range(0, total_inteval, pf_interval):
############################ Publishing Voltage to GridLAB-D #######################################################
voltage_gld = complex(votlage_cosim_bus*1000)

############################ Publishing Voltage to GridLAB-D #######################################################

voltage_gld = complex(voltage_cosim_bus*1000)
logger.info("Voltage value = {} kV".format(abs(voltage_gld)/1000))
for i in range(0,pubkeys_count):
pub = pubid["m{}".format(i)]
status = h.helicsPublicationPublishComplex(pub, voltage_gld.real, voltage_gld.imag)
# status = h.helicsEndpointSendEventRaw(epid, "fixed_price", 10, t)

while grantedtime < t:
grantedtime = h.helicsFederateRequestTime (fed, t)
time.sleep(0.1)
############################# Subscribing to Feeder Load from to GridLAB-D ##############################################

############################# Subscribing to Feeder Load from to GridLAB-D ##############################################

for i in range(0,subkeys_count):
sub = subid["m{}".format(i)]
sub = subid["m{}".format(i)]
rload, iload = h.helicsInputGetComplex(sub)
logger.info("Python Federate grantedtime = {}".format(grantedtime))
logger.info("Load value = {} kW".format(complex(rload, iload)/1000))
#print(votlage_plot,real_demand)
#print(voltage_plot,real_demand)

actual_demand=peak_demand*bus_profiles[x,:]
ppc['bus'][:,2]=actual_demand
ppc['bus'][:,3]=actual_demand*math.tan(math.acos(.85))
ppc['bus'][cosim_bus,2]=rload*load_amplification_factor/1000000
ppc['bus'][cosim_bus,3]=iload*load_amplification_factor/1000000
ppopt = ppoption(PF_ALG=1)

print('PF TIme is {} and ACOPF time is {}'.format(time_pf[x], time_opf[k]))
############################ Running OPF For optimal power flow intervals ##############################
if (time_pf[x] == time_opf[k]):

############################ Running OPF For optimal power flow intervals ##############################

if (time_pf[x] == time_opf[k]):
results_opf = runopf(ppc, ppopt)
if (results_opf['success']):
ppc['bus'] = results_opf['bus']
Expand All @@ -208,9 +200,9 @@ def destroy_federate(fed):
LMP_solved = numpy.vstack((LMP_solved,results_opf['bus'][:,13]))
opf_time = time_opf[0:k+1]/3600
k=k+1
################################ Running PF For optimal power flow intervals ##############################

################################ Running PF For optimal power flow intervals ##############################

solved_pf = runpf(ppc, ppopt)
results_pf = solved_pf[0]
ppc['bus'] = results_pf['bus']
Expand All @@ -220,35 +212,35 @@ def destroy_federate(fed):
if (x == 0):
voltages = results_pf['bus'][:,7]
real_demand = results_pf['bus'][:,2]
distribuiton_load = [rload/1000000]
distribution_load = [rload/1000000]
else:
voltages = numpy.vstack((voltages,results_pf['bus'][:,7]))
real_demand = numpy.vstack((real_demand,results_pf['bus'][:,2]))
distribuiton_load.append(rload/1000000)
distribution_load.append(rload/1000000)
pf_time = time_pf[0:x+1]/3600
votlage_cosim_bus=results_pf['bus'][cosim_bus,7]*results_pf['bus'][cosim_bus,9]
votlage_plot.append(votlage_cosim_bus)
######################### Plotting the Voltages and Load of the Co-SIM bus ##############################################

voltage_cosim_bus=results_pf['bus'][cosim_bus,7]*results_pf['bus'][cosim_bus,9]
voltage_plot.append(voltage_cosim_bus)

######################### Plotting the Voltages and Load of the Co-SIM bus ##############################################

if (x > 0) :
ax1.clear()
ax1.plot(pf_time,votlage_plot,'r--')
ax1.plot(pf_time,voltage_plot,'r--')
ax1.set_xlim([0,25])
ax1.set_ylabel('Voltage [in kV]')
ax1.set_xlabel('Time [in hours]')
ax2.clear()
ax2.plot(pf_time,real_demand[:,cosim_bus],'k')
ax2.set_xlim([0, 25])
ax2.set_xlim([0, 25])
ax2.set_ylabel('Load from distribution [in MW]')
ax2.set_xlabel('Time [in hours]')
plt.show(block=False)
plt.pause(0.1)
x=x+1

########################## Creating headers and Printing results to CSVs #####################################

head = str('Time(in Hours)')
for i in range(voltages.shape[1]):
head = head+','+('Bus'+str(i+1))
Expand All @@ -264,6 +256,3 @@ def destroy_federate(fed):
logger.info("Destroying federate")
destroy_federate(fed)
logger.info("Done!")



0 comments on commit 149ca28

Please sign in to comment.