Example #1
0
void voltdump::dump(TIMESTAMP t){
	char namestr[64];
	char timestr[64];
	FINDLIST *nodes = NULL;
	OBJECT *obj = NULL;
	FILE *outfile = NULL;
	node *pnode;
//	CLASS *nodeclass = NULL;
//	PROPERTY *vA, *vB, *vC;

	if(group[0] == 0){
		nodes = gl_find_objects(FL_NEW,FT_MODULE,SAME,"powerflow",FT_END);
	} else {
		nodes = gl_find_objects(FL_NEW,FT_MODULE,SAME,"powerflow",AND,FT_GROUPID,SAME,group.get_string(),FT_END);
	}

	if(nodes == NULL){
		gl_warning("no nodes were found to dump");
		return;
	}

	outfile = fopen(filename, "w");
	if(outfile == NULL){
		gl_error("voltdump unable to open %s for output", filename.get_string());
		return;
	}

	//nodeclass = node::oclass;
	//vA=gl_find_property(nodeclass, "

	int node_count = 0;
	while (obj=gl_find_next(nodes,obj)){
		if(gl_object_isa(obj, "node", "powerflow")){
			node_count += 1;
		}
	}
	/* print column names */
	gl_printtime(t, timestr, 64);
	fprintf(outfile,"# %s run at %s on %i nodes\n", filename.get_string(), timestr, node_count);
	if (mode == VDM_RECT)
		fprintf(outfile,"node_name,voltA_real,voltA_imag,voltB_real,voltB_imag,voltC_real,voltC_imag\n");
	else if (mode == VDM_POLAR)
		fprintf(outfile,"node_name,voltA_mag,voltA_angle,voltB_mag,voltB_angle,voltC_mag,voltC_angle\n");
	
	obj = 0;
	while (obj=gl_find_next(nodes,obj)){
		if(gl_object_isa(obj, "node", "powerflow")){
			pnode = OBJECTDATA(obj,node);
			if(obj->name == NULL){
				sprintf(namestr, "%s:%i", obj->oclass->name, obj->id);
			}
			if(mode == VDM_RECT){
				fprintf(outfile,"%s,%f,%f,%f,%f,%f,%f\n",(obj->name ? obj->name : namestr),pnode->voltage[0].Re(),pnode->voltage[0].Im(),pnode->voltage[1].Re(),pnode->voltage[1].Im(),pnode->voltage[2].Re(),pnode->voltage[2].Im());
			} else if(mode == VDM_POLAR){
				fprintf(outfile,"%s,%f,%f,%f,%f,%f,%f\n",(obj->name ? obj->name : namestr),pnode->voltage[0].Mag(),pnode->voltage[0].Arg(),pnode->voltage[1].Mag(),pnode->voltage[1].Arg(),pnode->voltage[2].Mag(),pnode->voltage[2].Arg());
			}
		}
	}
	fclose(outfile);
}
/** Initialize water heater model properties - randomized defaults for all published variables
 **/
int virtual_battery::init(OBJECT *parent)
{
	
	parent2=parent;
	first_time=0;
	first_time2=0;
	actual=0;
	temp_capacity=0;
	if(parent != NULL){
		if((parent->flags & OF_INIT) != OF_INIT){
			char objname[256];
			gl_verbose("virtual_battery::init(): deferring initialization on %s", gl_name(parent, objname, 255));
			return 2; // defer
		}
	}
	OBJECT *hdr = OBJECTHDR(this);
	hdr->flags |= OF_SKIPSAFE;

		///////////////////////////////find auction object/////////////////////////////////////
				 static FINDLIST *xt1=NULL;
				 xt1=gl_find_objects(FL_NEW,FT_CLASS,SAME,"auction",FT_END);
				 OBJECT *firstt1= gl_find_next(xt1,NULL);
				 OBJECT *it1;
				 for(it1=firstt1;it1!=NULL;it1=it1->next)
				 {
				
					 if(gl_object_isa(it1,"auction"))
				     {

						
						 auction_object=it1;
						
					 }

				 }
       /////////////////////////////////////////////////////////////////////////////////////////
       /////////////////////////////find climate object ///////////////////////////////////////

		FINDLIST *climates = NULL; 
		OBJECT *obj;
		climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
		obj = gl_find_next(climates,NULL);

		if (gl_object_isa(obj,"climate"))
		{
			climate_object=obj;
		}





      ///////////////////////////////////////////////////////////////////////////////////////	
	// check the load configuration before initializing the parent class
	
	return 1;
	
}
Example #3
0
/** Checks for climate object and maps the climate variables to the house object variables.  
Currently Tout, RHout and solar flux data from TMY files are used.  If no climate object is linked,
then Tout will be set to 74 degF, RHout is set to 75% and solar flux will be set to zero for all orientations.
**/
int house::init_climate()
{
	OBJECT *hdr = OBJECTHDR(this);

	// link to climate data
	static FINDLIST *climates = NULL;
	int not_found = 0;
	if (climates==NULL && not_found==0) 
	{
		climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
		if (climates==NULL)
		{
			not_found = 1;
			gl_warning("house: no climate data found, using static data");

			//default to mock data
			static double tout=74.0, rhout=0.75, solar[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
			pTout = &tout;
			pRhout = &rhout;
			pSolar = &solar[0];
		}
		else if (climates->hit_count>1)
		{
			gl_warning("house: %d climates found, using first one defined", climates->hit_count);
		}
	}
	if (climates!=NULL)
	{
		if (climates->hit_count==0)
		{
			//default to mock data
			static double tout=74.0, rhout=0.75, solar[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
			pTout = &tout;
			pRhout = &rhout;
			pSolar = &solar[0];
		}
		else //climate data was found
		{
			// force rank of object w.r.t climate
			OBJECT *obj = gl_find_next(climates,NULL);
			if (obj->rank<=hdr->rank)
				gl_set_dependent(obj,hdr);
			pTout = (double*)GETADDR(obj,gl_get_property(obj,"temperature"));
			pRhout = (double*)GETADDR(obj,gl_get_property(obj,"humidity"));
			pSolar = (double*)GETADDR(obj,gl_get_property(obj,"solar_flux"));
		}
	}
	return 1;
}
Example #4
0
EXPORT int check()
{
	/* check each link to make sure it has a node at either end */
	FINDLIST *list = gl_find_objects(FL_NEW,FT_MODULE,SAME,"powerflow",NULL);
	OBJECT *obj=NULL;
	int *nodemap,	/* nodemap marks where nodes are */
		*linkmap,	/* linkmap counts the number of links to/from a given node */
		*tomap;		/* counts the number of references to any given node */
	int errcount = 0;
	int objct = 0;
	int queuef = 0, queueb = 0, queuect = 0;
	int islandct = 0;
	int i, j;
	GLOBALVAR *gvroot = NULL;
	PFLIST anchor, *tlist = NULL;
	link **linklist = NULL,
		 **linkqueue = NULL;

	objct = gl_get_object_count();
	anchor.ptr = NULL;
	anchor.next = NULL;

	nodemap = (int *)malloc((size_t)(objct*sizeof(int)));
	linkmap = (int *)malloc((size_t)(objct*sizeof(int)));
	tomap = (int *)malloc((size_t)(objct*sizeof(int)));
	linkqueue = (link **)malloc((size_t)(objct*sizeof(link *)));
	linklist = (link **)malloc((size_t)(objct*sizeof(link *)));
	memset(nodemap, 0, objct*sizeof(int));
	memset(linkmap, 0, objct*sizeof(int));
	memset(tomap, 0, objct*sizeof(int));
	memset(linkqueue, 0, objct*sizeof(link *));
	memset(linklist, 0, objct*sizeof(link *));
	/* per-object checks */

	/* check from/to info on links */
	while (obj=gl_find_next(list,obj))
	{
		if (gl_object_isa(obj,"node"))
		{
			/* add to node map */
			nodemap[obj->id]+=1;
			/* if no parent, then add to anchor list */
			if(obj->parent == NULL){
				tlist = (PFLIST *)malloc(sizeof(PFLIST));
				tlist->ptr = obj;
				tlist->next = anchor.next;
				anchor.next = tlist;
				tlist = NULL;
			}
		}
		else if (gl_object_isa(obj,"link"))
		{
			link *pLink = OBJECTDATA(obj,link);
			OBJECT *from = pLink->from;
			OBJECT *to = pLink->to;
			node *tNode = OBJECTDATA(to, node);
			node *fNode = OBJECTDATA(from, node);
			/* count 'to' reference */
			tomap[to->id]++;
			/* check link connections */
			if (from==NULL){
				gl_error("link %s (%s:%d) from object is not specified", pLink->get_name(), pLink->oclass->name, pLink->get_id());
				++errcount;
			}
			else if (!gl_object_isa(from,"node")){
				gl_error("link %s (%s:%d) from object is not a node", pLink->get_name(), pLink->oclass->name, pLink->get_id());
				++errcount;
			} else { /* is a "from" and it isa(node) */
				linkmap[from->id]++; /* mark that this node has a link from it */
			}
			if (to==NULL){
				gl_error("link %s (%s:%d) to object is not specified", pLink->get_name(), pLink->oclass->name, pLink->get_id());
				++errcount;
			}
			else if (!gl_object_isa(to,"node")){
				gl_error("link %s (%s:%d) to object is not a node", pLink->get_name(), pLink->oclass->name, pLink->get_id());
				++errcount;
			} else { /* is a "to" and it isa(node) */
				linkmap[to->id]++; /* mark that this node has links to it */
			}
			/* add link to heap? */
			if((from != NULL) && (to != NULL) && (linkmap[from->id] > 0) && (linkmap[to->id] > 0)){
				linklist[queuect] = pLink;
				queuect++;
			}
			//	check phases
			/* this isn't cooperating with me.  -MH */
/*			if(tNode->get_phases(PHASE_A) == fNode->get_phases(PHASE_A)){
				gl_error("link:%i: to, from nodes have mismatched A phase (%i vs %i)", obj->id, tNode->get_phases(PHASE_A), fNode->get_phases(PHASE_A));
				++errcount;
			}
			if(tNode->get_phases(PHASE_B) == fNode->get_phases(PHASE_B)){
				gl_error("link:%i: to, from nodes have mismatched B phase (%i vs %i)", obj->id, tNode->get_phases(PHASE_B), fNode->get_phases(PHASE_B));
				++errcount;
			}
			if(tNode->get_phases(PHASE_C) == fNode->get_phases(PHASE_C)){
				gl_error("link:%i: to, from nodes have mismatched C phase (%i vs %i)", obj->id, tNode->get_phases(PHASE_C), fNode->get_phases(PHASE_C));
				++errcount;
			}
			if(tNode->get_phases(PHASE_D) == fNode->get_phases(PHASE_D)){
				gl_error("link:%i: to, from nodes have mismatched D phase (%i vs %i)", obj->id, tNode->get_phases(PHASE_D), fNode->get_phases(PHASE_D));
				++errcount;
			}
			if(tNode->get_phases(PHASE_N) == fNode->get_phases(PHASE_N)){
				gl_error("link:%i: to, from nodes have mismatched N phase (%i vs %i)", obj->id, tNode->get_phases(PHASE_N), fNode->get_phases(PHASE_N));
				++errcount;
			}*/
		}
	}

	for(i = 0; i < objct; ++i){ /* locate unlinked nodes */
		if(nodemap[i] != 0){
			if(linkmap[i] * nodemap[i] > 0){ /* there is a node at [i] and links to it*/
				;
			} else if(linkmap[i] == 1){ /* either a feeder or an endpoint */
				;
			} else { /* unattached node */
				gl_error("node:%i: node with no links to or from it", i);
				nodemap[i] *= -1; /* mark as unlinked */
				++errcount;
			}
		}
	}
	for(i = 0; i < objct; ++i){ /* mark by islands*/
		if(nodemap[i] > 0){ /* has linked node */
			linkmap[i] = i; /* island until proven otherwise */
		} else {
			linkmap[i] = -1; /* just making sure... */
		}
	}

	queueb = 0;
	for(i = 0; i < queuect; ++i){
		if(linklist[i] != NULL){ /* consume the next item */
			linkqueue[queueb] = linklist[i];
			linklist[i] = NULL;
			queueb++;
		}
		while(queuef < queueb){
			/* expand this island */
			linkmap[linkqueue[queuef]->to->id] = linkmap[linkqueue[queuef]->from->id];
			/* capture the adjacent nodes */
			for(j = 0; j < queuect; ++j){
				if(linklist[j] != NULL){
					if(linklist[j]->from->id == linkqueue[queuef]->to->id){
						linkqueue[queueb] = linklist[j];
						linklist[j] = NULL;
						++queueb;
					}
				}
			}
			++queuef;
		}
		/* we've consumed one island, grab another */
	}
	for(i = 0; i < objct; ++i){
		if(nodemap[i] != 0){
			gl_testmsg("node:%i on island %i", i, linkmap[i]);
			if(linkmap[i] == i){
				++islandct;
			}
		}
		if(tomap[i] > 1){
			FINDLIST *cow = gl_find_objects(FL_NEW,FT_ID,SAME,i,NULL);
			OBJECT *moo = gl_find_next(cow, NULL);
			char grass[64];
			gl_output("object #%i, \'%s\', has more than one link feeding to it (this will diverge)", i, gl_name(moo, grass, 64));
		}
	}
	gl_output("Found %i islands", islandct);
	tlist = anchor.next;
	while(tlist != NULL){
		PFLIST *tptr = tlist;
		tlist = tptr->next;
		free(tptr);
	}

	/*	An extra something to check link directionality,
	 *	if the root node has been defined on the command line.
	 *	-d3p988 */
	gvroot = gl_global_find("powerflow::rootnode");
	if(gvroot != NULL){
		PFLIST *front=NULL, *back=NULL, *del=NULL; /* node queue */
		OBJECT *_node = gl_get_object((char *)gvroot->prop->addr);
		OBJECT *_link = NULL;
		int *rankmap = (int *)malloc((size_t)(objct*sizeof(int)));
		int bct = 0;
		if(_node == NULL){
			gl_error("powerflow check(): Unable to do directionality check, root node name not found.");
		} else {
			gl_testmsg("Powerflow Check ~ Backward Links:");
		}
		for(int i = 0; i < objct; ++i){
			rankmap[i] = objct;
		}
		rankmap[_node->id] = 0;
		front = (PFLIST *)malloc(sizeof(PFLIST));
		front->next = NULL;
		front->ptr = _node;
		back = front;
		while(front != NULL){
			// find all links from the node
			for(OBJECT *now=gl_find_next(list, NULL); now != NULL; now = gl_find_next(list, now)){
				link *l;
				if(!gl_object_isa(now, "link"))
					continue;
				l = OBJECTDATA(now, link);
				if((l->from != front->ptr) && (l->to != front->ptr)){
					continue;
				} else if(rankmap[l->from->id]<objct && rankmap[l->to->id]<objct){
					continue;
				} else if(rankmap[l->from->id] < rankmap[l->to->id]){
					/* mark */
					rankmap[l->to->id] = rankmap[l->from->id]+1;
				} else if(rankmap[l->from->id] > rankmap[l->to->id]){
					/* swap & mark */
					OBJECT *t = l->from;
					gl_testmsg("reversed link: %s goes from %s to %s", now->name, l->from->name, l->to->name);
					l->from = l->to;
					l->to = t;
					rankmap[l->to->id] = rankmap[l->from->id]+1;;
				}
				// enqueue the "to" node
				back->next = (PFLIST *)malloc(sizeof(PFLIST));
				back->next->next = NULL;
				//back->next->ptr = l->to;
				back = back->next;
				back->ptr = l->to;
			}
			del = front;
			front = front->next;
			free(del);
		}
	}

	free(nodemap);
	free(linkmap);
	free(linklist);
	free(linkqueue);
	return 0;
}
int group_recorder::init(OBJECT *obj){
	OBJECT *gr_obj = 0;

	// check for group
	if(0 == group_def[0]){
		if(strict){
			gl_error("group_recorder::init(): no group defined");
			/* TROUBLESHOOT
				group_recorder must define a group in "group_def".
			 */
			return 0;
		} else {
			gl_warning("group_recorder::init(): no group defined");
			tape_status = TS_ERROR;
			return 1; // nothing more to do
		}
	}

	// check for filename
	if(0 == filename[0]){
		// if no filename, auto-generate based on ID
		if(strict){
			gl_error("group_recorder::init(): no filename defined in strict mode");
			return 0;
		} else {
			sprintf(filename, "%256s-%256i.csv", oclass->name, obj->id);
			gl_warning("group_recorder::init(): no filename defined, auto-generating '%s'", filename);
			/* TROUBLESHOOT
				group_recorder requires a filename.  If none is provided, a filename will be generated
				using a combination of the classname and the core-assigned ID number.
			*/
		}
	}

	// check valid write interval
	write_interval = (int64)(dInterval);
	if(-1 > write_interval){
		gl_error("group_recorder::init(): invalid write_interval of %i, must be -1 or greater", write_interval);
		/* TROUBLESHOOT
			The group_recorder interval must be -1, 0, or a positive number of seconds.
		*/
		return 0;
	}

	// all flush intervals are valid
	flush_interval = (int64)dFlush_interval;
	
	
	// build group
	//	* invariant?
	//	* non-empty set?
	items = gl_find_objects(FL_GROUP, group_def);
	if(0 == items){
		if(strict){
			gl_error("group_recorder::init(): unable to construct a set with group definition");
			/* TROUBLESHOOT
				An error occured while attempting to build and populate the find list with the specified group definition.
			 */
			return 0;
		} else {
			gl_warning("group_recorder::init(): unable to construct a set with group definition");
			tape_status = TS_ERROR;
			return 1; // nothing more to do
		}
	}
	if(1 > items->hit_count){
		if(strict){
			gl_error("group_recorder::init(): the defined group returned an empty set");
			/* TROUBLESHOOT
				Placeholder.
			 */
			return 0;
		} else {
			gl_warning("group_recorder::init(): the defined group returned an empty set");
			tape_status = TS_ERROR;
			return 1;
		}
	}
	
	// open file
	rec_file = fopen(filename, "w");
	if(0 == rec_file){
		if(strict){
			gl_error("group_recorder::init(): unable to open file '%s' for writing", filename);
			return 0;
		} else {
			gl_warning("group_recorder::init(): unable to open file '%s' for writing", filename);
			/* TROUBLESHOOT
				If the group_recorder cannot open the specified output file, it will 
			 */
			tape_status = TS_ERROR;
			return 1;
		}
	}

	// turn list into objlist, count items
	obj_count = 0;
	for(gr_obj = gl_find_next(items, 0); gr_obj != 0; gr_obj = gl_find_next(items, gr_obj) ){
		prop_ptr = gl_get_property(gr_obj, property_name);
		// might make this a 'strict-only' issue in the future
		if(prop_ptr == NULL){
			gl_error("group_recorder::init(): unable to find property '%s' in an object of type '%s'", property_name, gr_obj->oclass->name);
			/* TROUBLESHOOT
				An error occured while reading the specified property in one of the objects.
			 */
			return 0;
		}
		++obj_count;
		if(obj_list == 0){
			obj_list = new quickobjlist(gr_obj, prop_ptr);
		} else {
			obj_list->tack(gr_obj, prop_ptr);
		}
	}

	tape_status = TS_OPEN;
	if(0 == write_header()){
		gl_error("group_recorder::init(): an error occured when writing the file header");
		/* TROUBLESHOOT
			Unexpected IO error.
		 */
		tape_status = TS_ERROR;
		return 0;
	}
	

	return 1;
}
Example #6
0
/* Object initialization is called once after all object have been created */
int metrics::init(OBJECT *parent)
{
	OBJECT *hdr = OBJECTHDR(this);
	int index, indexa, indexb, returnval;
	char work_metrics[1025];
	char *startVal, *endVal, *workVal;
	char workbuffer[1025];
	char metricbuffer[257];
	FILE *FPVal;
	FINDLIST *CandidateObjs;
	OBJECT *temp_obj;
	bool *temp_bool;
	FUNCTIONADDR funadd = NULL;

	//Ensure our "module metrics" object is populated
	if (module_metrics_obj == NULL)
	{
		GL_THROW("Please specify a module metrics object for metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		To operate properly, the metrics object must have the corresponding module's
		metrics calculator linked.  If this object is missing, metrics has no idea
		what to calculate and will not proceed.
		*/
	}

	//It's not null, map up the init function and call it (this must exist, even if it does nothing)
	funadd = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"init_reliability"));
					
	//Make sure it was found
	if (funadd == NULL)
	{
		GL_THROW("Unable to map reliability init function on %s in %s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		While attempting to initialize the reliability module in the "module of interest" metrics device,
		a error was encountered.  Ensure this object fully supports reliability and try again.  If the bug
		persists, please submit your code and a bug report to the trac website.
		*/
	}

	Extra_Data = ((void *(*)(OBJECT *, OBJECT *))(*funadd))(module_metrics_obj,hdr);

	//Make sure it worked
	if (Extra_Data==NULL)
	{
		GL_THROW("Unable to map reliability init function on %s in %s",module_metrics_obj->name,hdr->name);
		//defined above
	}

	//Figure out how many indices we should be finding
	index = 0;

	while ((metrics_oi[index] != '\0') && (index < 1024))
	{
		if (metrics_oi[index] == ',')
		{
			num_indices++;	//Increment counter
		}

		index++;	//Increment pointer
	}

	//Make sure we didn't blow the top off
	if (index == 1024)
	{
		GL_THROW("Maximum length exceeded on metrics_of_interest in metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		While parsing the metrics_of_interest list, the maximum length (1024 characters) was
		reached.  This can cause undesired behavior.  Ensure the metrics list is within this
		character count.  If it is, please try again.  If the error persists, please submit
		your code and a bug report via the trac website.
		*/
	}

	//See if at least one was found.  If it was, that means there are 2 (it counts commas)
	if (num_indices >= 1)
		num_indices++;
	
	//See if we were a solitary one - if so, increment accordingly
	if ((num_indices == 0) && (index > 1))
		num_indices = 1;

	//Make sure at least one was found
	if (num_indices == 0)
	{
		GL_THROW("No indices of interest specified for metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		No indices were found to read.  Please specify the proper indices and try again.
		*/
	}

	//Malloc us up!
	CalcIndices = (INDEXARRAY*)gl_malloc(num_indices * sizeof(INDEXARRAY));

	//Make sure it worked
	if (CalcIndices == NULL)
	{
		GL_THROW("Failure to allocate indices memory in metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		While allocating the storage matrix for the indices to calculate, an error occurred.
		Please try again.  If the error persists, please submit you code and a bug report
		using the trac website.
		*/
	}

	//Initialize these, just in case
	for (index=0; index<num_indices; index++)
	{
		CalcIndices[index].MetricLoc = NULL;	//No address by default
		
		for (indexa=0; indexa<257; indexa++)	//+1 due to end \0
			CalcIndices[index].MetricName[indexa]='\0';
	}

	//Populate it up - copy it first so we don't destroy the original
	metrics_oi.copy_to(work_metrics);

	//Set initial pointers
	startVal = work_metrics;
	endVal = work_metrics;

	//Loop through and find them
	for (index=0; index<num_indices; index++)	//Loop through
	{
		//Find the next comma or end point
		while ((*endVal != ',') && (*endVal != '\0'))
		{
			endVal++;
		}

		//Replace us (comma) with EOS (\0)
		*endVal='\0';

		//Copy us into the structure
		workVal = startVal;
		indexa = 0;
		while ((workVal<=endVal) && (indexa < 256))
		{
			//Copy the value in
			CalcIndices[index].MetricName[indexa] = *workVal;

			//Copy into secondary
			metricbuffer[indexa] = *workVal;

			//Increment pointers
			indexa++;
			workVal++;
		}

		//apply the "_int" portion for the interval search
		indexb = indexa-1;

		//Now update pointers appropriately and proceed
		endVal++;
		startVal = endVal;
		
		//Now try to find this variable
		CalcIndices[index].MetricLoc = get_metric(module_metrics_obj,CalcIndices[index].MetricName);

		//Make sure it worked
		if (CalcIndices[index].MetricLoc == NULL)
		{
			GL_THROW("Unable to find metric %s in object %s for metric:%s",CalcIndices[index].MetricName.get_string(),module_metrics_obj->name,hdr->name);
			/*  TROUBLESHOOT
			While attempting to map out a reliability metric, the desired metric was not found.  Please check the variable
			name and ensure the metric is being published in the module metrics object and try again.  If the error persists,
			please submit your code and a bug report to the trac website.
			*/
		}

		//Get the interval metric - if it exists - and there is room
		if ((indexb+4) <= 256)
		{
			metricbuffer[indexb] = '_';
			metricbuffer[(indexb+1)] = 'i';
			metricbuffer[(indexb+2)] = 'n';
			metricbuffer[(indexb+3)] = 't';
			metricbuffer[(indexb+4)] = '\0';

			//Try to map it
			CalcIndices[index].MetricLocInterval = get_metric(module_metrics_obj,metricbuffer);

			//No NULL check - if it wasn't found, we won't deal with it
		}
	}//end metric traversion
	
	//Map our reset functions for ease
	reset_interval_func = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"reset_interval_metrics"));
	
	//Make sure it worked
	if (reset_interval_func == NULL)
	{
		GL_THROW("Failed to map interval reset in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		While attempting to map the interval statistics reset function, the metrics object encountered a problem.
		Please make sure the module metrics object supports a "reset_interval_metrics" function.  If so, please try again.
		If the error persists, please submit your code and a bug report using the trac website.
		*/
	}

	reset_annual_func = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"reset_annual_metrics"));

	//Make sure it worked
	if (reset_annual_func == NULL)
	{
		GL_THROW("Failed to map annual reset in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		While attempting to map the annual statistics reset function, the metrics object encountered a problem.
		Please make sure the module metrics object supports a "reset_interval_metrics" function.  If so, please try again.
		If the error persists, please submit your code and a bug report using the trac website.
		*/
	}

	compute_metrics = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"calc_metrics"));

	//Make sure it worked
	if (compute_metrics == NULL)
	{
		GL_THROW("Failed to map metric computation function in metrics object %s for metrics:%s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		While attempting to map the function to compute the desired metrics, the metrics object encountered a problem.
		Please make sure the module metrics object supports a "calc_metrics" function.  If so, please try again.
		If the error persists, please submit your code and a bug report using the trac website.
		*/
	}

	//Call the resets - interval
	returnval = ((int (*)(OBJECT *, OBJECT *))(*reset_interval_func))(hdr,module_metrics_obj);

	if (returnval != 1)	//See if it failed
	{
		GL_THROW("Failed to reset interval metrics for %s by metrics:%s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		The metrics object encountered an error while attempting to reset the interval statistics variables.
		Please try again.  If the error persists, submit your code and a bug report via the trac website.
		*/
	}

	//Call the resets - annual
	returnval = ((int (*)(OBJECT *, OBJECT *))(*reset_annual_func))(hdr,module_metrics_obj);

	if (returnval != 1)	//See if it failed
	{
		GL_THROW("Failed to reset annual metrics for %s by metrics:%s",module_metrics_obj->name,hdr->name);
		/*  TROUBLESHOOT
		The metrics object encountered an error while attempting to reset the annual statistics variables.
		Please try again.  If the error persists, submit your code and a bug report via the trac website.
		*/
	}

	//Convert our calculation interval to a timestamp
	metric_interval = (TIMESTAMP)metric_interval_dbl;
	report_interval = (TIMESTAMP)report_interval_dbl;

	//See if it is a year - flag appropriately
	if (metric_interval == 31536000)
		metric_equal_annual = true;

	//Make sure we have a file name provided
	if (report_file[0] == '\0')	//None specified
	{
		GL_THROW("Please specify a proper report file name if you would like an output file from metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		While attempting to write the report file, an invalid file name was provided.  Please provide a valid file name
		and try again.
		*/
	}

	//Open the file to clear it
	FPVal = fopen(report_file,"wt");

	//Make sure it worked
	if (FPVal == NULL)
	{
		GL_THROW("Unable to create the report file '%s' for metrics:%s",report_file,hdr->name);
		/*  TROUBLESHOOT
		While attempting to write the metrics output file, an error occurred.  Please make sure you
		have write permissions at that location and try again.  If the error persists, please submit
		your code and a bug report using the trac website.
		*/
	}

	//It must exist - write the typical header nonsense
	fprintf(FPVal,"Reliability report for %s\n", gl_global_getvar("modelname",workbuffer,(1025*sizeof(char))));

	//Find our lucky candidate objects
	CandidateObjs = gl_find_objects(FL_GROUP,customer_group.get_string());
	if (CandidateObjs==NULL)
	{
		GL_THROW("Failure to find devices for %s specified as: %s",hdr->name,customer_group.get_string());
		/*  TROUBLESHOOT
		While attempting to populate the list of devices to check for reliability metrics, the metrics
		object failed to find any desired objects.  Please make sure the objects exist and try again.
		If the bug persists, please submit your code using the trac website.
		*/
	}

	//Do a zero-find check as well
	if (CandidateObjs->hit_count == 0)
	{
		GL_THROW("Failure to find devices for %s specified as: %s",hdr->name,customer_group.get_string());
		//Defined above
	}

	//Pull the count
	CustomerCount = CandidateObjs->hit_count;

	//Make us an array!
	Customers = (CUSTARRAY*)gl_malloc(CustomerCount*sizeof(CUSTARRAY));

	//Make sure it worked
	if (Customers == NULL)
	{
		GL_THROW("Failure to allocate customer list memory in metrics:%s",hdr->name);
		/*  TROUBLESHOOT
		While allocating the memory for the list of customers, GridLAB-D encountered a problem.
		Please try again.  If the error persists, please submit your code and a bug report via the
		trac website.
		*/
	}

	//Let's populate the beast now!
	temp_obj = NULL;
	for (index=0; index<CustomerCount; index++)
	{
		//Find the object
		temp_obj = gl_find_next(CandidateObjs, temp_obj);

		if (temp_obj == NULL)
		{
			GL_THROW("Failed to populate customer list in metrics: %s",hdr->name);
			/*  TROUBLESHOOT
			While populating the metrics customer list, an object failed to be
			located.  Please try again.  If the error persists, please submit your
			code and a bug report to the trac website.
			*/
		}

		Customers[index].CustomerObj = temp_obj;

		//Try to find our "outage" indicator and map its address
		temp_bool = get_outage_flag(temp_obj, "customer_interrupted");

		//make sure it found it
		if (temp_bool == NULL)
		{
			GL_THROW("Unable to find interrupted flag for customer object %s in metrics:%s",temp_obj->name,hdr->name);
			/*  TROUBLESHOOT
			While attempting to link to the 'customer interrupted' flag, an error occurred.  Please ensure the object
			supports being polled by reliability as a customer (customer_interrupted exists as a published property) and
			try again.  If the error persists, please submit your code and a bug report via the trac website.
			*/
		}

		//Write this value in
		Customers[index].CustInterrupted = temp_bool;

		if (index == 0)	//First customer, handle slightly different
		{
			//Populate the secondary index - needs to exist, even if never used
			//Try to find our secondary "outage" indicator and map its address
			temp_bool = get_outage_flag(temp_obj, "customer_interrupted_secondary");

			//make sure it found it
			if (temp_bool == NULL)	//Not found, assume no one else wants one
			{
				gl_warning("Unable to find secondary interruption flag, no secondary interruptions recorded in metrics:%s",hdr->name);
				/*  TROUBLESHOOT
				While attempting to link to the 'secondary customer interrupted' flag, it was not found.  THe object may not support
				"secondary interruption counts" and this message is valid.  If a secondary count was desired, ensure the object
				supports being polled by reliability as a customer (customer_interrupted_secondary exists as a published property) and
				try again.  If the error persists, please submit your code and a bug report via the trac website.
				*/
			}
			else	//One found, assume all want one now
			{
				secondary_interruptions_count = true;
				
				//Write this value in
				Customers[index].CustInterrupted_Secondary = temp_bool;
			}
		}
		else if (secondary_interruptions_count == true)	//Decided we want it
		{
			//Populate the secondary index - needs to exist, even if never used
			//Try to find our secondary "outage" indicator and map its address
			temp_bool = get_outage_flag(temp_obj, "customer_interrupted_secondary");

			//make sure it found it
			if (temp_bool == NULL)
			{
				GL_THROW("Unable to find secondary interruption flag for customer object %s in metrics:%s",temp_obj->name,hdr->name);
				/*  TROUBLESHOOT
				While attempting to link to the 'secondary customer interrupted' flag, an error occurred.  Please ensure the object
				supports being polled by reliability as a customer (customer_interrupted_secondary exists as a published property) and
				try again.  If the error persists, please submit your code and a bug report via the trac website.
				*/
			}

			//Write this value in
			Customers[index].CustInterrupted_Secondary = temp_bool;
		}
		//Defaulted else - unwanted

	}//end population loop

	//Free up list
	gl_free(CandidateObjs);

	//Write the customer count and header information to the file we have going
	fprintf(FPVal,"Number of customers = %d\n\n",CustomerCount);

	//See if the particular metrics object has any "comments" to add to the file header (units, notes, etc.)
	funadd = NULL;	//Reset function pointer - just in case

	//Map up the "extra print" function - if it isn't there, well nothing is done
	funadd = (FUNCTIONADDR)(gl_get_function(module_metrics_obj,"logfile_extra"));

	//See if it was found
	if (funadd != NULL)
	{
		//Do the extra printing
		returnval = ((int (*)(OBJECT *, char *))(*funadd))(module_metrics_obj,workbuffer);

		//Make sure it worked
		if (returnval==0)
		{
			GL_THROW("Failed to write extra header material for %s in %s",module_metrics_obj->name,hdr->name);
			/*  TROUBLESHOOT
			While attempting to write the extra material into the file header, an error occurred.  Please try again.
			If the error persists, please submit your code and a bug report via the trac website.
			*/
		}

		//Print it out
		fprintf(FPVal,"%s",workbuffer);
	}

	//Close the file handle
	fclose(FPVal);

	return 1; /* return 1 on success, 0 on failure - We're so awesome we always assume we work */
}
int ZIPload::init(OBJECT *parent)
{
	
	
	
		////////////////////////////////////SEARCH////////////////////////////////////
	
	 static FINDLIST *xt2=NULL;
				 xt2=gl_find_objects(FL_NEW,FT_CLASS,SAME,"irrigation_controller",FT_END);
				 OBJECT *firstt2= gl_find_next(xt2,NULL);
				 OBJECT *it2;
				 for(it2=firstt2;it2!=NULL;it2=it2->next)
				 {
				
					 if(gl_object_isa(it2,"irrigation_controller"))
				     {
						

						 if(OBJECTHDR(this)->id==it2->parent->id)
						{
							irrigation_contr_object=it2;
							// printf("%d %d",OBJECTHDR(this)->id,irrigation_contr_object->id);
						 //system("pause");
						}
						 else
						 {
							// irrigation_contr_object=NULL;
						 }

					 }
				 }


				static FINDLIST *xt1=NULL;
				 xt1=gl_find_objects(FL_NEW,FT_CLASS,SAME,"auction",FT_END);
				 OBJECT *firstt1= gl_find_next(xt1,NULL);
				 OBJECT *it1;
				 for(it1=firstt1;it1!=NULL;it1=it1->next)
				 {
				
					 if(gl_object_isa(it1,"auction"))
				     {

						
						 auction_object=it1;
						
					 }

				 }

	//////////////////////////////////////////////////////////////////////////////

	if(parent != NULL){
		if((parent->flags & OF_INIT) != OF_INIT){
			char objname[256];
			gl_verbose("zipload::init(): deferring initialization on %s", gl_name(parent, objname, 255));
			return 2; // defer
		}
	}
	OBJECT *hdr = OBJECTHDR(this);
	hdr->flags |= OF_SKIPSAFE;

	if (demand_response_mode == true)
	{
		gl_warning("zipload_init: The demand response zipload is an experimental model at this time.");
		/*  TROUBLESHOOT
		The warning is pretty obvious.  However, over time, we will be developing this model further.  If you have any questions 
		about it, please see the Matlab files found in ../design/dr_model/ or read the paper titled "On the Equilibrium Dynamics of Demand Response"
		submitted to HICSS 2011 or post your questions on the WIKI forum.
		*/
		
		// Initial error checks
		if (abs(eta) > 1)
		{
			GL_THROW("zipload_init: demand_rate (eta) must be between -1 and 1.");
			/*  TROUBLESHOOT
			The demand rate is limited to values between -1 and 1 (inclusive).  Please reset to an appropriate value.
			*/
		}
		if (phi < 0 || phi > 1)
		{
			GL_THROW("zipload_init: duty_cycle (phi) must be between 0 and 1.");
			/*  TROUBLESHOOT
			The duty cycle is only explicitly used if ron and roff are not set.  In normal operation, phi will be calculated from
			ron and roff as a function of time.  However, if ron and roff are not set, the initial values for ron and roff are calculated
			from phi.  Please set to a value between 1 and 0 (inclusive).
			*/
		}
		
		// Set up the buffers and perform some error checks
		if (L > 0)
			if (L < 70)
				drm.nbins = L;
			else
			{
				gl_warning("zipload_init: Using a value for thermostatic_control_range (L) greater than 50 may cause some instabilities.");
				/*  TROUBLESHOOT
				This warning is shown only as a reminder.  Large values of L (thermostatic_control_range) can cause instabilities for some
				combinations of ron and roff.  If you receive inderminant numbers as part of the solution, try reducing L.
				*/
			}
		else
		{
			GL_THROW("zipload_init: thermostatic_control_range (L) must be greater than 0.");
			/*  TROUBLESHOOT
			The thermostatic control range must be a positive integer value, since this is used to create the number of bins 
			for the discrete solution.
			*/
		}

		drm.off = (double*)malloc(sizeof(double)*L);
		drm.on = (double*)malloc(sizeof(double)*L);
		if (drm.off==NULL || drm.on==NULL)
		{
			GL_THROW("zipload_init: memory allocation error.  Please report this error.");
			/*  TROUBLESHOOT
			If you receive this error, something went horribly wrong with a memory allocation. Please report this to TRAC and provide
			the glm file that caused it.
			*/
		}

		/* setup the initial population */
		if (ron == -1 || roff == -1)
		{
			if (phi <= 0.5)
			{
				roff = phi/(1-phi);
				ron = 1;
				gl_warning("ron or roff was not set.  Using phi to calculate.  Step changes in demand rates as a function of time will be ignored.");
				/*  TROUBLESHOOT
				Ideally, in the method currently being used, ron and roff (heating and cooling rates) should be used to calculate phi.
				If you receive this error, the phi is being used to calculate ron and roff initially.  However, phi does not update  
				ron and roff at each time step, so you will not be able to perform disturbances of demand.  If you wish this, please use
				ron and roff as a function of time instead.  This can also be caused by using a schedule or player transform to describe 
				the ron or roff values - essentially during the initialization, the value is not described yet.  There is no current fix for
				this, but can be "faked" by setting phi to the correct initial value and waiting a couple of timesteps for things to settle.
				*/
			}
			else
			{
				roff = 1;
				ron = (1-phi)/phi;
				gl_warning("ron or roff was not set.  Using phi to calculate. Step changes in demand rates as a function of time will be ignored.");
				/*  TROUBLESHOOT
				Ideally, in the method currently being used, ron and roff (heating and cooling rates) should be used to calculate phi.
				If you receive this error, the phi is being used to calculate ron and roff initially.  However, phi does not update  
				ron and roff at each time step, so you will not be able to perform disturbances of demand.  If you wish this, please use
				ron and roff as a function of time instead.  This can also be caused by using a schedule or player transform to describe 
				the ron or roff values - essentially during the initialization, the value is not described yet.  There is no current fix for
				this, but can be "faked" by setting phi to the correct initial value and waiting a couple of timesteps for things to settle.
				*/
			}
		}
		else
			phi = roff / (ron + roff);

		if (roff < 0 || ron < 0)
		{
			GL_THROW("zipload_init: rate_of_cooling and rate_of_heating must be greater than or equal to 0.");
			/*  TROUBLESHOOT
			Rates of heating and cooling should be positive or zero values.  These values describe how fast objects transition from a 
			cooler to hotter temperature, or vice versa, and have been defined as positive values in this model.
			*/
		}

		non = noff = 0;
		double test_N = 0;

		for (x=0; x<L; x++)
		{
			/* exponential distribution */
			if (eta != 0)
			{
				drm.on[x] = N * eta * (1-phi) * exp(eta*(L-0.5-x)/roff) / (exp(eta*L/roff)-1);
				drm.off[x] = drm.on[x] * ron/roff;
				test_N += drm.on[x] + drm.off[x];
				//non += drm.on[x] = eta * (1-phi) * exp(eta*(L-x+0.5)/roff) / (exp(eta*L/roff)-1);
				//noff += drm.off[x] = drm.on[x]*ron/roff;
			}

			/* uniform distribution */
			else
			{
				non += drm.on[x] = N * phi/L;
				noff += drm.off[x] = N * (1-phi)/L;
				printf("testsfsdfsdfs : : : ;%f %f",non,noff);
			}
		}

		/* check for valid population */
		if (abs(test_N - N) != 0)
		{
			double extra = N - test_N;
			drm.off[0] += extra;
		}
		
	}

	if (duty_cycle > 1 || duty_cycle < 0)
	{
		if (duty_cycle != -1)
		{
			GL_THROW("Value of duty cycle is set to a value outside of 0-1.");
			/*  TROUBLESHOOT
			By definition, a duty cycle must be between, and including, 0 and 1.  Zero will turn the
			duty cycle function OFF.  Please specify a duty_cycle value between 0 and 1.
			*/
		}
	}

	// We're using a duty cycle mode
	if (duty_cycle != -1)
	{
		if (period <= 0)
		{
			GL_THROW("Period is less than or equal to zero.");
			/*  TROUBLESHOOT
			When using duty cycle mode, the period must be a positive value.
			*/
		}
		if (phase < 0 || phase > 1)
		{
			GL_THROW("Phase is not between zero and one.");
			/*  TROUBLESHOOT
			When using duty cycle mode, the phase must be specified as a value between 0 and 1.  This
			will set the initial phase as a percentage of the period.  The "duty" will assume to be
			applied at the beginning of each period.  Randomizing this input value will prevent syncing of
			objects.
			*/
		}
	}

	if (heatgain_only == true)
	{
		load.config = EUC_HEATLOAD;
		load.power_fraction = load.current_fraction = load.impedance_fraction = 0.0;
	}
	if (is_240)	//See if the 220/240 flag needs to be set
	{
		load.config |= EUC_IS220;
	}

	load.breaker_amps = breaker_val;
	
	only_once=0;
	first_time=0;
	return residential_enduse::init(parent);
}
Example #8
0
void billdump::dump(TIMESTAMP t){
	char namestr[64];
	char timestr[64];
	FINDLIST *nodes = NULL;
	OBJECT *obj = NULL;
	FILE *outfile = NULL;
	triplex_meter *pnode;
	meter *qnode;
	

//	CLASS *nodeclass = NULL;
//	PROPERTY *vA, *vB, *vC;

	if (meter_type == METER_TP)
	{
		if(group[0] == 0){
			nodes = gl_find_objects(FL_NEW,FT_CLASS,SAME,"triplex_meter",FT_END);
		} else {
			nodes = gl_find_objects(FL_NEW,FT_CLASS,SAME,"triplex_meter",AND,FT_GROUPID,SAME,group,FT_END);
		}
	}
	else
	{
		if(group[0] == 0){
			nodes = gl_find_objects(FL_NEW,FT_CLASS,SAME,"meter",FT_END);
		} else {
			nodes = gl_find_objects(FL_NEW,FT_CLASS,SAME,"meter",AND,FT_GROUPID,SAME,group,FT_END);
		}
	}

	if(nodes == NULL){
		gl_warning("no nodes were found to dump");
		return;
	}

	outfile = fopen(filename, "w");
	if(outfile == NULL){
		gl_error("billdump unable to open %s for output", filename);
		return;
	}

	//nodeclass = node::oclass;
	//vA=gl_find_property(nodeclass, "

	if (meter_type == METER_TP)
	{
		/* print column names */
		gl_printtime(t, timestr, 64);
		fprintf(outfile,"# %s run at %s on %i triplex meters\n", filename, timestr, nodes->hit_count);
		fprintf(outfile,"meter_name,previous_monthly_bill,previous_monthly_energy\n");
		while (obj=gl_find_next(nodes,obj)){
			if(gl_object_isa(obj, "triplex_meter", "powerflow")){
				pnode = OBJECTDATA(obj,triplex_meter);
				if(obj->name == NULL){
					sprintf(namestr, "%s:%i", obj->oclass->name, obj->id);
				}
				fprintf(outfile,"%s,%f,%f\n",(obj->name ? obj->name : namestr),pnode->previous_monthly_bill,pnode->previous_monthly_energy);
			}
		}
	}
	else
	{
		/* print column names */
		gl_printtime(t, timestr, 64);
		fprintf(outfile,"# %s run at %s on %i meters\n", filename, timestr, nodes->hit_count);
		fprintf(outfile,"meter_name,previous_monthly_bill,previous_monthly_energy\n");
		while (obj=gl_find_next(nodes,obj)){
			if(gl_object_isa(obj, "meter", "powerflow")){
				qnode = OBJECTDATA(obj,meter);
				if(obj->name == NULL){
					sprintf(namestr, "%s:%i", obj->oclass->name, obj->id);
				}
				fprintf(outfile,"%s,%f,%f\n",(obj->name ? obj->name : namestr),qnode->previous_monthly_bill,qnode->previous_monthly_energy);
			}
		}
	}
	fclose(outfile);
}
Example #9
0
/** Checks for climate object and maps the climate variables to the house object variables.  
Currently Tout, RHout and solar_service flux data from TMY files are used.  If no climate object is linked,
then Tout will be set to 59 degF, RHout is set to 75% and solar_service flux will be set to zero for all orientations.
**/
int solar_service::init_climate()
{
	OBJECT *hdr = OBJECTHDR(this);
	OBJECT *obj = NULL;

	// link to climate data
	FINDLIST *climates = NULL;
	
	if (solar_service_model_tilt != PLAYERVAL)
	{
		if (weather!=NULL)
		{
			if(!gl_object_isa(weather, "climate")){
				// strcmp failure
				gl_error("weather property refers to a(n) \"%s\" object and not a climate object", weather->oclass->name);
				/*  TROUBLESHOOT
				While attempting to map a climate property, the solar_service array encountered an object that is not a climate object.
				Please check to make sure a proper climate object is present, and/or specified.  If the bug persists, please
				submit your code and a bug report via the trac website.
				*/
				return 0;
			}
			obj = weather;
		}
		else	//No weather specified, search
		{
			climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
			if (climates==NULL)
			{
				//Ensure weather is set to NULL - catch below
				weather = NULL;
			}
			else if (climates->hit_count==0)
			{
				//Ensure weather is set to NULL - catch below
				weather = NULL;
			}
			else //climate data must have been found
			{
				if (climates->hit_count>1)
				{
					gl_warning("solar_servicepanel: %d climates found, using first one defined", climates->hit_count);
					/*  TROUBLESHOOT
					More than one climate object was found, so only the first one will be used by the solar_service array object
					*/
				}


				gl_verbose("solar_service init: climate data was found!");
				// force rank of object w.r.t climate
				obj = gl_find_next(climates,NULL);
				weather = obj;
			}
		}

		//Make sure it actually found one
		if (weather == NULL)
		{
			//Replicate above warning
			gl_warning("solar_servicepanel: no climate data found, using static data");
			/*  TROUBLESHOOT
			No climate object was found and player mode was not enabled, so the solar_service array object
			is utilizing default values for all relevant weather variables.
			*/

			//default to mock data
			static double tout=59.0, rhout=0.75, solar_service=92.902, wsout=0.0, albdefault=0.2;
			pTout = &tout;
			pRhout = &rhout;
			psolar_serviceD = &solar_service;	//Default all solar_service values to normal "optimal" 1000 W/m^2
			psolar_serviceH = &solar_service;
			psolar_serviceG = &solar_service;
			pAlbedo = &albdefault;
			pWindSpeed = &wsout;

			if (orientation_type==FIXED_AXIS)
			{
				GL_THROW("FIXED_AXIS requires a climate file!");
				/*  TROUBLESHOOT
				The FIXED_AXIS model for the PV array requires climate data to properly function.
				Please specify such data, or consider using a different tilt model.
				*/
			}
		}
		else if (!gl_object_isa(weather,"climate"))	//Semi redundant for "weather"
		{
			GL_THROW("weather object is not a climate object!");
			/*  TROUBLESHOOT
			The object specified for the weather property is not a climate object and will not work
			with the solar_service object.  Please specify a valid climate object, or let the solar_service object
			automatically connect.
			*/
		}
		else	//Must be a proper object
		{
			if((obj->flags & OF_INIT) != OF_INIT){
				char objname[256];
				gl_verbose("solar_service::init(): deferring initialization on %s", gl_name(obj, objname, 255));
				return 2; // defer
			}
			if (obj->rank<=hdr->rank)
				gl_set_dependent(obj,hdr);
		   
			pTout = (double*)GETADDR(obj,gl_get_property(obj,"temperature"));
//			pRhout = (double*)GETADDR(obj,gl_get_property(obj,"humidity"));	<---- Not used anywhere yet
			psolar_serviceD = (double*)GETADDR(obj,gl_get_property(obj,"solar_service_direct"));
			psolar_serviceH = (double*)GETADDR(obj,gl_get_property(obj,"solar_service_diffuse"));
			psolar_serviceG = (double*)GETADDR(obj,gl_get_property(obj,"solar_service_global"));
			pAlbedo = (double*)GETADDR(obj,gl_get_property(obj,"ground_reflectivity"));
			pWindSpeed = (double*)GETADDR(obj,gl_get_property(obj,"wind_speed"));

			//Should probably check these
			if (pTout==NULL)
			{
				GL_THROW("Failed to map outside temperature");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the outside air temperature.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			//No need to error check - doesn't exist in any formulations yet
			//if (pRhout==NULL)
			//{
			//	GL_THROW("Failed to map outside relative humidity");
			//	/*  TROUBLESHOOT
			//	The solar_service PV array failed to map the outside relative humidity.  Ensure this is
			//	properly specified in your climate data and try again.
			//	*/
			//}

			if (psolar_serviceD==NULL)
			{
				GL_THROW("Failed to map direct normal solar_service radiation");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the solar_service direct normal radiation.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			if (psolar_serviceH==NULL)
			{
				GL_THROW("Failed to map diffuse horizontal solar_service radiation");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the solar_service diffuse horizontal radiation.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			if (psolar_serviceG==NULL)
			{
				GL_THROW("Failed to map global horizontal solar_service radiation");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the solar_service global horizontal radiation.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			if (pAlbedo==NULL)
			{
				GL_THROW("Failed to map albedo/ground reflectance");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the ground reflectance.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			if (pWindSpeed==NULL)
			{
				GL_THROW("Failed to map wind speed");
				/*  TROUBLESHOOT
				The solar_service PV array failed to map the wind speed.  Ensure this is
				properly specified in your climate data and try again.
				*/
			}

			//If climate data was found, check other related variables
			if (fix_angle_lat==true)
			{
				if (obj->latitude < 0)	//Southern hemisphere
				{
					//Get the latitude from the climate file
					tilt_angle = -obj->latitude;
				}
				else	//Northern
				{
					//Get the latitude from the climate file
					tilt_angle = obj->latitude;
				}
			}

			//Check the tilt angle for absurdity
			if (tilt_angle < 0)
			{
				GL_THROW("Invalid tilt_angle - tilt must be between 0 and 90 degrees");
				/*  TROUBLESHOOT
				A negative tilt angle was specified.  This implies the array is under the ground and will
				not receive any meaningful solar_service irradiation.  Please correct the tilt angle and try again.
				*/
			}
			else if (tilt_angle > 90.0)
			{
				GL_THROW("Invalid tilt angle - values above 90 degrees are unsupported!");
				/*  TROUBLESHOOT
				An tilt angle over 90 degrees (straight up and down) was specified.  Beyond this angle, the
				tilt algorithm does not function properly.  Please specific the tilt angle between 0 and 90 degrees
				and try again.
				*/
			}

			//Check the solar_service method
			if (orientation_type == FIXED_AXIS)
			{
				//See which function we want to use
				if (solar_service_model_tilt==LIUJORDAN)
				{
					//Map up the "classic" function
					calc_solar_service_radiation = (FUNCTIONADDR)(gl_get_function(obj,"calculate_solar_service_radiation_shading_degrees"));
				}
				else if (solar_service_model_tilt==SOLPOS)	//Use the solpos/Perez tilt model
				{
					//Map up the "classic" function
					calc_solar_service_radiation = (FUNCTIONADDR)(gl_get_function(obj,"calc_solpos_radiation_shading_degrees"));
				}
								
				//Make sure it was found
				if (calc_solar_service_radiation == NULL)
				{
					GL_THROW("Unable to map solar_service radiation function on %s in %s",obj->name,hdr->name);
					/*  TROUBLESHOOT
					While attempting to initialize the photovoltaic array mapping of the solar_service radiation function.
					Please try again.  If the bug persists, please submit your GLM and a bug report via the trac website.
					*/
				}

				//Check azimuth for absurdity as well
				if ((orientation_azimuth<0.0) || (orientation_azimuth > 360.0))
				{
					GL_THROW("orientation_azimuth must be a value representing a valid cardinal direction of 0 to 360 degrees!");
					/*  TROUBLESHOOT
					The orientation_azimuth property is expected values on the cardinal points degree system.  For this convention, 0 or
					360 is north, 90 is east, 180 is south, and 270 is west.  Please specify a direction within the 0 to 360 degree bound and try again.
					*/
				}

				//Map up our azimuth now too, if needed - Liu & Jordan model assumes 0 = equator facing
				if (solar_service_model_tilt == LIUJORDAN)
				{
					if (obj->latitude>0.0)	//North - "south" is equatorial facing
					{
						orientation_azimuth_corrected =  180.0 - orientation_azimuth;
					}
					else if (obj->latitude<0.0) //South - "north" is equatorial facing
					{
						gl_warning("solar_service:%s - Default solar_service position model is not recommended for southern hemisphere!",hdr->name);
						/*  TROUBLESHOOT
						The Liu-Jordan (default) solar_service position and tilt model was built around the northern
						hemisphere.  As such, operating in the southern hemisphere does not provide completely accurate
						results.  They are close, but tilted surfaces are not properly accounted for.  It is recommended
						that the solar_service_TILT_MODEL SOLPOS be used for southern hemisphere operations.
						*/

						if ((orientation_azimuth >= 0.0) && (orientation_azimuth <= 180.0))
						{
							orientation_azimuth_corrected =  orientation_azimuth;	//East positive
						}
						else if (orientation_azimuth == 360.0) //Special case for those who like 360 as North
						{
							orientation_azimuth_corrected = 0.0;
						}
						else	//Must be west
						{
							orientation_azimuth_corrected = orientation_azimuth - 360.0;
						}
					}
					else	//Equator - erm....
					{
						GL_THROW("Exact equator location of array detected - unknown how to handle orientation");
						/*  TROUBLESHOOT
						The solar_service orientation algorithm implemented inside GridLAB-D does not understand how to orient
						itself for an array exactly on the equator.  Shift it north or south a little bit to get valid results.
						*/
					}
				}
				else	//Right now only SOLPOS, which is "correct" - if another is implemented, may need another case
					orientation_azimuth_corrected = orientation_azimuth;
			}
			//Defaulted else for now - don't do anything
		}//End valid weather - mapping check
	}
	else	//Player mode, just drop a message
	{
		gl_warning("solar_service object:%s is in player mode - be sure to specify relevant values",hdr->name);
		/*  TROUBLESHOOT
		The solar_service array object is in player mode.  It will not take values from climate files or objects.
		Be sure to specify the Insolation, ambient_temperature, and wind_speed values as necessary.  It also
		will not incorporate any tilt functionality, since the Insolation value is expected to already include
		this adjustment.
		*/
	}

	return 1;
}
TIMESTAMP irrigation_controller::sync(TIMESTAMP t0, TIMESTAMP t1){
	double bid = -1.0;
	int64 no_bid = 0; // flag gets set when the current temperature drops in between the the heating setpoint and cooling setpoint curves
	double demand = 0.0;
	double rampify = 0.0;
	extern double bid_offset;
	double deadband_shift = 0.0;
	double shift_direction = 0.0;
	double shift_setpoint = 0.0;
	double prediction_ramp = 0.0;
	double prediction_range = 0.0;
	double midpoint = 0.0;
	OBJECT *hdr = OBJECTHDR(this);
	


if(insync==0)
{
	insync=2;
}
else if(insync==2)
{
	x=gl_get_double_by_name(parent2,"actual_power_non_zero");
//	printf("%d %f			 ",parent2->id,*x);
	//system("pause");

		insync=1;
		pDemand=x;
		initial_zipload_power=x;
}


	if(first_period==0)  //for two diffrent periods
	{

	
	//OBJECT *p=gl_get_object("sensor");
	// double *humidity=gl_get_double_by_name(p,"humidity");
	 double *humidity=gl_get_double_by_name(soil_sensor,"humidity");
		
		*pMonitor =*humidity;
		//printf("irrigaiton:%d %f	\n",soil_sensor->id,*pMonitor);
	//	system("pause");
		
	//printf("%f %f",*pMonitor,setpoint0);
	//system("pause");
	/* short circuit if the state variable doesn't change during the specified interval */
	if((t1 < next_run) && (market->market_id == lastmkt_id)){
		if(t1 <= next_run - bid_delay){
			if(use_predictive_bidding == TRUE && ((control_mode == CN_RAMP && last_setpoint != setpoint0) || (control_mode == CN_DOUBLE_RAMP && (last_heating_setpoint != heating_setpoint0 || last_cooling_setpoint != cooling_setpoint0)))) {
				;
			} else {// check to see if we have changed states
				if(pState == 0){
					return next_run;
				} else if(*pState == last_pState){
					return next_run;
				}
			}
		} else {
			return next_run;
		}
	}
	
	if(use_predictive_bidding == TRUE){
		deadband_shift = *pDeadband * 0.5;
	}

	if(control_mode == CN_RAMP){
		// if market has updated, continue onwards
		if(market->market_id != lastmkt_id){// && (*pAvg == 0.0 || *pStd == 0.0 || setpoint0 == 0.0)){
			//printf("EDWWWWWWWWWWWWWWWWWWW\n");
			//system("pause");
			lastmkt_id = market->market_id;
			lastbid_id = -1; // clear last bid id, refers to an old market
			// update using last price
			// T_set,a = T_set + (P_clear - P_avg) * | T_lim - T_set | / (k_T * stdev24)

			clear_price = market->current_frame.clearing_price;

			if(use_predictive_bidding == TRUE){
				if((dir > 0 && clear_price < last_p) || (dir < 0 && clear_price > last_p)){
					shift_direction = -1;
				} else if((dir > 0 && clear_price >= last_p) || (dir < 0 && clear_price <= last_p)){
					shift_direction = 1;
				} else {
					shift_direction = 0;
				}
			}
			if(fabs(*pStd) < bid_offset){
				set_temp = setpoint0;
			} else if(clear_price < *pAvg && range_low != 0){
				set_temp = setpoint0 + (clear_price - *pAvg) * fabs(range_low) / (ramp_low * *pStd) + deadband_shift*shift_direction;
			} else if(clear_price > *pAvg && range_high != 0){
				set_temp = setpoint0 + (clear_price - *pAvg) * fabs(range_high) / (ramp_high * *pStd) + deadband_shift*shift_direction;
			} else {
				set_temp = setpoint0 + deadband_shift*shift_direction;
			}

			if((use_override == OU_ON) && (pOverride != 0)){
				if(clear_price <= last_p){
					// if we're willing to pay as much as, or for more than the offered price, then run.
					*pOverride = 1;
				} else {
					*pOverride = -1;
				}
			}

			// clip
			if(set_temp > max){
				set_temp = max;
			} else if(set_temp < min){
				set_temp = min;
			}

			*pSetpoint = set_temp;
			//gl_verbose("irrigation_controller::postsync(): temp %f given p %f vs avg %f",set_temp, market->next.price, market->avg24);
		}
		
		if(dir > 0){
				//edw mpainei
			if(use_predictive_bidding == TRUE){
				if(*pState == 0 && *pMonitor > (max - deadband_shift)){
					bid = market->pricecap;
				} else if(*pState != 0 && *pMonitor < (min + deadband_shift)){
					bid = 0.0;
					no_bid = 1;
				} else if(*pState != 0 && *pMonitor > max){
					bid = market->pricecap;
				} else if(*pState == 0 && *pMonitor < min){
					bid = 0.0;
					no_bid = 1;
				}
			} else {
				if(*pMonitor > max){
			//		printf("sto max");
				
					bid = market->pricecap;
				} else if (*pMonitor < min){
				//	printf("sto min");
					
					bid = -1.0;
					no_bid = 0;
				}
			}
		} else if(dir < 0){
		
				
			if(use_predictive_bidding == TRUE){
				if(*pState == 0 && *pMonitor < (min + deadband_shift)){
					bid = market->pricecap;
				} else if(*pState != 0 && *pMonitor > (max - deadband_shift)){
					bid = 0.0;
					no_bid = 1;
				} else if(*pState != 0 && *pMonitor < min){
					bid = market->pricecap;
				} else if(*pState == 0 && *pMonitor > max){
					bid = 0.0;
					no_bid = 1;
				}
			} else {
				if(*pMonitor < min){
					bid = market->pricecap;
				} else if (*pMonitor > max){
					bid = 0.0;
					no_bid = 0;
				}
			}
		} else if(dir == 0){

				
			if(use_predictive_bidding == TRUE){
				if(direction == 0.0) {
					gl_error("the variable direction did not get set correctly.");
				} else if((*pMonitor > max + deadband_shift || (*pState != 0 && *pMonitor > min - deadband_shift)) && direction > 0){
					bid = market->pricecap;
				} else if((*pMonitor < min - deadband_shift || (*pState != 0 && *pMonitor < max + deadband_shift)) && direction < 0){
					bid = market->pricecap;
				} else {
					bid = 0.0;
					no_bid = 0;
				}
			} else {
				if(*pMonitor < min){
					bid = market->pricecap;
				} else if(*pMonitor > max){
					bid = 0.0;
					no_bid = 0;
				} else {
					bid = *pAvg;
				}
			}
		}
		
		// calculate bid price
	//printf("%f,monitor:%f,min:%f max:%f, setpoint:%f\n",*humidity,*pMonitor,min,max,setpoint0);
		if(*pMonitor > setpoint0){
			k_T = ramp_low;
			T_lim = range_low;
			bid=0;
			
		  // printf("values : %f %f %f \n",bid,k_T, T_lim );
		} else if(*pMonitor < setpoint0) {
			//printf("right_side ");
		    
			k_T = ramp_low;
			T_lim = range_low;
			//printf("values : %f %f %f \n",bid,k_T, T_lim );

			///////////////////close all the controllers////////////////////////////
						
				static FINDLIST *xt1=NULL;
				 xt1=gl_find_objects(FL_NEW,FT_CLASS,SAME,"controller",FT_END);
				 OBJECT *firstt1= gl_find_next(xt1,NULL);
				 OBJECT *it1;
				 for(it1=firstt1;it1!=NULL;it1=it1->next)
				 {
				
					 if(gl_object_isa(it1,"controller"))
				     {
						 gl_set_value_by_name(it1,"second_period_for_market","1")  ;
						 
				     }
			     }


		//////////////////////////////////////////////////////////////////////////////////
		} else {
			
			k_T = 0.0;
			T_lim = 0.0;
		}
	
			
		if(bid < 0.0 && *pMonitor != setpoint0) {		
			
			gl_set_value_by_name(soil_sensor,"irrigate_flag","1");
			last_q = *initial_zipload_power;
			*pDemand =*initial_zipload_power;
			
			bid = *pAvg + ( (fabs(*pStd) < bid_offset) ? 0.0 : (*pMonitor - setpoint0) * (k_T * *pStd) / fabs(T_lim) );
			//printf("price:%f %f %f %f\n",bid,(*pMonitor - setpoint0) ,(k_T * *pStd) , fabs(T_lim));
				
	
			//////////////////////////////////////
			char x_position_string[1024];
			double *prev=gl_get_double_by_name(parent2,"prev_base_power");
		    double pos_x = *prev;
			sprintf(x_position_string, "%f", pos_x);
			gl_set_value_by_name(parent2,"base_power",x_position_string);
			/////////////////////////////////////

		} else if(*pMonitor == setpoint0) {
			bid = *pAvg;
			
		}
		else
		{
		    last_q=0;
			
			gl_set_value_by_name(parent2,"base_power","0");
		}

		// bid the response part of the load
		double residual = *pTotal;
		/* WARNING ~ bid ID check will not work properly */
		KEY bid_id = (KEY)(lastmkt_id == market->market_id ? lastbid_id : -1);
		// override
		//bid_id = -1;
		
		if(last_q > 0 && no_bid != 1){
			
			last_p = bid;
			last_q= *initial_zipload_power;
		
			//if(last_p < 0)
			//{
				//last_p=clear_price;
			//}
			if(0 != strcmp(market->unit, "")){
				if(0 == gl_convert("kW", market->unit, &(last_q))){
					gl_error("unable to convert bid units from 'kW' to '%s'", market->unit.get_string());
					return TS_INVALID;
				}
			}
			//lastbid_id = market->submit(OBJECTHDR(this), -last_q, last_p, bid_id, (BIDDERSTATE)(pState != 0 ? *pState : 0));
			if(pState != 0){
				
				lastbid_id = submit_bid_state(pMarket, hdr, -last_q, last_p, (*pState > 0 ? 1 : 0), bid_id);
			} else {
				
				lastbid_id = submit_bid(pMarket, hdr, -last_q, last_p, bid_id);
			}
			residual -= *pLoad;

		} else {
			last_p = 0;
			last_q = 0;
			gl_verbose("%s's is not bidding", hdr->name);
		}
		if(residual < -0.001)
			gl_warning("irrigation_controller:%d: residual unresponsive load is negative! (%.1f kW)", hdr->id, residual);
	} 

	if (pState != 0)
		last_pState = *pState;

	
	char timebuf[128];
	gl_printtime(t1,timebuf,127);
	

	return TS_NEVER;


	//}
	
	} //end of first_period==0
}
TIMESTAMP irrigation_controller::presync(TIMESTAMP t0, TIMESTAMP t1){



	//two different periods
		if(first_time==0)
	    {
		first_time=t1;
			     }

			if(gl_todays(t1)-gl_todays(first_time)==2)
			{
				first_period=1;
				static FINDLIST *xt1=NULL;
				 xt1=gl_find_objects(FL_NEW,FT_CLASS,SAME,"controller",FT_END);
				 OBJECT *firstt1= gl_find_next(xt1,NULL);
				 OBJECT *it1;
				 for(it1=firstt1;it1!=NULL;it1=it1->next)
				 {
				
					 if(gl_object_isa(it1,"controller"))
				     {
						 gl_set_value_by_name(it1,"second_period_for_market","1")  ;
						 
				     }
			     }

	
			}
			
	if(slider_setting < -0.001)
		slider_setting = 0.0;
	if(slider_setting_heat < -0.001)
		slider_setting_heat = 0.0;
	if(slider_setting_cool < -0.001)
		slider_setting_cool = 0.0;
	if(slider_setting > 1.0)
		slider_setting = 1.0;
	if(slider_setting_heat > 1.0)
		slider_setting_heat = 1.0;
	if(slider_setting_cool > 1.0)
		slider_setting_cool = 1.0;

	if(control_mode == CN_RAMP && setpoint0 == -1)
		setpoint0 = *pSetpoint; // auto tha einai to orio gia to humidity to setpoint pou tha vazei o xristis
	


	if(control_mode == CN_RAMP){
		if (slider_setting == -0.001){
			min = setpoint0 + range_low;
			max = setpoint0 + range_high;
		} else if(slider_setting > 0){
			min = setpoint0 + range_low * slider_setting;
			max = setpoint0 + range_high * slider_setting;
			if(range_low != 0)
				ramp_low = 2 + (1 - slider_setting);
			else
				ramp_low = 0;
			if(range_high != 0)
				ramp_high = 2 + (1 - slider_setting);
			else
				ramp_high = 0;
		} else {
			min = setpoint0;
			max = setpoint0;
		}
	}
	if((thermostat_mode != TM_INVALID && thermostat_mode != TM_OFF) || t1 >= time_off)
		last_mode = thermostat_mode;
	else if(thermostat_mode == TM_INVALID)
		last_mode = TM_OFF;// this initializes last mode to off

	if(thermostat_mode != TM_INVALID)
		previous_mode = thermostat_mode;
	else
		previous_mode = TM_OFF;

	return TS_NEVER;
}
Example #12
0
int pqload::init(OBJECT *parent){
	int rv = 0;
	int w_rv = 0;

	// init_weather from house_e.cpp:init_weather
	static FINDLIST *climates = NULL;
	OBJECT *hdr = OBJECTHDR(this);
	int not_found = 0;
	if (climates==NULL && not_found==0) 
	{
		climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
		if (climates==NULL)
		{
			not_found = 1;
			gl_warning("pqload: no climate data found");
		}
		else if (climates->hit_count>1)
		{
			gl_warning("pqload: %d climates found, using first one defined", climates->hit_count);
		}
	}
	if (climates!=NULL)
	{
		if (climates->hit_count==0)
		{
			//default to mock data
		}
		else //climate data was found
		{
			// force rank of object w.r.t climate
			OBJECT *obj = gl_find_next(climates,NULL);
			if(weather == NULL){
				weather = NULL;
			} else {
				if (obj->rank<=hdr->rank)
					gl_set_dependent(obj,hdr);
				weather = obj;
			}
		}
	}

	// old check
	if(weather != NULL){
		temperature = gl_get_property(weather, "temperature");
		if(temperature == NULL){
			gl_error("Unable to find temperature property in weather object!");
			++w_rv;
		}
		
		humidity = gl_get_property(weather, "humidity");
		if(humidity == NULL){
			gl_error("Unable to find humidity property in weather object!");
			++w_rv;
		}

		solar = gl_get_property(weather, "solar_flux");
		if(solar == NULL){
			gl_error("Unable to find solar_flux property in weather object!");
			++w_rv;
		}

		wind = gl_get_property(weather, "wind_speed");
		if(wind == NULL){
			gl_error("Unable to find wind_speed property in weather object!");
			++w_rv;
		}

		rain = gl_get_property(weather, "rainfall"); /* not yet implemented in climate */
		if(rain == NULL){
			gl_error("Unable to find rainfall property in weather object!");
			//++w_rv;
		}
	}

	rv = load::init(parent);

	return w_rv ? 0 : rv;
}
Example #13
0
/* Checks for climate object and maps the climate variables to the windturb object variables.  
If no climate object is linked, then default pressure, temperature, and wind speed will be used. */
int windturb_dg::init_climate()
{
	OBJECT *hdr = OBJECTHDR(this);

	// link to climate data
	static FINDLIST *climates = NULL;
	int not_found = 0;

	climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
	if (climates==NULL)
	{
		not_found = 1;
		gl_warning("windturb_dg (id:%d)::init_climate(): no climate data found, using static data",hdr->id);

		//default to mock data
		static double air_dens = std_air_dens, avgWS = avg_ws, Press = std_air_press, Temp = std_air_temp;
		pWS = &avgWS;
		pPress = &Press;
		pTemp = &Temp;

	}
	else if (climates->hit_count>1)
	{
		gl_verbose("windturb_dg: %d climates found, using first one defined", climates->hit_count);
	}
	// }
	if (climates!=NULL)
	{
		if (climates->hit_count==0)
		{
			//default to mock data
			gl_warning("windturb_dg (id:%d)::init_climate(): no climate data found, using static data",hdr->id);
			static double air_dens = std_air_dens, avgWS = avg_ws, Press = std_air_press, Temp = std_air_temp;
			pWS = &avgWS;
			pPress = &Press;
			pTemp = &Temp;
		}
		else //climate data was found
		{
			// force rank of object w.r.t climate
			OBJECT *obj = gl_find_next(climates,NULL);
			if (obj->rank<=hdr->rank)
				gl_set_dependent(obj,hdr);
			pWS = (double*)GETADDR(obj,gl_get_property(obj,"wind_speed"));  
			pPress = (double*)GETADDR(obj,gl_get_property(obj,"pressure"));
			pTemp = (double*)GETADDR(obj,gl_get_property(obj,"temperature"));

			//Make sure it worked
			if (pWS==NULL)
			{
				GL_THROW("windturb_dg (id:%d): Unable to map wind_speed from climate object",obj->id);
			}
			if (pPress==NULL)
			{
				GL_THROW("windturb_dg (id:%d): Unable to map air pressure from climate object",obj->id);
			}
			if (pTemp==NULL)
			{
				GL_THROW("windturb_dg (id:%d): Unable to map air temperature from climate object",obj->id);
			}
		}
	}
	return 1;
}
Example #14
0
/* Object initialization is called once after all object have been created */
int office::init(OBJECT *parent)
{
	double oversize = 1.2; /* oversizing factor */
	update_control_setpoints();
	/* sets up default office parameters if none were passed:  floor height = 9ft; interior mass = 2000 Btu/degF;
	interior/exterior ua = 2 Btu/degF/h; floor area = 4000 sf*/

	if (zone.design.floor_area == 0)
		zone.design.floor_area = 10000;
	if (zone.design.floor_height == 0)
		zone.design.floor_height = 9;
	if (zone.design.interior_mass == 0)
		zone.design.interior_mass = 40000;
	if (zone.design.interior_ua == 0)
		zone.design.interior_ua = 1;
	if (zone.design.exterior_ua == 0)
		zone.design.exterior_ua = .375;

	if (zone.hvac.cooling.design_temperature == 0)
		zone.hvac.cooling.design_temperature = 93; // Pittsburgh, PA
	if (zone.hvac.heating.design_temperature == 0)  
		zone.hvac.heating.design_temperature = -6;  // Pittsburgh, PA
	

	if (zone.hvac.minimum_ach==0)
		zone.hvac.minimum_ach = 1.5;
	if (zone.control.economizer_cutin==0)
		zone.control.economizer_cutin=60;
	if (zone.control.auxiliary_cutin==0)
		zone.control.auxiliary_cutin=2;

	/* schedule */
	if (strcmp(zone.design.schedule,"")==0)
		strcpy(zone.design.schedule,"1-5 8-17"); /* default is unoccupied, MTWRF 8a-5p is occupied */
	occupancy_schedule(zone.design.schedule,occupied);

	/* automatic sizing of HVAC equipment */
	if (zone.hvac.heating.capacity==0)
		zone.hvac.heating.capacity = oversize*(zone.design.exterior_ua*(zone.control.heating_setpoint-zone.hvac.heating.design_temperature) /* envelope */
			- (zone.hvac.heating.design_temperature - zone.control.heating_setpoint) * (0.2402 * 0.0735 * zone.design.floor_height * zone.design.floor_area) * zone.hvac.minimum_ach); /* vent */
	if (zone.hvac.cooling.capacity==0)
		zone.hvac.cooling.capacity = oversize*(-zone.design.exterior_ua*(zone.hvac.cooling.design_temperature-zone.control.cooling_setpoint) /* envelope */
			- (zone.design.window_area[0]+zone.design.window_area[1]+zone.design.window_area[2]+zone.design.window_area[3]+zone.design.window_area[4]
				+zone.design.window_area[5]+zone.design.window_area[6]+zone.design.window_area[7]+zone.design.window_area[8])*100*3.412*zone.design.glazing_coeff /* solar */
			- (zone.hvac.cooling.design_temperature - zone.control.cooling_setpoint) * (0.2402 * 0.0735 * zone.design.floor_height * zone.design.floor_area) * zone.hvac.minimum_ach /* vent */
			- (zone.lights.capacity + zone.plugs.capacity)*3.412); /* lights and plugs */
	if (zone.hvac.cooling.cop==0)
		zone.hvac.cooling.cop=-3;
	if (zone.hvac.heating.cop==0)
		zone.hvac.heating.cop= 1.25;

	OBJECT *hdr = OBJECTHDR(this);

	// link to climate data
	static FINDLIST *climates = gl_find_objects(FL_NEW,FT_CLASS,SAME,"climate",FT_END);
	if (climates==NULL)
		gl_warning("office: no climate data found, using static data");
	else if (climates->hit_count>1)
		gl_warning("house: %d climates found, using first one defined", climates->hit_count);
	if (climates->hit_count>0)
	{
		OBJECT *obj = gl_find_next(climates,NULL);
		if (obj->rank<=hdr->rank)
			gl_set_dependent(obj,hdr);
		zone.current.pTemperature = (double*)GETADDR(obj,gl_get_property(obj,"temperature"));
		zone.current.pHumidity = (double*)GETADDR(obj,gl_get_property(obj,"humidity"));
		zone.current.pSolar = (double*)GETADDR(obj,gl_get_property(obj,"solar_flux"));
	}

	/* sanity check the initial values (no ticket) */
	struct {
		char *desc;
		bool test;
	} map[] = {
		/* list simple tests to be made on data (no ticket) */
		{"floor height is not valid", zone.design.floor_height<=0},
		{"interior mass is not valid", zone.design.interior_mass<=0},
		{"interior UA is not valid", zone.design.interior_ua<=0},
		{"exterior UA is not valid", zone.design.exterior_ua<=0},
		{"floor area is not valid",zone.design.floor_area<=0},
		{"control setpoint deadpoint is invalid", zone.control.setpoint_deadband<=0},
		{"heating and cooling setpoints conflict",TheatOn>=TcoolOff},
		{"cooling capacity is not negative", zone.hvac.cooling.capacity>=0},
		{"heating capacity is not positive", zone.hvac.heating.capacity<=0},
		{"cooling cop is not negative", zone.hvac.cooling.cop>=0},
		{"heating cop is not positive", zone.hvac.heating.cop<=0},
		{"minimum ach is not positive", zone.hvac.minimum_ach<=0},
		{"auxiliary cutin is not positive", zone.control.auxiliary_cutin<=0},
		{"economizer cutin is above cooling setpoint deadband", zone.control.economizer_cutin>=zone.control.cooling_setpoint-zone.control.setpoint_deadband},
	};
	int i;
	for (i=0; i<sizeof(map)/sizeof(map[0]); i++)
	{
		if (map[i].test)
			throw map[i].desc;
	}
	return 1; /* return 1 on success, 0 on failure */
}
Example #15
0
//int solver_matpower(double *rbus, unsigned int nbus, double *rgen, unsigned int ngen, 
//	double *rbranch, unsigned int nbranch, double *rgencost, unsigned int ngencost,
//	double *rareas,	unsigned int nareas)
int solver_matpower(vector<unsigned int> bus_BUS_I, vector<unsigned int> branch_F_BUS, vector<unsigned int> branch_T_BUS, vector<unsigned int> gen_GEN_BUS, vector<unsigned int> gen_NCOST,unsigned int BASEMVA)
{	
	unsigned int nbus = 0;
	unsigned int ngen = 0;
	unsigned int nbranch = 0;
	//unsigned int ngencost = 0;
	//unsigned int nareas = 0;
	//unsigned int nbaseMVA = 0;

	vector<bus> vec_bus;
	vector<gen> vec_gen;
	vector<branch> vec_branch;
	//vector<areas> vec_areas;
	//vector<gen_cost> vec_gencost;
	//vector<baseMVA> vec_baseMVA;
	

	
	//printf("========Getting Data=============\n");

	// Get Bus objects
	OBJECT *temp_obj = NULL;
	bus *list_bus;
	FINDLIST *bus_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"bus",FT_END);
	while (gl_find_next(bus_list,temp_obj)!=NULL)
	{
		
		temp_obj = gl_find_next(bus_list,temp_obj);
		list_bus = OBJECTDATA(temp_obj,bus);
		vec_bus.push_back(*list_bus);
		
        };

	// Get Generator objects
	gen *list_gen;
	FINDLIST *gen_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"gen",FT_END);
	temp_obj = NULL;
	
	while (gl_find_next(gen_list,temp_obj)!=NULL)
	{
		temp_obj = gl_find_next(gen_list,temp_obj);
		list_gen = OBJECTDATA(temp_obj,gen);
		vec_gen.push_back(*list_gen);
        };

	// Get Line/Branch Objects
	branch *list_branch;
	FINDLIST *branch_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"branch",FT_END);
	temp_obj = NULL;

	while (gl_find_next(branch_list,temp_obj)!=NULL)	
	{
		temp_obj = gl_find_next(branch_list,temp_obj);
		list_branch = OBJECTDATA(temp_obj,branch);
		vec_branch.push_back(*list_branch);
	}

	// Get Area Objects
/*
	areas *list_areas;
	FINDLIST *areas_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"areas",FT_END);
	temp_obj = NULL;
	
	while (gl_find_next(areas_list,temp_obj) != NULL)
	{
		temp_obj = gl_find_next(areas_list,temp_obj);
		list_areas = OBJECTDATA(temp_obj,areas);
		vec_areas.push_back(*list_areas);
	}
*/
	
	// Get Generator Cost objects
	/*
	gen_cost *list_gen_cost;
	FINDLIST *gen_cost_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"gen_cost",FT_END);
	temp_obj = NULL;

	while (gl_find_next(gen_cost_list,temp_obj)!=NULL)
	{
		temp_obj = gl_find_next(gen_cost_list,temp_obj);
		list_gen_cost = OBJECTDATA(temp_obj,gen_cost);
		vec_gencost.push_back(*list_gen_cost);

	}
	*/
	// Get Base Information object
	//baseMVA *list_baseMVA;
	//FINDLIST *baseMVA_list = gl_find_objects(FL_NEW,FT_CLASS,SAME,"baseMVA",FT_END);
	//temp_obj = NULL;
	//temp_obj = gl_find_next(baseMVA_list,temp_obj);
	//list_baseMVA = OBJECTDATA(temp_obj,baseMVA);
	//vec_baseMVA.push_back(*list_baseMVA);

	// Get the size of each class
	nbus = vec_bus.size();
	ngen = vec_gen.size();
	nbranch = vec_branch.size();
	//ngencost = vec_gencost.size();
	//nareas = vec_areas.size();
	//nbaseMVA = vec_baseMVA.size();


	// create arrays for input and allocate memory
	double *rbus;
	rbus = (double *) calloc(nbus*BUS_ATTR,sizeof(double));

	double *rgen;
	rgen = (double *) calloc(ngen*GEN_ATTR,sizeof(double));	

	double *rbranch;
	rbranch = (double *) calloc(nbranch*BRANCH_ATTR,sizeof(double));

	double *rareas;
	rareas = (double *) calloc(AREA_ATTR,sizeof(double));

	double rbaseMVA;

	double *rgencost; // allocation of memory is in the following part
	
	

	
	// insert bus data for rbus
	vector<bus>::iterator iter_bus = vec_bus.begin();
	if (nbus > 1)
	{
		for (unsigned int i=0; i < nbus; i++)
		{
			//rbus[i+0*nbus] = (double)iter_bus->BUS_I;
			rbus[i+0*nbus] = bus_BUS_I[i];
			rbus[i+1*nbus] = (double)iter_bus->BUS_TYPE;
			rbus[i+2*nbus] = iter_bus->PD;
			rbus[i+3*nbus] = iter_bus->QD;
			rbus[i+4*nbus] = iter_bus->GS;
			rbus[i+5*nbus] = iter_bus->BS;
			//rbus[i+6*nbus] = (double)iter_bus->BUS_AREA;
			rbus[i+6*nbus] = 1;
			rbus[i+7*nbus] = iter_bus->VM;
			rbus[i+8*nbus] = iter_bus->VA;
			rbus[i+9*nbus] = iter_bus->BASE_KV;
			rbus[i+10*nbus] = (double)iter_bus->ZONE;
			rbus[i+11*nbus] = iter_bus->VMAX;
			rbus[i+12*nbus] = iter_bus->VMIN;
			iter_bus++;
		}
	}

	
	// insert data for rgen
	vector<gen>::iterator iter_gen = vec_gen.begin();
	unsigned int max_order = 0;
	for (unsigned int i =0; i< ngen; i++)
	{
		if (gen_NCOST[i] > max_order)
			max_order = gen_NCOST[i];
		iter_gen++;
	}
	rgencost = (double *) calloc(ngen*(GENCOST_ATTR+max_order),sizeof(double));

	iter_gen = vec_gen.begin();

	for (unsigned int i = 0; i < ngen; i++)
	{
		//rgen[i+0*ngen] = (double) iter_gen->GEN_BUS;
		rgen[i+0*ngen] = gen_GEN_BUS[i];
		rgen[i+1*ngen] = iter_gen->PG;
		rgen[i+2*ngen] = iter_gen->QG;
		rgen[i+3*ngen] = iter_gen->QMAX;
		rgen[i+4*ngen] = iter_gen->QMIN;
		rgen[i+5*ngen] = iter_gen->VG;
		rgen[i+6*ngen] = iter_gen->MBASE;
		rgen[i+7*ngen] = iter_gen->GEN_STATUS;
		rgen[i+8*ngen] = iter_gen->PMAX;
		rgen[i+9*ngen] = iter_gen->PMIN;
		rgen[i+10*ngen] = iter_gen->PC1;
		rgen[i+11*ngen] = iter_gen->PC2;
		rgen[i+12*ngen] = iter_gen->QC1MIN;
		rgen[i+13*ngen] = iter_gen->QC1MAX;
		rgen[i+14*ngen] = iter_gen->QC2MIN;
		rgen[i+15*ngen] = iter_gen->QC2MAX;
		rgen[i+16*ngen] = iter_gen->RAMP_AGC;
		rgen[i+17*ngen] = iter_gen->RAMP_10;
		rgen[i+18*ngen] = iter_gen->RAMP_30;
		rgen[i+19*ngen] = iter_gen->RAMP_Q;
		rgen[i+20*ngen] = iter_gen->APF;

		// Cost info
		rgencost[i+0*ngen] = iter_gen->MODEL;
		rgencost[i+1*ngen] = iter_gen->STARTUP;
		rgencost[i+2*ngen] = iter_gen->SHUTDOWN;
		//rgencost[i+3*ngen] = (double)iter_gen->NCOST;
		rgencost[i+3*ngen] = gen_NCOST[i];
		string double_string(iter_gen->COST);
		vector<string> v;
		v = split(double_string,',');
		for (unsigned int j=0; j<v.size();j++)
		{
			rgencost[i+(4+j)*ngen] = atof(v[j].c_str());
		}
		if (gen_NCOST[i] != max_order)
		{
			for (unsigned int j = gen_NCOST[i]; j< max_order; j++)
			{
				rgencost[i+(4+j)*ngen] = 0.0;
			}
		}

		iter_gen++;
	}	



	// insert data for rbranch
	vector<branch>::iterator iter_branch = vec_branch.begin();
	for (unsigned int i = 0; i < nbranch; i++)
	{
		//rbranch[i+0*nbranch] = (double)iter_branch->F_BUS;
		rbranch[i+0*nbranch] = branch_F_BUS[i];
		//rbranch[i+1*nbranch] = (double)iter_branch->T_BUS;
		rbranch[i+1*nbranch] = branch_T_BUS[i];
		rbranch[i+2*nbranch] = iter_branch->BR_R;
		rbranch[i+3*nbranch] = iter_branch->BR_X;
		rbranch[i+4*nbranch] = iter_branch->BR_B;
		rbranch[i+5*nbranch] = iter_branch->RATE_A;
		rbranch[i+6*nbranch] = iter_branch->RATE_B;		
		rbranch[i+7*nbranch] = iter_branch->RATE_C;
		rbranch[i+8*nbranch] = iter_branch->TAP;
		rbranch[i+9*nbranch] = iter_branch->SHIFT;
		rbranch[i+10*nbranch] = (double)iter_branch->BR_STATUS;
		rbranch[i+11*nbranch] = iter_branch->ANGMIN;
		rbranch[i+12*nbranch] = iter_branch->ANGMAX;
		iter_branch++;
	}

	
	// insert data for rareas
	//vector<areas>::const_iterator iter_areas = vec_areas.begin();
	//for (unsigned int i = 0; i < nareas; i++)
	//{
		rareas[0] = 1;
		rareas[1] = 1;
	//	iter_areas++;
	//} 

	// insert data for rbaseMVA
	//vector<baseMVA>::const_iterator iter_baseMVA = vec_baseMVA.begin();
	//rbaseMVA = iter_baseMVA->BASEMVA;
	rbaseMVA = BASEMVA;

	// insert data for rgencost
	/*
	vector<gen_cost>::const_iterator iter_gencost = vec_gencost.begin();

	unsigned int max_order = 0;
	for (unsigned int i = 0; i<ngencost; i++)
	{
		if (iter_gencost->NCOST > max_order)
			max_order = iter_gencost->NCOST;
		iter_gencost++;
		
	}
	
	rgencost = (double *) calloc(ngencost*(GENCOST_ATTR+max_order),sizeof(double));
	
	iter_gencost = vec_gencost.begin();
	for (unsigned int i = 0; i<ngencost; i++)
	{
		// Only support model 2: ticket 4
		if (iter_gencost -> MODEL != 2)
			GL_THROW("Unsupported model for generation cost\n");

		rgencost[i+0*ngencost] = iter_gencost->MODEL;
		rgencost[i+1*ngencost] = iter_gencost->STARTUP;
		rgencost[i+2*ngencost] = iter_gencost->SHUTDOWN;
		rgencost[i+3*ngencost] = (double)iter_gencost->NCOST;
		string double_string(iter_gencost->COST);
		vector<string> v;
		v = split(double_string,',');
		for (unsigned int j = 0; j<v.size();j++)
		{
			rgencost[i+(4+j)*ngencost] = atof(v[j].c_str());
		}
		if (iter_gencost->NCOST != max_order)
		{
			for (unsigned int j = iter_gencost->NCOST; j < max_order; j++)
				rgencost[i+(4+j)*ngencost] = 0.0;
		}
		iter_gencost++;
	}
	*/



	// Run the Solver function
	//printf("Running Test\n");
        libopfInitialize();
	//mxArray* basemva = initArray(rbaseMVA,nbaseMVA,BASEMVA_ATTR);
	mxArray* basemva_array = mxCreateDoubleMatrix(1,1,mxREAL);
	*mxGetPr(basemva_array) = rbaseMVA;

	// change to MATLAB MAT format
	mxArray* bus_array = initArray(rbus, nbus, BUS_ATTR);	
	mxArray* gen_array = initArray(rgen, ngen, GEN_ATTR);
	mxArray* branch_array = initArray(rbranch, nbranch, BRANCH_ATTR);
	mxArray* gencost_array = initArray(rgencost, ngen, GENCOST_ATTR+max_order);
	//mxArray* areas_array = initArray(rareas, nareas, AREA_ATTR);
	mxArray* areas_array = initArray(rareas, 1, AREA_ATTR);

	mxArray* busout;
	mxArray* genout;
	mxArray* branchout;
	mxArray* f;
	mxArray* success;



	mxArray* plhs[5];
	mxArray* prhs[6];
	plhs[0] = busout;
	plhs[1] = genout;
	plhs[2] = branchout;
	plhs[3] = f;
	plhs[4] = success;

	prhs[0] = basemva_array;
	prhs[1] = bus_array;
	prhs[2] = gen_array;
	prhs[3] = branch_array;
	prhs[4] = areas_array;
	prhs[5] = gencost_array;

	mlxOpf(5, plhs, 6, prhs); // cout if first parameter is 0;
	//mlxOpf(0,plhs,6,prhs);


	// Get data from array
	double *obus = getArray(plhs[0]);
	double *ogen = getArray(plhs[1]);
	double *obranch = getArray(plhs[2]);

	// Update class bus

	temp_obj = NULL;
	for (unsigned int i=0; i < nbus; i++)
	{
		/*		
		iter_bus->PD = obus[i+2*nbus];
		iter_bus->QD = obus[i+3*nbus];
		iter_bus->GS = obus[i+4*nbus];
		iter_bus->BS = obus[i+5*nbus];
		iter_bus->VM = obus[i+7*nbus];		
		iter_bus->VA = obus[i+8*nbus];
		iter_bus->VMAX = obus[i+11*nbus];
		iter_bus->VMIN = obus[i+12*nbus];
		iter_bus->LAM_P = obus[i+13*nbus];
		iter_bus->LAM_Q = obus[i+14*nbus];
		iter_bus->MU_VMAX = obus[i+15*nbus];
		iter_bus->MU_VMIN = obus[i+16*nbus];
		//iter_bus++;
		*/
		//printf("====Before Test part VM %f; %f\n",iter_bus->VM,obus[i+7*nbus]);
		
		temp_obj = gl_find_next(bus_list,temp_obj);

		
		//Matpower does not overwrite the generator power in bus class
		setObjectValue_Double(temp_obj,"PD",obus[i+2*nbus]);
		setObjectValue_Double(temp_obj,"QD",obus[i+3*nbus]);
		setObjectValue_Double(temp_obj,"GS",obus[i+4*nbus]);
		setObjectValue_Double(temp_obj,"BS",obus[i+5*nbus]);
		setObjectValue_Double(temp_obj,"VM",obus[i+7*nbus]);
		setObjectValue_Double(temp_obj,"VA",obus[i+8*nbus]);
		setObjectValue_Double(temp_obj,"VMAX",obus[i+11*nbus]);
		setObjectValue_Double(temp_obj,"VMIN",obus[i+12*nbus]);
		setObjectValue_Double(temp_obj,"LAM_P",obus[i+13*nbus]);
		setObjectValue_Double(temp_obj,"LAM_Q",obus[i+14*nbus]);
		setObjectValue_Double(temp_obj,"MU_VMAX",obus[i+15*nbus]);
		setObjectValue_Double(temp_obj,"MU_VMIN",obus[i+16*nbus]);

		// obus[i+9*nbus] is BASE_KV. The unit is KV.
		setObjectValue_Double2Complex_inDegree(temp_obj,"CVoltageA",obus[i+7*nbus]*obus[i+9*nbus]*1000,obus[i+8*nbus]);
		setObjectValue_Double2Complex_inDegree(temp_obj,"CVoltageB",obus[i+7*nbus]*obus[i+9*nbus]*1000,obus[i+8*nbus]+2/3*PI);
		setObjectValue_Double2Complex_inDegree(temp_obj,"CVoltageC",obus[i+7*nbus]*obus[i+9*nbus]*1000,obus[i+8*nbus]-2/3*PI);
		setObjectValue_Double(temp_obj,"V_nom",obus[i+7*nbus]*obus[i+9*nbus]*1000);
		
		//printf("BUS: %f LAM_P %f\n",obus[i+0*nbus],obus[i+13*nbus]);
		//cout<<"BUS "<<obus[i+0*nbus]<<"LAM_P "<<obus[i+13*nbus]<<endl;
	}
/*
	unsigned int NumOfElement = mxGetNumberOfElements(plhs[0]);
	for (unsigned int i =0; i<NumOfElement; i++)
	{
		printf("%f ",obus[i]);
		if ((i+1)%nbus == 0)
			printf("\n");
	}
	

	printf("========================\n");

	iter_bus = vec_bus.begin();
	for (unsigned int i=0;i< nbus; i++)
	{
		printf("Bus %d; PD %f; QD %f; VM %f; VA %f;\n",iter_bus->BUS_I,iter_bus->PD,iter_bus->QD,iter_bus->VM,iter_bus->VA);
		iter_bus++;
	}
*/	
	// Update class gen
	
	iter_gen = vec_gen.begin();
	temp_obj = NULL;
	for (unsigned int i = 0; i < ngen; i++)
	{
/*		
		iter_gen->PG = ogen[i+1*ngen];
		iter_gen->QG = ogen[i+2*ngen];
		iter_gen->QMAX = ogen[i+3*ngen];
		iter_gen->QMIN = ogen[i+4*ngen];
		iter_gen->VG = ogen[i+5*ngen];
		iter_gen->PC1 = ogen[i+10*ngen];
		iter_gen->PC2 = ogen[i+11*ngen];
		iter_gen->RAMP_AGC = ogen[i+16*ngen];
		iter_gen->RAMP_10 = ogen[i+17*ngen];
		iter_gen->RAMP_30 = ogen[i+18*ngen];
		iter_gen->RAMP_Q = ogen[i+19*ngen];
		iter_gen->APF = ogen[i+20*ngen];
		iter_gen->MU_PMAX = ogen[i+21*ngen];
		iter_gen->MU_PMIN = ogen[i+22*ngen];
		iter_gen->MU_QMAX = ogen[i+23*ngen];
		iter_gen->MU_QMIN = ogen[i+24*ngen];
		iter_gen++;
*/
		temp_obj = gl_find_next(gen_list,temp_obj);
		setObjectValue_Double(temp_obj,"PG",ogen[i+1*ngen]);
		setObjectValue_Double(temp_obj,"QG",ogen[i+2*ngen]);
		setObjectValue_Double(temp_obj,"QMAX",ogen[i+3*ngen]);
		setObjectValue_Double(temp_obj,"QMIN",ogen[i+4*ngen]);
		setObjectValue_Double(temp_obj,"VG",ogen[i+5*ngen]);
		setObjectValue_Double(temp_obj,"PC1",ogen[i+10*ngen]);
		setObjectValue_Double(temp_obj,"PC2",ogen[i+11*ngen]);
		setObjectValue_Double(temp_obj,"RAMP_AGC",ogen[i+16*ngen]);
		setObjectValue_Double(temp_obj,"RAMP_10",ogen[i+17*ngen]);
		setObjectValue_Double(temp_obj,"RAMP_30",ogen[i+18*ngen]);
		setObjectValue_Double(temp_obj,"RAMP_Q",ogen[i+19*ngen]);
		setObjectValue_Double(temp_obj,"APF",ogen[i+20*ngen]);
		setObjectValue_Double(temp_obj,"MU_PMAX",ogen[i+21*ngen]);
		setObjectValue_Double(temp_obj,"MU_PMIN",ogen[i+22*ngen]);
		setObjectValue_Double(temp_obj,"MU_QMAX",ogen[i+23*ngen]);
		setObjectValue_Double(temp_obj,"MU_QMIN",ogen[i+24*ngen]);



		// Calculate Price
		double price = 0;
		unsigned int NCOST = (unsigned int)rgencost[i+3*ngen];
		//printf("Bus %d, order %d ",i,NCOST);
		for (unsigned int j = 0; j < NCOST; j++)
		{
			price += pow(ogen[i+1*ngen],NCOST-1-j)*rgencost[i+(4+j)*ngen];
			//printf("Coeff %d: %f and price %f",j,rgencost[i+(4+j)*ngencost],price);
		}

		setObjectValue_Double(temp_obj,"Price",price);
		//printf("\nBus %d, Price %f\n",i,price);
		
		iter_gen++;
	}

	// Update class branch	
	
	
	//iter_branch = vec_branch.begin();
	temp_obj = NULL;
	for (unsigned int i = 0; i<nbranch; i++)
	{
/*
		iter_branch->PF = obranch[i+13*nbranch];
		iter_branch->QF = obranch[i+14*nbranch];
		iter_branch->PT = obranch[i+15*nbranch];
		iter_branch->QT = obranch[i+16*nbranch];
		iter_branch->MU_SF = obranch[i+17*nbranch];
		iter_branch->MU_ST = obranch[i+18*nbranch];
		iter_branch->MU_ANGMIN = obranch[i+19*nbranch];
		iter_branch->MU_ANGMAX = obranch[i+20*nbranch];
		iter_branch++;
*/

		temp_obj = gl_find_next(branch_list,temp_obj);
		setObjectValue_Double(temp_obj,"PF",obranch[i+13*nbranch]);
		setObjectValue_Double(temp_obj,"QF",obranch[i+14*nbranch]);
		setObjectValue_Double(temp_obj,"PT",obranch[i+15*nbranch]);
		setObjectValue_Double(temp_obj,"QT",obranch[i+16*nbranch]);
		setObjectValue_Double(temp_obj,"MU_SF",obranch[i+17*nbranch]);
		setObjectValue_Double(temp_obj,"MU_ST",obranch[i+18*nbranch]);
		setObjectValue_Double(temp_obj,"MU_ANGMIN",obranch[i+19*nbranch]);
		setObjectValue_Double(temp_obj,"MU_ANGMAX",obranch[i+20*nbranch]);
	}
	
	// free space
	//printf("Free r..\n");
	free(rbus);
	free(rgen);
	free(rbranch);
	free(rareas);
	//free(rbaseMVA);
	free(rgencost);
	
	//printf("Free o..\n");	
	free(obus);
	free(ogen);
	free(obranch);

	vec_bus.clear();
	vec_gen.clear();
	vec_branch.clear();
	//vec_gencost.clear();
	//vec_baseMVA.clear();


	short ifsuccess = (short)*getArray(plhs[3]);
	//printf("suceess %f\n",*getArray(plhs[4]));
	return ifsuccess;

}
Example #16
0
/**
* Object initialization is called once after all object have been created
*
* @param parent a pointer to this object's parent
* @return 1 on success, 0 on error
*/
int histogram::init(OBJECT *parent)
{
	PROPERTY *prop = NULL;
	OBJECT *obj = OBJECTHDR(this);
	char tprop[64], tpart[8];
	int e = 0;
	TAPEFUNCS *tf = 0;
	tprop[0]=0;
	tpart[0] = 0;

	if(parent == NULL) /* better have a group... */
	{
		OBJECT *group_obj = NULL;
		CLASS *oclass = NULL;
		if(group[0] == NULL){
			gl_error("Histogram has no parent and no group");
			return 0;
		}
		group_list = gl_find_objects(FL_GROUP,group.get_string());
		if(group_list == NULL){
			gl_error("Histogram group could not be parsed");
			return 0;
		}
		if(group_list->hit_count < 1){
			gl_error("Histogram group is an empty set");
			return 0;
		}
		/* non-empty set */

		/* parse complex part of property */
		test_for_complex(tprop, tpart);
	
		while(group_obj = gl_find_next(group_list, group_obj)){
			prop = gl_find_property(group_obj->oclass, property.get_string());
			if(prop == NULL){
				gl_error("Histogram group is unable to find prop '%s' in class '%s' for group '%s'", property.get_string(), group_obj->oclass->name, group.get_string());
				return 0;
			}
			/* check to see if all the group objects are in the same class, allowing us to cache the target property */
			if (oclass == NULL){
				oclass = group_obj->oclass;
				prop_ptr = prop;
			}
			if(oclass != group_obj->oclass){
				prop_ptr = NULL;
			} 
			
		}
	} else { /* if we have a parent, we only focus on that one object */

		test_for_complex(tprop, tpart);

		prop = gl_find_property(parent->oclass, property.get_string());
		
		if(prop == NULL){
			gl_error("Histogram parent '%s' of class '%s' does not contain property '%s'", parent->name ? parent->name : "(anon)", parent->oclass->name, property.get_string());
			return 0;
		} else {
			prop_ptr = prop; /* saved for later */
		}
	}

	// initialize first timesteps
	if(counting_interval > 0.0)
		next_count = gl_globalclock + counting_interval;
	if(sampling_interval > 0.0)
		next_sample = gl_globalclock + sampling_interval;
	/*
	 *	This will create a uniform partition over the specified range
	 */
	if((bin_count > 0) && (min < max))
	{
		int i=0;
		double range = max - min;
		double step = range/bin_count;
		//throw("Histogram bin_count is temporarily disabled.");
		bin_list = (BIN *)gl_malloc(sizeof(BIN) * bin_count);
		if(bin_list == NULL){
			gl_error("Histogram malloc error: unable to alloc %i * %i bytes for %s", bin_count, sizeof(BIN), obj->name ? obj->name : "(anon. histogram)");
			return 0;
		}
		memset(bin_list, 0, sizeof(BIN) * bin_count);
		for(i = 0; i < bin_count; i++){
			bin_list[i].low_val = min + i * step;
			bin_list[i].high_val = bin_list[i].low_val + step;
			bin_list[i].low_inc = 1;
			bin_list[i].high_inc = 0;
		}
		bin_list[i-1].high_inc = 1;	/* tail value capture */
		binctr = (int *)gl_malloc(sizeof(int) * bin_count);
		memset(binctr, 0, sizeof(int) * bin_count);
	}
	else if (bins[0] != 0)
	/*
	 *	This will parse the bin strings as specified.  The valid basic form is "(a..b)".  Brackets are optional, [ & ] are inclusive.  A dash may replace the '..'.
	 *	If a or b is not present, the bin will fill in a positve/negative infinity.
	 */
	{
		char *cptr = bins;
		char bincpy[1025];
		int i = 0;
		bin_count = 1; /* assume at least one */
		/* would be better to count the number of times strtok succeeds, but this should work -mh */
		//while(*cptr != 0){
		for(cptr = bins; *cptr != 0; ++cptr){
			if(*cptr == ',' && cptr[1] != 0){
				++bin_count;
			}
		//	++cptr;
		}
		bin_list = (BIN *)gl_malloc(sizeof(BIN) * bin_count);
		if(bin_list == NULL){
			gl_error("Histogram malloc error: unable to alloc %i * %i bytes for %s", bin_count, sizeof(BIN), obj->name ? obj->name : "(anon. histogram)");
			return 0;
		}
		memset(bin_list, 0, sizeof(BIN) * bin_count);
		memcpy(bincpy, bins, 1024);
		cptr = strtok(bincpy, ",\t\r\n\0");
		if(prop->ptype == PT_complex || prop->ptype == PT_double || prop->ptype == PT_int16 || prop->ptype == PT_int32 || prop->ptype == PT_int64 || prop->ptype == PT_float || prop->ptype == PT_real){
			for(i = 0; i < bin_count && cptr != NULL; ++i){
				if(parse_bin_val(cptr, bin_list+i) == 0){
					gl_error("Histogram unable to parse \'%s\' in %s", cptr, obj->name ? obj->name : "(unnamed histogram)");
					return 0;
				}
				cptr = strtok(NULL, ",\t\r\n\0"); /* minor efficiency gain to use the incremented pointer from parse_bin */
			}
		} else if (prop->ptype == PT_enumeration || prop->ptype == PT_set){
			for(i = 0; i < bin_count && cptr != NULL; ++i){
				if(parse_bin_enum(cptr, bin_list+i, prop) == 0){
					gl_error("Histogram unable to parse \'%s\' in %s", cptr, obj->name ? obj->name : "(unnamed histogram)");
					return 0;
				}
				cptr = strtok(NULL, ",\t\r\n\0"); /* minor efficiency gain to use the incremented pointer from parse_bin */
			}
		}

		if(i < bin_count){
			gl_error("Histrogram encountered a problem parsing bins for %s", obj->name ? obj->name : "(unnamed histogram)");
			return 0;
		}
		binctr = (int *)malloc(sizeof(int) * bin_count);
		memset(binctr, 0, sizeof(int) * bin_count);
	} else {
		gl_error("Histogram has neither bins or a bin range to work with");
		return 0;
	}

	/* open file ~ copied from recorder.c */
		/* if prefix is omitted (no colons found) */
//	if (sscanf(filename,"%32[^:]:%1024[^:]:%[^:]",ftype,fname,flags)==1)
//	{
		/* filename is file by default */
		strcpy(fname,filename);
//		strcpy(ftype,"file");
//	}
	/* if no filename given */
	if (strcmp(fname,"")==0)

		/* use object name-id as default file name */
		sprintf(fname,"%s-%d.%s",obj->parent->oclass->name,obj->parent->id, ftype.get_string());

	/* if type is file or file is stdin */
	tf = get_ftable(mode);
	if(tf == NULL)
		return 0;
	ops = tf->histogram; /* same mentality as a recorder, 'cept for the header properties */
	if(ops == NULL)
		return 0;
	return ops->open(this, fname, flags);
}