def insertWorkingDirectory(optionArgument):

    print("Setting new working directory")

    if optionArgument == None:
        optionArgument = ""
        loopQuestion = True
        defaultWD = os.path.expanduser(
            os.path.join('~', 'starfish_working_directory'))
        print(
            "Enter an absolute or relative path to set the working directory, or (q) quit"
        )
        input_prompt = "[Press enter to use the default path {}]: ".format(
            defaultWD)
        optionArgument = input3(input_prompt) or defaultWD

    if optionArgument != "q":
        optionArgument = os.path.expanduser(optionArgument)

        if os.path.isdir(optionArgument):
            saveConfigFile({'WorkingDirectory': optionArgument})
            updateKnownWorkingDirectories()
            print("   working directory set!")
        else:
            print("  working directory does not exist! try to create folder")
            try:
                os.mkdir(optionArgument)
                saveConfigFile({'WorkingDirectory': optionArgument})
                updateKnownWorkingDirectories()
                print("   created working directory folder successfully")
                print("   working directory set!")
            except:
                print(
                    "  WARNING: moduleStartUp.insertWorkingDirectory() could not set WorkingDirectory {} directory does not exists!"
                    .format(optionArgument))
Example #2
0
def main(args=None):

    print("")
    print('=====================================')
    print('#     STARFiSh_v0.4.19.10.2016      #')
    print('=====================================')

    mainMenuInput = ""
    while mainMenuInput not in ['q']:
        print('\n Main menu:\n')
        print(" [1] - run simulation | Main.py")
        if NOVNC:
            VNCSTR = "(Not Available)"
        else:
            VNCSTR = ""
        print(" [2] -{} run vnc (vascular network creator) | vnc.py".format(
            VNCSTR))
        if NOVIZ:
            VIZSTR = "(Not Available)"
        else:
            VIZSTR = ""
        print(" [3] -{} run visualisation | Visualisation.py".format(VIZSTR))
        print(
            " [4] - run uncertainty quantification tool box | VascularPolynomialChaos.py"
        )
        print(" [q] - quit \n")
        while mainMenuInput not in ('1', '2', '3', '4', 'q'):
            mainMenuInput = input3("what to do? ")

        if mainMenuInput == '1':
            print("\n .. running simulation \n")
            simulator.main()
            mainMenuInput = ""

        if mainMenuInput == '2' and NOVNC:
            print("\n .. vnc not available \n")
            mainMenuInput = ""
        elif mainMenuInput == '2':
            print("\n .. running vnc \n")
            vnc.main()
            mainMenuInput = ""

        if mainMenuInput == '3' and NOVIZ:
            print("\n .. visualisation not available \n")
            mainMenuInput = ""
        elif mainMenuInput == '3':
            print("\n .. running visualisation \n")
            visualisationToolBox.main()
            mainMenuInput = ""

        if mainMenuInput == '4':
            print("\n .. running uncertainty quantification tool box \n")
            uqsaToolBox.uncertaintyPropagation()
            mainMenuInput = ""

    print("bye bye ..")
Example #3
0
def defineSimulationDescription():
    simulationDescription = input3(
        "\n  Type in description of the simulation case: ")
    try:
        simulationDescription = str(simulationDescription)
    except:
        print('ERROR: no String Convertable input given, system exit')
        exit()
    if simulationDescription in ['', ' ']: simulationDescription = '-'
    return simulationDescription
Example #4
0
def userInputEvaluationInt(maxBound,
                           minBound=0,
                           question="    insert your choice, (q)-quit: "):
    '''
    Question user to isert an integer number between minBound and maxBound
    '''
    appropriateInputList = [
        str(int(i + minBound)) for i in range(maxBound - minBound)
    ]
    userInput = "NONE"
    appropriateInputList.append('q')
    print("")
    while userInput not in appropriateInputList:
        userInput = input3(question)
    print("")
    if userInput == 'q': exit()
    else: return int(userInput)
Example #5
0
def defineDataNumber(networkName):

    print(
        "No solution-datanumber defined (3 characters)! It needs to be defined"
    )

    #TODO CRITICAL this fails for template networks
    existingDataNumbers = findExistingDataNumbers(networkName)
    correctDataNumber = False

    prettyPrintList(
        "\n        Existing dataNumbers for this network: {}".format(
            networkName), existingDataNumbers)

    while correctDataNumber == False:
        dataNumber = input3("\n  Please enter datanumber (3 characters): ")
        testedFailed = False
        try:
            dataNumber, xx = evaluateDataNumber(dataNumber)
        except ValueError as e:
            print(e)
            testedFailed = True

        if dataNumber in existingDataNumbers:
            listToPrint = [
                " keep this datanumber and overwrite simulation case",
                " enter new data number"
            ]
            prettyPrintList(
                "\n        Simulation case with datanumber exits already".
                format(networkName), listToPrint)
            userInput = userInputEvaluationInt(2, 0, "     What to do? ")
            if userInput == 0:
                correctDataNumber = True

            elif userInput == 0:
                dataNumber = False
                correctDataNumber = False

        elif testedFailed == False:
            correctDataNumber = True

    return dataNumber
Example #6
0
def chooseUQSACaseFile(networkName):
    """
    console Interface to choose a vascularPolynomialChaos Config File
     including the possibility to create a template Config File
    Input:
        networkName of VascularNetwork
    Output:
        networkName,dataNumber of the Config File (networkName should be the same)
    """
    from starfish.VascularPolynomialChaosLib import classUqsaCase

    workingDirectory = mFPH.getDirectory('workingDirectory', '', '', 'read')
    networkDirectory = os.path.join(*[workingDirectory, networkName])

    filesNetworkDir = os.listdir(networkDirectory)
    filenames = []

    for fileNetworkDir in filesNetworkDir:
        # check if polychaos directory:
        if 'vascularPolynomialChaos' in fileNetworkDir:
            allFilenames = os.listdir(
                os.path.join(*[workingDirectory, networkName, fileNetworkDir]))
            for filename in allFilenames:
                if ".xml" in filename and "uqsaCase" in filename:
                    filenames.append(filename)

    print(
        "\n  No dataNumber for UQSAcase file passed, choose between all available UQSAcase files:"
    )
    print(
        "  (NB: use -n dataNumber to define a specific UQSAcase you want to open)\n"
    )
    print("   [   0 ] - Create new template uqsa case file and exit")
    print("   [   1 ] - Create new template uqsa case file and run")
    indexOffset = 2
    if filenames != []:
        prettyPrintList('', filenames, indexOffset=indexOffset)

    question = "  Choose Option or Config-File you want to open according to its number:, (q)-quit: "
    userInput = userInputEvaluationInt(indexOffset + len(filenames), 0,
                                       question)

    if userInput in [0, 1]:

        userInputDataNumber = 'xxxx'
        dataNumber = False
        while dataNumber == False:
            userInputDataNumber = input3(
                "\n  Insert dataNumber for polynomial Chaos case (overwrites if existing): "
            )
            dataNumber = evaluateDataNumber(userInputDataNumber,
                                            exception="Warning")[0]

        # create template configuration
        configurationFilePathTemplate = mFPH_VPC.getFilePath(
            'uqsaCaseTemplateFile', networkName, dataNumber, 'read')
        uqsaCase = classUqsaCase.UqsaCase()
        uqsaCase.loadXMLFile(configurationFilePathTemplate)

        # TODO: check if file exits and ask if it should be overwritten
        configurationFilePath = mFPH_VPC.getFilePath('uqsaCaseXmlFile',
                                                     networkName, dataNumber,
                                                     'write')
        uqsaCase.writeXMLFile(configurationFilePath)
        # copy network file
        toCopyFile = mFPH.getFilePath('networkXmlFile', networkName, 'xxx',
                                      'write')
        destinationFile = mFPH_VPC.getFilePath('vpcNetworkXmlFile',
                                               networkName, dataNumber,
                                               'write')
        shutil.copy(toCopyFile, destinationFile)
        if userInput == 0:
            print("files created!, exit()")
            exit()

    else:
        networkName = filenames[userInput - indexOffset]
        dataNumber = networkName.split('.')[0].split('_')[-1]

    return dataNumber
 def extremaFinderFunction(self, dataPure, quantityNamePure, sampleSize, simulationTime, searchPointOfInflection):
     
     allDesieredPointsDetected = False
     delta = 0.005
     
     colordef  = ['r','g','b','m','k','c']
     markerdef = ['o','d','x','s','*','v']
     colors       = colordef*len(markerdef)
     markerstyles = [item for sublist in [ [i]*len(colordef) for i in markerdef] for item in sublist]
         
                                     
     while allDesieredPointsDetected == False:   
         amplitudesList = []
         timingList = []
         numberOfPointsFirst = None
         for sampleIndex in range(sampleSize):
             
             dataPureCurr = dataPure[sampleIndex]
             
             if searchPointOfInflection == True:
                 
                 pointInfAmp,pointInfTime = mProc.calculatePointOfInflection(dataPureCurr, simulationTime, simulationTime[0])
                 minMaxPoints = [[pointInfAmp],[pointInfTime]]
                 numberOfPointsCurrent = len(minMaxPoints[0])
                 if numberOfPointsFirst == None: numberOfPointsFirst = numberOfPointsCurrent
                 
             else:
                 minMaxPoints = mProc.minMaxFunction(dataPureCurr,timeValues=simulationTime,delta=delta, seperateMinMax = False ) 
                 
                 numberOfPointsCurrent = len(minMaxPoints[0])
                 if numberOfPointsFirst == None: numberOfPointsFirst = numberOfPointsCurrent
                 
                 deltaAltered = delta
                 while numberOfPointsCurrent != numberOfPointsFirst:
                     if numberOfPointsCurrent < numberOfPointsFirst:
                         deltaAltered -= delta*0.1
                     elif numberOfPointsCurrent > numberOfPointsFirst:
                         deltaAltered += delta*0.1
                     dataPureCurr = dataPure[sampleIndex]
                     minMaxPoints = mProc.minMaxFunction(dataPureCurr,timeValues=simulationTime,delta=deltaAltered, seperateMinMax = False ) 
                     numberOfPointsCurrent = len(minMaxPoints[0])
             
                                                                 
             amplitudesList.append(minMaxPoints[0])
             timingList.append(minMaxPoints[1])
             
             for c,m,t,x in zip(colors,markerstyles,minMaxPoints[1],minMaxPoints[0]):
                 plt.plot(t,x,'o',color = c,marker=m, markersize = 5)
             
             if numberOfPointsCurrent == numberOfPointsFirst:
                 plt.plot(simulationTime,dataPureCurr,'g', alpha = 0.2)
             elif numberOfPointsCurrent < numberOfPointsFirst:
                 plt.plot(simulationTime,dataPureCurr,'m', alpha = 1.0)
             elif numberOfPointsCurrent > numberOfPointsFirst:
                 plt.plot(simulationTime,dataPureCurr,'k', alpha = 1.0)
         
         # break for inflection point
         if searchPointOfInflection == True:
             allDesieredPointsDetected = True
             break
                 
         plt.title(quantityNamePure)
         plt.show(block = False)
         
         print('\n    Extrema detection all simulations are evaluated:')
         print('      [0] - Analyse all points')
         print('      [1] - Choose points for analysis')
         print('      [2] - Not all desiered peaks are detected (redo and adjust search-delta)')
         suggestions = [str(i) for i in range(3)]
         answer = "nothing"
         while answer not in suggestions:
             answer =input3("What do you want to do: ")
             
         if answer == '0':
             answerSelectionSplit = [str(i) for i in range(numberOfPointsFirst)]
             allDesieredPointsDetected = True
                             
         if answer == '1':
             allDesieredPointsDetected = True
             print("\n    points found for analysis:")
             for i in range(numberOfPointsFirst):
                 print("      [{}] - color: {}, marker style {}".format(i,colors[i],markerstyles[i]))
             answerSelectionSplit = ['']
             while sum([item in [str(i) for i in range(numberOfPointsFirst)] for item in answerSelectionSplit]) != len(answerSelectionSplit):
                 answerSelection =input3("    please enter the numbers of the points (separated with comma): ")
                 if ',' in answerSelection:
                     answerSelectionSplit = answerSelection.split(',')
                 elif ' ' in answerSelection:
                     answerSelectionSplit = answerSelection.split(' ')
                 else:
                     answerSelectionSplit = [answerSelection]
                                
         elif answer == '2':
             answer2 = "haha"
             convertableToFloat = False
             while convertableToFloat == False:
                 answer2 =input3("please redefine delta, current delta value == {} ".format(delta))
                 try:
                     delta = float(answer2)
                     convertableToFloat = True
                 except ValueError as v:
                     print("{} not convertable to float!!".format(v))
                     
         #TODO: save the figures and close ..
         plt.close()
         
     # get the data of the selected points
     selectedPoints = np.array([int(i) for i in answerSelectionSplit])    
     amplitudeData =  np.array(amplitudesList)
     timingData    =  np.array(timingList)
         
     return selectedPoints, amplitudeData, timingData