Minsky: 3.17.0
minsky::Minsky Class Reference

#include <minsky.h>

Inheritance diagram for minsky::Minsky:
Inheritance graph
Collaboration diagram for minsky::Minsky:
Collaboration graph

Public Types

enum  CmdData { no_command, is_const, is_setterGetter, generic }
 
enum  MemCheckResult { OK, proceed, abort }
 check whether to proceed or abort, given a request to allocate bytes of memory. Implemented in MinskyTCL More...
 
using AvailableOperationsMapping = classdesc::StringKeyMap< std::vector< OperationType::Type > >
 

Public Member Functions

void addNewPublicationTab (const std::string &name)
 
void addCanvasItemToPublicationTab (size_t i)
 
bool multipleEquities () const
 
bool multipleEquities (const bool &m)
 
bool edited () const
 reflects whether the model has been changed since last save More...
 
bool reset_flag () const
 true if reset needs to be called prior to numerical integration More...
 
void markEdited ()
 indicate model has been changed since last saved More...
 
void requestReset ()
 
void requestRedraw ()
 requests a redraw of the curren active tab More...
 
bool resetIfFlagged () override
 checks whether a reset is required, and resets the simulation if so More...
 
void populateMissingDimensions ()
 fills in dimensions table with all loaded ravel axes More...
 
void populateMissingDimensionsFromVariable (const VariableValue &, bool &incompatibleMessageDisplayed)
 populate missing dimensions from a variableValue More...
 
void populateMissingDimensionsFromVariable (const VariableValue &v)
 
void renameDimension (const std::string &oldName, const std::string &newName)
 
void setGodleyIconResource (const string &s)
 
void setGroupIconResource (const string &s)
 
void setLockIconResource (const string &locked, const string &unlocked)
 
void setRavelIconResource (const string &s)
 
std::set< string > matchingTableColumns (const GodleyIcon &currTable, GodleyAssetClass::AssetClass ac)
 
void importDuplicateColumn (GodleyTable &srcTable, int srcCol)
 find any duplicate column, and use it as a source column for balanceDuplicateColumns More...
 
void balanceDuplicateColumns (const GodleyIcon &srcTable, int srcCol)
 makes all duplicated columns consistent with srcTable, srcCol More...
 
std::vector< std::string > allGodleyFlowVars () const
 
 Minsky ()
 
 ~Minsky ()
 
void clearAllMaps (bool clearHistory)
 
void clearAllMaps ()
 
void clearAllMapsTCL ()
 
VariablePtr definingVar (const std::string &valueId) const
 returns reference to variable defining (ie input wired) for valueId More...
 
void saveCanvasItemAsFile (const string &fileName) const
 
void initGodleys ()
 
void cut ()
 erase items in current selection, put copy into clipboard More...
 
void copy () const
 copy items in current selection into clipboard More...
 
void paste ()
 paste clipboard as a new group or ungrouped items on the canvas. canvas.itemFocus is set to refer to the new group or items. More...
 
bool clipboardEmpty () const
 return true if nothing available in clipboard More...
 
void saveSelectionAsFile (const string &fileName) const
 
void insertGroupFromFile (const string &file)
 
void makeVariablesConsistent ()
 
void imposeDimensions ()
 
void garbageCollect ()
 
bool cycleCheck () const
 checks for presence of illegal cycles in network. Returns true if there are some More...
 
void openLogFile (const string &)
 opens the log file, and writes out a header line describing names of all variables More...
 
void closeLogFile ()
 closes log file More...
 
bool loggingEnabled () const
 returns true if logging is in operation More...
 
void constructEquations ()
 construct the equations based on input data More...
 
void dimensionalAnalysis () const
 performs dimension analysis, throws if there is a problem More...
 
void deleteAllUnits ()
 removes units markup from all variables in model More...
 
bool checkEquationOrder () const
 consistency check of the equation order. Should return true. Outputs the operation number of the invalidly ordered operation. More...
 
double deltaT () const
 
void reset ()
 resets the variables back to their initial values More...
 
std::vector< double > step ()
 step the equations (by n steps, default 1) More...
 
void save (const std::string &filename)
 
void load (const std::string &filename)
 load from a file More...
 
void displayErrorItem (const Item &op) const
 indicate operation item has error, if visible, otherwise contining group More...
 
std::string autoSaveFile () const
 name of an auto save file More...
 
void setAutoSaveFile (const std::string &file)
 initialises auto saving empty file to turn off autosave More...
 
void clearHistory ()
 clear history More...
 
void checkPushHistory ()
 called periodically to ensure history up to date More...
 
bool pushHistory ()
 push current model state onto history if it differs from previous More...
 
bool commandHook (const std::string &command, unsigned nargs)
 Executed after each interpreter command to maintain undo/redo stack, edited flag, autosaving etc. More...
 
virtual CmdData getCommandData (const std::string &command) const
 return meta information on a given command More...
 
long undo (int changes=1)
 restore model to state changes ago More...
 
void convertVarType (const std::string &name, VariableType::Type type)
 Converts variable(s) named by name into a variable of type type. More...
 
void addIntegral ()
 add integral to current canvas item (which must be variable convertible to an integral variable More...
 
bool inputWired (const std::string &name) const
 returns true if any variable of name name has a wired input More...
 
void renderCanvasToPS (const std::string &filename)
 render canvas to a postscript file More...
 
void renderCanvasToPDF (const std::string &filename)
 render canvas to a PDF file More...
 
void renderCanvasToSVG (const std::string &filename)
 render canvas to an SVG file More...
 
void renderCanvasToPNG (const std::string &filename)
 render canvas to a PNG image file More...
 
void renderCanvasToPNG (const std::string &filename, const Canvas::ZoomCrop &z)
 Render canvas to a PNG file filename, scaling the canvas temporarily by zoom, shifts it to left, top, and crops to width, height (in ZoomCrop struct). More...
 
void renderCanvasToEMF (const std::string &filename)
 render canvas to a EMF image file (Windows only) More...
 
void renderAllPlotsAsSVG (const string &prefix) const
 render all plots More...
 
void exportAllPlotsAsCSV (const string &prefix) const
 export all plots More...
 
void setAllDEmode (bool)
 set DE mode on all godley tables More...
 
void srand (int seed)
 set std library RNG seed More...
 
void setGodleyDisplayValue (bool displayValues, GodleyTable::DisplayStyle displayStyle)
 set display value mode on all godley table editor modes More...
 
void importVensim (const std::string &)
 import a Vensim file More...
 
void redrawAllGodleyTables ()
 request all Godley table windows to redraw More...
 
virtual void setBusyCursor ()
 set/clear busy cursor in GUI More...
 
virtual void clearBusyCursor ()
 
virtual void progress (const std::string &title, int)
 set progress bar, out of 100, labelling the progress bar with title More...
 
virtual void bookmarkRefresh ()
 refresh the bookmark menu after changes More...
 
virtual void resetScroll ()
 reset main window scroll bars after model has been panned More...
 
virtual void message (const std::string &)
 display a message in a popup box on the GUI More...
 
virtual void runItemDeletedCallback (const Item &)
 run callback attached to item More...
 
virtual MemCheckResult checkMemAllocation (size_t bytes) const
 
vector< string > listFonts () const
 
void latex (const std::string &filename, bool wrapLaTeXLines)
 
void matlab (const std::string &filename)
 
string latex2pango (const std::string &x)
 
void autoLayout ()
 auto layout current open group and recentre More...
 
void randomLayout ()
 randomly layout current open group and recentre reinitialises canvas to the group located in item More...
 
void openGroupInCanvas ()
 
void openModelInCanvas ()
 reinitialises canvas to the toplevel group More...
 
void listAllInstances ()
 
void nameCurrentItem (const std::string &name)
 
void itemFromNamedItem (const std::string &name)
 
bool triggerCheckMemAllocationCallback () const
 trigger checkMem callback for testing purposes More...
 
char getc () const
 Used to implement a pause until return pressed for attaching debugger purposes. More...
 
void setDefinition (const std::string &valueId, const std::string &definition)
 add/replace a definition for a flow variable given by valueId More...
 
void reloadAllCSVParameters ()
 reload all CSV parameters from latest values in files. More...
 
void pushFlags ()
 push and pop state of the flags More...
 
void popFlags ()
 push and pop state of the flags More...
 
- Public Member Functions inherited from minsky::RungeKutta
virtual ~RungeKutta ()=default
 
void rkreset ()
 reset the simulation More...
 
void rkstep ()
 step the equations (by n steps, default 1) evaluate the flow equations without stepping. More...
 
void evalEquations ()
 

Static Public Member Functions

static void saveGroupAsFile (const Group &, const string &fileName)
 
static void exportSchema (const std::string &filename, int schemaLevel=1)
 
static std::string ecolabVersion ()
 
static std::string ravelVersion ()
 
static bool ravelAvailable ()
 
static bool ravelExpired ()
 
static int daysUntilRavelExpires ()
 
static std::size_t physicalMem ()
 returns amount of memory installed on system More...
 
static int numOpArgs (OperationType::Type o)
 
static OperationType::Group classifyOp (OperationType::Type o)
 
static std::vector< std::string > availableOperations ()
 list of available operations More...
 
static Minsky::AvailableOperationsMapping availableOperationsMapping ()
 
static std::vector< std::string > variableTypes ()
 list of available variable types More...
 
static std::vector< std::string > assetClasses ()
 return list of available asset classes More...
 
static std::string defaultFont ()
 the default used by Pango More...
 
static std::string defaultFont (const std::string &x)
 the default used by Pango More...
 
static double fontScale ()
 an extra scaling factor of Pango fonts More...
 
static double fontScale (double)
 an extra scaling factor of Pango fonts More...
 

Public Attributes

PannableTab< EquationDisplayequationDisplay
 
FontDisplay fontSampler
 
PhillipsDiagram phillipsDiagram
 
std::vector< PubTabpublicationTabs
 
VariableValues variableValues
 
Dimensions dimensions
 
Conversions conversions
 
std::map< Units, double > maxValue
 stash the maximum absolute value obtained by a dimensioned quantity More...
 
std::map< Units, double > maxFlowValue
 
SVGRenderer histogramResource
 
Exclude< std::map< std::string, std::shared_ptr< CallableFunction > > > userFunctions
 
GroupPtr model {new Group}
 
Canvas canvas {model}
 
std::set< string > logVarList
 set of variables (valueIds) to log More...
 
double lastT {0}
 previous timestep More...
 
int numBackups =1
 number of previous versions of saved files to keep save to a file More...
 
std::string fileVersion
 Minsky version file was saved under. More...
 
unsigned maxHistory {100}
 maximum no. of history states to save More...
 
int maxWaitMS =100
 maximum wait in millisecond between redrawing canvas during simulation More...
 
bool doPushHistory =true
 flag to indicate whether a TCL should be pushed onto the history stack, or logged in a recording. This is used to avoid movements being added to recordings and undo history More...
 
bool displayValues =false
 
GodleyTable::DisplayStyle displayStyle =GodleyTable::sign
 
std::shared_ptr< VariableInstanceListvariableInstanceList
 supports navigation to all instances of current variable More...
 
std::map< std::string, std::weak_ptr< Item > > namedItems
 
VariablePane variablePane
 
- Public Attributes inherited from minsky::RungeKutta
double t {0}
 time More...
 
bool running =false
 controls whether simulation is running More...
 
bool reverse =false
 reverse direction of simulation More...
 
EvalGodley evalGodley
 
- Public Attributes inherited from minsky::Simulation
double stepMin {0}
 
double stepMax {0.01}
 
int nSteps {1}
 
double epsRel {1e-2}
 
double epsAbs {1e-3}
 
int order {4}
 
bool implicit {false}
 
int simulationDelay {0}
 
std::string timeUnit
 
double tmax {INFINITY}
 
double t0 {0}
 

Static Public Attributes

static const std::string minskyVersion =MINSKY_VERSION
 
- Static Public Attributes inherited from minsky::ValueVector
static std::vector< double, CIVITA_ALLOCATOR< double > > stockVars
 vector of variables that are integrated via Runge-Kutta. These variables label the columns of the Godley table More...
 
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
 variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table More...
 

Private Member Functions

 CLASSDESC_ACCESS (Minsky)
 
std::string diagnoseNonFinite () const
 returns a diagnostic about an item that is infinite or NaN. Either a variable name, or and operator type. More...
 
void logVariables () const
 write current state of all variables to the log file More...
 
void balanceColumns (const GodleyIcon &srcGodley, int srcCol, GodleyIcon &destGodley, int destCol) const
 balance two Godley columns More...
 
void removeItems (Wire &wire)
 remove the definition network from wire, up to, but not including attached variables. More...
 

Private Attributes

Exclude< ptime > lastRedraw
 
bool m_multipleEquities =false
 

Additional Inherited Members

- Protected Member Functions inherited from minsky::RungeKutta
void evalEquations (double result[], double, const double vars[])
 
void evalJacobian (Matrix &, double, const double vars[])
 
- Static Protected Member Functions inherited from minsky::RungeKutta
static int RKfunction (double, const double y[], double f[], void *)
 function to be integrated (internal use) More...
 
static int jacobian (double, const double y[], double *, double dfdt[], void *)
 compute jacobian (internal use) More...
 

Detailed Description

Definition at line 119 of file minsky.h.

Member Typedef Documentation

◆ AvailableOperationsMapping

using minsky::Minsky::AvailableOperationsMapping = classdesc::StringKeyMap<std::vector<OperationType::Type> >

Definition at line 496 of file minsky.h.

Member Enumeration Documentation

◆ CmdData

Enumerator
no_command 
is_const 
is_setterGetter 
generic 

Definition at line 362 of file minsky.h.

◆ MemCheckResult

check whether to proceed or abort, given a request to allocate bytes of memory. Implemented in MinskyTCL

Enumerator
OK 
proceed 
abort 

Definition at line 449 of file minsky.h.

Constructor & Destructor Documentation

◆ Minsky()

minsky::Minsky::Minsky ( )
inline

Definition at line 229 of file minsky.h.

229  :
230  equationDisplay(*this) {
231  lastRedraw=boost::posix_time::microsec_clock::local_time();
232  model->iHeight(std::numeric_limits<float>::max());
233  model->iWidth(std::numeric_limits<float>::max());
234  model->self=model;
235  publicationTabs.emplace_back("Publication");
236  }
PannableTab< EquationDisplay > equationDisplay
Definition: minsky.h:141
Exclude< ptime > lastRedraw
Definition: minsky.h:130
std::vector< PubTab > publicationTabs
Definition: minsky.h:144
GroupPtr model
Definition: minsky.h:242

◆ ~Minsky()

minsky::Minsky::~Minsky ( )

Definition at line 119 of file minsky.cc.

References minsky::remove().

120  {
121  if (edited() && autoSaver)
122  // if we're at this point, then the user has already been asked to save, and chosen no.
123  boost::filesystem::remove(autoSaver->fileName);
124  }
bool edited() const
reflects whether the model has been changed since last save
Definition: minsky.h:157
void remove(std::vector< T > &x, const V &v)
remove an element from a vector. V must be comparable to a T
Definition: str.h:89
Here is the call graph for this function:

Member Function Documentation

◆ addCanvasItemToPublicationTab()

void minsky::Minsky::addCanvasItemToPublicationTab ( size_t  i)
inline

Definition at line 147 of file minsky.h.

147  {
148  if (canvas.item && i<publicationTabs.size())
149  publicationTabs[i].items.emplace_back(canvas.item);
150  }
std::vector< PubTab > publicationTabs
Definition: minsky.h:144
Canvas canvas
Definition: minsky.h:243
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ addIntegral()

void minsky::Minsky::addIntegral ( )

add integral to current canvas item (which must be variable convertible to an integral variable

Definition at line 1526 of file minsky.cc.

References minsky::Item::moveTo().

1527  {
1528  if (auto v=canvas.item->variableCast())
1529  if (auto g=v->group.lock())
1530  {
1531  // nb throws if conversion cannot be performed
1532  convertVarType(v->valueId(),VariableType::integral);
1533  auto integ=new IntOp;
1534  g->addItem(integ);
1535  integ->moveTo(canvas.item->x(), canvas.item->y());
1536  // remove intVar from its group
1537  if (auto g=integ->intVar->group.lock())
1538  g->removeItem(*integ->intVar);
1539  integ->intVar=dynamic_pointer_cast<VariableBase>(canvas.item);
1540  integ->toggleCoupled();
1541 
1543  }
1544  }
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
void convertVarType(const std::string &name, VariableType::Type type)
Converts variable(s) named by name into a variable of type type.
Definition: minsky.cc:1456
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175
Here is the call graph for this function:

◆ addNewPublicationTab()

void minsky::Minsky::addNewPublicationTab ( const std::string &  name)
inline

Definition at line 146 of file minsky.h.

146 {publicationTabs.emplace_back(name);}
std::vector< PubTab > publicationTabs
Definition: minsky.h:144

◆ allGodleyFlowVars()

vector< string > minsky::Minsky::allGodleyFlowVars ( ) const

Definition at line 819 of file minsky.cc.

820  {
821  set<string> r;
822  model->recursiveDo(&GroupItems::items, [&](const Items&, Items::const_iterator i) {
823  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
824  {
825  auto flowVars=g->table.getVariables();
826  r.insert(flowVars.begin(),flowVars.end());
827  }
828  return false;
829  });
830  return {r.begin(),r.end()};
831  }
std::vector< ItemPtr > Items
Definition: item.h:360
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table
GroupPtr model
Definition: minsky.h:242

◆ assetClasses()

vector< string > minsky::Minsky::assetClasses ( )
static

return list of available asset classes

Definition at line 1609 of file minsky.cc.

1610  {return enumVals<GodleyTable::AssetClass>();}

◆ autoLayout()

void minsky::Minsky::autoLayout ( )

auto layout current open group and recentre

Definition at line 1624 of file minsky.cc.

1625  {
1626  canvas.model->autoLayout();
1627  canvas.recentre();
1628  }
void recentre()
adjust canvas so that -ve coordinates appear on canvas
Definition: canvas.cc:929
Model model
Definition: canvas.h:103
Canvas canvas
Definition: minsky.h:243

◆ autoSaveFile()

std::string minsky::Minsky::autoSaveFile ( ) const
inline

name of an auto save file

Definition at line 343 of file minsky.h.

343 {return autoSaver? autoSaver->fileName: std::string();}

◆ availableOperations()

vector< string > minsky::Minsky::availableOperations ( )
static

list of available operations

Definition at line 1605 of file minsky.cc.

1606  {return enumVals<OperationType::Type>();}

◆ availableOperationsMapping()

Minsky::AvailableOperationsMapping minsky::Minsky::availableOperationsMapping ( )
static

Definition at line 1612 of file minsky.cc.

References minsky::op.

1613  {
1616  {
1617  if (classifyOp(op)==OperationType::general) continue;
1618  if (op==OperationType::copy) continue;
1619  r[classdesc::to_string(classifyOp(op))].push_back(op);
1620  }
1621  return r;
1622  }
static OperationType::Group classifyOp(OperationType::Type o)
Definition: minsky.h:481
classdesc::StringKeyMap< std::vector< OperationType::Type > > AvailableOperationsMapping
Definition: minsky.h:496

◆ balanceColumns()

void minsky::Minsky::balanceColumns ( const GodleyIcon srcGodley,
int  srcCol,
GodleyIcon destGodley,
int  destCol 
) const
private

balance two Godley columns

Definition at line 644 of file minsky.cc.

References minsky::FlowCoef::coef, minsky::GodleyIcon::flowSignature(), minsky::FlowCoef::name, minsky::scope(), minsky::FlowCoef::str(), minsky::GodleyIcon::table, minsky::trimWS(), minsky::uqName(), and minsky::GodleyIcon::valueId().

645  {
646  auto& srcTable=srcGodley.table;
647  auto& destTable=destGodley.table;
648  // reverse lookup tables for mapping flow variable to destination row numbers via row labels
649  map<string,string> srcRowLabels;
650  map<string, int> destRowLabels;
651  set<string> uniqueSrcRowLabels; // check for uniqueness of source row labels
652  for (size_t row=1; row!=srcTable.rows(); ++row)
653  if (!srcTable.initialConditionRow(row) && !srcTable.cell(row,0).empty() &&
654  !srcTable.cell(row,srcCol).empty())
655  {
656  if (!uniqueSrcRowLabels.insert(srcTable.cell(row,0)).second)
657  throw runtime_error("Duplicate source row label: "+srcTable.cell(row,0));
658  const FlowCoef fc(srcTable.cell(row,srcCol));
659  if (!fc.name.empty())
660  srcRowLabels[srcGodley.valueId(fc.name)]=
661  trimWS(srcTable.cell(row,0));
662  }
663  else if (srcTable.initialConditionRow(row))
664  // copy directly into destination initial condition,
665  for (size_t r=1; r<destTable.rows(); ++r)
666  if (destTable.initialConditionRow(r))
667  destTable.cell(r,destCol)=srcTable.cell(row,srcCol);
668  for (size_t row=1; row!=destTable.rows(); ++row)
669  if (!destTable.initialConditionRow(row) && !destTable.cell(row,0).empty())
670  destRowLabels[trimWS(destTable.cell(row,0))]=row;
671 
672 
673  // compute column signature for both src and destination columns
674  map<string,double> srcFlows=srcGodley.flowSignature(srcCol),
675  destFlows=destGodley.flowSignature(destCol);
676  // items to add
677  for (map<string,double>::iterator i=srcFlows.begin(); i!=srcFlows.end(); ++i)
678  if (i->second != destFlows[i->first])
679  {
680  const int scope=-1;
681  if (i->first.find(':')!=string::npos)
682  minsky::scope(i->first);
683  FlowCoef df;
684  if (scope==-1 || !variableValues.count(i->first))
685  df.name=uqName(i->first);
686  else
687  df.name=variableValues[i->first]->name;
688  df.coef=i->second-destFlows[i->first];
689  if (df.coef==0) continue;
690  const string flowEntry=df.str();
691  const string rowLabel=srcRowLabels[srcGodley.valueId(i->first)];
692  const map<string,int>::iterator dr=destRowLabels.find(rowLabel);
693  if (dr!=destRowLabels.end())
694  if (FlowCoef(destTable.cell(dr->second, destCol)).coef==0)
695  destTable.cell(dr->second, destCol) = flowEntry;
696  else
697  // add a new blank labelled flow line
698  {
699  destTable.resize(destTable.rows()+1,destTable.cols());
700  destTable.cell(destTable.rows()-1, destCol) = flowEntry;
701  }
702  else
703  // labels don't match, so add a new labelled line
704  {
705  destTable.resize(destTable.rows()+1,destTable.cols());
706  destTable.cell(destTable.rows()-1, 0) = rowLabel;
707  destRowLabels[rowLabel] = destTable.rows()-1;
708  destTable.cell(destTable.rows()-1, destCol) = flowEntry;
709  }
710  }
711  // items to delete
712  set<size_t> rowsToDelete;
713  for (map<string,double>::iterator i=destFlows.begin(); i!=destFlows.end(); ++i)
714  if (i->second!=0 && srcFlows[i->first]==0)
715  for (size_t row=1; row<destTable.rows(); ++row)
716  {
717  FlowCoef fc(destTable.cell(row, destCol));
718  if (!fc.name.empty())
719  fc.name=destGodley.valueId(fc.name);
720  if (fc.name==destGodley.valueId(i->first))
721  {
722  destTable.cell(row, destCol).clear();
723  // if this leaves an empty row, delete entire row
724  for (size_t c=0; c<destTable.cols(); ++c)
725  if (!destTable.cell(row, c).empty())
726  goto rowNotEmpty;
727  rowsToDelete.insert(row);
728  rowNotEmpty:;
729  }
730  }
731  // amalgamate unlabelled rows with singular value
732  map<string,double> unlabelledSigs;
733  for (size_t row=1; row<destTable.rows(); ++row)
734  {
735  if (!destTable.singularRow(row, destCol)) continue;
736  const FlowCoef fc(destTable.cell(row, destCol));
737  unlabelledSigs[fc.name]+=fc.coef;
738  rowsToDelete.insert(row);
739  }
740  // append amalgamated rows
741  for (auto& i: unlabelledSigs)
742  if (i.second!=0)
743  {
744  destTable.insertRow(destTable.rows());
745  destTable.cell(destTable.rows()-1,destCol)=FlowCoef(i.second,i.first).str();
746  }
747 
748  for (auto row=rowsToDelete.rbegin(); row!=rowsToDelete.rend(); ++row)
749  destTable.deleteRow(*row);
750  }
VariableValues variableValues
Definition: minsky.h:188
size_t scope(const string &name)
extract scope from a qualified variable name
Definition: valueId.cc:83
std::string uqName(const std::string &name)
extract unqualified portion of name
Definition: valueId.cc:135
std::string trimWS(const std::string &s)
Definition: str.h:49
Here is the call graph for this function:

◆ balanceDuplicateColumns()

void minsky::Minsky::balanceDuplicateColumns ( const GodleyIcon srcTable,
int  srcCol 
)

makes all duplicated columns consistent with srcTable, srcCol

Definition at line 752 of file minsky.cc.

References minsky::GodleyTable::assetClass(), minsky::GodleyTable::cell(), minsky::GodleyTable::cols(), minsky::GodleyIcon::table, minsky::trimWS(), and minsky::GodleyIcon::valueId().

Referenced by minsky::GodleyIcon::deleteRow(), minsky::GodleyTableEditor::mouseUp(), minsky::GodleyIcon::setCell(), and minsky::GodleyTableEditor::update().

753  {
754  const GodleyTable& srcTable=srcGodley.table;
755  if (srcCol<0 || size_t(srcCol)>=srcTable.cols()) return;
756  // find if there is a matching column
757  const string& colName=srcGodley.valueId(trimWS(srcTable.cell(0,srcCol)));
758  if (colName.empty() || colName==":_") return; //ignore blank columns
759 
760  bool matchFound=false;
761  model->recursiveDo
762  (&Group::items,
763  [&](Items& m, Items::iterator i)
764  {
765  if (auto gi=dynamic_cast<GodleyIcon*>(i->get()))
766  {
767  if (&gi->table==&srcTable) // if source table, then check for duplicated asset/equity columns
768  {
769  for (size_t col=1; col<gi->table.cols(); col++)
770  if (col==size_t(srcCol)) continue; // skip over source column
771  else if (srcGodley.valueId(trimWS(srcTable.cell(0,col)))==colName)
772  {
773  switch (srcGodley.table.assetClass(srcCol))
774  {
776  if (srcTable.assetClass(col)!=GodleyAssetClass::equity)
777  throw error("asset column %s matches a non-liability column",colName.c_str());
778  break;
780  if (srcTable.assetClass(col)!=GodleyAssetClass::asset)
781  throw error("equity column %s matches a non-asset column",colName.c_str());
782  break;
783  default:
784  throw error("invalid asset class for duplicate column %s",colName.c_str());
785  }
786  balanceColumns(srcGodley, srcCol, *gi, col);
787  }
788  }
789  else // match asset/liability columns on different Godley tables
790  for (size_t col=1; col<gi->table.cols(); col++)
791  if (gi->valueId(trimWS(gi->table.cell(0,col)))==colName) // we have a match
792  {
793  // checks asset class rules
794  switch (srcGodley.table.assetClass(srcCol))
795  {
797  if (gi->table.assetClass(col)!=GodleyAssetClass::liability)
798  throw error("asset column %s matches a non-liability column",colName.c_str());
799  break;
801  if (gi->table.assetClass(col)!=GodleyAssetClass::asset)
802  throw error("liability column %s matches a non-asset column",colName.c_str());
803  break;
804  default:
805  throw error("invalid asset class for duplicate column %s",colName.c_str());
806  }
807 
808  // checks that nom more than two duplicated columns exist
809  if (matchFound)
810  throw error("more than one duplicated column detected for %s",colName.c_str());
811  matchFound=true;
812  balanceColumns(srcGodley, srcCol, *gi, col);
813  }
814  }
815  return false;
816  }); // TODO - this lambda is FAR too long!
817  }
void balanceColumns(const GodleyIcon &srcGodley, int srcCol, GodleyIcon &destGodley, int destCol) const
balance two Godley columns
Definition: minsky.cc:644
std::vector< ItemPtr > Items
Definition: item.h:360
std::string trimWS(const std::string &s)
Definition: str.h:49
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:
Here is the caller graph for this function:

◆ bookmarkRefresh()

virtual void minsky::Minsky::bookmarkRefresh ( )
inlinevirtual

refresh the bookmark menu after changes

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 436 of file minsky.h.

Referenced by minsky::GroupItems::addItem(), minsky::Item::adjustBookmark(), minsky::Group::deleteItem(), and minsky::Canvas::openGroupInCanvas().

436 {}
Here is the caller graph for this function:

◆ checkEquationOrder()

bool minsky::Minsky::checkEquationOrder ( ) const

consistency check of the equation order. Should return true. Outputs the operation number of the invalidly ordered operation.

Definition at line 1176 of file minsky.cc.

References minsky::op.

1177  {
1178  ecolab::array<bool> fvInit(flowVars.size(), false);
1179  // firstly, find all flowVars that are constants
1180  for (auto& v: variableValues)
1181  if (!inputWired(v.first) && v.second->idx()>=0)
1182  fvInit[v.second->idx()]=true;
1183 
1184  for (auto& e: equations)
1185  if (auto eo=dynamic_cast<const ScalarEvalOp*>(e.get()))
1186  {
1187  if (eo->out < 0|| (eo->numArgs()>0 && eo->in1.empty()) ||
1188  (eo->numArgs() > 1 && eo->in2.empty()))
1189  {
1190  return false;
1191  }
1192  switch (eo->numArgs())
1193  {
1194  case 0:
1195  fvInit[eo->out]=true;
1196  break;
1197  case 1:
1198  fvInit[eo->out]=!eo->flow1 || fvInit[eo->in1[0]];
1199  break;
1200  case 2:
1201  // we need to check if an associated binary operator has
1202  // an unwired input, and if so, treat its input as
1203  // initialised, since it has already been initialised in
1204  // getInputFromVar()
1205  if (auto op=eo->state)
1206  switch (op->type())
1207  {
1210  fvInit[eo->in1[0]] |= op->ports(1).lock()->wires().empty();
1211  fvInit[eo->in2[0][0].idx] |= op->ports(3).lock()->wires().empty();
1212  break;
1213  default: break;
1214  }
1215 
1216  fvInit[eo->out]=
1217  (!eo->flow1 || fvInit[eo->in1[0]]) && (!eo->flow2 || fvInit[eo->in2[0][0].idx]);
1218  break;
1219  default: break;
1220  }
1221  // if (!fvInit[eo.out])
1222  // cerr << "Operation "<<opIdOfEvalOp(eo)<<" out of order"<<endl;
1223  }
1224 
1225  return all(fvInit);
1226  }
bool inputWired(const std::string &name) const
returns true if any variable of name name has a wired input
Definition: minsky.h:385
VariableValues variableValues
Definition: minsky.h:188
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table

◆ checkMemAllocation()

virtual MemCheckResult minsky::Minsky::checkMemAllocation ( size_t  bytes) const
inlinevirtual

Definition at line 450 of file minsky.h.

450 {return OK;}

◆ checkPushHistory()

void minsky::Minsky::checkPushHistory ( )
inline

called periodically to ensure history up to date

Definition at line 351 of file minsky.h.

351 {if (historyPtr==history.size()) pushHistory();}
bool pushHistory()
push current model state onto history if it differs from previous
Definition: minsky.cc:1264

◆ CLASSDESC_ACCESS()

minsky::Minsky::CLASSDESC_ACCESS ( Minsky  )
private

◆ classifyOp()

static OperationType::Group minsky::Minsky::classifyOp ( OperationType::Type  o)
inlinestatic

Definition at line 481 of file minsky.h.

References minsky::OperationType::classify().

481 {return OperationType::classify(o);}
static Group classify(Type t)
Here is the call graph for this function:

◆ clearAllMaps() [1/2]

void minsky::Minsky::clearAllMaps ( bool  clearHistory)

Definition at line 126 of file minsky.cc.

127  {
128  model->clear();
130  equations.clear();
131  integrals.clear();
134  maxValue.clear();
135  PhillipsFlow::maxFlow.clear();
136  PhillipsStock::maxStock.clear();
138  publicationTabs.clear();
139  publicationTabs.emplace_back("Publication");
140  userFunctions.clear();
142 
143  flowVars.clear();
144  stockVars.clear();
145 
146  dimensions.clear();
147  namedItems.clear();
148  flags=reset_needed|fullEqnDisplay_needed;
150  if (doClearHistory) clearHistory();
151  }
static std::vector< double, CIVITA_ALLOCATOR< double > > stockVars
vector of variables that are integrated via Runge-Kutta. These variables label the columns of the God...
VariableValues variableValues
Definition: minsky.h:188
void update()
update variables from model, using previous height value
Definition: variablePane.cc:89
std::map< Units, double > maxValue
stash the maximum absolute value obtained by a dimensioned quantity
Definition: minsky.h:192
static std::map< Units, double > maxFlow
void openGroupInCanvas(const ItemPtr &item)
reinitialises canvas to the group located in item
Definition: canvas.cc:694
static std::map< Units, double > maxStock
VariablePane variablePane
Definition: minsky.h:523
std::vector< PubTab > publicationTabs
Definition: minsky.h:144
Canvas canvas
Definition: minsky.h:243
static const std::string minskyVersion
Definition: minsky.h:323
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table
Exclude< std::map< std::string, std::shared_ptr< CallableFunction > > > userFunctions
Definition: minsky.h:240
std::map< std::string, std::weak_ptr< Item > > namedItems
Definition: minsky.h:515
PhillipsDiagram phillipsDiagram
Definition: minsky.h:143
GroupPtr model
Definition: minsky.h:242
Dimensions dimensions
Definition: minsky.h:189
std::string fileVersion
Minsky version file was saved under.
Definition: minsky.h:337
void clearHistory()
clear history
Definition: minsky.h:349

◆ clearAllMaps() [2/2]

void minsky::Minsky::clearAllMaps ( )
inline

Definition at line 246 of file minsky.h.

References clearAllMaps().

Referenced by clearAllMaps().

246 {clearAllMaps(true);}
void clearAllMaps()
Definition: minsky.h:246
Here is the call graph for this function:
Here is the caller graph for this function:

◆ clearAllMapsTCL()

void minsky::Minsky::clearAllMapsTCL ( )
inline

Definition at line 248 of file minsky.h.

248 {clearAllMaps(true);}
void clearAllMaps()
Definition: minsky.h:246

◆ clearBusyCursor()

virtual void minsky::Minsky::clearBusyCursor ( )
inlinevirtual

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 431 of file minsky.h.

431 {}

◆ clearHistory()

void minsky::Minsky::clearHistory ( )
inline

clear history

Definition at line 349 of file minsky.h.

349 {history.clear(); historyPtr=0;}

◆ clipboardEmpty()

bool minsky::Minsky::clipboardEmpty ( ) const
inline

return true if nothing available in clipboard

Definition at line 267 of file minsky.h.

267 {return clipboard.getClipboard().empty();}

◆ closeLogFile()

void minsky::Minsky::closeLogFile ( )
inline

closes log file

Definition at line 287 of file minsky.h.

287 {outputDataFile.reset();}

◆ commandHook()

bool minsky::Minsky::commandHook ( const std::string &  command,
unsigned  nargs 
)

Executed after each interpreter command to maintain undo/redo stack, edited flag, autosaving etc.

Parameters
command'.' separated command
nargsnumber of arguments
Returns
whether to save the command when recording events

Definition at line 1325 of file minsky.cc.

Referenced by minsky::RESTMinsky::commandHook().

1326  {
1327  static const set<string> constableCommands={ // commands that should not trigger the edit flag
1328  "minsky.availableOperations",
1329  "minsky.canvas.displayDelayedTooltip",
1330  "minsky.canvas.findVariableDefinition",
1331  "minsky.canvas.focusFollowsMouse",
1332  "minsky.canvas.moveTo",
1333  "minsky.canvas.model.moveTo",
1334  "minsky.canvas.model.zoom",
1335  /* we record mouse movements, but filter from history */
1336  "minsky.canvas.mouseDown",
1337  "minsky.canvas.mouseMove",
1338  "minsky.canvas.position",
1339  "minsky.canvas.recentre",
1340  "minsky.canvas.select",
1341  "minsky.canvas.selectVar",
1342  "minsky.canvas.scaleFactor",
1343  "minsky.canvas.zoom",
1344  "minsky.canvas.zoomToFit",
1345  "minsky.histogramResource.setResource",
1346  "minsky.model.moveTo",
1347  "minsky.clearAllMaps",
1348  "minsky.doPushHistory",
1349  "minsky.fontScale",
1350  "minsky.load",
1351  "minsky.model.zoom",
1352  "minsky.multipleEquities",
1353  "minsky.openGroupInCanvas",
1354  "minsky.openModelInCanvas",
1355  "minsky.popFlags",
1356  "minsky.pushFlags",
1357  "minsky.pushHistory",
1358  "minsky.redrawAllGodleyTables",
1359  "minsky.reverse",
1360  "minsky.running",
1361  "minsky.save",
1362  "minsky.select",
1363  "minsky.selectVar",
1364  "minsky.setGodleyDisplayValue",
1365  "minsky.setGodleyIconResource",
1366  "minsky.setGroupIconResource",
1367  "minsky.setLockIconResource",
1368  "minsky.setRavelIconResource",
1369  "minsky.setAutoSaveFile",
1370  "minsky.step",
1371  "minsky.undo"
1372  };
1373  if (doPushHistory && !constableCommands.contains(command) &&
1374  command.find("minsky.phillipsDiagram")==string::npos &&
1375  command.find("minsky.equationDisplay")==string::npos &&
1376  command.find("minsky.publicationTabs")==string::npos &&
1377  command.find(".renderFrame")==string::npos &&
1378  command.find(".requestRedraw")==string::npos &&
1379  command.find(".backgroundColour")==string::npos &&
1380  command.find(".get")==string::npos &&
1381  command.find(".@elem")==string::npos &&
1382  command.find(".mouseFocus")==string::npos
1383  )
1384  {
1385  auto t=getCommandData(command);
1386  if (t==generic || (t==is_setterGetter && nargs>0))
1387  {
1388  const bool modelChanged=pushHistory();
1389  if (modelChanged && command.find(".keyPress")==string::npos)
1390  {
1391  markEdited();
1392  }
1393  return modelChanged;
1394  }
1395  }
1396  return command=="minsky.canvas.requestRedraw" || command=="minsky.canvas.mouseDown" || command=="minsky.canvas.mouseMove" || command.find(".get")!=string::npos;
1397  }
bool pushHistory()
push current model state onto history if it differs from previous
Definition: minsky.cc:1264
void markEdited()
indicate model has been changed since last saved
Definition: minsky.h:161
virtual CmdData getCommandData(const std::string &command) const
return meta information on a given command
Definition: minsky.h:365
bool doPushHistory
flag to indicate whether a TCL should be pushed onto the history stack, or logged in a recording...
Definition: minsky.h:370
double t
time
Definition: rungeKutta.h:57
Here is the caller graph for this function:

◆ constructEquations()

void minsky::Minsky::constructEquations ( )

construct the equations based on input data

Exceptions
ecolab::errorif the data is inconsistent

Definition at line 392 of file minsky.cc.

References minsky::canonicalName(), f, MathDAG::SystemOfEquations::populateEvalOpVector(), minsky::timeUnit, MathDAG::SystemOfEquations::updatePortVariableValue(), and minsky::valueIdFromScope().

393  {
394  if (cycleCheck()) throw error("cyclic network detected");
395 
396  const ProgressUpdater pu(progressState,"Construct equations",8);
397  garbageCollect();
398  equations.clear();
399  integrals.clear();
400  ++progressState;
401 
402  // add all user defined functions to the global symbol tables
403  userFunctions.clear();
404  model->recursiveDo
405  (&Group::items,
406  [this](const Items&, Items::const_iterator it){
407  if (auto f=dynamic_pointer_cast<CallableFunction>(*it))
408  userFunctions[valueIdFromScope((*it)->group.lock(), canonicalName(f->name()))]=f;
409  return false;
410  });
411  ++progressState;
412  model->recursiveDo
413  (&Group::groups,
414  [this](const Groups&, Groups::const_iterator it){
415  userFunctions[valueIdFromScope((*it)->group.lock(), canonicalName((*it)->name()))]=*it;
416  return false;
417  });
418  ++progressState;
419 
421 
422  MathDAG::SystemOfEquations system(*this);
423  ++progressState;
424  assert(variableValues.validEntries());
425  system.populateEvalOpVector(equations, integrals);
426  ++progressState;
427  assert(variableValues.validEntries());
428  system.updatePortVariableValue(equations);
429  }
function f
Definition: canvas.m:1
bool validEntries() const
checks that all entry names are valid
VariableValues variableValues
Definition: minsky.h:188
std::string timeUnit
Definition: simulation.h:35
std::vector< ItemPtr > Items
Definition: item.h:360
std::vector< GroupPtr > Groups
Definition: group.h:52
void garbageCollect()
Definition: minsky.cc:374
string canonicalName(const string &name)
convert a raw name into a canonical name - this is not idempotent.
Definition: valueId.cc:63
bool cycleCheck() const
checks for presence of illegal cycles in network. Returns true if there are some
Definition: minsky.cc:1158
Groups groups
Definition: group.h:77
Exclude< std::map< std::string, std::shared_ptr< CallableFunction > > > userFunctions
Definition: minsky.h:240
string valueIdFromScope(const GroupPtr &scope, const std::string &name)
value Id from scope and canonical name name
Definition: valueId.cc:128
GroupPtr model
Definition: minsky.h:242
static std::string timeUnit
Definition: evalOp.h:50
Here is the call graph for this function:

◆ convertVarType()

void minsky::Minsky::convertVarType ( const std::string &  name,
VariableType::Type  type 
)

Converts variable(s) named by name into a variable of type type.

Exceptions
ifconversion is disallowed

Definition at line 1456 of file minsky.cc.

References minsky::isValueId(), and minsky::var.

Referenced by minsky::IntOp::description(), minsky::VariableBase::retype(), and minsky::GodleyIcon::updateVars().

1457  {
1458  assert(isValueId(name));
1459  const VariableValues::iterator i=variableValues.find(name);
1460  if (i==variableValues.end())
1461  throw error("variable %s doesn't exist",name.c_str());
1462  if (i->second->type()==type) return; // nothing to do!
1463 
1464  string newName=name; // useful for checking flows and stocks with same name and renaming them as the case may be. for ticket 1272
1465  model->recursiveDo
1467  [&](const Items&,Items::const_iterator i)
1468  {
1469  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
1470  {
1471  if (type!=VariableType::flow)
1472  for (auto& v: g->flowVars())
1473  if (v->valueId()==name)
1474  {
1475  newName=v->name()+"^{Flow}";
1476  const VariableValues::iterator iv=variableValues.find(newName);
1477  if (iv==variableValues.end()) {g->table.renameFlows(v->name(),newName); v->retype(VariableType::flow);}
1478  else throw error("flow variables in Godley tables cannot be converted to a different type");
1479  }
1480  if (type!=VariableType::stock)
1481  for (auto& v: g->stockVars())
1482  if (v->valueId()==name)
1483  {
1484  newName=v->name()+"^{Stock}";
1485  const VariableValues::iterator iv=variableValues.find(newName);
1486  if (iv==variableValues.end()) {g->table.renameStock(v->name(),newName); v->retype(VariableType::stock);}
1487  else throw error("stock variables in Godley tables cannot be converted to a different type");
1488  }
1489  }
1490  return false;
1491  });
1492 
1493  if (auto var=definingVar(name))
1494  // we want to be able to convert stock vars to flow vars when their input is wired. condition is only met when newName has not been changed above. for ticket 1272
1495  if (name==newName && var->type() != type && (!var->isStock() || var->controller.lock()))
1496  throw error("cannot convert a variable to a type other than its defined type");
1497 
1498  // filter out invalid targets
1499  switch (type)
1500  {
1503  throw error("convertVarType not supported for type=%s",
1504  VariableType::typeName(type).c_str());
1505  default: break;
1506  }
1507 
1508  // convert all references
1509  model->recursiveDo(&Group::items,
1510  [&](Items&, Items::iterator i) {
1511  if (auto v=VariablePtr(*i))
1512  if (v->valueId()==name)
1513  {
1514  v.retype(type);
1515  if (*i==canvas.item)
1516  canvas.item=v;
1517  *i=v;
1518  }
1519  return false;
1520  });
1521  auto init=i->second->init();
1522  i->second=VariableValuePtr(type,i->second->name);
1523  i->second->init(init);
1524  }
VariableValues variableValues
Definition: minsky.h:188
std::vector< ItemPtr > Items
Definition: item.h:360
Canvas canvas
Definition: minsky.h:243
static std::string typeName(int t)
Definition: variableType.cc:30
VariablePtr definingVar(const std::string &valueId) const
returns reference to variable defining (ie input wired) for valueId
Definition: minsky.cc:204
bool isValueId(const string &name)
check that name is a valid valueId (useful for assertions)
Definition: valueId.cc:33
GroupPtr model
Definition: minsky.h:242
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175
Here is the call graph for this function:
Here is the caller graph for this function:

◆ copy()

void minsky::Minsky::copy ( ) const

copy items in current selection into clipboard

Definition at line 190 of file minsky.cc.

References minsky::schemaURL, and classdesc::xml_pack().

Referenced by minsky::Canvas::select().

191  {
192  if (canvas.selection.empty())
193  clipboard.putClipboard(""); // clear clipboard
194  else
195  {
197  ostringstream os;
198  xml_pack_t packer(os, schemaURL);
199  xml_pack(packer, "Minsky", m);
200  clipboard.putClipboard(os.str());
201  }
202  }
void xml_pack(classdesc::xml_pack_t &, const ecolab::string &, ecolab::Plot &)
Definition: plotWidget.h:215
Canvas canvas
Definition: minsky.h:243
bool empty() const
Definition: group.h:100
const char * schemaURL
Definition: saver.cc:26
Selection selection
Definition: canvas.h:105
Here is the call graph for this function:
Here is the caller graph for this function:

◆ cut()

void minsky::Minsky::cut ( )

erase items in current selection, put copy into clipboard

Definition at line 156 of file minsky.cc.

157  {
158  copy();
159  for (auto& i: canvas.selection.items)
160  {
161  if (auto v=i->variableCast())
162  if (v->controller.lock())
163  continue; // do not delete a variable controlled by another item
164  model->deleteItem(*i);
165  }
166  for (auto& i: canvas.selection.groups)
167  model->removeGroup(*i);
168  for (auto& i: canvas.selection.wires)
169  model->removeWire(*i);
170  canvas.item.reset();
171  canvas.itemFocus.reset();
172 #ifndef NDEBUG
173  garbageCollect();
174  for (auto& i: canvas.selection.items)
175  {
176  if (auto v=i->variableCast())
177  if (v->controller.lock())
178  continue; // variable controlled by another item is not being destroyed
179  assert(i.use_count()==1);
180  }
181  for (auto& i: canvas.selection.groups)
182  assert(i.use_count()==1);
183  for (auto& i: canvas.selection.wires)
184  assert(i.use_count()==1);
185 #endif
188  }
void copy() const
copy items in current selection into clipboard
Definition: minsky.cc:190
Canvas canvas
Definition: minsky.h:243
void garbageCollect()
Definition: minsky.cc:374
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
Groups groups
Definition: group.h:77
ItemPtr itemFocus
item selected by clicking
Definition: canvas.h:106
Selection selection
Definition: canvas.h:105
GroupPtr model
Definition: minsky.h:242
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ cycleCheck()

bool minsky::Minsky::cycleCheck ( ) const

checks for presence of illegal cycles in network. Returns true if there are some

Definition at line 1158 of file minsky.cc.

1159  {
1160  // construct the network schematic
1161  Network net;
1162  for (auto& w: model->findWires([](const WirePtr&){return true;}))
1163  net.emplace(w->from().get(), w->to().get());
1164  for (auto& i: model->findItems([](const ItemPtr&){return true;}))
1165  if (!dynamic_cast<IntOp*>(i.get()) && !dynamic_cast<GodleyIcon*>(i.get()))
1166  for (unsigned j=1; j<i->portsSize(); ++j)
1167  net.emplace(i->ports(j).lock().get(), i->ports(0).lock().get());
1168 
1169  for (auto& i: net)
1170  if (!i.first->input() && !net.portsVisited.contains(i.first))
1171  if (net.followWire(i.first))
1172  return true;
1173  return false;
1174  }
std::shared_ptr< Item > ItemPtr
Definition: item.h:55
std::shared_ptr< Wire > WirePtr
Definition: wire.h:98
GroupPtr model
Definition: minsky.h:242

◆ daysUntilRavelExpires()

static int minsky::Minsky::daysUntilRavelExpires ( )
inlinestatic

Definition at line 335 of file minsky.h.

335 {return ravelCAPI::daysUntilExpired();}

◆ defaultFont() [1/2]

string minsky::Minsky::defaultFont ( )
static

the default used by Pango

Definition at line 1750 of file minsky.cc.

References minsky::_defaultFont.

1751  {return _defaultFont? _defaultFont.get(): "";}
static std::unique_ptr< char[]> _defaultFont
Definition: minsky.cc:1748

◆ defaultFont() [2/2]

string minsky::Minsky::defaultFont ( const std::string &  x)
static

the default used by Pango

Definition at line 1753 of file minsky.cc.

References minsky::_defaultFont.

1754  {
1755  _defaultFont.reset(new char[x.length()+1]);
1756  strncpy(_defaultFont.get(),x.c_str(),x.length()+1);
1757  ecolab::Pango::defaultFamily=_defaultFont.get();
1758  return x;
1759  }
static std::unique_ptr< char[]> _defaultFont
Definition: minsky.cc:1748

◆ definingVar()

VariablePtr minsky::Minsky::definingVar ( const std::string &  valueId) const

returns reference to variable defining (ie input wired) for valueId

Definition at line 204 of file minsky.cc.

References minsky::valueId().

Referenced by minsky::VariableValue::hypercube(), minsky::VariableValue::init(), minsky::Canvas::renameItem(), minsky::VariableValues::resetValue(), minsky::VariableBase::sliderVisible(), and minsky::GodleyIcon::update().

205  {
206  return dynamic_pointer_cast<VariableBase>
207  (model->findAny(&Group::items, [&](const ItemPtr& x) {
208  auto v=x->variableCast();
209  return v && v->valueId()==valueId && v->defined();
210  }));
211  }
std::shared_ptr< Item > ItemPtr
Definition: item.h:55
string valueId(const string &name)
construct a valueId from fully qualified name @ name should not be canonicalised
Definition: valueId.cc:75
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:
Here is the caller graph for this function:

◆ deleteAllUnits()

void minsky::Minsky::deleteAllUnits ( )

removes units markup from all variables in model

Definition at line 459 of file minsky.cc.

References minsky::timeUnit.

460  {
461  for (auto& i: variableValues)
462  i.second->units.clear();
463  timeUnit.clear();
464  }
VariableValues variableValues
Definition: minsky.h:188
std::string timeUnit
Definition: simulation.h:35

◆ deltaT()

double minsky::Minsky::deltaT ( ) const
inline

Definition at line 308 of file minsky.h.

308 {return t-lastT;}
double lastT
previous timestep
Definition: minsky.h:307
double t
time
Definition: rungeKutta.h:57

◆ diagnoseNonFinite()

string minsky::Minsky::diagnoseNonFinite ( ) const
private

returns a diagnostic about an item that is infinite or NaN. Either a variable name, or and operator type.

Definition at line 998 of file minsky.cc.

References minsky::anonymous_namespace{userFunction.cc}::isfinite().

999  {
1000  // firstly check if any variables are not finite
1001  for (VariableValues::const_iterator v=variableValues.begin();
1002  v!=variableValues.end(); ++v)
1003  if (!isfinite(v->second->value()))
1004  return v->first;
1005 
1006  // now check operator equations
1007  for (EvalOpVector::const_iterator e=equations.begin(); e!=equations.end(); ++e)
1008  if (!isfinite(flowVars[(*e)->out]))
1009  return OperationType::typeName((*e)->type());
1010  return "";
1011  }
VariableValues variableValues
Definition: minsky.h:188
static std::string typeName(int type)
return the symbolic name of type
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table
Here is the call graph for this function:

◆ dimensionalAnalysis()

void minsky::Minsky::dimensionalAnalysis ( ) const

performs dimension analysis, throws if there is a problem

Definition at line 431 of file minsky.cc.

432  {
433  const_cast<Minsky*>(this)->variableValues.resetUnitsCache();
434  // increment varsPassed by one to prevent resettting the cache on each check
435  const IncrDecrCounter vpIdc(VariableBase::varsPassed);
436  model->recursiveDo
437  (&Group::items,
438  [&](Items& m, Items::iterator i)
439  {
440  if (auto v=(*i)->variableCast())
441  {
442  // check only the defining variables
443  if (v->isStock() && (v->inputWired() || v->controller.lock().get()))
444  v->checkUnits();
445  }
446  else if ((*i)->portsSize()>0 && !(*i)->ports(0).lock()->input() &&
447  (*i)->ports(0).lock()->wires().empty())
448  (*i)->checkUnits(); // check anything with an unwired output port
449  else if (auto p=(*i)->plotWidgetCast())
450  for (size_t j=0; j<p->portsSize(); ++j)
451  p->ports(j).lock()->checkUnits();
452  else if (auto p=dynamic_cast<Sheet*>(i->get()))
453  for (size_t j=0; j<p->portsSize(); ++j)
454  p->ports(j).lock()->checkUnits();
455  return false;
456  });
457  }
VariableValues variableValues
Definition: minsky.h:188
std::vector< ItemPtr > Items
Definition: item.h:360
static int varsPassed
for caching units calculation factory method
Definition: variable.h:103
GroupPtr model
Definition: minsky.h:242

◆ displayErrorItem()

void minsky::Minsky::displayErrorItem ( const Item op) const

indicate operation item has error, if visible, otherwise contining group

Definition at line 1229 of file minsky.cc.

References minsky::Canvas::itemIndicator, pyminsky::minsky, minsky::op, and resetScroll().

Referenced by MathDAG::OperationDAGBase::addEvalOps(), minsky::TensorOpFactory::create(), minsky::RungeKutta::evalEquations(), minsky::anonymous_namespace{minsky.cc}::Network::followWire(), MathDAG::SystemOfEquations::makeDAG(), MathDAG::anonymous_namespace{equations.cc}::NoArgument::NoArgument(), and minsky::Item::throw_error().

1230  {
1231  // this method is logically const, but because of the way
1232  // canvas rendering is done, canvas state needs updating
1233  auto& canvas=const_cast<Canvas&>(this->canvas);
1234  if (op.visible())
1235  canvas.itemIndicator=canvas.model->findItem(op);
1236  else if (auto v=op.variableCast())
1237  if (auto c=v->controller.lock())
1238  displayErrorItem(*c);
1239 
1240  if (!canvas.itemIndicator)
1241  if (auto g=op.group.lock())
1242  {
1243  while (g && !g->visible()) g=g->group.lock();
1244  if (g && g->visible())
1246  }
1247 
1248  if (canvas.itemIndicator)
1249  {
1250  auto physX=canvas.itemIndicator->x();
1251  auto physY=canvas.itemIndicator->y();
1252  if (physX<100 || physX>canvas.frameArgs().childWidth-100 ||
1253  physY<100 || physY>canvas.frameArgs().childHeight-100)
1254  {
1255  canvas.model->moveTo(0.5*canvas.frameArgs().childWidth-physX+canvas.model->x(),
1256  0.5*canvas.frameArgs().childHeight-physY+canvas.model->y());
1257  minsky().resetScroll();
1258  }
1259  }
1260  //requestRedraw calls back into TCL, so don't call it from the simulation thread. See ticket #973
1261  if (!RKThreadRunning) canvas.requestRedraw();
1262  }
const RenderFrameArgs & frameArgs() const
void displayErrorItem(const Item &op) const
indicate operation item has error, if visible, otherwise contining group
Definition: minsky.cc:1229
Model model
Definition: canvas.h:103
ItemPtr itemIndicator
for drawing error indicator on the canvas
Definition: canvas.h:120
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
virtual void resetScroll()
reset main window scroll bars after model has been panned
Definition: minsky.h:439
Minsky & minsky()
global minsky object
Definition: addon.cc:545
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ecolabVersion()

static std::string minsky::Minsky::ecolabVersion ( )
inlinestatic

Definition at line 324 of file minsky.h.

324 {return VERSION;}

◆ edited()

bool minsky::Minsky::edited ( ) const
inline

reflects whether the model has been changed since last save

Definition at line 157 of file minsky.h.

157 {return flags & is_edited;}

◆ exportAllPlotsAsCSV()

void minsky::Minsky::exportAllPlotsAsCSV ( const string &  prefix) const

export all plots

Definition at line 1562 of file minsky.cc.

References minsky::str().

1563  {
1564  unsigned plotNum=0;
1565  model->recursiveDo(&Group::items,
1566  [&](Items&, Items::iterator i) {
1567  if (auto p=(*i)->plotWidgetCast())
1568  {
1569  if (!p->title.empty())
1570  p->exportAsCSV((prefix+"-"+p->title+".csv"));
1571  else
1572  p->exportAsCSV((prefix+"-"+str(plotNum++)+".csv"));
1573  }
1574  return false;
1575  });
1576  }
std::vector< ItemPtr > Items
Definition: item.h:360
std::string str(T x)
utility function to create a string representation of a numeric type
Definition: str.h:33
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:

◆ exportSchema()

void minsky::Minsky::exportSchema ( const std::string &  filename,
int  schemaLevel = 1 
)
static

Definition at line 1105 of file minsky.cc.

References f, minsky::schemaURL, and classdesc::xsd_generate().

1106  {
1107  xsd_generate_t x;
1108  switch (schemaLevel)
1109  {
1110  case 0:
1111  xsd_generate(x,"Minsky",schema0::Minsky());
1112  break;
1113  case 1:
1114  xsd_generate(x,"Minsky",schema1::Minsky());
1115  break;
1116  case 2:
1117  xsd_generate(x,"Minsky",schema2::Minsky());
1118  break;
1119  case 3:
1120  xsd_generate(x,"Minsky",schema3::Minsky());
1121  break;
1122  }
1123  ofstream f(filename);
1124  x.output(f,schemaURL);
1125  }
function f
Definition: canvas.m:1
void xsd_generate(xsd_generate_t &g, const string &d, const minsky::Optional< T > &a)
Definition: optional.h:77
const char * schemaURL
Definition: saver.cc:26
Here is the call graph for this function:

◆ fontScale() [1/2]

double minsky::Minsky::fontScale ( )
static

an extra scaling factor of Pango fonts

Definition at line 1761 of file minsky.cc.

1762  {return ecolab::Pango::scaleFactor;}

◆ fontScale() [2/2]

double minsky::Minsky::fontScale ( double  s)
static

an extra scaling factor of Pango fonts

Definition at line 1764 of file minsky.cc.

1765  {return ecolab::Pango::scaleFactor=s;}

◆ garbageCollect()

void minsky::Minsky::garbageCollect ( )

Definition at line 374 of file minsky.cc.

375  {
377  stockVars.clear();
378  flowVars.clear();
379  equations.clear();
380  integrals.clear();
381 
382  // remove all temporaries
383  for (auto v=variableValues.begin(); v!=variableValues.end();)
384  if (v->second->temp())
385  variableValues.erase(v++);
386  else
387  ++v;
388 
390  }
void makeVariablesConsistent()
Definition: minsky.cc:337
static std::vector< double, CIVITA_ALLOCATOR< double > > stockVars
vector of variables that are integrated via Runge-Kutta. These variables label the columns of the God...
VariableValues variableValues
Definition: minsky.h:188
void reset()
reset all variableValues to their initial conditions
static std::vector< double, CIVITA_ALLOCATOR< double > > flowVars
variables defined as a simple function of the stock variables, also known as lhs variables. These variables appear in the body of the Godley table

◆ getc()

char minsky::Minsky::getc ( ) const
inline

Used to implement a pause until return pressed for attaching debugger purposes.

Definition at line 526 of file minsky.h.

526 {return std::getc(stdin);}

◆ getCommandData()

virtual CmdData minsky::Minsky::getCommandData ( const std::string &  command) const
inlinevirtual

return meta information on a given command

Reimplemented in minsky::RESTMinsky.

Definition at line 365 of file minsky.h.

365 {return generic;}

◆ importDuplicateColumn()

void minsky::Minsky::importDuplicateColumn ( GodleyTable srcTable,
int  srcCol 
)

find any duplicate column, and use it as a source column for balanceDuplicateColumns

Definition at line 617 of file minsky.cc.

References minsky::GodleyTable::cell(), minsky::GodleyTable::cols(), and minsky::trimWS().

Referenced by minsky::GodleyTableEditor::importStockVarByCol(), minsky::GodleyIcon::setCell(), and minsky::GodleyTableEditor::update().

618  {
619  if (srcCol<0 || size_t(srcCol)>=srcTable.cols()) return;
620  // find any duplicate column, and use it to do balanceDuplicateColumns
621  const string& colName=trimWS(srcTable.cell(0,srcCol));
622  if (colName.empty()) return; //ignore blank columns
623 
624  try
625  {
626  model->recursiveDo
627  (&Group::items,
628  [&](Items& m, Items::iterator i)
629  {
630  if (auto gi=dynamic_cast<GodleyIcon*>(i->get()))
631  for (size_t col=1; col<gi->table.cols(); col++)
632  if ((&gi->table!=&srcTable || int(col)!=srcCol) && trimWS(gi->table.cell(0,col))==colName) // we have a match
633  balanceDuplicateColumns(*gi, col);
634  return false;
635  });
636  }
637  catch (...) // in the event of business rules being violated, delete column name
638  {
639  srcTable.cell(0,srcCol).clear();
640  throw;
641  }
642  }
void balanceDuplicateColumns(const GodleyIcon &srcTable, int srcCol)
makes all duplicated columns consistent with srcTable, srcCol
Definition: minsky.cc:752
std::vector< ItemPtr > Items
Definition: item.h:360
std::string trimWS(const std::string &s)
Definition: str.h:49
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:
Here is the caller graph for this function:

◆ importVensim()

void minsky::Minsky::importVensim ( const std::string &  filename)

import a Vensim file

Definition at line 1598 of file minsky.cc.

References f, and minsky::readMdl().

1599  {
1600  ifstream f(filename);
1601  readMdl(*model,*this,f);
1603  }
function f
Definition: canvas.m:1
void readMdl(Group &group, Simulation &simParms, istream &mdlFile)
import a Vensim mdl file into group, also populating simParms from the control block ...
Definition: mdlReader.cc:250
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:

◆ imposeDimensions()

void minsky::Minsky::imposeDimensions ( )

Definition at line 364 of file minsky.cc.

Referenced by minsky::Ravel::setDimension().

365  {
366  for (auto& v: variableValues)
367  {
368  v.second->imposeDimensions(dimensions);
369  v.second->tensorInit.imposeDimensions(dimensions);
370  }
371  }
VariableValues variableValues
Definition: minsky.h:188
Dimensions dimensions
Definition: minsky.h:189
Here is the caller graph for this function:

◆ initGodleys()

void minsky::Minsky::initGodleys ( )

Definition at line 856 of file minsky.cc.

857  {
858  auto toGodleyIcon=[](const ItemPtr& i) {return dynamic_cast<GodleyIcon*>(i.get());};
859  auto godleyItems=model->findAll<GodleyIcon*>
860  (toGodleyIcon, &GroupItems::items, toGodleyIcon);
861  evalGodley.initialiseGodleys(GodleyIt(godleyItems.begin()),
862  GodleyIt(godleyItems.end()), variableValues);
863  }
EvalGodley evalGodley
Definition: rungeKutta.h:60
VariableValues variableValues
Definition: minsky.h:188
std::shared_ptr< Item > ItemPtr
Definition: item.h:55
void initialiseGodleys(const GodleyIterator &begin, const GodleyIterator &end, const VariableValues &values)
initialise this to a sequence of Godley tables - adaptors provided below
Definition: evalGodley.h:120
GroupPtr model
Definition: minsky.h:242

◆ inputWired()

bool minsky::Minsky::inputWired ( const std::string &  name) const
inline

returns true if any variable of name name has a wired input

Definition at line 385 of file minsky.h.

Referenced by minsky::GroupItems::addWire().

385 {return definingVar(name).get();}
VariablePtr definingVar(const std::string &valueId) const
returns reference to variable defining (ie input wired) for valueId
Definition: minsky.cc:204
Here is the caller graph for this function:

◆ insertGroupFromFile()

void minsky::Minsky::insertGroupFromFile ( const string &  file)

Definition at line 322 of file minsky.cc.

References schema3::Minsky::populateGroup(), and minsky::stripByteOrderingMarker().

323  {
324  ifstream inf(file);
325  if (!inf)
326  throw runtime_error(string("failed to open ")+file);
328  xml_unpack_t saveFile(inf);
329  const schema3::Minsky currentSchema(saveFile);
330 
331  const GroupPtr g(new Group);
332  currentSchema.populateGroup(*model->addGroup(g));
333  g->resizeOnContents();
334  canvas.itemFocus=g;
335  }
Canvas canvas
Definition: minsky.h:243
ItemPtr itemFocus
item selected by clicking
Definition: canvas.h:106
std::shared_ptr< Group > GroupPtr
Definition: port.h:32
GroupPtr model
Definition: minsky.h:242
void stripByteOrderingMarker(std::istream &s)
checks if the input stream has the UTF-8 byte ordering marker, and removes it if present ...
Definition: str.h:147
Here is the call graph for this function:

◆ itemFromNamedItem()

void minsky::Minsky::itemFromNamedItem ( const std::string &  name)
inline

Definition at line 517 of file minsky.h.

517 {canvas.item=namedItems[name].lock();}
Canvas canvas
Definition: minsky.h:243
std::map< std::string, std::weak_ptr< Item > > namedItems
Definition: minsky.h:515
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ latex()

void minsky::Minsky::latex ( const std::string &  filename,
bool  wrapLaTeXLines 
)

Definition at line 1767 of file minsky.cc.

References f, MathDAG::SystemOfEquations::latex(), and MathDAG::SystemOfEquations::latexWrapped().

1768  {
1769  if (cycleCheck()) throw error("cyclic network detected");
1770  ofstream f(filename);
1771 
1772  f<<"\\documentclass{article}\n";
1773  if (wrapLaTeXLines)
1774  {
1775  f<<"\\usepackage{breqn}\n\\begin{document}\n";
1777  }
1778  else
1779  {
1780  f<<"\\begin{document}\n";
1782  }
1783  f<<"\\end{document}\n";
1784  }
function f
Definition: canvas.m:1
ostream & latexWrapped(ostream &) const
Definition: equations.cc:933
bool cycleCheck() const
checks for presence of illegal cycles in network. Returns true if there are some
Definition: minsky.cc:1158
ostream & latex(ostream &) const
render as a LaTeX eqnarray Use LaTeX brqn environment to wrap long lines
Definition: equations.cc:902
Here is the call graph for this function:

◆ latex2pango()

string minsky::Minsky::latex2pango ( const std::string &  x)
inline

Definition at line 492 of file minsky.h.

References minsky::latexToPango().

492 {return latexToPango(x.c_str());}
std::string latexToPango(const char *s)
Definition: latexMarkup.h:30
Here is the call graph for this function:

◆ listAllInstances()

void minsky::Minsky::listAllInstances ( )

Definition at line 1636 of file minsky.cc.

1637  {
1638  if (canvas.item)
1639  if (auto v=canvas.item->variableCast())
1640  {
1641  variableInstanceList=std::make_shared<VariableInstanceList>(*canvas.model, v->valueId());
1642  return;
1643  }
1644  variableInstanceList.reset();
1645  }
Model model
Definition: canvas.h:103
Canvas canvas
Definition: minsky.h:243
std::shared_ptr< VariableInstanceList > variableInstanceList
supports navigation to all instances of current variable
Definition: minsky.h:512
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ listFonts()

vector<string> minsky::Minsky::listFonts ( ) const
inline

Definition at line 455 of file minsky.h.

455  {
456  vector<string> r;
457 #ifdef PANGO
458  PangoFontFamily **families;
459  int num;
460  pango_font_map_list_families(pango_cairo_font_map_get_default(),
461  &families,&num);
462  for (int i=0; i<num; ++i)
463  r.push_back(pango_font_family_get_name(families[i]));
464  g_free(families);
465  std::sort(r.begin(),r.end());
466 #endif
467  return r;
468  }

◆ load()

void minsky::Minsky::load ( const std::string &  filename)

load from a file

Definition at line 1047 of file minsky.cc.

References schema3::Minsky::populateMinsky(), schema3::Minsky::schemaVersion, minsky::stripByteOrderingMarker(), and schema3::Minsky::version.

1048  {
1049  running=false;
1050  clearAllMaps(true);
1051 
1052  ifstream inf(filename);
1053  if (!inf)
1054  throw runtime_error("failed to open "+filename);
1056 
1057  {
1058  const BusyCursor busy(*this);
1059  xml_unpack_t saveFile(inf);
1060  const schema3::Minsky currentSchema(saveFile);
1061  currentSchema.populateMinsky(*this);
1062  if (currentSchema.schemaVersion<currentSchema.version)
1063  message("You are converting the model from an older version of Minsky. "
1064  "Once you save this file, you may not be able to open this file"
1065  " in older versions of Minsky.");
1066  }
1067 
1068  const LocalMinsky lm(*this); // populateMinsky resets the local minsky pointer, so restore it here
1069  flags=fullEqnDisplay_needed;
1070 
1071  // try balancing all Godley tables
1072  try
1073  {
1074  model->recursiveDo(&Group::items,
1075  [this](Items&,Items::iterator i) {
1076  try
1077  {
1078  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
1079  {
1080  for (unsigned j=1; j<g->table.cols(); ++j)
1082  }
1083  (*i)->adjustBookmark();
1084  }
1085  catch (...) {}
1086  return false;
1087  });
1088 
1089  // try resetting the system, but ignore any errors
1090  reset();
1092  }
1093  catch (...) {flags|=reset_needed;}
1095  canvas.moveTo(0,0); // force placement of ports
1096  // sometimes we need to recalculate the bounding boxes
1097  model->recursiveDo(&Group::items,
1098  [](Items&,Items::iterator i) {
1099  (*i)->updateBoundingBox();
1100  return false;
1101  });
1102  pushHistory();
1103  }
virtual void message(const std::string &)
display a message in a popup box on the GUI
Definition: minsky.h:442
void balanceDuplicateColumns(const GodleyIcon &srcTable, int srcCol)
makes all duplicated columns consistent with srcTable, srcCol
Definition: minsky.cc:752
bool pushHistory()
push current model state onto history if it differs from previous
Definition: minsky.cc:1264
void reset()
resets the variables back to their initial values
Definition: minsky.cc:865
void populateMissingDimensions()
fills in dimensions table with all loaded ravel axes
Definition: minsky.cc:496
std::vector< ItemPtr > Items
Definition: item.h:360
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
void moveTo(float x, float y) override
move this so that (x,y) is centred
Definition: canvas.h:129
void clearAllMaps()
Definition: minsky.h:246
GroupPtr model
Definition: minsky.h:242
void stripByteOrderingMarker(std::istream &s)
checks if the input stream has the UTF-8 byte ordering marker, and removes it if present ...
Definition: str.h:147
bool running
controls whether simulation is running
Definition: rungeKutta.h:58
Here is the call graph for this function:

◆ loggingEnabled()

bool minsky::Minsky::loggingEnabled ( ) const
inline

returns true if logging is in operation

Definition at line 291 of file minsky.h.

291 {return outputDataFile.get();}

◆ logVariables()

void minsky::Minsky::logVariables ( ) const
private

write current state of all variables to the log file

Definition at line 107 of file minsky.cc.

108  {
109  if (outputDataFile)
110  {
111  *outputDataFile<<t;
112  for (auto& v: variableValues)
113  if (logVarList.contains(v.first))
114  *outputDataFile<<" "<<v.second->value();
115  *outputDataFile<<endl;
116  }
117  }
std::set< string > logVarList
set of variables (valueIds) to log
Definition: minsky.h:289
VariableValues variableValues
Definition: minsky.h:188
double t
time
Definition: rungeKutta.h:57

◆ makeVariablesConsistent()

void minsky::Minsky::makeVariablesConsistent ( )

Definition at line 337 of file minsky.cc.

338  {
339  // remove variableValues not in variables
340  set<string> existingNames;
341  existingNames.insert("constant:zero");
342  existingNames.insert("constant:one");
343  vector<GodleyIcon*> godleysToUpdate;
344  model->recursiveDo(&Group::items,
345  [&](Items&,Items::iterator i) {
346  if (auto v=(*i)->variableCast())
347  existingNames.insert(v->valueId());
348  // ensure Godley table variables are the correct types
349  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
350  godleysToUpdate.push_back(g);
351  return false;
352  }
353  );
354 
355  for (auto g: godleysToUpdate) g->update();
356  for (auto i=variableValues.begin(); i!=variableValues.end(); )
357  if (existingNames.contains(i->first))
358  ++i;
359  else
360  variableValues.erase(i++);
361 
362  }
VariableValues variableValues
Definition: minsky.h:188
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242

◆ markEdited()

void minsky::Minsky::markEdited ( )
inline

indicate model has been changed since last saved

Definition at line 161 of file minsky.h.

Referenced by minsky::Canvas::keyPress(), and minsky::GodleyTable::markEdited().

161  {
162  flags |= is_edited | fullEqnDisplay_needed;
163  if (!running) flags|=reset_needed; // don't reset when running
167  }
void update()
update variables from model, using previous height value
Definition: variablePane.cc:89
Model model
Definition: canvas.h:103
VariablePane variablePane
Definition: minsky.h:523
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
bool running
controls whether simulation is running
Definition: rungeKutta.h:58
void updateTimestamp()
Definition: canvas.h:72
Here is the caller graph for this function:

◆ matchingTableColumns()

std::set< string > minsky::Minsky::matchingTableColumns ( const GodleyIcon currTable,
GodleyAssetClass::AssetClass  ac 
)
Returns
available matching columns from other Godley tables
Parameters
currTable- this table, not included in the matching process

Definition at line 566 of file minsky.cc.

References minsky::godley, and minsky::scope().

Referenced by minsky::GodleyTableEditor::matchingTableColumnsByCol().

567  {
568  std::set<string> r;
570  // matching liability with assets and vice-versa
571  switch (ac)
572  {
575  target_ac=GodleyAssetClass::asset;
576  break;
578  target_ac=GodleyAssetClass::liability;
579  break;
580  default:
581  return r; // other types do not match anything
582  }
583 
584  std::set<string> duplicatedColumns;
585  model->recursiveDo
586  (&Group::items,
587  [&](Items& m, Items::iterator it)
588  {
589  if (auto gi=dynamic_cast<GodleyIcon*>(it->get()))
590  {
591  for (size_t i=1; i<gi->table.cols(); ++i)
592  if (!gi->table.cell(0,i).empty())
593  {
594  auto v=gi->table.cell(0,i);
595  auto scope=minsky::scope(gi->group.lock(),v);
596  if (scope->higher(*godley.group.lock()))
597  v=':'+v; //NOLINT
598  else if (scope!=godley.group.lock())
599  continue; // variable is inaccessible
600  if (r.contains(v) || gi->table.assetClass(i)!=target_ac)
601  {
602  r.erase(v); // column already duplicated, or in current, nothing to match
603  duplicatedColumns.insert(v);
604  }
605  else if (!duplicatedColumns.contains(v) && gi->table.assetClass(i)==target_ac &&
606  // insert unmatched asset columns from this table only for equity (feature #174)
607  // otherwise matches are between separate tables
608  ((ac!=GodleyAssetClass::equity && gi!=&godley) || (ac==GodleyAssetClass::equity && gi==&godley) ))
609  r.insert(v);
610  }
611  }
612  return false;
613  });
614  return r;
615  }
size_t scope(const string &name)
extract scope from a qualified variable name
Definition: valueId.cc:83
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:
Here is the caller graph for this function:

◆ matlab()

void minsky::Minsky::matlab ( const std::string &  filename)
inline

Definition at line 485 of file minsky.h.

References f, and MathDAG::SystemOfEquations::matlab().

485  {
486  if (cycleCheck()) throw error("cyclic network detected");
487  ofstream f(filename);
489  }
function f
Definition: canvas.m:1
ostream & matlab(ostream &) const
render as MatLab code create equations suitable for Runge-Kutta solver
Definition: equations.cc:963
bool cycleCheck() const
checks for presence of illegal cycles in network. Returns true if there are some
Definition: minsky.cc:1158
Here is the call graph for this function:

◆ message()

virtual void minsky::Minsky::message ( const std::string &  )
inlinevirtual

display a message in a popup box on the GUI

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 442 of file minsky.h.

442 {}

◆ multipleEquities() [1/2]

bool minsky::Minsky::multipleEquities ( ) const
inline

Definition at line 153 of file minsky.h.

153 {return m_multipleEquities;}
bool m_multipleEquities
Definition: minsky.h:132

◆ multipleEquities() [2/2]

bool minsky::Minsky::multipleEquities ( const bool &  m)

Definition at line 89 of file minsky.cc.

89  {
93  return m_multipleEquities;
94  }
void redrawAllGodleyTables()
request all Godley table windows to redraw
Definition: minsky.cc:1715
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
bool m_multipleEquities
Definition: minsky.h:132

◆ nameCurrentItem()

void minsky::Minsky::nameCurrentItem ( const std::string &  name)
inline

Definition at line 516 of file minsky.h.

516 {namedItems[name]=canvas.item;}
Canvas canvas
Definition: minsky.h:243
std::map< std::string, std::weak_ptr< Item > > namedItems
Definition: minsky.h:515
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ numOpArgs()

int minsky::Minsky::numOpArgs ( OperationType::Type  o)
static

Definition at line 1786 of file minsky.cc.

References minsky::op.

1787  {
1788  const OperationPtr op(o);
1789  return op->numPorts()-1;
1790  }

◆ openGroupInCanvas()

void minsky::Minsky::openGroupInCanvas ( )
inline

Definition at line 507 of file minsky.h.

void openGroupInCanvas(const ItemPtr &item)
reinitialises canvas to the group located in item
Definition: canvas.cc:694
Canvas canvas
Definition: minsky.h:243
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ openLogFile()

void minsky::Minsky::openLogFile ( const string &  name)

opens the log file, and writes out a header line describing names of all variables

Definition at line 96 of file minsky.cc.

References minsky::CSVQuote().

97  {
98  outputDataFile.reset(new ofstream(name));
99  *outputDataFile<< "#time";
100  for (auto& v: variableValues)
101  if (logVarList.contains(v.first))
102  *outputDataFile<<" "<<CSVQuote(v.second->name,' ');
103  *outputDataFile<<endl;
104  }
std::set< string > logVarList
set of variables (valueIds) to log
Definition: minsky.h:289
VariableValues variableValues
Definition: minsky.h:188
std::string CSVQuote(const std::string &x, char sep)
quotes a string if it contains a separator character, and double quotes quotes
Definition: str.h:162
Here is the call graph for this function:

◆ openModelInCanvas()

void minsky::Minsky::openModelInCanvas ( )
inline

reinitialises canvas to the toplevel group

Definition at line 509 of file minsky.h.

void openGroupInCanvas(const ItemPtr &item)
reinitialises canvas to the group located in item
Definition: canvas.cc:694
Canvas canvas
Definition: minsky.h:243
GroupPtr model
Definition: minsky.h:242

◆ paste()

void minsky::Minsky::paste ( )

paste clipboard as a new group or ungrouped items on the canvas. canvas.itemFocus is set to refer to the new group or items.

Definition at line 219 of file minsky.cc.

References schema3::Minsky::populateGroup(), and minsky::valueId().

221  {
222  // don't paste if previous created item hasn't been placed yet.
223  if (canvas.itemFocus) return;
224  map<string,string> existingParms;
225  // preserve initial conditions.
226  for (auto& [valueId,vv]: variableValues)
227  existingParms.emplace(valueId,vv->init());
228 
229  istringstream is(clipboard.getClipboard());
230  xml_unpack_t unpacker(is);
231  schema3::Minsky m(unpacker);
232  GroupPtr g(new Group);
233  g->self=g;
234  m.populateGroup(*g);
235 
236  // stash values of parameters in the copied group, for ticket 1258
237  for (auto& i: g->items)
238  if (auto v=i->variableCast(); v && v->type()==VariableType::parameter)
239  existingParms.emplace(v->valueId(),v->init());
240 
241  // Default pasting no longer occurs as grouped items or as a group within a group. Fix for tickets 1080/1098
243  // The following is only necessary if one pastes into an existing model. For ticket 1258
244  if (!history.empty() || !canvas.model.get()->empty()) {
245  bool alreadyDefinedMessageDisplayed=false;
246 
247  // convert stock variables that aren't defined to flow variables, and other fix up multiply defined vars
248  g->recursiveDo(&GroupItems::items,
249  [&](Items&, Items::iterator i) {
250  if (auto v=(*i)->variableCast())
251  if (v->defined() || v->isStock())
252  {
253  // if defined, check no other defining variable exists
254  auto alreadyDefined = canvas.model->findAny
256  [&v](const ItemPtr& j)
257  {return j.get()!=v && j->variableCast() && j->variableCast()->defined();});
258  if (v->isStock())
259  {
260  if (v->defined() && alreadyDefined && !alreadyDefinedMessageDisplayed)
261  {
262  message("Integral/Stock variable "+v->name()+" already defined.");
263  alreadyDefinedMessageDisplayed=true;
264  }
265  else if (!v->defined() && !alreadyDefined)
266  {
267  // need to do this var explicitly, as not currently part of model structure
268  if (auto vp=VariablePtr(*i))
269  {
270  vp.retype(VariableType::flow);
271  *i=vp;
272  convertVarType(vp->valueId(), VariableType::flow);
273  }
274  }
275  }
276  else if (alreadyDefined)
277  {
278  // delete defining wire from this
279  assert(v->portsSize()>1 && !v->ports(1).lock()->wires().empty());
280  g->removeWire(*v->ports(1).lock()->wires()[0]);
281  }
282  }
283  return false;
284  });
285  }
286 
287  canvas.model->addGroup(g); // needed to ensure wires are correctly handled
288  auto copyOfItems=g->items;
289  auto copyOfGroups=g->groups;
290 
291  // ungroup g, putting all its contents on the canvas
292  canvas.model->moveContents(*g);
293 
294  // leave newly ungrouped items in selection
295  for (auto& i: copyOfItems)
297 
298  // ensure that initial values of pasted parameters are correct. for ticket 1258
299  for (auto& p: existingParms)
300  if (auto vv=variableValues.find(p.first); vv!=variableValues.end())
301  vv->second->init(p.second);
302  existingParms.clear();
303 
304  // Attach mouse focus only to first visible item in selection. For ticket 1098.
305  for (auto& i: canvas.selection.items)
306  if (i->visible())
307  {
308  canvas.setItemFocus(i);
309  break;
310  }
311 
312  if (!copyOfGroups.empty()) canvas.setItemFocus(copyOfGroups[0]);
313 
314  canvas.model->removeGroup(*g);
316  }
317  catch (...)
318  {
319  throw runtime_error("clipboard data invalid");
320  }
virtual void message(const std::string &)
display a message in a popup box on the GUI
Definition: minsky.h:442
VariableValues variableValues
Definition: minsky.h:188
void setItemFocus(const ItemPtr &x)
sets itemFocus, and resets mouse offset for placement
Definition: canvas.h:167
std::shared_ptr< Item > ItemPtr
Definition: item.h:55
string valueId(const string &name)
construct a valueId from fully qualified name @ name should not be canonicalised
Definition: valueId.cc:75
Model model
Definition: canvas.h:103
std::vector< ItemPtr > Items
Definition: item.h:360
Canvas canvas
Definition: minsky.h:243
void ensureItemInserted(const ItemPtr &item)
check if item already present, and if not, inserts item delegates to ensureGroupInserted if passed a ...
Definition: selection.cc:60
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
ItemPtr itemFocus
item selected by clicking
Definition: canvas.h:106
Selection selection
Definition: canvas.h:105
std::shared_ptr< Group > GroupPtr
Definition: port.h:32
void convertVarType(const std::string &name, VariableType::Type type)
Converts variable(s) named by name into a variable of type type.
Definition: minsky.cc:1456
Here is the call graph for this function:

◆ physicalMem()

size_t minsky::Minsky::physicalMem ( )
static

returns amount of memory installed on system

Definition at line 1725 of file minsky.cc.

1726  {
1727 #if defined(__linux__)
1728  struct sysinfo s;
1729  sysinfo(&s);
1730  return s.totalram;
1731 #elif defined(WIN32)
1732  MEMORYSTATUSEX s{sizeof(MEMORYSTATUSEX)};
1733  GlobalMemoryStatusEx(&s);
1734  return s.ullTotalPhys;
1735 #elif defined(__APPLE__)
1736  int mib[]={CTL_HW,HW_MEMSIZE};
1737  uint64_t physical_memory;
1738  size_t length = sizeof(uint64_t);
1739  if (sysctl(mib, sizeof(mib)/sizeof(int), &physical_memory, &length, NULL, 0))
1740  perror("physicalMem:");
1741  return physical_memory;
1742 #else
1743  // all else fails, return max value
1744  return ~0UL;
1745 #endif
1746  }

◆ popFlags()

void minsky::Minsky::popFlags ( )
inline

push and pop state of the flags

Definition at line 174 of file minsky.h.

174  {
175  if (!flagStack.empty()) {
176  flags=flagStack.back();
177  flagStack.pop_back();
178  }
179  }

◆ populateMissingDimensions()

void minsky::Minsky::populateMissingDimensions ( )

fills in dimensions table with all loaded ravel axes

Definition at line 496 of file minsky.cc.

496  {
497  // populate from variable value table first, then override by ravels
498  bool incompatibleMessageDisplayed=false;
499  for (auto& v: variableValues)
500  populateMissingDimensionsFromVariable(*v.second, incompatibleMessageDisplayed);
501  model->recursiveDo
502  (&Group::items,[&](Items& m, Items::iterator it)
503  {
504  if (auto ri=dynamic_cast<Ravel*>(it->get()))
505  {
506  auto state=ri->getState();
507  for (auto& j: state.handleStates)
508  dimensions.emplace(j.description,Dimension());
509  }
510  return false;
511  });
512  requestReset();
513  }
void requestReset()
Definition: minsky.cc:466
VariableValues variableValues
Definition: minsky.h:188
std::vector< ItemPtr > Items
Definition: item.h:360
void populateMissingDimensionsFromVariable(const VariableValue &, bool &incompatibleMessageDisplayed)
populate missing dimensions from a variableValue
Definition: minsky.cc:515
GroupPtr model
Definition: minsky.h:242
Dimensions dimensions
Definition: minsky.h:189

◆ populateMissingDimensionsFromVariable() [1/2]

void minsky::Minsky::populateMissingDimensionsFromVariable ( const VariableValue v,
bool &  incompatibleMessageDisplayed 
)

populate missing dimensions from a variableValue

Parameters
incompatibleMessageDisplayedboolean flag to make message display single shot

Definition at line 515 of file minsky.cc.

References minsky::VariableValue::hypercube().

Referenced by minsky::VariableBase::importFromCSV().

516  {
517  set<string> varDimensions;
518  for (auto& xv: v.hypercube().xvectors)
519  {
520  auto d=dimensions.find(xv.name);
521  if (d==dimensions.end())
522  {
523  dimensions.emplace(xv.name, xv.dimension);
524  varDimensions.insert(xv.name);
525  }
526  else if (d->second.type!=xv.dimension.type && !incompatibleMessageDisplayed)
527  {
528  message("Incompatible dimension type for dimension "+d->first+". Please adjust the global dimension in the dimensions dialog, which can be found under the Edit menu.");
529  incompatibleMessageDisplayed=true;
530  }
531  }
532  // set all newly populated dimensions on Ravels to forward sort order
533  model->recursiveDo
534  (&Group::items,[&](Items& m, Items::iterator it)
535  {
536  if (auto ri=dynamic_cast<Ravel*>(it->get()))
537  for (size_t i=0; i<ri->numHandles(); ++i)
538  if (varDimensions.contains(ri->handleDescription(i)))
539  ri->setHandleSortOrder(ravel::HandleSort::forward, i);
540  return false;
541  });
542  }
virtual void message(const std::string &)
display a message in a popup box on the GUI
Definition: minsky.h:442
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242
Dimensions dimensions
Definition: minsky.h:189
Here is the call graph for this function:
Here is the caller graph for this function:

◆ populateMissingDimensionsFromVariable() [2/2]

void minsky::Minsky::populateMissingDimensionsFromVariable ( const VariableValue v)
inline

Definition at line 199 of file minsky.h.

200  {bool dummy; populateMissingDimensionsFromVariable(v,dummy);}
void populateMissingDimensionsFromVariable(const VariableValue &, bool &incompatibleMessageDisplayed)
populate missing dimensions from a variableValue
Definition: minsky.cc:515

◆ progress()

virtual void minsky::Minsky::progress ( const std::string &  title,
int   
)
inlinevirtual

set progress bar, out of 100, labelling the progress bar with title

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 433 of file minsky.h.

Referenced by minsky::Progress::displayProgress().

433 {}
Here is the caller graph for this function:

◆ pushFlags()

void minsky::Minsky::pushFlags ( )
inline

push and pop state of the flags

Definition at line 173 of file minsky.h.

173 {flagStack.push_back(flags);}

◆ pushHistory()

bool minsky::Minsky::pushHistory ( )

push current model state onto history if it differs from previous

Definition at line 1264 of file minsky.cc.

References classdesc::xml_pack().

Referenced by minsky::PubTab::addNote(), minsky::Canvas::copyItem(), minsky::PhillipsDiagram::init(), minsky::PubTab::mouseUp(), minsky::PhillipsDiagram::mouseUp(), minsky::VariableBase::onMouseMotion(), minsky::PubTab::removeItemAt(), and minsky::PubTab::removeSelf().

1265  {
1266  // do not pushHistory after undo or redo
1267  if (undone)
1268  return undone=false;
1269 
1270  // go via a schema object, as serialising minsky::Minsky has
1271  // problems due to port management
1272  schema3::Minsky m(*this, false /* don't pack tensor data */);
1273  pack_t buf;
1274  buf<<m;
1275  if (history.empty())
1276  {
1277  history.emplace_back();
1278  buf.swap(history.back());
1279  historyPtr=history.size();
1280  return true;
1281  }
1282  while (history.size()>maxHistory)
1283  history.pop_front();
1284  if (history.empty() || history.back().size()!=buf.size() || memcmp(buf.data(), history.back().data(), buf.size())!=0)
1285  {
1286  // check XML versions differ (slower)
1287  ostringstream prev, curr;
1288  xml_pack_t prevXbuf(prev), currXbuf(curr);
1289  xml_pack(currXbuf,"Minsky",m);
1290  schema3::Minsky previousMinsky;
1291  history.back().reseto()>>previousMinsky;
1292  xml_pack(prevXbuf,"Minsky",previousMinsky);
1293 
1294  if (curr.str()!=prev.str())
1295  {
1296  // This bit of code outputs an XML representation that can be
1297  // used for debugging issues related to unnecessary
1298  // history pushes.
1299  //buf.reseto()>>m;
1300  //xml_pack_t tb(cout);
1301  //tb.prettyPrint=true;
1302  //xml_pack(tb,"Minsky",m);
1303  //cout<<"------"<<endl;
1304  history.emplace_back();
1305  buf.swap(history.back());
1306  historyPtr=history.size();
1307  if (autoSaver && doPushHistory)
1308  try
1309  {
1310  //autoSaver->packer.prettyPrint=true;
1311  autoSaver->save(m);
1312  }
1313  catch (...)
1314  {
1315  autoSaver.reset();
1316  throw;
1317  }
1318  return true;
1319  }
1320  }
1321  historyPtr=history.size();
1322  return false;
1323  }
unsigned maxHistory
maximum no. of history states to save
Definition: minsky.h:339
void xml_pack(classdesc::xml_pack_t &, const ecolab::string &, ecolab::Plot &)
Definition: plotWidget.h:215
bool doPushHistory
flag to indicate whether a TCL should be pushed onto the history stack, or logged in a recording...
Definition: minsky.h:370
Here is the call graph for this function:
Here is the caller graph for this function:

◆ randomLayout()

void minsky::Minsky::randomLayout ( )

randomly layout current open group and recentre reinitialises canvas to the group located in item

Definition at line 1630 of file minsky.cc.

1631  {
1632  canvas.model->randomLayout();
1633  canvas.recentre();
1634  }
void recentre()
adjust canvas so that -ve coordinates appear on canvas
Definition: canvas.cc:929
Model model
Definition: canvas.h:103
Canvas canvas
Definition: minsky.h:243

◆ ravelAvailable()

static bool minsky::Minsky::ravelAvailable ( )
inlinestatic

Definition at line 333 of file minsky.h.

333 {return ravelCAPI::available();}

◆ ravelExpired()

static bool minsky::Minsky::ravelExpired ( )
inlinestatic

Definition at line 334 of file minsky.h.

334 {return ravelCAPI::available() && ravelCAPI::daysUntilExpired()<0;}

◆ ravelVersion()

static std::string minsky::Minsky::ravelVersion ( )
inlinestatic

Definition at line 325 of file minsky.h.

325  {
326  if (ravelCAPI::Ravel::available())
327  {
328  int d=ravelCAPI::Ravel::daysUntilExpired();
329  return ravelCAPI::Ravel::version() + ": "+((d>=0)?("Expires in "+std::to_string(d)+" day"+(d!=1?"s":"")): "Expired");
330  }
331  else return "unavailable";
332  }

◆ redrawAllGodleyTables()

void minsky::Minsky::redrawAllGodleyTables ( )

request all Godley table windows to redraw

Definition at line 1715 of file minsky.cc.

Referenced by minsky::GodleyTableEditor::update().

1716  {
1717  model->recursiveDo(&Group::items,
1718  [&](Items&,Items::iterator i) {
1719  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
1720  g->popup.requestRedraw();
1721  return false;
1722  });
1723  }
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242
Here is the caller graph for this function:

◆ reloadAllCSVParameters()

void minsky::Minsky::reloadAllCSVParameters ( )

reload all CSV parameters from latest values in files.

Definition at line 1701 of file minsky.cc.

1702  {
1703  model->recursiveDo(&GroupItems::items,
1704  [&](Items&, Items::iterator i) {
1705  if (auto v=(*i)->variableCast())
1706  {
1707  v->reloadCSV();
1708  requestReset();
1709  }
1710  return false;
1711  });
1712  }
void requestReset()
Definition: minsky.cc:466
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242

◆ removeItems()

void minsky::Minsky::removeItems ( Wire wire)
private

remove the definition network from wire, up to, but not including attached variables.

Definition at line 1647 of file minsky.cc.

References minsky::wire.

1648  {
1649  if (wire.from()->wires().size()==1)
1650  { // only remove higher up the network if this item is the only item feeding from it
1651  auto& item=wire.from()->item();
1652  if (!item.variableCast())
1653  {
1654  for (size_t i=1; i<item.portsSize(); ++i)
1655  if (auto p=item.ports(i).lock())
1656  for (auto w: p->wires())
1657  removeItems(*w);
1658  model->removeItem(item);
1659  }
1660  else if (auto p=item.ports(1).lock())
1661  if (p->wires().empty())
1662  model->removeItem(item); // remove non-definition variables as well
1663  }
1664  model->removeWire(wire);
1665  }
void removeItems(Wire &wire)
remove the definition network from wire, up to, but not including attached variables.
Definition: minsky.cc:1647
GroupPtr model
Definition: minsky.h:242

◆ renameDimension()

void minsky::Minsky::renameDimension ( const std::string &  oldName,
const std::string &  newName 
)

Definition at line 544 of file minsky.cc.

545  {
546  auto i=dimensions.find(oldName);
547  if (i!=dimensions.end())
548  {
549  dimensions[newName]=i->second;
550  dimensions.erase(i);
551  }
552 
553  for (auto& v: variableValues)
554  {
555  auto hc=v.second->tensorInit.hypercube();
556  for (auto& x: hc.xvectors)
557  if (x.name==oldName)
558  {
559  x.name=newName;
560  }
561  v.second->tensorInit.hypercube(hc);
562  }
563  }
VariableValues variableValues
Definition: minsky.h:188
Dimensions dimensions
Definition: minsky.h:189

◆ renderAllPlotsAsSVG()

void minsky::Minsky::renderAllPlotsAsSVG ( const string &  prefix) const

render all plots

Definition at line 1547 of file minsky.cc.

References minsky::str().

1548  {
1549  unsigned plotNum=0;
1550  model->recursiveDo(&Group::items,
1551  [&](Items&, Items::iterator i) {
1552  if (auto p=(*i)->plotWidgetCast())
1553  {
1554  if (!p->title.empty())
1555  p->RenderNativeWindow::renderToSVG(prefix+"-"+p->title+".svg");
1556  else
1557  p->RenderNativeWindow::renderToSVG(prefix+"-"+str(plotNum++)+".svg");
1558  }
1559  return false;
1560  });
1561  }
std::vector< ItemPtr > Items
Definition: item.h:360
std::string str(T x)
utility function to create a string representation of a numeric type
Definition: str.h:33
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:

◆ renderCanvasToEMF()

void minsky::Minsky::renderCanvasToEMF ( const std::string &  filename)
inline

render canvas to a EMF image file (Windows only)

Definition at line 404 of file minsky.h.

404 {canvas.renderToEMF(filename);}
Canvas canvas
Definition: minsky.h:243

◆ renderCanvasToPDF()

void minsky::Minsky::renderCanvasToPDF ( const std::string &  filename)
inline

render canvas to a PDF file

Definition at line 390 of file minsky.h.

390 {canvas.renderToPDF(filename);}
Canvas canvas
Definition: minsky.h:243

◆ renderCanvasToPNG() [1/2]

void minsky::Minsky::renderCanvasToPNG ( const std::string &  filename)
inline

render canvas to a PNG image file

Definition at line 394 of file minsky.h.

394 {canvas.renderToPNG(filename);}
Canvas canvas
Definition: minsky.h:243

◆ renderCanvasToPNG() [2/2]

void minsky::Minsky::renderCanvasToPNG ( const std::string &  filename,
const Canvas::ZoomCrop z 
)
inline

Render canvas to a PNG file filename, scaling the canvas temporarily by zoom, shifts it to left, top, and crops to width, height (in ZoomCrop struct).

Definition at line 400 of file minsky.h.

401  {canvas.renderToPNGCropped(filename,z);}
Canvas canvas
Definition: minsky.h:243
void renderToPNGCropped(const std::string &filename, const ZoomCrop &)
Render to a PNG file filename, scaling the canvas temporarily by zoom, shifts it to left...
Definition: canvas.cc:945

◆ renderCanvasToPS()

void minsky::Minsky::renderCanvasToPS ( const std::string &  filename)
inline

render canvas to a postscript file

Definition at line 388 of file minsky.h.

388 {canvas.renderToPS(filename);}
Canvas canvas
Definition: minsky.h:243

◆ renderCanvasToSVG()

void minsky::Minsky::renderCanvasToSVG ( const std::string &  filename)
inline

render canvas to an SVG file

Definition at line 392 of file minsky.h.

392 {canvas.renderToSVG(filename);}
Canvas canvas
Definition: minsky.h:243

◆ requestRedraw()

void minsky::Minsky::requestRedraw ( )

requests a redraw of the curren active tab

Definition at line 486 of file minsky.cc.

487  {
488  // requestRedraw on all tabs - only the active one will actually do anything
490  equationDisplay.requestRedraw();
492  for (auto& pub: publicationTabs)
493  pub.requestRedraw();
494  }
PannableTab< EquationDisplay > equationDisplay
Definition: minsky.h:141
std::vector< PubTab > publicationTabs
Definition: minsky.h:144
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
PhillipsDiagram phillipsDiagram
Definition: minsky.h:143

◆ requestReset()

void minsky::Minsky::requestReset ( )

Definition at line 466 of file minsky.cc.

Referenced by minsky::Ravel::collapseAllHandles(), minsky::Canvas::deleteItem(), minsky::Canvas::deleteWire(), minsky::Sheet::draw(), minsky::RavelPopup::mouseOver(), minsky::PubTab::mouseUp(), minsky::Canvas::mouseUp(), minsky::Ravel::onKeyPress(), minsky::VariableBase::onKeyPress(), minsky::VariableBase::onMouseMotion(), minsky::Ravel::pickSliceLabels(), minsky::Group::renameAllInstances(), and minsky::Ravel::sortByValue().

467  {
468  if (resetDuration<resetNowThreshold)
469  {
470  try
471  {
472  reset();
473  }
474  catch (...)
475  {}
476  return;
477  }
478  flags|=reset_needed;
479  // schedule reset for some time in the future
480  if (resetDuration<resetPostponedThreshold)
481  resetAt=std::chrono::system_clock::now()+resetPostponedThreshold;
482  else // postpone "indefinitely"
483  resetAt=std::chrono::time_point<std::chrono::system_clock>::max();
484  }
void reset()
resets the variables back to their initial values
Definition: minsky.cc:865
Here is the caller graph for this function:

◆ reset()

void minsky::Minsky::reset ( )

resets the variables back to their initial values

Definition at line 865 of file minsky.cc.

References minsky::onStackExit(), and minsky::wire.

Referenced by minsky::Lock::toggleLocked().

867  {
868  // do not reset while simulation is running
869  if (RKThreadRunning)
870  {
871  flags |= reset_needed;
872  if (RKThreadRunning) return;
873  }
874 
875  auto start=chrono::high_resolution_clock::now();
876  auto updateResetDuration=onStackExit([&]{resetDuration=chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now()-start);});
877  canvas.itemIndicator.reset();
878  const BusyCursor busy(*this);
880  lastT=t0;
881  const ProgressUpdater pu(progressState,"Resetting",5);
884  ++progressState;
885  // if no stock variables in system, add a dummy stock variable to
886  // make the simulation proceed
887  if (stockVars.empty()) stockVars.resize(1,0);
888 
889  initGodleys();
890  ++progressState;
891 
892  if (!stockVars.empty())
893  rkreset();
894 
895  // update flow variable
896  evalEquations();
897  ++progressState;
898 
899  // populate ravel hypercubes first, before reattaching plots.
900  model->recursiveDo
901  (&Group::items,
902  [&](Items& m, Items::iterator i)
903  {
904  if (auto r=dynamic_cast<Ravel*>(i->get()))
905  {
906  if (r->ports(1).lock()->numWires()>0)
907  if (auto vv=r->ports(1).lock()->getVariableValue())
908  r->populateHypercube(vv->hypercube());
909  }
910  else if (auto v=(*i)->variableCast())
911  v->resetMiniPlot();
912  return false;
913  });
914 
915  // attach the plots
916  model->recursiveDo
917  (&Group::items,
918  [&](Items& m, Items::iterator it)
919  {
920  if (auto p=(*it)->plotWidgetCast())
921  {
922  p->disconnectAllVars();// clear any old associations
923  p->clearPenAttributes();
924  p->autoScale();
925  for (size_t i=0; i<p->portsSize(); ++i)
926  {
927  auto pp=p->ports(i).lock();
928  for (auto wire: pp->wires())
929  if (auto fromPort=wire->from())
930  if (auto vv=wire->from()->getVariableValue())
931  if (vv->idx()>=0)
932  p->connectVar(vv, i);
933  }
934  p->clear();
935  if (running)
936  p->updateIcon(t);
937  else
938  p->addConstantCurves();
939  p->requestRedraw();
940  }
941  return false;
942  });
943  ++progressState;
944 
945  // if (running)
946  flags &= ~reset_needed; // clear reset flag
947  resetAt=std::chrono::time_point<std::chrono::system_clock>::max();
948  // else
949  // flags |= reset_needed; // enforce another reset at simulation start
950  running=false;
951 
952  requestRedraw();
953 
954  // update maxValues
955  PhillipsFlow::maxFlow.clear();
956  PhillipsStock::maxStock.clear();
957  for (auto& v: variableValues)
958  {
959  if (v.second->type()==VariableType::stock)
960  {
961  PhillipsStock::maxStock[v.second->units]+=v.second->value();
962  }
963  }
964  for (auto& i: PhillipsStock::maxStock) i.second=abs(i.second);
965  }
966  catch (...)
967  {
968  // in the event of an exception, clear reset flag
969  flags &= ~reset_needed; // clear reset flag
970  resetAt=std::chrono::time_point<std::chrono::system_clock>::max();
971  resetDuration=chrono::milliseconds::max();
972  throw;
973  }
double lastT
previous timestep
Definition: minsky.h:307
void rkreset()
reset the simulation
Definition: rungeKutta.cc:122
void constructEquations()
construct the equations based on input data
Definition: minsky.cc:392
static std::vector< double, CIVITA_ALLOCATOR< double > > stockVars
vector of variables that are integrated via Runge-Kutta. These variables label the columns of the God...
static double t
Definition: evalOp.h:49
VariableValues variableValues
Definition: minsky.h:188
static std::map< Units, double > maxFlow
static std::map< Units, double > maxStock
ItemPtr itemIndicator
for drawing error indicator on the canvas
Definition: canvas.h:120
std::vector< ItemPtr > Items
Definition: item.h:360
Canvas canvas
Definition: minsky.h:243
void initGodleys()
Definition: minsky.cc:856
OnStackExit< F > onStackExit(F f)
generator function
Definition: str.h:85
double t
time
Definition: rungeKutta.h:57
GroupPtr model
Definition: minsky.h:242
void evalEquations()
Definition: rungeKutta.h:70
bool running
controls whether simulation is running
Definition: rungeKutta.h:58
void requestRedraw()
requests a redraw of the curren active tab
Definition: minsky.cc:486
Here is the call graph for this function:
Here is the caller graph for this function:

◆ reset_flag()

bool minsky::Minsky::reset_flag ( ) const
inline

true if reset needs to be called prior to numerical integration

Definition at line 159 of file minsky.h.

Referenced by minsky::Canvas::mouseMove().

159 {return flags & reset_needed;}
Here is the caller graph for this function:

◆ resetIfFlagged()

bool minsky::Minsky::resetIfFlagged ( )
inlineoverridevirtual

checks whether a reset is required, and resets the simulation if so

Returns
whether simulation was reset

Reimplemented from minsky::RungeKutta.

Definition at line 182 of file minsky.h.

182  {
183  if (reset_flag())
184  reset();
185  return reset_flag();
186  }
void reset()
resets the variables back to their initial values
Definition: minsky.cc:865
bool reset_flag() const
true if reset needs to be called prior to numerical integration
Definition: minsky.h:159

◆ resetScroll()

virtual void minsky::Minsky::resetScroll ( )
inlinevirtual

reset main window scroll bars after model has been panned

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 439 of file minsky.h.

Referenced by displayErrorItem(), minsky::VariableInstanceList::gotoInstance(), and minsky::Canvas::zoomToDisplay().

439 {}
Here is the caller graph for this function:

◆ runItemDeletedCallback()

virtual void minsky::Minsky::runItemDeletedCallback ( const Item )
inlinevirtual

run callback attached to item

Definition at line 445 of file minsky.h.

Referenced by minsky::Group::deleteItem().

445 {}
Here is the caller graph for this function:

◆ save()

void minsky::Minsky::save ( const std::string &  filename)

Definition at line 1013 of file minsky.cc.

References minsky::Saver::os, minsky::Saver::packer, minsky::remove(), and minsky::Saver::save().

1014  {
1015  // back up to temporary file name
1016  rename(filename.c_str(), (filename+"~").c_str());
1017 
1018  const schema3::Minsky m(*this);
1019  Saver saver(filename);
1020  saver.packer.prettyPrint=true;
1021  try
1022  {
1023  saver.save(m);
1024  }
1025  catch (...) {
1026  // rename backup in place
1027  rename((filename+"~").c_str(), filename.c_str());
1028  // if exception is due to file error, provide a more useful message
1029  if (!saver.os)
1030  throw runtime_error("cannot save to "+filename);
1031  throw;
1032  }
1033  pushHistory(); // ensure history is up to date to prevent trivial setting of dirty flag
1034  flags &= ~is_edited;
1036  if (autoSaver)
1037  boost::filesystem::remove(autoSaver->fileName);
1038  // rotate saved versions
1039  for (int i=numBackups; i>1; --i)
1040  rename((filename+";"+to_string(i-1)).c_str(), (filename+";"+to_string(i)).c_str());
1041  if (numBackups>0)
1042  rename((filename+"~").c_str(), (filename+";1").c_str());
1043  else
1044  ::remove((filename+"~").c_str());
1045  }
bool pushHistory()
push current model state onto history if it differs from previous
Definition: minsky.cc:1264
void remove(std::vector< T > &x, const V &v)
remove an element from a vector. V must be comparable to a T
Definition: str.h:89
int numBackups
number of previous versions of saved files to keep save to a file
Definition: minsky.h:312
static const std::string minskyVersion
Definition: minsky.h:323
std::string fileVersion
Minsky version file was saved under.
Definition: minsky.h:337
Here is the call graph for this function:

◆ saveCanvasItemAsFile()

void minsky::Minsky::saveCanvasItemAsFile ( const string &  fileName) const
inline

Definition at line 254 of file minsky.h.

255  {if (auto g=dynamic_cast<Group*>(canvas.item.get())) saveGroupAsFile(*g,fileName);}
static void saveGroupAsFile(const Group &, const string &fileName)
Definition: minsky.cc:213
Canvas canvas
Definition: minsky.h:243
ItemPtr item
item or wire obtained by get*At() calls
Definition: canvas.h:175

◆ saveGroupAsFile()

void minsky::Minsky::saveGroupAsFile ( const Group g,
const string &  fileName 
)
static

Definition at line 213 of file minsky.cc.

References minsky::Saver::save().

214  {
215  const schema3::Minsky m(g);
216  Saver(fileName).save(m);
217  }
Here is the call graph for this function:

◆ saveSelectionAsFile()

void minsky::Minsky::saveSelectionAsFile ( const string &  fileName) const
inline

Definition at line 268 of file minsky.h.

268 {saveGroupAsFile(canvas.selection,fileName);}
static void saveGroupAsFile(const Group &, const string &fileName)
Definition: minsky.cc:213
Canvas canvas
Definition: minsky.h:243
Selection selection
Definition: canvas.h:105

◆ setAllDEmode()

void minsky::Minsky::setAllDEmode ( bool  mode)

set DE mode on all godley tables

Definition at line 1578 of file minsky.cc.

1578  {
1579  model->recursiveDo(&GroupItems::items, [mode](Items&,Items::iterator i) {
1580  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
1581  g->table.setDEmode(mode);
1582  return false;
1583  });
1584  }
std::vector< ItemPtr > Items
Definition: item.h:360
GroupPtr model
Definition: minsky.h:242

◆ setAutoSaveFile()

void minsky::Minsky::setAutoSaveFile ( const std::string &  file)

initialises auto saving empty file to turn off autosave

Definition at line 1792 of file minsky.cc.

1792  {
1793  if (file.empty())
1794  autoSaver.reset();
1795  else
1796  autoSaver.reset(new BackgroundSaver(file));
1797  }

◆ setBusyCursor()

virtual void minsky::Minsky::setBusyCursor ( )
inlinevirtual

set/clear busy cursor in GUI

Reimplemented in minsky::anonymous_namespace{addon.cc}::AddOnMinsky.

Definition at line 430 of file minsky.h.

430 {}

◆ setDefinition()

void minsky::Minsky::setDefinition ( const std::string &  valueId,
const std::string &  definition 
)

add/replace a definition for a flow variable given by valueId

Definition at line 1667 of file minsky.cc.

References minsky::UserFunction::expression, minsky::flipped(), minsky::group, minsky::Item::moveTo(), minsky::Item::ports(), minsky::valueId(), minsky::var, and minsky::Item::width().

1668  {
1669  auto var=definingVar(valueId);
1670  if (!var) // find
1671  var=dynamic_pointer_cast<VariableBase>(model->findAny(&GroupItems::items, [&](const ItemPtr& it) {
1672  if (auto v=it->variableCast())
1673  return v->valueId()==valueId;
1674  return false;
1675  }));
1676  if (var)
1677  if (auto p=var->ports(1).lock())
1678  {
1679  auto group=var->group.lock();
1680  if (!group) group=model;
1681  UserFunction* udf=p->wires().empty()? nullptr: dynamic_cast<UserFunction*>(&p->wires().front()->from()->item());
1682  if (!udf)
1683  {
1684  // remove previous definition network
1685  for (auto w: p->wires())
1686  {
1687  assert(w);
1688  removeItems(*w);
1689  }
1690 
1691  udf=new UserFunction(var->name()+"()");
1692  group->addItem(udf); // ownership passed
1693  const bool notFlipped=!flipped(var->rotation());
1694  udf->moveTo(var->x()+(notFlipped? -1:1)*0.6*(var->width()+udf->width()), var->y());
1695  group->addWire(udf->ports(0), var->ports(1));
1696  }
1697  udf->expression=definition;
1698  }
1699  }
std::shared_ptr< Item > ItemPtr
Definition: item.h:55
string valueId(const string &name)
construct a valueId from fully qualified name @ name should not be canonicalised
Definition: valueId.cc:75
void removeItems(Wire &wire)
remove the definition network from wire, up to, but not including attached variables.
Definition: minsky.cc:1647
bool flipped(double rotation)
returns if the angle (in degrees) is in the second or third quadrant
Definition: geometry.h:102
VariablePtr definingVar(const std::string &valueId) const
returns reference to variable defining (ie input wired) for valueId
Definition: minsky.cc:204
GroupPtr model
Definition: minsky.h:242
Here is the call graph for this function:

◆ setGodleyDisplayValue()

void minsky::Minsky::setGodleyDisplayValue ( bool  displayValues,
GodleyTable::DisplayStyle  displayStyle 
)

set display value mode on all godley table editor modes

Definition at line 1586 of file minsky.cc.

1587  {
1589  this->displayStyle=displayStyle;
1591  model->recursiveDo(&GroupItems::items, [](Items&,Items::iterator i) {
1592  if (auto g=dynamic_cast<GodleyIcon*>(i->get()))
1593  g->popup.requestRedraw();
1594  return false;
1595  });
1596  }
bool displayValues
Definition: minsky.h:417
GodleyTable::DisplayStyle displayStyle
Definition: minsky.h:418
std::vector< ItemPtr > Items
Definition: item.h:360
Canvas canvas
Definition: minsky.h:243
void requestRedraw()
request a redraw on the screen
Definition: canvas.h:292
GroupPtr model
Definition: minsky.h:242

◆ setGodleyIconResource()

void minsky::Minsky::setGodleyIconResource ( const string &  s)
inline

Definition at line 203 of file minsky.h.

References minsky::SVGRenderer::setResource(), and minsky::GodleyIcon::svgRenderer.

void setResource(const std::string &resource)
initialise object from an SVG file
Definition: SVGItem.cc:57
static SVGRenderer svgRenderer
SVG icon to display when not in editor mode.
Definition: godleyIcon.h:62
Here is the call graph for this function:

◆ setGroupIconResource()

void minsky::Minsky::setGroupIconResource ( const string &  s)
inline

Definition at line 205 of file minsky.h.

References minsky::SVGRenderer::setResource(), and minsky::Group::svgRenderer.

static SVGRenderer svgRenderer
Definition: group.h:257
void setResource(const std::string &resource)
initialise object from an SVG file
Definition: SVGItem.cc:57
Here is the call graph for this function:

◆ setLockIconResource()

void minsky::Minsky::setLockIconResource ( const string &  locked,
const string &  unlocked 
)
inline

Definition at line 207 of file minsky.h.

References minsky::Lock::lockedIcon, minsky::SVGRenderer::setResource(), and minsky::Lock::unlockedIcon.

207  {
210  }
void setResource(const std::string &resource)
initialise object from an SVG file
Definition: SVGItem.cc:57
static SVGRenderer lockedIcon
Definition: lock.h:42
static SVGRenderer unlockedIcon
Definition: lock.h:43
Here is the call graph for this function:

◆ setRavelIconResource()

void minsky::Minsky::setRavelIconResource ( const string &  s)
inline

Definition at line 211 of file minsky.h.

References minsky::SVGRenderer::setResource(), and minsky::Ravel::svgRenderer.

void setResource(const std::string &resource)
initialise object from an SVG file
Definition: SVGItem.cc:57
static SVGRenderer svgRenderer
SVG icon to display when not in editor mode.
Definition: ravelWrap.h:83
Here is the call graph for this function:

◆ srand()

void minsky::Minsky::srand ( int  seed)
inline

set std library RNG seed

Definition at line 414 of file minsky.h.

414 {::srand(seed);}
void srand(int seed)
set std library RNG seed
Definition: minsky.h:414

◆ step()

vector< double > minsky::Minsky::step ( )

step the equations (by n steps, default 1)

Definition at line 975 of file minsky.cc.

976  {
977  lastT=t;
978  rkstep();
979 
980  logVariables();
981 
982  model->recursiveDo
983  (&Group::items,
984  [&](Items&, Items::iterator i)
985  {(*i)->updateIcon(t); return false;});
986 
987  // throttle redraws
988  const time_duration maxWait=milliseconds(maxWaitMS);
989  if ((microsec_clock::local_time()-(ptime&)lastRedraw) > maxWait)
990  {
991  requestRedraw();
992  lastRedraw=microsec_clock::local_time();
993  }
994 
995  return {t, deltaT()};
996  }
void rkstep()
step the equations (by n steps, default 1) evaluate the flow equations without stepping.
Definition: rungeKutta.cc:130
double lastT
previous timestep
Definition: minsky.h:307
void logVariables() const
write current state of all variables to the log file
Definition: minsky.cc:107
Exclude< ptime > lastRedraw
Definition: minsky.h:130
std::vector< ItemPtr > Items
Definition: item.h:360
double deltaT() const
Definition: minsky.h:308
double t
time
Definition: rungeKutta.h:57
GroupPtr model
Definition: minsky.h:242
int maxWaitMS
maximum wait in millisecond between redrawing canvas during simulation
Definition: minsky.h:340
void requestRedraw()
requests a redraw of the curren active tab
Definition: minsky.cc:486

◆ triggerCheckMemAllocationCallback()

bool minsky::Minsky::triggerCheckMemAllocationCallback ( ) const
inline

trigger checkMem callback for testing purposes

Definition at line 520 of file minsky.h.

521  {return checkMemAllocation(std::numeric_limits<size_t>::max());}
virtual MemCheckResult checkMemAllocation(size_t bytes) const
Definition: minsky.h:450

◆ undo()

long minsky::Minsky::undo ( int  changes = 1)

restore model to state changes ago

Returns
index of current state in history

Definition at line 1400 of file minsky.cc.

References schema3::Minsky::phillipsDiagram, schema3::Minsky::populateGroup(), schema3::PhillipsDiagram::populatePhillipsDiagram(), schema3::Minsky::populatePublicationTabs(), and schema3::Minsky::zoomFactor.

Referenced by minsky::Canvas::copyItem().

1401  {
1402  // save current state for later restoration if needed
1403  if (historyPtr==history.size())
1404  pushHistory();
1405  historyPtr-=changes;
1406  if (historyPtr > 0 && historyPtr <= history.size())
1407  {
1408  schema3::Minsky m;
1409  history[historyPtr-1].reseto()>>m;
1410  // stash tensorInit data for later restoration
1411  auto stashedValues=std::move(variableValues);
1412  // preserve bookmarks. For now, we can only preserve model and canvas.model bookmarks
1413  // count the total number of bookmarks
1414  unsigned numBookmarks=0;
1415  model->recursiveDo(&GroupItems::groups, [&](const Groups&,const Groups::const_iterator i) {
1416  numBookmarks+=(*i)->bookmarks.size();
1417  return false;
1418  });
1419  auto stashedGlobalBookmarks=model->bookmarks;
1420  auto stashedCanvasBookmarks=canvas.model->bookmarks;
1421  clearAllMaps(false);
1422  model->clear();
1423  m.populateGroup(*model);
1424  model->setZoom(m.zoomFactor);
1427  requestRedraw();
1428 
1429  // restore tensorInit data
1430  for (auto& v: variableValues)
1431  {
1432  auto stashedValue=stashedValues.find(v.first);
1433  if (stashedValue!=stashedValues.end())
1434  v.second->tensorInit=std::move(stashedValue->second->tensorInit);
1435  }
1436  // restore bookmarks
1437  model->bookmarks=std::move(stashedGlobalBookmarks);
1438  canvas.model->bookmarks=std::move(stashedCanvasBookmarks);
1439  unsigned numBookmarksAfterwards=0;
1440  model->recursiveDo(&GroupItems::groups, [&](const Groups&,const Groups::const_iterator i) {
1441  numBookmarksAfterwards+=(*i)->bookmarks.size();
1442  return false;
1443  });
1444  if (numBookmarksAfterwards!=numBookmarks)
1445  message("This undo/redo operation potentially deletes some bookmarks");
1446  try {requestReset();}
1447  catch (...) {}
1448 
1449  }
1450  else
1451  historyPtr+=changes; // revert
1452  undone=true; //ensure next pushHistory is ignored
1453  return historyPtr;
1454  }
virtual void message(const std::string &)
display a message in a popup box on the GUI
Definition: minsky.h:442
void populatePublicationTabs(std::vector< minsky::PubTab > &) const
Definition: schema3.cc:610
double zoomFactor
Definition: schema3.h:255
void requestReset()
Definition: minsky.cc:466
bool pushHistory()
push current model state onto history if it differs from previous
Definition: minsky.cc:1264
void populatePhillipsDiagram(minsky::PhillipsDiagram &) const
populate a Phillips Diagram from this
Definition: schema3.cc:850
VariableValues variableValues
Definition: minsky.h:188
void populateGroup(minsky::Group &g) const
populate a group object from this. This mutates the ids in a consistent way into the free id space of...
Definition: schema3.cc:636
PhillipsDiagram phillipsDiagram
Definition: schema3.h:259
Model model
Definition: canvas.h:103
std::vector< PubTab > publicationTabs
Definition: minsky.h:144
Canvas canvas
Definition: minsky.h:243
std::vector< GroupPtr > Groups
Definition: group.h:52
Groups groups
Definition: group.h:77
PhillipsDiagram phillipsDiagram
Definition: minsky.h:143
void clearAllMaps()
Definition: minsky.h:246
GroupPtr model
Definition: minsky.h:242
void requestRedraw()
requests a redraw of the curren active tab
Definition: minsky.cc:486
Here is the call graph for this function:
Here is the caller graph for this function:

◆ variableTypes()

vector< string > minsky::Minsky::variableTypes ( )
static

list of available variable types

Definition at line 1607 of file minsky.cc.

1608  {return enumVals<VariableType::Type>();}

Member Data Documentation

◆ canvas

◆ conversions

Conversions minsky::Minsky::conversions

Definition at line 190 of file minsky.h.

Referenced by schema3::Minsky::Minsky(), and schema3::Minsky::populateMinsky().

◆ dimensions

◆ displayStyle

GodleyTable::DisplayStyle minsky::Minsky::displayStyle =GodleyTable::sign

Definition at line 418 of file minsky.h.

◆ displayValues

bool minsky::Minsky::displayValues =false

Definition at line 417 of file minsky.h.

Referenced by minsky::GodleyTableEditor::draw().

◆ doPushHistory

bool minsky::Minsky::doPushHistory =true

flag to indicate whether a TCL should be pushed onto the history stack, or logged in a recording. This is used to avoid movements being added to recordings and undo history

Definition at line 370 of file minsky.h.

◆ equationDisplay

PannableTab<EquationDisplay> minsky::Minsky::equationDisplay

Definition at line 141 of file minsky.h.

◆ fileVersion

std::string minsky::Minsky::fileVersion

Minsky version file was saved under.

Definition at line 337 of file minsky.h.

Referenced by schema3::Minsky::populateMinsky().

◆ fontSampler

FontDisplay minsky::Minsky::fontSampler

Definition at line 142 of file minsky.h.

◆ histogramResource

SVGRenderer minsky::Minsky::histogramResource

◆ lastRedraw

Exclude<ptime> minsky::Minsky::lastRedraw
private

Definition at line 130 of file minsky.h.

◆ lastT

double minsky::Minsky::lastT {0}

previous timestep

Definition at line 307 of file minsky.h.

◆ logVarList

std::set<string> minsky::Minsky::logVarList

set of variables (valueIds) to log

Definition at line 289 of file minsky.h.

◆ m_multipleEquities

bool minsky::Minsky::m_multipleEquities =false
private

Definition at line 132 of file minsky.h.

◆ maxFlowValue

std::map<Units, double> minsky::Minsky::maxFlowValue

Definition at line 193 of file minsky.h.

◆ maxHistory

unsigned minsky::Minsky::maxHistory {100}

maximum no. of history states to save

Definition at line 339 of file minsky.h.

◆ maxValue

std::map<Units, double> minsky::Minsky::maxValue

stash the maximum absolute value obtained by a dimensioned quantity

Definition at line 192 of file minsky.h.

◆ maxWaitMS

int minsky::Minsky::maxWaitMS =100

maximum wait in millisecond between redrawing canvas during simulation

Definition at line 340 of file minsky.h.

Referenced by minsky::Canvas::reportDrawTime().

◆ minskyVersion

const std::string minsky::Minsky::minskyVersion =MINSKY_VERSION
static

Definition at line 323 of file minsky.h.

Referenced by schema3::Minsky::Minsky().

◆ model

◆ namedItems

std::map<std::string,std::weak_ptr<Item> > minsky::Minsky::namedItems

Definition at line 515 of file minsky.h.

◆ numBackups

int minsky::Minsky::numBackups =1

number of previous versions of saved files to keep save to a file

Definition at line 312 of file minsky.h.

◆ phillipsDiagram

PhillipsDiagram minsky::Minsky::phillipsDiagram

Definition at line 143 of file minsky.h.

Referenced by schema3::Minsky::Minsky(), and schema3::Minsky::populateMinsky().

◆ publicationTabs

std::vector<PubTab> minsky::Minsky::publicationTabs

◆ userFunctions

Exclude<std::map<std::string, std::shared_ptr<CallableFunction> > > minsky::Minsky::userFunctions

Definition at line 240 of file minsky.h.

Referenced by minsky::UserFunction::compile(), and minsky::UserFunction::units().

◆ variableInstanceList

std::shared_ptr<VariableInstanceList> minsky::Minsky::variableInstanceList

supports navigation to all instances of current variable

Definition at line 512 of file minsky.h.

◆ variablePane

VariablePane minsky::Minsky::variablePane

Definition at line 523 of file minsky.h.

◆ variableValues


The documentation for this class was generated from the following files: